session-export.spec.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /**
  2. * session.export host path: the GET download endpoint streams a ZIP whose
  3. * files are the stored artifacts verbatim (root + optional descendants), and
  4. * the degenerate compositions fail loudly (missing services → 500, missing
  5. * root → 404, missing descendant → errored stream).
  6. */
  7. import { randomBytes } from 'node:crypto'
  8. import { describe, expect, it, vi } from 'vitest'
  9. import { Context } from '@deepseek-ai/cordis'
  10. import { unzipSync, strFromU8 } from 'fflate'
  11. import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'
  12. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  13. import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
  14. import type { SessionLineageNode } from '@deepseek-ai/dsh-session-query'
  15. import type { SessionRawArtifact } from '@deepseek-ai/dsh-session-persistence'
  16. import ApiProxyService, { createApiProxy, toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy'
  17. const sid = (id: string): SessionId => id as SessionId
  18. function header(id: string, parentSession?: SessionId): SessionHeader {
  19. return {
  20. version: 0,
  21. id: sid(id),
  22. createdAt: 1000,
  23. cwd: '/proj',
  24. ...parentSession === undefined ? {} : { parentSession },
  25. delegationDepth: parentSession === undefined ? 0 : 1,
  26. }
  27. }
  28. function artifact(id: string, parentSession?: SessionId, content?: string): SessionRawArtifact {
  29. return {
  30. meta: header(id, parentSession),
  31. filename: 'session.jsonl',
  32. content: content ?? `{"type":"session","version":0,"id":"${id}","createdAt":1000}\n{"type":"turn/start","seq":0,"time":2000,"data":{"turn":1}}\n`,
  33. }
  34. }
  35. function node(id: string, ...descendants: SessionLineageNode[]): SessionLineageNode {
  36. return { session: { header: header(id, sid('session-root')), live: false, persisted: true }, descendants }
  37. }
  38. /** One durable image object served by the fake attachment store. */
  39. function storedImage(id: string, mediaType: ImageAttachmentRef['mediaType'] = 'image/png') {
  40. return {
  41. ref: { attachmentId: sid(id), mediaType, bytes: 4, width: 2, height: 2 } as unknown as ImageAttachmentRef,
  42. data: new Uint8Array([1, 2, 3, 4]),
  43. }
  44. }
  45. /** A user/message event line carrying one image reference. */
  46. function imageEventLine(id: string, mediaType: ImageAttachmentRef['mediaType'] = 'image/png'): string {
  47. return `{"type":"user/message","seq":1,"time":1000,"data":{"content":[{"type":"image","attachment":{"attachmentId":"${id}","mediaType":"${mediaType}","bytes":4,"width":2,"height":2}}]}}`
  48. }
  49. async function buildApi(
  50. artifacts: Record<string, SessionRawArtifact>,
  51. descendants: SessionLineageNode[] = [],
  52. services: {
  53. query?: boolean
  54. persistence?: boolean | 'throw' | 'unsupported'
  55. attachments?: boolean | ((ref: ImageAttachmentRef, signal?: AbortSignal) => Promise<ReturnType<typeof storedImage>>)
  56. sessions?: {
  57. get(id: SessionId): { readonly id: SessionId } | undefined
  58. flush(session: { readonly id: SessionId }): Promise<boolean>
  59. }
  60. readRaw?: (id: SessionId, signal?: AbortSignal) => Promise<SessionRawArtifact | undefined>
  61. traceSession?: (id: SessionId, signal?: AbortSignal) => Promise<{
  62. target: { header: SessionHeader; live: boolean; persisted: boolean }
  63. ancestors: readonly SessionLineageNode[]
  64. complete: boolean
  65. root: { header: SessionHeader; live: boolean; persisted: boolean }
  66. descendants: readonly SessionLineageNode[]
  67. }>
  68. compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
  69. } = {},
  70. ) {
  71. const ctx = new Context()
  72. await ctx.plugin(UserInteractionService)
  73. const query = services.query ?? true
  74. const persistence = services.persistence ?? true
  75. if (query) {
  76. ctx.provide('sessionQuery', {
  77. traceSession: services.traceSession ?? (async () => ({
  78. target: { header: header('session-root'), live: false, persisted: true },
  79. ancestors: [],
  80. complete: true,
  81. root: { header: header('session-root'), live: false, persisted: true },
  82. descendants,
  83. })),
  84. } as never)
  85. }
  86. if (persistence) {
  87. ctx.provide('sessionPersistence', {
  88. supportsRawArtifacts: persistence !== 'unsupported',
  89. readRaw: services.readRaw ?? (async (id: SessionId) => {
  90. if (persistence === 'throw') throw new Error('/host/private/session.jsonl')
  91. return artifacts[id]
  92. }),
  93. } as never)
  94. }
  95. if (services.attachments !== false) {
  96. const readImage = typeof services.attachments === 'function'
  97. ? services.attachments
  98. : async (ref: ImageAttachmentRef) => storedImage(String(ref.attachmentId), ref.mediaType)
  99. ctx.provide('attachments', {
  100. imageLimits: {} as never,
  101. validateImage: async () => {},
  102. saveImage: async () => { throw new Error('export never saves images') },
  103. readImage,
  104. } as never)
  105. }
  106. if (services.sessions !== undefined) ctx.provide('sessions', services.sessions as never)
  107. return createApiProxy(ctx, {
  108. defaultModelSelection: () => ({ provider: 'p', model: 'm' }),
  109. cwd: '/tmp',
  110. ...services.compressionLevel === undefined
  111. ? {}
  112. : { sessionExportCompressionLevel: services.compressionLevel },
  113. })
  114. }
  115. async function responseBytes(response: Response): Promise<Uint8Array> {
  116. return new Uint8Array(await response.arrayBuffer())
  117. }
  118. describe('session export compression config', () => {
  119. it('defaults to level 6 and rejects values outside the integer 0-9 range', () => {
  120. expect(ApiProxyService.Config({})).toEqual({ sessionExportCompressionLevel: 6 })
  121. expect(ApiProxyService.Config({ sessionExportCompressionLevel: 0 }))
  122. .toEqual({ sessionExportCompressionLevel: 0 })
  123. expect(ApiProxyService.Config({ sessionExportCompressionLevel: 9 }))
  124. .toEqual({ sessionExportCompressionLevel: 9 })
  125. for (const value of [-1, 10, 1.5]) {
  126. expect(() => ApiProxyService.Config({ sessionExportCompressionLevel: value } as never)).toThrow()
  127. }
  128. })
  129. })
  130. describe('session.export download endpoint', () => {
  131. it('streams a ZIP with the root artifact verbatim under its original filename', async () => {
  132. const api = await buildApi({ 'session-root': artifact('session-root') })
  133. const response = await toFetchHandler(api).fetch(
  134. new Request('http://host/api/session.export?sessionId=session-root'),
  135. )
  136. expect(response.status).toBe(200)
  137. expect(response.headers.get('content-type')).toBe('application/zip')
  138. expect(response.headers.get('content-disposition')).toContain('dsh-session-session-root.zip')
  139. const files = unzipSync(await responseBytes(response))
  140. expect(Object.keys(files)).toEqual(['session.jsonl'])
  141. expect(strFromU8(files['session.jsonl'] as Uint8Array)).toBe(artifact('session-root').content)
  142. })
  143. it('uses the resolved compression level for ZIP entries', async () => {
  144. const root = artifact('session-root', undefined, 'compressible\n'.repeat(32 * 1024))
  145. const storedApi = await buildApi({ 'session-root': root }, [], { compressionLevel: 0 })
  146. const compressedApi = await buildApi({ 'session-root': root }, [], { compressionLevel: 9 })
  147. const stored = await storedApi.downloads.sessionLog(
  148. { sessionId: sid('session-root'), includeDescendants: false },
  149. new AbortController().signal,
  150. )
  151. const compressed = await compressedApi.downloads.sessionLog(
  152. { sessionId: sid('session-root'), includeDescendants: false },
  153. new AbortController().signal,
  154. )
  155. const storedBytes = await responseBytes(stored)
  156. const compressedBytes = await responseBytes(compressed)
  157. expect(compressedBytes.byteLength).toBeLessThan(storedBytes.byteLength)
  158. expect(strFromU8(unzipSync(compressedBytes)['session.jsonl'] as Uint8Array)).toBe(root.content)
  159. })
  160. it('includes descendant artifacts under subagents/<id>/ when requested', async () => {
  161. const api = await buildApi({
  162. 'session-root': artifact('session-root'),
  163. 'child-a': artifact('child-a', sid('session-root')),
  164. 'grandchild-a': artifact('grandchild-a', sid('child-a')),
  165. }, [
  166. node('child-a', node('grandchild-a')),
  167. ])
  168. const response = await toFetchHandler(api).fetch(
  169. new Request('http://host/api/session.export?sessionId=session-root&includeDescendants=true'),
  170. )
  171. expect(response.status).toBe(200)
  172. const files = unzipSync(await responseBytes(response))
  173. expect(Object.keys(files).sort()).toEqual([
  174. 'session.jsonl',
  175. 'subagents/child-a/session.jsonl',
  176. 'subagents/grandchild-a/session.jsonl',
  177. ])
  178. expect(strFromU8(files['subagents/child-a/session.jsonl'] as Uint8Array))
  179. .toBe(artifact('child-a').content)
  180. })
  181. it('flushes each live root and descendant immediately before reading its artifact', async () => {
  182. const stored: Record<string, SessionRawArtifact> = {
  183. 'session-root': artifact('session-root', undefined, 'stale root'),
  184. 'child-a': artifact('child-a', sid('session-root'), 'stale child'),
  185. }
  186. const durable: Record<string, SessionRawArtifact> = {
  187. 'session-root': artifact('session-root', undefined, 'durable root'),
  188. 'child-a': artifact('child-a', sid('session-root'), 'durable child'),
  189. }
  190. const flushed: SessionId[] = []
  191. const api = await buildApi(stored, [node('child-a')], {
  192. sessions: {
  193. get: id => durable[id] === undefined ? undefined : { id },
  194. flush: async (session) => {
  195. const artifactAfterFlush = durable[session.id]
  196. if (artifactAfterFlush === undefined) throw new Error('unexpected session')
  197. flushed.push(session.id)
  198. stored[session.id] = artifactAfterFlush
  199. return true
  200. },
  201. },
  202. })
  203. const response = await toFetchHandler(api).fetch(
  204. new Request('http://host/api/session.export?sessionId=session-root&includeDescendants=true'),
  205. )
  206. const files = unzipSync(await responseBytes(response))
  207. expect(flushed).toEqual([sid('session-root'), sid('child-a')])
  208. expect(strFromU8(files['session.jsonl'] as Uint8Array)).toBe('durable root')
  209. expect(strFromU8(files['subagents/child-a/session.jsonl'] as Uint8Array)).toBe('durable child')
  210. })
  211. it('reads a cold artifact without asking the live-session store to flush', async () => {
  212. const flush = vi.fn(async () => true)
  213. const root = artifact('session-root')
  214. const api = await buildApi({ 'session-root': root }, [], {
  215. sessions: {
  216. get: () => undefined,
  217. flush,
  218. },
  219. })
  220. const response = await api.downloads.sessionLog(
  221. { sessionId: sid('session-root'), includeDescendants: false },
  222. new AbortController().signal,
  223. )
  224. const files = unzipSync(await responseBytes(response))
  225. expect(flush).not.toHaveBeenCalled()
  226. expect(strFromU8(files['session.jsonl'] as Uint8Array)).toBe(root.content)
  227. })
  228. it('answers 404 for a missing root session', async () => {
  229. const api = await buildApi({})
  230. const response = await toFetchHandler(api).fetch(
  231. new Request('http://host/api/session.export?sessionId=session-root'),
  232. )
  233. expect(response.status).toBe(404)
  234. })
  235. it('answers 501 when the persistence backend has no per-session raw artifacts', async () => {
  236. const api = await buildApi({}, [], { persistence: 'unsupported' })
  237. const response = await toFetchHandler(api).fetch(
  238. new Request('http://host/api/session.export?sessionId=session-root'),
  239. )
  240. expect(response.status).toBe(501)
  241. expect(await response.text()).toContain('does not expose per-session raw artifacts')
  242. })
  243. it('answers 400 when the sessionId query parameter is absent', async () => {
  244. const api = await buildApi({ 'session-root': artifact('session-root') })
  245. const response = await toFetchHandler(api).fetch(
  246. new Request('http://host/api/session.export?includeDescendants=true'),
  247. )
  248. expect(response.status).toBe(400)
  249. })
  250. it('answers 400 for an includeDescendants value other than true or false', async () => {
  251. const api = await buildApi({ 'session-root': artifact('session-root') })
  252. const response = await toFetchHandler(api).fetch(
  253. new Request('http://host/api/session.export?sessionId=session-root&includeDescendants=1'),
  254. )
  255. expect(response.status).toBe(400)
  256. })
  257. it('answers 500 when the deployment mounts no persistence or session-query service', async () => {
  258. const api = await buildApi({}, [], { query: false, persistence: false })
  259. const response = await toFetchHandler(api).fetch(
  260. new Request('http://host/api/session.export?sessionId=session-root'),
  261. )
  262. expect(response.status).toBe(500)
  263. expect(await response.text()).toContain('session-query')
  264. })
  265. it('fails the whole export when a descendant has no stored artifact', async () => {
  266. const api = await buildApi({
  267. 'session-root': artifact('session-root'),
  268. }, [node('child-missing')])
  269. const response = await toFetchHandler(api).fetch(
  270. new Request('http://host/api/session.export?sessionId=session-root&includeDescendants=true'),
  271. )
  272. expect(response.status).toBe(200)
  273. // The stream errors before completing, so the body read rejects rather
  274. // than returning a truncated-but-valid archive.
  275. await expect(response.arrayBuffer()).rejects.toThrow()
  276. })
  277. it('keeps an astral character whole when its surrogate pair straddles a push boundary', async () => {
  278. // The push loop slices by 2^16 code units and must back off one unit when
  279. // the boundary lands inside a surrogate pair; otherwise the pair re-encodes
  280. // as U+FFFD and the exported artifact is silently corrupted.
  281. const root = { ...artifact('session-root'), content: `${'a'.repeat((1 << 16) - 1)}😀tail` }
  282. const api = await buildApi({ 'session-root': root })
  283. const response = await toFetchHandler(api).fetch(
  284. new Request('http://host/api/session.export?sessionId=session-root'),
  285. )
  286. const files = unzipSync(await responseBytes(response))
  287. expect(strFromU8(files['session.jsonl'] as Uint8Array)).toBe(root.content)
  288. })
  289. it('splits a long artifact on a plain code-unit boundary without backoff', async () => {
  290. // A boundary that lands on a BMP character needs no surrogate backoff; the
  291. // round trip must still be byte-identical across the multi-chunk push.
  292. const root = { ...artifact('session-root'), content: 'z'.repeat((1 << 16) + 4096) }
  293. const api = await buildApi({ 'session-root': root })
  294. const response = await toFetchHandler(api).fetch(
  295. new Request('http://host/api/session.export?sessionId=session-root'),
  296. )
  297. const files = unzipSync(await responseBytes(response))
  298. expect(strFromU8(files['session.jsonl'] as Uint8Array)).toBe(root.content)
  299. })
  300. it('waits for response pull capacity before reading the next archive entry', async () => {
  301. const root = artifact('session-root', undefined, [
  302. imageEventLine('after-root'),
  303. randomBytes(512 * 1024).toString('base64'),
  304. ].join('\n'))
  305. let imageReads = 0
  306. const api = await buildApi({ 'session-root': root }, [], {
  307. attachments: async (ref) => {
  308. imageReads += 1
  309. return storedImage(String(ref.attachmentId), ref.mediaType)
  310. },
  311. })
  312. vi.useFakeTimers()
  313. let response: Response | undefined
  314. try {
  315. response = await toFetchHandler(api).fetch(
  316. new Request('http://host/api/session.export?sessionId=session-root'),
  317. )
  318. // Exhausting timer turns must not advance a producer whose byte queue is
  319. // full; only a consumer pull can release it.
  320. await vi.runAllTimersAsync()
  321. expect(imageReads).toBe(0)
  322. } finally {
  323. vi.useRealTimers()
  324. }
  325. if (response === undefined) throw new Error('missing export response')
  326. const files = unzipSync(await responseBytes(response))
  327. expect(imageReads).toBe(1)
  328. expect(files['media/after-root.png']).toEqual(storedImage('after-root').data)
  329. })
  330. it('exports an empty artifact as an empty zip entry', async () => {
  331. const root = { ...artifact('session-root'), content: '' }
  332. const api = await buildApi({ 'session-root': root })
  333. const response = await toFetchHandler(api).fetch(
  334. new Request('http://host/api/session.export?sessionId=session-root'),
  335. )
  336. const files = unzipSync(await responseBytes(response))
  337. expect(Object.keys(files)).toEqual(['session.jsonl'])
  338. expect(strFromU8(files['session.jsonl'] as Uint8Array)).toBe('')
  339. })
  340. it('exports a shared lineage node once (seen-set dedup)', async () => {
  341. const api = await buildApi({
  342. 'session-root': artifact('session-root'),
  343. 'child-a': artifact('child-a', sid('session-root')),
  344. 'child-b': artifact('child-b', sid('session-root')),
  345. shared: artifact('shared', sid('child-a')),
  346. }, [
  347. node('child-a', node('shared')),
  348. node('child-b', node('shared')),
  349. ])
  350. const response = await toFetchHandler(api).fetch(
  351. new Request('http://host/api/session.export?sessionId=session-root&includeDescendants=true'),
  352. )
  353. const files = unzipSync(await responseBytes(response))
  354. expect(Object.keys(files).sort()).toEqual([
  355. 'session.jsonl',
  356. 'subagents/child-a/session.jsonl',
  357. 'subagents/child-b/session.jsonl',
  358. 'subagents/shared/session.jsonl',
  359. ])
  360. })
  361. it('answers 500 without leaking the backend error when the root artifact read fails', async () => {
  362. const api = await buildApi({}, [], { query: true, persistence: 'throw' })
  363. const response = await toFetchHandler(api).fetch(
  364. new Request('http://host/api/session.export?sessionId=session-root'),
  365. )
  366. expect(response.status).toBe(500)
  367. const body = await response.text()
  368. expect(body).toBe('session log export failed to prepare the stored artifact')
  369. expect(body).not.toContain('/host/private/')
  370. })
  371. it('answers the private-error-safe 500 when the live root flush fails', async () => {
  372. const api = await buildApi({ 'session-root': artifact('session-root') }, [], {
  373. sessions: {
  374. get: id => ({ id }),
  375. flush: async () => { throw new Error('/host/private/flush-state') },
  376. },
  377. })
  378. const response = await toFetchHandler(api).fetch(
  379. new Request('http://host/api/session.export?sessionId=session-root'),
  380. )
  381. expect(response.status).toBe(500)
  382. const body = await response.text()
  383. expect(body).toBe('session log export failed to prepare the stored artifact')
  384. expect(body).not.toContain('/host/private/')
  385. })
  386. it('forwards one request signal through root, lineage, and descendant reads', async () => {
  387. const reads: Array<{ id: SessionId; signal: AbortSignal | undefined }> = []
  388. const traces: AbortSignal[] = []
  389. const api = await buildApi({}, [node('child-a')], {
  390. readRaw: async (id, signal) => {
  391. reads.push({ id, signal })
  392. return id === sid('session-root')
  393. ? artifact('session-root')
  394. : artifact('child-a', sid('session-root'))
  395. },
  396. traceSession: async (_id, signal) => {
  397. if (signal !== undefined) traces.push(signal)
  398. return {
  399. target: { header: header('session-root'), live: false, persisted: true },
  400. ancestors: [],
  401. complete: true,
  402. root: { header: header('session-root'), live: false, persisted: true },
  403. descendants: [node('child-a')],
  404. }
  405. },
  406. })
  407. const controller = new AbortController()
  408. const response = await api.downloads.sessionLog(
  409. { sessionId: sid('session-root'), includeDescendants: true },
  410. controller.signal,
  411. )
  412. await response.arrayBuffer()
  413. const producerSignal = traces[0]
  414. if (producerSignal === undefined) throw new Error('missing lineage signal')
  415. expect(reads[0]).toEqual({ id: sid('session-root'), signal: controller.signal })
  416. expect(reads[1]).toEqual({ id: sid('child-a'), signal: producerSignal })
  417. const cancellation = new Error('request cancelled after response')
  418. controller.abort(cancellation)
  419. expect(producerSignal.aborted).toBe(true)
  420. expect(producerSignal.reason).toBe(cancellation)
  421. })
  422. it('preserves request cancellation instead of translating it to HTTP 500', async () => {
  423. const api = await buildApi({ 'session-root': artifact('session-root') })
  424. const controller = new AbortController()
  425. const cancellation = new Error('request cancelled')
  426. controller.abort(cancellation)
  427. await expect(api.downloads.sessionLog(
  428. { sessionId: sid('session-root'), includeDescendants: false },
  429. controller.signal,
  430. )).rejects.toBe(cancellation)
  431. })
  432. it('aborts descendant work and terminates ZIP production when its reader cancels', async () => {
  433. let reportDescendantStarted!: (signal: AbortSignal) => void
  434. const descendantStarted = new Promise<AbortSignal>((resolve) => {
  435. reportDescendantStarted = resolve
  436. })
  437. const api = await buildApi({}, [node('child-a')], {
  438. readRaw: async (id, signal) => {
  439. if (id === sid('session-root')) return artifact('session-root')
  440. if (signal === undefined) throw new Error('missing descendant signal')
  441. reportDescendantStarted(signal)
  442. return new Promise((_, reject) => {
  443. signal.addEventListener('abort', () => {
  444. reject(signal.reason as Error)
  445. }, { once: true })
  446. })
  447. },
  448. })
  449. const response = await api.downloads.sessionLog(
  450. { sessionId: sid('session-root'), includeDescendants: true },
  451. new AbortController().signal,
  452. )
  453. const reader = response.body?.getReader()
  454. if (reader === undefined) throw new Error('missing response body')
  455. const descendantSignal = await descendantStarted
  456. const cancellation = new Error('download consumer left')
  457. await reader.cancel(cancellation)
  458. expect(descendantSignal.aborted).toBe(true)
  459. expect(descendantSignal.reason).toBe(cancellation)
  460. })
  461. it('aborts attachment reads when its reader cancels', async () => {
  462. let reportAttachmentStarted!: (signal: AbortSignal) => void
  463. const attachmentStarted = new Promise<AbortSignal>((resolve) => {
  464. reportAttachmentStarted = resolve
  465. })
  466. const root = artifact('session-root', undefined, [
  467. '{"type":"session","version":0,"id":"session-root","createdAt":1000}',
  468. imageEventLine('slow-img'),
  469. ].join('\n') + '\n')
  470. const api = await buildApi({ 'session-root': root }, [], {
  471. attachments: async (_ref, signal) => {
  472. if (signal === undefined) throw new Error('missing attachment signal')
  473. reportAttachmentStarted(signal)
  474. return new Promise((_, reject) => {
  475. signal.addEventListener('abort', () => {
  476. reject(signal.reason as Error)
  477. }, { once: true })
  478. })
  479. },
  480. })
  481. const response = await api.downloads.sessionLog(
  482. { sessionId: sid('session-root'), includeDescendants: false },
  483. new AbortController().signal,
  484. )
  485. const reader = response.body?.getReader()
  486. if (reader === undefined) throw new Error('missing response body')
  487. const attachmentSignal = await attachmentStarted
  488. const cancellation = new Error('download consumer left during attachment read')
  489. await reader.cancel(cancellation)
  490. expect(attachmentSignal.aborted).toBe(true)
  491. expect(attachmentSignal.reason).toBe(cancellation)
  492. })
  493. it('uses a stable Error reason when its reader cancels without one', async () => {
  494. let reportDescendantStarted!: (signal: AbortSignal) => void
  495. const descendantStarted = new Promise<AbortSignal>((resolve) => {
  496. reportDescendantStarted = resolve
  497. })
  498. const api = await buildApi({}, [node('child-a')], {
  499. readRaw: async (id, signal) => {
  500. if (id === sid('session-root')) return artifact('session-root')
  501. if (signal === undefined) throw new Error('missing descendant signal')
  502. reportDescendantStarted(signal)
  503. return new Promise((_, reject) => {
  504. signal.addEventListener('abort', () => {
  505. reject(signal.reason as Error)
  506. }, { once: true })
  507. })
  508. },
  509. })
  510. const response = await api.downloads.sessionLog(
  511. { sessionId: sid('session-root'), includeDescendants: true },
  512. new AbortController().signal,
  513. )
  514. const reader = response.body?.getReader()
  515. if (reader === undefined) throw new Error('missing response body')
  516. const descendantSignal = await descendantStarted
  517. await reader.cancel()
  518. expect(descendantSignal.reason).toEqual(new Error('session log export stream cancelled'))
  519. })
  520. it('normalizes a non-Error descendant failure before erroring the stream', async () => {
  521. const api = await buildApi({}, [node('child-a')], {
  522. readRaw: async (id) => {
  523. if (id === sid('session-root')) return artifact('session-root')
  524. throw 'descendant read failed'
  525. },
  526. })
  527. const response = await api.downloads.sessionLog(
  528. { sessionId: sid('session-root'), includeDescendants: true },
  529. new AbortController().signal,
  530. )
  531. await expect(response.arrayBuffer()).rejects.toEqual(new Error('descendant read failed'))
  532. })
  533. it('includes media objects referenced by the root log under media/<id>.<ext>', async () => {
  534. const root = artifact('session-root', undefined, [
  535. '{"type":"session","version":0,"id":"session-root","createdAt":1000}',
  536. imageEventLine('img-1'),
  537. ].join('\n') + '\n')
  538. const api = await buildApi({ 'session-root': root })
  539. const response = await toFetchHandler(api).fetch(
  540. new Request('http://host/api/session.export?sessionId=session-root'),
  541. )
  542. expect(response.status).toBe(200)
  543. const files = unzipSync(await responseBytes(response))
  544. expect(Object.keys(files).sort()).toEqual(['media/img-1.png', 'session.jsonl'])
  545. expect(files['media/img-1.png']).toEqual(storedImage('img-1').data)
  546. })
  547. it('collects media referenced from nested tool results', async () => {
  548. const nested = '{"type":"assistant/message","seq":2,"time":2000,"data":{"content":[{"type":"tool-result","content":[{"type":"image","attachment":{"attachmentId":"nested-1","mediaType":"image/webp","bytes":4,"width":2,"height":2}}]}]}}'
  549. const root = artifact('session-root', undefined, [
  550. '{"type":"session","version":0,"id":"session-root","createdAt":1000}',
  551. nested,
  552. ].join('\n') + '\n')
  553. const api = await buildApi({ 'session-root': root })
  554. const response = await toFetchHandler(api).fetch(
  555. new Request('http://host/api/session.export?sessionId=session-root'),
  556. )
  557. const files = unzipSync(await responseBytes(response))
  558. expect(Object.keys(files).sort()).toEqual(['media/nested-1.webp', 'session.jsonl'])
  559. })
  560. it('scans the wrapped, inserted, and chunk carriers plus non-object content items', async () => {
  561. const block = (id: string, mediaType: string) =>
  562. `{"type":"image","attachment":{"attachmentId":"${id}","mediaType":"${mediaType}","bytes":4,"width":2,"height":2}}`
  563. const wrapped = `{"type":"assistant/message","seq":2,"time":2000,"data":{"message":{"role":"assistant","content":["noise",${block('wrapped-1', 'image/jpeg')}]}}}`
  564. const inserted = `{"type":"context/inserted","seq":3,"time":3000,"data":{"inserted":[{"content":[${block('inserted-1', 'image/gif')}]}]}}`
  565. const chunk = `{"type":"assistant/chunk","seq":4,"time":4000,"data":{"chunk":{"type":"block-end","block":${block('chunk-1', 'image/png')}}}}`
  566. const root = artifact('session-root', undefined, [
  567. '{"type":"session","version":0,"id":"session-root","createdAt":1000}',
  568. wrapped,
  569. inserted,
  570. chunk,
  571. ].join('\n') + '\n')
  572. const api = await buildApi({ 'session-root': root })
  573. const response = await toFetchHandler(api).fetch(
  574. new Request('http://host/api/session.export?sessionId=session-root'),
  575. )
  576. const files = unzipSync(await responseBytes(response))
  577. expect(Object.keys(files).sort()).toEqual([
  578. 'media/chunk-1.png',
  579. 'media/inserted-1.gif',
  580. 'media/wrapped-1.jpg',
  581. 'session.jsonl',
  582. ])
  583. })
  584. it('deduplicates one media object referenced by several included logs', async () => {
  585. const line = imageEventLine('shared-img')
  586. const root = artifact('session-root', undefined, [
  587. '{"type":"session","version":0,"id":"session-root","createdAt":1000}',
  588. line,
  589. ].join('\n') + '\n')
  590. const child = artifact('child-a', sid('session-root'), [
  591. '{"type":"session","version":0,"id":"child-a","createdAt":1000}',
  592. line,
  593. ].join('\n') + '\n')
  594. const api = await buildApi({ 'session-root': root, 'child-a': child }, [node('child-a')])
  595. const response = await toFetchHandler(api).fetch(
  596. new Request('http://host/api/session.export?sessionId=session-root&includeDescendants=true'),
  597. )
  598. const files = unzipSync(await responseBytes(response))
  599. expect(files['media/shared-img.png']).toEqual(storedImage('shared-img').data)
  600. expect(Object.keys(files).filter(name => name.startsWith('media/'))).toEqual(['media/shared-img.png'])
  601. })
  602. it('includes descendant media only when descendants are requested', async () => {
  603. const child = artifact('child-a', sid('session-root'), [
  604. '{"type":"session","version":0,"id":"child-a","createdAt":1000}',
  605. imageEventLine('child-img'),
  606. ].join('\n') + '\n')
  607. const api = await buildApi({ 'session-root': artifact('session-root'), 'child-a': child }, [node('child-a')])
  608. const without = await toFetchHandler(api).fetch(
  609. new Request('http://host/api/session.export?sessionId=session-root'),
  610. )
  611. expect(Object.keys(unzipSync(await responseBytes(without)))).toEqual(['session.jsonl'])
  612. const withDescendants = await toFetchHandler(api).fetch(
  613. new Request('http://host/api/session.export?sessionId=session-root&includeDescendants=true'),
  614. )
  615. expect(Object.keys(unzipSync(await responseBytes(withDescendants))).sort()).toEqual([
  616. 'media/child-img.png',
  617. 'session.jsonl',
  618. 'subagents/child-a/session.jsonl',
  619. ])
  620. })
  621. it('fails the whole export when a referenced image cannot be read', async () => {
  622. const root = artifact('session-root', undefined, [
  623. '{"type":"session","version":0,"id":"session-root","createdAt":1000}',
  624. imageEventLine('gone-img'),
  625. ].join('\n') + '\n')
  626. const api = await buildApi({ 'session-root': root }, [], {
  627. attachments: async () => { throw new Error('attachment bytes missing') },
  628. })
  629. const response = await toFetchHandler(api).fetch(
  630. new Request('http://host/api/session.export?sessionId=session-root'),
  631. )
  632. expect(response.status).toBe(200)
  633. await expect(response.arrayBuffer()).rejects.toThrow('attachment bytes missing')
  634. })
  635. it('answers 500 when the deployment mounts no attachments service', async () => {
  636. const api = await buildApi({ 'session-root': artifact('session-root') }, [], { attachments: false })
  637. const response = await toFetchHandler(api).fetch(
  638. new Request('http://host/api/session.export?sessionId=session-root'),
  639. )
  640. expect(response.status).toBe(500)
  641. expect(await response.text()).toContain('attachments')
  642. })
  643. })