chat-code-subcalls.spec.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 sub-row click opens details for the sub-callId. 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: [], todos: [], 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. const sessionsFake = {
  80. list,
  81. binding: (id: SessionId) => (id === SID
  82. ? { sessionId: SID, session, ctx: { effect: () => {}, on: () => () => {} } }
  83. : undefined),
  84. scope: () => ({ get: () => scoped }),
  85. scopeOf: () => SID,
  86. provide: (descriptor: { resolve: (binding: unknown) => { hooks?: Record<string, unknown>; props?: Record<string, unknown> } }) => {
  87. const contribution = descriptor.resolve(sessionsFake.binding(SID))
  88. Object.assign(provided.hooks, contribution.hooks ?? {})
  89. Object.assign(provided.props, contribution.props ?? {})
  90. return () => {}
  91. },
  92. provideInfo: (id: string) => (id === SID
  93. ? { sessionId: SID, hooks: { session, ...provided.hooks }, props: provided.props }
  94. : undefined),
  95. maybeProvideInfo: (id: string | undefined) => (id === SID
  96. ? { sessionId: SID, hooks: { session, ...provided.hooks }, props: provided.props }
  97. : { hooks: provided.hooks, props: provided.props }),
  98. create: vi.fn(),
  99. open: vi.fn(),
  100. }
  101. ctx.provide('sessions', sessionsFake)
  102. ctx.provide('workspaces', {
  103. list: createSnapshotStore<WorkspaceListState>({
  104. items: [], state: 'idle', phase: 'ready', error: null,
  105. baselinesReady: true, recentWorkspaceId: undefined,
  106. }),
  107. startSession: vi.fn(),
  108. sendSession: vi.fn(),
  109. })
  110. ctx.provide('layout', layout)
  111. ctx.provide('i18n', { bind: () => (key: string) => key })
  112. slots.install(createSlotRenderer())
  113. slots.register({
  114. name: 'root',
  115. children: {
  116. 'conversation': { kind: 'single', scope: 'session-maybe' },
  117. 'details': { kind: 'single', scope: 'session' },
  118. },
  119. }, AppRoot)
  120. const fiber = ctx.plugin({ inject: [...inject], apply })
  121. await fiber.await()
  122. return { ctx, slots, fiber, session, layout }
  123. }
  124. function mountApp(slots: SlotsService) {
  125. return render(<>{slots.renderSlot('root', {})}</>)
  126. }
  127. describe('run_code sub-calls through the real chat machinery', () => {
  128. it('renders the code-variant parent row with the description summary and nested sub-rows', async () => {
  129. const parent = 'call-64'
  130. const dispatches = new Map([[parent, [
  131. subCall(11, parent, 1, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  132. subCall(12, parent, 2, 'mystery', { n: 1 }, 'ok'),
  133. ]]])
  134. const b = await bench(snapshotWith([codeResult(10, parent)], dispatches))
  135. const view = mountApp(b.slots)
  136. // Parent row: the code variant with the model-authored description.
  137. const codeRoot = view.container.querySelector('[data-variant="code"]')
  138. expect(codeRoot).not.toBeNull()
  139. expect(view.getByText('Code')).toBeTruthy()
  140. expect(view.getByText('List the notes directory')).toBeTruthy()
  141. // Nested rows are ALWAYS visible (no parent expand needed): the bash
  142. // sub-call landed in the bash sample plugin's keyed registration — Bash ·
  143. // description chrome, same as a top-level bash row — and the unregistered
  144. // sub-tool fell back to GenericToolCard at the same render site.
  145. const nest = view.container.querySelector('[data-subcalls]')
  146. expect(nest).not.toBeNull()
  147. expect(nest!.querySelector('[data-sample="bash-global"]')).not.toBeNull()
  148. expect(view.getByText('Bash')).toBeTruthy()
  149. expect(view.getByText('List notes')).toBeTruthy()
  150. expect(view.getByText('Tool call')).toBeTruthy()
  151. })
  152. it('renders Cordis sub-calls with lifecycle titles over the generic variants', async () => {
  153. const parent = 'call-cordis'
  154. const code = 'return { name: "audit", apply(ctx) {} }'
  155. const dispatches = new Map([[parent, [
  156. subCall(11, parent, 1, 'cordis_inspect', { what: 'temporary' }, '## Temporary Plugins'),
  157. subCall(12, parent, 2, 'cordis_mount', { code }, 'Temporary Plugin dyn-2 is running'),
  158. subCall(13, parent, 3, 'cordis_unmount', { id: 'dyn-2' }, 'Temporary Plugin dyn-2 was unmounted and removed.'),
  159. ]]])
  160. const b = await bench(snapshotWith([codeResult(10, parent)], dispatches))
  161. const view = mountApp(b.slots)
  162. const nest = view.container.querySelector('[data-subcalls]')!
  163. expect(nest.querySelector('[data-tool="cordis_inspect"]')?.textContent).toContain('Inspect')
  164. const mounted = nest.querySelector('[data-variant="code"]')
  165. expect(mounted?.textContent).toContain(`Mount temporary Plugin${code}`)
  166. expect(nest.querySelector('[data-tool="cordis_unmount"]')?.textContent)
  167. .toContain('Unmount temporary Plugindyn-2')
  168. fireEvent.click(mounted!.querySelector('button[aria-expanded]')!)
  169. expect(mounted!.querySelector('pre.shiki')?.textContent).toBe(code)
  170. })
  171. it('expanding the code row reveals the program body verbatim (shiki-tokenized)', async () => {
  172. const parent = 'call-64'
  173. const b = await bench(snapshotWith([codeResult(10, parent)], new Map()))
  174. const view = mountApp(b.slots)
  175. // The code row is expandable via its leading control (body = the program).
  176. const toggle = view.container.querySelector('[data-variant="code"] button[aria-expanded]')
  177. expect(toggle).not.toBeNull()
  178. fireEvent.click(toggle!)
  179. // Shiki splits the program into token spans inside one <pre class="shiki">:
  180. // assert the whole text and the highlighted tree rather than one node.
  181. const pre = view.container.querySelector('pre.shiki')
  182. expect(pre).not.toBeNull()
  183. expect(pre!.textContent).toContain('const listing = await tools.bash')
  184. expect(pre!.querySelectorAll('span[style]').length).toBeGreaterThan(3)
  185. })
  186. it('an isError sub-call renders the error state dot exactly like a failed native row', async () => {
  187. const parent = 'call-64'
  188. const dispatches = new Map([[parent, [
  189. subCall(11, parent, 1, 'mystery', { n: 1 }, 'Error: boom', true),
  190. ]]])
  191. const b = await bench(snapshotWith([codeResult(10, parent)], dispatches))
  192. const view = mountApp(b.slots)
  193. const nested = view.container.querySelector('[data-subcalls] [data-variant][data-state="error"]')
  194. expect(nested).not.toBeNull()
  195. })
  196. it('a sub-row click opens details for the sub-callId', async () => {
  197. const parent = 'call-64'
  198. const dispatches = new Map([[parent, [
  199. subCall(11, parent, 1, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  200. ]]])
  201. const b = await bench(snapshotWith([codeResult(10, parent)], dispatches))
  202. const view = mountApp(b.slots)
  203. view.getByText('List notes').click()
  204. expect(b.layout.openDetails).toHaveBeenCalledTimes(1)
  205. })
  206. it('a RUNNING run_code call nests its so-far dispatches under the spinner row', async () => {
  207. const parent = 'call-live'
  208. const dispatches = new Map([[parent, [
  209. subCall(21, parent, 1, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  210. ]]])
  211. const b = await bench(snapshotWith([], dispatches, [runningCode(parent)]))
  212. const view = mountApp(b.slots)
  213. const running = view.container.querySelector('[data-variant="code"][data-state="running"]')
  214. expect(running).not.toBeNull()
  215. const nest = view.container.querySelector('[data-subcalls]')
  216. expect(nest).not.toBeNull()
  217. expect(nest!.querySelector('[data-sample="bash-global"]')).not.toBeNull()
  218. })
  219. it('a started-but-unsettled sub-call renders the running state exactly like a native in-flight row', async () => {
  220. const parent = 'call-live'
  221. const runningSub: CodeSubCall = {
  222. callId: `${parent}:code:1`, name: 'grep', argsRaw: '{"pattern":"todo"}',
  223. turn: 0, step: 0, time: 21_000, callView: null,
  224. }
  225. const dispatches = new Map([[parent, [runningSub]]])
  226. const b = await bench(snapshotWith([], dispatches, [runningCode(parent)]))
  227. const view = mountApp(b.slots)
  228. // The nested row derives 'running' from the RunningToolCall shape — the
  229. // same StateDot ring a native in-flight row wears.
  230. const nested = view.container.querySelector('[data-subcalls] [data-variant][data-state="running"]')
  231. expect(nested).not.toBeNull()
  232. })
  233. it('an ordinary tool row renders no sub-call nest', async () => {
  234. const parent = 'call-64'
  235. const plain: ToolResultNode = {
  236. kind: 'tool-result', seq: 10, time: 10_000, callId: parent,
  237. call: { name: 'mystery', argsRaw: '{"n":1}' },
  238. callTime: 9_500,
  239. content: [], isError: false, callView: null, resultView: null,
  240. }
  241. const b = await bench(snapshotWith([plain], new Map()))
  242. const view = mountApp(b.slots)
  243. expect(view.container.querySelector('[data-subcalls]')).toBeNull()
  244. })
  245. })