chat-code-subcalls.client.spec.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. // @vitest-environment jsdom
  2. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  3. import { cleanup, fireEvent } from '@testing-library/react'
  4. import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
  5. import type {
  6. ChatSnapshot, RunningToolCall, ToolCallBlock, ToolResultNode,
  7. } from '@deepseek-ai/dsh-client-ui-chat/client'
  8. import type { SessionId } from '@deepseek-ai/dsh-session/types'
  9. import { SlotTestRuntime, TestRemote, stubSettingsScope } from '@deepseek-ai/dsh-client-test-runtime'
  10. import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
  11. import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
  12. import {
  13. ConversationEventRegistry, ConversationViewRegistry, type ConvViewOwnerProps,
  14. } from '@deepseek-ai/dsh-client-ui-conversation/client'
  15. import { en as conversationEn, NS as CONVERSATION_NS, zh as conversationZh } from '@deepseek-ai/dsh-client-ui-conversation/src/client/locales.ts'
  16. import { apply as applyChat, inject as injectChat } from '@deepseek-ai/dsh-client-ui-chat/client'
  17. import { apply as applyTool, inject as injectTool } from '../src/client/apply.ts'
  18. import { toolChatSnapshot } from './tool-fixtures.client.ts'
  19. const SID = 's1' as SessionId
  20. /** jsdom has no ResizeObserver; the composer seat publishes its height through one. */
  21. class ResizeObserverStub {
  22. observe(): void {}
  23. unobserve(): void {}
  24. disconnect(): void {}
  25. }
  26. const runtimes: SlotTestRuntime[] = []
  27. afterEach(async () => {
  28. cleanup()
  29. vi.unstubAllGlobals()
  30. for (const runtime of runtimes.splice(0)) await runtime.dispose()
  31. })
  32. beforeEach(() => {
  33. localStorage.clear()
  34. vi.stubGlobal('ResizeObserver', ResizeObserverStub)
  35. })
  36. const PROGRAM = 'const listing = await tools.bash({ command: "ls notes", description: "List notes" })\nreturn listing'
  37. const RUN_CODE_ARGS = JSON.stringify({ code: PROGRAM, description: 'List the notes directory' })
  38. const codeResult = (seq: number, callId: string): ToolResultNode => ({
  39. kind: 'tool-result', seq, time: seq * 1_000, callId,
  40. call: { name: 'run_code', argsRaw: RUN_CODE_ARGS },
  41. callTime: seq * 1_000 - 500,
  42. content: [{ type: 'text', text: 'demo.txt' }], isError: false,
  43. subCalls: [],
  44. })
  45. const runningCode = (callId: string): RunningToolCall => ({
  46. callId, name: 'run_code', argsRaw: RUN_CODE_ARGS, turn: 9, step: 0, time: 9_000,
  47. subCalls: [],
  48. })
  49. const subCall = (
  50. seq: number, parent: string, n: number, name: string, args: object, resultText: string, isError = false,
  51. ): ToolCallBlock => ({
  52. kind: 'tool-result', seq, time: seq * 1_000,
  53. callId: `${parent}:code:${n}`,
  54. parentCallId: parent,
  55. call: { name, argsRaw: JSON.stringify(args) },
  56. callTime: seq * 1_000,
  57. content: [{ type: 'text', text: resultText }], isError,
  58. subCalls: [],
  59. })
  60. function snapshotWith(
  61. nodes: ToolResultNode[],
  62. subCalls: readonly ToolCallBlock[],
  63. runningCalls: RunningToolCall[] = [],
  64. ): ChatSnapshot {
  65. const nestedNodes = nodes.map(node => ({ ...node, subCalls }))
  66. const nestedRunningCalls = runningCalls.map(call => ({ ...call, subCalls }))
  67. return toolChatSnapshot(nestedNodes, nestedRunningCalls)
  68. }
  69. /** Test-owned AppFrame role: declares and renders the Chat view list. */
  70. type AppRootProps = PropsRenderSlots<'conversation.view'>
  71. const VIEW_OWNER: ConvViewOwnerProps = {
  72. viewRequest: null,
  73. openView: () => {},
  74. completeViewRequest: () => {},
  75. }
  76. function AppRoot({ renderSlot }: AppRootProps) {
  77. return <>{renderSlot('conversation.view', VIEW_OWNER, { only: 'chat' })}</>
  78. }
  79. const ROOT_CHILDREN = {
  80. 'conversation.view': { kind: 'list', scope: 'session' },
  81. } as const
  82. /**
  83. * Same real-stack bench as the toolview-slot spec: renderer, Chat target, and
  84. * Tool registrations; fakes only at service boundaries.
  85. */
  86. async function bench(snapshot: ChatSnapshot) {
  87. const runtime = await SlotTestRuntime.create()
  88. runtimes.push(runtime)
  89. const ctx = runtime.ctx
  90. const chat = createSnapshotStore(snapshot)
  91. const events = new ConversationEventRegistry(ctx)
  92. const views = new ConversationViewRegistry(ctx)
  93. ctx.provide('settingsScope', { bind: () => stubSettingsScope().scope } as never)
  94. ctx.provide('uiConversation', {
  95. events,
  96. views,
  97. binding: () => ({ target: () => chat }),
  98. } as never)
  99. await runtime.sessions.add({
  100. id: SID,
  101. summary: { title: 'S', displayTitle: 'S', cwd: '/w' },
  102. snapshot: { running: snapshot.legacy.runningCalls.length > 0 },
  103. })
  104. const layout = { openDetails: vi.fn(), closeDetails: vi.fn() }
  105. const openWorkspacePath = vi.fn(async () => ({ ok: true, value: { opened: true } }))
  106. ctx.provide('layout', layout as never)
  107. const sidebarRight = { openResource: vi.fn<(address: string) => void>() }
  108. ctx.provide('sidebarRight', sidebarRight as never)
  109. ctx.provide('uiWorkspace', {} as never)
  110. new TestRemote(ctx, { session: { openWorkspacePath } })
  111. const locale = new LocaleRuntime(ctx)
  112. ctx.provide('locale', locale)
  113. locale.register(CONVERSATION_NS, { zh: conversationZh, en: conversationEn })
  114. runtime.slots.installLocale(locale)
  115. await runtime.root.declare(ROOT_CHILDREN, AppRoot)
  116. await runtime.mount({ inject: [...injectChat], apply: applyChat })
  117. await runtime.mount({ inject: [...injectTool], apply: applyTool })
  118. return { runtime, layout, openWorkspacePath, sidebarRight }
  119. }
  120. function mountApp(runtime: SlotTestRuntime) {
  121. return runtime.renderRoot()
  122. }
  123. describe('run_code sub-calls through the real chat machinery', () => {
  124. it('renders the code-variant parent row with the description summary and nested sub-rows', async () => {
  125. const parent = 'call-64'
  126. const subCalls = [
  127. subCall(11, parent, 1, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  128. subCall(12, parent, 2, 'mystery', { n: 1 }, 'ok'),
  129. ]
  130. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  131. const view = mountApp(b.runtime)
  132. // Parent row: the code variant with the model-authored description.
  133. const codeRoot = view.container.querySelector('[data-variant="code"]')
  134. expect(codeRoot).not.toBeNull()
  135. expect(view.getByText('Code')).toBeTruthy()
  136. expect(view.getByText('List the notes directory')).toBeTruthy()
  137. const nest = view.container.querySelector('[data-subcalls]')
  138. expect(nest).not.toBeNull()
  139. expect(nest!.querySelector('[data-sample="bash"]')).not.toBeNull()
  140. expect(view.getByText('Bash')).toBeTruthy()
  141. expect(view.getByText('List notes')).toBeTruthy()
  142. expect(view.getByText('Tool call')).toBeTruthy()
  143. const bashRow = nest!.querySelector('[data-sample="bash"]')!
  144. expect(bashRow.getAttribute('role')).toBe('button')
  145. fireEvent.click(bashRow)
  146. expect(nest!.querySelector('[data-terminal]')).not.toBeNull()
  147. expect(view.getByText('ls notes')).toBeTruthy()
  148. expect(nest!.querySelector('[data-terminal]')!.textContent).toContain('demo.txt')
  149. })
  150. it('renders Cordis sub-calls with lifecycle titles over the generic variants', async () => {
  151. const parent = 'call-cordis'
  152. const subCalls = [
  153. subCall(11, parent, 1, 'cordis_runtime_inspect', { what: 'temporary' }, '## Dynamic Packages'),
  154. subCall(12, parent, 2, 'cordis_run', { id: 'dyn-2' }, 'Dynamic package dyn-2 is running'),
  155. subCall(13, parent, 3, 'cordis_undefine', { id: 'dyn-2' }, 'Dynamic package dyn-2 was discarded.'),
  156. ]
  157. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  158. const view = mountApp(b.runtime)
  159. const nest = view.container.querySelector('[data-subcalls]')!
  160. // Each run-control verb names its act and shows the package id; without the
  161. // owned titles all three would read "Tool call · cordis_run · dyn-2".
  162. expect(nest.querySelector('[data-tool="cordis_runtime_inspect"]')?.textContent).toContain('Inspect')
  163. expect(nest.querySelector('[data-tool="cordis_run"]')?.textContent).toContain('Run Cordis Plugindyn-2')
  164. expect(nest.querySelector('[data-tool="cordis_undefine"]')?.textContent).toContain('Remove Cordis Plugindyn-2')
  165. // None of them is a code row: the program belongs to cordis_define, whose
  166. // own keyed card renders it (the next case covers the code row itself).
  167. expect(nest.querySelector('[data-variant="code"]')).toBeNull()
  168. })
  169. it('expanding the code row reveals the program body verbatim (shiki-tokenized)', async () => {
  170. const parent = 'call-64'
  171. const b = await bench(snapshotWith([codeResult(10, parent)], []))
  172. const view = mountApp(b.runtime)
  173. // The code row is expandable via the whole summary row (body = the program).
  174. const toggle = view.container.querySelector('[data-variant="code"] [data-expandable]')
  175. expect(toggle).not.toBeNull()
  176. fireEvent.click(toggle!)
  177. // Shiki splits the program into token spans inside one <pre class="shiki">:
  178. // assert the whole text and the highlighted tree rather than one node.
  179. const pre = view.container.querySelector('pre.shiki')
  180. expect(pre).not.toBeNull()
  181. expect(pre!.textContent).toContain('const listing = await tools.bash')
  182. expect(pre!.querySelectorAll('span[style]').length).toBeGreaterThan(3)
  183. })
  184. it('an isError sub-call renders the error state dot exactly like a failed native row', async () => {
  185. const parent = 'call-64'
  186. const subCalls = [
  187. subCall(11, parent, 1, 'mystery', { n: 1 }, 'Error: boom', true),
  188. ]
  189. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  190. const view = mountApp(b.runtime)
  191. const nested = view.container.querySelector('[data-subcalls] [data-variant][data-state="error"]')
  192. expect(nested).not.toBeNull()
  193. })
  194. it('a file sub-row click opens the file in the Sidebar; bash sub-rows open nothing', async () => {
  195. const parent = 'call-64'
  196. const subCalls = [
  197. subCall(11, parent, 1, 'read', { path: 'notes/demo.txt' }, 'ok'),
  198. subCall(12, parent, 2, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  199. ]
  200. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  201. const view = mountApp(b.runtime)
  202. view.getByText('notes/demo.txt').click()
  203. await vi.waitFor(() => {
  204. expect(b.sidebarRight.openResource).toHaveBeenCalledWith('dsh-resource://file/session/s1/notes/demo.txt')
  205. })
  206. expect(b.openWorkspacePath).not.toHaveBeenCalled()
  207. view.getByText('List notes').click()
  208. expect(b.sidebarRight.openResource).toHaveBeenCalledTimes(1)
  209. })
  210. it('a RUNNING run_code call nests its so-far dispatches under the spinner row', async () => {
  211. const parent = 'call-live'
  212. const subCalls = [
  213. subCall(21, parent, 1, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  214. ]
  215. const b = await bench(snapshotWith([], subCalls, [runningCode(parent)]))
  216. const view = mountApp(b.runtime)
  217. const running = view.container.querySelector('[data-variant="code"][data-state="running"]')
  218. expect(running).not.toBeNull()
  219. const nest = view.container.querySelector('[data-subcalls]')
  220. expect(nest).not.toBeNull()
  221. expect(nest!.querySelector('[data-sample="bash"]')).not.toBeNull()
  222. })
  223. it('a started-but-unsettled sub-call renders the running state exactly like a native in-flight row', async () => {
  224. const parent = 'call-live'
  225. const runningSub: ToolCallBlock = {
  226. callId: `${parent}:code:1`, name: 'grep', argsRaw: '{"pattern":"todo"}',
  227. parentCallId: parent,
  228. turn: 0, step: 0, time: 21_000, subCalls: [],
  229. }
  230. const b = await bench(snapshotWith([], [runningSub], [runningCode(parent)]))
  231. const view = mountApp(b.runtime)
  232. // The nested row derives 'running' from the RunningToolCall shape — the
  233. // same data-state chrome (row sweep) a native in-flight row wears.
  234. const nested = view.container.querySelector('[data-subcalls] [data-variant][data-state="running"]')
  235. expect(nested).not.toBeNull()
  236. })
  237. it('an ordinary tool row renders no sub-call nest', async () => {
  238. const parent = 'call-64'
  239. const plain: ToolResultNode = {
  240. kind: 'tool-result', seq: 10, time: 10_000, callId: parent,
  241. call: { name: 'mystery', argsRaw: '{"n":1}' },
  242. callTime: 9_500,
  243. content: [], isError: false, subCalls: [],
  244. }
  245. const b = await bench(snapshotWith([plain], []))
  246. const view = mountApp(b.runtime)
  247. expect(view.container.querySelector('[data-subcalls]')).toBeNull()
  248. })
  249. })