input-matrix.spec.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // @vitest-environment jsdom
  2. /**
  3. * Impact-matrix projection tests (design §5.2 影响矩阵, 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 { afterEach, describe, expect, it, vi } from 'vitest'
  9. import { act, cleanup, fireEvent, render } from '@testing-library/react'
  10. import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
  11. import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
  12. import type { ClientContext, ConversationSnapshot, SessionId } from '@deepseek-ai/dsh-client-runtime/client'
  13. import type { SubmitOutcome } from '@deepseek-ai/dsh-client-ui-slash/client'
  14. import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
  15. import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
  16. import { SessionInputShell } from '../src/client/input/facade.ts'
  17. import { InputBar } from '../src/client/skeleton/InputBar.tsx'
  18. import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx'
  19. import { zh } from '../src/client/locales.ts'
  20. afterEach(cleanup)
  21. const SCTX = {} as ClientContext
  22. const SID = 's1' as SessionId
  23. /** Standard-props InputBar mount over a real shell (the composer-bar entry shape). */
  24. function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled?: boolean }) {
  25. const session = createSnapshotStore<ConversationSnapshot>({
  26. sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], codeDispatches: new Map(),
  27. pending: [], queue: [], running: over?.running ?? false, composerPhase: 'active',
  28. removed: over?.disabled ?? false, openState: 'open', openError: null, hasMore: false,
  29. loadingOlder: false, promptError: null, blank: false, lastAgentError: null,
  30. })
  31. const props: InputBarProps = {
  32. sessionId: SID,
  33. SessionProvider: ({ children }) => children(SID),
  34. useSession: bindSnapshotSelector(session),
  35. useSessions: bindSnapshotSelector(createSnapshotStore({
  36. ids: [], byId: {}, current: undefined, phase: 'ready',
  37. })),
  38. useWorkspaces: bindSnapshotSelector(createSnapshotStore({
  39. items: [], archivedSessionIds: [], state: 'idle', phase: 'ready', error: null,
  40. baselinesReady: true, recentWorkspaceId: undefined,
  41. })),
  42. useProjection: (() => undefined),
  43. useInput: bindSnapshotSelector(shell.state),
  44. inputActions: shell.actions,
  45. keyboard: shell,
  46. toggleCommandMenu: vi.fn(),
  47. useNotices: bindSnapshotSelector(shell.notices),
  48. useLexicon: bindSnapshotSelector(shell.lexicon),
  49. useMenuLauncher: bindSnapshotSelector(createSnapshotStore<string | null>(null)),
  50. renderSlot: (() => null) as InputBarProps['renderSlot'],
  51. stop: vi.fn(),
  52. command: () => Promise.resolve(true),
  53. // Mirrors the real lookup chain (conversation namespace, then common).
  54. t: makeTranslate(zh, commonZh),
  55. variant: 'composer',
  56. }
  57. return render(<InputBar {...props} />)
  58. }
  59. function bench(over?: { running?: boolean; disabled?: boolean; submit?: (args: string) => Promise<SubmitOutcome> }) {
  60. const sink = vi.fn()
  61. const shell = new SessionInputShell({ actx: SCTX, defaultSink: sink })
  62. const wiring = shell
  63. const view = mountBar(shell, over)
  64. const textarea = view.container.querySelector('textarea')!
  65. const claim = (token = '/goal ', hint = '目标') => {
  66. act(() => {
  67. shell.setDraft(token)
  68. shell.beginCommand(
  69. {
  70. token, hint,
  71. submit: over?.submit ?? (() => Promise.resolve({ kind: 'success' as const, source: 'command', name: 'goal' })),
  72. },
  73. { start: 0, end: token.length, draftRev: shell.snapshot.draftRev },
  74. )
  75. })
  76. }
  77. return { view, textarea, shell, wiring, sink, claim }
  78. }
  79. describe('matrix row: plain', () => {
  80. it('enter falls to the default sink; no claim on the currency; edits free', () => {
  81. const { textarea, shell, sink } = bench()
  82. fireEvent.change(textarea, { target: { value: '普通消息' } })
  83. expect(shell.snapshot.claim).toBeUndefined()
  84. fireEvent.keyDown(textarea, { key: 'Enter' })
  85. expect(sink).toHaveBeenCalledWith('普通消息', 'queue')
  86. expect(shell.snapshot.phase).toBe('plain')
  87. })
  88. })
  89. describe('matrix row: claimed', () => {
  90. it('publishes the claim currency, colors the token, hints while args are blank, and edits stay free', () => {
  91. const { view, textarea, shell, claim } = bench()
  92. claim()
  93. expect(shell.snapshot.claim).toEqual({ token: '/goal ', hint: '目标' })
  94. expect(view.container.querySelector('[data-decoration="token"]')?.textContent).toBe('/goal ')
  95. // The zh dictionary owns a hint.goal entry, which overrides the raw claim hint (production behavior).
  96. expect(view.container.querySelector('[data-decoration="hint"]')?.textContent).toBe('输入目标,智能体将持续执行')
  97. expect((textarea).readOnly).toBe(false)
  98. // Free editing beyond the token: hint drops, claim holds.
  99. fireEvent.change(textarea, { target: { value: '/goal 发布版本' } })
  100. expect(shell.snapshot.phase).toBe('claimed')
  101. expect(view.container.querySelector('[data-decoration="hint"]')).toBeNull()
  102. })
  103. it('enter routes to claim.submit (command lane, never the queue sink)', async () => {
  104. const submit = vi.fn(() => Promise.resolve({ kind: 'success' as const, text: '完成', source: 'command', name: 'goal' }))
  105. const { view, textarea, sink, claim } = bench({ submit })
  106. claim()
  107. fireEvent.change(textarea, { target: { value: '/goal 发布' } })
  108. fireEvent.keyDown(textarea, { key: 'Enter' })
  109. expect(sink).not.toHaveBeenCalled()
  110. await vi.waitFor(() => { expect(submit).toHaveBeenCalledWith('发布', SCTX) })
  111. // Commit: draft cleared, notice surfaced, back to plain.
  112. await vi.waitFor(() => { expect((textarea).value).toBe('') })
  113. expect(view.getByText('完成')).toBeTruthy()
  114. })
  115. it('backspacing the token auto-releases to plain and the visuals vanish (scenario H)', () => {
  116. const { view, textarea, shell, claim } = bench()
  117. claim()
  118. fireEvent.change(textarea, { target: { value: '/goa 发布' } }) // token broken
  119. expect(shell.snapshot.phase).toBe('plain')
  120. expect(shell.snapshot.claim).toBeUndefined()
  121. expect(view.container.querySelector('[data-decoration="token"]')).toBeNull()
  122. })
  123. })
  124. describe('matrix row: submitting', () => {
  125. it('locks enter, renders pending + read-only, keeps the claim snapshot on the currency', async () => {
  126. const submit = vi.fn(() => new Promise<SubmitOutcome>(() => {})) // never settles
  127. const { textarea, shell, sink, claim } = bench({ submit })
  128. claim()
  129. fireEvent.keyDown(textarea, { key: 'Enter' })
  130. expect(shell.snapshot.phase).toBe('submitting')
  131. expect(shell.snapshot.claim).toBeDefined()
  132. expect((textarea).readOnly).toBe(true)
  133. // Enter is dead inside the lock (submit dispatch is microtask-deferred).
  134. await vi.waitFor(() => { expect(submit).toHaveBeenCalledTimes(1) })
  135. fireEvent.keyDown(textarea, { key: 'Enter' })
  136. await Promise.resolve()
  137. expect(submit).toHaveBeenCalledTimes(1)
  138. expect(sink).not.toHaveBeenCalled()
  139. })
  140. it('rollback with unchanged draft returns to claimed with the notice; drifted draft only notices', async () => {
  141. let rejectSubmit!: (e: Error) => void
  142. const submit = vi.fn(() => new Promise<SubmitOutcome>((_res, rej) => { rejectSubmit = rej }))
  143. const first = bench({ submit })
  144. first.claim()
  145. fireEvent.keyDown(first.textarea, { key: 'Enter' })
  146. await vi.waitFor(() => { expect(submit).toHaveBeenCalled() })
  147. act(() => { rejectSubmit(new Error('执行失败')) })
  148. await vi.waitFor(() => { expect(first.shell.snapshot.phase).toBe('claimed') })
  149. expect((first.textarea).value).toBe('/goal ')
  150. expect(first.view.getByText('执行失败')).toBeTruthy()
  151. cleanup()
  152. // Drift: typing during flight wins; no restore, plain, notice only.
  153. const submit2 = vi.fn(() => new Promise<SubmitOutcome>((_res, rej) => { rejectSubmit = rej }))
  154. const second = bench({ submit: submit2 })
  155. second.claim()
  156. fireEvent.keyDown(second.textarea, { key: 'Enter' })
  157. await vi.waitFor(() => { expect(submit2).toHaveBeenCalled() })
  158. act(() => { second.shell.setDraft('用户飞行中打的新稿') })
  159. act(() => { rejectSubmit(new Error('晚到失败')) })
  160. await vi.waitFor(() => { expect(second.shell.snapshot.phase).toBe('plain') })
  161. expect((second.textarea).value).toBe('用户飞行中打的新稿')
  162. expect(second.view.getByText('晚到失败')).toBeTruthy()
  163. })
  164. })
  165. describe('matrix row: locked (session disabled)', () => {
  166. it('disables the textarea and chrome; the machine currency is untouched', () => {
  167. const { view, textarea, shell } = bench({ disabled: true })
  168. expect((textarea).disabled).toBe(true)
  169. expect((view.getByLabelText('命令') as HTMLButtonElement).disabled).toBe(true)
  170. expect(shell.snapshot.phase).toBe('plain')
  171. })
  172. it('running does NOT lock (queue cut 1): typing and enter-queue stay live', () => {
  173. const { textarea, sink } = bench({ running: true })
  174. expect((textarea).disabled).toBe(false)
  175. fireEvent.change(textarea, { target: { value: '排队' } })
  176. fireEvent.keyDown(textarea, { key: 'Enter' })
  177. expect(sink).toHaveBeenCalledWith('排队', 'queue')
  178. })
  179. })
  180. describe('matrix row: takeover (orthogonal axis)', () => {
  181. it('the machine state survives outside the render tree (claim lives on the shell, not the DOM)', () => {
  182. const { view, shell, claim } = bench()
  183. claim()
  184. // Takeover hides the composer (overlay chain keeps it mounted-but-hidden);
  185. // even a full unmount keeps the claim: state lives on the resident shell.
  186. view.unmount()
  187. expect(shell.snapshot.phase).toBe('claimed')
  188. expect(shell.snapshot.claim?.token).toBe('/goal ')
  189. expect(shell.snapshot.draft).toBe('/goal ')
  190. })
  191. })