control-queue.host.spec.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import { Context } from '@deepseek-ai/cordis'
  2. import AgentRegistry from '@deepseek-ai/dsh-agent'
  3. import type { Agent, Inbox } from '@deepseek-ai/dsh-agent'
  4. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  5. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  6. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  7. import { describe, expect, it } from 'vitest'
  8. import { SessionControlController } from '../src/control.ts'
  9. import type { SessionControlFrame } from '../src/types.ts'
  10. import { createInboxFixture } from '@deepseek-ai/dsh-agent-loop-testkit'
  11. async function harness(): Promise<{
  12. ctx: Context
  13. control: SessionControlController
  14. agent: Agent
  15. inbox: Inbox
  16. }> {
  17. const ctx = new Context()
  18. await ctx.plugin(SessionStore)
  19. await ctx.plugin(SessionProjectionRegistry)
  20. await ctx.plugin(AgentRegistry)
  21. await ctx.plugin(SessionProjectionRegistry)
  22. const session = ctx.sessions.create(SessionId('queue-session'))
  23. const agent = { id: session.id, session, inbox: undefined as never, status: 'running', ctx } as unknown as Agent
  24. Object.assign(agent, { inbox: createInboxFixture(ctx.sessionProjections, session).inbox })
  25. ctx.agents.register(agent)
  26. return { ctx, control: new SessionControlController(ctx), agent, inbox: agent.inbox }
  27. }
  28. function message(text: string, source: 'user' | 'plugin' = 'user') {
  29. return createUserMessage({
  30. content: [{ type: 'text', text }],
  31. source: source === 'user' ? { kind: 'user' } : { kind: 'plugin', plugin: 'fixture' },
  32. })
  33. }
  34. describe('Session control queue projection', () => {
  35. /** Consume frames until the next queue replacement (inbox projection frames interleave). */
  36. async function nextQueueFrame(
  37. iterator: AsyncIterator<SessionControlFrame>,
  38. ): Promise<Extract<SessionControlFrame, { type: 'queue' }>> {
  39. for (;;) {
  40. const next = await iterator.next()
  41. if (next.done) throw new Error('stream ended before a queue frame')
  42. if (next.value.type === 'queue') return next.value
  43. }
  44. }
  45. it('projects both pending lists in baselines and live replacement frames', async () => {
  46. const { control, inbox } = await harness()
  47. const queued = message('queued')
  48. const steering = message('steering')
  49. const context = message('context', 'plugin')
  50. inbox.append('next-turn', queued)
  51. inbox.append('next-step', steering)
  52. inbox.append('next-step', context)
  53. const abort = new AbortController()
  54. const iterator = control.control(abort.signal)[Symbol.asyncIterator]()
  55. const opened = await iterator.next()
  56. expect(opened.value).toMatchObject({
  57. type: 'baseline',
  58. value: {
  59. queues: {
  60. 'queue-session': [
  61. { id: queued.id, placement: 'queued' },
  62. { id: steering.id, placement: 'steering' },
  63. { id: context.id, placement: 'context' },
  64. ],
  65. },
  66. },
  67. })
  68. const replacement = message('replacement')
  69. inbox.append('next-turn', replacement)
  70. const replaced = await nextQueueFrame(iterator)
  71. expect(replaced.items.map(item => item.id)).toContain(replacement.id)
  72. inbox.remove(steering.id)
  73. const removed = await nextQueueFrame(iterator)
  74. expect(removed.items.map(item => item.id)).not.toContain(steering.id)
  75. abort.abort()
  76. await iterator.next()
  77. })
  78. it('derives queue replacements from the completed projection regardless of registration order', async () => {
  79. const ctx = new Context()
  80. await ctx.plugin(SessionStore)
  81. await ctx.plugin(AgentRegistry)
  82. const control = new SessionControlController(ctx)
  83. await ctx.plugin(SessionProjectionRegistry)
  84. const session = ctx.sessions.create(SessionId('late-projection-queue'))
  85. const agent = { id: session.id, session, inbox: undefined as never, status: 'running', ctx } as unknown as Agent
  86. Object.assign(agent, { inbox: createInboxFixture(ctx.sessionProjections, session).inbox })
  87. ctx.agents.register(agent)
  88. const abort = new AbortController()
  89. const iterator = control.control(abort.signal)[Symbol.asyncIterator]()
  90. await iterator.next()
  91. const pending = message('late projection')
  92. agent.inbox.append('next-turn', pending)
  93. await expect(iterator.next()).resolves.toMatchObject({
  94. value: {
  95. type: 'projection',
  96. key: 'inbox',
  97. value: { 'next-turn': [{ id: pending.id }], 'next-step': [] },
  98. },
  99. })
  100. await expect(nextQueueFrame(iterator)).resolves.toMatchObject({
  101. items: [{ id: pending.id, placement: 'queued' }],
  102. })
  103. abort.abort()
  104. await iterator.next()
  105. })
  106. it('projects the prompt rpcId from a user-rpc source and omits it elsewhere', async () => {
  107. const { control, inbox } = await harness()
  108. const identified = createUserMessage({
  109. content: [{ type: 'text', text: 'browser prompt' }],
  110. source: { kind: 'user', rpcId: 'req-42' as never },
  111. })
  112. inbox.append('next-turn', identified)
  113. inbox.append('next-step', message('plain steering'))
  114. const abort = new AbortController()
  115. const iterator = control.control(abort.signal)[Symbol.asyncIterator]()
  116. const opened = await iterator.next()
  117. if (opened.done || opened.value.type !== 'baseline') throw new Error('missing baseline')
  118. const items = opened.value.value.queues['queue-session' as SessionId] ?? []
  119. expect(items.map(item => ({ id: item.id, placement: item.placement, rpcId: item.rpcId }))).toEqual([
  120. { id: identified.id, placement: 'queued', rpcId: 'req-42' },
  121. { id: items[1]?.id, placement: 'steering', rpcId: undefined },
  122. ])
  123. expect('rpcId' in (items[1] ?? {})).toBe(false)
  124. abort.abort()
  125. await iterator.next()
  126. })
  127. it('ignores inbox events without the exact live Agent session', async () => {
  128. const { ctx, control, agent, inbox } = await harness()
  129. const abort = new AbortController()
  130. const iterator = control.control(abort.signal)[Symbol.asyncIterator]()
  131. await iterator.next()
  132. const unrelated = ctx.sessions.create(SessionId('unrelated-queue'))
  133. unrelated.append('agent/inbox/spliced', {
  134. target: 'next-turn',
  135. start: 0,
  136. inserted: [message('unrelated')],
  137. })
  138. const replacement = ctx.sessions.create(SessionId('replacement-session'))
  139. Object.defineProperty(agent, 'session', { configurable: true, value: replacement })
  140. inbox.append('next-turn', message('wrong-session'))
  141. abort.abort()
  142. await iterator.next()
  143. })
  144. it('drops broadcasts after cancellation has ended its queue', async () => {
  145. const { control, inbox } = await harness()
  146. const abort = new AbortController()
  147. const iterator = control.control(abort.signal)[Symbol.asyncIterator]()
  148. await iterator.next()
  149. const waiting = iterator.next()
  150. await Promise.resolve()
  151. abort.abort()
  152. inbox.append('next-turn', message('late'))
  153. await expect(waiting).resolves.toMatchObject({ done: true })
  154. })
  155. it('ends active streams on context disposal after flushing buffered frames', async () => {
  156. const { ctx, control, inbox } = await harness()
  157. const iterator = control.control(new AbortController().signal)[Symbol.asyncIterator]()
  158. await iterator.next()
  159. const first = message('first')
  160. const second = message('second')
  161. inbox.append('next-turn', first)
  162. inbox.append('next-turn', second)
  163. const queues: Extract<SessionControlFrame, { type: 'queue' }>[] = []
  164. await ctx.fiber.dispose()
  165. for (;;) {
  166. const next = await iterator.next()
  167. if (next.done) break
  168. if (next.value.type === 'queue') queues.push(next.value)
  169. }
  170. expect(queues.map(queue => queue.items.map(item => item.id))).toEqual([[first.id], [first.id, second.id]])
  171. })
  172. })