cancel.spec.ts 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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. )).not.toThrow()
  470. })
  471. it('cancel during reasoning-only streaming finalizes the reasoning prefix', async () => {
  472. const adapter = new MockAdapter([{
  473. hangAfter: [
  474. { type: 'block-start', index: 0, blockType: 'reasoning' },
  475. { type: 'reasoning-delta', index: 0, text: 'thinking about it' },
  476. { type: 'usage', usage: { inputTokens: 7, outputTokens: 4 } },
  477. ],
  478. }])
  479. const ctx = await harness(adapter)
  480. const agent = await ctx.agentLoop.create(SessionId('reasoning-finalize'), { provider: 'mock', model: 'mock' })
  481. send(agent, 'go')
  482. await new Promise(r => setTimeout(r, 30))
  483. agent.cancel({ kind: 'user' })
  484. await waitForIdle(ctx, agent)
  485. const message = agent.session.snapshotEvents().find(e => e.type === 'assistant/message')
  486. expect(message?.type === 'assistant/message' ? message.data.message.content : undefined)
  487. .toEqual([{ type: 'reasoning', text: 'thinking about it' }])
  488. // A usage chunk delivered before the cancel travels with the finalized prefix.
  489. expect(message?.type === 'assistant/message' ? message.data.usage : undefined)
  490. .toEqual({ inputTokens: 7, outputTokens: 4 })
  491. })
  492. it('cancel drops a half-streamed tool call and keeps the completed text before it', async () => {
  493. const adapter = new MockAdapter([{
  494. hangAfter: [
  495. { type: 'block-start', index: 0, blockType: 'text' },
  496. { type: 'text-delta', index: 0, text: 'reading the file' },
  497. { type: 'block-end', index: 0, block: { type: 'text', text: 'reading the file' } },
  498. { type: 'block-start', index: 1, blockType: 'tool-call' },
  499. { type: 'tool-call-delta', index: 1, id: ToolCallId('c1'), name: 'read', argumentsDelta: '{"pa' },
  500. ],
  501. }])
  502. const ctx = await harness(adapter)
  503. const agent = await ctx.agentLoop.create(SessionId('tool-call-drop'), { provider: 'mock', model: 'mock' })
  504. send(agent, 'go')
  505. await new Promise(r => setTimeout(r, 30))
  506. agent.cancel({ kind: 'user' })
  507. await waitForIdle(ctx, agent)
  508. // The undispatched call is dropped whole — no dangling tool_use to pair.
  509. const message = agent.session.snapshotEvents().find(e => e.type === 'assistant/message')
  510. expect(message?.type === 'assistant/message' ? message.data.message.content : undefined)
  511. .toEqual([{ type: 'text', text: 'reading the file' }])
  512. expect(agent.session.snapshotEvents().some(e => e.type === 'tool/call')).toBe(false)
  513. })
  514. it('cancel during error recovery does not finalize the failed stream', async () => {
  515. const adapter = new MockAdapter([[
  516. { type: 'block-start', index: 0, blockType: 'text' },
  517. { type: 'text-delta', index: 0, text: 'doomed partial' },
  518. { type: 'finish', reason: { kind: 'error', failure: { message: 'boom', code: 'SERVER_ERROR' } } },
  519. ]])
  520. const ctx = await harness(adapter)
  521. const agent = await ctx.agentLoop.create(SessionId('recovery-cancel'), { provider: 'mock', model: 'mock' })
  522. // Cancellation lands while agent/request-error is in flight — the window
  523. // dsh-llm-retry opens when its backoff waits after appending llm/retry.
  524. ctx.on('agent/request-error', async ({ agent: subject }) => {
  525. if (subject === agent) subject.cancel({ kind: 'user' })
  526. })
  527. send(agent, 'go')
  528. await waitForIdle(ctx, agent)
  529. // The failed stream's prefix stays off the surface: clients reset it on
  530. // retry, and provider failures commit nothing.
  531. expect(agent.session.snapshotEvents().some(e => e.type === 'assistant/message')).toBe(false)
  532. const end = agent.session.snapshotEvents().find(e => e.type === 'turn/end')
  533. expect(end?.type === 'turn/end' ? end.data.reason.kind : undefined).toBe('aborted')
  534. })
  535. it('retry retains the failed attempt while the final message embeds only its own stream', async () => {
  536. const adapter = new MockAdapter([
  537. [
  538. { type: 'block-start', index: 0, blockType: 'text' },
  539. { type: 'text-delta', index: 0, text: 'doomed partial' },
  540. { type: 'finish', reason: { kind: 'error', failure: { message: 'boom', code: 'SERVER_ERROR' } } },
  541. ],
  542. textResponse('recovered'),
  543. ])
  544. const ctx = await harness(adapter)
  545. const agent = await ctx.agentLoop.create(SessionId('retry-discards-content'), { provider: 'mock', model: 'mock' })
  546. ctx.on('agent/request-error', async () => ({ kind: 'retry' as const }))
  547. send(agent, 'go')
  548. await waitForIdle(ctx, agent)
  549. const messages = agent.session.snapshotEvents().filter(e => e.type === 'assistant/message')
  550. expect(messages).toHaveLength(1)
  551. const message = messages[0]!
  552. expect(message.type === 'assistant/message' ? message.data.message.content : undefined)
  553. .toEqual([{ type: 'text', text: 'recovered' }])
  554. expect(message.type === 'assistant/message' ? message.data.interrupted : undefined).toBeUndefined()
  555. const failed = agent.session.snapshotEvents().find(e => e.type === 'assistant/attempt')
  556. expect(failed?.type === 'assistant/attempt'
  557. ? expandAssistantStream(failed.data.stream).some(member => (
  558. member.chunk.type === 'text-delta' && member.chunk.text === 'doomed partial'
  559. ))
  560. : false).toBe(true)
  561. expect(message.type === 'assistant/message'
  562. ? expandAssistantStream(message.data.stream).some(member => (
  563. member.chunk.type === 'text-delta' && member.chunk.text === 'doomed partial'
  564. ))
  565. : true).toBe(false)
  566. })
  567. it('retains a partial attempt when stream middleware rejects without cancellation', async () => {
  568. const failure = new Error('provider transport failed')
  569. const adapter = new MockAdapter([[
  570. { type: 'block-start', index: 0, blockType: 'text' },
  571. { type: 'text-delta', index: 0, text: 'partial before failure' },
  572. ]])
  573. const ctx = await harness(adapter)
  574. const agent = await ctx.agentLoop.create(SessionId('provider-stream-rejection'), { provider: 'mock', model: 'mock' })
  575. ctx.on('llm/stream', async function* (_options, next) {
  576. for await (const chunk of next()) {
  577. yield chunk
  578. if (chunk.type === 'text-delta') throw failure
  579. }
  580. })
  581. send(agent, 'go')
  582. await waitForIdle(ctx, agent)
  583. const attempt = agent.session.snapshotEvents().find(event => event.type === 'assistant/attempt')
  584. expect(attempt?.type === 'assistant/attempt'
  585. ? expandAssistantStream(attempt.data.stream).map(member => member.chunk)
  586. : []).toContainEqual({ type: 'text-delta', index: 0, text: 'partial before failure' })
  587. expect(agent.session.snapshotEvents().find(event => event.type === 'turn/end')).toMatchObject({
  588. type: 'turn/end', data: { reason: { kind: 'error', error: { message: failure.message } } },
  589. })
  590. })
  591. it('cancel before any visible content finalizes nothing', async () => {
  592. const adapter = new MockAdapter([{
  593. hangAfter: [
  594. { type: 'block-start', index: 0, blockType: 'tool-call' },
  595. { type: 'tool-call-delta', index: 0, id: ToolCallId('c1'), name: 'read', argumentsDelta: '{"pa' },
  596. ],
  597. }])
  598. const ctx = await harness(adapter)
  599. const agent = await ctx.agentLoop.create(SessionId('nothing-to-finalize'), { provider: 'mock', model: 'mock' })
  600. send(agent, 'go')
  601. await new Promise(r => setTimeout(r, 30))
  602. agent.cancel({ kind: 'user' })
  603. await waitForIdle(ctx, agent)
  604. expect(agent.session.snapshotEvents().some(e => e.type === 'assistant/message')).toBe(false)
  605. })
  606. it('cancel from a synchronous step/start session-event listener drops the step (post-step-start window)', async () => {
  607. const adapter = new MockAdapter([textResponse('should not stream')])
  608. const ctx = await harness(adapter)
  609. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  610. // A step/start session-event listener fires AFTER step/start is appended
  611. // (and after the pre-step extension point), so cancelling there lands in the SECOND
  612. // cancel check (the one that must closeStep() to balance the already-open
  613. // step) — distinct from a turn-start cancel, caught before the step opens.
  614. let streamed = false
  615. ctx.on('agent/assistant-stream', ({ frame }) => { if (frame.type === 'chunk') streamed = true })
  616. const dispose = ctx.on('session/event', (session, event) => {
  617. if (session === agent.session && event.type === 'step/start') agent.cancel({ kind: 'user' })
  618. })
  619. const reasons: TurnEndReason[] = []
  620. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  621. send(agent, 'go')
  622. await waitForIdle(ctx, agent)
  623. dispose()
  624. // No step streamed, the turn ended with the coarse aborted outcome, and the
  625. // log is balanced (the open step was closed by the cancel branch).
  626. expect(streamed).toBe(false)
  627. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  628. const types = agent.session.snapshotEvents().map(e => e.type)
  629. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  630. })
  631. it('disposal from a synchronous step/start session-event listener stops before adapter dispatch', async () => {
  632. const adapter = new MockAdapter([textResponse('should not stream')])
  633. const ctx = new Context()
  634. await ctx.plugin(LlmRuntime)
  635. await ctx.plugin(SessionStore)
  636. await ctx.plugin(SessionProjectionRegistry)
  637. await ctx.plugin(SystemPrompt)
  638. await ctx.plugin(ToolRuntime)
  639. await ctx.plugin(AgentRegistry)
  640. await ctx.plugin(AgentLoop, { agents: [] })
  641. ctx.llm.registerAdapter(['mock'], adapter)
  642. const handle = await ctx.agents.create({
  643. sessionId: SessionId('dispose-step-start-session'),
  644. agentOptions: { provider: 'mock', model: 'mock' },
  645. })
  646. const agent = handle.agent
  647. let disposalDone: Promise<void> | undefined
  648. let streamed = false
  649. ctx.on('agent/assistant-stream', ({ frame }) => { if (frame.type === 'chunk') streamed = true })
  650. ctx.on('session/event', (session, event) => {
  651. if (session === agent.session && event.type === 'step/start') disposalDone = handle.dispose()
  652. })
  653. send(agent, 'go')
  654. await disposalDone
  655. await driverDone(agent)
  656. expect(streamed).toBe(false)
  657. expect(adapter.requests).toHaveLength(0)
  658. expect(agent.session.snapshotEvents().some(e => e.type === 'turn/end')).toBe(false)
  659. const types = agent.session.snapshotEvents().map(e => e.type)
  660. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  661. })
  662. it('cancel during the stopping window ends the turn aborted and runs no further step', async () => {
  663. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  664. const ctx = await harness(adapter)
  665. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  666. let steps = 0
  667. const reasons: TurnEndReason[] = []
  668. ctx.on('session/event', (_session, event) => {
  669. if (event.type === 'step/start') steps += 1
  670. if (event.type === 'turn/end') reasons.push(event.data.reason)
  671. })
  672. let cancelled = false
  673. ctx.on('agent/turn-stopping', ({ agent: subject }) => {
  674. if (subject === agent && !cancelled) {
  675. cancelled = true
  676. agent.cancel({ kind: 'user' })
  677. }
  678. })
  679. send(agent, 'go')
  680. await waitForIdle(ctx, agent)
  681. // Only ONE step ran (the second was cancelled in the stopping window),
  682. // and the shared turn signal classified the durable outcome as aborted.
  683. expect(steps).toBe(1)
  684. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }])
  685. })
  686. it('cancel from a synchronous agent/status(running) listener drops the turn (window 2)', async () => {
  687. const adapter = new MockAdapter([textResponse('should not run')])
  688. const ctx = await harness(adapter)
  689. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  690. // `agent/status` is synchronous, so cancellation can land before the
  691. // durable turn-start commit and must drop the reserved work.
  692. let streamed = false
  693. ctx.on('agent/assistant-stream', ({ frame }) => { if (frame.type === 'chunk') streamed = true })
  694. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  695. if (subject === agent && status === 'running') agent.cancel({ kind: 'user' })
  696. })
  697. send(agent, 'go')
  698. await waitForIdle(ctx, agent)
  699. dispose()
  700. // No turn opened, no step streamed, and a later prompt still runs (the marker
  701. // was reset).
  702. expect(streamed).toBe(false)
  703. expect(agent.session.snapshotEvents().some(e => e.type === 'turn/start')).toBe(false)
  704. })
  705. it('a running-listener cancellation replays replacement work at convergence', async () => {
  706. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  707. const ctx = await harness(adapter)
  708. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  709. let replaced = false
  710. const dispose = ctx.on('agent/status', ({ agent: subject, status }) => {
  711. if (subject !== agent || status !== 'running' || replaced) return
  712. replaced = true
  713. agent.cancel({ kind: 'user' })
  714. send(agent, 'B')
  715. })
  716. send(agent, 'A')
  717. const idle = agent.whenIdle()
  718. await idle
  719. dispose()
  720. // B's wake was latched behind the cancelled driver: it runs on its own.
  721. expect(userTexts(agent)).toEqual(['B'])
  722. expect(agent.inbox.nextTurn).toHaveLength(0)
  723. expect(adapter.requests).toHaveLength(1)
  724. const replacementIdle = waitForIdle(ctx, agent)
  725. send(agent, 'C')
  726. await replacementIdle
  727. expect(userTexts(agent)).toEqual(['B', 'C'])
  728. expect(adapter.requests).toHaveLength(2)
  729. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/end')).toHaveLength(2)
  730. })
  731. it('a prompt queued during pre-step cancellation replays at convergence', async () => {
  732. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  733. const ctx = await harness(adapter)
  734. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  735. send(agent, 'A')
  736. const idle = agent.whenIdle()
  737. agent.cancel({ kind: 'user' })
  738. send(agent, 'B')
  739. await idle
  740. expect(userTexts(agent)).toEqual(['B'])
  741. expect(agent.inbox.nextTurn).toHaveLength(0)
  742. expect(adapter.requests).toHaveLength(1)
  743. const replacementIdle = waitForIdle(ctx, agent)
  744. send(agent, 'C')
  745. await replacementIdle
  746. expect(userTexts(agent)).toEqual(['B', 'C'])
  747. expect(adapter.requests).toHaveLength(2)
  748. expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/end')).toHaveLength(3)
  749. })
  750. it("cancel clears the turn's steering — it is not re-enqueued as a fresh turn", async () => {
  751. const adapter = new MockAdapter(['hang'])
  752. const ctx = await harness(adapter)
  753. const agent = await ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  754. send(agent, 'go')
  755. await new Promise(r => setTimeout(r, 30))
  756. expect(agent.status).toBe('running')
  757. // Steer (joins the running turn's steering FIFO), then cancel: the steering
  758. // must be dropped, NOT re-enqueued as a new queued turn.
  759. agent.steer(createUserMessage({ content: [{ type: 'text', text: 'steer text' }], source: { kind: 'user' } }))
  760. agent.cancel({ kind: 'user' })
  761. await waitForIdle(ctx, agent)
  762. // After the cancelled turn settles, the agent is idle with NO follow-up turn
  763. // started from the dropped steering.
  764. await new Promise(r => setTimeout(r, 30))
  765. expect(agent.status).toBe('idle')
  766. const turnStarts = agent.session.snapshotEvents().filter(e => e.type === 'turn/start')
  767. expect(turnStarts.length).toBe(1) // only the original (cancelled) turn
  768. // The steering text was dropped — it never reached the log.
  769. const flat = agent.session.snapshotEvents()
  770. .filter(e => e.type === 'user/message')
  771. .flatMap(e => e.data.content)
  772. .flatMap(b => b.type === 'text' ? [b.text] : [])
  773. expect(flat).not.toContain('steer text')
  774. })
  775. it('replays replacement work queued synchronously by an abort observer', async () => {
  776. const adapter = new MockAdapter([
  777. 'hang',
  778. textResponse('replacement reply'),
  779. textResponse('wake reply'),
  780. ])
  781. const ctx = await harness(adapter)
  782. const agent = await ctx.agentLoop.create(SessionId('abort-observer-replacement'), { provider: 'mock', model: 'mock' })
  783. send(agent, 'original')
  784. await expect.poll(() => adapter.requests.length).toBe(1)
  785. const signal = adapter.requests[0]?.signal
  786. if (signal === undefined) throw new Error('model request omitted its turn signal')
  787. signal.addEventListener('abort', () => { send(agent, 'replacement') }, { once: true })
  788. const idle = agent.whenIdle()
  789. agent.cancel({ kind: 'user' })
  790. await Promise.race([
  791. idle,
  792. new Promise((_resolve, reject) => {
  793. setTimeout(() => {
  794. reject(new Error(`replacement did not settle: ${JSON.stringify({
  795. status: agent.status,
  796. requests: adapter.requests.length,
  797. users: userTexts(agent),
  798. events: agent.session.snapshotEvents().map(event => event.type),
  799. })}`))
  800. }, 1000)
  801. }),
  802. ])
  803. // The abort-observer wake was latched: replacement runs at convergence,
  804. // so the original turn is followed by a completed replacement turn.
  805. expect(adapter.requests).toHaveLength(2)
  806. expect(userTexts(agent)).toEqual(['original', 'replacement'])
  807. expect(agent.inbox.nextTurn).toHaveLength(0)
  808. const reasons = agent.session.snapshotEvents()
  809. .filter(event => event.type === 'turn/end')
  810. .map(event => event.type === 'turn/end' ? event.data.reason : undefined)
  811. expect(reasons).toEqual([{ kind: 'aborted', reason: { kind: 'user' } }, { kind: 'completed' }])
  812. const replacementIdle = waitForIdle(ctx, agent)
  813. send(agent, 'wake it')
  814. await replacementIdle
  815. expect(adapter.requests).toHaveLength(3)
  816. expect(userTexts(agent)).toEqual(['original', 'replacement', 'wake it'])
  817. })
  818. it('keeps the first typed cause for an active turn', async () => {
  819. const adapter = new MockAdapter(['hang'])
  820. const ctx = await harness(adapter)
  821. const agent = await ctx.agentLoop.create(SessionId('typed-first-wins'), { provider: 'mock', model: 'mock' })
  822. const supplied: { kind: 'parent' | 'user' } = { kind: 'parent' }
  823. send(agent, 'go')
  824. await expect.poll(() => adapter.requests.length).toBe(1)
  825. agent.cancel(supplied)
  826. agent.cancel({ kind: 'user' })
  827. await waitForIdle(ctx, agent)
  828. const runtimeReason: unknown = adapter.requests[0]?.signal?.reason
  829. expect(runtimeReason).toEqual({ kind: 'parent' })
  830. expect(runtimeReason).toBe(supplied)
  831. const turnEnd = agent.session.snapshotEvents().findLast(event => event.type === 'turn/end')
  832. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({
  833. kind: 'aborted',
  834. reason: { kind: 'parent' },
  835. })
  836. })
  837. it('preserves the first user cancellation when lifecycle teardown races it', async () => {
  838. const adapter = new MockAdapter(['hang'])
  839. const ctx = await harness(adapter)
  840. const handle = await ctx.agents.create({
  841. sessionId: SessionId('cancel-dispose-race'),
  842. agentOptions: { provider: 'mock', model: 'mock' },
  843. })
  844. const { agent } = handle
  845. send(agent, 'go')
  846. await expect.poll(() => adapter.requests.length).toBe(1)
  847. agent.cancel({ kind: 'user' })
  848. await handle.dispose()
  849. const turnEnd = agent.session.snapshotEvents().findLast(event => event.type === 'turn/end')
  850. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'aborted', reason: { kind: 'user' } })
  851. })
  852. it.each([
  853. 'pre-step',
  854. 'system-prompt',
  855. 'request',
  856. 'stopping',
  857. 'tool',
  858. ] as const)('lets a cooperative %s boundary settle from the explicit turn signal', async (stage) => {
  859. const adapter = new MockAdapter(stage === 'tool'
  860. ? [toolCallResponse('blocked-tool', 'blocked', {})]
  861. : [textResponse('done')])
  862. const ctx = await harness(adapter)
  863. const agent = await ctx.agentLoop.create(SessionId(`cooperative-${stage}`), { provider: 'mock', model: 'mock' })
  864. const started = Promise.withResolvers<undefined>()
  865. const blockUntilAbort = async (signal: AbortSignal): Promise<void> => {
  866. started.resolve(undefined)
  867. if (signal.aborted) return
  868. await new Promise<void>((resolve) => {
  869. signal.addEventListener('abort', () => { resolve() }, { once: true })
  870. })
  871. }
  872. switch (stage) {
  873. case 'pre-step':
  874. ctx.on('agent/pre-step', async ({ agent: subject, signal }, next) => {
  875. if (subject === agent) await blockUntilAbort(signal)
  876. return next()
  877. })
  878. break
  879. case 'system-prompt':
  880. ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
  881. if (context.agent === agent) {
  882. if (context.signal === undefined) throw new Error('turn assembly omitted its signal')
  883. await blockUntilAbort(context.signal)
  884. }
  885. return next()
  886. })
  887. break
  888. case 'request':
  889. ctx.on('agent/request', async ({ agent: subject, signal }, next) => {
  890. if (subject === agent) await blockUntilAbort(signal)
  891. return next()
  892. })
  893. break
  894. case 'stopping':
  895. ctx.on('agent/turn-stopping', async ({ agent: subject, signal }) => {
  896. if (subject === agent) await blockUntilAbort(signal)
  897. })
  898. break
  899. case 'tool':
  900. ctx.tools.register(defineContentToolFixture({
  901. name: 'blocked',
  902. description: 'wait for cancellation',
  903. parameters: {},
  904. execute: async (_args, exec) => {
  905. if (exec.signal === undefined) throw new Error('tool execution omitted its signal')
  906. await blockUntilAbort(exec.signal)
  907. return [{ type: 'text', text: 'cancelled' }]
  908. },
  909. }))
  910. break
  911. }
  912. send(agent, 'go')
  913. await started.promise
  914. const idle = agent.whenIdle()
  915. agent.cancel({ kind: 'user' })
  916. await idle
  917. const turnEnd = agent.session.snapshotEvents().findLast(event => event.type === 'turn/end')
  918. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason)
  919. .toEqual({ kind: 'aborted', reason: { kind: 'user' } })
  920. await ctx.fiber.dispose()
  921. })
  922. })