commands-queue-attachment.host.spec.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import { Context } from '@deepseek-ai/cordis'
  2. import AgentRegistry, { agentEvents, Inbox } from '@deepseek-ai/dsh-agent'
  3. import type { Agent, ModelSelectionRef } from '@deepseek-ai/dsh-agent'
  4. import { AttachmentError, AttachmentId } from '@deepseek-ai/dsh-attachment'
  5. import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
  6. import { createUserMessage, MessageId } from '@deepseek-ai/dsh-llm'
  7. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  8. import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
  9. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  10. import { describe, expect, it, vi } from 'vitest'
  11. import { ApiSessionAgentController } from '../src/agent.ts'
  12. import { SessionCommandController } from '../src/commands.ts'
  13. async function commandHarness(): Promise<{
  14. ctx: Context
  15. controller: SessionCommandController
  16. agent: Agent
  17. inbox: Inbox
  18. steer: ReturnType<typeof vi.fn>
  19. cancel: ReturnType<typeof vi.fn>
  20. }> {
  21. const ctx = new Context()
  22. await ctx.plugin(SessionStore)
  23. await ctx.plugin(SessionProjectionRegistry)
  24. await ctx.plugin(AgentRegistry)
  25. const session = ctx.sessions.create(SessionId('commands-session'), { meta: { cwd: '/workspace' } })
  26. const steer = vi.fn()
  27. const cancel = vi.fn()
  28. const agent = {
  29. id: session.id,
  30. session,
  31. inbox: undefined as never,
  32. status: 'running',
  33. ctx,
  34. steer,
  35. followup: vi.fn(),
  36. cancel,
  37. } as unknown as Agent
  38. Object.assign(agent, { inbox: new Inbox(ctx, agent.session, agentEvents(ctx, agent)) })
  39. ctx.agents.register(agent)
  40. ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never)
  41. ctx.provide('agentDefaultModel', {
  42. currentSelection: () => ({ provider: 'fixture', model: 'fixture-model' }),
  43. saveSelection: () => Promise.resolve(),
  44. } as never)
  45. const selection: ModelSelectionRef = {
  46. current: { provider: 'fixture', model: 'fixture-model' },
  47. assembled: undefined,
  48. }
  49. const agents = {
  50. resolveAgent: () => Promise.resolve({ agent }),
  51. selectionFor: () => selection,
  52. serializeImageAdmission: <Value>(_agent: Agent, operation: () => Promise<Value>) => operation(),
  53. composeAgent: () => Promise.resolve({ setup: () => {} }),
  54. } as unknown as ApiSessionAgentController
  55. return { ctx, controller: new SessionCommandController(ctx, agents, '/workspace'), agent, inbox: agent.inbox, steer, cancel }
  56. }
  57. async function expectFailure(operation: Promise<unknown>, code: string): Promise<void> {
  58. await expect(operation).rejects.toMatchObject({ failure: { code } })
  59. }
  60. describe('Session queue commands', () => {
  61. it('edits, removes, steers, and rejects stale queue occurrences', async () => {
  62. const { ctx, controller, agent, inbox, steer, cancel } = await commandHarness()
  63. const queued = createUserMessage({ content: [{ type: 'text', text: 'queued' }], source: { kind: 'user' } })
  64. const nextStep = createUserMessage({ content: [{ type: 'text', text: 'step' }], source: { kind: 'user' } })
  65. inbox.append('next-turn', queued)
  66. inbox.append('next-step', nextStep)
  67. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  68. sessionId: agent.id,
  69. itemId: queued.id,
  70. action: {
  71. kind: 'edit',
  72. content: [{
  73. type: 'image',
  74. attachment: {
  75. attachmentId: AttachmentId('att-edit'), mediaType: 'image/png', bytes: 1, width: 1, height: 1,
  76. },
  77. }],
  78. },
  79. })), 'attachment-error')
  80. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  81. sessionId: SessionId('missing'), itemId: queued.id, action: { kind: 'remove' },
  82. })), 'queue-item-not-found')
  83. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  84. sessionId: agent.id, itemId: MessageId('missing'), action: { kind: 'remove' },
  85. })), 'queue-item-not-found')
  86. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  87. sessionId: agent.id, itemId: nextStep.id, action: { kind: 'steer' },
  88. })), 'steer-unavailable')
  89. Object.assign(agent, { status: 'idle' })
  90. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  91. sessionId: agent.id, itemId: queued.id, action: { kind: 'steer' },
  92. })), 'steer-unavailable')
  93. expect(controller.updateQueue({
  94. sessionId: agent.id,
  95. itemId: queued.id,
  96. action: { kind: 'edit', content: [{ type: 'text', text: 'edited' }] },
  97. })).toEqual({ accepted: true })
  98. expect(inbox.nextTurn[0]?.content).toEqual([{ type: 'text', text: 'edited' }])
  99. expect(controller.updateQueue({
  100. sessionId: agent.id, itemId: nextStep.id, action: { kind: 'remove' },
  101. })).toEqual({ accepted: true })
  102. Object.assign(agent, { status: 'running' })
  103. const steered = inbox.nextTurn[0]
  104. if (steered === undefined) throw new Error('missing edited queue item')
  105. expect(controller.updateQueue({
  106. sessionId: agent.id, itemId: steered.id, action: { kind: 'steer' },
  107. })).toEqual({ accepted: true })
  108. expect(steer).toHaveBeenCalledWith(steered)
  109. await expectFailure(Promise.resolve().then(() => controller.cancel({
  110. sessionId: SessionId('missing'),
  111. })), 'session-not-found')
  112. expect(controller.cancel({ sessionId: agent.id })).toEqual({ accepted: true })
  113. expect(cancel).toHaveBeenCalledWith({ kind: 'user' }, { keepInbox: true })
  114. await ctx.fiber.dispose()
  115. })
  116. })
  117. function imageRef(id: string): ImageAttachmentRef {
  118. return {
  119. attachmentId: AttachmentId(id),
  120. mediaType: 'image/png',
  121. bytes: 1,
  122. width: 1,
  123. height: 1,
  124. }
  125. }
  126. function event(type: string, seq: number, data: unknown): SessionEvent {
  127. return { type, seq, time: seq + 1, data } as SessionEvent
  128. }
  129. async function persistedController(
  130. events: SessionEvent[],
  131. readImage: (ref: ImageAttachmentRef) => Promise<{ ref: ImageAttachmentRef; data: Uint8Array }>,
  132. ): Promise<{ ctx: Context; controller: SessionCommandController; sessionId: SessionId }> {
  133. const ctx = new Context()
  134. await ctx.plugin(SessionStore)
  135. const sessionId = SessionId('cold-attachment')
  136. const meta: SessionHeader = { version: 0, id: sessionId, createdAt: 1, cwd: '/workspace' }
  137. ctx.provide('sessionPersistence', {
  138. list: () => Promise.resolve([meta]),
  139. inspect: () => Promise.resolve({ meta, events }),
  140. } as never)
  141. ctx.provide('attachments', { readImage } as never)
  142. const agents = { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController
  143. return { ctx, controller: new SessionCommandController(ctx, agents, '/workspace'), sessionId }
  144. }
  145. describe('Session attachment authorization', () => {
  146. it('finds references in direct, message, inserted, nested, and streamed content', async () => {
  147. const nested = imageRef('nested')
  148. const message = imageRef('message')
  149. const inserted = imageRef('inserted')
  150. const streamed = imageRef('streamed')
  151. const events = [
  152. event('fixture/direct', 0, {
  153. content: [null, [], { type: 'tool-result', content: [{ type: 'text', text: 'none' }] }, {
  154. type: 'tool-result', content: [{ type: 'image', attachment: nested }],
  155. }],
  156. }),
  157. event('assistant/message', 1, { message: { content: [{ type: 'image', attachment: message }] } }),
  158. event('agent/inbox/spliced', 2, { inserted: [{ content: [{ type: 'image', attachment: inserted }] }] }),
  159. event('assistant/chunk', 3, {
  160. chunk: { type: 'block-end', block: { type: 'image', attachment: streamed } },
  161. }),
  162. ]
  163. const readImage = vi.fn((ref: ImageAttachmentRef) => Promise.resolve({ ref, data: Uint8Array.of(1) }))
  164. const { ctx, controller, sessionId } = await persistedController(events, readImage)
  165. for (const ref of [nested, message, inserted, streamed]) {
  166. await expect(controller.attachment({ sessionId, attachmentId: ref.attachmentId }))
  167. .resolves.toEqual({ attachment: ref, data: 'AQ==' })
  168. }
  169. expect(readImage).toHaveBeenCalledTimes(4)
  170. await ctx.fiber.dispose()
  171. })
  172. it('maps missing persistence identities and attachment backend failures', async () => {
  173. const noPersistence = new Context()
  174. await noPersistence.plugin(SessionStore)
  175. const noPersistenceController = new SessionCommandController(
  176. noPersistence,
  177. { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController,
  178. '/workspace',
  179. )
  180. await expectFailure(noPersistenceController.attachment({
  181. sessionId: SessionId('missing'), attachmentId: AttachmentId('att'),
  182. }), 'internal')
  183. const missing = new Context()
  184. await missing.plugin(SessionStore)
  185. missing.provide('sessionPersistence', {
  186. list: () => Promise.resolve([]),
  187. inspect: vi.fn(),
  188. } as never)
  189. const missingController = new SessionCommandController(
  190. missing,
  191. { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController,
  192. '/workspace',
  193. )
  194. await expectFailure(missingController.attachment({
  195. sessionId: SessionId('missing'), attachmentId: 'att' as never,
  196. }), 'session-not-found')
  197. for (const thrown of [
  198. new AttachmentError('stored image is unavailable', 'ATTACHMENT_NOT_FOUND'),
  199. new Error('backend offline'),
  200. ]) {
  201. const ref = imageRef(`failure-${thrown.name}`)
  202. const fixture = await persistedController(
  203. [event('fixture/content', 0, { content: [{ type: 'image', attachment: ref }] })],
  204. () => Promise.reject(thrown),
  205. )
  206. await expectFailure(fixture.controller.attachment({
  207. sessionId: fixture.sessionId,
  208. attachmentId: ref.attachmentId,
  209. }), thrown instanceof AttachmentError ? 'attachment-error' : 'internal')
  210. await fixture.ctx.fiber.dispose()
  211. }
  212. })
  213. })