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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 } 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-details-render.client.tsx'
  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('uiConversation', {
  94. events,
  95. views,
  96. binding: () => ({ target: () => chat }),
  97. } as never)
  98. await runtime.sessions.add({
  99. id: SID,
  100. summary: { title: 'S', displayTitle: 'S' },
  101. snapshot: { running: snapshot.legacy.runningCalls.length > 0 },
  102. })
  103. const layout = { openDetails: vi.fn(), closeDetails: vi.fn() }
  104. const openPath = vi.fn(async () => {})
  105. ctx.provide('layout', layout as never)
  106. ctx.provide('uiWorkspace', { openPath } as never)
  107. ctx.provide('connection', {
  108. api: { settings: {} },
  109. isLoopback: false,
  110. hostDescription: { getSnapshot: () => undefined, subscribe: () => () => {} },
  111. } as never)
  112. const locale = new LocaleRuntime(ctx)
  113. ctx.provide('locale', locale)
  114. locale.register(CONVERSATION_NS, { zh: conversationZh, en: conversationEn })
  115. runtime.slots.installLocale(locale)
  116. await runtime.root.declare(ROOT_CHILDREN, AppRoot)
  117. await runtime.mount({ inject: [...injectChat], apply: applyChat })
  118. await runtime.mount({ inject: [...injectTool], apply: applyTool })
  119. return { runtime, layout, openPath }
  120. }
  121. function mountApp(runtime: SlotTestRuntime) {
  122. return runtime.renderRoot()
  123. }
  124. describe('run_code sub-calls through the real chat machinery', () => {
  125. it('renders the code-variant parent row with the description summary and nested sub-rows', async () => {
  126. const parent = 'call-64'
  127. const subCalls = [
  128. subCall(11, parent, 1, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  129. subCall(12, parent, 2, 'mystery', { n: 1 }, 'ok'),
  130. ]
  131. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  132. const view = mountApp(b.runtime)
  133. // Parent row: the code variant with the model-authored description.
  134. const codeRoot = view.container.querySelector('[data-variant="code"]')
  135. expect(codeRoot).not.toBeNull()
  136. expect(view.getByText('Code')).toBeTruthy()
  137. expect(view.getByText('List the notes directory')).toBeTruthy()
  138. const nest = view.container.querySelector('[data-subcalls]')
  139. expect(nest).not.toBeNull()
  140. expect(nest!.querySelector('[data-sample="bash"]')).not.toBeNull()
  141. expect(view.getByText('Bash')).toBeTruthy()
  142. expect(view.getByText('List notes')).toBeTruthy()
  143. expect(view.getByText('Tool call')).toBeTruthy()
  144. })
  145. it('renders Cordis sub-calls with lifecycle titles over the generic variants', async () => {
  146. const parent = 'call-cordis'
  147. const subCalls = [
  148. subCall(11, parent, 1, 'cordis_runtime_inspect', { what: 'temporary' }, '## Dynamic Packages'),
  149. subCall(12, parent, 2, 'cordis_run', { id: 'dyn-2' }, 'Dynamic package dyn-2 is running'),
  150. subCall(13, parent, 3, 'cordis_undefine', { id: 'dyn-2' }, 'Dynamic package dyn-2 was discarded.'),
  151. ]
  152. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  153. const view = mountApp(b.runtime)
  154. const nest = view.container.querySelector('[data-subcalls]')!
  155. // Each run-control verb names its act and shows the package id; without the
  156. // owned titles all three would read "Tool call · cordis_run · dyn-2".
  157. expect(nest.querySelector('[data-tool="cordis_runtime_inspect"]')?.textContent).toContain('Inspect')
  158. expect(nest.querySelector('[data-tool="cordis_run"]')?.textContent).toContain('Run Cordis Plugindyn-2')
  159. expect(nest.querySelector('[data-tool="cordis_undefine"]')?.textContent).toContain('Remove Cordis Plugindyn-2')
  160. // None of them is a code row: the program belongs to cordis_define, whose
  161. // own keyed card renders it (the next case covers the code row itself).
  162. expect(nest.querySelector('[data-variant="code"]')).toBeNull()
  163. })
  164. it('expanding the code row reveals the program body verbatim (shiki-tokenized)', async () => {
  165. const parent = 'call-64'
  166. const b = await bench(snapshotWith([codeResult(10, parent)], []))
  167. const view = mountApp(b.runtime)
  168. // The code row is expandable via the whole summary row (body = the program).
  169. const toggle = view.container.querySelector('[data-variant="code"] [data-expandable]')
  170. expect(toggle).not.toBeNull()
  171. fireEvent.click(toggle!)
  172. // Shiki splits the program into token spans inside one <pre class="shiki">:
  173. // assert the whole text and the highlighted tree rather than one node.
  174. const pre = view.container.querySelector('pre.shiki')
  175. expect(pre).not.toBeNull()
  176. expect(pre!.textContent).toContain('const listing = await tools.bash')
  177. expect(pre!.querySelectorAll('span[style]').length).toBeGreaterThan(3)
  178. })
  179. it('an isError sub-call renders the error state dot exactly like a failed native row', async () => {
  180. const parent = 'call-64'
  181. const subCalls = [
  182. subCall(11, parent, 1, 'mystery', { n: 1 }, 'Error: boom', true),
  183. ]
  184. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  185. const view = mountApp(b.runtime)
  186. const nested = view.container.querySelector('[data-subcalls] [data-variant][data-state="error"]')
  187. expect(nested).not.toBeNull()
  188. })
  189. it('a file sub-row click opens the host path; bash sub-rows do not open details', async () => {
  190. const parent = 'call-64'
  191. const subCalls = [
  192. subCall(11, parent, 1, 'read', { path: 'notes/demo.txt' }, 'ok'),
  193. subCall(12, parent, 2, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  194. ]
  195. const b = await bench(snapshotWith([codeResult(10, parent)], subCalls))
  196. const view = mountApp(b.runtime)
  197. view.getByText('notes/demo.txt').click()
  198. expect(b.layout.openDetails).not.toHaveBeenCalled()
  199. await vi.waitFor(() => {
  200. expect(b.openPath).toHaveBeenCalledWith('notes/demo.txt')
  201. })
  202. view.getByText('List notes').click()
  203. expect(b.layout.openDetails).not.toHaveBeenCalled()
  204. })
  205. it('a RUNNING run_code call nests its so-far dispatches under the spinner row', async () => {
  206. const parent = 'call-live'
  207. const subCalls = [
  208. subCall(21, parent, 1, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
  209. ]
  210. const b = await bench(snapshotWith([], subCalls, [runningCode(parent)]))
  211. const view = mountApp(b.runtime)
  212. const running = view.container.querySelector('[data-variant="code"][data-state="running"]')
  213. expect(running).not.toBeNull()
  214. const nest = view.container.querySelector('[data-subcalls]')
  215. expect(nest).not.toBeNull()
  216. expect(nest!.querySelector('[data-sample="bash"]')).not.toBeNull()
  217. })
  218. it('a started-but-unsettled sub-call renders the running state exactly like a native in-flight row', async () => {
  219. const parent = 'call-live'
  220. const runningSub: ToolCallBlock = {
  221. callId: `${parent}:code:1`, name: 'grep', argsRaw: '{"pattern":"todo"}',
  222. parentCallId: parent,
  223. turn: 0, step: 0, time: 21_000, subCalls: [],
  224. }
  225. const b = await bench(snapshotWith([], [runningSub], [runningCode(parent)]))
  226. const view = mountApp(b.runtime)
  227. // The nested row derives 'running' from the RunningToolCall shape — the
  228. // same data-state chrome (row sweep) a native in-flight row wears.
  229. const nested = view.container.querySelector('[data-subcalls] [data-variant][data-state="running"]')
  230. expect(nested).not.toBeNull()
  231. })
  232. it('an ordinary tool row renders no sub-call nest', async () => {
  233. const parent = 'call-64'
  234. const plain: ToolResultNode = {
  235. kind: 'tool-result', seq: 10, time: 10_000, callId: parent,
  236. call: { name: 'mystery', argsRaw: '{"n":1}' },
  237. callTime: 9_500,
  238. content: [], isError: false, subCalls: [],
  239. }
  240. const b = await bench(snapshotWith([plain], []))
  241. const view = mountApp(b.runtime)
  242. expect(view.container.querySelector('[data-subcalls]')).toBeNull()
  243. })
  244. })