refactor(web): hand session exports to browser downloads

The export endpoint already streams a ZIP response, but the web client immediately converted that response into a Blob. That forced the complete archive through JavaScript memory before a download could start and coupled transport, buffering, object-URL lifetime, and filename handling to the trajectory view.

Navigate a temporary download anchor directly to the export endpoint instead. The browser now owns streaming and HTTP failure presentation, while a standalone delivery module owns URL construction and filename sanitization. Focused tests cover the handoff, rejection behavior, and the assembled session view; the package README and feature note record the new ownership boundary.
This commit is contained in:
Tianyi Cui
2026-08-11 14:57:38 +08:00
parent 104724d866
commit 7f14c7e165
10 changed files with 73 additions and 72 deletions

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-08-10-web-session-log-export.md
2026-08-10-web-session-log-export.md: 427b6478ac44fb28030aa932630f276de7bb2edc
2026-08-10-web-session-log-export.zh.md: 63b9804a54cda7eea4ff793d78a925fe296d06cb
2026-08-10-web-session-log-export.md: 6e9372ebec89f5aacef4e806fae77982d265c97b
2026-08-10-web-session-log-export.zh.md: e2f640efd735acd9e4d5d72bbfefdb01e7559161

View File

@@ -12,8 +12,8 @@ The Trajectory view had no way to hand a debugging artifact to a human: the raw
- **The export is a host-only download, not an RPC**: `GET /api/session.export?sessionId=…&includeDescendants=true` streams one ZIP attachment. Every file is a session's **stored artifact text verbatim**: `readRaw` on the persistence service reads the backend's own durable bytes (the JSONL backend decodes its physical zstd frames, or returns plaintext) — never a reconstruction from parsed events, so packed-chunk rows, key order, and line breaks survive byte-for-byte — under its original base name (`session.jsonl` at the root, `subagents/<id>/session.jsonl` for descendants). Compression runs on the host with fflate's streaming `Zip`/`ZipDeflate` API, each entry deflated in bounded chunks as it is produced, so the response is chunked as it is generated and the host never holds the whole archive in one buffer (at most one descendant's artifact text beyond the preloaded root), and production yields whenever the response queue fills, so a slow consumer bounds the accumulation (fflate's callback is synchronous — the drain point is the only backpressure). No manifest is written — every file is byte-identical to the durable artifact and self-describing through its own header line.
- **Error vocabulary is HTTP-native**: missing services → 500, missing root session → 404 (both decided before any byte streams), a descendant without a stored artifact → the stream errors (fail-loud, never silent under-export). The carrier (`toFetchHandler`) already applies the `/api` trust fence; the GET branch sits beside the existing SSE GET routes, and `ApiProxy.downloads.sessionLog` (host-only, no wire envelope, absent from `IApiClient`) implements it.
- **The UI just downloads**: the 导出 button fetches the endpoint and saves the response; the `session.log` RPC that an earlier iteration shipped was removed — the download endpoint is its only consumer, and the repo rule is no public interface without a current owner. The client bundle no longer carries fflate (the earlier browser-entry-alias pitfall is moot).
- The 导出 button lives in the Trajectory toolbar; the plugin exposes `exportLog` through the view's inject face (components never touch ctx) and resolves the view tab label through the locale service (`轨迹` in Chinese, `Trajectory` in English). In-flight state disables the button; a failure surfaces in a visible alert bar under the toolbar.
- **The UI just downloads**: the 导出 button hands the endpoint directly to the browser's native download manager, so JavaScript neither fetches nor buffers the ZIP; the `session.log` RPC that an earlier iteration shipped was removed — the download endpoint is its only consumer, and the repo rule is no public interface without a current owner. The client bundle carries no archive implementation.
- The 导出 button lives in the Trajectory toolbar; the plugin exposes `exportLog` through the view's inject face (components never touch ctx) and resolves the view tab label through the locale service (`轨迹` in Chinese, `Trajectory` in English). In-flight state disables the button during the handoff; a synchronous browser-handoff failure surfaces in a visible alert bar, while HTTP delivery is owned and reported by the browser.
## Alternatives considered
@@ -26,5 +26,5 @@ The Trajectory view had no way to hand a debugging artifact to a human: the raw
- Export fidelity: every exported file is byte-identical to the backend's durable artifact as of the read moment (a live session may append after the read; the export reflects the durable state at read time). The archive name is `dsh-session-<sanitized-id>.zip` and archive paths sanitize ids before they can shape entries.
- `readRaw` joins the persistence service as a concrete default (`undefined` for backends without a per-session artifact, e.g. SQLite) with a JSONL-backend override that owns the compression decode. `ApiProxy.downloads.sessionLog` adds one host-only member to the contract plus a host-side query schema and a GET branch in the fetch handler — no RPC map row, envelope schema, or client `IApiClient` surface.
- Fixture mode (no host) answers 404 for the export, so the button's error bar explains the gap instead of hanging; the navigation-panes golden snapshot includes the 导出 button.
- Fixture mode (no host) answers 404 for the export, which the browser reports as a failed download; the navigation-panes golden snapshot includes the 导出 button.
- Deferred: transcript.md and a report/feedback bundle remain future work; the byte-faithful, manifest-free shape keeps the v2 bundle extension cheap.

View File

@@ -12,8 +12,8 @@ Trajectory 视图没有任何方式把调试工件交到人手里:原始会话
- **导出是宿主侧的下载面,不是 RPC**`GET /api/session.export?sessionId=…&includeDescendants=true` 流式返回一个 ZIP 附件。每个文件都是会话**存储工件的逐字原文**:持久化服务新增的 `readRaw` 读取后端自己的持久化字节jsonl 后端解码其物理 zstd 帧,或直接返回明文)——绝非从解析后事件重建,因此 chunk 打包、键序、换行全部逐字节保留——放在其原始基础文件名下(根为 `session.jsonl`,子代理为 `subagents/<id>/session.jsonl`)。压缩在宿主侧用 fflate 的流式 `Zip`/`ZipDeflate` API 完成每个条目按有界分块边产出边压缩响应随生成分块写出宿主从不把整个归档放进单个缓冲区除预载的根外最多同时持有一条后代的工件文本且每当响应队列填满时生产会让出慢消费者因此只产生有界的积压fflate 的回调是同步的——让出点是唯一的背压手段)。不写清单——每个文件都与持久化工件逐字节一致,并通过自身 header 行自描述。
- **错误词汇是 HTTP 原生的**:服务缺失 → 500根会话缺失 → 404两者都在任何字节流出前判定后代缺少存储工件 → 流失败fail-loud绝不静默少导出。载体`toFetchHandler`)已对 `/api` 应用信任围栏GET 分支与既有 SSE GET 路由并列,由 `ApiProxy.downloads.sessionLog`host-only、无 wire 信封、不在 `IApiClient` 上)实现。
- **UI 只负责下载**:「导出」按钮 fetch 该端点并保存响应;早先迭代发布的 `session.log` RPC 已删除——下载端点是它唯一的消费者,仓库规则是不留无当前所有者的公共接口。客户端 bundle 不再携带 fflate早先的浏览器入口别名坑随之消失
- 「导出」按钮位于 Trajectory 工具栏;插件通过视图的 inject face 暴露 `exportLog`(组件从不接触 ctx并通过 locale 服务解析视图标签页标题(中文「轨迹」、英文 "Trajectory")。进行中状态会禁用按钮;失败会在工具栏下方的可见警示条中显示
- **UI 只负责下载**:「导出」按钮将端点直接交给浏览器原生下载管理器,因此 JavaScript 既不会 fetch 也不会缓冲 ZIP;早先迭代发布的 `session.log` RPC 已删除——下载端点是它唯一的消费者,仓库规则是不留无当前所有者的公共接口。客户端 bundle 不包含任何归档实现
- 「导出」按钮位于 Trajectory 工具栏;插件通过视图的 inject face 暴露 `exportLog`(组件从不接触 ctx并通过 locale 服务解析视图标签页标题(中文「轨迹」、英文 "Trajectory")。进行中状态会在交接期间禁用按钮;同步的浏览器交接失败会在可见警示条中显示,而 HTTP 交付由浏览器负责并报告
## 考虑过的替代方案
@@ -26,5 +26,5 @@ Trajectory 视图没有任何方式把调试工件交到人手里:原始会话
- 导出保真度:每个导出文件都与读取时刻的后端持久化工件逐字节一致(活跃会话可能在读取后继续追加;导出反映的是读取时的持久化状态)。压缩包名为 `dsh-session-<sanitized-id>.zip`,归档路径在塑造条目前会先净化会话 id。
- `readRaw` 以具体默认(无每会话工件的后端如 SQLite 返回 `undefined`加入持久化服务jsonl 后端覆写并自持压缩解码。`ApiProxy.downloads.sessionLog` 为契约新增一个 host-only 成员,外加宿主侧 query schema并在 fetch handler 加一个 GET 分支——没有 RPC map 行、信封 schema 或客户端 `IApiClient` 面。
- fixture 模式(无宿主)对导出应答 404按钮的错误条会解释这个缺口而非挂起navigation-panes golden 快照包含「导出」按钮。
- fixture 模式(无宿主)对导出应答 404浏览器会将其报告为下载失败navigation-panes golden 快照包含「导出」按钮。
- 暂缓transcript.md 以及 report/feedback 打包留待后续;逐字节忠实、无清单的形态让 v2 的打包扩展保持廉价。

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-trajectory/README.md
README.md: e82b2cc9d4a65c3095aeee7002fb6c43a43b695d
README.zh.md: a1ba62393c2aae3f6baa7c481dd80f04dbbb477d
README.md: f4b3bd223c2872f0341d49bdaa102440d73b4f29
README.zh.md: 9bcb3b6ad98d672cc524c168f2024be9ba56b577

View File

@@ -2,7 +2,7 @@
English | [中文](README.zh.md)
Trajectory renders a turn-aware event ledger with selectable User, Assistant, Tool, and nested Subtool records. Thick rules mark Turn boundaries, compact inline markers identify Steps, and the main ledger keeps only index, event, and content; selection opens a local inspector for token usage, duration, Input, Output, and Timing. Scrollable Summary regions keep their scrollbar thumbs transparent until the region is hovered or contains keyboard focus, without changing the reserved scroll geometry. A standalone compaction request appears chronologically in its own `Between turns` section, while a numbered compaction remains inside its owning turn. Long ledgers open at the current tail, load one older page when the user reaches the loaded range's top, and mount only the visible row window plus a small overscan; request-only separators share the next measurable virtual item, while semantic row keys and ARIA indexes survive prepends. Selection, timeline navigation, folding, search, and Request totals cover the currently loaded window. The ledger covers records with an explicit loading row until the initial tail is positioned and while an older page is pending. A fixed Overview above the ledger projects real record start/duration timing from left to right; when earlier records remain unloaded and the viewport includes the loaded domain's start, a neutral ellipsis control identifies the omitted prefix and loads one earlier page without assigning unknown history fabricated duration. Assistant spans divide recorded TTFT from decoding, and a 500 ms hover reveals exact clock and duration details. Dragging an interval focuses the ledger on every record active at any point in that inclusive range, while clearing the selection restores the full loaded ledger. Wheel gestures zoom the time domain. A right-button click clears the selected interval, while a right-button drag pans an already zoomed viewport without changing it. The initial view and streaming updates stay at the tail; scrolling upward suspends following so new records do not interrupt inspection of earlier rows. Content-only stream frames preserve virtual row keys and heights, reuse measurements, and do not issue repeated tail-scroll writes. The toolbar's Export button downloads the session log — the root plus every subagent descendant — as a ZIP streamed by the host (`GET /api/session.export`): every file is the session's stored artifact text verbatim (`session.jsonl` at the root, `subagents/<id>/session.jsonl` for descendants; no manifest, byte-identical to the backend's durable artifact), and every image any included log references sits under `media/<attachmentId>.<ext>`. Fixture mode (no host) answers 404 for the export. Completed replies retain assembled blocks, timing, and usage in Trajectory target State, while the shared Session window keeps the raw Events. Trajectory asks the conversation shell to float the composer over the full-height ledger, while its responsive vertical scrollers reserve the composer's live height so final rows remain reachable. Trajectory-owned Definitions assemble business records, including cancellation-frozen Assistant and Tool records, from the shared Session window, so Trajectory neither reads nor changes the Chat conversation snapshot. The package provides no service and declares no Context merge; it registers target-specific Event Definitions, a Trajectory view builder, and one tab in the conversation's `'conversation.view'` slot ring. Contract: api-contracts v3 §8.
Trajectory renders a turn-aware event ledger with selectable User, Assistant, Tool, and nested Subtool records. Thick rules mark Turn boundaries, compact inline markers identify Steps, and the main ledger keeps only index, event, and content; selection opens a local inspector for token usage, duration, Input, Output, and Timing. Scrollable Summary regions keep their scrollbar thumbs transparent until the region is hovered or contains keyboard focus, without changing the reserved scroll geometry. A standalone compaction request appears chronologically in its own `Between turns` section, while a numbered compaction remains inside its owning turn. Long ledgers open at the current tail, load one older page when the user reaches the loaded range's top, and mount only the visible row window plus a small overscan; request-only separators share the next measurable virtual item, while semantic row keys and ARIA indexes survive prepends. Selection, timeline navigation, folding, search, and Request totals cover the currently loaded window. The ledger covers records with an explicit loading row until the initial tail is positioned and while an older page is pending. A fixed Overview above the ledger projects real record start/duration timing from left to right; when earlier records remain unloaded and the viewport includes the loaded domain's start, a neutral ellipsis control identifies the omitted prefix and loads one earlier page without assigning unknown history fabricated duration. Assistant spans divide recorded TTFT from decoding, and a 500 ms hover reveals exact clock and duration details. Dragging an interval focuses the ledger on every record active at any point in that inclusive range, while clearing the selection restores the full loaded ledger. Wheel gestures zoom the time domain. A right-button click clears the selected interval, while a right-button drag pans an already zoomed viewport without changing it. The initial view and streaming updates stay at the tail; scrolling upward suspends following so new records do not interrupt inspection of earlier rows. Content-only stream frames preserve virtual row keys and heights, reuse measurements, and do not issue repeated tail-scroll writes. The toolbar's Export button hands the session log — the root plus every subagent descendant — directly to the browser download manager as a ZIP streamed by the host (`GET /api/session.export`), so JavaScript never buffers the response: every file is the session's stored artifact text verbatim (`session.jsonl` at the root, `subagents/<id>/session.jsonl` for descendants; no manifest, byte-identical to the backend's durable artifact), and every image any included log references sits under `media/<attachmentId>.<ext>`. Fixture mode (no host) answers 404 for the export. Completed replies retain assembled blocks, timing, and usage in Trajectory target State, while the shared Session window keeps the raw Events. Trajectory asks the conversation shell to float the composer over the full-height ledger, while its responsive vertical scrollers reserve the composer's live height so final rows remain reachable. Trajectory-owned Definitions assemble business records, including cancellation-frozen Assistant and Tool records, from the shared Session window, so Trajectory neither reads nor changes the Chat conversation snapshot. The package provides no service and declares no Context merge; it registers target-specific Event Definitions, a Trajectory view builder, and one tab in the conversation's `'conversation.view'` slot ring. Contract: api-contracts v3 §8.
## Model Experience

View File

@@ -2,7 +2,7 @@
[English](README.md) | 中文
Trajectory 渲染按轮次组织的事件记录表,其中可选择用户、助手、工具和嵌套子工具记录。较粗的分割线标示轮次边界,紧凑的行内标记标识步骤,主记录表仅保留索引、事件和内容;选择记录则会打开局部检查器,查看 token 用量、耗时、输入、输出和计时。可滚动的概述区域默认保持滚动条滑块透明直到鼠标悬停该区域或其中包含键盘焦点时才显示同时不改变滚动条预留的几何空间。独立运行的压缩compaction请求会按时间顺序显示在自己的 `Between turns` 区段中,而带编号的压缩仍位于其所属轮次内。长记录表打开时定位于当前尾部,用户到达已加载范围顶部时加载一页更早的历史,并且只挂载可见行窗口和少量额外缓冲行;仅含请求的分隔行并入下一个具备可测高度的虚拟项,语义行键和 ARIA 索引在向前补页后保持不变。选择、时间线导航、折叠、搜索和请求汇总只覆盖当前已加载的窗口。初始尾部完成定位前以及更早页面仍在等待时,记录表会用明确的加载行遮住真实记录。固定在记录表上方的 Overview 区域从左到右投影记录的真实开始时间与耗时;仍有更早记录未加载且 viewport 包含已加载时间域起点时,中性的省略号控件会标识被省略的前缀,并可加载一页更早历史,而不会为未知部分虚构耗时。助手时间条会区分记录到的 TTFT 与解码时间,悬停 500 ms 后可查看精确时刻和耗时详情。拖选一个区间会将记录表聚焦到活动区间与该闭区间有重叠的所有记录,清除选择则恢复完整的已加载记录表。滚轮手势用于缩放时间域。右键单击会清除所选区间;在已放大的 viewport 上按住右键拖动则只会平移视图,不会改变该区间。初始视图和流式更新都会停留在尾部;向上滚动会暂停跟随,因此新记录不会打断对旧记录的检查。仅含内容更新的流式帧会保持虚拟行的键和高度不变、复用测量结果,并且不会重复写入末尾滚动位置。工具栏的 “Export” 按钮会将会话日志——根会话及其全部子代理——下载为宿主流式返回的 ZIP`GET /api/session.export`):每个文件都是会话存储工件的逐字原文(根为 `session.jsonl`,子代理为 `subagents/<id>/session.jsonl`;无清单,与后端持久化工件逐字节一致),每个被包含日志引用的图片则放在 `media/<attachmentId>.<ext>` 下。fixture 模式(无宿主)对导出应答 404。已完成的回复会在 Trajectory target State 中保留组装后的 blocks、计时与用量共享 Session 窗口则保留原始 Event。Trajectory 要求会话壳将 composer 作为浮层置于全高记录表上方;其响应式纵向滚动容器会预留 composer 的实时高度确保仍可滚动到最后几行。Trajectory 自有的 Definition 从共享 Session 窗口组装业务记录,其中包括因取消而冻结的助手和工具记录,因此 Trajectory 既不读取也不改变 Chat 会话快照。该包不提供 service也不声明 Context 合并;它会注册 target 专属 Event Definition、Trajectory view builder以及会话 `'conversation.view'` slot 环中的一个视图标签页。约定api-contracts v3 §8。
Trajectory 渲染按轮次组织的事件记录表,其中可选择用户、助手、工具和嵌套子工具记录。较粗的分割线标示轮次边界,紧凑的行内标记标识步骤,主记录表仅保留索引、事件和内容;选择记录则会打开局部检查器,查看 token 用量、耗时、输入、输出和计时。可滚动的概述区域默认保持滚动条滑块透明直到鼠标悬停该区域或其中包含键盘焦点时才显示同时不改变滚动条预留的几何空间。独立运行的压缩compaction请求会按时间顺序显示在自己的 `Between turns` 区段中,而带编号的压缩仍位于其所属轮次内。长记录表打开时定位于当前尾部,用户到达已加载范围顶部时加载一页更早的历史,并且只挂载可见行窗口和少量额外缓冲行;仅含请求的分隔行并入下一个具备可测高度的虚拟项,语义行键和 ARIA 索引在向前补页后保持不变。选择、时间线导航、折叠、搜索和请求汇总只覆盖当前已加载的窗口。初始尾部完成定位前以及更早页面仍在等待时,记录表会用明确的加载行遮住真实记录。固定在记录表上方的 Overview 区域从左到右投影记录的真实开始时间与耗时;仍有更早记录未加载且 viewport 包含已加载时间域起点时,中性的省略号控件会标识被省略的前缀,并可加载一页更早历史,而不会为未知部分虚构耗时。助手时间条会区分记录到的 TTFT 与解码时间,悬停 500 ms 后可查看精确时刻和耗时详情。拖选一个区间会将记录表聚焦到活动区间与该闭区间有重叠的所有记录,清除选择则恢复完整的已加载记录表。滚轮手势用于缩放时间域。右键单击会清除所选区间;在已放大的 viewport 上按住右键拖动则只会平移视图,不会改变该区间。初始视图和流式更新都会停留在尾部;向上滚动会暂停跟随,因此新记录不会打断对旧记录的检查。仅含内容更新的流式帧会保持虚拟行的键和高度不变、复用测量结果,并且不会重复写入末尾滚动位置。工具栏的 “Export” 按钮会将会话日志——根会话及其全部子代理——为宿主流式返回的 ZIP`GET /api/session.export`直接交给浏览器下载管理器,因此 JavaScript 不会缓冲响应:每个文件都是会话存储工件的逐字原文(根为 `session.jsonl`,子代理为 `subagents/<id>/session.jsonl`;无清单,与后端持久化工件逐字节一致),每个被包含日志引用的图片则放在 `media/<attachmentId>.<ext>` 下。fixture 模式(无宿主)对导出应答 404。已完成的回复会在 Trajectory target State 中保留组装后的 blocks、计时与用量共享 Session 窗口则保留原始 Event。Trajectory 要求会话壳将 composer 作为浮层置于全高记录表上方;其响应式纵向滚动容器会预留 composer 的实时高度确保仍可滚动到最后几行。Trajectory 自有的 Definition 从共享 Session 窗口组装业务记录,其中包括因取消而冻结的助手和工具记录,因此 Trajectory 既不读取也不改变 Chat 会话快照。该包不提供 service也不声明 Context 合并;它会注册 target 专属 Event Definition、Trajectory view builder以及会话 `'conversation.view'` slot 环中的一个视图标签页。约定api-contracts v3 §8。
## 模型体验

View File

@@ -1,7 +1,8 @@
/**
* Session log export: browser download of the host-streamed ZIP. The archive
* itself is produced and streamed by the host (GET /api/session.export); this
* module only derives the download filename and triggers the browser save.
* Session log export delivery. The host streams the archive from
* `GET /api/session.export`; this module owns the browser-native download
* handoff so the browser can stream the response directly to its download
* manager instead of buffering the ZIP in JavaScript.
* @module
*/
@@ -27,16 +28,18 @@ export function sessionLogZipFilename(sessionId: string): string {
}
/**
* Trigger a browser download of a blob response.
* @param blob - the response body to save (passed straight through, no copy).
* @param filename - the download filename.
* Hand one host-streamed session archive to the browser download manager.
* The operation resolves after dispatching the native download; HTTP delivery
* continues outside JavaScript and is reported by the browser itself.
* @param sessionId - the root session id to export with all descendants.
* @returns a promise that rejects if the browser handoff itself fails.
*/
export function downloadBlob(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = filename
anchor.click()
// Revoke one tick later: some browsers read the blob URL after click().
setTimeout(() => { URL.revokeObjectURL(url) }, 0)
export function downloadSessionLog(sessionId: string): Promise<void> {
return Promise.resolve().then(() => {
const query = new URLSearchParams({ sessionId, includeDescendants: 'true' })
const anchor = document.createElement('a')
anchor.href = `/api/session.export?${query.toString()}`
anchor.download = sessionLogZipFilename(sessionId)
anchor.click()
})
}

View File

@@ -10,7 +10,7 @@ import type {} from '@deepseek-ai/dsh-client-locale/client'
// owning package) must be in the program for the register calls to type.
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
import { createTrajectoryDurationStore } from './duration-store.ts'
import { downloadBlob, sessionLogZipFilename } from './export-log.ts'
import { downloadSessionLog } from './export-log.ts'
import { en, NS, zh } from './locales.ts'
import { registerTrajectoryAssistantDefinition } from './trajectory-assistant-definition.ts'
import { registerTrajectoryCompactionDefinitions } from './trajectory-compaction-definition.ts'
@@ -60,23 +60,7 @@ export function apply(ctx: Context): void {
return session.getSnapshot().views.get('trajectory') !== before
},
setActualDuration: (value) => { duration.set(value) },
exportLog: async () => {
// The host streams the ZIP (root + descendant artifacts verbatim)
// from GET /api/session.export; the browser downloads the response.
// A null origin (no-location Node contexts) falls back like the
// carrier's resolveBase so the URL stays valid.
const loc = (globalThis as { location?: { origin?: string } }).location
const origin = loc?.origin !== undefined && loc.origin !== 'null' ? loc.origin : 'http://dsh.internal'
const url = new URL('/api/session.export', origin)
url.searchParams.set('sessionId', sessionId)
url.searchParams.set('includeDescendants', 'true')
const response = await fetch(url)
if (!response.ok) {
const detail = await response.text().catch(() => '')
throw new Error(`Export failed: HTTP ${response.status}${detail === '' ? '' : ` ${detail}`}`)
}
downloadBlob(await response.blob(), sessionLogZipFilename(sessionId))
},
exportLog: () => downloadSessionLog(sessionId),
}
},
}, TrajectoryView))

