| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204 |
- import { describe, expect, it, vi } from 'vitest'
- import { Context } from 'cordis'
- import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
- import AgentLoop from '@deepseek-ai/dsh-agent-loop'
- import LlmService from '@deepseek-ai/dsh-llm'
- import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
- import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
- import ToolRegistry from '@deepseek-ai/dsh-tools'
- import { MockAdapter, textResponse } from './mock-adapter.ts'
- async function harness(adapter: MockAdapter): Promise<Context> {
- const ctx = new Context()
- await ctx.plugin(LlmService)
- await ctx.plugin(SessionStore)
- await ctx.plugin(SystemPrompt)
- await ctx.plugin(ToolRegistry)
- await ctx.plugin(AgentRegistry)
- await ctx.plugin(AgentLoop, { agents: [] })
- ctx.llm.registerAdapter(['mock'], adapter)
- return ctx
- }
- function send(agent: Agent, text: string): void {
- agent.followup({ content: [{ type: 'text', text }], source: { kind: 'user' } })
- }
- describe('Agent', () => {
- it('idle inject() appends context without opening a turn or requesting a flush', async () => {
- const adapter = new MockAdapter([textResponse('ok')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- let flushes = 0
- ctx.on('session/flush', () => { flushes += 1 })
- agent.inject({ content: [{ type: 'text', text: 'context' }], source: { kind: 'plugin', plugin: 'p' } })
- expect(agent.session.events.map(event => event.type)).toEqual(['user/message'])
- expect(agent.status).toBe('idle')
- expect(adapter.requests).toHaveLength(0)
- await agent.whenIdle()
- expect(flushes).toBe(0)
- })
- it('inject() preserves an explicitly empty plugin source', async () => {
- const ctx = await harness(new MockAdapter([textResponse('ok')]))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- agent.inject({ content: [{ type: 'text', text: 'empty plugin source' }], source: { kind: 'plugin', plugin: '' } })
- const injected = agent.session.events.at(-1)
- expect(injected?.type === 'user/message' && injected.data.source)
- .toEqual({ kind: 'plugin', plugin: '' })
- })
- it('idle inject() rejects invalid input before append', async () => {
- const ctx = await harness(new MockAdapter([textResponse('ok')]))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- expect(() => {
- agent.inject({ content: [{ type: 'text', text: 'x', bad: 1n } as never], source: { kind: 'plugin', plugin: 'p' } })
- }).toThrow(/non-JSON-serializable/)
- expect(agent.session.events).toHaveLength(0)
- })
- it('steer() while idle becomes a woken prompt turn', async () => {
- const adapter = new MockAdapter([textResponse('ok')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- agent.steer({ content: [{ type: 'text', text: 'steer idle' }], source: { kind: 'plugin', plugin: 'test' } })
- await agent.whenIdle()
- expect(agent.session.events.some(event => event.type === 'user/message')).toBe(true)
- expect(adapter.requests).toHaveLength(1)
- })
- it('emits one running and idle transition for one completed turn', async () => {
- const ctx = await harness(new MockAdapter([textResponse('ok')]))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const statuses: string[] = []
- ctx.on('agent/status', (subject, status) => {
- if (subject === agent) statuses.push(status)
- })
- send(agent, 'hi')
- await agent.whenIdle()
- expect(statuses).toEqual(['running', 'idle'])
- })
- it('awaits the turn-end checkpoint before claiming the next queued turn', async () => {
- const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const firstFlush = Promise.withResolvers<undefined>()
- const flushedTurns: number[] = []
- ctx.on('session/flush', async (session) => {
- const turnEnd = session.events.findLast(event => event.type === 'turn/end')
- flushedTurns.push(turnEnd?.data.turn ?? 0)
- if (turnEnd?.data.turn === 1) await firstFlush.promise
- })
- send(agent, 'first')
- send(agent, 'second')
- await vi.waitFor(() => { expect(flushedTurns).toEqual([1]) })
- expect(adapter.requests).toHaveLength(1)
- firstFlush.resolve(undefined)
- await agent.whenIdle()
- expect(adapter.requests).toHaveLength(2)
- expect(flushedTurns).toEqual([1, 2])
- })
- it('keeps whenIdle pending through the final turn checkpoint', async () => {
- const ctx = await harness(new MockAdapter([textResponse('done')]))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const flush = Promise.withResolvers<undefined>()
- let flushStarted = false
- ctx.on('session/flush', () => {
- flushStarted = true
- return flush.promise
- })
- send(agent, 'go')
- await vi.waitFor(() => { expect(flushStarted).toBe(true) })
- let idleSettled = false
- const idle = agent.whenIdle().then(() => { idleSettled = true })
- await Promise.resolve()
- expect(idleSettled).toBe(false)
- flush.resolve(undefined)
- await idle
- expect(agent.status).toBe('idle')
- })
- it('reports a rejected turn-end checkpoint and continues queued work', async () => {
- const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
- const ctx = await harness(adapter)
- const warning = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const failure = new Error('disk unavailable')
- const errors: { turn: number; step: number; error: unknown }[] = []
- let flushes = 0
- ctx.on('session/flush', () => {
- flushes += 1
- if (flushes === 1) throw failure
- })
- ctx.on('agent/error', (subject, turn, step, error) => {
- if (subject === agent) errors.push({ turn, step, error })
- })
- send(agent, 'first')
- send(agent, 'second')
- await agent.whenIdle()
- expect(adapter.requests).toHaveLength(2)
- expect(flushes).toBe(2)
- expect(errors).toEqual([{ turn: 1, step: 1, error: failure }])
- expect(warning).toHaveBeenCalledWith(expect.stringContaining('session/flush failed at turn 1: disk unavailable'))
- warning.mockRestore()
- })
- it('whenIdle() resolves immediately without active work', async () => {
- const ctx = await harness(new MockAdapter([textResponse('ok')]))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- await agent.whenIdle()
- expect(agent.status).toBe('idle')
- })
- it('whenIdle() waits for active work until explicit cancellation', async () => {
- const ctx = await harness(new MockAdapter(['hang']))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- send(agent, 'queued')
- let settled = false
- const idle = agent.whenIdle().then(() => { settled = true })
- await Promise.resolve()
- expect(settled).toBe(false)
- agent.cancel({ kind: 'user' })
- await idle
- expect(agent.status).toBe('idle')
- })
- it('contains a throwing status listener on both transitions', async () => {
- const ctx = await harness(new MockAdapter([textResponse('ok')]))
- const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => undefined)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- ctx.on('agent/status', (_subject, status) => {
- throw new Error(`bad ${status} listener`)
- })
- send(agent, 'go')
- await agent.whenIdle()
- expect(agent.status).toBe('idle')
- expect(warn).toHaveBeenCalledWith(
- expect.stringContaining('agent event "agent/status" listener threw'),
- )
- })
- })
|