cancel.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /**
  2. * Tests for the queue-aware `Agent.cancel()` primitive. `cancel()` is the broad verb — it
  3. * clears queued + steering work, aborts an in-flight step, and drops a turn about to start —
  4. * whereas a bare step abort (the loop's private `AbortController`) kills only the current step
  5. * and leaves the queue intact. The suite covers every landing window plus marker
  6. * reset and `whenIdle()` quiescence.
  7. * @module dsh-agent-loop/tests/cancel
  8. */
  9. import { describe, expect, it } from 'vitest'
  10. import { Context } from 'cordis'
  11. import LlmService, { type Message } from '@deepseek-ai/dsh-llm'
  12. import SessionStore, { SessionId, TurnEndReason } from '@deepseek-ai/dsh-session'
  13. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  14. import ToolRegistry 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 } from './mock-adapter.ts'
  18. function driverDone(agent: Agent): Promise<void> {
  19. return (agent as Agent & { done: Promise<void> }).done
  20. }
  21. async function harness(adapter: MockAdapter) {
  22. const ctx = new Context()
  23. await ctx.plugin(LlmService)
  24. await ctx.plugin(SessionStore)
  25. await ctx.plugin(SystemPrompt)
  26. await ctx.plugin(ToolRegistry)
  27. await ctx.plugin(AgentRegistry)
  28. await ctx.plugin(AgentLoop, { agents: [] })
  29. ctx.llm.registerAdapter(['mock'], adapter)
  30. return ctx
  31. }
  32. function send(agent: Agent, text: string) {
  33. agent.send([{ type: 'text', text }])
  34. }
  35. /** Resolve on the agent's next idle transition (event-based, not status poll). */
  36. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  37. return new Promise((resolve) => {
  38. const dispose = ctx.on('agent/status', (subject, status) => {
  39. if (subject === agent && status === 'idle') { dispose(); resolve() }
  40. })
  41. })
  42. }
  43. /** All user-message texts recorded in the log (to assert what actually ran). */
  44. function userTexts(agent: Agent): string[] {
  45. return agent.session.events
  46. .filter(e => e.type === 'user/message')
  47. .flatMap(e => e.type === 'user/message' ? e.data.content : [])
  48. .flatMap(b => b.type === 'text' ? [b.text] : [])
  49. }
  50. describe('Agent.cancel()', () => {
  51. it('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('nothing to cancel')
  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('pre-step cancel drops the about-to-start turn (no turn is opened)', async () => {
  65. const adapter = new MockAdapter([textResponse('should not run')])
  66. const ctx = await harness(adapter)
  67. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  68. // send() queues synchronously (status still idle, loop microtask not yet
  69. // resumed). Cancel in that pre-step window: the queued turn must not run.
  70. send(agent, 'drop me')
  71. agent.cancel('pre-step')
  72. // Give the loop a chance to wake and process the cancel.
  73. await new Promise(r => setTimeout(r, 30))
  74. // No turn was opened — the queued prompt was dropped, never recorded.
  75. expect(userTexts(agent)).toEqual([])
  76. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(false)
  77. expect(agent.status).toBe('idle')
  78. })
  79. it('a whenIdle() waiter registered BEFORE a pre-step cancel resolves (F1 hang guard)', async () => {
  80. const adapter = new MockAdapter([textResponse('x')])
  81. const ctx = await harness(adapter)
  82. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  83. // This waiter cannot rely on a running→idle transition because cancellation
  84. // drops the turn before it runs; the skip path must settle it directly.
  85. send(agent, 'q')
  86. const idle = agent.whenIdle()
  87. agent.cancel('pre-step')
  88. // Must resolve (not hang). A timeout makes the failure a clear test failure.
  89. await Promise.race([
  90. idle,
  91. new Promise((_r, reject) => setTimeout(() => { reject(new Error('whenIdle hung after pre-step cancel')) }, 1000)),
  92. ])
  93. expect(agent.status).toBe('idle')
  94. })
  95. it('cancel() mid-step aborts the in-flight model call; the turn ends aborted', async () => {
  96. const adapter = new MockAdapter(['hang'])
  97. const ctx = await harness(adapter)
  98. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  99. const reasons: TurnEndReason[] = []
  100. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  101. send(agent, 'go')
  102. await new Promise(r => setTimeout(r, 30))
  103. expect(agent.status).toBe('running')
  104. agent.cancel('mid-step')
  105. await waitForIdle(ctx, agent)
  106. expect(reasons).toEqual([{ kind: 'aborted', reason: 'mid-step' }])
  107. })
  108. it('cancel() with no reason defaults to "cancelled" when aborting an in-flight step', async () => {
  109. const adapter = new MockAdapter(['hang'])
  110. const ctx = await harness(adapter)
  111. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  112. const reasons: TurnEndReason[] = []
  113. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  114. send(agent, 'go')
  115. await new Promise(r => setTimeout(r, 30))
  116. agent.cancel() // no reason → default 'cancelled'
  117. await waitForIdle(ctx, agent)
  118. expect(reasons).toEqual([{ kind: 'aborted', reason: 'cancelled' }])
  119. })
  120. it('a prompt sent AFTER a cancelled turn settles runs normally (marker reset)', async () => {
  121. const adapter = new MockAdapter(['hang', textResponse('second reply')])
  122. const ctx = await harness(adapter)
  123. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  124. // First turn hangs; cancel it mid-step.
  125. send(agent, 'first')
  126. await new Promise(r => setTimeout(r, 30))
  127. agent.cancel('cancel first')
  128. await waitForIdle(ctx, agent)
  129. // The marker must have been reset after the cancelled turn — a fresh prompt
  130. // runs to completion rather than being dropped by a stale marker.
  131. send(agent, 'second')
  132. await waitForIdle(ctx, agent)
  133. expect(userTexts(agent)).toContain('second')
  134. // The second turn completed (its reply was streamed).
  135. const reasons = agent.session.events.filter(e => e.type === 'turn/end')
  136. expect(reasons.length).toBe(2)
  137. })
  138. it('cancel from inside the agent/session-prefix waterfall drops the step (prefix-composition window)', async () => {
  139. const adapter = new MockAdapter([textResponse('should not stream')])
  140. const ctx = await harness(adapter)
  141. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  142. // Prefix composition runs before the pre-step seam on the instance's first
  143. // step; a cancel landing inside it must drop the about-to-start step
  144. // without running the seam or the model.
  145. let streamed = false
  146. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  147. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next) => {
  148. agent.cancel('from prefix composition')
  149. return next()
  150. })
  151. const reasons: TurnEndReason[] = []
  152. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  153. send(agent, 'go')
  154. await waitForIdle(ctx, agent)
  155. expect(streamed).toBe(false)
  156. expect(reasons).toEqual([{ kind: 'aborted', reason: 'from prefix composition' }])
  157. })
  158. it('disposal from inside the agent/session-prefix waterfall ends the turn disposed (prefix-composition window)', async () => {
  159. const adapter = new MockAdapter([textResponse('should not stream')])
  160. const ctx = new Context()
  161. await ctx.plugin(LlmService)
  162. await ctx.plugin(SessionStore)
  163. await ctx.plugin(SystemPrompt)
  164. await ctx.plugin(ToolRegistry)
  165. await ctx.plugin(AgentRegistry)
  166. await ctx.plugin(AgentLoop, { agents: [] })
  167. ctx.llm.registerAdapter(['mock'], adapter)
  168. const handle = await ctx.agents.create({
  169. sessionId: SessionId('dispose-prefix-session'),
  170. agentOptions: { provider: 'mock', model: 'mock' },
  171. })
  172. const agent = handle.agent
  173. let disposalDone: Promise<void> | undefined
  174. let streamed = false
  175. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  176. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next) => {
  177. disposalDone = handle.dispose()
  178. return next()
  179. })
  180. send(agent, 'go')
  181. await new Promise(resolve => setTimeout(resolve, 0))
  182. await disposalDone
  183. await driverDone(agent)
  184. // No step opened, no model call ran, and the turn closed disposed.
  185. expect(streamed).toBe(false)
  186. expect(adapter.requests).toHaveLength(0)
  187. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  188. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'disposed' })
  189. })
  190. it('a cancel-interrupted prefix composition is discarded: the next send recomposes and ships the fresh prefix (stale-cache guard)', async () => {
  191. const adapter = new MockAdapter([textResponse('reply')])
  192. const ctx = await harness(adapter)
  193. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  194. // The interrupted first composition must not cache its degraded empty value;
  195. // the next prompt recomposes and logs/sends the fresh prefix.
  196. const opener: Message = { role: 'user', content: [{ type: 'text', text: 'fresh opener' }] }
  197. let compositions = 0
  198. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => {
  199. compositions += 1
  200. if (compositions === 1) {
  201. agent.cancel('mid-composition')
  202. return next()
  203. }
  204. return [opener, ...await next()]
  205. })
  206. send(agent, 'dropped')
  207. await waitForIdle(ctx, agent)
  208. send(agent, 'real prompt')
  209. await waitForIdle(ctx, agent)
  210. expect(compositions).toBe(2)
  211. expect(adapter.requests).toHaveLength(1)
  212. expect(adapter.requests[0]?.messages[0]).toEqual(opener)
  213. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  214. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.messagePrefix).toEqual([opener])
  215. })
  216. it('cancel from a synchronous turn/start session-event listener drops the step (step-start window)', async () => {
  217. const adapter = new MockAdapter([textResponse('should not stream')])
  218. const ctx = await harness(adapter)
  219. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  220. // A turn/start listener fires before a step controller exists, so the
  221. // turn-scoped marker—not step abort—must drop the pending step.
  222. let streamed = false
  223. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  224. const dispose = ctx.on('session/event', (session, event) => {
  225. if (session === agent.session && event.type === 'turn/start') agent.cancel('from turn-start')
  226. })
  227. const reasons: TurnEndReason[] = []
  228. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  229. send(agent, 'go')
  230. await waitForIdle(ctx, agent)
  231. dispose()
  232. // No step streamed (the model never ran), and the turn ended aborted with
  233. // the CALLER's reason — the marker carries `cancel(reason)` through even
  234. // though no AbortController observed it in this window.
  235. expect(streamed).toBe(false)
  236. expect(reasons).toEqual([{ kind: 'aborted', reason: 'from turn-start' }])
  237. })
  238. it('cancel from a synchronous step/start session-event listener drops the step (post-step-start window)', async () => {
  239. const adapter = new MockAdapter([textResponse('should not stream')])
  240. const ctx = await harness(adapter)
  241. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  242. // A step/start session-event listener fires AFTER step/start is appended
  243. // (and after the pre-step seam), so cancelling there lands in the SECOND
  244. // cancel check (the one that must closeStep() to balance the already-open
  245. // step) — distinct from a turn-start cancel, caught before the step opens.
  246. let streamed = false
  247. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  248. const dispose = ctx.on('session/event', (session, event) => {
  249. if (session === agent.session && event.type === 'step/start') agent.cancel('from step-start')
  250. })
  251. const reasons: TurnEndReason[] = []
  252. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  253. send(agent, 'go')
  254. await waitForIdle(ctx, agent)
  255. dispose()
  256. // No step streamed, the turn ended aborted with the caller's reason, and the
  257. // log is balanced (the open step was closed by the cancel branch).
  258. expect(streamed).toBe(false)
  259. expect(reasons).toEqual([{ kind: 'aborted', reason: 'from step-start' }])
  260. const types = agent.session.events.map(e => e.type)
  261. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  262. })
  263. it('disposal from a synchronous step/start session-event listener closes the open step as disposed', async () => {
  264. const adapter = new MockAdapter([textResponse('should not stream')])
  265. const ctx = new Context()
  266. await ctx.plugin(LlmService)
  267. await ctx.plugin(SessionStore)
  268. await ctx.plugin(SystemPrompt)
  269. await ctx.plugin(ToolRegistry)
  270. await ctx.plugin(AgentRegistry)
  271. await ctx.plugin(AgentLoop, { agents: [] })
  272. ctx.llm.registerAdapter(['mock'], adapter)
  273. const handle = await ctx.agents.create({
  274. sessionId: SessionId('dispose-step-start-session'),
  275. agentOptions: { provider: 'mock', model: 'mock' },
  276. })
  277. const agent = handle.agent
  278. let disposalDone: Promise<void> | undefined
  279. let streamed = false
  280. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  281. ctx.on('session/event', (session, event) => {
  282. if (session === agent.session && event.type === 'step/start') disposalDone = handle.dispose()
  283. })
  284. send(agent, 'go')
  285. await disposalDone
  286. await driverDone(agent)
  287. expect(streamed).toBe(false)
  288. expect(adapter.requests).toHaveLength(0)
  289. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  290. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'disposed' })
  291. const types = agent.session.events.map(e => e.type)
  292. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  293. })
  294. it('cancel during the continuation window ends the turn aborted and runs no further step', async () => {
  295. // A continuation-waterfall listener cancels DURING the continuation decision
  296. // (the finished step's AbortController is already cleared), and votes to
  297. // continue — but the turn-scoped marker checked right after must end the turn
  298. // `aborted` and run NO second step.
  299. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  300. const ctx = await harness(adapter)
  301. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  302. let steps = 0
  303. const reasons: TurnEndReason[] = []
  304. ctx.on('session/event', (_session, event) => {
  305. if (event.type === 'step/start') steps += 1
  306. if (event.type === 'turn/end') reasons.push(event.data.reason)
  307. })
  308. let continued = false
  309. ctx.on('agent/turn-continuation', async (subject, _turn, _default, next) => {
  310. if (subject === agent && !continued) {
  311. continued = true
  312. agent.cancel('from continuation')
  313. return { action: 'continue' as const } // vote to continue — the post-waterfall marker check must override
  314. }
  315. return next()
  316. })
  317. send(agent, 'go')
  318. await waitForIdle(ctx, agent)
  319. // Only ONE step ran (the second was cancelled in the continuation window),
  320. // and the turn ended aborted with the CALLER's reason (carried by the
  321. // marker, since the finished step's AbortController was already cleared).
  322. expect(steps).toBe(1)
  323. expect(reasons).toEqual([{ kind: 'aborted', reason: 'from continuation' }])
  324. })
  325. it('cancel from a synchronous agent/status(running) listener drops the turn (window 2)', async () => {
  326. const adapter = new MockAdapter([textResponse('should not run')])
  327. const ctx = await harness(adapter)
  328. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  329. // `agent/status` is synchronous, so cancellation can land after the first
  330. // pre-step check; the second check must drop the now-empty turn.
  331. let streamed = false
  332. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  333. const dispose = ctx.on('agent/status', (subject, status) => {
  334. if (subject === agent && status === 'running') agent.cancel('from running listener')
  335. })
  336. send(agent, 'go')
  337. await waitForIdle(ctx, agent)
  338. dispose()
  339. // No turn opened, no step streamed, and a later prompt still runs (the marker
  340. // was reset).
  341. expect(streamed).toBe(false)
  342. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(false)
  343. })
  344. it('window 2: whenIdle() does NOT resolve early when a running listener cancels then queues replacement work', async () => {
  345. // Cancellation must not settle idle while replacement work remains queued.
  346. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  347. const ctx = await harness(adapter)
  348. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  349. let replaced = false
  350. const dispose = ctx.on('agent/status', (subject, status) => {
  351. if (subject !== agent || status !== 'running' || replaced) return
  352. replaced = true
  353. agent.cancel('drop A')
  354. send(agent, 'B')
  355. })
  356. send(agent, 'A')
  357. const idle = agent.whenIdle()
  358. await idle
  359. dispose()
  360. // whenIdle() resolved only AFTER B's turn ran: B's user message + a turn/end
  361. // are in the log, and A was dropped.
  362. expect(userTexts(agent)).toContain('B')
  363. expect(userTexts(agent)).not.toContain('A')
  364. expect(agent.session.events.some(e => e.type === 'turn/end')).toBe(true)
  365. })
  366. it('whenIdle() does NOT resolve early when a new prompt is queued during a pre-step cancel', async () => {
  367. // The subtle race: a whenIdle() waiter is registered for prompt A; cancel() clears A;
  368. // prompt B is queued before the loop resumes from the idle wait.
  369. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  370. const ctx = await harness(adapter)
  371. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  372. send(agent, 'A') // queues A (status still idle, loop microtask pending)
  373. const idle = agent.whenIdle() // registers a waiter (idle + hasQueued → no fast path)
  374. agent.cancel('drop A') // arms marker, clears A
  375. send(agent, 'B') // B races in before the loop resumes
  376. // whenIdle() must resolve only after B's turn fully ran — by which point B's user message
  377. // and a turn/end are in the log.
  378. await idle
  379. expect(userTexts(agent)).toContain('B')
  380. expect(agent.session.events.some(e => e.type === 'turn/end')).toBe(true)
  381. // A was dropped (never ran); only B's turn is recorded.
  382. expect(userTexts(agent)).not.toContain('A')
  383. })
  384. it("cancel clears the turn's steering — it is not re-enqueued as a fresh turn", async () => {
  385. const adapter = new MockAdapter(['hang'])
  386. const ctx = await harness(adapter)
  387. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  388. send(agent, 'go')
  389. await new Promise(r => setTimeout(r, 30))
  390. expect(agent.status).toBe('running')
  391. // Steer (joins the running turn's steering FIFO), then cancel: the steering
  392. // must be dropped, NOT re-enqueued as a new queued turn.
  393. agent.steer([{ type: 'text', text: 'steer text' }])
  394. agent.cancel('cancel with steering')
  395. await waitForIdle(ctx, agent)
  396. // After the cancelled turn settles, the agent is idle with NO follow-up turn
  397. // started from the dropped steering.
  398. await new Promise(r => setTimeout(r, 30))
  399. expect(agent.status).toBe('idle')
  400. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  401. expect(turnStarts.length).toBe(1) // only the original (cancelled) turn
  402. // The steering text was dropped — it never reached the log.
  403. const flat = agent.session.events
  404. .filter(e => e.type === 'steering/message')
  405. .flatMap(e => e.type === 'steering/message' ? e.data.content : [])
  406. .flatMap(b => b.type === 'text' ? [b.text] : [])
  407. expect(flat).not.toContain('steer text')
  408. })
  409. })