Merge remote-tracking branch 'origin/master' into worktree/web-plugin-config

This commit is contained in:
Yichen Jiang
2026-08-11 19:04:03 +08:00
55 changed files with 735 additions and 200 deletions

View File

@@ -2835,8 +2835,8 @@ function createFixtureWorld(options: FixtureOptions): FixtureWorld {
return Promise.resolve({ accepted: true })
},
// Satisfies the ApiProxy contract type only: the browser export button
// fetches GET /api/session.export directly (window.fetch), so this stub is
// never reached through the fixture's dispatch.
// hands GET /api/session.export to the native download manager, so this
// stub is never reached through the fixture's dispatch.
downloads: {
sessionLog: () => Promise.resolve(new Response('fixture mode does not serve session export', { status: 404 })),
},

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')
})
})
})