cancel.spec.ts 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. import { ToolCallId, createUserMessage, expandAssistantStream } 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 LlmRuntime from '@deepseek-ai/dsh-llm'
  12. import SessionStore, { Session, SessionId, SessionLogOffset, TurnEndReason } from '@deepseek-ai/dsh-session'
  13. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  14. import ToolRuntime, { 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 SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  18. import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts'
  19. function driverDone(agent: Agent): Promise<void> {
  20. return (agent as Agent & { done: Promise<void> }).done
  21. }
  22. async function harness(adapter: MockAdapter) {
  23. const ctx = new Context()
  24. await ctx.plugin(LlmRuntime)
  25. await ctx.plugin(SessionStore)
  26. await ctx.plugin(SessionProjectionRegistry)
  27. await ctx.plugin(SystemPrompt)
  28. await ctx.plugin(ToolRuntime)
  29. await ctx.plugin(AgentRegistry)
  30. await ctx.plugin(AgentLoop, { agents: [] })
  31. ctx.llm.registerAdapter(['mock'], adapter)
  32. return ctx
  33. }
  34. function send(agent: Agent, text: string) {
  35. agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
  36. }
  37. /** Resolve on the agent's next idle transition (event-based, not status poll). */
  38. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  39. return new Promise((resolve) => {
  40. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  41. if (subject === agent && status === 'idle') { dispose(); resolve() }
  42. })
  43. })
  44. }
  45. /** All user-message texts recorded in the log (to assert what actually ran). */
  46. function userTexts(agent: Agent): string[] {
  47. return agent.session.snapshotEvents()
  48. .filter(e => e.type === 'user/message')
  49. .flatMap(e => e.type === 'user/message' ? e.data.content : [])
  50. .flatMap(b => b.type === 'text' ? [b.text] : [])
  51. }
  52. describe('Agent.cancel()', () => {
  53. it('cancel() on an idle agent with nothing queued is a no-op; the next prompt runs (F2 leak guard)', async () => {
  54. const adapter = new MockAdapter([textResponse('reply')])
  55. const ctx = await harness(adapter)
  56. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  57. // The loop is parked at the idle wait with nothing queued. A cancel here must
  58. // NOT arm the marker — otherwise the next legitimate prompt would be dropped.
  59. agent.cancel({ kind: 'user' })
  60. send(agent, 'real prompt')
  61. await waitForIdle(ctx, agent)
  62. // The prompt ran: its user message is in the log and one turn completed.
  63. expect(userTexts(agent)).toEqual(['real prompt'])
  64. expect(agent.session.snapshotEvents().some(e => e.type === 'turn/end')).toBe(true)
  65. })
  66. it('cancel({ keepInbox: true }) does not restore work already claimed by a waking send', async () => {
  67. const adapter = new MockAdapter([textResponse('wake reply')])
  68. const ctx = await harness(adapter)
  69. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  70. agent.followup(createUserMessage({
  71. content: [{ type: 'text', text: 'preserved' }],
  72. source: { kind: 'user' },
  73. }))
  74. // A waking send starts and claims synchronously, so keepInbox has no
  75. // pending item to preserve by the time this cancellation runs.
  76. agent.cancel({ kind: 'user' }, { keepInbox: true })
  77. expect(agent.session.snapshotEvents().some(event =>
  78. event.type === 'agent/inbox/spliced' && event.data.outcome === 'canceled')).toBe(false)
  79. await agent.whenIdle()
  80. expect(agent.inbox.nextTurn).toHaveLength(0)
  81. expect(userTexts(agent)).toEqual([])
  82. expect(adapter.requests).toHaveLength(0)
  83. expect(agent.session.snapshotEvents().findLast(event => event.type === 'turn/end')?.data.reason)
  84. .toEqual({ kind: 'aborted', reason: { kind: 'user' } })
  85. const idle = waitForIdle(ctx, agent)
  86. send(agent, 'wake it')
  87. await idle
  88. expect(userTexts(agent)).toEqual(['wake it'])
  89. expect(adapter.requests).toHaveLength(1)
  90. })
  91. it('cancel({ keepInbox: true }) parks queued work after an active turn aborts', async () => {
  92. const adapter = new MockAdapter([
  93. 'hang',
  94. textResponse('preserved reply'),
  95. textResponse('wake reply'),
  96. ])
  97. const ctx = await harness(adapter)
  98. const agent = await ctx.agentLoop.create(SessionId('keep-after-abort'), { provider: 'mock', model: 'mock' })
  99. send(agent, 'active')
  100. await new Promise(resolve => setTimeout(resolve, 30))
  101. send(agent, 'preserved')
  102. agent.cancel({ kind: 'user' }, { keepInbox: true })
  103. await agent.whenIdle()
  104. expect(userTexts(agent)).toEqual(['active'])
  105. expect(agent.inbox.nextTurn).toHaveLength(1)
  106. expect(adapter.requests).toHaveLength(1)
  107. const idle = waitForIdle(ctx, agent)
  108. send(agent, 'wake it')
  109. await idle
  110. expect(userTexts(agent)).toEqual(['active', 'preserved', 'wake it'])
  111. expect(adapter.requests).toHaveLength(3)
  112. })
  113. it('cancel({ keepInbox: true }) latches a waking send landing in the abort-to-idle window', async () => {
  114. const adapter = new MockAdapter(['hang', textResponse('B reply')])
  115. const ctx = await harness(adapter)
  116. const agent = await ctx.agentLoop.create(SessionId('latch-window'), { provider: 'mock', model: 'mock' })
  117. send(agent, 'active')
  118. await new Promise(resolve => setTimeout(resolve, 30))
  119. // The abort signal is set but the driver has not converged to idle yet:
  120. // the waking send must be latched, not parked until another wake.
  121. agent.cancel({ kind: 'user' }, { keepInbox: true })
  122. send(agent, 'B')
  123. await agent.whenIdle()
  124. expect(userTexts(agent)).toEqual(['active', 'B'])
  125. expect(adapter.requests).toHaveLength(2)
  126. expect(agent.inbox.nextTurn).toHaveLength(0)
  127. expect(agent.session.snapshotEvents().filter(e => e.type === 'turn/end').map(e =>
  128. e.type === 'turn/end' ? e.data.reason : null)).toEqual([
  129. { kind: 'aborted', reason: { kind: 'user' } },
  130. { kind: 'completed' },
  131. ])
  132. })
  133. it('cancel() without keepInbox clears a latched wake alongside the inbox', async () => {
  134. const adapter = new MockAdapter(['hang', textResponse('C reply')])
  135. const ctx = await harness(adapter)
  136. const agent = await ctx.agentLoop.create(SessionId('latch-cleared'), { provider: 'mock', model: 'mock' })
  137. send(agent, 'active')
  138. await new Promise(resolve => setTimeout(resolve, 30))
  139. agent.cancel({ kind: 'user' }, { keepInbox: true })
  140. send(agent, 'B') // latched behind the aborted activity
  141. agent.cancel({ kind: 'user' }) // drops the inbox and the latch with it
  142. await agent.whenIdle()
  143. expect(userTexts(agent)).toEqual(['active'])
  144. expect(agent.inbox.nextTurn).toHaveLength(0)
  145. expect(adapter.requests).toHaveLength(1)
  146. send(agent, 'C')
  147. await agent.whenIdle()
  148. expect(userTexts(agent)).toEqual(['active', 'C'])
  149. expect(adapter.requests).toHaveLength(2)
  150. })
  151. it('removing the latched wake before convergence suppresses the replay', async () => {
  152. const adapter = new MockAdapter(['hang'])
  153. const ctx = await harness(adapter)
  154. const agent = await ctx.agentLoop.create(SessionId('removed-latched-wake'), { provider: 'mock', model: 'mock' })
  155. send(agent, 'active')
  156. await new Promise(resolve => setTimeout(resolve, 30))
  157. agent.cancel({ kind: 'user' }, { keepInbox: true })
  158. const steer = createUserMessage({ content: [{ type: 'text', text: 'steer me' }], source: { kind: 'user' } })
  159. agent.steer(steer) // latched behind the aborted activity
  160. agent.inbox.remove(steer.id) // the wake is retracted before convergence
  161. await agent.whenIdle()
  162. expect(userTexts(agent)).toEqual(['active'])
  163. expect(adapter.requests).toHaveLength(1)
  164. expect(agent.inbox.nextTurn).toHaveLength(0)
  165. expect(agent.status).toBe('idle')
  166. // No replay with nothing to run: the latched message is gone, so no
  167. // empty follow-up turn is recorded.
  168. expect(agent.session.snapshotEvents().filter(e => e.type === 'turn/start')).toHaveLength(1)
  169. })
  170. it('latches a wake arriving deep into a slow abort convergence', async () => {
  171. // The stream notices the abort only after 50ms, so the driver stays in
  172. // the abort-to-idle window long after `cancel()` returned: the wake must
  173. // be latched across the whole window, not just the same-tick case.
  174. const adapter = new MockAdapter(['hang-slow', textResponse('B reply')])
  175. const ctx = await harness(adapter)
  176. const agent = await ctx.agentLoop.create(SessionId('slow-convergence'), { provider: 'mock', model: 'mock' })
  177. send(agent, 'A')
  178. await new Promise(resolve => setTimeout(resolve, 30))
  179. agent.cancel({ kind: 'user' }, { keepInbox: true })
  180. await new Promise(resolve => setTimeout(resolve, 10))
  181. send(agent, 'B')
  182. await agent.whenIdle()
  183. expect(userTexts(agent)).toEqual(['A', 'B'])
  184. expect(adapter.requests).toHaveLength(2)
  185. expect(agent.inbox.nextTurn).toHaveLength(0)
  186. })
  187. it('does not latch a wake landing after disposal begins', async () => {
  188. const adapter = new MockAdapter(['hang-slow', textResponse('late reply')])
  189. const ctx = await harness(adapter)
  190. const handle = await ctx.agents.create({
  191. sessionId: SessionId('dispose-window-wake'),
  192. agentOptions: { provider: 'mock', model: 'mock' },
  193. })
  194. const agent = handle.agent
  195. send(agent, 'active')
  196. await new Promise(resolve => setTimeout(resolve, 30))
  197. // Dispose cancels with `{ kind: 'disposed' }`; a wake landing in the
  198. // abort-to-idle window must not latch, so `whenIdle()` does not wait on
  199. // a model turn over the session being torn down.
  200. const disposal = handle.dispose()
  201. setTimeout(() => { send(agent, 'late wake') }, 10)
  202. await disposal
  203. expect(adapter.requests).toHaveLength(1)
  204. expect(userTexts(agent)).toEqual(['active'])
  205. })
  206. it('cancel after waking send closes its synchronously opened turn without a step', async () => {
  207. const adapter = new MockAdapter([textResponse('should not run')])
  208. const ctx = await harness(adapter)
  209. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  210. send(agent, 'drop me first')
  211. send(agent, 'drop me second')
  212. agent.cancel({ kind: 'user' })
  213. await new Promise(r => setTimeout(r, 30))
  214. expect(userTexts(agent)).toEqual([])
  215. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1)
  216. expect(agent.session.snapshotEvents().filter(event => event.type === 'step/start')).toHaveLength(0)
  217. expect(agent.session.snapshotEvents().findLast(event => event.type === 'turn/end')?.data.reason)
  218. .toEqual({ kind: 'aborted', reason: { kind: 'user' } })
  219. expect(agent.status).toBe('idle')
  220. })
  221. it('disposal from the running notification drops queued work before turn start', async () => {
  222. const adapter = new MockAdapter([textResponse('should not run')])
  223. const ctx = await harness(adapter)
  224. const handle = await ctx.agents.create({
  225. sessionId: SessionId('dispose-running-session'),
  226. agentOptions: { provider: 'mock', model: 'mock' },
  227. })
  228. const agent = handle.agent
  229. const running = Promise.withResolvers<undefined>()
  230. let disposalDone: Promise<void> | undefined
  231. ctx.on('agent/status', ({ agent: subject, status }) => {
  232. if (subject !== agent || status !== 'running') return
  233. disposalDone = handle.dispose()
  234. running.resolve(undefined)
  235. })
  236. send(agent, 'drop before claim')
  237. await running.promise
  238. if (disposalDone === undefined) throw new Error('running listener did not start disposal')
  239. await disposalDone
  240. await driverDone(agent)
  241. expect(agent.status).toBe('idle')
  242. expect(agent.session.snapshotEvents().some(event => event.type === 'turn/start')).toBe(false)
  243. expect(userTexts(agent)).toEqual([])
  244. expect(adapter.requests).toHaveLength(0)
  245. })
  246. it('a whenIdle() waiter registered BEFORE a pre-step cancel resolves (F1 hang guard)', async () => {
  247. const adapter = new MockAdapter([textResponse('x')])
  248. const ctx = await harness(adapter)
  249. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  250. // This waiter cannot rely on a running→idle transition because cancellation
  251. // drops the turn before it runs; the skip path must settle it directly.
  252. send(agent, 'q')
  253. const idle = agent.whenIdle()
  254. agent.cancel({ kind: 'user' })
  255. // Must resolve (not hang). A timeout makes the failure a clear test failure.
  256. await Promise.race([
  257. idle,
  258. new Promise((_r, reject) => setTimeout(() => { reject(new Error('whenIdle hung after pre-step cancel')) }, 1000)),
  259. ])
  260. expect(agent.status).toBe('idle')
  261. })
  262. it('idle-listener cancellation settles its waiter without cancelling later work', async () => {
  263. const adapter = new MockAdapter([textResponse('first reply'), textResponse('later reply')])
  264. const ctx = await harness(adapter)
  265. const agent = await ctx.agentLoop.create(SessionId('idle-listener-cancel'), { provider: 'mock', model: 'mock' })
  266. const replacementRegistered = Promise.withResolvers<undefined>()
  267. let replacementObservation: Promise<{ status: string; requests: number; turns: number }> | undefined
  268. ctx.on('agent/status', ({ agent: subject, status }) => {
  269. if (subject !== agent || status !== 'idle' || replacementObservation !== undefined) return
  270. send(agent, 'cancelled replacement')
  271. replacementObservation = agent.whenIdle().then(() => ({
  272. status: agent.status,
  273. requests: adapter.requests.length,
  274. turns: agent.session.snapshotEvents().filter(event => event.type === 'turn/start').length,
  275. }))
  276. agent.cancel({ kind: 'user' })
  277. replacementRegistered.resolve(undefined)
  278. })
  279. send(agent, 'first')
  280. await replacementRegistered.promise
  281. if (replacementObservation === undefined) throw new Error('idle listener did not register replacement work')
  282. await expect(Promise.race([
  283. replacementObservation,
  284. new Promise((_resolve, reject) => setTimeout(() => { reject(new Error('whenIdle hung after idle-listener cancel')) }, 1000)),
  285. ])).resolves.toEqual({ status: 'idle', requests: 1, turns: 2 })
  286. const idle = waitForIdle(ctx, agent)
  287. send(agent, 'later')
  288. await idle
  289. expect(adapter.requests).toHaveLength(2)
  290. expect(userTexts(agent)).toEqual(['first', 'later'])
  291. })
  292. it('replacement work queued after idle-listener cancellation replays at convergence', async () => {
  293. const adapter = new MockAdapter([
  294. textResponse('first reply'),
  295. textResponse('replacement reply'),
  296. textResponse('wake reply'),
  297. ])
  298. const ctx = await harness(adapter)
  299. const agent = await ctx.agentLoop.create(SessionId('idle-listener-post-cancel-send'), { provider: 'mock', model: 'mock' })
  300. const replacementRegistered = Promise.withResolvers<undefined>()
  301. let replacementIdle: Promise<void> | undefined
  302. ctx.on('agent/status', ({ agent: subject, status }) => {
  303. if (subject !== agent || status !== 'idle' || replacementIdle !== undefined) return
  304. send(agent, 'cancelled replacement')
  305. agent.cancel({ kind: 'user' })
  306. send(agent, 'surviving replacement')
  307. replacementIdle = agent.whenIdle()
  308. replacementRegistered.resolve(undefined)
  309. })
  310. send(agent, 'first')
  311. await replacementRegistered.promise
  312. if (replacementIdle === undefined) throw new Error('idle listener did not register replacement work')
  313. await replacementIdle
  314. // The wake sent after the cancel fired is latched: the surviving
  315. // replacement runs at convergence without a third message.
  316. expect(adapter.requests).toHaveLength(2)
  317. expect(userTexts(agent)).toEqual(['first', 'surviving replacement'])
  318. expect(agent.inbox.nextTurn).toHaveLength(0)
  319. const idle = waitForIdle(ctx, agent)
  320. send(agent, 'wake it')
  321. await idle
  322. expect(adapter.requests).toHaveLength(3)
  323. expect(userTexts(agent)).toEqual(['first', 'surviving replacement', 'wake it'])
  324. })
  325. it('cancel() mid-step aborts the active turn and drops every queued tail item', async () => {
  326. const adapter = new MockAdapter(['hang'])
  327. const ctx = await harness(adapter)
  328. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  329. const reasons: TurnEndReason[] = []
  330. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  331. send(agent, 'go')
  332. await new Promise(r => setTimeout(r, 30))
  333. expect(agent.status).toBe('running')
  334. send(agent, 'queued tail')
  335. agent.cancel({ kind: 'user' })
  336. await waitForIdle(ctx, agent)
  337. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  338. expect(userTexts(agent)).toEqual(['go'])
  339. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(1)
  340. expect(adapter.requests).toHaveLength(1)
  341. })
  342. it('cancel from an assistant/message observer skips execution but balances replay', async () => {
  343. const adapter = new MockAdapter([
  344. toolCallResponse('c1', 'danger', {}),
  345. textResponse('recovered after cancellation'),
  346. ])
  347. const ctx = await harness(adapter)
  348. let executions = 0
  349. ctx.tools.register(defineContentToolFixture({
  350. name: 'danger',
  351. description: 'must not run after cancellation',
  352. parameters: {},
  353. async execute() {
  354. executions += 1
  355. return [{ type: 'text', text: 'ran' }]
  356. },
  357. }))
  358. const agent = await ctx.agentLoop.create(SessionId('cancel-after-assistant-message'), { provider: 'mock', model: 'mock' })
  359. const dispose = ctx.on('session/event', (session, event) => {
  360. if (session === agent.session && event.type === 'assistant/message') {
  361. agent.cancel({ kind: 'user' })
  362. }
  363. })
  364. const reasons: TurnEndReason[] = []
  365. ctx.on('session/event', (_session, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  366. send(agent, 'go')
  367. await waitForIdle(ctx, agent)
  368. dispose()
  369. expect(executions).toBe(0)
  370. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  371. const call = agent.session.snapshotEvents().find(event => event.type === 'tool/call')
  372. const result = agent.session.snapshotEvents().find(event => event.type === 'tool/result')
  373. expect(call?.type === 'tool/call' ? call.data.callId : undefined).toBe('c1')
  374. expect(result?.type === 'tool/result' ? result.data : undefined).toMatchObject({
  375. message: {
  376. source: { kind: 'tool', callId: 'c1' },
  377. content: [{ type: 'tool-result', toolCallId: 'c1', isError: true }],
  378. },
  379. error: { name: 'AbortError', code: TOOL_ABORTED_BEFORE_DISPATCH },
  380. })
  381. send(agent, 'continue safely')
  382. await waitForIdle(ctx, agent)
  383. const replayedResult = adapter.requests[1]!.messages
  384. .flatMap(message => message.content)
  385. .find(block => block.type === 'tool-result')
  386. expect(replayedResult).toMatchObject({ toolCallId: 'c1', isError: true })
  387. expect(reasons).toEqual([
  388. { kind: 'aborted', reason: { kind: 'user' } },
  389. { kind: 'completed' },
  390. ])
  391. })
  392. it('a prompt sent AFTER a cancelled turn settles runs normally (marker reset)', async () => {
  393. const adapter = new MockAdapter(['hang', textResponse('second reply')])
  394. const ctx = await harness(adapter)
  395. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  396. // First turn hangs; cancel it mid-step.
  397. send(agent, 'first')
  398. await new Promise(r => setTimeout(r, 30))
  399. agent.cancel({ kind: 'user' })
  400. await waitForIdle(ctx, agent)
  401. // The marker must have been reset after the cancelled turn — a fresh prompt
  402. // runs to completion rather than being dropped by a stale marker.
  403. send(agent, 'second')
  404. await waitForIdle(ctx, agent)
  405. expect(userTexts(agent)).toContain('second')
  406. // The second turn completed (its reply was streamed).
  407. const reasons = agent.session.snapshotEvents().filter(e => e.type === 'turn/end')
  408. expect(reasons.length).toBe(2)
  409. })
  410. it('cancel mid-stream finalizes the streamed prefix onto the surface', async () => {
  411. const adapter = new MockAdapter(['hang', textResponse('after')])
  412. const ctx = await harness(adapter)
  413. const agent = await ctx.agentLoop.create(SessionId('partial-finalize'), { provider: 'mock', model: 'mock' })
  414. send(agent, 'go')
  415. await new Promise(r => setTimeout(r, 30))
  416. agent.cancel({ kind: 'user' })
  417. await waitForIdle(ctx, agent)
  418. // The prefix the user watched stream is committed as the step's message,
  419. // carrying the truncation marker and exact embedded stream that delivered it.
  420. const message = agent.session.snapshotEvents().find(e => e.type === 'assistant/message')
  421. expect(message?.type === 'assistant/message' ? message.data.message.content : undefined)
  422. .toEqual([{ type: 'text', text: 'partial' }])
  423. expect(message?.type === 'assistant/message' ? message.data.interrupted : undefined).toBe(true)
  424. expect(message?.type === 'assistant/message'
  425. ? expandAssistantStream(message.data.stream).some(member => (
  426. member.chunk.type === 'text-delta' && member.chunk.text === 'partial'
  427. ))
  428. : false).toBe(true)
  429. expect(message?.sourceEventSeqs).toBeUndefined()
  430. const types = agent.session.snapshotEvents().map(e => e.type)
  431. expect(types.indexOf('assistant/message')).toBeLessThan(types.indexOf('step/end'))
  432. expect(types.indexOf('step/end')).toBeLessThan(types.indexOf('turn/end'))
  433. // The next request derives the finalized prefix: the model sees what the user saw.
  434. send(agent, 'continue')
  435. await waitForIdle(ctx, agent)
  436. const replayed = adapter.requests[1]!.messages
  437. .filter(m => m.role === 'assistant')
  438. .flatMap(m => m.content)
  439. .flatMap(b => b.type === 'text' ? [b.text] : [])
  440. expect(replayed).toContain('partial')
  441. })
  442. it('retains terminal replay state when cancellation races the final stream chunk', async () => {
  443. const response = textResponse('complete')
  444. const replayState = { response: { id: 'response' }, blocks: ['text-meta'] }
  445. response[response.length - 1] = {
  446. type: 'finish', reason: { kind: 'stop' }, replayState,
  447. }
  448. const adapter = new MockAdapter([response])
  449. const ctx = await harness(adapter)
  450. const agent = await ctx.agentLoop.create(SessionId('terminal-cancel-replay'), {
  451. provider: 'mock', model: 'mock',
  452. })
  453. ctx.on('agent/assistant-stream', ({ agent: subject, frame }) => {
  454. if (subject === agent && frame.type === 'chunk' && frame.chunk.type === 'finish') {
  455. agent.cancel({ kind: 'user' })
  456. }
  457. })
  458. send(agent, 'go')
  459. await waitForIdle(ctx, agent)
  460. const message = agent.session.snapshotEvents().find(event => event.type === 'assistant/message')
  461. expect(message?.type === 'assistant/message' ? message.data.message.source.replayState : undefined)
  462. .toEqual(replayState)
  463. expect(message?.type === 'assistant/message' ? message.data.interrupted : undefined).toBe(true)
  464. expect(() => Session.fromRestore(
  465. agent.session.id,
  466. structuredClone([...agent.session.snapshotEvents()]),
  467. structuredClone(agent.session.header),
  468. SessionLogOffset(0),
  469. 'detached',
  470. )).not.toThrow()
  471. })
  472. it('cancel during reasoning-only streaming finalizes the reasoning prefix', async () => {
  473. const adapter = new MockAdapter([{
  474. hangAfter: [
  475. { type: 'block-start', index: 0, blockType: 'reasoning' },
  476. { type: 'reasoning-delta', index: 0, text: 'thinking about it' },
  477. { type: 'usage', usage: { inputTokens: 7, outputTokens: 4 } },
  478. ],
  479. }])
  480. const ctx = await harness(adapter)
  481. const agent = await ctx.agentLoop.create(SessionId('reasoning-finalize'), { provider: 'mock', model: 'mock' })
  482. send(agent, 'go')
  483. await new Promise(r => setTimeout(r, 30))
  484. agent.cancel({ kind: 'user' })
  485. await waitForIdle(ctx, agent)
  486. const message = agent.session.snapshotEvents().find(e => e.type === 'assistant/message')
  487. expect(message?.type === 'assistant/message' ? message.data.message.content : undefined)
  488. .toEqual([{ type: 'reasoning', text: 'thinking about it' }])
  489. // A usage chunk delivered before the cancel travels with the finalized prefix.
  490. expect(message?.type === 'assistant/message' ? message.data.usage : undefined)
  491. .toEqual({ inputTokens: 7, outputTokens: 4 })
  492. })
  493. it('cancel drops a half-streamed tool call and keeps the completed text before it', async () => {
  494. const adapter = new MockAdapter([{
  495. hangAfter: [
  496. { type: 'block-start', index: 0, blockType: 'text' },
  497. { type: 'text-delta', index: 0, text: 'reading the file' },
  498. { type: 'block-end', index: 0, block: { type: 'text', text: 'reading the file' } },
  499. { type: 'block-start', index: 1, blockType: 'tool-call' },
  500. { type: 'tool-call-delta', index: 1, id: ToolCallId('c1'), name: 'read', argumentsDelta: '{"pa' },
  501. ],
  502. }])
  503. const ctx = await harness(adapter)
  504. const agent = await ctx.agentLoop.create(SessionId('tool-call-drop'), { provider: 'mock', model: 'mock' })
  505. send(agent, 'go')
  506. await new Promise(r => setTimeout(r, 30))
  507. agent.cancel({ kind: 'user' })
  508. await waitForIdle(ctx, agent)
  509. // The undispatched call is dropped whole — no dangling tool_use to pair.
  510. const message = agent.session.snapshotEvents().find(e => e.type === 'assistant/message')
  511. expect(message?.type === 'assistant/message' ? message.data.message.content : undefined)
  512. .toEqual([{ type: 'text', text: 'reading the file' }])
  513. expect(agent.session.snapshotEvents().some(e => e.type === 'tool/call')).toBe(false)
  514. })
  515. it('cancel during error recovery does not finalize the failed stream', async () => {
  516. const adapter = new MockAdapter([[
  517. { type: 'block-start', index: 0, blockType: 'text' },
  518. { type: 'text-delta', index: 0, text: 'doomed partial' },
  519. { type: 'finish', reason: { kind: 'error', failure: { message: 'boom', code: 'SERVER_ERROR' } } },
  520. ]])
  521. const ctx = await harness(adapter)
  522. const agent = await ctx.agentLoop.create(SessionId('recovery-cancel'), { provider: 'mock', model: 'mock' })
  523. // Cancellation lands while agent/request-error is in flight — the window
  524. // dsh-llm-retry opens when its backoff waits after appending llm/retry.
  525. ctx.on('agent/request-error', async ({ agent: subject }) => {
  526. if (subject === agent) subject.cancel({ kind: 'user' })
  527. })
  528. send(agent, 'go')
  529. await waitForIdle(ctx, agent)
  530. // The failed stream's prefix stays off the surface: clients reset it on
  531. // retry, and provider failures commit nothing.
  532. expect(agent.session.snapshotEvents().some(e => e.type === 'assistant/message')).toBe(false)
  533. const end = agent.session.snapshotEvents().find(e => e.type === 'turn/end')
  534. expect(end?.type === 'turn/end' ? end.data.reason.kind : undefined).toBe('aborted')
  535. })
  536. it('retry retains the failed attempt while the final message embeds only its own stream', async () => {
  537. const adapter = new MockAdapter([
  538. [
  539. { type: 'block-start', index: 0, blockType: 'text' },
  540. { type: 'text-delta', index: 0, text: 'doomed partial' },
  541. { type: 'finish', reason: { kind: 'error', failure: { message: 'boom', code: 'SERVER_ERROR' } } },
  542. ],
  543. textResponse('recovered'),
  544. ])
  545. const ctx = await harness(adapter)
  546. const agent = await ctx.agentLoop.create(SessionId('retry-discards-content'), { provider: 'mock', model: 'mock' })
  547. ctx.on('agent/request-error', async () => ({ kind: 'retry' as const }))
  548. send(agent, 'go')
  549. await waitForIdle(ctx, agent)
  550. const messages = agent.session.snapshotEvents().filter(e => e.type === 'assistant/message')
  551. expect(messages).toHaveLength(1)
  552. const message = messages[0]!
  553. expect(message.type === 'assistant/message' ? message.data.message.content : undefined)
  554. .toEqual([{ type: 'text', text: 'recovered' }])
  555. expect(message.type === 'assistant/message' ? message.data.interrupted : undefined).toBeUndefined()
  556. const failed = agent.session.snapshotEvents().find(e => e.type === 'assistant/attempt')
  557. expect(failed?.type === 'assistant/attempt'
  558. ? expandAssistantStream(failed.data.stream).some(member => (
  559. member.chunk.type === 'text-delta' && member.chunk.text === 'doomed partial'
  560. ))
  561. : false).toBe(true)
  562. expect(message.type === 'assistant/message'
  563. ? expandAssistantStream(message.data.stream).some(member => (
  564. member.chunk.type === 'text-delta' && member.chunk.text === 'doomed partial'
  565. ))
  566. : true).toBe(false)
  567. })
  568. it('retains a partial attempt when stream middleware rejects without cancellation', async () => {
  569. const failure = new Error('provider transport failed')
  570. const adapter = new MockAdapter([[
  571. { type: 'block-start', index: 0, blockType: 'text' },
  572. { type: 'text-delta', index: 0, text: 'partial before failure' },
  573. ]])
  574. const ctx = await harness(adapter)
  575. const agent = await ctx.agentLoop.create(SessionId('provider-stream-rejection'), { provider: 'mock', model: 'mock' })
  576. ctx.on('llm/stream', async function* (_options, next) {
  577. for await (const chunk of next()) {
  578. yield chunk
  579. if (chunk.type === 'text-delta') throw failure
  580. }
  581. })
  582. send(agent, 'go')
  583. await waitForIdle(ctx, agent)
  584. const attempt = agent.session.snapshotEvents().find(event => event.type === 'assistant/attempt')
  585. expect(attempt?.type === 'assistant/attempt'
  586. ? expandAssistantStream(attempt.data.stream).map(member => member.chunk)
  587. : []).toContainEqual({ type: 'text-delta', index: 0, text: 'partial before failure' })
  588. expect(agent.session.snapshotEvents().find(event => event.type === 'turn/end')).toMatchObject({
  589. type: 'turn/end', data: { reason: { kind: 'error', error: { message: failure.message } } },
  590. })
  591. })
  592. it('cancel before any visible content finalizes nothing', async () => {
  593. const adapter = new MockAdapter([{
  594. hangAfter: [
  595. { type: 'block-start', index: 0, blockType: 'tool-call' },
  596. { type: 'tool-call-delta', index: 0, id: ToolCallId('c1'), name: 'read', argumentsDelta: '{"pa' },
  597. ],
  598. }])
  599. const ctx = await harness(adapter)
  600. const agent = await ctx.agentLoop.create(SessionId('nothing-to-finalize'), { provider: 'mock', model: 'mock' })
  601. send(agent, 'go')
  602. await new Promise(r => setTimeout(r, 30))
  603. agent.cancel({ kind: 'user' })
  604. await waitForIdle(ctx, agent)
  605. expect(agent.session.snapshotEvents().some(e => e.type === 'assistant/message')).toBe(false)
  606. })
  607. it('cancel from a synchronous step/start session-event listener drops the step (post-step-start window)', async () => {
  608. const adapter = new MockAdapter([textResponse('should not stream')])
  609. const ctx = await harness(adapter)
  610. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  611. // A step/start session-event listener fires AFTER step/start is appended
  612. // (and after the pre-step extension point), so cancelling there lands in the SECOND
  613. // cancel check (the one that must closeStep() to balance the already-open
  614. // step) — distinct from a turn-start cancel, caught before the step opens.
  615. let streamed = false
  616. ctx.on('agent/assistant-stream', ({ frame }) => { if (frame.type === 'chunk') streamed = true })
  617. const dispose = ctx.on('session/event', (session, event) => {
  618. if (session === agent.session && event.type === 'step/start') agent.cancel({ kind: 'user' })
  619. })
  620. const reasons: TurnEndReason[] = []
  621. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  622. send(agent, 'go')
  623. await waitForIdle(ctx, agent)
  624. dispose()
  625. // No step streamed, the turn ended with the coarse aborted outcome, and the
  626. // log is balanced (the open step was closed by the cancel branch).
  627. expect(streamed).toBe(false)
  628. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  629. const types = agent.session.snapshotEvents().map(e => e.type)
  630. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  631. })
  632. it('disposal from a synchronous step/start session-event listener stops before adapter dispatch', async () => {
  633. const adapter = new MockAdapter([textResponse('should not stream')])
  634. const ctx = new Context()
  635. await ctx.plugin(LlmRuntime)
  636. await ctx.plugin(SessionStore)
  637. await ctx.plugin(SessionProjectionRegistry)
  638. await ctx.plugin(SystemPrompt)
  639. await ctx.plugin(ToolRuntime)
  640. await ctx.plugin(AgentRegistry)
  641. await ctx.plugin(AgentLoop, { agents: [] })
  642. ctx.llm.registerAdapter(['mock'], adapter)
  643. const handle = await ctx.agents.create({
  644. sessionId: SessionId('dispose-step-start-session'),
  645. agentOptions: { provider: 'mock', model: 'mock' },
  646. })
  647. const agent = handle.agent
  648. let disposalDone: Promise<void> | undefined
  649. let streamed = false
  650. ctx.on('agent/assistant-stream', ({ frame }) => { if (frame.type === 'chunk') streamed = true })
  651. ctx.on('session/event', (session, event) => {
  652. if (session === agent.session && event.type === 'step/start') disposalDone = handle.dispose()
  653. })
  654. send(agent, 'go')
  655. await disposalDone
  656. await driverDone(agent)
  657. expect(streamed).toBe(false)
  658. expect(adapter.requests).toHaveLength(0)
  659. expect(agent.session.snapshotEvents().some(e => e.type === 'turn/end')).toBe(false)
  660. const types = agent.session.snapshotEvents().map(e => e.type)
  661. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  662. })
  663. it('cancel during the stopping window ends the turn aborted and runs no further step', async () => {
  664. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  665. const ctx = await harness(adapter)
  666. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  667. let steps = 0
  668. const reasons: TurnEndReason[] = []
  669. ctx.on('session/event', (_session, event) => {
  670. if (event.type === 'step/start') steps += 1
  671. if (event.type === 'turn/end') reasons.push(event.data.reason)
  672. })
  673. let cancelled = false
  674. ctx.on('agent/turn-stopping', ({ agent: subject }) => {
  675. if (subject === agent && !cancelled) {
  676. cancelled = true
  677. agent.cancel({ kind: 'user' })
  678. }
  679. })
  680. send(agent, 'go')
  681. await waitForIdle(ctx, agent)
  682. // Only ONE step ran (the second was cancelled in the stopping window),
  683. // and the shared turn signal classified the durable outcome as aborted.
  684. expect(steps).toBe(1)
  685. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  686. })
  687. it('cancel from a synchronous agent/status(running) listener drops the turn (window 2)', async () => {
  688. const adapter = new MockAdapter([textResponse('should not run')])
  689. const ctx = await harness(adapter)
  690. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  691. // `agent/status` is synchronous, so cancellation can land before the
  692. // durable turn-start commit and must drop the reserved work.
  693. let streamed = false
  694. ctx.on('agent/assistant-stream', ({ frame }) => { if (frame.type === 'chunk') streamed = true })
  695. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  696. if (subject === agent && status === 'running') agent.cancel({ kind: 'user' })
  697. })
  698. send(agent, 'go')
  699. await waitForIdle(ctx, agent)
  700. dispose()
  701. // No turn opened, no step streamed, and a later prompt still runs (the marker
  702. // was reset).
  703. expect(streamed).toBe(false)
  704. expect(agent.session.snapshotEvents().some(e => e.type === 'turn/start')).toBe(false)
  705. })
  706. it('a running-listener cancellation replays replacement work at convergence', async () => {
  707. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  708. const ctx = await harness(adapter)
  709. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  710. let replaced = false
  711. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  712. if (subject !== agent || status !== 'running' || replaced) return
  713. replaced = true
  714. agent.cancel({ kind: 'user' })
  715. send(agent, 'B')
  716. })
  717. send(agent, 'A')
  718. const idle = agent.whenIdle()
  719. await idle
  720. dispose()
  721. // B's wake was latched behind the cancelled driver: it runs on its own.
  722. expect(userTexts(agent)).toEqual(['B'])
  723. expect(agent.inbox.nextTurn).toHaveLength(0)
  724. expect(adapter.requests).toHaveLength(1)
  725. const replacementIdle = waitForIdle(ctx, agent)
  726. send(agent, 'C')
  727. await replacementIdle
  728. expect(userTexts(agent)).toEqual(['B', 'C'])
  729. expect(adapter.requests).toHaveLength(2)
  730. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/end')).toHaveLength(2)
  731. })
  732. it('a prompt queued during pre-step cancellation replays at convergence', async () => {
  733. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  734. const ctx = await harness(adapter)
  735. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  736. send(agent, 'A')
  737. const idle = agent.whenIdle()
  738. agent.cancel({ kind: 'user' })
  739. send(agent, 'B')
  740. await idle
  741. expect(userTexts(agent)).toEqual(['B'])
  742. expect(agent.inbox.nextTurn).toHaveLength(0)
  743. expect(adapter.requests).toHaveLength(1)
  744. const replacementIdle = waitForIdle(ctx, agent)
  745. send(agent, 'C')
  746. await replacementIdle
  747. expect(userTexts(agent)).toEqual(['B', 'C'])
  748. expect(adapter.requests).toHaveLength(2)
  749. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/end')).toHaveLength(3)
  750. })
  751. it("cancel clears the turn's steering — it is not re-enqueued as a fresh turn", async () => {
  752. const adapter = new MockAdapter(['hang'])
  753. const ctx = await harness(adapter)
  754. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  755. send(agent, 'go')
  756. await new Promise(r => setTimeout(r, 30))
  757. expect(agent.status).toBe('running')
  758. // Steer (joins the running turn's steering FIFO), then cancel: the steering
  759. // must be dropped, NOT re-enqueued as a new queued turn.
  760. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'steer text' }], source: { kind: 'user' } }))
  761. agent.cancel({ kind: 'user' })
  762. await waitForIdle(ctx, agent)
  763. // After the cancelled turn settles, the agent is idle with NO follow-up turn
  764. // started from the dropped steering.
  765. await new Promise(r => setTimeout(r, 30))
  766. expect(agent.status).toBe('idle')
  767. const turnStarts = agent.session.snapshotEvents().filter(e => e.type === 'turn/start')
  768. expect(turnStarts.length).toBe(1) // only the original (cancelled) turn
  769. // The steering text was dropped — it never reached the log.
  770. const flat = agent.session.snapshotEvents()
  771. .filter(e => e.type === 'user/message')
  772. .flatMap(e => e.data.content)
  773. .flatMap(b => b.type === 'text' ? [b.text] : [])
  774. expect(flat).not.toContain('steer text')
  775. })
  776. it('replays replacement work queued synchronously by an abort observer', async () => {
  777. const adapter = new MockAdapter([
  778. 'hang',
  779. textResponse('replacement reply'),
  780. textResponse('wake reply'),
  781. ])
  782. const ctx = await harness(adapter)
  783. const agent = await ctx.agentLoop.create(SessionId('abort-observer-replacement'), { provider: 'mock', model: 'mock' })
  784. send(agent, 'original')
  785. await expect.poll(() => adapter.requests.length).toBe(1)
  786. const signal = adapter.requests[0]?.signal
  787. if (signal === undefined) throw new Error('model request omitted its turn signal')
  788. signal.addEventListener('abort', () => { send(agent, 'replacement') }, { once: true })
  789. const idle = agent.whenIdle()
  790. agent.cancel({ kind: 'user' })
  791. await Promise.race([
  792. idle,
  793. new Promise((_resolve, reject) => {
  794. setTimeout(() => {
  795. reject(new Error(`replacement did not settle: ${JSON.stringify({
  796. status: agent.status,
  797. requests: adapter.requests.length,
  798. users: userTexts(agent),
  799. events: agent.session.snapshotEvents().map(event => event.type),
  800. })}`))
  801. }, 1000)
  802. }),
  803. ])
  804. // The abort-observer wake was latched: replacement runs at convergence,
  805. // so the original turn is followed by a completed replacement turn.
  806. expect(adapter.requests).toHaveLength(2)
  807. expect(userTexts(agent)).toEqual(['original', 'replacement'])
  808. expect(agent.inbox.nextTurn).toHaveLength(0)
  809. const reasons = agent.session.snapshotEvents()
  810. .filter(event => event.type === 'turn/end')
  811. .map(event => event.type === 'turn/end' ? event.data.reason : undefined)
  812. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }, { kind: 'completed' }])
  813. const replacementIdle = waitForIdle(ctx, agent)
  814. send(agent, 'wake it')
  815. await replacementIdle
  816. expect(adapter.requests).toHaveLength(3)
  817. expect(userTexts(agent)).toEqual(['original', 'replacement', 'wake it'])
  818. })
  819. it('keeps the first typed cause for an active turn', async () => {
  820. const adapter = new MockAdapter(['hang'])
  821. const ctx = await harness(adapter)
  822. const agent = await ctx.agentLoop.create(SessionId('typed-first-wins'), { provider: 'mock', model: 'mock' })
  823. const supplied: { kind: 'parent' | 'user' } = { kind: 'parent' }
  824. send(agent, 'go')
  825. await expect.poll(() => adapter.requests.length).toBe(1)
  826. agent.cancel(supplied)
  827. agent.cancel({ kind: 'user' })
  828. await waitForIdle(ctx, agent)
  829. const runtimeReason: unknown = adapter.requests[0]?.signal?.reason
  830. expect(runtimeReason).toEqual({ kind: 'parent' })
  831. expect(runtimeReason).toBe(supplied)
  832. const turnEnd = agent.session.snapshotEvents().findLast(event => event.type === 'turn/end')
  833. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({
  834. kind: 'aborted',
  835. reason: { kind: 'parent' },
  836. })
  837. })
  838. it('preserves the first user cancellation when lifecycle teardown races it', async () => {
  839. const adapter = new MockAdapter(['hang'])
  840. const ctx = await harness(adapter)
  841. const handle = await ctx.agents.create({
  842. sessionId: SessionId('cancel-dispose-race'),
  843. agentOptions: { provider: 'mock', model: 'mock' },
  844. })
  845. const { agent } = handle
  846. send(agent, 'go')
  847. await expect.poll(() => adapter.requests.length).toBe(1)
  848. agent.cancel({ kind: 'user' })
  849. await handle.dispose()
  850. const turnEnd = agent.session.snapshotEvents().findLast(event => event.type === 'turn/end')
  851. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted', reason: { kind: 'user' } })
  852. })
  853. it.each([
  854. 'pre-step',
  855. 'system-prompt',
  856. 'request',
  857. 'stopping',
  858. 'tool',
  859. ] as const)('lets a cooperative %s boundary settle from the explicit turn signal', async (stage) => {
  860. const adapter = new MockAdapter(stage === 'tool'
  861. ? [toolCallResponse('blocked-tool', 'blocked', {})]
  862. : [textResponse('done')])
  863. const ctx = await harness(adapter)
  864. const agent = await ctx.agentLoop.create(SessionId(`cooperative-${stage}`), { provider: 'mock', model: 'mock' })
  865. const started = Promise.withResolvers<undefined>()
  866. const blockUntilAbort = async (signal: AbortSignal): Promise<void> => {
  867. started.resolve(undefined)
  868. if (signal.aborted) return
  869. await new Promise<void>((resolve) => {
  870. signal.addEventListener('abort', () => { resolve() }, { once: true })
  871. })
  872. }
  873. switch (stage) {
  874. case 'pre-step':
  875. ctx.on('agent/pre-step', async ({ agent: subject, signal }, next) => {
  876. if (subject === agent) await blockUntilAbort(signal)
  877. return next()
  878. })
  879. break
  880. case 'system-prompt':
  881. ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
  882. if (context.agent === agent) {
  883. if (context.signal === undefined) throw new Error('turn assembly omitted its signal')
  884. await blockUntilAbort(context.signal)
  885. }
  886. return next()
  887. })
  888. break
  889. case 'request':
  890. ctx.on('agent/request', async ({ agent: subject, signal }, next) => {
  891. if (subject === agent) await blockUntilAbort(signal)
  892. return next()
  893. })
  894. break
  895. case 'stopping':
  896. ctx.on('agent/turn-stopping', async ({ agent: subject, signal }) => {
  897. if (subject === agent) await blockUntilAbort(signal)
  898. })
  899. break
  900. case 'tool':
  901. ctx.tools.register(defineContentToolFixture({
  902. name: 'blocked',
  903. description: 'wait for cancellation',
  904. parameters: {},
  905. execute: async (_args, exec) => {
  906. if (exec.signal === undefined) throw new Error('tool execution omitted its signal')
  907. await blockUntilAbort(exec.signal)
  908. return [{ type: 'text', text: 'cancelled' }]
  909. },
  910. }))
  911. break
  912. }
  913. send(agent, 'go')
  914. await started.promise
  915. const idle = agent.whenIdle()
  916. agent.cancel({ kind: 'user' })
  917. await idle
  918. const turnEnd = agent.session.snapshotEvents().findLast(event => event.type === 'turn/end')
  919. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason)
  920. .toEqual({ kind: 'aborted', reason: { kind: 'user' } })
  921. await ctx.fiber.dispose()
  922. })
  923. })