diff-card.client.spec.tsx 20 KB

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