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

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