queue-dock.spec.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. // @vitest-environment jsdom
  2. /**
  3. * QueueDock rendering and operations: authoritative rows, inline editing,
  4. * collapse state, removal, strict steering, failure notices, and live retirement.
  5. */
  6. import { afterEach, describe, expect, it, vi } from 'vitest'
  7. import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'
  8. import { useSyncExternalStore } from 'react'
  9. import type {
  10. ConversationSnapshot, QueuedMessage, SessionId, SessionListState,
  11. } from '@deepseek-ai/dsh-client-runtime/client'
  12. import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
  13. import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
  14. import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
  15. import type { QueueItemId } from '../src/client/contract/queue.ts'
  16. import type { InputState } from '../src/client/input/contract.ts'
  17. import { zh } from '../src/client/locales.ts'
  18. import { QueueDock, queueDockEntry, type QueueDockInjected, type QueueDockProps } from '../src/client/queue/QueueDock.tsx'
  19. afterEach(cleanup)
  20. const SID = 's1' as SessionId
  21. const iid = (id: string): QueueItemId => id as QueueItemId
  22. function row(id: string, text: string | null, preview = text ?? '[image]'): QueuedMessage {
  23. return {
  24. id: iid(id), messageId: `message-${id}` as never, placement: 'queued',
  25. content: text === null ? [{ type: 'image', data: 'x' } as never] : [{ type: 'text', text }],
  26. preview, text,
  27. }
  28. }
  29. function snapshotWith(queue: QueuedMessage[]): ConversationSnapshot {
  30. return {
  31. sessionId: SID, nodes: [], turnTimings: new Map(), turnEnds: new Map(), partial: null, runningCalls: [], codeDispatches: new Map(),
  32. pending: [], queue, running: true, composerPhase: 'active', removed: false, openState: 'open', openError: null,
  33. hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent: null, lastAgentError: null,
  34. }
  35. }
  36. /** Minimal live source backing the useSession stub. */
  37. function liveSession(initial: ConversationSnapshot) {
  38. let snapshot = initial
  39. const listeners = new Set<() => void>()
  40. const useSession: SnapshotSelectorHook<ConversationSnapshot> = selector =>
  41. useSyncExternalStore(
  42. (listener) => {
  43. listeners.add(listener)
  44. return () => listeners.delete(listener)
  45. },
  46. () => selector(snapshot),
  47. )
  48. return {
  49. useSession,
  50. push(next: ConversationSnapshot): void {
  51. snapshot = next
  52. for (const listener of [...listeners]) listener()
  53. },
  54. }
  55. }
  56. const INPUT_STATE: InputState = { draft: '', draftRev: 0, phase: 'plain', occurrences: [], queue: [] }
  57. // Standard locale seat stub mirroring the real ns → common → key chain.
  58. const t: QueueDockProps['t'] = makeTranslate(zh, commonZh)
  59. function kitFor(snapshot: ConversationSnapshot, injected: Partial<QueueDockInjected> = {}) {
  60. return {
  61. sessionId: SID,
  62. t,
  63. useSessions: (() => { throw new Error('unused') }) as unknown as SnapshotSelectorHook<SessionListState>,
  64. useWorkspaces: (() => { throw new Error('unused') }) as never,
  65. useProjection: (() => undefined) as never,
  66. useInput: (() => { throw new Error('unused') }) as never,
  67. inputActions: { setDraft: () => {}, submit: () => {} } as never,
  68. session: snapshot,
  69. input: INPUT_STATE,
  70. updateQueue: vi.fn(() => Promise.resolve()),
  71. notify: vi.fn(),
  72. ...injected,
  73. }
  74. }
  75. describe('QueueDock', () => {
  76. it('renders null while the queue is empty', () => {
  77. const snap = snapshotWith([])
  78. const source = liveSession(snap)
  79. const { container } = render(<QueueDock {...kitFor(snap)} useSession={source.useSession} />)
  80. expect(container.innerHTML).toBe('')
  81. })
  82. it('leaves pending steering to the conversation flow', () => {
  83. const steering = { ...row('s-1', 'interrupt'), placement: 'steering' as const }
  84. const snap = snapshotWith([steering])
  85. const source = liveSession(snap)
  86. const { container } = render(<QueueDock {...kitFor(snap)} useSession={source.useSession} />)
  87. expect(container.innerHTML).toBe('')
  88. })
  89. it('renders one row directly and defaults multiple rows to a collapsible count header', () => {
  90. const single = snapshotWith([row('i-1', 'one')])
  91. const source = liveSession(single)
  92. const view = render(<QueueDock {...kitFor(single)} useSession={source.useSession} />)
  93. expect(view.queryByRole('button', { name: '1 条排队消息' })).toBeNull()
  94. expect(view.getByText('one')).toBeTruthy()
  95. act(() => { source.push(snapshotWith([row('i-1', 'one'), row('i-2', 'two')])) })
  96. const header = view.getByRole('button', { name: '2 条排队消息' })
  97. expect(header.getAttribute('aria-expanded')).toBe('false')
  98. expect(document.getElementById(header.getAttribute('aria-controls')!)).toBeTruthy()
  99. expect(view.queryByText('one')).toBeNull()
  100. expect(view.queryByText('two')).toBeNull()
  101. fireEvent.click(header)
  102. expect(header.getAttribute('aria-expanded')).toBe('true')
  103. expect(view.getByText('one')).toBeTruthy()
  104. expect(view.getByText('two')).toBeTruthy()
  105. fireEvent.click(header)
  106. expect(header.getAttribute('aria-expanded')).toBe('false')
  107. expect(view.queryByText('one')).toBeNull()
  108. })
  109. it('keeps an active single-row editor visible when another item arrives', () => {
  110. const single = snapshotWith([row('i-edit', 'before')])
  111. const source = liveSession(single)
  112. const view = render(<QueueDock {...kitFor(single)} useSession={source.useSession} />)
  113. fireEvent.click(view.getByLabelText('编辑排队消息'))
  114. fireEvent.change(view.getByLabelText('编辑排队消息'), { target: { value: 'draft' } })
  115. act(() => {
  116. source.push(snapshotWith([row('i-edit', 'before'), row('i-2', 'second')]))
  117. })
  118. const header = view.getByRole('button', { name: '2 条排队消息' })
  119. expect(header).toHaveProperty('disabled', true)
  120. expect(header.getAttribute('aria-expanded')).toBe('true')
  121. expect(view.getByRole('textbox', { name: '编辑排队消息' })).toHaveProperty('value', 'draft')
  122. expect(view.getByText('second')).toBeTruthy()
  123. fireEvent.click(view.getByLabelText('取消编辑'))
  124. expect(header).toHaveProperty('disabled', false)
  125. expect(header.getAttribute('aria-expanded')).toBe('false')
  126. expect(view.queryByText('second')).toBeNull()
  127. })
  128. it('keeps an in-flight row action visible when another item arrives', async () => {
  129. const single = snapshotWith([row('i-remove', 'remove me')])
  130. const source = liveSession(single)
  131. let finishUpdate: (() => void) | undefined
  132. const updateQueue = vi.fn(() => new Promise<void>((resolve) => { finishUpdate = resolve }))
  133. const view = render(
  134. <QueueDock {...kitFor(single, { updateQueue })} useSession={source.useSession} />,
  135. )
  136. fireEvent.click(view.getByLabelText('删除排队消息'))
  137. act(() => {
  138. source.push(snapshotWith([row('i-remove', 'remove me'), row('i-2', 'second')]))
  139. })
  140. const header = view.getByRole('button', { name: '2 条排队消息' })
  141. expect(header).toHaveProperty('disabled', true)
  142. expect(header.getAttribute('aria-expanded')).toBe('true')
  143. expect(view.getByText('remove me')).toBeTruthy()
  144. expect(view.getByText('second')).toBeTruthy()
  145. act(() => { finishUpdate?.() })
  146. await waitFor(() => {
  147. expect(header).toHaveProperty('disabled', false)
  148. expect(header.getAttribute('aria-expanded')).toBe('false')
  149. })
  150. })
  151. it('defaults a new multi-row queue to collapsed after the prior queue empties', () => {
  152. const first = snapshotWith([row('i-1', 'one'), row('i-2', 'two')])
  153. const source = liveSession(first)
  154. const view = render(<QueueDock {...kitFor(first)} useSession={source.useSession} />)
  155. fireEvent.click(view.getByRole('button', { name: '2 条排队消息' }))
  156. expect(view.getByText('one')).toBeTruthy()
  157. act(() => { source.push(snapshotWith([])) })
  158. expect(view.container.innerHTML).toBe('')
  159. act(() => {
  160. source.push(snapshotWith([row('i-3', 'three'), row('i-4', 'four')]))
  161. })
  162. const header = view.getByRole('button', { name: '2 条排队消息' })
  163. expect(header.getAttribute('aria-expanded')).toBe('false')
  164. expect(view.queryByText('three')).toBeNull()
  165. })
  166. it('renders active actions and disables editing for mixed-content rows', () => {
  167. const snap = snapshotWith([
  168. row('i-1', '第一条排队消息'),
  169. row('i-2', null, 'image [image]'),
  170. ])
  171. const source = liveSession(snap)
  172. const { container, getByRole } = render(<QueueDock {...kitFor(snap)} useSession={source.useSession} />)
  173. fireEvent.click(getByRole('button', { name: '2 条排队消息' }))
  174. expect([...container.querySelectorAll('li')].map(item => item.textContent))
  175. .toEqual(['第一条排队消息', 'image [image]'])
  176. expect(container.querySelectorAll('button')).toHaveLength(7)
  177. expect(container.querySelectorAll('[aria-label="编辑排队消息"]')).toHaveLength(2)
  178. expect(container.querySelectorAll('[aria-label="删除排队消息"]')).toHaveLength(2)
  179. expect(container.querySelectorAll('[aria-label="插话发送"]')).toHaveLength(2)
  180. expect((container.querySelectorAll('[aria-label="编辑排队消息"]')[0] as HTMLButtonElement).disabled).toBe(false)
  181. expect((container.querySelectorAll('[aria-label="编辑排队消息"]')[1] as HTMLButtonElement).disabled).toBe(true)
  182. expect(container.querySelectorAll('[aria-label="编辑排队消息"]')[1]?.getAttribute('title'))
  183. .toBe('包含非文本内容,暂不支持编辑')
  184. })
  185. it('edits text inline with save and cancel controls, then saves with the same item identity', async () => {
  186. const snap = snapshotWith([row('i-edit', 'before')])
  187. const source = liveSession(snap)
  188. const updateQueue = vi.fn(() => Promise.resolve())
  189. const { getByLabelText, queryByLabelText } = render(
  190. <QueueDock {...kitFor(snap, { updateQueue })} useSession={source.useSession} />,
  191. )
  192. fireEvent.click(getByLabelText('编辑排队消息'))
  193. const editor = getByLabelText('编辑排队消息') as HTMLInputElement
  194. expect(getByLabelText('保存排队消息')).toBeTruthy()
  195. expect(getByLabelText('取消编辑')).toBeTruthy()
  196. expect(queryByLabelText('删除排队消息')).toBeNull()
  197. fireEvent.change(editor, { target: { value: 'after' } })
  198. fireEvent.keyDown(editor, { key: 'Enter' })
  199. await waitFor(() => {
  200. expect(updateQueue).toHaveBeenCalledWith(iid('i-edit'), {
  201. kind: 'edit',
  202. content: [{ type: 'text', text: 'after' }],
  203. })
  204. })
  205. })
  206. it('cancels an edit by button or Escape without mutating the queue', () => {
  207. const snap = snapshotWith([row('i-edit', 'before')])
  208. const source = liveSession(snap)
  209. const updateQueue = vi.fn(() => Promise.resolve())
  210. const { getByLabelText, getByText } = render(
  211. <QueueDock {...kitFor(snap, { updateQueue })} useSession={source.useSession} />,
  212. )
  213. fireEvent.click(getByLabelText('编辑排队消息'))
  214. fireEvent.change(getByLabelText('编辑排队消息'), { target: { value: 'abandoned' } })
  215. fireEvent.click(getByLabelText('取消编辑'))
  216. expect(getByText('before')).toBeTruthy()
  217. fireEvent.click(getByLabelText('编辑排队消息'))
  218. fireEvent.keyDown(getByLabelText('编辑排队消息'), { key: 'Escape' })
  219. expect(getByText('before')).toBeTruthy()
  220. expect(updateQueue).not.toHaveBeenCalled()
  221. })
  222. it('keeps editing during IME composition and disables a blank save', () => {
  223. const snap = snapshotWith([row('i-edit', 'before')])
  224. const source = liveSession(snap)
  225. const updateQueue = vi.fn(() => Promise.resolve())
  226. const { getByLabelText } = render(
  227. <QueueDock {...kitFor(snap, { updateQueue })} useSession={source.useSession} />,
  228. )
  229. fireEvent.click(getByLabelText('编辑排队消息'))
  230. const editor = getByLabelText('编辑排队消息')
  231. fireEvent.change(editor, { target: { value: ' ' } })
  232. expect(getByLabelText('保存排队消息')).toHaveProperty('disabled', true)
  233. fireEvent.change(editor, { target: { value: '输入中' } })
  234. fireEvent.keyDown(editor, { key: 'Enter', isComposing: true })
  235. expect(updateQueue).not.toHaveBeenCalled()
  236. expect(getByLabelText('编辑排队消息')).toBeTruthy()
  237. })
  238. it('removes the addressed row', async () => {
  239. const snap = snapshotWith([row('i-1', 'one'), row('i-2', 'two')])
  240. const source = liveSession(snap)
  241. const updateQueue = vi.fn(() => Promise.resolve())
  242. const { getAllByLabelText, getByRole } = render(
  243. <QueueDock {...kitFor(snap, { updateQueue })} useSession={source.useSession} />,
  244. )
  245. fireEvent.click(getByRole('button', { name: '2 条排队消息' }))
  246. fireEvent.click(getAllByLabelText('删除排队消息')[0]!)
  247. await waitFor(() => {
  248. expect(updateQueue).toHaveBeenCalledWith(iid('i-1'), { kind: 'remove' })
  249. })
  250. })
  251. it('strictly steers complete row content only while the agent is running', async () => {
  252. const running = snapshotWith([row('i-steer', null, 'image [image]')])
  253. const source = liveSession(running)
  254. const updateQueue = vi.fn(() => Promise.resolve())
  255. const rendered = render(
  256. <QueueDock {...kitFor(running, { updateQueue })} useSession={source.useSession} />,
  257. )
  258. const button = rendered.getByLabelText('插话发送')
  259. expect(button).toHaveProperty('disabled', false)
  260. fireEvent.click(button)
  261. await waitFor(() => {
  262. expect(updateQueue).toHaveBeenCalledWith(iid('i-steer'), { kind: 'steer' })
  263. })
  264. act(() => { source.push({ ...running, running: false }) })
  265. expect(rendered.getByLabelText('插话发送')).toHaveProperty('disabled', true)
  266. expect(rendered.getByLabelText('插话发送').getAttribute('title')).toBe('仅运行中可插话发送')
  267. })
  268. it('renders a session-backed subagent Queue without unsupported actions', () => {
  269. const snap = {
  270. ...snapshotWith([row('i-subagent', 'pending child follow-up')]),
  271. subagent: {
  272. address: {
  273. parentSessionId: 'parent' as SessionId,
  274. childSessionId: SID,
  275. mode: 'continuable' as const,
  276. },
  277. parentAvailable: true,
  278. },
  279. }
  280. const source = liveSession(snap)
  281. const view = render(
  282. <QueueDock {...kitFor(snap)} useSession={source.useSession} />,
  283. )
  284. expect(view.getByText('pending child follow-up')).toBeTruthy()
  285. expect(view.queryByLabelText('编辑排队消息')).toBeNull()
  286. expect(view.queryByLabelText('删除排队消息')).toBeNull()
  287. expect(view.queryByLabelText('插话发送')).toBeNull()
  288. })
  289. it('keeps the row and reports a genuine steer failure', async () => {
  290. const snap = snapshotWith([row('i-steer-race', 'pending steer')])
  291. const source = liveSession(snap)
  292. const notify = vi.fn()
  293. const updateQueue = vi.fn(() => Promise.reject(new Error('transport failed')))
  294. const { getByLabelText, getByText } = render(
  295. <QueueDock {...kitFor(snap, { updateQueue, notify })} useSession={source.useSession} />,
  296. )
  297. fireEvent.click(getByLabelText('插话发送'))
  298. await waitFor(() => {
  299. expect(notify).toHaveBeenCalledWith(
  300. 'error',
  301. '插话发送失败,请重试。',
  302. )
  303. })
  304. expect(getByText('pending steer')).toBeTruthy()
  305. })
  306. it('keeps the row and surfaces a notice when an operation loses the claim race', async () => {
  307. const snap = snapshotWith([row('i-race', 'pending')])
  308. const source = liveSession(snap)
  309. const notify = vi.fn()
  310. const updateQueue = vi.fn(() => Promise.reject(new Error('not found')))
  311. const { getByLabelText, getByText } = render(
  312. <QueueDock {...kitFor(snap, { updateQueue, notify })} useSession={source.useSession} />,
  313. )
  314. fireEvent.click(getByLabelText('删除排队消息'))
  315. await waitFor(() => {
  316. expect(notify).toHaveBeenCalledWith('error', '删除失败:这条消息可能已经开始发送。')
  317. })
  318. expect(getByText('pending')).toBeTruthy()
  319. })
  320. it('follows authoritative retirement back to null', () => {
  321. const snap = snapshotWith([row('i-1', '在场')])
  322. const source = liveSession(snap)
  323. const { container } = render(<QueueDock {...kitFor(snap)} useSession={source.useSession} />)
  324. expect(container.textContent).toContain('在场')
  325. act(() => { source.push(snapshotWith([])) })
  326. expect(container.innerHTML).toBe('')
  327. })
  328. it('registers as the terminal composer-context entry', () => {
  329. expect(queueDockEntry.name).toBe('conversation-queue-dock')
  330. expect(queueDockEntry.inject).toEqual(['slots', 'conversation', 'sessions'])
  331. const register = vi.fn()
  332. queueDockEntry.apply({ slots: { register } } as never)
  333. expect(register).toHaveBeenCalledWith(
  334. expect.objectContaining({ name: 'conversation.input.dock', id: 'queue', order: 20 }),
  335. QueueDock,
  336. )
  337. })
  338. })