cancel.spec.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. /**
  3. * Tests for the queue-aware `Agent.cancel()` primitive. The default clears
  4. * queued and steering work, while `keepInbox` preserves pending input for a
  5. * later wake after the active turn reaches quiescence. The suite
  6. * covers every landing window plus signal reset and `whenIdle()` quiescence.
  7. * @module dsh-agent-loop/tests/cancel
  8. */
  9. import { describe, expect, it } from 'vitest'
  10. import { Context } from '@deepseek-ai/cordis'
  11. import LlmService from '@deepseek-ai/dsh-llm'
  12. import SessionStore, { SessionId, TurnEndReason } from '@deepseek-ai/dsh-session'
  13. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  14. import ToolRegistry, { defineContentToolFixture, TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools'
  15. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  16. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  17. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  18. function driverDone(agent: Agent): Promise<void> {
  19. return (agent as Agent & { done: Promise<void> }).done
  20. }
  21. async function harness(adapter: MockAdapter) {
  22. const ctx = new Context()
  23. await ctx.plugin(LlmService)
  24. await ctx.plugin(SessionStore)
  25. await ctx.plugin(SystemPrompt)
  26. await ctx.plugin(ToolRegistry)
  27. await ctx.plugin(AgentRegistry)
  28. await ctx.plugin(AgentLoop, { agents: [] })
  29. ctx.llm.registerAdapter(['mock'], adapter)
  30. return ctx
  31. }
  32. function send(agent: Agent, text: string) {
  33. agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
  34. }
  35. /** Resolve on the agent's next idle transition (event-based, not status poll). */
  36. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  37. return new Promise((resolve) => {
  38. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  39. if (subject === agent && status === 'idle') { dispose(); resolve() }
  40. })
  41. })
  42. }
  43. /** All user-message texts recorded in the log (to assert what actually ran). */
  44. function userTexts(agent: Agent): string[] {
  45. return agent.session.events
  46. .filter(e => e.type === 'user/message')
  47. .flatMap(e => e.type === 'user/message' ? e.data.content : [])
  48. .flatMap(b => b.type === 'text' ? [b.text] : [])
  49. }
  50. describe('Agent.cancel()', () => {
  51. it('cancel() on an idle agent with nothing queued is a no-op; the next prompt runs (F2 leak guard)', async () => {
  52. const adapter = new MockAdapter([textResponse('reply')])
  53. const ctx = await harness(adapter)
  54. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  55. // The loop is parked at the idle wait with nothing queued. A cancel here must
  56. // NOT arm the marker — otherwise the next legitimate prompt would be dropped.
  57. agent.cancel({ kind: 'user' })
  58. send(agent, 'real prompt')
  59. await waitForIdle(ctx, agent)
  60. // The prompt ran: its user message is in the log and one turn completed.
  61. expect(userTexts(agent)).toEqual(['real prompt'])
  62. expect(agent.session.events.some(e => e.type === 'turn/end')).toBe(true)
  63. })
  64. it('cancel({ keepInbox: true }) does not restore work already claimed by a waking send', async () => {
  65. const adapter = new MockAdapter([textResponse('wake reply')])
  66. const ctx = await harness(adapter)
  67. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  68. agent.followup(createUserMessage({
  69. content: [{ type: 'text', text: 'preserved' }],
  70. source: { kind: 'user' },
  71. }))
  72. // A waking send starts and claims synchronously, so keepInbox has no
  73. // pending item to preserve by the time this cancellation runs.
  74. agent.cancel({ kind: 'user' }, { keepInbox: true })
  75. expect(agent.session.events.some(event =>
  76. event.type === 'agent/inbox/spliced' && event.data.outcome === 'canceled')).toBe(false)
  77. await agent.whenIdle()
  78. expect(agent.inbox.nextTurn).toHaveLength(0)
  79. expect(userTexts(agent)).toEqual([])
  80. expect(adapter.requests).toHaveLength(0)
  81. expect(agent.session.events.findLast(event => event.type === 'turn/end')?.data.reason)
  82. .toEqual({ kind: 'aborted', reason: { kind: 'user' } })
  83. const idle = waitForIdle(ctx, agent)
  84. send(agent, 'wake it')
  85. await idle
  86. expect(userTexts(agent)).toEqual(['wake it'])
  87. expect(adapter.requests).toHaveLength(1)
  88. })
  89. it('cancel({ keepInbox: true }) parks queued work after an active turn aborts', async () => {
  90. const adapter = new MockAdapter([
  91. 'hang',
  92. textResponse('preserved reply'),
  93. textResponse('wake reply'),
  94. ])
  95. const ctx = await harness(adapter)
  96. const agent = ctx.agentLoop.create(SessionId('keep-after-abort'), { provider: 'mock', model: 'mock' })
  97. send(agent, 'active')
  98. await new Promise(resolve => setTimeout(resolve, 30))
  99. send(agent, 'preserved')
  100. agent.cancel({ kind: 'user' }, { keepInbox: true })
  101. await agent.whenIdle()
  102. expect(userTexts(agent)).toEqual(['active'])
  103. expect(agent.inbox.nextTurn).toHaveLength(1)
  104. expect(adapter.requests).toHaveLength(1)
  105. const idle = waitForIdle(ctx, agent)
  106. send(agent, 'wake it')
  107. await idle
  108. expect(userTexts(agent)).toEqual(['active', 'preserved', 'wake it'])
  109. expect(adapter.requests).toHaveLength(3)
  110. })
  111. it('cancel({ keepInbox: true }) latches a waking send landing in the abort-to-idle window', async () => {
  112. const adapter = new MockAdapter(['hang', textResponse('B reply')])
  113. const ctx = await harness(adapter)
  114. const agent = ctx.agentLoop.create(SessionId('latch-window'), { provider: 'mock', model: 'mock' })
  115. send(agent, 'active')
  116. await new Promise(resolve => setTimeout(resolve, 30))
  117. // The abort signal is set but the driver has not converged to idle yet:
  118. // the waking send must be latched, not parked until another wake.
  119. agent.cancel({ kind: 'user' }, { keepInbox: true })
  120. send(agent, 'B')
  121. await agent.whenIdle()
  122. expect(userTexts(agent)).toEqual(['active', 'B'])
  123. expect(adapter.requests).toHaveLength(2)
  124. expect(agent.inbox.nextTurn).toHaveLength(0)
  125. expect(agent.session.events.filter(e => e.type === 'turn/end').map(e =>
  126. e.type === 'turn/end' ? e.data.reason : null)).toEqual([
  127. { kind: 'aborted', reason: { kind: 'user' } },
  128. { kind: 'completed' },
  129. ])
  130. })
  131. it('cancel() without keepInbox clears a latched wake alongside the inbox', async () => {
  132. const adapter = new MockAdapter(['hang', textResponse('C reply')])
  133. const ctx = await harness(adapter)
  134. const agent = ctx.agentLoop.create(SessionId('latch-cleared'), { provider: 'mock', model: 'mock' })
  135. send(agent, 'active')
  136. await new Promise(resolve => setTimeout(resolve, 30))
  137. agent.cancel({ kind: 'user' }, { keepInbox: true })
  138. send(agent, 'B') // latched behind the aborted activity
  139. agent.cancel({ kind: 'user' }) // drops the inbox and the latch with it
  140. await agent.whenIdle()
  141. expect(userTexts(agent)).toEqual(['active'])
  142. expect(agent.inbox.nextTurn).toHaveLength(0)
  143. expect(adapter.requests).toHaveLength(1)
  144. send(agent, 'C')
  145. await agent.whenIdle()
  146. expect(userTexts(agent)).toEqual(['active', 'C'])
  147. expect(adapter.requests).toHaveLength(2)
  148. })
  149. it('removing the latched wake before convergence suppresses the replay', async () => {
  150. const adapter = new MockAdapter(['hang'])
  151. const ctx = await harness(adapter)
  152. const agent = ctx.agentLoop.create(SessionId('removed-latched-wake'), { provider: 'mock', model: 'mock' })
  153. send(agent, 'active')
  154. await new Promise(resolve => setTimeout(resolve, 30))
  155. agent.cancel({ kind: 'user' }, { keepInbox: true })
  156. const steer = createUserMessage({ content: [{ type: 'text', text: 'steer me' }], source: { kind: 'user' } })
  157. agent.steer(steer) // latched behind the aborted activity
  158. agent.inbox.remove(steer.id) // the wake is retracted before convergence
  159. await agent.whenIdle()
  160. expect(userTexts(agent)).toEqual(['active'])
  161. expect(adapter.requests).toHaveLength(1)
  162. expect(agent.inbox.nextTurn).toHaveLength(0)
  163. expect(agent.status).toBe('idle')
  164. // No replay with nothing to run: the latched message is gone, so no
  165. // empty follow-up turn is recorded.
  166. expect(agent.session.events.filter(e => e.type === 'turn/start')).toHaveLength(1)
  167. })
  168. it('latches a wake arriving deep into a slow abort convergence', async () => {
  169. // The stream notices the abort only after 50ms, so the driver stays in
  170. // the abort-to-idle window long after `cancel()` returned: the wake must
  171. // be latched across the whole window, not just the same-tick case.
  172. const adapter = new MockAdapter(['hang-slow', textResponse('B reply')])
  173. const ctx = await harness(adapter)
  174. const agent = ctx.agentLoop.create(SessionId('slow-convergence'), { provider: 'mock', model: 'mock' })
  175. send(agent, 'A')
  176. await new Promise(resolve => setTimeout(resolve, 30))
  177. agent.cancel({ kind: 'user' }, { keepInbox: true })
  178. await new Promise(resolve => setTimeout(resolve, 10))
  179. send(agent, 'B')
  180. await agent.whenIdle()
  181. expect(userTexts(agent)).toEqual(['A', 'B'])
  182. expect(adapter.requests).toHaveLength(2)
  183. expect(agent.inbox.nextTurn).toHaveLength(0)
  184. })
  185. it('does not latch a wake landing after disposal begins', async () => {
  186. const adapter = new MockAdapter(['hang-slow', textResponse('late reply')])
  187. const ctx = await harness(adapter)
  188. const handle = await ctx.agents.create({
  189. sessionId: SessionId('dispose-window-wake'),
  190. agentOptions: { provider: 'mock', model: 'mock' },
  191. })
  192. const agent = handle.agent
  193. send(agent, 'active')
  194. await new Promise(resolve => setTimeout(resolve, 30))
  195. // Dispose cancels with `{ kind: 'disposed' }`; a wake landing in the
  196. // abort-to-idle window must not latch, so `whenIdle()` does not wait on
  197. // a model turn over the session being torn down.
  198. const disposal = handle.dispose()
  199. setTimeout(() => { send(agent, 'late wake') }, 10)
  200. await disposal
  201. expect(adapter.requests).toHaveLength(1)
  202. expect(userTexts(agent)).toEqual(['active'])
  203. })
  204. it('cancel after waking send closes its synchronously opened turn without a step', async () => {
  205. const adapter = new MockAdapter([textResponse('should not run')])
  206. const ctx = await harness(adapter)
  207. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  208. send(agent, 'drop me first')
  209. send(agent, 'drop me second')
  210. agent.cancel({ kind: 'user' })
  211. await new Promise(r => setTimeout(r, 30))
  212. expect(userTexts(agent)).toEqual([])
  213. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  214. expect(agent.session.events.filter(event => event.type === 'step/start')).toHaveLength(0)
  215. expect(agent.session.events.findLast(event => event.type === 'turn/end')?.data.reason)
  216. .toEqual({ kind: 'aborted', reason: { kind: 'user' } })
  217. expect(agent.status).toBe('idle')
  218. })
  219. it('disposal from the running notification drops queued work before turn start', async () => {
  220. const adapter = new MockAdapter([textResponse('should not run')])
  221. const ctx = await harness(adapter)
  222. const handle = await ctx.agents.create({
  223. sessionId: SessionId('dispose-running-session'),
  224. agentOptions: { provider: 'mock', model: 'mock' },
  225. })
  226. const agent = handle.agent
  227. const running = Promise.withResolvers<undefined>()
  228. let disposalDone: Promise<void> | undefined
  229. ctx.on('agent/status', ({ agent: subject, status }) => {
  230. if (subject !== agent || status !== 'running') return
  231. disposalDone = handle.dispose()
  232. running.resolve(undefined)
  233. })
  234. send(agent, 'drop before claim')
  235. await running.promise
  236. if (disposalDone === undefined) throw new Error('running listener did not start disposal')
  237. await disposalDone
  238. await driverDone(agent)
  239. expect(agent.status).toBe('idle')
  240. expect(agent.session.events.some(event => event.type === 'turn/start')).toBe(false)
  241. expect(userTexts(agent)).toEqual([])
  242. expect(adapter.requests).toHaveLength(0)
  243. })
  244. it('a whenIdle() waiter registered BEFORE a pre-step cancel resolves (F1 hang guard)', async () => {
  245. const adapter = new MockAdapter([textResponse('x')])
  246. const ctx = await harness(adapter)
  247. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  248. // This waiter cannot rely on a running→idle transition because cancellation
  249. // drops the turn before it runs; the skip path must settle it directly.
  250. send(agent, 'q')
  251. const idle = agent.whenIdle()
  252. agent.cancel({ kind: 'user' })
  253. // Must resolve (not hang). A timeout makes the failure a clear test failure.
  254. await Promise.race([
  255. idle,
  256. new Promise((_r, reject) => setTimeout(() => { reject(new Error('whenIdle hung after pre-step cancel')) }, 1000)),
  257. ])
  258. expect(agent.status).toBe('idle')
  259. })
  260. it('idle-listener cancellation settles its waiter without cancelling later work', async () => {
  261. const adapter = new MockAdapter([textResponse('first reply'), textResponse('later reply')])
  262. const ctx = await harness(adapter)
  263. const agent = ctx.agentLoop.create(SessionId('idle-listener-cancel'), { provider: 'mock', model: 'mock' })
  264. const replacementRegistered = Promise.withResolvers<undefined>()
  265. let replacementObservation: Promise<{ status: string; requests: number; turns: number }> | undefined
  266. ctx.on('agent/status', ({ agent: subject, status }) => {
  267. if (subject !== agent || status !== 'idle' || replacementObservation !== undefined) return
  268. send(agent, 'cancelled replacement')
  269. replacementObservation = agent.whenIdle().then(() => ({
  270. status: agent.status,
  271. requests: adapter.requests.length,
  272. turns: agent.session.events.filter(event => event.type === 'turn/start').length,
  273. }))
  274. agent.cancel({ kind: 'user' })
  275. replacementRegistered.resolve(undefined)
  276. })
  277. send(agent, 'first')
  278. await replacementRegistered.promise
  279. if (replacementObservation === undefined) throw new Error('idle listener did not register replacement work')
  280. await expect(Promise.race([
  281. replacementObservation,
  282. new Promise((_resolve, reject) => setTimeout(() => { reject(new Error('whenIdle hung after idle-listener cancel')) }, 1000)),
  283. ])).resolves.toEqual({ status: 'idle', requests: 1, turns: 2 })
  284. const idle = waitForIdle(ctx, agent)
  285. send(agent, 'later')
  286. await idle
  287. expect(adapter.requests).toHaveLength(2)
  288. expect(userTexts(agent)).toEqual(['first', 'later'])
  289. })
  290. it('replacement work queued after idle-listener cancellation replays at convergence', async () => {
  291. const adapter = new MockAdapter([
  292. textResponse('first reply'),
  293. textResponse('replacement reply'),
  294. textResponse('wake reply'),
  295. ])
  296. const ctx = await harness(adapter)
  297. const agent = ctx.agentLoop.create(SessionId('idle-listener-post-cancel-send'), { provider: 'mock', model: 'mock' })
  298. const replacementRegistered = Promise.withResolvers<undefined>()
  299. let replacementIdle: Promise<void> | undefined
  300. ctx.on('agent/status', ({ agent: subject, status }) => {
  301. if (subject !== agent || status !== 'idle' || replacementIdle !== undefined) return
  302. send(agent, 'cancelled replacement')
  303. agent.cancel({ kind: 'user' })
  304. send(agent, 'surviving replacement')
  305. replacementIdle = agent.whenIdle()
  306. replacementRegistered.resolve(undefined)
  307. })
  308. send(agent, 'first')
  309. await replacementRegistered.promise
  310. if (replacementIdle === undefined) throw new Error('idle listener did not register replacement work')
  311. await replacementIdle
  312. // The wake sent after the cancel fired is latched: the surviving
  313. // replacement runs at convergence without a third message.
  314. expect(adapter.requests).toHaveLength(2)
  315. expect(userTexts(agent)).toEqual(['first', 'surviving replacement'])
  316. expect(agent.inbox.nextTurn).toHaveLength(0)
  317. const idle = waitForIdle(ctx, agent)
  318. send(agent, 'wake it')
  319. await idle
  320. expect(adapter.requests).toHaveLength(3)
  321. expect(userTexts(agent)).toEqual(['first', 'surviving replacement', 'wake it'])
  322. })
  323. it('cancel() mid-step aborts the active turn and drops every queued tail item', async () => {
  324. const adapter = new MockAdapter(['hang'])
  325. const ctx = await harness(adapter)
  326. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  327. const reasons: TurnEndReason[] = []
  328. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  329. send(agent, 'go')
  330. await new Promise(r => setTimeout(r, 30))
  331. expect(agent.status).toBe('running')
  332. send(agent, 'queued tail')
  333. agent.cancel({ kind: 'user' })
  334. await waitForIdle(ctx, agent)
  335. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  336. expect(userTexts(agent)).toEqual(['go'])
  337. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  338. expect(adapter.requests).toHaveLength(1)
  339. })
  340. it('cancel from an assistant/message observer skips execution but balances replay', async () => {
  341. const adapter = new MockAdapter([
  342. toolCallResponse('c1', 'danger', {}),
  343. textResponse('recovered after cancellation'),
  344. ])
  345. const ctx = await harness(adapter)
  346. let executions = 0
  347. ctx.tools.register(defineContentToolFixture({
  348. name: 'danger',
  349. description: 'must not run after cancellation',
  350. parameters: {},
  351. async execute() {
  352. executions += 1
  353. return [{ type: 'text', text: 'ran' }]
  354. },
  355. }))
  356. const agent = ctx.agentLoop.create(SessionId('cancel-after-assistant-message'), { provider: 'mock', model: 'mock' })
  357. const dispose = ctx.on('session/event', (session, event) => {
  358. if (session === agent.session && event.type === 'assistant/message') {
  359. agent.cancel({ kind: 'user' })
  360. }
  361. })
  362. const reasons: TurnEndReason[] = []
  363. ctx.on('session/event', (_session, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  364. send(agent, 'go')
  365. await waitForIdle(ctx, agent)
  366. dispose()
  367. expect(executions).toBe(0)
  368. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  369. const call = agent.session.events.find(event => event.type === 'tool/call')
  370. const result = agent.session.events.find(event => event.type === 'tool/result')
  371. expect(call?.type === 'tool/call' ? call.data.callId : undefined).toBe('c1')
  372. expect(result?.type === 'tool/result' ? result.data : undefined).toMatchObject({
  373. message: {
  374. source: { kind: 'tool', callId: 'c1' },
  375. content: [{ type: 'tool-result', toolCallId: 'c1', isError: true }],
  376. },
  377. error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  378. })
  379. send(agent, 'continue safely')
  380. await waitForIdle(ctx, agent)
  381. const replayedResult = adapter.requests[1]!.messages
  382. .flatMap(message => message.content)
  383. .find(block => block.type === 'tool-result')
  384. expect(replayedResult).toMatchObject({ toolCallId: 'c1', isError: true })
  385. expect(reasons).toEqual([
  386. { kind: 'aborted', reason: { kind: 'user' } },
  387. { kind: 'completed' },
  388. ])
  389. })
  390. it('a prompt sent AFTER a cancelled turn settles runs normally (marker reset)', async () => {
  391. const adapter = new MockAdapter(['hang', textResponse('second reply')])
  392. const ctx = await harness(adapter)
  393. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  394. // First turn hangs; cancel it mid-step.
  395. send(agent, 'first')
  396. await new Promise(r => setTimeout(r, 30))
  397. agent.cancel({ kind: 'user' })
  398. await waitForIdle(ctx, agent)
  399. // The marker must have been reset after the cancelled turn — a fresh prompt
  400. // runs to completion rather than being dropped by a stale marker.
  401. send(agent, 'second')
  402. await waitForIdle(ctx, agent)
  403. expect(userTexts(agent)).toContain('second')
  404. // The second turn completed (its reply was streamed).
  405. const reasons = agent.session.events.filter(e => e.type === 'turn/end')
  406. expect(reasons.length).toBe(2)
  407. })
  408. it('cancel from a synchronous step/start session-event listener drops the step (post-step-start window)', async () => {
  409. const adapter = new MockAdapter([textResponse('should not stream')])
  410. const ctx = await harness(adapter)
  411. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  412. // A step/start session-event listener fires AFTER step/start is appended
  413. // (and after the pre-step extension point), so cancelling there lands in the SECOND
  414. // cancel check (the one that must closeStep() to balance the already-open
  415. // step) — distinct from a turn-start cancel, caught before the step opens.
  416. let streamed = false
  417. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  418. const dispose = ctx.on('session/event', (session, event) => {
  419. if (session === agent.session && event.type === 'step/start') agent.cancel({ kind: 'user' })
  420. })
  421. const reasons: TurnEndReason[] = []
  422. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  423. send(agent, 'go')
  424. await waitForIdle(ctx, agent)
  425. dispose()
  426. // No step streamed, the turn ended with the coarse aborted outcome, and the
  427. // log is balanced (the open step was closed by the cancel branch).
  428. expect(streamed).toBe(false)
  429. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  430. const types = agent.session.events.map(e => e.type)
  431. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  432. })
  433. it('disposal from a synchronous step/start session-event listener stops before adapter dispatch', async () => {
  434. const adapter = new MockAdapter([textResponse('should not stream')])
  435. const ctx = new Context()
  436. await ctx.plugin(LlmService)
  437. await ctx.plugin(SessionStore)
  438. await ctx.plugin(SystemPrompt)
  439. await ctx.plugin(ToolRegistry)
  440. await ctx.plugin(AgentRegistry)
  441. await ctx.plugin(AgentLoop, { agents: [] })
  442. ctx.llm.registerAdapter(['mock'], adapter)
  443. const handle = await ctx.agents.create({
  444. sessionId: SessionId('dispose-step-start-session'),
  445. agentOptions: { provider: 'mock', model: 'mock' },
  446. })
  447. const agent = handle.agent
  448. let disposalDone: Promise<void> | undefined
  449. let streamed = false
  450. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  451. ctx.on('session/event', (session, event) => {
  452. if (session === agent.session && event.type === 'step/start') disposalDone = handle.dispose()
  453. })
  454. send(agent, 'go')
  455. await disposalDone
  456. await driverDone(agent)
  457. expect(streamed).toBe(false)
  458. expect(adapter.requests).toHaveLength(0)
  459. expect(agent.session.events.some(e => e.type === 'turn/end')).toBe(false)
  460. const types = agent.session.events.map(e => e.type)
  461. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  462. })
  463. it('cancel during the stopping window ends the turn aborted and runs no further step', async () => {
  464. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  465. const ctx = await harness(adapter)
  466. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  467. let steps = 0
  468. const reasons: TurnEndReason[] = []
  469. ctx.on('session/event', (_session, event) => {
  470. if (event.type === 'step/start') steps += 1
  471. if (event.type === 'turn/end') reasons.push(event.data.reason)
  472. })
  473. let cancelled = false
  474. ctx.on('agent/turn-stopping', ({ agent: subject }) => {
  475. if (subject === agent && !cancelled) {
  476. cancelled = true
  477. agent.cancel({ kind: 'user' })
  478. }
  479. })
  480. send(agent, 'go')
  481. await waitForIdle(ctx, agent)
  482. // Only ONE step ran (the second was cancelled in the stopping window),
  483. // and the shared turn signal classified the durable outcome as aborted.
  484. expect(steps).toBe(1)
  485. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  486. })
  487. it('cancel from a synchronous agent/status(running) listener drops the turn (window 2)', async () => {
  488. const adapter = new MockAdapter([textResponse('should not run')])
  489. const ctx = await harness(adapter)
  490. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  491. // `agent/status` is synchronous, so cancellation can land before the
  492. // durable turn-start commit and must drop the reserved work.
  493. let streamed = false
  494. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  495. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  496. if (subject === agent && status === 'running') agent.cancel({ kind: 'user' })
  497. })
  498. send(agent, 'go')
  499. await waitForIdle(ctx, agent)
  500. dispose()
  501. // No turn opened, no step streamed, and a later prompt still runs (the marker
  502. // was reset).
  503. expect(streamed).toBe(false)
  504. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(false)
  505. })
  506. it('a running-listener cancellation replays replacement work at convergence', async () => {
  507. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  508. const ctx = await harness(adapter)
  509. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  510. let replaced = false
  511. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  512. if (subject !== agent || status !== 'running' || replaced) return
  513. replaced = true
  514. agent.cancel({ kind: 'user' })
  515. send(agent, 'B')
  516. })
  517. send(agent, 'A')
  518. const idle = agent.whenIdle()
  519. await idle
  520. dispose()
  521. // B's wake was latched behind the cancelled driver: it runs on its own.
  522. expect(userTexts(agent)).toEqual(['B'])
  523. expect(agent.inbox.nextTurn).toHaveLength(0)
  524. expect(adapter.requests).toHaveLength(1)
  525. const replacementIdle = waitForIdle(ctx, agent)
  526. send(agent, 'C')
  527. await replacementIdle
  528. expect(userTexts(agent)).toEqual(['B', 'C'])
  529. expect(adapter.requests).toHaveLength(2)
  530. expect(agent.session.events.filter(event => event.type === 'turn/end')).toHaveLength(2)
  531. })
  532. it('a prompt queued during pre-step cancellation replays at convergence', async () => {
  533. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  534. const ctx = await harness(adapter)
  535. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  536. send(agent, 'A')
  537. const idle = agent.whenIdle()
  538. agent.cancel({ kind: 'user' })
  539. send(agent, 'B')
  540. await idle
  541. expect(userTexts(agent)).toEqual(['B'])
  542. expect(agent.inbox.nextTurn).toHaveLength(0)
  543. expect(adapter.requests).toHaveLength(1)
  544. const replacementIdle = waitForIdle(ctx, agent)
  545. send(agent, 'C')
  546. await replacementIdle
  547. expect(userTexts(agent)).toEqual(['B', 'C'])
  548. expect(adapter.requests).toHaveLength(2)
  549. expect(agent.session.events.filter(event => event.type === 'turn/end')).toHaveLength(3)
  550. })
  551. it("cancel clears the turn's steering — it is not re-enqueued as a fresh turn", async () => {
  552. const adapter = new MockAdapter(['hang'])
  553. const ctx = await harness(adapter)
  554. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  555. send(agent, 'go')
  556. await new Promise(r => setTimeout(r, 30))
  557. expect(agent.status).toBe('running')
  558. // Steer (joins the running turn's steering FIFO), then cancel: the steering
  559. // must be dropped, NOT re-enqueued as a new queued turn.
  560. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'steer text' }], source: { kind: 'user' } }))
  561. agent.cancel({ kind: 'user' })
  562. await waitForIdle(ctx, agent)
  563. // After the cancelled turn settles, the agent is idle with NO follow-up turn
  564. // started from the dropped steering.
  565. await new Promise(r => setTimeout(r, 30))
  566. expect(agent.status).toBe('idle')
  567. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  568. expect(turnStarts.length).toBe(1) // only the original (cancelled) turn
  569. // The steering text was dropped — it never reached the log.
  570. const flat = agent.session.events
  571. .filter(e => e.type === 'user/message')
  572. .flatMap(e => e.data.content)
  573. .flatMap(b => b.type === 'text' ? [b.text] : [])
  574. expect(flat).not.toContain('steer text')
  575. })
  576. it('replays replacement work queued synchronously by an abort observer', async () => {
  577. const adapter = new MockAdapter([
  578. 'hang',
  579. textResponse('replacement reply'),
  580. textResponse('wake reply'),
  581. ])
  582. const ctx = await harness(adapter)
  583. const agent = ctx.agentLoop.create(SessionId('abort-observer-replacement'), { provider: 'mock', model: 'mock' })
  584. send(agent, 'original')
  585. await expect.poll(() => adapter.requests.length).toBe(1)
  586. const signal = adapter.requests[0]?.signal
  587. if (signal === undefined) throw new Error('model request omitted its turn signal')
  588. signal.addEventListener('abort', () => { send(agent, 'replacement') }, { once: true })
  589. const idle = agent.whenIdle()
  590. agent.cancel({ kind: 'user' })
  591. await Promise.race([
  592. idle,
  593. new Promise((_resolve, reject) => {
  594. setTimeout(() => {
  595. reject(new Error(`replacement did not settle: ${JSON.stringify({
  596. status: agent.status,
  597. requests: adapter.requests.length,
  598. users: userTexts(agent),
  599. events: agent.session.events.map(event => event.type),
  600. })}`))
  601. }, 1000)
  602. }),
  603. ])
  604. // The abort-observer wake was latched: replacement runs at convergence,
  605. // so the original turn is followed by a completed replacement turn.
  606. expect(adapter.requests).toHaveLength(2)
  607. expect(userTexts(agent)).toEqual(['original', 'replacement'])
  608. expect(agent.inbox.nextTurn).toHaveLength(0)
  609. const reasons = agent.session.events
  610. .filter(event => event.type === 'turn/end')
  611. .map(event => event.type === 'turn/end' ? event.data.reason : undefined)
  612. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }, { kind: 'completed' }])
  613. const replacementIdle = waitForIdle(ctx, agent)
  614. send(agent, 'wake it')
  615. await replacementIdle
  616. expect(adapter.requests).toHaveLength(3)
  617. expect(userTexts(agent)).toEqual(['original', 'replacement', 'wake it'])
  618. })
  619. it('keeps the first typed cause for an active turn', async () => {
  620. const adapter = new MockAdapter(['hang'])
  621. const ctx = await harness(adapter)
  622. const agent = ctx.agentLoop.create(SessionId('typed-first-wins'), { provider: 'mock', model: 'mock' })
  623. const supplied: { kind: 'parent' | 'user' } = { kind: 'parent' }
  624. send(agent, 'go')
  625. await expect.poll(() => adapter.requests.length).toBe(1)
  626. agent.cancel(supplied)
  627. agent.cancel({ kind: 'user' })
  628. await waitForIdle(ctx, agent)
  629. const runtimeReason: unknown = adapter.requests[0]?.signal?.reason
  630. expect(runtimeReason).toEqual({ kind: 'parent' })
  631. expect(runtimeReason).toBe(supplied)
  632. const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end')
  633. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({
  634. kind: 'aborted',
  635. reason: { kind: 'parent' },
  636. })
  637. })
  638. it('preserves the first user cancellation when lifecycle teardown races it', async () => {
  639. const adapter = new MockAdapter(['hang'])
  640. const ctx = await harness(adapter)
  641. const handle = await ctx.agents.create({
  642. sessionId: SessionId('cancel-dispose-race'),
  643. agentOptions: { provider: 'mock', model: 'mock' },
  644. })
  645. const { agent } = handle
  646. send(agent, 'go')
  647. await expect.poll(() => adapter.requests.length).toBe(1)
  648. agent.cancel({ kind: 'user' })
  649. await handle.dispose()
  650. const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end')
  651. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted', reason: { kind: 'user' } })
  652. })
  653. it.each([
  654. 'pre-step',
  655. 'system-prompt',
  656. 'request',
  657. 'stopping',
  658. 'tool',
  659. ] as const)('lets a cooperative %s boundary settle from the explicit turn signal', async (stage) => {
  660. const adapter = new MockAdapter(stage === 'tool'
  661. ? [toolCallResponse('blocked-tool', 'blocked', {})]
  662. : [textResponse('done')])
  663. const ctx = await harness(adapter)
  664. const agent = ctx.agentLoop.create(SessionId(`cooperative-${stage}`), { provider: 'mock', model: 'mock' })
  665. const started = Promise.withResolvers<undefined>()
  666. const blockUntilAbort = async (signal: AbortSignal): Promise<void> => {
  667. started.resolve(undefined)
  668. if (signal.aborted) return
  669. await new Promise<void>((resolve) => {
  670. signal.addEventListener('abort', () => { resolve() }, { once: true })
  671. })
  672. }
  673. switch (stage) {
  674. case 'pre-step':
  675. ctx.on('agent/pre-step', async ({ agent: subject, signal }, next) => {
  676. if (subject === agent) await blockUntilAbort(signal)
  677. return next()
  678. })
  679. break
  680. case 'system-prompt':
  681. ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
  682. if (context.agent === agent) {
  683. if (context.signal === undefined) throw new Error('turn assembly omitted its signal')
  684. await blockUntilAbort(context.signal)
  685. }
  686. return next()
  687. })
  688. break
  689. case 'request':
  690. ctx.on('agent/request', async ({ agent: subject, signal }, next) => {
  691. if (subject === agent) await blockUntilAbort(signal)
  692. return next()
  693. })
  694. break
  695. case 'stopping':
  696. ctx.on('agent/turn-stopping', async ({ agent: subject, signal }) => {
  697. if (subject === agent) await blockUntilAbort(signal)
  698. })
  699. break
  700. case 'tool':
  701. ctx.tools.register(defineContentToolFixture({
  702. name: 'blocked',
  703. description: 'wait for cancellation',
  704. parameters: {},
  705. execute: async (_args, exec) => {
  706. if (exec.signal === undefined) throw new Error('tool execution omitted its signal')
  707. await blockUntilAbort(exec.signal)
  708. return [{ type: 'text', text: 'cancelled' }]
  709. },
  710. }))
  711. break
  712. }
  713. send(agent, 'go')
  714. await started.promise
  715. const idle = agent.whenIdle()
  716. agent.cancel({ kind: 'user' })
  717. await idle
  718. const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end')
  719. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason)
  720. .toEqual({ kind: 'aborted', reason: { kind: 'user' } })
  721. await ctx.fiber.dispose()
  722. })
  723. })