chat-code-subcalls.spec.tsx 13 KB

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