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

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