From a4493ceb39a9e2619837876adb14f33e432fe3da Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 16 Sep 2026 20:12:32 +0800 Subject: [PATCH 01/10] fix(deliverables): scroll the split review columns together on both axes Each unwrapped split column is its own scroll container, and only the horizontal offset was mirrored onto the other side, so wheel-scrolling one column left the other behind and the paired rows drifted apart. Mirror the vertical offset the same way. --- .../src/client/ReviewTab.module.css | 2 +- .../ui-deliverables/src/client/ReviewTab.tsx | 12 +++++++----- .../tests/review-tab.client.spec.tsx | 14 ++++++++------ 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/packages/client/ui-deliverables/src/client/ReviewTab.module.css b/packages/client/ui-deliverables/src/client/ReviewTab.module.css index 5ec23f198b..0405eda4fb 100644 --- a/packages/client/ui-deliverables/src/client/ReviewTab.module.css +++ b/packages/client/ui-deliverables/src/client/ReviewTab.module.css @@ -1,4 +1,4 @@ -/** Review tab: a file selector and icon tools in the document preview's header row, then numbered diff lines in the code font. Unwrapped split columns clip their lines and scroll sideways together; wrapped ones share rows so the sides stay aligned. */ +/** Review tab: a file selector and icon tools in the document preview's header row, then numbered diff lines in the code font. Unwrapped split columns clip their lines and scroll together on both axes; wrapped ones share rows so the sides stay aligned. */ .root { display: flex; flex-direction: column; box-sizing: border-box; width: 100%; height: 100%; min-height: 0; color: var(--dsw-alias-label-primary); } .header { display: flex; flex: 0 0 auto; gap: 6px; align-items: center; box-sizing: border-box; height: 38px; padding: 0 6px 0 8px; border-bottom: 0.5px solid var(--dsw-alias-border-l3); } .selector { flex: 0 1 auto; min-width: 0; } diff --git a/packages/client/ui-deliverables/src/client/ReviewTab.tsx b/packages/client/ui-deliverables/src/client/ReviewTab.tsx index 35a4350e6c..dbf2a7b40a 100644 --- a/packages/client/ui-deliverables/src/client/ReviewTab.tsx +++ b/packages/client/ui-deliverables/src/client/ReviewTab.tsx @@ -272,17 +272,19 @@ function hunkHeader(hunk: WorkspaceDiffHunk): string { /** * The side-by-side view without wrapping: two columns that clip their long - * lines and scroll sideways together, so a long line on one side never runs - * under the other and both sides show the same columns of text. Every line is - * one fixed-height row, which keeps the sides aligned. + * lines and scroll together on both axes, so a long line on one side never + * runs under the other and both sides show the same rows and columns of text. + * Every line is one fixed-height row, which keeps the sides aligned. */ function SplitColumns({ hunks }: { hunks: readonly WorkspaceDiffHunk[] }): ReactNode { const paired = useMemo(() => hunks.map(hunk => ({ header: hunkHeader(hunk), rows: splitRows(hunk) })), [hunks]) const columns = useRef>({ left: null, right: null }) - // Mirror one side's horizontal offset onto the other; the mirrored side's own scroll event then finds nothing to change. + // Mirror one side's offsets onto the other; the mirrored side's own scroll event then finds nothing to change. const follow = (side: 'left' | 'right') => (event: UIEvent): void => { const other = columns.current[side === 'left' ? 'right' : 'left'] - if (other !== null && other.scrollLeft !== event.currentTarget.scrollLeft) other.scrollLeft = event.currentTarget.scrollLeft + for (const axis of ['scrollLeft', 'scrollTop'] as const) { + if (other !== null && other[axis] !== event.currentTarget[axis]) other[axis] = event.currentTarget[axis] + } } return (
diff --git a/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx b/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx index 84e76ddc3a..92088e4622 100644 --- a/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx +++ b/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx @@ -238,14 +238,16 @@ describe('ReviewTab', () => { expect(side('left').map(line => line.getAttribute('data-diff-line'))).toEqual(['context', 'del', 'add', 'context', 'del', 'del']) expect(side('left').map(line => line.textContent)).toEqual(['1a', '2b', '', '3d', '10x', '20z']) expect(side('right').map(line => line.textContent)).toEqual(['1a', '2B', '3c', '4d', '11y', '']) - // The two sides scroll sideways together, whichever side the reader drags. + // The two sides scroll together on both axes, whichever side the reader drags. const [left, right] = ['left', 'right'].map(name => view.container.querySelector(`[data-diff-side="${name}"]`) as HTMLDivElement) - fireEvent.scroll(left!, { target: { scrollLeft: 40 } }) - expect(right!.scrollLeft).toBe(40) + fireEvent.scroll(left!, { target: { scrollLeft: 40, scrollTop: 66 } }) + expect([right!.scrollLeft, right!.scrollTop]).toEqual([40, 66]) fireEvent.scroll(right!, { target: { scrollLeft: 15 } }) - expect(left!.scrollLeft).toBe(15) - fireEvent.scroll(right!, { target: { scrollLeft: 15 } }) - expect(left!.scrollLeft).toBe(15) + expect([left!.scrollLeft, left!.scrollTop]).toEqual([15, 66]) + fireEvent.scroll(right!, { target: { scrollTop: 22 } }) + expect([left!.scrollLeft, left!.scrollTop]).toEqual([15, 22]) + fireEvent.scroll(right!, { target: { scrollLeft: 15, scrollTop: 22 } }) + expect([left!.scrollLeft, left!.scrollTop]).toEqual([15, 22]) expect(view.getByRole('button', { name: en['review.splitAria'] }).getAttribute('aria-pressed')).toBe('true') // Wrapped lines vary in height, so both sides share one row per pair. fireEvent.click(view.getByRole('button', { name: en['review.wrapAria'] })) From b5cbcad85481eb0fef1fc39bd2a1712da45947b7 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 18 Sep 2026 15:17:13 +0800 Subject: [PATCH 02/10] fix(web): preserve split diff scroll offsets across clamped peers --- apps/web/tests/changed-files-turn.e2e.ts | 37 +++++++++++++++++++ .../client/ui-deliverables/README.i18n.yaml | 4 +- packages/client/ui-deliverables/README.md | 2 + packages/client/ui-deliverables/README.zh.md | 2 + .../src/client/ReviewTab.module.css | 2 +- .../ui-deliverables/src/client/ReviewTab.tsx | 14 +++++-- .../tests/review-tab.client.spec.tsx | 8 ++++ 7 files changed, 63 insertions(+), 6 deletions(-) diff --git a/apps/web/tests/changed-files-turn.e2e.ts b/apps/web/tests/changed-files-turn.e2e.ts index 295c8d65fb..c7e94f0dec 100644 --- a/apps/web/tests/changed-files-turn.e2e.ts +++ b/apps/web/tests/changed-files-turn.e2e.ts @@ -157,6 +157,43 @@ describe('web e2e: a git workspace turn ends with its changed files', () => { await review.locator('[data-review-view="split"]').waitFor({ state: 'visible' }) await expect.poll(() => drawn(review.locator('[data-diff-side="left"]'))).toEqual(['del:1# 示例项目', 'context:2', 'context:3一个用于演示的仓库。']) expect(await drawn(review.locator('[data-diff-side="right"]'))).toEqual(['del:1# 项目说明', 'context:2', 'context:3一个用于演示的仓库。']) + // Constrain the recorded three-row diff to exercise unequal horizontal ranges and classic scrollbars. + const scrollLayout = await page.addStyleTag({ content: ` + [data-changes-review] { height: 120px !important; } + [data-diff-side] { scrollbar-width: auto; } + [data-diff-side]::-webkit-scrollbar { width: 16px; height: 16px; } + [data-diff-side="left"] { width: 65px; } + ` }) + try { + const left = review.locator('[data-diff-side="left"]') + const right = review.locator('[data-diff-side="right"]') + const metrics = (side: typeof left) => side.evaluate(element => ({ + x: element.scrollLeft, y: element.scrollTop, + maxX: element.scrollWidth - element.clientWidth, + maxY: element.scrollHeight - element.clientHeight, + bottom: element.lastElementChild!.getBoundingClientRect().bottom, + })) + const initialLeft = await metrics(left) + const initialRight = await metrics(right) + expect(initialLeft.maxX).toBeGreaterThan(0) + expect(initialRight.maxX).toBe(0) + expect(initialLeft.maxY).toBeGreaterThan(0) + expect(initialLeft.maxY).toBe(initialRight.maxY) + await left.evaluate((element) => { element.scrollLeft = element.scrollWidth }) + await expect.poll(async () => (await metrics(left)).x).toBe(initialLeft.maxX) + await left.evaluate((element) => { element.scrollTop = element.scrollHeight }) + await expect.poll(async () => (await metrics(right)).y).toBe(initialLeft.maxY) + // Two frames allow the browser-generated peer event to run before checking the source. + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))) + expect((await metrics(left)).x).toBe(initialLeft.maxX) + expect((await metrics(left)).y).toBe(initialLeft.maxY) + expect((await metrics(left)).bottom).toBeCloseTo((await metrics(right)).bottom, 1) + await right.evaluate((element) => { element.scrollTop = 0 }) + await expect.poll(async () => (await metrics(left)).y).toBe(0) + expect((await metrics(left)).x).toBe(initialLeft.maxX) + } finally { + await scrollLayout.evaluate(element => element.remove()) + } await review.getByRole('button', { name: '自动换行' }).click() await review.locator('[data-review-view][data-review-wrap]').waitFor({ state: 'visible' }) await expect.poll(() => drawn(review)).toEqual(['del:1# 示例项目1# 项目说明', 'context:22', 'context:3一个用于演示的仓库。3一个用于演示的仓库。']) diff --git a/packages/client/ui-deliverables/README.i18n.yaml b/packages/client/ui-deliverables/README.i18n.yaml index e1d9351ebc..457551a057 100644 --- a/packages/client/ui-deliverables/README.i18n.yaml +++ b/packages/client/ui-deliverables/README.i18n.yaml @@ -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-deliverables/README.md -README.md: 393fc8919bf64d71f5b61628871358aac0fc53d5 -README.zh.md: 1deeb28a04d7bfe07403559c14eb19da021b7e65 +README.md: a5d333353bd9c342be0549c70773ed38123e0ba8 +README.zh.md: 9704b73e5377491d6379bf8cf3424b4f30b2fda0 diff --git a/packages/client/ui-deliverables/README.md b/packages/client/ui-deliverables/README.md index 393fc8919b..a5d333353b 100644 --- a/packages/client/ui-deliverables/README.md +++ b/packages/client/ui-deliverables/README.md @@ -44,6 +44,8 @@ The card renders the summary the Host serves for the turn's latest `workspace/ch A row opens the turn's `changes-review` tab, addressed by the viewed Session and the announcing event's sequence and titled by the turn, on that row's file; another row of the same card reveals the same tab on its file. The header's file selector lists every recorded file with its counts and switches the comparison; the selected file's counts follow it. The header's tools switch between the unified view and a side-by-side view that pairs each run of deletions with the additions that follow it, switch line wrapping, open the whole current file in the Sidebar, and, with a Host desktop available, open it in the default application with the same pending and retryable-error states as the cards; the view and wrap choices are kept per tab. The tab reads the summary and each comparison once through the authenticated routes. A text comparison lists its hunks with the old and new line numbers of every line, additions and deletions in the success and error colours, and a note when the file was created or deleted in the turn, when both sides hold the same lines, when the Host's line comparison timed out and every line shows as replaced, or when the tab stopped drawing at 5,000 lines. A binary or oversized file, a comparison the Host no longer serves, and a failed read each show one line instead; a failed read offers Retry. The comparison is the turn's snapshot of the file, not its current content. +Without wrapping, the two columns synchronize vertical scrolling and horizontal offsets up to each side’s available range. Both horizontal scrollbars remain at the bottom of the visible comparison; scrolling vertically preserves a long line’s horizontal offset when the other side fits without horizontal scrolling. + ### Inline-code links The closing prose links produced or delivered paths: an inline-code token resolves by exact path, or by being exactly the basename of exactly one such path — a basename two paths share stays inert rather than guessing, so a mention can never open the wrong file. A resolved mention keeps its code chip and takes the markdown sheet's link language, with the full path as its title. diff --git a/packages/client/ui-deliverables/README.zh.md b/packages/client/ui-deliverables/README.zh.md index 1deeb28a04..9704b73e53 100644 --- a/packages/client/ui-deliverables/README.zh.md +++ b/packages/client/ui-deliverables/README.zh.md @@ -44,6 +44,8 @@ Web 的 `standard`、`ptc` 与 `cordis` preset 提供 `present` 用于声明交 行在该行的文件上打开本轮的 `changes-review` tab,其地址由当前查看的 Session 和宣告事件的序号组成,以轮号作标题;同一张卡片的另一行会在其文件上显示同一个 tab。头部的文件选择器列出所有记录的文件及其行数,用于切换对比;所选文件的行数跟在后面。头部的工具在单栏视图和左右视图之间切换,后者把每一段删除与紧随其后的新增逐行配对;切换自动换行;在 Sidebar 中打开当前整个文件;Host 有桌面时用默认应用打开它,等待与可重试错误状态与卡片一致。视图与换行的选择按 tab 保留。tab 通过经过认证的路由各读取一次摘要和每个对比。文本对比逐个列出 hunk,每一行带旧侧和新侧的行号,新增与删除分别用成功色和错误色,并在文件是本轮新建或删除、两侧内容相同、Host 的逐行对比超时而按整文件替换显示,或 tab 在 5000 行处停止绘制时给出一行说明。二进制或过大的文件、Host 已不再提供的对比,以及读取失败各显示一行提示;读取失败时提供重试。对比是本轮对该文件的快照,不是它当前的内容。 +关闭自动换行时,两列同步纵向滚动,横向偏移同步到各自可滚动范围内。两侧横向滚动条始终位于可见对比区域底部;如果只有一侧需要横向滚动,上下滚动会保留该侧的横向偏移。 + ### 行内代码链接 收尾正文链接产出或已交付的路径:行内代码 token 按精确路径解析,或当它恰好等于其中某条路径的 basename 且该路径唯一时解析——两条路径共享同一 basename 时保持不可点击而不作猜测,因此提及绝不打开错误的文件。解析成功的提及保留代码标签,并采用 Markdown 样式表的链接样式,完整路径作为其 `title`。 diff --git a/packages/client/ui-deliverables/src/client/ReviewTab.module.css b/packages/client/ui-deliverables/src/client/ReviewTab.module.css index 0405eda4fb..aef4abf94f 100644 --- a/packages/client/ui-deliverables/src/client/ReviewTab.module.css +++ b/packages/client/ui-deliverables/src/client/ReviewTab.module.css @@ -22,7 +22,7 @@ .status { display: flex; gap: 12px; align-items: center; margin: 0; padding: 16px; font-size: 13px; color: var(--dsw-alias-label-secondary); } .body { display: flex; flex: 1 1 auto; flex-direction: column; min-height: 0; overflow: auto; padding: 8px 0 16px; font: var(--dsw-font-markdown-code-block); } .columns { display: grid; flex: 1 1 auto; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); min-height: 0; } -.column { min-width: 0; overflow-x: auto; } +.column { min-width: 0; overflow-x: scroll; } .column + .column { border-left: 0.5px solid var(--dsw-alias-border-l3); } .sideLine { display: grid; grid-template-columns: 3.5em max-content; box-sizing: border-box; min-width: 100%; width: max-content; min-height: 22px; line-height: 22px; white-space: pre; } .note { margin: 0; padding: 4px 16px 8px; font: var(--dsw-font-xs-13); color: var(--dsw-alias-label-tertiary); } diff --git a/packages/client/ui-deliverables/src/client/ReviewTab.tsx b/packages/client/ui-deliverables/src/client/ReviewTab.tsx index 8572eae364..7749023260 100644 --- a/packages/client/ui-deliverables/src/client/ReviewTab.tsx +++ b/packages/client/ui-deliverables/src/client/ReviewTab.tsx @@ -280,11 +280,19 @@ function hunkHeader(hunk: WorkspaceDiffHunk): string { function SplitColumns({ hunks }: { hunks: readonly WorkspaceDiffHunk[] }): ReactNode { const paired = useMemo(() => hunks.map(hunk => ({ header: hunkHeader(hunk), rows: splitRows(hunk) })), [hunks]) const columns = useRef>({ left: null, right: null }) - // Mirror one side's offsets onto the other; the mirrored side's own scroll event then finds nothing to change. + const offsets = useRef({ left: { scrollLeft: 0, scrollTop: 0 }, right: { scrollLeft: 0, scrollTop: 0 } }) const follow = (side: 'left' | 'right') => (event: UIEvent): void => { - const other = columns.current[side === 'left' ? 'right' : 'left'] + const peer = side === 'left' ? 'right' : 'left' + const other = columns.current[peer] for (const axis of ['scrollLeft', 'scrollTop'] as const) { - if (other !== null && other[axis] !== event.currentTarget[axis]) other[axis] = event.currentTarget[axis] + const value = event.currentTarget[axis] + if (offsets.current[side][axis] === value) continue + offsets.current[side][axis] = value + if (other !== null) { + other[axis] = value + // Record the browser-clamped offset so its scroll event cannot pull the source back. + offsets.current[peer][axis] = other[axis] + } } } return ( diff --git a/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx b/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx index 92088e4622..5ae0970da4 100644 --- a/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx +++ b/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx @@ -248,6 +248,14 @@ describe('ReviewTab', () => { expect([left!.scrollLeft, left!.scrollTop]).toEqual([15, 22]) fireEvent.scroll(right!, { target: { scrollLeft: 15, scrollTop: 22 } }) expect([left!.scrollLeft, left!.scrollTop]).toEqual([15, 22]) + // A short peer clamps horizontal writes to zero, including the resulting scroll event. + Object.defineProperty(right, 'scrollLeft', { configurable: true, get: () => 0, set: () => {} }) + fireEvent.scroll(left!, { target: { scrollLeft: 100 } }) + fireEvent.scroll(right!) + expect(left!.scrollLeft).toBe(100) + fireEvent.scroll(left!, { target: { scrollTop: 44 } }) + fireEvent.scroll(right!) + expect([left!.scrollLeft, right!.scrollTop]).toEqual([100, 44]) expect(view.getByRole('button', { name: en['review.splitAria'] }).getAttribute('aria-pressed')).toBe('true') // Wrapped lines vary in height, so both sides share one row per pair. fireEvent.click(view.getByRole('button', { name: en['review.wrapAria'] })) From cc9caed57b2b4c2b40f9a40325ffd0a22fa825e7 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 18 Sep 2026 15:19:50 +0800 Subject: [PATCH 03/10] fix(web): type browser regression style cleanup as Node --- apps/web/tests/changed-files-turn.e2e.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/tests/changed-files-turn.e2e.ts b/apps/web/tests/changed-files-turn.e2e.ts index c7e94f0dec..aa5729df55 100644 --- a/apps/web/tests/changed-files-turn.e2e.ts +++ b/apps/web/tests/changed-files-turn.e2e.ts @@ -192,7 +192,7 @@ describe('web e2e: a git workspace turn ends with its changed files', () => { await expect.poll(async () => (await metrics(left)).y).toBe(0) expect((await metrics(left)).x).toBe(initialLeft.maxX) } finally { - await scrollLayout.evaluate(element => element.remove()) + await scrollLayout.evaluate(element => element.parentNode!.removeChild(element)) } await review.getByRole('button', { name: '自动换行' }).click() await review.locator('[data-review-view][data-review-wrap]').waitFor({ state: 'visible' }) From 419d7c57c7332af7158658383e9d99e52750fb85 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 18 Sep 2026 15:23:00 +0800 Subject: [PATCH 04/10] fix(web): make scroll frame callback return explicit --- apps/web/tests/changed-files-turn.e2e.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/tests/changed-files-turn.e2e.ts b/apps/web/tests/changed-files-turn.e2e.ts index aa5729df55..fd85c388f8 100644 --- a/apps/web/tests/changed-files-turn.e2e.ts +++ b/apps/web/tests/changed-files-turn.e2e.ts @@ -184,7 +184,7 @@ describe('web e2e: a git workspace turn ends with its changed files', () => { await left.evaluate((element) => { element.scrollTop = element.scrollHeight }) await expect.poll(async () => (await metrics(right)).y).toBe(initialLeft.maxY) // Two frames allow the browser-generated peer event to run before checking the source. - await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())))) + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => { resolve() })))) expect((await metrics(left)).x).toBe(initialLeft.maxX) expect((await metrics(left)).y).toBe(initialLeft.maxY) expect((await metrics(left)).bottom).toBeCloseTo((await metrics(right)).bottom, 1) From 8f2a1835145ce1c5b13680be4a78f37341d4564a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 18 Sep 2026 15:26:22 +0800 Subject: [PATCH 05/10] fix(web): document paired column ref lifetime --- .../client/ui-deliverables/src/client/ReviewTab.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/client/ui-deliverables/src/client/ReviewTab.tsx b/packages/client/ui-deliverables/src/client/ReviewTab.tsx index 7749023260..cebabaccd3 100644 --- a/packages/client/ui-deliverables/src/client/ReviewTab.tsx +++ b/packages/client/ui-deliverables/src/client/ReviewTab.tsx @@ -284,15 +284,15 @@ function SplitColumns({ hunks }: { hunks: readonly WorkspaceDiffHunk[] }): React const follow = (side: 'left' | 'right') => (event: UIEvent): void => { const peer = side === 'left' ? 'right' : 'left' const other = columns.current[peer] + /* v8 ignore next -- Both column refs are attached before browser scroll events can run. */ + if (other === null) return for (const axis of ['scrollLeft', 'scrollTop'] as const) { const value = event.currentTarget[axis] if (offsets.current[side][axis] === value) continue offsets.current[side][axis] = value - if (other !== null) { - other[axis] = value - // Record the browser-clamped offset so its scroll event cannot pull the source back. - offsets.current[peer][axis] = other[axis] - } + other[axis] = value + // Record the browser-clamped offset so its scroll event cannot pull the source back. + offsets.current[peer][axis] = other[axis] } } return ( From 3e216c3d64fdd7892ddfdfef554372d1fb23ea17 Mon Sep 17 00:00:00 2001 From: lsdsjy Date: Fri, 18 Sep 2026 15:35:50 +0800 Subject: [PATCH 06/10] feat(ui-chat): add performance and usage display preference (#4478) * feat(ui-chat): add performance and usage display preference * fix(ui-chat): address performance preference review findings * test(ui-chat): refresh Chinese turn footer snapshots * docs(ui-chat): clarify completed-turn timing visibility * test(ui-chat): capture preference failure screenshots * fix(ui-chat): align performance preference with current icons --------- Co-authored-by: lsdsjy <1356263+lsdsjy@users.noreply.github.com> --- ...-07-composer-session-stats-pills.i18n.yaml | 4 +- ...2026-09-07-composer-session-stats-pills.md | 2 + ...6-09-07-composer-session-stats-pills.zh.md | 2 + ...-16-performance-usage-preference.i18n.yaml | 6 ++ ...2026-09-16-performance-usage-preference.md | 31 +++++++ ...6-09-16-performance-usage-preference.zh.md | 31 +++++++ .../clickable-links-gallery/ui.expected.md | 1 - .../expected/cordis-history/ui.expected.md | 3 - .../conversation-expanded.expected.md | 1 - .../conversation.expected.md | 1 - .../markdown-cjk-strong/ui.expected.md | 1 - .../expected/markdown-images/ui.expected.md | 1 - .../markdown-inline-code-links/ui.expected.md | 1 - .../expected/math-rendering/ui.expected.md | 1 - .../settings-chrome/dialog-en.expected.md | 2 + .../settings-chrome/dialog.expected.md | 2 + .../skill-user-invoke/ui-expanded.expected.md | 1 - .../expected/skill-user-invoke/ui.expected.md | 1 - .../stats-paged-history/ui.expected.md | 28 ------ .../steer-all/settled-expanded.expected.md | 1 - .../expected/steer-all/settled.expected.md | 1 - apps/web/tests/message-actions.e2e.ts | 33 ++++++- apps/web/tests/skill-tool-row.e2e.ts | 1 - apps/web/tests/turn-tail-actions.e2e.ts | 17 +--- packages/client/ui-chat/README.i18n.yaml | 4 +- packages/client/ui-chat/README.md | 4 +- packages/client/ui-chat/README.zh.md | 4 +- packages/client/ui-chat/src/chat-settings.ts | 14 ++- packages/client/ui-chat/src/client/apply.ts | 23 ++++- .../ui-chat/src/client/chat/StatsPills.tsx | 31 +++++-- .../src/client/chat/TurnTailNodeView.tsx | 29 ++---- .../src/client/chat/TurnUsagePanel.tsx | 76 +-------------- .../ui-chat/src/client/chat/message-chrome.ts | 13 +-- .../client/chat/register-node-renderers.ts | 6 +- .../ui-chat/src/client/contract/chat-nodes.ts | 2 - .../ui-chat/src/client/contract/slots.ts | 12 ++- .../src/client/contract/turn-metrics.ts | 60 +----------- .../client/conversation-nodes/turn-tail.ts | 4 - packages/client/ui-chat/src/client/locale.ts | 18 ++-- .../ui-chat/src/client/performance-usage.ts | 30 ++++++ .../client/settings/PerformanceUsageRow.tsx | 46 +++++++++ ...ow.module.css => PreferenceRow.module.css} | 2 +- .../src/client/settings/PreferenceRow.tsx | 56 +++++++++++ .../src/client/settings/TranscriptViewRow.tsx | 47 ++-------- .../ui-chat/tests/chat-apply.client.spec.tsx | 24 ++++- .../tests/chat-branch-tails.client.spec.tsx | 1 + .../tests/chat-settings.client.spec.ts | 7 +- .../tests/chat-snapshot-fixture.client.ts | 4 - .../ui-chat/tests/chat-stats.client.spec.tsx | 23 ++++- .../ui-chat/tests/chat-view.client.spec.tsx | 33 +++---- ...nversation-node-definitions.client.spec.ts | 2 - .../tests/gate-branch-tails.client.spec.tsx | 1 + .../tests/performance-usage.client.spec.ts | 30 ++++++ .../transcript-view-policy.client.spec.ts | 6 +- .../tests/transcript-view-row.client.spec.tsx | 24 ++++- .../ui-chat/tests/turn-metrics.client.spec.ts | 93 +------------------ .../tests/turn-usage-panel.client.spec.tsx | 37 +------- .../src/client/slot-catalog.ts | 11 ++- .../web/changed-files-turn/ui.expected.md | 1 - .../web/deepseek-messages-chat/ui.expected.md | 1 - .../feedback-command/ack-expanded.expected.md | 1 - .../web/feedback-command/ack.expected.md | 1 - .../feedback-release/ack-expanded.expected.md | 1 - .../web/feedback-release/ack.expected.md | 1 - .../web/file-upload-round/ui.expected.md | 1 - .../fresh-round-trip/ui-expanded.expected.md | 1 - snapshots/web/fresh-round-trip/ui.expected.md | 1 - .../ui-expanded.expected.md | 2 - .../goal-multi-turn-actions/ui.expected.md | 2 - .../reloaded-expanded.expected.md | 1 - .../web/lifecycle-chrome/reloaded.expected.md | 1 - .../cancel-expanded.expected.md | 1 - .../web/live-interactions/cancel.expected.md | 1 - .../retry-expanded.expected.md | 1 - .../web/live-interactions/retry.expected.md | 1 - .../web/message-actions/compact.expected.md | 1 + snapshots/web/message-actions/ui.expected.md | 6 +- snapshots/web/minimal-preset/ui.expected.md | 1 - .../plan-review/approved-expanded.expected.md | 1 - .../web/plan-review/approved.expected.md | 1 - snapshots/web/present-svg/ui.expected.md | 1 - snapshots/web/present/ui.expected.md | 1 - snapshots/web/ptc-round/ui.expected.md | 1 - .../answered-expanded.expected.md | 1 - .../question-composer/answered.expected.md | 1 - .../preserved-expanded.expected.md | 1 - .../web/queue-actions/preserved.expected.md | 1 - .../web/queued-image/delivered.expected.md | 3 - .../seeded-history/command-row.expected.md | 1 - .../seeded-history/feedback-row.expected.md | 1 - .../seeded-history/ui-expanded.expected.md | 1 - snapshots/web/seeded-history/ui.expected.md | 1 - snapshots/web/skill-tool-row/ui.expected.md | 1 - .../web/steering/settled-expanded.expected.md | 1 - snapshots/web/steering/settled.expected.md | 1 - .../sidebar-chat.expected.md | 1 - .../ui-expanded.expected.md | 2 - .../web/subagent-conversation/ui.expected.md | 2 - .../turn-tail-actions/completed.expected.md | 1 - .../web/turn-tail-actions/focused.expected.md | 1 - .../web/turn-tail-actions/settled.expected.md | 1 - .../usage-expanded.expected.md | 1 - snapshots/web/web-search-round/ui.expected.md | 1 - snapshots/web/workflow-run/ui.expected.md | 1 - 104 files changed, 488 insertions(+), 519 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-09-16-performance-usage-preference.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-09-16-performance-usage-preference.md create mode 100644 .agents/notes/implemented/feature/2026-09-16-performance-usage-preference.zh.md create mode 100644 packages/client/ui-chat/src/client/performance-usage.ts create mode 100644 packages/client/ui-chat/src/client/settings/PerformanceUsageRow.tsx rename packages/client/ui-chat/src/client/settings/{TranscriptViewRow.module.css => PreferenceRow.module.css} (92%) create mode 100644 packages/client/ui-chat/src/client/settings/PreferenceRow.tsx create mode 100644 packages/client/ui-chat/tests/performance-usage.client.spec.ts create mode 100644 snapshots/web/message-actions/compact.expected.md diff --git a/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.i18n.yaml b/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.i18n.yaml index 0c2c513623..d4ef512e91 100644 --- a/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.i18n.yaml @@ -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-09-07-composer-session-stats-pills.md -2026-09-07-composer-session-stats-pills.md: d165aab471bc5958cb7a0b287d278a0ae48485ee -2026-09-07-composer-session-stats-pills.zh.md: dac136d4e60e50b026ed082eb7a006a80059c328 +2026-09-07-composer-session-stats-pills.md: 50d3d3294ed012773657ba9849e45835c361d8be +2026-09-07-composer-session-stats-pills.zh.md: 97b91b601e62e8b06ab13a764babb4dd3b25bfce diff --git a/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.md b/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.md index d165aab471..50d3d3294e 100644 --- a/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.md +++ b/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.md @@ -10,6 +10,8 @@ The session stats strip under the composer (`StatsLine`, ui-chat, mounted on `co ## Decision +The [performance and usage preference](2026-09-16-performance-usage-preference.md) governs statistic visibility and removes the completed-turn elapsed-time action. + `StatsPills` (packages/client/ui-chat/src/client/chat/StatsPills.tsx) replaces `StatsLine` on the same `conversation.composer.dock` slot; the losing variant is deleted, its shared helpers (`deriveStats`, `formatDuration`, `cacheHitPercent`, `billedInputTokens`) absorbed into the new module, and the dead `stats.llm`, `stats.toolCall`, `stats.ttftAverage`, `stats.tokensPerSecond`, and `stats.tokens` locale keys removed. - **Two icon pills, two dialogs.** A gauge pill (new `IconGaugeOutlineRegular`, dial center optically dropped to y=8.75 because the bottom-open arc reads high) shows `{turns} 轮 {steps} 步` plus output TPS and click-opens the 会话统计 dialog (LLM time, tool time, average TTFT, TPS); a log with no timed figure would open an empty dialog, so that pill renders as a static reading instead of a button. A database pill (`IconDatabaseOutlineRegular`) shows the compact billed total plus cache-hit share and click-opens the Token 用量 dialog (cache hit, uncached input, cache read, output, and cache write when non-zero — exact counts). Both dialogs wear the shared `stat-dialog` module (portal panel, anchored placement, outside-dismiss, optionally externally owned open state) extracted for exactly this two-consumer split; the pills row owns one exclusive open slot, so opening either dialog closes the other, and each button carries an explicit `aria-label` that separates with ` · ` the segments the aria-hidden sep glyph joins visually. [StatsPills](../../../../packages/client/ui-chat/src/client/chat/StatsPills.tsx) owns the zero cache-write omission. diff --git a/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.zh.md b/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.zh.md index dac136d4e6..97b91b601e 100644 --- a/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.zh.md +++ b/.agents/notes/implemented/feature/2026-09-07-composer-session-stats-pills.zh.md @@ -10,6 +10,8 @@ Status: implemented ## 决定 +[性能与用量偏好](2026-09-16-performance-usage-preference.zh.md)管理统计可见性,并移除已完成轮次的耗时操作。 + `StatsPills`(packages/client/ui-chat/src/client/chat/StatsPills.tsx)在同一 `conversation.composer.dock` 插槽上取代 `StatsLine`;落选变体已删除,其共享工具函数(`deriveStats`、`formatDuration`、`cacheHitPercent`、`billedInputTokens`)并入新模块,废弃的 `stats.llm`、`stats.toolCall`、`stats.ttftAverage`、`stats.tokensPerSecond`、`stats.tokens` 文案键一并移除。 - **两个图标 pill、两个弹层。** 仪表盘 pill(新增 `IconGaugeOutlineRegular`,因下开口圆弧视觉偏高而把表盘中心光学下移到 y=8.75)展示 `{turns} 轮 {steps} 步` 加输出 TPS,点击打开「会话统计」弹层(模型用时、工具调用用时、首 token 平均、输出速度);日志里没有任何计时数字时弹层会是空的,此时该 pill 渲染为静态读数而非按钮。数据库 pill(`IconDatabaseOutlineRegular`)展示紧凑计费总量加缓存命中率,点击打开「Token 用量」弹层(缓存命中、未缓存输入、缓存读取、输出,以及非零时的缓存写入——精确计数)。两个弹层共用为这两处消费者抽出的 `stat-dialog` 模块(portal 面板、锚定定位、点击外部关闭、可选的外部持有开合状态);pill 行持有唯一的互斥开合槽位,打开任一弹层即关闭另一个,且每个按钮携带显式 `aria-label`,用 ` · ` 分隔 aria-hidden 分隔符在视觉上连接的两段文本。[StatsPills](../../../../packages/client/ui-chat/src/client/chat/StatsPills.tsx)负责缓存写入为零时省略该行的规则。 diff --git a/.agents/notes/implemented/feature/2026-09-16-performance-usage-preference.i18n.yaml b/.agents/notes/implemented/feature/2026-09-16-performance-usage-preference.i18n.yaml new file mode 100644 index 0000000000..2da6cd2bfa --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-16-performance-usage-preference.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# 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-09-16-performance-usage-preference.md +2026-09-16-performance-usage-preference.md: 36ab30561fccc6c824ee8483f5a533a9178f11c5 +2026-09-16-performance-usage-preference.zh.md: ecfd19c41c861116d18829b355bf8c8df4ea929a diff --git a/.agents/notes/implemented/feature/2026-09-16-performance-usage-preference.md b/.agents/notes/implemented/feature/2026-09-16-performance-usage-preference.md new file mode 100644 index 0000000000..36ab30561f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-16-performance-usage-preference.md @@ -0,0 +1,31 @@ +# Agent Note: Performance and usage detail preference + +Status: implemented + +English | [中文](2026-09-16-performance-usage-preference.zh.md) + +## Problem + +Always-visible counts and accounting controls add density to Chat even when readers only need output speed and cache effectiveness. + +## Decision + +Chat owns `ui-chat.performanceUsage` in its existing settings namespace. General Settings offers Compact and Detailed, with Detailed as the default to preserve access to accounting. Both the composer and turn-tail renderer consume the same accepted settings source through framework-bound hooks. Host settings own persistence, validation, and failed-write recovery. + +Compact retains only available output speed and cache-hit percentage under the composer. These readings are plain text with no statistics dialog. Detailed retains session statistic dialogs and per-Turn usage. Neither mode renders the elapsed-time action in the completed-turn footer. This preference changes presentation, never telemetry collection, accounting, or Session events. + +The [composer statistics decision](2026-09-07-composer-session-stats-pills.md) remains authoritative for accounting sources, dialog exclusivity, and composer spacing in Detailed mode. + +The requested footer design prioritizes message actions and token accounting in both modes. Completed turns therefore expose no per-turn elapsed-time control; Detailed restores accounting detail, not that control. The running clock and session-wide timing statistics remain independent of this choice. + +## Alternatives considered + +**Default to Compact.** This would hide accounting controls for existing users without an explicit choice. The request defines both modes but no default, so Detailed preserves their access. + +**Filter telemetry when Compact is selected.** This would discard information needed after switching to Detailed or reopening history. A display preference must not change recorded data. + +## Consequences + +Unavailable speed or cache-hit data is omitted rather than replaced with invented values. The settings scope provides one accepted value to all consumers without duplicating subscription state. Component coverage checks mode-specific visibility; the [recorded-session browser scenario](../../../../apps/web/tests/message-actions.e2e.ts) exercises selection, reload persistence, and Compact output. + +On non-loopback browsers, the preference remains process-local because the settings scope cannot persist writes. Explicit selections update every consumer immediately; accepted Host settings reconcile the live value on loopback browsers. diff --git a/.agents/notes/implemented/feature/2026-09-16-performance-usage-preference.zh.md b/.agents/notes/implemented/feature/2026-09-16-performance-usage-preference.zh.md new file mode 100644 index 0000000000..ecfd19c41c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-16-performance-usage-preference.zh.md @@ -0,0 +1,31 @@ +# Agent Note:性能与用量详细程度偏好 + +Status: implemented + +[English](2026-09-16-performance-usage-preference.md) | 中文 + +## Problem + +当读者只需要输出速度和缓存效果时,始终显示的计数和记账控件会增加聊天界面的密度。 + +## Decision + +Chat 在既有设置命名空间中拥有 `ui-chat.performanceUsage`。通用设置提供简洁和详细选项,默认详细以保留记账入口。输入框和轮次页脚渲染器通过框架绑定的 Hook 消费同一个已接受设置源。Host 设置负责持久化、校验和写入失败恢复。 + +简洁模式仅在输入框下方保留可用的输出速度和缓存命中率。这些读数为纯文本,不提供统计卡片。详细模式保留会话统计卡片和每轮用量。两种模式均不渲染已完成轮次页脚中的耗时操作。该偏好只改变展示,不改变遥测收集、记账或 Session 事件。 + +[输入框统计决策](2026-09-07-composer-session-stats-pills.zh.md)仍负责详细模式中的记账来源、卡片互斥和输入框间距。 + +所要求的页脚设计在两种模式下均优先展示消息操作和 token 记账。因此,已完成轮次不提供单轮耗时控件;详细模式恢复记账详情,不恢复该控件。运行中的时钟和会话级计时统计独立于此选择。 + +## Alternatives considered + +**默认简洁。** 这会在已有用户未明确选择时隐藏记账控件。需求定义了两种模式但未指定默认值,因此详细模式保留既有入口。 + +**选择简洁时过滤遥测。** 这会丢弃切换回详细模式或重新打开历史时需要的信息。展示偏好不能改变记录数据。 + +## Consequences + +不可用的速度或缓存命中数据会被省略,不填入虚构值。设置作用域为所有消费者提供同一个已接受值,无需复制订阅状态。组件覆盖检查不同模式的可见性;[录制会话浏览器场景](../../../../apps/web/tests/message-actions.e2e.ts)验证选择、刷新持久化和简洁模式输出。 + +在非回环地址浏览器中,设置作用域无法持久化写入,因此该偏好仅在当前进程内生效。明确选择会立即更新所有使用方;回环地址浏览器收到 Host 已接受的设置后会同步当前值。 diff --git a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md index 1634cf19fe..67f77b8b26 100644 --- a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md +++ b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md @@ -146,7 +146,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "Back to bottom" - textbox "Message or run a task, / commands, @ files or sessions" diff --git a/apps/web/tests/expected/cordis-history/ui.expected.md b/apps/web/tests/expected/cordis-history/ui.expected.md index 16ea029e39..db5236e711 100644 --- a/apps/web/tests/expected/cordis-history/ui.expected.md +++ b/apps/web/tests/expected/cordis-history/ui.expected.md @@ -38,7 +38,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 9/1 {{clock}} - button "Thought for a while" - paragraph: The Cordis Plugin is running. @@ -46,7 +45,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 9/1 {{clock}} Use only Cordis tools. Call cordis_stop with pluginId "snap-1". After it succeeds, reply exactly CORDIS_UI_DONE and stop. 9/1 {{clock}} - button "Copy" - button "1 tool call" [expanded] @@ -58,7 +56,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 9/1 {{clock}} - button "Back to bottom" - textbox "Message or run a task, / commands, @ files or sessions" diff --git a/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md b/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md index 138f34efad..610d173e1e 100644 --- a/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md +++ b/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md @@ -24,7 +24,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/apps/web/tests/expected/github-ready-review/conversation.expected.md b/apps/web/tests/expected/github-ready-review/conversation.expected.md index a5be99f8ee..7167daea13 100644 --- a/apps/web/tests/expected/github-ready-review/conversation.expected.md +++ b/apps/web/tests/expected/github-ready-review/conversation.expected.md @@ -22,7 +22,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md b/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md index bc95d13b0e..c8f054e060 100644 --- a/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md +++ b/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md @@ -38,7 +38,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/apps/web/tests/expected/markdown-images/ui.expected.md b/apps/web/tests/expected/markdown-images/ui.expected.md index 3794be0c0c..be7317eb3e 100644 --- a/apps/web/tests/expected/markdown-images/ui.expected.md +++ b/apps/web/tests/expected/markdown-images/ui.expected.md @@ -24,7 +24,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md b/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md index 1428ede808..c637b199dd 100644 --- a/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md +++ b/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md @@ -28,7 +28,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/apps/web/tests/expected/math-rendering/ui.expected.md b/apps/web/tests/expected/math-rendering/ui.expected.md index df043015fa..faab58a5b2 100644 --- a/apps/web/tests/expected/math-rendering/ui.expected.md +++ b/apps/web/tests/expected/math-rendering/ui.expected.md @@ -33,7 +33,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/apps/web/tests/expected/settings-chrome/dialog-en.expected.md b/apps/web/tests/expected/settings-chrome/dialog-en.expected.md index f06841fc54..ace79f9802 100644 --- a/apps/web/tests/expected/settings-chrome/dialog-en.expected.md +++ b/apps/web/tests/expected/settings-chrome/dialog-en.expected.md @@ -21,6 +21,8 @@ - button "Decrease font size" - text: px Conversation display Controls process content in completed turns - button "Compact" + - text: Performance & usage Choose how much performance and usage information to show + - button "Detailed" - text: Developer tools Show tools and information for debugging and troubleshooting - switch "Developer tools" - text: Send behavior while busy What Enter and the Send button do while the agent is running; Cmd/Ctrl+Enter uses the other behavior diff --git a/apps/web/tests/expected/settings-chrome/dialog.expected.md b/apps/web/tests/expected/settings-chrome/dialog.expected.md index 0cd84e6a3c..212fabd235 100644 --- a/apps/web/tests/expected/settings-chrome/dialog.expected.md +++ b/apps/web/tests/expected/settings-chrome/dialog.expected.md @@ -21,6 +21,8 @@ - button "减小字号" - text: px 对话显示 控制已完成轮次的过程内容 - button "紧凑" + - text: 性能与用量 选择性能与用量信息展示的详细程度 + - button "详细" - text: 开发者工具 显示用于调试和排查问题的工具与信息 - switch "开发者工具" - text: 繁忙时的发送行为 智能体运行时 Enter 键和发送按钮的行为;Cmd/Ctrl+Enter 使用另一行为 diff --git a/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md b/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md index 6be4b09786..49ff06f442 100644 --- a/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md +++ b/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md @@ -20,7 +20,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/apps/web/tests/expected/skill-user-invoke/ui.expected.md b/apps/web/tests/expected/skill-user-invoke/ui.expected.md index 84934122b6..dc6265c650 100644 --- a/apps/web/tests/expected/skill-user-invoke/ui.expected.md +++ b/apps/web/tests/expected/skill-user-invoke/ui.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/apps/web/tests/expected/stats-paged-history/ui.expected.md b/apps/web/tests/expected/stats-paged-history/ui.expected.md index 706dd17b41..579e3689d4 100644 --- a/apps/web/tests/expected/stats-paged-history/ui.expected.md +++ b/apps/web/tests/expected/stats-paged-history/ui.expected.md @@ -42,7 +42,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m2 7/25 {{clock}} - button "Copy" - paragraph: r2 @@ -50,7 +49,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m3 7/25 {{clock}} - button "Copy" - paragraph: r3 @@ -58,7 +56,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m4 7/25 {{clock}} - button "Copy" - paragraph: r4 @@ -66,7 +63,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m5 7/25 {{clock}} - button "Copy" - paragraph: r5 @@ -74,7 +70,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m6 7/25 {{clock}} - button "Copy" - paragraph: r6 @@ -82,7 +77,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m7 7/25 {{clock}} - button "Copy" - paragraph: r7 @@ -90,7 +84,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m8 7/25 {{clock}} - button "Copy" - paragraph: r8 @@ -98,7 +91,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m9 7/25 {{clock}} - button "Copy" - paragraph: r9 @@ -106,7 +98,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m10 7/25 {{clock}} - button "Copy" - paragraph: r10 @@ -114,7 +105,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m11 7/25 {{clock}} - button "Copy" - paragraph: r11 @@ -122,7 +112,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m12 7/25 {{clock}} - button "Copy" - paragraph: r12 @@ -130,7 +119,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m13 7/25 {{clock}} - button "Copy" - paragraph: r13 @@ -138,7 +126,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m14 7/25 {{clock}} - button "Copy" - paragraph: r14 @@ -146,7 +133,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m15 7/25 {{clock}} - button "Copy" - paragraph: r15 @@ -154,7 +140,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m16 7/25 {{clock}} - button "Copy" - paragraph: r16 @@ -162,7 +147,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m17 7/25 {{clock}} - button "Copy" - paragraph: r17 @@ -170,7 +154,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m18 7/25 {{clock}} - button "Copy" - paragraph: r18 @@ -178,7 +161,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m19 7/25 {{clock}} - button "Copy" - paragraph: r19 @@ -186,7 +168,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m20 7/25 {{clock}} - button "Copy" - paragraph: r20 @@ -194,7 +175,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m21 7/25 {{clock}} - button "Copy" - paragraph: r21 @@ -202,7 +182,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m22 7/25 {{clock}} - button "Copy" - paragraph: r22 @@ -210,7 +189,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m23 7/25 {{clock}} - button "Copy" - paragraph: r23 @@ -218,7 +196,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m24 7/25 {{clock}} - button "Copy" - paragraph: r24 @@ -226,7 +203,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m25 7/25 {{clock}} - button "Copy" - paragraph: r25 @@ -234,7 +210,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m26 7/25 {{clock}} - button "Copy" - paragraph: r26 @@ -242,7 +217,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m27 7/25 {{clock}} - button "Copy" - paragraph: r27 @@ -250,7 +224,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} m28 7/25 {{clock}} - button "Copy" - paragraph: r28 @@ -258,7 +231,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: 7/25 {{clock}} - button "Back to bottom" - textbox "Message or run a task, / commands, @ files or sessions" diff --git a/apps/web/tests/expected/steer-all/settled-expanded.expected.md b/apps/web/tests/expected/steer-all/settled-expanded.expected.md index 02f1062df9..4e6fcc0ac8 100644 --- a/apps/web/tests/expected/steer-all/settled-expanded.expected.md +++ b/apps/web/tests/expected/steer-all/settled-expanded.expected.md @@ -23,7 +23,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/apps/web/tests/expected/steer-all/settled.expected.md b/apps/web/tests/expected/steer-all/settled.expected.md index 5efb1d79ff..28daa440d7 100644 --- a/apps/web/tests/expected/steer-all/settled.expected.md +++ b/apps/web/tests/expected/steer-all/settled.expected.md @@ -20,7 +20,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/apps/web/tests/message-actions.e2e.ts b/apps/web/tests/message-actions.e2e.ts index 2d4061c414..85a16c58a5 100644 --- a/apps/web/tests/message-actions.e2e.ts +++ b/apps/web/tests/message-actions.e2e.ts @@ -11,7 +11,7 @@ import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { SessionId } from '@deepseek-ai/dsh-session' import { - assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, + acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, parseSeedFixture, renderSeedFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { newEnglishPage, saveFailureShot } from './support.ts' @@ -313,6 +313,35 @@ describe('web e2e: message IconActions and clocks on settled history', () => { await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) }) + it.skipIf(MODE === 'record')('persists performance detail and hides statistics in Compact', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-performance-usage')) + const stats = page.locator('[data-composer-stats]') + await page.getByRole('button', { name: 'Settings', exact: true }).click() + const dialog = page.getByRole('dialog', { name: 'Settings', exact: true }) + const row = dialog.getByText('Performance & usage', { exact: true }).locator('../..') + await row.getByRole('button', { name: 'Detailed', exact: true }).click() + await page.getByRole('menuitem', { name: 'Compact', exact: true }).click() + await expect.poll(() => scaffold.ctx.settings.get('ui-chat')).toMatchObject({ performanceUsage: 'compact' }) + await dialog.getByRole('button', { name: 'Close', exact: true }).click() + await expect.poll(() => stats.locator('button').count()).toBe(0) + expect(await stats.textContent()).not.toContain('turns') + expect(await stats.textContent()).toContain('Cache hit') + await stats.hover() + expect(await page.getByRole('dialog').count()).toBe(0) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'compact.expected.md'), await captureStableAria(page, '[data-composer-stats]', scaffold.workspaceCwd), MODE) + const warningStart = tripwire.warnings.length + await page.reload() + await page.getByRole('button', { name: 'Settings', exact: true }).click() + await row.getByRole('button', { name: 'Compact', exact: true }).waitFor() + acknowledgeReloadConnectionLoss(tripwire, warningStart) + await row.getByRole('button', { name: 'Compact', exact: true }).click() + await page.getByRole('menuitem', { name: 'Detailed', exact: true }).click() + await expect.poll(() => scaffold.ctx.settings.get('ui-chat')).toMatchObject({ performanceUsage: 'detailed' }) + await dialog.getByRole('button', { name: 'Close', exact: true }).click() + await expect.poll(() => stats.locator('button').count()).toBe(2) + expect(await page.locator('[data-turn-tail]').getByRole('button', { name: /Ran for/ }).count()).toBe(0) + }) + it.skipIf(MODE === 'record')('forks through the settled-message and session-row actions', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-message-fork')) // The second answer is followed by another completed user turn in the source. @@ -380,6 +409,6 @@ describe('web e2e: message IconActions and clocks on settled history', () => { it.skipIf(MODE === 'record')('issued zero model calls and kept a closed inventory', async () => { expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) - await assertFixtureInventory(SNAPSHOT_DIR, ['fork.expected.md', 'ui.expected.md']) + await assertFixtureInventory(SNAPSHOT_DIR, ['compact.expected.md', 'fork.expected.md', 'ui.expected.md']) }) }) diff --git a/apps/web/tests/skill-tool-row.e2e.ts b/apps/web/tests/skill-tool-row.e2e.ts index 7cdc11770c..628803ad48 100644 --- a/apps/web/tests/skill-tool-row.e2e.ts +++ b/apps/web/tests/skill-tool-row.e2e.ts @@ -70,7 +70,6 @@ describe.skipIf(MODE === 'record')('web e2e: dedicated Skill tool row', () => { const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)) .replace(/\b\d{1,2}\/\d{1,2}(?= \{\{clock\}\})/g, '{{date}}') - .replace(/\{\{date\}\} (?=\{\{clock\}\} Ran for)/g, '') .split(SEED_ID).join('{{seededId}}') await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) expect(tripwire.pageErrors).toEqual([]) diff --git a/apps/web/tests/turn-tail-actions.e2e.ts b/apps/web/tests/turn-tail-actions.e2e.ts index 02f7540aab..7ea13e1c9c 100644 --- a/apps/web/tests/turn-tail-actions.e2e.ts +++ b/apps/web/tests/turn-tail-actions.e2e.ts @@ -177,11 +177,9 @@ describe('web e2e: assistant IconActions wait for the turn to end', () => { const trigger = page.getByRole('button', { name: /Usage 15\.8K tok/ }) await expect.poll(() => trigger.count(), { timeout: 10_000 }).toBe(1) expect(await trigger.getAttribute('aria-expanded')).toBe('false') - // The usage pill carries the icon and the turn total; the time pill beside - // it carries the run time, and both keep their details dialog-only. expect(await trigger.textContent()).toBe('Usage 15.8K tok') const timeTrigger = page.getByRole('button', { name: /^Ran for \S+$/ }) - expect(await timeTrigger.count()).toBe(1) + expect(await timeTrigger.count()).toBe(0) expect(await page.locator('[data-turn-tail]').getByText(/tok\/s|TTFT/).count()).toBe(0) expect(await page.getByRole('dialog').count()).toBe(0) @@ -198,12 +196,6 @@ describe('web e2e: assistant IconActions wait for the turn to end', () => { await page.keyboard.press('Escape') expect(await page.getByRole('dialog').count()).toBe(0) - await timeTrigger.click() - const timeDialog = page.getByRole('dialog', { name: 'Turn time and speed' }) - expect(await timeDialog.count()).toBe(1) - expect(await timeDialog.getByText(/tok\/s/).count()).toBe(0) - expect(await timeDialog.getByText('Time to first token (TTFT)', { exact: true }).count()).toBe(0) - await page.keyboard.press('Escape') await trigger.click() const expanded = await captureStableAria(page, '[class*="centerCol"]', scaffold!.workspaceCwd) @@ -211,12 +203,9 @@ describe('web e2e: assistant IconActions wait for the turn to end', () => { const warningStart = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) - await expect.poll(() => timeTrigger.count(), { timeout: 15_000 }).toBe(1) + await expect.poll(() => trigger.count(), { timeout: 15_000 }).toBe(1) acknowledgeReloadConnectionLoss(tripwire, warningStart) - await timeTrigger.click() - expect(await timeDialog.count()).toBe(1) - expect(await timeDialog.getByText(/tok\/s/).count()).toBe(0) - expect(await timeDialog.getByText('Time to first token (TTFT)', { exact: true }).count()).toBe(0) + expect(await timeTrigger.count()).toBe(0) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }, 120_000) diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index c9bc9c511d..d8e7c6416f 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -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-chat/README.md -README.md: 95066b18f125df32a63d4ba6336bd0e83e0518a2 -README.zh.md: f4697aac4f8ef9c19fe05449affb142ac4e84060 +README.md: 7f3d905b026edeb538de87dc5e54e0f05cd3c3bc +README.zh.md: 118fc29fdb4960dfc1606d7e9cd0a1ccaea9843d diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 95066b18f1..7f3d905b02 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -51,7 +51,9 @@ Generic command rows retain the ordinary command glyph in every lifecycle state; A completed Turn shows an expandable usage row only when the loaded window includes `turn/start` and every started model attempt reports safe, exact usage. The row omits unavailable optional buckets. Incomplete or contradictory accounting hides the complete disclosure instead of presenting a partial total. -After Assistant replies settle, the completed-turn timing dialog omits TTFT and decoding speed, both after live replies and after reopening history. Elapsed turn time remains available. The Session Stats pill reads timing independently from its durable projection. +Settings → General → Performance & usage stores `ui-chat.performanceUsage` as `detailed` (default) or `compact`. Compact shows only available output speed and cache-hit percentage beneath the composer, without interactive statistic dialogs or per-Turn usage. Detailed exposes session statistics and per-Turn token usage. Neither mode shows elapsed time in the completed-turn footer. The preference changes presentation only; accounting and Session events remain intact. + +On non-loopback browsers, the preference remains process-local because the settings scope cannot persist writes. Explicit selections update every consumer immediately; accepted Host settings reconcile the live value on loopback browsers. ## Completed-turn footer diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index f4697aac4f..118fc29fdb 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -51,7 +51,9 @@ Assistant Markdown 中的 HTTP(S) 链接在普通点击时会在该类型已注 只有当已加载窗口包含 `turn/start`,且每次已启动的模型尝试都报告安全、精确的用量时,已完成轮次才显示可展开的用量行。该行会省略不可用的可选用量桶。记账不完整或相互矛盾时,整个详情都不显示,避免把部分总量冒充完整结果。 -Assistant 回复结算后,已完成轮次的计时对话框不显示 TTFT 和解码速度,实时回复完成后和重新打开历史后都如此。轮次总耗时仍可用。Session Stats 药丸从其持久化投影独立读取计时。 +设置 → 通用设置 → 性能与用量将 `ui-chat.performanceUsage` 保存为 `detailed`(默认)或 `compact`。简洁模式仅在输入框下方显示可用的输出速度和缓存命中率,不显示统计交互卡片或每轮用量。详细模式提供会话统计和每轮 token 用量。两种模式的已完成轮次页脚均不显示耗时。该偏好仅影响展示,记账和 Session 事件保持完整。 + +在非回环地址浏览器中,设置作用域无法持久化写入,因此该偏好仅在当前进程内生效。明确选择会立即更新所有使用方;回环地址浏览器收到 Host 已接受的设置后会同步当前值。 ## 已完成轮次的页脚 diff --git a/packages/client/ui-chat/src/chat-settings.ts b/packages/client/ui-chat/src/chat-settings.ts index 00433288f9..dbf9014320 100644 --- a/packages/client/ui-chat/src/chat-settings.ts +++ b/packages/client/ui-chat/src/chat-settings.ts @@ -1,4 +1,4 @@ -/** Chat transcript preferences stored in the Host user-settings document. */ +/** Chat display preferences stored in the Host user-settings document. */ import z from '@deepseek-ai/schemastery' @@ -17,13 +17,25 @@ export type TranscriptViewMode = typeof TRANSCRIPT_VIEW_MODES[number] /** Default preserves the compact process disclosure introduced by Chat. */ export const DEFAULT_TRANSCRIPT_VIEW_MODE: TranscriptViewMode = 'compact' +/** Performance and usage detail levels accepted by user settings. */ +export const PERFORMANCE_USAGE_MODES = ['compact', 'detailed'] as const + +/** Performance and usage presentation. */ +export type PerformanceUsageMode = typeof PERFORMANCE_USAGE_MODES[number] + +/** Preserve detailed accounting for users without an explicit preference. */ +export const DEFAULT_PERFORMANCE_USAGE: PerformanceUsageMode = 'detailed' + /** Durable Chat section shared by the Host schema and browser scope. */ export interface ChatSettings { /** Presentation mode for completed Turn process content. */ transcriptView: TranscriptViewMode + /** Detail level for composer statistics and completed-Turn usage. */ + performanceUsage: PerformanceUsageMode } /** Durable Chat schema; also the wire envelope the browser scope validates against. */ export const ChatSettingsSchema: z = z.object({ + performanceUsage: z.union([...PERFORMANCE_USAGE_MODES]).default(DEFAULT_PERFORMANCE_USAGE), [TRANSCRIPT_VIEW_FIELD]: z.union([...TRANSCRIPT_VIEW_MODES]).default(DEFAULT_TRANSCRIPT_VIEW_MODE), }) diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index c9822804ab..21a63ab782 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -35,6 +35,8 @@ import { TranscriptViewRow, type TranscriptViewRowInjected } from './settings/Tr import { createChatStore } from './stores.ts' import { TranscriptViewPolicy } from './transcript-view.ts' import { CHAT_SETTINGS_NAMESPACE, type ChatSettings } from '../chat-settings.ts' +import { PerformanceUsageRow, type PerformanceUsageRowInjected } from './settings/PerformanceUsageRow.tsx' +import { PerformanceUsagePolicy } from './performance-usage.ts' import { useTurnDataValue } from './chat/use-turn-data.ts' const CHAT_NODE_INJECT: ChatNodeTurnDataInjected = { @@ -70,7 +72,6 @@ export function apply(ctx: Context): void { return source } registerConversationNodes(ctx) - registerChatNodeRenderers(ctx) ctx.uiSession.provide({ hooks: ['chat'], resolve: binding => ({ hooks: { chat: chatSource(binding) } }), @@ -80,9 +81,22 @@ export function apply(ctx: Context): void { const t = ctx.locale.bind(NS) const chatStore = createChatStore() const chatScrollPositions = new Map() - const transcriptView = new TranscriptViewPolicy( - ctx.settingsScope.bind({ namespace: CHAT_SETTINGS_NAMESPACE }), - ) + const chatSettings = ctx.settingsScope.bind({ namespace: CHAT_SETTINGS_NAMESPACE }) + const transcriptView = new TranscriptViewPolicy(chatSettings) + const performancePolicy = new PerformanceUsagePolicy(chatSettings) + const performanceUsage = performancePolicy.mode + registerChatNodeRenderers(ctx, performanceUsage) + + ctx.slots.inject('settings.general.item', () => ctx.slots.register({ + name: 'settings.general.item', + id: 'performance-usage', + order: 13, + locale: NS, + inject: (): PerformanceUsageRowInjected => ({ + hooks: { performanceUsage }, + setPerformanceUsage: (mode) => { performancePolicy.setMode(mode) }, + }), + }, PerformanceUsageRow)) ctx.slots.inject('settings.general.item', () => ctx.slots.register({ name: 'settings.general.item', @@ -179,6 +193,7 @@ export function apply(ctx: Context): void { ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({ name: 'conversation.composer.dock', id: 'stats', order: 0, locale: NS, + inject: () => ({ hooks: { performanceUsage } }), }, StatsPills)) ctx.slots.inject('conversation.approval.detail', () => diff --git a/packages/client/ui-chat/src/client/chat/StatsPills.tsx b/packages/client/ui-chat/src/client/chat/StatsPills.tsx index 7141ab323e..e7ba095dd9 100644 --- a/packages/client/ui-chat/src/client/chat/StatsPills.tsx +++ b/packages/client/ui-chat/src/client/chat/StatsPills.tsx @@ -1,6 +1,5 @@ -// Session stats under the composer, split into two icon pills: a gauge pill -// (turn/step counts + output speed) opening the time-and-speed dialog, and a -// database pill (total tokens + cache hit) opening the token-usage dialog. +// Composer statistics: Compact exposes speed and cache hit as plain readings; +// Detailed exposes counts and totals with time and token-usage dialogs. // Settled-node identity prevents stream-delta updates from rerendering the row. // Mounted on 'conversation.composer.dock' so it sticks with the composer in the // active conversation scrollport (see ConversationRoot data-conversation-scroll). @@ -9,11 +8,11 @@ import { memo, useMemo, useState } from 'react' import { createPortal } from 'react-dom' import { IconDatabaseOutlineRegular, IconGaugeOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { UseProjection } from '@deepseek-ai/dsh-api-session-controller/client' -import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots' +import type { InjectFace, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: merges the sessionStats key into SessionProjectionMap for useProjection. import type {} from '@deepseek-ai/dsh-session-stats/client' import type { TokenUsageProjection } from '@deepseek-ai/dsh-token-meter/client' -import type { ChatViewSlotProps } from '../contract/slots.ts' +import type { ChatViewSlotProps, PerformanceUsageInjected } from '../contract/slots.ts' import type { ChatSnapshot } from '../contract/snapshot.ts' import { formatTokensPerSecond } from './message-chrome.ts' import { assistantStepReading } from '../contract/turn-metrics.ts' @@ -121,7 +120,7 @@ export function billedInputTokens(usage: TokenUsageProjection): number { } /** Props: the conversation-snapshot selector plus the projection read seat. */ -export interface StatsPillsProps { +export interface StatsPillsProps extends InjectFace { useChat: SnapshotSelectorHook useProjection: UseProjection /** The owning dock's locale seat. */ @@ -314,7 +313,8 @@ function UsagePill({ usage, t, dialog }: { ) } -export const StatsPills = memo(function StatsPills({ useChat, useProjection, t }: StatsPillsProps) { +export const StatsPills = memo(function StatsPills({ useChat, useProjection, usePerformanceUsage, t }: StatsPillsProps) { + const mode = usePerformanceUsage(value => value) const settledNodes = useChat(s => s.legacy.nodes) const usage = useProjection('tokenUsage') // One exclusive slot for both dialogs: opening either pill closes the other. @@ -329,9 +329,24 @@ export const StatsPills = memo(function StatsPills({ useChat, useProjection, t } // billing (e.g. every request failed) shows its counts without a usage pill. const hasTokens = usage !== undefined && (billedInputTokens(usage) > 0 || usage.outputTokens > 0) + if (mode === 'compact') { + const speed = stats.decodeMs > 0 + ? t('message.tokensPerSecond', { tps: formatTokensPerSecond(stats.decodeTokens / (stats.decodeMs / 1_000)) }) + : null + const cacheHit = hasTokens ? cacheHitPercent(usage) : null + if (speed === null && cacheHit === null) return null + return ( +
+ {speed !== null && {speed}} + {cacheHit !== null && ( + {t('stats.cacheHit', { percent: cacheHit })} + )} +
+ ) + } if (stats.steps === 0 && !hasTokens) return null return ( -
+
{stats.steps > 0 && ( & PropsRenderSlots<'conversation.chat.turnTail' | 'conversation.chat.assistant-actions'> + & InjectFace /** Turn-local actions and feature tail over the Location index, independent of Assistant placement. */ export const TurnTailNodeView = memo(function TurnTailNodeView({ - node, openFile, forkAt, renderSlot, t, useChat, + node, openFile, forkAt, renderSlot, t, useChat, usePerformanceUsage, }: TurnTailNodeViewProps) { + const detailed = usePerformanceUsage(mode => mode) === 'detailed' const data = node.data const hasLaterChatNode = useChat(snapshot => snapshot.locations.getTurn(data.turn).at(-1) !== node.key) @@ -25,9 +27,6 @@ export const TurnTailNodeView = memo(function TurnTailNodeView({ const owner: TurnTailOwnerProps = { turn, seq: closing?.finalNode.seq ?? data.seq, openFile } const tail = renderSlot('conversation.chat.turnTail', owner) if (closing === null) return tail === null ? null :
{tail}
- const runMs = turn.start === undefined || turn.end === undefined - ? undefined - : Math.max(0, turn.end.time - turn.start.time) // Interruption-frozen partials carry no messageId, so they address no // durable message and contribute no per-message actions. const messageId = closing.finalNode.messageId @@ -49,19 +48,9 @@ export const TurnTailNodeView = memo(function TurnTailNodeView({ branchUnavailable={data.branchUnavailable || hasLaterChatNode} className={css.actions} extraActions={assistantActions} - usageAction={( - <> - {data.tokenUsage !== undefined && } - {runMs !== undefined && ( - - )} - - )} + usageAction={detailed && data.tokenUsage !== undefined + ? + : null} t={t} />
diff --git a/packages/client/ui-chat/src/client/chat/TurnUsagePanel.tsx b/packages/client/ui-chat/src/client/chat/TurnUsagePanel.tsx index 765650b5ca..460d1092a2 100644 --- a/packages/client/ui-chat/src/client/chat/TurnUsagePanel.tsx +++ b/packages/client/ui-chat/src/client/chat/TurnUsagePanel.tsx @@ -1,13 +1,9 @@ -// Icon-row Turn-stat actions: a database pill labelled with the turn total -// click-opens the per-Turn usage dialog, and a clock pill labelled with the -// turn wall time click-opens the Turn-time dialog. Both sit right of the -// branch action in the tail's IconActions row, ahead of the plain clock text. +/** Completed-Turn token usage action and its accounting details dialog. */ import { createPortal } from 'react-dom' -import { IconClockOutlineRegular, IconDatabaseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconDatabaseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { TurnTokenUsage } from '../contract/chat-nodes.ts' import type { ChatViewSlotProps } from '../contract/slots.ts' -import { formatLatencySeconds, formatRunDuration, formatTokensPerSecond } from './message-chrome.ts' import { formatCacheHitPercent, formatExactTokens, formatTokens } from './token-format.ts' import { MEASURE_STYLE, useStatDialog } from './stat-dialog.ts' import css from './TurnUsagePanel.module.css' @@ -19,17 +15,6 @@ export interface TurnUsagePanelProps { t: ChatViewSlotProps['t'] } -export interface TurnTimePanelProps { - /** Turn wall time in ms, the pill's label. */ - runMs: number - /** Turn decode throughput, a dialog row when known. */ - tokensPerSecond?: number | undefined - /** Turn first-step TTFT in ms, a dialog row when known. */ - ttftMs?: number | undefined - /** The owning view's locale seat, passed down as a plain prop. */ - t: ChatViewSlotProps['t'] -} - function formatCompactCount(value: number, t: ChatViewSlotProps['t']): string { return t('message.turnUsage.count', { count: formatTokens(value, t) }) } @@ -123,60 +108,3 @@ export function TurnUsagePanel({ usage, t }: TurnUsagePanelProps) { ) } - -/** - * Turn-time IconActions pill with a click-open Turn-time details dialog. - * @param props - Turn timing facts and locale seat. - * @returns The clock-and-duration trigger and, while open, its portaled dialog anchored above the trigger. - */ -export function TurnTimePanel({ runMs, tokensPerSecond, ttftMs, t }: TurnTimePanelProps) { - const { open, setOpen, rootRef, panelRef, pos } = useStatDialog() - return ( - - - {open && createPortal( -
-
- - - {t('message.turnTime.title')} - -
-
-
-
{t('message.turnTime.duration')}
-
{formatRunDuration(runMs, t)}
- {tokensPerSecond !== undefined && ( - <> -
{t('message.turnTime.speed')}
-
{t('message.tokensPerSecond', { tps: formatTokensPerSecond(tokensPerSecond) })}
- - )} - {ttftMs !== undefined && ( - <> -
{t('message.turnTime.ttft')}
-
{t('duration.seconds', { seconds: formatLatencySeconds(ttftMs) })}
- - )} -
-
, - document.body, - )} - - ) -} diff --git a/packages/client/ui-chat/src/client/chat/message-chrome.ts b/packages/client/ui-chat/src/client/chat/message-chrome.ts index 4bd134a2a9..36c4a3f0bd 100644 --- a/packages/client/ui-chat/src/client/chat/message-chrome.ts +++ b/packages/client/ui-chat/src/client/chat/message-chrome.ts @@ -35,7 +35,7 @@ export function msUntilNextLocalMidnight(ms: number): number { } /** - * Localized elapsed-time label shared by running and settled turn chrome. + * Localized elapsed-time label for the running conversation clock. * @param ms - Elapsed duration in milliseconds (negatives clamp to zero). * @param t - Translate seat supplying the duration templates. * @returns Display string in whole seconds; minutes and seconds once the @@ -55,17 +55,6 @@ export function formatRunDuration(ms: number, t: RunDurationTranslate): string { : t('duration.seconds', { seconds }) } -/** - * Sub-turn latency figure: one decimal under ten seconds, whole seconds - * beyond. Unit-less so the locale template owns the second suffix. - * @param ms - Latency in milliseconds (negatives clamp to zero). - * @returns Display number in seconds without unit. - */ -export function formatLatencySeconds(ms: number): string { - const s = Math.max(0, ms) / 1000 - return s < 10 ? String(Math.round(s * 10) / 10) : String(Math.round(s)) -} - /** * Decode-throughput figure: whole tokens from ten up, one decimal below. * @param tps - Tokens per second. diff --git a/packages/client/ui-chat/src/client/chat/register-node-renderers.ts b/packages/client/ui-chat/src/client/chat/register-node-renderers.ts index 79b35fd85a..f8f78000f1 100644 --- a/packages/client/ui-chat/src/client/chat/register-node-renderers.ts +++ b/packages/client/ui-chat/src/client/chat/register-node-renderers.ts @@ -1,4 +1,6 @@ import type { Context } from '@deepseek-ai/cordis' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { PerformanceUsageMode } from '../../chat-settings.ts' import { NS } from '../locale.ts' import { AssistantNodeView } from './AssistantNodeView.tsx' import { CommandNodeView, ManualCompactionNodeView } from './CommandNodeView.tsx' @@ -13,8 +15,9 @@ import { TurnTailNodeView } from './TurnTailNodeView.tsx' /** * Register this package's business renderers behind the keyed Chat Node seat. * @param ctx - owning UI Conversation context. + * @param performanceUsage - live statistics detail preference. */ -export function registerChatNodeRenderers(ctx: Context): void { +export function registerChatNodeRenderers(ctx: Context, performanceUsage: ObservableSnapshot): void { ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( { name: 'conversation.chat.node', key: 'user', locale: NS }, UserMessageNodeView)) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( @@ -47,6 +50,7 @@ export function registerChatNodeRenderers(ctx: Context): void { name: 'conversation.chat.node', key: 'turn-tail', locale: NS, + inject: () => ({ hooks: { performanceUsage } }), children: { 'conversation.chat.turnTail': { kind: 'list', scope: 'session' }, 'conversation.chat.assistant-actions': { kind: 'list', scope: 'session' }, diff --git a/packages/client/ui-chat/src/client/contract/chat-nodes.ts b/packages/client/ui-chat/src/client/contract/chat-nodes.ts index d04bdfd90e..cade646b1c 100644 --- a/packages/client/ui-chat/src/client/contract/chat-nodes.ts +++ b/packages/client/ui-chat/src/client/contract/chat-nodes.ts @@ -91,8 +91,6 @@ export interface TurnTailChatData { readonly closing: FinalAssistantChatData | null /** Whether non-rendered later evidence makes the closing seq non-tail. */ readonly branchUnavailable: boolean - readonly ttftMs?: number - readonly tokensPerSecond?: number /** Exact per-Turn accounting; absent when the loaded evidence is incomplete. */ readonly tokenUsage?: TurnTokenUsage } diff --git a/packages/client/ui-chat/src/client/contract/slots.ts b/packages/client/ui-chat/src/client/contract/slots.ts index 91c3adad7b..d5b007b7cf 100644 --- a/packages/client/ui-chat/src/client/contract/slots.ts +++ b/packages/client/ui-chat/src/client/contract/slots.ts @@ -9,7 +9,7 @@ import type { InjectFace, KeyedSnapshotSelectorHook, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore, SlotHookFactory, SnapshotSelectorHook, } from '@deepseek-ai/dsh-client-ui-slots' -import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { ObservableSnapshot, SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { MarkdownFileMentions } from '@deepseek-ai/dsh-client-ui-primitives' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { createChatStore } from '../stores.ts' @@ -19,7 +19,7 @@ import type { ChatNodeProcessSource, ChatNodeSource, ChatSnapshot, ChatTurnProcessPresentation, } from './snapshot.ts' import type { TurnProcessSpec } from './turn-process.ts' -import type { TranscriptViewMode } from '../../chat-settings.ts' +import type { PerformanceUsageMode, TranscriptViewMode } from '../../chat-settings.ts' /** Selector hook over the current Conversation binding's Chat target. */ export type UseChat = SnapshotSelectorHook @@ -128,6 +128,14 @@ export interface ChatScrollPosition { readonly scrollTop: number } +/** Shared settings source for the performance row, composer, and turn tail. */ +export interface PerformanceUsageInjected { + hooks: { + /** Accepted performance and usage detail preference. */ + performanceUsage: ObservableSnapshot + } +} + /** Business callbacks injected into the Chat view. */ export interface ChatViewInjected { hooks: { diff --git a/packages/client/ui-chat/src/client/contract/turn-metrics.ts b/packages/client/ui-chat/src/client/contract/turn-metrics.ts index a9f4dbc7c0..6cbd619beb 100644 --- a/packages/client/ui-chat/src/client/contract/turn-metrics.ts +++ b/packages/client/ui-chat/src/client/contract/turn-metrics.ts @@ -1,17 +1,9 @@ -// Latency/throughput folds shared by the settled turn footer and StatsPills. +// Assistant timing readings used by session statistics. import type { - AssistantMessageNode, ConversationNode, + AssistantMessageNode, } from '@deepseek-ai/dsh-client-ui-conversation/client' -/** Latency and decode-throughput readings for one turn's footer. */ -export interface TurnMetrics { - /** First-step TTFT in ms; absent when that step carries no recorded timing. */ - ttftMs?: number - /** Decode throughput over steps carrying both timing and provider usage. */ - tokensPerSecond?: number -} - /** One assistant step's derivable latency facts; null marks an unrecorded part. */ export interface StepReading { /** step/start → first token delta, in ms. */ @@ -49,51 +41,3 @@ export function assistantStepReading(node: AssistantNode): StepReading { : null return { ttftMs, decodeMs, outputTokens: usageOutputTokens(node.usage) } } - -interface TurnFold { - firstStep: number - firstStepTtftMs: number | null - decodeMs: number - outputTokens: number - sampled: boolean -} - -/** - * Fold assistant nodes into per-turn footer metrics. - * - * TTFT is the turn's lowest-step request-dispatch-to-first-token reading, so - * it is only meaningful when the turn's start is inside - * the loaded window (the caller gates on `turnTimings`, which shares that - * window). Throughput divides summed output tokens by summed decode wall time, - * counting only steps that carry both. - * @param nodes - Snapshot nodes of the loaded window. - * @returns Turn number → available metrics; turns with none are absent. - */ -export function deriveTurnMetrics(nodes: readonly ConversationNode[]): Map { - const folds = new Map() - for (const node of nodes) { - if (node.kind !== 'assistant') continue - const reading = assistantStepReading(node) - let fold = folds.get(node.turn) - if (fold === undefined) { - fold = { firstStep: node.step, firstStepTtftMs: reading.ttftMs, decodeMs: 0, outputTokens: 0, sampled: false } - folds.set(node.turn, fold) - } else if (node.step < fold.firstStep) { - fold.firstStep = node.step - fold.firstStepTtftMs = reading.ttftMs - } - if (reading.decodeMs !== null && reading.outputTokens !== null) { - fold.decodeMs += reading.decodeMs - fold.outputTokens += reading.outputTokens - fold.sampled = true - } - } - const metrics = new Map() - for (const [turn, fold] of folds) { - const entry: TurnMetrics = {} - if (fold.firstStepTtftMs !== null) entry.ttftMs = fold.firstStepTtftMs - if (fold.sampled && fold.decodeMs > 0) entry.tokensPerSecond = fold.outputTokens / (fold.decodeMs / 1000) - if (entry.ttftMs !== undefined || entry.tokensPerSecond !== undefined) metrics.set(turn, entry) - } - return metrics -} diff --git a/packages/client/ui-chat/src/client/conversation-nodes/turn-tail.ts b/packages/client/ui-chat/src/client/conversation-nodes/turn-tail.ts index 3206b1cea3..1cccf210f3 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/turn-tail.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/turn-tail.ts @@ -9,7 +9,6 @@ import { deriveTurnTokenUsage } from '@deepseek-ai/dsh-token-meter/client' import type { AssistantChatData, FinalAssistantChatData, TurnTailChatData, } from '../contract/chat-nodes.ts' -import { deriveTurnMetrics } from '../contract/turn-metrics.ts' import { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode } from './common.ts' import { toAssistantBlocks } from './event-projection.ts' @@ -146,7 +145,6 @@ function tailData(context: ConversationNodeContext): TurnTailChat latestTranscriptSeq = candidate } } - const metrics = deriveTurnMetrics(finalized.map(candidate => candidate.finalNode)).get(end.event.data.turn) const tokenUsage = context.start?.event.type === 'turn/start' ? deriveTurnTokenUsage(context.matches.map(match => match.event).filter(isSessionEvent)) : undefined @@ -156,8 +154,6 @@ function tailData(context: ConversationNodeContext): TurnTailChat time: end.event.time, closing, branchUnavailable: closing === null || latestTranscriptSeq !== closing.finalNode.seq, - ...metrics?.ttftMs === undefined ? {} : { ttftMs: metrics.ttftMs }, - ...metrics?.tokensPerSecond === undefined ? {} : { tokensPerSecond: metrics.tokensPerSecond }, ...tokenUsage === undefined ? {} : { tokenUsage }, } } diff --git a/packages/client/ui-chat/src/client/locale.ts b/packages/client/ui-chat/src/client/locale.ts index 5468ed9df4..344fef13d0 100644 --- a/packages/client/ui-chat/src/client/locale.ts +++ b/packages/client/ui-chat/src/client/locale.ts @@ -27,6 +27,10 @@ export const zh = { 'chat.turnNavigation.jump': '跳转到第 {turn} 轮', 'chat.turnNavigation.jumpLoad': '加载并跳转到第 {turn} 轮', 'chat.turnNavigation.turn': '第 {turn} 轮', + 'settings.performance.title': '性能与用量', + 'settings.performance.description': '选择性能与用量信息展示的详细程度', + 'settings.performance.compact': '简洁', + 'settings.performance.detailed': '详细', 'settings.transcript.title': '对话显示', 'settings.transcript.description': '控制已完成轮次的过程内容', 'settings.transcript.normal': '标准', @@ -81,7 +85,6 @@ export const zh = { 'message.turnError': '本轮运行失败', 'message.maxTokens': '已达到输出 token 上限', 'message.maxTokens.hint': '回答被截断,已有输出保留在对话中。发送“继续”可让模型接着输出。', - 'message.ranFor': '用时 {duration}', 'message.tokensPerSecond': '{tps} tok/s', 'message.turnUsage.title': '本轮用量', 'message.turnUsage.consumed': '用量 {total}', @@ -93,10 +96,6 @@ export const zh = { 'message.turnUsage.output': '输出', 'message.turnUsage.reasoning': '(其中推理 {tokens})', 'message.turnUsage.count': '{count} tok', - 'message.turnTime.title': '本轮用时和速度', - 'message.turnTime.duration': '本轮总用时', - 'message.turnTime.speed': '输出速度(TPS)', - 'message.turnTime.ttft': '首 token 用时(TTFT)', 'duration.seconds': '{seconds}秒', 'duration.minutes': '{minutes}分{seconds}秒', 'duration.hours': '{hours}小时{minutes}分{seconds}秒', @@ -138,6 +137,10 @@ export const en = { 'chat.turnNavigation.jump': 'Jump to turn {turn}', 'chat.turnNavigation.jumpLoad': 'Load and jump to turn {turn}', 'chat.turnNavigation.turn': 'Turn {turn}', + 'settings.performance.title': 'Performance & usage', + 'settings.performance.description': 'Choose how much performance and usage information to show', + 'settings.performance.compact': 'Compact', + 'settings.performance.detailed': 'Detailed', 'settings.transcript.title': 'Conversation display', 'settings.transcript.description': 'Controls process content in completed turns', 'settings.transcript.normal': 'Normal', @@ -192,7 +195,6 @@ export const en = { 'message.turnError': 'This turn failed', 'message.maxTokens': 'Output token limit reached', 'message.maxTokens.hint': 'The reply was cut off; earlier output is preserved in the conversation. Send "continue" to let the model resume.', - 'message.ranFor': 'Ran for {duration}', 'message.tokensPerSecond': '{tps} tok/s', 'message.turnUsage.title': 'Turn usage', 'message.turnUsage.consumed': 'Usage {total}', @@ -204,10 +206,6 @@ export const en = { 'message.turnUsage.output': 'Output', 'message.turnUsage.reasoning': ' ({tokens} reasoning)', 'message.turnUsage.count': '{count} tok', - 'message.turnTime.title': 'Turn time and speed', - 'message.turnTime.duration': 'Total run time', - 'message.turnTime.speed': 'Tokens per second (TPS)', - 'message.turnTime.ttft': 'Time to first token (TTFT)', 'duration.seconds': '{seconds}s', 'duration.minutes': '{minutes}m {seconds}s', 'duration.hours': '{hours}h {minutes}m {seconds}s', diff --git a/packages/client/ui-chat/src/client/performance-usage.ts b/packages/client/ui-chat/src/client/performance-usage.ts new file mode 100644 index 0000000000..b724416c05 --- /dev/null +++ b/packages/client/ui-chat/src/client/performance-usage.ts @@ -0,0 +1,30 @@ +/** Performance detail preference with process-local choices on memory-only settings scopes. */ +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { SettingsScope } from '@deepseek-ai/dsh-client-ui-settings/client' +import { DEFAULT_PERFORMANCE_USAGE, type ChatSettings, type PerformanceUsageMode } from '../chat-settings.ts' + +/** Shared live preference for the settings row and chat statistics. */ +export class PerformanceUsagePolicy { + /** Current choice, reconciled with accepted Host settings when available. */ + readonly mode = createSnapshotStore(DEFAULT_PERFORMANCE_USAGE) + + /** @param host - Chat settings scope, durable on loopback and memory-only elsewhere. */ + constructor(private readonly host: SettingsScope) { + const adopt = (): void => { + const accepted = host.getSnapshot().value?.performanceUsage + if (accepted !== undefined) this.mode.set(accepted) + } + host.subscribe(adopt) + adopt() + } + + /** + * Publish a choice immediately and persist it when the scope supports writes. + * @param mode - Statistics detail selected by the user. + */ + setMode(mode: PerformanceUsageMode): void { + if (mode === this.mode.getSnapshot()) return + this.mode.set(mode) + void this.host.set('performanceUsage', mode) + } +} diff --git a/packages/client/ui-chat/src/client/settings/PerformanceUsageRow.tsx b/packages/client/ui-chat/src/client/settings/PerformanceUsageRow.tsx new file mode 100644 index 0000000000..db05aaebb9 --- /dev/null +++ b/packages/client/ui-chat/src/client/settings/PerformanceUsageRow.tsx @@ -0,0 +1,46 @@ +/** General Settings row for performance and usage detail. */ + +import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { PerformanceUsageMode } from '../../chat-settings.ts' +import type { PerformanceUsageInjected } from '../contract/slots.ts' +import type { ChatKey } from '../locale.ts' +import { PreferenceRow } from './PreferenceRow.tsx' + +/** Registration-side performance and usage preference face. */ +export interface PerformanceUsageRowInjected extends PerformanceUsageInjected { + /** Change the performance and usage detail. */ + setPerformanceUsage: (mode: PerformanceUsageMode) => void +} + +/** Full Settings-row props. */ +export type PerformanceUsageRowProps = + PropsRuntime<'settings.general.item'> + & PropsLocale<'chat'> + & InjectFace + +const OPTIONS: readonly { id: PerformanceUsageMode; label: ChatKey }[] = [ + { id: 'compact', label: 'settings.performance.compact' }, + { id: 'detailed', label: 'settings.performance.detailed' }, +] + +/** + * Render the performance and usage detail selector. + * @param props - composed Settings slot props. + * @returns the preference row. + */ +export function PerformanceUsageRow({ usePerformanceUsage, setPerformanceUsage, t }: PerformanceUsageRowProps) { + const mode = usePerformanceUsage(value => value) + const selectedLabel = mode === 'detailed' + ? 'settings.performance.detailed' + : 'settings.performance.compact' + return ( + ({ id: option.id, label: t(option.label) }))} + onSelect={(value) => { setPerformanceUsage(value as PerformanceUsageMode) }} + /> + ) +} diff --git a/packages/client/ui-chat/src/client/settings/TranscriptViewRow.module.css b/packages/client/ui-chat/src/client/settings/PreferenceRow.module.css similarity index 92% rename from packages/client/ui-chat/src/client/settings/TranscriptViewRow.module.css rename to packages/client/ui-chat/src/client/settings/PreferenceRow.module.css index 1ab93f1d52..27e3a05ab7 100644 --- a/packages/client/ui-chat/src/client/settings/TranscriptViewRow.module.css +++ b/packages/client/ui-chat/src/client/settings/PreferenceRow.module.css @@ -1,4 +1,4 @@ -/* Completed-Turn transcript preference row: label plus selector pill. */ +/* Chat preference row: label plus selector pill. */ .row { display: flex; diff --git a/packages/client/ui-chat/src/client/settings/PreferenceRow.tsx b/packages/client/ui-chat/src/client/settings/PreferenceRow.tsx new file mode 100644 index 0000000000..c5b216b455 --- /dev/null +++ b/packages/client/ui-chat/src/client/settings/PreferenceRow.tsx @@ -0,0 +1,56 @@ +/** Localized two-column selector shared by Chat preference rows. */ +import { useState } from 'react' +import { IconChevronDownOutlineRegular, Menu } from '@deepseek-ai/dsh-client-ui-primitives' +import css from './PreferenceRow.module.css' + +/** + * Render a preference label and its menu. + * @param props - localized copy, selected value, choices, and mutation callback. + * @returns the settings row. + */ +export function PreferenceRow({ title, description, value, selectedLabel, options, onSelect }: { + title: string + description: string + value: string + selectedLabel: string + options: readonly { id: string; label: string }[] + onSelect: (value: string) => void +}) { + const [open, setOpen] = useState(false) + const closeMenu = () => { setOpen(false) } + const selectMode = (id: string) => { + closeMenu() + onSelect(id) + } + const selector = ( + + ) + + return ( +
+
+
{title}
+
{description}
+
+ +
+ ) +} diff --git a/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx b/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx index b3b188c69c..7dc7df7363 100644 --- a/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx +++ b/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx @@ -1,12 +1,10 @@ /** General Settings row for completed-Turn transcript presentation. */ -import { useState } from 'react' import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' -import { IconChevronDownOutlineRegular, Menu } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { TranscriptViewMode } from '../../chat-settings.ts' import type { ChatKey } from '../locale.ts' -import css from './TranscriptViewRow.module.css' +import { PreferenceRow } from './PreferenceRow.tsx' /** Registration-side transcript preference face. */ export interface TranscriptViewRowInjected { @@ -36,44 +34,17 @@ const OPTIONS: readonly { id: TranscriptViewMode; label: ChatKey }[] = [ */ export function TranscriptViewRow({ useTranscriptView, setTranscriptView, t }: TranscriptViewRowProps) { const mode = useTranscriptView(value => value) - const [open, setOpen] = useState(false) const selectedLabel = mode === 'normal' ? 'settings.transcript.normal' : 'settings.transcript.compact' - const closeMenu = () => { setOpen(false) } - const selectMode = (id: string) => { - closeMenu() - setTranscriptView(id as TranscriptViewMode) - } - const selector = ( - - ) - return ( -
-
-
{t('settings.transcript.title')}
-
{t('settings.transcript.description')}
-
- ({ id: option.id, label: t(option.label) }))} - selectedId={mode} - onSelect={selectMode} - align="end" - portal - anchor={selector} - /> -
+ ({ id: option.id, label: t(option.label) }))} + onSelect={(value) => { setTranscriptView(value as TranscriptViewMode) }} + /> ) } diff --git a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx index 20096e9f8c..92290ff074 100644 --- a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx @@ -23,6 +23,7 @@ import { import type { ChatNodeTurnDataInjected, ChatSnapshot, TranscriptViewRowInjected, UseChatNodeTurnData, } from '@deepseek-ai/dsh-client-ui-chat/client' +import type { PerformanceUsageRowInjected } from '../src/client/settings/PerformanceUsageRow.tsx' import { CHAT_SETTINGS_NAMESPACE, type ChatSettings } from '../src/chat-settings.ts' declare module '@deepseek-ai/dsh-client-ui-conversation/client' { @@ -93,7 +94,7 @@ describe('Chat apply wiring', () => { expect(b.runtime.slots.entries('conversation.composer.dock').map(row => row.options.id)) .toEqual(['stats']) expect(b.runtime.slots.entries('settings.general.item').map(row => row.options.id)) - .toEqual(['transcript-view', 'composer-enter']) + .toEqual(['transcript-view', 'performance-usage', 'composer-enter']) await b.runtime.dispose() }) @@ -109,12 +110,31 @@ describe('Chat apply wiring', () => { expect(b.chatSettings.set).toHaveBeenCalledWith('transcriptView', 'normal') b.chatSettings.publish({ - status: 'ready', value: { transcriptView: 'compact' }, revision: 1, writable: true, + status: 'ready', value: { transcriptView: 'compact', performanceUsage: 'detailed' }, revision: 1, writable: true, }) expect(face.hooks.transcriptView.getSnapshot()).toBe('compact') await b.runtime.dispose() }) + it('shares the accepted performance preference with settings, composer, and turn tails', async () => { + const b = await bench() + const row = b.runtime.slots.entries('settings.general.item').find(entry => entry.options.id === 'performance-usage')! + const face = (row.inject as unknown as () => PerformanceUsageRowInjected)() + expect(face.hooks.performanceUsage.getSnapshot()).toBe('detailed') + face.setPerformanceUsage('compact') + expect(b.chatSettings.set).toHaveBeenCalledWith('performanceUsage', 'compact') + b.chatSettings.publish({ value: { transcriptView: 'compact', performanceUsage: 'compact' } }) + expect(face.hooks.performanceUsage.getSnapshot()).toBe('compact') + for (const entry of [ + b.runtime.slots.entries('conversation.composer.dock').find(entry => entry.options.id === 'stats')!, + b.runtime.slots.entries('conversation.chat.node').find(entry => entry.options.key === 'turn-tail')!, + ]) { + const injected = (entry.inject as unknown as () => Pick)() + expect(injected.hooks.performanceUsage).toBe(face.hooks.performanceUsage) + } + await b.runtime.dispose() + }) + it('shares one Chat store while keeping it distinct from Conversation state', async () => { const b = await bench() const conversationStore = storeOf(b.runtime, 'conversation.session') diff --git a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx index cc447d8ff0..4e2493d17c 100644 --- a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx @@ -1064,6 +1064,7 @@ describe('small branch tails', () => { const source = { getSnapshot: () => snap, subscribe: () => () => {} } const view = render( selector('detailed')} t={t} useChat={bindSnapshotSelector(source)} useProjection={(key: string) => key === 'tokenUsage' diff --git a/packages/client/ui-chat/tests/chat-settings.client.spec.ts b/packages/client/ui-chat/tests/chat-settings.client.spec.ts index 54ecf4c63e..ad5ae6ab89 100644 --- a/packages/client/ui-chat/tests/chat-settings.client.spec.ts +++ b/packages/client/ui-chat/tests/chat-settings.client.spec.ts @@ -21,10 +21,13 @@ describe('ui-chat Host settings', () => { await fiber.await() const ns = CHAT_SETTINGS_NAMESPACE - expect(ctx.settings.get(ns)).toEqual({ transcriptView: DEFAULT_TRANSCRIPT_VIEW_MODE }) + expect(ctx.settings.get(ns)).toEqual({ transcriptView: DEFAULT_TRANSCRIPT_VIEW_MODE, performanceUsage: 'detailed' }) await ctx.settings.update(ns, { transcriptView: 'normal' }) - expect(ctx.settings.get(ns)).toEqual({ transcriptView: 'normal' }) + expect(ctx.settings.get(ns)).toEqual({ transcriptView: 'normal', performanceUsage: 'detailed' }) await expect(ctx.settings.update(ns, { transcriptView: 'dense' })).rejects.toThrow() + await ctx.settings.update(ns, { performanceUsage: 'compact' }) + expect(ctx.settings.get(ns)).toMatchObject({ performanceUsage: 'compact' }) + await expect(ctx.settings.update(ns, { performanceUsage: 'hidden' })).rejects.toThrow() await fiber.dispose() expect(ctx.settings.describe().map(row => row.ns)).not.toContain(ns) diff --git a/packages/client/ui-chat/tests/chat-snapshot-fixture.client.ts b/packages/client/ui-chat/tests/chat-snapshot-fixture.client.ts index 6914089291..21b0d483ff 100644 --- a/packages/client/ui-chat/tests/chat-snapshot-fixture.client.ts +++ b/packages/client/ui-chat/tests/chat-snapshot-fixture.client.ts @@ -8,7 +8,6 @@ import type { ConversationLocationDataSource, ConversationLocationDataStore, ConversationTurnDataMap, TurnLocation, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { TurnTokenUsage } from '../src/client/contract/chat-nodes.ts' -import { deriveTurnMetrics } from '../src/client/contract/turn-metrics.ts' import { sameTurnNavigationItem, turnNavigationItem, } from '../src/client/conversation-nodes/turn-navigation.ts' @@ -461,7 +460,6 @@ export function chatSnapshotFixture(input: { return (location.kind === 'turn' || location.kind === 'step') && location.turn.turn === turnNumber }) - const metrics = deriveTurnMetrics(legacy.nodes).get(turnNumber) const tokenUsage = input.turnUsages?.get(turnNumber) const tailData = { turn: turnNumber, @@ -471,8 +469,6 @@ export function chatSnapshotFixture(input: { branchUnavailable: closing === null || preceding?.kind !== 'assistant-step' || (preceding.data as ReturnType).finalNode.seq !== closing.finalNode.seq, - ...metrics?.ttftMs === undefined ? {} : { ttftMs: metrics.ttftMs }, - ...metrics?.tokensPerSecond === undefined ? {} : { tokensPerSecond: metrics.tokensPerSecond }, ...tokenUsage === undefined ? {} : { tokenUsage }, } dataStore.set('turn-tail', tailData) diff --git a/packages/client/ui-chat/tests/chat-stats.client.spec.tsx b/packages/client/ui-chat/tests/chat-stats.client.spec.tsx index af16ba4d43..fdf4556bce 100644 --- a/packages/client/ui-chat/tests/chat-stats.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-stats.client.spec.tsx @@ -145,7 +145,7 @@ describe('StatsPills', () => { source: { getSnapshot(): ChatSnapshot; subscribe(fn: () => void): () => void }, values: Record = { tokenUsage: USAGE }, ): StatsPillsProps { - return { useChat: bindSnapshotSelector(source), useProjection: projections(values), t: tEn } + return { usePerformanceUsage: selector => selector('detailed'), useChat: bindSnapshotSelector(source), useProjection: projections(values), t: tEn } } function tokenUsage(cacheReadTokens: number, uncachedInputTokens: number) { @@ -158,6 +158,27 @@ describe('StatsPills', () => { timing: { stepStartTime: 1_000, firstTokenTime: 1_800, completedTime: 4_800 }, }) + it('compact keeps only speed and cache hit, with no interactive statistics', () => { + const { source } = makeSource({ nodes: [timedStep()] }) + const view = render( selector('compact')} />) + expect(view.container.textContent).toBe('20 tok/sCache hit 90%') + expect(view.queryByRole('button')).toBeNull() + fireEvent.mouseOver(view.getByText('20 tok/s')) + expect(view.queryByRole('dialog')).toBeNull() + view.rerender() + expect(view.getAllByRole('button')).toHaveLength(2) + fireEvent.click(view.getAllByRole('button')[0]!) + expect(view.getByRole('dialog')).toBeTruthy() + view.rerender( selector('compact')} />) + expect(view.queryByRole('dialog')).toBeNull() + }) + + it('compact omits unavailable metrics instead of showing counts', () => { + const { source } = makeSource({ nodes: [assistant(1, 1)] }) + const view = render( selector('compact')} />) + expect(view.container.textContent).toBe('') + }) + it('renders the counts reading and usage pill and hides a brand-new empty session', () => { const { source } = makeSource({ nodes: [assistant(1, 1)] }) const view = render() diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 7913f00b7c..a25692a2d5 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -275,6 +275,7 @@ function makeHarness( // Rows and the harness must observe the same chat-store instance. const chat = createChatStore().create() const transcriptView = createSnapshotStore('compact') + const performanceUsage = createSnapshotStore<'compact' | 'detailed'>('detailed') const t = makeTranslate(zh, commonZh) const toolOwners: Array<{ callId: string @@ -334,6 +335,7 @@ function makeHarness( case 'turn-tail': return ( ()} renderSlot={renderTurnTailSlot} SessionProvider={props.SessionProvider} @@ -442,6 +444,7 @@ function makeHarness( openFile, openSkill, loadOlder, loadThrough, openView, setOutline: (value: unknown) => { outlineValue = value }, chatScroll, forkAt, toolOwners, + setPerformanceUsage: (mode: 'compact' | 'detailed') => { performanceUsage.set(mode) }, setTranscriptView: (mode: TranscriptViewMode) => { transcriptView.set(mode) }, setNodeRenderer: (renderer: React.ComponentProps['renderSlot']) => { nodeSlotOverride = renderer @@ -1896,7 +1899,7 @@ describe('ChatView', () => { expect(view.getAllByRole('button', { name: '复制' })).toHaveLength(4) }) - it('the actions-owning assistant footer shows the turn run time', () => { + it('the assistant footer omits turn run time', () => { const h = makeHarness({ nodes: [ user(1, 'hi'), // time 1_000 @@ -1909,10 +1912,10 @@ describe('ChatView', () => { }) const view = render() // The exact turn/end includes trailing tool activity after the final text. - expect(view.container.querySelector('[data-turn-tail="1"]')?.textContent).toContain('用时 19秒') + expect(view.container.querySelector('[data-turn-tail="1"]')?.textContent).not.toContain('用时 19秒') }) - it('the actions-owning assistant footer shows an hour-scale run time', () => { + it('the assistant footer omits hour-scale run time', () => { const h = makeHarness({ nodes: [ user(1, 'hi'), @@ -1925,10 +1928,10 @@ describe('ChatView', () => { }) const view = render() expect(view.container.querySelector('[data-turn-tail="1"]')?.textContent) - .toContain('用时 1小时05分03秒') + .not.toContain('用时 1小时05分03秒') }) - it('the settled footer exposes ttft, decode throughput, and usage as the details trigger', () => { + it('the settled footer shows usage only in Detailed mode', () => { const first: AssistantMessageNode = { kind: 'assistant', seq: 2, time: 2_000, turn: 1, step: 1, blocks: [{ kind: 'text', text: 'mid' }], timing: { stepStartTime: 1_000, firstTokenTime: 2_200, completedTime: 5_200 }, @@ -1962,17 +1965,11 @@ describe('ChatView', () => { expect(dialog.textContent).toContain('缓存命中49.4%') expect(dialog.textContent).toContain('未缓存输入5,060 tok') fireEvent.keyDown(document, { key: 'Escape' }) - // The time pill carries the run time; first-step ttft (1.2s) and 100 - // tokens over 5s of decode move into its dialog. - const timeTrigger = view.getByRole('button', { name: /用时 19秒/ }) - expect(timeTrigger.textContent).toBe('用时 19秒') - expect(view.queryByText(/速度 20 tok\/s|首 token/)).toBeNull() - fireEvent.click(timeTrigger) - const timeDialog = view.getByRole('dialog') - expect(timeDialog.getAttribute('aria-label')).toBe('本轮用时和速度') - expect(timeDialog.textContent).toContain('本轮总用时19秒') - expect(timeDialog.textContent).toContain('输出速度(TPS)20 tok/s') - expect(timeDialog.textContent).toContain('首 token 用时(TTFT)1.2秒') + expect(view.queryByRole('button', { name: /用时/ })).toBeNull() + act(() => { h.setPerformanceUsage('compact') }) + expect(view.queryByRole('button', { name: /用量/ })).toBeNull() + act(() => { h.setPerformanceUsage('detailed') }) + expect(view.getByRole('button', { name: /用量/ })).toBeTruthy() }) it('withholds the usage-details trigger when turn usage is outside the window', () => { @@ -1987,9 +1984,7 @@ describe('ChatView', () => { turnEnds: new Map([[1, 20]]), }) const view = render() - // Timing facts keep their pill, but with no usage in the window there is - // no usage pill to click. - expect(view.getByRole('button', { name: /用时/ })).toBeTruthy() + expect(view.queryByRole('button', { name: /用时/ })).toBeNull() expect(view.queryByRole('button', { name: /用量/ })).toBeNull() }) diff --git a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts index 7caa2f8fd9..f393a952bf 100644 --- a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts +++ b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts @@ -987,8 +987,6 @@ describe('built-in conversation node Definitions', () => { }) const tail = node(view, 'turn-tail')?.data as TurnTailChatData expect(tail.turn).toBe(1) - expect(tail.ttftMs).toBeUndefined() - expect(tail.tokensPerSecond).toBeUndefined() } }) diff --git a/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx index a778ba7bfb..8bfb4014b6 100644 --- a/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx @@ -46,6 +46,7 @@ describe('render branch tails', () => { const source = { getSnapshot: () => snap, subscribe: () => () => {} } const view = render( selector('detailed')} t={t} useChat={bindSnapshotSelector(source)} useProjection={() => undefined} diff --git a/packages/client/ui-chat/tests/performance-usage.client.spec.ts b/packages/client/ui-chat/tests/performance-usage.client.spec.ts new file mode 100644 index 0000000000..00e862cfe6 --- /dev/null +++ b/packages/client/ui-chat/tests/performance-usage.client.spec.ts @@ -0,0 +1,30 @@ +// @vitest-environment jsdom +import { describe, expect, it } from 'vitest' +import { stubSettingsScope } from '@deepseek-ai/dsh-client-test-runtime' +import type { ChatSettings } from '../src/chat-settings.ts' +import { PerformanceUsagePolicy } from '../src/client/performance-usage.ts' + +describe('PerformanceUsagePolicy', () => { + it('keeps explicit choices live when a memory-only scope cannot persist them', () => { + const host = stubSettingsScope() + host.publish({ mode: 'memory', status: 'ready' }) + const policy = new PerformanceUsagePolicy(host.scope) + expect(policy.mode.getSnapshot()).toBe('detailed') + policy.setMode('compact') + expect(policy.mode.getSnapshot()).toBe('compact') + expect(host.set).toHaveBeenCalledWith('performanceUsage', 'compact') + host.publish({ value: undefined, writable: false }) + expect(policy.mode.getSnapshot()).toBe('compact') + policy.setMode('compact') + expect(host.set).toHaveBeenCalledTimes(1) + }) + + it('adopts accepted Host settings at construction and after updates', () => { + const host = stubSettingsScope() + host.publish({ value: { transcriptView: 'normal', performanceUsage: 'compact' } }) + const policy = new PerformanceUsagePolicy(host.scope) + expect(policy.mode.getSnapshot()).toBe('compact') + host.publish({ value: { transcriptView: 'normal', performanceUsage: 'detailed' } }) + expect(policy.mode.getSnapshot()).toBe('detailed') + }) +}) diff --git a/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts b/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts index b0781e1edf..84717bb5c0 100644 --- a/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts +++ b/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts @@ -30,18 +30,18 @@ describe('TranscriptViewPolicy', () => { const host = stubSettingsScope() const policy = new TranscriptViewPolicy(host.scope) - host.publish({ status: 'ready', value: { transcriptView: 'normal' }, revision: 1, writable: true }) + host.publish({ status: 'ready', value: { transcriptView: 'normal', performanceUsage: 'detailed' }, revision: 1, writable: true }) expect(policy.mode.getSnapshot()).toBe('normal') policy.setMode('normal') expect(host.set).not.toHaveBeenCalled() - host.publish({ value: { transcriptView: 'compact' }, revision: 2 }) + host.publish({ value: { transcriptView: 'compact', performanceUsage: 'detailed' }, revision: 2 }) expect(policy.mode.getSnapshot()).toBe('compact') }) it('adopts an accepted section standing at construction', () => { const host = stubSettingsScope() - host.publish({ status: 'ready', value: { transcriptView: 'normal' }, revision: 1, writable: true }) + host.publish({ status: 'ready', value: { transcriptView: 'normal', performanceUsage: 'detailed' }, revision: 1, writable: true }) expect(new TranscriptViewPolicy(host.scope).mode.getSnapshot()).toBe('normal') }) }) diff --git a/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx b/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx index 0c544c1211..f3ac40e704 100644 --- a/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/transcript-view-row.client.spec.tsx @@ -8,6 +8,8 @@ import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { TranscriptViewRow, type TranscriptViewRowProps } from '../src/client/settings/TranscriptViewRow.tsx' +import { PerformanceUsageRow } from '../src/client/settings/PerformanceUsageRow.tsx' +import type { PerformanceUsageMode } from '../src/chat-settings.ts' import { en, zh } from '../src/client/locale.ts' afterEach(cleanup) @@ -46,7 +48,7 @@ function mount(mode: 'normal' | 'compact' = 'compact', dictionary: typeof en | t t: makeTranslate(dictionary), } render() - return { setTranscriptView } + return { setTranscriptView, props } } describe('TranscriptViewRow', () => { @@ -76,3 +78,23 @@ describe('TranscriptViewRow', () => { expect(screen.getByRole('button', { name: '标准' })).toBeDefined() }) }) + + +describe('PerformanceUsageRow', () => { + it('selects compact statistics independently of conversation display', () => { + const b = mount() + const source = createSnapshotStore('detailed') + const setPerformanceUsage = vi.fn((mode: PerformanceUsageMode) => { source.set(mode) }) + render() + expect(screen.getByText('Performance & usage')).toBeDefined() + fireEvent.click(screen.getByRole('button', { name: 'Detailed' })) + fireEvent.click(screen.getByRole('menuitem', { name: 'Compact' })) + expect(setPerformanceUsage).toHaveBeenCalledWith('compact') + expect(screen.getAllByRole('button', { name: 'Compact' })).toHaveLength(2) + expect(b.setTranscriptView).not.toHaveBeenCalled() + }) +}) diff --git a/packages/client/ui-chat/tests/turn-metrics.client.spec.ts b/packages/client/ui-chat/tests/turn-metrics.client.spec.ts index 1d92c61335..7d0ffed6e4 100644 --- a/packages/client/ui-chat/tests/turn-metrics.client.spec.ts +++ b/packages/client/ui-chat/tests/turn-metrics.client.spec.ts @@ -1,11 +1,11 @@ -// Per-turn latency/throughput fold and the footer figure formatters. +// Assistant timing readings and statistics formatting. import { describe, expect, it } from 'vitest' import type { - AssistantMessageNode, ConversationNode, UserMessageNode, + AssistantMessageNode, } from '@deepseek-ai/dsh-client-ui-chat/client' -import { assistantStepReading, deriveTurnMetrics } from '../src/client/contract/turn-metrics.ts' -import { formatLatencySeconds, formatTokensPerSecond } from '../src/client/chat/message-chrome.ts' +import { assistantStepReading } from '../src/client/contract/turn-metrics.ts' +import { formatTokensPerSecond } from '../src/client/chat/message-chrome.ts' import { formatCacheHitPercent } from '../src/client/chat/token-format.ts' interface StepSpec { @@ -22,10 +22,6 @@ const assistant = ({ seq, turn, step, timing, usage }: StepSpec): AssistantMessa ...(usage === undefined ? {} : { usage }), }) -const user = (seq: number): UserMessageNode => ({ - kind: 'user', seq, time: seq * 1_000, content: [{ type: 'text', text: 'hi' }] as never, source: null, -}) - describe('assistantStepReading', () => { it('derives ttft, decode time, and output tokens from a fully recorded step', () => { const reading = assistantStepReading(assistant({ @@ -66,92 +62,11 @@ describe('assistantStepReading', () => { }) }) -describe('deriveTurnMetrics', () => { - it('takes ttft from the lowest step and throughput over all sampled steps', () => { - const nodes: ConversationNode[] = [ - user(1), - // Out of step order on purpose: the lowest step owns the ttft slot. - assistant({ - seq: 4, turn: 1, step: 2, - timing: { stepStartTime: 10_000, firstTokenTime: 10_200, completedTime: 12_200 }, - usage: { outputTokens: 60 }, - }), - assistant({ - seq: 2, turn: 1, step: 1, - timing: { stepStartTime: 1_000, firstTokenTime: 2_200, completedTime: 5_200 }, - usage: { outputTokens: 40 }, - }), - ] - // 100 tokens over 5s of decode. - expect(deriveTurnMetrics(nodes).get(1)).toEqual({ ttftMs: 1_200, tokensPerSecond: 20 }) - }) - - it('emits ttft without throughput when no step carries usage', () => { - const nodes = [assistant({ - seq: 2, turn: 1, step: 1, - timing: { stepStartTime: 1_000, firstTokenTime: 1_900, completedTime: 3_000 }, - })] - expect(deriveTurnMetrics(nodes).get(1)).toEqual({ ttftMs: 900 }) - }) - - it('emits throughput without ttft when only a later step is recorded', () => { - const nodes = [ - assistant({ seq: 2, turn: 1, step: 1 }), - assistant({ - seq: 4, turn: 1, step: 2, - timing: { stepStartTime: 10_000, firstTokenTime: 10_500, completedTime: 12_500 }, - usage: { outputTokens: 30 }, - }), - ] - expect(deriveTurnMetrics(nodes).get(1)).toEqual({ tokensPerSecond: 15 }) - }) - - it('omits turns with no readings and zero-decode throughput', () => { - const nodes = [ - assistant({ seq: 2, turn: 1, step: 1 }), - assistant({ - seq: 4, turn: 2, step: 1, - timing: { stepStartTime: null, firstTokenTime: 5_000, completedTime: 5_000 }, - usage: { outputTokens: 10 }, - }), - ] - expect(deriveTurnMetrics(nodes).size).toBe(0) - }) - - it('keeps turns independent and ignores non-assistant nodes', () => { - const nodes: ConversationNode[] = [ - user(1), - assistant({ - seq: 2, turn: 1, step: 1, - timing: { stepStartTime: 1_000, firstTokenTime: 1_400, completedTime: 2_400 }, - usage: { outputTokens: 10 }, - }), - user(3), - assistant({ - seq: 4, turn: 2, step: 1, - timing: { stepStartTime: 4_000, firstTokenTime: 4_100, completedTime: 6_100 }, - usage: { outputTokens: 100 }, - }), - ] - const metrics = deriveTurnMetrics(nodes) - expect(metrics.get(1)).toEqual({ ttftMs: 400, tokensPerSecond: 10 }) - expect(metrics.get(2)).toEqual({ ttftMs: 100, tokensPerSecond: 50 }) - }) -}) - describe('footer figure formatters', () => { it('omits a redundant decimal zero in cache-hit percentages', () => { expect(formatCacheHitPercent(1, 2, 1)).toBe('50') }) - it('formats latency with one decimal under ten seconds and whole seconds beyond', () => { - expect(formatLatencySeconds(840)).toBe('0.8') - expect(formatLatencySeconds(1_000)).toBe('1') - expect(formatLatencySeconds(9_949)).toBe('9.9') - expect(formatLatencySeconds(12_400)).toBe('12') - expect(formatLatencySeconds(-5)).toBe('0') - }) - it('formats throughput with whole tokens from ten up and one decimal below', () => { expect(formatTokensPerSecond(34.4)).toBe('34') expect(formatTokensPerSecond(9.96)).toBe('10') diff --git a/packages/client/ui-chat/tests/turn-usage-panel.client.spec.tsx b/packages/client/ui-chat/tests/turn-usage-panel.client.spec.tsx index cd1704eb61..107ca55f9e 100644 --- a/packages/client/ui-chat/tests/turn-usage-panel.client.spec.tsx +++ b/packages/client/ui-chat/tests/turn-usage-panel.client.spec.tsx @@ -4,7 +4,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { cleanup, fireEvent, render } from '@testing-library/react' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' -import { TurnTimePanel, TurnUsagePanel } from '../src/client/chat/TurnUsagePanel.tsx' +import { TurnUsagePanel } from '../src/client/chat/TurnUsagePanel.tsx' import type { TurnTokenUsage } from '../src/client/contract/chat-nodes.ts' import { en } from '../src/client/locale.ts' @@ -96,38 +96,3 @@ describe('TurnUsagePanel', () => { expect(view.queryByRole('dialog')).toBeNull() }) }) - -describe('TurnTimePanel', () => { - it('shows a clock-and-duration pill and opens the time dialog on click', () => { - const view = render( - , - ) - const trigger = view.getByRole('button') - expect(trigger.textContent).toBe('Ran for 19s') - expect(trigger.querySelector('svg')).not.toBeNull() - expect(trigger.getAttribute('aria-haspopup')).toBe('dialog') - expect(view.queryByRole('dialog')).toBeNull() - - fireEvent.click(trigger) - expect(trigger.getAttribute('aria-expanded')).toBe('true') - const dialog = view.getByRole('dialog') - expect(dialog.getAttribute('aria-label')).toBe('Turn time and speed') - expect(dialog.parentElement).toBe(document.body) - const details = dialog.querySelector('[data-turn-time-details]') as HTMLElement - expect(details.textContent).toContain('Total run time19s') - expect(details.textContent).toContain('Tokens per second (TPS)20 tok/s') - expect(details.textContent).toContain('Time to first token (TTFT)1.2s') - - fireEvent.keyDown(document, { key: 'Escape' }) - expect(view.queryByRole('dialog')).toBeNull() - }) - - it('omits unrecorded speed and TTFT rows', () => { - const view = render() - fireEvent.click(view.getByRole('button')) - const dialog = view.getByRole('dialog') - expect(dialog.textContent).toContain('Total run time3s') - expect(dialog.textContent).not.toContain('Tokens per second') - expect(dialog.textContent).not.toContain('Time to first token') - }) -}) diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 690e574c27..927527cd5c 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -176,7 +176,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.assistant-actions\', () => ctx.slots.register(\n { name: \'conversation.chat.assistant-actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:219', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:227', }, { key: 'conversation.chat.commandview', @@ -224,7 +224,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.commandview\', () => ctx.slots.register(\n { name: \'conversation.chat.commandview\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:207', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:215', }, { key: 'conversation.chat.node', @@ -293,7 +293,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.node\', () => ctx.slots.register(\n { name: \'conversation.chat.node\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:188', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:196', }, { key: 'conversation.chat.turnTail', @@ -354,7 +354,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.turnTail\', () => ctx.slots.register(\n { name: \'conversation.chat.turnTail\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:213', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:221', }, { key: 'conversation.composer', @@ -1128,7 +1128,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.message.images\', () => ctx.slots.register(\n { name: \'conversation.message.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:201', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:209', }, { key: 'conversation.plan-review.actions', @@ -1991,6 +1991,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ declaredBy: 'an entry in \'settings.section\' (client-ui-settings-general), so it exists while that entry is mounted', occupants: [ 'client-locale LanguageRow id \'language\'', + 'client-ui-chat PerformanceUsageRow id \'performance-usage\'', 'client-ui-chat TranscriptViewRow id \'transcript-view\'', 'client-ui-conversation EnterBehaviorRow id \'composer-enter\'', 'client-ui-permission-presets PermissionRow id \'permission\'', diff --git a/snapshots/web/changed-files-turn/ui.expected.md b/snapshots/web/changed-files-turn/ui.expected.md index e6d546d851..35a1a4d004 100644 --- a/snapshots/web/changed-files-turn/ui.expected.md +++ b/snapshots/web/changed-files-turn/ui.expected.md @@ -99,5 +99,4 @@ - button "有问题的回答" - button "在新对话中分支" - button "用量 36.2K tok" -- button "用时 {{duration}}" - text: {{clock}} diff --git a/snapshots/web/deepseek-messages-chat/ui.expected.md b/snapshots/web/deepseek-messages-chat/ui.expected.md index 3822fac786..df658c2f8f 100644 --- a/snapshots/web/deepseek-messages-chat/ui.expected.md +++ b/snapshots/web/deepseek-messages-chat/ui.expected.md @@ -18,7 +18,6 @@ - button "有问题的回答" - button "在新对话中分支" - button "用量 8.2K tok" -- button "用时 {{duration}}" - text: {{clock}} - textbox "发消息或创建任务, / 调用指令, @ 文件或对话" - button "添加文件或调用指令" diff --git a/snapshots/web/feedback-command/ack-expanded.expected.md b/snapshots/web/feedback-command/ack-expanded.expected.md index 679a7f2ecc..193f1e1cff 100644 --- a/snapshots/web/feedback-command/ack-expanded.expected.md +++ b/snapshots/web/feedback-command/ack-expanded.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - 'button "feedback Feedback recorded for session session-{{uuid}} Anonymous user: {{uuid}}."' - textbox "Message or run a task, / commands, @ files or sessions" diff --git a/snapshots/web/feedback-command/ack.expected.md b/snapshots/web/feedback-command/ack.expected.md index 8de2c855f3..c9e9bad335 100644 --- a/snapshots/web/feedback-command/ack.expected.md +++ b/snapshots/web/feedback-command/ack.expected.md @@ -16,7 +16,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - 'button "feedback Feedback recorded for session session-{{uuid}} Anonymous user: {{uuid}}."' - textbox "Message or run a task, / commands, @ files or sessions" diff --git a/snapshots/web/feedback-release/ack-expanded.expected.md b/snapshots/web/feedback-release/ack-expanded.expected.md index 679a7f2ecc..193f1e1cff 100644 --- a/snapshots/web/feedback-release/ack-expanded.expected.md +++ b/snapshots/web/feedback-release/ack-expanded.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - 'button "feedback Feedback recorded for session session-{{uuid}} Anonymous user: {{uuid}}."' - textbox "Message or run a task, / commands, @ files or sessions" diff --git a/snapshots/web/feedback-release/ack.expected.md b/snapshots/web/feedback-release/ack.expected.md index 8de2c855f3..c9e9bad335 100644 --- a/snapshots/web/feedback-release/ack.expected.md +++ b/snapshots/web/feedback-release/ack.expected.md @@ -16,7 +16,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - 'button "feedback Feedback recorded for session session-{{uuid}} Anonymous user: {{uuid}}."' - textbox "Message or run a task, / commands, @ files or sessions" diff --git a/snapshots/web/file-upload-round/ui.expected.md b/snapshots/web/file-upload-round/ui.expected.md index dd833a9103..373474e2e9 100644 --- a/snapshots/web/file-upload-round/ui.expected.md +++ b/snapshots/web/file-upload-round/ui.expected.md @@ -20,7 +20,6 @@ - button "Bad response" - button "Branch into a new conversation" - button "Usage 17.3K tok" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/fresh-round-trip/ui-expanded.expected.md b/snapshots/web/fresh-round-trip/ui-expanded.expected.md index 59857b3a36..aaa7617775 100644 --- a/snapshots/web/fresh-round-trip/ui-expanded.expected.md +++ b/snapshots/web/fresh-round-trip/ui-expanded.expected.md @@ -20,7 +20,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/fresh-round-trip/ui.expected.md b/snapshots/web/fresh-round-trip/ui.expected.md index 8fcd0762e2..517580bf06 100644 --- a/snapshots/web/fresh-round-trip/ui.expected.md +++ b/snapshots/web/fresh-round-trip/ui.expected.md @@ -16,7 +16,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md b/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md index 9dda6dd66b..439bfe0fed 100644 --- a/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md +++ b/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md @@ -42,7 +42,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "System prompt" - button "5 tool calls · 2 messages" [expanded] @@ -124,7 +123,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "Back to bottom" - textbox "Message or run a task, / commands, @ files or sessions" diff --git a/snapshots/web/goal-multi-turn-actions/ui.expected.md b/snapshots/web/goal-multi-turn-actions/ui.expected.md index 22d915bc3e..de78d8224b 100644 --- a/snapshots/web/goal-multi-turn-actions/ui.expected.md +++ b/snapshots/web/goal-multi-turn-actions/ui.expected.md @@ -28,7 +28,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "System prompt" - button "5 tool calls · 2 messages" @@ -85,7 +84,6 @@ - button "Bad response" - button "Branch into a new conversation" - tooltip "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md b/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md index 3b481f8cca..bb2569da3d 100644 --- a/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md +++ b/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/lifecycle-chrome/reloaded.expected.md b/snapshots/web/lifecycle-chrome/reloaded.expected.md index 7c17dfc106..1cef83a500 100644 --- a/snapshots/web/lifecycle-chrome/reloaded.expected.md +++ b/snapshots/web/lifecycle-chrome/reloaded.expected.md @@ -16,7 +16,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/live-interactions/cancel-expanded.expected.md b/snapshots/web/live-interactions/cancel-expanded.expected.md index 94a19be9f9..38df9a295c 100644 --- a/snapshots/web/live-interactions/cancel-expanded.expected.md +++ b/snapshots/web/live-interactions/cancel-expanded.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/live-interactions/cancel.expected.md b/snapshots/web/live-interactions/cancel.expected.md index b5f6d26fd0..fb25f9e5d1 100644 --- a/snapshots/web/live-interactions/cancel.expected.md +++ b/snapshots/web/live-interactions/cancel.expected.md @@ -17,7 +17,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/live-interactions/retry-expanded.expected.md b/snapshots/web/live-interactions/retry-expanded.expected.md index 0e6187e973..72429a5f1d 100644 --- a/snapshots/web/live-interactions/retry-expanded.expected.md +++ b/snapshots/web/live-interactions/retry-expanded.expected.md @@ -20,7 +20,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/live-interactions/retry.expected.md b/snapshots/web/live-interactions/retry.expected.md index af9acdfd3a..e02699f7b7 100644 --- a/snapshots/web/live-interactions/retry.expected.md +++ b/snapshots/web/live-interactions/retry.expected.md @@ -16,7 +16,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/message-actions/compact.expected.md b/snapshots/web/message-actions/compact.expected.md new file mode 100644 index 0000000000..fe95152fa5 --- /dev/null +++ b/snapshots/web/message-actions/compact.expected.md @@ -0,0 +1 @@ +- text: {{throughput}} tok/s Cache hit 98% diff --git a/snapshots/web/message-actions/ui.expected.md b/snapshots/web/message-actions/ui.expected.md index 98a48bb121..4f94675057 100644 --- a/snapshots/web/message-actions/ui.expected.md +++ b/snapshots/web/message-actions/ui.expected.md @@ -20,9 +20,7 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" [disabled] -- text: Available only on the last message of a completed turn -- button "Ran for {{duration}}" -- text: {{clock}} +- text: Available only on the last message of a completed turn {{clock}} - button "Read a.txt": - text: Read - button "a.txt" @@ -37,7 +35,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} Keep this later input in the original conversation. {{clock}} - button "Copy" - paragraph: ORIGINAL ONLY @@ -45,7 +42,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/minimal-preset/ui.expected.md b/snapshots/web/minimal-preset/ui.expected.md index 7ad491e0cf..747da8bbea 100644 --- a/snapshots/web/minimal-preset/ui.expected.md +++ b/snapshots/web/minimal-preset/ui.expected.md @@ -19,7 +19,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/plan-review/approved-expanded.expected.md b/snapshots/web/plan-review/approved-expanded.expected.md index 1c7fce2311..742e32348d 100644 --- a/snapshots/web/plan-review/approved-expanded.expected.md +++ b/snapshots/web/plan-review/approved-expanded.expected.md @@ -26,7 +26,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/plan-review/approved.expected.md b/snapshots/web/plan-review/approved.expected.md index da51f924a1..17cb2ec82d 100644 --- a/snapshots/web/plan-review/approved.expected.md +++ b/snapshots/web/plan-review/approved.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/present-svg/ui.expected.md b/snapshots/web/present-svg/ui.expected.md index 8d1982ff68..3a6f85583c 100644 --- a/snapshots/web/present-svg/ui.expected.md +++ b/snapshots/web/present-svg/ui.expected.md @@ -44,5 +44,4 @@ - button "有问题的回答" - button "在新对话中分支" - button "用量 32K tok" -- button "用时 {{duration}}" - text: {{clock}} diff --git a/snapshots/web/present/ui.expected.md b/snapshots/web/present/ui.expected.md index e4c3ec81e6..20ec6c8afe 100644 --- a/snapshots/web/present/ui.expected.md +++ b/snapshots/web/present/ui.expected.md @@ -51,7 +51,6 @@ - button "Bad response" - button "Branch into a new conversation" - button "Usage 19K tok" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/ptc-round/ui.expected.md b/snapshots/web/ptc-round/ui.expected.md index e9212ee443..77daf41f67 100644 --- a/snapshots/web/ptc-round/ui.expected.md +++ b/snapshots/web/ptc-round/ui.expected.md @@ -27,7 +27,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/question-composer/answered-expanded.expected.md b/snapshots/web/question-composer/answered-expanded.expected.md index 1da8b2f2cd..58b3ed28b3 100644 --- a/snapshots/web/question-composer/answered-expanded.expected.md +++ b/snapshots/web/question-composer/answered-expanded.expected.md @@ -23,7 +23,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/question-composer/answered.expected.md b/snapshots/web/question-composer/answered.expected.md index d865c5f8e6..6e7738f321 100644 --- a/snapshots/web/question-composer/answered.expected.md +++ b/snapshots/web/question-composer/answered.expected.md @@ -16,7 +16,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/queue-actions/preserved-expanded.expected.md b/snapshots/web/queue-actions/preserved-expanded.expected.md index 22d8b78588..4efa97d7c0 100644 --- a/snapshots/web/queue-actions/preserved-expanded.expected.md +++ b/snapshots/web/queue-actions/preserved-expanded.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "2 queued messages" [expanded] - list: diff --git a/snapshots/web/queue-actions/preserved.expected.md b/snapshots/web/queue-actions/preserved.expected.md index 6864b1fc3d..099622b124 100644 --- a/snapshots/web/queue-actions/preserved.expected.md +++ b/snapshots/web/queue-actions/preserved.expected.md @@ -17,7 +17,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "2 queued messages" [expanded] - list: diff --git a/snapshots/web/queued-image/delivered.expected.md b/snapshots/web/queued-image/delivered.expected.md index d2ebeeb0bb..4e3aaa548f 100644 --- a/snapshots/web/queued-image/delivered.expected.md +++ b/snapshots/web/queued-image/delivered.expected.md @@ -21,7 +21,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "queued.png, click to view original": - img "queued.png" @@ -33,7 +32,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} Continue with the queued comparison {{clock}} - button "Copy" - button "Thought for a while" @@ -42,7 +40,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/seeded-history/command-row.expected.md b/snapshots/web/seeded-history/command-row.expected.md index 63052fbda9..72449c0f85 100644 --- a/snapshots/web/seeded-history/command-row.expected.md +++ b/snapshots/web/seeded-history/command-row.expected.md @@ -26,7 +26,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "compact Compacted 5 history items (~{{tokens}} tokens)" - button "Context injection AGENTS.md" diff --git a/snapshots/web/seeded-history/feedback-row.expected.md b/snapshots/web/seeded-history/feedback-row.expected.md index 9238eb5070..ca827139a0 100644 --- a/snapshots/web/seeded-history/feedback-row.expected.md +++ b/snapshots/web/seeded-history/feedback-row.expected.md @@ -26,7 +26,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "compact Compacted 5 history items (~{{tokens}} tokens)" - button "Context injection AGENTS.md" diff --git a/snapshots/web/seeded-history/ui-expanded.expected.md b/snapshots/web/seeded-history/ui-expanded.expected.md index b7606e8776..cedbc667dd 100644 --- a/snapshots/web/seeded-history/ui-expanded.expected.md +++ b/snapshots/web/seeded-history/ui-expanded.expected.md @@ -26,7 +26,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "compact Compacted 5 history items (~{{tokens}} tokens)" - button "Context injection AGENTS.md" diff --git a/snapshots/web/seeded-history/ui.expected.md b/snapshots/web/seeded-history/ui.expected.md index 9a40a350d9..57b3f91a06 100644 --- a/snapshots/web/seeded-history/ui.expected.md +++ b/snapshots/web/seeded-history/ui.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "compact Compacted 5 history items (~{{tokens}} tokens)" - button "Context injection AGENTS.md" diff --git a/snapshots/web/skill-tool-row/ui.expected.md b/snapshots/web/skill-tool-row/ui.expected.md index d3dfcb56f3..d0d16efd83 100644 --- a/snapshots/web/skill-tool-row/ui.expected.md +++ b/snapshots/web/skill-tool-row/ui.expected.md @@ -22,7 +22,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{date}} {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/steering/settled-expanded.expected.md b/snapshots/web/steering/settled-expanded.expected.md index dab18a04b1..a1427d9404 100644 --- a/snapshots/web/steering/settled-expanded.expected.md +++ b/snapshots/web/steering/settled-expanded.expected.md @@ -20,7 +20,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/steering/settled.expected.md b/snapshots/web/steering/settled.expected.md index d327666fc1..04ad8d224d 100644 --- a/snapshots/web/steering/settled.expected.md +++ b/snapshots/web/steering/settled.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/subagent-conversation/sidebar-chat.expected.md b/snapshots/web/subagent-conversation/sidebar-chat.expected.md index 63ccfba712..588d7bc778 100644 --- a/snapshots/web/subagent-conversation/sidebar-chat.expected.md +++ b/snapshots/web/subagent-conversation/sidebar-chat.expected.md @@ -7,7 +7,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/subagent-conversation/ui-expanded.expected.md b/snapshots/web/subagent-conversation/ui-expanded.expected.md index c32ce44656..5e7253e2fe 100644 --- a/snapshots/web/subagent-conversation/ui-expanded.expected.md +++ b/snapshots/web/subagent-conversation/ui-expanded.expected.md @@ -24,7 +24,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "System prompt" - text: Now give the same explanation to a human reader. {{clock}} @@ -36,7 +35,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/subagent-conversation/ui.expected.md b/snapshots/web/subagent-conversation/ui.expected.md index 63534c81fb..62af856938 100644 --- a/snapshots/web/subagent-conversation/ui.expected.md +++ b/snapshots/web/subagent-conversation/ui.expected.md @@ -22,7 +22,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - button "System prompt" - text: Now give the same explanation to a human reader. {{clock}} @@ -33,7 +32,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/turn-tail-actions/completed.expected.md b/snapshots/web/turn-tail-actions/completed.expected.md index 8f3053942f..7b3c3e481e 100644 --- a/snapshots/web/turn-tail-actions/completed.expected.md +++ b/snapshots/web/turn-tail-actions/completed.expected.md @@ -17,7 +17,6 @@ - button "Bad response" - button "Branch into a new conversation" - button "Usage 15.8K tok" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/turn-tail-actions/focused.expected.md b/snapshots/web/turn-tail-actions/focused.expected.md index d79d578b20..860191368f 100644 --- a/snapshots/web/turn-tail-actions/focused.expected.md +++ b/snapshots/web/turn-tail-actions/focused.expected.md @@ -21,7 +21,6 @@ - button "Bad response" - button "Branch into a new conversation" - button "Usage 15.8K tok" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/turn-tail-actions/settled.expected.md b/snapshots/web/turn-tail-actions/settled.expected.md index 09c57d760e..4312288efa 100644 --- a/snapshots/web/turn-tail-actions/settled.expected.md +++ b/snapshots/web/turn-tail-actions/settled.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/turn-tail-actions/usage-expanded.expected.md b/snapshots/web/turn-tail-actions/usage-expanded.expected.md index f725ddc0c2..64a4b1b0ef 100644 --- a/snapshots/web/turn-tail-actions/usage-expanded.expected.md +++ b/snapshots/web/turn-tail-actions/usage-expanded.expected.md @@ -17,7 +17,6 @@ - button "Bad response" - button "Branch into a new conversation" - button "Usage 15.8K tok" [expanded] -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/web-search-round/ui.expected.md b/snapshots/web/web-search-round/ui.expected.md index 32429834ab..27d0cce32c 100644 --- a/snapshots/web/web-search-round/ui.expected.md +++ b/snapshots/web/web-search-round/ui.expected.md @@ -18,7 +18,6 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" diff --git a/snapshots/web/workflow-run/ui.expected.md b/snapshots/web/workflow-run/ui.expected.md index f8023a0622..40d39e64cf 100644 --- a/snapshots/web/workflow-run/ui.expected.md +++ b/snapshots/web/workflow-run/ui.expected.md @@ -12,5 +12,4 @@ - button "Good response" - button "Bad response" - button "Branch into a new conversation" -- button "Ran for {{duration}}" - text: {{clock}} From d4ed1d93d8a008c6eff2bd5a3ee81197b4e43cbf Mon Sep 17 00:00:00 2001 From: winewill <324803222+winewill@users.noreply.github.com> Date: Fri, 18 Sep 2026 11:48:45 +0800 Subject: [PATCH 07/10] feat(desktop): share Windows runtime signature cache across worktrees --- ...-windows-runtime-signature-cache.i18n.yaml | 4 +- ...6-09-17-windows-runtime-signature-cache.md | 12 ++ ...9-17-windows-runtime-signature-cache.zh.md | 12 ++ apps/desktop/.env.windows.example | 5 +- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 8 +- apps/desktop/README.zh.md | 8 +- apps/desktop/package.json | 2 + .../scripts/desktop-package-environment.mjs | 4 +- .../manage-windows-signature-cache.mjs | 28 +++ apps/desktop/scripts/package-target.ts | 31 +++- apps/desktop/scripts/sign-primary-runtime.ts | 56 +++--- .../windows-signature-cache-directory.d.mts | 14 ++ .../windows-signature-cache-directory.mjs | 38 ++++ .../windows-signature-cache-directory.ps1 | 40 ++++ .../scripts/windows-signature-cache.d.mts | 46 ++++- .../scripts/windows-signature-cache.mjs | 173 +++++++++++++++--- .../scripts/windows-signing-stage.d.mts | 16 ++ .../desktop/scripts/windows-signing-stage.mjs | 61 ++++++ .../tests/fixtures/windows-signing-stage.mjs | 27 +++ .../tests/package-target-stages.spec.ts | 12 ++ .../windows-signature-cache-directory.spec.ts | 35 ++++ .../tests/windows-signature-cache.spec.ts | 89 ++++++++- .../tests/windows-signing-stage.spec.ts | 125 +++++++++++++ pnpm-lock.yaml | 3 + 25 files changed, 789 insertions(+), 64 deletions(-) create mode 100644 apps/desktop/scripts/manage-windows-signature-cache.mjs create mode 100644 apps/desktop/scripts/windows-signature-cache-directory.d.mts create mode 100644 apps/desktop/scripts/windows-signature-cache-directory.mjs create mode 100644 apps/desktop/scripts/windows-signature-cache-directory.ps1 create mode 100644 apps/desktop/scripts/windows-signing-stage.d.mts create mode 100644 apps/desktop/scripts/windows-signing-stage.mjs create mode 100644 apps/desktop/tests/fixtures/windows-signing-stage.mjs create mode 100644 apps/desktop/tests/windows-signature-cache-directory.spec.ts create mode 100644 apps/desktop/tests/windows-signing-stage.spec.ts diff --git a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.i18n.yaml b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.i18n.yaml index 04d246c108..b2cef5b014 100644 --- a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.i18n.yaml +++ b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.i18n.yaml @@ -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/process/2026-09-17-windows-runtime-signature-cache.md -2026-09-17-windows-runtime-signature-cache.md: 909e39b5c06ed9d529df7553de324295aadf43fe -2026-09-17-windows-runtime-signature-cache.zh.md: c7ee5e1ca5105c21e3a7f4b43342dee20331e88b +2026-09-17-windows-runtime-signature-cache.md: 3182f46680fd862e123a54a7703b0b0dcad8fd79 +2026-09-17-windows-runtime-signature-cache.zh.md: 72b3599b28244d390a00ac5aa1eea0f5f8834c86 diff --git a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md index 909e39b5c0..3182f46680 100644 --- a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md +++ b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md @@ -12,6 +12,12 @@ Windows packaging reconstructs unsigned native dependencies on each build. Signi Cache complete signed runtime files by original content, public certificate, SignTool bytes, signing-script bytes and cache format. Keep valid vendor signatures. Restore a cache hit through a private staged copy only after checking the input record, signed-file digest, Windows trust, timestamp and configured certificate; reject invalid entries without automatic repair or hardware fallback. Publish complete entries atomically, and retain an existing valid entry when concurrent publishers collide. +Share the cache only within the current Windows account. Require a fixed local drive, current-account ownership and a private destination DACL; reject linked or redirected paths. Programs running as that account remain trusted. Explicit migration copies complete integrity-checked entries without modifying its source or replacing an existing valid entry. Different timestamp bytes at the same input/policy key do not require replacement; every actual restoration still verifies Windows trust. + +The default cache lives beside the account's existing signing state under the user profile. AppData is unsuitable for this default because an MSIX launcher can redirect new files into its private package storage, separating otherwise identical worktrees launched from different programs. A validated explicit directory remains available for isolated build storage. + +Serialize each complete signing stage and cache-maintenance operation with an exclusive Windows file handle. The lock covers preflight, primary-runtime signing, application-runtime signing and artifact creation separately, leaving compilation and preparation concurrent. A waiter rechecks the cache after acquisition. Stage ownership and the retained hardware-attempt interlock have different lifetimes: closing the stage handle releases contention, while hardware failures and interruptions retain the existing attempt evidence and never authorize an automatic retry. + Group public-key inspection into bounded batches of 32 files with at most four processes. Require one ordered result for every requested path and await every process in a failed batch. Preserve verification immediately after each hardware signature, before the next signing request. The [primary-runtime decision](../feature/2026-09-14-desktop-primary-runtime.md) continues to own runtime contents, vendor-signature preservation and execution checks. The [release decision](../architecture/2026-08-25-electron-desktop-packaging-and-updates.md) continues to own release identity and signing. Neither is superseded. The cache must preserve their supervised preflight, per-user signing interlock, single-file hardware calls, signed inventory and final packaged-runtime validation. @@ -24,6 +30,10 @@ The [primary-runtime decision](../feature/2026-09-14-desktop-primary-runtime.md) **Whole signed-runtime artifacts only.** They can also avoid extraction and copying, but require assembly and dependency-graph identities. Per-file caching can reuse unchanged native dependencies when application code or one dependency changes. +**Per-entry locks only.** They avoid duplicate signatures for one key but do not coordinate different files, preflight or installer signing against the same hardware token. Stage-wide ownership covers those calls without holding a lock during unrelated compilation. + +**Cache-age expiry.** Age alone does not establish that a timestamped signature is invalid. Rechecking current Windows trust preserves the validation requirement without periodically repeating unchanged hardware signatures. + ## Consequences Repeated builds with unchanged native inputs avoid hardware calls for cached files while retaining preflight and final artifact signing. Changed content or signing policy misses the cache. Corrupt, incomplete, untrusted or incorrectly timestamped entries fail without replacing the target or retrying hardware. Concurrent publication and interrupted processes cannot expose incomplete entries or damage another build's files. @@ -33,3 +43,5 @@ Six complete signed Windows x64 builds cover an empty signature cache, repeated ## Risks The cache consumes local disk and depends on the build account controlling its files and records. It is not a distribution format for untrusted remote caches. Signature validation still depends on Windows trust services; cache hits do not authorize clearing a signing interlock or retrying a failed token operation. A timestamp-service failure can interrupt a cold build even after a successful preflight. + +No automatic capacity eviction runs. Explicit maintenance waits for stage ownership and retires complete entries before deleting their files; interrupted staging directories remain distinguishable from published entries. Runtime summaries count actual publications separately from retained collisions, and report cache verification time separately from signing time. They do not measure the entire package's verification cost. diff --git a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md index c7ee5e1ca5..72b3599b28 100644 --- a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md +++ b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md @@ -12,6 +12,12 @@ Windows 打包每次都会重新生成未签名的原生依赖。为未变化的 按原始内容、公开证书、SignTool 字节、签名脚本字节和缓存格式缓存完整已签名运行时文件。保留有效厂商签名。缓存命中后,通过私有暂存副本核对输入记录、已签名文件摘要、Windows 信任、时间戳和配置的证书,再恢复目标文件;无效缓存项直接失败,不自动修复或回退到硬件签名。完整缓存项原子发布,并发发布冲突时保留已有有效项。 +缓存仅在当前 Windows 账户内共享。要求固定本地磁盘、当前账户所有权及私有目标目录 DACL;拒绝带链接或被重定向的路径。同账户运行的程序仍受信任。显式迁移复制通过完整性检查的完整缓存项,不修改源目录,也不替换已有有效项。同一输入和策略键下的时间戳字节不同,不构成替换理由;每次实际恢复仍验证 Windows 信任。 + +默认缓存位于用户目录下,与账户已有签名状态放在一起。AppData 不适合作为此默认位置,因为 MSIX 启动器可能将新文件重定向到私有包存储,使不同程序启动的相同 worktree 使用不同缓存。独立构建存储仍可指定经过验证的显式目录。 + +通过 Windows 独占文件句柄串行执行每个完整签名阶段及缓存维护操作。锁分别覆盖预检、主要运行时签名、应用运行时签名及产物生成,编译和准备仍可并行。等待者在获取锁后重新检查缓存。阶段所有权与持久保留的硬件尝试互锁具有不同生命周期:关闭阶段句柄释放竞争锁,而硬件失败或中断保留现有尝试证据,绝不构成自动重试授权。 + 公钥验签按每批 32 个文件分组,最多同时运行四个进程。要求每个请求路径都有一条顺序对应的结果,并等待失败批次中的所有进程退出。每次硬件签名后仍立即验签,通过后才开始下一个签名请求。 [主要运行时决策](../feature/2026-09-14-desktop-primary-runtime.zh.md) 继续定义运行时内容、厂商签名保留和执行检查。[发布决策](../architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md) 继续定义发布身份和签名。两者均未被取代。缓存必须保留受监督预检、每用户签名互锁、单文件硬件调用、已签名内容清单和最终打包运行时验证。 @@ -24,6 +30,10 @@ Windows 打包每次都会重新生成未签名的原生依赖。为未变化的 **仅复用整个已签名运行时制品。** 该方案还可以省去解压和复制,但需要标识组装流程及依赖图。逐文件缓存可以在应用代码或单个依赖变化时复用其余未变化的原生依赖。 +**仅使用逐项锁。** 它能避免同一键的重复签名,却无法协调不同文件、预检或安装器签名对同一硬件令牌的访问。阶段级所有权覆盖这些调用,不在无关编译期间持锁。 + +**按缓存年龄过期。** 年龄本身不能说明带时间戳的签名无效。重新检查当前 Windows 信任可以保留验证要求,同时避免周期性重复未变化的硬件签名。 + ## Consequences 原生输入未变化的重复构建不再为缓存覆盖的文件调用硬件签名,但仍执行预检和最终制品签名。内容或签名策略变化时缓存未命中。损坏、不完整、不可信或时间戳不合格的缓存项必须失败,不替换目标文件,也不重试硬件。并发发布和进程中断不能暴露不完整缓存项或损坏其他构建的文件。 @@ -33,3 +43,5 @@ Windows 打包每次都会重新生成未签名的原生依赖。为未变化的 ## Risks 缓存占用本地磁盘,并依赖构建账户控制缓存文件及记录。它不是用于不可信远程缓存的分发格式。签名验证仍依赖 Windows 信任服务;缓存命中不构成清除签名互锁或重试失败令牌操作的授权。即使预检成功,时间戳服务故障仍可能中断冷构建。 + +不执行自动容量淘汰。显式维护等待阶段所有权,在删除文件前先将完整缓存项移出已发布名称;中断的暂存目录仍可与已发布项区分。运行时摘要区分实际发布和冲突保留,并将缓存验证耗时与签名耗时分别记录;它不测量整个安装包的验证成本。 diff --git a/apps/desktop/.env.windows.example b/apps/desktop/.env.windows.example index e162c805d0..80ecebb7a5 100644 --- a/apps/desktop/.env.windows.example +++ b/apps/desktop/.env.windows.example @@ -1,5 +1,5 @@ # Copy to .env.windows (Git ignored). Use UTF-8 and quote secrets containing # or spaces. -# Paths may be absolute or relative to apps/desktop. Values are not shell-expanded. +# Credential file paths may be absolute or relative to apps/desktop. Values are not shell-expanded. DSH_DESKTOP_APP_ID=com.deepseek.harness DSH_DESKTOP_AUTO_UPDATE_ENV=test DOWNLOAD_TEST_ORIGIN= @@ -16,6 +16,9 @@ DSH_DESKTOP_WINDOWS_SIGNTOOL= DSH_DESKTOP_WINDOWS_KEY_CONTAINER= DSH_DESKTOP_WINDOWS_TOKEN_PIN= +# Optional absolute, private local directory; defaults to %USERPROFILE%\.dsh-desktop-signing\signature-cache\v1. +# DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR=C:\Users\build\.dsh-desktop-signing\signature-cache\v1 + # Optional upload configuration; packaging does not require these credentials. # DOWNLOAD_TEST_COS_BUCKET= # DOWNLOAD_TEST_COS_SECRET_ID= diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 0c0db6e288..364ccfffd7 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -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 apps/desktop/README.md -README.md: 531c168c0d3fc3091a330f5350d0a85ac3009f08 -README.zh.md: 6a20f83623a54e8f87d05104280b97ddfb2a796a +README.md: 9a20ec4b919c31f9d3427181ae984c30206aed19 +README.zh.md: a5b876ab97c108db51ebbcea45a78322234ffaa0 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 531c168c0d..9a20ec4b91 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -210,7 +210,13 @@ Run `pnpm --dir apps/desktop run test:installer` from the repository root on an ### Windows EV signing -Runtime signing caches complete signed files under `.desktop-build/targets/win-x64/signature-cache`. Entries identify the original bytes, public certificate and signing toolchain. Restoring an entry checks its digest, Windows trust, timestamp and certificate before replacing the unsigned file; invalid entries stop packaging without hardware fallback. The cache requires trusted local build storage and retains entries until removed. Preflight, hardware interlocks and final artifact signing still apply. Cache qualification and design limits are tracked in the [runtime signature cache decision](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md). +Runtime signing shares complete signed files across the current Windows account's worktrees. `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR` in `.env.windows` selects an absolute fixed-drive directory; the default is `%USERPROFILE%\.dsh-desktop-signing\signature-cache\v1`. Cache directories must belong to the current account and exclude other ordinary accounts from their access permissions; linked paths are rejected. Entries identify the original bytes, public certificate and signing toolchain. Every restoration checks the digest, Windows trust, timestamp and certificate before replacing the unsigned file; invalid entries stop packaging without hardware fallback. Cache age alone does not trigger signing. The cache trusts programs running as the same account and does not defend against administrators. The [runtime signature cache decision](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md) owns qualification and design limits. + +Preflight, primary-runtime signing, application-runtime signing and artifact creation each hold the account's signing-stage lock until their supervised child processes settle. Other builds wait before entering those stages; compilation and preparation do not hold the lock. Runtime signing workers own their locks, so terminating only the outer packaging process does not unlock a surviving cache user. Migration and maintenance acquire the same lock; older or external signing commands do not participate and must be scheduled separately. Stage waiting is outside the preflight deadline. Closing the stage handle releases ordinary contention without removing the separate hardware-attempt interlock; a retained hardware failure still requires operator recovery. + +Each runtime stage writes `SIGNATURE_CACHE_SUMMARY` to stdout and its packaging journal, including the actual directory, policy identity, hit/miss counts, newly published and retained entries, signing requests, avoided signing requests and validation failures. Timings distinguish signing, cache trust verification and restoration; restoration includes its trust check and staging cleanup. These counters exclude preflight, final artifact signing and the outer runtime signature checks. Stage lock events record waiting separately. + +Use `pnpm --dir apps/desktop run cache:windows-signatures --usage` to inspect complete-entry bytes and counts, or `--from ` to import an explicitly selected cache owned by the same account. Migration leaves the source unchanged, skips staging names, rejects corrupt entries and retains valid existing entries even when their timestamp bytes differ. `--clear` explicitly removes complete entries under the stage lock; no automatic capacity eviction runs. `--directory ` selects a maintenance destination without loading release credentials. Incomplete staging entries remain untouched and are counted separately; inspect them only after all builds have stopped. These commands never clear hardware failure evidence. Default storage is outside AppData so MSIX launcher virtualization does not split the account's cache; redirected overrides fail explicitly. Signed Windows builds run a supervised signing preflight before compilation or dependency preparation. Static configuration, certificate validity, audit storage, compiler availability and any retained signing interlock are checked without token access. The local .NET Framework C# compiler creates a small private probe; the production signer signs it once, and verification requires the configured certificate and a timestamp before building continues. The probe is never executed. The overall 60-second preflight deadline includes timestamp attempts; deadline expiry, hardware signing errors and verification failures stop the run without another hardware attempt. Success proves the current signing path works, not that the PIN was independently authenticated: SafeNet may reuse login state. Do not log out or repeat authentication to test the PIN. `--check`, preparation-only and `--unsigned` modes do not run this hardware preflight; unsigned artifacts remain ineligible for release upload. Automated regression tests use a fake signer; release operators qualify real hardware separately. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 6a20f83623..a5b876ab97 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -211,7 +211,13 @@ Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI ### Windows EV 签名 -运行时签名将完整的已签名文件缓存在 `.desktop-build/targets/win-x64/signature-cache`。缓存项标识原始字节、公钥证书和签名工具链。恢复缓存项时,先检查摘要、Windows 信任状态、时间戳和证书,再替换未签名文件;缓存项无效会停止打包,不回退到硬件签名。缓存要求受信任的本地构建存储,并保留缓存项直到被移除。预检、硬件互锁和最终产物签名仍然执行。[运行时签名缓存决策](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md)记录缓存验收要求和设计限制。 +运行时签名在当前 Windows 账户的各 worktree 间共享完整的已签名文件。`.env.windows` 中的 `DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR` 指定固定本地磁盘上的绝对目录;默认值为 `%USERPROFILE%\.dsh-desktop-signing\signature-cache\v1`。缓存目录必须属于当前账户,访问权限不得向其他普通账户开放;带链接的路径会被拒绝。缓存项标识原始字节、公钥证书和签名工具链。每次恢复都检查摘要、Windows 信任状态、时间戳和证书,再替换未签名文件;缓存项无效会停止打包,不回退到硬件签名。不会仅因缓存较旧而重新签名。缓存信任同账户运行的程序,不防御管理员。[运行时签名缓存决策](../../.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md)定义验收要求和设计限制。 + +预检、主要运行时签名、应用运行时签名和产物生成分别持有账户级签名阶段锁,直到受监督的子进程结束。其他构建进入这些阶段前等待;编译和准备步骤不持锁。运行时签名进程自行持锁,因此仅终止外层打包进程不会释放仍在访问缓存的阶段锁。迁移及维护获取同一把锁;旧版或外部签名命令不参与排队,应另行避免并发。阶段等待不计入预检期限。关闭阶段句柄会释放普通竞争锁,不删除独立的硬件尝试互锁;遗留硬件失败仍需操作人员恢复。 + +每个运行时阶段向标准输出及打包日志写入 `SIGNATURE_CACHE_SUMMARY`,包含实际目录、策略标识、命中及未命中数、新发布及保留项数、签名请求数、省去的签名请求数和验证失败数。计时区分签名、缓存信任验证及恢复;恢复耗时包含其信任检查和暂存清理。这些统计不包含预检、最终产物签名及外层运行时验签。阶段锁事件单独记录等待时间。 + +使用 `pnpm --dir apps/desktop run cache:windows-signatures --usage` 查看完整缓存项的字节数和数量,或用 `--from ` 导入显式指定、属于同账户的旧缓存。迁移不修改源目录,跳过暂存名称,拒绝损坏项,并保留已有有效项,即使它们的时间戳字节不同。`--clear` 在阶段锁保护下显式删除完整缓存项;不执行自动容量淘汰。`--directory ` 指定维护目标目录,无需加载发布凭据。不完整暂存项保持原状并单独计数;仅在所有构建停止后检查它们。这些命令绝不清除硬件失败证据。默认存储位于 AppData 之外,避免 MSIX 启动器虚拟化将账户缓存拆开;被重定向的覆盖目录会明确失败。 Windows 签名构建在编译或准备依赖前执行受监督的签名预检。静态配置、证书有效期、审计存储、编译器可用性及遗留签名锁的检查不访问 Token。本地 .NET Framework C# 编译器生成一个专用小探针,由正式签名器仅签名一次,随后必须验出配置的证书和时间戳才能继续构建。探针绝不执行。预检的整体 60 秒期限包含时间戳尝试;超时、硬件签名报错或验签失败都会停止本轮流程,不再次调用硬件。成功只证明当前签名路径可用,不证明 PIN 已独立认证:SafeNet 可能复用登录状态。不要为了验证 PIN 而注销或重复认证。`--check`、仅准备和 `--unsigned` 模式不执行此硬件预检;未签名产物仍不能发布上传。自动回归测试使用假签名器,真实硬件由发布操作人员单独验收。 diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c060f1c673..3d6133cb75 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -15,6 +15,7 @@ "prepare:runtime": "tsx scripts/prepare-runtime.ts", "prepare:primary-runtime": "tsx scripts/prepare-primary-runtime.ts", "sign:primary-runtime": "tsx scripts/sign-primary-runtime.ts", + "cache:windows-signatures": "node scripts/manage-windows-signature-cache.mjs", "prepare:packages": "tsx scripts/prepare-package-set.ts", "prepare:dsh": "tsx scripts/prepare-dsh.ts", "prepare:package": "tsx scripts/package-target.ts --prepare-only", @@ -52,6 +53,7 @@ "extract-zip": "^2.0.1", "fflate": "^0.8.2", "js-yaml": "^4.2.0", + "koffi": "^3.1.0", "pnpm": "11.7.0", "tar": "^7.5.0", "typescript": "^6.0.3" diff --git a/apps/desktop/scripts/desktop-package-environment.mjs b/apps/desktop/scripts/desktop-package-environment.mjs index 0166288df4..ee4f31b2bb 100644 --- a/apps/desktop/scripts/desktop-package-environment.mjs +++ b/apps/desktop/scripts/desktop-package-environment.mjs @@ -8,10 +8,11 @@ import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, resolveMacOSS import { resolveDesktopAutoUpdateConfig } from './desktop-auto-update-environment.mjs' import { createWindowsTokenSigner } from './windows-sign.mjs' import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' +import { resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs' const APP_ROOT = fileURLToPath(new URL('..', import.meta.url)) const SHARED_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN))|DOWNLOAD_(?:TEST|PROD)_(?:ORIGIN|COS_BUCKET|COS_SECRET_ID|COS_SECRET_KEY))$/u -const WINDOWS_SETTING = /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN)$/u +const WINDOWS_SETTING = /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN|SIGNATURE_CACHE_DIR)$/u const MACOS_SETTING = /^(?:DSH_DESKTOP_MACOS_(?:SIGNING_IDENTITY|TEAM_ID)|APPLE_(?:API_KEY|API_KEY_ID|API_ISSUER|ID|APP_SPECIFIC_PASSWORD|TEAM_ID|KEYCHAIN|KEYCHAIN_PROFILE)|CSC_(?:LINK|KEY_PASSWORD))$/u const AMBIENT_RELEASE_SETTING = /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|MANDATORY_UPDATE_.*|WINDOWS_.*|MACOS_.*)|APPLE_.*|(?:WIN_)?CSC_.*|DOWNLOAD_(?:TEST|PROD)_.*)$/iu const FILE_SETTINGS = ['DSH_DESKTOP_WINDOWS_CER_FILE', 'DSH_DESKTOP_WINDOWS_SIGNTOOL', 'APPLE_API_KEY', 'APPLE_KEYCHAIN', 'CSC_LINK'] @@ -85,6 +86,7 @@ export function validateDesktopPackageEnvironment(environment, target, options = tokenPin: environment.DSH_DESKTOP_WINDOWS_TOKEN_PIN, keyContainer: environment.DSH_DESKTOP_WINDOWS_KEY_CONTAINER, }) + if (!options.prepareOnly) resolveWindowsSignatureCacheDirectory(environment) } else { resolveMacOSSigningEnvironment(environment) const strategies = [ diff --git a/apps/desktop/scripts/manage-windows-signature-cache.mjs b/apps/desktop/scripts/manage-windows-signature-cache.mjs new file mode 100644 index 0000000000..de44540c70 --- /dev/null +++ b/apps/desktop/scripts/manage-windows-signature-cache.mjs @@ -0,0 +1,28 @@ +/** Explicit current-account migration and storage inspection under the signing-stage lock. */ +import { parseArgs } from 'node:util' +import { loadDesktopPackageEnvironment } from './desktop-package-environment.mjs' +import { prepareWindowsSignatureCacheDirectory, resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs' +import { maintainSignatureCache, migrateSignatureCache } from './windows-signature-cache.mjs' +import { withWindowsSigningStage } from './windows-signing-stage.mjs' + +const { values } = parseArgs({ options: { + from: { type: 'string' }, usage: { type: 'boolean' }, clear: { type: 'boolean' }, directory: { type: 'string' }, +} }) +if ([values.from !== undefined, values.usage === true, values.clear === true].filter(Boolean).length !== 1) { + throw new Error('Specify exactly one of --from , --usage or --clear') +} +const environment = values.directory === undefined ? loadDesktopPackageEnvironment('win32') + : { DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: values.directory } +const root = resolveWindowsSignatureCacheDirectory(environment) +const record = event => process.stdout.write(`${JSON.stringify(event)}\n`) +await withWindowsSigningStage({ stage: values.from !== undefined ? 'cache-migration' : 'cache-maintenance', record }, async () => { + await prepareWindowsSignatureCacheDirectory(root) + if (values.from !== undefined) { + const source = resolveWindowsSignatureCacheDirectory({ DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: values.from }) + await prepareWindowsSignatureCacheDirectory(source, true) + record({ type: 'signature-cache-migration-summary', ...await migrateSignatureCache({ source, root, record }) }) + return + } + record({ type: values.clear ? 'signature-cache-cleared' : 'signature-cache-usage', root, + ...await maintainSignatureCache(root, values.clear) }) +}) diff --git a/apps/desktop/scripts/package-target.ts b/apps/desktop/scripts/package-target.ts index aede75a697..cff4df6006 100644 --- a/apps/desktop/scripts/package-target.ts +++ b/apps/desktop/scripts/package-target.ts @@ -11,7 +11,9 @@ import { import { desktopTargetBuildPaths } from './desktop-build-paths.mjs' import { packageMacOSArtifacts, type DesktopPrepackagedArtifact } from './package-macos.ts' import { loadDesktopPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs' -import { createPackagingRun } from './packaging-run.mjs' +import { createPackagingRun, recordPackagingEvent } from './packaging-run.mjs' +import { withWindowsSigningStage } from './windows-signing-stage.mjs' +import { prepareWindowsSignatureCacheDirectory, resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs' import { withMacOSSigningKeychain } from './macos-signing-keychain.mjs' const APP_ROOT = resolve(import.meta.dirname, '..') @@ -22,6 +24,7 @@ const WINDOWS_SIGNING_ENV_NAMES = [ 'DSH_DESKTOP_WINDOWS_KEY_CONTAINER', 'DSH_DESKTOP_WINDOWS_SIGNTOOL', 'DSH_DESKTOP_WINDOWS_TOKEN_PIN', + 'DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR', ] as const const DESKTOP_UPLOAD_CREDENTIAL_ENV_NAMES = new Set([ 'DOWNLOAD_TEST_COS_SECRET_ID', @@ -332,11 +335,31 @@ export async function packageTarget( if (!invocation.unsigned && environment[name] !== undefined) electronBuilderEnv[name] = environment[name] } const signPrimaryRuntime = target.platform === 'win32' && !invocation.unsigned && !invocation.prepareOnly + const signedStage = async (stage: string, operation: () => Promise): Promise => { + if (!signPrimaryRuntime) return operation() + if (run === undefined) throw new Error('desktop package: signed Windows packaging requires a supervised run') + const controller = new AbortController() + const interrupted = (): void => controller.abort() + const detach = (): void => { + process.removeListener('SIGINT', interrupted) + process.removeListener('SIGTERM', interrupted) + } + process.once('SIGINT', interrupted) + process.once('SIGTERM', interrupted) + try { + const options = { stage, signal: controller.signal, record: (event: object): void => recordPackagingEvent(run.directory, event) } + await withWindowsSigningStage(options, async () => { + detach() + await operation() + }) + } finally { detach() } + } if (signPrimaryRuntime) { if (run === undefined) throw new Error('desktop package: signed Windows packaging requires a supervised run') - await run.run('preflight:windows-signing', process.execPath, + await prepareWindowsSignatureCacheDirectory(resolveWindowsSignatureCacheDirectory(environment)) + await signedStage('preflight', () => run.run('preflight:windows-signing', process.execPath, ['--import', 'tsx/esm', join(APP_ROOT, 'scripts/windows-signing-preflight.ts')], - { cwd: APP_ROOT, env: electronBuilderEnv, timeoutMs: 60_000 }) + { cwd: APP_ROOT, env: electronBuilderEnv, timeoutMs: 60_000 })) } await execute(['run', 'build:official'], buildEnv, REPOSITORY_ROOT) await execute(['run', 'release:pack', '--family', 'dsh', '--out', buildPaths.packedDsh], buildEnv, REPOSITORY_ROOT) @@ -376,7 +399,7 @@ export async function packageTarget( environment: electronBuilderEnv, }, artifact => execute(desktopElectronBuilderArguments(target, false, artifact), electronBuilderEnv)) } else { - await execute(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv) + await signedStage('artifacts', () => execute(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv)) } if (signPrimaryRuntime) await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts'], targetEnv) if (!invocation.directory && !invocation.unsigned) writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts) diff --git a/apps/desktop/scripts/sign-primary-runtime.ts b/apps/desktop/scripts/sign-primary-runtime.ts index 2f93208c60..d48711b4a0 100644 --- a/apps/desktop/scripts/sign-primary-runtime.ts +++ b/apps/desktop/scripts/sign-primary-runtime.ts @@ -5,6 +5,8 @@ import { join, resolve } from 'node:path' import { createWindowsTokenSigner } from './windows-sign.mjs' import { inspectWindowsRuntimeSignature, signWindowsCode, type WindowsCodeSigningOptions } from './windows-runtime-signature.mjs' import { createCachedSigner, signatureCacheIdentity } from './windows-signature-cache.mjs' +import { prepareWindowsSignatureCacheDirectory, resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs' +import { withWindowsSigningStage } from './windows-signing-stage.mjs' import { failPackagingRun, recordPackagingEvent } from './packaging-run.mjs' import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' import { smokePrimaryRuntime } from './prepare-primary-runtime.ts' @@ -50,30 +52,38 @@ async function main(): Promise { const certificateFile = process.env.DSH_DESKTOP_WINDOWS_CER_FILE if (!certificateFile) throw new Error('primary runtime signing requires the configured certificate') const thumbprint = new X509Certificate(await readFile(certificateFile)).fingerprint.replaceAll(':', '') + const record = (event: object): void => { recordPackagingEvent(runDirectory, event) } try { - const paths = resolveDesktopTargetBuildPaths() - const record = (event: object): void => { recordPackagingEvent(runDirectory, event) } - const sign = createWindowsTokenSigner({ certificateFile, signTool: process.env.DSH_DESKTOP_WINDOWS_SIGNTOOL, - keyContainer: process.env.DSH_DESKTOP_WINDOWS_KEY_CONTAINER, tokenPin: process.env.DSH_DESKTOP_WINDOWS_TOKEN_PIN }) - const identity = await signatureCacheIdentity([ - await realpath(certificateFile), await realpath(process.env.DSH_DESKTOP_WINDOWS_SIGNTOOL!), - join(import.meta.dirname, 'windows-sign.cmd'), join(import.meta.dirname, 'windows-sign.mjs'), - join(import.meta.dirname, 'windows-timestamp.mjs'), - ]) - const options = { - thumbprint, - sign: createCachedSigner({ root: join(paths.root, 'signature-cache'), identity, thumbprint, - sign, inspect: inspectWindowsRuntimeSignature, record }), - record, - } - if (process.argv.includes('--dsh')) { - const version = JSON.parse(await readFile(join(paths.dsh, 'package.json'), 'utf8')).version as string - await signWindowsDesktopRuntime(paths.dsh, version, { ...options, - smoke: descriptor => smokePreparedRuntime(paths.dsh, join(paths.electron, 'electron.exe'), paths.runtime, descriptor), - }) - } else { - await signWindowsPrimaryRuntime(join(paths.runtime, 'primary-runtime'), { ...options, smoke: smokePrimaryRuntime }) - } + await withWindowsSigningStage({ stage: process.argv.includes('--dsh') ? 'dsh-runtime' : 'primary-runtime', record }, async () => { + const paths = resolveDesktopTargetBuildPaths() + const sign = createWindowsTokenSigner({ certificateFile, signTool: process.env.DSH_DESKTOP_WINDOWS_SIGNTOOL, + keyContainer: process.env.DSH_DESKTOP_WINDOWS_KEY_CONTAINER, tokenPin: process.env.DSH_DESKTOP_WINDOWS_TOKEN_PIN }) + const identity = await signatureCacheIdentity([ + await realpath(certificateFile), await realpath(process.env.DSH_DESKTOP_WINDOWS_SIGNTOOL!), + join(import.meta.dirname, 'windows-sign.cmd'), join(import.meta.dirname, 'windows-sign.mjs'), + join(import.meta.dirname, 'windows-timestamp.mjs'), + ]) + const cacheRoot = resolveWindowsSignatureCacheDirectory(process.env) + await prepareWindowsSignatureCacheDirectory(cacheRoot) + const cachedSign = createCachedSigner({ root: cacheRoot, identity, thumbprint, + sign, inspect: inspectWindowsRuntimeSignature, record }) + const options = { thumbprint, sign: cachedSign, record } + record({ type: 'signature-cache-open', root: cachedSign.summary().root, identity }) + try { + if (process.argv.includes('--dsh')) { + const version = JSON.parse(await readFile(join(paths.dsh, 'package.json'), 'utf8')).version as string + await signWindowsDesktopRuntime(paths.dsh, version, { ...options, + smoke: descriptor => smokePreparedRuntime(paths.dsh, join(paths.electron, 'electron.exe'), paths.runtime, descriptor), + }) + } else { + await signWindowsPrimaryRuntime(join(paths.runtime, 'primary-runtime'), { ...options, smoke: smokePrimaryRuntime }) + } + } finally { + const summary = cachedSign.summary() + record({ type: 'signature-cache-summary', ...summary }) + process.stdout.write(`SIGNATURE_CACHE_SUMMARY ${JSON.stringify(summary)}\n`) + } + }) } catch (error) { failPackagingRun(runDirectory, 'primary-runtime-signing-or-smoke-failed') throw error diff --git a/apps/desktop/scripts/windows-signature-cache-directory.d.mts b/apps/desktop/scripts/windows-signature-cache-directory.d.mts new file mode 100644 index 0000000000..411767c61f --- /dev/null +++ b/apps/desktop/scripts/windows-signature-cache-directory.d.mts @@ -0,0 +1,14 @@ +/** + * Resolve the current account's cache or a file-owned absolute local override. + * @param environment Packaging configuration; an absent override uses the current account's signing-state directory. + * @returns Normalized drive path; rejects relative, network, device and alternate-stream paths. + */ +export function resolveWindowsSignatureCacheDirectory(environment: NodeJS.ProcessEnv): string + +/** + * Validate directory ownership, links, drive type and destination access permissions. + * @param path Absolute directory to create or inspect. + * @param existingSource Validate an existing migration source without changing its permissions. + * @returns Resolves after validation; never reads cache entries from another account's directory. + */ +export function prepareWindowsSignatureCacheDirectory(path: string, existingSource?: boolean): Promise diff --git a/apps/desktop/scripts/windows-signature-cache-directory.mjs b/apps/desktop/scripts/windows-signature-cache-directory.mjs new file mode 100644 index 0000000000..3d4a30b880 --- /dev/null +++ b/apps/desktop/scripts/windows-signature-cache-directory.mjs @@ -0,0 +1,38 @@ +/** Resolve and validate the current account's shared runtime-signature cache. */ +import { execFile } from 'node:child_process' +import { homedir } from 'node:os' +import { realpath } from 'node:fs/promises' +import { join, resolve, win32 } from 'node:path' +import { promisify } from 'node:util' +import { scrubWindowsSigningEnvironment } from './windows-sign.mjs' + +/** + * Resolve the file-owned override or the current account's signing-state cache without reading its contents. + * @param {NodeJS.ProcessEnv} environment File-owned packaging configuration. + * @returns {string} Absolute local cache path; relative, network, device and alternate-stream paths are rejected. + */ +export function resolveWindowsSignatureCacheDirectory(environment) { + const path = environment.DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR + ?? win32.join(homedir(), '.dsh-desktop-signing', 'signature-cache', 'v1') + if (!/^[a-z]:[\\/]/iu.test(path) || path.slice(2).includes(':') || /[\0\r\n]/u.test(path)) { + throw new Error('DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR must be an absolute local drive directory') + } + return win32.resolve(path) +} + +/** + * Create private current-account storage or validate an explicitly selected migration source. + * @param {string} path Absolute local directory. + * @param {boolean} existingSource Require an existing, current-account-owned migration source without changing its permissions. + * @returns {Promise} Resolves after checking drive type, ancestor links, ownership and destination permissions. + */ +export async function prepareWindowsSignatureCacheDirectory(path, existingSource = false) { + if (process.platform !== 'win32') throw new Error('Windows signature cache directory validation requires Windows') + await promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-File', + join(import.meta.dirname, 'windows-signature-cache-directory.ps1'), '-CachePath', resolve(path), + ...(existingSource ? ['-ExistingSource'] : []), + ], { env: scrubWindowsSigningEnvironment(process.env), windowsHide: true, timeout: 60_000 }) + if ((await realpath(path)).toLowerCase() !== resolve(path).toLowerCase()) { + throw new Error('Signature cache directory is redirected; configure DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR outside redirected storage') + } +} diff --git a/apps/desktop/scripts/windows-signature-cache-directory.ps1 b/apps/desktop/scripts/windows-signature-cache-directory.ps1 new file mode 100644 index 0000000000..4ea88dd487 --- /dev/null +++ b/apps/desktop/scripts/windows-signature-cache-directory.ps1 @@ -0,0 +1,40 @@ +# Validate account ownership before accessing cache contents; new caches receive a private DACL. +param([Parameter(Mandatory=$true)][string]$CachePath, [switch]$ExistingSource) +$ErrorActionPreference = 'Stop' +[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new() +Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop +$currentSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User +$fullPath = [System.IO.Path]::GetFullPath($CachePath) +if ($fullPath -notmatch '^[A-Za-z]:\\' -or $CachePath -notmatch '^[A-Za-z]:[\\/]') { throw 'Signature cache requires an absolute local drive path' } +$drive = [System.IO.DriveInfo]::new([System.IO.Path]::GetPathRoot($fullPath)) +if ($drive.DriveType -ne [System.IO.DriveType]::Fixed) { throw 'Signature cache requires a fixed local drive' } +for ($ancestor = [System.IO.DirectoryInfo]::new($fullPath); $null -ne $ancestor; $ancestor = $ancestor.Parent) { + if ($ancestor.Exists -and ($ancestor.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) { + throw 'Signature cache cannot use reparse points in its path' + } +} +if ([System.IO.File]::Exists($fullPath)) { throw 'Signature cache path must be a directory' } +if (-not [System.IO.Directory]::Exists($fullPath)) { + if ($ExistingSource) { throw 'Signature cache migration source does not exist' } + $null = [System.IO.Directory]::CreateDirectory($fullPath) + $acl = [System.Security.AccessControl.DirectorySecurity]::new() + $acl.SetOwner($currentSid) + $acl.SetAccessRuleProtection($true, $false) + foreach ($sid in @($currentSid.Value, 'S-1-5-18', 'S-1-5-32-544')) { + $identity = [System.Security.Principal.SecurityIdentifier]::new($sid) + $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow') + $acl.AddAccessRule($rule) + } + Set-Acl -LiteralPath $fullPath -AclObject $acl +} +$acl = Get-Acl -LiteralPath $fullPath +if ($acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -ne $currentSid.Value) { + throw 'Signature cache directory must belong to the current Windows account' +} +if (-not $ExistingSource) { + foreach ($rule in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) { + if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($currentSid.Value, 'S-1-5-18', 'S-1-5-32-544')) { + throw 'Signature cache permissions must exclude other ordinary Windows accounts' + } + } +} diff --git a/apps/desktop/scripts/windows-signature-cache.d.mts b/apps/desktop/scripts/windows-signature-cache.d.mts index bc45bf1b52..4c90d5bd8a 100644 --- a/apps/desktop/scripts/windows-signature-cache.d.mts +++ b/apps/desktop/scripts/windows-signature-cache.d.mts @@ -18,9 +18,53 @@ export interface WindowsSignatureCacheOptions { */ export function signatureCacheIdentity(files: readonly string[]): Promise +/** Counters include failed attempts; restore time includes trust verification and staging cleanup. */ +export interface WindowsSignatureCacheSummary { + root: string + identity: string + hits: number + misses: number + published: number + retained: number + signingCalls: number + avoidedSigningCalls: number + validationFailures: number + verificationMs: number + restoreMs: number + signingMs: number +} + +/** Serial cache callback with a snapshot of this instance's completed and failed operations. */ +export type WindowsCachedSigner = ReturnType & { + /** @returns Current counters and elapsed times; does not wait for queued operations. */ + summary(): WindowsSignatureCacheSummary +} + /** * Reuse complete signed files only after input, integrity, identity and timestamp checks. * @param options Cache policy, supervised signer, public-key verifier and audit sink. * @returns Serial signer that stops its queue on any failure and never repairs invalid cache entries. */ -export function createCachedSigner(options: WindowsSignatureCacheOptions): ReturnType +export function createCachedSigner(options: WindowsSignatureCacheOptions): WindowsCachedSigner + +/** The caller validates ownership and holds the user-wide signing-stage lock throughout migration. */ +export interface SignatureCacheMigrationOptions { + source: string + root: string + record: (event: object) => void +} + +/** + * Copy complete entries without changing the source or replacing valid destination entries. + * @param options Validated directories and credential-free audit sink. + * @returns Counts of published, retained and skipped entries; corruption rejects without repair. Actual use rechecks trust. + */ +export function migrateSignatureCache(options: SignatureCacheMigrationOptions): Promise<{ published: number, retained: number, skipped: number }> + +/** + * Inspect or explicitly clear complete entries under the caller's signing-stage lock. + * @param root Validated current-account cache directory. + * @param clear Remove complete entries after atomic retirement; incomplete staging directories remain untouched. + * @returns Count and bytes of complete entries, plus the number of skipped incomplete entries. + */ +export function maintainSignatureCache(root: string, clear?: boolean): Promise<{ entries: number, bytes: number, incomplete: number }> diff --git a/apps/desktop/scripts/windows-signature-cache.mjs b/apps/desktop/scripts/windows-signature-cache.mjs index a4302badbe..1df9cd955f 100644 --- a/apps/desktop/scripts/windows-signature-cache.mjs +++ b/apps/desktop/scripts/windows-signature-cache.mjs @@ -1,6 +1,6 @@ /** Cache complete signed files; corrupt entries stop the caller before hardware access. */ -import { createHash } from 'node:crypto' -import { copyFile, lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises' +import { createHash, randomUUID } from 'node:crypto' +import { copyFile, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, unlink, writeFile } from 'node:fs/promises' import { basename, dirname, join, resolve, toNamespacedPath } from 'node:path' const digest = bytes => createHash('sha256').update(bytes).digest('hex') @@ -22,7 +22,8 @@ async function regularFile(path) { async function directory(path) { const stat = await lstat(path) - if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(path) !== resolve(path)) { + const normalize = value => process.platform === 'win32' ? toNamespacedPath(resolve(value)).toLowerCase() : resolve(value) + if (!stat.isDirectory() || stat.isSymbolicLink() || normalize(await realpath(path)) !== normalize(path)) { throw new Error(`signature cache: expected unlinked directory: ${path}`) } } @@ -32,21 +33,113 @@ function validSignature(signature, thumbprint) { && signature.thumbprint?.toUpperCase() === thumbprint.toUpperCase() } +async function readCacheEntry(entry, key) { + await directory(entry) + const record = JSON.parse((await regularFile(join(entry, 'record.json'))).toString('utf8')) + if (record === null || typeof record !== 'object' || record.version !== 1 || record.key !== key + || typeof record.inputDigest !== 'string' || !/^[a-f\d]{64}$/u.test(record.inputDigest) + || typeof record.identity !== 'string' || typeof record.signedDigest !== 'string' + || !/^[a-f\d]{64}$/u.test(record.signedDigest) + || digest(JSON.stringify({ version: 1, inputDigest: record.inputDigest, identity: record.identity })) !== key) { + throw new Error('signature cache: invalid input record') + } + if (digest(await regularFile(join(entry, 'payload'))) !== record.signedDigest) throw new Error('signature cache: corrupt signed payload') + return record +} + +/** + * Import complete integrity-checked entries while the caller holds the signing-stage lock. + * @param {import('./windows-signature-cache.mjs').SignatureCacheMigrationOptions} options Validated source, private destination and audit sink. + * @returns {Promise<{published: number, retained: number, skipped: number}>} Counts; existing valid entries win even when timestamp bytes differ. Trust is rechecked at actual use. + */ +export async function migrateSignatureCache(options) { + if (resolve(options.source).toLowerCase() === resolve(options.root).toLowerCase()) throw new Error('signature cache: migration source equals destination') + await directory(options.source) + await mkdir(options.root, { recursive: true }) + await directory(options.root) + const counts = { published: 0, retained: 0, skipped: 0 } + for (const key of await readdir(options.source)) { + if (!/^[a-f\d]{64}$/u.test(key)) { + counts.skipped++ + options.record({ type: 'signature-cache-migration-skipped', reason: 'not-complete-entry-name' }) + continue + } + const source = join(options.source, key) + await readCacheEntry(source, key) + const target = join(options.root, key) + let exists = false + try { await lstat(target); exists = true } + catch (error) { if (error.code !== 'ENOENT') throw error } + if (exists) { + await readCacheEntry(target, key) + counts.retained++ + continue + } + const staging = await mkdtemp(toNamespacedPath(join(options.root, '.publish-'))) + try { + await copyFile(join(source, 'record.json'), join(staging, 'record.json')) + await copyFile(join(source, 'payload'), join(staging, 'payload')) + await readCacheEntry(staging, key) + await rename(staging, target) + counts.published++ + } finally { await rm(staging, { recursive: true, force: true }) } + } + return counts +} + +/** + * Count or explicitly clear complete entries while the caller holds the signing-stage lock. + * @param {string} root Validated, current-account cache directory. + * @param {boolean} clear Retire each complete entry atomically before removing its two regular files. + * @returns {Promise<{entries: number, bytes: number, incomplete: number}>} Complete-entry size and count; incomplete entries are left untouched. + */ +export async function maintainSignatureCache(root, clear = false) { + await directory(root) + let entries = 0 + let bytes = 0 + let incomplete = 0 + for (const name of await readdir(root)) { + if (!/^[a-f\d]{64}$/u.test(name)) { incomplete++; continue } + const entry = join(root, name) + await directory(entry) + const files = await readdir(entry) + if (files.length !== 2 || !files.includes('record.json') || !files.includes('payload')) { + throw new Error('signature cache: unexpected files prevent cache maintenance') + } + for (const file of files) { + const stat = await lstat(join(entry, file)) + if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('signature cache: expected a regular entry file') + bytes += stat.size + } + if (clear) { + const retired = join(root, `.clear-${randomUUID()}`) + await rename(entry, retired) + for (const file of files) await unlink(join(retired, file)) + await rmdir(retired) + } + entries++ + } + return { entries, bytes, incomplete } +} + /** * Wrap a supervised signer with immutable entries keyed by unsigned bytes and signing policy. * @param {import('./windows-signature-cache.mjs').WindowsSignatureCacheOptions} options Cache policy and existing supervised operations. - * @returns {ReturnType} Serial, fail-stop signing callback; cache hits still verify trust and timestamp. + * @returns {import('./windows-signature-cache.mjs').WindowsCachedSigner} Serial, fail-stop callback with counters; cache hits still verify trust and timestamp. */ export function createCachedSigner(options) { let pending = Promise.resolve() + const statistics = { hits: 0, misses: 0, published: 0, retained: 0, signingCalls: 0, validationFailures: 0, + verificationMs: 0, restoreMs: 0, signingMs: 0 } + async function verify(path) { + const start = performance.now() + try { + if (!validSignature(await options.inspect(path), options.thumbprint)) throw new Error('signature cache: invalid signature') + } finally { statistics.verificationMs += performance.now() - start } + } async function readEntry(entry, key, inputDigest) { - await directory(entry) - const record = JSON.parse((await regularFile(join(entry, 'record.json'))).toString('utf8')) - if (record === null || typeof record !== 'object' || record.version !== 1 || record.key !== key || record.inputDigest !== inputDigest - || record.identity !== options.identity || typeof record.signedDigest !== 'string' - || !/^[a-f\d]{64}$/u.test(record.signedDigest)) throw new Error('signature cache: invalid input record') - const payload = await regularFile(join(entry, 'payload')) - if (digest(payload) !== record.signedDigest) throw new Error('signature cache: corrupt signed payload') + const record = await readCacheEntry(entry, key) + if (record.inputDigest !== inputDigest || record.identity !== options.identity) throw new Error('signature cache: invalid input record') return record } async function sign(configuration) { @@ -60,38 +153,66 @@ export function createCachedSigner(options) { try { await lstat(entry); hit = true } catch (error) { if (error.code !== 'ENOENT') throw error } if (hit) { - const record = await readEntry(entry, key, inputDigest) - const staging = await mkdtemp(toNamespacedPath(join(dirname(configuration.path), '.signature-restore-'))) + const start = performance.now() try { - const candidate = join(staging, basename(configuration.path)) - await copyFile(join(entry, 'payload'), candidate) - if (digest(await regularFile(candidate)) !== record.signedDigest) throw new Error('signature cache: restore changed signed bytes') - if (!validSignature(await options.inspect(candidate), options.thumbprint)) throw new Error('signature cache: invalid cached signature') - if (digest(await regularFile(configuration.path)) !== inputDigest) throw new Error('signature cache: target changed before restore') - await rename(candidate, configuration.path) - } finally { await rm(staging, { recursive: true, force: true }) } + const record = await readEntry(entry, key, inputDigest) + const staging = await mkdtemp(toNamespacedPath(join(dirname(configuration.path), '.signature-restore-'))) + try { + const candidate = join(staging, basename(configuration.path)) + await copyFile(join(entry, 'payload'), candidate) + if (digest(await regularFile(candidate)) !== record.signedDigest) throw new Error('signature cache: restore changed signed bytes') + try { await verify(candidate) } + catch (error) { throw new Error('signature cache: invalid cached signature', { cause: error }) } + if (digest(await regularFile(configuration.path)) !== inputDigest) throw new Error('signature cache: target changed before restore') + await rename(candidate, configuration.path) + } finally { await rm(staging, { recursive: true, force: true }) } + } catch (error) { + statistics.validationFailures++ + options.record({ type: 'signature-cache-validation-failed', key, path: configuration.path }) + throw error + } finally { statistics.restoreMs += performance.now() - start } + statistics.hits++ options.record({ type: 'signature-cache-hit', key, path: configuration.path }) return } + statistics.misses++ options.record({ type: 'signature-cache-miss', key, path: configuration.path }) - await options.sign(configuration) - if (!validSignature(await options.inspect(configuration.path), options.thumbprint)) throw new Error('signature cache: new signature verification failed') + const start = performance.now() + statistics.signingCalls++ + try { await options.sign(configuration) } + finally { statistics.signingMs += performance.now() - start } + try { await verify(configuration.path) } + catch (error) { + statistics.validationFailures++ + options.record({ type: 'signature-cache-validation-failed', key, path: configuration.path }) + throw new Error('signature cache: new signature verification failed', { cause: error }) + } const staging = await mkdtemp(toNamespacedPath(join(options.root, '.publish-'))) try { await copyFile(configuration.path, join(staging, 'payload')) const signedDigest = digest(await regularFile(join(staging, 'payload'))) if (signedDigest !== digest(await regularFile(configuration.path))) throw new Error('signature cache: signed file changed during publication') await writeFile(join(staging, 'record.json'), JSON.stringify({ version: 1, key, inputDigest, identity: options.identity, signedDigest }), { flag: 'wx', flush: true }) - try { await rename(staging, entry) } + let published = false + try { await rename(staging, entry); published = true } catch (error) { if (!['EEXIST', 'ENOTEMPTY', 'EPERM'].includes(error.code)) throw error - await readEntry(entry, key, inputDigest) + try { await readEntry(entry, key, inputDigest) } + catch (validationError) { + statistics.validationFailures++ + options.record({ type: 'signature-cache-validation-failed', key, path: configuration.path }) + throw validationError + } } - options.record({ type: 'signature-cache-published', key, path: configuration.path }) + if (published) statistics.published++ + else statistics.retained++ + options.record({ type: published ? 'signature-cache-published' : 'signature-cache-retained', key, path: configuration.path }) } finally { await rm(staging, { recursive: true, force: true }) } } - return configuration => { + const signer = configuration => { pending = pending.then(() => sign(configuration)) return pending } + signer.summary = () => ({ root: options.root, identity: options.identity, ...statistics, avoidedSigningCalls: statistics.hits }) + return signer } diff --git a/apps/desktop/scripts/windows-signing-stage.d.mts b/apps/desktop/scripts/windows-signing-stage.d.mts new file mode 100644 index 0000000000..12f8e49101 --- /dev/null +++ b/apps/desktop/scripts/windows-signing-stage.d.mts @@ -0,0 +1,16 @@ +/** Stage-wide ownership is independent of the retained hardware-attempt interlock. */ +export interface WindowsSigningStageOptions { + stage: string + record: (event: object) => void + signal?: AbortSignal + /** Test-only storage isolates independent processes from the real account's signing state. */ + stateDirectory?: string +} + +/** + * Queue one complete signing or cache-maintenance stage under the account's exclusive file handle. + * @param options Audit sink, optional wait cancellation and isolated test storage. + * @param operation Stage that awaits all owned children before settling. + * @returns The stage result, after releasing the handle; acquisition errors never run the stage. + */ +export function withWindowsSigningStage(options: WindowsSigningStageOptions, operation: () => Promise): Promise diff --git a/apps/desktop/scripts/windows-signing-stage.mjs b/apps/desktop/scripts/windows-signing-stage.mjs new file mode 100644 index 0000000000..65e0043fac --- /dev/null +++ b/apps/desktop/scripts/windows-signing-stage.mjs @@ -0,0 +1,61 @@ +/** Serialize complete signing and cache-maintenance stages without clearing hardware failure evidence. */ +import { lstat, mkdir, realpath } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join, resolve, toNamespacedPath } from 'node:path' +import { setTimeout } from 'node:timers/promises' + +let bindings +async function windows() { + if (process.platform !== 'win32') throw new Error('Windows signing stages require Windows') + if (bindings !== undefined) return bindings + const koffi = (await import('koffi')).default + const kernel = koffi.load('kernel32.dll') + bindings = { + open: kernel.func('__stdcall', 'CreateFileW', 'intptr', ['str16', 'uint', 'uint', 'void*', 'uint', 'uint', 'intptr']), + close: kernel.func('__stdcall', 'CloseHandle', 'int', ['intptr']), + error: kernel.func('__stdcall', 'GetLastError', 'uint', []), + } + return bindings +} + +/** + * Hold one account-wide exclusive file handle until a stage and its children have settled. + * @template T + * @param {import('./windows-signing-stage.mjs').WindowsSigningStageOptions} options Audit sink, cancellation and isolated test storage. + * @param {() => Promise} operation Entire stage, including verification and cache publication. + * @returns {Promise} Stage result; contention waits, all other acquisition errors stop before the operation. + */ +export async function withWindowsSigningStage(options, operation) { + const api = await windows() + const root = options.stateDirectory ?? join(homedir(), '.dsh-desktop-signing') + await mkdir(root, { recursive: true }) + const stat = await lstat(root) + if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(root) !== resolve(root)) { + throw new Error('Windows signing stage requires an unlinked local state directory') + } + const path = join(root, 'stage.lock') + try { + const file = await lstat(path) + if (!file.isFile() || file.isSymbolicLink()) throw new Error('Windows signing stage requires a regular lock file') + } catch (error) { if (error.code !== 'ENOENT') throw error } + const start = performance.now() + let handle + let waiting = false + for (;;) { + options.signal?.throwIfAborted() + // OPEN_ALWAYS retains the same file; denying sharing prevents concurrent holders and deletion. + handle = api.open(toNamespacedPath(path), 0xc0000000, 0, null, 4, 0x80, 0) + if (handle !== -1) break + const code = api.error() + if (code !== 32) throw new Error(`Windows signing stage cannot open its lock (Win32 ${code})`) + if (!waiting) { options.record({ type: 'signing-stage-wait', stage: options.stage }); waiting = true } + await setTimeout(100, undefined, { signal: options.signal }) + } + try { + options.record({ type: 'signing-stage-acquired', stage: options.stage, waitMs: performance.now() - start }) + return await operation() + } finally { + if (api.close(handle) === 0) throw new Error(`Windows signing stage cannot release its lock (Win32 ${api.error()})`) + options.record({ type: 'signing-stage-released', stage: options.stage }) + } +} diff --git a/apps/desktop/tests/fixtures/windows-signing-stage.mjs b/apps/desktop/tests/fixtures/windows-signing-stage.mjs new file mode 100644 index 0000000000..9a2621b06c --- /dev/null +++ b/apps/desktop/tests/fixtures/windows-signing-stage.mjs @@ -0,0 +1,27 @@ +/** Independent process exercising stage ownership and cache reuse with a hardware-free signer. */ +import { appendFile, readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { withWindowsSigningStage } from '../../scripts/windows-signing-stage.mjs' +import { createCachedSigner, maintainSignatureCache } from '../../scripts/windows-signature-cache.mjs' + +const [root, input, mode] = process.argv.slice(2) +const release = new Promise(resolve => process.once('message', resolve)) +await withWindowsSigningStage({ stateDirectory: join(root, 'state'), stage: 'fixture', record: event => process.send(event) }, async () => { + process.send({ type: 'entered' }) + await release + if (mode === 'clear') { + await maintainSignatureCache(join(root, 'cache'), true) + return + } + const thumbprint = 'A'.repeat(40) + const signer = createCachedSigner({ root: join(root, 'cache'), identity: 'fixture', thumbprint, + record: event => process.send(event), + inspect: async path => ({ status: (await readFile(path, 'utf8')).startsWith('signed:') ? 'Valid' : 'NotSigned', timestamped: true, thumbprint }), + sign: async ({ path }) => { + await appendFile(join(root, 'hardware-calls'), 'call\n') + await writeFile(path, `signed:${await readFile(path, 'utf8')}`) + }, + }) + await signer({ path: input, hash: 'sha256', isNest: false }) +}) +process.disconnect() diff --git a/apps/desktop/tests/package-target-stages.spec.ts b/apps/desktop/tests/package-target-stages.spec.ts index 6a238f1026..e74bedc215 100644 --- a/apps/desktop/tests/package-target-stages.spec.ts +++ b/apps/desktop/tests/package-target-stages.spec.ts @@ -1,6 +1,15 @@ import { writeFileSync } from 'node:fs' import { afterEach, expect, it, vi } from 'vitest' import { packageTarget, parseDesktopPackageInvocation } from '../scripts/package-target.ts' +import { withWindowsSigningStage } from '../scripts/windows-signing-stage.mjs' + +vi.mock('../scripts/windows-signing-stage.mjs', () => ({ + withWindowsSigningStage: vi.fn(async (_options: object, operation: () => Promise) => operation()), +})) +vi.mock('../scripts/windows-signature-cache-directory.mjs', () => ({ + prepareWindowsSignatureCacheDirectory: vi.fn(async () => {}), + resolveWindowsSignatureCacheDirectory: vi.fn(() => 'C:\\fixture-cache'), +})) // Keep the real orchestration and manifest reads; this suite owns no release directories or subprocesses. vi.mock('node:fs', async importOriginal => ({ @@ -29,6 +38,8 @@ it('requires one signing preflight before building, then records only the comple await packageTarget(parseDesktopPackageInvocation(['win-x64'], 'win32', 'x64'), environment, run) expect(stages.slice(0, 2)).toEqual(['preflight:windows-signing', 'run build:official']) expect(stages.filter(stage => stage === 'preflight:windows-signing')).toHaveLength(1) + expect(vi.mocked(withWindowsSigningStage).mock.calls.map(([options]) => options.stage)) + .toEqual(['preflight', 'artifacts']) expect(run.run.mock.calls[0]![3]).toMatchObject({ env: { DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'fixture-pin' }, timeoutMs: 60_000 }) expect(run.run.mock.calls[1]![3].env).not.toHaveProperty('DSH_DESKTOP_WINDOWS_TOKEN_PIN') expect(stages.indexOf('run sign:primary-runtime --dsh')).toBeGreaterThan(stages.indexOf('run prepare:dsh --defer-runtime-smoke')) @@ -59,6 +70,7 @@ it.each(['--unsigned', '--prepare-only'])('keeps %s hardware-free and creates no expect(stages).not.toContain('preflight:windows-signing') expect(stages).not.toContain('run sign:primary-runtime') expect(stages).not.toContain('run sign:primary-runtime --dsh') + expect(withWindowsSigningStage).not.toHaveBeenCalled() for (const call of run.run.mock.calls) expect(call[3].env).not.toHaveProperty('DSH_DESKTOP_WINDOWS_TOKEN_PIN') expect(writeFileSync).not.toHaveBeenCalled() }) diff --git a/apps/desktop/tests/windows-signature-cache-directory.spec.ts b/apps/desktop/tests/windows-signature-cache-directory.spec.ts new file mode 100644 index 0000000000..f5ffe76e44 --- /dev/null +++ b/apps/desktop/tests/windows-signature-cache-directory.spec.ts @@ -0,0 +1,35 @@ +import { execFile } from 'node:child_process' +import { mkdtemp, rm, symlink } from 'node:fs/promises' +import { join } from 'node:path' +import { homedir } from 'node:os' +import { promisify } from 'node:util' +import { expect, it } from 'vitest' +import { prepareWindowsSignatureCacheDirectory, resolveWindowsSignatureCacheDirectory } from '../scripts/windows-signature-cache-directory.mjs' + +it.skipIf(process.platform !== 'win32')('resolves an account cache independently of checkout and LocalAppData virtualization', () => { + expect(resolveWindowsSignatureCacheDirectory({ LOCALAPPDATA: 'C:\\Users\\build\\AppData\\Local' })) + .toBe(join(homedir(), '.dsh-desktop-signing', 'signature-cache', 'v1')) +}) + +it('accepts an explicit local cache directory', () => { + expect(resolveWindowsSignatureCacheDirectory({ DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: 'D:/private-cache' })) + .toBe('D:\\private-cache') +}) + +it.each(['', 'cache', 'C:cache', '\\cache', '\\\\server\\share', '\\\\?\\C:\\cache', 'C:\\cache:stream']) +('rejects unsupported cache path %j', (path) => { + expect(() => resolveWindowsSignatureCacheDirectory({ DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: path })).toThrow(/absolute local/u) +}) + +it.skipIf(process.platform !== 'win32')('creates private storage and rejects linked or publicly readable cache roots', async (t) => { + const root = await mkdtemp(join(import.meta.dirname, 'directory-test-')) + t.onTestFinished(() => rm(root, { recursive: true, force: true })) + const cache = join(root, 'private') + await prepareWindowsSignatureCacheDirectory(cache) + await prepareWindowsSignatureCacheDirectory(cache) + const link = join(root, 'linked') + await symlink(cache, link, 'junction') + await expect(prepareWindowsSignatureCacheDirectory(join(link, 'child'))).rejects.toThrow(/reparse/u) + await promisify(execFile)('icacls.exe', [cache, '/grant', '*S-1-1-0:(OI)(CI)R'], { windowsHide: true }) + await expect(prepareWindowsSignatureCacheDirectory(cache)).rejects.toThrow(/permissions/u) +}) diff --git a/apps/desktop/tests/windows-signature-cache.spec.ts b/apps/desktop/tests/windows-signature-cache.spec.ts index d1794a66e0..975feb6fbe 100644 --- a/apps/desktop/tests/windows-signature-cache.spec.ts +++ b/apps/desktop/tests/windows-signature-cache.spec.ts @@ -3,7 +3,7 @@ import { it as test, type TestContext } from 'vitest' import assert from 'node:assert/strict' import { mkdtemp, readFile, readdir, rm, writeFile, mkdir, symlink } from 'node:fs/promises' import { join } from 'node:path' -import { createCachedSigner, signatureCacheIdentity } from '../scripts/windows-signature-cache.mjs' +import { createCachedSigner, maintainSignatureCache, migrateSignatureCache, signatureCacheIdentity } from '../scripts/windows-signature-cache.mjs' async function fixture(t: TestContext) { const root = await mkdtemp(join(import.meta.dirname, 'cache-test-')) @@ -34,6 +34,20 @@ test('unchanged bytes restored in another file avoid another hardware call', asy assert.equal(f.state.events.filter(e => 'type' in e && e.type === 'signature-cache-hit').length, 1) }) +test('cache summaries distinguish avoided signatures from actual signing attempts', async (t) => { + const f = await fixture(t) + const signer = createCachedSigner(f.options) + await signer(f.request) + await writeFile(f.path, 'original') + await signer(f.request) + const { verificationMs, restoreMs, signingMs, ...summary } = signer.summary() + assert.deepEqual(summary, { root: f.cache, identity: f.options.identity, hits: 1, misses: 1, + published: 1, retained: 0, signingCalls: 1, avoidedSigningCalls: 1, validationFailures: 0 }) + assert(verificationMs >= 0 && restoreMs >= 0 && signingMs >= 0) + assert.equal(f.state.hardwareCalls, summary.signingCalls) + assert.equal(await readFile(f.path, 'utf8'), 'signed:original') +}) + test('restores cached signatures into deeply nested dependency paths', async (t) => { const f = await fixture(t) await createCachedSigner(f.options)(f.request) @@ -64,7 +78,10 @@ for (const corrupt of ['payload', 'record.json']) test(`corrupt ${corrupt} stops const entry = (await readdir(f.cache)).find(name => !name.startsWith('.')) assert(entry) await writeFile(join(f.cache, entry, corrupt), 'corrupt') - await assert.rejects(createCachedSigner(f.options)(f.request)) + const signer = createCachedSigner(f.options) + await assert.rejects(signer(f.request)) + assert.equal(signer.summary().validationFailures, 1) + assert.equal(signer.summary().avoidedSigningCalls, 0) assert.equal(f.state.hardwareCalls, 1) assert.equal(await readFile(f.path, 'utf8'), 'original') }) @@ -89,6 +106,8 @@ test('hardware failure rejects queued work without publishing an entry or retryi assert(results.every(result => result.status === 'rejected')) assert.equal(f.state.hardwareCalls, 1) assert.deepEqual(await readdir(f.cache), []) + assert.equal(signer.summary().signingCalls, 1) + assert.equal(signer.summary().validationFailures, 0) }) test('a failed new signature verification never publishes a cache entry', async (t) => { @@ -140,6 +159,8 @@ test('two writers publish one complete entry without overwriting another writer' createCachedSigner(options)({ ...f.request, path: second }), ]) for (const result of results) if (result.status === 'rejected') throw result.reason + assert.equal(f.state.events.filter(e => 'type' in e && e.type === 'signature-cache-published').length, 1) + assert.equal(f.state.events.filter(e => 'type' in e && e.type === 'signature-cache-retained').length, 1) assert.equal((await readdir(f.cache)).length, 1) await writeFile(f.path, 'original') await createCachedSigner(f.options)(f.request) @@ -166,3 +187,67 @@ test('a target changed during verification is never replaced with stale cache by assert.equal(f.state.hardwareCalls, 1) assert(!(await readdir(f.root)).some(name => name.startsWith('.signature-restore-'))) }) + +test('migration preserves different valid timestamp bytes at the same destination key', async (t) => { + const f = await fixture(t) + await createCachedSigner(f.options)(f.request) + const destination = join(f.root, 'shared') + await writeFile(f.path, 'original') + await createCachedSigner({ ...f.options, root: destination, + sign: async ({ path }) => writeFile(path, 'signed:original:another-timestamp'), + })(f.request) + const key = (await readdir(f.cache))[0]! + const sourceRecord = await readFile(join(f.cache, key, 'record.json'), 'utf8') + const counts = await migrateSignatureCache({ source: f.cache, root: destination, record: () => {} }) + assert.deepEqual(counts, { published: 0, retained: 1, skipped: 0 }) + assert.equal(await readFile(join(destination, key, 'payload'), 'utf8'), 'signed:original:another-timestamp') + assert.equal(await readFile(join(f.cache, key, 'record.json'), 'utf8'), sourceRecord) +}) + +test('migration copies complete entries and skips staging directories without reading them', async (t) => { + const f = await fixture(t) + await createCachedSigner(f.options)(f.request) + await mkdir(join(f.cache, '.publish-incomplete')) + const destination = join(f.root, 'shared') + assert.deepEqual(await migrateSignatureCache({ source: f.cache, root: destination, record: () => {} }), + { published: 1, retained: 0, skipped: 1 }) + await writeFile(f.path, 'original') + await createCachedSigner({ ...f.options, root: destination })(f.request) + assert.equal(f.state.hardwareCalls, 1) + assert.equal(await readFile(f.path, 'utf8'), 'signed:original') + assert.equal((await readdir(destination)).length, 1) +}) + +test('migration refuses a corrupt existing destination instead of replacing it', async (t) => { + const f = await fixture(t) + await createCachedSigner(f.options)(f.request) + const destination = join(f.root, 'shared') + await migrateSignatureCache({ source: f.cache, root: destination, record: () => {} }) + const key = (await readdir(destination))[0]! + await writeFile(join(destination, key, 'payload'), 'corrupt') + await assert.rejects(migrateSignatureCache({ source: f.cache, root: destination, record: () => {} }), /corrupt/u) + assert.equal(await readFile(join(destination, key, 'payload'), 'utf8'), 'corrupt') +}) + +test('maintenance counts and clears complete entries while preserving incomplete staging', async (t) => { + const f = await fixture(t) + await createCachedSigner(f.options)(f.request) + await mkdir(join(f.cache, '.publish-incomplete')) + const usage = await maintainSignatureCache(f.cache) + assert.equal(usage.entries, 1) + assert(usage.bytes > 0) + assert.equal(usage.incomplete, 1) + assert.deepEqual(await maintainSignatureCache(f.cache, true), usage) + assert.deepEqual(await readdir(f.cache), ['.publish-incomplete']) + assert.equal(await readFile(f.path, 'utf8'), 'signed:original') +}) + +test('maintenance refuses unexpected entry contents without deleting them', async (t) => { + const f = await fixture(t) + await createCachedSigner(f.options)(f.request) + const key = (await readdir(f.cache))[0]! + const unexpected = join(f.cache, key, 'unrecognized') + await writeFile(unexpected, 'keep') + await assert.rejects(maintainSignatureCache(f.cache, true), /unexpected files/u) + assert.equal(await readFile(unexpected, 'utf8'), 'keep') +}) diff --git a/apps/desktop/tests/windows-signing-stage.spec.ts b/apps/desktop/tests/windows-signing-stage.spec.ts new file mode 100644 index 0000000000..5c1e1b1865 --- /dev/null +++ b/apps/desktop/tests/windows-signing-stage.spec.ts @@ -0,0 +1,125 @@ +import { fork, type ChildProcess } from 'node:child_process' +import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { expect, it, type TestContext } from 'vitest' +import { withWindowsSigningStage } from '../scripts/windows-signing-stage.mjs' + +const test = it.skipIf(process.platform !== 'win32') + +interface StageChild { + process: ChildProcess + events: string[] + closed: Promise<{ code: number | null; signal: NodeJS.Signals | null }> + wait: (event: string) => Promise +} + +async function fixture(t: TestContext) { + const root = await mkdtemp(join(import.meta.dirname, 'stage-test-')) + const children: StageChild[] = [] + t.onTestFinished(async () => { + for (const item of children) { + if (item.process.exitCode === null && item.process.signalCode === null) item.process.kill() + await item.closed + } + await rm(root, { recursive: true, force: true }) + }) + function child(input: string, mode = 'sign'): StageChild { + const process = fork(join(import.meta.dirname, 'fixtures/windows-signing-stage.mjs'), [root, input, mode], { + execArgv: [], stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + }) + const events: string[] = [] + let stderr = '' + process.stderr!.on('data', (chunk) => { stderr += String(chunk) }) + const waiters = new Map void>() + process.on('message', (message: { type: string }) => { events.push(message.type); waiters.get(message.type)?.() }) + const closed = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => { + process.once('close', (code, signal) => { resolve({ code, signal }) }) + }) + const failed = new Promise((_resolve, reject) => { process.once('error', reject) }) + const item = { process, events, closed, + wait: (event: string) => Promise.race([ + events.includes(event) ? Promise.resolve() : new Promise(resolve => waiters.set(event, resolve)), + closed.then((result) => { throw new Error(`fixture exited before ${event}: ${JSON.stringify(result)} ${stderr}`) }), + failed, + ]), + } + children.push(item) + return item + } + const first = join(root, 'first.node') + const second = join(root, 'second.node') + await writeFile(first, 'original') + await writeFile(second, 'original') + return { root, first, second, child } +} + +test('independent signing stages wait and recheck the cache before accessing hardware', async (t) => { + const f = await fixture(t) + const first = f.child(f.first) + await first.wait('entered') + const second = f.child(f.second) + await second.wait('signing-stage-wait') + expect(second.events).not.toContain('entered') + first.process.send('release') + expect(await first.closed).toEqual({ code: 0, signal: null }) + await second.wait('entered') + second.process.send('release') + expect(await second.closed).toEqual({ code: 0, signal: null }) + expect(await readFile(join(f.root, 'hardware-calls'), 'utf8')).toBe('call\n') + expect(await readFile(f.second, 'utf8')).toBe('signed:original') + expect(second.events).toContain('signature-cache-hit') +}) + +test('an interrupted holder releases only the stage lock and retains hardware failure evidence', async (t) => { + const f = await fixture(t) + const first = f.child(f.first) + await first.wait('entered') + const evidence = join(f.root, 'state/attempt.json') + await writeFile(evidence, 'retained hardware attempt') + first.process.kill() + await first.closed + await withWindowsSigningStage({ stateDirectory: join(f.root, 'state'), stage: 'inspect', record: () => {} }, async () => { + expect(await readFile(evidence, 'utf8')).toBe('retained hardware attempt') + }) +}) + +test('a failed stage releases its handle before another process enters', async (t) => { + const f = await fixture(t) + await expect(withWindowsSigningStage({ stateDirectory: join(f.root, 'state'), stage: 'failed', record: () => {} }, async () => { + throw new Error('stage failed') + })).rejects.toThrow('stage failed') + const next = f.child(f.first) + await next.wait('entered') + next.process.send('release') + expect(await next.closed).toEqual({ code: 0, signal: null }) +}) + +test('a cancelled waiter never enters and does not release another process lock', async (t) => { + const f = await fixture(t) + const holder = f.child(f.first) + await holder.wait('entered') + const controller = new AbortController() + let entered = false + await expect(withWindowsSigningStage({ stateDirectory: join(f.root, 'state'), stage: 'cancelled', signal: controller.signal, + record: (event) => { if ('type' in event && event.type === 'signing-stage-wait') controller.abort() }, + }, async () => { entered = true })).rejects.toThrow() + expect(entered).toBe(false) + holder.process.send('release') + expect(await holder.closed).toEqual({ code: 0, signal: null }) +}) + +test('cache clearing waits until another process finishes signing and publishing', async (t) => { + const f = await fixture(t) + const signer = f.child(f.first) + await signer.wait('entered') + const cleaner = f.child(f.second, 'clear') + await cleaner.wait('signing-stage-wait') + expect(cleaner.events).not.toContain('entered') + signer.process.send('release') + expect(await signer.closed).toEqual({ code: 0, signal: null }) + await cleaner.wait('entered') + cleaner.process.send('release') + expect(await cleaner.closed).toEqual({ code: 0, signal: null }) + expect(await readdir(join(f.root, 'cache'))).toEqual([]) + expect(await readFile(f.first, 'utf8')).toBe('signed:original') +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d28edf0ab4..76a5a131fb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -575,6 +575,9 @@ importers: js-yaml: specifier: ^4.2.0 version: 4.3.1 + koffi: + specifier: ^3.1.0 + version: 3.1.1 pnpm: specifier: 11.7.0 version: 11.7.0 From 7754a6fd49e306ca132c4f0eed892028a2f78e2a Mon Sep 17 00:00:00 2001 From: winewill <324803222+winewill@users.noreply.github.com> Date: Fri, 18 Sep 2026 11:58:57 +0800 Subject: [PATCH 08/10] test(desktop): isolate Windows cache path from host platform --- apps/desktop/tests/windows-sign.spec.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/desktop/tests/windows-sign.spec.ts b/apps/desktop/tests/windows-sign.spec.ts index 8af2036a5f..53113a2b36 100644 --- a/apps/desktop/tests/windows-sign.spec.ts +++ b/apps/desktop/tests/windows-sign.spec.ts @@ -163,6 +163,7 @@ describe('Windows token signing', () => { DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', DSH_DESKTOP_WINDOWS_CER_FILE: certificateFile, DSH_DESKTOP_WINDOWS_SIGNTOOL: signTool, DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'fixture-pin', DSH_DESKTOP_WINDOWS_KEY_CONTAINER: 'fixture-container', + DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: 'C:\\fixture\\signature-cache', }, { platform: 'win32', arch: 'x64' }) expect(execFile).not.toHaveBeenCalled() vi.mocked(execFile).mockImplementationOnce((...args: unknown[]) => { From 1a7308fbaa76cb07430df8ee0541294cccff7df8 Mon Sep 17 00:00:00 2001 From: winewill <324803222+winewill@users.noreply.github.com> Date: Fri, 18 Sep 2026 14:14:42 +0800 Subject: [PATCH 09/10] test(shell): synchronize background process completion --- .../shell/bash-local/tests/executor.spec.ts | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/shell/bash-local/tests/executor.spec.ts b/packages/shell/bash-local/tests/executor.spec.ts index 5edc656b1d..36ae874486 100644 --- a/packages/shell/bash-local/tests/executor.spec.ts +++ b/packages/shell/bash-local/tests/executor.spec.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync } from 'node:fs' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterAll, describe, expect, it, vi } from 'vitest' @@ -164,15 +164,25 @@ describe('LocalBashExecutor.run', () => { }) describe('LocalBashExecutor.start (background process handles)', () => { - it('start returns immediately with a running handle that settles as completed', async () => { + it('start returns a running handle before the child is allowed to finish', async (t) => { const { bash } = await setup() - const before = Date.now() - const proc = await bash.start(bash.resolve({ command: 'sleep 0.2; echo done' })) - expect(Date.now() - before).toBeLessThan(150) + const directory = mkdtempSync(join(spillDir, 'start-')) + const proc = await bash.start(bash.resolve({ + command: 'echo ready; while [ ! -f release ]; do sleep 0.02; done; echo done', + workdir: directory, + })) + t.onTestFinished(async () => { + proc.kill() + await proc.done + rmSync(directory, { recursive: true, force: true }) + }) + await readUntil(proc, 'ready\n') expect(proc.status).toBe('running') + writeFileSync(join(directory, 'release'), '') await proc.done expect(proc.status).toBe('completed') expect(proc.exitCode).toBe(0) + expect(proc.readOutput().delta).toBe('done\n') }) it('threads stdin and extra env into a background process', async () => { From 750bf4988ee39aecfba8f0eb043e622979dfdf13 Mon Sep 17 00:00:00 2001 From: winewill <324803222+winewill@users.noreply.github.com> Date: Fri, 18 Sep 2026 15:36:40 +0800 Subject: [PATCH 10/10] fix(desktop): initialize Windows cache under stage ownership --- ...26-09-17-windows-runtime-signature-cache.i18n.yaml | 4 ++-- .../2026-09-17-windows-runtime-signature-cache.md | 2 +- .../2026-09-17-windows-runtime-signature-cache.zh.md | 2 +- apps/desktop/README.i18n.yaml | 4 ++-- apps/desktop/README.md | 4 ++-- apps/desktop/README.zh.md | 4 ++-- apps/desktop/scripts/package-target.ts | 10 ++++++---- .../scripts/windows-signature-cache-directory.mjs | 2 +- apps/desktop/scripts/windows-signature-cache.d.mts | 2 +- apps/desktop/scripts/windows-signing-stage.mjs | 3 ++- apps/desktop/tests/package-target-stages.spec.ts | 11 +++++++++++ .../tests/windows-signature-cache-directory.spec.ts | 11 ++++++++++- apps/desktop/tests/windows-signing-stage.spec.ts | 9 +++++++++ 13 files changed, 50 insertions(+), 18 deletions(-) diff --git a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.i18n.yaml b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.i18n.yaml index b2cef5b014..b2f71a9f4d 100644 --- a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.i18n.yaml +++ b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.i18n.yaml @@ -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/process/2026-09-17-windows-runtime-signature-cache.md -2026-09-17-windows-runtime-signature-cache.md: 3182f46680fd862e123a54a7703b0b0dcad8fd79 -2026-09-17-windows-runtime-signature-cache.zh.md: 72b3599b28244d390a00ac5aa1eea0f5f8834c86 +2026-09-17-windows-runtime-signature-cache.md: 911e0277199bac55165fbc4adebb22e2599043b9 +2026-09-17-windows-runtime-signature-cache.zh.md: bb8cdd6bdca445c94e8e77cddb68008d7b27f7ad diff --git a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md index 3182f46680..911e027719 100644 --- a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md +++ b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.md @@ -38,7 +38,7 @@ The [primary-runtime decision](../feature/2026-09-14-desktop-primary-runtime.md) Repeated builds with unchanged native inputs avoid hardware calls for cached files while retaining preflight and final artifact signing. Changed content or signing policy misses the cache. Corrupt, incomplete, untrusted or incorrectly timestamped entries fail without replacing the target or retrying hardware. Concurrent publication and interrupted processes cannot expose incomplete entries or damage another build's files. -Six complete signed Windows x64 builds cover an empty signature cache, repeated inputs, application changes and one controlled native-file content change. Warm builds reduce hardware calls from 379 to 17 and elapsed time from 37:38 to 12:36–12:42 on the measured host, while final runtime checks pass. Download caches remain populated; the controlled file change tests invalidation, not a dependency-version upgrade. Installer execution and update qualification remain separate. +Complete signed Windows x64 builds on one host measure an empty shared cache and reuse from a separate fresh worktree: hardware calls fall from 379 to 17, elapsed time from 37:03 to 13:45, and all 362 runtime entries hit. Cache restoration takes 132 seconds, including 130 seconds of current trust verification. Both builds pass final runtime smoke and signed-artifact checks. Downloads are prepared before timing; each scenario is one complete run. A separate controlled native-file change produces miss/hit/miss with two hardware calls; it tests invalidation, not a dependency-version upgrade. Installer execution and update qualification remain separate. ## Risks diff --git a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md index 72b3599b28..bb8cdd6bdc 100644 --- a/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md +++ b/.agents/notes/implemented/process/2026-09-17-windows-runtime-signature-cache.zh.md @@ -38,7 +38,7 @@ Windows 打包每次都会重新生成未签名的原生依赖。为未变化的 原生输入未变化的重复构建不再为缓存覆盖的文件调用硬件签名,但仍执行预检和最终制品签名。内容或签名策略变化时缓存未命中。损坏、不完整、不可信或时间戳不合格的缓存项必须失败,不替换目标文件,也不重试硬件。并发发布和进程中断不能暴露不完整缓存项或损坏其他构建的文件。 -六轮完整 Windows x64 签名构建覆盖空签名缓存、重复输入、应用变化和单个原生文件的受控内容变化。在测量主机上,热构建将硬件调用从 379 次降至 17 次,耗时从 37:38 降至 12:36–12:42,且最终运行时检查通过。下载缓存保持已填充;受控文件变化验证缓存失效,不代表依赖版本升级。安装器执行和更新验收仍需单独进行。 +同一主机上的完整 Windows x64 签名构建测量空共享缓存与另一个全新 worktree 的复用:硬件调用从 379 次降至 17 次,耗时从 37:03 降至 13:45,362 个运行时缓存项全部命中。缓存恢复耗时 132 秒,其中当前信任验证占 130 秒。两轮均通过最终运行时 smoke 及签名产物检查。下载内容在计时前准备好;每种场景均为一次完整运行。另一次受控原生文件变更产生未命中、命中、未命中的结果,合计两次硬件调用;它验证缓存失效,不代表依赖版本升级。安装器执行和更新验收仍需单独进行。 ## Risks diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 364ccfffd7..191e1afaf1 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -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 apps/desktop/README.md -README.md: 9a20ec4b919c31f9d3427181ae984c30206aed19 -README.zh.md: a5b876ab97c108db51ebbcea45a78322234ffaa0 +README.md: 5de3550de473cb71704025e1d60057611b15987c +README.zh.md: 057094c80e1197e0216f660ea788dabc0d436573 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 9a20ec4b91..5de3550de4 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -214,9 +214,9 @@ Runtime signing shares complete signed files across the current Windows account' Preflight, primary-runtime signing, application-runtime signing and artifact creation each hold the account's signing-stage lock until their supervised child processes settle. Other builds wait before entering those stages; compilation and preparation do not hold the lock. Runtime signing workers own their locks, so terminating only the outer packaging process does not unlock a surviving cache user. Migration and maintenance acquire the same lock; older or external signing commands do not participate and must be scheduled separately. Stage waiting is outside the preflight deadline. Closing the stage handle releases ordinary contention without removing the separate hardware-attempt interlock; a retained hardware failure still requires operator recovery. -Each runtime stage writes `SIGNATURE_CACHE_SUMMARY` to stdout and its packaging journal, including the actual directory, policy identity, hit/miss counts, newly published and retained entries, signing requests, avoided signing requests and validation failures. Timings distinguish signing, cache trust verification and restoration; restoration includes its trust check and staging cleanup. These counters exclude preflight, final artifact signing and the outer runtime signature checks. Stage lock events record waiting separately. +Each runtime stage writes `SIGNATURE_CACHE_SUMMARY` to stdout and its packaging journal, including the actual directory, policy identity, hit/miss counts, newly published and retained entries, signing requests, avoided signing requests and validation failures. Timings distinguish signing, trust verification of restored and newly signed files, and restoration; restoration includes its trust check and staging cleanup. These counters exclude preflight, final artifact signing and the outer runtime signature checks. Stage lock events record waiting separately. -Use `pnpm --dir apps/desktop run cache:windows-signatures --usage` to inspect complete-entry bytes and counts, or `--from ` to import an explicitly selected cache owned by the same account. Migration leaves the source unchanged, skips staging names, rejects corrupt entries and retains valid existing entries even when their timestamp bytes differ. `--clear` explicitly removes complete entries under the stage lock; no automatic capacity eviction runs. `--directory ` selects a maintenance destination without loading release credentials. Incomplete staging entries remain untouched and are counted separately; inspect them only after all builds have stopped. These commands never clear hardware failure evidence. Default storage is outside AppData so MSIX launcher virtualization does not split the account's cache; redirected overrides fail explicitly. +Use `pnpm --dir apps/desktop run cache:windows-signatures --usage` to inspect structurally complete-entry bytes and counts, or `--from ` to import an explicitly selected cache owned by the same account. Migration leaves the source unchanged, skips staging names, rejects corrupt entries and retains valid existing entries even when their timestamp bytes differ. `--clear` explicitly removes complete entries under the stage lock; no automatic capacity eviction runs. `--directory ` selects a maintenance destination without loading release credentials. Incomplete staging entries remain untouched and are counted separately; inspect them only after all builds have stopped. These commands never clear hardware failure evidence. Default storage is outside AppData so MSIX launcher virtualization does not split the account's cache; redirected overrides fail explicitly. Signed Windows builds run a supervised signing preflight before compilation or dependency preparation. Static configuration, certificate validity, audit storage, compiler availability and any retained signing interlock are checked without token access. The local .NET Framework C# compiler creates a small private probe; the production signer signs it once, and verification requires the configured certificate and a timestamp before building continues. The probe is never executed. The overall 60-second preflight deadline includes timestamp attempts; deadline expiry, hardware signing errors and verification failures stop the run without another hardware attempt. Success proves the current signing path works, not that the PIN was independently authenticated: SafeNet may reuse login state. Do not log out or repeat authentication to test the PIN. `--check`, preparation-only and `--unsigned` modes do not run this hardware preflight; unsigned artifacts remain ineligible for release upload. Automated regression tests use a fake signer; release operators qualify real hardware separately. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index a5b876ab97..057094c80e 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -215,9 +215,9 @@ Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI 预检、主要运行时签名、应用运行时签名和产物生成分别持有账户级签名阶段锁,直到受监督的子进程结束。其他构建进入这些阶段前等待;编译和准备步骤不持锁。运行时签名进程自行持锁,因此仅终止外层打包进程不会释放仍在访问缓存的阶段锁。迁移及维护获取同一把锁;旧版或外部签名命令不参与排队,应另行避免并发。阶段等待不计入预检期限。关闭阶段句柄会释放普通竞争锁,不删除独立的硬件尝试互锁;遗留硬件失败仍需操作人员恢复。 -每个运行时阶段向标准输出及打包日志写入 `SIGNATURE_CACHE_SUMMARY`,包含实际目录、策略标识、命中及未命中数、新发布及保留项数、签名请求数、省去的签名请求数和验证失败数。计时区分签名、缓存信任验证及恢复;恢复耗时包含其信任检查和暂存清理。这些统计不包含预检、最终产物签名及外层运行时验签。阶段锁事件单独记录等待时间。 +每个运行时阶段向标准输出及打包日志写入 `SIGNATURE_CACHE_SUMMARY`,包含实际目录、策略标识、命中及未命中数、新发布及保留项数、签名请求数、省去的签名请求数和验证失败数。计时区分签名、恢复文件和新签名文件的信任验证及恢复;恢复耗时包含其信任检查和暂存清理。这些统计不包含预检、最终产物签名及外层运行时验签。阶段锁事件单独记录等待时间。 -使用 `pnpm --dir apps/desktop run cache:windows-signatures --usage` 查看完整缓存项的字节数和数量,或用 `--from ` 导入显式指定、属于同账户的旧缓存。迁移不修改源目录,跳过暂存名称,拒绝损坏项,并保留已有有效项,即使它们的时间戳字节不同。`--clear` 在阶段锁保护下显式删除完整缓存项;不执行自动容量淘汰。`--directory ` 指定维护目标目录,无需加载发布凭据。不完整暂存项保持原状并单独计数;仅在所有构建停止后检查它们。这些命令绝不清除硬件失败证据。默认存储位于 AppData 之外,避免 MSIX 启动器虚拟化将账户缓存拆开;被重定向的覆盖目录会明确失败。 +使用 `pnpm --dir apps/desktop run cache:windows-signatures --usage` 查看结构完整的缓存项字节数和数量,或用 `--from ` 导入显式指定、属于同账户的旧缓存。迁移不修改源目录,跳过暂存名称,拒绝损坏项,并保留已有有效项,即使它们的时间戳字节不同。`--clear` 在阶段锁保护下显式删除完整缓存项;不执行自动容量淘汰。`--directory ` 指定维护目标目录,无需加载发布凭据。不完整暂存项保持原状并单独计数;仅在所有构建停止后检查它们。这些命令绝不清除硬件失败证据。默认存储位于 AppData 之外,避免 MSIX 启动器虚拟化将账户缓存拆开;被重定向的覆盖目录会明确失败。 Windows 签名构建在编译或准备依赖前执行受监督的签名预检。静态配置、证书有效期、审计存储、编译器可用性及遗留签名锁的检查不访问 Token。本地 .NET Framework C# 编译器生成一个专用小探针,由正式签名器仅签名一次,随后必须验出配置的证书和时间戳才能继续构建。探针绝不执行。预检的整体 60 秒期限包含时间戳尝试;超时、硬件签名报错或验签失败都会停止本轮流程,不再次调用硬件。成功只证明当前签名路径可用,不证明 PIN 已独立认证:SafeNet 可能复用登录状态。不要为了验证 PIN 而注销或重复认证。`--check`、仅准备和 `--unsigned` 模式不执行此硬件预检;未签名产物仍不能发布上传。自动回归测试使用假签名器,真实硬件由发布操作人员单独验收。 diff --git a/apps/desktop/scripts/package-target.ts b/apps/desktop/scripts/package-target.ts index cff4df6006..6988a4edac 100644 --- a/apps/desktop/scripts/package-target.ts +++ b/apps/desktop/scripts/package-target.ts @@ -356,10 +356,12 @@ export async function packageTarget( } if (signPrimaryRuntime) { if (run === undefined) throw new Error('desktop package: signed Windows packaging requires a supervised run') - await prepareWindowsSignatureCacheDirectory(resolveWindowsSignatureCacheDirectory(environment)) - await signedStage('preflight', () => run.run('preflight:windows-signing', process.execPath, - ['--import', 'tsx/esm', join(APP_ROOT, 'scripts/windows-signing-preflight.ts')], - { cwd: APP_ROOT, env: electronBuilderEnv, timeoutMs: 60_000 })) + await signedStage('preflight', async () => { + await prepareWindowsSignatureCacheDirectory(resolveWindowsSignatureCacheDirectory(environment)) + await run.run('preflight:windows-signing', process.execPath, + ['--import', 'tsx/esm', join(APP_ROOT, 'scripts/windows-signing-preflight.ts')], + { cwd: APP_ROOT, env: electronBuilderEnv, timeoutMs: 60_000 }) + }) } await execute(['run', 'build:official'], buildEnv, REPOSITORY_ROOT) await execute(['run', 'release:pack', '--family', 'dsh', '--out', buildPaths.packedDsh], buildEnv, REPOSITORY_ROOT) diff --git a/apps/desktop/scripts/windows-signature-cache-directory.mjs b/apps/desktop/scripts/windows-signature-cache-directory.mjs index 3d4a30b880..69b2064672 100644 --- a/apps/desktop/scripts/windows-signature-cache-directory.mjs +++ b/apps/desktop/scripts/windows-signature-cache-directory.mjs @@ -28,7 +28,7 @@ export function resolveWindowsSignatureCacheDirectory(environment) { */ export async function prepareWindowsSignatureCacheDirectory(path, existingSource = false) { if (process.platform !== 'win32') throw new Error('Windows signature cache directory validation requires Windows') - await promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-File', + await promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', join(import.meta.dirname, 'windows-signature-cache-directory.ps1'), '-CachePath', resolve(path), ...(existingSource ? ['-ExistingSource'] : []), ], { env: scrubWindowsSigningEnvironment(process.env), windowsHide: true, timeout: 60_000 }) diff --git a/apps/desktop/scripts/windows-signature-cache.d.mts b/apps/desktop/scripts/windows-signature-cache.d.mts index 4c90d5bd8a..e68abdf345 100644 --- a/apps/desktop/scripts/windows-signature-cache.d.mts +++ b/apps/desktop/scripts/windows-signature-cache.d.mts @@ -18,7 +18,7 @@ export interface WindowsSignatureCacheOptions { */ export function signatureCacheIdentity(files: readonly string[]): Promise -/** Counters include failed attempts; restore time includes trust verification and staging cleanup. */ +/** Counters include failed attempts; verification covers both restored and newly signed files, while restore time includes its verification and staging cleanup. */ export interface WindowsSignatureCacheSummary { root: string identity: string diff --git a/apps/desktop/scripts/windows-signing-stage.mjs b/apps/desktop/scripts/windows-signing-stage.mjs index 65e0043fac..d81ef8bdc3 100644 --- a/apps/desktop/scripts/windows-signing-stage.mjs +++ b/apps/desktop/scripts/windows-signing-stage.mjs @@ -30,7 +30,8 @@ export async function withWindowsSigningStage(options, operation) { const root = options.stateDirectory ?? join(homedir(), '.dsh-desktop-signing') await mkdir(root, { recursive: true }) const stat = await lstat(root) - if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(root) !== resolve(root)) { + const normalize = value => toNamespacedPath(resolve(value)).toLowerCase() + if (!stat.isDirectory() || stat.isSymbolicLink() || normalize(await realpath(root)) !== normalize(root)) { throw new Error('Windows signing stage requires an unlinked local state directory') } const path = join(root, 'stage.lock') diff --git a/apps/desktop/tests/package-target-stages.spec.ts b/apps/desktop/tests/package-target-stages.spec.ts index e74bedc215..bdf636ef57 100644 --- a/apps/desktop/tests/package-target-stages.spec.ts +++ b/apps/desktop/tests/package-target-stages.spec.ts @@ -2,6 +2,7 @@ import { writeFileSync } from 'node:fs' import { afterEach, expect, it, vi } from 'vitest' import { packageTarget, parseDesktopPackageInvocation } from '../scripts/package-target.ts' import { withWindowsSigningStage } from '../scripts/windows-signing-stage.mjs' +import { prepareWindowsSignatureCacheDirectory } from '../scripts/windows-signature-cache-directory.mjs' vi.mock('../scripts/windows-signing-stage.mjs', () => ({ withWindowsSigningStage: vi.fn(async (_options: object, operation: () => Promise) => operation()), @@ -52,6 +53,16 @@ it('requires one signing preflight before building, then records only the comple expect(writeFileSync).toHaveBeenCalledOnce() }) +it('initializes shared storage only after acquiring the preflight stage lock', async () => { + const { run } = supervisor() + vi.mocked(withWindowsSigningStage).mockImplementationOnce(async (_options, operation) => { + expect(prepareWindowsSignatureCacheDirectory).not.toHaveBeenCalled() + await operation() + expect(prepareWindowsSignatureCacheDirectory).toHaveBeenCalledOnce() + }) + await packageTarget(parseDesktopPackageInvocation(['win-x64'], 'win32', 'x64'), environment, run) +}) + it.each(['preflight:windows-signing', 'run build:official', 'run sign:primary-runtime', 'run prepare:dsh --defer-runtime-smoke', 'run sign:primary-runtime --dsh', 'exec tsx scripts/smoke-packaged-runtime.ts', 'exec electron-builder --config electron-builder.config.mjs --win --x64 --publish never']) diff --git a/apps/desktop/tests/windows-signature-cache-directory.spec.ts b/apps/desktop/tests/windows-signature-cache-directory.spec.ts index f5ffe76e44..d910624f18 100644 --- a/apps/desktop/tests/windows-signature-cache-directory.spec.ts +++ b/apps/desktop/tests/windows-signature-cache-directory.spec.ts @@ -3,7 +3,7 @@ import { mkdtemp, rm, symlink } from 'node:fs/promises' import { join } from 'node:path' import { homedir } from 'node:os' import { promisify } from 'node:util' -import { expect, it } from 'vitest' +import { expect, it, vi } from 'vitest' import { prepareWindowsSignatureCacheDirectory, resolveWindowsSignatureCacheDirectory } from '../scripts/windows-signature-cache-directory.mjs' it.skipIf(process.platform !== 'win32')('resolves an account cache independently of checkout and LocalAppData virtualization', () => { @@ -16,6 +16,15 @@ it('accepts an explicit local cache directory', () => { .toBe('D:\\private-cache') }) +it.skipIf(process.platform !== 'win32')('prepares storage when the inherited process execution policy is Restricted', async (t) => { + const root = await mkdtemp(join(import.meta.dirname, 'directory-test-')) + t.onTestFinished(() => rm(root, { recursive: true, force: true })) + vi.stubEnv('PSExecutionPolicyPreference', 'Restricted') + t.onTestFinished(() => { vi.unstubAllEnvs() }) + await prepareWindowsSignatureCacheDirectory(join(root, 'private')) + expect(process.env.PSExecutionPolicyPreference).toBe('Restricted') +}) + it.each(['', 'cache', 'C:cache', '\\cache', '\\\\server\\share', '\\\\?\\C:\\cache', 'C:\\cache:stream']) ('rejects unsupported cache path %j', (path) => { expect(() => resolveWindowsSignatureCacheDirectory({ DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: path })).toThrow(/absolute local/u) diff --git a/apps/desktop/tests/windows-signing-stage.spec.ts b/apps/desktop/tests/windows-signing-stage.spec.ts index 5c1e1b1865..a205681781 100644 --- a/apps/desktop/tests/windows-signing-stage.spec.ts +++ b/apps/desktop/tests/windows-signing-stage.spec.ts @@ -94,6 +94,15 @@ test('a failed stage releases its handle before another process enters', async ( expect(await next.closed).toEqual({ code: 0, signal: null }) }) +test('accepts a state directory whose spelling differs only in Windows path case', async (t) => { + const f = await fixture(t) + let entered = false + await withWindowsSigningStage({ stateDirectory: join(f.root, 'state').toUpperCase(), stage: 'case', record: () => {} }, async () => { + entered = true + }) + expect(entered).toBe(true) +}) + test('a cancelled waiter never enters and does not release another process lock', async (t) => { const f = await fixture(t) const holder = f.child(f.first)