1
0

diff-card.spec.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // @vitest-environment jsdom
  2. // The diff render intent on the web side: the pure diffCardModel derivation
  3. // over callView/resultView, and both conversation render sites that consume it
  4. // — the chat tool row's expanded body (GenericToolCard / FileMutationRow) and
  5. // the details panel's Output section.
  6. import { afterEach, describe, expect, it, vi } from 'vitest'
  7. import { cleanup, fireEvent, render } from '@testing-library/react'
  8. import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
  9. import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
  10. import type {
  11. ConversationSnapshot, RunningToolCall, SessionId, SessionListState, ToolResultNode, WorkspaceListState,
  12. } from '@deepseek-ai/dsh-client-runtime/client'
  13. import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-client-connection/client'
  14. import type { SelectionTarget } from '@deepseek-ai/dsh-client-ui-conversation/client'
  15. import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
  16. import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
  17. import { CHAT_DIFF_MAX_LINES, diffCardModel } from '../src/client/contract/diff-card-model.ts'
  18. import { createChatStore } from '../src/client/stores.ts'
  19. import { GenericToolCard, type GenericToolCardProps } from '../src/client/chat/GenericToolCard.tsx'
  20. import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx'
  21. import { FileMutationRow, fileMutationToolview } from '../src/client/toolviews/file-mutation-row.tsx'
  22. import { zh } from '../src/client/locales.ts'
  23. afterEach(cleanup)
  24. /** FileMutationRow's full prop shape (ToolRow runtime share + conversation locale seat). */
  25. type FileMutationRowProps = Parameters<typeof FileMutationRow>[0]
  26. const SID = 's1' as SessionId
  27. const t = makeTranslate(zh, commonZh)
  28. const ARGS = '{"file_path":"notes/demo.txt","old_string":"hello","new_string":"hello fixture"}'
  29. /** The edit tool's own call view (a call-time diff derived from the arguments). */
  30. const callDiff = (over?: Partial<Extract<ToolCallView, { card: 'diff' }>>): ToolCallView => ({
  31. card: 'diff', title: 'Edit notes/demo.txt',
  32. diffs: [{ path: 'notes/demo.txt', oldText: 'hello', newText: 'hello fixture' }], ...over,
  33. })
  34. /** The edit tool's own result view (the applied hunk diff). */
  35. const resultDiff = (over?: Partial<Extract<ToolResultView, { card: 'diff' }>>): ToolResultView => ({
  36. card: 'diff', title: 'Edit notes/demo.txt',
  37. diffs: [{ path: 'notes/demo.txt', oldText: 'hello', newText: 'hello fixture' }], ...over,
  38. })
  39. const running = (over?: Partial<RunningToolCall>): RunningToolCall => ({
  40. callId: 'c1', name: 'edit', argsRaw: ARGS,
  41. turn: 1, step: 1, time: 1_000, callView: callDiff(), ...over,
  42. })
  43. const settled = (over?: Partial<ToolResultNode>): ToolResultNode => ({
  44. kind: 'tool-result', seq: 10, time: 2_000, callId: 'c1',
  45. call: { name: 'edit', argsRaw: ARGS },
  46. callTime: 1_000,
  47. content: [{ type: 'text', text: 'The file notes/demo.txt has been updated successfully.' }], isError: false,
  48. callView: callDiff(), resultView: resultDiff(), ...over,
  49. })
  50. describe('diffCardModel', () => {
  51. it('derives a running card from the call view alone', () => {
  52. expect(diffCardModel(running())).toEqual({
  53. card: { diffs: [{ path: 'notes/demo.txt', oldText: 'hello', newText: 'hello fixture' }] },
  54. })
  55. })
  56. it('derives a settled card from the result view, which replaces the call-time diff', () => {
  57. // The applied hunks (result) win over the args-derived call diff.
  58. expect(diffCardModel(settled({
  59. resultView: resultDiff({ diffs: [{ path: 'notes/demo.txt', oldText: 'a', newText: 'b' }] }),
  60. }))).toEqual({
  61. card: { diffs: [{ path: 'notes/demo.txt', oldText: 'a', newText: 'b' }] },
  62. })
  63. })
  64. it('renders a settled diff even when the window dropped the call head', () => {
  65. // A truncated call carries only the result view, which holds the whole change.
  66. expect(diffCardModel(settled({ call: null, callView: null }))?.card.diffs).toHaveLength(1)
  67. })
  68. it('returns null for every non-diff call: no views, generic views, unknown cards', () => {
  69. expect(diffCardModel(running({ callView: null }))).toBeNull()
  70. expect(diffCardModel(settled({ callView: null, resultView: null }))).toBeNull()
  71. expect(diffCardModel(running({ callView: { card: 'generic', title: 'read x' } }))).toBeNull()
  72. // A generic result settles a diff call on the generic path (write/edit's
  73. // own execution-error arm).
  74. expect(diffCardModel(settled({ resultView: { card: 'generic' } }))).toBeNull()
  75. // A card tag this UI version does not know arrives over the wire; the
  76. // documented generic-card default takes it, not a crash.
  77. const future = { card: 'chart', title: 'plot' } as unknown as ToolCallView
  78. expect(diffCardModel(running({ callView: future }))).toBeNull()
  79. expect(diffCardModel(settled({
  80. callView: future, resultView: { card: 'chart' } as unknown as ToolResultView,
  81. }))).toBeNull()
  82. })
  83. it('falls back to null for a malformed diff payload off the wire', () => {
  84. // toolEventViewSchema validates only the `card` string, so a version
  85. // mismatch can deliver a diff card with an unusable diffs field. Each shape
  86. // routes to the generic path instead of throwing inside DiffBlock.
  87. const bad = (diffs: unknown): ToolResultView => ({ card: 'diff', diffs } as unknown as ToolResultView)
  88. expect(diffCardModel(settled({ resultView: bad(undefined) }))).toBeNull()
  89. expect(diffCardModel(settled({ resultView: bad([]) }))).toBeNull()
  90. expect(diffCardModel(settled({ resultView: bad('nope') }))).toBeNull()
  91. expect(diffCardModel(settled({ resultView: bad([null]) }))).toBeNull()
  92. expect(diffCardModel(settled({ resultView: bad([{ path: 1, oldText: null, newText: 'x' }]) }))).toBeNull()
  93. expect(diffCardModel(settled({ resultView: bad([{ path: 'a', oldText: 5, newText: 'x' }]) }))).toBeNull()
  94. expect(diffCardModel(settled({ resultView: bad([{ path: 'a', oldText: null, newText: 9 }]) }))).toBeNull()
  95. // The running side narrows identically.
  96. expect(diffCardModel(running({ callView: { card: 'diff', diffs: 'nope' } as unknown as ToolCallView }))).toBeNull()
  97. })
  98. })
  99. describe('chat row diff body', () => {
  100. const ownerProps = (block: RunningToolCall | ToolResultNode): GenericToolCardProps => ({
  101. callId: 'c1', toolName: 'edit', block, openFile: vi.fn(), t,
  102. })
  103. it('the expanded body is the applied diff, capped tighter than the panel', () => {
  104. expect(CHAT_DIFF_MAX_LINES).toBeLessThan(16)
  105. const view = render(<GenericToolCard {...ownerProps(settled())} />)
  106. // Collapsed: the summary row (path) only, no diff body.
  107. expect(view.queryByText('hello fixture')).toBeNull()
  108. // The path link is not the expand control; the leading toggle is.
  109. fireEvent.click(view.container.querySelector('[data-expandable]')!)
  110. expect(view.container.querySelector('[data-diff]')).not.toBeNull()
  111. expect(view.getByText('hello fixture')).toBeTruthy()
  112. })
  113. it('a running diff call expands to its intended change', () => {
  114. const view = render(<GenericToolCard {...ownerProps(running())} />)
  115. fireEvent.click(view.container.querySelector('[data-expandable]')!)
  116. expect(view.container.querySelector('[data-diff]')).not.toBeNull()
  117. })
  118. it('a non-diff call keeps the args-JSON text body', () => {
  119. // A non-file tool name so the row is not single-file (no path link), and its
  120. // args body is the fallback the diff card must not have replaced.
  121. const view = render(<GenericToolCard {...{
  122. callId: 'c1', toolName: 'some_tool', openFile: vi.fn(), t,
  123. block: settled({
  124. call: { name: 'some_tool', argsRaw: '{"foo":"bar"}' },
  125. callView: null, resultView: null,
  126. }),
  127. }} />)
  128. fireEvent.click(view.container.querySelector('[data-expandable]')!)
  129. expect(view.container.querySelector('[data-diff]')).toBeNull()
  130. expect(view.getByText(/"foo"/)).toBeTruthy()
  131. })
  132. })
  133. describe('FileMutationRow diff card', () => {
  134. const list = () => createSnapshotStore<SessionListState>({
  135. ids: [SID],
  136. byId: { [SID]: { id: SID, displayTitle: 'r', running: false, blank: false, updatedAt: 0, cwd: '/w/app' } },
  137. current: SID,
  138. phase: 'ready',
  139. subagentsByParent: {},
  140. currentAddress: undefined,
  141. })
  142. const rowProps = (block: RunningToolCall | ToolResultNode, toolName = 'edit'): FileMutationRowProps => ({
  143. callId: 'c1', toolName, block, openFile: vi.fn(), cwd: '/w/app',
  144. sessionId: SID, useSessions: bindSnapshotSelector(list()),
  145. t,
  146. } as unknown as FileMutationRowProps)
  147. /** The whole summary row is the expand toggle (ToolRow's unified interaction). */
  148. const toggleRow = (view: { container: HTMLElement }) => {
  149. fireEvent.click(view.container.querySelector('[data-expandable]')!)
  150. }
  151. it('collapses to the summary row; expanding reveals the applied diff card', () => {
  152. const view = render(<FileMutationRow {...rowProps(settled())} />)
  153. // The diff card is collapsed by default — not in the DOM until expanded.
  154. expect(view.container.querySelector('[data-diff]')).toBeNull()
  155. expect(view.queryByText('hello fixture')).toBeNull()
  156. toggleRow(view)
  157. expect(view.container.querySelector('[data-diff]')).not.toBeNull()
  158. expect(view.getByText('hello fixture')).toBeTruthy()
  159. expect(view.getByText('复制')).toBeTruthy()
  160. })
  161. it('the summary is a path link that opens the tool path through the host', () => {
  162. const openFile = vi.fn()
  163. const view = render(<FileMutationRow {...{ ...rowProps(settled()), openFile }} />)
  164. // The path link rides the collapsed summary, so it opens without expanding.
  165. fireEvent.click(view.getByRole('button', { name: 'notes/demo.txt' }))
  166. // The row passes the tool's own path; the injected openFile resolves it
  167. // against the session cwd (apply.ts), so the row must not resolve twice.
  168. expect(openFile).toHaveBeenCalledWith('notes/demo.txt')
  169. })
  170. it('registers under write too, rendering a create as an added-only diff', () => {
  171. const writeArgs = '{"file_path":"notes/new.txt","content":"hello fixture\\n"}'
  172. const view = render(<FileMutationRow {...rowProps(settled({
  173. call: { name: 'write', argsRaw: writeArgs },
  174. callView: { card: 'diff', title: 'Write notes/new.txt', diffs: [{ path: 'notes/new.txt', oldText: null, newText: 'hello fixture' }] },
  175. resultView: { card: 'diff', title: 'Write notes/new.txt', diffs: [{ path: 'notes/new.txt', oldText: null, newText: 'hello fixture' }] },
  176. }), 'write')} />)
  177. // The footer counts live inside the collapsed diff card.
  178. toggleRow(view)
  179. expect(view.getByText('└ +1 -0 · 1 file')).toBeTruthy()
  180. })
  181. it('reflects the run state on its leading slot', () => {
  182. const runningView = render(<FileMutationRow {...rowProps(running())} />)
  183. expect(runningView.container.querySelector('[data-state="running"]')).not.toBeNull()
  184. cleanup()
  185. const errorView = render(<FileMutationRow {...rowProps(settled({ isError: true, resultView: null, callView: null }))} />)
  186. expect(errorView.container.querySelector('[data-state="error"]')).not.toBeNull()
  187. })
  188. it('a mutation call with no diff view renders the summary row alone', () => {
  189. const view = render(<FileMutationRow {...rowProps(settled({ callView: null, resultView: null }))} />)
  190. // No diff material: expanding shows the args-JSON body, never a diff card.
  191. expect(view.container.querySelector('[data-diff]')).toBeNull()
  192. toggleRow(view)
  193. expect(view.container.querySelector('[data-diff]')).toBeNull()
  194. })
  195. it('surfaces the result text when an errored mutation has no diff card', () => {
  196. // write/edit return undefined from presentResult on isError, so the failure
  197. // has no diff — ToolRow shows the model-facing error text as the collapsed
  198. // summary's first line (errorSummary) instead of a bare red dot.
  199. const view = render(<FileMutationRow {...rowProps(settled({
  200. isError: true, callView: null, resultView: null,
  201. content: [{ type: 'text', text: 'old_string not found in notes/demo.txt' }],
  202. }))} />)
  203. expect(view.container.querySelector('[data-diff]')).toBeNull()
  204. expect(view.getByText('old_string not found in notes/demo.txt')).toBeTruthy()
  205. })
  206. it('falls back to the error name/code when an errored result has no text block', () => {
  207. const view = render(<FileMutationRow {...rowProps(settled({
  208. isError: true, callView: null, resultView: null, content: [],
  209. error: { name: 'ToolError', code: 'sandbox_denied' },
  210. }))} />)
  211. expect(view.getByText('ToolError: sandbox_denied')).toBeTruthy()
  212. })
  213. it('shows no error summary for a successful diff or a running call', () => {
  214. // ToolRow's error-color summary line is set only on the error state.
  215. const ok = render(<FileMutationRow {...rowProps(settled())} />)
  216. expect(ok.container.querySelector('[class*="_errorSummary_"]')).toBeNull()
  217. cleanup()
  218. const run = render(<FileMutationRow {...rowProps(running())} />)
  219. expect(run.container.querySelector('[class*="_errorSummary_"]')).toBeNull()
  220. })
  221. it('shows the stopped state when the call was interrupted', () => {
  222. const view = render(<FileMutationRow {...rowProps(settled({
  223. callView: null, resultView: null, isError: true,
  224. error: { name: 'ToolError', code: 'interrupted' },
  225. }))} />)
  226. expect(view.container.querySelector('[data-state="stopped"]')).not.toBeNull()
  227. // The amber StateDot is aria-hidden, so ToolRow carries the state to AT as
  228. // visually-hidden text; without it a stopped row is a colour-only signal.
  229. expect(view.getByText('已停止')).toBeTruthy()
  230. })
  231. it('renders a plain summary span when the call carries no file path', () => {
  232. // Empty args leave deriveFilePath undefined, so the summary is not a link.
  233. const view = render(<FileMutationRow {...rowProps(settled({
  234. call: { name: 'edit', argsRaw: '' }, callView: null, resultView: null,
  235. }))} />)
  236. expect(view.container.querySelector('[class*="_fileLink_"]')).toBeNull()
  237. expect(view.container.querySelector('[class*="_summary_"]')).not.toBeNull()
  238. })
  239. })
  240. describe('fileMutationToolview registration', () => {
  241. it('registers one component under both edit and write, and each disposes', () => {
  242. const registered: { key: string; locale: unknown; disposed: boolean }[] = []
  243. const disposers: (() => void)[] = []
  244. const ctx = {
  245. slots: {
  246. register: ({ key, locale }: { name: string; key: string; locale?: string }) => {
  247. const entry = { key, locale, disposed: false }
  248. registered.push(entry)
  249. const dispose = () => { entry.disposed = true }
  250. disposers.push(dispose)
  251. return dispose
  252. },
  253. },
  254. }
  255. fileMutationToolview.apply(ctx as never)
  256. expect(registered.map(r => r.key).sort()).toEqual(['edit', 'write'])
  257. // Both keys claim the conversation locale seat ToolRow's body copy needs.
  258. expect(registered.map(r => r.locale)).toEqual(['conversation', 'conversation'])
  259. // The registrant's inject seam is the load-order contract the row relies on.
  260. expect(fileMutationToolview.inject).toEqual(['slots', 'conversation'])
  261. // Disposal removes each contribution (packages/AGENTS.md registry contract).
  262. for (const dispose of disposers) dispose()
  263. expect(registered.every(r => r.disposed)).toBe(true)
  264. })
  265. })
  266. describe('DetailsPanel diff Output section', () => {
  267. function mount(snapshot: ConversationSnapshot, selection: SelectionTarget | null, cwd?: string) {
  268. localStorage.clear()
  269. const chat = createChatStore().create()
  270. if (selection !== null) chat.actions.select(selection)
  271. const sessions = createSnapshotStore<SessionListState>(cwd === undefined
  272. ? { ids: [], byId: {}, current: undefined, phase: 'ready', subagentsByParent: {}, currentAddress: undefined }
  273. : {
  274. ids: [SID],
  275. byId: { [SID]: { id: SID, displayTitle: 'r', running: false, blank: false, updatedAt: 0, cwd } },
  276. current: SID,
  277. phase: 'ready',
  278. subagentsByParent: {},
  279. currentAddress: undefined,
  280. })
  281. const workspaces = createSnapshotStore<WorkspaceListState>({
  282. items: [], archivedSessionIds: [], state: 'idle', phase: 'ready', error: null,
  283. baselinesReady: true, recentWorkspaceId: undefined,
  284. })
  285. return render(
  286. <DetailsPanel
  287. sessionId={SID}
  288. useSession={bindSnapshotSelector({ getSnapshot: () => snapshot, subscribe: () => () => {} })}
  289. useSessions={bindSnapshotSelector(sessions)}
  290. useWorkspaces={bindSnapshotSelector(workspaces)}
  291. useInput={(() => { throw new Error('unused') })}
  292. inputActions={{ setDraft: () => {}, submit: () => {} }}
  293. useProjection={(() => undefined)}
  294. useStore={bindSnapshotSelector(chat)}
  295. actions={chat.actions}
  296. closeDetails={vi.fn()}
  297. t={t}
  298. />,
  299. )
  300. }
  301. function snapshot(over: Partial<ConversationSnapshot> = {}): ConversationSnapshot {
  302. return {
  303. sessionId: SID, nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [], codeDispatches: new Map(),
  304. pending: [], queue: [], running: false, composerPhase: 'active', removed: false,
  305. openState: 'open', openError: null, hasMore: false, loadingOlder: false,
  306. promptError: null, blank: false, subagent: null, lastAgentError: null, ...over,
  307. }
  308. }
  309. const target: SelectionTarget = { turnSeq: 10, callId: 'c1', toolName: 'edit' }
  310. it('renders the applied diff at full height, keeping the JSON Input section', () => {
  311. const view = mount(snapshot({ nodes: [settled()] }), target)
  312. expect(view.getByText(/"file_path"/)).toBeTruthy()
  313. expect(view.container.querySelector('[data-diff]')).not.toBeNull()
  314. expect(view.getByText('hello fixture')).toBeTruthy()
  315. })
  316. it('a running diff call renders its intended change, not the 运行中… placeholder', () => {
  317. const view = mount(snapshot({ runningCalls: [running()] }), target)
  318. expect(view.container.querySelector('[data-diff]')).not.toBeNull()
  319. expect(view.queryByText('运行中…')).toBeNull()
  320. })
  321. it('a non-diff result keeps the flattened pre', () => {
  322. const view = mount(snapshot({
  323. nodes: [settled({
  324. callView: null, resultView: null,
  325. content: [{ type: 'text', text: 'permission denied' }],
  326. })],
  327. }), target)
  328. expect(view.container.querySelector('[data-diff]')).toBeNull()
  329. expect(view.getByText('输出').closest('section')?.querySelector('pre')?.textContent).toBe('permission denied')
  330. })
  331. })