View File

@@ -1,12 +1,15 @@
// @vitest-environment node
// @vitest-environment jsdom
/**
* Session-log export filename derivation. The archive itself is produced and
* streamed by the host (GET /api/session.export); this package only derives
* the download filename and triggers the browser save.
* Session-log export browser delivery: safe filename derivation and a native
* download handoff that leaves the streamed response outside JavaScript.
*/
import { describe, expect, it } from 'vitest'
import { sessionLogZipFilename } from '../src/client/export-log.ts'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { downloadSessionLog, sessionLogZipFilename } from '../src/client/export-log.ts'
afterEach(() => {
vi.restoreAllMocks()
})
describe('sessionLogZipFilename', () => {
it('keeps safe session ids verbatim', () => {
@@ -22,3 +25,27 @@ describe('sessionLogZipFilename', () => {
expect(sessionLogZipFilename('..')).toBe('dsh-session-__.zip')
})
})
describe('downloadSessionLog', () => {
it('hands the descendant-inclusive endpoint directly to the browser', async () => {
const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
await downloadSessionLog('session/with spaces')
expect(click).toHaveBeenCalledOnce()
const anchor = click.mock.contexts[0] as HTMLAnchorElement
const url = new URL(anchor.href)
expect(url.pathname).toBe('/api/session.export')
expect(url.searchParams.get('sessionId')).toBe('session/with spaces')
expect(url.searchParams.get('includeDescendants')).toBe('true')
expect(anchor.download).toBe('dsh-session-session_with_spaces.zip')
})
it('rejects when the browser download handoff fails', async () => {
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {
throw new Error('download denied')
})
await expect(downloadSessionLog('session-root')).rejects.toThrow('download denied')
})
})

View File

@@ -1141,39 +1141,26 @@ describe('timeline projection', () => {
describe('session log export', () => {
afterEach(() => {
vi.unstubAllGlobals()
Reflect.deleteProperty(URL, 'createObjectURL')
Reflect.deleteProperty(HTMLAnchorElement.prototype, 'click')
})
it('downloads the host-streamed ZIP with descendants on click', async () => {
// exportLog always fetches a URL instance, so the mock's shape stays narrow.
const fetchMock = vi.fn(async (input: URL) => {
expect(input.pathname).toBe('/api/session.export')
expect(input.searchParams.get('sessionId')).toBe(SID)
expect(input.searchParams.get('includeDescendants')).toBe('true')
return new Response('zip-bytes')
})
vi.stubGlobal('fetch', fetchMock)
const createObjectURL = vi.fn(() => 'blob:export')
URL.createObjectURL = createObjectURL
const clickAnchor = vi.fn()
HTMLAnchorElement.prototype.click = clickAnchor
const b = await bench(historySnapshot(NODES))
mount(b.slots)
fireEvent.click(screen.getByRole('tab', { name: 'Trajectory' }))
fireEvent.click(screen.getByRole('button', { name: 'Export session log' }))
await vi.waitFor(() => {
expect(fetchMock).toHaveBeenCalledOnce()
})
// The blob download lands a few microtasks after the fetch settles.
await vi.waitFor(() => {
expect(createObjectURL).toHaveBeenCalled()
})
expect(clickAnchor).toHaveBeenCalled()
await vi.waitFor(() => { expect(clickAnchor).toHaveBeenCalledOnce() })
const anchor = clickAnchor.mock.contexts[0] as HTMLAnchorElement
const url = new URL(anchor.href)
expect(url.pathname).toBe('/api/session.export')
expect(url.searchParams.get('sessionId')).toBe(SID)
expect(url.searchParams.get('includeDescendants')).toBe('true')
})
it('surfaces the download failure in the visible alert bar', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('boom', { status: 404 })))
it('surfaces a browser handoff failure in the visible alert bar', async () => {
HTMLAnchorElement.prototype.click = vi.fn(() => { throw new Error('download denied') })
const b = await bench(historySnapshot(NODES))
mount(b.slots)
fireEvent.click(screen.getByRole('tab', { name: 'Trajectory' }))
@@ -1181,7 +1168,7 @@ describe('session log export', () => {
await vi.waitFor(() => {
const alert = screen.queryByRole('alert')
expect(alert).not.toBeNull()
expect(alert!.textContent).toContain('HTTP 404')
expect(alert!.textContent).toContain('download denied')
})
})
})