cancel.spec.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. /**
  3. * Tests for the queue-aware `Agent.cancel()` primitive. `cancel()` is the broad verb — it
  4. * clears queued + steering work, aborts the active turn, and drops work not yet claimed by the
  5. * driver without leaking cancellation into a replacement prompt. The suite covers every landing
  6. * window plus signal reset and `whenIdle()` quiescence.
  7. * @module dsh-agent-loop/tests/cancel
  8. */
  9. import { describe, expect, it, vi } from 'vitest'
  10. import { Context } from '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', (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('notifies every observer before clearing work and contains listener failures', async () => {
  52. const adapter = new MockAdapter([textResponse('must remain unused')])
  53. const ctx = await harness(adapter)
  54. const agent = ctx.agentLoop.create(SessionId('cancel-event'), { provider: 'mock', model: 'mock' })
  55. const warned = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
  56. const seen: string[] = []
  57. ctx.on('agent/cancel-requested', (subject, cause) => {
  58. if (subject !== agent) return
  59. seen.push(`first:${cause.kind}`)
  60. subject.followup(createUserMessage({ content: [{ type: 'text', text: 'queued by cancel observer' }], source: { kind: 'user' } }))
  61. throw new Error('observer failed')
  62. })
  63. ctx.on('agent/cancel-requested', (subject, cause) => {
  64. if (subject === agent) seen.push(`second:${cause.kind}`)
  65. })
  66. send(agent, 'drop me')
  67. agent.cancel({ kind: 'user' })
  68. await new Promise(resolve => setTimeout(resolve, 30))
  69. agent.cancel({ kind: 'parent' })
  70. expect(seen).toEqual(['first:user', 'second:user'])
  71. expect(userTexts(agent)).toEqual([])
  72. expect(adapter.requests).toHaveLength(0)
  73. expect(warned).toHaveBeenCalledWith(expect.stringContaining('agent/cancel-requested'))
  74. })
  75. it('cancel() on an idle agent with nothing queued is a no-op; the next prompt runs (F2 leak guard)', async () => {
  76. const adapter = new MockAdapter([textResponse('reply')])
  77. const ctx = await harness(adapter)
  78. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  79. // The loop is parked at the idle wait with nothing queued. A cancel here must
  80. // NOT arm the marker — otherwise the next legitimate prompt would be dropped.
  81. agent.cancel({ kind: 'user' })
  82. send(agent, 'real prompt')
  83. await waitForIdle(ctx, agent)
  84. // The prompt ran: its user message is in the log and one turn completed.
  85. expect(userTexts(agent)).toEqual(['real prompt'])
  86. expect(agent.session.events.some(e => e.type === 'turn/end')).toBe(true)
  87. })
  88. it('cancel({ keepInbox: true }) preserves queued work and emits no discard', async () => {
  89. const adapter = new MockAdapter([textResponse('reply')])
  90. const ctx = await harness(adapter)
  91. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  92. const discards: unknown[] = []
  93. ctx.on('agent/inbox/discard', (subject, items) => { if (subject === agent) discards.push(items) })
  94. const cancelRequests: unknown[] = []
  95. ctx.on('agent/cancel-requested', (subject, cause) => { if (subject === agent) cancelRequests.push(cause) })
  96. // Queue a turn WITHOUT waking the driver, so it sits in the inbox.
  97. agent.send(createUserMessage({ content: [{ type: 'text', text: 'preserved' }], source: { kind: 'user' } }), { target: 'next-turn', wakeup: false })
  98. // keepInbox cancel: no active turn, work preserved, no discard event. With
  99. // nothing to abort and nothing discarded, the call is a documented no-op,
  100. // so it emits no cancel-requested either.
  101. agent.cancel({ kind: 'user' }, { keepInbox: true })
  102. expect(discards).toEqual([])
  103. expect(cancelRequests).toEqual([])
  104. // The preserved item still runs once the driver is woken by a later send.
  105. send(agent, 'wake it')
  106. await waitForIdle(ctx, agent)
  107. expect(userTexts(agent)).toEqual(['preserved', 'wake it'])
  108. })
  109. it('a lone quiet (wakeup:false) send leaves the agent parked at idle', async () => {
  110. const adapter = new MockAdapter([textResponse('reply')])
  111. const ctx = await harness(adapter)
  112. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  113. // A quiet item alone must NOT wake the driver: no turn runs and whenIdle
  114. // resolves (the agent is quiescent), leaving the item queued.
  115. agent.send(createUserMessage({ content: [{ type: 'text', text: 'quiet' }], source: { kind: 'user' } }), { target: 'next-turn', wakeup: false })
  116. await agent.whenIdle()
  117. expect(agent.status).toBe('idle')
  118. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(false)
  119. // A later waking send drives the loop, and the quiet item rides along first.
  120. send(agent, 'wake')
  121. await waitForIdle(ctx, agent)
  122. expect(userTexts(agent)).toEqual(['quiet', 'wake'])
  123. })
  124. it('cancelling a parked quiet item settles a pending whenIdle() without a later send', async () => {
  125. const adapter = new MockAdapter([textResponse('reply')])
  126. const ctx = await harness(adapter)
  127. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  128. agent.send(createUserMessage({ content: [{ type: 'text', text: 'quiet' }], source: { kind: 'user' } }), { target: 'next-turn', wakeup: false })
  129. const idle = agent.whenIdle()
  130. agent.cancel({ kind: 'user' })
  131. await idle
  132. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(false)
  133. })
  134. it('pre-step cancel drops the about-to-start turn (no turn is opened)', async () => {
  135. const adapter = new MockAdapter([textResponse('should not run')])
  136. const ctx = await harness(adapter)
  137. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  138. // send() queues synchronously (status still idle, loop microtask not yet
  139. // resumed). Cancel in that pre-step window: the queued turn must not run.
  140. send(agent, 'drop me first')
  141. send(agent, 'drop me second')
  142. agent.cancel({ kind: 'user' })
  143. // Give the loop a chance to wake and process the cancel.
  144. await new Promise(r => setTimeout(r, 30))
  145. // No turn was opened — the queued prompt was dropped, never recorded.
  146. expect(userTexts(agent)).toEqual([])
  147. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(false)
  148. expect(agent.status).toBe('idle')
  149. })
  150. it('disposal from the running notification drops queued work before turn start', async () => {
  151. const adapter = new MockAdapter([textResponse('should not run')])
  152. const ctx = await harness(adapter)
  153. const handle = await ctx.agents.create({
  154. sessionId: SessionId('dispose-running-session'),
  155. agentOptions: { provider: 'mock', model: 'mock' },
  156. })
  157. const agent = handle.agent
  158. const running = Promise.withResolvers<undefined>()
  159. let disposalDone: Promise<void> | undefined
  160. ctx.on('agent/status', (subject, status) => {
  161. if (subject !== agent || status !== 'running') return
  162. disposalDone = handle.dispose()
  163. running.resolve(undefined)
  164. })
  165. send(agent, 'drop before claim')
  166. await running.promise
  167. if (disposalDone === undefined) throw new Error('running listener did not start disposal')
  168. await disposalDone
  169. await driverDone(agent)
  170. expect(agent.status).toBe('idle')
  171. expect(agent.session.events.some(event => event.type === 'turn/start')).toBe(false)
  172. expect(userTexts(agent)).toEqual([])
  173. expect(adapter.requests).toHaveLength(0)
  174. })
  175. it('a whenIdle() waiter registered BEFORE a pre-step cancel resolves (F1 hang guard)', async () => {
  176. const adapter = new MockAdapter([textResponse('x')])
  177. const ctx = await harness(adapter)
  178. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  179. // This waiter cannot rely on a running→idle transition because cancellation
  180. // drops the turn before it runs; the skip path must settle it directly.
  181. send(agent, 'q')
  182. const idle = agent.whenIdle()
  183. agent.cancel({ kind: 'user' })
  184. // Must resolve (not hang). A timeout makes the failure a clear test failure.
  185. await Promise.race([
  186. idle,
  187. new Promise((_r, reject) => setTimeout(() => { reject(new Error('whenIdle hung after pre-step cancel')) }, 1000)),
  188. ])
  189. expect(agent.status).toBe('idle')
  190. })
  191. it('idle-listener cancellation settles its waiter without cancelling later work', async () => {
  192. const adapter = new MockAdapter([textResponse('first reply'), textResponse('later reply')])
  193. const ctx = await harness(adapter)
  194. const agent = ctx.agentLoop.create(SessionId('idle-listener-cancel'), { provider: 'mock', model: 'mock' })
  195. const replacementRegistered = Promise.withResolvers<undefined>()
  196. let replacementObservation: Promise<{ status: string; requests: number; turns: number }> | undefined
  197. ctx.on('agent/status', (subject, status) => {
  198. if (subject !== agent || status !== 'idle' || replacementObservation !== undefined) return
  199. send(agent, 'cancelled replacement')
  200. replacementObservation = agent.whenIdle().then(() => ({
  201. status: agent.status,
  202. requests: adapter.requests.length,
  203. turns: agent.session.events.filter(event => event.type === 'turn/start').length,
  204. }))
  205. agent.cancel({ kind: 'user' })
  206. replacementRegistered.resolve(undefined)
  207. })
  208. send(agent, 'first')
  209. await replacementRegistered.promise
  210. if (replacementObservation === undefined) throw new Error('idle listener did not register replacement work')
  211. await expect(Promise.race([
  212. replacementObservation,
  213. new Promise((_resolve, reject) => setTimeout(() => { reject(new Error('whenIdle hung after idle-listener cancel')) }, 1000)),
  214. ])).resolves.toEqual({ status: 'idle', requests: 1, turns: 1 })
  215. const idle = waitForIdle(ctx, agent)
  216. send(agent, 'later')
  217. await idle
  218. expect(adapter.requests).toHaveLength(2)
  219. expect(userTexts(agent)).toEqual(['first', 'later'])
  220. })
  221. it('replacement work queued after idle-listener cancellation still runs', async () => {
  222. const adapter = new MockAdapter([textResponse('first reply'), textResponse('replacement reply')])
  223. const ctx = await harness(adapter)
  224. const agent = ctx.agentLoop.create(SessionId('idle-listener-post-cancel-send'), { provider: 'mock', model: 'mock' })
  225. const replacementRegistered = Promise.withResolvers<undefined>()
  226. let replacementIdle: Promise<void> | undefined
  227. ctx.on('agent/status', (subject, status) => {
  228. if (subject !== agent || status !== 'idle' || replacementIdle !== undefined) return
  229. send(agent, 'cancelled replacement')
  230. agent.cancel({ kind: 'user' })
  231. send(agent, 'surviving replacement')
  232. replacementIdle = agent.whenIdle()
  233. replacementRegistered.resolve(undefined)
  234. })
  235. send(agent, 'first')
  236. await replacementRegistered.promise
  237. if (replacementIdle === undefined) throw new Error('idle listener did not register replacement work')
  238. await replacementIdle
  239. expect(adapter.requests).toHaveLength(2)
  240. expect(userTexts(agent)).toEqual(['first', 'surviving replacement'])
  241. })
  242. it('cancel() mid-step aborts the active turn and drops every queued tail item', async () => {
  243. const adapter = new MockAdapter(['hang'])
  244. const ctx = await harness(adapter)
  245. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  246. const reasons: TurnEndReason[] = []
  247. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  248. send(agent, 'go')
  249. await new Promise(r => setTimeout(r, 30))
  250. expect(agent.status).toBe('running')
  251. send(agent, 'queued tail')
  252. agent.cancel({ kind: 'user' })
  253. await waitForIdle(ctx, agent)
  254. expect(reasons).toEqual([{ kind: 'aborted' }])
  255. expect(userTexts(agent)).toEqual(['go'])
  256. expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
  257. expect(adapter.requests).toHaveLength(1)
  258. })
  259. it('cancel from an assistant/message observer skips execution but balances replay', async () => {
  260. const adapter = new MockAdapter([
  261. toolCallResponse('c1', 'danger', {}),
  262. textResponse('recovered after cancellation'),
  263. ])
  264. const ctx = await harness(adapter)
  265. let executions = 0
  266. ctx.tools.register(defineContentToolFixture({
  267. name: 'danger',
  268. description: 'must not run after cancellation',
  269. parameters: {},
  270. async execute() {
  271. executions += 1
  272. return [{ type: 'text', text: 'ran' }]
  273. },
  274. }))
  275. const agent = ctx.agentLoop.create(SessionId('cancel-after-assistant-message'), { provider: 'mock', model: 'mock' })
  276. const dispose = ctx.on('session/event', (session, event) => {
  277. if (session === agent.session && event.type === 'assistant/message') {
  278. agent.cancel({ kind: 'user' })
  279. }
  280. })
  281. const reasons: TurnEndReason[] = []
  282. ctx.on('session/event', (_session, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  283. send(agent, 'go')
  284. await waitForIdle(ctx, agent)
  285. dispose()
  286. expect(executions).toBe(0)
  287. expect(reasons).toEqual([{ kind: 'aborted' }])
  288. const call = agent.session.events.find(event => event.type === 'tool/call')
  289. const result = agent.session.events.find(event => event.type === 'tool/result')
  290. expect(call?.type === 'tool/call' ? call.data.callId : undefined).toBe('c1')
  291. expect(result?.type === 'tool/result' ? result.data : undefined).toMatchObject({
  292. message: {
  293. source: { kind: 'tool', callId: 'c1' },
  294. content: [{ type: 'tool-result', toolCallId: 'c1', isError: true }],
  295. },
  296. error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  297. })
  298. send(agent, 'continue safely')
  299. await waitForIdle(ctx, agent)
  300. const replayedResult = adapter.requests[1]!.messages
  301. .flatMap(message => message.content)
  302. .find(block => block.type === 'tool-result')
  303. expect(replayedResult).toMatchObject({ toolCallId: 'c1', isError: true })
  304. expect(reasons).toEqual([
  305. { kind: 'aborted' },
  306. { kind: 'completed' },
  307. ])
  308. })
  309. it('a prompt sent AFTER a cancelled turn settles runs normally (marker reset)', async () => {
  310. const adapter = new MockAdapter(['hang', textResponse('second reply')])
  311. const ctx = await harness(adapter)
  312. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  313. // First turn hangs; cancel it mid-step.
  314. send(agent, 'first')
  315. await new Promise(r => setTimeout(r, 30))
  316. agent.cancel({ kind: 'user' })
  317. await waitForIdle(ctx, agent)
  318. // The marker must have been reset after the cancelled turn — a fresh prompt
  319. // runs to completion rather than being dropped by a stale marker.
  320. send(agent, 'second')
  321. await waitForIdle(ctx, agent)
  322. expect(userTexts(agent)).toContain('second')
  323. // The second turn completed (its reply was streamed).
  324. const reasons = agent.session.events.filter(e => e.type === 'turn/end')
  325. expect(reasons.length).toBe(2)
  326. })
  327. it('cancel from a synchronous turn/start session-event listener drops the step (step-start window)', async () => {
  328. const adapter = new MockAdapter([textResponse('should not stream')])
  329. const ctx = await harness(adapter)
  330. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  331. // A turn/start listener fires before a step controller exists, so the
  332. // turn-scoped marker—not step abort—must drop the pending step.
  333. let streamed = false
  334. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  335. const dispose = ctx.on('session/event', (session, event) => {
  336. if (session === agent.session && event.type === 'turn/start') agent.cancel({ kind: 'user' })
  337. })
  338. const reasons: TurnEndReason[] = []
  339. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  340. send(agent, 'go')
  341. await waitForIdle(ctx, agent)
  342. dispose()
  343. // No step streamed (the model never ran), and the turn ended aborted with
  344. // the caller's cause — the marker carries `cancel(cause)` through even
  345. // though no AbortController observed it in this window.
  346. expect(streamed).toBe(false)
  347. expect(reasons).toEqual([{ kind: 'aborted' }])
  348. })
  349. it('cancel from a synchronous step/start session-event listener drops the step (post-step-start window)', async () => {
  350. const adapter = new MockAdapter([textResponse('should not stream')])
  351. const ctx = await harness(adapter)
  352. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  353. // A step/start session-event listener fires AFTER step/start is appended
  354. // (and after the pre-step seam), so cancelling there lands in the SECOND
  355. // cancel check (the one that must closeStep() to balance the already-open
  356. // step) — distinct from a turn-start cancel, caught before the step opens.
  357. let streamed = false
  358. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  359. const dispose = ctx.on('session/event', (session, event) => {
  360. if (session === agent.session && event.type === 'step/start') agent.cancel({ kind: 'user' })
  361. })
  362. const reasons: TurnEndReason[] = []
  363. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  364. send(agent, 'go')
  365. await waitForIdle(ctx, agent)
  366. dispose()
  367. // No step streamed, the turn ended with the coarse aborted outcome, and the
  368. // log is balanced (the open step was closed by the cancel branch).
  369. expect(streamed).toBe(false)
  370. expect(reasons).toEqual([{ kind: 'aborted' }])
  371. const types = agent.session.events.map(e => e.type)
  372. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  373. })
  374. it('disposal from a synchronous step/start session-event listener closes the open step as disposed', async () => {
  375. const adapter = new MockAdapter([textResponse('should not stream')])
  376. const ctx = new Context()
  377. await ctx.plugin(LlmService)
  378. await ctx.plugin(SessionStore)
  379. await ctx.plugin(SystemPrompt)
  380. await ctx.plugin(ToolRegistry)
  381. await ctx.plugin(AgentRegistry)
  382. await ctx.plugin(AgentLoop, { agents: [] })
  383. ctx.llm.registerAdapter(['mock'], adapter)
  384. const handle = await ctx.agents.create({
  385. sessionId: SessionId('dispose-step-start-session'),
  386. agentOptions: { provider: 'mock', model: 'mock' },
  387. })
  388. const agent = handle.agent
  389. let disposalDone: Promise<void> | undefined
  390. let streamed = false
  391. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  392. ctx.on('session/event', (session, event) => {
  393. if (session === agent.session && event.type === 'step/start') disposalDone = handle.dispose()
  394. })
  395. send(agent, 'go')
  396. await disposalDone
  397. await driverDone(agent)
  398. expect(streamed).toBe(false)
  399. expect(adapter.requests).toHaveLength(0)
  400. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  401. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'disposed' })
  402. const types = agent.session.events.map(e => e.type)
  403. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  404. })
  405. it('cancel during the stopping window ends the turn aborted and runs no further step', async () => {
  406. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  407. const ctx = await harness(adapter)
  408. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  409. let steps = 0
  410. const reasons: TurnEndReason[] = []
  411. ctx.on('session/event', (_session, event) => {
  412. if (event.type === 'step/start') steps += 1
  413. if (event.type === 'turn/end') reasons.push(event.data.reason)
  414. })
  415. let cancelled = false
  416. ctx.on('agent/turn-stopping', (subject) => {
  417. if (subject === agent && !cancelled) {
  418. cancelled = true
  419. agent.cancel({ kind: 'user' })
  420. }
  421. })
  422. send(agent, 'go')
  423. await waitForIdle(ctx, agent)
  424. // Only ONE step ran (the second was cancelled in the stopping window),
  425. // and the shared turn signal classified the durable outcome as aborted.
  426. expect(steps).toBe(1)
  427. expect(reasons).toEqual([{ kind: 'aborted' }])
  428. })
  429. it('cancel from a synchronous agent/status(running) listener drops the turn (window 2)', async () => {
  430. const adapter = new MockAdapter([textResponse('should not run')])
  431. const ctx = await harness(adapter)
  432. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  433. // `agent/status` is synchronous, so cancellation can land after the first
  434. // pre-step check; the second check must drop the now-empty turn.
  435. let streamed = false
  436. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  437. const dispose = ctx.on('agent/status', (subject, status) => {
  438. if (subject === agent && status === 'running') agent.cancel({ kind: 'user' })
  439. })
  440. send(agent, 'go')
  441. await waitForIdle(ctx, agent)
  442. dispose()
  443. // No turn opened, no step streamed, and a later prompt still runs (the marker
  444. // was reset).
  445. expect(streamed).toBe(false)
  446. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(false)
  447. })
  448. it('window 2: whenIdle() does NOT resolve early when a running listener cancels then queues replacement work', async () => {
  449. // Cancellation must not settle idle while replacement work remains queued.
  450. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  451. const ctx = await harness(adapter)
  452. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  453. let replaced = false
  454. const dispose = ctx.on('agent/status', (subject, status) => {
  455. if (subject !== agent || status !== 'running' || replaced) return
  456. replaced = true
  457. agent.cancel({ kind: 'user' })
  458. send(agent, 'B')
  459. })
  460. send(agent, 'A')
  461. const idle = agent.whenIdle()
  462. await idle
  463. dispose()
  464. // whenIdle() resolved only AFTER B's turn ran: B's user message + a turn/end
  465. // are in the log, and A was dropped.
  466. expect(userTexts(agent)).toContain('B')
  467. expect(userTexts(agent)).not.toContain('A')
  468. expect(agent.session.events.some(e => e.type === 'turn/end')).toBe(true)
  469. })
  470. it('whenIdle() does NOT resolve early when a new prompt is queued during a pre-step cancel', async () => {
  471. // The subtle race: a whenIdle() waiter is registered for prompt A; cancel() clears A;
  472. // prompt B is queued before the loop resumes from the idle wait.
  473. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  474. const ctx = await harness(adapter)
  475. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  476. send(agent, 'A') // queues A (status still idle, loop microtask pending)
  477. const idle = agent.whenIdle() // registers a waiter (idle + hasQueued → no fast path)
  478. agent.cancel({ kind: 'user' }) // arms marker, clears A
  479. send(agent, 'B') // B races in before the loop resumes
  480. // whenIdle() must resolve only after B's turn fully ran — by which point B's user message
  481. // and a turn/end are in the log.
  482. await idle
  483. expect(userTexts(agent)).toContain('B')
  484. expect(agent.session.events.some(e => e.type === 'turn/end')).toBe(true)
  485. // A was dropped (never ran); only B's turn is recorded.
  486. expect(userTexts(agent)).not.toContain('A')
  487. })
  488. it("cancel clears the turn's steering — it is not re-enqueued as a fresh turn", async () => {
  489. const adapter = new MockAdapter(['hang'])
  490. const ctx = await harness(adapter)
  491. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  492. send(agent, 'go')
  493. await new Promise(r => setTimeout(r, 30))
  494. expect(agent.status).toBe('running')
  495. // Steer (joins the running turn's steering FIFO), then cancel: the steering
  496. // must be dropped, NOT re-enqueued as a new queued turn.
  497. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'steer text' }], source: { kind: 'user' } }))
  498. agent.cancel({ kind: 'user' })
  499. await waitForIdle(ctx, agent)
  500. // After the cancelled turn settles, the agent is idle with NO follow-up turn
  501. // started from the dropped steering.
  502. await new Promise(r => setTimeout(r, 30))
  503. expect(agent.status).toBe('idle')
  504. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  505. expect(turnStarts.length).toBe(1) // only the original (cancelled) turn
  506. // The steering text was dropped — it never reached the log.
  507. const flat = agent.session.events
  508. .filter(e => e.type === 'steering/message')
  509. .flatMap(e => e.type === 'steering/message' ? e.data.message.content : [])
  510. .flatMap(b => b.type === 'text' ? [b.text] : [])
  511. expect(flat).not.toContain('steer text')
  512. })
  513. it('keeps replacement work queued synchronously by an abort observer', async () => {
  514. const adapter = new MockAdapter(['hang', textResponse('replacement reply')])
  515. const ctx = await harness(adapter)
  516. const agent = ctx.agentLoop.create(SessionId('abort-observer-replacement'), { provider: 'mock', model: 'mock' })
  517. send(agent, 'original')
  518. await expect.poll(() => adapter.requests.length).toBe(1)
  519. const signal = adapter.requests[0]?.signal
  520. if (signal === undefined) throw new Error('model request omitted its turn signal')
  521. signal.addEventListener('abort', () => { send(agent, 'replacement') }, { once: true })
  522. const idle = waitForIdle(ctx, agent)
  523. agent.cancel({ kind: 'user' })
  524. await Promise.race([
  525. idle,
  526. new Promise((_resolve, reject) => {
  527. setTimeout(() => {
  528. reject(new Error(`replacement did not settle: ${JSON.stringify({
  529. status: agent.status,
  530. requests: adapter.requests.length,
  531. users: userTexts(agent),
  532. events: agent.session.events.map(event => event.type),
  533. })}`))
  534. }, 1000)
  535. }),
  536. ])
  537. expect(adapter.requests).toHaveLength(2)
  538. expect(userTexts(agent)).toEqual(['original', 'replacement'])
  539. const reasons = agent.session.events
  540. .filter(event => event.type === 'turn/end')
  541. .map(event => event.type === 'turn/end' ? event.data.reason : undefined)
  542. expect(reasons).toEqual([{ kind: 'aborted' }, { kind: 'completed' }])
  543. })
  544. it('keeps the first typed cause for an active turn and detaches the runtime reason', async () => {
  545. const adapter = new MockAdapter(['hang'])
  546. const ctx = await harness(adapter)
  547. const agent = ctx.agentLoop.create(SessionId('typed-first-wins'), { provider: 'mock', model: 'mock' })
  548. const supplied: { kind: 'parent' | 'user' } = { kind: 'parent' }
  549. send(agent, 'go')
  550. await expect.poll(() => adapter.requests.length).toBe(1)
  551. agent.cancel(supplied)
  552. supplied.kind = 'user'
  553. agent.cancel({ kind: 'user' })
  554. await waitForIdle(ctx, agent)
  555. const runtimeReason: unknown = adapter.requests[0]?.signal?.reason
  556. expect(runtimeReason).toEqual({ kind: 'parent' })
  557. expect(runtimeReason).not.toBe(supplied)
  558. expect(Object.isFrozen(runtimeReason)).toBe(true)
  559. const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end')
  560. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' })
  561. })
  562. it('preserves the first user cancellation when lifecycle teardown races it', async () => {
  563. const adapter = new MockAdapter(['hang'])
  564. const ctx = await harness(adapter)
  565. const handle = await ctx.agents.create({
  566. sessionId: SessionId('cancel-dispose-race'),
  567. agentOptions: { provider: 'mock', model: 'mock' },
  568. })
  569. const { agent } = handle
  570. send(agent, 'go')
  571. await expect.poll(() => adapter.requests.length).toBe(1)
  572. agent.cancel({ kind: 'user' })
  573. await handle.dispose()
  574. const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end')
  575. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' })
  576. })
  577. it.each([
  578. 'prompt-submit',
  579. 'system-prompt',
  580. 'step',
  581. 'request',
  582. 'stopping',
  583. 'tool',
  584. ] as const)('lets a cooperative %s boundary settle from the explicit turn signal', async (stage) => {
  585. const adapter = new MockAdapter(stage === 'tool'
  586. ? [toolCallResponse('blocked-tool', 'blocked', {})]
  587. : [textResponse('done')])
  588. const ctx = await harness(adapter)
  589. const agent = ctx.agentLoop.create(SessionId(`cooperative-${stage}`), { provider: 'mock', model: 'mock' })
  590. const started = Promise.withResolvers<undefined>()
  591. const blockUntilAbort = async (signal: AbortSignal): Promise<void> => {
  592. started.resolve(undefined)
  593. if (signal.aborted) return
  594. await new Promise<void>((resolve) => {
  595. signal.addEventListener('abort', () => { resolve() }, { once: true })
  596. })
  597. }
  598. switch (stage) {
  599. case 'prompt-submit':
  600. ctx.on('agent/prompt-submit', async (subject, _message, signal, next) => {
  601. if (subject === agent) await blockUntilAbort(signal)
  602. return next()
  603. })
  604. break
  605. case 'system-prompt':
  606. ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
  607. if (context.agent === agent) {
  608. if (context.signal === undefined) throw new Error('turn assembly omitted its signal')
  609. await blockUntilAbort(context.signal)
  610. }
  611. return next()
  612. })
  613. break
  614. case 'step':
  615. ctx.on('agent/step', async (subject, _turn, _step, signal) => {
  616. if (subject === agent) await blockUntilAbort(signal)
  617. })
  618. break
  619. case 'request':
  620. ctx.on('agent/request', async (subject, _turn, _step, signal, next) => {
  621. if (subject === agent) await blockUntilAbort(signal)
  622. return next()
  623. })
  624. break
  625. case 'stopping':
  626. ctx.on('agent/turn-stopping', async (subject, _turn, signal) => {
  627. if (subject === agent) await blockUntilAbort(signal)
  628. })
  629. break
  630. case 'tool':
  631. ctx.tools.register(defineContentToolFixture({
  632. name: 'blocked',
  633. description: 'wait for cancellation',
  634. parameters: {},
  635. execute: async (_args, exec) => {
  636. if (exec.signal === undefined) throw new Error('tool execution omitted its signal')
  637. await blockUntilAbort(exec.signal)
  638. return [{ type: 'text', text: 'cancelled' }]
  639. },
  640. }))
  641. break
  642. }
  643. send(agent, 'go')
  644. await started.promise
  645. const idle = agent.whenIdle()
  646. agent.cancel({ kind: 'user' })
  647. await idle
  648. const turnEnd = agent.session.events.findLast(event => event.type === 'turn/end')
  649. if (stage === 'prompt-submit') {
  650. expect(turnEnd).toBeUndefined()
  651. } else {
  652. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted' })
  653. }
  654. await ctx.fiber.dispose()
  655. })
  656. })