cancel.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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, { defineTool } 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(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('cancel from an assistant/message observer skips execution but balances replay', async () => {
  121. const adapter = new MockAdapter([
  122. toolCallResponse('c1', 'danger', {}),
  123. textResponse('recovered after cancellation'),
  124. ])
  125. const ctx = await harness(adapter)
  126. let executions = 0
  127. ctx.tools.register(defineTool({
  128. name: 'danger',
  129. description: 'must not run after cancellation',
  130. parameters: {},
  131. async execute() {
  132. executions += 1
  133. return [{ type: 'text', text: 'ran' }]
  134. },
  135. }))
  136. const agent = ctx.agentLoop.create(SessionId('cancel-after-assistant-message'), { provider: 'mock', model: 'mock' })
  137. const dispose = ctx.on('session/event', (session, event) => {
  138. if (session === agent.session && event.type === 'assistant/message') {
  139. agent.cancel('cancelled after assistant message')
  140. }
  141. })
  142. const reasons: TurnEndReason[] = []
  143. ctx.on('session/event', (_session, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  144. send(agent, 'go')
  145. await waitForIdle(ctx, agent)
  146. dispose()
  147. expect(executions).toBe(0)
  148. expect(reasons).toEqual([{ kind: 'aborted', reason: 'cancelled after assistant message' }])
  149. const call = agent.session.events.find(event => event.type === 'tool/call')
  150. const result = agent.session.events.find(event => event.type === 'tool/result')
  151. expect(call?.type === 'tool/call' ? call.data.callId : undefined).toBe('c1')
  152. expect(result?.type === 'tool/result' ? result.data : undefined).toMatchObject({
  153. callId: 'c1',
  154. isError: true,
  155. error: { name: 'AbortError', code: 'ABORTED' },
  156. })
  157. send(agent, 'continue safely')
  158. await waitForIdle(ctx, agent)
  159. const replayedResult = adapter.requests[1]!.messages
  160. .flatMap(message => message.content)
  161. .find(block => block.type === 'tool-result')
  162. expect(replayedResult).toMatchObject({ toolCallId: 'c1', isError: true })
  163. expect(reasons).toEqual([
  164. { kind: 'aborted', reason: 'cancelled after assistant message' },
  165. { kind: 'completed' },
  166. ])
  167. })
  168. it('a prompt sent AFTER a cancelled turn settles runs normally (marker reset)', async () => {
  169. const adapter = new MockAdapter(['hang', textResponse('second reply')])
  170. const ctx = await harness(adapter)
  171. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  172. // First turn hangs; cancel it mid-step.
  173. send(agent, 'first')
  174. await new Promise(r => setTimeout(r, 30))
  175. agent.cancel('cancel first')
  176. await waitForIdle(ctx, agent)
  177. // The marker must have been reset after the cancelled turn — a fresh prompt
  178. // runs to completion rather than being dropped by a stale marker.
  179. send(agent, 'second')
  180. await waitForIdle(ctx, agent)
  181. expect(userTexts(agent)).toContain('second')
  182. // The second turn completed (its reply was streamed).
  183. const reasons = agent.session.events.filter(e => e.type === 'turn/end')
  184. expect(reasons.length).toBe(2)
  185. })
  186. it('cancel from inside the agent/session-prefix waterfall drops the step (prefix-composition window)', async () => {
  187. const adapter = new MockAdapter([textResponse('should not stream')])
  188. const ctx = await harness(adapter)
  189. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  190. // Prefix composition runs before the pre-step seam on the instance's first
  191. // step; a cancel landing inside it must drop the about-to-start step
  192. // without running the seam or the model.
  193. let streamed = false
  194. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  195. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next) => {
  196. agent.cancel('from prefix composition')
  197. return next()
  198. })
  199. const reasons: TurnEndReason[] = []
  200. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  201. send(agent, 'go')
  202. await waitForIdle(ctx, agent)
  203. expect(streamed).toBe(false)
  204. expect(reasons).toEqual([{ kind: 'aborted', reason: 'from prefix composition' }])
  205. })
  206. it('disposal from inside the agent/session-prefix waterfall ends the turn disposed (prefix-composition window)', async () => {
  207. const adapter = new MockAdapter([textResponse('should not stream')])
  208. const ctx = new Context()
  209. await ctx.plugin(LlmService)
  210. await ctx.plugin(SessionStore)
  211. await ctx.plugin(SystemPrompt)
  212. await ctx.plugin(ToolRegistry)
  213. await ctx.plugin(AgentRegistry)
  214. await ctx.plugin(AgentLoop, { agents: [] })
  215. ctx.llm.registerAdapter(['mock'], adapter)
  216. const handle = await ctx.agents.create({
  217. sessionId: SessionId('dispose-prefix-session'),
  218. agentOptions: { provider: 'mock', model: 'mock' },
  219. })
  220. const agent = handle.agent
  221. let disposalDone: Promise<void> | undefined
  222. let streamed = false
  223. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  224. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next) => {
  225. disposalDone = handle.dispose()
  226. return next()
  227. })
  228. send(agent, 'go')
  229. await new Promise(resolve => setTimeout(resolve, 0))
  230. await disposalDone
  231. await driverDone(agent)
  232. // No step opened, no model call ran, and the turn closed disposed.
  233. expect(streamed).toBe(false)
  234. expect(adapter.requests).toHaveLength(0)
  235. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  236. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'disposed' })
  237. })
  238. it('a cancel-interrupted prefix composition is discarded: the next send recomposes and ships the fresh prefix (stale-cache guard)', async () => {
  239. const adapter = new MockAdapter([textResponse('reply')])
  240. const ctx = await harness(adapter)
  241. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  242. // The interrupted first composition must not cache its degraded empty value;
  243. // the next prompt recomposes and logs/sends the fresh prefix.
  244. const opener: Message = { role: 'user', content: [{ type: 'text', text: 'fresh opener' }] }
  245. let compositions = 0
  246. ctx.on('agent/session-prefix', async (_agent, _prefix, _signal, next): Promise<Message[]> => {
  247. compositions += 1
  248. if (compositions === 1) {
  249. agent.cancel('mid-composition')
  250. return next()
  251. }
  252. return [opener, ...await next()]
  253. })
  254. send(agent, 'dropped')
  255. await waitForIdle(ctx, agent)
  256. send(agent, 'real prompt')
  257. await waitForIdle(ctx, agent)
  258. expect(compositions).toBe(2)
  259. expect(adapter.requests).toHaveLength(1)
  260. expect(adapter.requests[0]?.messages[0]).toEqual(opener)
  261. const headerEvent = agent.session.events.find(e => e.type === 'request/header')
  262. expect(headerEvent?.type === 'request/header' && headerEvent.data.header.messagePrefix).toEqual([opener])
  263. })
  264. it('cancel from a synchronous turn/start session-event listener drops the step (step-start window)', async () => {
  265. const adapter = new MockAdapter([textResponse('should not stream')])
  266. const ctx = await harness(adapter)
  267. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  268. // A turn/start listener fires before a step controller exists, so the
  269. // turn-scoped marker—not step abort—must drop the pending step.
  270. let streamed = false
  271. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  272. const dispose = ctx.on('session/event', (session, event) => {
  273. if (session === agent.session && event.type === 'turn/start') agent.cancel('from turn-start')
  274. })
  275. const reasons: TurnEndReason[] = []
  276. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  277. send(agent, 'go')
  278. await waitForIdle(ctx, agent)
  279. dispose()
  280. // No step streamed (the model never ran), and the turn ended aborted with
  281. // the CALLER's reason — the marker carries `cancel(reason)` through even
  282. // though no AbortController observed it in this window.
  283. expect(streamed).toBe(false)
  284. expect(reasons).toEqual([{ kind: 'aborted', reason: 'from turn-start' }])
  285. })
  286. it('cancel from a synchronous step/start session-event listener drops the step (post-step-start window)', async () => {
  287. const adapter = new MockAdapter([textResponse('should not stream')])
  288. const ctx = await harness(adapter)
  289. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  290. // A step/start session-event listener fires AFTER step/start is appended
  291. // (and after the pre-step seam), so cancelling there lands in the SECOND
  292. // cancel check (the one that must closeStep() to balance the already-open
  293. // step) — distinct from a turn-start cancel, caught before the step opens.
  294. let streamed = false
  295. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  296. const dispose = ctx.on('session/event', (session, event) => {
  297. if (session === agent.session && event.type === 'step/start') agent.cancel('from step-start')
  298. })
  299. const reasons: TurnEndReason[] = []
  300. ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
  301. send(agent, 'go')
  302. await waitForIdle(ctx, agent)
  303. dispose()
  304. // No step streamed, the turn ended aborted with the caller's reason, and the
  305. // log is balanced (the open step was closed by the cancel branch).
  306. expect(streamed).toBe(false)
  307. expect(reasons).toEqual([{ kind: 'aborted', reason: 'from step-start' }])
  308. const types = agent.session.events.map(e => e.type)
  309. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  310. })
  311. it('disposal from a synchronous step/start session-event listener closes the open step as disposed', async () => {
  312. const adapter = new MockAdapter([textResponse('should not stream')])
  313. const ctx = new Context()
  314. await ctx.plugin(LlmService)
  315. await ctx.plugin(SessionStore)
  316. await ctx.plugin(SystemPrompt)
  317. await ctx.plugin(ToolRegistry)
  318. await ctx.plugin(AgentRegistry)
  319. await ctx.plugin(AgentLoop, { agents: [] })
  320. ctx.llm.registerAdapter(['mock'], adapter)
  321. const handle = await ctx.agents.create({
  322. sessionId: SessionId('dispose-step-start-session'),
  323. agentOptions: { provider: 'mock', model: 'mock' },
  324. })
  325. const agent = handle.agent
  326. let disposalDone: Promise<void> | undefined
  327. let streamed = false
  328. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  329. ctx.on('session/event', (session, event) => {
  330. if (session === agent.session && event.type === 'step/start') disposalDone = handle.dispose()
  331. })
  332. send(agent, 'go')
  333. await disposalDone
  334. await driverDone(agent)
  335. expect(streamed).toBe(false)
  336. expect(adapter.requests).toHaveLength(0)
  337. const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
  338. expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toEqual({ kind: 'disposed' })
  339. const types = agent.session.events.map(e => e.type)
  340. expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
  341. })
  342. it('cancel during the continuation window ends the turn aborted and runs no further step', async () => {
  343. // A continuation-waterfall listener cancels DURING the continuation decision
  344. // (the finished step's AbortController is already cleared), and votes to
  345. // continue — but the turn-scoped marker checked right after must end the turn
  346. // `aborted` and run NO second step.
  347. const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
  348. const ctx = await harness(adapter)
  349. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  350. let steps = 0
  351. const reasons: TurnEndReason[] = []
  352. ctx.on('session/event', (_session, event) => {
  353. if (event.type === 'step/start') steps += 1
  354. if (event.type === 'turn/end') reasons.push(event.data.reason)
  355. })
  356. let continued = false
  357. ctx.on('agent/turn-continuation', async (subject, _turn, _default, next) => {
  358. if (subject === agent && !continued) {
  359. continued = true
  360. agent.cancel('from continuation')
  361. return { action: 'continue' as const } // vote to continue — the post-waterfall marker check must override
  362. }
  363. return next()
  364. })
  365. send(agent, 'go')
  366. await waitForIdle(ctx, agent)
  367. // Only ONE step ran (the second was cancelled in the continuation window),
  368. // and the turn ended aborted with the CALLER's reason (carried by the
  369. // marker, since the finished step's AbortController was already cleared).
  370. expect(steps).toBe(1)
  371. expect(reasons).toEqual([{ kind: 'aborted', reason: 'from continuation' }])
  372. })
  373. it('cancel from a synchronous agent/status(running) listener drops the turn (window 2)', async () => {
  374. const adapter = new MockAdapter([textResponse('should not run')])
  375. const ctx = await harness(adapter)
  376. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  377. // `agent/status` is synchronous, so cancellation can land after the first
  378. // pre-step check; the second check must drop the now-empty turn.
  379. let streamed = false
  380. ctx.on('session/event', (_s, event) => { if (event.type === 'assistant/chunk') streamed = true })
  381. const dispose = ctx.on('agent/status', (subject, status) => {
  382. if (subject === agent && status === 'running') agent.cancel('from running listener')
  383. })
  384. send(agent, 'go')
  385. await waitForIdle(ctx, agent)
  386. dispose()
  387. // No turn opened, no step streamed, and a later prompt still runs (the marker
  388. // was reset).
  389. expect(streamed).toBe(false)
  390. expect(agent.session.events.some(e => e.type === 'turn/start')).toBe(false)
  391. })
  392. it('window 2: whenIdle() does NOT resolve early when a running listener cancels then queues replacement work', async () => {
  393. // Cancellation must not settle idle while replacement work remains queued.
  394. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  395. const ctx = await harness(adapter)
  396. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  397. let replaced = false
  398. const dispose = ctx.on('agent/status', (subject, status) => {
  399. if (subject !== agent || status !== 'running' || replaced) return
  400. replaced = true
  401. agent.cancel('drop A')
  402. send(agent, 'B')
  403. })
  404. send(agent, 'A')
  405. const idle = agent.whenIdle()
  406. await idle
  407. dispose()
  408. // whenIdle() resolved only AFTER B's turn ran: B's user message + a turn/end
  409. // are in the log, and A was dropped.
  410. expect(userTexts(agent)).toContain('B')
  411. expect(userTexts(agent)).not.toContain('A')
  412. expect(agent.session.events.some(e => e.type === 'turn/end')).toBe(true)
  413. })
  414. it('whenIdle() does NOT resolve early when a new prompt is queued during a pre-step cancel', async () => {
  415. // The subtle race: a whenIdle() waiter is registered for prompt A; cancel() clears A;
  416. // prompt B is queued before the loop resumes from the idle wait.
  417. const adapter = new MockAdapter([textResponse('A reply'), textResponse('B reply')])
  418. const ctx = await harness(adapter)
  419. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  420. send(agent, 'A') // queues A (status still idle, loop microtask pending)
  421. const idle = agent.whenIdle() // registers a waiter (idle + hasQueued → no fast path)
  422. agent.cancel('drop A') // arms marker, clears A
  423. send(agent, 'B') // B races in before the loop resumes
  424. // whenIdle() must resolve only after B's turn fully ran — by which point B's user message
  425. // and a turn/end are in the log.
  426. await idle
  427. expect(userTexts(agent)).toContain('B')
  428. expect(agent.session.events.some(e => e.type === 'turn/end')).toBe(true)
  429. // A was dropped (never ran); only B's turn is recorded.
  430. expect(userTexts(agent)).not.toContain('A')
  431. })
  432. it("cancel clears the turn's steering — it is not re-enqueued as a fresh turn", async () => {
  433. const adapter = new MockAdapter(['hang'])
  434. const ctx = await harness(adapter)
  435. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  436. send(agent, 'go')
  437. await new Promise(r => setTimeout(r, 30))
  438. expect(agent.status).toBe('running')
  439. // Steer (joins the running turn's steering FIFO), then cancel: the steering
  440. // must be dropped, NOT re-enqueued as a new queued turn.
  441. agent.steer([{ type: 'text', text: 'steer text' }])
  442. agent.cancel('cancel with steering')
  443. await waitForIdle(ctx, agent)
  444. // After the cancelled turn settles, the agent is idle with NO follow-up turn
  445. // started from the dropped steering.
  446. await new Promise(r => setTimeout(r, 30))
  447. expect(agent.status).toBe('idle')
  448. const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
  449. expect(turnStarts.length).toBe(1) // only the original (cancelled) turn
  450. // The steering text was dropped — it never reached the log.
  451. const flat = agent.session.events
  452. .filter(e => e.type === 'steering/message')
  453. .flatMap(e => e.type === 'steering/message' ? e.data.content : [])
  454. .flatMap(b => b.type === 'text' ? [b.text] : [])
  455. expect(flat).not.toContain('steer text')
  456. })
  457. })