From f92f984d3dad43ae138a4c2b0b5ef2733d97fb11 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 16 Sep 2026 19:48:48 +0800 Subject: [PATCH 01/45] docs(notes): propose one card per delivered changed file --- ...09-16-delivered-file-single-card.i18n.yaml | 6 +++ .../2026-09-16-delivered-file-single-card.md | 41 +++++++++++++++++++ ...026-09-16-delivered-file-single-card.zh.md | 41 +++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 .agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.i18n.yaml create mode 100644 .agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.md create mode 100644 .agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.zh.md diff --git a/.agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.i18n.yaml b/.agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.i18n.yaml new file mode 100644 index 0000000000..cc205c7391 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.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/proposed/feature/2026-09-16-delivered-file-single-card.md +2026-09-16-delivered-file-single-card.md: 65edb58a97a3c67550df37a4172863faa9d2eae4 +2026-09-16-delivered-file-single-card.zh.md: c21857071184fc3a5f4d97eb524606f465c82ae1 diff --git a/.agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.md b/.agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.md new file mode 100644 index 0000000000..65edb58a97 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.md @@ -0,0 +1,41 @@ +# Agent Note: One card per delivered changed file + +Status: proposed + +English | [中文](2026-09-16-delivered-file-single-card.zh.md) + +## Problem + +A finished turn ends with two file surfaces: the [changed-files card](../../implemented/feature/2026-09-11-turn-changed-files-card.md) lists every file the turn changed with its line counts and opens the [review tab](../../implemented/feature/2026-09-15-changed-file-diff-preview.md) on that file, and a delivery card for every file the model declared through [present](../../implemented/feature/2026-09-08-present-workspace-source-files.md) previews it in the Sidebar and opens it natively. A file the turn both changed and delivered appears in both, and the second appearance tells the user nothing new; the recorded `changed-files-turn` scenario shows four files as four rows and four cards. + +The two surfaces differ in what they offer and how long they live. The row carries counts and the comparison; the card carries the model's description, the preview, and the native actions. The card's content lives only in the Host process, so a conversation reopened after a Host restart has no changed-files card, while `deliverables/presented` events persist in the Session log and their cards come back. + +## Proposal + +Render a file the turn both changed and delivered once, on its delivery card. The changed-files card drops that file's row and keeps its header, which still names the turn's complete file count and summed counts and still opens the review on the turn; when every changed file was delivered only the header remains. The delivery card gains the file's added and deleted lines, or its binary or oversized label, beside the file name, and that label opens the review tab on the file, so the comparison, the preview, the native actions, and the description stay available from one place. Files only changed or only delivered render as before, and turns never share data. + +Matching is lexical, on the Client, at render time: separators normalized to `/`, `.` segments dropped, `..` folded, and an absolute path under the Session working directory stated relative to it. Repeated deliveries of one file in a turn merge under the same key, keeping the latest description. Two spellings that meet only through a symbolic link stay distinct. + +Nothing durable changes: no Session event, no Host route, and no recorder change; the merge lives in `packages/client/ui-deliverables` beside the card derivation. After a Host restart the changed-files card is absent and the delivery cards render as today, without a special case. + +## Alternatives considered + +**Keeping the row and dropping the card** costs less code, but turns a deliverable's default entry from the preview into the comparison: a report or SVG becomes one diff row, and a binary deliverable becomes a `binary` label with no preview at all. + +**Asking the model not to `present` files the changed-files card will list** cannot work: the `workspace/changes` event is never model-visible and its coverage depends on git, ignore rules, the file cap, and temporary-directory exclusion; `present` is shared by the `standard`, `ptc`, and `cordis` presets whose headless and SDK consumers have no changed-files card; and after a Host restart an undelivered file has no entry at all. The tool description also requires delivering every requested output, which the [delivery decision](../../implemented/feature/2026-09-08-present-workspace-source-files.md) settled. + +**One combined card** that lists every changed file with delivery actions on the delivered rows would merge two surfaces with different lifetimes into one and reopen the card design; the proposal keeps both surfaces and moves only the duplicate. + +## Acceptance criteria + +- A file both changed and delivered in one turn renders one delivery card and no changed-files row; the header count and totals still cover it. +- The delivery card shows the file's counts, and that label opens the turn's review tab on the file; preview, native actions, and the description remain. +- Repeated deliveries of one file in a turn render one card; files with the same basename in different directories render separately. +- Reloading the page renders the same result as the first render; after a Host restart the delivery cards render without the changed-files card. +- The `changed-files-turn` and `present-svg` recorded scenarios and the package unit tests cover the merge. + +## Risks + +- A delivery spelled through a symbolic link, or with an absolute path outside the working directory that the recorder spelled differently, is not matched and renders twice; the README lists this as a known limitation. +- A changed-files card reduced to its header may read as incomplete; the header keeps the complete count so the review still lists every file. +- The counts label on a 60px delivery card competes for space with long file names; the design of that label is open until a design is agreed. diff --git a/.agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.zh.md b/.agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.zh.md new file mode 100644 index 0000000000..c218570711 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-09-16-delivered-file-single-card.zh.md @@ -0,0 +1,41 @@ +# Agent Note: 交付的改动文件只显示一张卡片 + +Status: proposed + +[English](2026-09-16-delivered-file-single-card.md) | 中文 + +## 问题 + +一轮结束时有两个文件区块:[改动文件卡片](../../implemented/feature/2026-09-11-turn-changed-files-card.zh.md)列出本轮改动的每个文件及其增删行数,并在该文件上打开 [review tab](../../implemented/feature/2026-09-15-changed-file-diff-preview.zh.md);模型通过 [present](../../implemented/feature/2026-09-08-present-workspace-source-files.zh.md) 声明的每个文件有一张交付卡片,在 Sidebar 中预览并用原生应用打开。本轮既改动又交付的文件在两处都出现,第二次出现没有给用户任何新信息;录制的 `changed-files-turn` 场景里四个文件显示为四行加四张卡片。 + +两个区块提供的东西和寿命都不同。行有行数和对比;卡片有模型写的说明、预览和原生操作。卡片的内容只活在 Host 进程里,Host 重启后重新打开的会话没有改动文件卡片,而 `deliverables/presented` 事件持久化在 Session log 里,它们的卡片会回来。 + +## 提议 + +本轮既改动又交付的文件只显示一次,显示在交付卡片上。改动文件卡片去掉该文件的行,保留头部;头部仍写本轮完整的文件数和汇总行数,仍在本轮上打开 review;所有改动文件都被交付时只剩头部。交付卡片在文件名旁补上该文件的增删行数,或二进制、过大标签,点击该标签在该文件上打开 review tab,这样对比、预览、原生操作和说明都从同一处可达。只改动或只交付的文件照旧显示,不同轮次之间不共享数据。 + +匹配在 Client 渲染时按词法进行:分隔符统一为 `/`,去掉 `.` 段,折叠 `..`,落在 Session 工作目录下的绝对路径改写为相对路径。同一轮内重复交付同一文件按同一个键合并,保留最新的说明。只经软链才相同的两种拼写保持不同。 + +持久化的东西都不变:没有新的 Session 事件、没有 Host 路由、recorder 不改;合并逻辑放在 `packages/client/ui-deliverables` 里卡片推导的旁边。Host 重启后改动文件卡片不存在,交付卡片按现在的方式渲染,不需要特殊处理。 + +## 考虑过的替代方案 + +**保留行、去掉卡片**代码更少,但交付物的默认入口从预览变成对比:一份报告或 SVG 变成一行 diff,二进制交付物变成一个「二进制」标签,完全没有预览。 + +**让模型不要 `present` 改动文件卡片会列出的文件**行不通:`workspace/changes` 事件从不进模型上下文,它的覆盖范围取决于 git、ignore 规则、文件数上限和临时目录排除;`present` 由 `standard`、`ptc`、`cordis` 三个 preset 共用,它们的 headless 和 SDK 消费者没有改动文件卡片;Host 重启后没交付的文件就没有任何入口。工具描述也要求交付用户要的每个产出,这是[交付决定](../../implemented/feature/2026-09-08-present-workspace-source-files.zh.md)定下的。 + +**一张合并卡片**,列出每个改动文件并在被交付的行上放交付操作,会把两个寿命不同的区块并成一个,并重开卡片设计;本提议保留两个区块,只挪走重复的那份。 + +## 验收标准 + +- 同一轮既改动又交付的文件只显示一张交付卡片,没有改动文件行;头部的数量和汇总仍包含它。 +- 交付卡片显示该文件的行数,点击该标签在该文件上打开本轮的 review tab;预览、原生操作和说明都保留。 +- 同一轮重复交付同一文件只显示一张卡片;不同目录下同名的文件分别显示。 +- 重新加载页面后的渲染结果与首次一致;Host 重启后交付卡片照常渲染,没有改动文件卡片。 +- `changed-files-turn` 和 `present-svg` 录制场景以及本包单测覆盖这次合并。 + +## 风险 + +- 经软链拼写的交付,或 recorder 拼法不同的工作目录外绝对路径,不会被匹配到,仍显示两次;README 把它列为已知限制。 +- 只剩头部的改动文件卡片可能显得不完整;头部保留完整数量,review 仍列出每个文件。 +- 60px 高的交付卡片上,行数标签会和长文件名争空间;该标签的样式在设计定下之前保持开放。 From a4493ceb39a9e2619837876adb14f33e432fe3da Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 16 Sep 2026 20:12:32 +0800 Subject: [PATCH 02/45] 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 dcf2b678963e451d8d7ef75ba1d7cad1a58ac1c4 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 16 Sep 2026 21:00:57 +0800 Subject: [PATCH 03/45] feat(web): open Sidebar-previewed files in the default application The document preview declares two child slots handing the previewed file and its Host path to other plugins: the header actions after its own controls, and the empty state of a file it cannot render, where Retry stood. Empty-state read failures now name their recourse: not-text and too-large offer the handoff, not-found and non-regular paths offer nothing, and the rest keep Retry. The unsupported-suffix empty state offers the same seat. ui-open-in-app fills both seats with an "Open" split button (default application, or the file manager reveal from its menu) and an empty-state "Open in default app" button. Both call the Session Remote the Host already publishes: canOpenWorkspacePath once per page decides whether they render, openWorkspacePath runs each gesture. Only the pressed control disables while its gesture settles; a failure announces once through a transient toast. The delivery cards keep their own opener this iteration. The design, slot pair, failure classification, and toast rule come from Yifffan's PR #4120. --- ...in-default-app-for-sidebar-files.i18n.yaml | 6 + ...6-open-in-default-app-for-sidebar-files.md | 29 ++++ ...pen-in-default-app-for-sidebar-files.zh.md | 29 ++++ apps/web/tests/document-preview.e2e.ts | 67 ++++++++- .../tests/fixtures/native-open-on.patch.yml | 4 + apps/web/tests/seeded-history.e2e.ts | 16 ++- apps/web/tests/seeded-history.overlay.yml | 17 +++ packages/client/README.i18n.yaml | 4 +- packages/client/README.md | 2 +- packages/client/README.zh.md | 2 +- .../client/ui-open-in-app/README.i18n.yaml | 4 +- packages/client/ui-open-in-app/README.md | 22 ++- packages/client/ui-open-in-app/README.zh.md | 22 ++- packages/client/ui-open-in-app/package.json | 11 +- .../src/client/OpenPathAction.module.css | 62 ++++++++ .../src/client/OpenPathAction.tsx | 132 ++++++++++++++++++ .../src/client/OpenPathEmptyAction.module.css | 27 ++++ .../src/client/OpenPathEmptyAction.tsx | 40 ++++++ .../client/ui-open-in-app/src/client/index.ts | 44 +++++- .../ui-open-in-app/src/client/locales.ts | 18 ++- .../src/client/open-failure-toast.tsx | 25 ++++ .../ui-open-in-app/src/client/open-path.ts | 75 ++++++++++ .../tests/browser-plugin.client.spec.ts | 48 ++++++- .../tests/open-path-action.client.spec.tsx | 132 ++++++++++++++++++ .../tests/open-path.client.spec.ts | 71 ++++++++++ packages/client/ui-open-in-app/tsconfig.json | 9 ++ .../README.i18n.yaml | 4 +- .../ui-sidebar-documentpreview/README.md | 8 +- .../ui-sidebar-documentpreview/README.zh.md | 8 +- .../src/client/TextPreview.tsx | 44 ++++-- .../src/client/document/contract.ts | 29 ++++ .../src/client/failure-line.ts | 22 +++ .../src/client/index.ts | 2 + .../tests/document-toolbar.client.spec.tsx | 18 ++- .../tests/failure-line.client.spec.ts | 19 ++- .../tests/fixtures.client.ts | 15 +- .../tests/text-preview.client.spec.tsx | 56 ++++++-- .../src/client/slot-catalog.ts | 120 +++++++++++++++- pnpm-lock.yaml | 9 ++ .../web/document-preview/document.expected.md | 2 + .../web/document-preview/paging.patch.yml | 4 + .../seeded-history/file-preview.expected.md | 3 + 42 files changed, 1194 insertions(+), 87 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.md create mode 100644 .agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.zh.md create mode 100644 apps/web/tests/fixtures/native-open-on.patch.yml create mode 100644 apps/web/tests/seeded-history.overlay.yml create mode 100644 packages/client/ui-open-in-app/src/client/OpenPathAction.module.css create mode 100644 packages/client/ui-open-in-app/src/client/OpenPathAction.tsx create mode 100644 packages/client/ui-open-in-app/src/client/OpenPathEmptyAction.module.css create mode 100644 packages/client/ui-open-in-app/src/client/OpenPathEmptyAction.tsx create mode 100644 packages/client/ui-open-in-app/src/client/open-failure-toast.tsx create mode 100644 packages/client/ui-open-in-app/src/client/open-path.ts create mode 100644 packages/client/ui-open-in-app/tests/open-path-action.client.spec.tsx create mode 100644 packages/client/ui-open-in-app/tests/open-path.client.spec.ts diff --git a/.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.i18n.yaml b/.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.i18n.yaml new file mode 100644 index 0000000000..e49b11bebd --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.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-open-in-default-app-for-sidebar-files.md +2026-09-16-open-in-default-app-for-sidebar-files.md: c66d79618bea5c8bc190f50141169aea3090d833 +2026-09-16-open-in-default-app-for-sidebar-files.zh.md: 3a22f9abcc5f0c19af59efdf0be48b50facb2e40 diff --git a/.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.md b/.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.md new file mode 100644 index 0000000000..c66d79618b --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.md @@ -0,0 +1,29 @@ +# Agent Note: Open Sidebar-previewed files in the default application + +Status: implemented + +English | [中文](2026-09-16-open-in-default-app-for-sidebar-files.zh.md) + +## Problem + +Opening a file in its Host default application or showing it in the file manager existed only on the delivery cards, through routes and a fetch controller private to `ui-deliverables` and addressed by Session, declaration-event sequence, and file index. The right Sidebar's document preview offered no native handoff: a video, an archive, an office document, a file the reader rejected as non-text, or an oversized file dead-ended on an explanation, with Retry as the only control even where a second read could not help (issue #3932). Those files have no delivery event to address, so the existing plumbing could not serve a second surface. A first implementation (PR #4120, by Yifffan) added a new `ui-open-locally` package with its own Host routes and moved the delivery cards onto it; product review asked instead that file opening live in the existing open-in-app feature and accepted an intermediate state for this iteration. + +## Decision + +[ui-open-in-app](../../../../packages/client/ui-open-in-app/README.md) owns the browser controls. The document preview of [ui-sidebar-documentpreview](../../../../packages/client/ui-sidebar-documentpreview/README.md) declares two Session-scoped list child slots whose owner props carry the previewed file and its absolute Host path, rendered only once the file's metadata reports that path: `sidebar.right.tab.document.actions` after the header's own controls, in every state that shows the header, and `sidebar.right.tab.document.unpreviewable` where Retry would stand. The preview classifies an empty-state read failure: `not-text` and `too-large` are readable files the preview cannot render and offer the unpreviewable slot; `not-found` and `not-regular-file` offer only their explanation; every other failure keeps Retry because a second read may resolve it. The unsupported-suffix empty state, which never reads, offers the same slot. + +ui-open-in-app fills both slots: an "Open ▾" split button whose main button opens the file in the default application and whose menu adds the file-manager reveal, and an "Open in default app" empty-state button. Neither control renders until the Host answered that a desktop exists. The controls call the Session Remote the Host already publishes, `session.canOpenWorkspacePath` once per page and `session.openWorkspacePath` per gesture with the absolute path and, for reveal, `action: 'reveal'`; no new Host route exists. Both controls share one gesture hook: only the control the user pressed disables while its call settles, a failed call resolves as a failure kind, and that control announces it once through a transient toast, so no failure state persists on a control. + +## Alternatives considered + +**A new `ui-open-locally` package with its own Host routes** (PR #4120) is where the slot pair, the failure classification, the split-button design, and the toast rule come from. It was set aside because the repository already has an open-in-app feature and a second package for opening things locally duplicates it; the routes it added re-verified through the Session filesystem what `openWorkspacePath` already accepts from any authenticated client. + +**Host routes in `dsh-host-open-in-app`** serving desktop facts and a path open would let the Host name the file manager and distinguish a missing file from a failed launch. They would make the Host half depend on `sessionController`, `workspaceFiles`, and `fs` for two calls the Session Remote already publishes, so the Remote is used directly and the reveal label stays generic. + +**Moving the delivery cards onto these controls now** would repeat the largest part of PR #4120, including the cross-plugin runtime import its review rejected and the recorded delivery scenarios it had to migrate. The cards keep their own routes this iteration. + +## Consequences + +Every previewed file with a Host path can be opened locally from the Sidebar, including files that were never delivered. The delivery cards and the preview run two openers over one Host capability; unifying them, and deciding per surface between the full application list and the default application only, is the next step the product direction names. The reveal menu item says "Show file location" on every platform because the Session Remote reports no file manager. Default-application open carries the Host's file-association execution semantics for what it opens; the guard is the explicit user gesture on a file the Session can already read, and no new Host authority was granted. + +Unit tests cover the failure classification, the preview's rendering of each recourse and its withholding of the seats before a Host path is known, the path controller's desktop read and gesture outcomes, both controls' visibility, busy isolation, and toast, and the plugin's registration and fiber-disposal removal. The keyless Web document-preview scenario drives the unsupported-suffix controls against a stubbed opener on POSIX hosts, and the seeded-history file-preview golden pins the header control. diff --git a/.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.zh.md b/.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.zh.md new file mode 100644 index 0000000000..3a22f9abcc --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.zh.md @@ -0,0 +1,29 @@ +# Agent Note:用默认应用打开 Sidebar 预览的文件 + +Status: implemented + +[English](2026-09-16-open-in-default-app-for-sidebar-files.md) | 中文 + +## 问题 + +用 Host 默认应用打开文件、或在文件管理器中显示文件,此前只存在于交付卡片上,走的是 `ui-deliverables` 私有的路由与 fetch 控制器,按 Session、声明事件序号和文件下标定位。右侧 Sidebar 的文档预览没有任何本地交接:视频、压缩包、office 文档、被读取器判为非文本的文件、过大的文件,都停在一行说明上,唯一的控件是重试,哪怕再读一次也无济于事(issue #3932)。这些文件没有交付事件可供定位,所以现有管线无法服务第二个界面。第一版实现(PR #4120,作者 Yifffan)新增了 `ui-open-locally` 包,自带 Host 路由,并把交付卡片也迁了过去;产品评审要求改为把文件打开放进现有的 open-in-app 功能,并接受本期先落一个中间态。 + +## 决定 + +[ui-open-in-app](../../../../packages/client/ui-open-in-app/README.zh.md) 拥有浏览器侧的控件。[ui-sidebar-documentpreview](../../../../packages/client/ui-sidebar-documentpreview/README.zh.md) 的文档预览声明两个 Session 作用域的 list 子 slot,owner props 携带当前文件及其 Host 绝对路径,只在文件元数据报出该路径后渲染:`sidebar.right.tab.document.actions` 在每个显示头部的状态里跟在头部自有控件之后,`sidebar.right.tab.document.unpreviewable` 占据原本放重试的位置。预览对空态的读取失败分类:`not-text` 与 `too-large` 是可读但预览无法渲染的文件,提供 unpreviewable slot;`not-found` 与 `not-regular-file` 只给说明;其余失败保留重试,因为再读一次可能解决。不支持后缀的空态不发起读取,提供同一个 slot。 + +ui-open-in-app 填满这两个 slot:一个「打开 ▾」分体按钮,主按钮用默认应用打开文件,菜单再加文件管理器定位;一个空态的「使用默认应用打开」按钮。Host 回答有桌面之前,两个控件都不渲染。控件调用 Host 早已发布的 Session Remote:每页调用一次 `session.canOpenWorkspacePath`,每个手势调用一次 `session.openWorkspacePath`,带上绝对路径,定位时再带 `action: 'reveal'`;没有新增任何 Host 路由。两个控件共用一个手势 hook:只有用户按下的那个控件在调用结算期间禁用,失败的调用解析为一个失败种类,由该控件通过短暂 toast 提示一次,控件上不残留失败状态。 + +## 考虑过的备选 + +**新建自带 Host 路由的 `ui-open-locally` 包**(PR #4120)是这对 slot、失败分类、分体按钮设计和 toast 规则的来源。放弃它是因为仓库已经有 open-in-app 功能,再来一个负责本地打开的包属于重复;它新增的路由经由 Session 文件系统重新校验的,正是 `openWorkspacePath` 已经接受任意已认证客户端传入的东西。 + +**在 `dsh-host-open-in-app` 里加 Host 路由**提供桌面信息和按路径打开,能让 Host 报出文件管理器的名字,并区分文件不存在和启动失败。但这会让 Host 半边为了 Session Remote 已经发布的两个调用而依赖 `sessionController`、`workspaceFiles` 与 `fs`,所以直接使用 Remote,定位标签保持通用说法。 + +**现在就把交付卡片迁到这些控件上**会重做 PR #4120 里最大的那部分,包括评审否决的跨插件运行时导入,以及它不得不迁移的交付录制场景。本期卡片保留自己的路由。 + +## 后果 + +每个有 Host 路径的预览文件都能从 Sidebar 本地打开,包括从未交付过的文件。交付卡片和预览在同一项 Host 能力上跑着两套打开器;把它们统一起来,并按界面决定展示完整应用列表还是只展示默认应用,是产品方向点名的下一步。定位菜单项在所有平台都写「显示文件位置」,因为 Session Remote 不报告文件管理器。用默认应用打开带有 Host 文件关联的执行语义;护栏是用户对 Session 已可读文件的明确手势,没有授予任何新的 Host 权限。 + +单元测试覆盖失败分类、预览对每种出路的渲染以及在 Host 路径未知时对座位的保留、路径控制器的桌面读取与手势结果、两个控件的可见性、忙碌隔离与 toast,以及插件的注册与 fiber 释放时的移除。无密钥的 Web 文档预览场景在 POSIX 主机上用桩打开器驱动不支持后缀的控件,seeded-history 的文件预览 golden 固定住头部控件。 diff --git a/apps/web/tests/document-preview.e2e.ts b/apps/web/tests/document-preview.e2e.ts index 00fcf849e0..226ae750f4 100644 --- a/apps/web/tests/document-preview.e2e.ts +++ b/apps/web/tests/document-preview.e2e.ts @@ -1,11 +1,12 @@ -/** Keyless document-preview smoke through a real Session, Files tab, and shipped renderers. */ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +/** Keyless document-preview smoke through a real Session, Files tab, shipped renderers, and the default-application controls. */ +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { join, relative } from 'node:path' +import { delimiter, join, relative } from 'node:path' import { fileURLToPath } from 'node:url' import type { Browser, Locator, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed, vi } from 'vitest' +import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import { pdfFixture } from '../../../packages/client/ui-sidebar-documentpreview/tests/pdf-fixture.ts' import { assertFixtureInventory, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold } from './scaffold.ts' import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' @@ -18,6 +19,8 @@ const PAGE_LINES = 64 const SHOT_DIR = fileURLToPath(new URL('../../../.artifacts/screenshots/0908-document-preview', import.meta.url)) const PROMPT = 'Reply with the single word LIGHTHOUSE and stop.' const MODE = webSnapshotMode() +/** The stubbed opener runs as a POSIX script; Windows keeps its real file associations out of the lane. */ +const STUB_OPENER = process.platform !== 'win32' const TINY_PNG = Buffer.from( 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64', @@ -57,10 +60,34 @@ describe.skipIf(MODE === 'record')('web e2e: document preview through Files', () let page: Page let tripwire: ReturnType let outsideRoot: string | undefined + let nativeRoot: string | undefined + let openLog = '' + const opened = async (): Promise> => + (await readFile(openLog, 'utf8')).split('\n').filter(Boolean).map(line => JSON.parse(line) as { path: string; action: 'open' | 'reveal' }) beforeAll(async () => { outsideRoot = await mkdtemp(join(tmpdir(), 'dsh-preview-outside-')) - scaffold = await launchWebScaffold({ replayFixture: FIXTURE, paceMs: 5, compareReplaySession: false, extraOverlayPath: PAGING_PATCH }) + if (STUB_OPENER) { + // Exercise the built Host through its actual OS command, replacing only the desktop application. + nativeRoot = await mkdtemp(join(tmpdir(), 'dsh-preview-native-')) + openLog = join(nativeRoot, 'opened.jsonl') + await writeFile(openLog, '') + const command = process.platform === 'darwin' ? 'open' : 'xdg-open' + await writeFile(join(nativeRoot, command), `#!${process.execPath} +const fs = require('node:fs'); +const path = process.argv[2] === '-R' ? process.argv[3] : process.argv[2]; +const action = process.argv[2] === '-R' || fs.statSync(path).isDirectory() ? 'reveal' : 'open'; +fs.appendFileSync(${JSON.stringify(openLog)}, JSON.stringify({ path, action }) + '\\n'); +`, { mode: 0o700 }) + vi.stubEnv('PATH', `${nativeRoot}${delimiter}${process.env.PATH ?? ''}`) + } + // The Open In rows carry the default-application controls; the SSH marker + // keeps the host's application catalog empty, so the Session-header split + // button stays off every platform while the pinned desktop serves the file controls. + scaffold = await launchWebScaffold({ + replayFixture: FIXTURE, paceMs: 5, compareReplaySession: false, extraOverlayPath: PAGING_PATCH, + openInAppEnvironment: createLaunchEnvironmentSnapshot([{ source: 'process', values: { SSH_CONNECTION: '10.0.0.2 55000 10.0.0.9 22' } }]), + }) browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) @@ -75,7 +102,9 @@ describe.skipIf(MODE === 'record')('web e2e: document preview through Files', () try { await scaffold?.close() } finally { + vi.unstubAllEnvs() if (outsideRoot !== undefined) await rm(outsideRoot, { recursive: true, force: true }) + if (nativeRoot !== undefined) await rm(nativeRoot, { recursive: true, force: true }) } } }) @@ -474,13 +503,39 @@ describe.skipIf(MODE === 'record')('web e2e: document preview through Files', () await column.locator('[data-files-entry="file"]').getByRole('button', { name: 'clip.mp4', exact: true }).click() const unsupported = column.locator('[data-textpreview-state="unsupported"]') await unsupported.waitFor({ timeout: 15_000 }) - const unsupportedLine = await unsupported.locator('[data-textpreview-unsupported]').innerText() + const unsupportedLine = await unsupported.locator('[data-textpreview-unsupported] p').innerText() expect(unsupportedLine).toContain('Preview is not available for this file type yet.') expect(await unsupported.locator('[data-textpreview-path]').innerText()).toContain('clip.mp4') expect(await unsupported.locator('[data-document-viewer-menu]').count()).toBe(0) expect(await unsupported.locator('[data-textpreview-tool="reload"]').count()).toBe(0) + // The default-application controls land once the Host answered the pinned desktop read. + const headerOpen = unsupported.locator('[data-open-path-open]') + await headerOpen.waitFor({ timeout: 15_000 }) + const emptyOpen = unsupported.locator('[data-textpreview-unsupported] [data-open-path-unpreviewable]') + await emptyOpen.waitFor({ timeout: 15_000 }) await successShot(page, 'unsupported') - sections.push(['## Unviewable binary', '', '- State: unsupported', `- Line: ${unsupportedLine.trim()}`].join('\n')) + sections.push([ + '## Unviewable binary', '', + '- State: unsupported', + `- Line: ${unsupportedLine.trim()}`, + `- Header control: ${await headerOpen.innerText()}`, + `- Empty-state control: ${await emptyOpen.innerText()}`, + ].join('\n')) + if (STUB_OPENER) { + // Real Host gestures against the stubbed opener: default application from the empty state, reveal from the header menu. + const clip = join(cwd, 'clip.mp4') + await emptyOpen.click() + await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(1) + await unsupported.locator('[data-open-path-more]').click() + await page.getByRole('menuitem', { name: 'Show file location', exact: true }).click() + await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(2) + const gestures = await opened() + expect(gestures[0]).toEqual({ path: clip, action: 'open' }) + expect(gestures[1]?.action).toBe('reveal') + expect([clip, cwd]).toContain(gestures[1]?.path) + // Gesture facts stay out of the golden: the stub does not run on Windows. + expect(await page.getByRole('alert').count()).toBe(0) + } expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) await compareOrRefreshGolden(EXPECTED, sections.join('\n\n'), MODE) diff --git a/apps/web/tests/fixtures/native-open-on.patch.yml b/apps/web/tests/fixtures/native-open-on.patch.yml new file mode 100644 index 0000000000..b96dbfbd9c --- /dev/null +++ b/apps/web/tests/fixtures/native-open-on.patch.yml @@ -0,0 +1,4 @@ +# Pin desktop availability so native-open controls render identically in headless CI. +- id: session-controller + config: + nativeOpen: true diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts index 9d58ad53b2..788902d336 100644 --- a/apps/web/tests/seeded-history.e2e.ts +++ b/apps/web/tests/seeded-history.e2e.ts @@ -15,6 +15,7 @@ import { fileURLToPath } from 'node:url' import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContentBlock, Message } from '@deepseek-ai/dsh-llm' import { deriveEventMessage, SessionId } from '@deepseek-ai/dsh-session' @@ -206,8 +207,15 @@ describe('web e2e: seeded history renders through cold resume', () => { let seededThroughSeq = -1 beforeAll(async () => { - scaffold = await launchWebScaffold(process.platform === 'win32' ? {} : { - extraOverlayPath: fileURLToPath(new URL('./fixtures/sidebar-terminal.patch.yml', import.meta.url)), + // The POSIX terminal fixture stays off Windows; the pinned desktop applies + // everywhere. The Open In rows carry the document header's file controls, + // and the SSH marker keeps the application catalog empty so the + // Session-header split button stays out of every golden. + scaffold = await launchWebScaffold({ + extraOverlayPath: fileURLToPath(new URL(process.platform === 'win32' + ? './fixtures/native-open-on.patch.yml' + : './seeded-history.overlay.yml', import.meta.url)), + openInAppEnvironment: createLaunchEnvironmentSnapshot([{ source: 'process', values: { SSH_CONNECTION: '10.0.0.2 55000 10.0.0.9 22' } }]), }) // Composer recording uses a child workspace; seedSession owns the scaffold root. const sessionCwd = MODE === 'record' ? join(scaffold.workspaceCwd, 'workspace') : scaffold.workspaceCwd @@ -447,6 +455,8 @@ describe('web e2e: seeded history renders through cold resume', () => { await expect.poll(() => path.textContent()).toBe(absolutePath) expect(await path.getAttribute('title')).toBe(absolutePath) await expect.poll(() => column.locator('[data-textpreview-line="1"]').textContent()).toBe('alpha\n') + // The header's "Open" control lands once the Host answered the desktop read. + await column.locator('[data-open-path-open]').waitFor({ timeout: 5_000 }) const preview = await captureStableAria(page, '[data-textpreview-state="text"]', scaffold.workspaceCwd) await compareOrRefreshGolden(FILE_PREVIEW_EXPECTED, preview, MODE) // Put the column back so the later goldens see the default frame. @@ -737,12 +747,14 @@ describe('web e2e: seeded history renders through cold resume', () => { const column = page.locator('[data-rightbar-col]') await expect.poll(() => column.locator('[data-textpreview-line="1"]').textContent()).toBe('alpha\n') const tabId = await column.locator('[data-dockkit-tab]').getAttribute('data-dockkit-tab') + await column.locator('[data-open-path-open]').waitFor({ timeout: 5_000 }) const preview = await captureStableAria(page, '[data-textpreview-state="text"]', scaffold.workspaceCwd) const warningStart = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) acknowledgeReloadConnectionLoss(tripwire, warningStart) await expect.poll(() => column.locator('[data-textpreview-line="1"]').textContent()).toBe('alpha\n') expect(await column.locator('[data-dockkit-tab]').getAttribute('data-dockkit-tab')).toBe(tabId) + await column.locator('[data-open-path-open]').waitFor({ timeout: 5_000 }) const restoredPreview = await captureStableAria(page, '[data-textpreview-state="text"]', scaffold.workspaceCwd) expect(restoredPreview).toBe(preview) }) diff --git a/apps/web/tests/seeded-history.overlay.yml b/apps/web/tests/seeded-history.overlay.yml new file mode 100644 index 0000000000..be32e87fc5 --- /dev/null +++ b/apps/web/tests/seeded-history.overlay.yml @@ -0,0 +1,17 @@ +# The cold-resume lane's own overlay: the bounded terminal fixture the terminal +# replacement case drives, plus a pinned desktop so the document header's +# "Open" control lands in the file-preview golden on every platform. +- id: terminal-controller + config: + maxTerminals: 2 + unattendedTimeoutMs: 2000 + activityPollIntervalMs: 100 + cleanupRetryMs: 100 + shellCandidates: [/bin/bash, /bin/sh] + shell: + path: /bin/bash + name: bash + args: [--noprofile, --norc, -i] +- id: session-controller + config: + nativeOpen: true diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index 348648a215..a2ebb863dd 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/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/README.md -README.md: d3aee40a79e5d57029d8af42c333abcd5a9112a9 -README.zh.md: a3776a2c1034cb747fb191c206b52d570ec47aaf +README.md: ff0acc7da1be69e0fb76ed3ce72d31d490dcd32c +README.zh.md: 22ab17872ae3a0f62de05bc7ace41fd92332b355 diff --git a/packages/client/README.md b/packages/client/README.md index d3aee40a79..ff0acc7da1 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -78,7 +78,7 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-message-feedback/`](ui-message-feedback/README.md) | The feedback surface: per-message Like/Dislike in the assistant-message action strip, and the feedback dialog behind both ratings and `/feedback` | — | | [`ui-directory-picker-browse/`](ui-directory-picker-browse/README.md) | In-app directory browsing surface for the workspace directory flow | — | | [`ui-directory-picker-native/`](ui-directory-picker-native/README.md) | Native directory-picker surface driving the local Desktop or Host OS chooser | — | -| [`ui-open-in-app/`](ui-open-in-app/README.md) | Session-header split button opening the workspace directory in an installed application | — | +| [`ui-open-in-app/`](ui-open-in-app/README.md) | Session-header split button opening the workspace directory in an installed application, and the document preview's default-application controls for one file | — | ----- diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index a3776a2c10..22ab17872a 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -78,7 +78,7 @@ kind: "package-group" | [`ui-message-feedback/`](ui-message-feedback/README.zh.md) | 反馈界面:助手消息操作条中的逐消息赞踩,以及点赞、点踩与 `/feedback` 背后的反馈弹窗 | — | | [`ui-directory-picker-browse/`](ui-directory-picker-browse/README.zh.md) | 面向工作区目录流程的应用内目录浏览界面 | — | | [`ui-directory-picker-native/`](ui-directory-picker-native/README.zh.md) | 驱动本地 Desktop 或 Host OS 选择器的原生目录选择界面 | — | -| [`ui-open-in-app/`](ui-open-in-app/README.zh.md) | 在已安装应用中打开工作区目录的会话标题栏拆分按钮 | — | +| [`ui-open-in-app/`](ui-open-in-app/README.zh.md) | 在已安装应用中打开工作区目录的会话标题栏拆分按钮,以及文档预览里用默认应用打开单个文件的控件 | — | ----- diff --git a/packages/client/ui-open-in-app/README.i18n.yaml b/packages/client/ui-open-in-app/README.i18n.yaml index bab8f0bd17..aa155f7e22 100644 --- a/packages/client/ui-open-in-app/README.i18n.yaml +++ b/packages/client/ui-open-in-app/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-open-in-app/README.md -README.md: d242d5a84dffbf0895485f7c79eafd5e332fe446 -README.zh.md: e954b7c71e8c4dbd1b19a041aafb7fe154631fbb +README.md: 91d259c73ad73460bca151d9e4cacfb6338c62ab +README.zh.md: 30d28f0681c6abfd7b3ea3ab3dc341df7fb3bdaf diff --git a/packages/client/ui-open-in-app/README.md b/packages/client/ui-open-in-app/README.md index d242d5a84d..91d259c73a 100644 --- a/packages/client/ui-open-in-app/README.md +++ b/packages/client/ui-open-in-app/README.md @@ -1,5 +1,5 @@ --- -description: "Web Session-header \"Open In...\" split button: launches the remembered application on the session workspace directory and lists every application the host probed as installed." +description: "Web \"Open In...\" controls: the Session-header split button launching the remembered application on the workspace directory, and the document preview's default-application open and reveal controls for one file." kind: "package-reference" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -This package provides the browser surface of the open-in-app feature: a Session-header split button whose main button opens the current session's workspace directory (the summary's `cwd`) in the remembered application, and whose chevron lists every catalog application the host probed as installed. Availability, icons, and launches come from the host routes of [`dsh-host-open-in-app`](../../host/open-in-app/README.md); mount the two packages together. A session without a workspace directory, or a host where nothing nameable is installed, renders no button at all. +This package provides the browser surface of the open-in-app feature. A Session-header split button opens the current session's workspace directory (the summary's `cwd`) in the remembered application, and its chevron lists every catalog application the host probed as installed; availability, icons, and launches come from the host routes of [`dsh-host-open-in-app`](../../host/open-in-app/README.md), so mount the two packages together. In the right Sidebar's document preview, an "Open" split button and an empty-state button open the previewed file in its default application or show its location, through the Session Remote. A host without the capability renders none of these controls. ## Table of Contents @@ -25,12 +25,14 @@ This package provides the browser surface of the open-in-app feature: a Session- ## Use this package -Mount this plugin in the Web composition beside [`dsh-host-open-in-app`](../../host/open-in-app/README.md); the pair composes the whole feature in two cordis.yml rows and this row takes no config. The Session header grows an "Open In..." split button whenever the host probed at least one installed catalog application and the session has a known workspace directory. +Mount this plugin in the Web composition beside [`dsh-host-open-in-app`](../../host/open-in-app/README.md); the pair composes the whole feature in two cordis.yml rows and this row takes no config. The Session header grows an "Open In..." split button whenever the host probed at least one installed catalog application and the session has a known workspace directory. The document preview of [`ui-sidebar-documentpreview`](../ui-sidebar-documentpreview/README.md) grows its file controls whenever the Host reports a desktop through the Session Remote's `session.canOpenWorkspacePath`; removing this row removes every control at once. ### What to expect The main button shows the remembered application's icon — the real application icon wherever the host extracts one (macOS bundle icons, Windows executable icons, Linux theme icons), a generic glyph where it serves none — and a design-system tooltip ("Open locally"); clicking launches immediately. The chevron opens a dense menu of the installed applications with the remembered one marked by a filled row. Availability is read once per page from the host; the last chosen application persists in the browser (`dsh.open-in-app.choice`), and a choice that is no longer installed falls back to the first available entry. A launch that finishes quickly leaves the button untouched — the dimmed busy treatment appears only after 250 ms in flight — and a failed launch shows the error tooltip and a red outline for two seconds. All copy lives in the bilingual `open-in-app` locale namespace; an application id the dictionaries cannot name is not offered. +In the document preview, the header's "Open ▾" split button opens the previewed file in the Host's default application from its main button, and its menu offers that action and "Show file location" (the file manager's reveal). A file the preview cannot render, whether an unsupported suffix such as video or an archive or a file the reader rejected as non-text or oversized, shows an "Open in default app" button in its empty state where Retry would otherwise stand. Both controls hand the Host the absolute path the file's metadata reports, appear only after the Host answered that a desktop is available, disable only while their own gesture settles, and announce a failed gesture once through a transient toast ("Could not open. Try again." or "Could not show the file location. Try again."); nothing stays on the control afterwards. + ----- @@ -39,7 +41,9 @@ The main button shows the remembered application's icon — the real application
Implementation internals — click to expand -The plugin registers the split button on `conversation.session.header.utilities` through the standard slot/inject currency and registers the `open-in-app` dictionaries as one effect. A page-lifetime controller ([`src/client/controller.ts`](src/client/controller.ts)) owns the once-per-page availability read, the persisted choice snapshot store, and the launch POST; the component receives both stores through the inject `hooks` compartment, so every Session header shares one truth. Route paths and wire payload types are inlined from the host package's browser-safe `@deepseek-ai/dsh-host-open-in-app/shared` subpath. In-flight launches are guarded by a ref — repeat clicks and menu picks during a launch are ignored whole (a pick would otherwise persist a choice the gesture never opened) — and the busy/error dress is timer-driven around the `launch` promise. The node half is an empty `apply` that keeps the plugin on the host roster. +The plugin registers the split button on `conversation.session.header.utilities` through the standard slot/inject currency and registers the `open-in-app` dictionaries as one effect. A page-lifetime controller ([`src/client/controller.ts`](src/client/controller.ts)) owns the once-per-page availability read, the persisted choice snapshot store, and the launch POST; the component receives both stores through the inject `hooks` compartment, so every Session header shares one truth. Route paths and wire payload types are inlined from the host package's browser-safe `@deepseek-ai/dsh-host-open-in-app/shared` subpath. In-flight launches are guarded by a ref — repeat clicks and menu picks during a launch are ignored whole (a pick would otherwise persist a choice the gesture never opened) — and the busy/error dress is timer-driven around the `launch` promise. + +The file controls register on the document preview's `sidebar.right.tab.document.actions` and `sidebar.right.tab.document.unpreviewable` child slots, whose owner props carry the previewed file and its absolute Host path. A second page-lifetime controller ([`src/client/open-path.ts`](src/client/open-path.ts)) reads the Session Remote's `session.canOpenWorkspacePath` once per page into a desktop snapshot store both controls share, and runs each gesture through `session.openWorkspacePath` with the path and, for reveal, `action: 'reveal'`; a refused or rejected call resolves as the failure kind the control announces. The controls share one gesture hook that owns the pending flag and the toast, so a gesture from one control never restyles the other. The node half is an empty `apply` that keeps the plugin on the host roster.
@@ -50,6 +54,8 @@ The plugin registers the split button on `conversation.session.header.utilities` - [dsh-host-open-in-app](../../host/open-in-app/README.md) — the host routes serving availability, icons, and launches, and the catalog behind them. - [dsh-session-log-export](../../session-query/session-log-export/README.md) — the sibling Session-header action. +- [ui-sidebar-documentpreview](../ui-sidebar-documentpreview/README.md) — the document preview declaring the header and empty-state child slots the file controls occupy. +- [ui-deliverables](../ui-deliverables/README.md) — the delivery cards, which still open declared files through their own routes. - [Web client architecture](../../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md) — how browser plugin rows load and register slots. ----- @@ -68,7 +74,9 @@ None; this package neither assembles nor sends a provider request. - **The dictionaries gate the menu.** A host catalog extension without a matching `app.` entry in both dictionaries stays invisible instead of showing a raw id; extending the catalog means extending [`dsh-host-open-in-app`](../../host/open-in-app/README.md) and this package's locales together. -- **Availability is read once per page.** An application installed while the page is open appears after a reload (and, host-side, after a host restart). +- **Availability is read once per page.** An application installed while the page is open appears after a reload (and, host-side, after a host restart); the desktop answer behind the file controls is read once per page as well. +- **One reveal label for every platform.** The Session Remote reports whether a desktop exists, not which file manager it runs, so the menu says "Show file location" rather than naming Finder or File Explorer as the delivery cards do. +- **The delivery cards keep their own opener.** [`ui-deliverables`](../ui-deliverables/README.md) still opens declared files through its own Session-and-event routes; folding those cards onto the file controls here is deferred to the [Agent Note](../../../.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.md). ### Dev Note @@ -76,8 +84,8 @@ None; this package neither assembles nor sends a provider request.
Working context for maintainers — click to expand -The feature-level decisions, including the split into the host package and this surface, are recorded in the [promotion Agent Note](../../../.agents/notes/implemented/feature/2026-08-25-promote-open-anywhere-plugin.md). +The feature-level decisions, including the split into the host package and this surface, are recorded in the [promotion Agent Note](../../../.agents/notes/implemented/feature/2026-08-25-promote-open-anywhere-plugin.md); the document preview's file controls are recorded in the [default-application Agent Note](../../../.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.md).
-**Runtime invariant:** No companion is published. The plugin registers one dictionary effect and one header-slot entry whose disposal the HMR-safety spec proves; availability and choice live in the controller's snapshot stores with no second copy to diverge. +**Runtime invariant:** No companion is published. The plugin registers one dictionary effect and three slot entries whose disposal the HMR-safety spec proves; application availability, the choice, and the desktop answer live in the controllers' snapshot stores with no second copy to diverge. diff --git a/packages/client/ui-open-in-app/README.zh.md b/packages/client/ui-open-in-app/README.zh.md index e954b7c71e..30d28f0681 100644 --- a/packages/client/ui-open-in-app/README.zh.md +++ b/packages/client/ui-open-in-app/README.zh.md @@ -1,5 +1,5 @@ --- -description: "Web 会话头部 \"Open In...\" 分体按钮:在记住的应用中打开会话 workspace 目录,并列出主机探测到已安装的全部应用。" +description: "Web \"Open In...\" 控件:会话头部在记住的应用中打开 workspace 目录的分体按钮,以及文档预览里用默认应用打开、显示单个文件位置的控件。" kind: "package-reference" --- @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -本包提供 open-in-app 功能的浏览器表面:会话头部的一个分体按钮,主按钮在记住的应用中打开当前会话的 workspace 目录(会话摘要的 `cwd`),下拉箭头列出主机探测到已安装的全部 catalog 应用。可用性、图标与启动均来自 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 的主机路由;两个包应一起挂载。没有 workspace 目录的会话、或没装任何可命名应用的主机,完全不渲染按钮。 +本包提供 open-in-app 功能的浏览器表面。会话头部的分体按钮在记住的应用中打开当前会话的 workspace 目录(会话摘要的 `cwd`),下拉箭头列出主机探测到已安装的全部 catalog 应用;可用性、图标与启动均来自 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 的主机路由,所以两个包要一起挂载。在右侧 Sidebar 的文档预览里,一个「打开」分体按钮和一个空态按钮经由 Session Remote 用默认应用打开当前文件或显示其位置。主机没有这项能力时,这些控件一个都不渲染。 ## 目录 @@ -25,12 +25,14 @@ kind: "package-reference" ## 使用本包 -把本插件与 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 并排挂进 Web 组合;这对包用两行 cordis.yml 组成完整功能,本行不接受任何配置。只要主机探测到至少一个已安装的 catalog 应用且会话有已知的 workspace 目录,会话头部就会出现 "Open In..." 分体按钮。 +把本插件与 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 并排挂进 Web 组合;这对包用两行 cordis.yml 组成完整功能,本行不接受任何配置。只要主机探测到至少一个已安装的 catalog 应用且会话有已知的 workspace 目录,会话头部就会出现 "Open In..." 分体按钮。只要 Host 通过 Session Remote 的 `session.canOpenWorkspacePath` 报告有桌面,[`ui-sidebar-documentpreview`](../ui-sidebar-documentpreview/README.zh.md) 的文档预览就会长出文件控件;删掉这一行会一次去掉所有控件。 ### 预期行为 主按钮显示记住的应用图标——凡主机能提取的都是应用真实图标(macOS bundle 图标、Windows 可执行文件图标、Linux 主题图标),提取不到时是通用占位图形——并带设计系统 tooltip(「在本地打开」);点击立即启动。下拉箭头打开已安装应用的紧凑菜单,记住的条目以整行填充标记。可用性每页读取一次;上次选择的应用持久化在浏览器中(`dsh.open-in-app.choice`),不再安装的选择回退到第一个可用条目。快速完成的启动不改变按钮外观——变暗的等待态只在飞行超过 250 毫秒后出现——失败的启动显示错误 tooltip 与红色描边两秒。所有文案在双语 `open-in-app` locale 命名空间中;词典无法命名的应用 id 不会被提供。 +在文档预览里,头部的「打开 ▾」分体按钮的主按钮用 Host 默认应用打开当前文件,菜单提供同一动作和「显示文件位置」(文件管理器的定位)。预览无法渲染的文件,无论是视频、压缩包这类不支持的后缀,还是被读取器判为非文本或过大的文件,都会在空态里原本放重试的位置显示「使用默认应用打开」按钮。两个控件都把文件元数据报出的绝对路径交给 Host,只在 Host 回答有桌面之后出现,只在自己的手势结算期间禁用,失败时通过短暂 toast 提示一次(「打开失败,请重试」或「无法显示文件位置,请重试」),之后控件上不残留任何状态。 + ----- @@ -39,7 +41,9 @@ kind: "package-reference"
实现内幕——点击展开 -插件通过标准 slot/inject 机制把分体按钮注册到 `conversation.session.header.utilities`,并以一个 effect 注册 `open-in-app` 词典。一个页面生命周期的 controller([`src/client/controller.ts`](src/client/controller.ts))拥有每页一次的可用性读取、持久化选择的 snapshot store 与启动 POST;组件经 inject 的 `hooks` 隔间接收两个 store,因此所有会话头部共享同一份事实。路由路径与 wire 载荷类型从主机包的浏览器安全子路径 `@deepseek-ai/dsh-host-open-in-app/shared` 内联。飞行中的启动由 ref 守卫——启动期间的重复点击与菜单选择被整体忽略(否则会持久化一个该手势从未打开的选择)——busy/error 视觉由围绕 `launch` promise 的定时器驱动。节点半边是一个空 `apply`,让插件出现在主机侧的插件名册上。 +插件通过标准 slot/inject 机制把分体按钮注册到 `conversation.session.header.utilities`,并以一个 effect 注册 `open-in-app` 词典。一个页面生命周期的 controller([`src/client/controller.ts`](src/client/controller.ts))拥有每页一次的可用性读取、持久化选择的 snapshot store 与启动 POST;组件经 inject 的 `hooks` 隔间接收两个 store,因此所有会话头部共享同一份事实。路由路径与 wire 载荷类型从主机包的浏览器安全子路径 `@deepseek-ai/dsh-host-open-in-app/shared` 内联。飞行中的启动由 ref 守卫——启动期间的重复点击与菜单选择被整体忽略(否则会持久化一个该手势从未打开的选择)——busy/error 视觉由围绕 `launch` promise 的定时器驱动。 + +文件控件注册在文档预览的 `sidebar.right.tab.document.actions` 与 `sidebar.right.tab.document.unpreviewable` 子 slot 上,owner props 携带当前文件及其 Host 绝对路径。第二个页面生命周期的 controller([`src/client/open-path.ts`](src/client/open-path.ts))每页读取一次 Session Remote 的 `session.canOpenWorkspacePath`,写进两个控件共用的桌面 snapshot store,并把每个手势交给 `session.openWorkspacePath`,带上路径,定位时再带 `action: 'reveal'`;被拒绝或抛错的调用解析为控件要提示的失败种类。两个控件共用一个手势 hook,由它持有 pending 标志和 toast,所以一个控件的手势不会改变另一个控件的样子。节点半边是一个空 `apply`,让插件出现在主机侧的插件名册上。
@@ -50,6 +54,8 @@ kind: "package-reference" - [dsh-host-open-in-app](../../host/open-in-app/README.zh.md)——提供可用性、图标与启动的主机路由,及其背后的目录。 - [dsh-session-log-export](../../session-query/session-log-export/README.zh.md)——会话头部的姊妹动作。 +- [ui-sidebar-documentpreview](../ui-sidebar-documentpreview/README.zh.md)——声明文件控件所占头部与空态子 slot 的文档预览。 +- [ui-deliverables](../ui-deliverables/README.zh.md)——交付卡片,仍通过自己的路由打开声明过的文件。 - [Web client 架构](../../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.zh.md)——浏览器插件行如何加载并注册 slot。 ----- @@ -68,7 +74,9 @@ kind: "package-reference" - **词典把守菜单。** 主机目录的新条目若在两份词典中没有对应的 `app.` 条目,将保持不可见而不是显示裸 id;扩展目录意味着同时扩展 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 与本包的 locale。 -- **可用性每页只读一次。** 页面打开期间安装的应用要重新加载页面后才出现(主机侧还需主机重启)。 +- **可用性每页只读一次。** 页面打开期间安装的应用要重新加载页面后才出现(主机侧还需主机重启);文件控件背后的桌面回答同样每页只读一次。 +- **所有平台共用一个定位标签。** Session Remote 只报告有没有桌面,不报告它跑的是哪个文件管理器,所以菜单写「显示文件位置」,而不像交付卡片那样点名访达或文件资源管理器。 +- **交付卡片保留自己的打开器。** [`ui-deliverables`](../ui-deliverables/README.zh.md) 仍通过自己按 Session 与事件定位的路由打开声明过的文件;把这些卡片并到这里的文件控件上,延后到 [Agent Note](../../../.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.zh.md) 记录的后续工作。 ### 开发备注 @@ -76,8 +84,8 @@ kind: "package-reference"
维护者工作语境——点击展开 -功能层面的各项决定,包括拆分为主机包与本表面包,记录在[转正 Agent Note](../../../.agents/notes/implemented/feature/2026-08-25-promote-open-anywhere-plugin.zh.md)。 +功能层面的各项决定,包括拆分为主机包与本表面包,记录在[转正 Agent Note](../../../.agents/notes/implemented/feature/2026-08-25-promote-open-anywhere-plugin.zh.md);文档预览的文件控件记录在[默认应用 Agent Note](../../../.agents/notes/implemented/feature/2026-09-16-open-in-default-app-for-sidebar-files.zh.md)。
-**运行时不变式:** 不发布伴生入口。插件注册一个词典 effect 和一个 header slot 条目,HMR 安全性 spec 证明二者都会在资源释放时撤销;可用性与选择存储在控制器的快照存储中,不存在可能与之分歧的第二份副本。 +**运行时不变式:** 不发布伴生入口。插件注册一个词典 effect 和三个 slot 条目,HMR 安全性 spec 证明它们都会在资源释放时撤销;应用可用性、选择与桌面回答存储在控制器的快照存储中,不存在可能与之分歧的第二份副本。 diff --git a/packages/client/ui-open-in-app/package.json b/packages/client/ui-open-in-app/package.json index 0b8b93b67d..35fe0dacd0 100644 --- a/packages/client/ui-open-in-app/package.json +++ b/packages/client/ui-open-in-app/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-open-in-app", - "description": "Web Session-header \"Open In...\" split button opening the session workspace directory in a locally installed application", + "description": "Web \"Open In...\" controls: the Session-header split button opening the workspace directory in an installed application, and the document preview's default-application controls for one file", "version": "0.1.6-alpha.1", "publishConfig": { "access": "public" @@ -38,10 +38,14 @@ "dsh": { "client": { "inject": [ + "@deepseek-ai/dsh-api-gateway", + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-api-session-controller", "@deepseek-ai/dsh-client-locale", "@deepseek-ai/dsh-client-ui-conversation", "@deepseek-ai/dsh-client-ui-renderer", - "@deepseek-ai/dsh-client-ui-session" + "@deepseek-ai/dsh-client-ui-session", + "@deepseek-ai/dsh-client-ui-sidebar-documentpreview" ], "platform": "web" } @@ -51,6 +55,8 @@ }, "devDependencies": { "@deepseek-ai/cordis": "workspace:^", + "@deepseek-ai/dsh-api-gateway": "workspace:^", + "@deepseek-ai/dsh-api-remotes": "workspace:^", "@deepseek-ai/dsh-api-session-controller": "workspace:^", "@deepseek-ai/dsh-client-locale": "workspace:^", "@deepseek-ai/dsh-client-store": "workspace:^", @@ -59,6 +65,7 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", "@deepseek-ai/dsh-client-ui-renderer": "workspace:^", "@deepseek-ai/dsh-client-ui-session": "workspace:^", + "@deepseek-ai/dsh-client-ui-sidebar-documentpreview": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-host-open-in-app": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", diff --git a/packages/client/ui-open-in-app/src/client/OpenPathAction.module.css b/packages/client/ui-open-in-app/src/client/OpenPathAction.module.css new file mode 100644 index 0000000000..f12b033102 --- /dev/null +++ b/packages/client/ui-open-in-app/src/client/OpenPathAction.module.css @@ -0,0 +1,62 @@ +/* Sized to sit in the document header's 28px control row beside its round + icon buttons: a hairline pill with a 12px label and a narrow chevron half. */ + +.menuAnchor { + display: inline-flex; + flex: none; + align-self: center; +} + +.split { + display: inline-flex; + align-items: stretch; + box-sizing: border-box; + height: 28px; + overflow: hidden; + border: 0.5px solid var(--dsw-alias-border-l3); + border-radius: 14px; + font-family: var(--dsw-font-family); +} + +.main, +.chevron { + display: inline-flex; + align-items: center; + justify-content: center; + border: 0; + background: none; + color: var(--dsw-alias-label-primary); + font-size: 12px; + line-height: 16px; + white-space: nowrap; + cursor: pointer; +} + +.main { + padding: 5px 8px 5px 10px; +} + +.chevron { + padding: 5px 6px 5px 4px; + border-left: 0.5px solid var(--dsw-alias-border-l3); + color: var(--dsw-alias-label-secondary); +} + +.main:hover:not(:disabled), +.main:focus-visible, +.chevron:hover:not(:disabled), +.chevron:focus-visible { + background: var(--dsw-alias-interactive-bg-hover); +} + +/* Pending disables clicks without a restyle; only hover feedback pauses. */ +.main:disabled, +.chevron:disabled { + cursor: default; +} + +.menuIcon { + display: block; + width: 16px; + height: 16px; +} diff --git a/packages/client/ui-open-in-app/src/client/OpenPathAction.tsx b/packages/client/ui-open-in-app/src/client/OpenPathAction.tsx new file mode 100644 index 0000000000..8df8374dde --- /dev/null +++ b/packages/client/ui-open-in-app/src/client/OpenPathAction.tsx @@ -0,0 +1,132 @@ +/** + * Document-header split button: the main button opens the previewed file in + * its default application, the chevron's menu adds the file-manager reveal. + * Both path controls share the gesture hook declared here. + */ +import { useEffect, useState } from 'react' +import type { ReactNode } from 'react' +import { + IconChevronDownOutline14, IconFolderOpenOutline16, IconRightUpOutline16, Menu, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { InjectFace, PropsLocale, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client' +import type { OpenInAppPathAction, OpenInAppPathFailure } from './open-path.ts' +import { useOpenFailureToast } from './open-failure-toast.tsx' +import type { NS } from './locales.ts' +import css from './OpenPathAction.module.css' + +/** Desktop availability and the gesture carrier injected into both path controls. */ +export interface OpenPathInjected { + hooks: { + openInAppDesktop: ObservableSnapshot + } + loadDesktop: () => Promise + openPath: (path: string, action: OpenInAppPathAction) => Promise +} + +/** Full props of the document-header contribution. */ +export type OpenPathActionProps = + PropsRuntime<'sidebar.right.tab.document.actions'> + & PropsLocale + & InjectFace + +/** What one path control needs from its props: the file, the injected face, and copy. */ +type PathGestureProps = Pick & { + t: TranslateNS +} + +/** + * Desktop availability, this control's own pending state, and a gesture + * runner announcing failures through this control's toast. Only the control + * that ran the gesture disables while it settles; failure never persists on + * the control. + * @param props - the file's Host path, the injected face, and copy. + * @returns availability, pending, the toast to render, and the runner. + */ +export function usePathGesture({ absolutePath, useOpenInAppDesktop, loadDesktop, openPath, t }: PathGestureProps): { + available: boolean + pending: boolean + toast: ReactNode + act: (action: OpenInAppPathAction) => void +} { + const desktop = useOpenInAppDesktop(value => value) + const [pending, setPending] = useState(false) + const { toast, show } = useOpenFailureToast() + useEffect(() => { + if (desktop === null) void loadDesktop() + }, [desktop, loadDesktop]) + return { + available: desktop === true, + pending, + toast, + act: (action) => { + setPending(true) + void openPath(absolutePath, action).then((failure) => { + if (failure !== null) show(t(`path.${failure}`)) + }).finally(() => { setPending(false) }) + }, + } +} + +/** + * Render the split button, or nothing until the Host reports a desktop. + * @param props - the previewed file, the injected face, and copy. + * @returns the split button with its menu and toast, or null. + */ +export function OpenPathAction(props: OpenPathActionProps): ReactNode { + const { t } = props + const [menuOpen, setMenuOpen] = useState(false) + const { available, pending, toast, act } = usePathGesture(props) + if (!available) return null + const run = (action: OpenInAppPathAction): void => { + setMenuOpen(false) + act(action) + } + return ( + <> + { setMenuOpen(false) }} + items={[ + { id: 'open', icon: , label: t('path.defaultApp') }, + { id: 'reveal', icon: , label: t('path.reveal') }, + ]} + onSelect={(id) => { run(id === 'reveal' ? 'reveal' : 'open') }} + anchor={( +
+ + + + +
+ )} + /> + {toast} + + ) +} diff --git a/packages/client/ui-open-in-app/src/client/OpenPathEmptyAction.module.css b/packages/client/ui-open-in-app/src/client/OpenPathEmptyAction.module.css new file mode 100644 index 0000000000..252c870293 --- /dev/null +++ b/packages/client/ui-open-in-app/src/client/OpenPathEmptyAction.module.css @@ -0,0 +1,27 @@ +/* The empty state's capsule, sized like the preview's own Retry + (ui-sidebar-documentpreview TextPreview `.retry`) so the two recourses read + as one family. */ +.open { + display: inline-flex; + flex: none; + gap: 6px; + align-items: center; + height: 32px; + padding: 0 12px 0 14px; + color: var(--dsw-alias-label-primary); + font-size: var(--dsh-content-font-size-secondary, 13px); + font-family: inherit; + background: transparent; + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: 16px; + cursor: pointer; +} + +.open:hover:not(:disabled) { + background: var(--dsw-alias-interactive-bg-hover); +} + +/* Pending disables clicks without a restyle; only hover feedback pauses. */ +.open:disabled { + cursor: default; +} diff --git a/packages/client/ui-open-in-app/src/client/OpenPathEmptyAction.tsx b/packages/client/ui-open-in-app/src/client/OpenPathEmptyAction.tsx new file mode 100644 index 0000000000..0f2b752139 --- /dev/null +++ b/packages/client/ui-open-in-app/src/client/OpenPathEmptyAction.tsx @@ -0,0 +1,40 @@ +/** Empty-state contribution: open a file the document preview cannot render in its default application. */ +import type { ReactNode } from 'react' +import { IconRightUpOutline16 } from '@deepseek-ai/dsh-client-ui-primitives' +import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client' +import type { NS } from './locales.ts' +import { usePathGesture, type OpenPathInjected } from './OpenPathAction.tsx' +import css from './OpenPathEmptyAction.module.css' + +/** Full props of the unpreviewable empty-state contribution. */ +export type OpenPathEmptyActionProps = + PropsRuntime<'sidebar.right.tab.document.unpreviewable'> + & PropsLocale + & InjectFace + +/** + * Render the default-application open button, or nothing until the Host reports a desktop. + * @param props - the unpreviewable file, the injected face, and copy. + * @returns the open button and its toast, or null. + */ +export function OpenPathEmptyAction(props: OpenPathEmptyActionProps): ReactNode { + const { t } = props + const { available, pending, toast, act } = usePathGesture(props) + if (!available) return null + return ( + <> + + {toast} + + ) +} diff --git a/packages/client/ui-open-in-app/src/client/index.ts b/packages/client/ui-open-in-app/src/client/index.ts index c3e4d88f98..05aae1e925 100644 --- a/packages/client/ui-open-in-app/src/client/index.ts +++ b/packages/client/ui-open-in-app/src/client/index.ts @@ -1,18 +1,28 @@ /** * Browser half of open-in-app: one Session-header split button opening the * session's workspace directory (the summary's `cwd`) in the remembered - * installed application. Availability arrives once per page from the host - * apps route; the last choice persists in the browser through the controller's - * persisted snapshot store. + * installed application, and the document preview's default-application + * controls opening one previewed file. Application availability arrives once + * per page from the host apps route and the last choice persists in the + * browser through the controller's persisted snapshot store; desktop + * availability for file paths arrives once per page from the Session Remote, + * which also runs the open and reveal gestures. */ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' +import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client' +import type {} from '@deepseek-ai/dsh-api-gateway/client' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-api-session-controller/remote' import { OPEN_IN_APP_ICON_PREFIX } from '@deepseek-ai/dsh-host-open-in-app/shared' import { OpenInAppController } from './controller.ts' import { OpenInAppAction, type OpenInAppActionInjected } from './OpenInAppAction.tsx' +import { OpenInAppPathController } from './open-path.ts' +import { OpenPathAction, type OpenPathInjected } from './OpenPathAction.tsx' +import { OpenPathEmptyAction } from './OpenPathEmptyAction.tsx' import { en, NS, zh, type OpenInAppKey } from './locales.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -23,17 +33,22 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } export type { OpenInAppActionInjected, OpenInAppActionProps } from './OpenInAppAction.tsx' +export type { OpenInAppPathAction, OpenInAppPathFailure, OpenInAppPathRemote } from './open-path.ts' +export type { OpenPathActionProps, OpenPathInjected } from './OpenPathAction.tsx' +export type { OpenPathEmptyActionProps } from './OpenPathEmptyAction.tsx' -/** Required services for locale registration and the header-slot contribution. */ -export const inject = ['sessions', 'slots', 'locale'] +/** Required services: sessions, the slot registry, copy, and the Remote carrier with its `session` namespace. */ +export const inject = ['sessions', 'slots', 'locale', 'remote', 'remote.session'] /** - * Client plugin body: register the dictionaries and the header split button. + * Client plugin body: register the dictionaries, the header split button, and + * the document preview's path controls. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { const controller = new OpenInAppController() void controller.load() + const paths = new OpenInAppPathController(ctx.remote) ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'open-in-app: dictionaries') ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({ name: 'conversation.session.header.utilities', @@ -50,4 +65,21 @@ export function apply(ctx: ClientContext): void { iconUrl: appId => `${OPEN_IN_APP_ICON_PREFIX}/${appId}`, }), }, OpenInAppAction)) + const pathInjected = (): OpenPathInjected => ({ + hooks: { openInAppDesktop: paths.desktop }, + loadDesktop: () => paths.load(), + openPath: (path, action) => paths.openPath(path, action), + }) + ctx.slots.inject('sidebar.right.tab.document.actions', () => ctx.slots.register({ + name: 'sidebar.right.tab.document.actions', + id: 'open-in-app', + locale: NS, + inject: pathInjected, + }, OpenPathAction)) + ctx.slots.inject('sidebar.right.tab.document.unpreviewable', () => ctx.slots.register({ + name: 'sidebar.right.tab.document.unpreviewable', + id: 'open-in-app', + locale: NS, + inject: pathInjected, + }, OpenPathEmptyAction)) } diff --git a/packages/client/ui-open-in-app/src/client/locales.ts b/packages/client/ui-open-in-app/src/client/locales.ts index a5cadacd05..3142716615 100644 --- a/packages/client/ui-open-in-app/src/client/locales.ts +++ b/packages/client/ui-open-in-app/src/client/locales.ts @@ -1,4 +1,4 @@ -/** `open-in-app` namespace dictionaries. */ +/** `open-in-app` namespace dictionaries: the workspace split button and the document-preview path controls. */ /** Dictionary namespace owned by this plugin. */ export const NS = 'open-in-app' @@ -44,6 +44,14 @@ export const zh = { 'open.error': '打开失败', 'menu.toggle': '选择打开方式', 'menu.aria': '打开方式', + 'path.open': '打开', + 'path.open.tooltip': '用默认应用打开', + 'path.more': '更多打开方式', + 'path.defaultApp': '用默认应用打开', + 'path.reveal': '显示文件位置', + 'path.unpreviewable': '使用默认应用打开', + 'path.openError': '打开失败,请重试', + 'path.revealError': '无法显示文件位置,请重试', ...PRODUCT_NAMES, 'app.finder': '访达', 'app.explorer': '文件资源管理器', @@ -58,6 +66,14 @@ export const en: Record = { 'open.error': 'Failed to open', 'menu.toggle': 'Choose an app to open in', 'menu.aria': 'Open in', + 'path.open': 'Open', + 'path.open.tooltip': 'Open in the default app', + 'path.more': 'More ways to open', + 'path.defaultApp': 'Open in default app', + 'path.reveal': 'Show file location', + 'path.unpreviewable': 'Open in default app', + 'path.openError': 'Could not open. Try again.', + 'path.revealError': 'Could not show the file location. Try again.', ...PRODUCT_NAMES, 'app.finder': 'Finder', 'app.explorer': 'File Explorer', diff --git a/packages/client/ui-open-in-app/src/client/open-failure-toast.tsx b/packages/client/ui-open-in-app/src/client/open-failure-toast.tsx new file mode 100644 index 0000000000..721e2b9f6f --- /dev/null +++ b/packages/client/ui-open-in-app/src/client/open-failure-toast.tsx @@ -0,0 +1,25 @@ +/** Per-control failure banner for path gestures. */ +import { useRef, useState } from 'react' +import type { ReactNode } from 'react' +import { IconWarningOutline16, Toast } from '@deepseek-ai/dsh-client-ui-primitives' + +/** + * Transient failure banner owned by the control that initiated the gesture, + * so one failed request announces once, from the control the user pressed. + * @returns `toast` to render inside the control and `show` to announce one + * failure with resolved copy; announcing again replays the banner. + */ +export function useOpenFailureToast(): { toast: ReactNode; show: (text: string) => void } { + // The seq keys the banner so the same failure text replays instead of staying silently in place. + const seq = useRef(0) + const [banner, setBanner] = useState<{ seq: number; text: string } | null>(null) + return { + toast: banner === null + ? null + : } onDone={() => { setBanner(null) }} />, + show: (text) => { + seq.current += 1 + setBanner({ seq: seq.current, text }) + }, + } +} diff --git a/packages/client/ui-open-in-app/src/client/open-path.ts b/packages/client/ui-open-in-app/src/client/open-path.ts new file mode 100644 index 0000000000..161fcf104f --- /dev/null +++ b/packages/client/ui-open-in-app/src/client/open-path.ts @@ -0,0 +1,75 @@ +/** + * Default-application actions on one Host file path, over the Session Remote: + * whether this Host can hand a path to a desktop, and the open or reveal call. + * The desktop answer is read once per page; a failed read renders no control. + */ +import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' +import type { SessionOpenWorkspacePathRequest } from '@deepseek-ai/dsh-api-session-controller/types' + +/** What a path gesture asks of the Host desktop: the default application, or the file manager showing the file. */ +export type OpenInAppPathAction = 'open' | 'reveal' + +/** Failure kind of one settled path gesture, for the initiating control to announce. */ +export type OpenInAppPathFailure = 'openError' | 'revealError' + +/** The slice of the Client Remote the path actions call. */ +export interface OpenInAppPathRemote { + readonly session: { + /** Whether the Host can hand a workspace path to a native desktop. */ + canOpenWorkspacePath(): Promise> + /** Open one Host path in its default application, or reveal it in the file manager. */ + openWorkspacePath(request: SessionOpenWorkspacePathRequest, signal?: AbortSignal): Promise> + } +} + +/** Page-lifetime desktop availability and the open/reveal carrier shared by every path control. */ +export class OpenInAppPathController { + /** Whether the Host desktop can open paths; null until the Host answered, false also after a failed read. */ + readonly desktop: SnapshotStore = createSnapshotStore(null) + private loading: Promise | undefined + + /** + * @param remote - the Session Remote namespace answering availability and running gestures. + */ + constructor(private readonly remote: OpenInAppPathRemote) {} + + /** + * Read desktop availability once per controller life; concurrent calls share the read. + * @returns after availability is published. + */ + load(): Promise { + this.loading ??= this.run() + return this.loading + } + + /** + * Open one Host path in its default application, or reveal it in the file manager. + * @param path - absolute path on the Host, as the file's metadata reports it. + * @param action - default application open, or file-manager reveal. + * @returns the failure kind to announce, or `null` once the Host acknowledged. + */ + async openPath(path: string, action: OpenInAppPathAction): Promise { + const request: SessionOpenWorkspacePathRequest = action === 'reveal' ? { path, action } : { path } + let ok = false + try { + ok = (await this.remote.session.openWorkspacePath(request)).ok + } catch { + // Swallows carrier rejections: a Host that cannot be reached failed the + // gesture like a Host that refused it, and the control announces that. + } + return ok ? null : action === 'open' ? 'openError' : 'revealError' + } + + private async run(): Promise { + let available = false + try { + const result = await this.remote.session.canOpenWorkspacePath() + available = result.ok && result.value + } catch { + // Swallows carrier rejections: an unreachable Host reads as no desktop, + // so the preview shows no path control rather than a broken one. + } + this.desktop.set(available) + } +} diff --git a/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts b/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts index eefdae245d..9b289c7b64 100644 --- a/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts @@ -1,7 +1,7 @@ /** - * Browser-half lifecycle over the real SlotRegistry: the dictionary and - * header-slot registrations with fiber teardown proving removal (HMR safety) - * and the injected controller face. + * Browser-half lifecycle over the real SlotRegistry: the dictionary, + * header-slot, and document-preview path registrations with fiber teardown + * proving removal (HMR safety) and the injected controller faces. */ import { Context } from '@deepseek-ai/cordis' @@ -9,16 +9,26 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' -import { apply, inject, type OpenInAppActionInjected } from '../src/client/index.ts' +import { apply, inject, type OpenInAppActionInjected, type OpenPathInjected } from '../src/client/index.ts' import { apply as nodeApply } from '../src/index.ts' import { OpenInAppAction } from '../src/client/OpenInAppAction.tsx' +import { OpenPathAction } from '../src/client/OpenPathAction.tsx' +import { OpenPathEmptyAction } from '../src/client/OpenPathEmptyAction.tsx' import { en, NS, zh } from '../src/client/locales.ts' afterEach(() => { vi.unstubAllGlobals() }) -/** Boot the browser half over a real slot tree that declares the header list. */ +/** The Session Remote slice the path controls call; answers a desktop and acknowledges every gesture. */ +const remote = { + session: { + canOpenWorkspacePath: vi.fn(async () => ({ ok: true as const, value: true })), + openWorkspacePath: vi.fn(async () => ({ ok: true as const, value: { opened: true as const } })), + }, +} + +/** Boot the browser half over a real slot tree that declares the header list and the document-preview seats. */ async function bench(): Promise<{ ctx: Context; fiber: ReturnType }> { const ctx = new Context() await ctx.plugin(SlotRegistry).await() @@ -26,10 +36,14 @@ async function bench(): Promise<{ ctx: Context; fiber: ReturnType null) ctx.provide('sessions', {}) ctx.provide('locale', new LocaleRuntime(ctx)) + ctx.provide('remote', remote as never) + ctx.provide('remote.session', remote.session as never) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() return { ctx, fiber } @@ -41,7 +55,29 @@ function headerEntryIds(ctx: Context): (string | undefined)[] { describe('open-in-app browser half', () => { it('declares the services it binds', () => { - expect(inject).toEqual(['sessions', 'slots', 'locale']) + expect(inject).toEqual(['sessions', 'slots', 'locale', 'remote', 'remote.session']) + }) + + it('registers both document-preview path controls behind one desktop answer, and fiber teardown removes them', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ apps: [] }), { status: 200 }))) + const { ctx, fiber } = await bench() + const header = ctx.slots.entries('sidebar.right.tab.document.actions')[0] + const empty = ctx.slots.entries('sidebar.right.tab.document.unpreviewable')[0] + expect(header?.component).toBe(OpenPathAction) + expect(empty?.component).toBe(OpenPathEmptyAction) + expect(header?.options).toMatchObject({ id: 'open-in-app' }) + const face = (header?.inject as unknown as () => OpenPathInjected)() + const emptyFace = (empty?.inject as unknown as () => OpenPathInjected)() + expect(emptyFace.hooks.openInAppDesktop).toBe(face.hooks.openInAppDesktop) + expect(face.hooks.openInAppDesktop.getSnapshot()).toBeNull() + await Promise.all([face.loadDesktop(), emptyFace.loadDesktop()]) + expect(remote.session.canOpenWorkspacePath).toHaveBeenCalledOnce() + expect(face.hooks.openInAppDesktop.getSnapshot()).toBe(true) + expect(await face.openPath('/w/clip.mp4', 'reveal')).toBeNull() + expect(remote.session.openWorkspacePath).toHaveBeenLastCalledWith({ path: '/w/clip.mp4', action: 'reveal' }) + await fiber.dispose() + expect(ctx.slots.entries('sidebar.right.tab.document.actions').map(entry => entry.options.id)).not.toContain('open-in-app') + expect(ctx.slots.entries('sidebar.right.tab.document.unpreviewable').map(entry => entry.options.id)).not.toContain('open-in-app') }) it('registers the header split button, and fiber teardown removes it (HMR safety)', async () => { diff --git a/packages/client/ui-open-in-app/tests/open-path-action.client.spec.tsx b/packages/client/ui-open-in-app/tests/open-path-action.client.spec.tsx new file mode 100644 index 0000000000..819b6473e2 --- /dev/null +++ b/packages/client/ui-open-in-app/tests/open-path-action.client.spec.tsx @@ -0,0 +1,132 @@ +// @vitest-environment jsdom +/** + * The two document-preview path controls: hidden until the Host reports a + * desktop, busy only for their own gesture, and announcing a failure once + * through their own toast. + */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { OpenPathAction, type OpenPathActionProps } from '../src/client/OpenPathAction.tsx' +import { OpenPathEmptyAction, type OpenPathEmptyActionProps } from '../src/client/OpenPathEmptyAction.tsx' +import type { OpenInAppPathAction, OpenInAppPathFailure } from '../src/client/open-path.ts' +import { zh } from '../src/client/locales.ts' + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + vi.useRealTimers() +}) + +const t = makeTranslate(zh) +const FILE = { sessionId: 's-1' as SessionId, path: 'work/clip.mp4' } +const ABSOLUTE_PATH = '/host/project/work/clip.mp4' + +interface Bench { + props: OpenPathActionProps & OpenPathEmptyActionProps + desktop: ReturnType> + loadDesktop: ReturnType + openPath: ReturnType Promise>> +} + +function bench(over: { desktop?: boolean | null; openPath?: Bench['openPath'] } = {}): Bench { + const desktop = createSnapshotStore(over.desktop === undefined ? true : over.desktop) + const loadDesktop = vi.fn(async () => {}) + const openPath = over.openPath ?? vi.fn(async () => null) + function useSelector(source: { getSnapshot(): T }): (select: (value: T) => R) => R { + return select => select(source.getSnapshot()) + } + const props = { + file: FILE, + absolutePath: ABSOLUTE_PATH, + useOpenInAppDesktop: useSelector(desktop), + loadDesktop, + openPath, + t, + } as unknown as Bench['props'] + return { props, desktop, loadDesktop, openPath } +} + +describe('OpenPathAction visibility', () => { + it('renders nothing and asks for the desktop answer while it is unknown, and nothing without a desktop', () => { + const unknown = bench({ desktop: null }) + const { container } = render() + expect(container.innerHTML).toBe('') + expect(unknown.loadDesktop).toHaveBeenCalledOnce() + cleanup() + const absent = bench({ desktop: false }) + expect(render().container.innerHTML).toBe('') + expect(absent.loadDesktop).not.toHaveBeenCalled() + }) +}) + +describe('OpenPathAction gestures', () => { + it('opens the file in its default application from the main button and reveals it from the menu', async () => { + const b = bench() + render() + const main = screen.getByRole('button', { name: zh['path.open'] }) + await act(async () => { fireEvent.click(main) }) + expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'open') + fireEvent.click(screen.getByRole('button', { name: zh['path.more'] })) + await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: zh['path.reveal'] })) }) + expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'reveal') + expect(screen.queryByRole('menu')).toBeNull() + }) + + it('offers the default application from the menu too, and Escape closes the menu without a gesture', async () => { + const b = bench() + render() + const more = screen.getByRole('button', { name: zh['path.more'] }) + fireEvent.click(more) + expect(more.getAttribute('aria-expanded')).toBe('true') + fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' }) + expect(screen.queryByRole('menu')).toBeNull() + expect(b.openPath).not.toHaveBeenCalled() + fireEvent.click(more) + await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: zh['path.defaultApp'] })) }) + expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'open') + }) + + it('disables both halves while its own gesture settles and leaves no failure on the control', async () => { + const settled = Promise.withResolvers() + const b = bench({ openPath: vi.fn(() => settled.promise) }) + const { container } = render() + const main = screen.getByRole('button', { name: zh['path.open'] }) + fireEvent.click(main) + expect(main).toHaveProperty('disabled', true) + expect(screen.getByRole('button', { name: zh['path.more'] })).toHaveProperty('disabled', true) + expect(container.querySelector('[data-open-path]')?.getAttribute('data-state')).toBe('busy') + fireEvent.click(main) + expect(b.openPath).toHaveBeenCalledOnce() + await act(async () => { settled.resolve('openError'); await settled.promise }) + expect(main).toHaveProperty('disabled', false) + expect(container.querySelector('[data-open-path]')?.getAttribute('data-state')).toBe('idle') + expect(screen.getByRole('alert').textContent).toContain(zh['path.openError']) + }) +}) + +describe('OpenPathEmptyAction', () => { + it('renders nothing without a desktop and opens the file in its default application with one', async () => { + const absent = bench({ desktop: false }) + expect(render().container.innerHTML).toBe('') + cleanup() + const b = bench() + render() + await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.unpreviewable'] })) }) + expect(b.openPath).toHaveBeenCalledWith(ABSOLUTE_PATH, 'open') + expect(screen.queryByRole('alert')).toBeNull() + }) + + it('announces a failed open once through its own toast, which leaves after its hold and fade', async () => { + vi.useFakeTimers() + const b = bench({ openPath: vi.fn(async () => 'openError' as const) }) + render() + await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.unpreviewable'] })) }) + expect(screen.getAllByRole('alert')).toHaveLength(1) + expect(screen.getByRole('alert').textContent).toContain(zh['path.openError']) + act(() => { vi.advanceTimersByTime(4_000) }) + expect(screen.queryByRole('alert')).toBeNull() + }) +}) diff --git a/packages/client/ui-open-in-app/tests/open-path.client.spec.ts b/packages/client/ui-open-in-app/tests/open-path.client.spec.ts new file mode 100644 index 0000000000..2e8560f7cf --- /dev/null +++ b/packages/client/ui-open-in-app/tests/open-path.client.spec.ts @@ -0,0 +1,71 @@ +/** Path controller behavior: the once-per-page desktop read and the open/reveal outcomes over the Session Remote. */ + +import { describe, expect, it, vi } from 'vitest' +import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import type { SessionOpenWorkspacePathRequest } from '@deepseek-ai/dsh-api-session-controller/types' +import { OpenInAppPathController, type OpenInAppPathRemote } from '../src/client/open-path.ts' + +type SessionRemote = OpenInAppPathRemote['session'] + +function remoteOf(over: Partial = {}): OpenInAppPathRemote { + return { + session: { + canOpenWorkspacePath: async () => ({ ok: true, value: true }), + openWorkspacePath: async () => ({ ok: true, value: { opened: true } }), + ...over, + }, + } +} + +describe('OpenInAppPathController desktop availability', () => { + it('starts unanswered and shares one read across concurrent loads', async () => { + const canOpenWorkspacePath = vi.fn(async () => ({ ok: true as const, value: true })) + const controller = new OpenInAppPathController(remoteOf({ canOpenWorkspacePath })) + expect(controller.desktop.getSnapshot()).toBeNull() + await Promise.all([controller.load(), controller.load()]) + await controller.load() + expect(canOpenWorkspacePath).toHaveBeenCalledOnce() + expect(controller.desktop.getSnapshot()).toBe(true) + }) + + it('publishes no desktop for a refusing Host, a failed answer, and a rejecting carrier', async () => { + const refusing = new OpenInAppPathController(remoteOf({ canOpenWorkspacePath: async () => ({ ok: true, value: false }) })) + await refusing.load() + expect(refusing.desktop.getSnapshot()).toBe(false) + + const failed = new OpenInAppPathController(remoteOf({ + canOpenWorkspacePath: async () => ({ ok: false, error: new RemoteError('gateway/internal', 'boom', {}) }), + })) + await failed.load() + expect(failed.desktop.getSnapshot()).toBe(false) + + const rejecting = new OpenInAppPathController(remoteOf({ canOpenWorkspacePath: () => Promise.reject(new Error('down')) })) + await rejecting.load() + expect(rejecting.desktop.getSnapshot()).toBe(false) + }) +}) + +describe('OpenInAppPathController gestures', () => { + it('sends the default-application open without an action and the reveal with one', async () => { + const openWorkspacePath = vi.fn(async (_request: SessionOpenWorkspacePathRequest, _signal?: AbortSignal) => + ({ ok: true as const, value: { opened: true as const } })) + const controller = new OpenInAppPathController(remoteOf({ openWorkspacePath })) + expect(await controller.openPath('/w/clip.mp4', 'open')).toBeNull() + expect(await controller.openPath('/w/clip.mp4', 'reveal')).toBeNull() + expect(openWorkspacePath.mock.calls.map(call => call[0])).toEqual([ + { path: '/w/clip.mp4' }, + { path: '/w/clip.mp4', action: 'reveal' }, + ]) + }) + + it('names the failed gesture for a refused answer and for a rejecting carrier', async () => { + const refused = new OpenInAppPathController(remoteOf({ + openWorkspacePath: async () => ({ ok: false, error: new RemoteError('gateway/internal', 'boom', {}) }), + })) + expect(await refused.openPath('/w/clip.mp4', 'open')).toBe('openError') + expect(await refused.openPath('/w/clip.mp4', 'reveal')).toBe('revealError') + + const rejecting = new OpenInAppPathController(remoteOf({ openWorkspacePath: () => Promise.reject(new Error('down')) })) + expect(await rejecting.openPath('/w/clip.mp4', 'open')).toBe('openError') + }) +}) diff --git a/packages/client/ui-open-in-app/tsconfig.json b/packages/client/ui-open-in-app/tsconfig.json index 4264bb7cab..55f2ded3e1 100644 --- a/packages/client/ui-open-in-app/tsconfig.json +++ b/packages/client/ui-open-in-app/tsconfig.json @@ -11,6 +11,12 @@ { "path": "../../../vendor/cordis" }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, { "path": "../../api/session-controller/tsconfig.client.json" }, @@ -35,6 +41,9 @@ { "path": "../ui-session" }, + { + "path": "../ui-sidebar-documentpreview" + }, { "path": "../ui-slots" } diff --git a/packages/client/ui-sidebar-documentpreview/README.i18n.yaml b/packages/client/ui-sidebar-documentpreview/README.i18n.yaml index 6bf77e5972..07be1c50ac 100644 --- a/packages/client/ui-sidebar-documentpreview/README.i18n.yaml +++ b/packages/client/ui-sidebar-documentpreview/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-sidebar-documentpreview/README.md -README.md: d4e114aa6e12171d61f8a5284fdbe923916fe0d9 -README.zh.md: 32cb704d29fd0009fdf7a51235617c25029295f0 +README.md: c0cb4796036d3ca20e7f3bbd239c9816a177feeb +README.zh.md: 7b47c00b85b6c128946e3070d805b52b2a0781ef diff --git a/packages/client/ui-sidebar-documentpreview/README.md b/packages/client/ui-sidebar-documentpreview/README.md index d4e114aa6e..c0cb479603 100644 --- a/packages/client/ui-sidebar-documentpreview/README.md +++ b/packages/client/ui-sidebar-documentpreview/README.md @@ -1,5 +1,5 @@ --- -description: "Document previews in the right Sidebar: shared file loading and controls, selectable Markdown, code, image, PDF and HTML renderers, and plain-text fallback." +description: "Document previews in the right Sidebar: shared file loading and controls, selectable Markdown, code, image, PDF and HTML renderers, plain-text fallback, and child slots handing a file to the Host desktop." kind: "package-reference" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Preview readable files in the right Sidebar and choose among registered renderers without opening another tab. Markdown and code receive accumulated text pages; PDF, HTML, and common images receive complete bytes; unknown file extensions use plain text. The tab owns loading, file status, renderer selection, wrap, and reload, while document bodies register through the same metadata registry and child slot. The Sidebar tab kind is `text`. +Preview readable files in the right Sidebar and choose among registered renderers without opening another tab. Markdown and code receive accumulated text pages; PDF, HTML, and common images receive complete bytes; unknown file extensions use plain text. The tab owns loading, file status, renderer selection, wrap, and reload, while document bodies register through the same metadata registry and child slot. Two further child slots let another plugin hand the previewed file to the Host desktop from the header and from the empty state of a file the preview cannot render. The Sidebar tab kind is `text`. ## Table of Contents @@ -27,7 +27,7 @@ Preview readable files in the right Sidebar and choose among registered renderer ## What it registers - **The type** — `ctx.sidebarRightTabs.register(...)` with id `@deepseek-ai/dsh-client-ui-sidebar-documentpreview` (this implementation's identity in the tab system, and the key its body registers under), kind `text`, pattern `dsh-resource://file/**`, band `fallback`. `canOpen` accepts only Session addresses, whose paths may be relative or absolute; bare `absolute` addresses are not claimed. A type registered at the `extension` or `builtin` band for a narrower pattern (say `*.png`) takes those addresses; other supported files land here. The whole address is the content identity, so two files with one name in different directories, or one path under two sessions, are two tabs; the decoded basename is the tab title, and the keyed `sidebar.right.pane.tab.title` seat places its extension-specific `FileTypeIcon` before that title. -- **The body** — the keyed `sidebar.right.pane.tab` seat under the type's id. Its fixed header shows the Host's absolute path when available, otherwise the requested path; directories use tertiary label colour, the name uses primary label colour, and a clipped path retains and fades toward its final segment while its tooltip exposes the full value. A dropdown selects among matching renderers and plain text; a suffix declared binary (bitmap images, PDF) drops the plain-text fallback, and a single remaining candidate renders no viewer control at all. A known binary container suffix with no registered renderer (audio, video, archives, office documents) shows an unsupported empty state under the path header — the file-type icon and one explanatory line — and never issues a read. A wrap toggle appears only when the selected renderer declares `wrap: true`; its glyph describes the mode the click selects, and the per-tab preference starts on. Reload stays in this header, not the Sidebar's tab strip. The body reaches every pane edge; each renderer owns its content inset and may own an inner scrollport. This intentionally differs from the Files tab's 2px right-side scrollbar offset: previews keep the full pane width so edge-to-edge HTML and code scrollports end at the pane edge. +- **The body** — the keyed `sidebar.right.pane.tab` seat under the type's id. Its fixed header shows the Host's absolute path when available, otherwise the requested path; directories use tertiary label colour, the name uses primary label colour, and a clipped path retains and fades toward its final segment while its tooltip exposes the full value. A dropdown selects among matching renderers and plain text; a suffix declared binary (bitmap images, PDF) drops the plain-text fallback, and a single remaining candidate renders no viewer control at all. A known binary container suffix with no registered renderer (audio, video, archives, office documents) shows an unsupported empty state under the path header — the file-type icon and one explanatory line — and never issues a read. Two Session-scoped list child slots hand the previewed file to other plugins once its metadata reports a Host path, both with `file` and `absolutePath` as owner props: `sidebar.right.tab.document.actions` renders after the header's own controls in every state that shows the header, and `sidebar.right.tab.document.unpreviewable` renders in the unsupported empty state and in the empty state of a readable file the preview cannot render (`not-text`, `too-large`), where Retry would otherwise stand; a carrier or unclassified read failure keeps Retry, and a missing or non-regular path offers only its explanation. The shipped occupant of both is [`ui-open-in-app`](../ui-open-in-app/README.md). A wrap toggle appears only when the selected renderer declares `wrap: true`; its glyph describes the mode the click selects, and the per-tab preference starts on. Reload stays in this header, not the Sidebar's tab strip. The body reaches every pane edge; each renderer owns its content inset and may own an inner scrollport. This intentionally differs from the Files tab's 2px right-side scrollbar offset: previews keep the full pane width so edge-to-edge HTML and code scrollports end at the pane edge. - **Shared loading and view state**, session-scoped and bucketed by tab id. The store holds accumulated pages or complete bytes, read and observed versions, loading/failure state, renderer choice, scroll offset, wrap, and the answered navigation revision. The ordinary inject face calls Remote readers and writes through declared store actions. Reloads and loading-mode changes retire older requests; the tab's abort signal forgets its state. Document implementations register metadata with `ctx.documentPreviews.register({ id, extensions, binaryExtensions?, priority, title, loading, wrap? })` and a body under the same `id` in the keyed, Session-scoped `sidebar.right.tab.document` child slot. `binaryExtensions` names the suffixes among `extensions` whose bytes are not readable text; a file matching one loses the plain-text fallback among its viewer choices. Own both registrations with effects and wait for the child slot through `ctx.slots.inject`. Bodies receive `resourceAddress`, prepared `content`, `wrap`, `scrollportRef`, and the standard `useTabInfo`/`useResource` hooks; they do not receive a custom resource loader. A renderer that owns an inner scrolling element attaches `scrollportRef` to it, and the owner returns to the shared body when that element unmounts. Metadata declares `loading: 'text-pages'` or `'bytes-complete'`. The registry retains all matching alternatives: `extension` (the default) ranks above `builtin`, then longer suffixes rank first, then registration order. The dropdown preserves a selected implementation while it remains available; removing it selects the next candidate. Builtin bodies use these same registrations. @@ -43,7 +43,7 @@ A tab uses the Session address built by `fileAddressFor`, carrying a relative or The body reads its record, navigation and lifetime through `useTabInfo().tab`. `useResource<'file'>(tab.contentId)` supplies metadata; ordinary inject callbacks supply content reads: - The resource snapshot contains only `status`, `value`, and `failure`; `value` is `WorkspaceFileStat` metadata. Content reads do not wait for the first metadata frame once the provider is available. Observation failures take precedence over Preview's change notice; neither automatically replaces loaded content. -- **Text pages** — plain text, Markdown, and code read through an inject callback to `remote.workspaceFiles.read(sessionId, path, { offset }, signal)`. The first mount reads page one; scrolling to the body end or **Load more** requests the next page until `eof`. The owner delivers the accumulated prefix as `{ kind: 'text', text, pages, eof }`, including source offsets and line counts. Markdown and code render that prefix incrementally; they do not render each page as a separate document. A newer-version page past page one restarts from the beginning rather than mixing versions. A failure before any content fills the body with the file-type icon, explanation, and retry; a later failure retains loaded content and adds the retry below it. +- **Text pages** — plain text, Markdown, and code read through an inject callback to `remote.workspaceFiles.read(sessionId, path, { offset }, signal)`. The first mount reads page one; scrolling to the body end or **Load more** requests the next page until `eof`. The owner delivers the accumulated prefix as `{ kind: 'text', text, pages, eof }`, including source offsets and line counts. Markdown and code render that prefix incrementally; they do not render each page as a separate document. A newer-version page past page one restarts from the beginning rather than mixing versions. A failure before any content fills the body with the file-type icon, the explanation, and the recourse the failure names (Retry, the unpreviewable child slot, or nothing); a later failure retains loaded content and adds the retry below it. - **Complete bytes** — PDF, HTML, and common images use an inject callback to `remote.workspaceFiles.readAll(sessionId, path, signal)`. `rpc.ts` decodes the wire base64 into `data: Uint8Array` for `{ kind: 'bytes', data }`. The Host's `maxFileBytes` cap rejects oversized files rather than truncating them. PDF copies retained bytes before worker transfer, keeping the Preview buffer usable. Bytes stay in transient view state, never persisted layouts or Session JSONL. Loading-mode changes retire previous results. - **Reload** — only the current Preview tab rereads through its Remote callbacks, preserving its scroll preference and retiring older requests. Its change notice compares the read version and the observation captured at read start with later `resource.value.version`; an already observed version does not become a new change after refresh. Reads neither refresh shared metadata nor clear another tab's notice. diff --git a/packages/client/ui-sidebar-documentpreview/README.zh.md b/packages/client/ui-sidebar-documentpreview/README.zh.md index 32cb704d29..7b47c00b85 100644 --- a/packages/client/ui-sidebar-documentpreview/README.zh.md +++ b/packages/client/ui-sidebar-documentpreview/README.zh.md @@ -1,5 +1,5 @@ --- -description: "右侧 Sidebar 的文档预览:共享文件加载与控件,可选 Markdown、代码、图片、PDF 和 HTML 渲染器,并以纯文本兜底。" +description: "右侧 Sidebar 的文档预览:共享文件加载与控件,可选 Markdown、代码、图片、PDF 和 HTML 渲染器,以纯文本兜底,并提供把文件交给 Host 桌面的子 slot。" kind: "package-reference" --- @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -在右侧 Sidebar 预览可读文件,无需另开 tab 即可切换已注册的渲染器。Markdown 和代码接收累计文本页;PDF、HTML 和常见图片接收完整字节;未知文件扩展名使用纯文本。tab 负责加载、文件状态、渲染器选择、换行和重新载入,文档正文通过同一元数据注册表与子 slot 注册。Sidebar tab 的 kind 为 `text`。 +在右侧 Sidebar 预览可读文件,无需另开 tab 即可切换已注册的渲染器。Markdown 和代码接收累计文本页;PDF、HTML 和常见图片接收完整字节;未知文件扩展名使用纯文本。tab 负责加载、文件状态、渲染器选择、换行和重新载入,文档正文通过同一元数据注册表与子 slot 注册。另有两个子 slot 让别的插件从头部和从无法渲染文件的空态把当前文件交给 Host 桌面。Sidebar tab 的 kind 为 `text`。 ## 目录 @@ -27,7 +27,7 @@ kind: "package-reference" ## 注册了什么 - **类型** —— `ctx.sidebarRightTabs.register(...)`,id 为 `@deepseek-ai/dsh-client-ui-sidebar-documentpreview`(这个实现在 tab 系统中的身份,也是其正文注册所用的键),kind `text`,pattern `dsh-resource://file/**`,档位 `fallback`。`canOpen` 只接受 Session 地址,其中路径可为相对或绝对路径;不认领裸 `absolute` 地址。在 `extension` 或 `builtin` 档以更窄 pattern(比如 `*.png`)注册的类型接走那些地址;其他受支持文件落到这里。整个地址就是内容身份,所以不同目录下同名的两个文件、或同一路径在两个会话之下,是两个 tab;解码后的 basename 是 tab 标题,keyed slot `sidebar.right.pane.tab.title` 会在标题前放置按扩展名选择的 `FileTypeIcon`。 -- **正文** —— keyed slot `sidebar.right.pane.tab`,键为类型的 id。固定头部在可用时显示 Host 的绝对路径,否则显示请求路径;目录使用三级标签色,文件名使用一级标签色,路径过长时保留末段并向开头淡出,提示中仍提供完整值。下拉菜单可在匹配的渲染器与纯文本间切换;声明为二进制的后缀(位图图片、PDF)不提供纯文本兜底,只剩一个候选时完全不渲染查看器控件。已知的二进制容器后缀(音频、视频、压缩包、office 文档)没有注册渲染器时,在路径头部下方显示不支持预览的空态——文件类型图标加一行说明——并且不会发起读取。仅当所选渲染器声明 `wrap: true` 时显示换行开关;图标表示点击后切换到的模式,该偏好按 tab 保存,初始开启。重新载入仍在此头部,不放入 Sidebar 的 tab 条。正文贴合格的每条边,各渲染器自行提供内容留白,并可拥有内部滚动区。这与 Files tab 右侧预留 2px 滚动条间距的布局有意不同:Preview 使用格的完整宽度,使贴边 HTML 与代码滚动区终止于格的边缘。 +- **正文** —— keyed slot `sidebar.right.pane.tab`,键为类型的 id。固定头部在可用时显示 Host 的绝对路径,否则显示请求路径;目录使用三级标签色,文件名使用一级标签色,路径过长时保留末段并向开头淡出,提示中仍提供完整值。下拉菜单可在匹配的渲染器与纯文本间切换;声明为二进制的后缀(位图图片、PDF)不提供纯文本兜底,只剩一个候选时完全不渲染查看器控件。已知的二进制容器后缀(音频、视频、压缩包、office 文档)没有注册渲染器时,在路径头部下方显示不支持预览的空态——文件类型图标加一行说明——并且不会发起读取。两个 Session 作用域的 list 子 slot 在文件元数据报出 Host 路径后把当前文件交给其他插件,owner props 都是 `file` 与 `absolutePath`:`sidebar.right.tab.document.actions` 在每个显示头部的状态里渲染在头部自有控件之后;`sidebar.right.tab.document.unpreviewable` 渲染在不支持预览的空态里,以及可读但本预览无法渲染的文件(`not-text`、`too-large`)的空态里,占据原本放重试的位置;载体或未分类的读取失败仍保留重试,不存在或非普通文件的路径只给说明。两者已发布的占位者都是 [`ui-open-in-app`](../ui-open-in-app/README.zh.md)。仅当所选渲染器声明 `wrap: true` 时显示换行开关;图标表示点击后切换到的模式,该偏好按 tab 保存,初始开启。重新载入仍在此头部,不放入 Sidebar 的 tab 条。正文贴合格的每条边,各渲染器自行提供内容留白,并可拥有内部滚动区。这与 Files tab 右侧预留 2px 滚动条间距的布局有意不同:Preview 使用格的完整宽度,使贴边 HTML 与代码滚动区终止于格的边缘。 - **共享加载与视图状态**,会话作用域、按 tab id 分桶。store 持有累计页或完整字节、读取与观察版本、加载/失败状态、渲染器选择、滚动位置、换行和已响应的导航 revision。普通 inject face 调用 Remote 读取,并经声明的 store action 写入。重新载入和加载模式变化会淘汰旧请求;tab 的中止信号清理其状态。 文档实现在 `ctx.documentPreviews.register({ id, extensions, binaryExtensions?, priority, title, loading, wrap? })` 注册元数据,并以相同 `id` 向 keyed、Session 作用域的子 slot `sidebar.right.tab.document` 注册正文。`binaryExtensions` 列出 `extensions` 中字节不可按文本阅读的后缀;匹配这类后缀的文件在其查看器选项中不再提供纯文本兜底。两处注册都由 effect 持有,通过 `ctx.slots.inject` 等待子 slot。正文接收 `resourceAddress`、准备好的 `content`、`wrap`、`scrollportRef` 和标准 `useTabInfo`/`useResource` 钩子,不接收自定义资源加载器。拥有内部滚动元素的渲染器把 `scrollportRef` 挂到该元素上;该元素卸载后,owner 恢复使用共享正文。元数据声明 `loading: 'text-pages'` 或 `'bytes-complete'`。注册表保留所有匹配备选:`extension`(默认)优先于 `builtin`,随后按更长的后缀、再按注册顺序排列。所选实现仍可用时,下拉选择保持不变;移除后选择下一个候选。内置正文也使用相同注册方式。 @@ -43,7 +43,7 @@ tab 使用 `fileAddressFor` 构造的 Session 地址,携带相对或绝对路 正文通过 `useTabInfo().tab` 读取记录、导航和生命周期。`useResource<'file'>(tab.contentId)` 提供元数据,普通 inject 回调提供内容读取: - 资源快照仅包含 `status`、`value` 和 `failure`;`value` 是 `WorkspaceFileStat` 元数据。提供方可用后,内容读取无需等待首个元数据帧。观察失败优先于 Preview 的变更提示显示;两者都不会自动替换已加载内容。 -- **文本页** —— 纯文本、Markdown 和代码通过 inject 回调调用 `remote.workspaceFiles.read(sessionId, path, { offset }, signal)`。首次挂载读取第一页;滚动到正文末尾或点击 **加载更多** 会读取下一页,直到 `eof`。owner 以 `{ kind: 'text', text, pages, eof }` 提供累计前缀,包含源码偏移和行数。Markdown 和代码增量渲染此前缀,不把每页当成独立文档。第一页之后到达的更新版本页会使读取从头开始,避免混合版本。尚无内容时,失败会以文件类型图标、说明与重试按钮填满正文;较晚的失败保留已有内容并在其下提供重试。 +- **文本页** —— 纯文本、Markdown 和代码通过 inject 回调调用 `remote.workspaceFiles.read(sessionId, path, { offset }, signal)`。首次挂载读取第一页;滚动到正文末尾或点击 **加载更多** 会读取下一页,直到 `eof`。owner 以 `{ kind: 'text', text, pages, eof }` 提供累计前缀,包含源码偏移和行数。Markdown 和代码增量渲染此前缀,不把每页当成独立文档。第一页之后到达的更新版本页会使读取从头开始,避免混合版本。尚无内容时,失败会以文件类型图标、说明和该失败对应的出路(重试、unpreviewable 子 slot,或什么都不给)填满正文;较晚的失败保留已有内容并在其下提供重试。 - **完整字节** —— PDF、HTML 和常见图片通过 inject 回调调用 `remote.workspaceFiles.readAll(sessionId, path, signal)`。`rpc.ts` 将线路上的 base64 解码为 `data: Uint8Array`,供 `{ kind: 'bytes', data }` 使用。Host 的 `maxFileBytes` 上限拒绝超大文件,不截断。PDF 在传给 worker 前复制保留的字节,使 Preview 缓冲区仍可使用。字节仅保存在临时视图状态中,绝不进入持久布局或 Session JSONL。加载模式变化会淘汰先前结果。 - **重新载入** —— 仅当前 Preview tab 通过自己的 Remote 回调重读,保留滚动偏好并淘汰旧请求。变更提示将读取版本及起读时的观察版本与后续 `resource.value.version` 比较;刷新前已观察到的版本不会被当成新变化。读取既不刷新共享元数据,也不清除其它 tab 的提示。 diff --git a/packages/client/ui-sidebar-documentpreview/src/client/TextPreview.tsx b/packages/client/ui-sidebar-documentpreview/src/client/TextPreview.tsx index 9430ec53a8..e98863b09c 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/TextPreview.tsx +++ b/packages/client/ui-sidebar-documentpreview/src/client/TextPreview.tsx @@ -18,7 +18,7 @@ import type { InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStor import { FileTypeIcon, IconRefreshOutline16, Menu, Tooltip, classifyFileType } from '@deepseek-ai/dsh-client-ui-primitives' import { pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' import type { TextInjected } from './face.ts' -import { failureLine } from './failure-line.ts' +import { emptyFailureRecourse, failureLine } from './failure-line.ts' import { IconNowrapFill16, IconWrapFill16 } from './icons.tsx' import { LoadingIndicator } from './LoadingIndicator.tsx' import { hostFileOf } from './rpc.ts' @@ -82,7 +82,7 @@ export interface TextPreviewInjected extends TextInjected { /** The body's composed props: the tab, its navigation, the shared store and face, and copy. */ export type TextPreviewProps = & PropsRuntime<'sidebar.right.pane.tab'> - & PropsRenderSlots<'sidebar.right.tab.document'> + & PropsRenderSlots<'sidebar.right.tab.document' | 'sidebar.right.tab.document.actions' | 'sidebar.right.tab.document.unpreviewable'> & PropsStore & InjectFace & PropsLocale<'sidebarDocumentPreview'> @@ -120,7 +120,10 @@ export function TextPreview({ const pathRef = useRef(null) const pathTextRef = useRef(null) const [menuOpen, setMenuOpen] = useState(false) - const displayPath = meta.value?.absolutePath ?? current?.complete?.absolutePath ?? file.path + const absolutePath = meta.value?.absolutePath ?? current?.complete?.absolutePath + const displayPath = absolutePath ?? file.path + // Contributions that hand the file to the Host wait for its Host path. + const fileOwner = absolutePath === undefined ? undefined : { file, absolutePath } usePathClipped(pathRef, pathTextRef, displayPath, state !== undefined) // Every tab of this type is a `file` resource address, so its params are the // `file` type's; the union is narrowed on the one field read, not validated. @@ -195,18 +198,21 @@ export function TextPreview({ }, [mode, loaded, current?.complete, current?.eof]) // A known binary suffix with no matching renderer never reads: no plain-text - // fallback, no viewer control, only the path and the unsupported line. + // fallback, no viewer control, only the path, the unsupported line, and the + // contributions that hand the file to the Host. if (selected === undefined && unviewable) { const { name: unsupportedName } = pathPartsOf(displayPath) return (
+ {fileOwner !== undefined && renderSlot('sidebar.right.tab.document.actions', fileOwner)}

{t('unsupportedFile')}

+ {fileOwner !== undefined && renderSlot('sidebar.right.tab.document.unpreviewable', fileOwner)}
@@ -315,6 +321,7 @@ export function TextPreview({ + {fileOwner !== undefined && renderSlot('sidebar.right.tab.document.actions', fileOwner)}
) : ( - // With no content, retry the selected renderer's read; metadata - // observation remains owned by the resource provider. + // With no content, the failure names its recourse: retry the + // selected renderer's read when a second read may resolve it, hand + // a file this preview cannot render to the unpreviewable + // contributions, and offer nothing for a path with nothing to show. + // Metadata observation remains owned by the resource provider.

{failureLine(t, current.failure)}

- + {emptyFailureRecourse(current.failure) === 'open' && fileOwner !== undefined + && renderSlot('sidebar.right.tab.document.unpreviewable', fileOwner)} + {emptyFailureRecourse(current.failure) === 'retry' && ( + + )}
))} {mode === 'text-pages' && current !== undefined && loaded.length > 0 && !current.eof && current.failure === undefined && ( diff --git a/packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts b/packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts index 11f7cd1c24..2f76b49bf4 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts +++ b/packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts @@ -2,6 +2,7 @@ import type { PropsRuntime, SlotHookFactory } from '@deepseek-ai/dsh-client-ui-slots' import type { UseSidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { RefCallback } from 'react' +import type { SessionFile } from '../rpc.ts' /** One loaded text window, retaining source line positions. */ export interface DocumentTextPage { @@ -41,6 +42,34 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } } } + /** + * Header toolbar contributions acting on the previewed file, rendered + * after the preview's own controls once the file's Host path is known. + */ + 'sidebar.right.tab.document.actions': { + kind: 'list' + scope: 'session' + owner: { + /** The previewed file: the Session the read runs under and the path handed to the Host. */ + readonly file: SessionFile + /** The file's absolute path on the Host, from its metadata. */ + readonly absolutePath: string + } + } + /** + * Empty-state contributions for a file this preview cannot render, + * offered where Retry would stand once the file's Host path is known. + */ + 'sidebar.right.tab.document.unpreviewable': { + kind: 'list' + scope: 'session' + owner: { + /** The previewed file: the Session the read runs under and the path handed to the Host. */ + readonly file: SessionFile + /** The file's absolute path on the Host, from its metadata. */ + readonly absolutePath: string + } + } } } diff --git a/packages/client/ui-sidebar-documentpreview/src/client/failure-line.ts b/packages/client/ui-sidebar-documentpreview/src/client/failure-line.ts index edf82ae9c6..625e3843cf 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/failure-line.ts +++ b/packages/client/ui-sidebar-documentpreview/src/client/failure-line.ts @@ -33,3 +33,25 @@ export function failureLine(t: TranslateNS<'sidebarDocumentPreview'>, failure: R default: return t('error.unavailable', { message: failure.message }) } } + +/** The action an empty preview offers beside its failure line. */ +export type EmptyFailureRecourse = 'open' | 'retry' | 'none' + +/** + * Choose the empty state's action for one settled read failure. + * @param failure - the settled Remote failure. + * @returns `open` for a readable file this preview cannot render, `none` for a + * path with nothing to show or open, `retry` for the rest: carrier and + * unclassified failures a second read may resolve. + */ +export function emptyFailureRecourse(failure: RemoteFailure): EmptyFailureRecourse { + switch (failure.code) { + case 'workspace-file/not-text': + case 'workspace-file/too-large': + return 'open' + case 'workspace-file/not-found': + case 'workspace-file/not-regular-file': + return 'none' + default: return 'retry' + } +} diff --git a/packages/client/ui-sidebar-documentpreview/src/client/index.ts b/packages/client/ui-sidebar-documentpreview/src/client/index.ts index ef76084e07..e677e0e0b5 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/index.ts +++ b/packages/client/ui-sidebar-documentpreview/src/client/index.ts @@ -100,6 +100,8 @@ export function apply(ctx: ClientContext): void { name: 'sidebar.right.pane.tab', key: TEXTPREVIEW_ID, locale: NS, store, children: { 'sidebar.right.tab.document': { kind: 'keyed', scope: 'session', inject: { hooks: { tabInfo: documentTabInfoFactory } } }, + 'sidebar.right.tab.document.actions': { kind: 'list', scope: 'session' }, + 'sidebar.right.tab.document.unpreviewable': { kind: 'list', scope: 'session' }, }, inject: (sessionId, actions): TextPreviewInjected => ({ ...face(sessionId, actions), hooks: { documentPreviews: source } }), }, diff --git a/packages/client/ui-sidebar-documentpreview/tests/document-toolbar.client.spec.tsx b/packages/client/ui-sidebar-documentpreview/tests/document-toolbar.client.spec.tsx index 0fa5189b44..8b31dce6ac 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/document-toolbar.client.spec.tsx +++ b/packages/client/ui-sidebar-documentpreview/tests/document-toolbar.client.spec.tsx @@ -25,7 +25,9 @@ function codeProps(h: ReturnType): TextPreviewProps { ...props, useDocumentPreviews: selector => selector([definition]), // This adapter only receives the concrete document slot, not an arbitrary generic key. - renderSlot: (_key, owner) => } t={key => key} />, + renderSlot: (key: string, owner: unknown) => key === 'sidebar.right.tab.document' + ? } t={key => key} /> + : null, } } @@ -104,18 +106,19 @@ describe('document toolbar', () => { await pending.promise }) h.bytes.mockReturnValueOnce(pending.promise) - const renderSlot = vi.fn(() => null) + const renderSlot = vi.fn((_key: string) => null) + const documentRenders = (): number => renderSlot.mock.calls.filter(call => call[0] === 'sidebar.right.tab.document').length const props: TextPreviewProps = { ...h.props(), useDocumentPreviews: selector => selector([binary]), renderSlot } const view = render() expect(view.getByRole('status').hasAttribute('data-document-loading')).toBe(true) expect(view.getByRole('status').getAttribute('aria-label')).toBe('loading') expect(view.container.querySelector('[data-textpreview-body]')?.firstElementChild).toBe(view.getByRole('status')) - expect(renderSlot).not.toHaveBeenCalled() + expect(documentRenders()).toBe(0) await act(async () => { pending.resolve(result) await pending.promise }) - expect(renderSlot).toHaveBeenCalled() + expect(documentRenders()).toBeGreaterThan(0) expect(view.queryByRole('status')).toBeNull() }) @@ -123,7 +126,7 @@ describe('document toolbar', () => { const h = harness() const result = { ok: true as const, value: { absolutePath: ABSOLUTE_PATH, version: 'v1', offset: 0, data: btoa('all'), bytes: 3, eof: true } } const read = h.bytes.mockResolvedValueOnce({ - ok: false, error: new RemoteError('workspace-file/not-found', 'Missing file', { path: ABSOLUTE_PATH }), + ok: false, error: new RemoteError('gateway/internal', 'socket closed', {}), }).mockResolvedValue(result) h.useResource.mockReturnValue({ status: 'loading', value: undefined, failure: undefined }) const props: TextPreviewProps = { @@ -245,6 +248,11 @@ describe('document toolbar', () => { expect(view.container.querySelector('[data-textpreview-path]')).not.toBeNull() expect(view.container.querySelector('[data-document-viewer-menu]')).toBeNull() expect(view.container.querySelector('[data-textpreview-tool="reload"]')).toBeNull() + // Both handoff seats receive the file once its Host path is known. + const header = view.container.querySelector('[data-textpreview-path]')?.parentElement + expect(header?.querySelector('[data-slot="sidebar.right.tab.document.actions"]')?.getAttribute('data-slot-path')).toBe(ABSOLUTE_PATH) + const empty = view.container.querySelector('[data-textpreview-unsupported]') + expect(empty?.querySelector('[data-slot="sidebar.right.tab.document.unpreviewable"]')?.getAttribute('data-slot-file')).toBe('work/clip.mp4') expect(h.read).not.toHaveBeenCalled() expect(h.bytes).not.toHaveBeenCalled() h.controller.abort() diff --git a/packages/client/ui-sidebar-documentpreview/tests/failure-line.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/failure-line.client.spec.ts index c43804d8ef..134cf3e822 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/failure-line.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/failure-line.client.spec.ts @@ -6,7 +6,7 @@ import type { RemoteFailure } from '@deepseek-ai/dsh-api-remotes/client' import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' // The namespace declaration `TranslateNS<'sidebarDocumentPreview'>` resolves against. import type {} from '../src/client/index.ts' -import { failureLine } from '../src/client/failure-line.ts' +import { emptyFailureRecourse, failureLine } from '../src/client/failure-line.ts' /** Key-echoing translate that also shows its parameters, so a formatted value is visible. */ const t: TranslateNS<'sidebarDocumentPreview'> = (key, params) => @@ -33,3 +33,20 @@ describe('failureLine', () => { expect(failureLine(t, failure('gateway/internal', {}, 'socket closed'))).toBe('error.unavailable(message=socket closed)') }) }) + +describe('emptyFailureRecourse', () => { + it('hands a readable file the preview cannot render to the Host', () => { + expect(emptyFailureRecourse(failure('workspace-file/not-text'))).toBe('open') + expect(emptyFailureRecourse(failure('workspace-file/too-large', { limit: 512 }))).toBe('open') + }) + + it('offers nothing for a path with nothing to show or open', () => { + expect(emptyFailureRecourse(failure('workspace-file/not-found'))).toBe('none') + expect(emptyFailureRecourse(failure('workspace-file/not-regular-file'))).toBe('none') + }) + + it('retries carrier and unclassified failures', () => { + expect(emptyFailureRecourse(failure('gateway/internal'))).toBe('retry') + expect(emptyFailureRecourse(failure('someday/a-new-code'))).toBe('retry') + }) +}) diff --git a/packages/client/ui-sidebar-documentpreview/tests/fixtures.client.ts b/packages/client/ui-sidebar-documentpreview/tests/fixtures.client.ts index 200626232c..a240fa7c9a 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/fixtures.client.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/fixtures.client.ts @@ -122,9 +122,18 @@ export function harness(script: Record> onTestFinished(() => { controller.abort() }) const tabActions = { openResource: vi.fn(), openTab: vi.fn(), close: vi.fn(), replace: vi.fn() } const definitions = [textBodyDefinition(() => t('viewer.text'))] - const renderSlot: TextPreviewProps['renderSlot'] = (_key, owner, opts) => createElement(TextBody, { - ...owner, useTabInfo: opts.hookContext, sessionId: SESSION, useResource, - } as unknown as DocumentPreviewProps) + // The document seat renders the plain body; the file-handoff seats render a + // marker carrying what the owner handed them. + const renderSlot: TextPreviewProps['renderSlot'] = (key: string, owner: unknown, opts?: { hookContext?: unknown }) => + key === 'sidebar.right.tab.document' + ? createElement(TextBody, { + ...owner as object, useTabInfo: opts?.hookContext, sessionId: SESSION, useResource, + } as unknown as DocumentPreviewProps) + : createElement('div', { + 'data-slot': key, + 'data-slot-file': (owner as { file: SessionFile }).file.path, + 'data-slot-path': (owner as { absolutePath: string }).absolutePath, + }) const props = (navigation: { params?: unknown; revision: number } = { revision: 1 }) => ({ useTabInfo: () => ({ sidebar: { expanded: true, fullscreen: false }, diff --git a/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx b/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx index 733bc6decc..b29d663a27 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx +++ b/packages/client/ui-sidebar-documentpreview/tests/text-preview.client.spec.tsx @@ -88,7 +88,9 @@ function codeProps(h: ReturnType, navigation: { params?: unknown return { ...props, useDocumentPreviews: selector => selector([definition]), - renderSlot: (_key, owner) => } t={key => key} />, + renderSlot: (key: string, owner: unknown) => key === 'sidebar.right.tab.document' + ? } t={key => key} /> + : null, } } @@ -253,15 +255,16 @@ describe('TextPreview — pages', () => { }) it('says why a page failed and retries the same page', async () => { - const h = harness({ 1: failure('workspace-file/not-text', { path: PATH }) }) + const h = harness({ 1: failure('gateway/internal', { path: PATH }) }) const view = render() await settle() const failed = view.container.querySelector('[data-textpreview-failed]') - expect(failed?.getAttribute('data-textpreview-failed')).toBe('workspace-file/not-text') - expect(view.container.textContent).toContain('error.notText') + expect(failed?.getAttribute('data-textpreview-failed')).toBe('gateway/internal') + expect(view.container.textContent).toContain('error.unavailable(message=boom)') // Nothing read yet: the failure stands as the body, under the file's type sheet. expect(failed?.querySelector('svg')).not.toBeNull() expect(view.container.querySelector('[data-textpreview-more]')).toBeNull() + expect(view.container.querySelector('[data-slot="sidebar.right.tab.document.unpreviewable"]')).toBeNull() h.script(1, page(1, ['one'], true)) click(view.container, '[data-textpreview-retry]') await settle() @@ -270,6 +273,40 @@ describe('TextPreview — pages', () => { expect(view.container.querySelector('[data-textpreview-failed]')).toBeNull() }) + it('hands a readable file it cannot render to the unpreviewable seat instead of Retry', async () => { + const h = harness({ 1: failure('workspace-file/not-text', { path: PATH }) }) + const view = render() + await settle() + const failed = view.container.querySelector('[data-textpreview-failed]') + expect(failed?.getAttribute('data-textpreview-failed')).toBe('workspace-file/not-text') + expect(view.container.textContent).toContain('error.notText') + expect(view.container.querySelector('[data-textpreview-retry]')).toBeNull() + const seat = failed?.querySelector('[data-slot="sidebar.right.tab.document.unpreviewable"]') + expect(seat?.getAttribute('data-slot-file')).toBe(PATH) + expect(seat?.getAttribute('data-slot-path')).toBe(ABSOLUTE_PATH) + // The header's own handoff seat receives the same file. + const actions = view.container.querySelector('[data-slot="sidebar.right.tab.document.actions"]') + expect(actions?.getAttribute('data-slot-path')).toBe(ABSOLUTE_PATH) + }) + + it('offers neither Retry nor a handoff for a path with nothing to show', async () => { + const h = harness({ 1: failure('workspace-file/not-found', { path: PATH }) }) + const view = render() + await settle() + expect(view.container.querySelector('[data-textpreview-failed]')?.getAttribute('data-textpreview-failed')).toBe('workspace-file/not-found') + expect(view.container.querySelector('[data-textpreview-retry]')).toBeNull() + expect(view.container.querySelector('[data-slot="sidebar.right.tab.document.unpreviewable"]')).toBeNull() + }) + + it('withholds the handoff seats until the file reports a Host path', async () => { + const h = harness({ 1: failure('workspace-file/not-text', { path: PATH }) }) + h.setVersion(undefined) + const view = render() + await settle() + expect(view.container.querySelector('[data-textpreview-failed]')).not.toBeNull() + expect(view.container.querySelector('[data-slot]')).toBeNull() + }) + it('says why a later page failed on a line under the pages already read', async () => { const h = harness({ 1: page(1, ['a'], false), 2: failure('workspace-file/too-large', { path: PATH, limit: 1024 }) }) const view = render() @@ -429,7 +466,7 @@ describe('TextPreview — navigation and view', () => { it('rebinds scrolling when the selected Slot body is replaced without changing the renderer id', async () => { const h = harness({ 1: page(1, ['a', 'b', 'c'], true) }) const code = codeProps(h, { revision: 1 }) - const fallback: TextPreviewProps = { ...code, renderSlot: () =>
} + const fallback: TextPreviewProps = { ...code, renderSlot: (key: string) => key === 'sidebar.right.tab.document' ?
: null } const view = render() await settle() const outer = body(view.container) @@ -465,10 +502,11 @@ describe('TextPreview — navigation and view', () => { const props: TextPreviewProps = { ...base, useDocumentPreviews: selector => selector(definitions), - renderSlot: (_key, owner, opts) => { - const documentOwner = owner as unknown as OwnerOf<'sidebar.right.tab.document'> - if (opts.entryKey === 'code') return key} /> - if (opts.entryKey === PLAIN_BODY_ID) return + renderSlot: (key: string, owner: unknown, opts?: { entryKey?: string }) => { + if (key !== 'sidebar.right.tab.document') return null + const documentOwner = owner as OwnerOf<'sidebar.right.tab.document'> + if (opts?.entryKey === 'code') return key} /> + if (opts?.entryKey === PLAIN_BODY_ID) return return
}, } 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 8752a7de89..8600979078 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -2449,7 +2449,125 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.tab.document\', () => ctx.slots.register(\n { name: \'sidebar.right.tab.document\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:24', + source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:25', + }, + { + key: 'sidebar.right.tab.document.actions', + kind: 'list', + scope: 'session', + summary: 'Header toolbar contributions acting on the previewed file, rendered after the preview\'s own controls once the file\'s Host path is known.', + doc: 'Header toolbar contributions acting on the previewed file, rendered after the preview\'s own controls once the file\'s Host path is known.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [ + '/** The file one tab reads: the session the read runs under and the path handed to the Host. */\nexport interface SessionFile {\n /** The Session whose workspace resolves relative paths. */\n readonly sessionId: SessionId\n /** The path the Host receives, absolute or relative to the addressed Session\'s workspace. */\n readonly path: string\n}', + ], + ownerPropsReferences: [ + 'SessionId', + ], + standardProps: [ + 'useResource: UseResource', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionPendingInteraction: UseSessionPendingInteraction', + 'useWorkspaces: SnapshotSelectorHook', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'sidebar.right.pane.tab\' (client-ui-sidebar-documentpreview), so it exists while that entry is mounted', + occupants: [ + 'client-ui-open-in-app OpenPathAction id \'open-in-app\'', + ], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.tab.document.actions\', () => ctx.slots.register(\n { name: \'sidebar.right.tab.document.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:46', + }, + { + key: 'sidebar.right.tab.document.unpreviewable', + kind: 'list', + scope: 'session', + summary: 'Empty-state contributions for a file this preview cannot render, offered where Retry would stand once the file\'s Host path is known.', + doc: 'Empty-state contributions for a file this preview cannot render, offered where Retry would stand once the file\'s Host path is known.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [ + '/** The file one tab reads: the session the read runs under and the path handed to the Host. */\nexport interface SessionFile {\n /** The Session whose workspace resolves relative paths. */\n readonly sessionId: SessionId\n /** The path the Host receives, absolute or relative to the addressed Session\'s workspace. */\n readonly path: string\n}', + ], + ownerPropsReferences: [ + 'SessionId', + ], + standardProps: [ + 'useResource: UseResource', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionPendingInteraction: UseSessionPendingInteraction', + 'useWorkspaces: SnapshotSelectorHook', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'sidebar.right.pane.tab\' (client-ui-sidebar-documentpreview), so it exists while that entry is mounted', + occupants: [ + 'client-ui-open-in-app OpenPathEmptyAction id \'open-in-app\'', + ], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.tab.document.unpreviewable\', () => ctx.slots.register(\n { name: \'sidebar.right.tab.document.unpreviewable\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts:57', }, { key: 'sidebar.right.tab.guide', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e6e695e59b..6e4598a6db 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3488,6 +3488,12 @@ importers: '@deepseek-ai/cordis': specifier: workspace:^ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-api-gateway': + specifier: workspace:^ + version: link:../../api/gateway + '@deepseek-ai/dsh-api-remotes': + specifier: workspace:^ + version: link:../../api/remotes '@deepseek-ai/dsh-api-session-controller': specifier: workspace:^ version: link:../../api/session-controller @@ -3512,6 +3518,9 @@ importers: '@deepseek-ai/dsh-client-ui-session': specifier: workspace:^ version: link:../ui-session + '@deepseek-ai/dsh-client-ui-sidebar-documentpreview': + specifier: workspace:^ + version: link:../ui-sidebar-documentpreview '@deepseek-ai/dsh-client-ui-slots': specifier: workspace:^ version: link:../ui-slots diff --git a/snapshots/web/document-preview/document.expected.md b/snapshots/web/document-preview/document.expected.md index 03286e76b8..203b6d2ff4 100644 --- a/snapshots/web/document-preview/document.expected.md +++ b/snapshots/web/document-preview/document.expected.md @@ -51,3 +51,5 @@ - State: unsupported - Line: Preview is not available for this file type yet. +- Header control: Open +- Empty-state control: Open in default app diff --git a/snapshots/web/document-preview/paging.patch.yml b/snapshots/web/document-preview/paging.patch.yml index b75ea4838d..96788cc5aa 100644 --- a/snapshots/web/document-preview/paging.patch.yml +++ b/snapshots/web/document-preview/paging.patch.yml @@ -3,3 +3,7 @@ name: '@deepseek-ai/dsh-api-workspace-files' config: maxLines: 64 +# Pin desktop availability so the default-application controls render identically in headless CI. +- id: session-controller + config: + nativeOpen: true diff --git a/snapshots/web/seeded-history/file-preview.expected.md b/snapshots/web/seeded-history/file-preview.expected.md index d11b2479b2..44d3d39044 100644 --- a/snapshots/web/seeded-history/file-preview.expected.md +++ b/snapshots/web/seeded-history/file-preview.expected.md @@ -3,4 +3,7 @@ - img - button "Read the file again": - img +- button "Open" +- button "More ways to open": + - img - text: alpha From eeb9b03465b942c59ae6219adb2479ff8f658c72 Mon Sep 17 00:00:00 2001 From: Yichen Yan <5031346+oraluben@users.noreply.github.com> Date: Thu, 17 Sep 2026 12:35:21 +0800 Subject: [PATCH 04/45] feat(web): serve the shell, API and plugin resources from the document directory --- ...-24-browser-token-authentication.i18n.yaml | 4 +- ...2026-08-24-browser-token-authentication.md | 4 +- ...6-08-24-browser-token-authentication.zh.md | 4 +- ...web-document-relative-app-routes.i18n.yaml | 6 + ...-09-14-web-document-relative-app-routes.md | 47 ++++++ ...-14-web-document-relative-app-routes.zh.md | 47 ++++++ .../tests/web-failure-matrix.expected.e2e.ts | 2 +- apps/cli/tests/web-auth.e2e.ts | 5 +- apps/web/public/manifest.webmanifest | 7 +- apps/web/tests/assembled-boot.ts | 11 +- apps/web/tests/prefix-proxy.ts | 145 +++++++++++++++++ apps/web/tests/public-mount.e2e.ts | 128 +++++++++++++++ apps/web/tests/pwa-manifest.e2e.ts | 10 +- apps/web/tests/scaffold.ts | 85 ++++++++-- apps/web/tsconfig.json | 2 + docs/subsystems/client-modules.i18n.yaml | 4 +- docs/subsystems/client-modules.md | 9 +- docs/subsystems/client-modules.zh.md | 9 +- .../api/gateway/src/client/stream-client.ts | 17 +- .../api/gateway/tests/gateway.client.spec.ts | 32 ++-- packages/api/remotes/tests/built-lib.e2e.ts | 150 ++++++++++-------- packages/bundle/web-app/README.i18n.yaml | 4 +- packages/bundle/web-app/README.md | 2 +- packages/bundle/web-app/README.zh.md | 2 +- packages/client/connection/README.i18n.yaml | 4 +- packages/client/connection/README.md | 2 +- packages/client/connection/README.zh.md | 2 +- .../client/connection/src/browser-auth.ts | 18 +-- packages/client/connection/src/client/rpc.ts | 18 +-- packages/client/connection/src/rpc.ts | 4 +- .../tests/browser-auth.host.spec.ts | 27 +++- .../tests/client-apply.client.spec.ts | 6 +- packages/client/hmr/src/client/index.ts | 5 +- packages/client/hmr/src/events.ts | 6 + .../client/hmr/tests/node-half.client.spec.ts | 2 +- packages/client/modules/README.i18n.yaml | 4 +- packages/client/modules/README.md | 2 +- packages/client/modules/README.zh.md | 2 +- .../client/modules/src/client/manifest.ts | 11 +- packages/client/modules/src/index.ts | 73 +++++++-- packages/client/modules/src/invariant.ts | 4 +- .../modules/tests/loader.client.spec.ts | 50 +++--- .../modules/tests/node-half.client.spec.ts | 66 +++++--- .../inspector/src/client/cdp/sources.ts | 15 +- .../inspector/tests/plugin.client.spec.ts | 2 +- .../webworker-runtime/src/client/client.ts | 3 +- .../tests/client/apply-injections.spec.ts | 4 +- .../tests/client/load-bundle.spec.ts | 10 +- .../host/frontend-static/README.i18n.yaml | 4 +- packages/host/frontend-static/README.md | 4 +- packages/host/frontend-static/README.zh.md | 4 +- packages/host/frontend-static/src/index.ts | 7 +- .../tests/frontend-static.spec.ts | 15 +- packages/host/webserver/src/injections.ts | 2 +- .../client-runtime/src/assembly/roster.ts | 12 +- .../tests/assembly-modules.client.spec.ts | 8 +- .../tests/assembly-roster.client.spec.ts | 12 +- tsconfig.host.json | 2 + 58 files changed, 866 insertions(+), 280 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md create mode 100644 .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.zh.md create mode 100644 apps/web/tests/prefix-proxy.ts create mode 100644 apps/web/tests/public-mount.e2e.ts diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml index 88e2561815..af52bdcb23 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.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/architecture/2026-08-24-browser-token-authentication.md -2026-08-24-browser-token-authentication.md: cdfed1f250de6def39e386cf9fcd2e536c6c97e4 -2026-08-24-browser-token-authentication.zh.md: 29f3a6c0a2d83ed1c17b9c0bc5988c9472741f3f +2026-08-24-browser-token-authentication.md: 47d6afe1bf4cd8169eb4e8ec92a30bf0fee32c8a +2026-08-24-browser-token-authentication.zh.md: 13ecf55e41c7bb1455177bdd6a87a3a83d94ca6f diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md index cdfed1f250..47d6afe1bf 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.md @@ -12,9 +12,9 @@ The Web Host runs tool-capable Sessions with the current operating-system user's `dsh-client-connection` authenticates the complete Host API before dispatch. Every API Proxy method, Remote unary call, generic Connection channel, and Remote WebSocket stream requires the same browser session; endpoint ownership and method names do not alter authority. The existing Host/Origin checks run first and retain their DNS-rebinding and cross-site-request role, returning 403 when they fail. A trusted Host without a valid browser session receives 401. The browser-trust rules remain owned by the [carrier-level browser trust decision](2026-07-28-api-browser-trust-boundary.md). -Each Host process generates a random launch token, retained by the root application context across Connection hot reloads. `dsh-web-app` prints and opens the normal root URL with that token in the query once per process. `frontend-static` asks Connection to authorize index responses: only `GET /?token=...` exchanges the process token for a cookie, then redirects to clean `/`; the token is not accepted on API paths or in an Authorization header. An obsolete token paired with a valid cookie redirects to clean `/`. Missing and invalid credentials receive one minimal 401 response. Static non-index assets remain public. +Each Host process generates a random launch token, retained by the root application context across Connection hot reloads. `dsh-web-app` prints and opens the normal root URL with that token in the query once per process. `frontend-static` asks Connection to authorize index responses: only `GET /?token=...` exchanges the process token for a cookie, then redirects to clean `./`; the token is not accepted on API paths or in an Authorization header. An obsolete token paired with a valid cookie redirects to clean `./`. Missing and invalid credentials receive one minimal 401 response. Static non-index assets remain public. -The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. It omits `Secure` because the shipped server uses loopback HTTP. There is no logout operation or reverse-proxy-specific handling. +The cookie is a signed, authority-bound bearer. Its deterministic name and signed payload both include the normalized hostname plus port, so one Harness home can run independent Web ports without cookie collisions. The payload carries safe-integer issue and expiry times under an absolute lifetime; `cookieMaxAgeDays` defaults to 30. The cookie is host-only, `Path=/`, `HttpOnly`, and `SameSite=Strict`. It omits `Secure` because the shipped server uses loopback HTTP. There is no logout operation. The HMAC secret is a versioned `grant` record at `client-connection/browser-session` in `ctx.credentials`; the local provider stores it in `$DSH_HOME/.credentials.yaml`. Connection loads or creates the record during activation and retains the secret for synchronous request verification. An active Connection continues using its loaded secret if the durable record changes; the next activation loads the replacement or creates a missing record, so deleting the record and restarting the process revokes every existing cookie. Invalid owner payloads fail loud instead of being replaced. The launch token itself is never persisted and changes on every process start, while an unexpired cookie remains valid across restarts on the same authority. diff --git a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md index 29f3a6c0a2..13ecf55e41 100644 --- a/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-24-browser-token-authentication.zh.md @@ -12,9 +12,9 @@ Web Host 以当前操作系统用户的权限运行具有工具能力的 Session `dsh-client-connection` 在分发前认证完整 Host API。每个 API Proxy 方法、Remote 一元调用、通用 Connection channel 和 Remote WebSocket stream 都要求同一个浏览器会话;endpoint 所有权与方法名称不改变 authority。既有 Host/Origin 校验先执行,继续负责 DNS rebinding 和跨站请求防御,失败时返回 403。Host 可信但没有有效浏览器会话时返回 401。浏览器信任规则仍由[载体级浏览器信任决策](2026-07-28-api-browser-trust-boundary.zh.md)持有。 -每个 Host 进程生成随机启动令牌,并由应用根 context 跨 Connection 热重载保留。`dsh-web-app` 每个进程只打印并打开一次 query 中带该令牌的普通根 URL。`frontend-static` 请求 Connection 授权 index 响应:只有 `GET /?token=...` 会把进程令牌交换为 cookie,再重定向到干净的 `/`;API 路径和 Authorization header 都不接受该令牌。过时令牌如果同时带有有效 cookie,会重定向到干净的 `/`。缺失与无效凭据得到同一份最小 401 响应。非 index 静态资产保持公开。 +每个 Host 进程生成随机启动令牌,并由应用根 context 跨 Connection 热重载保留。`dsh-web-app` 每个进程只打印并打开一次 query 中带该令牌的普通根 URL。`frontend-static` 请求 Connection 授权 index 响应:只有 `GET /?token=...` 会把进程令牌交换为 cookie,再重定向到干净的 `./`;API 路径和 Authorization header 都不接受该令牌。过时令牌如果同时带有有效 cookie,会重定向到干净的 `./`。缺失与无效凭据得到同一份最小 401 响应。非 index 静态资产保持公开。 -cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。随附服务器使用 loopback HTTP,因此不设置 `Secure`。这里没有 logout 操作或反向代理专用处理。 +cookie 是签名且绑定 authority 的 bearer。确定性名称与签名 payload 都包含规范化 hostname 和 port,因此同一 Harness home 可以在不同 Web port 运行而不发生 cookie 冲突。payload 在绝对有效期内携带安全整数形式的签发与过期时间;`cookieMaxAgeDays` 默认为 30。cookie 是 host-only、`Path=/`、`HttpOnly`、`SameSite=Strict`。随附服务器使用 loopback HTTP,因此不设置 `Secure`。这里没有 logout 操作。 HMAC 密钥是 `ctx.credentials` 中位于 `client-connection/browser-session` 的版本化 `grant` 记录;本地提供方将其存入 `$DSH_HOME/.credentials.yaml`。Connection 在激活期间加载或创建该记录,并保留密钥以同步校验请求。持久记录发生变化后,当前 Connection 继续使用已加载的密钥;下一次激活会加载替换记录或创建缺失记录,因此删除记录并重启进程会撤销全部既有 cookie。无效 owner payload 会明确失败,而不是被覆盖。启动令牌本身绝不持久化并在每次进程启动时变化;未过期 cookie 则能在相同 authority 上跨重启继续有效。 diff --git a/.agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.i18n.yaml new file mode 100644 index 0000000000..8f06bf7290 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.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/architecture/2026-09-14-web-document-relative-app-routes.md +2026-09-14-web-document-relative-app-routes.md: fbf30253bbfcc23eb09847f93c1b1f047459d31b +2026-09-14-web-document-relative-app-routes.zh.md: c302ec88a4205239148132513d1ff2a4385033e8 diff --git a/.agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md b/.agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md new file mode 100644 index 0000000000..fbf30253bb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md @@ -0,0 +1,47 @@ +# Agent Note: Web app-owned routes are document-relative + +Status: implemented + +English | [中文](2026-09-14-web-document-relative-app-routes.zh.md) + +## Problem + +Every browser reference to a shell-owned route was origin-root absolute: `/api/...` RPC, `/plugins/??...` plugin bundles, the Remote stream mux, the HMR event stream, and the launch entry's token-cleanup redirect to `/`. One listener served behind a prefix-stripping proxy (a mount such as `https://host/tools/dsh/` that forwards `/tools/dsh/...` as `/...`) therefore saw those requests at the origin root, where no route answers them: the shell, its plugin bundles, and its streams all missed. A single bundle has to serve both the origin root and any mount without a second build. + +The mount cannot be recovered from the transport. A configured base URL makes it deployment input, forwarded-prefix inference makes a request header authoritative for routing, and response rewriting in the proxy reimplements the same fact in fragments. The one place that already knows the mount is the served document itself. + +## Decision + +The served HTTP shell owns its document base. Its index carries exactly one ``, spliced in after the opening head tag once the index taps have run, so it precedes the boot manifest, every plugin-resource row, and any markup a tap inserted. The base freezes the entry directory: `/mount/` and `/mount/index.html` are the supported entries, and a document URL that later moves (an in-page `pushState`) does not move the base. Nothing infers a prefix, so deep direct loads and reloads are not entry points; a bare mount still needs the proxy's own normalization to its slash form. + +Browser references to those routes are relative to that document — `api/x`, `plugins/x` — while server route keys stay absolute pathnames: the RPC channel key `/api`, the `webServer` registration paths, and the response tables keyed by the combo route `/plugins/??...&rev=...`. A shared constant that names a key (`*_PATH`, `*_ENDPOINT`) is stripped at the boundary (`KEY.slice(1)`) before browser code uses it, and the browser form lives beside it as `*_ROUTE`. + +The Host composes browser references in one place per producer. Module graph rows and batch descriptors carry the document-relative combo reference; the source-map trailer carries the combo query alone, because a script's source-map reference resolves against that script's own directory (`.../plugins/`) rather than the document. The response table stays keyed by the absolute route, which is also what a request reaches after the proxy strips its prefix. + +The launch entry follows the same rule. `authenticatedUrl` adds the process token to the caller's URL and keeps its authority and mount, and the token exchange redirects to `./`, which removes the query token while preserving the request URL's directory. The Host/Origin fence and the cookie rules are unchanged. + +Consumers that need an absolute URL resolve against `document.baseURI`: the Gateway when it constructs its WebSocket URL and selects `ws:` or `wss:`, and the Inspector when it locates its own bundle from the boot graph. + +Desktop is the other document owner. Its window loads `dsh-app://app/`, an origin that serves the same dist at that root and forwards every app-owned path to the shell-owned Host, so its document directory already is the root and no base row is injected for it; it names that Host origin for the Gateway through the transport's `streamBaseUrl` instead. Its resources live at that root, which is also why the served HTTP shell's `./` does not apply to it. + +## Alternatives considered + +**A configured base URL as the routing base (`publicUrl`).** Rejected: the document already knows its own URL, so this adds a second, drift-prone source for a fact the page can read, and it would have to be plumbed to every consumer instead of one shell decision. The advertised public URL remains an operator-facing print/open input, not a routing input. + +**Inferring the mount from a forwarded-prefix header.** Rejected: it makes a request header authoritative for routing, so any client that sets it could move app-owned routes, and the proxy contract becomes server-visible configuration. + +**A shared `Connection.resolveUrl` or routes base.** The HTTP carrier's document base and the worker tunnel's Host-root mapping differ. Resolving every target in Connection would prepend a static preview path to worker-local routes or lose a served mount. Each carrier resolves its own targets; UI resource consumers use the document base. + +**An absolute `/` redirect with the proxy rewriting `Location`.** Rejected: the browser already knows the request's directory, and a configured redirect target cannot be right for both the loopback entry and a proxy mount. + +## Consequences + +One bundle serves the origin root and any mount, and the served document is the single source of the mount. The costs are explicit: the supported entries are only the dist root and the configured index path, a bare mount depends on the proxy's slash normalization, and a reload of a deep in-page path re-enters at that path rather than the frozen one. + +Routes owned by feature packages (open-in-app, deliverables, session-log export, uploads, markdown media) follow the same rule through their own `*_ROUTE` constants; the static gate that keeps browser sources on this rule is recorded with those changes. + +## Testing + +The frontend-static real-composition test serves the index through the Loader and asserts one `` that precedes an injected plugin-resource row and tap markup. The client-modules node-half suite asserts that graph rows, batch descriptors, and the source-map trailer are document-relative while the response table still serves them by route, and the client test roster plus the assembled-boot fixture carry the same relative form. `browser-auth.host.spec.ts` covers the `./` redirect and the authority- and mount-preserving `authenticatedUrl`; `frontend-static.spec.ts` and `apps/cli/tests/web-auth.e2e.ts` run the exchange through a real Loader composition and the built CLI. + +`apps/web/tests/public-mount.e2e.ts` is the browser proof: a real Chromium reaches one listener through the prefix-stripping proxy, the mounted WebSocket streams both ways, a `pushState` to a deeper path leaves `document.baseURI` at the mount, and a document-relative `fetch('api/session/create')` still succeeds beneath it. diff --git a/.agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.zh.md b/.agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.zh.md new file mode 100644 index 0000000000..c302ec88a4 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.zh.md @@ -0,0 +1,47 @@ +# Agent Note: Web 应用自有路由相对文档寻址 + +Status: implemented + +[English](2026-09-14-web-document-relative-app-routes.md) | 中文 + +## 问题 + +浏览器对外壳自有路由的每一处引用都以源站根绝对形式书写:`/api/...` RPC、`/plugins/??...` 插件 bundle、Remote 流 mux、HMR 事件流,以及启动入口清理 token 时重定向到的 `/`。当一个监听端口位于剥离前缀的代理之后(例如 `https://host/tools/dsh/` 这样的挂载,把 `/tools/dsh/...` 转发为 `/...`),这些请求会落在源站根,那里没有任何路由应答:外壳、插件 bundle、流全部落空。同一份 bundle 必须同时服务源站根与任一挂载,而不能为此再构建一次。 + +挂载点无法从传输层恢复。配置 base URL 会把它变成部署输入,转发前缀推断会让请求头对路由具有权威性,代理内改写在碎片里重复同一事实。唯一已经知道挂载点的地方,就是所服务的文档自身。 + +## 决策 + +所服务的 HTTP 外壳拥有自己的文档 base。其 index 携带唯一的 ``,在原始 index 转换执行后拼接于起始 head 标签之后,因此它先于启动 manifest、每一行插件资源,以及任何转换插入的标记。该 base 冻结入口目录:`/mount/` 与 `/mount/index.html` 是受支持的入口,而文档 URL 之后移动(页面内 `pushState`)不会移动 base。系统不推断任何前缀,因此深层直接加载与重新加载不是入口;裸挂载仍需依赖代理自身的规范化补齐尾部斜杠。 + +浏览器对这些路由的引用相对该文档——`api/x`、`plugins/x`——而服务端路由键保持绝对路径名:RPC channel 键 `/api`、`webServer` 注册路径,以及以 combo 路由 `/plugins/??...&rev=...` 为键的响应表。命名路由键的共享常量(`*_PATH`、`*_ENDPOINT`)在边界处被剥去前导斜杠(`KEY.slice(1)`)后浏览器代码才使用,浏览器形式以 `*_ROUTE` 与之并列。 + +宿主在每个生产者里只在一处组合浏览器引用。模块启动图 row 与批次描述符携带文档相对的 combo 引用;source-map trailer 只携带 combo 查询,因为脚本的 source-map 引用相对该脚本自身目录(`.../plugins/`)解析,而非相对文档。响应表仍以绝对路由为键,而请求在代理剥去前缀后到达的也正是该路由。 + +启动入口遵循同一规则。`authenticatedUrl` 把进程 token 加到调用方的 URL 上并保留其 authority 与挂载;token 交换重定向到 `./`,移除 query token 的同时保留请求 URL 的目录。Host/Origin 栅栏与 cookie 规则不变。 + +需要绝对 URL 的消费方相对 `document.baseURI` 解析:Gateway 构造 WebSocket URL 并选择 `ws:` 或 `wss:` 时,以及 Inspector 从启动图定位自身 bundle 时。 + +Desktop 是另一个文档所有者。它的窗口加载 `dsh-app://app/`:该来源在根目录提供同一份 dist,并把其他所有应用路径转发给它拥有的 Host,因此它的文档目录本就是根目录,无需为它注入 base 行;它改为通过传输层的 `streamBaseUrl` 为 Gateway 指定该 Host origin。它的资源就位于该根目录,这也是所服务 HTTP 外壳的 `./` 不适用于它的原因。 + +## 曾考虑的替代方案 + +**把配置 base URL 当作路由 base(`publicUrl`)。** 否决:文档已经知道自己的 URL,因此这是为页面本可读取的事实引入第二个易漂移来源,而且必须把它接入每个消费方,而不是只做一次外壳决策。对外公告的公开 URL 仍是面向运维的打印/打开输入,不是路由输入。 + +**从转发前缀请求头推断挂载点。** 否决:这会让请求头对路由具有权威性,任何设置该头的客户端都能挪动应用自有路由,代理约定也会变成服务端可见的配置。 + +**共享 `Connection.resolveUrl` 或 routes base。** HTTP 载体的文档基准与 worker tunnel 的 Host 根路径映射不同。在 Connection 中统一解析所有目标,会把静态 preview 路径加到 worker 本地路由之前,或丢失所服务的挂载。各载体解析自己的目标;UI 资源消费方使用文档基准。 + +**保留绝对 `/` 重定向并让代理改写 `Location`。** 否决:浏览器已经知道请求所在目录,而配置出来的重定向目标无法同时适用于 loopback 入口与代理挂载。 + +## 后果 + +一份 bundle 服务源站根与任一挂载,所服务的文档是挂载点的唯一来源。代价是显式的:受支持的入口只有 dist 根与配置的 index 路径;裸挂载依赖代理的斜杠规范化;页面内深层路径重新加载会在该路径重新进入,而非冻结目录。 + +功能包自有的路由(open-in-app、deliverables、会话日志导出、上传、markdown 媒体)通过各自的 `*_ROUTE` 常量遵循同一规则;让浏览器源码持续遵守该规则的静态门禁随那些改动一并记录。 + +## 测试 + +frontend-static 的真实组合测试通过 Loader 提供 index,并断言唯一的 `` 先于注入的插件资源行与转换标记。client-modules node 半侧测试断言启动图 row、批次描述符与 source-map trailer 均为文档相对,而响应表仍按路由提供它们,客户端测试 roster 与 assembled-boot fixture 携带同一相对形式。`browser-auth.host.spec.ts` 覆盖 `./` 重定向与保留 authority 和挂载的 `authenticatedUrl`;`frontend-static.spec.ts` 与 `apps/cli/tests/web-auth.e2e.ts` 分别经真实 Loader 组合与构建后的 CLI 运行该交换。 + +`apps/web/tests/public-mount.e2e.ts` 是浏览器证据:真实 Chromium 经剥离前缀的代理到达同一监听端口,挂载下的 WebSocket 双向成流,`pushState` 到更深路径后 `document.baseURI` 仍停在挂载点,而文档相对的 `fetch('api/session/create')` 在其下依然成功。 diff --git a/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts b/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts index 0c5b4c26d4..b1f89c11d1 100644 --- a/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts +++ b/apps/cli/tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts @@ -138,7 +138,7 @@ function start(f: ReturnType, extra: string[] = []) { expect(response.status).toBe(200) const html = await response.text() expect(html).toContain('__DSH_BOOT__') - const bundlePath = /')) + // A plugin row stands in for the Host's plugin-resource rows: the base the + // shell inserts must precede it, not merely exist. + const offRows = loaded.on('webserver/index-inject', (rows) => { + rows.push({ kind: 'script-preload', src: 'plugins/boot.js' }) + }) for (const path of ['/', '/index.html', '/?view=test']) { const got = await request(port, path, authenticated()) expect(got.status).toBe(200) expect(got.type).toBe('text/html; charset=utf-8') expect(got.body).toContain('__T__') expect(got.body).toContain('shell') + // The served document carries the entry-directory base exactly once, and + // it precedes every injected row and tap markup, so the shell's + // app-owned routes and the Host's resource rows resolve under one mount. + expect(got.body.match(/') + expect(base).toBeLessThan(got.body.indexOf('')) + expect(base).toBeLessThan(got.body.indexOf('')) } + offRows() expect(await request(port, '/', authenticated({ method: 'HEAD' }))).toEqual({ status: 200, type: 'text/html; charset=utf-8', diff --git a/packages/host/webserver/src/injections.ts b/packages/host/webserver/src/injections.ts index 5b431918f5..79734fd34a 100644 --- a/packages/host/webserver/src/injections.ts +++ b/packages/host/webserver/src/injections.ts @@ -20,7 +20,7 @@ export type IndexInjection = /** * External classic script, executed in table order: a parser-blocking tag * when served, an awaited fetch-and-execute in the worker form (whose - * loader resolves worker-only URLs such as `/plugins/...`). + * loader resolves worker-only references such as `plugins/...`). */ | { kind: 'script-src'; placement: IndexInjectionPlacement; src: string } /** Advisory preload for an external classic script; static workers may ignore it. */ diff --git a/packages/test-support/client-runtime/src/assembly/roster.ts b/packages/test-support/client-runtime/src/assembly/roster.ts index 82aa14df93..80b1c824b1 100644 --- a/packages/test-support/client-runtime/src/assembly/roster.ts +++ b/packages/test-support/client-runtime/src/assembly/roster.ts @@ -24,17 +24,17 @@ const LOCAL_REV = 'local' /** * Synthesize the raw `WebBootGraph` for `rows`: one `application` batch - * holding every row, `rev: 'local'`, placeholder `/plugins//client.js` - * URLs, since every module is seeded in process and never fetched. Validation - * stays with the production `parseBootManifest` inside the module system: - * duplicate names and an empty roster are rejected there, not here. + * holding every row, `rev: 'local'`, placeholder `plugins//client.js` + * references, since every module is seeded in process and never fetched. + * Validation stays with the production `parseBootManifest` inside the module + * system: duplicate names and an empty roster are rejected there, not here. * @param rows - roster rows in composition order. * @returns the unparsed graph, as `createClientModuleSystem` consumes it. */ export function graphFromRoster(rows: readonly ClientRosterRow[]): WebBootGraph { const entries: WebBootEntry[] = rows.map(row => ({ id: row.name, - url: `/plugins/${row.name}/client.js`, + url: `plugins/${row.name}/client.js`, rev: LOCAL_REV, ...(row.inject.length > 0 ? { inject: [...row.inject] } : {}), ...(row.immediately ? { immediately: true } : {}), @@ -44,7 +44,7 @@ export function graphFromRoster(rows: readonly ClientRosterRow[]): WebBootGraph entries, batches: [{ phase: 'application', - url: '/plugins/local.js', + url: 'plugins/local.js', rev: LOCAL_REV, entries: entries.map(entry => entry.id), }], diff --git a/packages/test-support/client-runtime/tests/assembly-modules.client.spec.ts b/packages/test-support/client-runtime/tests/assembly-modules.client.spec.ts index 999a99ea70..c3aded1f56 100644 --- a/packages/test-support/client-runtime/tests/assembly-modules.client.spec.ts +++ b/packages/test-support/client-runtime/tests/assembly-modules.client.spec.ts @@ -25,8 +25,8 @@ const row = (name: string, immediately = false) => ({ name, inject: [], immediat function graph(names: readonly string[]): WebBootGraph { return { rev: 'local', - entries: names.map(id => ({ id, url: `/plugins/${id}/client.js`, rev: 'local' })), - batches: [{ phase: 'application', url: '/plugins/all.js', rev: 'local', entries: [...names] }], + entries: names.map(id => ({ id, url: `plugins/${id}/client.js`, rev: 'local' })), + batches: [{ phase: 'application', url: 'plugins/all.js', rev: 'local', entries: [...names] }], } } @@ -77,8 +77,8 @@ describe('createInProcessModules', () => { it('rejects loudly instead of fetching when a graph row has no loaded module', async () => { const system = createInProcessModules(graph(['ghost']), new Map()) - await expect(system.prefetch('ghost')).rejects.toThrow('in-process modules never load bundles (/plugins/all.js)') - await expect(system.import('ghost', '', {})).rejects.toThrow('in-process modules never load bundles (/plugins/all.js)') + await expect(system.prefetch('ghost')).rejects.toThrow('in-process modules never load bundles (plugins/all.js)') + await expect(system.import('ghost', '', {})).rejects.toThrow('in-process modules never load bundles (plugins/all.js)') }) it('exposes the graph parsed by the production validator as its manifest', () => { diff --git a/packages/test-support/client-runtime/tests/assembly-roster.client.spec.ts b/packages/test-support/client-runtime/tests/assembly-roster.client.spec.ts index d1ccea2644..7ec7bf9711 100644 --- a/packages/test-support/client-runtime/tests/assembly-roster.client.spec.ts +++ b/packages/test-support/client-runtime/tests/assembly-roster.client.spec.ts @@ -11,22 +11,22 @@ const ROWS: readonly ClientRosterRow[] = [ ] describe('graphFromRoster', () => { - it('synthesizes one application batch over every row with placeholder URLs', () => { + it('synthesizes one application batch over every row with placeholder references', () => { expect(graphFromRoster(ROWS)).toEqual({ rev: 'local', entries: [ - { id: MODULES_PACKAGE, url: `/plugins/${MODULES_PACKAGE}/client.js`, rev: 'local', immediately: true }, - { id: '@x/a', url: '/plugins/@x/a/client.js', rev: 'local' }, - { id: '@x/b', url: '/plugins/@x/b/client.js', rev: 'local', inject: ['@x/a'], immediately: true }, + { id: MODULES_PACKAGE, url: `plugins/${MODULES_PACKAGE}/client.js`, rev: 'local', immediately: true }, + { id: '@x/a', url: 'plugins/@x/a/client.js', rev: 'local' }, + { id: '@x/b', url: 'plugins/@x/b/client.js', rev: 'local', inject: ['@x/a'], immediately: true }, ], - batches: [{ phase: 'application', url: '/plugins/local.js', rev: 'local', entries: [MODULES_PACKAGE, '@x/a', '@x/b'] }], + batches: [{ phase: 'application', url: 'plugins/local.js', rev: 'local', entries: [MODULES_PACKAGE, '@x/a', '@x/b'] }], }) }) it('parses through the production validator to plugin rows that mirror the roster, refusing duplicates and an empty roster', () => { const manifest = parseBootManifest(graphFromRoster(ROWS)) expect(manifest.plugins).toEqual(ROWS.map(row => ({ id: row.name, inject: [...row.inject], immediately: row.immediately }))) - expect(manifest.modules.map(row => row.initialUrl)).toEqual(['/plugins/local.js', '/plugins/local.js', '/plugins/local.js']) + expect(manifest.modules.map(row => row.initialUrl)).toEqual(['plugins/local.js', 'plugins/local.js', 'plugins/local.js']) const row = ROWS[1]! expect(() => parseBootManifest(graphFromRoster([row, row]))).toThrow('duplicate graph entry "@x/a"') expect(() => parseBootManifest(graphFromRoster([]))).toThrow('must be a non-empty string array') diff --git a/tsconfig.host.json b/tsconfig.host.json index 11fa5efe32..57ba05d8a4 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -12,6 +12,7 @@ "apps/web/tests/default-product-isolation.e2e.ts", "apps/web/tests/diff-context.e2e.ts", "apps/web/tests/scaffold.ts", + "apps/web/tests/prefix-proxy.ts", "apps/web/tests/auto-review-fixture.ts", "apps/web/tests/auto-review-denial.e2e.ts", "apps/web/tests/scaffold-generation.spec.ts", @@ -52,6 +53,7 @@ "apps/web/tests/onboarding-deepseek-config.e2e.ts", "apps/web/tests/onboarding-usable-provider.e2e.ts", "apps/web/tests/remote-welcome.e2e.ts", + "apps/web/tests/public-mount.e2e.ts", "apps/web/tests/workspace-new-session-folding.e2e.ts", "apps/web/tests/workspace-management.e2e.ts", "apps/web/tests/workspace-recency.e2e.ts", From 9ce43f925c94b9cb988b16f92bffd92a54405670 Mon Sep 17 00:00:00 2001 From: Kaige-Gao Date: Thu, 17 Sep 2026 16:40:13 +0800 Subject: [PATCH 05/45] feat(web): add feedback to session header menu --- ...8-feedback-dialog-and-categories.i18n.yaml | 4 +-- ...26-09-08-feedback-dialog-and-categories.md | 2 ++ ...09-08-feedback-dialog-and-categories.zh.md | 2 ++ apps/web/tests/message-feedback.e2e.ts | 36 +++++++++++++++++++ .../ui-message-feedback/README.i18n.yaml | 4 +-- packages/client/ui-message-feedback/README.md | 4 +-- .../client/ui-message-feedback/README.zh.md | 4 +-- .../ui-message-feedback/src/client/index.ts | 22 +++++++++++- .../tests/browser-plugin.client.spec.tsx | 14 ++++++++ .../session-log-export/README.i18n.yaml | 4 +-- .../session-log-export/README.md | 2 ++ .../session-log-export/README.zh.md | 2 ++ .../session-log-export/package.json | 1 + .../src/client/HeaderAction.tsx | 33 +++++++++++++---- .../session-log-export/src/client/index.ts | 17 ++++++--- .../session-log-export/src/client/locales.ts | 2 ++ .../tests/client-apply.client.spec.tsx | 21 +++++++++++ .../tests/header-action.client.spec.tsx | 32 ++++++++++++++--- .../session-log-export/tsconfig.client.json | 1 + pnpm-lock.yaml | 3 ++ scripts/gen-cordis-catalog.ts | 1 + 21 files changed, 184 insertions(+), 27 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.i18n.yaml b/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.i18n.yaml index 16c17f3405..ad7aa6aa6e 100644 --- a/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.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-08-feedback-dialog-and-categories.md -2026-09-08-feedback-dialog-and-categories.md: ee656946a9e5d2921a02a1b642041e5965661f31 -2026-09-08-feedback-dialog-and-categories.zh.md: ef2b2d4670aad12398125925dd1e1a7e7c10a5f0 +2026-09-08-feedback-dialog-and-categories.md: 271eb080dcca866ddbb5fee9df2d72ef9a1300ee +2026-09-08-feedback-dialog-and-categories.zh.md: 10f662e7d020c283bc250ffc75d71f757ddd6516 diff --git a/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.md b/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.md index ee656946a9..271eb080dc 100644 --- a/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.md +++ b/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.md @@ -14,6 +14,8 @@ The Web client had two disconnected feedback paths with no visible outcome. `/fe `ui-message-feedback` becomes the Web feedback surface. A per-session `FeedbackSurface` owns the message-feedback controller, a `FeedbackDialogController` for the draft, the submission, and the toast sequence, and the routing between them: a message target puts its selected judgment with the dialog's category and note through the message controller, while the Session target records through `ctx.remote.sessionFeedback`. A `FeedbackDialog` entry of `conversation.input.overlay` renders the Modal and Toast primitives from the dialog store. A decoration on the Host's `feedback` command opens the dialog for the Session from a menu pick or a bare Enter while `/feedback ` still reaches the Host; it uses the `action` kind in `CommandUiSpec`, which consumes the trigger token and runs a client callback without submitting anything. The later [symmetric message feedback submission](2026-09-10-symmetric-message-feedback-submission.md) decision owns the rating entry rule: either unrecorded rating opens the dialog, while clicking the recorded rating retracts it. The note popover, `clearNote`, and `clear` remain absent because the dialog is the only note editor. +The Session Header’s more-actions menu also opens the Session dialog through the `feedbackUi.openSession` Client service. The menu remains owned by `session-log-export`, while the existing per-session feedback controller owns the draft and submission. An observable tracks the optional feedback plugin’s availability, so unloading feedback removes only its menu row and leaves export usable. Opening or dismissing the form writes no feedback event; Submit records one Session remark. + The dialog is the shared Modal card at the design's width; the design's checkbox for including the conversation log is not built, because the log travels with every feedback event and is not optional. An oversized description still fails on submit with `note-too-large`; the dialog stays open with its draft and a warning toast presents the localized failure. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.zh.md b/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.zh.md index ef2b2d4670..10f662e7d0 100644 --- a/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.zh.md +++ b/.agents/notes/implemented/feature/2026-09-08-feedback-dialog-and-categories.zh.md @@ -14,6 +14,8 @@ Web 客户端有两条互不相连的反馈路径,且都没有可见结果。` `ui-message-feedback` 成为 Web 反馈界面。每个 Session 一个 `FeedbackSurface`,拥有消息反馈控制器、负责草稿、提交与 toast 序号的 `FeedbackDialogController`,以及两者之间的路由:消息目标经消息控制器 put 一条带弹窗分类与备注的所选评分,Session 目标经 `ctx.remote.sessionFeedback` 记录。`conversation.input.overlay` 的 `FeedbackDialog` 条目从弹窗 store 渲染 Modal 与 Toast 基元。宿主 `feedback` 命令上的装饰让菜单选中或不带参数的回车为 Session 打开弹窗,而 `/feedback ` 仍到达宿主;它使用 `CommandUiSpec` 中的 `action` 种类:裸调用消费触发 token 后运行一个客户端回调,不提交任何内容。后续的[对称消息反馈提交](2026-09-10-symmetric-message-feedback-submission.zh.md)决策拥有评分入口规则:任一未记录的评分都会打开弹窗,再次点击已记录的评分则撤回。备注浮层、`clearNote` 与 `clear` 继续保持移除,因为弹窗是唯一的备注编辑器。 +会话标题栏的更多操作菜单也通过 `feedbackUi.openSession` Client 服务打开 Session 弹窗。菜单仍由 `session-log-export` 持有,现有的逐 Session 反馈控制器持有草稿与提交。一个可观察值跟踪可选反馈插件的可用状态,因此卸载反馈插件只移除其菜单行,导出仍然可用。打开或关闭表单不写反馈事件;点击提交才记录一条 Session 反馈。 + 弹窗是共用的 Modal 卡片,宽度按设计稿;设计稿里「包括当前对话的日志」复选框不做,因为日志随每个反馈事件一起投递,不是可选项。超长描述仍在提交时以 `note-too-large` 失败;弹窗保留草稿并通过警告 toast 展示本地化错误。 ## 考虑过的替代方案 diff --git a/apps/web/tests/message-feedback.e2e.ts b/apps/web/tests/message-feedback.e2e.ts index df89180c18..f26202d4b8 100644 --- a/apps/web/tests/message-feedback.e2e.ts +++ b/apps/web/tests/message-feedback.e2e.ts @@ -145,4 +145,40 @@ describe('web e2e: durable per-message feedback', () => { expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }) + + it.skipIf(MODE === 'record')('opens the shared dialog from the header and records Session feedback only on submit', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-header-feedback')) + await openSeededSession() + await page.getByText('DONE', { exact: true }).waitFor({ timeout: 30_000 }) + const agent = scaffold.ctx.agents.get(SessionId(SEED_ID)) + if (agent === undefined) throw new Error('seeded session did not attach an agent') + const feedbackEvents = () => agent.session.snapshotEvents().filter(event => event.type.startsWith('feedback/')) + const before = feedbackEvents().length + const dialog = page.getByRole('dialog', { name: 'Submit feedback' }) + + await page.getByRole('button', { name: 'More actions', exact: true }).click() + await page.getByRole('menuitem', { name: 'Download session log' }).waitFor() + await page.getByRole('menuitem', { name: 'Feedback', exact: true }).click() + await dialog.waitFor() + expect(await page.getByRole('menu').count()).toBe(0) + expect(feedbackEvents()).toHaveLength(before) + await dialog.getByRole('textbox', { name: 'Feedback details' }).fill('discarded draft') + await dialog.getByRole('button', { name: 'Close', exact: true }).click() + expect(feedbackEvents()).toHaveLength(before) + + await page.getByRole('button', { name: 'More actions', exact: true }).click() + await page.getByRole('menuitem', { name: 'Feedback', exact: true }).click() + await dialog.waitFor() + expect(await dialog.getByRole('textbox', { name: 'Feedback details' }).inputValue()).toBe('') + await dialog.getByRole('button', { name: 'Product features and interaction', exact: true }).click() + await dialog.getByRole('textbox', { name: 'Feedback details' }).fill('Feedback from the Session menu.') + await dialog.getByRole('button', { name: 'Submit', exact: true }).click() + await expect.poll(() => dialog.count()).toBe(0) + await page.getByRole('alert').filter({ hasText: 'Thanks for your feedback' }).waitFor() + expect(feedbackEvents().slice(before)).toMatchObject([ + { type: 'feedback/record', data: { category: 'product-interaction', text: 'Feedback from the Session menu.' } }, + ]) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }, 60_000) }) diff --git a/packages/client/ui-message-feedback/README.i18n.yaml b/packages/client/ui-message-feedback/README.i18n.yaml index bdd5f1e664..642559b51f 100644 --- a/packages/client/ui-message-feedback/README.i18n.yaml +++ b/packages/client/ui-message-feedback/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-message-feedback/README.md -README.md: b37278e8d115a2ad61bb17ef8d884b0d888cd6a7 -README.zh.md: cd233061640f5e52ea9ca54ffe973bff3b957197 +README.md: bc33b02c6966bfa851614ef616c1ff9c583ae67d +README.zh.md: 88c1ba476c1a9c2a2df4b6cad471d78af65b83c9 diff --git a/packages/client/ui-message-feedback/README.md b/packages/client/ui-message-feedback/README.md index b37278e8d1..bc33b02c69 100644 --- a/packages/client/ui-message-feedback/README.md +++ b/packages/client/ui-message-feedback/README.md @@ -25,7 +25,7 @@ This package is the Web GUI's feedback surface: the Like/Dislike pair in the fin ## Use this package -Mount this plugin alongside `ui-conversation` and `ui-commands`; the Like/Dislike pair then appears in the action row of each turn's closing assistant message, between copy and branch, and the Feedback row of the composer menu opens the dialog. A recorded rating shows the filled glyph and stays visible without hover. Like and Dislike both open the dialog: seven category chips and a detail box are optional, and Submit records the selected judgment with whatever was filled in before the toast thanks the user; the conversation log travels with every feedback event. Clicking the recorded rating retracts it without opening the dialog. A bare `/feedback`, picked from the menu or typed and sent without text, opens the same dialog for the Session; `/feedback ` keeps the Host command path and its acknowledgement row. +Mount this plugin alongside `ui-conversation` and `ui-commands`; the Like/Dislike pair then appears in the action row of each turn's closing assistant message, between copy and branch, and Feedback in either the composer menu or the Session Header’s more-actions menu opens the same dialog. A recorded rating shows the filled glyph and stays visible without hover. Like and Dislike both open the dialog: seven category chips and a detail box are optional, and Submit records the selected judgment with whatever was filled in before the toast thanks the user; the conversation log travels with every feedback event. Clicking the recorded rating retracts it without opening the dialog. A bare `/feedback`, picked from the menu or typed and sent without text, opens the same dialog for the Session; `/feedback ` keeps the Host command path and its acknowledgement row. ### Failures @@ -39,7 +39,7 @@ A rating or list-load failure shows inline in the row; a submission failure show
Implementation internals — click to expand -The package contributes the `feedback` entry (order 10) of `conversation.chat.assistant-actions`, declared by ui-conversation and rendered inside the finalized assistant message's IconActions row, and the `feedback-dialog` entry (order 2) of `conversation.input.overlay`, which renders the Modal and Toast primitives through body portals and centers the toast over the composer card it mounts inside. The `/feedback` decoration is an `action` registered through `ctx.commandUi.decorate`, so a menu pick or a bare Enter consumes the trigger token and opens the dialog while an argued line still reaches the Host command. +The package contributes the `feedback` entry (order 10) of `conversation.chat.assistant-actions`, declared by ui-conversation and rendered inside the finalized assistant message's IconActions row, and the `feedback-dialog` entry (order 2) of `conversation.input.overlay`, which renders the Modal and Toast primitives through body portals and centers the toast over the composer card it mounts inside. The `feedbackUi.openSession(sessionId)` Client service opens that same Session-scoped dialog without recording feedback; the Header menu and command decoration both use it. The `/feedback` decoration is an `action` registered through `ctx.commandUi.decorate`, so a menu pick or a bare Enter consumes the trigger token and opens the dialog while an argued line still reaches the Host command. Per Session, one `MessageFeedbackController` backs every message control and one `FeedbackDialogController` owns the dialog draft, the submission, and the toast sequence. The message controller reads `messageFeedback.list` once, deferred to the first hover or focus rather than fired on mount, and serializes mutations so each carries the version last observed; a `version-conflict` reply carries the authoritative item and reconciles the view without refetching. Before either rating action proceeds, the row checks the committed item: the matching rating calls `retract`, which rechecks the rating in the serialized queue and becomes a no-op after a concurrent change, while any other state opens the dialog with the requested rating. The dialog controller submits by target: a message target puts that rating with the dialog's note and category through the message controller, and the Session target records through `ctx.remote.sessionFeedback`. Success closes the draft and raises the acknowledgement toast; a late success from a superseded draft raises that toast without closing the new draft; a failure keeps the draft open and raises a longer-lived warning toast. diff --git a/packages/client/ui-message-feedback/README.zh.md b/packages/client/ui-message-feedback/README.zh.md index cd23306164..88c1ba476c 100644 --- a/packages/client/ui-message-feedback/README.zh.md +++ b/packages/client/ui-message-feedback/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -与 `ui-conversation`、`ui-commands` 一起挂载本插件;Like/Dislike 对随即出现在每个轮次收尾助手消息的动作行中,位于复制与分支之间,输入框菜单里的「反馈」行则打开弹窗。已记录的评分显示实心图标,不需要悬停也一直可见。点赞和点踩都会打开弹窗:七个分类标签和一个详情框都可不填;提交后才会记录带所填内容的对应评分并弹出感谢 toast,对话日志随每个反馈事件一起投递。再次点击已记录的评分会直接撤回,不打开弹窗。不带文本的 `/feedback`,无论是从菜单选中还是直接输入后发送,都会为 Session 打开同一个弹窗;`/feedback ` 仍走宿主命令路径并显示确认行。 +与 `ui-conversation`、`ui-commands` 一起挂载本插件;Like/Dislike 对随即出现在每个轮次收尾助手消息的动作行中,位于复制与分支之间,输入框菜单或会话标题栏更多操作菜单里的「反馈」会打开同一个弹窗。已记录的评分显示实心图标,不需要悬停也一直可见。点赞和点踩都会打开弹窗:七个分类标签和一个详情框都可不填;提交后才会记录带所填内容的对应评分并弹出感谢 toast,对话日志随每个反馈事件一起投递。再次点击已记录的评分会直接撤回,不打开弹窗。不带文本的 `/feedback`,无论是从菜单选中还是直接输入后发送,都会为 Session 打开同一个弹窗;`/feedback ` 仍走宿主命令路径并显示确认行。 ### 失败 @@ -39,7 +39,7 @@ kind: "package-reference"
实现细节——点击展开 -本包贡献 `conversation.chat.assistant-actions` 的 `feedback` 条目(order 10),由 ui-conversation 声明并渲染在已定稿助手消息的 IconActions 行内;同时贡献 `conversation.input.overlay` 的 `feedback-dialog` 条目(order 2),它通过 body portal 渲染 Modal 与 Toast 基元,并让 toast 以其所在的输入框卡片为中心。`/feedback` 装饰是经 `ctx.commandUi.decorate` 注册的 `action`,因此菜单选中或不带参数的回车会消费触发 token 并打开弹窗,而带参数的命令行仍到达宿主命令。 +本包贡献 `conversation.chat.assistant-actions` 的 `feedback` 条目(order 10),由 ui-conversation 声明并渲染在已定稿助手消息的 IconActions 行内;同时贡献 `conversation.input.overlay` 的 `feedback-dialog` 条目(order 2),它通过 body portal 渲染 Modal 与 Toast 基元,并让 toast 以其所在的输入框卡片为中心。`feedbackUi.openSession(sessionId)` Client 服务打开同一个 Session 级弹窗,不记录反馈;标题栏菜单和命令装饰共用此方法。`/feedback` 装饰是经 `ctx.commandUi.decorate` 注册的 `action`,因此菜单选中或不带参数的回车会消费触发 token 并打开弹窗,而带参数的命令行仍到达宿主命令。 每个 Session 有一个 `MessageFeedbackController` 支撑所有消息控件,以及一个 `FeedbackDialogController` 拥有弹窗草稿、提交与 toast 序号。消息控制器只读取一次 `messageFeedback.list`,且延迟到首次 hover 或 focus 才发起,而非挂载时触发;变更串行执行,每次都携带最后观察到的版本,`version-conflict` 响应带回权威条目,据此对账视图而不重新拉取。任一评分操作执行前,该行都会检查已提交条目:评分相同则调用 `retract`,它会在串行队列内重新检查评分并在并发变更后变为无操作;其他状态则携带所选评分打开弹窗。弹窗控制器按目标提交:消息目标通过消息控制器 put 一条带弹窗备注与分类的对应评分,Session 目标通过 `ctx.remote.sessionFeedback` 记录。成功会关闭草稿并弹出确认 toast;被替换的旧草稿迟到的成功只弹确认 toast、不关闭新草稿;失败会保留弹窗并弹出停留时间更长的警告 toast。 diff --git a/packages/client/ui-message-feedback/src/client/index.ts b/packages/client/ui-message-feedback/src/client/index.ts index 91e6718f62..d421bf4d72 100644 --- a/packages/client/ui-message-feedback/src/client/index.ts +++ b/packages/client/ui-message-feedback/src/client/index.ts @@ -37,6 +37,21 @@ export type { } from './slots.ts' export type { MessageFeedbackKey } from './locales.ts' +/** Opens the existing Session feedback form without submitting feedback. */ +export interface FeedbackUi { + /** + * Open the Session feedback draft without recording feedback. + * @param sessionId - Session whose feedback draft to open. + */ + openSession(sessionId: SessionId): void +} + +declare module '@deepseek-ai/cordis' { + interface Context { + feedbackUi: FeedbackUi + } +} + /** Dictionary namespace owned by this plugin. */ const NS = 'feedback' @@ -65,6 +80,11 @@ export function apply(ctx: ClientContext): void { surfaces.clear() }, 'ui-message-feedback: per-session surfaces') + const feedbackUi: FeedbackUi = { + openSession: (sessionId) => { surfaceFor(sessionId).dialog.open({ kind: 'session' }) }, + } + ctx.provide('feedbackUi', feedbackUi) + // A reconnect can only invalidate what was already read; a cold Session // stays cold until something asks for it. ctx.on('connection/reset', () => { @@ -114,7 +134,7 @@ export function apply(ctx: ClientContext): void { scope.effect(() => scope.commandUi.decorate({ name: 'feedback', available: () => true, - ui: { kind: 'action', run: (session) => { surfaceFor(session.sessionId).dialog.open({ kind: 'session' }) } }, + ui: { kind: 'action', run: (session) => { feedbackUi.openSession(session.sessionId) } }, }), 'ui-message-feedback: /feedback decoration') }) } diff --git a/packages/client/ui-message-feedback/tests/browser-plugin.client.spec.tsx b/packages/client/ui-message-feedback/tests/browser-plugin.client.spec.tsx index 2bad94b036..e41e7d599a 100644 --- a/packages/client/ui-message-feedback/tests/browser-plugin.client.spec.tsx +++ b/packages/client/ui-message-feedback/tests/browser-plugin.client.spec.tsx @@ -164,6 +164,20 @@ describe('ui-message-feedback browser plugin', () => { expect(b.dialogEntry()!.inject!(sid('s2')).hooks.dialog.getSnapshot()).toMatchObject({ target: null, toast: 0 }) }) + it('opens the shared Session dialog through feedbackUi without recording anything', async () => { + const b = await bench() + await b.fiber.await() + const dialog = b.dialogEntry()!.inject!(sid('s1')) + b.ctx.feedbackUi.openSession(sid('s1')) + expect(dialog.hooks.dialog.getSnapshot().target).toEqual({ kind: 'session' }) + expect(b.dialogEntry()!.inject!(sid('s2')).hooks.dialog.getSnapshot().target).toBeNull() + expect(b.calls).toEqual([]) + dialog.dismiss() + expect(b.calls).toEqual([]) + await b.fiber.dispose() + expect(b.ctx.get('feedbackUi')).toBeUndefined() + }) + it('records a Session remark through the sessionFeedback Remote and a message judgment through put', async () => { const b = await bench() await b.fiber.await() diff --git a/packages/session-query/session-log-export/README.i18n.yaml b/packages/session-query/session-log-export/README.i18n.yaml index ae845c1725..3e072029dd 100644 --- a/packages/session-query/session-log-export/README.i18n.yaml +++ b/packages/session-query/session-log-export/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/session-query/session-log-export/README.md -README.md: 8697b0c2c105c928f5325f953b7fb663ae68e18e -README.zh.md: fe60c6ab8cc8d2d5e7515416bb72624584c11b9d +README.md: 23388e10b9c64071a666e9842a669e37d6b9545d +README.zh.md: 2af96f8621745fd6393f03905e4c6a978dbaf400 diff --git a/packages/session-query/session-log-export/README.md b/packages/session-query/session-log-export/README.md index 8697b0c2c1..23388e10b9 100644 --- a/packages/session-query/session-log-export/README.md +++ b/packages/session-query/session-log-export/README.md @@ -27,6 +27,8 @@ English | [中文](README.zh.md) Use this package when the Web bundle should let users export a session log. It requires Connection, the command registry, Session query and persistence, and attachments. Mount the plugin, then choose `Download session log` from the Session Header's more-actions menu or type `/export`; the browser downloads `dsh-session-.zip`. +When `ui-message-feedback` is mounted, the same menu also offers `Feedback`, which opens its existing Session feedback dialog. Opening or dismissing that form does not export the Session or submit feedback. The feedback row follows the feedback plugin’s availability; export remains available independently. + ### When to choose it Choose it for a Web deployment that needs user-facing session export with a visible download dialog. Avoid it when a programmatic or Host-side export is needed: this package produces a browser download, not a Host path write. The logs are serialized from persistence read handles, so any mounted backend is supported. diff --git a/packages/session-query/session-log-export/README.zh.md b/packages/session-query/session-log-export/README.zh.md index fe60c6ab8c..2af96f8621 100644 --- a/packages/session-query/session-log-export/README.zh.md +++ b/packages/session-query/session-log-export/README.zh.md @@ -27,6 +27,8 @@ kind: "package-reference" 当 Web bundle 需要让用户导出会话日志时使用本包。它需要 Connection、命令注册表、Session 查询与持久化以及附件服务。挂载插件,然后在 Session Header 的更多操作菜单中选择 `下载 Session 日志` 或输入 `/export`;浏览器会下载 `dsh-session-.zip`。 +挂载 `ui-message-feedback` 时,同一菜单还提供“反馈”,打开已有的 Session 反馈弹窗。打开或关闭该弹窗不会导出 Session 或提交反馈。反馈入口随反馈插件的可用状态显示;导出功能保持独立可用。 + ### 何时选择 为需要带可见下载弹窗的面向用户的会话导出的 Web 部署选择它。需要程序化或 Host 侧导出时避免使用:本包产生的是浏览器下载,而非 Host 路径写入。日志从持久化读句柄序列化而来,因此任何已挂载后端都受支持。 diff --git a/packages/session-query/session-log-export/package.json b/packages/session-query/session-log-export/package.json index 75d743253d..5edbe45d8e 100644 --- a/packages/session-query/session-log-export/package.json +++ b/packages/session-query/session-log-export/package.json @@ -56,6 +56,7 @@ "@deepseek-ai/dsh-client-store": "workspace:^", "@deepseek-ai/dsh-client-ui-commands": "workspace:^", "@deepseek-ai/dsh-client-ui-conversation": "workspace:^", + "@deepseek-ai/dsh-client-ui-message-feedback": "workspace:^", "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", "@deepseek-ai/dsh-client-ui-renderer": "workspace:^", "@deepseek-ai/dsh-client-ui-session": "workspace:^", diff --git a/packages/session-query/session-log-export/src/client/HeaderAction.tsx b/packages/session-query/session-log-export/src/client/HeaderAction.tsx index cb20cb9f9d..5e5b472659 100644 --- a/packages/session-query/session-log-export/src/client/HeaderAction.tsx +++ b/packages/session-query/session-log-export/src/client/HeaderAction.tsx @@ -1,16 +1,31 @@ import { useState } from 'react' import type { ReactNode } from 'react' -import { IconDownloadOutline16, IconEllipsisOutline16, Menu } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' +import type { InjectFace } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { IconDownloadOutline16, IconEllipsisOutline16, IconPaperPlaneOutline14, Menu } from '@deepseek-ai/dsh-client-ui-primitives' import { SessionLogDownloadDialog, type SessionLogDownloadDialogProps } from './Dialog.tsx' +import type { SessionLogDownloadDialogInjected } from './Dialog.tsx' import css from './HeaderAction.module.css' +/** The optional feedback plugin controls whether the Header offers its form. */ +export interface SessionLogDownloadHeaderInjected extends SessionLogDownloadDialogInjected { + hooks: SessionLogDownloadDialogInjected['hooks'] & { feedbackAvailable: ObservableSnapshot } + /** @param sessionId - Session whose existing feedback form to open. */ + openFeedback: (sessionId: SessionId) => void +} + +/** Session download props plus the optional feedback action. */ +export type SessionLogDownloadHeaderProps = SessionLogDownloadDialogProps & InjectFace + /** - * Render the Session Header more-actions icon button, its download menu, and the shared result dialog. + * Render the Session Header menu with download and optional feedback actions. * @param props - Session runtime, download controller, and localized copy. * @returns the persistent Header action and Session-scoped dialog. */ -export function SessionLogDownloadHeaderAction(props: SessionLogDownloadDialogProps): ReactNode { - const { sessionId, useSessionLogDownload, request, t } = props +export function SessionLogDownloadHeaderAction(props: SessionLogDownloadHeaderProps): ReactNode { + const { sessionId, useSessionLogDownload, useFeedbackAvailable, request, openFeedback, t } = props + const feedbackAvailable = useFeedbackAvailable(value => value) const entry = useSessionLogDownload(state => state.bySession[String(sessionId)]) const busy = entry?.status === 'downloading' const [open, setOpen] = useState(false) @@ -22,10 +37,14 @@ export function SessionLogDownloadHeaderAction(props: SessionLogDownloadDialogPr align="end" dense onClose={() => { setOpen(false) }} - items={[{ id: 'download', label: t('menu.download'), icon: , disabled: busy }]} - onSelect={() => { + items={[ + { id: 'download', label: t('menu.download'), icon: , disabled: busy }, + ...feedbackAvailable ? [{ id: 'feedback', label: t('menu.feedback'), icon: }] : [], + ]} + onSelect={(id) => { setOpen(false) - void request(sessionId) + if (id === 'feedback') openFeedback(sessionId) + else void request(sessionId) }} anchor={( @@ -275,7 +310,7 @@ function DetailTop({ crumbLabel, crumbText, onBack, icon, actions }: { readonly crumbLabel: string readonly crumbText: string readonly onBack: () => void - readonly icon?: ReactNode + readonly icon: ReactNode readonly actions?: ReactNode }): ReactNode { return ( @@ -285,7 +320,7 @@ function DetailTop({ crumbLabel, crumbText, onBack, icon, actions }: { {crumbText}
- + {actions}
@@ -314,6 +349,7 @@ function PackageCard({ pkg, t, busy, highlighted, onOpen, onSetEnabled }: { title={title} t={t} onOpen={onOpen} + icon={packageArtwork(pkg.name)} tags={( <> {beta ? {t('statusBeta')} : null} @@ -339,7 +375,7 @@ function ItemCard({ item, t, onOpen, renderSlot }: { }): ReactNode { return (
  • - +
  • ) } @@ -353,7 +389,7 @@ function ItemDetail({ item, t, onBack, renderSlot }: { }): ReactNode { return (
    - +

    {item.label}

    @@ -382,7 +418,7 @@ function RowDetail({ pkg, row, t, onBack, renderSlot }: { const key = rowConfigKey(pkg.name, row.rowId) return (
    - } /> + } />

    {row.rowId}

    @@ -431,6 +467,7 @@ function PackageDetail({ crumbLabel={t('backToList')} crumbText={t('crumbRoot')} onBack={onBack} + icon={packageArtwork(pkg.name)} actions={(
    {pkg.installed @@ -918,31 +955,21 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { - +
    ) : null} - {state.status === 'loading' ? ( + {showsCards && state.status === 'loading' ? (

    {t('loading')}

    ) : null} - {state.status === 'unavailable' ? ( + {showsCards && state.status === 'unavailable' ? (

    {t('unavailable')}

    ) : null} - {state.status === 'error' - ? ( -
    -

    - {t('error')} -

    - -
    - ) - : null} {state.notice === null || noticeLine === null ? null : ( @@ -986,12 +1013,24 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { ? { setView({ kind: 'list' }) }} /> : null} {loaded && showsCards - ? officialCards.length === 0 && mine.length === 0 + ? officialCards.length === 0 && mine.length === 0 && state.status !== 'error' ?

    {t('empty')}

    : ( <> {renderGroup('official', t('officialTitle'), officialCards)} {renderGroup('bundles', t('bundlesTitle'), mine.map(packageCard))} + {/* A failed package read trails the groups it left incomplete: right under Official on a + first-load failure, and after the kept cards when a refresh fails over stale data. */} + {state.status === 'error' + ? ( +
    +

    + {t('error')} +

    + +
    + ) + : null} ) : null} diff --git a/packages/client/ui-plugin-manager/src/client/locales.ts b/packages/client/ui-plugin-manager/src/client/locales.ts index 63071a5cb7..f8f666a219 100644 --- a/packages/client/ui-plugin-manager/src/client/locales.ts +++ b/packages/client/ui-plugin-manager/src/client/locales.ts @@ -6,7 +6,7 @@ export const zh = { title: '插件', intro: '添加和管理插件', loading: '正在读取插件…', - error: '暂时无法读取插件。', + error: '可能由于网络问题,无法读取全部插件', unavailable: '本部署没有可管理的 profile,无法安装或启停插件。', retry: '重试', refresh: '刷新', @@ -17,9 +17,9 @@ export const zh = { bundlesTitle: '已安装', officialTitle: '官方', builtinAgentTeamTitle: '智能体团队', - builtinAgentTeamDescription: '启用智能体团队协作与团队工具。', + builtinAgentTeamDescription: '把一个任务交给一支团队:主智能体按需创建队友,成员之间发消息沟通、共同维护一块任务看板,各自认领工作;中途退出也不丢进度。', builtinAgentTeamWebTitle: '智能体团队 Web 界面', - builtinAgentTeamWebDescription: '在浏览器中查看团队成员、任务看板和成员会话。', + builtinAgentTeamWebDescription: '在浏览器里看团队干活:谁在忙、谁空闲一目了然,任务看板实时更新,点开任意成员就能进入它的会话。', builtinAutoReviewTitle: '自动授权审查', builtinAutoReviewDescription: '提供自动审查权限模式,由模型在每次工具调用前判断是否授权。', statusProblem: '异常', @@ -168,7 +168,7 @@ export const en = { title: 'Plugins', intro: 'Add and manage plugins', loading: 'Reading plugins…', - error: 'Plugins are temporarily unavailable.', + error: 'Could not read all plugins, possibly due to a network problem', unavailable: 'This deployment runs without a manageable profile, so plugins cannot be installed or switched here.', retry: 'Retry', refresh: 'Refresh', @@ -179,9 +179,9 @@ export const en = { bundlesTitle: 'Installed', officialTitle: 'Official', builtinAgentTeamTitle: 'Agent Teams', - builtinAgentTeamDescription: 'Enable agent team collaboration and team tools.', + builtinAgentTeamDescription: 'Hand a task to a team: the lead agent creates teammates as needed, members message each other and claim work on a shared task board, and progress survives even if someone drops off mid-way.', builtinAgentTeamWebTitle: 'Agent Teams Web UI', - builtinAgentTeamWebDescription: 'View team members, the task board, and teammate sessions in the browser.', + builtinAgentTeamWebDescription: 'Watch the team at work in the browser: see who is busy and who is idle at a glance, follow the task board live, and open any member\'s own session with a click.', builtinAutoReviewTitle: 'Auto Authorization Review', builtinAutoReviewDescription: 'Add an Auto review permission mode that uses the model to assess authorization before each tool call.', statusProblem: 'Problem', diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 3e84437d9f..1e8fc33423 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -80,3 +80,6 @@ export type { MarkdownCodeLabels, MarkdownFileMentions, MarkdownLabels, Markdown export { extractMarkdownPlainText } from './markdown/plain-text.ts' export type { MarkdownPlainTextMode, MarkdownPlainTextOptions } from './markdown/plain-text.ts' export * from './icons/index.tsx' +export { + PluginArtworkTeam, PluginArtworkTerminal, PluginArtworkLoop, PluginArtworkSubagent, PluginArtworkSearch, PluginArtworkDefault, +} from './plugin-artwork.tsx' diff --git a/packages/client/ui-primitives/src/plugin-artwork.tsx b/packages/client/ui-primitives/src/plugin-artwork.tsx new file mode 100644 index 0000000000..2e70e6a71e --- /dev/null +++ b/packages/client/ui-primitives/src/plugin-artwork.tsx @@ -0,0 +1,107 @@ +/** + * Fixed-palette plugin artwork for the plugin management surfaces. Unlike the + * ic_ds_* set these glyphs carry their own brand colors and gradients instead + * of riding currentColor; all draw on a 36×36 viewBox and take {size, className}. + */ +import type { IconProps } from './icons/props.ts' + +/** Agent-team plugin artwork (four interlocking quadrants). */ +export const PluginArtworkTeam = ({ size = 36, className }: IconProps) => ( + + + + + + + + + + + + +) + +/** Terminal plugin artwork (prompt chevron and cursor bar). */ +export const PluginArtworkTerminal = ({ size = 36, className }: IconProps) => ( + + + + +) + +/** Agent-loop plugin artwork (four leaves circling a center). */ +export const PluginArtworkLoop = ({ size = 36, className }: IconProps) => ( + + + + + + + + + + + + +) + +/** Subagent plugin artwork (two stacked rounded squares); also marks one row inside a bundle. */ +export const PluginArtworkSubagent = ({ size = 36, className }: IconProps) => ( + + + + + + + + + + + + + + +) + +/** + * Web-search plugin artwork (conic-gradient ring and handle). SVG has no + * native conic gradient, so the ring clips an HTML div painted with CSS + * `conic-gradient` — the same emulation Figma exports; it renders inline in + * the browser UI but would stay empty in an `` or mask context. + */ +export const PluginArtworkSearch = ({ size = 36, className }: IconProps) => ( + + + + + +
    + + + + + + + + + +) + +/** Default plugin artwork for plugins without one of their own (connector blocks and a node). */ +export const PluginArtworkDefault = ({ size = 36, className }: IconProps) => ( + + + + + + + + + +) diff --git a/packages/client/ui-settings-plugins/src/client/locales.ts b/packages/client/ui-settings-plugins/src/client/locales.ts index e45dbb5cd0..562ed2d1e8 100644 --- a/packages/client/ui-settings-plugins/src/client/locales.ts +++ b/packages/client/ui-settings-plugins/src/client/locales.ts @@ -42,17 +42,17 @@ export const en: Record = { saveFailed: 'The deployment did not accept these values; they were left for you to correct.', invalidNumber: 'Enter a number, or leave blank to use the default.', bashTitle: 'Shell', - bashDescription: 'Limits every command the agent runs.', + bashDescription: 'Limit how long each command may run and how much it may output.', bashTimeoutMs: 'Command timeout (ms)', bashTimeoutMsHint: 'How long one command may run before it is terminated.', bashMaxOutputBytes: 'Output cap per stream (bytes)', bashMaxOutputBytesHint: 'Output beyond this spills to a temporary file rather than being lost.', agentLoopTitle: 'Agent loop', - agentLoopDescription: 'How the agent dispatches tool calls.', + agentLoopDescription: 'Control how the Agent dispatches tool calls.', agentLoopMaxParallel: 'Parallel tool calls', agentLoopMaxParallelHint: 'Upper bound on parallel-safe calls running at once within one step.', webSearchTitle: 'Web search', - webSearchDescription: 'The DeepSeek search provider.', + webSearchDescription: 'Set up the DeepSeek search provider.', webSearchApiKey: 'API key', webSearchApiKeyHint: 'Stored outside the settings file. Leave blank to keep the current key.', webSearchApiKeySet: 'A key is configured.', @@ -107,17 +107,17 @@ export const zh: Record = { saveFailed: '本部署没有接受这些值,已保留供你修改。', invalidNumber: '请填数字;留空表示使用默认值。', bashTitle: '终端', - bashDescription: '限制 agent 运行的每一条命令。', + bashDescription: '限制每条命令最多能跑多久、最多输出多少内容。', bashTimeoutMs: '命令超时(毫秒)', bashTimeoutMsHint: '单条命令允许运行多久,超时即终止。', bashMaxOutputBytes: '单流输出上限(字节)', bashMaxOutputBytesHint: '超出部分会转存到临时文件,而不是被丢弃。', agentLoopTitle: 'Agent 循环', - agentLoopDescription: 'Agent 如何派发工具调用。', + agentLoopDescription: '控制 Agent 派发工具调用的方式。', agentLoopMaxParallel: '并行工具调用数', agentLoopMaxParallelHint: '同一步内最多同时运行多少个可并行的调用。', webSearchTitle: '网页搜索', - webSearchDescription: 'DeepSeek 搜索提供方。', + webSearchDescription: '设置 DeepSeek 的搜索提供方。', webSearchApiKey: 'API Key', webSearchApiKeyHint: '不写入设置文件。留空表示保持当前密钥。', webSearchApiKeySet: '已配置密钥。', From e0264148b003197e24eeaedb69b7fd56e0656faa Mon Sep 17 00:00:00 2001 From: winewill Date: Fri, 18 Sep 2026 11:54:54 +0800 Subject: [PATCH 09/45] perf(desktop): configure macOS packaging concurrency and retain phase logs --- apps/desktop/.env.macos.example | 9 + apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 16 +- apps/desktop/README.zh.md | 16 +- apps/desktop/package.json | 1 + .../scripts/desktop-package-environment.mjs | 4 +- apps/desktop/scripts/logged-notarytool.d.mts | 9 + apps/desktop/scripts/logged-notarytool.mjs | 83 +++++++ .../scripts/macos-notarization-proxy.ts | 202 ++++++++++++++++++ .../scripts/macos-package-settings.d.mts | 23 ++ .../scripts/macos-package-settings.mjs | 47 ++++ .../scripts/notarize-macos-disk-images.mjs | 4 +- apps/desktop/scripts/notarize-macos.d.mts | 8 + apps/desktop/scripts/notarize-macos.mjs | 15 ++ apps/desktop/scripts/package-macos.ts | 14 +- apps/desktop/scripts/package-target.ts | 70 ++++-- apps/desktop/scripts/packaging-run.d.mts | 3 +- apps/desktop/scripts/packaging-run.mjs | 33 +-- apps/desktop/scripts/packaging-step.d.mts | 10 + apps/desktop/scripts/packaging-step.mjs | 38 ++++ apps/desktop/scripts/prepare-dsh.ts | 11 +- apps/desktop/scripts/prepare-runtime.ts | 9 +- .../tests/desktop-package-environment.spec.ts | 11 + .../tests/logged-notarytool-exit.spec.ts | 33 +++ apps/desktop/tests/logged-notarytool.spec.ts | 82 +++++++ .../tests/macos-notarization-proxy.spec.ts | 170 +++++++++++++++ .../tests/macos-package-settings.spec.ts | 34 +++ .../tests/package-target-stages.spec.ts | 47 ++++ apps/desktop/tests/packaging-run.spec.ts | 26 +++ apps/desktop/tests/packaging-step.spec.ts | 39 ++++ 30 files changed, 1019 insertions(+), 52 deletions(-) create mode 100644 apps/desktop/scripts/logged-notarytool.d.mts create mode 100755 apps/desktop/scripts/logged-notarytool.mjs create mode 100644 apps/desktop/scripts/macos-notarization-proxy.ts create mode 100644 apps/desktop/scripts/macos-package-settings.d.mts create mode 100644 apps/desktop/scripts/macos-package-settings.mjs create mode 100644 apps/desktop/scripts/notarize-macos.d.mts create mode 100644 apps/desktop/scripts/notarize-macos.mjs create mode 100644 apps/desktop/scripts/packaging-step.d.mts create mode 100644 apps/desktop/scripts/packaging-step.mjs create mode 100644 apps/desktop/tests/logged-notarytool-exit.spec.ts create mode 100644 apps/desktop/tests/logged-notarytool.spec.ts create mode 100644 apps/desktop/tests/macos-notarization-proxy.spec.ts create mode 100644 apps/desktop/tests/macos-package-settings.spec.ts create mode 100644 apps/desktop/tests/packaging-step.spec.ts diff --git a/apps/desktop/.env.macos.example b/apps/desktop/.env.macos.example index 53c3945f60..a63e9df809 100644 --- a/apps/desktop/.env.macos.example +++ b/apps/desktop/.env.macos.example @@ -4,6 +4,15 @@ DSH_DESKTOP_APP_ID=com.deepseek.harness DSH_DESKTOP_AUTO_UPDATE_ENV=test DOWNLOAD_TEST_ORIGIN= +# Workspace tarball workers; omit to use 4. Must be a positive integer. +DSH_DESKTOP_MACOS_PACK_CONCURRENCY=4 +# Optional independent proxy origins; empty values preserve inherited networking. +# Downloads: HTTP/HTTPS proxy for Electron, runtime assets, pnpm and builder downloads. +DSH_DESKTOP_MACOS_DOWNLOAD_PROXY= +# Apple tools: HTTP proxy temporarily applied to the active macOS network service. +# Requires permission to change system proxies; affects other applications during notarization. +DSH_DESKTOP_MACOS_NOTARIZATION_PROXY= + # The selected mandatory-update origin is required, including unsigned and preparation builds. DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN=https://harness-test.deepseek.com DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN=https://harness.deepseek.com diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 909bef683c..9746e5c403 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: c2a1f4df103d5fe74f4a25aa1bcfc1f8e38d3b1e -README.zh.md: 9dda03b4b40a7b46bf5e0f1404f77d73d397bfa4 +README.md: 09452eb23895040ad7f29967beb5aaef443c0b9d +README.zh.md: de3e317433056a6e3c92f11a1615e56d761d2e1a diff --git a/apps/desktop/README.md b/apps/desktop/README.md index c2a1f4df10..09452eb238 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -186,7 +186,21 @@ The macOS configuration uses the required release environment instead of accepti macOS signing visits real files without following Framework symlink aliases. PAK resources retain all shipped languages and are sealed by the enclosing Framework or application signature instead of receiving individual signatures. The [release policy](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) owns the dependency patch and verification requirements. -Company proxies can accelerate uploads to Apple's notarization service. See the company internal documentation for configuration. +Mac package commands print `DESKTOP_PACKAGING_RECORD` with a unique directory under `apps/desktop/.desktop-build/packaging-runs/`. After reading local configuration, each run retains `run.json` (version, Git commit, dirty-worktree flag, target and Node version), `events.jsonl` (timestamped phases, durations, parallel output attribution and proxy restoration), redacted child `stdout.log` / `stderr.log`, and `result.json` (overall outcome, stage results and artifact directory). Events also record pack concurrency and whether each proxy is configured. Logs survive failures and later builds; no automatic deletion runs. Missing `result.json` means completion is unconfirmed. Known credential values are redacted; environments and notarytool authentication arguments are not recorded. Nested phase durations overlap and must not be added together. + +App and DMG notarization each record a submission ID and separate `notarytool:upload:*` and `notarytool:wait:*` durations. Upload uses `submit --no-wait` and includes authentication, local validation, transfer and server acceptance; it is not pure transfer time. Waiting starts after that command returns and includes polling and remaining Apple processing; Apple can start processing before upload submission returns. Apple status and diagnostic logs are retained, including rejection; signature checks, acceptance checks and stapling remain owned by `@electron/notarize`. Directory-only package commands use this same measured App notarization path. Individual subprocess output remains live in the terminal, while phase failures and nested errors are retained in the journal. The configuration-only `check:package` command creates no run log. + +Mac packaging reads three tuning fields from `.env.macos`: + +| Setting | Default | Scope | +|---|---|---| +| `DSH_DESKTOP_MACOS_PACK_CONCURRENCY` | `4` | Workers for first-party and vendor workspace tarballs; requires a positive integer. | +| `DSH_DESKTOP_MACOS_DOWNLOAD_PROXY` | Empty | HTTP/HTTPS proxy origin for Electron, runtime assets, pnpm installation and builder downloads. | +| `DSH_DESKTOP_MACOS_NOTARIZATION_PROXY` | Empty | HTTP proxy origin for Apple tools through temporary system proxy settings. | + +The proxy fields are independent and reject URL credentials, paths, queries and fragments. Empty values preserve inherited networking. An explicit download proxy replaces child-process proxy variables and bypasses local hosts only; it does not change system settings. Windows and standalone `release:pack` retain their existing concurrency defaults. Company proxy addresses belong in the ignored local file; see internal documentation for addresses. + +Apple tooling uses the active macOS network service's HTTP/HTTPS proxies. Configured notarization routing checks proxy reachability, saves that service's settings, enables the proxy around both artifact lanes, and restores the saved values after both lanes settle. Directory-only builds apply it to App notarization after the signed directory build. This temporarily affects other applications and requires permission to change system proxies; PAC, auto-discovery, SOCKS and authenticated proxy configurations must be disabled first. One per-user lock prevents overlapping proxy transactions across checkouts; other users and network-setting tools must not change these settings concurrently. SIGINT/SIGTERM wait for active work before restoration. After forced termination or a restoration error, stop any remaining notarization processes and run `pnpm --dir apps/desktop run restore:mac-proxy`; the saved record remains until restoration succeeds. Configuration checks validate URL syntax without changing system settings or contacting the proxy. ### Unsigned Windows test installer diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 9dda03b4b4..de3e317433 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -187,7 +187,21 @@ macOS 配置使用必填发布环境,不会接受钥匙串中最先发现的 macOS 签名遍历真实文件,不跟随 Framework 的软链接别名。PAK 资源保留全部随附语言,由外层 Framework 或应用签名记录完整性,不逐个签名。[发布策略](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)负责依赖补丁和验证要求。 -可通过公司代理加速向 Apple 公证服务上传。代理配置参见公司内部文档。 +Mac 打包命令通过 `DESKTOP_PACKAGING_RECORD` 输出 `apps/desktop/.desktop-build/packaging-runs/` 下的唯一目录。读取本地配置后,每次运行保留 `run.json`(版本、Git 提交、工作区是否有改动、目标及 Node 版本)、`events.jsonl`(带时间戳的阶段、耗时、并行输出归属及代理恢复状态)、脱敏后的子进程 `stdout.log` / `stderr.log`,以及 `result.json`(整体结果、阶段结果和产物目录)。事件还记录打包并发数及各代理是否配置。失败和后续打包不会清除日志;没有自动删除流程。缺少 `result.json` 表示完成状态未经确认。已知凭据值会被遮盖;不记录环境变量全集或 notarytool 认证参数。嵌套阶段的耗时存在重叠,不能直接相加。 + +App 和 DMG 公证分别记录 submission ID,以及独立的 `notarytool:upload:*` 和 `notarytool:wait:*` 耗时。上传使用 `submit --no-wait`,包含认证、本地校验、传输和服务端受理,并非纯传输时间。等待从该命令返回后开始,包含轮询及剩余的 Apple 处理时间;Apple 可能在上传提交命令返回前已开始处理。日志保留 Apple 状态与诊断信息,包括拒绝结果;签名检查、接受状态校验和 stapling 仍由 `@electron/notarize` 负责。仅生成目录的打包命令也使用同一条可计时的 App 公证路径。各子进程输出仍实时显示在终端,阶段失败及嵌套错误保留在事件日志中。仅检查配置的 `check:package` 命令不创建运行日志。 + +Mac 打包从 `.env.macos` 读取三个调优字段: + +| 设置 | 默认值 | 作用范围 | +|---|---|---| +| `DSH_DESKTOP_MACOS_PACK_CONCURRENCY` | `4` | 第一方与 vendor workspace tarball 的打包 worker 数;必须是正整数。 | +| `DSH_DESKTOP_MACOS_DOWNLOAD_PROXY` | 空 | Electron、运行时资源、pnpm 安装及 builder 下载使用的 HTTP/HTTPS 代理 origin。 | +| `DSH_DESKTOP_MACOS_NOTARIZATION_PROXY` | 空 | 通过临时系统代理设置供 Apple 工具使用的 HTTP 代理 origin。 | + +两个代理字段互相独立,拒绝 URL 中的凭证、路径、查询参数和片段。空值沿用继承的网络设置。显式下载代理会替换子进程的代理变量,仅绕过本地主机;它不修改系统设置。Windows 与独立 `release:pack` 保持现有并发默认值。公司代理地址仅写入 Git 忽略的本地文件;具体地址参见内部文档。 + +Apple 工具使用 macOS 当前活动网络服务的 HTTP/HTTPS 代理。配置公证代理后,打包会检查代理可达性、保存该服务的设置,在两条产物任务期间启用代理,并在两条任务均结束后恢复原值。仅生成目录的打包会在签名目录构建完成后的 App 公证期间启用代理。这会临时影响其他应用,并要求修改系统代理的权限;必须先禁用 PAC、自动发现、SOCKS 及需要认证的代理配置。用户级锁阻止不同 checkout 的代理事务重叠;其他用户及网络设置工具不得同时修改这些设置。SIGINT/SIGTERM 会等待活动任务结束后恢复。强制终止或恢复失败后,先停止残留公证进程,再运行 `pnpm --dir apps/desktop run restore:mac-proxy`;保存的记录会保留到恢复成功。配置检查仅验证 URL 语法,不修改系统设置或连接代理。 ### 未签名 Windows 测试安装包 diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c060f1c673..08ff31f066 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -21,6 +21,7 @@ "verify:mac-signature": "node scripts/verify-macos-signature.mjs", "package": "tsx scripts/package-target.ts", "check:package": "tsx scripts/package-target.ts --check", + "restore:mac-proxy": "tsx scripts/macos-notarization-proxy.ts", "package:dir": "tsx scripts/package-target.ts --dir", "package:mac:arm64": "tsx scripts/package-target.ts mac-arm64", "package:mac:arm64:dir": "tsx scripts/package-target.ts mac-arm64 --dir", diff --git a/apps/desktop/scripts/desktop-package-environment.mjs b/apps/desktop/scripts/desktop-package-environment.mjs index 0166288df4..7eb7c0cb36 100644 --- a/apps/desktop/scripts/desktop-package-environment.mjs +++ b/apps/desktop/scripts/desktop-package-environment.mjs @@ -8,11 +8,12 @@ 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 { resolveMacOSPackageSettings } from './macos-package-settings.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 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 MACOS_SETTING = /^(?:DSH_DESKTOP_MACOS_(?:SIGNING_IDENTITY|TEAM_ID|PACK_CONCURRENCY|DOWNLOAD_PROXY|NOTARIZATION_PROXY)|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'] @@ -76,6 +77,7 @@ function requireReadableFile(environment, name) { export function validateDesktopPackageEnvironment(environment, target, options = {}) { resolveDesktopAppId(environment) resolveDesktopPolicyEnvironment(environment) + if (target.platform === 'darwin') resolveMacOSPackageSettings(environment) if (options.unsigned) return if (!options.prepareOnly) resolveDesktopAutoUpdateConfig(environment, target.platform, target.arch) if (target.platform === 'win32') { diff --git a/apps/desktop/scripts/logged-notarytool.d.mts b/apps/desktop/scripts/logged-notarytool.d.mts new file mode 100644 index 0000000000..552576ecf9 --- /dev/null +++ b/apps/desktop/scripts/logged-notarytool.d.mts @@ -0,0 +1,9 @@ +/** Separate upload and Apple processing timings without replacing electron-notarize's qualification. */ +/** + * Run the requested Apple command, splitting submit --wait into submit --no-wait and wait. + * @param args Arguments from the pinned electron-notarize library. + * @param directory Existing packaging journal. + * @param invoke Apple command executor. + * @returns Final tool output consumed by electron-notarize; upload failure prevents waiting. + */ +export function runLoggedNotarytool(args: readonly string[], directory?: string, invoke?: (args: readonly string[]) => Promise): Promise diff --git a/apps/desktop/scripts/logged-notarytool.mjs b/apps/desktop/scripts/logged-notarytool.mjs new file mode 100755 index 0000000000..ae2a9bf055 --- /dev/null +++ b/apps/desktop/scripts/logged-notarytool.mjs @@ -0,0 +1,83 @@ +#!/usr/bin/env node +/** Adapt electron-notarize's combined submit/wait into separately timed Apple operations. */ +import { execFile } from 'node:child_process' +import { basename, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { recordPackagingEvent, packagingOutputRedactor } from './packaging-run.mjs' +import { packagingStep } from './packaging-step.mjs' + +const exec = promisify(execFile) +const AUTH_FLAGS = new Set(['--apple-id', '--password', '--team-id', '--key', '--key-id', '--issuer', '--keychain', '--keychain-profile']) + +async function execute(args) { + try { + const { stdout } = await exec('/usr/bin/xcrun', ['notarytool', ...args], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }) + return stdout + } catch (error) { + // Apple can report rejection with a nonzero exit; electron-notarize needs its JSON ID to retrieve diagnostics. + if (args[0] === 'wait' && typeof error.code === 'number' && typeof error.stdout === 'string' && error.stdout.trim()) return error.stdout + throw error + } +} + +/** + * Return only the final JSON to electron-notarize, which owns acceptance checks and stapling retries. + * @param {readonly string[]} args Arguments supplied by the pinned electron-notarize library. + * @param {string | undefined} directory Existing packaging journal. + * @param {(args: readonly string[]) => Promise} invoke Apple command executor. + * @returns {Promise} Tool output; a failed upload never starts waiting. + */ +export async function runLoggedNotarytool(args, directory, invoke = execute) { + const credentials = args.filter((_, index) => AUTH_FLAGS.has(args[index - 1])) + if (args[0] !== 'submit' || !args.includes('--wait')) { + return packagingStep(directory, `notarytool:${args[0]}`, async () => { + const output = await invoke(args) + if (directory && args[0] === 'log') { + let text = '' + const redactor = packagingOutputRedactor(credentials, chunk => { text += chunk }) + redactor.write(Buffer.from(output)) + redactor.end() + recordPackagingEvent(directory, { type: 'notary-diagnostics', submissionId: args[1], text }) + } + return output + }, credentials) + } + const artifact = basename(args[1]) + const uploaded = await packagingStep(directory, `notarytool:upload:${artifact}`, + () => invoke(args.filter(arg => arg !== '--wait').concat('--no-wait')), credentials) + const submission = JSON.parse(uploaded) + if (typeof submission.id !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/iu.test(submission.id)) { + throw new Error('desktop notarization: submit returned no valid submission ID') + } + if (directory) recordPackagingEvent(directory, { type: 'notary-submission', artifact, submissionId: submission.id }) + const authorization = args.flatMap((arg, index) => AUTH_FLAGS.has(arg) ? [arg, args[index + 1]] : []) + const rejected = new Error('desktop notarization: Apple did not accept the submission') + let rejectedOutput + try { + return await packagingStep(directory, `notarytool:wait:${artifact}`, async () => { + const output = await invoke(['wait', submission.id, ...authorization, '--output-format', 'json']) + const result = JSON.parse(output) + if (directory) recordPackagingEvent(directory, { type: 'notary-result', artifact, submissionId: submission.id, status: result.status }) + if (result.id !== submission.id) throw new Error('desktop notarization: wait returned a different submission ID') + if (result.status !== 'Accepted') { + rejectedOutput = output + throw rejected + } + return output + }, credentials) + } catch (error) { + // Preserve rejected JSON for electron-notarize's diagnostic retrieval without marking the wait successful. + if (error === rejected) return rejectedOutput + throw error + } +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) { + try { process.stdout.write(await runLoggedNotarytool(process.argv.slice(2), process.env.DSH_DESKTOP_PACKAGING_RUN_DIR)) } + catch { + // execFile errors include credential-bearing argv; detailed failures are redacted in the journal. + process.stderr.write('desktop notarization: Apple command failed; see packaging events.jsonl\n') + process.exitCode = 1 + } +} diff --git a/apps/desktop/scripts/macos-notarization-proxy.ts b/apps/desktop/scripts/macos-notarization-proxy.ts new file mode 100644 index 0000000000..1da03c4d00 --- /dev/null +++ b/apps/desktop/scripts/macos-notarization-proxy.ts @@ -0,0 +1,202 @@ +/** Temporarily route Apple tools through the active macOS service; retain recovery data before mutation. */ + +import { execFileSync } from 'node:child_process' +import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { connect } from 'node:net' +import { homedir } from 'node:os' +import { dirname, join, resolve } from 'node:path' + +interface ProxyState { + readonly enabled: boolean + readonly server: string + readonly port: number +} +interface ProxyRecord { + readonly pid: number + readonly service: string + readonly http: ProxyState + readonly https: ProxyState +} +interface ProxyOperations { + readonly command: (executable: string, args: readonly string[]) => string + readonly reachable: (url: URL) => Promise + readonly ownerAlive: (pid: number) => boolean +} + +const LOCK = join(homedir(), 'Library', 'Caches', 'com.deepseek.harness', 'notarization-proxy') +const RECOVERY = 'pnpm --dir apps/desktop run restore:mac-proxy' +const NETWORKSETUP = '/usr/sbin/networksetup' +const operations: ProxyOperations = { + command(executable, args) { + return execFileSync(executable, [...args], { encoding: 'utf8', env: { PATH: '/usr/bin:/bin:/usr/sbin:/sbin', LANG: 'C' }, timeout: 15_000 }) + }, + reachable(url) { + return new Promise((resolveConnection, reject) => { + const socket = connect({ host: url.hostname.replace(/^\[|\]$/gu, ''), port: Number(url.port || '80') }) + let failure: Error | undefined + socket.setTimeout(5000, () => socket.destroy(new Error('desktop package: notarization proxy connection timed out'))) + socket.once('error', () => { failure = new Error('desktop package: notarization proxy is unreachable') }) + socket.once('connect', () => socket.destroy()) + socket.once('close', () => { if (failure) reject(failure); else resolveConnection() }) + }) + }, + ownerAlive(pid) { + try { process.kill(pid, 0); return true } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ESRCH') return false + throw error + } + }, +} + +function readProxy(service: string, secure: boolean, ops: ProxyOperations): ProxyState { + const output = ops.command(NETWORKSETUP, [secure ? '-getsecurewebproxy' : '-getwebproxy', service]) + const enabled = /^Enabled: (Yes|No)$/mu.exec(output)?.[1] + const server = /^Server: (.*)$/mu.exec(output)?.[1] + const port = /^Port: (\d+)$/mu.exec(output)?.[1] + if (enabled === undefined || server === undefined || port === undefined + || !/^Authenticated Proxy Enabled: 0$/mu.test(output) || Number(port) > 65535) { + throw new Error('desktop package: cannot preserve system proxy settings; authenticated proxies are unsupported') + } + return { enabled: enabled === 'Yes', server, port: Number(port) } +} + +function activeService(ops: ProxyOperations): string { + const route = ops.command('/sbin/route', ['-n', 'get', 'default']) + const device = /^\s*interface: (\S+)$/mu.exec(route)?.[1] + const services = ops.command(NETWORKSETUP, ['-listnetworkserviceorder']) + const matches = [...services.matchAll(/^\(\d+\) (.+)\n\(Hardware Port: .+, Device: ([^)]+)\)$/gmu)] + .filter(match => match[2] === device) + if (!device || matches.length !== 1) throw new Error('desktop package: cannot identify one active network service for notarization proxy') + return matches[0]![1]! +} + +function setProxy(service: string, secure: boolean, state: ProxyState, ops: ProxyOperations): void { + ops.command(NETWORKSETUP, [secure ? '-setsecurewebproxy' : '-setwebproxy', service, state.server, String(state.port), 'off']) + ops.command(NETWORKSETUP, [secure ? '-setsecurewebproxystate' : '-setwebproxystate', service, state.enabled ? 'on' : 'off']) + const actual = readProxy(service, secure, ops) + if (JSON.stringify(actual) !== JSON.stringify(state)) throw new Error('desktop package: system proxy change did not take effect') +} + +function restore(record: ProxyRecord, ops: ProxyOperations): void { + const errors: unknown[] = [] + for (const [secure, state] of [[false, record.http], [true, record.https]] as const) { + try { setProxy(record.service, secure, state, ops) } catch (error) { errors.push(error) } + } + if (errors.length) throw new AggregateError(errors, `desktop package: proxy restoration failed; retry ${RECOVERY}`) +} + +function readRecord(lock: string): ProxyRecord { + const value: unknown = JSON.parse(readFileSync(join(lock, 'original.json'), 'utf8')) + function isState(state: unknown): state is ProxyState { + if (state === null || typeof state !== 'object') return false + const s = state as Partial + return typeof s.enabled === 'boolean' && typeof s.server === 'string' && !/[\r\n\0]/u.test(s.server) + && typeof s.port === 'number' && Number.isInteger(s.port) && s.port >= 0 && s.port <= 65535 + } + if (value === null || typeof value !== 'object') throw new Error('desktop package: invalid proxy recovery record') + const record = value as Partial + if (!Number.isSafeInteger(record.pid) || record.pid! <= 0 || typeof record.service !== 'string' + || !record.service || /[\r\n\0]/u.test(record.service) || !isState(record.http) || !isState(record.https)) { + throw new Error('desktop package: invalid proxy recovery record') + } + return record as ProxyRecord +} + +/** + * Restore an interrupted run only after its owner exits; active or incomplete records fail closed. + * @param lock Per-user lock shared across checkouts; tests supply a private directory. + * @param ops Host operations; tests supply isolated system settings. + * @returns Nothing; retains the record when restoration fails. + */ +export function restoreMacOSNotarizationProxy(lock: string = LOCK, ops: ProxyOperations = operations): void { + const record = readRecord(lock) + if (ops.ownerAlive(record.pid)) throw new Error('desktop package: proxy owner is still running; wait for packaging to finish') + const recoveryLock = join(lock, 'recovering') + mkdirSync(recoveryLock, { mode: 0o700 }) + try { + restore(record, ops) + rmSync(lock, { recursive: true }) + } finally { rmSync(recoveryLock, { recursive: true, force: true }) } +} + +/** + * Hold the system HTTP/HTTPS proxy until all callback work settles, including after SIGINT/SIGTERM. + * @param proxyUrl Validated HTTP proxy origin, or undefined for unchanged system networking. + * @param action Work that drains every notarization lane before resolving or rejecting. + * @param lock Per-user exclusive recovery directory, shared across checkouts. + * @param ops Host operations; tests supply isolated system settings. + * @param report Reports restoration state to the packaging journal without exposing proxy addresses. + * @returns Callback result after verified restoration; forced termination leaves a recovery record. + */ +export async function withMacOSNotarizationProxy( + proxyUrl: string | undefined, + action: () => Promise, + lock: string = LOCK, + ops: ProxyOperations = operations, + report: (status: 'not-used' | 'restoration-pending' | 'enabled' | 'restored' | 'restore-failed') => void = () => {}, +): Promise { + if (proxyUrl === undefined) { report('not-used'); return action() } + const url = new URL(proxyUrl) + await ops.reachable(url) + mkdirSync(dirname(lock), { recursive: true, mode: 0o700 }) + try { mkdirSync(lock, { mode: 0o700 }) } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error + throw new Error(`desktop package: another run or interrupted proxy record exists; after its owner exits, run ${RECOVERY}`) + } + let original: ProxyRecord | undefined + let saved = false + let workError: unknown + let signal: string | undefined + const interrupted = (received: string) => { + signal = received + process.stderr.write('desktop package: waiting for notarization work to stop before restoring the system proxy\n') + } + process.on('SIGINT', interrupted) + process.on('SIGTERM', interrupted) + try { + const service = activeService(ops) + // PAC, discovery and SOCKS can override explicit proxies; do not silently change those policies. + const pac = ops.command(NETWORKSETUP, ['-getautoproxyurl', service]) + const discovery = ops.command(NETWORKSETUP, ['-getproxyautodiscovery', service]) + const socks = ops.command(NETWORKSETUP, ['-getsocksfirewallproxy', service]) + if (!/^Enabled: No$/mu.test(pac) || !/^Auto Proxy Discovery: Off$/mu.test(discovery) || !/^Enabled: No$/mu.test(socks)) { + throw new Error('desktop package: disable PAC, proxy discovery and SOCKS on the active service before configuring a notarization proxy') + } + original = { pid: process.pid, service, http: readProxy(service, false, ops), https: readProxy(service, true, ops) } + writeFileSync(join(lock, 'original.json'), `${JSON.stringify(original)}\n`, { flag: 'wx', mode: 0o600, flush: true }) + saved = true + report('restoration-pending') + const state = { enabled: true, server: url.hostname.replace(/^\[|\]$/gu, ''), port: Number(url.port || '80') } + setProxy(service, false, state, ops) + setProxy(service, true, state, ops) + report('enabled') + const result = await action() + if (signal) throw new Error(`desktop package: interrupted by ${signal}`) + return result + } catch (error) { + workError = error + throw error + } finally { + try { + if (saved && original) { + try { restore(original, ops) } catch (error) { report('restore-failed'); throw error } + report('restored') + } + rmSync(lock, { recursive: true }) + } catch (error) { + if (workError !== undefined) { + throw new AggregateError([workError, error], `desktop package: work and proxy cleanup failed; run ${RECOVERY}`) + } + throw error + } finally { + process.off('SIGINT', interrupted) + process.off('SIGTERM', interrupted) + } + } +} + +if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) { + if (process.platform !== 'darwin') throw new Error('desktop package: proxy recovery requires macOS') + restoreMacOSNotarizationProxy() + console.log('desktop package: original system proxy restored') +} diff --git a/apps/desktop/scripts/macos-package-settings.d.mts b/apps/desktop/scripts/macos-package-settings.d.mts new file mode 100644 index 0000000000..09b991752e --- /dev/null +++ b/apps/desktop/scripts/macos-package-settings.d.mts @@ -0,0 +1,23 @@ +/** File-owned macOS packaging concurrency and stage-specific proxies. */ + +/** Validated settings shared by preflight and stage execution. */ +export interface MacOSPackageSettings { + readonly packConcurrency: number + readonly downloadProxy?: string + readonly notarizationProxy?: string +} + +/** + * Validate tuning before any build or network operation. + * @param environment File-owned packaging settings. + * @returns Resolved settings; empty proxy fields preserve inherited networking. + */ +export function resolveMacOSPackageSettings(environment: NodeJS.ProcessEnv): MacOSPackageSettings + +/** + * Override routing only in download-capable subprocesses without mutating the parent. + * @param environment Parent environment. + * @param proxyUrl Validated proxy, or undefined to preserve inherited settings. + * @returns Child environment; explicit routing bypasses only local hosts. + */ +export function macOSDownloadEnvironment(environment: NodeJS.ProcessEnv, proxyUrl?: string): NodeJS.ProcessEnv diff --git a/apps/desktop/scripts/macos-package-settings.mjs b/apps/desktop/scripts/macos-package-settings.mjs new file mode 100644 index 0000000000..1ed93c3377 --- /dev/null +++ b/apps/desktop/scripts/macos-package-settings.mjs @@ -0,0 +1,47 @@ +/** Resolve file-owned macOS packaging concurrency and stage-specific proxies. */ + +function proxy(environment, name, protocols) { + const value = environment[name]?.trim() + if (!value) return undefined + let parsed + try { parsed = new URL(value) } catch { throw new Error(`desktop package: ${name} must be a proxy URL`) } + if (!protocols.includes(parsed.protocol) || !parsed.hostname || parsed.username || parsed.password + || parsed.pathname !== '/' || parsed.search || parsed.hash) { + throw new Error(`desktop package: ${name} requires an unauthenticated ${protocols.join('/')} proxy origin`) + } + return parsed.origin +} + +/** + * Validate tuning before any build or network operation. + * @param {NodeJS.ProcessEnv} environment File-owned packaging settings. + * @returns {{packConcurrency: number, downloadProxy?: string, notarizationProxy?: string}} Resolved settings; empty proxy fields preserve inherited networking. + */ +export function resolveMacOSPackageSettings(environment) { + const concurrency = environment.DSH_DESKTOP_MACOS_PACK_CONCURRENCY ?? '4' + if (!/^[1-9]\d*$/u.test(concurrency) || !Number.isSafeInteger(Number(concurrency))) { + throw new Error('desktop package: DSH_DESKTOP_MACOS_PACK_CONCURRENCY must be a positive integer') + } + return { + packConcurrency: Number(concurrency), + downloadProxy: proxy(environment, 'DSH_DESKTOP_MACOS_DOWNLOAD_PROXY', ['http:', 'https:']), + notarizationProxy: proxy(environment, 'DSH_DESKTOP_MACOS_NOTARIZATION_PROXY', ['http:']), + } +} + +/** + * Override proxy routing only in download-capable subprocesses, including Electron and pnpm. + * @param {NodeJS.ProcessEnv} environment Parent environment, never mutated. + * @param {string | undefined} proxyUrl Validated download proxy, or undefined to preserve inherited settings. + * @returns {NodeJS.ProcessEnv} Child environment; explicit routing bypasses only local hosts. + */ +export function macOSDownloadEnvironment(environment, proxyUrl) { + if (proxyUrl === undefined) return { ...environment } + return { + ...Object.fromEntries(Object.entries(environment).filter(([name]) => + !/^(?:(?:https?|all|no)_proxy|npm_config_(?:https?_proxy|proxy|noproxy)|ELECTRON_GET_USE_PROXY)$/iu.test(name))), + HTTP_PROXY: proxyUrl, HTTPS_PROXY: proxyUrl, http_proxy: proxyUrl, https_proxy: proxyUrl, + NO_PROXY: 'localhost,127.0.0.1,::1', no_proxy: 'localhost,127.0.0.1,::1', + ELECTRON_GET_USE_PROXY: '1', + } +} diff --git a/apps/desktop/scripts/notarize-macos-disk-images.mjs b/apps/desktop/scripts/notarize-macos-disk-images.mjs index de0a230a04..c99c06fac9 100644 --- a/apps/desktop/scripts/notarize-macos-disk-images.mjs +++ b/apps/desktop/scripts/notarize-macos-disk-images.mjs @@ -1,6 +1,6 @@ /** Notarize and qualify macOS disk images after electron-builder creates them. */ -import { notarize } from '@electron/notarize' +import { notarizeMacOS } from './notarize-macos.mjs' import { rmSync } from 'node:fs' import { resolveMacOSNotarizationEnvironment } from './desktop-release-environment.mjs' import { verifyMacOSDiskImage } from './verify-macos-signature.mjs' @@ -18,7 +18,7 @@ export async function notarizeMacOSDiskImageArtifact( artifact, env, expected, - submit = notarize, + submit = notarizeMacOS, verify = verifyMacOSDiskImage, ) { if (!artifact.file.endsWith('.dmg')) return diff --git a/apps/desktop/scripts/notarize-macos.d.mts b/apps/desktop/scripts/notarize-macos.d.mts new file mode 100644 index 0000000000..e0d2713deb --- /dev/null +++ b/apps/desktop/scripts/notarize-macos.d.mts @@ -0,0 +1,8 @@ +/** Notarize with separate upload and wait timings while preserving signature checks and stapling. */ +import type { MacOSNotarizationEnvironment } from './desktop-release-environment.mjs' +/** + * Notarize and staple an App or DMG through the measured notarytool adapter. + * @param options Validated Apple credentials and artifact path. + * @returns Resolves after acceptance and stapling; failures remain in the packaging journal. + */ +export function notarizeMacOS(options: MacOSNotarizationEnvironment & { appPath: string }): Promise diff --git a/apps/desktop/scripts/notarize-macos.mjs b/apps/desktop/scripts/notarize-macos.mjs new file mode 100644 index 0000000000..6ddec2781c --- /dev/null +++ b/apps/desktop/scripts/notarize-macos.mjs @@ -0,0 +1,15 @@ +/** Preserve electron-notarize's signature checks and stapling while recording separate Apple phases. */ +import { fileURLToPath } from 'node:url' +import { notarize } from '@electron/notarize' +import { packagingStep } from './packaging-step.mjs' + +/** + * Notarize and staple one App or DMG through the measured notarytool adapter. + * @param {object} options Validated credentials and appPath accepted by electron-notarize. + * @returns {Promise} Resolves only after Apple acceptance and stapling. + */ +export async function notarizeMacOS(options) { + const secrets = Object.entries(options).filter(([name]) => /password|key|appleId/iu.test(name)).map(([, value]) => String(value)) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'notarize-and-staple', + () => notarize({ ...options, notarytoolPath: fileURLToPath(new URL('./logged-notarytool.mjs', import.meta.url)) }), secrets) +} diff --git a/apps/desktop/scripts/package-macos.ts b/apps/desktop/scripts/package-macos.ts index 96fb3f7be4..c1a2cb5c71 100644 --- a/apps/desktop/scripts/package-macos.ts +++ b/apps/desktop/scripts/package-macos.ts @@ -4,7 +4,8 @@ import { execFile } from 'node:child_process' import { mkdtemp, rename, rm, stat } from 'node:fs/promises' import { basename, dirname, join } from 'node:path' import { promisify } from 'node:util' -import { notarize } from '@electron/notarize' +import { notarizeMacOS } from './notarize-macos.mjs' +import { packagingStep } from './packaging-step.mjs' import { resolveMacOSNotarizationEnvironment, resolveMacOSSigningEnvironment, @@ -45,15 +46,15 @@ const operations: MacOSArtifactOperations = { async copyApp(source, destination) { await execute('/usr/bin/ditto', [source, destination]) }, - notarize, + notarize: notarizeMacOS, verifySignature: verifyMacOSSignature, verifyNotarization: verifyMacOSNotarizedApplication, } -async function timed(label: string, action: () => Promise): Promise { +async function timed(label: string, action: () => Promise, secrets: readonly string[]): Promise { const start = performance.now() process.stdout.write(`desktop macOS packaging: ${label} started at ${new Date().toISOString()}\n`) - await action() + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, label, action, secrets) process.stdout.write(`desktop macOS packaging: ${label} completed in ${((performance.now() - start) / 1000).toFixed(2)}s\n`) } @@ -73,6 +74,7 @@ export async function packageMacOSArtifacts( apple: MacOSArtifactOperations = operations, ): Promise { const { arch, version, artifactsRoot, environment } = request + const secrets = Object.entries(environment).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '') const expected = resolveMacOSSigningEnvironment(environment) const credentials = resolveMacOSNotarizationEnvironment(environment) const update = resolveDesktopAutoUpdateConfig(environment, 'darwin', arch) @@ -95,10 +97,10 @@ export async function packageMacOSArtifacts( await apple.notarize({ appPath: zipApp, ...credentials }) apple.verifyNotarization(zipApp, expected) await build({ format: 'zip', appPath: zipApp, output: zipOutput }) - }), + }, secrets), timed('DMG creation and notarization', async () => { await build({ format: 'dmg', appPath: dmgApp, output: dmgOutput }) - }), + }, secrets), ]) const failures = results.filter(result => result.status === 'rejected') if (failures.length > 0) { diff --git a/apps/desktop/scripts/package-target.ts b/apps/desktop/scripts/package-target.ts index aede75a697..bcaf6825d6 100644 --- a/apps/desktop/scripts/package-target.ts +++ b/apps/desktop/scripts/package-target.ts @@ -1,6 +1,6 @@ /** Build one release target with matching Electron and dsh architecture. */ -import { spawn } from 'node:child_process' +import { execFileSync, spawn } from 'node:child_process' import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' import { parseArgs } from 'node:util' import { join, resolve } from 'node:path' @@ -11,8 +11,13 @@ 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 { withMacOSSigningKeychain } from './macos-signing-keychain.mjs' +import { macOSDownloadEnvironment, resolveMacOSPackageSettings } from './macos-package-settings.mjs' +import { packagingStep } from './packaging-step.mjs' +import { notarizeMacOS } from './notarize-macos.mjs' +import { resolveMacOSNotarizationEnvironment } from './desktop-release-environment.mjs' +import { withMacOSNotarizationProxy } from './macos-notarization-proxy.ts' const APP_ROOT = resolve(import.meta.dirname, '..') const REPOSITORY_ROOT = resolve(APP_ROOT, '..', '..') @@ -280,32 +285,50 @@ async function main(): Promise { const invocation = parseDesktopPackageInvocation(process.argv.slice(2)) const { target } = invocation const environment = loadDesktopPackageEnvironment(target.platform) - validateDesktopPackageEnvironment(environment, target, invocation) if (invocation.check) { + validateDesktopPackageEnvironment(environment, target, invocation) process.stdout.write(`desktop package: ${target.name} local configuration valid; signing and notarization were not attempted\n`) return } - const run = target.platform === 'win32' - ? createPackagingRun(join(APP_ROOT, '.desktop-build', 'packaging-runs'), { - target: target.name, unsigned: invocation.unsigned, version: packageVersion(join(APP_ROOT, 'package.json'), 'desktop package'), - }) : undefined - if (run !== undefined) console.log(`DESKTOP_PACKAGING_RECORD ${run.directory}`) + const secrets = Object.entries(environment).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '') + const run = createPackagingRun(join(APP_ROOT, '.desktop-build', 'packaging-runs'), { + target: target.name, unsigned: invocation.unsigned, directory: invocation.directory, prepareOnly: invocation.prepareOnly, + version: packageVersion(join(APP_ROOT, 'package.json'), 'desktop package'), node: process.version, + commit: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: REPOSITORY_ROOT, encoding: 'utf8' }).trim(), + dirty: execFileSync('git', ['status', '--porcelain', '--untracked-files=normal'], { cwd: REPOSITORY_ROOT, encoding: 'utf8' }).trim() !== '', + }, { parallel: target.platform === 'darwin', secrets }) + console.log(`DESKTOP_PACKAGING_RECORD ${run.directory}`) + const previousDirectory = process.env.DSH_DESKTOP_PACKAGING_RUN_DIR + process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = run.directory let success = false try { + await packagingStep(run.directory, 'configuration', async () => { validateDesktopPackageEnvironment(environment, target, invocation) }, secrets) if (target.platform === 'darwin') { - await withMacOSSigningKeychain(environment, signingEnvironment => packageTarget(invocation, signingEnvironment, run)) + const settings = resolveMacOSPackageSettings(environment) + recordPackagingEvent(run.directory, { type: 'macos-settings', packConcurrency: settings.packConcurrency, + downloadProxyConfigured: settings.downloadProxy !== undefined, + notarizationProxyConfigured: settings.notarizationProxy !== undefined }) + await packagingStep(run.directory, 'macos-package', () => withMacOSSigningKeychain(environment, + signingEnvironment => packageTarget(invocation, signingEnvironment, run)), secrets) } else { await packageTarget(invocation, environment, run) } success = true - } finally { run?.finish(success) } + } catch { + process.stderr.write(`desktop package: failed; see ${run.directory}/events.jsonl\n`) + process.exitCode = 1 + } finally { + if (previousDirectory === undefined) delete process.env.DSH_DESKTOP_PACKAGING_RUN_DIR + else process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = previousDirectory + run.finish(success) + } } /** * Prepare one release only after its signing preflight, without publishing from the builder. * @param invocation Validated host, target and packaging mode. * @param environment File-owned release configuration. - * @param run Windows stage supervisor; required for signed Windows packaging. + * @param run Persistent stage supervisor; required for signed Windows packaging and enabled for all release commands. * @returns Resolves after preparation or complete packaging; any failed stage prevents a release record. */ export async function packageTarget( @@ -315,6 +338,10 @@ export async function packageTarget( ): Promise { const { target } = invocation const execute = (args: readonly string[], env: NodeJS.ProcessEnv, cwd: string = APP_ROOT) => runPnpm(args, env, cwd, run) + const journal = target.platform === 'darwin' ? process.env.DSH_DESKTOP_PACKAGING_RUN_DIR : undefined + const proxyEvent = (status: string) => { if (journal) recordPackagingEvent(journal, { type: 'notarization-proxy', status }) } + const mac = target.platform === 'darwin' ? resolveMacOSPackageSettings(environment) : undefined + const packArguments = mac === undefined ? [] : ['--concurrency', String(mac.packConcurrency)] const buildPaths = desktopTargetBuildPaths(target.name) const releaseRecordPath = join(buildPaths.artifacts, desktopBuildRecordFilename(target.name)) if (!invocation.prepareOnly && !invocation.unsigned) { @@ -327,7 +354,8 @@ export async function packageTarget( DSH_DESKTOP_TARGET_PLATFORM: target.platform, DSH_DESKTOP_TARGET_ARCH: target.arch, } - const electronBuilderEnv = desktopElectronBuilderEnvironment(targetEnv, invocation.unsigned) + const downloadEnv = macOSDownloadEnvironment(targetEnv, mac?.downloadProxy) + const electronBuilderEnv = desktopElectronBuilderEnvironment(downloadEnv, invocation.unsigned) for (const name of WINDOWS_SIGNING_ENV_NAMES) { if (!invocation.unsigned && environment[name] !== undefined) electronBuilderEnv[name] = environment[name] } @@ -339,7 +367,7 @@ export async function packageTarget( { 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) + await execute(['run', 'release:pack', '--family', 'dsh', '--out', buildPaths.packedDsh, ...packArguments], buildEnv, REPOSITORY_ROOT) await execute([ '--dir', 'apps/desktop-host', @@ -347,7 +375,7 @@ export async function packageTarget( '--pack-destination', buildPaths.packedDsh, ], buildEnv, REPOSITORY_ROOT) - await execute(['run', 'release:pack', '--family', 'vendor', '--out', buildPaths.packedVendor], buildEnv, REPOSITORY_ROOT) + await execute(['run', 'release:pack', '--family', 'vendor', '--out', buildPaths.packedVendor, ...packArguments], buildEnv, REPOSITORY_ROOT) rmSync(buildPaths.packedLandlock, { recursive: true, force: true }) mkdirSync(buildPaths.packedLandlock, { recursive: true }) await execute(['--dir', 'native/system', 'run', 'build:ts'], buildEnv, REPOSITORY_ROOT) @@ -358,10 +386,10 @@ export async function packageTarget( '--pack-destination', buildPaths.packedLandlock, ], buildEnv, REPOSITORY_ROOT) - await execute(['run', 'prepare:runtime', ...(signPrimaryRuntime ? ['--defer-primary-runtime-smoke'] : [])], targetEnv) + await execute(['run', 'prepare:runtime', ...(signPrimaryRuntime ? ['--defer-primary-runtime-smoke'] : [])], downloadEnv) if (signPrimaryRuntime) await execute(['run', 'sign:primary-runtime'], electronBuilderEnv) await execute(['run', 'prepare:packages'], targetEnv) - await execute(['run', 'prepare:dsh', ...(signPrimaryRuntime ? ['--defer-runtime-smoke'] : [])], targetEnv) + await execute(['run', 'prepare:dsh', ...(signPrimaryRuntime ? ['--defer-runtime-smoke'] : [])], downloadEnv) if (signPrimaryRuntime) await execute(['run', 'sign:primary-runtime', '--dsh'], electronBuilderEnv) if (invocation.prepareOnly) return if (target.platform === 'darwin' && !invocation.directory) { @@ -369,17 +397,23 @@ export async function packageTarget( ...desktopElectronBuilderArguments(target, true), '--config.mac.notarize=false', ], electronBuilderEnv) - await packageMacOSArtifacts({ + await withMacOSNotarizationProxy(mac?.notarizationProxy, () => packageMacOSArtifacts({ arch: target.arch, version: packageVersion(join(APP_ROOT, 'package.json'), 'desktop package'), artifactsRoot: buildPaths.artifacts, environment: electronBuilderEnv, - }, artifact => execute(desktopElectronBuilderArguments(target, false, artifact), electronBuilderEnv)) + }, artifact => execute(desktopElectronBuilderArguments(target, false, artifact), electronBuilderEnv)), undefined, undefined, proxyEvent) + } else if (target.platform === 'darwin') { + await execute([...desktopElectronBuilderArguments(target, true), '--config.mac.notarize=false'], electronBuilderEnv) + const appPath = join(buildPaths.artifacts, target.arch === 'arm64' ? 'mac-arm64' : 'mac', 'DeepSeek Harness.app') + await withMacOSNotarizationProxy(mac?.notarizationProxy, + () => notarizeMacOS({ appPath, ...resolveMacOSNotarizationEnvironment(environment) }), undefined, undefined, proxyEvent) } else { await 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) + if (journal) recordPackagingEvent(journal, { type: 'artifacts', directory: buildPaths.artifacts }) } if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) await main() diff --git a/apps/desktop/scripts/packaging-run.d.mts b/apps/desktop/scripts/packaging-run.d.mts index 862436b0c3..672816805e 100644 --- a/apps/desktop/scripts/packaging-run.d.mts +++ b/apps/desktop/scripts/packaging-run.d.mts @@ -26,9 +26,10 @@ export function packagingOutputRedactor(secrets: readonly string[], emit: (text: * Allocate retained evidence and supervise sequential child-process stages. * @param root Parent directory for retained records. * @param metadata Public target/version metadata only. + * @param settings Opt-in parallel stages and additional credentials to redact. * @returns A run that blocks later stages after failure and awaits owned process termination. */ -export function createPackagingRun(root: string, metadata: object): { +export function createPackagingRun(root: string, metadata: object, settings?: { parallel?: boolean; secrets?: readonly string[] }): { directory: string run(stage: string, executable: string, args: readonly string[], options: { cwd: string diff --git a/apps/desktop/scripts/packaging-run.mjs b/apps/desktop/scripts/packaging-run.mjs index 6071b17952..6c62a59b87 100644 --- a/apps/desktop/scripts/packaging-run.mjs +++ b/apps/desktop/scripts/packaging-run.mjs @@ -1,6 +1,7 @@ /** Persist redacted packaging evidence and terminate the owned stage tree on fatal signing failures. */ +import { randomUUID } from 'node:crypto' import { spawn } from 'node:child_process' -import { appendFileSync, existsSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs' +import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs' import { join, resolve } from 'node:path' import { StringDecoder } from 'node:string_decoder' @@ -59,22 +60,26 @@ export function packagingOutputRedactor(secrets, emit) { * Allocate a run whose failures never become release completion records. * @param {string} root Parent for retained packaging records. * @param {object} metadata Public target/version metadata only. + * @param {{parallel?: boolean, secrets?: readonly string[]}} settings Parallel stages are opt-in; secrets include credentials removed from child environments. * @returns {{directory: string, run: (stage: string, executable: string, args: readonly string[], options: {cwd: string, env: NodeJS.ProcessEnv, timeoutMs?: number}) => Promise, finish: (success: boolean) => void}} Owned run supervisor; an optional stage deadline records timeout independently of exit status and awaits termination. */ -export function createPackagingRun(root, metadata) { +export function createPackagingRun(root, metadata, settings = {}) { + const started = performance.now() mkdirSync(root, { recursive: true }) const directory = realpathSync(mkdtempSync(join(resolve(root), `${new Date().toISOString().replaceAll(':', '-')}-`))) for (const name of ['events.jsonl', 'stdout.log', 'stderr.log']) { writeFileSync(join(directory, name), '', { flag: 'wx', mode: 0o600 }) } - writeFileSync(join(directory, 'run.json'), `${JSON.stringify({ startedAt: new Date().toISOString(), pid: process.pid, ...metadata })}\n`, { flag: 'wx', flush: true }) + writeFileSync(join(directory, 'run.json'), `${JSON.stringify({ startedAt: new Date().toISOString(), pid: process.pid, ...metadata })}\n`, { flag: 'wx', mode: 0o600, flush: true }) let failed = false - let active = false + let active = 0 const fatal = join(directory, 'fatal.json') async function run(stage, executable, args, options) { if (failed || existsSync(fatal)) throw new Error(`desktop package: run is blocked; see ${directory}`) - if (active) throw new Error('desktop package: supervised stages must run sequentially') - active = true + if (active && !settings.parallel) throw new Error('desktop package: supervised stages must run sequentially') + active++ + const stageId = randomUUID() + const started = performance.now() let child let fatalObserved = false let launchError = false @@ -112,22 +117,23 @@ export function createPackagingRun(root, metadata) { process.once('SIGINT', interrupted) process.once('SIGTERM', interrupted) try { - recordPackagingEvent(directory, { type: 'stage-start', stage }) + recordPackagingEvent(directory, { type: 'stage-start', stage, stageId }) child = spawn(executable, [...args], { cwd: options.cwd, env: { ...options.env, DSH_DESKTOP_PACKAGING_RUN_DIR: directory }, windowsHide: true, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] }) closed = new Promise(resolveClose => { child.once('error', () => { launchError = true }) child.once('close', (code, signal) => { stageClosed = true; resolveClose({ code, signal }) }) }) - recordPackagingEvent(directory, { type: 'stage-spawn', stage, childPid: child.pid }) + recordPackagingEvent(directory, { type: 'stage-spawn', stage, stageId, childPid: child.pid }) if (options.timeoutMs !== undefined) deadline = setTimeout(() => { timedOut = true; stop() }, options.timeoutMs) - const secrets = Object.entries(options.env).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD/iu.test(name)).map(([, value]) => value ?? '') + const secrets = [...(settings.secrets ?? []), ...Object.entries(options.env).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '')] const streams = [['stdout', child.stdout, process.stdout], ['stderr', child.stderr, process.stderr]] for (const [name, stream, consoleStream] of streams) { let notification = '' const redactor = packagingOutputRedactor(secrets, text => { try { appendFileSync(join(directory, `${name}.log`), text, { flush: true }) + if (settings.parallel) recordPackagingEvent(directory, { type: 'output', stage, stageId, stream: name, text }) consoleStream.write(text) } catch { outputError = true; stop() } notification += text @@ -142,7 +148,7 @@ export function createPackagingRun(root, metadata) { const result = await closed await termination fatalObserved ||= existsSync(fatal) - recordPackagingEvent(directory, { type: 'stage-end', stage, ...result, timedOut, fatalObserved, launchError, outputError, terminationCode, terminationError }) + recordPackagingEvent(directory, { type: 'stage-end', stage, stageId, elapsedMs: performance.now() - started, ...result, timedOut, fatalObserved, launchError, outputError, terminationCode, terminationError }) if (result.code !== 0 || result.signal !== null || fatalObserved || launchError || outputError || terminationError) { failed = true throw new Error(`desktop package: ${stage} failed; evidence: ${directory}`) @@ -157,7 +163,7 @@ export function createPackagingRun(root, metadata) { clearTimeout(deadline) process.removeListener('SIGINT', interrupted) process.removeListener('SIGTERM', interrupted) - active = false + active-- } } return { @@ -165,7 +171,10 @@ export function createPackagingRun(root, metadata) { run, finish(success) { if (active) throw new Error('desktop package: cannot finish an active run') - writeFileSync(join(directory, 'result.json'), `${JSON.stringify({ completedAt: new Date().toISOString(), success: success && !failed && !existsSync(fatal) })}\n`, { flag: 'wx', flush: true }) + const events = readFileSync(join(directory, 'events.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)) + const stages = events.filter(event => event.type === 'stage-end') + const proxy = events.filter(event => event.type === 'notarization-proxy').at(-1)?.status ?? 'not-used' + writeFileSync(join(directory, 'result.json'), `${JSON.stringify({ completedAt: new Date().toISOString(), elapsedMs: performance.now() - started, success: success && !failed && !existsSync(fatal), proxy, artifacts: events.filter(event => event.type === 'artifacts').at(-1)?.directory, stages })}\n`, { flag: 'wx', mode: 0o600, flush: true }) }, } } diff --git a/apps/desktop/scripts/packaging-step.d.mts b/apps/desktop/scripts/packaging-step.d.mts new file mode 100644 index 0000000000..45f1ed48bb --- /dev/null +++ b/apps/desktop/scripts/packaging-step.d.mts @@ -0,0 +1,10 @@ +/** Persist in-process and Apple-tool phases in the packaging journal. */ +/** + * Record a phase outcome and redacted nested failure details. + * @param directory Existing run directory; undefined retains unrecorded callers. + * @param stage Public phase label, never credentials. + * @param action Work that settles all owned activity before returning. + * @param secrets Credential values removed from errors. + * @returns Action result; logging failures also reject the phase. + */ +export function packagingStep(directory: string | undefined, stage: string, action: () => Promise, secrets?: readonly string[]): Promise diff --git a/apps/desktop/scripts/packaging-step.mjs b/apps/desktop/scripts/packaging-step.mjs new file mode 100644 index 0000000000..75082dcd11 --- /dev/null +++ b/apps/desktop/scripts/packaging-step.mjs @@ -0,0 +1,38 @@ +/** Record in-process and Apple-tool phases in the same journal as packaging subprocesses. */ +import { randomUUID } from 'node:crypto' +import { recordPackagingEvent, packagingOutputRedactor } from './packaging-run.mjs' + +/** + * Persist a phase outcome, including nested failure details, without logging arguments or environments. + * @param {string | undefined} directory Existing run directory; undefined retains unrecorded callers. + * @param {string} stage Public phase label, never credentials. + * @param {() => Promise} action Work that settles all owned activity before returning. + * @param {readonly string[]} secrets Credential values removed from errors. + * @returns {Promise} Action result; logging failures also reject the phase. + */ +export async function packagingStep(directory, stage, action, secrets = Object.entries(process.env).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '')) { + if (directory === undefined) return action() + const stageId = randomUUID() + const started = performance.now() + recordPackagingEvent(directory, { type: 'stage-start', stage, stageId }) + try { + const result = await action() + recordPackagingEvent(directory, { type: 'stage-end', stage, stageId, elapsedMs: performance.now() - started, success: true }) + return result + } catch (error) { + const seen = new Set() + function details(value) { + if (!(value instanceof Error)) return String(value) + if (seen.has(value)) return '[circular error]' + seen.add(value) + return [value.stack ?? value.message, ...(value instanceof AggregateError ? value.errors.map(details) : []), + ...(value.cause === undefined ? [] : [details(value.cause)])].join('\n') + } + let message = '' + const redactor = packagingOutputRedactor(secrets, text => { message += text }) + redactor.write(Buffer.from(details(error))) + redactor.end() + recordPackagingEvent(directory, { type: 'stage-end', stage, stageId, elapsedMs: performance.now() - started, success: false, error: message }) + throw error + } +} diff --git a/apps/desktop/scripts/prepare-dsh.ts b/apps/desktop/scripts/prepare-dsh.ts index d1124618d6..5bb00b3fd7 100644 --- a/apps/desktop/scripts/prepare-dsh.ts +++ b/apps/desktop/scripts/prepare-dsh.ts @@ -1,5 +1,6 @@ /** Materialize the complete production runtime before publishing Desktop resources. */ +import { packagingStep } from './packaging-step.mjs' import { spawn } from 'node:child_process' import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -115,12 +116,12 @@ async function main(): Promise { copyFileSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGE_SET_FILE), join(BUILD_ROOT, DESKTOP_PACKAGE_SET_FILE)) cpSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGES_DIR), join(BUILD_ROOT, DESKTOP_PACKAGES_DIR), { recursive: true }) createRuntimeProjectMetadata(BUILD_ROOT, release) - await runPnpm(['install', '--lockfile-only']) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:lockfile', () => runPnpm(['install', '--lockfile-only'])) verifyDesktopCoreLockfile( readFileSync(join(BUILD_ROOT, 'pnpm-lock.yaml'), 'utf8'), readDesktopCorePackageSet(BUILD_ROOT, release.version), ) - await runPnpm(['install', '--prod', '--frozen-lockfile', '--trust-lockfile']) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:install', () => runPnpm(['install', '--prod', '--frozen-lockfile', '--trust-lockfile'])) const packageSet = readDesktopCorePackageSet(BUILD_ROOT, release.version) const targetName = resolveDesktopBuildTarget() const target = { platform: process.platform, arch: targetName.endsWith('arm64') ? 'arm64' : 'x64' } @@ -145,15 +146,15 @@ async function main(): Promise { throw new Error(`desktop runtime: missing required LibreOffice engine ${officeEngine}`) } if (process.platform === 'darwin') { - await signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env)) - await signMacOSRuntime(join(RUNTIME_ROOT, 'primary-runtime'), resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env)) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:dsh-native', () => signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env))) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:primary-native', () => signMacOSRuntime(join(RUNTIME_ROOT, 'primary-runtime'), resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env))) } await prepareRuntimeManifests(DSH_OUTPUT_ROOT) smokePrimaryRuntime(join(RUNTIME_ROOT, 'primary-runtime')) writeDesktopRuntime(DSH_OUTPUT_ROOT, release, packageSet.packages.map(entry => entry.name), target) const descriptor = await verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target) if (!process.argv.includes('--defer-runtime-smoke')) { - await smokePreparedRuntime(DSH_OUTPUT_ROOT, NODE, RUNTIME_ROOT, descriptor) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:smoke', () => smokePreparedRuntime(DSH_OUTPUT_ROOT, NODE, RUNTIME_ROOT, descriptor)) await verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target) } } catch (error) { diff --git a/apps/desktop/scripts/prepare-runtime.ts b/apps/desktop/scripts/prepare-runtime.ts index ee31e032ee..04ddd937b0 100644 --- a/apps/desktop/scripts/prepare-runtime.ts +++ b/apps/desktop/scripts/prepare-runtime.ts @@ -1,5 +1,6 @@ /** Prepare the target Electron distribution and pinned pnpm CLI. */ +import { packagingStep } from './packaging-step.mjs' import { execFileSync } from 'node:child_process' import { chmodSync, cpSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { createRequire } from 'node:module' @@ -32,9 +33,10 @@ async function main(): Promise { const arch = target.endsWith('arm64') ? 'arm64' : 'x64' const require = createRequire(import.meta.url) const { version } = require('electron/package.json') as { version: string } - const archive = await downloadArtifact({ version, platform, arch, artifactName: 'electron', cacheRoot: BUILD_PATHS.downloads }) + const archive = await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'download:electron', + () => downloadArtifact({ version, platform, arch, artifactName: 'electron', cacheRoot: BUILD_PATHS.downloads })) rmSync(BUILD_PATHS.electron, { recursive: true, force: true }) - await extractZip(archive, { dir: BUILD_PATHS.electron }) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'extract:electron', () => extractZip(archive, { dir: BUILD_PATHS.electron })) const executable = join(BUILD_PATHS.electron, platform === 'win32' ? 'electron.exe' : 'Electron.app/Contents/MacOS/Electron') const nodeVersion = execFileSync(executable, ['-p', 'process.versions.node'], { encoding: 'utf8', env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, @@ -49,7 +51,8 @@ async function main(): Promise { node: nodeVersion, pnpm: pnpmVersion, }, undefined, 2)}\n`) - await preparePrimaryRuntime({ deferSmoke: values['defer-primary-runtime-smoke'] }) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'prepare:primary-runtime', + () => preparePrimaryRuntime({ deferSmoke: values['defer-primary-runtime-smoke'] })) } await main() diff --git a/apps/desktop/tests/desktop-package-environment.spec.ts b/apps/desktop/tests/desktop-package-environment.spec.ts index 50d9726550..4e4cde74f1 100644 --- a/apps/desktop/tests/desktop-package-environment.spec.ts +++ b/apps/desktop/tests/desktop-package-environment.spec.ts @@ -134,3 +134,14 @@ describe('Desktop local packaging configuration', () => { }) }) }) + +it('owns macOS tuning in the local file and validates it before signing credentials', async () => { + await withDirectory(async (directory) => { + await writeFile(join(directory, '.env.macos'), 'DSH_DESKTOP_MACOS_PACK_CONCURRENCY=2\nDSH_DESKTOP_MACOS_DOWNLOAD_PROXY=http://proxy.example:8080\nDSH_DESKTOP_MACOS_NOTARIZATION_PROXY=\n') + const env = loadDesktopPackageEnvironment('darwin', { DSH_DESKTOP_MACOS_PACK_CONCURRENCY: '99' }, directory) + expect(env.DSH_DESKTOP_MACOS_PACK_CONCURRENCY).toBe('2') + expect(env.DSH_DESKTOP_MACOS_NOTARIZATION_PROXY).toBe('') + expect(() =>{ validateDesktopPackageEnvironment({ ...RELEASE, DSH_DESKTOP_MACOS_PACK_CONCURRENCY: '' }, MACOS) }).toThrow('PACK_CONCURRENCY') + expect(() =>{ validateDesktopPackageEnvironment({ ...RELEASE, DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: 'socks5://localhost:8080' }, MACOS) }).toThrow('NOTARIZATION_PROXY') + }) +}) diff --git a/apps/desktop/tests/logged-notarytool-exit.spec.ts b/apps/desktop/tests/logged-notarytool-exit.spec.ts new file mode 100644 index 0000000000..8deaf4ece4 --- /dev/null +++ b/apps/desktop/tests/logged-notarytool-exit.spec.ts @@ -0,0 +1,33 @@ +import { expect, it, vi } from 'vitest' +import { runLoggedNotarytool } from '../scripts/logged-notarytool.mjs' + +const command = vi.hoisted(() => vi.fn<(...args: unknown[]) => Promise<{ stdout: string; stderr: string }>>()) +vi.mock('node:child_process', async (importOriginal) => { + const { promisify } = await import('node:util') + return { + ...await importOriginal(), + execFile: Object.assign(() => {}, { [promisify.custom]: command }), + } +}) + +const id = '11111111-2222-3333-4444-555555555555' +const args = ['submit', '/fixture/app.zip', '--keychain-profile', 'fixture', '--wait', '--output-format', 'json'] + +it('passes Apple rejection JSON from a nonzero wait exit back to electron-notarize for diagnostic retrieval', async () => { + command.mockReset() + command.mockResolvedValueOnce({ stdout: JSON.stringify({ id }), stderr: '' }) + command.mockRejectedValueOnce(Object.assign(new Error('notarytool exited 65'), { + code: 65, stdout: JSON.stringify({ id, status: 'Invalid' }), stderr: '', + })) + expect(JSON.parse(await runLoggedNotarytool(args))).toEqual({ id, status: 'Invalid' }) + expect(command).toHaveBeenCalledTimes(2) +}) + +it('does not treat failed upload output as a completed submission', async () => { + command.mockReset() + command.mockRejectedValueOnce(Object.assign(new Error('upload failed'), { + code: 1, stdout: JSON.stringify({ id }), stderr: '', + })) + await expect(runLoggedNotarytool(args)).rejects.toThrow('upload failed') + expect(command).toHaveBeenCalledOnce() +}) diff --git a/apps/desktop/tests/logged-notarytool.spec.ts b/apps/desktop/tests/logged-notarytool.spec.ts new file mode 100644 index 0000000000..ad5a346b5e --- /dev/null +++ b/apps/desktop/tests/logged-notarytool.spec.ts @@ -0,0 +1,82 @@ +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { runLoggedNotarytool } from '../scripts/logged-notarytool.mjs' +import { createPackagingRun } from '../scripts/packaging-run.mjs' + +const id = '11111111-2222-3333-4444-555555555555' +const args = ['submit', '/fixture/app.zip', '--apple-id', 'private@example.test', '--password', 'secret-value', '--team-id', 'TEAM', '--wait', '--output-format', 'json'] +async function fixture(action: (directory: string) => Promise) { + const root = await mkdtemp(join(tmpdir(), 'notary-log-')) + try { await action(createPackagingRun(root, {}).directory) } finally { await rm(root, { recursive: true, force: true }) } +} + +it('finishes submission before starting wait and records the ID and separate timings', async () => { + await fixture(async (directory) => { + const uploaded = Promise.withResolvers() + const execute = vi.fn(async (command: readonly string[]) => command[0] === 'submit' ? uploaded.promise : JSON.stringify({ id, status: 'Accepted' })) + const work = runLoggedNotarytool(args, directory, execute) + try { + expect(execute).toHaveBeenCalledExactlyOnceWith(args.filter(arg => arg !== '--wait').concat('--no-wait')) + expect(await readFile(join(directory, 'events.jsonl'), 'utf8')).not.toContain('notarytool:wait') + } finally { uploaded.resolve(JSON.stringify({ id })) } + expect(JSON.parse(await work)).toEqual({ id, status: 'Accepted' }) + expect(execute.mock.calls[1]![0]).toEqual(['wait', id, '--apple-id', 'private@example.test', '--password', 'secret-value', '--team-id', 'TEAM', '--output-format', 'json']) + const log = await readFile(join(directory, 'events.jsonl'), 'utf8') + expect(log).toContain('notary-submission') + expect(log).toContain('notarytool:upload:app.zip') + expect(log).toContain('notarytool:wait:app.zip') + expect(log).toContain('elapsedMs') + expect(log).not.toContain('private@example.test') + expect(log).not.toContain('secret-value') + }) +}) + +it('records a redacted upload error without starting wait', async () => { + await fixture(async (directory) => { + const execute = vi.fn(async () => { throw new Error('rejected secret-value private@example.test') }) + await expect(runLoggedNotarytool(args, directory, execute)).rejects.toThrow('rejected') + expect(execute).toHaveBeenCalledOnce() + const log = await readFile(join(directory, 'events.jsonl'), 'utf8') + expect(log).toContain('"success":false') + expect(log).not.toContain('secret-value') + expect(log).not.toContain('private@example.test') + }) +}) + +it.each(['Invalid', 'Rejected'])('preserves %s for electron-notarize rejection handling', async (status) => { + const execute = vi.fn(async (command: readonly string[]) => JSON.stringify(command[0] === 'submit' ? { id } : { id, status })) + await fixture(async (directory) => { + expect(JSON.parse(await runLoggedNotarytool(args, directory, execute))).toEqual({ id, status }) + const log = await readFile(join(directory, 'events.jsonl'), 'utf8') + expect(log).toContain('\"success\":false') + expect(log).toContain(status) + }) +}) + +it('rejects missing submission IDs and mismatched wait results', async () => { + await expect(runLoggedNotarytool(args, undefined, async () => '{}')).rejects.toThrow('submission ID') + await expect(runLoggedNotarytool(args, undefined, async command => JSON.stringify(command[0] === 'submit' ? { id } : { id: 'other', status: 'Accepted' }))).rejects.toThrow('different submission ID') +}) + +it.each([ + ['--key', '/private/AuthKey.p8', '--key-id', 'KEY123', '--issuer', id], + ['--keychain-profile', 'release', '--keychain', '/private/release.keychain'], +])('preserves API-key and keychain authentication when waiting: %j', async (...auth) => { + const execute = vi.fn(async () => JSON.stringify({ id, status: 'Accepted' })) + await runLoggedNotarytool(['submit', '/fixture/release.dmg', ...auth, '--wait', '--output-format', 'json'], undefined, execute) + expect(execute.mock.calls[1]).toEqual([['wait', id, ...auth, '--output-format', 'json']]) +}) + +it('retains redacted Apple diagnostics and passes the original result to electron-notarize', async () => { + await fixture(async (directory) => { + const output = 'diagnostic for private@example.test' + const command = ['log', id, '--apple-id', 'private@example.test'] + expect(await runLoggedNotarytool(command, directory, async () => output)).toBe(output) + const log = await readFile(join(directory, 'events.jsonl'), 'utf8') + expect(log).toContain('notary-diagnostics') + expect(log).toContain('[REDACTED]') + expect(log).not.toContain('private@example.test') + }) +}) diff --git a/apps/desktop/tests/macos-notarization-proxy.spec.ts b/apps/desktop/tests/macos-notarization-proxy.spec.ts new file mode 100644 index 0000000000..a4e64423ee --- /dev/null +++ b/apps/desktop/tests/macos-notarization-proxy.spec.ts @@ -0,0 +1,170 @@ +import { existsSync, readFileSync } from 'node:fs' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { restoreMacOSNotarizationProxy, withMacOSNotarizationProxy } from '../scripts/macos-notarization-proxy.ts' + +async function fixture(action: (fixture: ReturnType, lock: string) => Promise): Promise { + const root = await mkdtemp(join(tmpdir(), 'mac-proxy-test-')) + try { await action(fakeSystem(), join(root, 'lock')) } finally { await rm(root, { recursive: true, force: true }) } +} + +function fakeSystem() { + const states = { + http: { enabled: false, server: 'old-http', port: 3128 }, + https: { enabled: true, server: 'old-https', port: 8080 }, + } + const original = structuredClone(states) + const control = { failSet: 0, setCount: 0, pac: false, authenticated: false } + const ops = { + reachable: vi.fn(async (_url: URL) => {}), + ownerAlive: vi.fn((_pid: number) => false), + command: vi.fn((executable: string, args: readonly string[]) => { + if (executable === '/sbin/route') return ' interface: en9\n' + if (args[0] === '-listnetworkserviceorder') return '(1) Ethernet\n(Hardware Port: USB LAN, Device: en9)\n\n(2) Wi-Fi\n(Hardware Port: Wi-Fi, Device: en0)\n' + expect(args[1]).toBe('Ethernet') + if (args[0] === '-getautoproxyurl') return `URL: http://pac\nEnabled: ${control.pac ? 'Yes' : 'No'}\n` + if (args[0] === '-getproxyautodiscovery') return 'Auto Proxy Discovery: Off\n' + if (args[0] === '-getsocksfirewallproxy') return 'Enabled: No\n' + const state = args[0]!.includes('secure') ? states.https : states.http + if (args[0]!.startsWith('-get')) return `Enabled: ${state.enabled ? 'Yes' : 'No'}\nServer: ${state.server}\nPort: ${state.port}\nAuthenticated Proxy Enabled: ${control.authenticated ? '1' : '0'}\n` + control.setCount++ + if (control.setCount === control.failSet) throw new Error('system write failed') + if (args[0]!.endsWith('state')) state.enabled = args[2] === 'on' + else { state.server = args[2]!; state.port = Number(args[3]); state.enabled = true } + return '' + }), + } + return { ops, states, original, control } +} + +it('preserves the network when no Apple proxy is configured', async () => { + await fixture(async ({ ops }, lock) => { + await expect(withMacOSNotarizationProxy(undefined, async () => 42, lock, ops)).resolves.toBe(42) + expect(ops.command).not.toHaveBeenCalled() + expect(ops.reachable).not.toHaveBeenCalled() + expect(existsSync(lock)).toBe(false) + }) +}) + +it.each([false, true])('restores both original proxies after settled work (failure=%s)', async (fail) => { + await fixture(async ({ ops, states, original }, lock) => { + const statuses: string[] = [] + const work = withMacOSNotarizationProxy('http://localhost:8888', async () => { + expect(states.http).toEqual({ enabled: true, server: 'localhost', port: 8888 }) + expect(states.https).toEqual(states.http) + const record = JSON.parse(readFileSync(join(lock, 'original.json'), 'utf8')) as { service: string } + expect(record.service).toBe('Ethernet') + if (fail) throw new Error('Apple refused') + return 42 + }, lock, ops, (status) => { statuses.push(status) }) + if (fail) await expect(work).rejects.toThrow('Apple refused') + else await expect(work).resolves.toBe(42) + expect(statuses).toEqual(['restoration-pending', 'enabled', 'restored']) + expect(states).toEqual(original) + expect(existsSync(lock)).toBe(false) + }) +}) + +it('does not steal a live lock and holds the proxy until concurrent work drains', async () => { + await fixture(async ({ ops, states, original }, lock) => { + const entered = Promise.withResolvers() + const finish = Promise.withResolvers() + const running = withMacOSNotarizationProxy('http://localhost:8888', async () => { entered.resolve(undefined); await finish.promise }, lock, ops) + try { + await entered.promise + await expect(withMacOSNotarizationProxy('http://localhost:8889', async () => {}, lock, ops)).rejects.toThrow('another run') + expect(states.http.port).toBe(8888) + expect(existsSync(lock)).toBe(true) + } finally { finish.resolve(undefined); await running } + expect(states).toEqual(original) + }) +}) + +it('restores partial setup and never calls Apple after a system write failure', async () => { + await fixture(async ({ ops, states, original, control }, lock) => { + control.failSet = 3 + const action = vi.fn(async () => {}) + await expect(withMacOSNotarizationProxy('http://localhost:8888', action, lock, ops)).rejects.toThrow('system write failed') + expect(action).not.toHaveBeenCalled() + expect(states).toEqual(original) + expect(existsSync(lock)).toBe(false) + }) +}) + +it.each(['pac', 'authenticated'] as const)('rejects unpreservable %s settings before mutation', async (kind) => { + await fixture(async ({ ops, states, original, control }, lock) => { + control[kind] = true + const action = vi.fn(async () => {}) + await expect(withMacOSNotarizationProxy('http://localhost:8888', action, lock, ops)).rejects.toThrow(/proxy|proxies/u) + expect(control.setCount).toBe(0) + expect(action).not.toHaveBeenCalled() + expect(states).toEqual(original) + }) +}) + +it('fails unreachable proxies before acquiring a lock or changing settings', async () => { + await fixture(async ({ ops }, lock) => { + ops.reachable.mockRejectedValueOnce(new Error('unreachable')) + await expect(withMacOSNotarizationProxy('http://localhost:8888', async () => {}, lock, ops)).rejects.toThrow('unreachable') + expect(ops.command).not.toHaveBeenCalled() + expect(existsSync(lock)).toBe(false) + }) +}) + +it('retains recovery data after failed restoration, rejects live owners, then recovers after owner exit', async () => { + await fixture(async ({ ops, states, original, control }, lock) => { + control.failSet = 5 + await expect(withMacOSNotarizationProxy('http://localhost:8888', async () => {}, lock, ops)).rejects.toThrow('restoration failed') + expect(existsSync(join(lock, 'original.json'))).toBe(true) + ops.ownerAlive.mockReturnValueOnce(true) + expect(() =>{ restoreMacOSNotarizationProxy(lock, ops) }).toThrow('still running') + restoreMacOSNotarizationProxy(lock, ops) + expect(states).toEqual(original) + expect(existsSync(lock)).toBe(false) + }) +}) + +it('rejects malformed saved state without invoking host commands', async () => { + await fixture(async ({ ops, control }, lock) => { + control.failSet = 5 + await expect(withMacOSNotarizationProxy('http://localhost:8888', async () => {}, lock, ops)).rejects.toThrow('restoration failed') + await writeFile(join(lock, 'original.json'), '{"pid":-1}') + ops.command.mockClear() + expect(() =>{ restoreMacOSNotarizationProxy(lock, ops) }).toThrow('invalid proxy recovery record') + expect(ops.command).not.toHaveBeenCalled() + }) +}) + +it('defers interruption until work settles and removes its signal listeners after restoration', async () => { + await fixture(async ({ ops, states, original }, lock) => { + const before = process.listenerCount('SIGTERM') + const entered = Promise.withResolvers() + const finish = Promise.withResolvers() + const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + const running = withMacOSNotarizationProxy('http://localhost:8888', async () => { entered.resolve(undefined); await finish.promise }, lock, ops) + const result = expect(running).rejects.toThrow('interrupted by SIGTERM') + try { + await entered.promise + // Deliver only the listener owned by this invocation; never signal the test runner or other suites. + const listener = process.listeners('SIGTERM').at(-1)! + listener('SIGTERM') + expect(states.http.port).toBe(8888) + expect(existsSync(lock)).toBe(true) + } finally { finish.resolve(undefined); await result; stderr.mockRestore() } + expect(states).toEqual(original) + expect(process.listenerCount('SIGTERM')).toBe(before) + }) +}) + +it('retains both the Apple failure and restoration failure', async () => { + await fixture(async ({ ops, control }, lock) => { + control.failSet = 5 + const appleError = new Error('Apple refused') + const result = withMacOSNotarizationProxy('http://localhost:8888', async () => { throw appleError }, lock, ops) + await expect(result).rejects.toMatchObject({ errors: [appleError, expect.any(AggregateError)] }) + expect(existsSync(join(lock, 'original.json'))).toBe(true) + restoreMacOSNotarizationProxy(lock, ops) + }) +}) diff --git a/apps/desktop/tests/macos-package-settings.spec.ts b/apps/desktop/tests/macos-package-settings.spec.ts new file mode 100644 index 0000000000..1daa31c70a --- /dev/null +++ b/apps/desktop/tests/macos-package-settings.spec.ts @@ -0,0 +1,34 @@ +import { expect, it } from 'vitest' +import { macOSDownloadEnvironment, resolveMacOSPackageSettings } from '../scripts/macos-package-settings.mjs' + +it('defaults to four workers and keeps download and Apple proxies independent', () => { + expect(resolveMacOSPackageSettings({})).toEqual({ packConcurrency: 4 }) + expect(resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_PACK_CONCURRENCY: '2', + DSH_DESKTOP_MACOS_DOWNLOAD_PROXY: 'https://download.example:8080', + DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: 'http://apple.example:8081', + })).toEqual({ packConcurrency: 2, downloadProxy: 'https://download.example:8080', notarizationProxy: 'http://apple.example:8081' }) + expect(resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_DOWNLOAD_PROXY: ' ', DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: '' })).toEqual({ packConcurrency: 4 }) +}) + +it.each(['', '0', '-1', '1.5', '1e2', 'Infinity', '9007199254740992'])('rejects invalid concurrency %j', (value) => { + expect(() => resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_PACK_CONCURRENCY: value })).toThrow('PACK_CONCURRENCY') +}) + +it.each(['socks5://host:8080', 'http://user:secret@host', 'http://host/path', 'http://host?query', 'http://host#fragment', 'invalid']) +('rejects unsupported proxy input without echoing it: %s', (value) => { + expect(() => resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: value })).toThrow('NOTARIZATION_PROXY') + expect(() => resolveMacOSPackageSettings({ DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: value })).not.toThrow(value) +}) + +it('overrides conflicting child proxy variables while preserving the parent and unrelated settings', () => { + const parent = { PATH: 'tools', HTTPS_PROXY: 'http://old', http_proxy: 'http://lower', ALL_PROXY: 'socks5://old', + NO_PROXY: '*', npm_config_proxy: 'http://npm', ELECTRON_GET_USE_PROXY: '0' } + expect(macOSDownloadEnvironment(parent)).toEqual(parent) + const child = macOSDownloadEnvironment(parent, 'http://new:8080') + expect(child).toMatchObject({ PATH: 'tools', HTTP_PROXY: 'http://new:8080', HTTPS_PROXY: 'http://new:8080', + http_proxy: 'http://new:8080', https_proxy: 'http://new:8080', ELECTRON_GET_USE_PROXY: '1', NO_PROXY: 'localhost,127.0.0.1,::1' }) + expect(child).not.toHaveProperty('ALL_PROXY') + expect(child).not.toHaveProperty('npm_config_proxy') + expect(parent.HTTPS_PROXY).toBe('http://old') + expect(parent.NO_PROXY).toBe('*') +}) diff --git a/apps/desktop/tests/package-target-stages.spec.ts b/apps/desktop/tests/package-target-stages.spec.ts index 6a238f1026..c78e637dc6 100644 --- a/apps/desktop/tests/package-target-stages.spec.ts +++ b/apps/desktop/tests/package-target-stages.spec.ts @@ -1,6 +1,14 @@ import { writeFileSync } from 'node:fs' import { afterEach, expect, it, vi } from 'vitest' import { packageTarget, parseDesktopPackageInvocation } from '../scripts/package-target.ts' +import { withMacOSNotarizationProxy } from '../scripts/macos-notarization-proxy.ts' +import { packageMacOSArtifacts } from '../scripts/package-macos.ts' + +vi.mock('../scripts/macos-notarization-proxy.ts', () => ({ + withMacOSNotarizationProxy: vi.fn(async (_proxy: string | undefined, action: () => Promise) => action()), +})) +vi.mock('../scripts/notarize-macos.mjs', () => ({ notarizeMacOS: vi.fn(async () => {}) })) +vi.mock('../scripts/package-macos.ts', () => ({ packageMacOSArtifacts: vi.fn(async () => {}) })) // Keep the real orchestration and manifest reads; this suite owns no release directories or subprocesses. vi.mock('node:fs', async importOriginal => ({ @@ -62,3 +70,42 @@ it.each(['--unsigned', '--prepare-only'])('keeps %s hardware-free and creates no for (const call of run.run.mock.calls) expect(call[3].env).not.toHaveProperty('DSH_DESKTOP_WINDOWS_TOKEN_PIN') expect(writeFileSync).not.toHaveBeenCalled() }) + +it.each([undefined, '2'])('passes macOS pack concurrency %s only to workspace packing and download routing only to download stages', async (concurrency) => { + const { run } = supervisor() + await packageTarget(parseDesktopPackageInvocation(['mac-arm64', '--prepare-only'], 'darwin', 'arm64'), { + ...environment, DSH_DESKTOP_MACOS_PACK_CONCURRENCY: concurrency, + DSH_DESKTOP_MACOS_DOWNLOAD_PROXY: 'http://downloads.example:8080', + DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: 'http://apple.example:8081', + }, run) + const calls = run.run.mock.calls + const packs = calls.filter(call => call[0].startsWith('run release:pack')) + expect(packs).toHaveLength(2) + for (const call of packs) expect(call[2].slice(-2)).toEqual(['--concurrency', concurrency ?? '4']) + for (const call of calls) { + expect(call[3].env.HTTP_PROXY).toBe(/^run prepare:(?:runtime|dsh)$/u.test(call[0]) ? 'http://downloads.example:8080' : undefined) + } + expect(withMacOSNotarizationProxy).not.toHaveBeenCalled() +}) + +it.each([false, true])('scopes the Apple proxy around notarization (directory=%s)', async (directory) => { + const { run } = supervisor() + await packageTarget(parseDesktopPackageInvocation(['mac-arm64', ...(directory ? ['--dir'] : [])], 'darwin', 'arm64'), { + ...environment, APPLE_KEYCHAIN_PROFILE: 'fixture', DSH_DESKTOP_MACOS_NOTARIZATION_PROXY: 'http://apple.example:8081', + }, run) + expect(withMacOSNotarizationProxy).toHaveBeenCalledExactlyOnceWith('http://apple.example:8081', expect.any(Function), undefined, undefined, expect.any(Function)) + expect(packageMacOSArtifacts).toHaveBeenCalledTimes(directory ? 0 : 1) + if (!directory) { + const signing = run.run.mock.calls.findIndex(call => call[0].includes('--config.mac.notarize=false')) + expect(signing).toBeGreaterThan(-1) + expect(run.run.mock.invocationCallOrder[signing]).toBeLessThan(vi.mocked(withMacOSNotarizationProxy).mock.invocationCallOrder[0]!) + } +}) + +it('does not write a release completion record when Apple proxy cleanup fails', async () => { + const { run } = supervisor() + vi.mocked(withMacOSNotarizationProxy).mockRejectedValueOnce(new Error('proxy restoration failed')) + await expect(packageTarget(parseDesktopPackageInvocation(['mac-arm64'], 'darwin', 'arm64'), environment, run)) + .rejects.toThrow('proxy restoration failed') + expect(writeFileSync).not.toHaveBeenCalled() +}) diff --git a/apps/desktop/tests/packaging-run.spec.ts b/apps/desktop/tests/packaging-run.spec.ts index 8fbf685dad..b0ff7fce39 100644 --- a/apps/desktop/tests/packaging-run.spec.ts +++ b/apps/desktop/tests/packaging-run.spec.ts @@ -94,3 +94,29 @@ describe('packaging run records', () => { } finally { await rm(root, { recursive: true, force: true }) } }) }) + +it('allows parallel Mac stages, attributes their output, and refuses finish until both settle', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-parallel-log-')) + try { + const run = createPackagingRun(root, { target: 'mac-fixture' }, { parallel: true, secrets: ['removed-p12-password'] }) + const script = "process.stdout.write(process.argv[1]+' removed-p12-password')" + const first = run.run('app', process.execPath, ['-e', script, 'app'], { cwd: root, env: environment }) + const second = run.run('dmg', process.execPath, ['-e', script, 'dmg'], { cwd: root, env: environment }) + const settled = Promise.allSettled([first, second]) + try { expect(() => { run.finish(true) }).toThrow('active run') } finally { await settled } + const results = await settled + expect(results.map(result => result.status)).toEqual(['fulfilled', 'fulfilled']) + run.finish(true) + const log = await readFile(join(run.directory, 'events.jsonl'), 'utf8') + const events = log.trim().split('\n').map(line => JSON.parse(line) as { type: string; stage: string; text?: string }) + expect(events.filter(event => event.type === 'stage-start' || event.type === 'stage-end').slice(0, 2).map(event => event.type)) + .toEqual(['stage-start', 'stage-start']) + expect(events.filter(event => event.type === 'output').map(event => event.stage).sort()).toEqual(['app', 'dmg']) + expect(log).not.toContain('removed-p12-password') + expect(events.filter(event => event.type === 'output').every(event => event.text?.includes('[REDACTED]'))).toBe(true) + const summary = JSON.parse(await readFile(join(run.directory, 'result.json'), 'utf8')) as { stages: unknown[]; elapsedMs: number } + expect(summary).toMatchObject({ success: true, proxy: 'not-used' }) + expect(typeof summary.elapsedMs).toBe('number') + expect(summary.stages).toHaveLength(2) + } finally { await rm(root, { recursive: true, force: true }) } +}) diff --git a/apps/desktop/tests/packaging-step.spec.ts b/apps/desktop/tests/packaging-step.spec.ts new file mode 100644 index 0000000000..a1fdbdeb01 --- /dev/null +++ b/apps/desktop/tests/packaging-step.spec.ts @@ -0,0 +1,39 @@ +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { createPackagingRun, recordPackagingEvent } from '../scripts/packaging-run.mjs' +import { packagingStep } from '../scripts/packaging-step.mjs' + +it('retains nested failures without credentials and includes the restored proxy in the final summary', async () => { + const root = await mkdtemp(join(tmpdir(), 'packaging-step-')) + try { + const run = createPackagingRun(root, { target: 'fixture' }) + const work = packagingStep(run.directory, 'notarization', async () => { + throw new AggregateError([new Error('secret-sentinel'), new Error('outer', { cause: new Error('secret-sentinel') })], 'Apple refused') + }, ['secret-sentinel']) + await expect(work).rejects.toThrow('Apple refused') + recordPackagingEvent(run.directory, { type: 'notarization-proxy', status: 'restored' }) + run.finish(false) + const events = await readFile(join(run.directory, 'events.jsonl'), 'utf8') + const summary = await readFile(join(run.directory, 'result.json'), 'utf8') + expect(events).toContain('[REDACTED]') + expect(events).toContain('outer') + expect(events).not.toContain('secret-sentinel') + expect(summary).not.toContain('secret-sentinel') + expect(JSON.parse(summary)).toMatchObject({ success: false, proxy: 'restored', stages: [{ stage: 'notarization', success: false }] }) + } finally { await rm(root, { recursive: true, force: true }) } +}) + +it('preserves unrecorded callers and records successful return values without persisting them', async () => { + const root = await mkdtemp(join(tmpdir(), 'packaging-step-result-')) + try { + const run = createPackagingRun(root, {}) + expect(await packagingStep(undefined, 'plain', async () => 42)).toBe(42) + expect(await packagingStep(run.directory, 'logged', async () => 'private-return-value')).toBe('private-return-value') + run.finish(true) + const events = await readFile(join(run.directory, 'events.jsonl'), 'utf8') + expect(events).toContain('"success":true') + expect(events).not.toContain('private-return-value') + } finally { await rm(root, { recursive: true, force: true }) } +}) From 76a592e3ab64bc060ad8aad40f8ec2c8f14785c9 Mon Sep 17 00:00:00 2001 From: winewill Date: Fri, 18 Sep 2026 11:57:56 +0800 Subject: [PATCH 10/45] refactor(desktop): configure test policy login origins --- apps/desktop/.env.macos.example | 9 ++--- apps/desktop/.env.windows.example | 9 ++--- apps/desktop/README.i18n.yaml | 4 +-- apps/desktop/README.md | 5 +-- apps/desktop/README.zh.md | 5 +-- .../scripts/desktop-policy-environment.d.mts | 1 + .../scripts/desktop-policy-environment.mjs | 8 +++++ .../scripts/test-windows-installer.mjs | 4 ++- apps/desktop/src/main.ts | 3 +- apps/desktop/src/mandatory-update-policy.ts | 9 +++++ apps/desktop/src/policy-test-auth.ts | 9 +++-- .../tests/desktop-package-environment.spec.ts | 3 +- .../tests/desktop-policy-environment.spec.ts | 35 +++++++++++++------ .../tests/installed-update-builder.spec.ts | 1 + .../installed-update-package-content.spec.ts | 2 +- .../desktop/tests/installer-packaging.spec.ts | 3 +- apps/desktop/tests/macos-signature.spec.ts | 3 ++ apps/desktop/tests/main-startup.spec.ts | 14 ++++---- .../tests/mandatory-update-policy.spec.ts | 11 +++++- apps/desktop/tests/policy-test-auth.spec.ts | 12 +++---- .../desktop/tests/windows-asar-unpack.spec.ts | 1 + .../tests/windows-update-publisher.spec.ts | 1 + 22 files changed, 104 insertions(+), 48 deletions(-) diff --git a/apps/desktop/.env.macos.example b/apps/desktop/.env.macos.example index 53c3945f60..d7da15ac63 100644 --- a/apps/desktop/.env.macos.example +++ b/apps/desktop/.env.macos.example @@ -5,11 +5,12 @@ DSH_DESKTOP_AUTO_UPDATE_ENV=test DOWNLOAD_TEST_ORIGIN= # The selected mandatory-update origin is required, including unsigned and preparation builds. -DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN=https://harness-test.deepseek.com -DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN=https://harness.deepseek.com -# Optional polling and fallback-page options; origin and authentication are selected automatically. +DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN= +DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN= +# Set approved login origins for test builds; omit allowedAuthOrigins for production. +# Optional polling and fallback-page options belong in the same JSON value. # The fallback-page allowlist defaults to the selected service origin. -# DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"intervalMs":600000}' +DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"allowedAuthOrigins":["https://login.example.com"]}' DSH_DESKTOP_MACOS_SIGNING_IDENTITY= DSH_DESKTOP_MACOS_TEAM_ID= diff --git a/apps/desktop/.env.windows.example b/apps/desktop/.env.windows.example index e162c805d0..a09951f402 100644 --- a/apps/desktop/.env.windows.example +++ b/apps/desktop/.env.windows.example @@ -5,11 +5,12 @@ DSH_DESKTOP_AUTO_UPDATE_ENV=test DOWNLOAD_TEST_ORIGIN= # The selected mandatory-update origin is required, including unsigned and preparation builds. -DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN=https://harness-test.deepseek.com -DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN=https://harness.deepseek.com -# Optional polling and fallback-page options; origin and authentication are selected automatically. +DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN= +DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN= +# Set approved login origins for test builds; omit allowedAuthOrigins for production. +# Optional polling and fallback-page options belong in the same JSON value. # The fallback-page allowlist defaults to the selected service origin. -# DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"intervalMs":600000}' +DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"allowedAuthOrigins":["https://login.example.com"]}' DSH_DESKTOP_WINDOWS_CER_FILE= DSH_DESKTOP_WINDOWS_SIGNTOOL= diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 909bef683c..e72f9bca8d 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: c2a1f4df103d5fe74f4a25aa1bcfc1f8e38d3b1e -README.zh.md: 9dda03b4b40a7b46bf5e0f1404f77d73d397bfa4 +README.md: bfe8f68bfbe43de4545255e8005a9ee33ab5f4b7 +README.zh.md: 163a0f070ba9c396d256633fc18afc566ea7a997 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index c2a1f4df10..bfe8f68bfb 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -275,15 +275,16 @@ Confirmed Host exit without successful task teardown displays localized recovery ### Mandatory update policy -The [mandatory client decision](../../.agents/notes/implemented/feature/2026-09-11-desktop-mandatory-update-client.md) owns policy polling and the blocking window. Packaging reads `.env.windows` or `.env.macos`: `DSH_DESKTOP_AUTO_UPDATE_ENV=test` (the default) selects `DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN`; `production` selects `DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN`. Templates use `https://harness-test.deepseek.com` and `https://harness.deepseek.com`, respectively. The selected origin is required before preparation or signing, including unsigned and preparation-only builds; the unselected origin is optional. These settings never fall back to the parent environment or the other deployment. Packaging embeds the selected policy with the application ID; packaged applications ignore runtime overrides. +The [mandatory client decision](../../.agents/notes/implemented/feature/2026-09-11-desktop-mandatory-update-client.md) owns policy polling and the blocking window. Packaging reads `.env.windows` or `.env.macos`: `DSH_DESKTOP_AUTO_UPDATE_ENV=test` (the default) selects `DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN`; `production` selects `DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN`. The templates leave both origins blank; fill in the selected deployment origin in the ignored local dotenv file. The selected origin is required before preparation or signing, including unsigned and preparation-only builds; the unselected origin is optional. These settings never fall back to the parent environment or the other deployment. Packaging embeds the selected policy with the application ID; packaged applications ignore runtime overrides. -Optional `DSH_DESKTOP_MANDATORY_UPDATE_CONFIG` JSON supplies polling and download-page options; packaging rejects `origin` and `authentication` inside it. The page allowlist defaults to the selected service origin; explicitly allow other approved download-page origins when needed. Test builds select `feishu-test`, and production selects `anonymous`. Policy requests reject redirects; only test authentication carries gateway cookies. Unpackaged development instead reads a complete policy JSON from this variable and requires `DSH_DESKTOP_APP_ID`; absent JSON disables development policy queries, and only anonymous development permits HTTP `127.0.0.1`. A user-initiated ordinary check triggers policy work concurrently but never waits for or reports a policy failure. Only a confirmed blocking decision cancels ordinary dialogs. Test authentication waits until the active ordinary dialog finishes, and cancellation or failure does not discard the updater result. +`DSH_DESKTOP_MANDATORY_UPDATE_CONFIG` JSON supplies test login origins and optional polling and download-page options; packaging rejects `origin` and `authentication` inside it. The page allowlist defaults to the selected service origin; explicitly allow other approved download-page origins when needed. Test builds select `feishu-test` and require `allowedAuthOrigins` in `DSH_DESKTOP_MANDATORY_UPDATE_CONFIG`; production selects `anonymous` and rejects that field. Each login origin must be an HTTPS origin without credentials, path, query, or fragment. The login window permits document navigation only to the selected policy origin and these configured origins. Policy requests reject redirects; only test authentication carries gateway cookies. Unpackaged development instead reads a complete policy JSON from this variable and requires `DSH_DESKTOP_APP_ID`; absent JSON disables development policy queries, and only anonymous development permits HTTP `127.0.0.1`. A user-initiated ordinary check triggers policy work concurrently but never waits for or reports a policy failure. Only a confirmed blocking decision cancels ordinary dialogs. Test authentication waits until the active ordinary dialog finishes, and cancellation or failure does not discard the updater result. | Resolved policy field | Meaning and default | |---|---| | `origin` | Required HTTPS API origin, without credentials, path, query, or fragment; requests use `/api/v0/check_client_update` | | `allowedPageOrigins` | Nonempty array of exact HTTPS origins; packaging defaults to the selected API origin; subdomains and alternate ports are not implied | | `authentication` | Packaging selects `feishu-test` for test and `anonymous` for production; unpackaged development defaults to `anonymous` | +| `allowedAuthOrigins` | Nonempty array of exact HTTPS login document origins for test authentication; forbidden for production | | `intervalMs` | Polling interval; default `600000` | | `timeoutMs` | Request deadline; default `15000` | | `maxBackoffMs` | Maximum failed-request interval including jitter; default `3600000`, at least `intervalMs` | diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 9dda03b4b4..163a0f070b 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -276,15 +276,16 @@ macOS 打包在组装 App 时、代码签名前写入 `Contents/Resources/app-up ### 强制更新策略 -[强更客户端决策](../../.agents/notes/implemented/feature/2026-09-11-desktop-mandatory-update-client.zh.md)负责策略查询和阻塞窗口。打包读取 `.env.windows` 或 `.env.macos`:`DSH_DESKTOP_AUTO_UPDATE_ENV=test`(默认值)选择 `DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN`;`production` 选择 `DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN`。模板分别使用 `https://harness-test.deepseek.com` 和 `https://harness.deepseek.com`。在准备产物或签名前,所选源站必须配置,包括未签名和仅准备构建;未选环境的源站可不填。这些配置不会回退到父进程环境或另一部署环境。打包将选定策略与应用 ID 写入元数据;打包应用忽略运行时覆盖。 +[强更客户端决策](../../.agents/notes/implemented/feature/2026-09-11-desktop-mandatory-update-client.zh.md)负责策略查询和阻塞窗口。打包读取 `.env.windows` 或 `.env.macos`:`DSH_DESKTOP_AUTO_UPDATE_ENV=test`(默认值)选择 `DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN`;`production` 选择 `DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN`。模板将两个源站留空;在 Git 忽略的目标 dotenv 文件中填写所选部署的源站。在准备产物或签名前,所选源站必须配置,包括未签名和仅准备构建;未选环境的源站可不填。这些配置不会回退到父进程环境或另一部署环境。打包将选定策略与应用 ID 写入元数据;打包应用忽略运行时覆盖。 -可选的 `DSH_DESKTOP_MANDATORY_UPDATE_CONFIG` JSON 提供轮询和下载页面选项;打包拒绝其中的 `origin` 和 `authentication`。页面白名单默认只包含所选服务源站;需要其他已批准下载页面源站时应显式配置。测试包选择 `feishu-test`,正式包选择 `anonymous`。策略请求拒绝重定向;仅测试鉴权携带网关 Cookie。未打包开发模式则从此变量读取完整策略 JSON,并要求 `DSH_DESKTOP_APP_ID`;缺少 JSON 会禁用开发模式策略查询,仅匿名开发允许 HTTP `127.0.0.1`。用户发起常规检查时会并发触发策略检查,但不会等待或展示策略失败。只有已确认的强更决定可以关闭常规弹窗。测试环境鉴权会等待当前常规弹窗结束,取消或失败不会丢弃 updater 结果。 +`DSH_DESKTOP_MANDATORY_UPDATE_CONFIG` JSON 提供测试登录源站,以及可选的轮询和下载页面选项;打包拒绝其中的 `origin` 和 `authentication`。页面白名单默认只包含所选服务源站;需要其他已批准下载页面源站时应显式配置。测试包选择 `feishu-test`,且必须在 `DSH_DESKTOP_MANDATORY_UPDATE_CONFIG` 中配置 `allowedAuthOrigins`;正式包选择 `anonymous`,并拒绝该字段。每个登录源站必须是没有凭据、路径、查询或片段的 HTTPS origin。登录窗口仅允许文档导航到所选策略源站和这些已配置源站。策略请求拒绝重定向;仅测试鉴权携带网关 Cookie。未打包开发模式则从此变量读取完整策略 JSON,并要求 `DSH_DESKTOP_APP_ID`;缺少 JSON 会禁用开发模式策略查询,仅匿名开发允许 HTTP `127.0.0.1`。用户发起常规检查时会并发触发策略检查,但不会等待或展示策略失败。只有已确认的强更决定可以关闭常规弹窗。测试环境鉴权会等待当前常规弹窗结束,取消或失败不会丢弃 updater 结果。 | 解析后的策略字段 | 含义与默认值 | |---|---| | `origin` | 必填 HTTPS API 源站,不含凭据、路径、查询或片段;请求使用 `/api/v0/check_client_update` | | `allowedPageOrigins` | 非空的精确 HTTPS 源站数组;打包时默认只包含所选 API 源站;不隐含子域名或其他端口 | | `authentication` | 打包时测试环境选择 `feishu-test`,正式环境选择 `anonymous`;未打包开发模式默认为 `anonymous` | +| `allowedAuthOrigins` | 测试鉴权必填的非空 HTTPS 登录文档源站数组;正式环境禁止配置 | | `intervalMs` | 轮询间隔;默认 `600000` | | `timeoutMs` | 请求截止时间;默认 `15000` | | `maxBackoffMs` | 含抖动的失败请求最大间隔;默认 `3600000`,不小于 `intervalMs` | diff --git a/apps/desktop/scripts/desktop-policy-environment.d.mts b/apps/desktop/scripts/desktop-policy-environment.d.mts index a9cd2995fe..7b2230a277 100644 --- a/apps/desktop/scripts/desktop-policy-environment.d.mts +++ b/apps/desktop/scripts/desktop-policy-environment.d.mts @@ -2,6 +2,7 @@ export interface DesktopPolicyEnvironment { origin: string allowedPageOrigins: string[] + allowedAuthOrigins?: string[] authentication: 'anonymous' | 'feishu-test' [key: string]: unknown } diff --git a/apps/desktop/scripts/desktop-policy-environment.mjs b/apps/desktop/scripts/desktop-policy-environment.mjs index a582e37772..591147578b 100644 --- a/apps/desktop/scripts/desktop-policy-environment.mjs +++ b/apps/desktop/scripts/desktop-policy-environment.mjs @@ -30,7 +30,15 @@ export function resolveDesktopPolicyEnvironment(environment) { } const pages = settings.allowedPageOrigins ?? [selected] if (!Array.isArray(pages) || pages.length === 0) throw new Error('desktop package: allowedPageOrigins must be a nonempty array') + const authOrigins = settings.allowedAuthOrigins + if (deployment === 'test' && (!Array.isArray(authOrigins) || authOrigins.length === 0)) { + throw new Error('desktop package: test policy requires nonempty allowedAuthOrigins') + } + if (deployment === 'production' && authOrigins !== undefined) { + throw new Error('desktop package: production policy must not configure allowedAuthOrigins') + } return { ...settings, origin: selected, allowedPageOrigins: pages.map(value => origin(value, 'allowedPageOrigins')), + ...(deployment === 'test' ? { allowedAuthOrigins: authOrigins.map(value => origin(value, 'allowedAuthOrigins')) } : {}), authentication: deployment === 'test' ? 'feishu-test' : 'anonymous' } } diff --git a/apps/desktop/scripts/test-windows-installer.mjs b/apps/desktop/scripts/test-windows-installer.mjs index 95e4db8b70..a92df3844e 100644 --- a/apps/desktop/scripts/test-windows-installer.mjs +++ b/apps/desktop/scripts/test-windows-installer.mjs @@ -44,7 +44,9 @@ try { DSH_DESKTOP_TARGET_PLATFORM: 'win32', DSH_DESKTOP_TARGET_ARCH: 'x64', DSH_DESKTOP_UNSIGNED: '1', CSC_IDENTITY_AUTO_DISCOVERY: 'false', ELECTRON_BUILDER_7Z_FILTER: 'BCJ', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: signingEnvironment.DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN - ?? 'https://harness-test.deepseek.com', + ?? 'https://test.example.com', + DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: signingEnvironment.DSH_DESKTOP_MANDATORY_UPDATE_CONFIG + ?? JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), ...signingRun ? { DSH_DESKTOP_PACKAGING_RUN_DIR: signingRun.directory } : {}, }) const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs') diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 5c21833b0e..8c21233fe0 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -728,7 +728,8 @@ async function main(): Promise { const policyConfig = resolveDesktopPolicyConfig(policyInput, !app.isPackaged) if (policyConfig !== undefined) { if (policyConfig.authentication === 'feishu-test') { - policyAuth = new DesktopPolicyTestAuth(policyConfig.origin, locale, () => mandatoryUI?.confirmationWindow ?? mainWindow, + policyAuth = new DesktopPolicyTestAuth(policyConfig.origin, policyConfig.allowedAuthOrigins, locale, + () => mandatoryUI?.confirmationWindow ?? mainWindow, (event) => { console.info(`desktop policy authentication: ${event}`); updateJournal?.action(`policy-login-${event}`) }) } const bundleId = app.isPackaged diff --git a/apps/desktop/src/mandatory-update-policy.ts b/apps/desktop/src/mandatory-update-policy.ts index 1ccc068969..584a52a966 100644 --- a/apps/desktop/src/mandatory-update-policy.ts +++ b/apps/desktop/src/mandatory-update-policy.ts @@ -16,6 +16,7 @@ export interface DesktopPolicyIdentity { export interface DesktopPolicyConfig { readonly origin: string readonly allowedPageOrigins: readonly string[] + readonly allowedAuthOrigins: readonly string[] readonly intervalMs: number readonly timeoutMs: number readonly maxBackoffMs: number @@ -74,12 +75,20 @@ export function resolveDesktopPolicyConfig(input: unknown, allowLoopback = false if (authentication !== 'anonymous' && authentication !== 'feishu-test') { throw new Error('desktop policy: authentication must be anonymous or feishu-test') } + const authOrigins = value.allowedAuthOrigins + if (authentication === 'feishu-test' && (!Array.isArray(authOrigins) || authOrigins.length === 0)) { + throw new Error('desktop policy: test authentication requires nonempty allowedAuthOrigins') + } + if (authentication === 'anonymous' && authOrigins !== undefined) { + throw new Error('desktop policy: anonymous policy must not configure allowedAuthOrigins') + } if (typeof jitter !== 'number' || !Number.isFinite(jitter) || jitter < 0 || jitter > 1 || maxBackoffMs < intervalMs) { throw new Error('desktop policy: jitter must be in [0, 1] and maxBackoffMs must cover intervalMs') } return { origin: origin(value.origin, authentication === 'anonymous' && allowLoopback), allowedPageOrigins: value.allowedPageOrigins.map(item => origin(item, false)), + allowedAuthOrigins: authentication === 'feishu-test' ? (authOrigins as unknown[]).map(item => origin(item, false)) : [], intervalMs, timeoutMs: duration('timeoutMs', 15_000), maxBackoffMs, jitter, authentication, } } diff --git a/apps/desktop/src/policy-test-auth.ts b/apps/desktop/src/policy-test-auth.ts index b7d5d65208..e7597a5e57 100644 --- a/apps/desktop/src/policy-test-auth.ts +++ b/apps/desktop/src/policy-test-auth.ts @@ -3,9 +3,6 @@ import { randomUUID } from 'node:crypto' import { BrowserWindow, session } from 'electron' import type { DesktopLocale } from './locale.ts' -const FEISHU_ORIGINS = ['https://open.feishu.cn', 'https://accounts.feishu.cn', - 'https://passport.feishu.cn', 'https://login.feishu.cn'] - /** Packaged placeholder document; it is the window's first document and needs no network. */ const LOGIN_LOADING_PAGE = 'renderer/policy-login-loading.html' @@ -28,11 +25,13 @@ export class DesktopPolicyTestAuth { /** * @param origin Validated HTTPS policy origin; login always starts at its root with fresh gateway state. + * @param allowedAuthOrigins Validated HTTPS origins for login document navigation. * @param locale Shell-owned login title. * @param parent Current application or mandatory-update window. * @param record Fixed, nonsecret login outcomes for diagnostic evidence. */ - constructor(private readonly origin: string, private readonly locale: DesktopLocale, + constructor(private readonly origin: string, private readonly allowedAuthOrigins: readonly string[], + private readonly locale: DesktopLocale, private readonly parent: () => BrowserWindow | undefined, private readonly record: (event: 'opened' | DesktopPolicyLoginResult) => void) { this.browserSession.setPermissionRequestHandler((_contents, _permission, callback) => { callback(false) }) @@ -144,7 +143,7 @@ export class DesktopPolicyTestAuth { let url: URL try { url = new URL(value) } catch { return false } return url.protocol === 'https:' && url.username === '' && url.password === '' - && (url.origin === this.origin || FEISHU_ORIGINS.includes(url.origin)) + && (url.origin === this.origin || this.allowedAuthOrigins.includes(url.origin)) } /** diff --git a/apps/desktop/tests/desktop-package-environment.spec.ts b/apps/desktop/tests/desktop-package-environment.spec.ts index 50d9726550..fb011401aa 100644 --- a/apps/desktop/tests/desktop-package-environment.spec.ts +++ b/apps/desktop/tests/desktop-package-environment.spec.ts @@ -6,7 +6,8 @@ import { loadDesktopPackageEnvironment, validateDesktopPackageEnvironment } from const WINDOWS = { platform: 'win32', arch: 'x64' } as const const MACOS = { platform: 'darwin', arch: 'arm64' } as const -const POLICY = { DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com' } +const POLICY = { DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', + DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }) } const RELEASE = { ...POLICY, DSH_DESKTOP_APP_ID: 'com.example.desktop', DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com' } const MAC_IDENTITY = { DSH_DESKTOP_MACOS_SIGNING_IDENTITY: 'Example Company (TEAMID1234)', DSH_DESKTOP_MACOS_TEAM_ID: 'TEAMID1234' } diff --git a/apps/desktop/tests/desktop-policy-environment.spec.ts b/apps/desktop/tests/desktop-policy-environment.spec.ts index 8316b833fc..e4d893eca0 100644 --- a/apps/desktop/tests/desktop-policy-environment.spec.ts +++ b/apps/desktop/tests/desktop-policy-environment.spec.ts @@ -3,28 +3,32 @@ import { resolveDesktopPolicyEnvironment } from '../scripts/desktop-policy-envir import { validateDesktopPackageEnvironment } from '../scripts/desktop-package-environment.mjs' import { resolveDesktopPolicyConfig } from '../src/mandatory-update-policy.ts' -const origins = { DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://harness-test.deepseek.com', - DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN: 'https://harness.deepseek.com' } +const origins = { DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://test.example.com', + DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN: 'https://prod.example.com' } +const auth = { DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }) } it.each(['test', 'production'] as const)('selects the %s policy and authentication together', (deployment) => { - const policy = resolveDesktopPolicyEnvironment({ ...origins, DSH_DESKTOP_AUTO_UPDATE_ENV: deployment }) + const policy = resolveDesktopPolicyEnvironment({ ...origins, ...(deployment === 'test' ? auth : {}), DSH_DESKTOP_AUTO_UPDATE_ENV: deployment }) const origin = deployment === 'test' ? origins.DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN : origins.DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN - expect(policy).toEqual({ origin, allowedPageOrigins: [origin], authentication: deployment === 'test' ? 'feishu-test' : 'anonymous' }) + expect(policy).toEqual({ origin, allowedPageOrigins: [origin], + ...(deployment === 'test' ? { allowedAuthOrigins: ['https://login.example.com'] } : {}), + authentication: deployment === 'test' ? 'feishu-test' : 'anonymous' }) expect(resolveDesktopPolicyConfig(policy)).toMatchObject(policy) }) it('requires only the selected origin, defaults to test, and accepts explicit page restrictions', () => { const policy = resolveDesktopPolicyEnvironment({ DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: origins.DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN, - DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedPageOrigins: ['https://download.deepseek.com'], intervalMs: 5000 }) }) - expect(policy).toMatchObject({ authentication: 'feishu-test', intervalMs: 5000, allowedPageOrigins: ['https://download.deepseek.com'] }) + DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'], + allowedPageOrigins: ['https://download.example.com'], intervalMs: 5000 }) }) + expect(policy).toMatchObject({ authentication: 'feishu-test', intervalMs: 5000, allowedPageOrigins: ['https://download.example.com'] }) expect(() => resolveDesktopPolicyEnvironment({ ...origins, DSH_DESKTOP_AUTO_UPDATE_ENV: 'prod' })).toThrow('production') }) -it.each([undefined, '', 'http://harness-test.deepseek.com', 'https://user:secret@harness-test.deepseek.com', - 'https://harness-test.deepseek.com/api', 'https://harness-test.deepseek.com/?secret=value'])('rejects invalid selected origin %s', (origin) => { - expect(() => resolveDesktopPolicyEnvironment({ DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: origin })).toThrow('HTTPS origin') - expect(() => resolveDesktopPolicyEnvironment({ DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: origin })).not.toThrow('secret=value') +it.each([undefined, '', 'http://test.example.com', 'https://user:secret@test.example.com', + 'https://test.example.com/api', 'https://test.example.com/?secret=value'])('rejects invalid selected origin %s', (origin) => { + expect(() => resolveDesktopPolicyEnvironment({ ...auth, DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: origin })).toThrow('HTTPS origin') + expect(() => resolveDesktopPolicyEnvironment({ ...auth, DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: origin })).not.toThrow('secret=value') }) it.each(['{', 'null', '[]', '{"origin":"https://old.example.com"}', '{"authentication":"anonymous"}', @@ -32,6 +36,17 @@ it.each(['{', 'null', '[]', '{"origin":"https://old.example.com"}', '{"authentic expect(() => resolveDesktopPolicyEnvironment({ ...origins, DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: options })).toThrow() }) +it.each([undefined, '[]', '["http://login.example.com"]', '["https://login.example.com/path"]', + '["https://user:secret@login.example.com"]'])('rejects missing or invalid test login origins %s', (value) => { + const settings = value === undefined ? {} : { allowedAuthOrigins: JSON.parse(value) as unknown } + expect(() => resolveDesktopPolicyEnvironment({ ...origins, DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify(settings) })).toThrow() +}) + +it('rejects login origins in production', () => { + expect(() => resolveDesktopPolicyEnvironment({ ...origins, ...auth, DSH_DESKTOP_AUTO_UPDATE_ENV: 'production' })) + .toThrow('must not configure allowedAuthOrigins') +}) + it.each([{ unsigned: true }, { prepareOnly: true }, {}])('fails before signing/preparation when policy is absent in %j', (options) => { for (const platform of ['win32', 'darwin'] as const) { expect(() => { validateDesktopPackageEnvironment({ DSH_DESKTOP_APP_ID: 'com.example.test' }, { platform, arch: 'x64' }, options) }) diff --git a/apps/desktop/tests/installed-update-builder.spec.ts b/apps/desktop/tests/installed-update-builder.spec.ts index 781a68687e..55ad22fd5d 100644 --- a/apps/desktop/tests/installed-update-builder.spec.ts +++ b/apps/desktop/tests/installed-update-builder.spec.ts @@ -20,6 +20,7 @@ vi.mock('../scripts/windows-sign.mjs', () => ({ const versions = ['0.1.6-nightly.20260914.1', '0.1.6-nightly.20260914.2'] as const const environment = { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: 'https://download-test.deepseek.com', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', + DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), DOWNLOAD_TEST_COS_BUCKET: 'bj-toc-download-test-1320056602' } const require = createRequire(import.meta.url) const { validateConfiguration } = require('app-builder-lib/out/util/config/config.js') as { diff --git a/apps/desktop/tests/installed-update-package-content.spec.ts b/apps/desktop/tests/installed-update-package-content.spec.ts index ddc53dbe50..8ecfeb9f39 100644 --- a/apps/desktop/tests/installed-update-package-content.spec.ts +++ b/apps/desktop/tests/installed-update-package-content.spec.ts @@ -61,7 +61,7 @@ async function fixture(body: (context: { await writeFile(join(source, 'package.json'), JSON.stringify({ name: `dsh-update-test-${run.id}`, version, dshDesktopAppId: run.appId, main: 'qualification-bootstrap.mjs', type: 'module', dshMandatoryUpdatePolicy: { origin: 'https://policy.example.com', allowedPageOrigins: ['https://policy.example.com'], - authentication: 'feishu-test' } })) + authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'] } })) for (const name of ['electron-updater', 'semver']) { await mkdir(join(source, 'node_modules', name), { recursive: true }) await cp(require.resolve(`${name}/package.json`), join(source, 'node_modules', name, 'package.json')) diff --git a/apps/desktop/tests/installer-packaging.spec.ts b/apps/desktop/tests/installer-packaging.spec.ts index 1eaa829407..1dcfcb24fd 100644 --- a/apps/desktop/tests/installer-packaging.spec.ts +++ b/apps/desktop/tests/installer-packaging.spec.ts @@ -16,7 +16,7 @@ describe('installer preparation preserves application dependencies', () => { const { createElectronBuilderConfig } = await import('../scripts/electron-builder-config.mjs') expect(() => createElectronBuilderConfig({ DSH_DESKTOP_APP_ID: 'com.example.installer', DSH_DESKTOP_AUTO_UPDATE_ENV: 'production', - DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://harness-test.deepseek.com', + DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://test.example.com', }, platform, 'x64')).toThrow('DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN') }) it.each(['win32', 'darwin'] as const)('keeps electron-builder responsible for node_modules on %s', async (platform) => { @@ -24,6 +24,7 @@ describe('installer preparation preserves application dependencies', () => { const env = { DSH_DESKTOP_APP_ID: 'com.example.installer', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', + DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), DSH_DESKTOP_TARGET_PLATFORM: platform, DSH_DESKTOP_TARGET_ARCH: 'x64', DSH_DESKTOP_UNSIGNED: platform === 'win32' ? '1' : '0', diff --git a/apps/desktop/tests/macos-signature.spec.ts b/apps/desktop/tests/macos-signature.spec.ts index eaf5f03920..2bd63adbaa 100644 --- a/apps/desktop/tests/macos-signature.spec.ts +++ b/apps/desktop/tests/macos-signature.spec.ts @@ -14,6 +14,7 @@ import { const RELEASE_ENVIRONMENT = { DSH_DESKTOP_APP_ID: 'com.example.desktop', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', + DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), DSH_DESKTOP_TARGET_PLATFORM: 'darwin', DSH_DESKTOP_TARGET_ARCH: 'arm64', DSH_DESKTOP_MACOS_SIGNING_IDENTITY: 'Example Company (TEAMID1234)', @@ -97,6 +98,7 @@ describe('desktop macOS release signature', () => { expect(() => createElectronBuilderConfig({ DSH_DESKTOP_APP_ID: RELEASE_ENVIRONMENT.DSH_DESKTOP_APP_ID, DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', + DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), DSH_DESKTOP_TARGET_PLATFORM: 'win32', }, 'win32')).toThrow(/DSH_DESKTOP_WINDOWS_CER_FILE/u) }) @@ -106,6 +108,7 @@ describe('desktop macOS release signature', () => { const config = createElectronBuilderConfig({ DSH_DESKTOP_APP_ID: RELEASE_ENVIRONMENT.DSH_DESKTOP_APP_ID, DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', + DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), DSH_DESKTOP_TARGET_PLATFORM: 'win32', DSH_DESKTOP_UNSIGNED: '1', }, 'win32', 'x64') diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 3df37cb4ae..81abfe8169 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -289,7 +289,7 @@ beforeEach(() => { vi.spyOn(console, 'info').mockImplementation(() => {}) vi.stubEnv('DSH_DESKTOP_PNPM_ENTRY', 'test-pnpm') vi.stubEnv('DSH_DESKTOP_DSH_DIR', 'test-runtime') - vi.stubGlobal('process', { ...process, platform: 'win32', resourcesPath: 'desktop-test-resources' }) + vi.stubGlobal('process', { ...process, platform: 'win32', arch: 'x64', resourcesPath: 'desktop-test-resources' }) vi.stubEnv('DSH_DESKTOP_HOST_INSPECT_PORT', undefined) vi.stubEnv('DSH_DESKTOP_MANDATORY_UPDATE_CONFIG', undefined) vi.stubEnv('DSH_DESKTOP_UPDATE_JOURNAL_DIR', undefined) @@ -340,7 +340,7 @@ describe('desktop main startup', () => { }) it('shows one explained startup login before Host readiness and joins concurrent checks without reopening it', async () => { - harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 1000, jitter: 0 } vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 }))) @@ -383,7 +383,7 @@ describe('desktop main startup', () => { }) it.each(['returned', 'cancelled', 'failed'] as const)('requires explicit test login and handles %s without downloading', async (outcome) => { - harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 10_000, jitter: 0 } const request = vi.fn().mockImplementation(async () => Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })) vi.stubGlobal('fetch', request) @@ -410,7 +410,7 @@ describe('desktop main startup', () => { }) it('does not open Feishu when the user declines test login', async () => { - harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'] } vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 }))) await readyForUpdate() @@ -420,7 +420,7 @@ describe('desktop main startup', () => { }) it('does not require gateway login to download an already available ordinary update', async () => { - harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'] } vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 }))) @@ -433,7 +433,7 @@ describe('desktop main startup', () => { }) it('retains the same blocking window and running Host after expired test login is cancelled', async () => { - harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 1000, jitter: 0 } const request = vi.fn().mockImplementation(async () => Response.json({ error: { code: 'UNAUTHENTICATED' } }, { status: 401 })) @@ -932,7 +932,7 @@ describe('desktop main startup', () => { }) it('queues policy authentication until the ordinary result dialog closes', async () => { - harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', + harness.embeddedPolicy = { origin: 'https://policy.example.com', authentication: 'feishu-test', allowedAuthOrigins: ['https://login.example.com'], allowedPageOrigins: ['https://downloads.example.com'], intervalMs: 10_000, jitter: 0 } const request = vi.fn() .mockResolvedValueOnce(Response.json({ code: 0, data: { biz_code: 0, biz_data: null } })) diff --git a/apps/desktop/tests/mandatory-update-policy.spec.ts b/apps/desktop/tests/mandatory-update-policy.spec.ts index e43e09c814..530c54d295 100644 --- a/apps/desktop/tests/mandatory-update-policy.spec.ts +++ b/apps/desktop/tests/mandatory-update-policy.spec.ts @@ -13,7 +13,7 @@ const instances: DesktopMandatoryUpdatePolicy[] = [] function fixture(authentication: 'anonymous' | 'feishu-test' = 'anonymous') { const request = vi.fn().mockResolvedValue(Response.json(clear)) const publish = vi.fn<(state: DesktopPolicyState) => void>() - const policy = new DesktopMandatoryUpdatePolicy(resolveDesktopPolicyConfig({ ...deployment, authentication })!, + const policy = new DesktopMandatoryUpdatePolicy(resolveDesktopPolicyConfig({ ...deployment, authentication, ...(authentication === 'feishu-test' ? { allowedAuthOrigins: ['https://login.example.com'] } : {}) })!, identity, publish, request) instances.push(policy) return { policy, request, publish } @@ -162,6 +162,15 @@ describe('mandatory update policy', () => { }) describe('policy deployment and page validation', () => { + it('requires validated login origins only for test authentication', () => { + expect(() => resolveDesktopPolicyConfig({ ...deployment, authentication: 'feishu-test' })).toThrow('allowedAuthOrigins') + expect(() => resolveDesktopPolicyConfig({ ...deployment, allowedAuthOrigins: ['https://login.example.com'] })).toThrow('anonymous') + expect(() => resolveDesktopPolicyConfig({ ...deployment, authentication: 'feishu-test', + allowedAuthOrigins: ['https://login.example.com/path'] })).toThrow('HTTPS origin') + expect(resolveDesktopPolicyConfig({ ...deployment, authentication: 'feishu-test', + allowedAuthOrigins: ['https://login.example.com'] })?.allowedAuthOrigins).toEqual(['https://login.example.com']) + }) + it('requires explicit production origins and confines HTTP to an explicit local policy fixture', () => { expect(resolveDesktopPolicyConfig(undefined)).toBeUndefined() expect(() => resolveDesktopPolicyConfig({ ...deployment, origin: 'http://127.0.0.1:19001' })).toThrow('HTTPS') diff --git a/apps/desktop/tests/policy-test-auth.spec.ts b/apps/desktop/tests/policy-test-auth.spec.ts index 517eda15ca..d830dd1d22 100644 --- a/apps/desktop/tests/policy-test-auth.spec.ts +++ b/apps/desktop/tests/policy-test-auth.spec.ts @@ -35,7 +35,7 @@ beforeEach(() => { vi.clearAllMocks() browserSession = makeSession(); window = makeWindow() native.partition.mockReturnValue(browserSession); native.create.mockReturnValue(window) - auth = new DesktopPolicyTestAuth('https://policy.example.com', resolveDesktopLocale('zh'), () => undefined, record) + auth = new DesktopPolicyTestAuth('https://policy.example.com', ['https://login.example.com'], resolveDesktopLocale('zh'), () => undefined, record) }) afterEach(async () => { await auth.dispose() }) @@ -64,7 +64,7 @@ it('opens a sandboxed window on explicit action and coalesces logins without aut expect(window.loadURL).not.toHaveBeenCalled() await vi.waitFor(() => { expect(window.loadURL).toHaveBeenCalledWith('https://policy.example.com/') }) expect(window.loadFile).toHaveBeenCalledTimes(1) - window.webContents.emit('did-navigate', {}, 'https://accounts.feishu.cn/open-apis/authen/v1/index?state=secret') + window.webContents.emit('did-navigate', {}, 'https://login.example.com/open-apis/authen/v1/index?state=secret') expect(window.isDestroyed()).toBe(false) window.webContents.emit('did-navigate', {}, 'https://policy.example.com/') expect(await pending).toBe('returned') @@ -121,7 +121,7 @@ it('cancels a login closed while the placeholder is still loading, without start it.each(['will-navigate', 'will-redirect'])('refuses unapproved %s targets without logging OAuth data', async (eventName) => { const pending = auth.login() const event = { preventDefault: vi.fn() } - window.webContents.emit(eventName, event, 'https://accounts.feishu.cn.evil.example/?code=secret') + window.webContents.emit(eventName, event, 'https://login.example.com.evil.example/?code=secret') expect(event.preventDefault).toHaveBeenCalledOnce() expect(await pending).toBe('failed') expect(record.mock.calls).toEqual([['opened'], ['failed']]) @@ -144,8 +144,8 @@ it('rejects child-frame escapes, permissions, downloads, new windows and HTTP au expect(await pending).toBe('failed') }) -it.each(['https://open.feishu.cn/', 'https://accounts.feishu.cn/', 'https://passport.feishu.cn/', - 'https://login.feishu.cn/'])('allows reviewed login documents: %s', (url) => { +it.each(['https://login.example.com/', 'https://login.example.com/', 'https://login.example.com/', + 'https://login.example.com/'])('allows reviewed login documents: %s', (url) => { const callback = vi.fn() browserSession.webRequest.onBeforeRequest.mock.calls[0]![0]({ resourceType: 'mainFrame', url }, callback) expect(callback).toHaveBeenCalledWith({ cancel: false }) @@ -157,7 +157,7 @@ it('keeps manual login open until close, reports cancellation once, and permits expect(await pending).toBe('cancelled') window = makeWindow(); native.create.mockReturnValue(window) const retry = auth.login() - window.webContents.emit('did-fail-load', {}, -105, 'raw URL error', 'https://accounts.feishu.cn/?state=secret', true) + window.webContents.emit('did-fail-load', {}, -105, 'raw URL error', 'https://login.example.com/?state=secret', true) expect(await retry).toBe('failed') expect(record.mock.calls).toEqual([['opened'], ['cancelled'], ['opened'], ['failed']]) }) diff --git a/apps/desktop/tests/windows-asar-unpack.spec.ts b/apps/desktop/tests/windows-asar-unpack.spec.ts index fc45a38ef9..ddfaf15de2 100644 --- a/apps/desktop/tests/windows-asar-unpack.spec.ts +++ b/apps/desktop/tests/windows-asar-unpack.spec.ts @@ -166,6 +166,7 @@ it.each([true, false])('validates the real builder hook for unsigned=%s', async await writeFile(certificate, 'fixture public certificate') const config = createElectronBuilderConfig({ DSH_DESKTOP_APP_ID: 'com.example.unpack', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', + DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] }), DSH_DESKTOP_TARGET_PLATFORM: 'win32', DSH_DESKTOP_TARGET_ARCH: 'x64', DSH_DESKTOP_UNSIGNED: unsigned ? '1' : '0', DSH_DESKTOP_WINDOWS_CER_FILE: certificate, DOWNLOAD_TEST_ORIGIN: 'https://updates.example.com', }, 'win32', 'x64', input.source) diff --git a/apps/desktop/tests/windows-update-publisher.spec.ts b/apps/desktop/tests/windows-update-publisher.spec.ts index 8967f67b87..2c27e600a1 100644 --- a/apps/desktop/tests/windows-update-publisher.spec.ts +++ b/apps/desktop/tests/windows-update-publisher.spec.ts @@ -51,6 +51,7 @@ describe('Windows update publisher', () => { beforeAll(() => { vi.stubEnv('DSH_DESKTOP_APP_ID', 'com.example.publisher-test') vi.stubEnv('DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN', 'https://policy.example.com') + vi.stubEnv('DSH_DESKTOP_MANDATORY_UPDATE_CONFIG', JSON.stringify({ allowedAuthOrigins: ['https://login.example.com'] })) vi.stubEnv('DSH_DESKTOP_TARGET_PLATFORM', 'win32') vi.stubEnv('DSH_DESKTOP_UNSIGNED', '1') }) From bd6447479dbd4a409f43b141508d564b0b050cb5 Mon Sep 17 00:00:00 2001 From: Yif <877193178@qq.com> Date: Fri, 18 Sep 2026 14:00:50 +0800 Subject: [PATCH 11/45] refine(plugin-manager): polish install dialog guide, input, and wizard states --- .../src/client/PluginManagerPage.module.css | 75 ++++++++++++------- .../src/client/PluginManagerPage.tsx | 30 ++++---- .../ui-plugin-manager/src/client/locales.ts | 12 +-- .../tests/components.client.spec.tsx | 6 +- .../client/ui-primitives/src/icons/index.tsx | 17 +++++ 5 files changed, 86 insertions(+), 54 deletions(-) diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css index 63f55bd302..ba90b04f93 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css @@ -397,7 +397,7 @@ /* Wider than the default dialog: pnpm's lines are long, and the terminal keeps them unwrapped. The card never outgrows the viewport; the running screens scroll inside it so the head's controls stay reachable. */ .installDialog { - width: min(540px, 100%); + width: min(560px, 100%); max-height: calc(100vh - 48px); } @@ -425,16 +425,22 @@ } .installField input[type='text'] { - height: 36px; - padding: 0 12px; + height: 40px; + padding: 0 14px; border: 0.5px solid var(--dsw-alias-border-l4); - border-radius: 10px; + border-radius: 14px; + outline: none; background: var(--dsw-alias-bg-layer-3); font: inherit; font-size: 13px; color: var(--dsw-alias-label-primary); } +.installField input[type='text']:focus { + border-color: var(--dsw-alias-brand-primary); + box-shadow: inset 0 0 0 0.5px var(--dsw-alias-brand-primary); +} + .installField input[aria-invalid='true'] { border-color: var(--dsw-alias-state-error-primary); } @@ -445,6 +451,7 @@ align-items: center; align-self: flex-start; gap: 4px; + margin-top: 4px; padding: 0; border: 0; background: none; @@ -470,13 +477,12 @@ display: flex; flex-direction: column; gap: 10px; - padding: 12px 14px; + padding: 8px 14px 14px; border: 0.5px solid var(--dsw-alias-border-l4); - border-radius: 12px; + border-radius: 14px; background: var(--dsw-alias-bg-layer-1); } -.guideIntro, .guideHint { margin: 0; font-size: 12px; @@ -488,10 +494,10 @@ .guideSafety { display: flex; align-items: flex-start; - gap: 6px; + gap: 8px; margin: 0; - padding: 8px 10px; - border-radius: 8px; + padding: 10px 12px; + border-radius: 10px; background: color-mix(in srgb, var(--dsw-alias-state-warning-primary, var(--dsw-alias-state-business-primary)) 12%, transparent); font-size: 12px; line-height: 18px; @@ -503,19 +509,10 @@ margin-top: 2px; } -.guideNote { - margin: 0; - padding: 8px 10px; - border-radius: 8px; - background: var(--dsw-alias-bg-layer-3); - font-size: 12px; - line-height: 18px; - color: var(--dsw-alias-label-secondary); -} - .guideList { display: flex; flex-direction: column; + gap: 2px; margin: 0; padding: 0; list-style: none; @@ -526,38 +523,43 @@ align-items: flex-start; gap: 10px; padding: 8px 0; - border-top: 0.5px solid var(--dsw-alias-border-l4); + border-radius: 10px; + background: var(--dsw-alias-bg-layer-2); } .guideIndex { + display: inline-flex; flex: none; + align-items: center; + justify-content: center; width: 20px; height: 20px; border-radius: 999px; corner-shape: round; - background: var(--dsw-alias-bg-layer-3); + background: var(--dsw-alias-bg-module-platform); font-size: 11px; - line-height: 20px; - text-align: center; - color: var(--dsw-alias-label-tertiary); + font-weight: 500; + color: var(--dsw-alias-label-secondary); } .guideMain { display: flex; flex: 1; flex-direction: column; - gap: 2px; + gap: 0; min-width: 0; } .guideTitle { - font-size: 12.5px; - font-weight: 600; + font-size: 13px; + font-weight: 500; + line-height: 20px; color: var(--dsw-alias-label-primary); } .guideExample { font-size: 12px; + line-height: 20px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; } @@ -581,7 +583,9 @@ /* The footer's only action spans the dialog, as the primary action of a short form does. */ .wide { width: 100%; + height: 40px; justify-content: center; + border-radius: 14px; } /* The installing, installed, and failed screens: a head row, the centred @@ -593,7 +597,7 @@ gap: 16px; min-width: 0; min-height: 0; - padding: 16px 20px 20px; + padding: 16px 20px 0; } /* Everything under the head: it scrolls when the runs' output makes the screen taller than the card. */ @@ -664,6 +668,14 @@ color: var(--dsw-alias-label-secondary); } +.wizardIcon[data-state='done'] { + color: var(--dsw-alias-state-success-secondary); +} + +.wizardIcon[data-state='error'] { + color: var(--dsw-alias-state-warn-label); +} + .wizardTitle { margin: 0; font-size: 18px; @@ -714,6 +726,11 @@ gap: 12px; } +.footAction { + height: 32px; + border-radius: 16px; +} + .detailsToggle { display: inline-flex; align-items: center; diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx index f27252c775..2e1fee9ea9 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx @@ -12,8 +12,8 @@ import { useEffect, useId, useState, type ReactNode } from 'react' import type { PluginInstallFailureKind } from '@deepseek-ai/dsh-api-remotes/client' import { - Button, IconChevronDownOutlineRegular, IconChevronLeftOutlineRegular, - IconChevronRightOutlineRegular, IconCloseOutlineRegular, + Button, IconCheckCircleFillRegular, IconChevronDownOutlineRegular, IconChevronLeftOutlineMedium, + IconChevronRightOutlineRegular, IconCloseOutlineMedium, IconPlusOutlineRegular, IconRefreshOutlineRegular, IconTrashOutlineRegular, IconWarningOutlineRegular, Input, Modal, PluginArtworkDefault, PluginArtworkLoop, PluginArtworkSearch, PluginArtworkSubagent, PluginArtworkTeam, PluginArtworkTerminal, @@ -672,19 +672,19 @@ function InstallDialog({ )} >
    -