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

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