queue-dock.spec.tsx 17 KB

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