diff-card.spec.tsx 17 KB

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