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

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