diff-card.spec.tsx 19 KB

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