skeleton.spec.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. // @vitest-environment jsdom
  2. /**
  3. * Skeleton acceptance over the four-share props form: empty-state transition
  4. * (same InputBar component in hero position, startSession submit, in-component
  5. * cwd derivation), ConversationRoot view switching through the store's view
  6. * field, DetailsPanel selection through the shared store. Components stay
  7. * pure — the framework shares are stubbed (useSession/useSessions), the store
  8. * share is a REAL createChatStore().create() instance (same construction path
  9. * as production), injected callbacks are spies.
  10. */
  11. import { cleanup, fireEvent, render, screen } from '@testing-library/react'
  12. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  13. import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
  14. import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
  15. import type { UseSession } from '@deepseek-ai/dsh-client-web-react'
  16. import type { ConversationSnapshot, PendingInteraction, SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client'
  17. import { PendingWait } from '@deepseek-ai/dsh-client-runtime/client'
  18. import { RpcId } from '@deepseek-ai/dsh-client-connection/client'
  19. import type { SelectionTarget, ViewTab } from '@deepseek-ai/dsh-client-ui-conversation/client'
  20. import type { ConversationRootProps } from '../src/client/skeleton/ConversationRoot.tsx'
  21. // Export discipline: packages/client/AGENTS.md.
  22. import { createChatStore } from '../src/client/stores.ts'
  23. import { ConversationRoot } from '../src/client/skeleton/ConversationRoot.tsx'
  24. import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx'
  25. import { EmptyState } from '../src/client/skeleton/EmptyState.tsx'
  26. const sid = (s: string): SessionId => s as SessionId
  27. afterEach(cleanup)
  28. beforeEach(() => {
  29. // jsdom normally provides localStorage; some host Node builds surface it as undefined.
  30. globalThis.localStorage?.clear()
  31. })
  32. /** Minimal conversation snapshot slice the skeleton reads. */
  33. interface FakeSnapshot {
  34. nodes: readonly {
  35. kind: string
  36. seq?: number
  37. time?: number
  38. callId?: string
  39. call?: { name: string; argsRaw: string } | null
  40. callTime?: number | null
  41. content?: readonly { type: string; text?: string }[]
  42. isError?: boolean
  43. callView?: null
  44. resultView?: null
  45. }[]
  46. runningCalls: readonly {
  47. callId: string
  48. name: string
  49. argsRaw: string
  50. turn?: number
  51. step?: number
  52. time?: number
  53. callView?: null
  54. }[]
  55. running: boolean
  56. removed: boolean
  57. promptError: { op: 'send' | 'stop'; error: { message: string; code: string } } | null
  58. pending: readonly PendingInteraction[]
  59. }
  60. function fakeSession(init: Partial<FakeSnapshot> = {}) {
  61. const store = createSnapshotStore<FakeSnapshot>({
  62. nodes: [], runningCalls: [], running: false, removed: false, promptError: null, pending: [], ...init,
  63. })
  64. return { store, useSession: bindSnapshotSelector(store) as unknown as UseSession<ConversationSnapshot> }
  65. }
  66. /** Sessions-list stub: the standard useSessions hook over a snapshot store. */
  67. function fakeSessions(rows: { id: string; title: string; cwd?: string; parentId?: string }[]) {
  68. const store = createSnapshotStore<SessionListState>({
  69. ids: rows.map(r => sid(r.id)),
  70. byId: Object.fromEntries(rows.map(r => [r.id, {
  71. id: sid(r.id), title: `durable ${r.title}`, displayTitle: r.title, running: false, updatedAt: 1,
  72. ...(r.cwd !== undefined ? { cwd: r.cwd } : {}),
  73. ...(r.parentId !== undefined ? { parentId: sid(r.parentId) } : {}),
  74. }])),
  75. current: undefined,
  76. } as SessionListState)
  77. return { store, useSessions: bindSnapshotSelector(store) }
  78. }
  79. /** SessionProvider seat stub (render-prop pass-through; ConversationRoot never invokes it). */
  80. const SessionProviderStub: ConversationRootProps['SessionProvider'] = ({ children }) => <>{children(sid('s1'))}</>
  81. describe('EmptyState', () => {
  82. const noopCreate = () => Promise.resolve()
  83. it('derives cwd options from the sessions list, submits startSession, failure surfaces locally', async () => {
  84. const { useSessions } = fakeSessions([
  85. { id: 'a', title: 'a', cwd: '/w/app' },
  86. { id: 'b', title: 'b', cwd: '/w/lib' },
  87. { id: 'c', title: 'c', cwd: '/w/app' }, // duplicate cwd dedupes
  88. ])
  89. let reject!: (e: Error) => void
  90. const startSession = vi.fn(() => new Promise<void>((_res, rej) => { reject = rej }))
  91. render(
  92. <EmptyState
  93. useSessions={useSessions}
  94. startSession={startSession}
  95. createWorkspaceSession={noopCreate}
  96. />,
  97. )
  98. const trigger = screen.getByRole('button', { name: '项目目录' })
  99. fireEvent.click(trigger)
  100. const menu = screen.getByRole('menu')
  101. expect([...menu.querySelectorAll('[role="menuitem"]')].map(el => el.textContent))
  102. .toEqual(['app', 'lib', 'New Workspace'])
  103. fireEvent.click(screen.getByRole('menuitem', { name: 'app' }))
  104. const box = screen.getByPlaceholderText('Message to run task, plan and build, enter for / commands')
  105. fireEvent.change(box, { target: { value: '造一个轮子' } })
  106. fireEvent.keyDown(box, { key: 'Enter' })
  107. expect(startSession).toHaveBeenCalledWith({ text: '造一个轮子', mode: 'queue', cwd: '/w/app' })
  108. reject(new Error('后端拒收'))
  109. expect(await screen.findByText(/后端拒收/)).toBeTruthy()
  110. // Draft survives the failure for retry.
  111. expect((box as HTMLTextAreaElement).value).toBe('造一个轮子')
  112. })
  113. it('Use a existing folder opens the path modal and Open Folder sets the chip', () => {
  114. const { useSessions } = fakeSessions([])
  115. render(
  116. <EmptyState
  117. useSessions={useSessions}
  118. startSession={() => Promise.resolve()}
  119. createWorkspaceSession={noopCreate}
  120. />,
  121. )
  122. fireEvent.click(screen.getByRole('button', { name: '项目目录' }))
  123. const newWs = screen.getByRole('menuitem', { name: 'New Workspace' })
  124. fireEvent.mouseEnter(newWs.parentElement as HTMLElement)
  125. fireEvent.click(screen.getByRole('menuitem', { name: 'Use a existing folder' }))
  126. expect(screen.getByRole('dialog', { name: 'Enter an existing folder path' })).toBeTruthy()
  127. const path = screen.getByLabelText('Folder path') as HTMLInputElement
  128. fireEvent.change(path, { target: { value: '/tmp/fresh' } })
  129. fireEvent.click(screen.getByRole('button', { name: 'Open Folder' }))
  130. expect(screen.queryByRole('dialog')).toBeNull()
  131. expect(screen.getByRole('button', { name: '项目目录' }).textContent).toContain('fresh')
  132. })
  133. it('Create new opens the modal and createWorkspaceSession succeeds', async () => {
  134. const { useSessions } = fakeSessions([])
  135. const createWorkspaceSession = vi.fn(() => Promise.resolve())
  136. render(
  137. <EmptyState
  138. useSessions={useSessions}
  139. startSession={() => Promise.resolve()}
  140. createWorkspaceSession={createWorkspaceSession}
  141. />,
  142. )
  143. fireEvent.click(screen.getByRole('button', { name: '项目目录' }))
  144. fireEvent.mouseEnter(screen.getByRole('menuitem', { name: 'New Workspace' }).parentElement as HTMLElement)
  145. fireEvent.click(screen.getByRole('menuitem', { name: 'Create new' }))
  146. expect(screen.getByRole('dialog', { name: 'Create new workspace' })).toBeTruthy()
  147. const name = screen.getByLabelText('Workspace name') as HTMLInputElement
  148. expect(name.value).toBe('New WorkSpace')
  149. fireEvent.change(name, { target: { value: 'My Proj' } })
  150. fireEvent.keyDown(name, { key: 'Enter' })
  151. await vi.waitFor(() => expect(createWorkspaceSession).toHaveBeenCalledWith('My Proj'))
  152. })
  153. it('Create modal Cancel dismisses without calling createWorkspaceSession', () => {
  154. const { useSessions } = fakeSessions([])
  155. const createWorkspaceSession = vi.fn(() => Promise.resolve())
  156. render(
  157. <EmptyState
  158. useSessions={useSessions}
  159. startSession={() => Promise.resolve()}
  160. createWorkspaceSession={createWorkspaceSession}
  161. />,
  162. )
  163. fireEvent.click(screen.getByRole('button', { name: '项目目录' }))
  164. fireEvent.mouseEnter(screen.getByRole('menuitem', { name: 'New Workspace' }).parentElement as HTMLElement)
  165. fireEvent.click(screen.getByRole('menuitem', { name: 'Create new' }))
  166. fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
  167. expect(screen.queryByRole('dialog')).toBeNull()
  168. expect(createWorkspaceSession).not.toHaveBeenCalled()
  169. })
  170. })
  171. describe('ConversationRoot', () => {
  172. function bench(
  173. tabs: ViewTab[], activeView?: string, init: Partial<FakeSnapshot> = {},
  174. renderSlotChain?: ConversationRootProps['renderSlotChain'],
  175. ) {
  176. const { useSession } = fakeSession({ nodes: [{ kind: 'user' }, { kind: 'user' }], ...init })
  177. const { useSessions } = fakeSessions([
  178. { id: 'root', title: 'proj' },
  179. { id: 's1', title: 'child', parentId: 'root' },
  180. ])
  181. const chat = createChatStore().create()
  182. if (activeView !== undefined) chat.actions.setView(activeView)
  183. const send = vi.fn()
  184. const stop = vi.fn()
  185. const open = vi.fn()
  186. // The renderSlot share as the outlet would bake it: renders a marker for
  187. // the ring key carrying the active-id filter (a Mock cannot satisfy the
  188. // generic method type directly — cast once at the prop seam).
  189. const renderSlot = vi.fn((key: string, _owner: object, opts?: { only?: string }) => (
  190. <div data-testid={`view-${opts?.only ?? '(all)'}`} data-slot={key} />
  191. ))
  192. const ui = render(
  193. <ConversationRoot
  194. sessionId={sid('s1')}
  195. useSession={useSession}
  196. useSessions={useSessions}
  197. useStore={bindSnapshotSelector(chat)}
  198. actions={chat.actions}
  199. renderSlot={renderSlot as unknown as ConversationRootProps['renderSlot']}
  200. renderSlotChain={renderSlotChain ?? ((_key, _owner, opts) => opts?.fallback ?? null)}
  201. SessionProvider={SessionProviderStub}
  202. views={{
  203. list: () => tabs,
  204. subscribe: () => () => {},
  205. version: () => 1,
  206. }}
  207. send={send}
  208. stop={stop}
  209. open={open}
  210. />)
  211. return { ui, chat, send, stop, open, renderSlot }
  212. }
  213. const tab = (id: string, label: string): ViewTab => ({ id, label })
  214. it('renders breadcrumb chain (useSessions-derived), meta turns, and the default chat view', () => {
  215. const { open } = bench([tab('chat', 'Chat'), tab('trajectory', 'Trajectory')])
  216. expect(screen.getByText('proj')).toBeTruthy()
  217. expect(screen.getByText('child')).toBeTruthy()
  218. expect(screen.getByText(/2 turns/)).toBeTruthy()
  219. expect(screen.getByTestId('view-chat')).toBeTruthy()
  220. // Ancestor crumb navigates; current crumb is disabled.
  221. fireEvent.click(screen.getByRole('button', { name: 'proj' }))
  222. expect(open).toHaveBeenCalledWith('root')
  223. expect((screen.getByRole('button', { name: 'child' }) as HTMLButtonElement).disabled).toBe(true)
  224. })
  225. it('switches views through the store view field and falls back on unknown ids', () => {
  226. const { chat } = bench([tab('chat', 'Chat'), tab('trajectory', 'Trajectory')])
  227. fireEvent.click(screen.getByRole('tab', { name: 'Trajectory' }))
  228. expect(chat.store.getSnapshot().view).toBe('trajectory')
  229. expect(screen.getByTestId('view-trajectory')).toBeTruthy()
  230. cleanup()
  231. // A stale persisted id (its view plugin unloaded) falls to the first view.
  232. bench([tab('chat', 'Chat'), tab('trajectory', 'Trajectory')], 'ghost-view')
  233. expect(screen.getByTestId('view-chat')).toBeTruthy()
  234. })
  235. it('renders the active view through the declared ring slot with the only filter', () => {
  236. const { renderSlot } = bench([tab('chat', 'Chat')])
  237. // No owner share: views take everything from the standard kit (contract).
  238. expect(renderSlot).toHaveBeenCalledWith('conversation.view', {}, { only: 'chat' })
  239. expect(screen.getByTestId('view-chat').getAttribute('data-slot')).toBe('conversation.view')
  240. })
  241. it('hides the tab strip with a single view; composer writes the store draft and sends it', () => {
  242. const { chat, send } = bench([tab('chat', 'Chat')])
  243. expect(screen.queryByRole('tablist')).toBeNull()
  244. const box = screen.getByPlaceholderText(/输入消息/)
  245. fireEvent.change(box, { target: { value: 'hi' } })
  246. // Typing goes through actions.setDraft into the shared store.
  247. expect(chat.store.getSnapshot().draft).toBe('hi')
  248. fireEvent.keyDown(box, { key: 'Enter' })
  249. expect(send).toHaveBeenCalledWith('hi', 'queue')
  250. })
  251. it('dispatches the pending list to the composer chain; all-decline falls back to InputBar', () => {
  252. const wait = new PendingWait('question', RpcId('rq'), sid('s1'),
  253. { questions: [{ id: 'mode', question: 'Choose?', options: [{ label: 'Fast' }] }] } as PendingWait<'question'>['payload'], vi.fn())
  254. // A matching entry takes the composer over.
  255. const renderSlotChain = vi.fn(() => <div>question takeover</div>) as unknown as ConversationRootProps['renderSlotChain']
  256. bench([tab('chat', 'Chat')], undefined, { pending: [wait] }, renderSlotChain)
  257. expect(screen.getByText('question takeover')).toBeTruthy()
  258. expect(screen.queryByPlaceholderText(/输入消息/)).toBeNull()
  259. // The owner dispatches the raw pending list (chain currency); routing
  260. // lives in entry selectors, not here.
  261. expect(renderSlotChain).toHaveBeenCalledWith(
  262. 'conversation.composer',
  263. expect.objectContaining({
  264. interactions: expect.arrayContaining([expect.objectContaining({ key: 'q:rq' })]),
  265. }),
  266. expect.objectContaining({ fallback: expect.anything() }),
  267. )
  268. cleanup()
  269. // Zero registered entries (default all-decline stub): the fallback IS the
  270. // default InputBar — behavior equals the pre-chain composer.
  271. bench([tab('chat', 'Chat')], undefined, { pending: [wait] })
  272. expect(screen.getByPlaceholderText(/输入消息/)).toBeTruthy()
  273. })
  274. })
  275. describe('DetailsPanel', () => {
  276. function benchDetails(snapshot: Partial<FakeSnapshot>, selection: SelectionTarget | null) {
  277. const { useSession } = fakeSession(snapshot)
  278. const { useSessions } = fakeSessions([])
  279. const chat = createChatStore().create()
  280. if (selection !== null) chat.actions.select(selection)
  281. const closeDetails = vi.fn()
  282. render(
  283. <DetailsPanel
  284. sessionId={sid('s1')}
  285. useSession={useSession}
  286. useSessions={useSessions}
  287. useStore={bindSnapshotSelector(chat)}
  288. actions={chat.actions}
  289. closeDetails={closeDetails}
  290. />)
  291. return { closeDetails, chat }
  292. }
  293. it('renders the selected call args and result off the shared store; close fires the injected callback', () => {
  294. const { closeDetails } = benchDetails({
  295. nodes: [{
  296. kind: 'tool-result', seq: 1, time: 1_000, callId: 'c1',
  297. call: { name: 'bash', argsRaw: '{"cmd":"ls"}' },
  298. callTime: 500,
  299. content: [{ type: 'text', text: 'file-a\nfile-b' }],
  300. isError: false, callView: null, resultView: null,
  301. }],
  302. }, { turnSeq: 1, callId: 'c1' })
  303. expect(screen.getByText('bash')).toBeTruthy()
  304. expect(screen.getByText(/"cmd": "ls"/)).toBeTruthy()
  305. expect(screen.getByText(/file-a/)).toBeTruthy()
  306. fireEvent.click(screen.getByRole('button', { name: '关闭详情' }))
  307. expect(closeDetails).toHaveBeenCalledTimes(1)
  308. })
  309. it('shows the empty hint without a selection and the running state for open calls', () => {
  310. benchDetails({ runningCalls: [{ callId: 'c9', name: 'bash', argsRaw: '{}', turn: 1, step: 1, time: 1_000, callView: null }] }, null)
  311. expect(screen.getByText(/点击消息流中的工具行/)).toBeTruthy()
  312. cleanup()
  313. benchDetails({ runningCalls: [{ callId: 'c9', name: 'bash', argsRaw: '{}', turn: 1, step: 1, time: 1_000, callView: null }] }, { turnSeq: 1, callId: 'c9' })
  314. expect(screen.getByText('运行中…')).toBeTruthy()
  315. })
  316. it('reports an out-of-window call distinctly', () => {
  317. benchDetails({}, { turnSeq: 1, callId: 'ghost' })
  318. expect(screen.getByText(/不在当前窗口内/)).toBeTruthy()
  319. })
  320. })