input-matrix.client.spec.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. // @vitest-environment jsdom
  2. /**
  3. * Impact-matrix projection tests (row by row): what each
  4. * phase projects onto the InputBar — enter routing, visuals (token color /
  5. * hint / pending), edit freedom, and the published currency's claim seat.
  6. * React over jsdom per the client testing discipline; the machine is real.
  7. */
  8. import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots'
  9. import { afterEach, describe, expect, it, vi } from 'vitest'
  10. import { act, cleanup, fireEvent, render } from '@testing-library/react'
  11. import type { Context } from '@deepseek-ai/cordis'
  12. import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client'
  13. import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
  14. import {
  15. bindSnapshotSelector, conversationSnapshot, sessionSnapshot,
  16. } from '@deepseek-ai/dsh-client-test-runtime'
  17. import type { SessionPendingInteractionSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'
  18. import type { SessionId } from '@deepseek-ai/dsh-session/types'
  19. import type { SubmitAttachment, SubmitOutcome } from '../src/client/contract/input.ts'
  20. import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
  21. import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
  22. import type { DraftAttachmentId } from '../src/client/contract/input.ts'
  23. import { SessionInputShell } from '../src/client/input/facade.ts'
  24. import { InputBar } from '../src/client/skeleton/InputBar.tsx'
  25. import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx'
  26. import { zh } from '../src/client/locales.ts'
  27. // Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps.
  28. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined })) as GlobalStandardProps['useResource']
  29. // jsdom implements no Range geometry (Lexical's scroll-into-view measures the
  30. // caret with one once the surface is genuinely contenteditable).
  31. Range.prototype.getBoundingClientRect = () => ({
  32. top: 0, bottom: 0, left: 0, right: 0, width: 0, height: 0, x: 0, y: 0, toJSON: () => ({}),
  33. })
  34. afterEach(cleanup)
  35. const SCTX = {} as Context
  36. const SID = 's1' as SessionId
  37. /** Standard-props InputBar mount over a real shell (the composer-bar entry shape). */
  38. function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled?: boolean }) {
  39. const session = createSnapshotStore<SessionSnapshot>({
  40. ...sessionSnapshot(SID),
  41. running: over?.running ?? false,
  42. removed: over?.disabled ?? false,
  43. })
  44. const props: InputBarProps = {
  45. usePanelInfo: selector => selector({ activePanelId: null }),
  46. sessionId: SID,
  47. SessionProvider: ({ children }) => children,
  48. useSession: bindSnapshotSelector(session),
  49. useSessions: bindSnapshotSelector(createSnapshotStore({
  50. ids: [], byId: {}, current: undefined, phase: 'ready',
  51. subagentsByParent: {}, jobsBySession: {}, currentAddress: undefined,
  52. })),
  53. useSessionPendingInteraction: bindSnapshotSelector(
  54. createSnapshotStore<SessionPendingInteractionSnapshot>(new Map()),
  55. ),
  56. useResource,
  57. useWorkspaces: bindSnapshotSelector(createSnapshotStore({
  58. items: [], archivedSessionIds: [], state: 'idle', phase: 'ready', error: null,
  59. baselinesReady: true, recentWorkspaceId: undefined,
  60. })),
  61. useProjection: (() => undefined),
  62. useConversation: bindSnapshotSelector(createSnapshotStore(conversationSnapshot())),
  63. useInput: bindSnapshotSelector(shell.state),
  64. inputActions: shell.actions,
  65. keyboard: shell,
  66. addFiles: () => null,
  67. useFileUploads: bindSnapshotSelector(createSnapshotStore({})),
  68. retryFileUpload: undefined,
  69. removeAttachment: () => {},
  70. // Every id resolves so the bar's registry prune never drops a test image.
  71. resolveDraftAttachments: ids => ids.map(id => ({
  72. kind: 'image' as const, id,
  73. file: new File([Uint8Array.of(1)], `${id}.png`, { type: 'image/png' }),
  74. previewUrl: `blob:${id}`,
  75. })),
  76. toggleCommandMenu: vi.fn(),
  77. useBusyEnter: bindSnapshotSelector(createSnapshotStore<'queue' | 'steer'>('queue')),
  78. useNotices: bindSnapshotSelector(shell.notices),
  79. useLexicon: bindSnapshotSelector(shell.lexicon),
  80. useMenuLauncher: bindSnapshotSelector(createSnapshotStore<string | null>(null)),
  81. renderSlot: (() => null) as InputBarProps['renderSlot'],
  82. stop: vi.fn(),
  83. command: () => Promise.resolve(true),
  84. t: makeTranslate(zh, commonZh),
  85. variant: 'composer',
  86. }
  87. return render(<InputBar {...props} />)
  88. }
  89. function bench(over?: {
  90. running?: boolean
  91. disabled?: boolean
  92. submit?: (args: string) => Promise<SubmitOutcome>
  93. serialize?: (ids: readonly DraftAttachmentId[]) => Promise<readonly SubmitAttachment[]>
  94. }) {
  95. const sink = vi.fn(() => Promise.resolve<SubmitOutcome>({ kind: 'success' }))
  96. const serialize = vi.fn(over?.serialize ?? (() => Promise.resolve<readonly SubmitAttachment[]>([])))
  97. const release = vi.fn()
  98. const shell = new SessionInputShell({ actx: SCTX, defaultSink: sink, commandAttachments: { serialize, release, unsupportedNotice: (token: string) => `${token.trim()} attachments-unsupported` } })
  99. const wiring = shell
  100. const view = mountBar(shell, over)
  101. const textarea = view.container.querySelector<HTMLDivElement>('[data-composer-input]')!
  102. const claim = (token = '/goal ', hint = '目标', attachments?: true) => {
  103. act(() => {
  104. shell.setDraft(token)
  105. shell.beginCommand(
  106. {
  107. name: token.slice(1).trim(), token, hint,
  108. ...(attachments === true ? { attachments: true } : {}),
  109. submit: over?.submit ?? (() => Promise.resolve({ kind: 'success' as const, source: 'command', name: 'goal' })),
  110. },
  111. { start: 0, end: token.length, draftRev: shell.snapshot.draftRev },
  112. )
  113. })
  114. }
  115. return { view, textarea, shell, wiring, sink, claim, serialize, release }
  116. }
  117. describe('matrix row: plain', () => {
  118. it('enter falls to the default sink; no claim on the currency; edits free', async () => {
  119. const { textarea, shell, sink } = bench()
  120. act(() => { shell.setDraft('普通消息') })
  121. expect(shell.snapshot.claim).toBeUndefined()
  122. fireEvent.keyDown(textarea, { key: 'Enter' })
  123. expect(sink).toHaveBeenCalledWith('普通消息', [], 'queue', expect.any(AbortSignal))
  124. // The detached default send never freezes the composer.
  125. expect(shell.snapshot.phase).toBe('plain')
  126. expect(shell.snapshot.draft).toBe('')
  127. expect(shell.snapshot.claim).toBeUndefined()
  128. })
  129. })
  130. describe('matrix row: claimed', () => {
  131. it('publishes the claim currency, colors the token, hints while args are blank, and edits stay free', () => {
  132. const { view, textarea, shell, claim } = bench()
  133. claim()
  134. act(() => { shell.editor.update(() => {}, { discrete: true }) }) // flush the queued decoration refresh
  135. expect(shell.snapshot.claim).toEqual({ name: 'goal', token: '/goal ', hint: '目标' })
  136. expect(view.container.querySelector('[data-lexical-text][style*="warn-label"]')?.textContent).toBe('/goal ')
  137. // The zh dictionary owns a hint.goal entry, which overrides the raw claim hint (production behavior).
  138. expect(textarea.style.getPropertyValue('--dsh-composer-hint')).toBe(JSON.stringify('输入目标,智能体将持续执行'))
  139. expect(textarea.getAttribute('contenteditable')).toBe('true')
  140. // Free editing beyond the token: hint drops, claim holds.
  141. act(() => { shell.setDraft('/goal 发布版本') })
  142. expect(shell.snapshot.phase).toBe('claimed')
  143. expect(textarea.style.getPropertyValue('--dsh-composer-hint')).toBe('')
  144. })
  145. it('enter routes to claim.submit (command lane, never the queue sink)', async () => {
  146. const submit = vi.fn(() => Promise.resolve({ kind: 'success' as const, text: '完成', source: 'command', name: 'goal' }))
  147. const { view, textarea, shell, sink, claim } = bench({ submit })
  148. claim()
  149. act(() => { shell.setDraft('/goal 发布') })
  150. fireEvent.keyDown(textarea, { key: 'Enter' })
  151. expect(sink).not.toHaveBeenCalled()
  152. await vi.waitFor(() => { expect(submit).toHaveBeenCalledWith('发布', SCTX, []) })
  153. // Commit: draft cleared, notice surfaced, back to plain.
  154. await vi.waitFor(() => { expect(shell.snapshot.draft).toBe('') })
  155. expect(view.getByText('完成')).toBeTruthy()
  156. })
  157. it('backspacing the token auto-releases to plain and the visuals vanish (scenario H)', () => {
  158. const { view, shell, claim } = bench()
  159. claim()
  160. act(() => { shell.setDraft('/goa 发布') }) // token broken
  161. expect(shell.snapshot.phase).toBe('plain')
  162. expect(shell.snapshot.claim).toBeUndefined()
  163. act(() => { shell.editor.update(() => {}, { discrete: true }) }) // flush the queued decoration refresh
  164. expect(view.container.querySelector('[data-lexical-text][style*="warn-label"]')).toBeNull()
  165. })
  166. })
  167. describe('matrix row: claimed with attachments', () => {
  168. const img = 'img-1' as DraftAttachmentId
  169. it('a claim without attachment acceptance blocks enter: one notice and the full draft retained', async () => {
  170. const submit = vi.fn(() => Promise.resolve({ kind: 'success' as const }))
  171. const { view, textarea, shell, sink, claim } = bench({ submit })
  172. claim()
  173. act(() => { shell.addAttachments([img]) })
  174. fireEvent.keyDown(textarea, { key: 'Enter' })
  175. await Promise.resolve()
  176. expect(shell.snapshot.phase).toBe('claimed')
  177. expect(submit).not.toHaveBeenCalled()
  178. expect(sink).not.toHaveBeenCalled()
  179. expect(view.getByText('/goal attachments-unsupported')).toBeTruthy()
  180. expect(shell.snapshot.attachmentIds).toEqual([img])
  181. expect(shell.snapshot.draft).toBe('/goal ')
  182. })
  183. it('an accepting claim serializes and forwards a mixed batch; success consumes and clears', async () => {
  184. const submit = vi.fn(() => Promise.resolve({ kind: 'success' as const }))
  185. const png: SubmitAttachment = { type: 'image', mediaType: 'image/png', data: 'AA==' }
  186. const file: SubmitAttachment = { type: 'file', receiptId: 'receipt-x' }
  187. const { textarea, shell, claim, serialize, release } = bench({ submit, serialize: () => Promise.resolve([png, file]) })
  188. claim('/goal ', '目标', true)
  189. // The claim currency carries the acceptance flag the pre-gate reads.
  190. expect(shell.snapshot.claim).toEqual({ name: 'goal', token: '/goal ', hint: '目标', attachments: true })
  191. act(() => { shell.addAttachments([img]) })
  192. fireEvent.keyDown(textarea, { key: 'Enter' })
  193. await vi.waitFor(() => { expect(submit).toHaveBeenCalledWith('', SCTX, [png, file]) })
  194. expect(serialize).toHaveBeenCalledWith([img])
  195. await vi.waitFor(() => { expect(shell.snapshot.draft).toBe('') })
  196. expect(release).toHaveBeenCalledWith([img])
  197. expect(shell.snapshot.attachmentIds).toEqual([])
  198. expect(shell.snapshot.phase).toBe('plain')
  199. })
  200. it('a handler error keeps a serialized file unreleased beside the notice and draft', async () => {
  201. const submit = vi.fn(() => Promise.resolve({ kind: 'error' as const, text: '处理失败' }))
  202. const file: SubmitAttachment = { type: 'file', receiptId: 'receipt-x' }
  203. const { view, textarea, shell, claim, release } = bench({ submit, serialize: () => Promise.resolve([file]) })
  204. claim('/goal ', '目标', true)
  205. act(() => { shell.addAttachments([img]) })
  206. fireEvent.keyDown(textarea, { key: 'Enter' })
  207. await vi.waitFor(() => { expect(view.getByText('处理失败')).toBeTruthy() })
  208. expect(shell.snapshot.phase).toBe('claimed')
  209. expect(shell.snapshot.attachmentIds).toEqual([img])
  210. expect(release).not.toHaveBeenCalled()
  211. expect(shell.snapshot.draft).toBe('/goal ')
  212. })
  213. it('a serialize rejection blocks the transaction: notice, no submit call, images kept', async () => {
  214. const submit = vi.fn(() => Promise.resolve({ kind: 'success' as const }))
  215. const { view, textarea, shell, claim, release } = bench({ submit, serialize: () => Promise.reject(new Error('附件已失效')) })
  216. claim('/goal ', '目标', true)
  217. act(() => { shell.addAttachments([img]) })
  218. fireEvent.keyDown(textarea, { key: 'Enter' })
  219. await vi.waitFor(() => { expect(view.getByText('附件已失效')).toBeTruthy() })
  220. expect(submit).not.toHaveBeenCalled()
  221. expect(shell.snapshot.attachmentIds).toEqual([img])
  222. expect(release).not.toHaveBeenCalled()
  223. expect(shell.snapshot.phase).toBe('claimed')
  224. })
  225. it('a disposed shell never lets a pending serialization reach claim.submit', async () => {
  226. const submit = vi.fn(() => Promise.resolve({ kind: 'success' as const }))
  227. let resolveSerialize!: (images: readonly SubmitAttachment[]) => void
  228. const { shell, textarea, claim } = bench({
  229. submit,
  230. serialize: () => new Promise((resolve) => { resolveSerialize = resolve }),
  231. })
  232. claim('/goal ', '目标', true)
  233. act(() => { shell.addAttachments([img]) })
  234. fireEvent.keyDown(textarea, { key: 'Enter' })
  235. await vi.waitFor(() => { expect(resolveSerialize).toBeDefined() })
  236. shell.dispose()
  237. resolveSerialize([{ type: 'image', mediaType: 'image/png', data: 'AA==' }])
  238. await Promise.resolve()
  239. await Promise.resolve()
  240. expect(submit).not.toHaveBeenCalled()
  241. })
  242. it('image removal is refused while a command submit is in flight', async () => {
  243. const submit = vi.fn(() => new Promise<SubmitOutcome>(() => {})) // never settles
  244. const { shell, textarea, claim } = bench({ submit, serialize: () => Promise.resolve([]) })
  245. claim('/goal ', '目标', true)
  246. act(() => { shell.addAttachments([img]) })
  247. fireEvent.keyDown(textarea, { key: 'Enter' })
  248. expect(shell.snapshot.phase).toBe('submitting')
  249. let removed = true
  250. act(() => { removed = shell.removeAttachment(img) })
  251. expect(removed).toBe(false)
  252. expect(shell.snapshot.attachmentIds).toEqual([img])
  253. })
  254. })
  255. describe('matrix row: submitting', () => {
  256. it('locks enter, renders pending + read-only, keeps the claim snapshot on the currency', async () => {
  257. const submit = vi.fn(() => new Promise<SubmitOutcome>(() => {})) // never settles
  258. const { textarea, shell, sink, claim } = bench({ submit })
  259. claim()
  260. fireEvent.keyDown(textarea, { key: 'Enter' })
  261. expect(shell.snapshot.phase).toBe('submitting')
  262. expect(shell.snapshot.claim).toBeDefined()
  263. expect(textarea.getAttribute('contenteditable')).toBe('false')
  264. // Enter is dead inside the lock (submit dispatch is microtask-deferred).
  265. await vi.waitFor(() => { expect(submit).toHaveBeenCalledTimes(1) })
  266. fireEvent.keyDown(textarea, { key: 'Enter' })
  267. await Promise.resolve()
  268. expect(submit).toHaveBeenCalledTimes(1)
  269. expect(sink).not.toHaveBeenCalled()
  270. })
  271. it('rollback with unchanged draft returns to claimed with the notice; drifted draft only notices', async () => {
  272. let rejectSubmit!: (e: Error) => void
  273. const submit = vi.fn(() => new Promise<SubmitOutcome>((_res, rej) => { rejectSubmit = rej }))
  274. const first = bench({ submit })
  275. first.claim()
  276. fireEvent.keyDown(first.textarea, { key: 'Enter' })
  277. await vi.waitFor(() => { expect(submit).toHaveBeenCalled() })
  278. act(() => { rejectSubmit(new Error('执行失败')) })
  279. await vi.waitFor(() => { expect(first.shell.snapshot.phase).toBe('claimed') })
  280. expect(first.shell.snapshot.draft).toBe('/goal ')
  281. expect(first.view.getByText('执行失败')).toBeTruthy()
  282. cleanup()
  283. // Drift: typing during flight wins; no restore, plain, notice only.
  284. const submit2 = vi.fn(() => new Promise<SubmitOutcome>((_res, rej) => { rejectSubmit = rej }))
  285. const second = bench({ submit: submit2 })
  286. second.claim()
  287. fireEvent.keyDown(second.textarea, { key: 'Enter' })
  288. await vi.waitFor(() => { expect(submit2).toHaveBeenCalled() })
  289. act(() => { second.shell.setDraft('用户飞行中打的新稿') })
  290. act(() => { rejectSubmit(new Error('晚到失败')) })
  291. await vi.waitFor(() => { expect(second.shell.snapshot.phase).toBe('plain') })
  292. expect(second.shell.snapshot.draft).toBe('用户飞行中打的新稿')
  293. expect(second.view.getByText('晚到失败')).toBeTruthy()
  294. })
  295. })
  296. describe('matrix row: locked (session disabled)', () => {
  297. it('disables the textarea and chrome; the machine currency is untouched', () => {
  298. const { view, textarea, shell } = bench({ disabled: true })
  299. expect(textarea.getAttribute('aria-disabled')).toBe('true')
  300. expect((view.getByLabelText('添加文件或调用指令') as HTMLButtonElement).disabled).toBe(true)
  301. expect(shell.snapshot.phase).toBe('plain')
  302. })
  303. it('running does NOT lock: typing and enter-queue stay live', () => {
  304. const { textarea, shell, sink } = bench({ running: true })
  305. expect(textarea.getAttribute('aria-disabled')).not.toBe('true')
  306. act(() => { shell.setDraft('排队') })
  307. fireEvent.keyDown(textarea, { key: 'Enter' })
  308. expect(sink).toHaveBeenCalledWith('排队', [], 'queue', expect.any(AbortSignal))
  309. })
  310. })
  311. describe('matrix row: takeover (orthogonal axis)', () => {
  312. it('the machine state survives outside the render tree (claim lives on the shell, not the DOM)', () => {
  313. const { view, shell, claim } = bench()
  314. claim()
  315. // Takeover hides the composer (overlay chain keeps it mounted-but-hidden);
  316. // even a full unmount keeps the claim: state lives on the resident shell.
  317. view.unmount()
  318. expect(shell.snapshot.phase).toBe('claimed')
  319. expect(shell.snapshot.claim?.token).toBe('/goal ')
  320. expect(shell.snapshot.draft).toBe('/goal ')
  321. })
  322. })