cancel.spec.ts 21 KB

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