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

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