cancel.spec.ts 42 KB

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