1
0

chat-code-subcalls.spec.tsx 14 KB

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