chat-code-subcalls.spec.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. // @vitest-environment jsdom
  2. // Code Mode sub-call acceptance on the REAL machinery stack (same bench as
  3. // chat-toolview-slot.spec): a run_code result renders the 'code' variant row
  4. // (description summary, program body), its logged sub-dispatches render as
  5. // always-visible nested rows through the SAME keyed toolview hole — the bash
  6. // sub-call lands in the bash sample plugin's registration exactly like a
  7. // top-level bash row, unregistered sub-tools fall back to GenericToolCard —
  8. // and a file sub-row click opens the host path. Running parents
  9. // (runningCalls) nest their so-far dispatches the same way.
  10. import { Context } from '@deepseek-ai/cordis'
  11. import { stubSettingsScope } from '@deepseek-ai/dsh-client-test-runtime'
  12. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  13. import { cleanup, fireEvent, render } from '@testing-library/react'
  14. import {
  15. ConversationEventRegistry, ConversationViewRegistry, createSnapshotStore,
  16. EMPTY_CONVERSATION_VIEWS, SlotsService,
  17. } from '@deepseek-ai/dsh-client-runtime/client'
  18. import type {
  19. ConversationSnapshot, RunningToolCall, SessionId, SessionListState,
  20. ToolCallBlock, ToolResultNode, WorkspaceListState,
  21. } from '@deepseek-ai/dsh-client-runtime/client'
  22. import { createSlotRenderer } from '@deepseek-ai/dsh-client-web-react'
  23. import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
  24. import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'
  25. import { apply as applyConversation, inject as injectConversation } from '@deepseek-ai/dsh-client-ui-conversation/client'
  26. import { apply as applyTool, inject as injectTool } from '../src/client/apply.ts'
  27. import { toolChatSnapshot } from './tool-details-render.tsx'
  28. const SID = 's1' as SessionId
  29. /** jsdom has no ResizeObserver; the composer seat publishes its height through one. */
  30. class ResizeObserverStub {
  31. observe(): void {}
  32. unobserve(): void {}
  33. disconnect(): void {}
  34. }
  35. afterEach(() => {
  36. cleanup()
  37. vi.unstubAllGlobals()
  38. })
  39. beforeEach(() => {
  40. localStorage.clear()
  41. vi.stubGlobal('ResizeObserver', ResizeObserverStub)
  42. })
  43. const PROGRAM = 'const listing = await tools.bash({ command: "ls notes", description: "List notes" })\nreturn listing'
  44. const RUN_CODE_ARGS = JSON.stringify({ code: PROGRAM, description: 'List the notes directory' })
  45. const codeResult = (seq: number, callId: string): ToolResultNode => ({
  46. kind: 'tool-result', seq, time: seq * 1_000, callId,
  47. call: { name: 'run_code', argsRaw: RUN_CODE_ARGS },
  48. callTime: seq * 1_000 - 500,
  49. content: [{ type: 'text', text: 'demo.txt' }], isError: false, callView: null, resultView: null,
  50. subCalls: [],
  51. })
  52. const runningCode = (callId: string): RunningToolCall => ({
  53. callId, name: 'run_code', argsRaw: RUN_CODE_ARGS, turn: 9, step: 0, time: 9_000, callView: null,
  54. subCalls: [],
  55. })
  56. const subCall = (
  57. seq: number, parent: string, n: number, name: string, args: object, resultText: string, isError = false,
  58. ): ToolCallBlock => ({
  59. kind: 'tool-result', seq, time: seq * 1_000,
  60. callId: `${parent}:code:${n}`,
  61. call: { name, argsRaw: JSON.stringify(args) },
  62. callTime: seq * 1_000,
  63. content: [{ type: 'text', text: resultText }], isError, callView: null, resultView: null,
  64. subCalls: [],
  65. })
  66. function snapshotWith(
  67. nodes: ToolResultNode[],
  68. subCalls: readonly ToolCallBlock[],
  69. runningCalls: RunningToolCall[] = [],
  70. ): ConversationSnapshot {
  71. const nestedNodes = nodes.map(node => ({ ...node, subCalls }))
  72. const nestedRunningCalls = runningCalls.map(call => ({ ...call, subCalls }))
  73. return {
  74. sessionId: SID, views: EMPTY_CONVERSATION_VIEWS,
  75. chat: toolChatSnapshot(nestedNodes, nestedRunningCalls),
  76. nodes: nestedNodes, turnTimings: new Map(), turnEnds: new Map(), partial: null,
  77. runningCalls: nestedRunningCalls,
  78. pending: [], queue: [], running: runningCalls.length > 0, composerPhase: 'active', removed: false,
  79. openState: 'open', openError: null,
  80. hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent: null, lastAgentError: null,
  81. }
  82. }
  83. /** Test-owned AppFrame role: declares and renders the resident conversation area. */
  84. type AppRootProps = PropsRenderSlots<'conversation' | 'details'>
  85. function AppRoot({ renderSlot }: AppRootProps) {
  86. return <>{renderSlot('conversation', {})}</>
  87. }
  88. /**
  89. * Same real-stack bench as the toolview-slot spec: SlotsService + renderer +
  90. * both owning package applies; fakes only at service boundaries.
  91. */
  92. async function bench(snapshot: ConversationSnapshot) {
  93. const ctx = new Context()
  94. const slotsFiber = ctx.plugin(SlotsService)
  95. await slotsFiber.await()
  96. await ctx.plugin(ConversationEventRegistry).await()
  97. await ctx.plugin(ConversationViewRegistry).await()
  98. const slots = ctx.get('slots') as SlotsService
  99. const session = createSnapshotStore<ConversationSnapshot>(snapshot)
  100. const list = createSnapshotStore<SessionListState>({
  101. ids: [SID],
  102. byId: { [SID]: { id: SID, title: 'S', displayTitle: 'S', running: false, blank: false, updatedAt: 1 } },
  103. current: SID,
  104. phase: 'ready', subagentsByParent: {}, tasksBySession: {}, currentAddress: undefined,
  105. })
  106. const scoped = { send: vi.fn(async () => {}), cancel: vi.fn(async () => {}) }
  107. const layout = { openDetails: vi.fn(), closeDetails: vi.fn() }
  108. // Provide-channel contributions land in this bundle the way the runtime
  109. // materializes them; the renderer host serves it through provideInfo.
  110. const provided: { hooks: Record<string, unknown>; props: Record<string, unknown> } = { hooks: {}, props: {} }
  111. // Identity-stable currentProvideInfo snapshot (uSES getSnapshot contract),
  112. // materialized on first render after the provide contributions landed.
  113. let infoCell: { sessionId: SessionId; hooks: Record<string, unknown>; props: Record<string, unknown> } | undefined
  114. const sessionsFake = {
  115. list,
  116. binding: (id: SessionId) => (id === SID
  117. ? { sessionId: SID, session, ctx: { effect: () => {}, on: () => () => {} } }
  118. : undefined),
  119. scope: () => ({ get: () => scoped }),
  120. scopeOf: () => SID,
  121. provide: (descriptor: { resolve: (binding: unknown) => { hooks?: Record<string, unknown>; props?: Record<string, unknown> } }) => {
  122. const contribution = descriptor.resolve(sessionsFake.binding(SID))
  123. Object.assign(provided.hooks, contribution.hooks ?? {})
  124. Object.assign(provided.props, contribution.props ?? {})
  125. return () => {}
  126. },
  127. provideInfo: (id: string) => (id === SID
  128. ? { sessionId: SID, hooks: { session, ...provided.hooks }, props: provided.props }
  129. : undefined),
  130. currentProvideInfo: {
  131. getSnapshot: () => infoCell ??= { sessionId: SID, hooks: { session, ...provided.hooks }, props: provided.props },
  132. subscribe: () => () => {},
  133. },
  134. create: vi.fn(),
  135. open: vi.fn(),
  136. }
  137. ctx.provide('sessions', sessionsFake)
  138. const workspaces = {
  139. list: createSnapshotStore<WorkspaceListState>({
  140. items: [], archivedSessionIds: [], state: 'idle', phase: 'ready', error: null,
  141. baselinesReady: true, recentWorkspaceId: undefined,
  142. }),
  143. startSession: vi.fn(),
  144. sendSession: vi.fn(),
  145. openPath: vi.fn(async () => {}),
  146. }
  147. ctx.provide('workspaces', workspaces)
  148. ctx.provide('layout', layout)
  149. ctx.provide('connection', { api: { settings: {} }, isLoopback: false } as never)
  150. // ui-theme's Appearance row binds a durable scope through these two.
  151. ctx.provide('remote', { $on: () => () => {} } as never)
  152. ctx.provide('settingsScope', { bind: () => stubSettingsScope().scope } as never)
  153. const locale = new LocaleService(ctx)
  154. ctx.provide('locale', locale)
  155. slots.installLocale(locale)
  156. slots.install(createSlotRenderer())
  157. slots.register({
  158. name: 'root',
  159. children: {
  160. 'conversation': { kind: 'single', scope: 'session-maybe' },
  161. 'details': { kind: 'single', scope: 'session' },
  162. },
  163. }, AppRoot)
  164. const fiber = ctx.plugin({ inject: [...injectConversation], apply: applyConversation })
  165. await fiber.await()
  166. const toolFiber = ctx.plugin({ inject: [...injectTool], apply: applyTool })
  167. await toolFiber.await()
  168. return { ctx, slots, fiber, toolFiber, session, layout, workspaces }
  169. }
  170. function mountApp(slots: SlotsService) {
  171. return render(<>{slots.renderSlot('root', {})}</>)
  172. }
  173. describe('run_code sub-calls through the real chat machinery', () => {
  174. it('renders the code-variant parent row with the description summary and nested sub-rows', async () => {
  175. const parent = 'call-64'
  176. const subCalls = [
  177. subCall(11, parent, 1, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  178. subCall(12, parent, 2, 'mystery', { n: 1 }, 'ok'),
  179. ]
  180. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  181. const view = mountApp(b.slots)
  182. // Parent row: the code variant with the model-authored description.
  183. const codeRoot = view.container.querySelector('[data-variant="code"]')
  184. expect(codeRoot).not.toBeNull()
  185. expect(view.getByText('Code')).toBeTruthy()
  186. expect(view.getByText('List the notes directory')).toBeTruthy()
  187. // Nested rows are ALWAYS visible (no parent expand needed): the bash
  188. // sub-call landed in the bash sample plugin's keyed registration — Bash ·
  189. // description chrome, same as a top-level bash row — and the unregistered
  190. // sub-tool fell back to GenericToolCard at the same render site.
  191. const nest = view.container.querySelector('[data-subcalls]')
  192. expect(nest).not.toBeNull()
  193. expect(nest!.querySelector('[data-sample="bash"]')).not.toBeNull()
  194. expect(view.getByText('Bash')).toBeTruthy()
  195. expect(view.getByText('List notes')).toBeTruthy()
  196. expect(view.getByText('Tool call')).toBeTruthy()
  197. })
  198. it('renders Cordis sub-calls with lifecycle titles over the generic variants', async () => {
  199. const parent = 'call-cordis'
  200. const code = 'return { name: "audit", apply(ctx) {} }'
  201. const subCalls = [
  202. subCall(11, parent, 1, 'cordis_inspect', { what: 'temporary' }, '## Temporary Plugins'),
  203. subCall(12, parent, 2, 'cordis_mount', { code }, 'Temporary Plugin dyn-2 is running'),
  204. subCall(13, parent, 3, 'cordis_unmount', { id: 'dyn-2' }, 'Temporary Plugin dyn-2 was unmounted and removed.'),
  205. ]
  206. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  207. const view = mountApp(b.slots)
  208. const nest = view.container.querySelector('[data-subcalls]')!
  209. expect(nest.querySelector('[data-tool="cordis_inspect"]')?.textContent).toContain('Inspect')
  210. const mounted = nest.querySelector('[data-variant="code"]')
  211. expect(mounted?.textContent).toContain(`Mount temporary Plugin${code}`)
  212. expect(nest.querySelector('[data-tool="cordis_unmount"]')?.textContent)
  213. .toContain('Unmount temporary Plugindyn-2')
  214. fireEvent.click(mounted!.querySelector('[data-expandable]')!)
  215. expect(mounted!.querySelector('pre.shiki')?.textContent).toBe(code)
  216. })
  217. it('expanding the code row reveals the program body verbatim (shiki-tokenized)', async () => {
  218. const parent = 'call-64'
  219. const b = await bench(snapshotWith([codeResult(10, parent)], []))
  220. const view = mountApp(b.slots)
  221. // The code row is expandable via the whole summary row (body = the program).
  222. const toggle = view.container.querySelector('[data-variant="code"] [data-expandable]')
  223. expect(toggle).not.toBeNull()
  224. fireEvent.click(toggle!)
  225. // Shiki splits the program into token spans inside one <pre class="shiki">:
  226. // assert the whole text and the highlighted tree rather than one node.
  227. const pre = view.container.querySelector('pre.shiki')
  228. expect(pre).not.toBeNull()
  229. expect(pre!.textContent).toContain('const listing = await tools.bash')
  230. expect(pre!.querySelectorAll('span[style]').length).toBeGreaterThan(3)
  231. })
  232. it('an isError sub-call renders the error state dot exactly like a failed native row', async () => {
  233. const parent = 'call-64'
  234. const subCalls = [
  235. subCall(11, parent, 1, 'mystery', { n: 1 }, 'Error: boom', true),
  236. ]
  237. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  238. const view = mountApp(b.slots)
  239. const nested = view.container.querySelector('[data-subcalls] [data-variant][data-state="error"]')
  240. expect(nested).not.toBeNull()
  241. })
  242. it('a file sub-row click opens the host path; bash sub-rows do not open details', async () => {
  243. const parent = 'call-64'
  244. const subCalls = [
  245. subCall(11, parent, 1, 'read', { path: 'notes/demo.txt' }, 'ok'),
  246. subCall(12, parent, 2, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  247. ]
  248. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  249. const view = mountApp(b.slots)
  250. view.getByText('notes/demo.txt').click()
  251. expect(b.layout.openDetails).not.toHaveBeenCalled()
  252. await vi.waitFor(() => {
  253. expect(b.workspaces.openPath).toHaveBeenCalledWith('notes/demo.txt')
  254. })
  255. view.getByText('List notes').click()
  256. expect(b.layout.openDetails).not.toHaveBeenCalled()
  257. })
  258. it('a RUNNING run_code call nests its so-far dispatches under the spinner row', async () => {
  259. const parent = 'call-live'
  260. const subCalls = [
  261. subCall(21, parent, 1, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  262. ]
  263. const b = await bench(snapshotWith([], subCalls, [runningCode(parent)]))
  264. const view = mountApp(b.slots)
  265. const running = view.container.querySelector('[data-variant="code"][data-state="running"]')
  266. expect(running).not.toBeNull()
  267. const nest = view.container.querySelector('[data-subcalls]')
  268. expect(nest).not.toBeNull()
  269. expect(nest!.querySelector('[data-sample="bash"]')).not.toBeNull()
  270. })
  271. it('a started-but-unsettled sub-call renders the running state exactly like a native in-flight row', async () => {
  272. const parent = 'call-live'
  273. const runningSub: ToolCallBlock = {
  274. callId: `${parent}:code:1`, name: 'grep', argsRaw: '{"pattern":"todo"}',
  275. turn: 0, step: 0, time: 21_000, callView: null, subCalls: [],
  276. }
  277. const b = await bench(snapshotWith([], [runningSub], [runningCode(parent)]))
  278. const view = mountApp(b.slots)
  279. // The nested row derives 'running' from the RunningToolCall shape — the
  280. // same data-state chrome (row sweep) a native in-flight row wears.
  281. const nested = view.container.querySelector('[data-subcalls] [data-variant][data-state="running"]')
  282. expect(nested).not.toBeNull()
  283. })
  284. it('an ordinary tool row renders no sub-call nest', async () => {
  285. const parent = 'call-64'
  286. const plain: ToolResultNode = {
  287. kind: 'tool-result', seq: 10, time: 10_000, callId: parent,
  288. call: { name: 'mystery', argsRaw: '{"n":1}' },
  289. callTime: 9_500,
  290. content: [], isError: false, callView: null, resultView: null, subCalls: [],
  291. }
  292. const b = await bench(snapshotWith([plain], []))
  293. const view = mountApp(b.slots)
  294. expect(view.container.querySelector('[data-subcalls]')).toBeNull()
  295. })
  296. })