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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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, {
  8. SESSION_FORMAT_VERSION, Session, SessionId, SessionLogOffset, SessionSeq,
  9. } from '@deepseek-ai/dsh-session'
  10. import type { SessionEvent, SessionHeader, UserMessage } from '@deepseek-ai/dsh-session'
  11. import { snapshotSubagentDescriptor, SUBAGENT_DESCRIPTOR_VERSION } from '@deepseek-ai/dsh-subagent'
  12. import { subagentIdentityProjectionDefinition } from '@deepseek-ai/dsh-subagent/src/projection.ts'
  13. import { describe, expect, it, vi } from 'vitest'
  14. import { ApiSessionAgentController } from '../src/agent.ts'
  15. import { SessionCommandController } from '../src/commands.ts'
  16. import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts'
  17. async function commandHarness(
  18. childMode?: 'continuable' | 'seeded-continuable' | 'seed-only' | 'one-shot' | 'unknown' | 'corrupt',
  19. ): Promise<{
  20. ctx: Context
  21. controller: SessionCommandController
  22. agent: Agent
  23. inbox: Inbox
  24. steer: ReturnType<typeof vi.fn>
  25. cancel: ReturnType<typeof vi.fn>
  26. }> {
  27. const ctx = new Context()
  28. await ctx.plugin(SessionStore)
  29. await ctx.plugin(AgentRegistry)
  30. installSessionReadTestServices(ctx)
  31. ctx.sessionProjections.register(subagentIdentityProjectionDefinition)
  32. const sessionId = SessionId('commands-session')
  33. const ancestor = Session.create(SessionId('ancestor'))
  34. ancestor.append('subagent/descriptor', snapshotSubagentDescriptor({
  35. mode: 'continuable', provider: 'test', label: 'ancestor',
  36. }))
  37. // A seeded child inherits exactly the ancestor prefix; its own descriptor
  38. // is appended after creation, as the continuation manager does. `seed-only`
  39. // never appends one: the identity folds as continuable, but from the
  40. // inherited prefix rather than this Session's own suffix.
  41. const lineage = childMode === 'seeded-continuable' || childMode === 'seed-only'
  42. ? ancestor.snapshotEvents()
  43. : undefined
  44. const session = ctx.sessions.create(sessionId, {
  45. ...lineage === undefined ? {} : { seed: lineage, inheritedEventCount: SessionLogOffset(lineage.length) },
  46. meta: {
  47. cwd: '/workspace',
  48. ...(childMode === undefined ? {} : {
  49. origin: 'subagent' as const,
  50. parentSession: SessionId('offline-parent'),
  51. }),
  52. ...lineage === undefined ? {} : { isSeeded: true },
  53. },
  54. })
  55. if (childMode === 'continuable' || childMode === 'seeded-continuable') {
  56. session.append('subagent/descriptor', snapshotSubagentDescriptor({
  57. mode: 'continuable', provider: 'test', label: 'child',
  58. }))
  59. } else if (childMode === 'one-shot') {
  60. session.append('subagent/descriptor', snapshotSubagentDescriptor({
  61. mode: 'one-shot', provider: 'test', label: 'child',
  62. }))
  63. } else if (childMode === 'corrupt') {
  64. session.append('subagent/descriptor', {
  65. version: SUBAGENT_DESCRIPTOR_VERSION,
  66. mode: 'continuable',
  67. provider: 1,
  68. } as never)
  69. }
  70. const inbox = new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} })
  71. const steer = vi.fn((message: UserMessage) => { inbox.append('next-step', message) })
  72. const cancel = vi.fn()
  73. const agent = {
  74. id: session.id,
  75. session,
  76. inbox,
  77. status: 'running',
  78. ctx,
  79. steer,
  80. followup: vi.fn(),
  81. cancel,
  82. } as unknown as Agent
  83. ctx.agents.register(agent)
  84. ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never)
  85. ctx.provide('agentDefaultModel', {
  86. currentSelection: () => ({ provider: 'fixture', model: 'fixture-model' }),
  87. saveSelection: () => Promise.resolve(),
  88. } as never)
  89. const selection: ModelSelectionRef = {
  90. current: { provider: 'fixture', model: 'fixture-model' },
  91. assembled: undefined,
  92. }
  93. const agents = {
  94. resolveAgent: () => Promise.resolve({ agent }),
  95. selectionFor: () => selection,
  96. serializeImageAdmission: <Value>(_agent: Agent, operation: () => Promise<Value>) => operation(),
  97. composeAgent: () => Promise.resolve({ setup: () => {} }),
  98. } as unknown as ApiSessionAgentController
  99. return {
  100. ctx,
  101. controller: new SessionCommandController(ctx, agents, '/workspace'),
  102. agent,
  103. inbox,
  104. steer,
  105. cancel,
  106. }
  107. }
  108. async function expectFailure(operation: Promise<unknown>, code: string): Promise<void> {
  109. await expect(operation).rejects.toMatchObject({ code })
  110. }
  111. describe('Session queue commands', () => {
  112. it('edits, removes, steers, and rejects stale queue occurrences', async () => {
  113. const { ctx, controller, agent, inbox, steer, cancel } = await commandHarness()
  114. const queued = createUserMessage({ content: [{ type: 'text', text: 'queued' }], source: { kind: 'user' } })
  115. const nextStep = createUserMessage({ content: [{ type: 'text', text: 'step' }], source: { kind: 'user' } })
  116. inbox.append('next-turn', queued)
  117. inbox.append('next-step', nextStep)
  118. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  119. sessionId: agent.id,
  120. itemId: queued.id,
  121. action: {
  122. kind: 'edit',
  123. content: [{
  124. type: 'image',
  125. attachment: {
  126. attachmentId: AttachmentId('att-edit'), mediaType: 'image/png', bytes: 1, width: 1, height: 1,
  127. },
  128. }],
  129. },
  130. })), 'session/attachment-invalid')
  131. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  132. sessionId: SessionId('missing'), itemId: queued.id, action: { kind: 'remove' },
  133. })), 'session/queue-item-not-found')
  134. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  135. sessionId: agent.id, itemId: MessageId('missing'), action: { kind: 'remove' },
  136. })), 'session/queue-item-not-found')
  137. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  138. sessionId: agent.id, itemId: nextStep.id, action: { kind: 'steer' },
  139. })), 'session/steer-unavailable')
  140. Object.assign(agent, { status: 'idle' })
  141. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  142. sessionId: agent.id, itemId: queued.id, action: { kind: 'steer' },
  143. })), 'session/steer-unavailable')
  144. expect(controller.updateQueue({
  145. sessionId: agent.id,
  146. itemId: queued.id,
  147. action: { kind: 'edit', content: [{ type: 'text', text: 'edited' }] },
  148. })).toEqual({ accepted: true })
  149. expect(inbox.nextTurn[0]?.content).toEqual([{ type: 'text', text: 'edited' }])
  150. // An edit rewrites content in place, so the occurrence a client addressed
  151. // by id stays addressable.
  152. expect(inbox.nextTurn[0]?.id).toBe(queued.id)
  153. expect(controller.updateQueue({
  154. sessionId: agent.id, itemId: nextStep.id, action: { kind: 'remove' },
  155. })).toEqual({ accepted: true })
  156. Object.assign(agent, { status: 'running' })
  157. const steered = inbox.nextTurn[0]
  158. if (steered === undefined) throw new Error('missing edited queue item')
  159. expect(controller.updateQueue({
  160. sessionId: agent.id, itemId: steered.id, action: { kind: 'steer' },
  161. })).toEqual({ accepted: true })
  162. expect(steer).toHaveBeenCalledWith(steered)
  163. const queuedFile = createUserMessage({
  164. content: [{
  165. type: 'file',
  166. attachment: { attachmentId: AttachmentId('file-queued'), name: 'queued.txt', bytes: 6 },
  167. }],
  168. source: { kind: 'user', rpcId: 'file-rpc' as never },
  169. })
  170. inbox.append('next-turn', queuedFile)
  171. expect(controller.updateQueue({
  172. sessionId: agent.id, itemId: queuedFile.id, action: { kind: 'steer' },
  173. })).toEqual({ accepted: true })
  174. expect(steer).toHaveBeenLastCalledWith(queuedFile)
  175. expect(queuedFile).toMatchObject({
  176. source: { kind: 'user', rpcId: 'file-rpc' },
  177. content: [{ type: 'file', attachment: { name: 'queued.txt', bytes: 6 } }],
  178. })
  179. await expectFailure(Promise.resolve().then(() => controller.cancel({
  180. sessionId: SessionId('missing'),
  181. })), 'session/not-found')
  182. expect(controller.cancel({ sessionId: agent.id })).toEqual({ accepted: true })
  183. expect(cancel).toHaveBeenCalledWith({ kind: 'user' }, { keepInbox: true })
  184. await ctx.fiber.dispose()
  185. })
  186. it.each(['continuable', 'seeded-continuable'] as const)(
  187. 'mutates both inbox destinations of a live %s child while its parent is offline',
  188. async (childMode) => {
  189. const { ctx, controller, agent, inbox, steer } = await commandHarness(childMode)
  190. const queued = createUserMessage({
  191. content: [{ type: 'text', text: 'queued' }], source: { kind: 'user' },
  192. })
  193. const context = createUserMessage({
  194. content: [{ type: 'text', text: 'context' }], source: { kind: 'plugin', plugin: 'test' },
  195. })
  196. inbox.append('next-turn', queued)
  197. inbox.append('next-step', context)
  198. expect(controller.updateQueue({
  199. sessionId: agent.id,
  200. itemId: context.id,
  201. action: { kind: 'edit', content: [{ type: 'text', text: 'edited context' }] },
  202. })).toEqual({ accepted: true })
  203. const editedContext = inbox.nextStep[0]
  204. expect(editedContext).toMatchObject({
  205. content: [{ type: 'text', text: 'edited context' }],
  206. source: context.source,
  207. })
  208. expect(editedContext?.id).toBe(context.id)
  209. if (editedContext === undefined) throw new Error('missing edited context')
  210. expect(controller.updateQueue({
  211. sessionId: agent.id, itemId: editedContext.id, action: { kind: 'remove' },
  212. })).toEqual({ accepted: true })
  213. expect(controller.updateQueue({
  214. sessionId: agent.id, itemId: queued.id, action: { kind: 'steer' },
  215. })).toEqual({ accepted: true })
  216. expect(steer).toHaveBeenCalledWith(queued)
  217. await ctx.fiber.dispose()
  218. },
  219. )
  220. it('removes the selected message before handing it to Agent steering', async () => {
  221. const { ctx, controller, agent, inbox, steer } = await commandHarness('continuable')
  222. const first = createUserMessage({
  223. content: [{ type: 'text', text: 'first' }], source: { kind: 'user' },
  224. })
  225. const second = createUserMessage({
  226. content: [{ type: 'text', text: 'second' }], source: { kind: 'user' },
  227. })
  228. inbox.append('next-turn', first)
  229. inbox.append('next-turn', second)
  230. // Stand in for the Agent's cancellation-convergence destination; the
  231. // command must accept whichever boundary `Agent.steer()` selects.
  232. steer.mockImplementation((message: UserMessage) => { inbox.append('next-turn', message) })
  233. expect(controller.updateQueue({
  234. sessionId: agent.id, itemId: first.id, action: { kind: 'steer' },
  235. })).toEqual({ accepted: true })
  236. expect(steer).toHaveBeenCalledWith(first)
  237. // Ordering proves the removal happened before delivery rather than after.
  238. expect(inbox.nextTurn).toEqual([second, first])
  239. expect(inbox.nextStep).toEqual([])
  240. await ctx.fiber.dispose()
  241. })
  242. it('keeps one-shot, seed-only, missing, and malformed child descriptors behind the ownership fence', async () => {
  243. for (const mode of ['one-shot', 'seed-only', 'unknown', 'corrupt'] as const) {
  244. const { ctx, controller, agent, inbox } = await commandHarness(mode)
  245. const queued = createUserMessage({
  246. content: [{ type: 'text', text: mode }], source: { kind: 'user' },
  247. })
  248. inbox.append('next-turn', queued)
  249. await expectFailure(Promise.resolve().then(() => controller.updateQueue({
  250. sessionId: agent.id, itemId: queued.id, action: { kind: 'remove' },
  251. })), 'session/agent-busy')
  252. expect(inbox.nextTurn).toEqual([queued])
  253. await ctx.fiber.dispose()
  254. }
  255. })
  256. })
  257. function imageRef(id: string): ImageAttachmentRef {
  258. return {
  259. attachmentId: AttachmentId(id),
  260. mediaType: 'image/png',
  261. bytes: 1,
  262. width: 1,
  263. height: 1,
  264. }
  265. }
  266. function event(type: string, seq: SessionSeq, data: unknown): SessionEvent {
  267. return { type, seq, time: seq + 1, data } as SessionEvent
  268. }
  269. async function persistedController(
  270. events: SessionEvent[],
  271. readImage: (ref: ImageAttachmentRef) => Promise<{ ref: ImageAttachmentRef; data: Uint8Array }>,
  272. ): Promise<{ ctx: Context; controller: SessionCommandController; sessionId: SessionId }> {
  273. const ctx = new Context()
  274. await ctx.plugin(SessionStore)
  275. const sessionId = SessionId('cold-attachment')
  276. const meta: SessionHeader = {
  277. version: SESSION_FORMAT_VERSION,
  278. id: sessionId,
  279. createdAt: 1,
  280. cwd: '/workspace',
  281. isSeeded: false,
  282. }
  283. ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
  284. list: () => Promise.resolve([meta]),
  285. inspect: () => Promise.resolve({
  286. meta,
  287. inheritedEventCount: SessionLogOffset(0),
  288. events,
  289. }),
  290. }) as never)
  291. installSessionReadTestServices(ctx)
  292. ctx.provide('attachments', { readImage } as never)
  293. const agents = { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController
  294. return { ctx, controller: new SessionCommandController(ctx, agents, '/workspace'), sessionId }
  295. }
  296. describe('Session attachment authorization', () => {
  297. it('finds references in direct, message, inserted, nested, and streamed content', async () => {
  298. const nested = imageRef('nested')
  299. const message = imageRef('message')
  300. const inserted = imageRef('inserted')
  301. const streamed = imageRef('streamed')
  302. const events = [
  303. { ...event('fixture/direct', SessionSeq(0), {
  304. content: [null, [], { type: 'tool-result', content: [{ type: 'text', text: 'none' }] }, {
  305. type: 'tool-result', content: [{ type: 'image', attachment: nested }],
  306. }],
  307. }), ignorable: true as const },
  308. { ...event('assistant/message', SessionSeq(1), {
  309. turn: 1,
  310. step: 1,
  311. stream: [],
  312. message: createAssistantMessage({
  313. content: [{ type: 'image', attachment: message }],
  314. source: { provider: 'fixture', model: 'fixture' },
  315. }),
  316. }), surfaceOp: 'append' as const },
  317. event('agent/inbox/spliced', SessionSeq(2), {
  318. target: 'next-turn',
  319. start: 0,
  320. inserted: [createUserMessage({
  321. content: [{ type: 'image', attachment: inserted }],
  322. source: { kind: 'user' },
  323. })],
  324. }),
  325. event('assistant/attempt', SessionSeq(3), {
  326. turn: 1,
  327. step: 1,
  328. stream: [
  329. {
  330. type: 'chunk',
  331. time: 3,
  332. chunk: { type: 'block-start', index: 0, blockType: 'text' },
  333. },
  334. {
  335. type: 'chunk',
  336. time: 3,
  337. chunk: { type: 'block-end', index: 0, block: { type: 'text', text: '' } },
  338. },
  339. ],
  340. }),
  341. event('assistant/attempt', SessionSeq(4), {
  342. turn: 1,
  343. step: 1,
  344. stream: [{
  345. type: 'chunk',
  346. time: 4,
  347. chunk: { type: 'block-end', index: 0, block: { type: 'image', attachment: streamed } },
  348. }],
  349. }),
  350. ]
  351. const readImage = vi.fn((ref: ImageAttachmentRef) => Promise.resolve({ ref, data: Uint8Array.of(1) }))
  352. const { ctx, controller, sessionId } = await persistedController(events, readImage)
  353. for (const ref of [nested, message, inserted, streamed]) {
  354. await expect(controller.attachment({ sessionId, attachmentId: ref.attachmentId }))
  355. .resolves.toEqual({ attachment: ref, data: 'AQ==' })
  356. }
  357. expect(readImage).toHaveBeenCalledTimes(4)
  358. await ctx.fiber.dispose()
  359. })
  360. it('maps missing persistence identities and attachment backend failures', async () => {
  361. const noPersistence = new Context()
  362. await noPersistence.plugin(SessionStore)
  363. installSessionReadTestServices(noPersistence)
  364. const noPersistenceController = new SessionCommandController(
  365. noPersistence,
  366. { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController,
  367. '/workspace',
  368. )
  369. await expectFailure(noPersistenceController.attachment({
  370. sessionId: SessionId('missing'), attachmentId: AttachmentId('att'),
  371. }), 'session/not-found')
  372. const missing = new Context()
  373. await missing.plugin(SessionStore)
  374. missing.provide('sessionPersistence', testSessionPersistence(missing, {
  375. list: () => Promise.resolve([]),
  376. inspect: vi.fn(),
  377. }) as never)
  378. installSessionReadTestServices(missing)
  379. const missingController = new SessionCommandController(
  380. missing,
  381. { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController,
  382. '/workspace',
  383. )
  384. await expectFailure(missingController.attachment({
  385. sessionId: SessionId('missing'), attachmentId: 'att' as never,
  386. }), 'session/not-found')
  387. for (const thrown of [
  388. new AttachmentError('stored image is unavailable', 'ATTACHMENT_NOT_FOUND'),
  389. new Error('backend offline'),
  390. ]) {
  391. const ref = imageRef(`failure-${thrown.name}`)
  392. const fixture = await persistedController(
  393. [event('fixture/content', SessionSeq(0), { content: [{ type: 'image', attachment: ref }] })],
  394. () => Promise.reject(thrown),
  395. )
  396. await expectFailure(fixture.controller.attachment({
  397. sessionId: fixture.sessionId,
  398. attachmentId: ref.attachmentId,
  399. }), thrown instanceof AttachmentError ? 'session/attachment-invalid' : 'gateway/internal')
  400. await fixture.ctx.fiber.dispose()
  401. }
  402. })
  403. it('maps a cold observation failure to an internal authorization error', async () => {
  404. const ctx = new Context()
  405. await ctx.plugin(SessionStore)
  406. installSessionReadTestServices(ctx)
  407. vi.spyOn(ctx.sessionQuery, 'observeSession').mockRejectedValue(new Error('storage offline'))
  408. const controller = new SessionCommandController(
  409. ctx,
  410. { resolveAgent: vi.fn() } as unknown as ApiSessionAgentController,
  411. '/workspace',
  412. )
  413. await expectFailure(controller.attachment({
  414. sessionId: SessionId('unreadable'), attachmentId: AttachmentId('att'),
  415. }), 'gateway/internal')
  416. await ctx.fiber.dispose()
  417. })
  418. })