submit-machine.client.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /**
  2. * SubmitMachine behavior: enter routing, adjudication outcomes, the claimed
  3. * lifecycle and its integrity watch, settlement (commit-draft and claim
  4. * re-entry decisions), anti-backwash, and per-session isolation. Text-edit
  5. * semantics live in the editor (lexical-editor-core spec) — the machine only
  6. * observes drafts through event payloads.
  7. */
  8. import { describe, expect, it } from 'vitest'
  9. import type { CommandClaim } from '../src/client/contract/input.ts'
  10. import type { InputEffect, SubmitAttempt } from '../src/client/contract/input.ts'
  11. import { SubmitMachine } from '../src/client/input/machine.ts'
  12. import { scanTextRefs } from '../src/client/input/decorations.ts'
  13. function claimOf(name: string, hint?: string): CommandClaim {
  14. return {
  15. token: `/${name} `,
  16. ...(hint !== undefined ? { hint } : {}),
  17. submit: async () => ({ kind: 'success' }),
  18. }
  19. }
  20. function effectAt<T extends InputEffect['type']>(
  21. effects: readonly InputEffect[], index: number, type: T,
  22. ): Extract<InputEffect, { type: T }> {
  23. const e = effects[index]
  24. expect(e?.type).toBe(type)
  25. return e as Extract<InputEffect, { type: T }>
  26. }
  27. /** Drive plain → adjudicating and hand back the minted attempt. */
  28. function enterAdjudicating(m: SubmitMachine, draft: string, mode: 'queue' | 'steer' = 'queue'): SubmitAttempt {
  29. const fx = m.dispatch({ type: 'enter', mode, draft })
  30. return effectAt(fx, 0, 'adjudicate').attempt
  31. }
  32. /** Drive plain → claimed → submitting and hand back attempt + claim. */
  33. function enterSubmitting(m: SubmitMachine, name: string, args: string): { attempt: SubmitAttempt; claim: CommandClaim } {
  34. const claim = claimOf(name)
  35. m.dispatch({ type: 'claim', claim })
  36. const fx = m.dispatch({ type: 'enter', mode: 'queue', draft: claim.token + args })
  37. return { attempt: effectAt(fx, 0, 'begin-submit').attempt, claim }
  38. }
  39. function staleAttempt(): SubmitAttempt {
  40. return { seq: 9999, signal: new AbortController().signal, draftSnapshot: '', mode: 'queue' }
  41. }
  42. describe('submit-machine: plain × enter', () => {
  43. it('empty and whitespace-only drafts produce nothing', () => {
  44. const m = new SubmitMachine()
  45. expect(m.dispatch({ type: 'enter', mode: 'queue', draft: '' })).toEqual([])
  46. expect(m.dispatch({ type: 'enter', mode: 'queue', draft: ' \n ' })).toEqual([])
  47. expect(m.state.phase).toBe('plain')
  48. })
  49. it('non-command text falls to the default sink with the draft and mode', () => {
  50. const m = new SubmitMachine()
  51. const fx = m.dispatch({ type: 'enter', mode: 'queue', draft: 'hello' })
  52. const sink = effectAt(fx, 0, 'default-sink')
  53. expect(sink.draft).toBe('hello')
  54. expect(sink.mode).toBe('queue')
  55. expect(sink.attempt.draftSnapshot).toBe('hello')
  56. expect(effectAt(fx, 1, 'commit-draft').retainSuffixOf).toBe('hello')
  57. expect(m.state.phase).toBe('plain')
  58. })
  59. it('retains an explicit steer mode on the default sink effect', () => {
  60. const m = new SubmitMachine()
  61. const fx = m.dispatch({ type: 'enter', mode: 'steer', draft: 'go' })
  62. expect(effectAt(fx, 0, 'default-sink').mode).toBe('steer')
  63. })
  64. it('leading "/" enters adjudicating with a minted attempt carrying the draft snapshot', () => {
  65. const m = new SubmitMachine()
  66. const fx = m.dispatch({ type: 'enter', mode: 'queue', draft: '/goal write tests' })
  67. const adjudicate = effectAt(fx, 0, 'adjudicate')
  68. expect(adjudicate.draft).toBe('/goal write tests')
  69. expect(adjudicate.attempt.draftSnapshot).toBe('/goal write tests')
  70. expect(adjudicate.attempt.signal.aborted).toBe(false)
  71. expect(m.state.phase).toBe('adjudicating')
  72. })
  73. it('leading is judged after trim including newlines', () => {
  74. const m = new SubmitMachine()
  75. const fx = m.dispatch({ type: 'enter', mode: 'queue', draft: ' \n /goal x' })
  76. expect(effectAt(fx, 0, 'adjudicate').draft).toBe(' \n /goal x')
  77. })
  78. it('a non-whitespace prefix before "/" is not leading — default sink', () => {
  79. const m = new SubmitMachine()
  80. const fx = m.dispatch({ type: 'enter', mode: 'queue', draft: 'see /goal' })
  81. expect(effectAt(fx, 0, 'default-sink').draft).toBe('see /goal')
  82. })
  83. })
  84. describe('submit-machine: adjudication outcomes', () => {
  85. it('{claim} moves to submitting; args split on the first whitespace, newlines kept', () => {
  86. const m = new SubmitMachine()
  87. const attempt = enterAdjudicating(m, '/goal write x\nand y')
  88. const fx = m.dispatch({ type: 'adjudicated', attempt, outcome: { claim: claimOf('goal') } })
  89. const begin = effectAt(fx, 0, 'begin-submit')
  90. expect(begin.args).toBe('write x\nand y')
  91. expect(m.state.phase).toBe('submitting')
  92. expect(m.state.claim?.token).toBe('/goal ')
  93. })
  94. it('bare "/goal" claim yields empty args; leading whitespace snapshot yields trimmed args', () => {
  95. const m = new SubmitMachine()
  96. const attempt = enterAdjudicating(m, '/goal')
  97. const fx = m.dispatch({ type: 'adjudicated', attempt, outcome: { claim: claimOf('goal') } })
  98. expect(effectAt(fx, 0, 'begin-submit').args).toBe('')
  99. const m2 = new SubmitMachine()
  100. const attempt2 = enterAdjudicating(m2, ' /goal args')
  101. const fx2 = m2.dispatch({ type: 'adjudicated', attempt: attempt2, outcome: { claim: claimOf('goal') } })
  102. expect(effectAt(fx2, 0, 'begin-submit').args).toBe('args')
  103. })
  104. it('undefined outcome falls back to the default sink with the snapshot', () => {
  105. const m = new SubmitMachine()
  106. const attempt = enterAdjudicating(m, '/unknown thing', 'steer')
  107. const fx = m.dispatch({ type: 'adjudicated', attempt, outcome: undefined })
  108. const sink = effectAt(fx, 0, 'default-sink')
  109. expect(sink.draft).toBe('/unknown thing')
  110. expect(sink.mode).toBe('steer')
  111. expect(effectAt(fx, 1, 'commit-draft').retainSuffixOf).toBe('/unknown thing')
  112. expect(m.state.phase).toBe('plain')
  113. })
  114. it("'handled' lands plain with zero effects (popup shell path)", () => {
  115. const m = new SubmitMachine()
  116. const attempt = enterAdjudicating(m, '/model')
  117. expect(m.dispatch({ type: 'adjudicated', attempt, outcome: 'handled' })).toEqual([])
  118. expect(m.state.phase).toBe('plain')
  119. })
  120. it('adjudication failure notices and keeps plain — no silent downgrade', () => {
  121. const m = new SubmitMachine()
  122. const attempt = enterAdjudicating(m, '/goal x')
  123. const fx = m.dispatch({ type: 'adjudication-failed', attempt, message: 'warmup failed' })
  124. expect(effectAt(fx, 0, 'notice')).toMatchObject({ level: 'error', text: 'warmup failed' })
  125. expect(m.state.phase).toBe('plain')
  126. })
  127. it('enter is a no-op while adjudicating (pending lock)', () => {
  128. const m = new SubmitMachine()
  129. enterAdjudicating(m, '/goal x')
  130. expect(m.dispatch({ type: 'enter', mode: 'queue', draft: '/goal x' })).toEqual([])
  131. expect(m.state.phase).toBe('adjudicating')
  132. })
  133. it('a stale attempt on adjudicated/adjudication-failed is dropped: same state, zero effects', () => {
  134. const m = new SubmitMachine()
  135. enterAdjudicating(m, '/goal x')
  136. expect(m.dispatch({ type: 'adjudicated', attempt: staleAttempt(), outcome: undefined })).toEqual([])
  137. expect(m.dispatch({ type: 'adjudication-failed', attempt: staleAttempt(), message: 'x' })).toEqual([])
  138. expect(m.state.phase).toBe('adjudicating')
  139. })
  140. it('an adjudicated result arriving after release is dropped (anti-backwash)', () => {
  141. const m = new SubmitMachine()
  142. const attempt = enterAdjudicating(m, '/goal x')
  143. m.dispatch({ type: 'release' })
  144. expect(attempt.signal.aborted).toBe(true)
  145. expect(m.dispatch({ type: 'adjudicated', attempt, outcome: { claim: claimOf('goal') } })).toEqual([])
  146. expect(m.state.phase).toBe('plain')
  147. })
  148. })
  149. describe('submit-machine: claimed lifecycle', () => {
  150. it('the claim event enters claimed and snapshots hint and images bits', () => {
  151. const m = new SubmitMachine()
  152. m.dispatch({ type: 'claim', claim: { ...claimOf('goal', 'set a goal'), attachments: true } })
  153. expect(m.state.phase).toBe('claimed')
  154. expect(m.state.claim).toMatchObject({ token: '/goal ', hint: 'set a goal', attachments: true })
  155. })
  156. it('claimed overwrites in place — no stack', () => {
  157. const m = new SubmitMachine()
  158. m.dispatch({ type: 'claim', claim: claimOf('goal') })
  159. m.dispatch({ type: 'claim', claim: claimOf('plan') })
  160. expect(m.state.claim?.token).toBe('/plan ')
  161. expect(m.state.phase).toBe('claimed')
  162. })
  163. it('submitting rejects the claim event (lock)', () => {
  164. const m = new SubmitMachine()
  165. enterSubmitting(m, 'goal', 'x')
  166. m.dispatch({ type: 'claim', claim: claimOf('plan') })
  167. expect(m.state.claim?.token).toBe('/goal ')
  168. expect(m.state.phase).toBe('submitting')
  169. })
  170. it('breaking startsWith(token) auto-releases back to plain', () => {
  171. const m = new SubmitMachine()
  172. m.dispatch({ type: 'claim', claim: claimOf('goal') })
  173. m.dispatch({ type: 'draft-changed', draft: '/goal args fine' })
  174. expect(m.state.phase).toBe('claimed')
  175. m.dispatch({ type: 'draft-changed', draft: '/goa' })
  176. expect(m.state.phase).toBe('plain')
  177. expect(m.state.claim).toBeUndefined()
  178. })
  179. it('explicit release returns to plain when nothing is in flight', () => {
  180. const m = new SubmitMachine()
  181. m.dispatch({ type: 'claim', claim: claimOf('goal') })
  182. m.dispatch({ type: 'release' })
  183. expect(m.state.phase).toBe('plain')
  184. expect(m.state.claim).toBeUndefined()
  185. })
  186. it('enter begins the submit transaction: args = draft minus token, multi-line legal', () => {
  187. const m = new SubmitMachine()
  188. m.dispatch({ type: 'claim', claim: claimOf('goal') })
  189. const fx = m.dispatch({ type: 'enter', mode: 'queue', draft: '/goal line one\nline two' })
  190. expect(effectAt(fx, 0, 'begin-submit').args).toBe('line one\nline two')
  191. })
  192. })
  193. describe('submit-machine: submitting transaction', () => {
  194. it('enter and claim are locked while submitting; draft-changed is recorded without leaving submitting', () => {
  195. const m = new SubmitMachine()
  196. enterSubmitting(m, 'goal', 'x')
  197. expect(m.dispatch({ type: 'enter', mode: 'queue', draft: '/goal x' })).toEqual([])
  198. m.dispatch({ type: 'draft-changed', draft: 'typed during flight' })
  199. expect(m.state.phase).toBe('submitting')
  200. })
  201. it('commit emits commit-draft with the snapshot, releases the claim, and relays the outcome text', () => {
  202. const m = new SubmitMachine()
  203. const { attempt } = enterSubmitting(m, 'goal', 'x')
  204. const fx = m.dispatch({
  205. type: 'submit-settled', attempt, ok: true, draft: '/goal x',
  206. outcome: { kind: 'success', text: 'goal saved' },
  207. })
  208. expect(effectAt(fx, 0, 'commit-draft').retainSuffixOf).toBe('/goal x')
  209. expect(effectAt(fx, 1, 'notice')).toMatchObject({ level: 'info', text: 'goal saved' })
  210. expect(m.state.phase).toBe('plain')
  211. expect(m.state.claim).toBeUndefined()
  212. })
  213. it('an error-kind outcome text relays as an error notice on success=false settles', () => {
  214. const m = new SubmitMachine()
  215. const { attempt } = enterSubmitting(m, 'goal', 'x')
  216. const fx = m.dispatch({
  217. type: 'submit-settled', attempt, ok: false, draft: 'deviated',
  218. outcome: { kind: 'error', text: 'rejected' },
  219. })
  220. expect(effectAt(fx, 0, 'notice')).toMatchObject({ level: 'error', text: 'rejected' })
  221. expect(m.state.phase).toBe('plain')
  222. })
  223. it('rollback with an undeviated draft keeps the claim and re-enters claimed', () => {
  224. const m = new SubmitMachine()
  225. const { attempt } = enterSubmitting(m, 'goal', 'x')
  226. m.dispatch({ type: 'submit-settled', attempt, ok: false, draft: '/goal x', message: 'transport' })
  227. expect(m.state.phase).toBe('claimed')
  228. expect(m.state.claim?.token).toBe('/goal ')
  229. })
  230. it('rollback with a deviated draft only notices — the newer input wins', () => {
  231. const m = new SubmitMachine()
  232. const { attempt } = enterSubmitting(m, 'goal', 'x')
  233. const fx = m.dispatch({ type: 'submit-settled', attempt, ok: false, draft: 'rewritten', message: 'transport' })
  234. expect(effectAt(fx, 0, 'notice')).toMatchObject({ level: 'error', text: 'transport' })
  235. expect(m.state.phase).toBe('plain')
  236. expect(m.state.claim).toBeUndefined()
  237. })
  238. it('enter-path rollback cannot re-enter claimed when the snapshot never carried the bare token prefix', () => {
  239. const m = new SubmitMachine()
  240. const attempt = enterAdjudicating(m, ' /goal x')
  241. m.dispatch({ type: 'adjudicated', attempt, outcome: { claim: claimOf('goal') } })
  242. m.dispatch({ type: 'submit-settled', attempt, ok: false, draft: ' /goal x', message: 'nope' })
  243. // The snapshot carries leading whitespace the token never had: plain, claim cleared.
  244. expect(m.state.phase).toBe('plain')
  245. expect(m.state.claim).toBeUndefined()
  246. })
  247. it('a stale settle after rollback + resubmit is dropped (anti-backwash)', () => {
  248. const m = new SubmitMachine()
  249. const { attempt: first } = enterSubmitting(m, 'goal', 'x')
  250. m.dispatch({ type: 'submit-settled', attempt: first, ok: false, draft: '/goal x', message: 'try again' })
  251. const fx = m.dispatch({ type: 'enter', mode: 'queue', draft: '/goal x' })
  252. const second = effectAt(fx, 0, 'begin-submit').attempt
  253. expect(m.dispatch({ type: 'submit-settled', attempt: first, ok: true, draft: '/goal x' })).toEqual([])
  254. expect(m.state.phase).toBe('submitting')
  255. m.dispatch({ type: 'submit-settled', attempt: second, ok: true, draft: '/goal x' })
  256. expect(m.state.phase).toBe('plain')
  257. })
  258. it('release mid-flight aborts the attempt and later settles are dropped', () => {
  259. const m = new SubmitMachine()
  260. const { attempt } = enterSubmitting(m, 'goal', 'x')
  261. m.dispatch({ type: 'release' })
  262. expect(attempt.signal.aborted).toBe(true)
  263. expect(m.dispatch({ type: 'submit-settled', attempt, ok: true, draft: '' })).toEqual([])
  264. expect(m.state.phase).toBe('plain')
  265. })
  266. it('send-committed clears unconditionally (image-only sends have no draft to retain)', () => {
  267. const m = new SubmitMachine()
  268. const fx = m.dispatch({ type: 'send-committed' })
  269. expect(effectAt(fx, 0, 'commit-draft').retainSuffixOf).toBeNull()
  270. const busy = new SubmitMachine()
  271. enterSubmitting(busy, 'goal', 'x')
  272. expect(busy.dispatch({ type: 'send-committed' })).toEqual([])
  273. })
  274. })
  275. describe('submit-machine: per-session isolation', () => {
  276. it('one instance per session: A submitting never locks B; settles land on their own instance', () => {
  277. const a = new SubmitMachine()
  278. const b = new SubmitMachine()
  279. const { attempt } = enterSubmitting(a, 'goal', 'x')
  280. const fx = b.dispatch({ type: 'enter', mode: 'queue', draft: 'hello' })
  281. expect(effectAt(fx, 0, 'default-sink').draft).toBe('hello')
  282. a.dispatch({ type: 'submit-settled', attempt, ok: true, draft: '/goal x' })
  283. expect(a.state.phase).toBe('plain')
  284. expect(b.state.phase).toBe('plain')
  285. })
  286. })
  287. describe('decorations: scanTextRefs', () => {
  288. const lexicon: ReadonlyMap<'/' | '@', readonly string[]> = new Map([
  289. ['/', ['commit-helper', 'goal'] as readonly string[]],
  290. ['@', ['research'] as readonly string[]],
  291. ])
  292. it('matches lexicon tokens at line start and after whitespace, in draft order', () => {
  293. const out = scanTextRefs('/goal then @research and /commit-helper', lexicon)
  294. expect(out.map(r => [r.start, r.end, r.trigger])).toEqual([
  295. [0, 5, '/'], [11, 20, '@'], [25, 39, '/'],
  296. ])
  297. })
  298. it('a cold (empty) lexicon scans nothing lexicon-based', () => {
  299. expect(scanTextRefs('/goal x', new Map())).toEqual([])
  300. })
  301. it('recognizes directory paths independently of the dynamic lexicon', () => {
  302. const out = scanTextRefs('see @src/x/ now', new Map())
  303. expect(out).toEqual([{ start: 4, end: 11, trigger: '@' }])
  304. })
  305. it('names off the lexicon do not match; triggers are routed per lexicon list', () => {
  306. expect(scanTextRefs('/research @goal', lexicon)).toEqual([])
  307. })
  308. it('a "/" token continued by a path never matches, even when the name is on the lexicon', () => {
  309. expect(scanTextRefs('/goal/x /goal/ /goal.md', lexicon)).toEqual([])
  310. })
  311. it('a "/" token glued to punctuation is not a reference: the host gesture is whitespace-bounded', () => {
  312. expect(scanTextRefs('/goal。 then /goal, now', lexicon)).toEqual([])
  313. })
  314. it('word boundary: a trigger glued to text never matches', () => {
  315. expect(scanTextRefs('x/goal y@research', lexicon)).toEqual([])
  316. })
  317. it('tokens never cross a newline; a token straight after one matches', () => {
  318. const out = scanTextRefs('a\n/goal', lexicon)
  319. expect(out).toEqual([{ start: 2, end: 7, trigger: '/' }])
  320. })
  321. })