agent.spec.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. import { describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService from '@deepseek-ai/dsh-llm'
  4. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
  8. import AgentLoop, { DEFAULT_MAX_PARALLEL_TOOL_CALLS } from '@deepseek-ai/dsh-agent-loop'
  9. import { bindReactLoopAgentContext, prepareReactLoopAgent, type ReactLoopAgent } from '../src/agent.ts'
  10. import { MockAdapter, textResponse } from './mock-adapter.ts'
  11. function driverDone(agent: Agent): Promise<void> {
  12. return (agent as Agent & { done: Promise<void> }).done
  13. }
  14. async function harness(adapter: MockAdapter) {
  15. const ctx = new Context()
  16. await ctx.plugin(LlmService)
  17. await ctx.plugin(SessionStore)
  18. await ctx.plugin(SystemPrompt)
  19. await ctx.plugin(ToolRegistry)
  20. await ctx.plugin(AgentRegistry)
  21. await ctx.plugin(AgentLoop, { agents: [] })
  22. ctx.llm.registerAdapter(['mock'], adapter)
  23. return ctx
  24. }
  25. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  26. return new Promise((resolve) => {
  27. const dispose = ctx.on('agent/status', (subject, status) => {
  28. if (subject === agent && status === 'idle') {
  29. dispose()
  30. resolve()
  31. }
  32. })
  33. })
  34. }
  35. function waitForStatus(ctx: Context, agent: Agent, expected: Agent['status']): Promise<void> {
  36. return new Promise((resolve) => {
  37. const dispose = ctx.on('agent/status', (subject, status) => {
  38. if (subject === agent && status === expected) {
  39. dispose()
  40. resolve()
  41. }
  42. })
  43. })
  44. }
  45. function send(agent: Agent, text: string) {
  46. agent.send([{ type: 'text', text }])
  47. }
  48. describe('Agent', () => {
  49. it('rejects access before context binding and a second driver for one session', async () => {
  50. const ctx = new Context()
  51. await ctx.plugin(SessionStore)
  52. const session = ctx.sessions.create(SessionId('exclusive-driver'))
  53. const prepared = prepareReactLoopAgent(
  54. ctx, SessionId('first-driver'), { provider: 'mock', model: 'mock' }, session, DEFAULT_MAX_PARALLEL_TOOL_CALLS,
  55. )
  56. expect(() => prepared.agent.ctx).toThrow('context is not bound')
  57. expect(() => prepareReactLoopAgent(
  58. ctx, SessionId('second-driver'), { provider: 'mock', model: 'mock' }, session, DEFAULT_MAX_PARALLEL_TOOL_CALLS,
  59. ))
  60. .toThrow('already has a concrete agent driver')
  61. await prepared.dispose()
  62. await ctx.fiber.dispose()
  63. })
  64. it('borrows caller options and binds its scoped context exactly once', async () => {
  65. const ctx = await harness(new MockAdapter([textResponse('unused')]))
  66. const options = { provider: 'mock', model: 'mock' }
  67. const agent = ctx.agentLoop.create(SessionId('owned-bindings'), options)
  68. expect(agent.options).toBe(options)
  69. expect(agent.id).toBe('owned-bindings')
  70. expect(agent.session.id).toBe(agent.id)
  71. expect(() => { bindReactLoopAgentContext(agent as ReactLoopAgent, new Context()) }).toThrow(/context is already bound/)
  72. await ctx.fiber.dispose()
  73. })
  74. it('send() throws after disposal', async () => {
  75. const adapter = new MockAdapter(['hang'])
  76. const ctx = await harness(adapter)
  77. let agent!: Agent
  78. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  79. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  80. }, { inject: ['agentLoop'] }))
  81. send(agent, 'go')
  82. await new Promise(r => setTimeout(r, 30))
  83. await fiber.dispose()
  84. await driverDone(agent)
  85. expect(() => { agent.send([{ type: 'text', text: 'too late' }]) }).toThrow('disposed')
  86. })
  87. it('steer() throws after disposal', async () => {
  88. const adapter = new MockAdapter(['hang'])
  89. const ctx = await harness(adapter)
  90. let agent!: Agent
  91. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  92. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  93. }, { inject: ['agentLoop'] }))
  94. send(agent, 'go')
  95. await new Promise(r => setTimeout(r, 30))
  96. await fiber.dispose()
  97. await driverDone(agent)
  98. expect(() => { agent.steer([{ type: 'text', text: 'too late' }]) }).toThrow('disposed')
  99. })
  100. it('inject() throws after disposal', async () => {
  101. const adapter = new MockAdapter(['hang'])
  102. const ctx = await harness(adapter)
  103. let agent!: Agent
  104. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  105. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  106. }, { inject: ['agentLoop'] }))
  107. send(agent, 'go')
  108. await new Promise(r => setTimeout(r, 30))
  109. await fiber.dispose()
  110. await driverDone(agent)
  111. expect(() => { agent.inject([{ type: 'text', text: 'too late' }]) }).toThrow('disposed')
  112. })
  113. it('inject() decides enclosure from the LOG (open turn), not agent status', async () => {
  114. const adapter = new MockAdapter([textResponse('ok')])
  115. const ctx = await harness(adapter)
  116. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  117. // Simulate an OPEN turn in the log while the agent is idle (status is not a
  118. // reliable open-turn signal). inject must append into that open turn, NOT
  119. // wrap a new one.
  120. agent.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
  121. agent.inject([{ type: 'text', text: 'mid' }], { source: { kind: 'plugin', plugin: 'p' } })
  122. expect(agent.session.events.filter(e => e.type === 'turn/start')).toHaveLength(1)
  123. expect(agent.session.events.at(-1)!.type).toBe('context/message')
  124. // Close the turn; now inject must wrap its own one-shot injection turn.
  125. agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
  126. agent.inject([{ type: 'text', text: 'after' }], { source: { kind: 'plugin', plugin: 'p' } })
  127. const starts = agent.session.events.filter(e => e.type === 'turn/start')
  128. expect(starts).toHaveLength(2)
  129. const last = starts[1]!
  130. expect(last.type === 'turn/start' && last.data.trigger.kind).toBe('injection')
  131. expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed
  132. })
  133. it('idle inject() contains a failing flush (logs, does not throw into the caller)', async () => {
  134. const adapter = new MockAdapter([textResponse('ok')])
  135. const ctx = await harness(adapter)
  136. // A persistence-like listener whose flush rejects.
  137. ctx.on('session/flush', () => { throw new Error('disk gone') })
  138. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  139. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  140. // inject() is synchronous and fires a fire-and-forget flush; a rejecting
  141. // flush must be contained (logged), never thrown into the caller.
  142. expect(() => { agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } }) }).not.toThrow()
  143. await new Promise(r => setTimeout(r, 20)) // let the contained flush settle
  144. expect(warn).toHaveBeenCalledWith(expect.stringContaining('flush after idle injection failed'))
  145. warn.mockRestore()
  146. })
  147. it('idle inject() closes its one-shot turn AND still checkpoints even if the append throws', async () => {
  148. const adapter = new MockAdapter([textResponse('ok')])
  149. const ctx = await harness(adapter)
  150. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  151. let flushes = 0
  152. ctx.on('session/flush', () => { flushes += 1 })
  153. // Non-serializable injected content makes Session.append throw AFTER
  154. // turn/start was recorded. The turn/end must still be appended (finally),
  155. // AND the durability checkpoint must still fire — the balanced turn is in
  156. // memory and a crash before the next turn/dispose would otherwise lose it.
  157. expect(() => {
  158. agent.inject([{ type: 'text', text: 'x', bad: 1n } as never], { source: { kind: 'plugin', plugin: 'p' } })
  159. }).toThrow(/non-JSON-serializable/)
  160. const types = agent.session.events.map(e => e.type)
  161. expect(types).toEqual(['turn/start', 'turn/end']) // balanced, no open turn
  162. await new Promise(r => setTimeout(r, 10)) // let the fire-and-forget flush run
  163. expect(flushes).toBe(1) // checkpoint fired despite the throw
  164. })
  165. it('idle inject() still checkpoints when a listener throws on the synthetic turn/end', async () => {
  166. const adapter = new MockAdapter([textResponse('ok')])
  167. const ctx = await harness(adapter)
  168. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  169. let flushes = 0
  170. ctx.on('session/flush', () => { flushes += 1 })
  171. // Session contains a throwing post-commit turn/end observer. The accepted
  172. // boundary still triggers the idle injection's durability checkpoint.
  173. let threw = false
  174. ctx.on('session/event', (_s, event) => {
  175. if (!threw && event.type === 'turn/end') { threw = true; throw new Error('boom turn/end') }
  176. })
  177. expect(() => { agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } }) }).not.toThrow()
  178. const types = agent.session.events.map(e => e.type)
  179. expect(types).toEqual(['turn/start', 'context/message', 'turn/end']) // balanced
  180. await new Promise(r => setTimeout(r, 10))
  181. expect(flushes).toBe(1) // checkpoint fired despite the throwing turn/end listener
  182. })
  183. it('idle inject() reports a failing flush via agent/error (step 0) AND the logger', async () => {
  184. const adapter = new MockAdapter([textResponse('ok')])
  185. const ctx = await harness(adapter)
  186. // A non-Error rejection exercises the String() normalization branch.
  187. ctx.on('session/flush', () => { throw 'disk gone' })
  188. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  189. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  190. const errors: { turn: number; step: number; message: string }[] = []
  191. ctx.on('agent/error', (_a, turn, step, error) => void errors.push({ turn, step, message: error.message }))
  192. agent.inject([{ type: 'text', text: 'notice' }], { source: { kind: 'plugin', plugin: 'p' } })
  193. await new Promise(r => setTimeout(r, 20)) // let the contained flush settle
  194. // Reported via agent/error (step 0 — the idle-injection convention) so
  195. // plugins monitoring agent/error see idle-injection persistence failures,
  196. // mirroring the loop's post-turn/end flush path. A non-Error throw is
  197. // normalized to an Error.
  198. expect(errors).toEqual([{ turn: 1, step: 0, message: 'disk gone' }])
  199. expect(warn).toHaveBeenCalledWith(expect.stringContaining('flush after idle injection failed'))
  200. warn.mockRestore()
  201. })
  202. it('idle inject() with a non-serializable source opens no turn (nothing to close)', async () => {
  203. const adapter = new MockAdapter([textResponse('ok')])
  204. const ctx = await harness(adapter)
  205. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  206. // A non-serializable source makes the turn/start append throw BEFORE the
  207. // event is pushed (Session.append validates before push), so NO turn opens.
  208. // The finally's isTurnOpen() guard sees no open turn and appends nothing —
  209. // the log stays empty, not left with a dangling turn/start.
  210. expect(() => {
  211. agent.inject([{ type: 'text', text: 'x' }], { source: { kind: 'plugin', plugin: 'p', bad: 1n } as never })
  212. }).toThrow(/non-JSON-serializable/)
  213. expect(agent.session.events).toHaveLength(0)
  214. })
  215. it('steer() when idle falls through to send() and starts a turn', async () => {
  216. const adapter = new MockAdapter([textResponse('ok')])
  217. const ctx = await harness(adapter)
  218. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  219. // steer while idle delegates to send
  220. agent.steer([{ type: 'text', text: 'steer idle' }], { source: { kind: 'plugin', plugin: 'test' } })
  221. await waitForIdle(ctx, agent)
  222. // The message was recorded as a user-level message (send path)
  223. expect(agent.session.events.some(e => e.type === 'user/message')).toBe(true)
  224. expect(adapter.requests).toHaveLength(1)
  225. })
  226. it('disposer is idempotent (double-stop)', async () => {
  227. // Create a bare Agent and start it through the package-internal
  228. // test seam. Then call its disposer twice — the second call hits the
  229. // early-return branch.
  230. const ctx = new Context()
  231. await ctx.plugin(SessionStore)
  232. await ctx.plugin(AgentRegistry)
  233. const session = ctx.sessions.create(SessionId('test'))
  234. const prepared = prepareReactLoopAgent(
  235. ctx, SessionId('bare'), { provider: 'mock', model: 'mock' }, session, DEFAULT_MAX_PARALLEL_TOOL_CALLS,
  236. )
  237. const { agent } = prepared
  238. // Start the loop to get the disposer; the agent waits for messages
  239. // (idle, never-resolving cancel), so it will stay idle.
  240. prepared.markPublished()
  241. const dispose = prepared.startDriver()
  242. // First dispose
  243. const firstDisposal = dispose()
  244. expect(agent.status).toBe('disposed')
  245. await firstDisposal
  246. // Second dispose — idempotent, no throw
  247. await expect(dispose()).resolves.toBeUndefined()
  248. expect(agent.status).toBe('disposed')
  249. })
  250. it('a pre-start disposal makes a later driver-start attempt inert', async () => {
  251. const ctx = new Context()
  252. await ctx.plugin(SessionStore)
  253. const session = ctx.sessions.create(SessionId('pre-start-dispose'))
  254. const prepared = prepareReactLoopAgent(
  255. ctx, SessionId('pre-start-dispose'), { provider: 'mock', model: 'mock' }, session, DEFAULT_MAX_PARALLEL_TOOL_CALLS,
  256. )
  257. await prepared.dispose()
  258. expect(prepared.agent.status).toBe('disposed')
  259. const dispose = prepared.startDriver()
  260. await dispose()
  261. await expect(prepared.agent.done).resolves.toBeUndefined()
  262. expect(prepared.agent.session.events).toEqual([])
  263. await ctx.fiber.dispose()
  264. })
  265. it('setting the same status does not emit agent/status again', async () => {
  266. const adapter = new MockAdapter([textResponse('ok')])
  267. const ctx = await harness(adapter)
  268. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  269. const statuses: string[] = []
  270. ctx.on('agent/status', (subject, status) => {
  271. if (subject === agent) statuses.push(status)
  272. })
  273. send(agent, 'hi')
  274. await waitForIdle(ctx, agent)
  275. // After the turn, agent is idle. Send again to trigger another attempt
  276. // to go idle — but it's already idle, so no emission.
  277. const idleTransitionCount = statuses.filter(s => s === 'idle').length
  278. expect(idleTransitionCount).toBe(1) // only the final transition from running
  279. })
  280. it('whenIdle() resolves immediately when the agent is not running', async () => {
  281. const adapter = new MockAdapter([textResponse('ok')])
  282. const ctx = await harness(adapter)
  283. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  284. // Fresh agent is idle — whenIdle() takes the not-running fast path and
  285. // resolves without subscribing. await must not hang.
  286. await agent.whenIdle()
  287. expect(agent.status).not.toBe('running')
  288. })
  289. it('whenIdle() waits for queued work that has not flipped status yet', async () => {
  290. const adapter = new MockAdapter(['hang'])
  291. const ctx = await harness(adapter)
  292. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  293. send(agent, 'queued')
  294. let settled = false
  295. const idle = agent.whenIdle().then(() => { settled = true })
  296. await Promise.resolve()
  297. expect(settled).toBe(false)
  298. await waitForStatus(ctx, agent, 'running')
  299. agent.cancel('done')
  300. await idle
  301. expect(settled).toBe(true)
  302. expect(agent.status).toBe('idle')
  303. })
  304. it('whenIdle() awaits the running→idle transition, ignoring other subjects/running events', async () => {
  305. const adapter = new MockAdapter([textResponse('ok'), textResponse('ok')])
  306. const ctx = await harness(adapter)
  307. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  308. const other = ctx.agentLoop.create(SessionId('a2'), { provider: 'mock', model: 'mock' })
  309. // Drive `agent` into `running`, then await whenIdle() — it subscribes to
  310. // agent/status and resolves on the first transition out of running.
  311. const running = new Promise<void>((resolve) => {
  312. const dispose = ctx.on('agent/status', (subject, status) => {
  313. if (subject === agent && status === 'running') { dispose(); resolve() }
  314. })
  315. })
  316. send(agent, 'go')
  317. await running
  318. expect(agent.status).toBe('running')
  319. // While `agent`'s whenIdle is pending, churn `other` through running→idle:
  320. // every status event it emits hits whenIdle's guard with `subject !== this`,
  321. // so the wait must ignore them and only resolve on `agent`'s own idle.
  322. send(other, 'go')
  323. await agent.whenIdle()
  324. expect(agent.status).toBe('idle')
  325. })
  326. it('whenIdle() subscribed while running resolves via done when the agent is then disposed', async () => {
  327. // Covers the waiter's disposed arm: whenIdle() queues an internal waiter
  328. // while running (not the fast path), then the disposer settles it and chains
  329. // `done` (loop exit), not an eager resolve. A bare Agent + direct
  330. // internal driver disposer keeps the emit synchronous.
  331. const ctx = new Context()
  332. await ctx.plugin(LlmService)
  333. await ctx.plugin(SessionStore)
  334. await ctx.plugin(SystemPrompt)
  335. await ctx.plugin(ToolRegistry)
  336. await ctx.plugin(AgentRegistry)
  337. const adapter = new MockAdapter(['hang'])
  338. ctx.llm.registerAdapter(['mock'], adapter)
  339. const session = ctx.sessions.create(SessionId('bare'))
  340. const prepared = prepareReactLoopAgent(
  341. ctx, SessionId('bare'), { provider: 'mock', model: 'mock' }, session, DEFAULT_MAX_PARALLEL_TOOL_CALLS,
  342. )
  343. const { agent } = prepared
  344. prepared.markPublished()
  345. const dispose = prepared.startDriver()
  346. agent.send([{ type: 'text', text: 'go' }])
  347. await new Promise(r => setTimeout(r, 30))
  348. expect(agent.status).toBe('running')
  349. const idle = agent.whenIdle() // queues an internal waiter (running)
  350. const disposal = dispose() // settles the waiter synchronously; whenIdle chains done
  351. await idle
  352. expect(agent.status).toBe('disposed')
  353. await disposal
  354. })
  355. it('whenIdle() subscribed while running survives a FIBER dispose (no hung promise)', async () => {
  356. // The waiter is internal agent state, NOT an effect-scoped ctx.on listener:
  357. // disposing the OWNING fiber runs the agent's listener disposers, which would
  358. // have dropped a ctx.on-based waiter before the 'disposed' transition and
  359. // hung the promise. With internal waiters, the fiber disposer still settles it.
  360. const adapter = new MockAdapter(['hang'])
  361. const ctx = await harness(adapter)
  362. let agent!: Agent
  363. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  364. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  365. }, { inject: ['agentLoop'] }))
  366. send(agent, 'go')
  367. await new Promise(r => setTimeout(r, 30))
  368. expect(agent.status).toBe('running')
  369. const idle = agent.whenIdle() // queued while running
  370. await fiber.dispose() // tears the fiber down (drops agent listeners)
  371. await idle // must resolve, not hang
  372. expect(agent.status).toBe('disposed')
  373. })
  374. it('whenIdle() on a disposed agent awaits the loop exit (done), not just the status flip', async () => {
  375. // The disposer emits agent/status('disposed') BEFORE the driver loop
  376. // unwinds, so whenIdle() must chain `done` (true quiescence) on the
  377. // disposed path. Dispose a running agent, then assert whenIdle() resolves
  378. // only after `done` — i.e. the loop has actually exited.
  379. const adapter = new MockAdapter(['hang'])
  380. const ctx = await harness(adapter)
  381. let agent!: Agent
  382. const fiber = await ctx.plugin(Object.assign((inner: Context) => {
  383. agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
  384. }, { inject: ['agentLoop'] }))
  385. send(agent, 'go')
  386. await new Promise(r => setTimeout(r, 30))
  387. let doneResolved = false
  388. void driverDone(agent).then(() => { doneResolved = true })
  389. await fiber.dispose() // sets status disposed, aborts, drains the loop
  390. expect(agent.status).toBe('disposed')
  391. // whenIdle() must not resolve before `done` has — chaining `done` is the
  392. // quiescence guarantee. By here dispose() awaited the loop, so done is
  393. // settled; whenIdle resolves and done is observed resolved.
  394. await agent.whenIdle()
  395. expect(doneResolved).toBe(true)
  396. })
  397. it('contains a throwing agent/status listener on the running transition', async () => {
  398. const adapter = new MockAdapter([textResponse('ok')])
  399. const ctx = await harness(adapter)
  400. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  401. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  402. ctx.on('agent/status', (_subject, status) => {
  403. if (status === 'running') throw new Error('bad running listener')
  404. })
  405. send(agent, 'go')
  406. await agent.whenIdle()
  407. expect(adapter.requests).toHaveLength(1)
  408. expect(agent.status).toBe('idle')
  409. expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent event "agent/status" listener threw'))
  410. warn.mockRestore()
  411. })
  412. it('contains a throwing agent/status listener on the idle transition', async () => {
  413. const adapter = new MockAdapter([textResponse('ok')])
  414. const ctx = await harness(adapter)
  415. const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
  416. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  417. ctx.on('agent/status', (_subject, status) => {
  418. if (status === 'idle') throw new Error('bad idle listener')
  419. })
  420. send(agent, 'go')
  421. await agent.whenIdle()
  422. expect(adapter.requests).toHaveLength(1)
  423. expect(agent.status).toBe('idle')
  424. expect(warn).toHaveBeenCalledWith(expect.stringContaining('agent event "agent/status" listener threw'))
  425. warn.mockRestore()
  426. })
  427. })