diff-card.client.spec.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. // @vitest-environment jsdom
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { cleanup, fireEvent, render } from '@testing-library/react'
  4. import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime'
  5. import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
  6. import type { RunningToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-ui-chat/client'
  7. import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client'
  8. import type { SessionId } from '@deepseek-ai/dsh-session/types'
  9. import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
  10. import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
  11. import { CHAT_DIFF_MAX_LINES, diffCardModel } from '../src/client/tool/models/diff-card-model.ts'
  12. import { GenericToolCard, type GenericToolCardProps } from '../src/client/tool/toolviews/GenericToolCard.tsx'
  13. import { FileMutationRow, fileMutationToolview } from '../src/client/tool/toolviews/file-mutation-row.tsx'
  14. import { zh } from '@deepseek-ai/dsh-client-ui-conversation/src/client/locales.ts'
  15. afterEach(cleanup)
  16. type FileMutationRowProps = Parameters<typeof FileMutationRow>[0]
  17. const SID = 's1' as SessionId
  18. const t = makeTranslate(zh, commonZh)
  19. const ARGS = '{"file_path":"notes/demo.txt","old_string":"hello","new_string":"hello fixture"}'
  20. const DIFFS = [{ path: 'notes/demo.txt', oldText: 'hello', newText: 'hello fixture' }]
  21. const running = (over?: Partial<RunningToolCall>): RunningToolCall => ({
  22. callId: 'c1', name: 'edit', argsRaw: ARGS,
  23. turn: 1, step: 1, time: 1_000, subCalls: [], ...over,
  24. })
  25. const settled = (over?: Partial<ToolResultNode>): ToolResultNode => ({
  26. kind: 'tool-result', seq: 10, time: 2_000, callId: 'c1',
  27. call: { name: 'edit', argsRaw: ARGS },
  28. callTime: 1_000,
  29. content: [{ type: 'text', text: 'The file notes/demo.txt has been updated successfully.' }], isError: false,
  30. meta: { diffs: DIFFS }, subCalls: [], ...over,
  31. })
  32. describe('diffCardModel', () => {
  33. it('derives a running card from raw edit arguments', () => {
  34. expect(diffCardModel(running())).toEqual({
  35. card: { diffs: [{ path: 'notes/demo.txt', oldText: 'hello', newText: 'hello fixture' }] },
  36. })
  37. })
  38. it('preserves the Host presenter\'s whole-file diff for an empty old_string', () => {
  39. expect(diffCardModel(running({
  40. argsRaw: '{"file_path":"notes/demo.txt","old_string":"","new_string":"replacement"}',
  41. }))).toEqual({
  42. card: { diffs: [{ path: 'notes/demo.txt', oldText: null, newText: 'replacement' }] },
  43. })
  44. })
  45. it.each([
  46. {
  47. command: 'create',
  48. args: { command: 'create', path: 'notes/new.txt', file_text: 'new file\n' },
  49. diff: { path: 'notes/new.txt', oldText: null, newText: 'new file\n' },
  50. },
  51. {
  52. command: 'str_replace',
  53. args: { command: 'str_replace', path: 'notes/demo.txt', old_str: 'old', new_str: 'new' },
  54. diff: { path: 'notes/demo.txt', oldText: 'old', newText: 'new' },
  55. },
  56. ])('preserves the running str_replace_editor $command diff', ({ args, diff }) => {
  57. expect(diffCardModel(running({
  58. name: 'str_replace_editor',
  59. argsRaw: JSON.stringify(args),
  60. }))).toEqual({ card: { diffs: [diff] } })
  61. })
  62. it('preserves str_replace_editor defaults and its settled Generic result', () => {
  63. const argsRaw = JSON.stringify({ command: 'str_replace', path: 'notes/demo.txt' })
  64. expect(diffCardModel(running({ name: 'str_replace_editor', argsRaw }))).toEqual({
  65. card: { diffs: [{ path: 'notes/demo.txt', oldText: null, newText: '' }] },
  66. })
  67. expect(diffCardModel(settled({
  68. call: { name: 'str_replace_editor', argsRaw },
  69. meta: { diffs: [{ path: 'notes/demo.txt', oldText: 'old', newText: 'new' }] },
  70. }))).toBeNull()
  71. })
  72. it('keeps unsupported or malformed str_replace_editor calls generic', () => {
  73. const editor = (args: Record<string, unknown>) => running({
  74. name: 'str_replace_editor', argsRaw: JSON.stringify(args),
  75. })
  76. expect(diffCardModel(editor({ command: 'view', path: 'notes/demo.txt' }))).toBeNull()
  77. expect(diffCardModel(editor({ command: 'insert', path: 'notes/demo.txt', new_str: 'x' }))).toBeNull()
  78. expect(diffCardModel(editor({ command: 'create', path: '', file_text: 'x' }))).toBeNull()
  79. expect(diffCardModel(editor({ command: 'create', path: 'notes/demo.txt', file_text: 1 }))).toBeNull()
  80. expect(diffCardModel(editor({ command: 'str_replace', path: 'notes/demo.txt', old_str: 1 }))).toBeNull()
  81. expect(diffCardModel(editor({ command: 'str_replace', path: 'notes/demo.txt', new_str: 1 }))).toBeNull()
  82. })
  83. it('derives a settled card from result metadata, which replaces the intended diff', () => {
  84. expect(diffCardModel(settled({
  85. meta: { diffs: [{ path: 'notes/demo.txt', oldText: 'a', newText: 'b' }] },
  86. }))).toEqual({
  87. card: { diffs: [{ path: 'notes/demo.txt', oldText: 'a', newText: 'b' }] },
  88. })
  89. })
  90. it('uses the intended write diff when successful metadata reports no applied hunk', () => {
  91. const writeArgs = JSON.stringify({ file_path: 'notes/new.txt', content: 'hello fixture\n' })
  92. expect(diffCardModel(settled({
  93. call: { name: 'write', argsRaw: writeArgs },
  94. meta: { diffs: [] },
  95. }))).toEqual({
  96. card: { diffs: [{ path: 'notes/new.txt', oldText: null, newText: 'hello fixture\n' }] },
  97. })
  98. })
  99. it('returns null for missing calls, errors, malformed args, unrelated tools, and child dispatches', () => {
  100. expect(diffCardModel(settled({ call: null }))).toBeNull()
  101. expect(diffCardModel(settled({ isError: true }))).toBeNull()
  102. expect(diffCardModel(running({ argsRaw: '{' }))).toBeNull()
  103. expect(diffCardModel(running({ name: 'read' }))).toBeNull()
  104. expect(diffCardModel(running({ parentCallId: 'parent' }))).toBeNull()
  105. expect(diffCardModel(settled({ parentCallId: 'parent' }))).toBeNull()
  106. })
  107. it('keeps edit generic for missing or malformed applied metadata', () => {
  108. expect(diffCardModel(settled({ meta: undefined }))).toBeNull()
  109. expect(diffCardModel(settled({ meta: null }))).toBeNull()
  110. expect(diffCardModel(settled({ meta: { diffs: 'nope' } }))).toBeNull()
  111. expect(diffCardModel(settled({ meta: { diffs: [null] } }))).toBeNull()
  112. expect(diffCardModel(settled({ meta: { diffs: [{ path: 1, oldText: null, newText: 'x' }] } }))).toBeNull()
  113. expect(diffCardModel(settled({ meta: { diffs: [{ path: 'a', oldText: 5, newText: 'x' }] } }))).toBeNull()
  114. expect(diffCardModel(settled({ meta: { diffs: [{ path: 'a', oldText: null, newText: 9 }] } }))).toBeNull()
  115. })
  116. it.each([
  117. undefined,
  118. null,
  119. { diffs: 'nope' },
  120. { diffs: [null] },
  121. ])('uses the intended write diff when applied metadata is absent or malformed: %j', (meta) => {
  122. const writeArgs = JSON.stringify({ file_path: 'notes/new.txt', content: 'hello fixture\n' })
  123. expect(diffCardModel(settled({
  124. call: { name: 'write', argsRaw: writeArgs },
  125. meta,
  126. }))).toEqual({
  127. card: { diffs: [{ path: 'notes/new.txt', oldText: null, newText: 'hello fixture\n' }] },
  128. })
  129. })
  130. it('validates mutation escalation fields but accepts unrelated open-root fields', () => {
  131. const args = (fields: Record<string, unknown>) => JSON.stringify({
  132. file_path: 'notes/demo.txt', old_string: 'hello', new_string: 'hello fixture', ...fields,
  133. })
  134. expect(diffCardModel(running({ argsRaw: args({ sandbox_permissions: 7, justification: 'Need access' }) }))).toBeNull()
  135. expect(diffCardModel(running({ argsRaw: args({ sandbox_permissions: 'workspace-write' }) }))).toBeNull()
  136. expect(diffCardModel(running({ argsRaw: args({ extension: { version: 1 } }) }))).not.toBeNull()
  137. })
  138. })
  139. describe('chat row diff body', () => {
  140. const ownerProps = (block: RunningToolCall | ToolResultNode): GenericToolCardProps => ({
  141. loadImage: vi.fn(() => Promise.reject(new Error('not used'))),
  142. callId: 'c1', toolName: 'edit', block, openFile: vi.fn(), t,
  143. })
  144. it('the expanded body is the applied diff, capped tighter than the panel', () => {
  145. expect(CHAT_DIFF_MAX_LINES).toBeLessThan(16)
  146. const view = render(<GenericToolCard {...ownerProps(settled())} />)
  147. // Collapsed: the summary row (path) only, no diff body.
  148. expect(view.queryByText('hello fixture')).toBeNull()
  149. // The path link is not the expand control; the leading toggle is.
  150. fireEvent.click(view.container.querySelector('[data-expandable]')!)
  151. expect(view.container.querySelector('[data-diff]')).not.toBeNull()
  152. expect(view.getByText('hello fixture')).toBeTruthy()
  153. })
  154. it('a running diff call expands to its intended change', () => {
  155. const view = render(<GenericToolCard {...ownerProps(running())} />)
  156. fireEvent.click(view.container.querySelector('[data-expandable]')!)
  157. expect(view.container.querySelector('[data-diff]')).not.toBeNull()
  158. })
  159. it('a non-diff call keeps the args-JSON text body', () => {
  160. // A non-file tool name so the row is not single-file (no path link), and its
  161. // args body is the fallback the diff card must not have replaced.
  162. const view = render(<GenericToolCard {...{
  163. callId: 'c1', toolName: 'some_tool', openFile: vi.fn(),
  164. loadImage: vi.fn(() => Promise.reject(new Error('not used'))), t,
  165. block: settled({
  166. call: { name: 'some_tool', argsRaw: '{"foo":"bar"}' },
  167. meta: undefined,
  168. }),
  169. }} />)
  170. fireEvent.click(view.container.querySelector('[data-expandable]')!)
  171. expect(view.container.querySelector('[data-diff]')).toBeNull()
  172. expect(view.getByText(/"foo"/)).toBeTruthy()
  173. })
  174. })
  175. describe('FileMutationRow diff card', () => {
  176. const list = () => createSnapshotStore<SessionListState>({
  177. ids: [SID],
  178. byId: { [SID]: { id: SID, displayTitle: 'r', running: false, blank: false, updatedAt: 0, cwd: '/w/app' } },
  179. current: SID,
  180. phase: 'ready',
  181. subagentsByParent: {}, jobsBySession: {},
  182. currentAddress: undefined,
  183. })
  184. const rowProps = (block: RunningToolCall | ToolResultNode, toolName = 'edit'): FileMutationRowProps => ({
  185. callId: 'c1', toolName, block, openFile: vi.fn(), cwd: '/w/app',
  186. sessionId: SID, useSessions: bindSnapshotSelector(list()),
  187. t,
  188. } as unknown as FileMutationRowProps)
  189. /** The whole summary row is the expand toggle (ToolRow's unified interaction). */
  190. const toggleRow = (view: { container: HTMLElement }) => {
  191. fireEvent.click(view.container.querySelector('[data-expandable]')!)
  192. }
  193. it('collapses to the summary row; expanding reveals the applied diff card', () => {
  194. const view = render(<FileMutationRow {...rowProps(settled())} />)
  195. // The diff card is collapsed by default — not in the DOM until expanded.
  196. expect(view.container.querySelector('[data-diff]')).toBeNull()
  197. expect(view.queryByText('hello fixture')).toBeNull()
  198. toggleRow(view)
  199. expect(view.container.querySelector('[data-diff]')).not.toBeNull()
  200. expect(view.getByText('hello fixture')).toBeTruthy()
  201. expect(view.getByText('复制')).toBeTruthy()
  202. })
  203. it('the summary is a path link that opens the tool path through the host', () => {
  204. const openFile = vi.fn()
  205. const view = render(<FileMutationRow {...{ ...rowProps(settled()), openFile }} />)
  206. // The path link rides the collapsed summary, so it opens without expanding.
  207. fireEvent.click(view.getByRole('button', { name: 'notes/demo.txt' }))
  208. // The row passes the tool's own path; the injected openFile resolves it
  209. // against the session cwd (apply.ts), so the row must not resolve twice.
  210. expect(openFile).toHaveBeenCalledWith('notes/demo.txt')
  211. })
  212. it('registers under write too, rendering a create as an added-only diff', () => {
  213. const writeArgs = '{"file_path":"notes/new.txt","content":"hello fixture\\n"}'
  214. const view = render(<FileMutationRow {...rowProps(settled({
  215. call: { name: 'write', argsRaw: writeArgs },
  216. meta: { diffs: [] },
  217. }), 'write')} />)
  218. // The collapsed row already carries the card's +/- totals beside the path.
  219. expect(view.getByText('+1 -0')).toBeTruthy()
  220. // The footer counts live inside the collapsed diff card.
  221. toggleRow(view)
  222. expect(view.getByText('└ +1 -0 · 1 个文件')).toBeTruthy()
  223. })
  224. it('reflects the run state on its leading slot', () => {
  225. const runningView = render(<FileMutationRow {...rowProps(running())} />)
  226. expect(runningView.container.querySelector('[data-state="running"]')).not.toBeNull()
  227. cleanup()
  228. const errorView = render(<FileMutationRow {...rowProps(settled({ isError: true }))} />)
  229. expect(errorView.container.querySelector('[data-state="error"]')).not.toBeNull()
  230. })
  231. it('a mutation result with no metadata renders the summary row alone', () => {
  232. const view = render(<FileMutationRow {...rowProps(settled({ meta: undefined }))} />)
  233. // No diff material: expanding shows the args-JSON body, never a diff card.
  234. expect(view.container.querySelector('[data-diff]')).toBeNull()
  235. toggleRow(view)
  236. expect(view.container.querySelector('[data-diff]')).toBeNull()
  237. })
  238. it('surfaces the result text when an errored mutation has no diff card', () => {
  239. // Failed mutations have no diff; ToolRow keeps the model-facing error text.
  240. const view = render(<FileMutationRow {...rowProps(settled({
  241. isError: true,
  242. content: [{ type: 'text', text: 'old_string not found in notes/demo.txt' }],
  243. }))} />)
  244. expect(view.container.querySelector('[data-diff]')).toBeNull()
  245. expect(view.getByText('old_string not found in notes/demo.txt')).toBeTruthy()
  246. })
  247. it('falls back to the error name/code when an errored result has no text block', () => {
  248. const view = render(<FileMutationRow {...rowProps(settled({
  249. isError: true, content: [],
  250. error: { name: 'ToolError', code: 'sandbox_denied' },
  251. }))} />)
  252. expect(view.getByText('ToolError: sandbox_denied')).toBeTruthy()
  253. })
  254. it('shows no error summary for a successful diff or a running call', () => {
  255. // ToolRow's error-color summary line is set only on the error state.
  256. const ok = render(<FileMutationRow {...rowProps(settled())} />)
  257. expect(ok.container.querySelector('[class*="_errorSummary_"]')).toBeNull()
  258. cleanup()
  259. const run = render(<FileMutationRow {...rowProps(running())} />)
  260. expect(run.container.querySelector('[class*="_errorSummary_"]')).toBeNull()
  261. })
  262. it('shows the stopped state when the call was interrupted', () => {
  263. const view = render(<FileMutationRow {...rowProps(settled({
  264. isError: true,
  265. error: { name: 'ToolError', code: 'interrupted' },
  266. }))} />)
  267. expect(view.container.querySelector('[data-state="stopped"]')).not.toBeNull()
  268. // The amber StateDot is aria-hidden, so ToolRow carries the state to AT as
  269. // visually-hidden text; without it a stopped row is a colour-only signal.
  270. expect(view.getByText('已停止')).toBeTruthy()
  271. })
  272. it('renders a plain summary span when the call carries no file path', () => {
  273. // Empty args leave deriveFilePath undefined, so the summary is not a link.
  274. const view = render(<FileMutationRow {...rowProps(settled({
  275. call: { name: 'edit', argsRaw: '' },
  276. }))} />)
  277. expect(view.container.querySelector('[class*="_fileLink_"]')).toBeNull()
  278. expect(view.container.querySelector('[class*="_summary_"]')).not.toBeNull()
  279. })
  280. })
  281. describe('fileMutationToolview registration', () => {
  282. it('registers one component under both edit and write, and each disposes', () => {
  283. const registered: { key: string; locale: unknown; disposed: boolean }[] = []
  284. const disposers: (() => void)[] = []
  285. let disposeInjection = (): void => {}
  286. const ctx = {
  287. slots: {
  288. inject: (_name: string, callback: () => Iterable<() => void>) => {
  289. const active = [...callback()]
  290. disposeInjection = () => { for (const dispose of active.reverse()) dispose() }
  291. return disposeInjection
  292. },
  293. register: ({ key, locale }: { name: string; key: string; locale?: string }) => {
  294. const entry = { key, locale, disposed: false }
  295. registered.push(entry)
  296. const dispose = () => { entry.disposed = true }
  297. disposers.push(dispose)
  298. return dispose
  299. },
  300. },
  301. }
  302. fileMutationToolview.apply(ctx as never)
  303. expect(registered.map(r => r.key).sort()).toEqual(['edit', 'write'])
  304. // Both keys claim the conversation locale seat ToolRow's body copy needs.
  305. expect(registered.map(r => r.locale)).toEqual(['conversation', 'conversation'])
  306. expect(fileMutationToolview.inject).toEqual(['slots'])
  307. // Disposal removes each contribution (packages/AGENTS.md registry contract).
  308. disposeInjection()
  309. expect(registered.every(r => r.disposed)).toBe(true)
  310. })
  311. })