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

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