From 2c9eda5b6f752a48396ce22387f569d0712e3183 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 8 Sep 2026 12:05:06 +0800 Subject: [PATCH 01/52] feat(client): add plan, compact, and shield glyphs for the composer menu --- .../client/ui-primitives/src/icons/index.tsx | 38 +++++++++++++++++++ .../ui-primitives/tests/icons.client.spec.tsx | 4 +- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index 4afc31089f..47682cfab3 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -934,3 +934,41 @@ export const IconArchiveOutline20 = ({ size = 20, className }: IconProps) => ( ) + +/** plan_outline_14 (design doc for #3567: the composer menu's Plan row glyph; drawn on a 14 grid) */ +export const IconPlanOutline14 = ({ size = 14, className }: IconProps) => ( + + + + + + + + +) + +/** compact_outline_16 (the composer's context-usage ring as a static glyph: a quiet track with one filled arc) */ +export const IconCompactOutline16 = ({ size = 16, className }: IconProps) => ( + + + + +) + +/** shield_outline_16 (design set 1556: the permission shield contour without a mode mark) */ +export const IconShieldOutline16 = ({ size = 16, className }: IconProps) => ( + + + +) diff --git a/packages/client/ui-primitives/tests/icons.client.spec.tsx b/packages/client/ui-primitives/tests/icons.client.spec.tsx index 1b9a9c7773..4cae7397ed 100644 --- a/packages/client/ui-primitives/tests/icons.client.spec.tsx +++ b/packages/client/ui-primitives/tests/icons.client.spec.tsx @@ -17,8 +17,8 @@ const icons = Object.fromEntries( const iconNames = Object.keys(icons) describe('ic_ds_ icon set', () => { - it('exports the full icon set (46 deepsuite + 21 figma extracts + eight product glyphs outside those sets)', () => { - expect(iconNames.length).toBe(75) + it('exports the full icon set (46 deepsuite + 21 figma extracts + eleven product glyphs outside those sets)', () => { + expect(iconNames.length).toBe(78) }) it.each(iconNames)('%s renders an svg with currentColor fills and no hardcoded palette', (name) => { From 5b1bb021cf9984dd75bfedb0ccb1ff9a913e3214 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 8 Sep 2026 12:28:40 +0800 Subject: [PATCH 02/52] feat(web): group, localize, and re-present the composer command menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The + button and a typed / open one menu with an Add section (File, Goal, Plan, Feedback) and a Commands section (Compact, Permission, Model, Export) in usage order; rows carry a glyph, a localized title and description, and the command name as an alias where the localized title differs. Built-in Host rows get their face from the ui-commands dictionaries when the catalog description is the canonical English text. A menu pick fills the locale's claim token (/计划 ) while the submission executes the catalog name, and a typed localized token resolves on Space and Enter in every locale. The File row is a new action contribution kind that opens the composer's file picker through the scoped slash/input-pick-files event; the paperclip button is removed and the + button reads "Add files or run commands". --- ...menu-sections-and-localized-rows.i18n.yaml | 6 + ...mposer-menu-sections-and-localized-rows.md | 37 +++++ ...ser-menu-sections-and-localized-rows.zh.md | 37 +++++ .../clickable-links-gallery/ui.expected.md | 4 +- .../conversation-expanded.expected.md | 4 +- .../conversation.expected.md | 4 +- .../goal-command-presentation/ui.expected.md | 4 +- .../markdown-cjk-strong/ui.expected.md | 4 +- .../expected/markdown-images/ui.expected.md | 4 +- .../markdown-inline-code-links/ui.expected.md | 4 +- .../expected/math-rendering/ui.expected.md | 4 +- .../reference-composer/order.expected.md | 4 +- .../skill-user-invoke/ui-expanded.expected.md | 4 +- .../expected/skill-user-invoke/ui.expected.md | 4 +- .../stats-paged-history/ui.expected.md | 4 +- .../expected/steer-all/mid-steer.expected.md | 4 +- .../steer-all/settled-expanded.expected.md | 4 +- .../expected/steer-all/settled.expected.md | 4 +- .../tests/goal-command-presentation.e2e.ts | 2 +- apps/web/tests/lifecycle-chrome.e2e.ts | 9 +- apps/web/tests/shipped-composition.e2e.ts | 2 +- .../mid-stream.expected.md | 4 +- .../client/connection/src/client/fixture.ts | 2 +- packages/client/ui-commands/README.i18n.yaml | 4 +- packages/client/ui-commands/README.md | 10 +- packages/client/ui-commands/README.zh.md | 10 +- .../client/ui-commands/src/client/contract.ts | 37 ++++- .../client/ui-commands/src/client/index.ts | 32 +++- .../client/ui-commands/src/client/locales.ts | 55 ++++++- .../ui-commands/src/client/presentation.ts | 132 +++++++++++++++++ .../client/ui-commands/src/client/service.ts | 111 +++++++++----- .../tests/browser-plugin.client.spec.ts | 24 ++- .../ui-commands/tests/service.client.spec.ts | 139 +++++++++++++++++- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 2 +- .../src/client/contract/input.ts | 13 ++ .../src/client/input/facade.ts | 24 +++ .../ui-conversation/src/client/input/hub.ts | 1 + .../ui-conversation/src/client/locales.ts | 6 +- .../src/client/skeleton/InputBar.tsx | 27 ++-- .../tests/input-bar.client.spec.tsx | 28 ++-- .../tests/input-matrix.client.spec.tsx | 2 +- .../client/ui-input-trigger/README.i18n.yaml | 4 +- packages/client/ui-input-trigger/README.md | 3 +- packages/client/ui-input-trigger/README.zh.md | 3 +- .../src/client/MenuView.module.css | 14 ++ .../ui-input-trigger/src/client/MenuView.tsx | 15 +- packages/client/ui-input-trigger/src/types.ts | 15 +- .../tests/menu-view.client.spec.tsx | 20 +++ .../ui-model-selection/src/client/index.ts | 9 +- .../ui-model-selection/src/client/locales.ts | 2 + .../tests/browser-plugin.client.spec.ts | 21 ++- .../tests/browser-plugin.client.spec.ts | 26 ++-- .../client/ui-primitives/src/rank-by-name.ts | 30 +++- .../tests/rank-by-name.client.spec.ts | 14 ++ .../feedback/command-feedback/src/index.ts | 2 +- .../tests/command-feedback.spec.ts | 2 +- packages/goal/command-goal/src/index.ts | 2 +- .../command-goal/tests/command-goal.spec.ts | 2 +- snapshots/web/bash-abort-row/ui.expected.md | 4 +- .../web/cordis-tool-round/ui.expected.md | 4 +- .../feedback-command/ack-expanded.expected.md | 4 +- .../web/feedback-command/ack.expected.md | 4 +- .../feedback-release/ack-expanded.expected.md | 4 +- .../web/feedback-release/ack.expected.md | 4 +- .../web/file-upload-round/ui.expected.md | 4 +- .../fresh-round-trip/ui-expanded.expected.md | 4 +- snapshots/web/fresh-round-trip/ui.expected.md | 4 +- .../ui-expanded.expected.md | 4 +- .../goal-multi-turn-actions/ui.expected.md | 4 +- .../command-menu-fuzzy.expected.md | 2 +- .../lifecycle-chrome/command-menu.expected.md | 16 +- .../web/lifecycle-chrome/hero.expected.md | 4 +- .../lifecycle-chrome/plan-active.expected.md | 4 +- .../reloaded-expanded.expected.md | 4 +- .../web/lifecycle-chrome/reloaded.expected.md | 4 +- .../cancel-expanded.expected.md | 4 +- .../web/live-interactions/cancel.expected.md | 4 +- .../live-interactions/error-auth.expected.md | 4 +- .../web/live-interactions/loading.expected.md | 4 +- .../retry-exhausted.expected.md | 4 +- .../retry-expanded.expected.md | 4 +- .../web/live-interactions/retry.expected.md | 4 +- .../running-draft.expected.md | 4 +- snapshots/web/message-actions/ui.expected.md | 4 +- snapshots/web/minimal-preset/ui.expected.md | 4 +- .../plan-review/approved-expanded.expected.md | 4 +- .../web/plan-review/approved.expected.md | 4 +- snapshots/web/ptc-round/ui.expected.md | 4 +- .../answered-expanded.expected.md | 4 +- .../question-composer/answered.expected.md | 4 +- .../question-composer/cancelled.expected.md | 4 +- .../web/queue-actions/collapsed.expected.md | 4 +- .../web/queue-actions/editing.expected.md | 4 +- .../web/queue-actions/failed.expected.md | 4 +- .../web/queue-actions/layout.expected.md | 4 +- .../preserved-expanded.expected.md | 4 +- .../web/queue-actions/preserved.expected.md | 4 +- .../web/queue-actions/sending.expected.md | 4 +- snapshots/web/queue-actions/ui.expected.md | 4 +- .../web/queued-image/delivered.expected.md | 4 +- snapshots/web/queued-image/queued.expected.md | 4 +- .../seeded-history/command-row.expected.md | 4 +- .../seeded-history/feedback-row.expected.md | 4 +- .../seeded-history/ui-expanded.expected.md | 4 +- snapshots/web/seeded-history/ui.expected.md | 4 +- snapshots/web/skill-tool-row/ui.expected.md | 4 +- .../web/steering/settled-expanded.expected.md | 4 +- snapshots/web/steering/settled.expected.md | 4 +- .../ui-expanded.expected.md | 4 +- .../web/subagent-conversation/ui.expected.md | 4 +- .../offline-composer.expected.md | 4 +- .../turn-tail-actions/completed.expected.md | 4 +- .../web/turn-tail-actions/focused.expected.md | 4 +- .../web/turn-tail-actions/running.expected.md | 4 +- .../web/turn-tail-actions/settled.expected.md | 4 +- .../usage-expanded.expected.md | 4 +- snapshots/web/web-search-round/ui.expected.md | 4 +- 119 files changed, 872 insertions(+), 380 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.md create mode 100644 .agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.zh.md create mode 100644 packages/client/ui-commands/src/client/presentation.ts diff --git a/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.i18n.yaml b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.i18n.yaml new file mode 100644 index 0000000000..fd023c5ddc --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.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-08-composer-menu-sections-and-localized-rows.md +2026-09-08-composer-menu-sections-and-localized-rows.md: c8fc2226a15828de14f623fc582473e72e3ec1f1 +2026-09-08-composer-menu-sections-and-localized-rows.zh.md: 5905c872ab583294aabf15a1b69f2dfe1312e4ba diff --git a/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.md b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.md new file mode 100644 index 0000000000..c8fc2226a1 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.md @@ -0,0 +1,37 @@ +# Agent Note: Composer menu sections, localized rows, and the File row + +Status: implemented + +English | [中文](2026-09-08-composer-menu-sections-and-localized-rows.zh.md) + +## Problem + +The composer's `+` button and a typed `/` listed every command in Host registration order as `name description`, all lowercase, with no glyphs and no grouping, beside a separate paperclip button for files. Under Chinese the rows stayed English because Host descriptors carry English text only, and a user who knew a command by its Chinese title could neither find it by that title nor see what to type. Issue #3567 and the design doc for it ask for two sections in usage order, a glyph and a left-aligned title per row with the description right-aligned, capitalized English titles, Chinese titles and descriptions that stay searchable in both languages and show the English command name, a Chinese fill for the Plan and Goal claims, and a File entry inside the menu. + +## Decision + +`ui-commands` owns the menu's presentation in `src/client/presentation.ts`: an Add section (`file`, `goal`, `plan`, `feedback`) and a Commands section (`compact`, `permission`, `model`, `export`), each in usage order, with rows outside both lists closing Commands in catalog order. The section lists are keyed by name; an empty query returns the sectioned rows, and a typed query returns the flat ranking of every visible row so the best match is always first. + +The six built-in Host commands get a client face from the `command` dictionaries — title, description, glyph, and claim token — when the catalog description equals the canonical English text; a scoped override or third-party command of the same name keeps its own description and only its section position follows the name. The English dictionary is byte-equal to the Host descriptors, and the `feedback` and `goal` descriptors are capitalized to match the other four. Contributions carry `label()`, `description()`, and `icon`, read on every candidate pass, so the `/model` row localizes without re-registration. + +A menu pick fills the locale's claim token: under Chinese, picking Plan fills `/计划 ` and the submission executes `/plan `. A typed token keeps its typed spelling as the claim, because the composer reads the arguments after the token it holds. `resolveCommandName` maps every localized token of every dictionary back to its command name, so `/计划` typed under any locale reaches the `plan` descriptor on Space and Enter, and a bare `/压缩` executes as `/compact`. + +The File row is an `action` contribution, a new `CommandUiSpec` kind whose bare invocation consumes the trigger token and runs a client callback without submitting anything; it therefore never refuses an attachment-carrying draft. The row raises the scoped `slash/input-pick-files` event, which `ui-conversation` routes to the composer's hidden file input through `ComposerKeyboard.bindFilePicker` under the same gate as drop intake; the paperclip button is removed. The `+` button's accessible name and tooltip read "Add files or run commands". + +`ui-input-trigger` renders the new row anatomy: `InputTriggerCandidate.label` is the title and a second search key of the shared `rankByName`, the name renders as a trailing alias when the label differs from it, `icon` accepts an icon component beside the reference glyph tokens, and the description is right-aligned. `ui-primitives` gains the Plan glyph from the design doc, a static ring for Compact, and the permission shield contour. + +## Alternatives considered + +**Localize descriptions on the Host.** The Host has no locale and its catalog is shared by every client; the client already owns product copy for every other surface (the locale-owned client UI copy decision), and the equality guard keeps a scoped or third-party descriptor verbatim. + +**Keep sections under a typed query.** Ranking inside sections put a prefix hit in Commands below weaker matches in Add (typing `e` listed Feedback and File above Export); a flat ranking keeps the best match first, and the headings only carry information while the list is complete. + +**Keep the paperclip beside the menu.** The design doc and the issue's acceptance criteria integrate the entry into the menu and forbid the old icon from showing twice; the hidden file input and the drop gate stay where they were. + +**A contribution-owned copy for the built-in Host rows.** Host packages have no client half to register from, so the copy has to live on the client; one table keyed by name in the package that already owns the `/` source keeps the design decision in one place. + +**A `token` alias only under the active locale.** Resolving through every dictionary costs nothing and lets a draft persisted under one locale submit under another. + +## Consequences + +The menu, the Host catalog, and the localized face are three separate facts joined by name and by the canonical English description; adding a built-in Host command means adding its `label.*`, `description.*`, and `token.*` keys, its glyph in `presentation.ts`, and its section position. The web e2e goldens and every expected ARIA snapshot that showed the paperclip or the `Commands` button changed in the same PR. A third-party command named like a built-in one is positioned by name but keeps its own description and gets no glyph, which is the intended reading of "the same name, another command". diff --git a/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.zh.md b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.zh.md new file mode 100644 index 0000000000..5905c872ab --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.zh.md @@ -0,0 +1,37 @@ +# Agent Note: Composer 菜单分节、本地化行与「文件」行 + +Status: implemented + +[English](2026-09-08-composer-menu-sections-and-localized-rows.md) | 中文 + +## 问题 + +composer 的 `+` 按钮与键入的 `/` 按宿主注册顺序把每个命令列成 `name description`,全部小写,没有图标也不分组,旁边还有一个单独的回形针按钮用于添加文件。中文界面下各行仍是英文,因为宿主描述符只携带英文文案;只知道命令中文名的用户既搜不到它,也看不出该输入什么。Issue #3567 及其设计稿要求:按使用频次分成两个小节,每行带图标、标题左对齐、说明右对齐,英文标题首字母大写,中文标题与说明在两种语言下都能搜索并同时显示英文命令名,计划与目标的声明用中文填入,以及把「文件」入口放进菜单。 + +## 决策 + +`ui-commands` 在 `src/client/presentation.ts` 里拥有菜单的展示:「添加」小节(`file`、`goal`、`plan`、`feedback`)与「指令」小节(`compact`、`permission`、`model`、`export`),各按使用频次排列,不在两个清单里的行按目录顺序排在「指令」末尾。小节清单按名字索引;空查询返回分节的行,输入查询后返回所有可见行的平铺排序,最佳匹配始终在第一位。 + +六个内置宿主命令在目录说明与规范英文文案相同时,从 `command` 词典取得客户端展示面:标题、说明、图标与声明 token;同名的作用域覆盖或第三方命令保留自己的说明,只有小节位置跟随名字。英文词典与宿主描述符逐字节相同,`feedback` 与 `goal` 的描述符改为首字母大写,与另外四个一致。贡献项携带 `label()`、`description()` 与 `icon`,每次生成候选项时读取,因此 `/model` 行无需重新注册即可本地化。 + +菜单选中填入当前语言的声明 token:中文下选中「计划」填入 `/计划 `,提交时执行 `/plan `。手输的 token 保留手输的写法作为声明,因为 composer 从它持有的 token 之后读取参数。`resolveCommandName` 把每本词典里的每个本地化 token 映射回命令名,因此在任何语言下键入的 `/计划` 在空格与回车裁决中都到达 `plan` 描述符,裸 `/压缩` 执行为 `/compact`。 + +「文件」行是一个 `action` 贡献项,这是 `CommandUiSpec` 新增的种类:裸调用消费掉触发 token 后运行一个客户端回调,不提交任何内容,因此绝不会拒绝带附件的草稿。该行触发会话作用域的 `slash/input-pick-files` 事件,`ui-conversation` 经 `ComposerKeyboard.bindFilePicker` 把它路由到 composer 隐藏的文件输入框,门槛与拖放入口相同;回形针按钮移除。`+` 按钮的无障碍名称与提示改为「添加文件或调用指令」。 + +`ui-input-trigger` 渲染新的行结构:`InputTriggerCandidate.label` 是标题,也是共享 `rankByName` 的第二个搜索键;label 与名字不同时名字渲染为尾随别名;`icon` 在引用图标 token 之外接受图标组件;说明右对齐。`ui-primitives` 新增设计稿给出的计划图标、压缩用的静态环形,以及权限盾形轮廓。 + +## 考虑过的替代方案 + +**在宿主侧本地化说明。** 宿主没有语言设置,目录又被所有客户端共享;客户端已经拥有其他所有界面的产品文案(客户端界面文案归语言所有的决策),相等性判断还能让作用域覆盖或第三方描述符原样保留。 + +**输入查询后保留小节。** 在小节内排序会把「指令」里的前缀命中排在「添加」里较弱的匹配之下(输入 `e` 时反馈与文件排在导出之上);平铺排序让最佳匹配始终靠前,小节标题只在列表完整时才有信息量。 + +**在菜单旁保留回形针。** 设计稿与 issue 的验收条件都要求把入口整合进菜单且旧图标不再重复显示;隐藏的文件输入框与拖放门槛保持原位。 + +**由贡献项拥有内置宿主行的文案。** 宿主包没有客户端一半可供注册,文案只能放在客户端;在已经拥有 `/` source 的包里用一张按名字索引的表,能把设计决策集中在一处。 + +**只在当前语言下解析 `token` 别名。** 遍历所有词典解析没有成本,还能让在一种语言下持久化的草稿在另一种语言下提交。 + +## 后果 + +菜单、宿主目录与本地化展示面是三份独立事实,靠名字与规范英文说明连接;新增一个内置宿主命令意味着补上它的 `label.*`、`description.*`、`token.*` 键、`presentation.ts` 里的图标与小节位置。Web e2e 基准与所有曾显示回形针或 `Commands` 按钮的 ARIA 快照在同一 PR 内更新。与内置命令同名的第三方命令按名字定位,但保留自己的说明且没有图标,这正是「同名的另一个命令」应有的解读。 diff --git a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md index 1bc1752380..b2ce4917b6 100644 --- a/apps/web/tests/expected/clickable-links-gallery/ui.expected.md +++ b/apps/web/tests/expected/clickable-links-gallery/ui.expected.md @@ -193,9 +193,7 @@ - button "Back to bottom": - img - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md b/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md index 92887b13f2..e831e97200 100644 --- a/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md +++ b/apps/web/tests/expected/github-ready-review/conversation-expanded.expected.md @@ -51,9 +51,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Read Only"': Read Only - button "Select model, current github-webhook-review-test/reply": diff --git a/apps/web/tests/expected/github-ready-review/conversation.expected.md b/apps/web/tests/expected/github-ready-review/conversation.expected.md index aa35d67e04..2f42c100cf 100644 --- a/apps/web/tests/expected/github-ready-review/conversation.expected.md +++ b/apps/web/tests/expected/github-ready-review/conversation.expected.md @@ -43,9 +43,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Read Only"': Read Only - button "Select model, current github-webhook-review-test/reply": diff --git a/apps/web/tests/expected/goal-command-presentation/ui.expected.md b/apps/web/tests/expected/goal-command-presentation/ui.expected.md index d5fddccca9..928d0baf06 100644 --- a/apps/web/tests/expected/goal-command-presentation/ui.expected.md +++ b/apps/web/tests/expected/goal-command-presentation/ui.expected.md @@ -17,9 +17,7 @@ - img - text: "goal No goal is currently set. Usage: /goal [|clear|edit |pause|resume]" - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md b/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md index 8cccd6e2a7..a6c5d051b3 100644 --- a/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md +++ b/apps/web/tests/expected/markdown-cjk-strong/ui.expected.md @@ -51,9 +51,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/markdown-images/ui.expected.md b/apps/web/tests/expected/markdown-images/ui.expected.md index 3e00a67cb0..f8cdccfdc6 100644 --- a/apps/web/tests/expected/markdown-images/ui.expected.md +++ b/apps/web/tests/expected/markdown-images/ui.expected.md @@ -30,9 +30,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md b/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md index e042455176..9c6287906f 100644 --- a/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md +++ b/apps/web/tests/expected/markdown-inline-code-links/ui.expected.md @@ -42,9 +42,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/math-rendering/ui.expected.md b/apps/web/tests/expected/math-rendering/ui.expected.md index 20e51e6c63..2bfd849bec 100644 --- a/apps/web/tests/expected/math-rendering/ui.expected.md +++ b/apps/web/tests/expected/math-rendering/ui.expected.md @@ -46,9 +46,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/reference-composer/order.expected.md b/apps/web/tests/expected/reference-composer/order.expected.md index 7ea2707435..f8b952b2c5 100644 --- a/apps/web/tests/expected/reference-composer/order.expected.md +++ b/apps/web/tests/expected/reference-composer/order.expected.md @@ -16,9 +16,7 @@ - img - text: Session recall Research notes - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md b/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md index f14b04d9a9..1472e0b212 100644 --- a/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md +++ b/apps/web/tests/expected/skill-user-invoke/ui-expanded.expected.md @@ -43,9 +43,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/skill-user-invoke/ui.expected.md b/apps/web/tests/expected/skill-user-invoke/ui.expected.md index e0901950d2..119d08381d 100644 --- a/apps/web/tests/expected/skill-user-invoke/ui.expected.md +++ b/apps/web/tests/expected/skill-user-invoke/ui.expected.md @@ -35,9 +35,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/stats-paged-history/ui.expected.md b/apps/web/tests/expected/stats-paged-history/ui.expected.md index 6a3f9ecbb6..a4d19d808d 100644 --- a/apps/web/tests/expected/stats-paged-history/ui.expected.md +++ b/apps/web/tests/expected/stats-paged-history/ui.expected.md @@ -462,9 +462,7 @@ - button "Back to bottom": - img - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/steer-all/mid-steer.expected.md b/apps/web/tests/expected/steer-all/mid-steer.expected.md index 11e83471a3..32b464ba62 100644 --- a/apps/web/tests/expected/steer-all/mid-steer.expected.md +++ b/apps/web/tests/expected/steer-all/mid-steer.expected.md @@ -34,9 +34,7 @@ - button "Copy": - img - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/steer-all/settled-expanded.expected.md b/apps/web/tests/expected/steer-all/settled-expanded.expected.md index b1644d07d5..f15b14ab09 100644 --- a/apps/web/tests/expected/steer-all/settled-expanded.expected.md +++ b/apps/web/tests/expected/steer-all/settled-expanded.expected.md @@ -53,9 +53,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/expected/steer-all/settled.expected.md b/apps/web/tests/expected/steer-all/settled.expected.md index acbaf1b148..4503a0585b 100644 --- a/apps/web/tests/expected/steer-all/settled.expected.md +++ b/apps/web/tests/expected/steer-all/settled.expected.md @@ -41,9 +41,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/apps/web/tests/goal-command-presentation.e2e.ts b/apps/web/tests/goal-command-presentation.e2e.ts index 70ad37a799..734aa20b03 100644 --- a/apps/web/tests/goal-command-presentation.e2e.ts +++ b/apps/web/tests/goal-command-presentation.e2e.ts @@ -51,7 +51,7 @@ describe('web e2e: /goal human transcript presentation', () => { const input = page.locator('[data-composer-input]').first() await input.fill('/go') const menu = page.getByRole('listbox', { name: 'Trigger suggestions' }) - await menu.getByRole('option', { name: 'goal set or view the goal for a long-running task' }) + await menu.getByRole('option', { name: 'Goal Set or view the goal for a long-running task' }) .waitFor({ timeout: 10_000 }) await input.press('Tab') await expect.poll(() => input.textContent()).toBe('/goal ') diff --git a/apps/web/tests/lifecycle-chrome.e2e.ts b/apps/web/tests/lifecycle-chrome.e2e.ts index 282aa0b1a9..86ba7af21b 100644 --- a/apps/web/tests/lifecycle-chrome.e2e.ts +++ b/apps/web/tests/lifecycle-chrome.e2e.ts @@ -71,12 +71,13 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () it.skipIf(MODE === 'record')('opens the shared slash menu from plus with only Command candidates', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-command-menu-launcher')) - const launcher = page.getByRole('button', { name: 'Commands' }) + const launcher = page.getByRole('button', { name: 'Add files or run commands' }) await launcher.click() const menu = page.getByRole('listbox', { name: 'Trigger suggestions' }) await menu.waitFor({ timeout: 10_000 }) const snapshot = await captureStableAria(page, '[role="listbox"]', scaffold.workspaceCwd) await compareOrRefreshGolden(COMMAND_MENU_EXPECTED, snapshot, MODE) + expect(snapshot).toContain('text: Add') expect(snapshot).toContain('text: Commands') expect(snapshot).not.toContain('text: Skills') expect(snapshot).not.toContain('text: Subagents') @@ -95,7 +96,7 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () )).toBeLessThan(1) await writeComposerDraft(page, input, '/cpt') await expect.poll(() => menu.getByRole('option').allTextContents()).toEqual([ - 'compactCompact older conversation history', + 'CompactCompact older conversation history', ]) const fuzzySnapshot = await captureStableAria(page, '[role="listbox"]', scaffold.workspaceCwd) await compareOrRefreshGolden(FUZZY_COMMAND_MENU_EXPECTED, fuzzySnapshot, MODE) @@ -112,10 +113,10 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () await activePage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(activePage, activeScaffold.workspaceCwd) const input = activePage.locator('[data-composer-input]').first() - await activePage.getByRole('button', { name: 'Commands' }).click() + await activePage.getByRole('button', { name: 'Add files or run commands' }).click() const menu = activePage.getByRole('listbox', { name: 'Trigger suggestions' }) await menu.waitFor({ timeout: 10_000 }) - await menu.getByRole('option', { name: 'plan Enter or leave plan mode' }).click() + await menu.getByRole('option', { name: 'Plan Enter or leave plan mode' }).click() await expect.poll(() => input.textContent()).toBe('/plan ') await input.press('Enter') const planButton = activePage.getByRole('button', { name: 'Plan mode on, press to turn off' }) diff --git a/apps/web/tests/shipped-composition.e2e.ts b/apps/web/tests/shipped-composition.e2e.ts index 61acc027fd..da22e6c2ca 100644 --- a/apps/web/tests/shipped-composition.e2e.ts +++ b/apps/web/tests/shipped-composition.e2e.ts @@ -183,7 +183,7 @@ it('assembles the shipped Web transport, catalog, guidance, and defaults', async try { expect(scaffold.ctx.commands.list(commandHandle.agent)).toContainEqual({ name: 'feedback', - description: 'record feedback about this session', + description: 'Record feedback about this session', input: { hint: '' }, }) } finally { diff --git a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md index 1ca602fbd7..4e8286c760 100644 --- a/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md +++ b/apps/web/tests/snapshots/streaming-fence-highlight/mid-stream.expected.md @@ -27,9 +27,7 @@ - code: "const first: number = 1 const second = \"two\" let tail" - status: Deep diving... - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current streaming-fence-highlight-test/streaming-fence": diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index e9440fee7f..17f0b95e05 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -2220,7 +2220,7 @@ function createFixtureWorld(options: FixtureOptions): FixtureWorld { value: [ { name: 'compact', description: 'fixture:压缩当前会话上下文' }, { name: 'echo', description: 'fixture:回显参数', input: { hint: 'text to echo' } }, - { name: 'goal', description: 'set or view the goal for a long-running task', input: { hint: '', attachments: true } }, + { name: 'goal', description: 'Set or view the goal for a long-running task', input: { hint: '', attachments: true } }, { name: 'permission', description: 'Switch the permission preset (sandbox mode + approval policy)', input: { hint: '' } }, { name: 'plan', description: 'Enter or leave plan mode', input: { hint: '[off|message]', attachments: true } }, ], diff --git a/packages/client/ui-commands/README.i18n.yaml b/packages/client/ui-commands/README.i18n.yaml index dc82321424..c5f908d731 100644 --- a/packages/client/ui-commands/README.i18n.yaml +++ b/packages/client/ui-commands/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-commands/README.md -README.md: e1264d10bd8ff807d8f348339e0c055607579407 -README.zh.md: c5323149aea1e38ff09262db9bd2aacad7b284ea +README.md: 31fd9925c08393735c56de891bafe985cc00b683 +README.zh.md: 76e4955014365f1c9890c98600c7cf1c347afbb0 diff --git a/packages/client/ui-commands/README.md b/packages/client/ui-commands/README.md index e1264d10bd..31fd9925c0 100644 --- a/packages/client/ui-commands/README.md +++ b/packages/client/ui-commands/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Typing a `/` command in the composer opens the matching surface — a registered popup, a host command's input, or a direct execution — and a command line is never silently downgraded to a plain prompt. Business packages contribute command surfaces through `ctx.commandUi`, registering a popupSelect spec (`/model`, `/permission`) or decorating an existing host command with a picker while the host keeps its catalog row and argument claim. Space and Enter resolve the line against the session's directory: a host descriptor with `input` is `leadingInput`, a registered `CommandUiSpec` is `popupSelect`, and everything else is `execute`. +Typing a `/` command in the composer opens the matching surface — a registered popup, a client action, a host command's input, or a direct execution — and a command line is never silently downgraded to a plain prompt. Business packages contribute command surfaces through `ctx.commandUi`, registering a popupSelect spec (`/model`, `/permission`) or an action, or decorating an existing host command with a picker while the host keeps its catalog row and argument claim. Space and Enter resolve the line against the session's directory: a host descriptor with `input` is `leadingInput`, a registered `CommandUiSpec` is `popupSelect` or `action`, and everything else is `execute`. The composer's `+` button and a typed `/` open the same menu: an Add section (File, Goal, Plan, Feedback) and a Commands section (Compact, Permission, Model, Export) in usage order, each row with a glyph, a localized title and description, and the command name as an alias where the localized title differs from it. ## Table of Contents @@ -29,7 +29,11 @@ Mount this plugin alongside `ui-input-trigger` and `ui-conversation`; the `/` so ### Kinds and decorations -A contribution is a client-owned command — a host-name collision fails loud. A decoration adds a bare-invocation popup to an EXISTING host command: the host command keeps its catalog row, its argument claim, and its lifecycle logging, and a decorated name with no host row in the session's directory never fires. Menu queries fuzzy-match ordered, case-insensitive subsequences of command names; prefixes rank first. +A contribution is a client-owned command — a host-name collision fails loud. Its UI is a popupSelect spec or an action: a callback a bare invocation runs after the trigger token is consumed, which submits nothing and therefore never refuses an attachment-carrying draft. The menu's File row is this package's own action; it opens the composer's file picker through the scoped `slash/input-pick-files` event wherever the composer accepts files, never on a subagent. A decoration adds a bare-invocation popup or action to an EXISTING host command: the host command keeps its catalog row, its argument claim, and its lifecycle logging, and a decorated name with no host row in the session's directory never fires. Menu queries fuzzy-match ordered, case-insensitive subsequences of command names and titles; prefixes rank first, and a typed query lists the matches flat without the section headings. + +### Built-in row faces + +Host descriptors carry English text only, so `src/client/presentation.ts` owns the client face of the six built-in Host commands: a catalog row whose description equals the canonical English text gets its localized title, description, glyph, and claim token from the `command` dictionaries, while a scoped override or third-party command of the same name keeps its own description and only its section position follows the name; rows outside both section lists close the Commands section in catalog order. Under Chinese, picking Plan fills the composer with `/计划 ` and the submission still executes `/plan `; a typed `/计划` or `/目标` resolves the same way on Space and Enter in every locale, so a draft written under one locale submits under another. Contributions supply their own `label`, `description`, and `icon`, read on every candidate pass, so a locale change reaches the next menu open without re-registration. ### Attachment-carrying submissions @@ -43,7 +47,7 @@ When the composer submits with images or generic files, only a host command decl
Implementation internals — click to expand -`src/client/contract.ts` is the fixed business contract: `CommandUiContract.register(name, spec)` and `decorate(name, spec)` are everything a business package consumes. `CommandDirectory` is the one wire-derived cache, keyed by session: ordinary sessions fetch through `command.list({sessionId})`, entries are soft-invalidated by the forwarded `commands/change` owner event and hard-invalidated by `connection/reset`, and epoch-guarded so a superseded pull can never overwrite a newer one. `matchSpace` answers synchronously from this cache only; `matchEnter` strong-waits it on the SubmitAttempt signal and rejects on warmup failure. After `command.execute` returns a matched result, the browser emits a local `command/executed` acknowledgment; other clients receive the durable command nodes through the Host event stream but never this acknowledgment. `PopupSelectController` is the headless shell state; `PopupSelectView` self-registers into `conversation.input.overlay` with per-session resolution. +`src/client/contract.ts` is the fixed business contract: `CommandUiContract.register(name, spec)` and `decorate(name, spec)` are everything a business package consumes. `CommandDirectory` is the one wire-derived cache, keyed by session: ordinary sessions fetch through `command.list({sessionId})`, entries are soft-invalidated by the forwarded `commands/change` owner event and hard-invalidated by `connection/reset`, and epoch-guarded so a superseded pull can never overwrite a newer one. `matchSpace` answers synchronously from this cache only; `matchEnter` strong-waits it on the SubmitAttempt signal and rejects on warmup failure. After `command.execute` returns a matched result, the browser emits a local `command/executed` acknowledgment; other clients receive the durable command nodes through the Host event stream but never this acknowledgment. `PopupSelectController` is the headless shell state; `PopupSelectView` self-registers into `conversation.input.overlay` with per-session resolution. `presentation.ts` holds the section lists, the built-in row faces, and the localized-token resolution; `candidates` sections an empty query and ranks a typed one through the shared `rankByName`.
diff --git a/packages/client/ui-commands/README.zh.md b/packages/client/ui-commands/README.zh.md index c5323149ae..76e4955014 100644 --- a/packages/client/ui-commands/README.zh.md +++ b/packages/client/ui-commands/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -在 composer 中键入 `/` 命令会打开匹配的表面——已注册的弹窗、宿主命令的输入或直接执行——命令行绝不会被静默降级为普通提示词。业务包经 `ctx.commandUi` 贡献命令表面:注册 popupSelect 贡献项(`/model`、`/permission`),或用选择器装饰既有宿主命令,宿主保留其目录行与参数声明。空格与回车对照会话目录解析命令行:带 `input` 的宿主描述符是 `leadingInput`,注册了 `CommandUiSpec` 的是 `popupSelect`,其余全部是 `execute`。 +在 composer 中键入 `/` 命令会打开匹配的表面——已注册的弹窗、客户端动作、宿主命令的输入或直接执行——命令行绝不会被静默降级为普通提示词。业务包经 `ctx.commandUi` 贡献命令表面:注册 popupSelect 贡献项(`/model`、`/permission`)或动作,或用选择器装饰既有宿主命令,宿主保留其目录行与参数声明。空格与回车对照会话目录解析命令行:带 `input` 的宿主描述符是 `leadingInput`,注册了 `CommandUiSpec` 的是 `popupSelect` 或 `action`,其余全部是 `execute`。composer 的 `+` 按钮与键入的 `/` 打开同一个菜单:「添加」小节(文件、目标、计划、反馈)与「指令」小节(压缩、权限、模型、下载日志)按使用频次排列,每行带图标、本地化的标题与说明,本地化标题与命令名不同时还显示命令名作为别名。 ## 目录 @@ -29,7 +29,11 @@ kind: "package-reference" ### 种类与装饰 -贡献项是客户端自有命令——与宿主命令同名会明确报错。装饰为**已存在的**宿主命令添加裸调用弹窗:宿主命令保留其目录行、参数声明与生命周期记账,被装饰的名字在会话目录中无宿主行时永不触发。菜单查询按顺序且不区分大小写地模糊匹配命令名的子序列;前缀排名最高。 +贡献项是客户端自有命令——与宿主命令同名会明确报错。它的 UI 是 popupSelect 规格或动作:裸调用在消费掉触发 token 之后运行的一个回调,它不提交任何内容,因此绝不会拒绝带附件的草稿。菜单里的「文件」行就是本包自己的动作;只要 composer 接受文件,它就经会话作用域的 `slash/input-pick-files` 事件打开 composer 的文件选择器,子智能体上不提供。装饰为**已存在的**宿主命令添加裸调用弹窗或动作:宿主命令保留其目录行、参数声明与生命周期记账,被装饰的名字在会话目录中无宿主行时永不触发。菜单查询按顺序且不区分大小写地模糊匹配命令名与标题的子序列;前缀排名最高,输入查询后匹配项平铺列出,不再带小节标题。 + +### 内置行的展示面 + +宿主描述符只携带英文文案,因此 `src/client/presentation.ts` 拥有六个内置宿主命令在客户端的展示面:目录行的说明与规范英文文案相同时,它从 `command` 词典取得本地化的标题、说明、图标与声明 token;同名的作用域覆盖或第三方命令保留自己的说明,只有小节位置跟随名字;不在两个小节清单里的行按目录顺序排在「指令」小节末尾。中文下选中「计划」会在 composer 填入 `/计划 `,提交仍执行 `/plan `;键入的 `/计划` 或 `/目标` 在任何语言下的空格与回车裁决中都同样解析,因此在一种语言下写的草稿在另一种语言下照样能提交。贡献项自带 `label`、`description` 与 `icon`,每次生成候选项时读取,语言切换后下一次打开菜单即生效,无需重新注册。 ### 带附件提交 @@ -43,7 +47,7 @@ composer 携带图片或通用文件提交时,只有声明了 `input.attachmen
实现细节——点击展开 -`src/client/contract.ts` 是固定的业务约定:`CommandUiContract.register(name, spec)` 与 `decorate(name, spec)` 是业务包消费的全部内容。`CommandDirectory` 是唯一的 wire 派生缓存,以会话为 key:普通会话经 `command.list({sessionId})` 拉取;条目由转发的 `commands/change` owner 事件软失效、由 `connection/reset` 硬失效,并以 epoch 把关,被取代的旧拉取永远无法覆盖更新的结果。`matchSpace` 只凭该缓存同步应答;`matchEnter` 在 SubmitAttempt 信号上强等缓存,预热失败即拒绝。`command.execute` 返回匹配结果后,浏览器发布本地 `command/executed` 确认;其他客户端经宿主事件流收到持久命令节点,但收不到这条确认。`PopupSelectController` 是不含界面的外壳状态;`PopupSelectView` 自注册进 `conversation.input.overlay`,按会话解析。 +`src/client/contract.ts` 是固定的业务约定:`CommandUiContract.register(name, spec)` 与 `decorate(name, spec)` 是业务包消费的全部内容。`CommandDirectory` 是唯一的 wire 派生缓存,以会话为 key:普通会话经 `command.list({sessionId})` 拉取;条目由转发的 `commands/change` owner 事件软失效、由 `connection/reset` 硬失效,并以 epoch 把关,被取代的旧拉取永远无法覆盖更新的结果。`matchSpace` 只凭该缓存同步应答;`matchEnter` 在 SubmitAttempt 信号上强等缓存,预热失败即拒绝。`command.execute` 返回匹配结果后,浏览器发布本地 `command/executed` 确认;其他客户端经宿主事件流收到持久命令节点,但收不到这条确认。`PopupSelectController` 是不含界面的外壳状态;`PopupSelectView` 自注册进 `conversation.input.overlay`,按会话解析。`presentation.ts` 持有小节清单、内置行的展示面与本地化 token 的解析;`candidates` 对空查询分小节、对输入的查询经共享的 `rankByName` 排序。
diff --git a/packages/client/ui-commands/src/client/contract.ts b/packages/client/ui-commands/src/client/contract.ts index 4f4374735b..d135c248d5 100644 --- a/packages/client/ui-commands/src/client/contract.ts +++ b/packages/client/ui-commands/src/client/contract.ts @@ -3,8 +3,10 @@ * CommandUiRuntime (`ctx.commandUi`) implements this face; business packages * consume `register` alone. */ +import type { ComponentType } from 'react' import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { ClientSessionContext } from '@deepseek-ai/dsh-client-ui-input-trigger/client' +import type { IconProps } from '@deepseek-ai/dsh-client-ui-primitives' /** Copy for an option that must be acknowledged before onSelect can run. */ export interface SelectConfirmation { @@ -31,26 +33,49 @@ export interface SelectOption { * The shell component is owned by ui-commands; business never sees it. Both * callbacks receive the ClientSessionContext captured at popup open. */ -export type CommandUiSpec = { +export interface PopupSelectSpec { readonly kind: 'popupSelect' options(session: ClientSessionContext, signal: AbortSignal): Promise onSelect(option: SelectOption, session: ClientSessionContext): void | Promise } +/** + * Business registration for the action command kind: a bare invocation + * consumes the trigger token and runs one client-side callback (the menu's + * File row opens the composer's file picker). It submits nothing, so an + * attachment-carrying draft never refuses it. + */ +export interface ActionSpec { + readonly kind: 'action' + /** + * Run the action for one session. + * @param session - the ClientSessionContext captured at invocation. + */ + run(session: ClientSessionContext): void +} + +/** The UI behavior of a contribution or decoration. */ +export type CommandUiSpec = PopupSelectSpec | ActionSpec + /** * One client-owned command contribution: a slash-menu entry whose behavior * lives entirely on the client (no host descriptor). Merged with the host * catalog by name — a collision with a host command fails loud at candidate - * synthesis, never shadows. + * synthesis, never shadows. Row copy is read on every candidate pass, so a + * locale change reaches the next menu open without re-registration. */ export interface CommandContribution { /** Command name without the leading slash (unique across contributions). */ readonly name: string - /** Menu row description. */ - readonly description: string + /** Localized menu row title; the name itself when absent. */ + label?(): string + /** Localized menu row description; the row shows none when absent. */ + description?(): string + /** Menu row glyph from the shared icon set. */ + readonly icon?: ComponentType /** Capability filter, called with a fresh projection per candidate pass. */ available(session: ClientSessionContext): boolean - /** The command's UI behavior (this phase: popupSelect only). */ + /** The command's UI behavior. */ readonly ui: CommandUiSpec } @@ -68,7 +93,7 @@ export interface CommandDecoration { readonly name: string /** Capability filter, called with a fresh projection per bare invocation. */ available(session: ClientSessionContext): boolean - /** The bare-invocation UI (this phase: popupSelect only). */ + /** The bare-invocation UI. */ readonly ui: CommandUiSpec } diff --git a/packages/client/ui-commands/src/client/index.ts b/packages/client/ui-commands/src/client/index.ts index 26e8a32e09..aaa9c8cab7 100644 --- a/packages/client/ui-commands/src/client/index.ts +++ b/packages/client/ui-commands/src/client/index.ts @@ -15,6 +15,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' 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 { IconPaperclipOutline16 } from '@deepseek-ai/dsh-client-ui-primitives' import { CommandUiRuntime } from './service.ts' import type { PopupSelectInjected } from './PopupSelectView.tsx' import { PopupSelectView } from './PopupSelectView.tsx' @@ -27,9 +28,12 @@ export { filterOptions, PopupSelectController } from './popup.ts' export type { PopupSelectDeps, PopupSpec, PopupState, TokenSegment } from './popup.ts' export type { PopupSelectInjected, PopupSelectViewProps } from './PopupSelectView.tsx' export type { - CommandContribution, CommandDecoration, CommandUiContract, CommandUiSpec, SelectConfirmation, SelectOption, + ActionSpec, CommandContribution, CommandDecoration, CommandUiContract, CommandUiSpec, PopupSelectSpec, + SelectConfirmation, SelectOption, } from './contract.ts' export type { CommandKey } from './locales.ts' +export { SECTION_ROWS, resolveCommandName } from './presentation.ts' +export type { MenuSection } from './presentation.ts' declare module '@deepseek-ai/cordis' { interface Context { @@ -39,7 +43,7 @@ declare module '@deepseek-ai/cordis' { declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { - /** The popupSelect shell's copy. */ + /** The menu rows' and the popupSelect shell's copy. */ command: CommandKey } } @@ -51,13 +55,33 @@ const NS = 'command' export const inject = ['inputTriggers', 'sessions', 'remote', 'remote.commands', 'locale'] /** - * Client plugin body: mount the service, then register the popupSelect shell - * into the input overlay once its declarer is up. + * Client plugin body: mount the service, register the menu's File row (an + * action opening the composer's file picker wherever the composer accepts + * files — never on a subagent), then register the popupSelect shell into the + * input overlay once its declarer is up. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-commands: dictionaries') ctx.plugin(CommandUiRuntime) + const t = ctx.locale.bind(NS) + ctx.inject(['commandUi', 'sessions'], (scope: ClientContext) => { + const command = scope.commandUi + const sessions = scope.get('sessions') as ISessions + scope.effect(() => command.register({ + name: 'file', + label: () => t('label.file'), + icon: IconPaperclipOutline16, + available: session => sessions.subagentAddress(session.sessionId) === undefined, + ui: { + kind: 'action', + run: (session) => { + const actx = sessions.scope(session.sessionId) + if (actx !== undefined) actx.bail(actx, 'slash/input-pick-files') + }, + }, + }), 'ui-commands: File row') + }) ctx.inject(['slots', 'commandUi', 'sessions'], (scope: ClientContext) => { const command = scope.commandUi const sessions = scope.get('sessions') as ISessions diff --git a/packages/client/ui-commands/src/client/locales.ts b/packages/client/ui-commands/src/client/locales.ts index 384597a9b2..3e1951f6f7 100644 --- a/packages/client/ui-commands/src/client/locales.ts +++ b/packages/client/ui-commands/src/client/locales.ts @@ -1,7 +1,33 @@ -/** `command` namespace dictionaries (the popupSelect shell's copy). */ +/** + * `command` namespace dictionaries: the composer menu's section headings, + * the client face (title, description, claim token) of the built-in Host + * commands whose catalog descriptors carry English text only, the File row's + * title, and the popupSelect shell's copy. + */ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { + 'section.add': '添加', + 'section.commands': '指令', + 'label.file': '文件', + 'label.goal': '目标', + 'label.plan': '计划', + 'label.feedback': '反馈', + 'label.compact': '压缩', + 'label.permission': '权限', + 'label.export': '下载日志', + 'description.goal': '设置或查看长期任务的目标', + 'description.plan': '进入或退出计划模式', + 'description.feedback': '记录关于本会话的反馈', + 'description.compact': '压缩较早的对话历史', + 'description.permission': '切换权限预设(沙箱模式与审批策略)', + 'description.export': '将本会话日志下载为 ZIP 压缩包', + 'token.goal': '目标', + 'token.plan': '计划', + 'token.feedback': '反馈', + 'token.compact': '压缩', + 'token.permission': '权限', + 'token.export': '导出', 'search.placeholder': '搜索…', 'search.aria': '筛选选项', 'status.loading': '正在加载选项…', @@ -15,8 +41,33 @@ export const zh = { /** The command namespace key union. */ export type CommandKey = keyof typeof zh -/** English dictionary, checked complete against the zh key set. */ +/** + * English dictionary, checked complete against the zh key set. Each + * `description.*` entry is byte-equal to the Host descriptor it localizes: + * that equality is how a catalog row is recognized as the built-in command. + */ export const en = { + 'section.add': 'Add', + 'section.commands': 'Commands', + 'label.file': 'File', + 'label.goal': 'Goal', + 'label.plan': 'Plan', + 'label.feedback': 'Feedback', + 'label.compact': 'Compact', + 'label.permission': 'Permission', + 'label.export': 'Export', + 'description.goal': 'Set or view the goal for a long-running task', + 'description.plan': 'Enter or leave plan mode', + 'description.feedback': 'Record feedback about this session', + 'description.compact': 'Compact older conversation history', + 'description.permission': 'Switch the permission preset (sandbox mode + approval policy)', + 'description.export': 'Download this Session log as a ZIP archive', + 'token.goal': 'goal', + 'token.plan': 'plan', + 'token.feedback': 'feedback', + 'token.compact': 'compact', + 'token.permission': 'permission', + 'token.export': 'export', 'search.placeholder': 'Search…', 'search.aria': 'Filter options', 'status.loading': 'Loading options…', diff --git a/packages/client/ui-commands/src/client/presentation.ts b/packages/client/ui-commands/src/client/presentation.ts new file mode 100644 index 0000000000..24ad746762 --- /dev/null +++ b/packages/client/ui-commands/src/client/presentation.ts @@ -0,0 +1,132 @@ +/** + * Design-owned presentation of the composer menu (design doc for #3567): + * the two sections with their usage order, and the client face of the + * built-in Host commands — localized title, description, claim token, and + * icon — whose catalog descriptors carry English text only. A catalog row is + * the built-in command when its description equals the canonical English + * text; a scoped override or third-party command of the same name keeps its + * own description and title, and only its section position follows the name. + */ +import type { ComponentType } from 'react' +import type { InputTriggerCandidate } from '@deepseek-ai/dsh-client-ui-input-trigger/client' +import { + IconCompactOutline16, IconDownloadOutline16, IconGoalOutline16, IconPlanOutline14, IconSendOutline16, + IconShieldOutline16, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { IconProps } from '@deepseek-ai/dsh-client-ui-primitives' +import type { TranslateNS } from '@deepseek-ai/dsh-client-locale/client' +import { en, zh } from './locales.ts' +import type { CommandKey } from './locales.ts' + +/** The menu's two sections. */ +export type MenuSection = 'add' | 'commands' + +/** Row names per section, highest usage first; rows outside both lists close the Commands section in catalog order. */ +export const SECTION_ROWS: Readonly> = { + add: ['file', 'goal', 'plan', 'feedback'], + commands: ['compact', 'permission', 'model', 'export'], +} + +/** The dictionary keys and glyph of one built-in Host command's client face. */ +interface HostFace { + readonly label: CommandKey + readonly description: CommandKey + readonly token: CommandKey + readonly icon: ComponentType +} + +/** One built-in Host command's face, keyed by its dictionary entries. */ +function hostFace(name: string, icon: ComponentType): readonly [string, HostFace] { + return [name, { + label: `label.${name}` as CommandKey, + description: `description.${name}` as CommandKey, + token: `token.${name}` as CommandKey, + icon, + }] +} + +/** Built-in Host commands whose client face this package owns. */ +const HOST_FACES: ReadonlyMap = new Map([ + hostFace('goal', IconGoalOutline16), + hostFace('plan', IconPlanOutline14), + hostFace('feedback', IconSendOutline16), + hostFace('compact', IconCompactOutline16), + hostFace('permission', IconShieldOutline16), + hostFace('export', IconDownloadOutline16), +]) + +/** The face of the built-in command a catalog row is, or undefined when the description is not the canonical English text. */ +function builtinFace(name: string, description: string): HostFace | undefined { + const face = HOST_FACES.get(name) + return face !== undefined && en[face.description] === description ? face : undefined +} + +/** + * The localized menu face of a catalog row. + * @param name - catalog command name. + * @param description - the catalog description. + * @param t - the `command` namespace translator. + * @returns title, description, and glyph for a built-in command; undefined + * for any other row, which keeps its catalog description. + */ +export function builtinRowFace( + name: string, + description: string, + t: TranslateNS<'command'>, +): Pick | undefined { + const face = builtinFace(name, description) + return face === undefined ? undefined : { label: t(face.label), description: t(face.description), icon: face.icon } +} + +/** + * The claim token of a catalog row in the current locale (the text the + * composer shows after a pick): the localized token of a built-in command, + * the name itself for any other row. + * @param name - catalog command name. + * @param description - the catalog description. + * @param t - the `command` namespace translator. + * @returns the token without its leading slash. + */ +export function claimToken(name: string, description: string, t: TranslateNS<'command'>): string { + const face = builtinFace(name, description) + return face === undefined ? name : t(face.token) +} + +/** Every localized claim token of every dictionary → the command name it stands for. */ +const TOKEN_ALIASES: ReadonlyMap = new Map( + [...HOST_FACES].flatMap(([name, face]) => + [zh[face.token], en[face.token]].filter(token => token !== name).map(token => [token, name] as const)), +) + +/** + * The command name a typed token stands for: a localized claim token of a + * built-in command in any dictionary resolves to that command, so a draft + * written under one locale still submits under another. + * @param token - the typed name without its leading slash. + * @returns the catalog command name. + */ +export function resolveCommandName(token: string): string { + return TOKEN_ALIASES.get(token) ?? token +} + +/** + * Arrange the empty-query menu: the Add section, then the Commands section, + * each in usage order, with unlisted rows closing Commands in their input + * order; each row carries its section heading. + * @param rows - the visible candidates in catalog-then-contribution order. + * @param t - the `command` namespace translator. + * @returns the sectioned rows. + */ +export function sectionRows(rows: readonly InputTriggerCandidate[], t: TranslateNS<'command'>): readonly InputTriggerCandidate[] { + const listed = new Set([...SECTION_ROWS.add, ...SECTION_ROWS.commands]) + const byName = new Map(rows.map(row => [row.name, row])) + const pick = (names: readonly string[]): InputTriggerCandidate[] => + names.flatMap((name) => { + const row = byName.get(name) + return row === undefined ? [] : [row] + }) + const add = pick(SECTION_ROWS.add).map(row => ({ ...row, section: t('section.add') })) + const commands = [...pick(SECTION_ROWS.commands), ...rows.filter(row => !listed.has(row.name))] + .map(row => ({ ...row, section: t('section.commands') })) + return [...add, ...commands] +} diff --git a/packages/client/ui-commands/src/client/service.ts b/packages/client/ui-commands/src/client/service.ts index ae7d350e46..c186b439ea 100644 --- a/packages/client/ui-commands/src/client/service.ts +++ b/packages/client/ui-commands/src/client/service.ts @@ -2,10 +2,12 @@ * CommandUiRuntime (`ctx.commandUi`): the '/' command source over the * session-keyed directory, the client-contribution registry, and the * per-session popupSelect controllers. Candidate synthesis merges the host - * catalog with contributions by availability, then position filtering and - * the `/` menu's shared name ranking (ui-primitives `rankByName`); a - * host/contribution name collision fails loud. Every execute - * addresses the session's agent by sessionId — sessions are always + * catalog with contributions by availability, gives built-in Host rows their + * localized face (presentation.ts), then position-filters; an empty query + * lists the Add and Commands sections in usage order, a typed query ranks + * every row by the `/` menu's shared name-and-label ranking (ui-primitives + * `rankByName`). A host/contribution name collision fails loud. Every + * execute addresses the session's agent by sessionId — sessions are always * agent-backed. */ import { Service } from '@deepseek-ai/cordis' @@ -27,6 +29,7 @@ import type { CommandContribution, CommandDecoration, CommandUiContract } from ' import type { CommandDescriptor } from './directory.ts' import { CommandDirectory } from './directory.ts' import { PopupSelectController } from './popup.ts' +import { builtinRowFace, claimToken, resolveCommandName, sectionRows } from './presentation.ts' import type { TokenSegment } from './popup.ts' declare module '@deepseek-ai/cordis' { @@ -185,47 +188,58 @@ export class CommandUiRuntime extends Service implements CommandUiContract { } } - /** Menu candidates: host catalog + contribution availability, then position filtering and the shared name ranking. */ + /** + * Menu candidates: host catalog + contribution availability, built-in rows + * localized, then position filtering; sections for an empty query, the + * shared name-and-label ranking for a typed one. + */ private async candidates(session: ClientSessionContext, req: CandidateRequest): Promise { const list = await this.directory.ensureReady(session.sessionId, req.signal) const rows: InputTriggerCandidate[] = [] const seen = new Set() for (const c of list) { seen.add(c.name) - rows.push({ name: c.name, description: c.description, ...(c.input !== undefined ? { hint: c.input.hint } : {}) }) + rows.push({ + name: c.name, + ...(builtinRowFace(c.name, c.description, this.t) ?? { description: c.description }), + ...(c.input !== undefined ? { hint: c.input.hint } : {}), + }) } for (const contribution of this.live.contributions.values()) { if (!contribution.available(session)) continue if (seen.has(contribution.name)) { throw new Error(`ui-commands: contribution /${contribution.name} collides with a host command`) } - rows.push({ name: contribution.name, description: contribution.description }) + rows.push({ + name: contribution.name, + ...(contribution.label === undefined ? {} : { label: contribution.label() }), + ...(contribution.description === undefined ? {} : { description: contribution.description() }), + ...(contribution.icon === undefined ? {} : { icon: contribution.icon }), + }) } - return rankByName( - rows.filter(c => req.position === 'leading' || c.hint === undefined), - req.query, - ) + const visible = rows.filter(c => req.position === 'leading' || c.hint === undefined) + return req.query === '' ? sectionRows(visible, this.t) : rankByName(visible, req.query) } - /** Decision table, menu column: contribution/decorated-host → popup; host input → claim; host bare → detached execute. */ + /** Decision table, menu column: contribution/decorated-host → popup or action; host input → claim; host bare → detached execute. */ private dispatch(pick: InputTriggerPick): PickOutcome { const name = pick.candidate.name const contribution = this.live.contributions.get(name) if (contribution !== undefined && contribution.available(pick.session)) { - this.openPopup(name, contribution.ui, pick.session, { via: 'menu', span: pick.span }) + this.invoke(name, contribution.ui, pick.session, { via: 'menu', span: pick.span }) return 'handled' } const desc = this.directory.resolve(pick.session.sessionId, name) if (desc === undefined) return undefined // snapshot swapped between menu and pick → miss - // A decoration replaces the HOST row's bare invocation with its popup; - // it decorates only a resolvable host command (checked above), never - // manufactures one, and never touches the argument claim below. + // A decoration replaces the HOST row's bare invocation with its popup or + // action; it decorates only a resolvable host command (checked above), + // never manufactures one, and never touches the argument claim below. const decoration = this.live.decorations.get(name) if (decoration !== undefined && decoration.available(pick.session)) { - this.openPopup(name, decoration.ui, pick.session, { via: 'menu', span: pick.span }) + this.invoke(name, decoration.ui, pick.session, { via: 'menu', span: pick.span }) return 'handled' } - if (desc.input !== undefined) return { claim: this.leadingClaim(desc, pick.session) } + if (desc.input !== undefined) return { claim: this.leadingClaim(desc, pick.session, claimToken(desc.name, desc.description, this.t)) } // Menu-pick execute consumes the trigger span before the detached run // (scoped event; the input owns the CAS guard). this.consumeVia(pick.session.sessionId, { via: 'menu', span: pick.span }) @@ -236,11 +250,11 @@ export class CommandUiRuntime extends Service implements CommandUiContract { /** Decision table, space column: hot-key sync check; only host leadingInput claims. */ private matchSpace(session: ClientSessionContext, token: string): PickOutcome { if (!token.startsWith('/')) return undefined - const name = token.slice(1) - if (this.live.contributions.has(name)) return undefined // popup kinds never claim on space + const name = resolveCommandName(token.slice(1)) + if (this.live.contributions.has(name)) return undefined // popup and action kinds never claim on space const desc = this.directory.resolve(session.sessionId, name) if (desc === undefined || desc.input === undefined) return undefined - return { claim: this.leadingClaim(desc, session) } + return { claim: this.leadingClaim(desc, session, token.slice(1)) } } /** @@ -250,10 +264,14 @@ export class CommandUiRuntime extends Service implements CommandUiContract { * args-tolerant. * * Envelope policy: an enter submission carrying attachments resolves only - * through a command declaring attachment acceptance. Every other command route — - * popup, non-accepting claim, bare detached execute — throws the refusal - * so the machine surfaces one composer notice and the draft and attachments - * stay in place; nothing executes and nothing is dropped. + * through a command declaring attachment acceptance. Every other submitting + * route — popup, non-accepting claim, bare detached execute — throws the + * refusal so the machine surfaces one composer notice and the draft and + * attachments stay in place; nothing executes and nothing is dropped. An + * action submits nothing and runs regardless. + * + * A typed token is resolved through the localized claim tokens, so a line + * written as `/计划` reaches the `plan` descriptor and executes as `/plan`. */ private async matchEnter( session: ClientSessionContext, @@ -266,16 +284,18 @@ export class CommandUiRuntime extends Service implements CommandUiContract { const ws = trimmed.search(/\s/) const token = ws === -1 ? trimmed : trimmed.slice(0, ws) const bare = ws === -1 - const name = token.slice(1) + const name = resolveCommandName(token.slice(1)) if (name === '') return undefined + // The Host line always carries the catalog name. + const canonical = `/${name}${trimmed.slice(token.length)}` const refuseAttachments = (): never => { throw new Error(this.t('notice.attachmentsUnsupported', { command: name })) } const contribution = this.live.contributions.get(name) if (contribution !== undefined && contribution.available(session)) { if (!bare) return undefined - if (envelope.attachments > 0) refuseAttachments() - this.openPopup(name, contribution.ui, session, { via: 'enter', token }) + if (envelope.attachments > 0 && contribution.ui.kind !== 'action') refuseAttachments() + this.invoke(name, contribution.ui, session, { via: 'enter', token }) return 'handled' } await this.directory.ensureReady(session.sessionId, signal) @@ -286,42 +306,57 @@ export class CommandUiRuntime extends Service implements CommandUiContract { if (bare) { const decoration = this.live.decorations.get(name) if (decoration !== undefined && decoration.available(session)) { - if (envelope.attachments > 0) refuseAttachments() - this.openPopup(name, decoration.ui, session, { via: 'enter', token }) + if (envelope.attachments > 0 && decoration.ui.kind !== 'action') refuseAttachments() + this.invoke(name, decoration.ui, session, { via: 'enter', token }) return 'handled' } } if (desc.input !== undefined) { if (envelope.attachments > 0 && desc.input.attachments !== true) refuseAttachments() - return { claim: this.leadingClaim(desc, session) } + return { claim: this.leadingClaim(desc, session, token.slice(1)) } } if (!bare) return undefined if (envelope.attachments > 0) refuseAttachments() this.consumeVia(session.sessionId, { via: 'enter', token }) - this.runDetached(desc, session, trimmed) + this.runDetached(desc, session, canonical) return 'handled' } - /** Open the session's popup for one contribution or decoration (menu pick / bare enter). */ - private openPopup( + /** + * Invoke one contribution or decoration (menu pick / bare enter): open the + * session's popup, or consume the token and run the action. + */ + private invoke( name: string, ui: CommandContribution['ui'], session: ClientSessionContext, segment: TokenSegment, ): void { + if (ui.kind === 'action') { + this.consumeVia(session.sessionId, segment) + ui.run(session) + return + } const actx = this.scopeFor(session.sessionId) if (actx === undefined) return this.popupFor(actx).open(name, ui, session, segment) } - /** Build the leadingInput claim: token `/name ` + the command.execute submit transaction. */ - private leadingClaim(desc: CommandDescriptor, session: ClientSessionContext): CommandClaim { - const token = `/${desc.name} ` + /** + * Build the leadingInput claim. The composer keeps the claimed token in + * the draft and reads the arguments after it, so the token is the spelling + * the draft will carry: the locale's token for a menu pick, the typed + * spelling for Space and Enter. The command.execute submit transaction + * always sends the catalog name. + */ + private leadingClaim(desc: CommandDescriptor, session: ClientSessionContext, shown: string): CommandClaim { + const token = `/${shown} ` + const line = `/${desc.name} ` return { token, ...(desc.input !== undefined ? { hint: desc.input.hint } : {}), ...(desc.input?.attachments === true ? { attachments: true } : {}), - submit: (args, _actx, attachments) => this.execute(session, token + args, attachments), + submit: (args, _actx, attachments) => this.execute(session, line + args, attachments), } } diff --git a/packages/client/ui-commands/tests/browser-plugin.client.spec.ts b/packages/client/ui-commands/tests/browser-plugin.client.spec.ts index c2143a35c3..eca06cfe44 100644 --- a/packages/client/ui-commands/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-commands/tests/browser-plugin.client.spec.ts @@ -32,8 +32,11 @@ async function bench() { ctx.provide('sessions', { scope: (id: SessionId) => scopes.get(id), scopeOf: (c: Context) => scopeOf(c), + subagentAddress: (id: SessionId) => id === sid('child') + ? { parentSessionId: sid('parent'), childSessionId: id, mode: 'continuable' as const } + : undefined, }) - const commandsRemote = { list: () => Promise.resolve([]) } + const commandsRemote = { list: () => Promise.resolve({ ok: true as const, value: [] }) } // The service subscribes its cache-invalidation events on construction, so // the Remote face needs `$on` even where this spec dispatches none. ctx.provide('remote', { commands: commandsRemote, $on: () => () => {} }) @@ -73,6 +76,25 @@ describe('apply', () => { expect(slots.entries('conversation.input.overlay')).toHaveLength(0) }) + it('registers the File row: an action that consumes the token and opens the scoped file picker; absent on a subagent', async () => { + const { sources, mint } = await bench() + const source = sources.get('/ command')! + const req = { query: '', position: 'leading' as const, drilled: false, signal: new AbortController().signal } + const rows = await source.candidates({ sessionId: sid('s1') }, req) + expect(rows).toEqual([{ name: 'file', label: 'File', icon: expect.any(Function) as never, section: 'Add' }]) + expect(await source.candidates({ sessionId: sid('child') }, req)).toEqual([]) + const scope = mint('s1') + const picks: string[] = [] + scope.ctx.on('slash/input-consume-token', () => { picks.push('consume'); return true }) + scope.ctx.on('slash/input-pick-files', () => { picks.push('pick-files'); return true }) + const span = { start: 0, end: 5, draftRev: 1 } + expect(source.onPick({ candidate: rows[0]!, session: { sessionId: sid('s1') }, position: 'leading', via: 'menu', action: 'pick', span })).toBe('handled') + expect(picks).toEqual(['consume', 'pick-files']) + // A session without a live scope runs nothing and throws nothing. + expect(source.onPick({ candidate: rows[0]!, session: { sessionId: sid('gone') }, position: 'leading', via: 'menu', action: 'pick', span })).toBe('handled') + expect(picks).toHaveLength(2) + }) + it('the overlay inject resolves the per-session popup controller by sessionId and fails loud on an unknown id', async () => { const { ctx, slots, mint } = await bench() const command = ctx.get('commandUi') as CommandUiRuntime diff --git a/packages/client/ui-commands/tests/service.client.spec.ts b/packages/client/ui-commands/tests/service.client.spec.ts index 23ce7ae505..0905a8b59b 100644 --- a/packages/client/ui-commands/tests/service.client.spec.ts +++ b/packages/client/ui-commands/tests/service.client.spec.ts @@ -13,8 +13,9 @@ import type { CommandResult } from '@deepseek-ai/dsh-commands/types' import { createScope, scopeOf } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' +import { IconGoalOutline16 } from '@deepseek-ai/dsh-client-ui-primitives' import type { ClientSessionContext, ConsumeTokenRequest, InputTriggerPick, InputTriggerSource, SubmitAttachment } from '@deepseek-ai/dsh-client-ui-input-trigger/client' -import type { CommandContribution, CommandDecoration, CommandUiSpec, SelectOption } from '../src/client/contract.ts' +import type { CommandContribution, CommandDecoration, PopupSelectSpec, SelectOption } from '../src/client/contract.ts' import type { CommandDescriptor } from '../src/client/directory.ts' import { CommandUiRuntime } from '../src/client/service.ts' @@ -155,7 +156,7 @@ function menuPick(source: InputTriggerSource, name: string, session: ClientSessi return source.onPick(pick) } -const themeUi = (over: Partial = {}): CommandUiSpec => ({ +const themeUi = (over: Partial = {}): PopupSelectSpec => ({ kind: 'popupSelect', options: () => Promise.resolve([{ id: 'dark', label: 'Dark' }]), onSelect: () => undefined, @@ -164,7 +165,7 @@ const themeUi = (over: Partial = {}): CommandUiSpec => ({ const themeContribution = (over: Partial = {}): CommandContribution => ({ name: 'theme', - description: 'client popup kind', + description: () => 'client popup kind', available: () => true, ui: themeUi(), ...over, @@ -224,7 +225,7 @@ describe('candidates', () => { const { source, listCalls } = await bench() const names = (await source.candidates(proj('s2'), req(''))).map(c => c.name) expect(listCalls).toEqual([{ sessionId: sid('s2') }]) - expect(names).toEqual(['plan', 'goal', 'attach']) + expect(names).toEqual(['goal', 'plan', 'attach']) }) it('hides leadingInput commands at inline position', async () => { @@ -238,7 +239,7 @@ describe('candidates', () => { const available = vi.fn((session: ClientSessionContext) => session.sessionId === sid('s1')) command.register(themeContribution({ available })) const s1Names = (await source.candidates(proj('s1'), req(''))).map(c => c.name) - expect(s1Names).toEqual(['plan', 'goal', 'theme']) + expect(s1Names).toEqual(['goal', 'plan', 'theme']) expect(available).toHaveBeenLastCalledWith(proj('s1')) const s2Names = (await source.candidates(proj('s2'), req(''))).map(c => c.name) expect(s2Names).not.toContain('theme') @@ -257,6 +258,132 @@ describe('candidates', () => { await expect(source.candidates(proj('s1'), req(''))).rejects.toThrow('collides with a host command') }) + describe('menu presentation (design doc for #3567)', () => { + /** The shipped catalog in Host registration order, with the canonical English descriptions. */ + const SHIPPED: CommandDescriptor[] = [ + { name: 'compact', description: 'Compact older conversation history' }, + { name: 'export', description: 'Download this Session log as a ZIP archive' }, + { name: 'feedback', description: 'Record feedback about this session', input: { hint: '' } }, + { name: 'goal', description: 'Set or view the goal for a long-running task', input: { hint: '', attachments: true } }, + { name: 'permission', description: 'Switch the permission preset (sandbox mode + approval policy)', input: { hint: '' } }, + { name: 'plan', description: 'Enter or leave plan mode', input: { hint: '[off|message]', attachments: true } }, + { name: 'deploy', description: 'third-party command' }, + ] + const Glyph = () => null + const fileContribution = (run = vi.fn()): CommandContribution => ({ + name: 'file', + label: () => 'command:label.file', + icon: Glyph, + available: () => true, + ui: { kind: 'action', run }, + }) + const modelContribution = (): CommandContribution => ({ + name: 'model', + label: () => '模型', + description: () => '选择本会话使用的模型', + icon: Glyph, + available: () => true, + ui: themeUi(), + }) + + it('an empty query lists Add then Commands in usage order; built-in rows carry their localized face, other rows their own text', async () => { + const { command, source } = await bench({ commands: () => Promise.resolve({ commands: SHIPPED }) }) + command.register(modelContribution()) + command.register(fileContribution()) + const rows = await source.candidates(proj('s1'), req('')) + expect(rows.map(row => row.name)).toEqual([ + 'file', 'goal', 'plan', 'feedback', 'compact', 'permission', 'model', 'export', 'deploy', + ]) + expect(rows.map(row => row.section)).toEqual([ + ...Array(4).fill('command:section.add'), + ...Array(5).fill('command:section.commands'), + ]) + expect(rows[1]).toEqual({ + name: 'goal', + label: 'command:label.goal', + description: 'command:description.goal', + icon: IconGoalOutline16, + hint: '', + section: 'command:section.add', + }) + expect(rows[0]).toEqual({ name: 'file', label: 'command:label.file', icon: Glyph, section: 'command:section.add' }) + expect(rows[6]).toMatchObject({ name: 'model', label: '模型', description: '选择本会话使用的模型', icon: Glyph }) + // A third-party command keeps its catalog text and gets no glyph. + expect(rows[8]).toEqual({ name: 'deploy', description: 'third-party command', section: 'command:section.commands' }) + }) + + it('a Host row of a built-in name with another description is not the built-in command', async () => { + const commands: CommandDescriptor[] = [{ name: 'goal', description: 'scoped goal', input: { hint: 'x' } }] + const { source } = await bench({ commands: () => Promise.resolve({ commands }) }) + const [row] = await source.candidates(proj('s1'), req('')) + expect(row).toEqual({ name: 'goal', description: 'scoped goal', hint: 'x', section: 'command:section.add' }) + }) + + it('a typed query ranks rows flat by name or label and drops the section headings', async () => { + const { command, source } = await bench({ commands: () => Promise.resolve({ commands: SHIPPED }) }) + command.register(modelContribution()) + const names = async (query: string) => (await source.candidates(proj('s1'), req(query))).map(c => c.name) + await expect(names('模型')).resolves.toEqual(['model']) + await expect(names('label.goal')).resolves.toEqual(['goal']) + await expect(names('ex')).resolves.toEqual(['export']) + // Prefix hits lead; the empty-query section order no longer applies. + await expect(names('pl')).resolves.toEqual(['plan', 'deploy']) + const rows = await source.candidates(proj('s1'), req('pl')) + expect(rows.every(row => row.section === undefined)).toBe(true) + }) + + it('an action contribution: the menu pick consumes the span and runs it; bare enter runs it even with attachments; an argued line misses', async () => { + const run = vi.fn() + const { command, source, mint, warm } = await bench({ commands: () => Promise.resolve({ commands: SHIPPED }) }) + command.register(fileContribution(run)) + const scope = mint('s1') + const consumes: ConsumeTokenRequest[] = [] + scope.ctx.on('slash/input-consume-token', (r) => { consumes.push(r); return true }) + await warm(proj('s1')) + expect(menuPick(source, 'file', proj('s1'))).toBe('handled') + expect(consumes).toEqual([{ guard: { kind: 'span', span: { start: 0, end: 5, draftRev: 3 } } }]) + expect(run).toHaveBeenCalledExactlyOnceWith(proj('s1')) + expect(await source.matchEnter!(proj('s1'), '/file', new AbortController().signal, { attachments: 2 })).toBe('handled') + expect(consumes[1]).toEqual({ guard: { kind: 'bare-token', token: '/file' } }) + expect(run).toHaveBeenCalledTimes(2) + expect(await source.matchEnter!(proj('s1'), '/file now', new AbortController().signal, { attachments: 0 })).toBeUndefined() + expect(source.matchSpace!(proj('s1'), '/file')).toBeUndefined() + }) + + it('a built-in claim shows the localized token and submits the catalog name', async () => { + const { source, warm, executeCalls } = await bench({ commands: () => Promise.resolve({ commands: SHIPPED }) }) + await warm(proj('s1')) + const outcome = menuPick(source, 'plan', proj('s1')) + if (outcome === undefined || outcome === 'handled' || !('claim' in outcome)) throw new Error('expected the claim') + expect(outcome.claim.token).toBe('/command:token.plan ') + await outcome.claim.submit('do x', new Context(), []) + expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/plan do x', images: [] }]) + }) + + it('a typed localized token resolves to the built-in command on space and enter; the Host line carries the catalog name', async () => { + const { source, mint, warm, executeCalls } = await bench({ commands: () => Promise.resolve({ commands: SHIPPED }) }) + mint('s1') + await warm(proj('s1')) + const space = source.matchSpace!(proj('s1'), '/计划') + if (space === undefined || space === 'handled' || !('claim' in space)) throw new Error('expected the plan claim') + expect(space.claim.hint).toBe('[off|message]') + // The claim keeps the typed spelling (the draft carries it and the + // arguments are read after it); the submission sends the catalog name. + expect(space.claim.token).toBe('/计划 ') + const enter = await source.matchEnter!(proj('s1'), '/目标 ship it', new AbortController().signal, { attachments: 0 }) + if (enter === undefined || enter === 'handled' || !('claim' in enter)) throw new Error('expected the goal claim') + expect(enter.claim.attachments).toBe(true) + expect(enter.claim.token).toBe('/目标 ') + await enter.claim.submit('ship it', new Context(), []) + expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/goal ship it', images: [] }]) + const typed = await source.matchEnter!(proj('s1'), '/plan now', new AbortController().signal, { attachments: 0 }) + if (typed === undefined || typed === 'handled' || !('claim' in typed)) throw new Error('expected the plan claim') + expect(typed.claim.token).toBe('/plan ') + executeCalls.length = 0 + expect(await source.matchEnter!(proj('s1'), '/压缩', new AbortController().signal, { attachments: 0 })).toBe('handled') + await vi.waitFor(() => { expect(executeCalls).toEqual([{ sessionId: sid('s1'), line: '/compact', images: [] }]) }) + }) + }) }) describe('decorations (bare-invocation UI on host commands)', () => { @@ -271,7 +398,7 @@ describe('decorations (bare-invocation UI on host commands)', () => { const { command, source } = await bench() command.decorate(goalDecoration()) const names = (await source.candidates(proj('s1'), req(''))).map(c => c.name) - expect(names).toEqual(['plan', 'goal']) + expect(names).toEqual(['goal', 'plan']) }) it('bare enter opens the popup; an argued line never consults the decoration (host claim)', async () => { diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index d93d7d7dc5..9bed7ed5c9 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/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-conversation/README.md -README.md: e06270a339a23fa17fb9d51642317fcf2aec6c0f -README.zh.md: 315fd3d7798145df7dbb6f504fe7b89c64827024 +README.md: cefb6f543151b4d52a817ef1539063c4b3207661 +README.zh.md: 385547e06bc90d9a46a2a0b416054efd35acded7 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index e06270a339..cefb6f5431 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -48,7 +48,7 @@ Default sends commit optimistically: Enter clears the draft, occurrence table, a Queued submission echoes show “Sending…” beside disabled edit, remove, and steer buttons; a collapsed dock keeps the sending status in its header. A matching Host queue row replaces the echo and enables each action according to its normal text-content and running-state requirements. Prompt acknowledgement alone does not enable queue actions. A failed submission removes its echo and displays an error; the composer restores the failed draft when it is empty or still contains the previous automatic restoration, preserving subsequently typed text. -While a normal composer is running, its primary pointer action remains Stop when the draft is empty or input is unavailable. Actionable text or attachments switch the same seat to Send; clearing or successfully submitting the draft restores Stop. The busy-Enter setting selects the Queue or Steer delivery for ordinary Sessions and continuable children, and the running Send button delivers through the same mode plain Enter resolves to; while it is enabled (no upload pending) over a plain message draft its label names that mode (Queue message or Steer message), so the setting governs Enter and the button together while Cmd/Ctrl+Enter still uses the other mode, and idle sessions, empty drafts, and `/` command lines keep the plain Send label ([decision](../../../.agents/notes/implemented/bug-fix/2026-09-04-busy-send-button-follows-enter-setting.md)). Their QueueDock rows share Edit, Remove, and Steer, and an empty draft shares the steer-all chord. One-shot children remain read-only. Plan mode and active goals do not change attachment intake. Continuable children keep separate Send and Stop actions but expose no paperclip, paste, or drop intake; if their parent is offline, Send and the composer gestures lock while QueueDock controls for the live inbox remain available ([decisions](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md), [inbox controls](../../../.agents/notes/implemented/feature/2026-08-27-continuable-subagent-human-inbox-control.md)). +While a normal composer is running, its primary pointer action remains Stop when the draft is empty or input is unavailable. Actionable text or attachments switch the same seat to Send; clearing or successfully submitting the draft restores Stop. The busy-Enter setting selects the Queue or Steer delivery for ordinary Sessions and continuable children, and the running Send button delivers through the same mode plain Enter resolves to; while it is enabled (no upload pending) over a plain message draft its label names that mode (Queue message or Steer message), so the setting governs Enter and the button together while Cmd/Ctrl+Enter still uses the other mode, and idle sessions, empty drafts, and `/` command lines keep the plain Send label ([decision](../../../.agents/notes/implemented/bug-fix/2026-09-04-busy-send-button-follows-enter-setting.md)). Their QueueDock rows share Edit, Remove, and Steer, and an empty draft shares the steer-all chord. One-shot children remain read-only. Plan mode and active goals do not change attachment intake. Continuable children keep separate Send and Stop actions but expose no File row, paste, or drop intake; if their parent is offline, Send and the composer gestures lock while QueueDock controls for the live inbox remain available ([decisions](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md), [inbox controls](../../../.agents/notes/implemented/feature/2026-08-27-continuable-subagent-human-inbox-control.md)). ## Temporary composer entries diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 315fd3d779..385547e06b 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -48,7 +48,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 排队提交的本地回显在禁用的编辑、删除、插话按钮旁显示“发送中…”;折叠后的队列在标题栏保留发送状态。匹配的 Host 队列行替换回显后,各操作按原有的纯文本内容和运行状态要求启用。仅收到 prompt 确认不会启用队列操作。提交失败会移除回显并显示错误;输入框为空或仍保留上一次自动恢复的内容时,composer 恢复失败草稿,保留用户随后输入的文字。 -普通 composer 运行时,如果草稿为空或输入不可用,主指针操作保持为 Stop。可提交的文字或附件会把同一位置切换为 Send;清空或成功提交草稿后恢复 Stop。繁忙态 Enter 设置为普通 Session 与可继续 child 选择 Queue 或 Steer 投递,运行中的 Send 按钮按 plain Enter 解析出的同一模式投递;当它在普通消息草稿上可用(没有待上传文件)时,其标签以该模式命名(排队发送或插话发送),因此该设置同时约束 Enter 与按钮,而 Cmd/Ctrl+Enter 仍使用另一模式;空闲会话、空草稿与 `/` 命令行保留普通的 Send 标签([决策](../../../.agents/notes/implemented/bug-fix/2026-09-04-busy-send-button-follows-enter-setting.zh.md))。它们的 QueueDock 行共享 Edit、Remove 与 Steer,空草稿也共享 steer-all 组合键。One-shot child 继续只读。Plan Mode 与 active goal 不改变附件入口。可继续 child 保留独立的 Send 与 Stop 操作,但不提供回形针、粘贴或拖放入口;parent 离线时,Send 与 composer 手势锁定,但在线 inbox 的 QueueDock 控制仍可使用([决策](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md)、[inbox 控制](../../../.agents/notes/implemented/feature/2026-08-27-continuable-subagent-human-inbox-control.zh.md))。 +普通 composer 运行时,如果草稿为空或输入不可用,主指针操作保持为 Stop。可提交的文字或附件会把同一位置切换为 Send;清空或成功提交草稿后恢复 Stop。繁忙态 Enter 设置为普通 Session 与可继续 child 选择 Queue 或 Steer 投递,运行中的 Send 按钮按 plain Enter 解析出的同一模式投递;当它在普通消息草稿上可用(没有待上传文件)时,其标签以该模式命名(排队发送或插话发送),因此该设置同时约束 Enter 与按钮,而 Cmd/Ctrl+Enter 仍使用另一模式;空闲会话、空草稿与 `/` 命令行保留普通的 Send 标签([决策](../../../.agents/notes/implemented/bug-fix/2026-09-04-busy-send-button-follows-enter-setting.zh.md))。它们的 QueueDock 行共享 Edit、Remove 与 Steer,空草稿也共享 steer-all 组合键。One-shot child 继续只读。Plan Mode 与 active goal 不改变附件入口。可继续 child 保留独立的 Send 与 Stop 操作,但不提供「文件」菜单项、粘贴或拖放入口;parent 离线时,Send 与 composer 手势锁定,但在线 inbox 的 QueueDock 控制仍可使用([决策](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md)、[inbox 控制](../../../.agents/notes/implemented/feature/2026-08-27-continuable-subagent-human-inbox-control.zh.md))。 ## 临时 composer entry diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index e9659e0022..8dc4ba66e1 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -167,6 +167,12 @@ declare module '@deepseek-ai/cordis' { * @mode bail */ 'slash/input-insert-text'(request: InsertTextRequest): true | undefined + /** + * Open the composer's file picker for the scoped session (the menu's + * File row); true when a mounted composer accepting files opened it. + * @mode bail + */ + 'slash/input-pick-files'(): true | undefined } } @@ -282,6 +288,13 @@ export interface ComposerKeyboard { space(): boolean /** Dismiss the popupSelect shell (any interaction outside the box). */ dismissPopup(): void + /** + * Bind the composer's file-picker opener for the scoped pick-files event; + * the composer decides inside `open` whether intake is currently allowed. + * @param open - opens the native file dialog. + * @returns the unbind disposer. + */ + bindFilePicker(open: () => void): () => void } /** One independently addressable row projected from the transient queue snapshot. */ diff --git a/packages/client/ui-conversation/src/client/input/facade.ts b/packages/client/ui-conversation/src/client/input/facade.ts index 1cacd83812..bd162708b7 100644 --- a/packages/client/ui-conversation/src/client/input/facade.ts +++ b/packages/client/ui-conversation/src/client/input/facade.ts @@ -154,6 +154,8 @@ export class SessionInputShell implements SessionInput { private disposed = false /** Draft persistence mirror (Conversation store write; receives the clipboard projection). */ private mirrorFn: ((text: string) => void) | undefined + /** The mounted composer's file-picker opener (scoped pick-files event target). */ + private filePickerFn: (() => void) | undefined /** Live lexicon subscription disposer; undefined until the controller resolves. */ private lexiconOff: (() => void) | undefined /** Default sends retained until admission settles or scope disposal releases their attachments. */ @@ -607,6 +609,28 @@ export class SessionInputShell implements SessionInput { } } + /** + * Bind the composer's file-picker opener (ComposerKeyboard face; unbind on unmount). + * @param open - opens the native file dialog. + * @returns the unbind disposer. + */ + bindFilePicker(open: () => void): () => void { + this.filePickerFn = open + return () => { + if (this.filePickerFn === open) this.filePickerFn = undefined + } + } + + /** + * Open the bound file picker (scoped pick-files event listener body). + * @returns whether a composer was bound to open it. + */ + pickFiles(): boolean { + if (this.filePickerFn === undefined) return false + this.filePickerFn() + return true + } + // ---- effect executor ---- /** The claim token the decoration transform styles; null while unclaimed. */ diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index f255877ddb..a0a974855e 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -121,6 +121,7 @@ export class InputHub implements SessionInputResolver { shell.consumeToken(req.guard) ? true : undefined), actx.on('slash/input-insert-text', req => shell.insertText(req.text, req.span, req.continue === true) ? true : undefined), + actx.on('slash/input-pick-files', () => shell.pickFiles() ? true : undefined), ] return () => { for (const off of offs) off() diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 4aeb755983..a8acc30216 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -19,7 +19,7 @@ export const zh = { 'placeholder.hero': '描述你想要构建的内容, / 调用指令, @ 文件或对话', 'placeholder.workspace': '选择一个工作区开始', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter 插话发送全部排队消息', - 'input.commands': '指令', + 'input.commands': '添加文件或调用指令', 'input.stop': '停止生成', 'input.send': '发送消息', 'input.send.queue': '排队发送', @@ -49,7 +49,6 @@ export const zh = { 'image.dimensionTooLarge': '图片宽高不能超过 {size}px,请缩小后重试', 'image.modelUnsupported': '当前模型不支持图片,请切换支持图片的模型', 'image.sendFailed': '图片发送失败({reason}),请重新添加图片后再试', - 'file.attach': '添加附件', 'file.pending': '待发送文件', 'file.remove': '移除文件 {name}', 'file.uploading': '上传中…', @@ -185,7 +184,7 @@ export const en = { 'placeholder.hero': 'Describe what you want to build, / commands, @ files or sessions', 'placeholder.workspace': 'Choose a workspace to start', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter steers all queued messages', - 'input.commands': 'Commands', + 'input.commands': 'Add files or run commands', 'input.stop': 'Stop generating', 'input.send': 'Send message', 'input.send.queue': 'Queue message', @@ -215,7 +214,6 @@ export const en = { 'image.dimensionTooLarge': 'Image sides must be at most {size}px; downscale it and try again', 'image.modelUnsupported': 'The current model does not support images; switch to a model that does', 'image.sendFailed': 'Sending images failed ({reason}); re-add them and try again', - 'file.attach': 'Add attachment', 'file.pending': 'Pending files', 'file.remove': 'Remove file {name}', 'file.uploading': 'Uploading…', diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index aa37b85ecf..0af8bfa831 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -17,7 +17,7 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { ChangeEvent, CSSProperties, KeyboardEvent, MouseEvent, ReactNode } from 'react' import clsx from 'clsx' import { - IconPaperclipOutline16, IconPlusOutline16, IconWarningOutline16, Toast, Tooltip, + IconPlusOutline16, IconWarningOutline16, Toast, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' // Type-only: the `plan` projection key merge (the TodoDock posture — the // composer reads a host-computed value; the domain owns the key). @@ -266,13 +266,22 @@ export const InputBar = memo(function InputBar({ // registration survives re-renders without re-arming per keystroke. const gate = useRef({ locked, machineBusy, canSteerQueue, running, steeringAvailable, busyEnter, - intakeFiles, uploadsPending, showToast, t, + intakeFiles, uploadsPending, showToast, t, canAcceptDrop, }) gate.current = { locked, machineBusy, canSteerQueue, running, steeringAvailable, busyEnter, - intakeFiles, uploadsPending, showToast, t, + intakeFiles, uploadsPending, showToast, t, canAcceptDrop, } + // The menu's File row opens the same hidden input the drop path feeds, + // under the drop gate the row itself cannot see. + useEffect(() => { + if (keyboard === undefined) return + return keyboard.bindFilePicker(() => { + if (gate.current.canAcceptDrop) fileInputRef.current?.click() + }) + }, [keyboard]) + useEffect(() => { if (editor === null || keyboard === undefined) return return registerComposerKeymap(editor, { @@ -491,18 +500,6 @@ export const InputBar = memo(function InputBar({ - - - { }) it('running continuable subagent keeps Send beside an independent Stop', () => { - const { button, interruptButton, textarea, sink, stop, view, slotCalls } = bench({ + const { button, interruptButton, textarea, sink, stop, view, slotCalls, shell } = bench({ running: true, draft: '后续消息', subagent: { @@ -888,9 +888,13 @@ describe('running and lock semantics', () => { expect(button.getAttribute('aria-label')).toBe('排队发送') expect(interruptButton).not.toBeNull() expect(textarea.getAttribute('aria-disabled')).not.toBe('true') - expect((view.getByLabelText('添加附件') as HTMLButtonElement).disabled).toBe(true) expect(view.container.querySelector('input[type="file"]')?.disabled).toBe(true) expect(attachmentOwner(slotCalls).canAcceptDrop).toBe(false) + // The menu's File row reaches the same gate: a bound picker stays shut. + const click = vi.spyOn(HTMLInputElement.prototype, 'click') + expect(shell.pickFiles()).toBe(true) + expect(click).not.toHaveBeenCalled() + click.mockRestore() fireEvent.click(button) expect(sink).toHaveBeenCalledWith('后续消息', [], 'queue', expect.any(AbortSignal)) fireEvent.click(interruptButton!) @@ -923,10 +927,14 @@ describe('running and lock semantics', () => { ['active goal', { goal: { phase: 'active' as const, objective: 'inspect files' } }], ])('%s keeps ordinary generic-file intake enabled', (_name, projection) => { const added = vi.fn(() => null) - const { view, slotCalls } = bench({ ...projection, addFiles: added }) - expect((view.getByLabelText('添加附件') as HTMLButtonElement).disabled).toBe(false) + const { view, slotCalls, shell } = bench({ ...projection, addFiles: added }) expect(view.container.querySelector('input[type="file"]')?.disabled).toBe(false) expect(attachmentOwner(slotCalls).canAcceptDrop).toBe(true) + // The menu's File row opens the hidden input through the bound picker. + const click = vi.spyOn(HTMLInputElement.prototype, 'click') + expect(shell.pickFiles()).toBe(true) + expect(click).toHaveBeenCalledOnce() + click.mockRestore() }) it('parent-offline running continuable locks Send but keeps independent Stop usable', () => { @@ -944,7 +952,7 @@ describe('running and lock semantics', () => { }) expect(textarea.getAttribute('aria-disabled')).toBe('true') expect(placeholderOf(view.container)).toBe('父会话已离线,无法继续发送;仍可停止当前运行') - expect((view.getByLabelText('指令') as HTMLButtonElement).disabled).toBe(true) + expect((view.getByLabelText('添加文件或调用指令') as HTMLButtonElement).disabled).toBe(true) expect(button.getAttribute('aria-label')).toBe('发送消息') expect(button.disabled).toBe(true) expect(interruptButton?.disabled).toBe(false) @@ -996,7 +1004,7 @@ describe('running and lock semantics', () => { const { textarea, view } = bench({ disabled: true }) expect(textarea.getAttribute('aria-disabled')).toBe('true') expect(placeholderOf(view.container)).toBe('会话不可用') - expect((view.getByLabelText('指令') as HTMLButtonElement).disabled).toBe(true) + expect((view.getByLabelText('添加文件或调用指令') as HTMLButtonElement).disabled).toBe(true) }) it('idle primary sends and disables on empty draft', () => { @@ -1129,7 +1137,7 @@ describe('running and lock semantics', () => { expect(editableOf(textarea)).toBe(false) expect(textarea.getAttribute('aria-haspopup')).toBe('menu') expect(textarea.getAttribute('aria-expanded')).toBe('false') - expect((view.getByLabelText('指令') as HTMLButtonElement).disabled).toBe(true) + expect((view.getByLabelText('添加文件或调用指令') as HTMLButtonElement).disabled).toBe(true) fireEvent.click(textarea) fireEvent.keyDown(textarea, { key: 'Enter' }) @@ -1432,7 +1440,7 @@ describe('strips and variants', () => { describe('command launcher chrome and control seats', () => { it('renders the command launcher; the Access chip is absent without the permissions projection; the control seats render EMPTY without entries', () => { const { view, slotCalls } = bench() - expect(view.getByLabelText('指令')).toBeTruthy() + expect(view.getByLabelText('添加文件或调用指令')).toBeTruthy() // Capability absent (no projection value): the chip renders nothing. expect(view.queryByLabelText(/^访问模式/)).toBeNull() // Every seat dispatched, nothing rendered (render passes may repeat; the @@ -1451,7 +1459,7 @@ describe('command launcher chrome and control seats', () => { const toggleCommandMenu = vi.fn() const { view, shell, menuLauncher } = bench({ draft: 'draft text', toggleCommandMenu }) act(() => { shell.editor.update(() => { $selectDetectSpan({ start: 2, end: 7 }) }, { discrete: true }) }) - const launcher = view.getByLabelText('指令') + const launcher = view.getByLabelText('添加文件或调用指令') expect(launcher.getAttribute('aria-expanded')).toBe('false') fireEvent.click(launcher) expect(toggleCommandMenu).toHaveBeenCalledExactlyOnceWith({ start: 2, end: 7 }) @@ -1621,7 +1629,7 @@ describe('command launcher chrome and control seats', () => { it('disabled locks the Access chip and command launcher (running does not)', () => { const permissions = { options: [{ value: 'workspace-write', name: 'workspace-write' }], currentValue: 'workspace-write' } const { view } = bench({ disabled: true, permissions }) - expect((view.getByLabelText('指令') as HTMLButtonElement).disabled).toBe(true) + expect((view.getByLabelText('添加文件或调用指令') as HTMLButtonElement).disabled).toBe(true) expect((view.getByLabelText(/^访问模式/) as HTMLButtonElement).disabled).toBe(true) cleanup() const live = bench({ running: true, permissions }) diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index c333d25ada..7015645633 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -317,7 +317,7 @@ describe('matrix row: locked (session disabled)', () => { it('disables the textarea and chrome; the machine currency is untouched', () => { const { view, textarea, shell } = bench({ disabled: true }) expect(textarea.getAttribute('aria-disabled')).toBe('true') - expect((view.getByLabelText('指令') as HTMLButtonElement).disabled).toBe(true) + expect((view.getByLabelText('添加文件或调用指令') as HTMLButtonElement).disabled).toBe(true) expect(shell.snapshot.phase).toBe('plain') }) diff --git a/packages/client/ui-input-trigger/README.i18n.yaml b/packages/client/ui-input-trigger/README.i18n.yaml index 61bfb92d3f..20d3a08cf2 100644 --- a/packages/client/ui-input-trigger/README.i18n.yaml +++ b/packages/client/ui-input-trigger/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-input-trigger/README.md -README.md: 9ad568027e4be8f2e9cc641270cbf6b2f870c59c -README.zh.md: 2926eb87d4738387cf6dc56d38a02f579ed267c4 +README.md: 60c96df61d12b9b3051faafb1a38ec18e5280dbe +README.zh.md: 3f9b35d02367f386497facec1319e4fc12a81921 diff --git a/packages/client/ui-input-trigger/README.md b/packages/client/ui-input-trigger/README.md index 9ad568027e..60c96df61d 100644 --- a/packages/client/ui-input-trigger/README.md +++ b/packages/client/ui-input-trigger/README.md @@ -25,7 +25,7 @@ This package powers the input trigger pipeline of the Web GUI: it detects `/` an ## Use this package -Mount this plugin alongside `ui-conversation`; the menu then appears in the input overlay when the user types a trigger under the caret. Grouped candidates render under title rows; a pick routes to the source, and the consuming surface applies the result — a slash command opens its popup or executes, a reference inserts its inline token. +Mount this plugin alongside `ui-conversation`; the menu then appears in the input overlay when the user types a trigger under the caret. Grouped candidates render under title rows, or under the section headings a source attaches to its own rows; a pick routes to the source, and the consuming surface applies the result — a slash command opens its popup or executes, a reference inserts its inline token. A row shows its icon, its title (the candidate `label`, or the `name` when no label is given), the `name` as a trailing alias when the label is not the name in another letter case, and the description right-aligned; a query matches either the name or the label. ### Keyboard and mouse @@ -74,7 +74,6 @@ None; this package neither assembles nor sends a provider request. These limits define the current trigger pipeline. They are current package constraints, not a general menu comparison or a task backlog. - **Global source layer only** — session-scope source registration (per-session shadowing) is designed but not enabled; the ledger tracks the trigger condition, a real per-session source need. -- **`InputTriggerCandidate.icon` renders as text** — `MenuView` drops the string into the icon slot verbatim; wiring to the design-system icon enum lands when that enum ships. - **Overlay SlotMap merge home is split from slot ownership** — the sole `conversation.input.overlay` merge lives here, while ui-conversation owns its anchor, children declaration, and lifecycle because the dependency direction is ui-conversation → ui-input-trigger. diff --git a/packages/client/ui-input-trigger/README.zh.md b/packages/client/ui-input-trigger/README.zh.md index 2926eb87d4..3f9b35d023 100644 --- a/packages/client/ui-input-trigger/README.zh.md +++ b/packages/client/ui-input-trigger/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -与 `ui-conversation` 一起挂载本插件;用户在光标处键入触发器时,菜单随即出现在输入浮层中。分组候选项渲染在标题行之下;pick 路由到 source,消费方表面应用其结果——斜杠命令打开其弹窗或执行,引用插入其行内 token。 +与 `ui-conversation` 一起挂载本插件;用户在光标处键入触发器时,菜单随即出现在输入浮层中。分组候选项渲染在标题行之下,或渲染在 source 附加在自己各行上的小节标题之下;pick 路由到 source,消费方表面应用其结果——斜杠命令打开其弹窗或执行,引用插入其行内 token。每一行显示图标、标题(候选项的 `label`,没有 label 时显示 `name`)、当标题不是 `name` 的另一种大小写写法时跟在标题后的 `name` 别名,以及右对齐的说明;查询同时匹配 name 与 label。 ### 键盘与鼠标 @@ -74,7 +74,6 @@ kind: "package-reference" 这些限制界定了当前触发流水线。它们是当前包约束,不是通用菜单对比或任务积压。 - **只有全局 source 层**——会话 scope 的 source 注册(逐会话遮蔽)已有设计但未启用;台账记录着触发条件,即真实的逐会话 source 需求。 -- **`InputTriggerCandidate.icon` 以文本渲染**——`MenuView` 把该字符串原样放进图标位;与设计系统图标枚举的接入将在该枚举交付后完成。 - **overlay 的 SlotMap 合并归属与槽位所有权分离**——唯一的 `conversation.input.overlay` 合并放在本包,而 ui-conversation 拥有其锚点、children 声明与生命周期,因为依赖方向是 ui-conversation → ui-input-trigger。 diff --git a/packages/client/ui-input-trigger/src/client/MenuView.module.css b/packages/client/ui-input-trigger/src/client/MenuView.module.css index 948bfac52f..4b9280fd4f 100644 --- a/packages/client/ui-input-trigger/src/client/MenuView.module.css +++ b/packages/client/ui-input-trigger/src/client/MenuView.module.css @@ -86,12 +86,26 @@ white-space: nowrap; } +/* The command name beside a localized title, in the description's ink so + the row reads title first. */ +.itemAlias { + flex: none; + max-width: 20%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--dsw-alias-label-tertiary); +} + +/* Right-aligned so every description ends at the same edge and the titles + read as one left column. */ .itemDescription { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + text-align: right; color: var(--dsw-alias-label-tertiary); } diff --git a/packages/client/ui-input-trigger/src/client/MenuView.tsx b/packages/client/ui-input-trigger/src/client/MenuView.tsx index 64be92b20a..2c0fe990a4 100644 --- a/packages/client/ui-input-trigger/src/client/MenuView.tsx +++ b/packages/client/ui-input-trigger/src/client/MenuView.tsx @@ -7,8 +7,10 @@ * rows only while it has none; pointer picks route back through * the service (combobox pattern — focus never leaves the textarea, so rows * are mousedown-handled and the highlight is exposed via - * aria-activedescendant on the listbox). A source publishing crumbs gets a - * breadcrumb header pinned above the scrolling list. + * aria-activedescendant on the listbox). A row reads title, then the + * command-name alias when the title is not the name in another letter case + * (a localized title), then the description right-aligned. A source publishing crumbs gets a breadcrumb + * header pinned above the scrolling list. */ import { Fragment, useEffect, useRef, useSyncExternalStore } from 'react' import clsx from 'clsx' @@ -150,10 +152,15 @@ export function MenuView({ menu, headers, onPick, onCrumb, onHover, onDismiss, t > {item.icon !== undefined && ( - + {typeof item.icon === 'string' + ? + : } )} - {item.name} + {item.label ?? item.name} + {item.label !== undefined && item.label.toLowerCase() !== item.name.toLowerCase() && ( + {item.name} + )} {item.description !== undefined && {item.description}} {item.drill === true && ( diff --git a/packages/client/ui-input-trigger/src/types.ts b/packages/client/ui-input-trigger/src/types.ts index acbe2a65a3..1ac9d4c4de 100644 --- a/packages/client/ui-input-trigger/src/types.ts +++ b/packages/client/ui-input-trigger/src/types.ts @@ -7,9 +7,11 @@ * never a Cordis context or the mutable Session. RPC and service access go * through the provider plugin's own root context captured at registration. */ +import type { ComponentType } from 'react' import type { PickOutcome, TokenSpan, } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { IconProps } from '@deepseek-ai/dsh-client-ui-primitives' import type { SessionId } from '@deepseek-ai/dsh-session/types' export type { @@ -40,14 +42,23 @@ export type PickVia = 'menu' | 'space' | 'enter' /** What a pick asks for: resolve the candidate, or drill into it in place. */ export type PickAction = 'pick' | 'drill' -/** Leading glyph token of one menu candidate, mapped to its SVG by the menu view. */ +/** Leading glyph token of one menu candidate, mapped to its reference SVG by the menu view. */ export type InputTriggerCandidateIcon = 'file' | 'folder' | 'session' /** One menu candidate. Pure display data — zero behavior declaration. */ export interface InputTriggerCandidate { + /** Identity: the pick payload, the exact-match key, and the first search key. */ readonly name: string + /** + * Display title; the name itself when absent. A label that is not the + * name in another letter case renders with the name as a trailing alias, + * and every label is the second search key (a localized title stays + * findable by its command name). + */ + readonly label?: string readonly description?: string - readonly icon?: InputTriggerCandidateIcon + /** Reference glyph token, or an icon component from the shared icon set. */ + readonly icon?: InputTriggerCandidateIcon | ComponentType readonly hint?: string /** Optional visual heading shared by adjacent candidates; sectioned groups omit their source-title row. */ readonly section?: string diff --git a/packages/client/ui-input-trigger/tests/menu-view.client.spec.tsx b/packages/client/ui-input-trigger/tests/menu-view.client.spec.tsx index f9912ba1f9..13fe143544 100644 --- a/packages/client/ui-input-trigger/tests/menu-view.client.spec.tsx +++ b/packages/client/ui-input-trigger/tests/menu-view.client.spec.tsx @@ -114,6 +114,26 @@ describe('MenuView', () => { expect(status.children).toHaveLength(2) }) + it('renders a localized label as the title with the name as its alias, an icon component, and the description', () => { + const Glyph = ({ size = 16 }: { size?: number | undefined }) => + mount(openState({ + groups: [{ + source: 'command', + status: 'ready', + items: [ + { name: 'plan', label: '计划', description: '进入或退出计划模式', icon: Glyph, section: '添加' }, + { name: 'file', label: 'File', section: '添加' }, + ], + }], + })) + const options = screen.getAllByRole('option') + expect(options.map(o => o.textContent)).toEqual(['计划plan进入或退出计划模式', 'File']) + expect(options[0]?.querySelector('[data-glyph="plan"]')?.getAttribute('width')).toBe('16') + // A label that is the name in another letter case renders no alias. + expect(options[1]?.querySelectorAll('span')).toHaveLength(1) + expect(screen.getAllByText('添加')).toHaveLength(1) + }) + it('keeps an opted-out source title hidden while its candidates are pending', () => { mount(openState({ groups: [{ source: 'reference', showGroupTitle: false, status: 'pending', items: [] }], diff --git a/packages/client/ui-model-selection/src/client/index.ts b/packages/client/ui-model-selection/src/client/index.ts index dd7d4a89fd..01a7f227bb 100644 --- a/packages/client/ui-model-selection/src/client/index.ts +++ b/packages/client/ui-model-selection/src/client/index.ts @@ -22,6 +22,7 @@ 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 { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import { IconDataOutline16 } from '@deepseek-ai/dsh-client-ui-primitives' import type { ModelDirectoryState } from './directory.ts' import { ModelDirectoryResolver } from './service.ts' import type { ModelSelectInjected } from './slots.ts' @@ -120,16 +121,16 @@ export function apply(ctx: ClientContext): void { // a locale change reaches the next publish. ctx.plugin(ModelDirectoryResolver, { blockReason: () => t('blocked.composer') }) - // Entry 1: the /model popupSelect over the shared directory. The command - // description is registry-held text: it reads t() once at registration and - // refreshes only on re-registration, not on locale change. + // Entry 1: the /model popupSelect over the shared directory. ctx.inject(['commandUi', 'modelDirectories'], (scope: ClientContext) => { const command = scope.get('commandUi') as CommandUiContract const models = scope.modelDirectories const sessions = scope.sessions scope.effect(() => command.register({ name: 'model', - description: t('command.description'), + label: () => t('command.label'), + description: () => t('command.description'), + icon: IconDataOutline16, available: session => sessions.subagentAddress(session.sessionId) === undefined, ui: { kind: 'popupSelect', diff --git a/packages/client/ui-model-selection/src/client/locales.ts b/packages/client/ui-model-selection/src/client/locales.ts index 3bf0774679..7a6a1b7d12 100644 --- a/packages/client/ui-model-selection/src/client/locales.ts +++ b/packages/client/ui-model-selection/src/client/locales.ts @@ -10,6 +10,7 @@ /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { + 'command.label': '模型', 'command.description': '选择本会话使用的模型', 'option.loadError': '目录加载失败:{message}', 'trigger.fallback': '选择模型', @@ -35,6 +36,7 @@ export type ModelKey = keyof typeof zh /** English dictionary, checked complete against the zh key set. */ export const en = { + 'command.label': 'Model', 'command.description': 'Select the model for this conversation', 'option.loadError': 'Catalog failed to load: {message}', 'trigger.fallback': 'Select model', diff --git a/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts b/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts index 1bf11733b5..7ffec18497 100644 --- a/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-model-selection/tests/browser-plugin.client.spec.ts @@ -16,7 +16,7 @@ import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime' import type { ModelSelection, ModelSelectionProjection } from '@deepseek-ai/dsh-api-session-controller/types' -import type { CommandContribution, SelectOption } from '@deepseek-ai/dsh-client-ui-commands/client' +import type { CommandContribution, PopupSelectSpec, SelectOption } from '@deepseek-ai/dsh-client-ui-commands/client' import type { ModelSelectInjected } from '../src/client/slots.ts' import { apply, inject } from '../src/client/index.ts' import { zh } from '../src/client/locales.ts' @@ -157,6 +157,11 @@ async function bench() { return { ctx, fiber, mint, calls, remote, contribution: () => contribution!, + popup: (): PopupSelectSpec => { + const ui = contribution!.ui + if (ui.kind !== 'popupSelect') throw new Error('expected the popupSelect kind') + return ui + }, seat: () => seats.get('conversation.input.model')!, hostCurrent: () => selected, setHostCurrent: (selection: ModelSelection) => { defaultSelection = selection }, @@ -182,7 +187,7 @@ describe('ui-model-selection dual entry', () => { it('popup options mark the host current active with the provider group in the detail', async () => { const b = await bench() b.mint('s1') - const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal) + const options = await b.popup().options(projection('s1'), new AbortController().signal) expect(options.map((o: SelectOption) => o.label)).toEqual(['DeepSeek-V4-Flash', 'DeepSeek-V4-Pro']) expect(options[0]).toMatchObject({ active: true, detail: 'DeepSeek' }) expect(options[1]?.active).toBeUndefined() @@ -209,7 +214,7 @@ describe('ui-model-selection dual entry', () => { reasoningEffort: 'max', }) // The POPUP's next options pass reflects it without a seat-side reload. - const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal) + const options = await b.popup().options(projection('s1'), new AbortController().signal) expect(options.find((o: SelectOption) => o.label === 'DeepSeek-V4-Pro')).toMatchObject({ active: true }) }) @@ -217,9 +222,9 @@ describe('ui-model-selection dual entry', () => { const b = await bench() b.mint('s1') const seatFace = b.seat().inject!(sid('s1')) - const options = await b.contribution().ui.options(projection('s1'), new AbortController().signal) + const options = await b.popup().options(projection('s1'), new AbortController().signal) const pro = options.find((o: SelectOption) => o.label === 'DeepSeek-V4-Pro')! - await b.contribution().ui.onSelect(pro, projection('s1')) + await b.popup().onSelect(pro, projection('s1')) expect(seatFace.directory.getSnapshot().current).toEqual({ provider: 'deepseek-official', model: 'deepseek-v4-pro', @@ -239,8 +244,8 @@ describe('ui-model-selection dual entry', () => { // The service face resolves the same instance the seat inject handed out. expect(b.ctx.modelDirectories.directoryFor(sid('a')).store).toBe(faceA.directory) await Promise.all([ - b.contribution().ui.options(projection('a'), new AbortController().signal), - b.contribution().ui.options(projection('b'), new AbortController().signal), + b.popup().options(projection('a'), new AbortController().signal), + b.popup().options(projection('b'), new AbortController().signal), ]) expect(b.calls.models).toBe(1) }) @@ -369,7 +374,7 @@ describe('ui-model-selection dual entry', () => { b.address(sid('child')) expect(b.contribution().available(projection('child'))).toBe(false) - await expect(b.contribution().ui.options( + await expect(b.popup().options( projection('child'), new AbortController().signal, )).rejects.toThrow(/unavailable for addressed subagent/) diff --git a/packages/client/ui-permission-presets/tests/browser-plugin.client.spec.ts b/packages/client/ui-permission-presets/tests/browser-plugin.client.spec.ts index e6f9cd39f8..f802b93b2d 100644 --- a/packages/client/ui-permission-presets/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-permission-presets/tests/browser-plugin.client.spec.ts @@ -15,7 +15,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { TestRemote, scriptedSettingsRemote } from '@deepseek-ai/dsh-client-test-runtime' import { apply as settingsApply, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client' -import type { CommandDecoration } from '@deepseek-ai/dsh-client-ui-commands/client' +import type { CommandDecoration, PopupSelectSpec } from '@deepseek-ai/dsh-client-ui-commands/client' import type { PermissionSelect } from '@deepseek-ai/dsh-permission-presets/client' import { PermissionRow, type PermissionRowInjected, @@ -82,6 +82,11 @@ async function bench() { ctx, fiber, locale, values, commands, remote, setResult: (r: { ok: boolean; matched?: boolean }) => { commandResult = r }, decoration: () => decoration, + popup: (): PopupSelectSpec => { + const ui = decoration!.ui + if (ui.kind !== 'popupSelect') throw new Error('expected the popupSelect kind') + return ui + }, permissionRow: () => ctx.slots.entries('settings.general.item') .find(entry => entry.component === PermissionRow), } @@ -110,11 +115,11 @@ describe('ui-permission browser plugin', () => { expect(c.available(proj)).toBe(false) b.values.set(sid('s1'), { ...SELECT, options: [...SELECT.options, { value: 'custom', name: 'Custom' }], currentValue: 'custom' }) expect(c.available(proj)).toBe(true) - const options = await c.ui.options(proj, new AbortController().signal) + const options = await b.popup().options(proj, new AbortController().signal) expect(options.map(option => option.id)).toEqual(['read-only', 'workspace-write', 'danger-full-access']) expect(options.every(option => option.active !== true)).toBe(true) b.values.set(sid('s1'), SELECT) - const again = await c.ui.options(proj, new AbortController().signal) + const again = await b.popup().options(proj, new AbortController().signal) expect(again.find(option => option.id === 'workspace-write')?.active).toBe(true) expect(again.find(option => option.id === 'read-only')?.detail).toBe('Reads only.') // English built-ins use product labels; other kebab-case names title-case. @@ -127,7 +132,7 @@ describe('ui-permission browser plugin', () => { confirmLabel: 'Enable Full access', }) b.locale.setLocale('zh') - const localized = await c.ui.options(proj, new AbortController().signal) + const localized = await b.popup().options(proj, new AbortController().signal) expect(localized.map(option => option.label)).toEqual(['仅可查看', '工作区内修改', '完全权限']) expect(localized.find(option => option.id === 'danger-full-access')?.confirmation).toEqual({ title: '确认启用完全权限?', @@ -143,28 +148,27 @@ describe('ui-permission browser plugin', () => { { value: '__proto__', name: '__proto__' }, { value: 'plain', name: 'Ask Every Time' }, ] }) - const passthrough = await c.ui.options(proj, new AbortController().signal) + const passthrough = await b.popup().options(proj, new AbortController().signal) expect(passthrough.map(option => option.label)).toEqual([ 'Project Files', 'Operator Mode', 'Custom Mode', '__proto__', 'Ask Every Time', ]) // A projection that vanished between availability and open throws. - expect(() => c.ui.options({ sessionId: sid('ghost') }, new AbortController().signal)) + expect(() => b.popup().options({ sessionId: sid('ghost') }, new AbortController().signal)) .toThrow(/not available on this host/) }) it('a pick submits the /permission line; rejection and unmatched throw', async () => { const b = await bench() - const c = b.decoration()! const proj = { sessionId: sid('s1') } b.values.set(sid('s1'), SELECT) - await c.ui.onSelect({ id: 'danger-full-access', label: 'danger-full-access' }, proj) + await b.popup().onSelect({ id: 'danger-full-access', label: 'danger-full-access' }, proj) expect(b.commands).toEqual(['/permission danger-full-access']) b.setResult({ ok: false }) - await expect(c.ui.onSelect({ id: 'read-only', label: 'read-only' }, proj)).rejects.toThrow(/permission switch failed/) + await expect(b.popup().onSelect({ id: 'read-only', label: 'read-only' }, proj)).rejects.toThrow(/permission switch failed/) b.setResult({ ok: true, matched: false }) - await expect(c.ui.onSelect({ id: 'read-only', label: 'read-only' }, proj)).rejects.toThrow(/no \/permission command/) + await expect(b.popup().onSelect({ id: 'read-only', label: 'read-only' }, proj)).rejects.toThrow(/no \/permission command/) // An unmaterialized session throws before any submit. - await expect(c.ui.onSelect({ id: 'read-only', label: 'read-only' }, { sessionId: sid('ghost') })) + await expect(b.popup().onSelect({ id: 'read-only', label: 'read-only' }, { sessionId: sid('ghost') })) .rejects.toThrow(/not materialized/) }) diff --git a/packages/client/ui-primitives/src/rank-by-name.ts b/packages/client/ui-primitives/src/rank-by-name.ts index 7dc3b3a0cc..2f7bdd880f 100644 --- a/packages/client/ui-primitives/src/rank-by-name.ts +++ b/packages/client/ui-primitives/src/rank-by-name.ts @@ -1,8 +1,9 @@ /** * Shared ranking for `/` menu candidates: the query must be a - * case-insensitive ordered subsequence of the candidate name. Prefix hits - * rank first, then the strongest alignment score, then the source order of - * the input. Decision record: + * case-insensitive ordered subsequence of the candidate name or, when the + * candidate carries one, of its display label (a localized title). Prefix + * hits rank first, then the strongest alignment score over either key, then + * the source order of the input. Decision record: * .agents/notes/archived/feature/2026-08-04-web-slash-command-fuzzy-discovery.md */ @@ -59,19 +60,32 @@ function alignmentScore(name: string, query: string): number | undefined { /** * Rank named items by a menu query. - * @param items - candidates in source order (a host catalog, then client contributions). + * @param items - candidates in source order (a host catalog, then client + * contributions); an item's optional `label` is a second search key beside + * its name. * @param rawQuery - the text typed after the trigger, matched case-insensitively. * @returns the matching items: prefix hits first, then by alignment score, * then in source order. The input list itself for an empty query. */ -export function rankByName(items: readonly T[], rawQuery: string): readonly T[] { +export function rankByName( + items: readonly T[], + rawQuery: string, +): readonly T[] { const query = rawQuery.toLowerCase() if (query === '') return items const ranked: Ranked[] = [] items.forEach((item, index) => { - const name = item.name.toLowerCase() - const score = alignmentScore(name, query) - if (score !== undefined) ranked.push({ item, index, prefix: name.startsWith(query), score }) + const keys = item.label === undefined ? [item.name] : [item.name, item.label] + let prefix = false + let score: number | undefined + for (const key of keys) { + const lower = key.toLowerCase() + const keyScore = alignmentScore(lower, query) + if (keyScore === undefined) continue + prefix ||= lower.startsWith(query) + score = score === undefined ? keyScore : Math.max(score, keyScore) + } + if (score !== undefined) ranked.push({ item, index, prefix, score }) }) ranked.sort((left, right) => Number(right.prefix) - Number(left.prefix) || right.score - left.score || left.index - right.index) diff --git a/packages/client/ui-primitives/tests/rank-by-name.client.spec.ts b/packages/client/ui-primitives/tests/rank-by-name.client.spec.ts index 89ed5c7733..027fbb4958 100644 --- a/packages/client/ui-primitives/tests/rank-by-name.client.spec.ts +++ b/packages/client/ui-primitives/tests/rank-by-name.client.spec.ts @@ -34,6 +34,20 @@ describe('rankByName', () => { expect(names(rankByName(named('aab', 'ab'), 'ab'))).toEqual(['ab', 'aab']) }) + it('matches the display label as a second key and keeps the stronger alignment', () => { + const items = [ + { name: 'goal', label: '目标' }, + { name: 'plan', label: '计划' }, + { name: 'permission', label: '权限' }, + ] + expect(names(rankByName(items, '目标'))).toEqual(['goal']) + expect(names(rankByName(items, 'goal'))).toEqual(['goal']) + expect(names(rankByName(items, 'p'))).toEqual(['plan', 'permission']) + expect(names(rankByName(items, '划'))).toEqual(['plan']) + // A label prefix hit ranks like a name prefix hit. + expect(names(rankByName([{ name: 'xplan', label: 'plan' }, { name: 'plant' }], 'pla'))).toEqual(['xplan', 'plant']) + }) + it('returns the ranked items with their payload intact', () => { const items = [{ name: 'goal', description: 'g' }, { name: 'plan', description: 'p' }] expect(rankByName(items, 'pl')).toEqual([{ name: 'plan', description: 'p' }]) diff --git a/packages/feedback/command-feedback/src/index.ts b/packages/feedback/command-feedback/src/index.ts index ef840fe9c8..771b8c6f69 100644 --- a/packages/feedback/command-feedback/src/index.ts +++ b/packages/feedback/command-feedback/src/index.ts @@ -60,7 +60,7 @@ function executeFeedbackCommand(invocation: CommandInvocation): CommandResult { export function apply(ctx: Context): void { ctx.commands.register({ name: 'feedback', - description: 'record feedback about this session', + description: 'Record feedback about this session', input: { hint: '' }, recordInput: false, handler: executeFeedbackCommand, diff --git a/packages/feedback/command-feedback/tests/command-feedback.spec.ts b/packages/feedback/command-feedback/tests/command-feedback.spec.ts index e59020bfc6..f9669bbf44 100644 --- a/packages/feedback/command-feedback/tests/command-feedback.spec.ts +++ b/packages/feedback/command-feedback/tests/command-feedback.spec.ts @@ -89,7 +89,7 @@ describe('@deepseek-ai/dsh-command-feedback registration', () => { expect(test.ctx.commands.list(test.agent)).toContainEqual({ name: 'feedback', - description: 'record feedback about this session', + description: 'Record feedback about this session', input: { hint: '' }, }) expect(test.ctx.commands.find(test.agent, 'feedback')).toMatchObject({ recordInput: false }) diff --git a/packages/goal/command-goal/src/index.ts b/packages/goal/command-goal/src/index.ts index b9e64ee7f2..4251ea72a2 100644 --- a/packages/goal/command-goal/src/index.ts +++ b/packages/goal/command-goal/src/index.ts @@ -189,7 +189,7 @@ function executeGoalCommand(ctx: Context, invocation: CommandInvocation): Comman export function apply(ctx: Context): void { ctx.commands.register({ name: 'goal', - description: 'set or view the goal for a long-running task', + description: 'Set or view the goal for a long-running task', input: { hint: '[|clear|edit |pause|resume]', attachments: true }, handler: invocation => executeGoalCommand(ctx, invocation), }) diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index 1c1761cf74..a8728b0ed1 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -99,7 +99,7 @@ describe('@deepseek-ai/dsh-command-goal registration', () => { expect(test.ctx.commands.list(test.agent)).toContainEqual({ name: 'goal', - description: 'set or view the goal for a long-running task', + description: 'Set or view the goal for a long-running task', input: { hint: '[|clear|edit |pause|resume]', attachments: true }, }) expect(test.ctx.commands.find(test.agent, 'goal')).toBeDefined() diff --git a/snapshots/web/bash-abort-row/ui.expected.md b/snapshots/web/bash-abort-row/ui.expected.md index 4af682fdb2..e41e520238 100644 --- a/snapshots/web/bash-abort-row/ui.expected.md +++ b/snapshots/web/bash-abort-row/ui.expected.md @@ -29,9 +29,7 @@ - img - text: "Failed Bash Error: tool call aborted before dispatch" - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Full access"': Full access - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/cordis-tool-round/ui.expected.md b/snapshots/web/cordis-tool-round/ui.expected.md index aa741273ff..3d9a16da72 100644 --- a/snapshots/web/cordis-tool-round/ui.expected.md +++ b/snapshots/web/cordis-tool-round/ui.expected.md @@ -117,9 +117,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/feedback-command/ack-expanded.expected.md b/snapshots/web/feedback-command/ack-expanded.expected.md index 6939707ba4..053c709e1f 100644 --- a/snapshots/web/feedback-command/ack-expanded.expected.md +++ b/snapshots/web/feedback-command/ack-expanded.expected.md @@ -47,9 +47,7 @@ - img - text: "feedback Feedback recorded for session session-{{uuid}} Anonymous user: {{uuid}}." - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/feedback-command/ack.expected.md b/snapshots/web/feedback-command/ack.expected.md index 75bd8bad1b..885b063af6 100644 --- a/snapshots/web/feedback-command/ack.expected.md +++ b/snapshots/web/feedback-command/ack.expected.md @@ -39,9 +39,7 @@ - img - text: "feedback Feedback recorded for session session-{{uuid}} Anonymous user: {{uuid}}." - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/feedback-release/ack-expanded.expected.md b/snapshots/web/feedback-release/ack-expanded.expected.md index 6939707ba4..053c709e1f 100644 --- a/snapshots/web/feedback-release/ack-expanded.expected.md +++ b/snapshots/web/feedback-release/ack-expanded.expected.md @@ -47,9 +47,7 @@ - img - text: "feedback Feedback recorded for session session-{{uuid}} Anonymous user: {{uuid}}." - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/feedback-release/ack.expected.md b/snapshots/web/feedback-release/ack.expected.md index 75bd8bad1b..885b063af6 100644 --- a/snapshots/web/feedback-release/ack.expected.md +++ b/snapshots/web/feedback-release/ack.expected.md @@ -39,9 +39,7 @@ - img - text: "feedback Feedback recorded for session session-{{uuid}} Anonymous user: {{uuid}}." - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/file-upload-round/ui.expected.md b/snapshots/web/file-upload-round/ui.expected.md index cbddcb3d63..676caf3bd4 100644 --- a/snapshots/web/file-upload-round/ui.expected.md +++ b/snapshots/web/file-upload-round/ui.expected.md @@ -41,9 +41,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash-Vision-Exp, reasoning effort high": diff --git a/snapshots/web/fresh-round-trip/ui-expanded.expected.md b/snapshots/web/fresh-round-trip/ui-expanded.expected.md index 0d877cc2e6..45a27897bf 100644 --- a/snapshots/web/fresh-round-trip/ui-expanded.expected.md +++ b/snapshots/web/fresh-round-trip/ui-expanded.expected.md @@ -51,9 +51,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/fresh-round-trip/ui.expected.md b/snapshots/web/fresh-round-trip/ui.expected.md index 61079e8d61..08dedf0100 100644 --- a/snapshots/web/fresh-round-trip/ui.expected.md +++ b/snapshots/web/fresh-round-trip/ui.expected.md @@ -35,9 +35,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md b/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md index c88d6d3c40..5783ef6a23 100644 --- a/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md +++ b/snapshots/web/goal-multi-turn-actions/ui-expanded.expected.md @@ -229,9 +229,7 @@ - button "Back to bottom": - img - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/goal-multi-turn-actions/ui.expected.md b/snapshots/web/goal-multi-turn-actions/ui.expected.md index bcd881ffef..1d731cceaa 100644 --- a/snapshots/web/goal-multi-turn-actions/ui.expected.md +++ b/snapshots/web/goal-multi-turn-actions/ui.expected.md @@ -117,9 +117,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/lifecycle-chrome/command-menu-fuzzy.expected.md b/snapshots/web/lifecycle-chrome/command-menu-fuzzy.expected.md index 13d915959d..96bf4bd119 100644 --- a/snapshots/web/lifecycle-chrome/command-menu-fuzzy.expected.md +++ b/snapshots/web/lifecycle-chrome/command-menu-fuzzy.expected.md @@ -1,3 +1,3 @@ - listbox "Trigger suggestions": - text: Commands - - option "compact Compact older conversation history" [selected] + - option "Compact Compact older conversation history" [selected] diff --git a/snapshots/web/lifecycle-chrome/command-menu.expected.md b/snapshots/web/lifecycle-chrome/command-menu.expected.md index ed7e837f3f..c720fee9e1 100644 --- a/snapshots/web/lifecycle-chrome/command-menu.expected.md +++ b/snapshots/web/lifecycle-chrome/command-menu.expected.md @@ -1,9 +1,11 @@ - listbox "Trigger suggestions": + - text: Add + - option "File" [selected] + - option "Goal Set or view the goal for a long-running task" + - option "Plan Enter or leave plan mode" + - option "Feedback Record feedback about this session" - text: Commands - - option "compact Compact older conversation history" [selected] - - option "export Download this Session log as a ZIP archive" - - option "feedback record feedback about this session" - - option "goal set or view the goal for a long-running task" - - option "permission Switch the permission preset (sandbox mode + approval policy)" - - option "plan Enter or leave plan mode" - - option "model Select the model for this conversation" + - option "Compact Compact older conversation history" + - option "Permission Switch the permission preset (sandbox mode + approval policy)" + - option "Model Select the model for this conversation" + - option "Export Download this Session log as a ZIP archive" diff --git a/snapshots/web/lifecycle-chrome/hero.expected.md b/snapshots/web/lifecycle-chrome/hero.expected.md index aa7c6a7728..7c5a8b7f98 100644 --- a/snapshots/web/lifecycle-chrome/hero.expected.md +++ b/snapshots/web/lifecycle-chrome/hero.expected.md @@ -31,9 +31,7 @@ - img - textbox "Describe what you want to build, / commands, @ files or sessions": - paragraph -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/lifecycle-chrome/plan-active.expected.md b/snapshots/web/lifecycle-chrome/plan-active.expected.md index bda1b957d8..da4ae2482b 100644 --- a/snapshots/web/lifecycle-chrome/plan-active.expected.md +++ b/snapshots/web/lifecycle-chrome/plan-active.expected.md @@ -30,9 +30,7 @@ - text: Standard mode - img - textbox "Describe what you want to build, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Plan mode on, press to turn off": Plan diff --git a/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md b/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md index f7e902be44..eb812c4193 100644 --- a/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md +++ b/snapshots/web/lifecycle-chrome/reloaded-expanded.expected.md @@ -43,9 +43,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/lifecycle-chrome/reloaded.expected.md b/snapshots/web/lifecycle-chrome/reloaded.expected.md index 47c78b4156..e44a7f6a62 100644 --- a/snapshots/web/lifecycle-chrome/reloaded.expected.md +++ b/snapshots/web/lifecycle-chrome/reloaded.expected.md @@ -35,9 +35,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/live-interactions/cancel-expanded.expected.md b/snapshots/web/live-interactions/cancel-expanded.expected.md index 906f3a9ed3..cbf5e8af58 100644 --- a/snapshots/web/live-interactions/cancel-expanded.expected.md +++ b/snapshots/web/live-interactions/cancel-expanded.expected.md @@ -40,9 +40,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/live-interactions/cancel.expected.md b/snapshots/web/live-interactions/cancel.expected.md index d50dc2c162..5529b89440 100644 --- a/snapshots/web/live-interactions/cancel.expected.md +++ b/snapshots/web/live-interactions/cancel.expected.md @@ -36,9 +36,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/live-interactions/error-auth.expected.md b/snapshots/web/live-interactions/error-auth.expected.md index d6cd35dcb3..6df10863c4 100644 --- a/snapshots/web/live-interactions/error-auth.expected.md +++ b/snapshots/web/live-interactions/error-auth.expected.md @@ -26,9 +26,7 @@ - text: This turn failedAPI key is invalid - code: AUTH - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/live-interactions/loading.expected.md b/snapshots/web/live-interactions/loading.expected.md index 3dfa3da484..4cb2835f8a 100644 --- a/snapshots/web/live-interactions/loading.expected.md +++ b/snapshots/web/live-interactions/loading.expected.md @@ -25,9 +25,7 @@ - paragraph: partial - status: Deep diving... - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/live-interactions/retry-exhausted.expected.md b/snapshots/web/live-interactions/retry-exhausted.expected.md index a9c40b178e..3995103b95 100644 --- a/snapshots/web/live-interactions/retry-exhausted.expected.md +++ b/snapshots/web/live-interactions/retry-exhausted.expected.md @@ -28,9 +28,7 @@ - text: This turn failedupstream 503 - code: SERVER - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/live-interactions/retry-expanded.expected.md b/snapshots/web/live-interactions/retry-expanded.expected.md index 6c3591cc67..4c959a711a 100644 --- a/snapshots/web/live-interactions/retry-expanded.expected.md +++ b/snapshots/web/live-interactions/retry-expanded.expected.md @@ -45,9 +45,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/live-interactions/retry.expected.md b/snapshots/web/live-interactions/retry.expected.md index 21ce478e78..996c067e9e 100644 --- a/snapshots/web/live-interactions/retry.expected.md +++ b/snapshots/web/live-interactions/retry.expected.md @@ -35,9 +35,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/live-interactions/running-draft.expected.md b/snapshots/web/live-interactions/running-draft.expected.md index 505805bc35..b0427febf7 100644 --- a/snapshots/web/live-interactions/running-draft.expected.md +++ b/snapshots/web/live-interactions/running-draft.expected.md @@ -26,9 +26,7 @@ - status: Deep diving... - textbox "Message or run a task, / commands, @ files or sessions": - paragraph: Queue this follow-up while the current turn is running. -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/message-actions/ui.expected.md b/snapshots/web/message-actions/ui.expected.md index 58ae5e04f7..37360d44eb 100644 --- a/snapshots/web/message-actions/ui.expected.md +++ b/snapshots/web/message-actions/ui.expected.md @@ -65,9 +65,7 @@ - text: Ran for {{duration}} - text: 7/25 {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/minimal-preset/ui.expected.md b/snapshots/web/minimal-preset/ui.expected.md index 9ad6fdf256..214dae5e98 100644 --- a/snapshots/web/minimal-preset/ui.expected.md +++ b/snapshots/web/minimal-preset/ui.expected.md @@ -40,9 +40,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/plan-review/approved-expanded.expected.md b/snapshots/web/plan-review/approved-expanded.expected.md index 43c4b97487..4ce1ce35b0 100644 --- a/snapshots/web/plan-review/approved-expanded.expected.md +++ b/snapshots/web/plan-review/approved-expanded.expected.md @@ -61,9 +61,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/plan-review/approved.expected.md b/snapshots/web/plan-review/approved.expected.md index c04fb13bad..2cd2060efa 100644 --- a/snapshots/web/plan-review/approved.expected.md +++ b/snapshots/web/plan-review/approved.expected.md @@ -41,9 +41,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/ptc-round/ui.expected.md b/snapshots/web/ptc-round/ui.expected.md index 94727a92fe..c97a610ec9 100644 --- a/snapshots/web/ptc-round/ui.expected.md +++ b/snapshots/web/ptc-round/ui.expected.md @@ -62,9 +62,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/question-composer/answered-expanded.expected.md b/snapshots/web/question-composer/answered-expanded.expected.md index a57598a5c3..55705b01be 100644 --- a/snapshots/web/question-composer/answered-expanded.expected.md +++ b/snapshots/web/question-composer/answered-expanded.expected.md @@ -53,9 +53,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/question-composer/answered.expected.md b/snapshots/web/question-composer/answered.expected.md index 7d7da25ef6..d8aa619f77 100644 --- a/snapshots/web/question-composer/answered.expected.md +++ b/snapshots/web/question-composer/answered.expected.md @@ -35,9 +35,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/question-composer/cancelled.expected.md b/snapshots/web/question-composer/cancelled.expected.md index d23da91aed..344aaacc60 100644 --- a/snapshots/web/question-composer/cancelled.expected.md +++ b/snapshots/web/question-composer/cancelled.expected.md @@ -32,9 +32,7 @@ - listitem: Which color do you prefer? - button "Inspect" - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/queue-actions/collapsed.expected.md b/snapshots/web/queue-actions/collapsed.expected.md index 6645c331fd..fad1b9caa0 100644 --- a/snapshots/web/queue-actions/collapsed.expected.md +++ b/snapshots/web/queue-actions/collapsed.expected.md @@ -26,9 +26,7 @@ - status: Deep diving... - button "2 queued messages" - textbox "Cmd/Ctrl+Enter steers all queued messages" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/queue-actions/editing.expected.md b/snapshots/web/queue-actions/editing.expected.md index d0586fb967..be5272ae75 100644 --- a/snapshots/web/queue-actions/editing.expected.md +++ b/snapshots/web/queue-actions/editing.expected.md @@ -42,9 +42,7 @@ - button "Cancel editing": - img - textbox "Cmd/Ctrl+Enter steers all queued messages" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/queue-actions/failed.expected.md b/snapshots/web/queue-actions/failed.expected.md index 02c1fa881b..044a159013 100644 --- a/snapshots/web/queue-actions/failed.expected.md +++ b/snapshots/web/queue-actions/failed.expected.md @@ -1,9 +1,7 @@ - alert: Queue submission failed (session/agent-busy) - textbox "Message or run a task, / commands, @ files or sessions": - paragraph: Queue submission to retry -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/queue-actions/layout.expected.md b/snapshots/web/queue-actions/layout.expected.md index 79f239edd8..586db15583 100644 --- a/snapshots/web/queue-actions/layout.expected.md +++ b/snapshots/web/queue-actions/layout.expected.md @@ -42,9 +42,7 @@ - img - button "2 queued messages" - textbox "Cmd/Ctrl+Enter steers all queued messages" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/queue-actions/preserved-expanded.expected.md b/snapshots/web/queue-actions/preserved-expanded.expected.md index 6e9d8c1134..1bb442434c 100644 --- a/snapshots/web/queue-actions/preserved-expanded.expected.md +++ b/snapshots/web/queue-actions/preserved-expanded.expected.md @@ -59,9 +59,7 @@ - button "Steer queued message" [disabled]: - img - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/queue-actions/preserved.expected.md b/snapshots/web/queue-actions/preserved.expected.md index a4547ed17d..ed0b3e98d0 100644 --- a/snapshots/web/queue-actions/preserved.expected.md +++ b/snapshots/web/queue-actions/preserved.expected.md @@ -55,9 +55,7 @@ - button "Steer queued message" [disabled]: - img - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/queue-actions/sending.expected.md b/snapshots/web/queue-actions/sending.expected.md index d2b2a0d9de..1bfaba53f8 100644 --- a/snapshots/web/queue-actions/sending.expected.md +++ b/snapshots/web/queue-actions/sending.expected.md @@ -35,9 +35,7 @@ - button "Steer queued message" [disabled]: - img - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/queue-actions/ui.expected.md b/snapshots/web/queue-actions/ui.expected.md index e7aa55934d..4cbf81a164 100644 --- a/snapshots/web/queue-actions/ui.expected.md +++ b/snapshots/web/queue-actions/ui.expected.md @@ -35,9 +35,7 @@ - button "Steer queued message": - img - textbox "Cmd/Ctrl+Enter steers all queued messages" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/queued-image/delivered.expected.md b/snapshots/web/queued-image/delivered.expected.md index 7ea64dd0f6..da192e1ff5 100644 --- a/snapshots/web/queued-image/delivered.expected.md +++ b/snapshots/web/queued-image/delivered.expected.md @@ -79,9 +79,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/queued-image/queued.expected.md b/snapshots/web/queued-image/queued.expected.md index 68d4ef90b7..13652ebae5 100644 --- a/snapshots/web/queued-image/queued.expected.md +++ b/snapshots/web/queued-image/queued.expected.md @@ -35,9 +35,7 @@ - button "Steer queued message": - img - textbox "Cmd/Ctrl+Enter steers all queued messages" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/seeded-history/command-row.expected.md b/snapshots/web/seeded-history/command-row.expected.md index 527ad8658a..56d3886be4 100644 --- a/snapshots/web/seeded-history/command-row.expected.md +++ b/snapshots/web/seeded-history/command-row.expected.md @@ -61,9 +61,7 @@ - img - text: permission preset read-only - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Read Only"': Read Only - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/seeded-history/feedback-row.expected.md b/snapshots/web/seeded-history/feedback-row.expected.md index ba2ac9fd6b..ff6f5e58be 100644 --- a/snapshots/web/seeded-history/feedback-row.expected.md +++ b/snapshots/web/seeded-history/feedback-row.expected.md @@ -65,9 +65,7 @@ - text: "feedback Feedback recorded for session {{seededId}} Anonymous user: {{uuid}}." - text: "Feedback recorded for session {{seededId}} Anonymous user: {{uuid}}." - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Read Only"': Read Only - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/seeded-history/ui-expanded.expected.md b/snapshots/web/seeded-history/ui-expanded.expected.md index b655c75182..affe391552 100644 --- a/snapshots/web/seeded-history/ui-expanded.expected.md +++ b/snapshots/web/seeded-history/ui-expanded.expected.md @@ -59,9 +59,7 @@ - img - text: Context injection AGENTS.md - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/seeded-history/ui.expected.md b/snapshots/web/seeded-history/ui.expected.md index 90642e4c58..7590043fe8 100644 --- a/snapshots/web/seeded-history/ui.expected.md +++ b/snapshots/web/seeded-history/ui.expected.md @@ -41,9 +41,7 @@ - img - text: Context injection AGENTS.md - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/skill-tool-row/ui.expected.md b/snapshots/web/skill-tool-row/ui.expected.md index 737d74f2a6..9ab9a4c0ca 100644 --- a/snapshots/web/skill-tool-row/ui.expected.md +++ b/snapshots/web/skill-tool-row/ui.expected.md @@ -54,9 +54,7 @@ - text: Ran for {{duration}} - text: {{date}} {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Full access"': Full access - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/steering/settled-expanded.expected.md b/snapshots/web/steering/settled-expanded.expected.md index fc4fa021e5..8eed39301f 100644 --- a/snapshots/web/steering/settled-expanded.expected.md +++ b/snapshots/web/steering/settled-expanded.expected.md @@ -46,9 +46,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/steering/settled.expected.md b/snapshots/web/steering/settled.expected.md index 0ff456ca8a..9d1e0d15a5 100644 --- a/snapshots/web/steering/settled.expected.md +++ b/snapshots/web/steering/settled.expected.md @@ -38,9 +38,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/subagent-conversation/ui-expanded.expected.md b/snapshots/web/subagent-conversation/ui-expanded.expected.md index 92e5e2c31a..a4ce835db9 100644 --- a/snapshots/web/subagent-conversation/ui-expanded.expected.md +++ b/snapshots/web/subagent-conversation/ui-expanded.expected.md @@ -73,9 +73,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment" [disabled]: +- button "Add files or run commands": - img - 'button "Access mode, current: Custom"': Custom - button "6% of context used" diff --git a/snapshots/web/subagent-conversation/ui.expected.md b/snapshots/web/subagent-conversation/ui.expected.md index ec7b77fe58..181af16fe0 100644 --- a/snapshots/web/subagent-conversation/ui.expected.md +++ b/snapshots/web/subagent-conversation/ui.expected.md @@ -61,9 +61,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment" [disabled]: +- button "Add files or run commands": - img - 'button "Access mode, current: Custom"': Custom - button "6% of context used" diff --git a/snapshots/web/subagent-interrupt/offline-composer.expected.md b/snapshots/web/subagent-interrupt/offline-composer.expected.md index e7f7483bc3..3d7e5e2db6 100644 --- a/snapshots/web/subagent-interrupt/offline-composer.expected.md +++ b/snapshots/web/subagent-interrupt/offline-composer.expected.md @@ -36,9 +36,7 @@ - button "Steer queued message": - img - textbox "Parent session offline; sending is unavailable but you can still stop the run" [disabled] -- button "Commands" [disabled]: - - img -- button "Add attachment" [disabled]: +- button "Add files or run commands" [disabled]: - img - 'button "Access mode, current: Custom" [disabled]': Custom - button "Stop generating" diff --git a/snapshots/web/turn-tail-actions/completed.expected.md b/snapshots/web/turn-tail-actions/completed.expected.md index 4f9b0b72f3..c108cda33d 100644 --- a/snapshots/web/turn-tail-actions/completed.expected.md +++ b/snapshots/web/turn-tail-actions/completed.expected.md @@ -38,9 +38,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/turn-tail-actions/focused.expected.md b/snapshots/web/turn-tail-actions/focused.expected.md index 2108bafd30..6cb8a8c450 100644 --- a/snapshots/web/turn-tail-actions/focused.expected.md +++ b/snapshots/web/turn-tail-actions/focused.expected.md @@ -51,9 +51,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/turn-tail-actions/running.expected.md b/snapshots/web/turn-tail-actions/running.expected.md index d4fced7fe3..a76a077206 100644 --- a/snapshots/web/turn-tail-actions/running.expected.md +++ b/snapshots/web/turn-tail-actions/running.expected.md @@ -35,9 +35,7 @@ - paragraph: partial - status: Deep diving... - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/turn-tail-actions/settled.expected.md b/snapshots/web/turn-tail-actions/settled.expected.md index fd6de1de07..57a4efebcf 100644 --- a/snapshots/web/turn-tail-actions/settled.expected.md +++ b/snapshots/web/turn-tail-actions/settled.expected.md @@ -37,9 +37,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/turn-tail-actions/usage-expanded.expected.md b/snapshots/web/turn-tail-actions/usage-expanded.expected.md index 916569dc9c..20d2aaba79 100644 --- a/snapshots/web/turn-tail-actions/usage-expanded.expected.md +++ b/snapshots/web/turn-tail-actions/usage-expanded.expected.md @@ -38,9 +38,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": diff --git a/snapshots/web/web-search-round/ui.expected.md b/snapshots/web/web-search-round/ui.expected.md index 1aa9b33fc1..64841a676e 100644 --- a/snapshots/web/web-search-round/ui.expected.md +++ b/snapshots/web/web-search-round/ui.expected.md @@ -43,9 +43,7 @@ - text: Ran for {{duration}} - text: {{clock}} - textbox "Message or run a task, / commands, @ files or sessions" -- button "Commands": - - img -- button "Add attachment": +- button "Add files or run commands": - img - 'button "Access mode, current: Workspace Write"': Workspace Write - button "Select model, current DeepSeek-V4-Flash": From c75e100893084b6d999e8e5cdc3eb62ebce5d310 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 8 Sep 2026 12:47:21 +0800 Subject: [PATCH 03/52] fix(client): share the shield contour and describe the menu glyphs by shape The permission selector and IconShieldOutline16 now read one exported SHIELD_OUTLINE_PATH; the icon-set header no longer claims every glyph is filled; the three menu glyph docs name what they draw and where they are used; the compact ring matches the set's extent; the icon pin asserts the three names. --- .../src/client/skeleton/PermissionSelect.tsx | 17 +++---- .../client/ui-primitives/src/icons/index.tsx | 44 +++++++++++++------ .../ui-primitives/tests/icons.client.spec.tsx | 8 ++++ 3 files changed, 47 insertions(+), 22 deletions(-) diff --git a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx index b54049efef..0a63c4cca8 100644 --- a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx @@ -2,7 +2,9 @@ import { useEffect, useState } from 'react' import type { ReactNode } from 'react' import clsx from 'clsx' import type { PermissionSelect as PermissionSelectValue } from '@deepseek-ai/dsh-permission-presets/client' -import { IconChevronDownOutline14, Menu, RiskConfirmation } from '@deepseek-ai/dsh-client-ui-primitives' +import { + IconChevronDownOutline14, Menu, RiskConfirmation, SHIELD_OUTLINE_PATH, SHIELD_OUTLINE_STROKE, +} from '@deepseek-ai/dsh-client-ui-primitives' import type { MenuEntry } from '@deepseek-ai/dsh-client-ui-primitives' import type { ComposerBarProps } from '../contract/slots.ts' import { en } from '../locales.ts' @@ -10,16 +12,15 @@ import css from './PermissionSelect.module.css' const FULL_ACCESS = 'danger-full-access' -/* Shield glyphs (design set 1556): check = read-only, pencil = workspace - write, exclamation = full access. currentColor so the trigger and menu - rows tint them with their own text color. */ - -const shieldOutline = 'M8.20554 0.899994L14.7901 3.36857V7.01026C14.7901 12 11.0466 14.2103 8.20554 15.3C5.36446 14.2103 1.62012 12 1.62012 7.01026V3.36857L8.20554 0.899994Z' +/* Shield glyphs (design set 1556) over the ui-primitives shield contour: + check = read-only, pencil = workspace write, exclamation = full access. + currentColor so the trigger and menu rows tint them with their own text + color. */ const permissionGlyphs = new Map([ ['read-only', ( - + )], @@ -34,7 +35,7 @@ const permissionGlyphs = new Map([ )], [FULL_ACCESS, ( - + diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index 47682cfab3..5679a6aebe 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -1,7 +1,8 @@ /** - * ic_ds_* icon set for the dsh web UI. All glyphs render fill="currentColor" - * and take {size, className}. Batch A mirrors the deepsuite icon library - * (same figma source); batch B glyphs are harness-only figma extracts. + * ic_ds_* icon set for the dsh web UI. All glyphs ride currentColor (filled + * or stroked) and take {size, className}. Batch A mirrors the deepsuite icon + * library (same figma source); batch B glyphs are harness-only figma + * extracts; the product glyphs at the end are hand-authored. */ import type { IconProps } from './props.ts' @@ -935,7 +936,12 @@ export const IconArchiveOutline20 = ({ size = 20, className }: IconProps) => ( ) -/** plan_outline_14 (design doc for #3567: the composer menu's Plan row glyph; drawn on a 14 grid) */ +/** + * Plan row glyph of the composer menu (#3567): a document with three ruled + * lines and a pencil over its corner. Drawn on a 14 grid whose content spans + * 0.5..13.5, so at the menu's 16px render it fills the same extent as the + * 16-grid glyphs beside it. + */ export const IconPlanOutline14 = ({ size = 14, className }: IconProps) => ( @@ -953,22 +959,32 @@ export const IconPlanOutline14 = ({ size = 14, className }: IconProps) => ( ) -/** compact_outline_16 (the composer's context-usage ring as a static glyph: a quiet track with one filled arc) */ +/** + * Compact row glyph of the composer menu: the composer's context-usage ring + * (ContextMeter) frozen at its resting look — a quiet track with one filled + * quarter arc. A restyle of the live ring revisits this copy. + */ export const IconCompactOutline16 = ({ size = 16, className }: IconProps) => ( - - + + ) -/** shield_outline_16 (design set 1556: the permission shield contour without a mode mark) */ +/** + * The permission shield contour on the 16 grid (design set 1556), stroked at + * {@link SHIELD_OUTLINE_STROKE}. The composer's permission selector composes + * its mode marks (check, pencil, exclamation) over this same path inside one + * svg, so the geometry lives here once. + */ +export const SHIELD_OUTLINE_PATH = 'M8.20554 0.899994L14.7901 3.36857V7.01026C14.7901 12 11.0466 14.2103 8.20554 15.3C5.36446 14.2103 1.62012 12 1.62012 7.01026V3.36857L8.20554 0.899994Z' + +/** Stroke width of {@link SHIELD_OUTLINE_PATH}. */ +export const SHIELD_OUTLINE_STROKE = '1.31831' + +/** Permission row glyph of the composer menu: the shield contour alone, without a mode mark. */ export const IconShieldOutline16 = ({ size = 16, className }: IconProps) => ( - + ) diff --git a/packages/client/ui-primitives/tests/icons.client.spec.tsx b/packages/client/ui-primitives/tests/icons.client.spec.tsx index 4cae7397ed..d8b566704a 100644 --- a/packages/client/ui-primitives/tests/icons.client.spec.tsx +++ b/packages/client/ui-primitives/tests/icons.client.spec.tsx @@ -19,6 +19,14 @@ const iconNames = Object.keys(icons) describe('ic_ds_ icon set', () => { it('exports the full icon set (46 deepsuite + 21 figma extracts + eleven product glyphs outside those sets)', () => { expect(iconNames.length).toBe(78) + // The composer menu's own glyphs, pinned by name. + expect(iconNames).toEqual(expect.arrayContaining(['IconPlanOutline14', 'IconCompactOutline16', 'IconShieldOutline16'])) + }) + + it('the permission selector composes its marks over the shield contour exported here', () => { + const { container } = render() + expect(container.querySelector('path')?.getAttribute('d')).toBe(primitives.SHIELD_OUTLINE_PATH) + expect(container.querySelector('path')?.getAttribute('stroke-width')).toBe(primitives.SHIELD_OUTLINE_STROKE) }) it.each(iconNames)('%s renders an svg with currentColor fills and no hardcoded palette', (name) => { From 8e4d3bab9fd0bb1b6b3fa4bc9a2174953cf9a1a8 Mon Sep 17 00:00:00 2001 From: 07akioni <07akioni2@gmail.com> Date: Tue, 8 Sep 2026 16:33:58 +0800 Subject: [PATCH 04/52] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96=E6=89=93?= =?UTF-8?q?=E5=8C=85=E6=96=B9=E5=BC=8F=E3=80=81=E5=90=AF=E5=8A=A8=E9=80=9F?= =?UTF-8?q?=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...on-desktop-packaging-and-updates.i18n.yaml | 4 +- ...-electron-desktop-packaging-and-updates.md | 60 +- ...ectron-desktop-packaging-and-updates.zh.md | 58 +- ...led-runtime-and-external-plugins.i18n.yaml | 6 + ...op-bundled-runtime-and-external-plugins.md | 51 ++ ...bundled-runtime-and-external-plugins.zh.md | 51 ++ ...ktop-uninstall-preserve-dsh-home.i18n.yaml | 6 + ...-08-desktop-uninstall-preserve-dsh-home.md | 95 ++++ ...-desktop-uninstall-preserve-dsh-home.zh.md | 95 ++++ apps/desktop-host/src/index.ts | 34 +- apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 58 +- apps/desktop/README.zh.md | 58 +- apps/desktop/electron-builder.config.d.mts | 4 +- apps/desktop/electron-builder.config.mjs | 17 +- apps/desktop/package.json | 5 +- apps/desktop/renderer/plugin-manager.html | 6 + apps/desktop/renderer/plugin-manager.js | 19 +- .../desktop/scripts/desktop-build-paths.d.mts | 4 +- apps/desktop/scripts/desktop-build-paths.mjs | 6 +- apps/desktop/scripts/macos-runtime.ts | 43 ++ apps/desktop/scripts/macos-seed-store.ts | 413 -------------- apps/desktop/scripts/package-target.ts | 4 +- apps/desktop/scripts/prepare-dsh.ts | 150 +++++ apps/desktop/scripts/prepare-seed.ts | 200 ------- apps/desktop/scripts/smoke-runtime.ts | 58 ++ .../scripts/verify-macos-signature.d.mts | 12 +- .../scripts/verify-macos-signature.mjs | 22 +- apps/desktop/src/core-package-set.ts | 2 +- apps/desktop/src/host-process.ts | 13 +- apps/desktop/src/ipc.ts | 10 + apps/desktop/src/locale.ts | 14 + apps/desktop/src/main.ts | 65 ++- apps/desktop/src/preload.ts | 6 + apps/desktop/src/profile-packages.ts | 254 +++++++++ apps/desktop/src/project-manager.ts | 348 +++++------- apps/desktop/src/release.ts | 4 +- apps/desktop/src/runtime-tree.ts | 180 ++++++ apps/desktop/src/seed-store.ts | 271 --------- apps/desktop/src/update-coordinator.ts | 2 +- .../desktop/tests/desktop-build-paths.spec.ts | 6 +- apps/desktop/tests/host-process.spec.ts | 35 +- apps/desktop/tests/macos-runtime.spec.ts | 48 ++ apps/desktop/tests/macos-seed-store.spec.ts | 245 -------- apps/desktop/tests/macos-signature.spec.ts | 49 +- apps/desktop/tests/package-target.spec.ts | 2 +- apps/desktop/tests/plugin-manager.spec.ts | 33 ++ apps/desktop/tests/plugin-pnpm.spec.ts | 72 +++ apps/desktop/tests/profile-packages.spec.ts | 81 +++ apps/desktop/tests/project-manager.spec.ts | 537 ++++++------------ apps/desktop/tests/runtime-fixture.ts | 42 ++ apps/desktop/tests/runtime-tree.spec.ts | 46 ++ apps/desktop/tests/seed-store.spec.ts | 167 ------ docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 4 +- docs/architecture.zh.md | 4 +- pnpm-lock.yaml | 89 +-- 57 files changed, 2013 insertions(+), 2163 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md create mode 100644 .agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md create mode 100644 .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.i18n.yaml create mode 100644 .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md create mode 100644 .agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md create mode 100644 apps/desktop/scripts/macos-runtime.ts delete mode 100644 apps/desktop/scripts/macos-seed-store.ts create mode 100644 apps/desktop/scripts/prepare-dsh.ts delete mode 100644 apps/desktop/scripts/prepare-seed.ts create mode 100644 apps/desktop/scripts/smoke-runtime.ts create mode 100644 apps/desktop/src/profile-packages.ts create mode 100644 apps/desktop/src/runtime-tree.ts delete mode 100644 apps/desktop/src/seed-store.ts create mode 100644 apps/desktop/tests/macos-runtime.spec.ts delete mode 100644 apps/desktop/tests/macos-seed-store.spec.ts create mode 100644 apps/desktop/tests/plugin-manager.spec.ts create mode 100644 apps/desktop/tests/plugin-pnpm.spec.ts create mode 100644 apps/desktop/tests/profile-packages.spec.ts create mode 100644 apps/desktop/tests/runtime-fixture.ts create mode 100644 apps/desktop/tests/runtime-tree.spec.ts delete mode 100644 apps/desktop/tests/seed-store.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml index 8aa7824f1f..e0081b64f5 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.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-25-electron-desktop-packaging-and-updates.md -2026-08-25-electron-desktop-packaging-and-updates.md: 6d22777c8913911dbb1d89c09de9e891636873c8 -2026-08-25-electron-desktop-packaging-and-updates.zh.md: 5108492ba6f029847735f570aa77c2cb505f981c +2026-08-25-electron-desktop-packaging-and-updates.md: fea2c419d73e4eff66de08483733cbc336b6f9af +2026-08-25-electron-desktop-packaging-and-updates.zh.md: 88e2875cd35909c0111926377df83c9fe21841dc diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md index 6d22777c89..fea2c419d7 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md @@ -10,13 +10,13 @@ DeepSeek Harness needs an Electron desktop application that reuses the Web UI, w The desktop application and an npm-installed dsh share the `.dsh` data root, but they may have different dsh and plugin versions. They must share supported product data without sharing executable packages, lockfiles, `node_modules`, plugin activation, or package-manager configuration. -The current GUI protocol binds the Web client and backend release. Independently versioning the Electron artifact and its pnpm-installed dsh would create unqualified shell, client, backend, and plugin combinations and make update availability ambiguous. +The current GUI protocol binds the Web client and backend release. Independently versioning the Electron artifact and its bundled dsh would create unqualified shell, client, backend, and plugin combinations and make update availability ambiguous. ## Decision Ship a small Electron shell with a bundled upstream Node.js executable and pinned pnpm. Electron starts the private Desktop Host package as an isolated child process; that package composes the installed dsh backend and matching client graph. Fetch metadata and bounded raw request and response chunks travel over two versioned framed byte pipes, Node IPC is reserved for readiness, fatal failure, and shutdown, and Electron serves validated assets through `dsh-app://`; it opens no listening port. Each frame carries a fixed marker, type, monotonic stream id, payload length, and validated payload. Serialized writers honor pipe drain, readers pause globally when a request or response stream applies backpressure, cancellation closes the matching stream, and late response frames for a retired stream stay inert. The Connection plugin provides its carrier-neutral RPC and Fetch registries without requiring `webServer`, while Client Modules provides the exact advertised combo-bundle responses to the shell-owned carrier; Web compositions attach their optional HTTP routes for both. The renderer keeps the same Fetch, RPC, and Remote-stream formats, while the child carrier avoids Base64 expansion and V8 serialization compatibility between Electron and the bundled upstream Node.js. Electron closes its request-pipe writer after sending shutdown, releasing an in-flight Windows pipe read before it waits for child exit. This follows the Electron reservation in the [GUI layering and RPC protocol note](../../archived/architecture/2026-07-19-gui-layering-and-rpc-protocol.md). -Electron owns the reserved profile at `.dsh/profiles/desktop`. Its exact `@deepseek-ai/dsh` dependency supplies the backend and matching Web UI, while the matching private `@deepseek-ai/dsh-desktop-host` dependency supplies only the Electron child-process entry and composition overlay. The dsh release, private Host, and their first-party dependency closures use local npm tarballs packed from the same source build; the profile manifest lists every core package as a local `file:` dependency, and `pnpm-workspace.yaml` repeats the mapping as overrides. The Host remains outside the public CLI package and is never published to npm. Desktop plugins are additional registry npm dependencies and ordered `dsh.profile.bundles` entries in the same profile, and resolve from its one `node_modules`. +Electron owns the reserved profile at `.dsh/profiles/desktop`. The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) owns core resource storage, external plugin dependencies, shared package links, and profile reconciliation. The private Desktop Host remains outside the public CLI package and is never published to npm. One Desktop release number identifies the Electron artifact and its exact `@deepseek-ai/dsh` and `@deepseek-ai/dsh-desktop-host` dependencies. A release cannot select a different core version at build or runtime. Updating dsh therefore requires a new Electron release even when shell code is unchanged. @@ -28,7 +28,7 @@ The browser Web UI, dsh backend, existing `dsh plugin` CLI, user npm, and user p |---|---| | Electron shell | Window and child lifecycle, framed byte pipes, lifecycle IPC, custom protocol, reserved desktop profile, plugin GUI, update coordination, rollback | | Bundled Node.js and pnpm | Execute dsh and install exact desktop-project dependencies without consulting user `PATH` or pnpm state | -| Desktop profile | One dependency graph, ordered bundle list, and `node_modules` for the desktop dsh package and desktop plugins | +| Desktop profile | External plugin dependencies, ordered enabled bundles, and shared links defined by the bundled-runtime decision | | Private Desktop Host package | Electron-only child-process entry and composition overlay installed with dsh but excluded from the public CLI package and npm publication | | Installed dsh package | Backend, matching Web UI, boot manifest, client bundles, and product behavior | | Shared `.dsh` owners | Sessions, settings, credentials, workspaces, and storage, guarded by their existing locks and format versions | @@ -55,15 +55,13 @@ The renderer uses `nodeIntegration: false`, `contextIsolation: true`, and `sandb package.json pnpm-lock.yaml pnpm-workspace.yaml - desktop-release.json - desktop-packages.json - desktop-packages/ + desktop-runtime-state.json node_modules/ sessions/ storages/ ``` -`.dsh/profiles/desktop` is the only active desktop profile. Its package manifest records the built-in and installed plugin bundle order; Electron alone mutates its dependencies, lockfile, and `node_modules`. Production startup rejects a bundle resolved outside this profile, including the CLI-maintained `.dsh/profiles/node_modules` fallback. Package content installed for the desktop profile uses `.dsh/desktop/pnpm/store`. +`.dsh/profiles/desktop` is the only active desktop profile. Its executable package ownership and allowed resolution directories follow the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). Plugin package content uses `.dsh/desktop/pnpm/store`. ## Installation and resolution @@ -71,35 +69,27 @@ The installer never mutates the active profile in place. It copies profile metad The process-lifetime Electron lock is the authoritative Desktop owner. The package transaction lock is depth defense and records the process that can still mutate package state: Electron between package operations and the spawned pnpm PID while pnpm runs. The owner change is truncated, written, and synchronized through the already-open exclusive lock file. If Electron terminates during pnpm execution, a later process observes the live worker and refuses to start a competing store or staging transaction; after that worker exits, the stale PID can be recovered. -The packaged seed is an offline installation kit, not an executable dsh tree. It contains the release identity, initial desktop-project manifest, a descriptor and immutable tarballs for the union of the first-party package closures rooted at dsh and the private Desktop Host, lockfile, integrity inventory, and required store subset. Each `mac-arm64`, `mac-x64`, and `win-x64` build owns its packed packages, runtime, package set, seed, pnpm preparation state, unpacked application, update metadata, and final artifacts under `.desktop-build/targets/`; only the immutable, checksum-verified Node.js download cache is shared. The release build requires the Electron package, root dsh package, and private Host package to have the same version, creates final npm tarballs from the official source build, locally packs the private Host, selects the reachable dsh, Host, and vendored packages plus the Landlock entry, and verifies that the Host tarball contains `lib/index.js` and `config/desktop.cordis.patch.yml`. The Host `files` manifest contains only that runtime entry and overlay, and the package is never published to npm. Public package tarballs remain the official `pnpm pack` results governed by each package's publication manifest; Desktop does not remove published declarations or otherwise create a second package-content policy. The seed manifest lists every selected package as a local direct dependency, automatic peer installation is disabled, and the workspace file overrides every selected first-party name to its local tarball. The target Node.js executes bundled pnpm, so pnpm's operating-system and CPU selection makes the materialized dependency graph and seed target-specific. Bundled pnpm disables its global virtual store, materializes external production dependencies from npm without lifecycle scripts, deletes `node_modules` and every temporary pnpm cache, config, and state directory, then performs a clean offline installation from the final store alone and checks the private Host entry and overlay. The build rejects any lockfile that resolves one of the local first-party names by registry version. Inventory generation follows removal of that second `node_modules` tree and temporary pnpm project registrations. Requiring both Host files before copying the package set and after offline installation prevents a release whose process entry loads but cannot compose its required overlay from reaching application signing. - -The seed stores pnpm content in 16 deterministic uncompressed tar shards selected by normalized store path. Apple notarization inspects Mach-O code inside those archives, so macOS seed preparation stages every referenced Mach-O content-addressed object and runs at most four independent Developer ID signers concurrently with a secure timestamp and hardened runtime. A signer failure is observed only after every active signer exits and leaves the original CAS objects and package index unchanged. After all signers succeed, preparation writes each object at its new SHA-512 path and transactionally rewrites every base and side-effects file reference in pnpm's MessagePack SQLite index. A second offline installation proves that pnpm resolves the rewritten store; preparation then shards it, extracts the final archives, and verifies every embedded signature. Package paths and non-native bytes remain unchanged, and the seed retains bundled architecture variants because removing files would create a Desktop-specific package file set. Seed integrity covers the shard manifest and every archive before extraction. Startup validates archive paths, entry types, uniqueness, and counts, extracts every shard into a unique Desktop-owned staging directory, replaces matching immutable store files, and transactionally merges each pnpm store version's SQLite `package_index` into `.dsh/desktop/pnpm/store`. Seed records replace matching keys while records downloaded for Desktop plugins remain. An interrupted file merge may leave valid immutable cache content, but each SQLite merge is atomic, and profile installation and activation still require pnpm integrity and the complete health check. - -Startup requires the packaged release identity to equal Electron's application version, then compares `.dsh/profiles/desktop/desktop-release.json` plus the installed dsh and Desktop Host packages with that release before launching the backend. It installs the new seed manifest and lockfile with `pnpm install --offline --frozen-lockfile --trust-lockfile` in staging. After Electron replacement, it restores every plugin bundle recorded in the active profile at its exact installed version through one offline pnpm add from the existing desktop store and metadata cache. The complete graph must pass the same health check before activation. - -The plugin GUI performs registry npm-package operations equivalent to `pnpm add --save-exact`, `pnpm remove `, and exact-version update in staging. Every mutation retains the local core-package descriptor, tarballs, dsh and Desktop Host dependencies, and complete override map. Electron validates the installed package manifest and updates the profile's dependency and ordered bundle entries; no renderer request can choose the registry, install directory, lifecycle policy, or arbitrary pnpm flags. - -The backend and Loader use `.dsh/profiles/desktop/package.json` as their profile manifest and npm resolution anchor. The shared profile loader composes its ordered bundle entries, then the private Desktop Host applies its packaged overlay. The Host, dsh, Cordis, desktop plugins, plugin dependencies, and peer dependencies resolve through the ordinary pnpm `node_modules` graph. A desktop plugin contributing `dsh.client` code enters the boot manifest only after the complete profile passes health checking. +Core materialization, first launch, plugin installation, and shared-module resolution follow the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). A desktop plugin contributing `dsh.client` code enters the client graph only after the complete profile passes health checking. ## Updates and recovery Electron update uses one `electron-updater` release stream and signed `electron-builder` artifacts. Its version is the Desktop release version; there is no independent dsh manifest, compatibility range, or dsh-only update operation. A foreground install waits for an in-flight background check rather than reusing its result as an install result. The update dialog downloads and installs the Electron artifact, then restarts into the new release. -Before the new release opens a window, startup reconciles dsh from its packaged seed while retaining installed desktop plugins. The health check covers dependency resolution, native modules, shell API compatibility, backend startup and shutdown, Web assets, and the client boot graph. An incompatible plugin blocks activation and leaves the previous project available for rollback. Startup fails visibly rather than launching a shell and dsh version that do not match. +Before opening the product window, startup validates the current bundled runtime and reconciles external plugins according to the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). Backend failure opens the Electron-owned recovery window instead of booting a mismatched dsh release. `DSH_DESKTOP_AUTO_UPDATE_ENV` selects the test deployment by default or the production deployment for both the target-specific generic-provider URL and COS destination. Release automation supplies the test HTTPS origin through `DOWNLOAD_TEST_ORIGIN` and each deployment's bucket through `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`; keeping mutable test routing and COS storage identities out of source lets deployment infrastructure change without a code release, while the public production origin remains fixed. Packaging resolves only the public updater URL, disables electron-builder publishing, removes every COS credential field from its subprocess environment, and writes a completion record only after electron-builder and every signing or notarization hook succeeds. Target upload additionally requires the selected bucket, then requires the completion record, root dsh version, Desktop version, version-derived channel metadata, artifact names, sizes, and SHA-512 values to agree before it reads the selected credentials or sends data. It uploads immutable versioned updater payloads and any separate blockmaps before replacing the channel metadata emitted by electron-builder, and it never deletes historical objects. Stable versions use the `latest` metadata name; prereleases use the first semantic-version prerelease identifier. NSIS embeds its blockmap in the signed executable; the macOS ZIP carries a separate blockmap. Both let electron-updater download changed blocks when supported, while application replacement and the local pnpm staging transaction remain separate operations. ## Security and release policy -Core dsh and the private Desktop Host come only from integrity-recorded local npm tarballs inside the signed Electron release; pnpm overrides prevent transitive core packages from falling back to a registry. Store archives are integrity-checked and fully validated in an isolated extraction directory before their files can enter writable package state. Plugin installation accepts registry package specs allowed by desktop policy but never raw pnpm commands. Exact versions, lockfile integrity, a reviewed `allowBuilds` set, user-only directory permissions, redacted diagnostics, and health checking are required before activation. +Core dsh and the private Desktop Host come only from the signed application resource tree. Plugin installation accepts registry package specs allowed by desktop policy but never raw pnpm commands. Exact versions, lockfile integrity, a reviewed `allowBuilds` set, user-only directory permissions, and health checking are required before activation. -Electron artifacts are signed; macOS artifacts are notarized. Release automation must supply the application ID, macOS Developer ID qualifier, expected Team ID, and one complete notarytool credential strategy through explicit environment variables. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS packaging requires signing so certificate discovery cannot silently select another installed identity or emit an unsigned release. Seed preparation verifies the exact Authority and Team ID plus the timestamp and hardened-runtime flags on every embedded Mach-O file. An after-sign hook performs Apple's deep strict application verification and requires the same leaf Authority and Team ID before artifact creation continues. Electron-builder then notarizes and staples the application and signs the DMG. The DMG artifact-completion hook separately notarizes and staples every DMG before requiring the configured identity, a valid ticket, and Gatekeeper acceptance; the upload event runs only after that hook succeeds. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. +Electron artifacts are signed; macOS artifacts are notarized. Release automation must supply the application ID, macOS Developer ID qualifier, expected Team ID, and one complete notarytool credential strategy through explicit environment variables. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS packaging requires signing so certificate discovery cannot silently select another installed identity or emit an unsigned release. Runtime preparation verifies the exact Authority and Team ID plus the timestamp and hardened-runtime flags on every embedded Mach-O file. An after-sign hook performs Apple's deep strict application verification and requires the same leaf Authority and Team ID before artifact creation continues. Electron-builder then notarizes and staples the application and signs the DMG. The DMG artifact-completion hook separately notarizes and staples every DMG before requiring the configured identity, a valid ticket, and Gatekeeper acceptance; the upload event runs only after that hook succeeds. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. -Windows release packaging supplies the public EV leaf certificate named by `DSH_DESKTOP_WINDOWS_CER_FILE` to the configured SafeNet-compatible SignTool through `/f` and identifies its matching private key through the required `DSH_DESKTOP_WINDOWS_KEY_CONTAINER`. The certificate file remains outside source control, and the private key remains on the USB token. The electron-builder hook passes each artifact to the CRLF `windows-sign.cmd`, whose single SignTool invocation uses the SafeNet `/kc "[{{PIN}}]=container"` value and CSP, a SHA-256 file digest, and a DigiCert SHA-256 RFC 3161 timestamp. The hook never substitutes another SignTool and never retries a failed request. Package orchestration withholds every `DSH_DESKTOP_WINDOWS_*` field from build and seed-preparation children and passes only the certificate path, SignTool path, key container, and PIN into electron-builder. The signer supplies only validated signing fields in an otherwise scrubbed CMD environment; the CMD disables delayed expansion, clears those fields before SignTool starts, and preserves the PIN only in the required SignTool command line. Every surfaced diagnostic replaces the PIN, and only the dedicated build account and administrators may inspect the runner. The signer signs electron-builder's temporary NSIS bootstrap before enterprise Code Integrity evaluates that executable and clears a generated executable's certificate-table entry only when it points beyond the file before applying the final signature. Packaging fails before producing unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. +Windows release packaging supplies the public EV leaf certificate named by `DSH_DESKTOP_WINDOWS_CER_FILE` to the configured SafeNet-compatible SignTool through `/f` and identifies its matching private key through the required `DSH_DESKTOP_WINDOWS_KEY_CONTAINER`. The certificate file remains outside source control, and the private key remains on the USB token. The electron-builder hook passes each artifact to the CRLF `windows-sign.cmd`, whose single SignTool invocation uses the SafeNet `/kc "[{{PIN}}]=container"` value and CSP, a SHA-256 file digest, and a DigiCert SHA-256 RFC 3161 timestamp. The hook never substitutes another SignTool and never retries a failed request. Package orchestration withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation children and passes only the certificate path, SignTool path, key container, and PIN into electron-builder. The signer supplies only validated signing fields in an otherwise scrubbed CMD environment; the CMD disables delayed expansion, clears those fields before SignTool starts, and preserves the PIN only in the required SignTool command line. Every surfaced diagnostic replaces the PIN, and only the dedicated build account and administrators may inspect the runner. The signer signs electron-builder's temporary NSIS bootstrap before enterprise Code Integrity evaluates that executable and clears a generated executable's certificate-table entry only when it points beyond the file before applying the final signature. Packaging fails before producing unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. -Packaged applications ignore development resource and project environment overrides. Only an unpackaged Electron process can replace the Node.js binary, pnpm entry, seed, or active project. +Packaged applications ignore development resource and project environment overrides. Only an unpackaged Electron process can replace the Node.js binary, pnpm entry, dsh resources, or active project. -The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compressed and 120–165 MB installed before the seed store subset. Architecture-specific builds must report actual component-level size deltas. +The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compressed and 120–165 MB installed before the dsh production tree. Architecture-specific builds must report actual component-level size deltas. ## Implementation @@ -107,10 +97,10 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr |---|---| | Shell | `apps/desktop` owns Electron windows, restricted preloads, the custom protocol, child lifecycle, project transactions, the plugin GUI, update coordination, and electron-builder configuration. | | Installed runtime | Private `@deepseek-ai/dsh-desktop-host` boots the portless desktop composition from the active project and streams API and asset responses over validated framed byte pipes. | -| Package state | The release seed and every later mutation run through bundled Node.js and pnpm with desktop-owned store, config, cache, state, and home paths; core packages resolve from release tarballs while plugins resolve from the fixed npm registry. | -| Qualification | macOS packaging requires the configured company identity and notary credentials, verifies every native seed object after final archive extraction, verifies the completed application signature, and requires notarization plus Gatekeeper acceptance for both the application and DMG. Windows packaging requires the configured public certificate, SafeNet private-key container, Token Password, and SignTool, and verifies every produced signature. Update hosting, previous-version installed-artifact tests, and platform GUI recordings remain release-environment gates. | +| Package state | Bundled Node.js executes immutable core resources; bundled pnpm modifies only the external plugin graph in Desktop staging. | +| Qualification | macOS packaging requires the configured company identity and notary credentials, verifies every native runtime file before inventory generation, verifies the completed application signature, and requires notarization plus Gatekeeper acceptance for both the application and DMG. Windows packaging requires the configured public certificate, SafeNet private-key container, Token Password, and SignTool, and verifies every produced signature. Update hosting, previous-version installed-artifact tests, and platform GUI recordings remain release-environment gates. | -`dev:desktop` builds the current workspace, projects the built CLI and private Desktop Host packages plus their dependency links into a disposable project, uses an isolated Harness home, opens the Main, Renderer, and Host debuggers, and starts unpackaged Electron without preparing release resources. Package mutation is disabled in this mode because its linked dependency graph is not a pnpm-installed desktop project. Fixed macOS arm64, macOS x64, and Windows x64 package commands pass one target through runtime preparation, seed installation, and electron-builder; each also has an unpacked-directory variant for release-path verification before installer generation. +`dev:desktop` builds the current workspace, projects the built CLI and private Desktop Host packages plus their dependency links into a disposable project, uses an isolated Harness home, opens the Main, Renderer, and Host debuggers, and starts unpackaged Electron without preparing release resources. Package mutation is disabled in this mode because its linked dependency graph is not a pnpm-installed desktop project. Fixed macOS arm64, macOS x64, and Windows x64 package commands pass one target through runtime preparation, runtime preparation, and electron-builder; each also has an unpacked-directory variant for release-path verification before installer generation. ## Alternatives considered @@ -122,11 +112,11 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr **Reuse the existing CLI or browser plugin installer.** That crosses the desktop authorization and release scope and can use the user's package-manager state. Desktop package mutation remains exclusively Electron-owned. -**Let the desktop profile use CLI-managed packages or plugins.** Either product could change the other's dependency graph, Cordis version, plugin version, or native module. The desktop profile therefore owns a complete `node_modules` and rejects bundle resolution through the CLI profile fallback. +**Let the desktop profile use CLI-managed packages or plugins.** Either product could change the other’s dependency graph, Cordis version, plugin version, or native module. Desktop rejects package resolution through the CLI profile fallback. -**Install dsh and plugins into separate desktop projects.** This creates a second resolution anchor and peer-dependency fallback. One ordinary npm project already provides the required installation and resolution model. +**Separate core and plugin resolution without shared package ownership.** That permits duplicate host modules and uncontrolled peer fallback. The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) supplies explicit links and dependency validation for the separate resource and profile directories. -**Remove non-target Mach-O files from registry packages.** Architecture pruning saves a small amount of seed space, but packages can deliberately ship several architecture variants and callers can observe their installed file set. Signing every shipped Mach-O object satisfies notarization without inventing a Desktop-specific package layout. +**Remove non-target Mach-O files from registry packages.** Architecture pruning saves a small amount of runtime space, but packages can deliberately ship several architecture variants and callers can observe their installed file set. Signing every shipped Mach-O object satisfies notarization without inventing a Desktop-specific package layout. **Export the Windows EV private key in a PFX file.** The externally supplied public leaf certificate lets SignTool construct the signature while `/csp` and `/kc` locate the hardware key. The EV private key remains non-exportable on the token. @@ -136,9 +126,9 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr ## Consequences -- A clean offline machine with no system Node.js or pnpm installs the seed into `.dsh/profiles/desktop` and starts a working dsh session. -- The signed application inventories a fixed small set of seed store shards instead of every pnpm cache file; every Mach-O object inside the macOS shards has the release Developer ID, secure timestamp, and hardened runtime, every Windows artifact has the configured hardware-backed EV signature, and the installed private store retains the ordinary pnpm layout. -- `.dsh/profiles/desktop/node_modules` contains and resolves the desktop dsh package and every GUI-installed desktop plugin. +- A clean offline machine without system Node.js or pnpm starts bundled dsh without installing core dependencies. +- The signed application inventories final runtime files; every macOS native file has the release Developer ID, secure timestamp, and hardened runtime, and every Windows artifact has the configured hardware-backed EV signature. +- `.dsh/profiles/desktop/node_modules` resolves shared host links and every GUI-installed desktop plugin. - Every desktop pnpm operation uses the bundled executable and `.dsh/desktop/pnpm/store`; none reads user `PATH`, config, store, or profile `node_modules`. - The Electron-only GUI installs, removes, and updates ordinary npm plugin packages without exposing raw pnpm arguments. - The backend and browser application cannot mutate desktop packages. @@ -157,8 +147,8 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr | Decision | Recommendation | |---|---| -| First launch | Bundle an offline seed store subset and install it through pnpm | -| Desktop profile | One Electron-owned reserved profile containing exact dsh and plugin dependencies | +| First launch | Validate bundled production packages and create profile links without installing core dependencies | +| Desktop profile | One Electron-owned reserved profile for external plugins and shared package links | | Plugin management | Electron-only GUI and package service; no CLI, backend, or browser installation path | | Activation | Staging project, complete health check, journaled directory replacement, one rollback copy | | Initial platforms | macOS arm64/x64 and Windows x64; Linux has no supported release target | @@ -175,3 +165,7 @@ An npm-installed dsh and desktop dsh may have different versions while sharing d Directory replacement differs across operating systems and can be interrupted. The activation journal and installed-artifact fault tests must prove recovery at every filesystem move. Code signing, notarization, and update hosting require production release infrastructure. Repository tests alone cannot complete that qualification. + +## Related proposals + +The [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) supersedes this note’s offline runtime preparation and single-project package ownership. Release identity, signing, portless transport, process ownership, and Electron-only package authorization remain owned here. diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md index 5108492ba6..88e2875cd3 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md @@ -10,13 +10,13 @@ DeepSeek Harness 需要一个复用 Web UI 的 Electron 桌面应用。该应用 桌面应用与通过 npm 安装的 dsh 共享 `.dsh` 数据根目录,但两者可能使用不同的 dsh 与插件版本。它们必须共享受支持的产品数据,同时不得共享可执行包、lockfile、`node_modules`、插件激活状态或包管理器配置。 -当前 GUI 协议绑定 Web 客户端与后端版本。Electron 产物与其中通过 pnpm 安装的 dsh 如果独立定版本,就会产生未经验证的壳、客户端、后端与插件组合,也无法明确判断更新是否可用。 +当前 GUI 协议绑定 Web 客户端与后端版本。Electron 产物与其中通过 内置 dsh 如果独立定版本,就会产生未经验证的壳、客户端、后端与插件组合,也无法明确判断更新是否可用。 ## 决策 交付一个小型 Electron 壳,其中内置上游 Node.js 可执行文件和固定版本的 pnpm。Electron 把私有 Desktop Host 包作为隔离子进程启动;该包组合已安装的 dsh 后端与匹配的客户端图。Fetch 元数据及有界的原始请求与响应分块通过两条带版本的分帧字节管道传递,Node IPC 只承载就绪、致命失败和关闭,Electron 通过 `dsh-app://` 提供经过验证的资源;它不会打开监听端口。每个帧都包含固定标记、类型、单调 stream id、负载长度和经过验证的负载。串行 writer 遵守 pipe drain,请求或响应 stream 施加背压时 reader 会全局暂停,取消会关闭匹配的 stream,已退役 stream 的迟到响应帧保持无效。Connection 插件无需 `webServer` 即可提供与载体无关的 RPC 与 Fetch 注册表,Client Modules 则向 shell-owned carrier 提供与广告内容完全一致的组合 bundle 响应;Web 组合为两者挂载可选 HTTP route。渲染进程保留相同的 Fetch、RPC 与 Remote-stream 格式,子进程载体则避免 Base64 膨胀,也不依赖 Electron 与内置上游 Node.js 之间的 V8 序列化兼容性。发送 shutdown 后,Electron 会关闭自己持有的请求管道写端,以便在等待子进程退出前释放 Windows 上仍在进行的管道读取。该设计沿用 [GUI 分层与 RPC 协议 Agent Note](../../archived/architecture/2026-07-19-gui-layering-and-rpc-protocol.md)中的 Electron 预留。 -Electron 拥有保留 profile `.dsh/profiles/desktop`。其中精确的 `@deepseek-ai/dsh` 依赖提供后端与匹配的 Web UI,匹配的私有 `@deepseek-ai/dsh-desktop-host` 依赖则只提供 Electron 子进程入口与组合 overlay。dsh 发布、私有 Host 及其第一方依赖闭包使用同一次源码构建生成的本地 npm tarball;profile manifest 把每个核心包列为本地 `file:` 依赖,`pnpm-workspace.yaml` 再通过 overrides 重复该映射。Host 不进入公共 CLI 包,也不会发布到 npm。桌面插件既是同一 profile 中来自 registry 的其他 npm 依赖,也是有序的 `dsh.profile.bundles` 条目,并从该 profile 唯一的 `node_modules` 解析。 +Electron 拥有 `.dsh/profiles/desktop` 保留 profile。[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)负责核心资源存储、外部插件依赖、共享包链接和 profile 协调。私有 Desktop Host 保持独立于公共 CLI 包,且不会发布到 npm。 一个 Desktop 发布号同时标识 Electron 产物及其精确的 `@deepseek-ai/dsh` 与 `@deepseek-ai/dsh-desktop-host` 依赖。发布不能在构建或运行时选择不同的核心版本。因此,即使壳代码没有变化,更新 dsh 也必须产生新的 Electron 发布。 @@ -28,7 +28,7 @@ Electron 拥有保留 profile `.dsh/profiles/desktop`。其中精确的 `@deepse |---|---| | Electron 壳 | 窗口与子进程生命周期、分帧字节管道、生命周期 IPC、自定义协议、保留 desktop profile、插件 GUI、更新协调、回滚 | | 内置 Node.js 与 pnpm | 执行 dsh 并安装桌面项目的精确依赖,不读取用户 `PATH` 或 pnpm 状态 | -| Desktop profile | 为桌面 dsh 包与桌面插件提供一个依赖图、有序 bundle 列表和一个 `node_modules` | +| Desktop profile | 由内置运行时决策定义的外部插件依赖、已启用 bundle 顺序和共享链接 | | 私有 Desktop Host 包 | 与 dsh 一起安装、但不进入公共 CLI 包或 npm 发布的 Electron 专用子进程入口与组合 overlay | | 已安装 dsh 包 | 后端、匹配的 Web UI、启动 manifest、客户端包和产品行为 | | 共享 `.dsh` owner | 会话、设置、凭据、工作区和存储,由其现有锁与格式版本保护 | @@ -55,15 +55,13 @@ Electron 拥有保留 profile `.dsh/profiles/desktop`。其中精确的 `@deepse package.json pnpm-lock.yaml pnpm-workspace.yaml - desktop-release.json - desktop-packages.json - desktop-packages/ + desktop-runtime-state.json node_modules/ sessions/ storages/ ``` -`.dsh/profiles/desktop` 是唯一活跃的 desktop profile。其 package manifest 记录内置与已安装插件 bundle 的顺序;只有 Electron 可以修改它的依赖、lockfile 和 `node_modules`。生产启动会拒绝解析到该 profile 之外的 bundle,包括 CLI 维护的 `.dsh/profiles/node_modules` fallback。desktop profile 安装的所有包内容都使用 `.dsh/desktop/pnpm/store`。 +`.dsh/profiles/desktop` 是唯一活动桌面 profile。其可执行包归属及允许解析的目录遵循[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)。插件包内容使用 `.dsh/desktop/pnpm/store`。 ## 安装与解析 @@ -71,33 +69,25 @@ Electron 拥有保留 profile `.dsh/profiles/desktop`。其中精确的 `@deepse 进程生命周期 Electron 锁是 Desktop 的权威 owner。包事务锁用于纵深防御,并记录仍能修改包状态的进程:包操作之间记录 Electron,pnpm 运行期间记录已生成的 pnpm PID。Owner 变更通过已经打开的排他锁文件完成截断、写入与同步。如果 Electron 在 pnpm 执行期间终止,后续进程会发现仍存活的 worker,并拒绝启动并发的 store 或 staging 事务;该 worker 退出后,陈旧 PID 才可以恢复。 -打包 seed 是离线安装包,而不是可执行 dsh 目录。它包含发布身份、初始桌面项目 manifest、分别以 dsh 和私有 Desktop Host 为根的第一方包闭包之并集的描述文件及不可变 tarball、lockfile、完整性清单和所需 store 子集。每个 `mac-arm64`、`mac-x64` 和 `win-x64` 构建都在 `.desktop-build/targets/` 下持有自己的打包输入、运行时、包集合、seed、pnpm 准备状态、未打包应用、更新元数据和最终产物;只有不可变且经过校验和验证的 Node.js 下载缓存会被共享。发布构建要求 Electron 包、根 dsh 包与私有 Host 包使用相同版本,从正式源码构建生成最终 npm tarball,在本地打包私有 Host,选择可达的 dsh、Host 与 vendored 包以及 Landlock 入口,并验证 Host tarball 中包含 `lib/index.js` 与 `config/desktop.cordis.patch.yml`。Host 的 `files` manifest 只包含该运行入口与 overlay,并且该包不会发布到 npm。公共包 tarball 仍是由各包发布 manifest 控制的正式 `pnpm pack` 结果;Desktop 不删除已发布的声明文件,也不建立第二套包内容策略。seed manifest 把每个选中的包列为本地直接依赖,关闭 peer dependency 自动安装,workspace 文件再把每个选中的第一方包 override 到对应本地 tarball。目标 Node.js 执行内置 pnpm,因此 pnpm 的操作系统和 CPU 选择会使物化的依赖图与 seed 成为目标专用内容。内置 pnpm 关闭全局 virtual store,在禁用生命周期脚本的情况下从 npm 物化外部生产依赖,删除 `node_modules` 以及所有临时 pnpm cache、config 和 state 目录,然后只使用最终 store 执行一次干净的离线安装,并检查私有 Host 的入口与 overlay。构建会拒绝任何通过 registry 版本解析本地第一方包名的 lockfile。生成清单前会删除第二次生成的 `node_modules` 和临时 pnpm 项目注册。在复制 package set 前与离线安装后都要求这两个 Host 文件,可防止进程入口能够加载、却无法组合所需 overlay 的发布进入应用签名阶段。 - -种子根据规范化 store 路径,把 pnpm 内容放入 16 个确定性的未压缩 tar 分片。Apple 公证会检查这些归档内的 Mach-O 代码,因此 macOS seed 会 staging 每个被引用的内容寻址 Mach-O 对象,最多并发四个独立的 Developer ID 签名进程,并带上安全时间戳与 hardened runtime。任一签名失败后,准备过程会等待已启动的签名进程全部退出,原始 CAS 对象与包索引保持不变。所有签名成功后,准备过程把每个对象写到新的 SHA-512 路径,并以事务方式重写 pnpm MessagePack SQLite 索引内全部基础文件和 side-effects 文件引用。第二次离线安装证明 pnpm 可以解析重写后的 store;准备过程随后完成分片、解包最终归档并验证每个内嵌签名。包路径和非原生字节保持不变;种子保留包内附带的架构变体,因为删除文件会创建 Desktop 专属的包文件集。种子完整性覆盖分片 manifest 和解包前的每个归档。启动时验证归档路径、条目类型、唯一性和数量,把所有分片解包到唯一且由 Desktop 拥有的 staging 目录,替换匹配的不可变 store 文件,并以事务方式把各 pnpm store 版本的 SQLite `package_index` 合并进 `.dsh/desktop/pnpm/store`。Seed 记录替换匹配的键,为 Desktop 插件下载的记录继续保留。中断的文件合并可能留下有效的不可变缓存内容,但每次 SQLite 合并都是原子的,profile 安装与激活仍必须通过 pnpm 完整性与完整健康检查。 - -启动过程先要求安装包内的发布身份等于 Electron 应用版本,再在启动后端前比较 `.dsh/profiles/desktop/desktop-release.json`、已安装 dsh 包、已安装 Desktop Host 包与该发布版本。它在 staging 中通过 `pnpm install --offline --frozen-lockfile --trust-lockfile` 安装新的 seed manifest 与 lockfile。Electron 替换后,启动过程再通过一次离线 pnpm add,从桌面端现有 store 与元数据缓存恢复活跃 profile 记录的每个插件 bundle 精确版本。完整依赖图必须通过同一套健康检查才能激活。 - -插件 GUI 执行等价于 `pnpm add --save-exact`、`pnpm remove ` 和精确版本更新的 registry npm 包操作。每次修改都保留本地核心包描述文件、tarball、dsh 与 Desktop Host 依赖和完整 override 映射。Electron 验证已安装包 manifest,并更新 profile 的依赖与有序 bundle 条目;任何渲染进程请求都不能选择 registry、安装目录、生命周期策略或任意 pnpm flag。 - -后端与 Loader 把 `.dsh/profiles/desktop/package.json` 作为 profile manifest 和 npm 解析锚点。公共 profile loader 先组合其中的有序 bundle 条目,再由私有 Desktop Host 应用其打包的 overlay。Host、dsh、Cordis、桌面插件、插件依赖和 peer dependency 均通过普通 pnpm `node_modules` 图解析。贡献 `dsh.client` 代码的桌面插件只有在完整 profile 通过健康检查后才进入启动 manifest。 +核心物化、首次启动、插件安装和共享模块解析遵循[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)。提供 `dsh.client` 代码的桌面插件只有在完整 profile 通过健康检查后才会进入客户端依赖图。 ## 更新与恢复 Electron 更新只使用一个 `electron-updater` 发布流和签名 `electron-builder` 产物。该版本就是 Desktop 发布版本;不存在独立 dsh manifest、兼容范围或仅更新 dsh 的操作。前台安装会等待正在进行的后台检查,而不会把检查结果复用成安装结果。更新弹窗下载并安装 Electron 产物,然后重启进入新发布。 -新发布在打开窗口前从安装包种子校准 dsh,同时保留已安装桌面插件。健康检查覆盖依赖解析、原生模块、壳 API 兼容性、后端启停、Web 资源和客户端启动图。不兼容插件会阻止激活,并保留上一个项目用于回滚。启动过程会明确失败,而不会运行版本不匹配的壳与 dsh。 +打开产品窗口前,启动过程会验证当前内置运行时,并根据[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)协调外部插件。后端失败会打开 Electron 拥有的恢复窗口,不会启动版本不匹配的 dsh。 `DSH_DESKTOP_AUTO_UPDATE_ENV` 默认为测试部署,也可以选择生产部署,并同时决定目标专用的 generic-provider URL 与 COS 目标。发布自动化通过 `DOWNLOAD_TEST_ORIGIN` 提供测试 HTTPS origin,并通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供各部署的 bucket;可变的测试路由与 COS 存储身份不写入源码,部署基础设施变更时无需发布新代码,而公开的生产 origin 仍固定。打包只解析公开更新 URL、禁止 electron-builder 发布、从子进程环境中删除每个 COS 凭据字段,并且只有在 electron-builder 以及每个签名或公证 hook 成功后才写入完成记录。目标上传还必须提供所选 bucket,随后会先要求完成记录、根 dsh 版本、Desktop 版本、根据版本得出的频道元数据、产物名称、大小与 SHA-512 全部一致,再读取所选凭据或发送数据。它先上传不可变且带版本的更新载荷与所有独立 blockmap,最后替换 electron-builder 生成的频道元数据,并且不会删除历史对象。稳定版本使用 `latest` 元数据名称,预发布版本则使用语义化版本的第一个预发布标识符。NSIS 把 blockmap 嵌入已签名的可执行文件,macOS ZIP 则使用独立 blockmap;两者都让 electron-updater 在平台支持时只下载变化的数据块,而应用替换与本地 pnpm staging 事务仍是两个独立操作。 ## 安全与发布策略 -核心 dsh 与私有 Desktop Host 只能来自签名 Electron 发布内经过完整性记录的本地 npm tarball;pnpm overrides 防止传递核心包回退到 registry。Store 归档经过完整性检查,并在隔离的解包目录中完成全部验证,归档文件随后才能进入可写包状态。插件安装接受桌面策略允许的 registry 包 spec,但绝不接受原始 pnpm 命令。激活前必须具备精确版本、lockfile 完整性、经过评审的 `allowBuilds` 集合、仅限用户的目录权限、遮盖后的诊断和健康检查。 +核心 dsh 和私有 Desktop Host 只来自签名应用的资源树。插件安装接受桌面策略允许的 registry 包规格,不接受原始 pnpm 命令。激活前要求精确版本、锁文件完整性、经过审查的 `allowBuilds` 集合、仅限用户访问的目录权限和健康检查。 -Electron 产物必须签名;macOS 产物必须公证。发布自动化必须通过明确的环境变量提供应用 ID、macOS Developer ID 限定名、预期 Team ID 与一套完整的 notarytool 凭据。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。Seed 准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。Electron-builder 随后公证应用并钉票、签署 DMG。DMG 的 artifact-completion hook 会单独公证每个 DMG 并钉票,再要求其使用配置的身份、具备有效票据并通过 Gatekeeper;只有该 hook 成功,上传事件才会执行。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 拥有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 +Electron 产物必须签名;macOS 产物必须公证。发布自动化必须通过明确的环境变量提供应用 ID、macOS Developer ID 限定名、预期 Team ID 与一套完整的 notarytool 凭据。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。运行时准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。Electron-builder 随后公证应用并钉票、签署 DMG。DMG 的 artifact-completion hook 会单独公证每个 DMG 并钉票,再要求其使用配置的身份、具备有效票据并通过 Gatekeeper;只有该 hook 成功,上传事件才会执行。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 拥有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 -Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool 提供 `DSH_DESKTOP_WINDOWS_CER_FILE` 指定的公开 EV 叶证书,并通过必需的 `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` 标识匹配的私钥。证书文件保留在源码仓库之外,私钥仍留在 USB Token 上。electron-builder hook 把每个产物交给采用 CRLF 的 `windows-sign.cmd`;该 CMD 只调用一次 SignTool,并指定 SafeNet `/kc "[{{PIN}}]=容器"` 值与 CSP、SHA-256 文件摘要和 DigiCert SHA-256 RFC 3161 时间戳。hook 不会改用其他 SignTool,也不会重试失败的请求。打包编排不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 seed 准备子进程,只会把证书路径、SignTool 路径、密钥容器和 PIN 传入 electron-builder。签名器在已清理的 CMD 环境中只提供经过校验的签名字段;CMD 会禁用延迟展开,在 SignTool 启动前清除这些字段,并仅在 SignTool 必需的命令行中保留 PIN。所有对外诊断都会替换 PIN,而且只能允许专用构建账号和管理员检查该 runner。签名器会在企业 Code Integrity 检查 electron-builder 的临时 NSIS bootstrap 前先为该可执行文件签名;对于生成的可执行文件,只有证书表条目指向文件末尾之外时,才会在最终签名前清除该条目。SignTool、证书、容器、PIN、Token 或签名不可用时,打包会在产生未签名产物前失败。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 持有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 +Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool 提供 `DSH_DESKTOP_WINDOWS_CER_FILE` 指定的公开 EV 叶证书,并通过必需的 `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` 标识匹配的私钥。证书文件保留在源码仓库之外,私钥仍留在 USB Token 上。electron-builder hook 把每个产物交给采用 CRLF 的 `windows-sign.cmd`;该 CMD 只调用一次 SignTool,并指定 SafeNet `/kc "[{{PIN}}]=容器"` 值与 CSP、SHA-256 文件摘要和 DigiCert SHA-256 RFC 3161 时间戳。hook 不会改用其他 SignTool,也不会重试失败的请求。打包编排不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程,只会把证书路径、SignTool 路径、密钥容器和 PIN 传入 electron-builder。签名器在已清理的 CMD 环境中只提供经过校验的签名字段;CMD 会禁用延迟展开,在 SignTool 启动前清除这些字段,并仅在 SignTool 必需的命令行中保留 PIN。所有对外诊断都会替换 PIN,而且只能允许专用构建账号和管理员检查该 runner。签名器会在企业 Code Integrity 检查 electron-builder 的临时 NSIS bootstrap 前先为该可执行文件签名;对于生成的可执行文件,只有证书表条目指向文件末尾之外时,才会在最终签名前清除该条目。SignTool、证书、容器、PIN、Token 或签名不可用时,打包会在产生未签名产物前失败。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 持有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 -打包应用会忽略开发资源和项目环境变量覆盖。只有未打包的 Electron 进程可以替换 Node.js 可执行文件、pnpm 入口、seed 或活跃项目。 +打包应用会忽略开发资源和项目环境变量覆盖。只有未打包的 Electron 进程可以替换 Node.js 可执行文件、pnpm 入口、dsh 资源 或活跃项目。 在种子 store 子集之外,内置上游 Node.js 与 pnpm 预计增加约 35–50 MB 压缩体积和 120–165 MB 安装体积。分架构构建必须报告实际组件级体积增量。 @@ -107,10 +97,10 @@ Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool |---|---| | 壳 | `apps/desktop` 负责 Electron 窗口、受限 preload、自定义协议、子进程生命周期、项目事务、插件 GUI、更新协调和 electron-builder 配置。 | | 已安装运行时 | 私有 `@deepseek-ai/dsh-desktop-host` 从活跃项目启动无端口桌面组合,并通过经过验证的分帧字节管道流式传输 API 与资源响应。 | -| 包状态 | 发布种子和后续每次修改都通过内置 Node.js 与 pnpm 执行,并使用桌面端拥有的 store、config、cache、state 和 home 路径;核心包从发布 tarball 解析,插件从固定 npm registry 解析。 | -| 资格验证 | macOS 打包要求已配置的公司身份与公证凭据可用,在解包最终归档后验证每个原生 seed 对象,验证完整应用签名,并要求应用和 DMG 都完成公证且通过 Gatekeeper。Windows 打包要求已配置的公开证书、SafeNet 私钥容器、Token Password 与 SignTool,并验证生成的每个签名。更新托管、跨上一版本的已安装产物测试和各平台 GUI 录制仍是发布环境门槛。 | +| 包状态 | 内置 Node.js 执行不可变核心资源;内置 pnpm 只修改 Desktop staging 中的外部插件依赖图。 | +| 资格验证 | macOS 打包要求已配置的公司身份与公证凭据可用,在生成清单前验证每个原生运行时文件,验证完整应用签名,并要求应用和 DMG 都完成公证且通过 Gatekeeper。Windows 打包要求已配置的公开证书、SafeNet 私钥容器、Token Password 与 SignTool,并验证生成的每个签名。更新托管、跨上一版本的已安装产物测试和各平台 GUI 录制仍是发布环境门槛。 | -`dev:desktop` 会构建当前 workspace,把已构建 CLI 包、私有 Desktop Host 包及其依赖链接投影为一次性项目,使用隔离的 Harness home,打开 Main、Renderer 和 Host 调试器,并在不准备发布资源的情况下启动未打包 Electron。该模式的链接依赖图不是由 pnpm 安装的桌面项目,因此会禁用包修改。固定的 macOS arm64、macOS x64 与 Windows x64 打包命令会把同一目标传给运行时准备、seed 安装和 electron-builder;每条命令还提供未封装安装器的变体,用于在生成安装器前验证发布路径。 +`dev:desktop` 会构建当前 workspace,把已构建 CLI 包、私有 Desktop Host 包及其依赖链接投影为一次性项目,使用隔离的 Harness home,打开 Main、Renderer 和 Host 调试器,并在不准备发布资源的情况下启动未打包 Electron。该模式的链接依赖图不是由 pnpm 安装的桌面项目,因此会禁用包修改。固定的 macOS arm64、macOS x64 与 Windows x64 打包命令会把同一目标传给运行时准备、运行时准备和 electron-builder;每条命令还提供未封装安装器的变体,用于在生成安装器前验证发布路径。 ## 考虑过的替代方案 @@ -122,11 +112,11 @@ Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool **复用现有 CLI 或浏览器插件安装器。** 这会跨越桌面授权与发布 scope,并可能使用用户的包管理器状态。桌面包修改完全由 Electron 拥有。 -**让 desktop profile 使用 CLI 管理的包或插件。** 任一产品都可能改变另一方的依赖图、Cordis 版本、插件版本或原生模块。因此 desktop profile 持有完整 `node_modules`,并拒绝通过 CLI profile fallback 解析 bundle。 +**让桌面 profile 使用 CLI 管理的包或插件。** 任一产品都可能改变另一产品的依赖图、Cordis 版本、插件版本或原生模块。Desktop 拒绝通过 CLI profile 回退目录解析包。 -**把 dsh 与插件安装到不同桌面项目。** 这会产生第二解析锚点和 peer dependency 回退。一个普通 npm 项目已经提供所需安装与解析模型。 +**分离核心与插件解析,却不明确共享包归属。** 这会允许宿主模块重复以及不可控的 peer 回退。[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)为分离的资源和 profile 目录提供明确链接及依赖验证。 -**从 registry 包删除非目标 Mach-O 文件。** 架构裁剪可以节省少量 seed 空间,但包可能有意附带多个架构变体,调用方也可以观察安装后的文件集。签署每个实际携带的 Mach-O 对象,无需发明 Desktop 专属包布局就能满足公证要求。 +**从 registry 包删除非目标 Mach-O 文件。** 架构裁剪可以节省少量 运行时空间,但包可能有意附带多个架构变体,调用方也可以观察安装后的文件集。签署每个实际携带的 Mach-O 对象,无需发明 Desktop 专属包布局就能满足公证要求。 **把 Windows EV 私钥导出到 PFX 文件。** 外部提供的公开叶证书让 SignTool 构造签名,`/csp` 与 `/kc` 则定位硬件密钥。EV 私钥保持不可导出,并留在 Token 上。 @@ -136,9 +126,9 @@ Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool ## 结果 -- 没有系统 Node.js 或 pnpm 的干净离线机器把种子安装进 `.dsh/profiles/desktop`,并启动可工作的 dsh 会话。 -- 已签名应用记录固定少量的 seed store 分片,而不是记录每个 pnpm 缓存文件;macOS 分片内每个 Mach-O 对象都带有发布 Developer ID、安全时间戳与 hardened runtime,每个 Windows 产物都带有配置的硬件支持 EV 签名,安装后的私有 store 仍保持普通 pnpm 布局。 -- `.dsh/profiles/desktop/node_modules` 包含并解析桌面 dsh 包和每个 GUI 安装的桌面插件。 +- 没有系统 Node.js 或 pnpm 的干净离线机器能够启动内置 dsh,无需安装核心依赖。 +- 签名应用记录最终运行时文件清单;每个 macOS 原生文件都具有发布 Developer ID、安全时间戳和 hardened runtime,每个 Windows 产物都具有配置的硬件 EV 签名。 +- `.dsh/profiles/desktop/node_modules` 能解析共享宿主链接和每个通过 GUI 安装的桌面插件。 - 每个桌面 pnpm 操作都使用内置可执行文件和 `.dsh/desktop/pnpm/store`;不读取用户 `PATH`、配置、store 或 profile `node_modules`。 - Electron-only GUI 安装、删除和更新普通 npm 插件包,而不暴露原始 pnpm 参数。 - 后端与浏览器应用不能修改桌面包。 @@ -157,8 +147,8 @@ Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool | 决策 | 建议 | |---|---| -| 首次启动 | 打包离线种子 store 子集,并通过 pnpm 安装 | -| Desktop profile | 一个包含精确 dsh 与插件依赖、由 Electron 持有的保留 profile | +| 首次启动 | 验证内置生产包并创建 profile 链接,不安装核心依赖 | +| 桌面 profile | 一个由 Electron 拥有的保留 profile,保存外部插件和共享包链接 | | 插件管理 | Electron-only GUI 与包服务;没有 CLI、后端或浏览器安装路径 | | 激活 | 暂存项目、完整健康检查、记录式目录替换和一个回滚副本 | | 初始平台 | macOS arm64/x64 与 Windows x64;Linux 尚无受支持的发布目标 | @@ -175,3 +165,7 @@ Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool 不同操作系统的目录替换行为不同,而且可能中断。激活记录与已安装产物故障测试必须证明每次文件系统移动都可以恢复。 代码签名、公证和更新托管需要生产发布基础设施。只运行仓库测试不能完成这些认证。 + +## 相关提案 + +[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)取代本记录的离线 运行时准备与单项目包归属决策。发布身份、签名、无端口传输、进程归属及仅限 Electron 的包授权仍由本记录负责。 diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml new file mode 100644 index 0000000000..9729df077f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.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-08-desktop-bundled-runtime-and-external-plugins.md +2026-09-08-desktop-bundled-runtime-and-external-plugins.md: 8278107fb3c37aca909541886d9379a1bfd64bac +2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md: b29eb1e6cbe19d4a5b4ea23a5d6159cfd3973bcd diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md new file mode 100644 index 0000000000..8278107fb3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md @@ -0,0 +1,51 @@ +# Agent Note: Bundle the Desktop runtime and retain external plugins + +Status: implemented + +English | [中文](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md) + +## Problem + +Installing the core dependency graph during Desktop initialization repeats work already done by the release builder. An offline store eliminates downloads but retains extraction, package-manager startup, and installation costs. Users need the application to start with its production packages present while retaining ordinary npm plugin installation and plugin state across application upgrades. + +Separate package directories can load duplicate Cordis or service modules. Retaining plugin files also does not prove compatibility with a new host API or Node runtime. + +## Decision + +[Runtime preparation](../../../../apps/desktop/scripts/prepare-dsh.ts) materializes the production graph once at build time and ships it through `extraResources/dsh`. The Electron shell stays in ASAR. A bundled upstream Node process runs the private Desktop Host from resources and loads enabled plugins from `$DSH_HOME/profiles/desktop`. + +Desktop has not been released. This is its first installation format; there are no readers or migrations for the unpublished seed-based profile. This note supersedes core seed installation and single-project dependency ownership in the [Desktop packaging decision](2026-08-25-electron-desktop-packaging-and-updates.md). That note continues to own release identity, signing, portless transport, process ownership, and Electron-only plugin authorization. No existing note is fully superseded or archived. + +## Package ownership + +The resource descriptor records the exact release, Node version, platform, architecture, shared package versions, and final file hashes. The runtime tree contains ordinary files and directories, without links back to pnpm’s build store. Native Mach-O files are signed before hashing; the application signer preserves their bytes and checks the inventory after signing. An explicit `dsh/node_modules` resource mapping bypasses electron-builder’s root `node_modules` exclusion, and the copied tree is verified before any signing or notarization. + +Every first-party package in the dsh and private Host production closures is shared. The profile contains directory symlinks to those resource packages, or junctions on Windows. Links resolve to real host package directories under normal Node resolution. Host and plugin imports therefore share the same module instance for each resolved export. Distinct ESM and CommonJS conditional exports remain distinct entry points; a link cannot merge a package’s dual implementations. + +External plugins declare shared host packages as peers. Ordinary dependencies remain plugin-owned and may differ from the versions used by dsh. Validation rejects incompatible enabled peers, nested or aliased copies of shared packages, private package links, and dependency resolution through CLI or other ancestor directories. A third-party package requiring host-wide instance identity must be explicitly added to the runtime’s shared inventory; matching version numbers alone are insufficient. + +The profile manifest records exact installed plugin dependencies separately from its enabled bundle list. Disabling a plugin preserves its package, lockfile entry, and user configuration. The shared links are Desktop-owned derived state, recorded separately from pnpm; package-manager operations run without those links, then Desktop recreates and validates them. + +## Transactions and upgrades + +First launch creates profile metadata and host links without running pnpm. A compatible release change or application relocation copies plugin files into staging, refreshes links, validates enabled peers, and boots the staged backend. Node version, platform, or architecture changes reinstall the locked plugin graph before activation. Writable staging and rollback files are independent copies, never hardlinks into the active profile. + +Dependency mutations install with scripts disabled, validate the plugin graph and host links, run the reviewed pending lifecycle builds, and validate again. This permits approved native dependencies to resolve host peers while preventing accidental duplicate host packages from reaching startup. The `allowBuilds` policy remains explicit; unsupported build-requiring dependencies fail the transaction. + +The transaction journal records source and target runtime identities and directory-move phases. Desktop waits for pnpm exit and stops the active backend before replacement. A failed or interrupted activation restores a complete profile. A runtime identity mismatch prevents the restored profile from booting under a different application release. The journal covers profile files, not arbitrary plugin startup effects or durable Session writes. + +An Electron-owned recovery window remains available when the backend cannot start. Users can update, remove, disable, or re-enable plugins and retry startup. Incompatible plugins are not silently deleted or automatically downgraded. Application rollback and profile rollback are separate operations; each backend launch requires the current runtime identity. + +## Alternatives considered + +- **Install the bundled offline seed at startup.** This preserves an ordinary pnpm installation procedure but repeats core extraction and installation on every affected machine. Materialized resources remove that work at the cost of more application files and release-builder responsibility. +- **Link all host dependencies into plugins.** This unnecessarily couples ordinary plugin dependencies to the host. Only the explicit shared inventory is linked; private packages retain independent versions. +- **Use hardlinks.** They cannot represent directories, may not cross volumes, share writable bytes, and retain old inodes after application replacement. Directory symlinks and Windows junctions express the intended package target. +- **Use `NODE_PATH` or preserve symlink paths.** These do not provide uniform ESM resolution or shared module identity. Normal package lookup through explicit links is directly testable. +- **Keep core packages in ASAR.** The backend uses upstream Node rather than Electron’s patched filesystem. Ordinary `extraResources` also preserves native loading and subprocess paths. + +## Consequences + +Core package installation is absent from first launch and compatible upgrades. Runtime integrity verification and a complete backend health check still cost startup time; no release latency or download-size improvement is claimed without measurement. Plugin preservation is conditional on host API and native runtime compatibility, with a visible recovery path when that condition fails. + +The [Desktop README](../../../../apps/desktop/README.md) owns operational guidance. Focused tests cover real pnpm installation and approved builds, shared ESM instance identity, private dependency versions, relocation, disabled plugins, native rebuild selection, activation failures, and transaction locking. Signed installed-artifact upgrades, macOS notarization, Windows junction/native behavior, release size and startup benchmarks, and real-model GUI recordings remain release-environment qualification requirements; unit fixtures do not substitute for them. diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md new file mode 100644 index 0000000000..b29eb1e6cb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md @@ -0,0 +1,51 @@ +# Agent Note: 内置 Desktop 运行时并保留外部插件 + +Status: implemented + +[English](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) | 中文 + +## 问题 + +Desktop 初始化时安装核心依赖图,会重复发布构建器已经完成的工作。离线 store 消除了下载,但仍有解压、包管理器启动和安装成本。用户需要应用在生产依赖已就绪时启动,同时保留普通 npm 插件安装能力,以及跨应用升级的插件状态。 + +分离的包目录可能加载重复的 Cordis 或服务模块。仅保留插件文件也不能证明它与新的宿主 API 或 Node 运行时兼容。 + +## 决策 + +[运行时准备](../../../../apps/desktop/scripts/prepare-dsh.ts)在构建时物化一次生产依赖图,并通过 `extraResources/dsh` 分发。Electron 壳保留在 ASAR 中。内置上游 Node 进程从资源启动私有 Desktop Host,并从 `$DSH_HOME/profiles/desktop` 加载已启用插件。 + +Desktop 尚未发布。这是它的第一种安装格式;不提供未发布 seed profile 的读取器或迁移。本记录取代 [Desktop 打包决策](2026-08-25-electron-desktop-packaging-and-updates.zh.md)中的核心 seed 安装和单项目依赖归属部分。该记录继续负责发布身份、签名、无端口传输、进程归属和仅限 Electron 的插件授权。没有现有记录被完全取代或归档。 + +## 包归属 + +资源描述文件记录精确发布版本、Node 版本、平台、架构、共享包版本和最终文件哈希。运行时树包含普通文件和目录,不包含指回 pnpm 构建 store 的链接。原生 Mach-O 文件先签名再哈希;应用签名器保留其字节,并在签名后检查清单。明确的 `dsh/node_modules` 资源映射绕过 electron-builder 对根 `node_modules` 的排除,并在任何签名或公证前验证复制后的依赖树。 + +dsh 与私有 Host 生产闭包中的每个第一方包都共享。profile 包含指向这些资源包的目录软链接,在 Windows 上使用 junction。正常 Node 解析会把链接解析到实际宿主包目录。因此,宿主与插件对每个已解析导出的导入共享同一模块实例。不同的 ESM 与 CommonJS 条件导出仍是不同入口;链接不能合并包的两套实现。 + +外部插件把共享宿主包声明为 peer。普通依赖由插件拥有,可以不同于 dsh 使用的版本。验证拒绝已启用插件的不兼容 peer、共享包的嵌套或别名副本、私有包链接,以及通过 CLI 或其他祖先目录解析依赖。如果第三方包需要宿主范围的实例身份,必须明确加入运行时共享清单;版本号相同并不足够。 + +profile manifest 分别记录精确的已安装插件依赖和已启用 bundle 列表。停用插件会保留其包、锁文件条目和用户配置。共享链接是 Desktop 拥有的派生状态,独立于 pnpm 记录;包管理器操作不携带这些链接,随后 Desktop 重建并验证它们。 + +## 事务与升级 + +首次启动创建 profile 元数据和宿主链接,不运行 pnpm。兼容的发布变化或应用移动会把插件文件复制到 staging,刷新链接,验证已启用的 peer,并启动 staging 后端。Node 版本、平台或架构变化时,激活前会重新安装锁定的插件依赖图。可写 staging 与回滚文件使用独立副本,不使用指向活动 profile 的硬链接。 + +依赖修改先禁用脚本安装,验证插件依赖图和宿主链接,运行经过审查的待执行生命周期构建,再次验证。这允许已批准的原生依赖解析宿主 peer,同时阻止意外的重复宿主包进入启动过程。`allowBuilds` 策略保持明确;不受支持且需要构建的依赖会使事务失败。 + +事务日志记录源与目标运行时身份以及目录移动阶段。Desktop 等待 pnpm 退出,并在替换前停止活动后端。失败或中断的激活会恢复完整 profile。运行时身份不匹配会阻止恢复的 profile 在其他应用版本下启动。事务日志覆盖 profile 文件,不覆盖任意插件启动副作用或持久 Session 写入。 + +后端无法启动时,Electron 拥有的恢复窗口仍可使用。用户可以更新、移除、停用或重新启用插件,并重试启动。不兼容插件不会被静默删除或自动降级。应用回滚与 profile 回滚是独立操作;每次后端启动都要求当前运行时身份。 + +## 考虑过的替代方案 + +- **启动时安装内置离线 seed。** 这保留普通 pnpm 安装流程,但会在每台受影响机器上重复核心解压与安装。物化资源消除了这部分工作,代价是更多应用文件和发布构建器责任。 +- **把所有宿主依赖链接给插件。** 这会让普通插件依赖与宿主产生不必要的耦合。只链接明确的共享清单;私有包保留独立版本。 +- **使用硬链接。** 它不能表示目录,可能无法跨卷,共享可写字节,并在应用替换后保留旧 inode。目录软链接和 Windows junction 能表达预期的包目标。 +- **使用 `NODE_PATH` 或保留软链接路径。** 它们不能提供统一的 ESM 解析或共享模块身份。通过明确链接进行正常包查找可以直接测试。 +- **把核心包留在 ASAR。** 后端使用上游 Node,而不是 Electron 修改过的文件系统。普通 `extraResources` 也能保留原生加载和子进程路径。 + +## 影响 + +首次启动和兼容升级不安装核心包。运行时完整性验证和完整后端健康检查仍需要启动时间;没有测量前,不声称发布启动延迟或下载体积改善。插件保留以宿主 API 和原生运行时兼容为条件,条件不满足时提供可见的恢复入口。 + +[Desktop README](../../../../apps/desktop/README.zh.md)负责操作说明。定向测试覆盖真实 pnpm 安装与已批准构建、共享 ESM 实例身份、私有依赖版本、应用移动、停用插件、原生重建选择、激活失败和事务锁。签名安装产物升级、macOS 公证、Windows junction 与原生行为、发布体积与启动基准,以及真实模型 GUI 录制仍是发布环境验收要求;单元夹具不能替代这些验证。 diff --git a/.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.i18n.yaml b/.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.i18n.yaml new file mode 100644 index 0000000000..cd64ee4423 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.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-08-desktop-uninstall-preserve-dsh-home.md +2026-09-08-desktop-uninstall-preserve-dsh-home.md: e1c2435814a4563f1fed6652d521928200d4ade7 +2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md: 27fd7c8cbec360db35cadc75ff26b575629ad571 diff --git a/.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md b/.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md new file mode 100644 index 0000000000..e1c2435814 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.md @@ -0,0 +1,95 @@ +# Agent Note: Uninstall Desktop while preserving the Harness home + +Status: proposed + +English | [中文](2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md) + +## Problem + +Users need Desktop uninstallation to remove its application files and external application state while retaining the complete Harness home. Removing an application directory does not account for browser storage, cached installers, or native updater state. Browser storage also contains unsent drafts and UI preferences, so removing it changes more than disk cache usage. + +The [packaging configuration](../../../../apps/desktop/electron-builder.config.mjs), [desktop entry](../../../../apps/desktop/src/main.ts), and [update coordinator](../../../../apps/desktop/src/update-coordinator.ts) are the inspection inputs. Source inspection identifies cleanup candidates; installed-artifact observation must establish the complete supported inventory before implementation is accepted. No uninstall experiment has yet established an exhaustive Windows or macOS inventory. + +## Proposal + +Provide an uninstall operation whose successful result leaves the complete default `~/.dsh` and any configured `DSH_HOME` intact, removes Desktop-owned files outside those homes, and removes the selected application installation. Preserve plugin files, package-manager state, sessions, settings, and credentials within the retained homes. Do not launch or repair the Desktop profile during cleanup. + +Windows Control Panel and Settings uninstallation will run this operation through NSIS. macOS will expose a localized **Uninstall and keep Harness data** action backed by a signed cleanup helper. Finder drag-to-Trash alone cannot invoke this operation; document that limitation and provide the same helper as a signed standalone uninstaller for users who already removed the application. A plain drag operation must not be advertised as complete cleanup. + +User-created projects, separately installed CLI software, user-saved downloads and exports, arbitrary third-party plugin/tool outputs, and OS-maintained audit/security records are outside application cleanup. Do not search the disk for names containing `dsh` or `DeepSeek`. The success promise concerns application-owned state, not deletion of user work or erasure of OS history. + +### 1. Establish ownership and actual paths + +Use disposable Windows and macOS accounts to capture filesystem and relevant registration differences across installation, first launch, draft editing, plugin installation, update download, update installation, and uninstallation. Inspect the packaged `package.json`, macOS `Info.plist`, `app-update.yml`, and runtime `app.getPath()` values. Include failed/interrupted updates. Record discovered owners and cleanup locations beside the desktop implementation, with fixture evidence rather than a dynamically accepted list of arbitrary absolute paths. + +| Candidate | Windows | macOS | Required treatment | +|---|---|---|---| +| Electron user/session data | Runtime `userData` and `sessionData`, normally under `%APPDATA%` | Runtime `userData` and `sessionData`, normally under `~/Library/Application Support` | Remove browser storage, preferences, cache, and `.updaterId`; disclose loss of unsent drafts. | +| Installer/update cache | `%LOCALAPPDATA%/` | `~/Library/Caches/` | Remove cached installers, ZIPs, blockmaps, pending downloads, and metadata; include the NSIS installer copy created during installation. | +| Native updater state | Any additional paths proved by the installed NSIS flow | App-specific Squirrel and `.ShipIt` cache/state/log directories | Stop the owned updater job and remove its remaining state after it exits. | +| Other native application state | App-owned files/registrations proved by observation | App-specific preferences, saved state, logs, or diagnostics proved by observation | Add only established ownership; an Electron path API alone does not prove a file is created. | +| Application and integration | Installation directory, installed shortcuts, installation/uninstallation registration | Selected `.app` and helper-owned integration | Use the native uninstall flow and validate the selected installation identity. | +| Harness home | Default `.dsh` and configured `DSH_HOME` | Default `.dsh` and configured `DSH_HOME` | Preserve the complete trees, including Desktop-only subdirectories. | + +Create one small application-owned cleanup inventory, consumed by packaging and cleanup implementations. Derive identity and updater cache names from the release metadata. The same inventory must explain test expectations. Verify any existing distributed release before adding a legacy path; do not introduce migrations for unpublished development layouts. + +### 2. Implement shared preservation and cleanup rules + +Resolve targets for the installation owner, not the elevated administrator's home. Preserve the default home even when an override is active, and protect configured homes recorded by Desktop as well as the current override. Validate any persisted record at this file boundary; it may protect a location but may never authorize deletion of an arbitrary location. + +Reject deletion of a protected home, its ancestor, or its contents. Account for case-insensitive paths, symlinks, Windows junctions/reparse points, and path replacement during cleanup. Do not follow a link into another tree. An installation or cache location containing a protected home is a conflict: stop before recursive removal and report the remaining path. Keep these checks in the actual native removal path, not only in a preview. + +Stop new windows, updates, and plugin mutations; finish or safely stop active operations; stop the owned Host/process tree; then wait for exit and released files before removal. Do not kill processes solely by executable name. Perform an ownership/path preflight before destructive steps. Treat missing targets as success, and support retry after partial cleanup. Report locked or inaccessible paths explicitly; a queued reboot deletion or partial result is not complete cleanup. + +Keep `.dsh` free of cleanup journals or receipts. Any temporary helper/state must live in a private temporary directory, avoid executable-search-path lookup, and have a bounded self-cleanup path. Verify that cleanup does not recreate Electron user data after it has been removed. Cancellation before removal leaves the installation usable. + +### 3. Windows implementation + +Keep the assisted NSIS installer (`oneClick: false`). Extend its custom uninstall hooks and removal ordering rather than replacing the complete installer. Do not depend on `deleteAppDataOnUninstall` to cover updater caches, custom paths, or protected homes. Apply preservation checks before the default installation-directory removal as well as before extra cleanup. + +Normal Control Panel, Settings, direct uninstaller, and silent uninstall must share the same cleanup rules and useful exit status. Automatic update/replacement must skip destructive user-state cleanup; validate the actual electron-updater flags and NSIS update condition with a real upgrade. A failed upgrade must retain browser data and `.dsh`. + +Per-user uninstall cleans that installation owner's Desktop state. All-user uninstall must identify each affected local user profile and clean its Desktop-owned state while preserving every Harness home, under the required Windows privileges. Do not resolve all users through one `$APPDATA` expansion. If an affected profile is inaccessible or another installation still owns a shared path, report that condition instead of deleting shared state or claiming complete cleanup. Include this distinction in the uninstall UI and silent result. + +Let NSIS remove the application, its installed shortcuts, and installation registration. Explicitly remove the application-owned cache/user-data inventory, including the cached copy of the installer. Preserve existing signing requirements for installer, uninstaller, and any added executable. Add a build-time check that custom hooks and the cleanup inventory are actually packaged. + +### 4. macOS implementation + +Add the localized uninstall action to the Electron-owned menu/recovery UI so it remains available when the Host cannot boot. Before proceeding, show that `.dsh` is retained and unsent drafts/UI preferences outside it are deleted. Complete cleanup must include removal of the selected application bundle; if only moving it to Trash, report that disk space remains until Trash is emptied. + +Use a signed helper that can finish after Electron and the Host exit. Verify bundle identity and the selected path before removing it; handle `/Applications`, `~/Applications`, and a relocated writable bundle. Obtain authorization only for paths requiring it. Coordinate with Squirrel/ShipIt, remove only this application's updater jobs/state, and delete the discovered external application directories and preferences. Include helper staging files in completion verification. + +Package the same cleanup implementation as a signed, notarized standalone uninstaller for the already-deleted-app case. It must not require the removed bundle or a working `.dsh` profile. A read-only mounted DMG is not an installed writable application; provide an actionable result rather than attempting to alter it. For a shared application installation, account for affected users and privileges as on Windows; report any state that could not be cleaned. + +### 5. Verification and documentation + +Add focused tests for target ownership, protected-home overlap, link/reparse-point traversal, identity mismatch, arbitrary-path rejection, custom/absent `DSH_HOME`, another installation sharing data, and inaccessible profiles. Exercise cancellation, active Host/update/plugin processes, interruption between removals, retries, and self-cleanup without using the developer's real home. Follow the [CI reliability workflow](../../../skills/dsh-ci-test-reliability/SKILL.md) when implementing process and filesystem tests. + +Run installed-artifact e2e checks on Windows and both shipped macOS architectures. Cover first installation without updates, one downloaded/installed update, failed update, per-user/shared installation, relocated application, and standalone macOS cleanup after drag deletion. Compare filesystem/registration inventories independently of the uninstaller's success response. Hash retained `.dsh` content after the app and CLI are quiescent and before removal; require identical content, paths, and link entries afterward. Do not require preserved runtime links to resolve after their application target is removed. + +Add owner-local expected output for uninstall UI and failure results. Add a keyless recorded-session scenario proving an existing conversation survives uninstall/reinstall; keep purely installer/UI expectations outside the top-level Session tree. Record the required real-server/model GUI GIF for the implementation PR. Update the [Desktop README](../../../../apps/desktop/README.md), its Chinese counterpart, user instructions, locale dictionaries, JSDoc, and this proposal's lifecycle when implementation ships. Select focused checks through [dsh-pre-push-checks](../../../skills/dsh-pre-push-checks/SKILL.md); signed packaging and real OS uninstall evidence are required, not replaceable by unit tests. + +## Alternatives considered + +**Keep the default uninstallers.** They do not establish removal of application-owned state outside the application directory and therefore do not meet the requested outcome. + +**Move all Electron and update data under `.dsh`.** This can simplify file placement but preserves caches and browser state instead of cleaning them, and does not by itself cover Squirrel/native state or existing external files. It is not the cleanup solution proposed here. + +**Detect Finder deletion with a permanent background watcher.** This adds a resident component that itself needs removal and cannot reliably cover deletion while it is stopped. Use an explicit uninstall operation. + +**Delete `.dsh/desktop` or `.dsh/profiles/desktop`.** These paths contain Desktop-specific state, but the requested retention rule preserves the whole Harness home rather than only conversations. + +## Acceptance criteria + +- A successful supported uninstall removes the selected application, its owned registrations, and every external application-owned path established by the installed-artifact inventory; no cleanup helper or updater process remains. +- Default and configured Harness homes retain identical content and links after quiescence. User projects and independent CLI installations remain intact. +- Windows Control Panel/Settings and silent uninstall satisfy the same retention rule. An actual automatic upgrade retains browser state and Harness data. +- macOS's explicit and standalone uninstallers satisfy the cleanup rule. Documentation accurately distinguishes them from Finder drag deletion and from merely moving files to Trash. +- Every unremoved owned path is reported with a retry/recovery action. Unavailable privileges, an inaccessible user profile, and shared ownership never produce a false full-success result. +- Fresh install and uninstall/reinstall tests prove no untracked outside-home application state survives and that retained conversations can be reopened. Native OS inventories, not only mocked API calls, establish completion. + +## Risks + +Deleting browser storage loses unsent drafts and UI preferences. Whole-home preservation deliberately retains Desktop plugins, pnpm state, and possibly dangling links until reinstall repairs them. Custom data paths and shared installations can prevent complete removal without additional privileges or path relocation; the operation must report that limitation rather than violate retention. + +OS-owned security/audit history and user-created files cannot be covered by a promise of erasing all traces. The [Desktop packaging decision](../../implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) and [bundled runtime/external plugin decision](../../implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md) remain independent authorities for packaging and data ownership; this proposal supersedes neither and archives no active note. diff --git a/.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md b/.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md new file mode 100644 index 0000000000..27fd7c8cbe --- /dev/null +++ b/.agents/notes/proposed/feature/2026-09-08-desktop-uninstall-preserve-dsh-home.zh.md @@ -0,0 +1,95 @@ +# Agent Note: 卸载 Desktop 并保留 Harness 主目录 + +Status: proposed + +[English](2026-09-08-desktop-uninstall-preserve-dsh-home.md) | 中文 + +## 问题 + +用户需要 Desktop 卸载删除应用文件及外部应用状态,同时保留完整的 Harness 主目录。删除应用目录并不能覆盖浏览器存储、安装器缓存或原生更新器状态。浏览器存储还包含未发送草稿和界面偏好,因此清理它不只是释放磁盘缓存。 + +[打包配置](../../../../apps/desktop/electron-builder.config.mjs)、[桌面入口](../../../../apps/desktop/src/main.ts)和[更新协调器](../../../../apps/desktop/src/update-coordinator.ts)是代码检查依据。源码检查用于识别清理候选项;实现验收前,必须通过已安装产物的观察确定受支持的完整清单。目前尚未通过卸载实验建立完整的 Windows 或 macOS 清单。 + +## 提案 + +提供卸载操作:成功后保留完整的默认 `~/.dsh` 和已配置的 `DSH_HOME`,删除这些主目录之外由 Desktop 拥有的文件,并移除选定的应用安装。保留主目录内的插件文件、包管理器状态、会话、设置和凭据。清理期间不得启动或修复 Desktop profile。 + +Windows 控制面板和设置中的卸载将通过 NSIS 执行此操作。macOS 将提供本地化的**卸载并保留 Harness 数据**操作,由签名的清理辅助程序完成;单纯通过 Finder 拖进废纸篓不能调用此操作,文档必须说明这一限制,并将同一辅助程序作为签名的独立卸载器提供给已经删除应用的用户。不得把单纯拖拽宣传为完整清理。 + +用户创建的项目、单独安装的 CLI(命令行界面)软件、用户保存的下载文件和导出文件、任意第三方插件或工具的输出,以及操作系统维护的审计和安全记录,不属于应用清理范围。不得按文件名包含 `dsh` 或 `DeepSeek` 全盘搜索。成功承诺针对应用拥有的状态,不包括删除用户工作成果或抹除系统历史。 + +### 1. 确定归属和实际路径 + +使用一次性 Windows 和 macOS 账户,记录安装、首次启动、编辑草稿、安装插件、下载更新、安装更新及卸载前后的文件系统和相关注册信息差异。检查打包后的 `package.json`、macOS `Info.plist`、`app-update.yml` 和运行时 `app.getPath()` 值。覆盖更新失败和中断。将发现的归属与清理位置记录在桌面实现附近,提供 fixture(测试前置数据)证据,不采用动态接收任意绝对路径的清单。 + +| 候选项 | Windows | macOS | 处理要求 | +|---|---|---|---| +| Electron 用户及会话数据 | 运行时 `userData` 和 `sessionData`,通常位于 `%APPDATA%` 下 | 运行时 `userData` 和 `sessionData`,通常位于 `~/Library/Application Support` 下 | 删除浏览器存储、偏好、缓存和 `.updaterId`;说明未发送草稿会丢失。 | +| 安装器及更新缓存 | `%LOCALAPPDATA%/` | `~/Library/Caches/` | 删除安装器副本、ZIP、blockmap、待处理下载和元数据;包括 NSIS 安装期间创建的安装器缓存副本。 | +| 原生更新器状态 | 通过实际安装的 NSIS 流程证实的其他路径 | 应用专属的 Squirrel 和 `.ShipIt` 缓存、状态及日志目录 | 停止所属更新任务,等待退出后删除残留状态。 | +| 其他原生应用状态 | 观察证实由应用拥有的文件和注册信息 | 观察证实的应用专属偏好、窗口恢复状态、日志或诊断数据 | 只加入归属已确定的项目;存在 Electron 路径 API 不足以证明文件会产生。 | +| 应用及系统集成 | 安装目录、安装的快捷方式、安装和卸载注册信息 | 选定的 `.app` 及辅助程序拥有的系统集成 | 使用原生卸载流程,并验证选定安装的身份。 | +| Harness 主目录 | 默认 `.dsh` 和已配置的 `DSH_HOME` | 默认 `.dsh` 和已配置的 `DSH_HOME` | 保留完整目录树,包括 Desktop 专属子目录。 | + +建立一份精简的应用清理清单,由打包和清理实现共同使用。应用身份与更新缓存名称从发布元数据推导。同一清单必须对应测试期望。加入旧路径前先核查实际已分发版本,不为未发布的开发布局增加迁移。 + +### 2. 实现共用的保留与清理规则 + +按安装所属用户解析目标,不能使用提权管理员的主目录。即使覆盖路径已启用,也保留默认主目录;同时保护 Desktop 已记录的配置主目录和当前覆盖路径。持久化记录在文件边界进行校验;记录可以保护位置,但绝不能授权删除任意位置。 + +拒绝删除受保护主目录、其祖先目录或其内容。处理路径大小写不敏感、符号链接、Windows junction/reparse point,以及清理期间路径被替换的情况。不得沿链接进入其他目录树。如果安装或缓存目录包含受保护主目录,则视为冲突:递归删除前停止,并报告剩余路径。这些检查必须位于实际原生删除流程中,不能只放在预览阶段。 + +阻止新窗口、更新和插件变更;完成或安全停止正在进行的操作;停止所属 Host 和进程树;等待进程退出并释放文件后再删除。不得仅凭可执行文件名终止进程。破坏性步骤前先检查归属和路径。目标不存在视为成功,部分清理后允许重试。明确报告被占用或无法访问的路径;已安排重启后删除或部分完成,不等于完整清理。 + +不得在 `.dsh` 写入清理日志或回执。临时辅助程序和状态必须位于私有临时目录,避免通过可执行文件搜索路径寻找程序,并具有有界的自行清理流程。验证清理不会在删除后重新创建 Electron 用户数据。删除开始前取消操作应保持安装可用。 + +### 3. Windows 实现 + +保留向导式 NSIS 安装器(`oneClick: false`)。扩展自定义卸载钩子和删除顺序,不替换整个安装器。不得依赖 `deleteAppDataOnUninstall` 覆盖更新缓存、自定义路径或主目录保护。在默认安装目录删除和额外清理前都应用保留检查。 + +正常控制面板、设置、直接运行卸载器和静默卸载必须共用清理规则,并返回有用的退出状态。自动更新或替换安装必须跳过破坏性的用户状态清理;通过实际升级验证 electron-updater 参数和 NSIS 更新条件。升级失败必须保留浏览器数据和 `.dsh`。 + +按用户安装的卸载清理该安装所属用户的 Desktop 状态。全用户卸载必须识别每个受影响的本地用户配置目录,在具备所需 Windows 权限的情况下清理其中由 Desktop 拥有的状态,并保留每个 Harness 主目录。不能用一次 `$APPDATA` 展开代表所有用户。如果受影响的用户目录无法访问,或另一个安装仍拥有共享路径,应报告该情况,不得删除共享状态或宣称完整清理。卸载界面和静默执行结果都要体现这一区别。 + +由 NSIS 删除应用、安装的快捷方式和安装注册信息。显式删除清单中的应用缓存和用户数据,包括缓存的安装器副本。维持安装器、卸载器及新增可执行文件的签名要求。增加构建期检查,证明自定义钩子和清理清单确实进入产物。 + +### 4. macOS 实现 + +在 Electron 拥有的菜单和恢复界面加入本地化卸载操作,保证 Host 无法启动时仍可使用。执行前说明保留 `.dsh`,并删除主目录外的未发送草稿和界面偏好。完整清理必须包括移除选定应用包;如果只是移入废纸篓,应说明清空废纸篓前仍占用磁盘。 + +使用签名的辅助程序,在 Electron 和 Host 退出后完成清理。删除前验证应用包身份和选定路径;覆盖 `/Applications`、`~/Applications` 及移动后的可写应用包。仅对需要权限的路径请求授权。协调 Squirrel/ShipIt,只移除本应用的更新任务和状态,再删除已识别的外部应用目录及偏好。完成验证必须包括辅助程序的临时文件。 + +把同一清理实现打包为签名、公证的独立卸载器,支持应用已被删除的情况。它不能依赖已删除的应用包或可启动的 `.dsh` profile。只读挂载的 DMG 不属于已安装的可写应用;应给出可操作的结果,不能尝试修改它。共享应用安装和 Windows 一样需要处理受影响用户及权限,并报告未能清理的状态。 + +### 5. 验证和文档 + +增加针对性测试,覆盖目标归属、受保护主目录重叠、链接和 reparse point 遍历、身份不匹配、任意路径拒绝、自定义或未设置的 `DSH_HOME`、另一安装共享数据,以及无法访问的用户配置目录。覆盖取消、活跃 Host/更新/插件进程、删除步骤间中断、重试及自行清理,禁止使用开发者真实主目录。实现进程和文件系统测试时遵循 [CI 可靠性工作流](../../../skills/dsh-ci-test-reliability/SKILL.md)。 + +在 Windows 和两个已发布 macOS 架构上执行已安装产物的 e2e 检查。覆盖首次安装且未更新、下载并安装一次更新、更新失败、按用户或共享安装、移动应用,以及拖拽删除后的独立 macOS 清理。独立比较文件系统和注册信息清单,不以卸载器的成功响应代替验证。应用和 CLI 静止后、删除前对保留的 `.dsh` 内容计算哈希;要求删除后内容、路径和链接条目完全一致。应用目标被删除后,不要求保留的运行时链接仍可解析。 + +为卸载界面和失败结果增加归属模块旁的预期输出。增加无密钥的录制会话场景,证明已有会话能跨卸载和重装保留;纯安装器或界面预期不放入顶层 Session 树。为实现 PR(Pull Request)录制规则要求的真实服务器和模型 GUI GIF。实现交付时更新 [Desktop README](../../../../apps/desktop/README.zh.md)、英文对应文档、用户说明、语言字典、JSDoc 和本提案的生命周期。通过 [dsh-pre-push-checks](../../../skills/dsh-pre-push-checks/SKILL.md) 选择针对性检查;签名打包和真实操作系统卸载证据为必需项,不能由单元测试替代。 + +## 考虑过的替代方案 + +**维持默认卸载器。** 它们不能证明应用目录之外的应用状态已被移除,因此不满足要求。 + +**把全部 Electron 和更新数据移到 `.dsh`。** 这能简化文件位置,但会保留缓存和浏览器状态而不是清理它们,而且自身不能覆盖 Squirrel/原生状态或已有的外部文件。本提案不采用它作为清理方案。 + +**通过常驻后台监视器检测 Finder 删除。** 这会增加一个本身也需要卸载的常驻组件,并且不能可靠覆盖监视器停止期间发生的删除。采用显式卸载操作。 + +**删除 `.dsh/desktop` 或 `.dsh/profiles/desktop`。** 这些路径包含 Desktop 专属状态,但要求保留的是整个 Harness 主目录,而不只是会话。 + +## 验收标准 + +- 受支持的卸载成功后,选定应用、它拥有的注册信息,以及已安装产物清单确定的每个外部应用路径均已移除;没有清理辅助程序或更新器进程残留。 +- 静止后,默认和已配置 Harness 主目录的内容及链接完全保留。用户项目和独立 CLI 安装保持完整。 +- Windows 控制面板、设置及静默卸载满足同一保留规则。实际自动升级保留浏览器状态和 Harness 数据。 +- macOS 显式操作和独立卸载器满足清理规则。文档准确区分它们与 Finder 拖拽删除,以及仅移入废纸篓的情况。 +- 每个未移除的所属路径都报告重试或恢复方式。权限不足、用户配置目录不可访问和共享归属均不得产生虚假的完整成功结果。 +- 首次安装及卸载重装测试证明,没有未纳入清单的主目录外应用状态残留,且能重新打开保留的会话。通过原生操作系统清单验证完成,不能只依赖模拟 API 调用。 + +## 风险 + +删除浏览器存储会丢失未发送草稿和界面偏好。完整保留主目录意味着有意保留 Desktop 插件、pnpm 状态,以及可能在重装修复前悬空的链接。自定义数据路径和共享安装可能需要额外权限或移动路径才能完整删除;操作必须报告限制,不能违反保留规则。 + +操作系统拥有的安全和审计历史,以及用户创建的文件,不能被“抹除所有痕迹”的承诺覆盖。[Desktop 打包决策](../../implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)和[内置运行时与外部插件决策](../../implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)继续分别拥有打包和数据归属规则;本提案不取代这两份记录,也不归档任何活跃记录。 diff --git a/apps/desktop-host/src/index.ts b/apps/desktop-host/src/index.ts index e85badba04..3abebfc3c6 100644 --- a/apps/desktop-host/src/index.ts +++ b/apps/desktop-host/src/index.ts @@ -149,12 +149,12 @@ function isProjectPath(projectDir: string, target: string): boolean { return path === root || path.startsWith(root + sep) } -function desktopPatches(projectDir: string, allowLinkedPackages: boolean): PatchOptions[] { - const dshRoot = dirname(packageManifestPath(projectDir, '@deepseek-ai/dsh')) +function desktopPatches(runtimeDir: string, projectDir: string, allowLinkedPackages: boolean): PatchOptions[] { + const dshRoot = dirname(packageManifestPath(runtimeDir, '@deepseek-ai/dsh')) const profile = loadProfileDirectory('dsh desktop', projectDir, join(dshRoot, 'package.json')) for (const layer of profile.layers) { - if (!allowLinkedPackages && !isProjectPath(projectDir, layer.packageDir)) { - throw new Error(`dsh desktop: profile bundle ${JSON.stringify(layer.packageName)} resolved outside the desktop profile`) + if (!allowLinkedPackages && !isProjectPath(projectDir, layer.packageDir) && !isProjectPath(runtimeDir, layer.packageDir)) { + throw new Error(`dsh desktop: profile bundle ${JSON.stringify(layer.packageName)} resolved outside the Desktop runtime and profile`) } } const layers = [ @@ -176,14 +176,14 @@ function desktopPatches(projectDir: string, allowLinkedPackages: boolean): Patch return layers.flat() } -function dshVersion(projectDir: string): string { - const manifest = readManifest(packageManifestPath(projectDir, '@deepseek-ai/dsh')) +function dshVersion(runtimeDir: string): string { + const manifest = readManifest(packageManifestPath(runtimeDir, '@deepseek-ai/dsh')) if (typeof manifest.version !== 'string') throw new Error('dsh desktop: installed dsh manifest has no version') return manifest.version } -function assetHandler(ctx: Context, projectDir: string): ConnectionFetchHandler { - const require = createRequire(join(projectDir, 'package.json')) +function assetHandler(ctx: Context, runtimeDir: string): ConnectionFetchHandler { + const require = createRequire(join(runtimeDir, 'package.json')) const distIndex = require.resolve('@deepseek-ai/dsh-web-frontend/dist/index.html') const distRoot = realpathSync(dirname(distIndex)) const renderIndex = async (): Promise => { @@ -270,12 +270,14 @@ interface NodeRequestInit extends RequestInit { /** * Boot one installed desktop npm project. + * @param runtimeDir - immutable dsh packages supplied by the Electron application. * @param projectDir - active or staged Electron-owned desktop profile. * @param writeResponse - serialized response-pipe writer that applies byte backpressure. * @param options - development-only allowance for workspace-linked bundle packages. * @returns controller after every Host and client-manifest row is active. */ export async function runDesktopHost( + runtimeDir: string, projectDir: string, writeResponse: (frame: Buffer) => Promise, options: { allowLinkedPackages?: boolean } = {}, @@ -287,6 +289,7 @@ export async function runDesktopHost( const environment = loadLayeredEnv('dsh desktop') let current: Context | undefined const ctx = await boot('dsh desktop', rootConfig, structuredClone(desktopPatches( + resolve(runtimeDir), absoluteProject, options.allowLinkedPackages === true, )), (hostCtx) => { @@ -303,7 +306,7 @@ export async function runDesktopHost( throw new Error('dsh desktop: composition did not provide connection, typertGateway, and clientModules') } const api = connection.createSharedFetchHandler('/api') - const assets = assetHandler(ctx, absoluteProject) + const assets = assetHandler(ctx, resolve(runtimeDir)) const streams = remoteStreamHandler(ctx) const requests = new Map() let disposing: Promise | undefined @@ -319,7 +322,7 @@ export async function runDesktopHost( } return { - dshVersion: dshVersion(absoluteProject), + dshVersion: dshVersion(resolve(runtimeDir)), cancel(streamId) { requests.get(streamId)?.abort() }, @@ -374,11 +377,12 @@ export async function runDesktopHost( } async function main(): Promise { - const projectDir = process.argv[2] - if (projectDir === undefined || process.send === undefined) { - throw new Error('dsh desktop: expected project directory, byte pipes, and a Node IPC channel') + const runtimeDir = process.argv[2] + const projectDir = process.argv[3] + if (runtimeDir === undefined || projectDir === undefined || process.send === undefined) { + throw new Error('dsh desktop: expected runtime and profile directories, byte pipes, and a Node IPC channel') } - const option = process.argv[3] + const option = process.argv[4] if (option !== undefined && option !== '--allow-linked-profile') { throw new Error(`dsh desktop: unsupported internal option ${JSON.stringify(option)}`) } @@ -403,7 +407,7 @@ async function main(): Promise { if ((error as NodeJS.ErrnoException).code !== 'ERR_IPC_CHANNEL_CLOSED') throw error } } - const controller = await runDesktopHost(projectDir, writeResponse, { allowLinkedPackages: option !== undefined }) + const controller = await runDesktopHost(runtimeDir, projectDir, writeResponse, { allowLinkedPackages: option !== undefined }) send({ type: 'ready', protocolVersion: DESKTOP_HOST_PROTOCOL_VERSION, diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index de168b99dd..123b44f866 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: cf350a9d5e9577f5cf52c4371b32f16e278133f9 -README.zh.md: df48eb5903e21cae9ff041626c28d41d12e5c632 +README.md: b2a51010dc37bcca7c7846819b72ababdc227496 +README.zh.md: 241a1e1d900fef49042a7526d29fc473ef568088 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index cf350a9d5e..b2a51010dc 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -10,46 +10,36 @@ The desktop application is an Electron shell around the dsh Web UI. It opens no |---|---|---| | Release identity | The shell API, Web client, backend, and plugin graph are qualified as one combination; independent versions would create untested combinations and ambiguous update availability. | Electron and `@deepseek-ai/dsh` always have the same exact version. A dsh upgrade is a Desktop release, even when the shell code is unchanged. | | Runtime | Electron's Node.js carries Electron patches, fuses, ABI, and lifecycle constraints, while system runtimes and package-manager state are uncontrolled. | dsh runs under the bundled upstream Node.js and every package operation uses the bundled pnpm. Electron's Node.js, system Node.js, system pnpm, and user package-manager configuration are outside the execution path. | -| Package sources | The exact dsh source build must be packageable before npm publication and install offline; plugins must remain ordinary user-selected npm packages. | The signed application carries locally packed first-party dsh packages and an offline seed store. Desktop plugins remain ordinary npm dependencies resolved from the fixed Desktop registry. | -| Seed transport | Apple notarization inspects code inside archives; shipping every pnpm store file separately would also make the application signature inventory tens of thousands of cache entries, while one compressed archive would amplify small package changes. | macOS packaging signs every Mach-O CAS object, rewrites its pnpm hashes, and proves another offline install before assigning store files to 16 deterministic uncompressed tar shards. The outer installer compresses them, and differential updates can reuse unchanged shards. | +| Package sources | Core installation at startup adds work even when offline. | `extraResources/dsh` carries a complete production dependency tree; the profile installs only external plugins. | +| Shared modules | Host APIs can depend on module identity. | Desktop links every bundled first-party package into the profile using directory symlinks, or Windows junctions; ordinary plugin dependencies remain local. | | State ownership | Sharing executable dependency graphs would let CLI and Desktop change each other's dsh, Cordis, plugin, or native-module versions, while two desktop processes could race on the same profile. | Electron acquires its process-lifetime single-instance lock before any profile access and exclusively owns `$DSH_HOME/profiles/desktop` plus its package-manager state. CLI and Desktop share supported product data under `$DSH_HOME`, but never executable packages, plugin activation, lockfiles, or `node_modules`. | | Transport | A listening Web service adds port ownership, authentication, CORS, and exposure concerns; Electron and upstream Node.js also need an explicit cross-process protocol. | The application opens no Web port. `dsh-app://` carries Web assets and Fetch traffic; framed byte pipes carry bounded request and response chunks with backpressure, while Node IPC carries only child lifecycle control. | | Activation | Dependency resolution, lifecycle scripts, native modules, and plugin startup can fail, and a process can stop during directory replacement. | Release and plugin changes install in staging, boot a complete backend health check, and replace the active profile only after success; a journal and one rollback profile cover interrupted replacement. | -| Updates | Independent shell and dsh updates would recreate version splits, while unchanged shell blocks should not require a complete transfer. | The Electron shell, matching dsh seed, Node.js, and pnpm form one signed update unit. Platform update artifacts may reuse unchanged blocks, but runtime version selection never splits from the Desktop release. | +| Updates | Independent shell and dsh updates would recreate version splits, while unchanged shell blocks should not require a complete transfer. | The Electron shell, matching dsh runtime, Node.js, and pnpm form one signed update unit. Platform update artifacts may reuse unchanged blocks, but runtime version selection never splits from the Desktop release. | The [Electron packaging and update Agent Note](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) owns the rationale, alternatives, security constraints, and release qualification requirements behind these decisions. ## Installation ownership -Electron owns the reserved profile at `$DSH_HOME/profiles/desktop`. Its manifest lists the built-in and installed plugin bundles in `dsh.profile.bundles`, while its `node_modules` contains the exact `@deepseek-ai/dsh` release, its matching private `@deepseek-ai/dsh-desktop-host`, and every desktop plugin. Keeping the Electron-only process entry and overlay in a private app package prevents Desktop implementation from becoming part of the public CLI package. The CLI cannot boot or mutate this profile. Electron always invokes its bundled Node.js and pnpm with the store at `$DSH_HOME/desktop/pnpm/store`; it never uses system pnpm or the caller's npm/pnpm configuration. +Electron owns `$DSH_HOME/profiles/desktop`. Its `dependencies` contains only installed external plugins at exact versions; `dsh.profile.bundles` contains the built-in bundles followed by enabled plugins. The signed application supplies dsh, the private Desktop Host, and their production packages from `resources/dsh`. Shared package links resolve to those actual directories. Both host and plugins execute in the same bundled upstream Node process, with normal realpath resolution; Desktop does not enable `--preserve-symlinks`. The CLI cannot boot or mutate this profile. The main dsh renderer receives only the desktop protocol marker. The separate plugin window receives structured list, install, remove, update, and update-check operations; neither renderer receives filesystem access, raw Electron IPC, a shell, or arbitrary pnpm arguments. Electron chooses typed English or Chinese shell copy from its application locale and falls back to English. Menus, native dialogs, and the plugin-management renderer use the same locale payload; the repository Client UI i18n gate checks these desktop sources. -### Seed installation +### Runtime and plugin activation -The packaged seed is an installation kit, not a ready-to-run `node_modules` tree. Packaging creates the lockfile, materializes the production graph online with lifecycle scripts disabled, deletes `node_modules` and every temporary pnpm cache, config, and state directory, and proves one complete installation offline from the final store alone with the private Desktop Host entry and overlay present. A macOS build stages every Mach-O object from pnpm's content-addressed store, Developer ID signs at most four independent copies concurrently, and updates the affected SHA-512 index records only after all signers succeed. Another offline install proves the rewritten store before sharding; preparation then extracts the final archives and verifies every embedded signature. The signed seed retains the release identity, local first-party tarballs and their descriptor, project metadata, lockfile, integrity inventory, and pnpm store content required to repeat that installation on the user's machine. +The signed `resources/dsh/desktop-runtime.json` binds the shell version, bundled Node version, platform, architecture, shared package versions, and final file inventory. Startup verifies the tree before creating host links. Core packages are never copied into profile storage or installed by pnpm at first launch. -| Seed content | Writable destination or use | -|---|---| -| `integrity.json` and `desktop-packages.json` | Verify every inventoried seed file, local tarball hash, and the bound dsh and Desktop Host versions before package state changes. | -| `store-archives.json` and `store-archives/*.tar` | Validate the deterministic uncompressed shards, extract them into a unique Desktop staging directory, replace matching immutable store files, and transactionally merge pnpm's versioned SQLite package index into `$DSH_HOME/desktop/pnpm/store` without removing packages already downloaded for Desktop plugins. | -| Project metadata and `desktop-packages/` | Copy into a unique `$DSH_HOME/desktop/staging//profile` project. | -| Lockfile and local package mappings | Drive the bundled pnpm installation without resolving a packaged core name from npm. | +1. A fresh profile creates its manifest and shared package links, then boots and stops the complete backend before activation. +2. A compatible application upgrade copies plugin files and configuration into staging, refreshes shared links, checks enabled plugins’ peer requirements, and runs the same backend health check. Plugin versions and lockfile remain unchanged; pnpm does not run. +3. A changed bundled Node version, platform, or architecture reinstalls the locked plugin graph with scripts disabled, validates and links host packages, then runs approved pending builds and validates again. +4. Plugin add, update, and remove operations use bundled pnpm and Desktop-owned package-manager state. Reserved host packages must be peers; nested copies and aliases of shared packages fail validation. Ordinary plugin dependencies must resolve inside the profile. +5. Activation stops the active backend, records runtime identities and the next directory move, and replaces the profile while retaining one rollback copy. Copies do not share writable hardlinks. A failed activation restores the previous profile; a profile belonging to another runtime cannot boot under the current shell. -Startup installs or reconciles the seed as one serialized transaction: +The Electron-owned plugin window remains available when backend startup fails. Disable one plugin or all plugins to retry with their files, exact versions, and configuration retained. Disabling removes only activation entries. Updating or removing an installed plugin remains available while it is disabled. Application rollback and profile rollback are separate; runtime compatibility is checked before any backend starts. -1. Recover an interrupted activation journal, verify the complete seed inventory and local package set, and require the seed version to equal Electron's application version. -2. If the active profile already contains that release plus the matching dsh and Desktop Host versions, verify its local package set and reuse it without reinstalling. -3. Otherwise validate every archive entry, extract all store shards into a temporary Desktop-owned staging directory, merge the package files and SQLite package-index records into the private store, create a staging profile, and run `pnpm install --offline --frozen-lockfile --trust-lockfile` through the bundled Node.js and pnpm. Seed records replace matching index keys while plugin-only records remain available. -4. During an Electron upgrade, read every plugin name and exact version from the old active profile and add those versions to staging with `--offline` from existing Desktop pnpm state. A first installation has no plugin-restore step. -5. Stop the active backend, boot and stop the complete staged backend as a health check, then restart the active backend before activation. This serialization prevents two desktop backends from sharing `$DSH_HOME`; installation or plugin incompatibility before activation deletes staging and leaves the active profile unchanged. -6. Persist each next activation phase before its directory move, move the active profile to `$DSH_HOME/desktop/rollback/profile`, and move staging into `$DSH_HOME/profiles/desktop`. Recovery combines the journal with the actual profile, rollback, and staging directories, so interruption in either write-to-move gap restores or retains a complete profile. - -GUI plugin mutations use the same staging, health-check, activation, and rollback path after installing registry packages into the shared Desktop pnpm store. - -The process-lifetime Electron lock is the primary desktop owner. The transaction lock is depth defense: it records Electron while preparing local state, records the spawned pnpm worker while that worker can still write, and returns ownership to Electron after the worker exits. A later process cannot treat a live orphaned worker as a stale transaction. +Package transactions hold an exclusive lock through pnpm process exit. Shared links use directory symlinks on macOS/Linux and junctions on Windows; hardlinks are unsuitable because they cannot represent package directories and would retain old file content after application replacement. Native builds follow the profile’s reviewed `allowBuilds` list; installing a new build-requiring package without approval in that list fails the transaction. ## Develop @@ -67,7 +57,7 @@ After an explicit build, `start:desktop` reconstructs the disposable project and pnpm run start:desktop ``` -Workspace development runs the current CLI and private Desktop Host packages under the invoking Node.js and disables desktop package mutations. Its explicitly linked disposable profile is the only mode allowed to resolve bundles outside its own directory. Use an unpacked application to exercise the bundled Node.js, bundled pnpm, release seed, plugin installation, staging, and rollback paths. +Workspace development runs the current CLI and private Desktop Host packages under the invoking Node.js and disables desktop package mutations. Its explicitly linked disposable profile is the only mode allowed to resolve bundles outside its own directory. Use an unpacked application to exercise the bundled Node.js, bundled pnpm, bundled dsh resources, plugin installation, staging, and rollback paths. ## Package @@ -88,7 +78,7 @@ export APPLE_API_ISSUER='' pnpm run package:desktop ``` -Release automation uses fixed target commands so runtime preparation, seed installation, and electron-builder receive the same platform and architecture: +Release automation uses fixed target commands so runtime preparation, dsh preparation, and electron-builder receive the same platform and architecture: ```sh pnpm run package:desktop:mac:arm64 @@ -98,7 +88,7 @@ pnpm run package:desktop:win:x64 The macOS arm64 command requires Apple Silicon. The macOS x64 command runs on Intel macOS or Apple Silicon with Rosetta. The Windows x64 command requires Windows x64. Linux is not a supported Desktop release target. -Each target owns its packed package inputs, prepared runtime, package set, seed, pnpm preparation state, unpacked application, update metadata, and final artifacts under `apps/desktop/.desktop-build/targets//`. The Node.js archive cache remains shared under `.desktop-build/downloads` because every archive name includes its version, platform, and architecture and is verified before extraction. A target build never consumes another target's mutable preparation state. +Each target owns its packed package inputs, prepared runtime, package set, dsh tree, pnpm preparation state, unpacked application, update metadata, and final artifacts under `apps/desktop/.desktop-build/targets//`. The Node.js archive cache remains shared under `.desktop-build/downloads` because every archive name includes its version, platform, and architecture and is verified before extraction. A target build never consumes another target's mutable preparation state. ### Upload updates @@ -125,7 +115,7 @@ pnpm run upload:mac:arm64 Set `DSH_DESKTOP_AUTO_UPDATE_ENV=production` before packaging, then provide `DOWNLOAD_PROD_COS_BUCKET` and the production credential pair before running `upload:mac:arm64`, `upload:mac:x64`, or `upload:win:x64`. Packaging does not require a COS bucket or credentials. It explicitly disables electron-builder publishing, strips all four COS credential fields from its subprocesses, and writes a target completion record only after electron-builder and every signing or notarization hook succeeds. Upload requires that record to match the selected environment, target, public URL, and current dsh version; it also requires the root dsh version, Desktop version, channel metadata version, artifact names, sizes, and SHA-512 values to agree before it reads the selected COS credential pair. It uploads only that target's immutable versioned artifacts, uploads the version-derived channel metadata last with `no-cache`, and never deletes historical objects. Stable releases use `latest-mac.yml` or `latest.yml`; a prerelease such as `alpha` uses `alpha-mac.yml` or `alpha.yml`, matching electron-builder's emitted filename. -The macOS configuration uses the required release environment instead of accepting whichever certificate appears first in a keychain. It rejects empty values, a malformed Team ID, a signing identity that includes electron-builder's unsupported `Developer ID Application:` prefix, and incomplete notarization credentials. macOS packaging requires the configured identity and its private key. Seed preparation applies that identity, a secure timestamp, and hardened runtime to every embedded Mach-O file; after signing the application, a deep strict check rejects any other leaf authority or Team ID before artifact creation. Electron-builder notarizes and staples the application before packaging and signs the DMG. The DMG artifact-completion hook then notarizes and staples it before requiring its exact identity, ticket, and Gatekeeper acceptance; only after the hook succeeds can electron-builder publish the file. The private key can come from the login keychain or electron-builder's standard `CSC_LINK` input; ambient `CSC_NAME` and certificate discovery order do not select the release owner. Notary credentials may instead use electron-builder's complete Apple ID or keychain-profile strategy. The two macOS identity variables are also required when repeating the application check manually with `pnpm --dir apps/desktop run verify:mac-signature -- `. +The macOS configuration uses the required release environment instead of accepting whichever certificate appears first in a keychain. It rejects empty values, a malformed Team ID, a signing identity that includes electron-builder's unsupported `Developer ID Application:` prefix, and incomplete notarization credentials. macOS packaging requires the configured identity and its private key. Runtime preparation applies that identity, a secure timestamp, and hardened runtime to every embedded Mach-O file; after signing the application, a deep strict check rejects any other leaf authority or Team ID before artifact creation. Electron-builder notarizes and staples the application before packaging and signs the DMG. The DMG artifact-completion hook then notarizes and staples it before requiring its exact identity, ticket, and Gatekeeper acceptance; only after the hook succeeds can electron-builder publish the file. The private key can come from the login keychain or electron-builder's standard `CSC_LINK` input; ambient `CSC_NAME` and certificate discovery order do not select the release owner. Notary credentials may instead use electron-builder's complete Apple ID or keychain-profile strategy. The two macOS identity variables are also required when repeating the application check manually with `pnpm --dir apps/desktop run verify:mac-signature -- `. ### Windows EV signing @@ -141,7 +131,7 @@ pnpm run package:desktop:win:x64 Insert and unlock the token before packaging. The electron-builder hook passes each artifact to the CRLF `scripts/windows-sign.cmd`, which invokes the configured SignTool once with `/f`, SafeNet `/kc "[{{PIN}}]=container"`, `/csp "eToken Base Cryptographic Provider"`, a SHA-256 file digest, and a DigiCert SHA-256 RFC 3161 timestamp. The hook never substitutes electron-builder's bundled SignTool and never retries a failed signing request. Windows packaging fails instead of emitting unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. -The PIN cannot contain `]`, a quote, or a line break because those characters delimit the SafeNet `/kc` value or its CMD argument. The CMD disables delayed expansion so a PIN containing `!` reaches SafeNet unchanged. Packaging withholds every `DSH_DESKTOP_WINDOWS_*` field from build and seed-preparation subprocesses, gives electron-builder only the four configured inputs, gives the signing CMD only the validated signing fields in an otherwise scrubbed environment, clears those fields before SignTool starts, and redacts SignTool diagnostics. SafeNet still requires the PIN in the SignTool process command line. Inject it as an ephemeral secret only on a controlled self-hosted Windows runner with the physical token attached; never commit it, put it in `.env`, or persist it as a Windows user or system environment variable. +The PIN cannot contain `]`, a quote, or a line break because those characters delimit the SafeNet `/kc` value or its CMD argument. The CMD disables delayed expansion so a PIN containing `!` reaches SafeNet unchanged. Packaging withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation subprocesses, gives electron-builder only the four configured inputs, gives the signing CMD only the validated signing fields in an otherwise scrubbed environment, clears those fields before SignTool starts, and redacts SignTool diagnostics. SafeNet still requires the PIN in the SignTool process command line. Inject it as an ephemeral secret only on a controlled self-hosted Windows runner with the physical token attached; never commit it, put it in `.env`, or persist it as a Windows user or system environment variable. Create a runnable application directory instead of an installer by using the matching `:dir` command, such as: @@ -156,21 +146,21 @@ To inspect or troubleshoot the prepared host-target resources without invoking e pnpm run prepare:desktop ``` -This diagnostic command is an alternative stopping point, not the first half of a two-command build. A later `package:desktop*` command repeats the official build and preparation so it cannot consume stale dsh packages, runtime files, or seed content. +This diagnostic command is an alternative stopping point, not the first half of a two-command build. A later `package:desktop*` command repeats the official build and preparation so it cannot consume stale dsh packages, runtime files, or dsh content. -Every package command performs the official repository build, packs the dsh and vendored package families, locally packs the private Desktop Host package, and packs the Landlock entry before preparing release resources. `prepare:packages` selects the union of the first-party production closures rooted at `@deepseek-ai/dsh` and `@deepseek-ai/dsh-desktop-host`, verifies that the private Host tarball contains `lib/index.js` and `config/desktop.cordis.patch.yml`, copies the selected tarballs into the seed input, and records their sizes and SHA-512 integrity. The Host package is never published to npm; its `files` manifest contains only that runtime entry and overlay. Public package tarballs remain the official `pnpm pack` outputs governed by each package's publication manifest, so Desktop adds no second filter, retains published declarations such as `lib/types`, and neither strips nor adds source maps independently. Registry packages likewise retain their published package bytes in pnpm's content-addressed store. The dsh release bump updates both private Desktop manifests together with the root and publishable workspaces; packaging also requires the root dsh package, Desktop Host package, and Electron package to have the same version. Neither dsh nor the private Host needs to be published to npm before the Desktop application is built. `prepare:runtime` downloads Node.js 24.17.0 from the official Node.js release service, verifies its SHA-256 entry before extraction, and executes the prepared target binary on a compatible build host to verify its reported version. It copies the pnpm version declared by the desktop package and records both runtime versions in the release seed. `prepare:seed` runs that target Node.js and bundled pnpm, so platform- and CPU-filtered optional dependencies make the pnpm store and seed target-specific. It generates local core-package mappings, disables the global virtual store, materializes external production dependencies from npm without lifecycle scripts, deletes `node_modules` and all temporary pnpm cache, config, and state, proves the complete graph installs offline with the private Host entry and overlay, performs the macOS rewrite when applicable, proves the rewritten store with another offline installation, removes temporary pnpm project registrations, and replaces the loose store with 16 deterministic uncompressed tar shards. It extracts those final shards and verifies every embedded macOS signature before inventory generation. Later GUI plugin operations retain the local core mappings while resolving plugin packages and their external dependencies from the fixed Desktop npm registry. `electron-builder` emits each target's platform artifacts under `apps/desktop/.desktop-build/targets//artifacts`; a later version keeps differently named immutable installers and blockmaps while replacing that target's unpacked application, diagnostics, completion record, and channel metadata. +Every package command builds the repository, packs the first-party production closures rooted at dsh and the private Desktop Host, and prepares target-specific Node and pnpm executables. `prepare:dsh` installs the production graph once at build time, copies materialized packages into `extraResources/dsh`, removes package-manager metadata, and writes `desktop-runtime.json` with shared package versions and final file hashes. On macOS it signs and verifies native files before inventory generation; electron-builder excludes this already-signed tree from nested re-signing. Resource mappings explicitly include `dsh/node_modules`, which the default root-directory filter omits; the copied inventory is checked before signing and again after signing. Signed installer, notarization, installed upgrade, and target-specific native-module qualification require the release environment. -An unpacked artifact contains four independent size contributors: Electron, the offline seed store shards and local dsh tarballs, the upstream Node.js and pnpm runtime, and the small shell application. The shards are uncompressed so the outer DMG, ZIP, or NSIS compressor and differential updater can operate on stable ranges. Filesystem size is not installer download size, so measure both separately. First packaged startup also extracts the seed store into `$DSH_HOME/desktop/pnpm/store` before installing the writable profile, so release qualification must measure both application and Harness-home disk use. +An unpacked artifact contains Electron, the materialized dsh production tree, upstream Node.js and pnpm, and the shell application. Installer size and filesystem size differ; release qualification measures both, plus the profile’s plugin storage and first-launch latency. The runtime trades more application files for eliminating core package installation on the user’s machine. ## Updates -A packaged application checks its target-specific release stream ten seconds after the main window opens; the localized **Check for Updates…** menu item triggers the same check manually. An available release opens one native confirmation dialog. Accepting it waits for an in-flight check, downloads and verifies the signed Desktop release, stops the dsh child, and hands installation plus restart to electron-updater. The next launch reconciles the version-bound seed before reopening the product window. +A packaged application checks its target-specific release stream ten seconds after the main window opens; the localized **Check for Updates…** menu item triggers the same check manually. An available release opens one native confirmation dialog. Accepting it waits for an in-flight check, downloads and verifies the signed Desktop release, stops the dsh child, and hands installation plus restart to electron-updater. The next launch reconciles the version-bound runtime before reopening the product window. -Electron-builder always emits generic-provider channel metadata for the deployment selected by `DSH_DESKTOP_AUTO_UPDATE_ENV`. NSIS differential packages and the macOS ZIP target allow electron-updater to reuse unchanged blocks; the manually installed DMG is notarized without a blockmap because it is not a macOS updater payload. The seed and shell still form one signed Desktop release. macOS signing and notarization credentials use electron-builder's standard environment; Windows EV signing uses the public certificate, validated SignTool, SafeNet container, and runner PIN described above. The required Desktop release environment selects the application and platform signature identities that the build verifies. +Electron-builder always emits generic-provider channel metadata for the deployment selected by `DSH_DESKTOP_AUTO_UPDATE_ENV`. NSIS differential packages and the macOS ZIP target allow electron-updater to reuse unchanged blocks; the manually installed DMG is notarized without a blockmap because it is not a macOS updater payload. The runtime and shell still form one signed Desktop release. macOS signing and notarization credentials use electron-builder's standard environment; Windows EV signing uses the public certificate, validated SignTool, SafeNet container, and runner PIN described above. The required Desktop release environment selects the application and platform signature identities that the build verifies. ## Low-level development overrides -`DSH_DESKTOP_NODE_BINARY`, `DSH_DESKTOP_PNPM_ENTRY`, `DSH_DESKTOP_SEED_DIR`, and `DSH_DESKTOP_DEV_PROJECT_DIR` select explicit resources for an unpackaged Electron process. Packaged applications ignore these variables and resolve signed resources from `process.resourcesPath`. +`DSH_DESKTOP_NODE_BINARY`, `DSH_DESKTOP_PNPM_ENTRY`, `DSH_DESKTOP_DSH_DIR`, and `DSH_DESKTOP_DEV_PROJECT_DIR` select explicit resources for an unpackaged Electron process. Packaged applications ignore these variables and resolve signed resources from `process.resourcesPath`. ## Known limitations diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index df48eb5903..241a1e1d90 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -10,46 +10,36 @@ |---|---|---| | 发布身份 | 桌面壳 API、Web 客户端、后端与插件依赖图作为一个组合完成验证;独立版本会产生未经验证的组合,并让更新可用性含糊不清。 | Electron 与 `@deepseek-ai/dsh` 始终使用同一精确版本。即使桌面壳代码不变,升级 dsh 也必须发布新 Desktop 版本。 | | 运行时 | Electron 的 Node.js 带有 Electron 补丁、fuse、ABI 与生命周期约束,而系统运行时和用户包管理器状态不可控。 | dsh 通过内置的上游 Node.js 运行,所有包操作都使用内置 pnpm。Electron 的 Node.js、系统 Node.js、系统 pnpm 与用户的包管理器配置都不进入执行路径。 | -| 包来源 | 必须能在发布到 npm 之前从同一次源码构建打包精确的 dsh,并支持离线安装;插件则需要保留为用户选择的普通 npm 包。 | 已签名应用携带本地打包的第一方 dsh 包与离线 seed store。桌面插件仍是从固定 Desktop registry 解析的普通 npm 依赖。 | -| Seed 传输 | Apple 公证会检查归档内的代码;把 pnpm store 的每个文件分别放入应用,还会让应用签名记录数万个缓存条目,而单个压缩归档会放大小幅包变更。 | macOS 打包先签署每个 Mach-O CAS 对象、重写其 pnpm 哈希并再次证明离线安装,再把 store 文件分配到 16 个确定性的未压缩 tar 分片。外层安装包负责压缩,差分更新可以复用未变化的分片。 | +| 包来源 | 即使离线,启动时安装核心依赖也会增加开销。 | `extraResources/dsh` 携带完整生产依赖树;profile 只安装外部插件。 | +| 共享模块 | 宿主 API 可能依赖模块实例身份。 | Desktop 用目录软链接或 Windows junction 把每个内置第一方包连接到 profile;普通插件依赖保留在本地。 | | 状态归属 | 共享可执行依赖图会让 CLI 与 Desktop 相互改变 dsh、Cordis、插件或原生模块版本,而两个桌面进程还可能争用同一个 profile。 | Electron 在访问任何 profile 前获取进程生命周期单实例锁,并独占 `$DSH_HOME/profiles/desktop` 及其包管理器状态。CLI 与 Desktop 共享 `$DSH_HOME` 下受支持的产品数据,但绝不共享可执行包、插件激活、锁文件或 `node_modules`。 | | 通信 | 监听 Web 服务会引入端口归属、认证、CORS 与暴露风险;Electron 与上游 Node.js 之间也需要明确的跨进程协议。 | 应用不打开 Web 端口。`dsh-app://` 承载 Web 资源和 Fetch 流量;分帧字节管道以背压传输有界请求与响应分块,Node IPC 只承载子进程生命周期控制。 | | 激活 | 依赖解析、生命周期脚本、原生模块与插件启动都可能失败,目录替换期间进程也可能中断。 | 发布与插件变更先安装到 staging,并启动完整后端执行健康检查;只有成功后才替换活跃 profile,中断替换由事务日志和一个 rollback profile 恢复。 | -| 更新 | 桌面壳与 dsh 独立更新会重新产生版本分裂,而桌面壳未变化的数据块不应强制完整传输。 | Electron 壳、匹配的 dsh seed、Node.js 与 pnpm 组成一个已签名更新单元。平台更新产物可以复用未变化的数据块,但运行时版本选择绝不脱离 Desktop 发布。 | +| 更新 | 桌面壳与 dsh 独立更新会重新产生版本分裂,而桌面壳未变化的数据块不应强制完整传输。 | Electron 壳、匹配的 dsh 运行时、Node.js 与 pnpm 组成一个已签名更新单元。平台更新产物可以复用未变化的数据块,但运行时版本选择绝不脱离 Desktop 发布。 | [Electron 打包与更新 Agent Note](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)记录了这些决策背后的理由、替代方案、安全约束和发布验证要求。 ## 安装归属 -Electron 拥有保留 profile `$DSH_HOME/profiles/desktop`。其 manifest 通过 `dsh.profile.bundles` 列出内置与已安装插件 bundle,`node_modules` 则同时包含精确版本的 `@deepseek-ai/dsh`、与之匹配的私有 `@deepseek-ai/dsh-desktop-host` 和所有桌面插件。把 Electron 专用进程入口与 overlay 放入私有应用包,可以避免 Desktop 实现成为公共 CLI 包的一部分。CLI 不能启动或修改该 profile。Electron 始终调用自身内置的 Node.js 与 pnpm,并把 store 固定在 `$DSH_HOME/desktop/pnpm/store`;它绝不使用系统 pnpm 或调用方的 npm/pnpm 配置。 +Electron 拥有 `$DSH_HOME/profiles/desktop`。其 `dependencies` 只包含已安装外部插件的精确版本;`dsh.profile.bundles` 包含内置 bundle,后接已启用插件。签名应用从 `resources/dsh` 提供 dsh、私有 Desktop Host 及其生产依赖。共享包链接解析到这些实际目录。宿主与插件在同一个内置上游 Node 进程中执行,使用正常的 realpath 解析;Desktop 不启用 `--preserve-symlinks`。CLI 不能启动或修改此 profile。 dsh 主渲染进程只获得桌面协议标记。独立插件窗口获得结构化的列出、安装、移除、更新和更新检查操作;两个渲染进程都拿不到文件系统、原始 Electron IPC、shell 或任意 pnpm 参数。 Electron 根据应用 locale 选择类型化的中英文字典,并以英文作为 fallback。菜单、原生对话框与插件管理渲染进程使用同一 locale 数据;仓库的 Client UI i18n gate 会检查这些桌面源文件。 -### Seed 安装 +### 运行时与插件激活 -安装包内的 seed 是安装工具包,不是可以直接运行的 `node_modules` 目录。打包过程会生成锁文件,在禁用生命周期脚本的情况下在线物化生产依赖图,删除 `node_modules` 以及所有临时 pnpm cache、config 和 state 目录,然后只使用最终 store 完成一次完整离线安装,并验证私有 Desktop Host 的入口与 overlay 均存在。macOS 构建随后从 pnpm 内容寻址 store staging 每个 Mach-O 对象,最多并发四个 Developer ID 签名进程,并且只在所有签名成功后才更新受影响的 SHA-512 索引记录。再一次离线安装会在分片前证明重写后的 store;准备过程随后解包最终归档,并验证每个内嵌签名。签名 seed 保留发布身份、本地第一方 tarball 及其描述文件、项目元数据、锁文件、完整性清单,以及在用户机器上重复该安装所需的 pnpm store 内容。 +签名资源中的 `resources/dsh/desktop-runtime.json` 绑定 shell 版本、内置 Node 版本、平台、架构、共享包版本和最终文件清单。启动会先验证依赖树,再创建宿主链接。首次启动不会把核心包复制到 profile 存储或通过 pnpm 安装核心包。 -| Seed 内容 | 可写目标或用途 | -|---|---| -| `integrity.json` 与 `desktop-packages.json` | 在修改包状态前验证清单记录的每个 seed 文件、本地 tarball 哈希以及绑定的 dsh 与 Desktop Host 版本。 | -| `store-archives.json` 与 `store-archives/*.tar` | 验证确定性的未压缩分片,把它们解包到唯一的 Desktop staging 目录,替换匹配的不可变 store 文件,并以事务方式把 pnpm 的版本化 SQLite 包索引合并进 `$DSH_HOME/desktop/pnpm/store`,且不移除已经为 Desktop 插件下载的包。 | -| 项目元数据与 `desktop-packages/` | 复制到唯一的 `$DSH_HOME/desktop/staging//profile` 项目。 | -| 锁文件与本地包映射 | 驱动内置 pnpm 完成安装,且不会从 npm 解析已打包的核心包名。 | +1. 新 profile 创建 manifest 和共享包链接,然后启动并停止完整后端,通过后才激活。 +2. 兼容的应用升级把插件文件和配置复制到 staging,刷新共享链接,检查已启用插件的 peer 要求,并执行相同的后端健康检查。插件版本和锁文件保持不变;不运行 pnpm。 +3. 内置 Node 版本、平台或架构变化时,禁用脚本重新安装锁定的插件依赖图,验证并链接宿主包,然后运行已批准的待执行构建并再次验证。 +4. 插件添加、更新和删除使用内置 pnpm 及 Desktop 独有的包管理器状态。保留的宿主包必须声明为 peer;共享包的嵌套副本和别名会被验证拒绝。普通插件依赖必须解析到 profile 内部。 +5. 激活会停止活动后端,记录运行时身份和下一次目录移动,并替换 profile,同时保留一个回滚副本。复制不共享可写硬链接。激活失败会恢复旧 profile;属于其他运行时的 profile 不能在当前 shell 下启动。 -启动过程把 seed 安装或校准为一个串行事务: +后端启动失败时,Electron 拥有的插件窗口仍然可用。可以停用一个或全部插件后重试,同时保留其文件、精确版本和配置。停用只移除激活条目。已停用插件仍可更新或删除。应用回滚和 profile 回滚分别处理;每次启动后端前都会检查运行时兼容性。 -1. 恢复中断的激活事务日志,验证完整 seed 清单与本地包集,并要求 seed 版本等于 Electron 应用版本。 -2. 如果活跃 profile 已包含该发布及匹配的 dsh 与 Desktop Host 版本,则验证其中的本地包集并直接复用,不重新安装。 -3. 否则验证每个归档条目,把全部 store 分片解包到 Desktop 拥有的临时 staging 目录,将包文件与 SQLite 包索引记录合并进私有 store,再创建 staging profile,并通过内置 Node.js 与 pnpm 执行 `pnpm install --offline --frozen-lockfile --trust-lockfile`。Seed 记录替换匹配的索引键,插件专属记录继续保留。 -4. Electron 升级时,从旧活跃 profile 读取每个插件的名称和精确版本,再通过现有 Desktop pnpm 状态以 `--offline` 把这些版本加入 staging。首次安装不执行插件恢复。 -5. 停止活跃后端,启动并停止完整的 staging 后端执行健康检查,再在激活前重新启动活跃后端。这种串行方式避免两个桌面后端共享 `$DSH_HOME`;安装错误或插件不兼容会删除 staging,并保持活跃 profile 不变。 -6. 在每次目录移动前先持久化下一个激活阶段,把活跃 profile 移到 `$DSH_HOME/desktop/rollback/profile`,再把 staging 移到 `$DSH_HOME/profiles/desktop`。恢复过程同时检查日志与真实的 profile、rollback 和 staging 目录,因此在任一个写入与移动间隙中断后仍会恢复或保留一个完整 profile。 - -GUI 插件修改会在把 registry 包安装到共享 Desktop pnpm store 后,使用相同的 staging、健康检查、激活与 rollback 路径。 - -进程生命周期 Electron 锁是桌面端的主要 owner。事务锁用于纵深防御:准备本地状态时记录 Electron,在 pnpm worker 仍可能写入时记录该 worker,worker 退出后再把 owner 交还 Electron。后续进程不会把仍然存活的孤儿 worker 误判为陈旧事务。 +包事务持有独占锁直到 pnpm 进程退出。共享链接在 macOS/Linux 使用目录软链接,在 Windows 使用 junction;硬链接无法表示包目录,而且应用替换后仍会保留旧文件内容,因此不适合此用途。原生构建遵循 profile 中经过审查的 `allowBuilds` 列表;新安装的包如果需要构建但未在列表中获准,事务会失败。 ## 开发 @@ -67,7 +57,7 @@ pnpm run dev:desktop pnpm run start:desktop ``` -Workspace 开发使用调用命令的 Node.js 运行当前 CLI 与私有 Desktop Host 包,并禁用桌面包修改;只有该模式明确链接的一次性 profile 可以从自身目录外解析 bundle。需要验证内置 Node.js、内置 pnpm、发布 seed、插件安装、staging 和 rollback 时,应运行未封装安装器的应用目录。 +Workspace 开发使用调用命令的 Node.js 运行当前 CLI 与私有 Desktop Host 包,并禁用桌面包修改;只有该模式明确链接的一次性 profile 可以从自身目录外解析 bundle。需要验证内置 Node.js、内置 pnpm、内置 dsh 资源、插件安装、staging 和 rollback 时,应运行未封装安装器的应用目录。 ## 打包 @@ -88,7 +78,7 @@ export APPLE_API_ISSUER='' pnpm run package:desktop ``` -发布自动化使用固定目标命令,确保运行时准备、seed 安装与 electron-builder 接收相同的平台和架构: +发布自动化使用固定目标命令,确保运行时准备、dsh 准备与 electron-builder 接收相同的平台和架构: ```sh pnpm run package:desktop:mac:arm64 @@ -98,7 +88,7 @@ pnpm run package:desktop:win:x64 macOS arm64 命令要求 Apple Silicon。macOS x64 命令可以在 Intel macOS 或带 Rosetta 的 Apple Silicon 上运行。Windows x64 命令要求 Windows x64。Desktop 尚不支持 Linux 发布目标。 -每个目标都在 `apps/desktop/.desktop-build/targets//` 下持有自己的打包输入、已准备运行时、包集合、seed、pnpm 准备状态、未打包应用、更新元数据和最终产物。Node.js 归档缓存继续由 `.desktop-build/downloads` 共享,因为每个归档文件名都包含版本、平台和架构,并且在解包前经过验证。目标构建绝不读取其他目标的可变准备状态。 +每个目标都在 `apps/desktop/.desktop-build/targets//` 下持有自己的打包输入、已准备运行时、包集合、dsh 依赖树、pnpm 准备状态、未打包应用、更新元数据和最终产物。Node.js 归档缓存继续由 `.desktop-build/downloads` 共享,因为每个归档文件名都包含版本、平台和架构,并且在解包前经过验证。目标构建绝不读取其他目标的可变准备状态。 ### 上传更新 @@ -125,7 +115,7 @@ pnpm run upload:mac:arm64 生产发布需在打包前设置 `DSH_DESKTOP_AUTO_UPDATE_ENV=production`,再在执行 `upload:mac:arm64`、`upload:mac:x64` 或 `upload:win:x64` 前提供 `DOWNLOAD_PROD_COS_BUCKET` 与生产凭据对。打包不要求 COS bucket 或凭据。它会明确禁止 electron-builder 发布,从其子进程中删除全部四个 COS 凭据字段,并且只有在 electron-builder 以及全部签名或公证 hook 成功后才写入目标完成记录。上传会先要求该记录与所选环境、目标、公开 URL 和当前 dsh 版本一致,再要求根 dsh 版本、Desktop 版本、频道元数据版本、产物名称、大小与 SHA-512 全部一致,之后才读取所选 COS 凭据对。它只上传该目标不可变且带版本的产物,最后以 `no-cache` 上传根据版本得出的频道元数据,并且不会删除历史对象。稳定版本使用 `latest-mac.yml` 或 `latest.yml`;`alpha` 等预发布版本则使用 `alpha-mac.yml` 或 `alpha.yml`,与 electron-builder 生成的文件名一致。 -macOS 配置使用必填发布环境,不会接受钥匙串中最先发现的证书。空值、格式错误的 Team ID、包含 electron-builder 不支持的 `Developer ID Application:` 前缀的签名身份,以及不完整的公证凭据都会被拒绝。macOS 打包要求已配置的身份及其私钥可用。Seed 准备会把该身份、安全时间戳与 hardened runtime 应用到每个内嵌 Mach-O 文件;应用签名完成后,深度严格检查会拒绝其他叶证书 Authority 或 Team ID,验证通过才生成发布产物。Electron-builder 会在封装前公证应用并钉票,然后签署 DMG。DMG 的 artifact-completion hook 随后会公证它并钉票,再要求其身份、票据与 Gatekeeper 验证全部通过;只有 hook 成功,electron-builder 才能发布该文件。私钥可以来自登录钥匙串或 electron-builder 的标准 `CSC_LINK` 输入;环境中的 `CSC_NAME` 与证书发现顺序都不能选择发布所有者。公证凭据也可以使用 electron-builder 支持的完整 Apple ID 或钥匙串 profile 方式。手动执行 `pnpm --dir apps/desktop run verify:mac-signature -- ` 重复应用检查时,也必须提供两个 macOS 身份变量。 +macOS 配置使用必填发布环境,不会接受钥匙串中最先发现的证书。空值、格式错误的 Team ID、包含 electron-builder 不支持的 `Developer ID Application:` 前缀的签名身份,以及不完整的公证凭据都会被拒绝。macOS 打包要求已配置的身份及其私钥可用。运行时准备会把该身份、安全时间戳与 hardened runtime 应用到每个内嵌 Mach-O 文件;应用签名完成后,深度严格检查会拒绝其他叶证书 Authority 或 Team ID,验证通过才生成发布产物。Electron-builder 会在封装前公证应用并钉票,然后签署 DMG。DMG 的 artifact-completion hook 随后会公证它并钉票,再要求其身份、票据与 Gatekeeper 验证全部通过;只有 hook 成功,electron-builder 才能发布该文件。私钥可以来自登录钥匙串或 electron-builder 的标准 `CSC_LINK` 输入;环境中的 `CSC_NAME` 与证书发现顺序都不能选择发布所有者。公证凭据也可以使用 electron-builder 支持的完整 Apple ID 或钥匙串 profile 方式。手动执行 `pnpm --dir apps/desktop run verify:mac-signature -- ` 重复应用检查时,也必须提供两个 macOS 身份变量。 ### Windows EV 签名 @@ -141,7 +131,7 @@ pnpm run package:desktop:win:x64 打包前插入并解锁 Token。electron-builder hook 把每个产物交给采用 CRLF 的 `scripts/windows-sign.cmd`;该 CMD 只调用一次已配置的 SignTool,并指定 `/f`、SafeNet `/kc "[{{PIN}}]=容器"`、`/csp "eToken Base Cryptographic Provider"`、SHA-256 文件摘要和 DigiCert SHA-256 RFC 3161 时间戳。hook 不会改用 electron-builder 内置的 SignTool,也不会重试失败的签名请求。SignTool、证书、容器、PIN、Token 或签名不可用时,Windows 打包会失败,不会生成未签名产物。 -PIN 不能包含 `]`、引号或换行,因为这些字符用于分隔 SafeNet `/kc` 值或对应的 CMD 参数。CMD 会禁用延迟展开,因此包含 `!` 的 PIN 可以原样到达 SafeNet。打包流程不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 seed 准备子进程;它只向 electron-builder 提供四个配置输入,在其他字段已经清理的环境中只向签名 CMD 提供经过校验的签名字段,在 SignTool 启动前清除这些字段,并遮盖 SignTool 诊断。SafeNet 仍要求 PIN 出现在 SignTool 进程命令行中。只能在连接了物理 Token 的受控 self-hosted Windows runner 上把它注入为临时 secret;绝不能提交该值、把它写进 `.env`,或持久保存为 Windows 用户或系统环境变量。 +PIN 不能包含 `]`、引号或换行,因为这些字符用于分隔 SafeNet `/kc` 值或对应的 CMD 参数。CMD 会禁用延迟展开,因此包含 `!` 的 PIN 可以原样到达 SafeNet。打包流程不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程;它只向 electron-builder 提供四个配置输入,在其他字段已经清理的环境中只向签名 CMD 提供经过校验的签名字段,在 SignTool 启动前清除这些字段,并遮盖 SignTool 诊断。SafeNet 仍要求 PIN 出现在 SignTool 进程命令行中。只能在连接了物理 Token 的受控 self-hosted Windows runner 上把它注入为临时 secret;绝不能提交该值、把它写进 `.env`,或持久保存为 Windows 用户或系统环境变量。 使用对应的 `:dir` 命令可以生成可直接运行的应用目录,而不是安装包,例如: @@ -156,21 +146,21 @@ pnpm run package:desktop:mac:arm64:dir pnpm run prepare:desktop ``` -这条诊断命令是另一种停止位置,并非两条命令构建流程的前半段。之后执行 `package:desktop*` 时仍会重新完成正式构建与准备,避免使用陈旧的 dsh 包、运行时文件或 seed 内容。 +这条诊断命令是另一种停止位置,并非两条命令构建流程的前半段。之后执行 `package:desktop*` 时仍会重新完成正式构建与准备,避免使用陈旧的 dsh 包、运行时文件或 dsh 内容。 -每条打包命令都会先执行仓库的正式构建,打包 dsh 与 vendored 包族,在本地打包私有 Desktop Host 包,并打包 Landlock 入口,然后再准备发布资源。`prepare:packages` 选择分别以 `@deepseek-ai/dsh` 和 `@deepseek-ai/dsh-desktop-host` 为根的第一方生产依赖闭包之并集,验证私有 Host tarball 同时包含 `lib/index.js` 与 `config/desktop.cordis.patch.yml`,把选中的 tarball 复制到 seed 输入,并记录其大小与 SHA-512 完整性。Host 包不会发布到 npm;它的 `files` manifest 只包含该运行入口与 overlay。公共包 tarball 仍是由各包发布 manifest 控制的正式 `pnpm pack` 输出,因此 Desktop 不增加第二套过滤规则,会保留 `lib/types` 等已发布声明,也不会独立删除或增加 source map。Registry 包同样在 pnpm 内容寻址 store 中保留其发布的包字节。dsh 发布版本更新会同步更新两个私有 Desktop manifest、仓库根与可发布 workspace;打包还会要求根 dsh 包、Desktop Host 包与 Electron 包使用同一版本。构建 Desktop 应用前不要求 dsh 或私有 Host 已发布到 npm。`prepare:runtime` 从 Node.js 官方发行服务下载 Node.js 24.17.0,在解压前验证其 SHA-256 条目,并在兼容的构建宿主上执行准备完成的目标二进制文件以验证其报告版本。它复制桌面包声明的 pnpm 版本,并把两个运行时版本记录进发布 seed。`prepare:seed` 运行该目标 Node.js 与内置 pnpm,因此按平台和 CPU 过滤的可选依赖会使 pnpm store 与 seed 成为目标专用内容。它生成本地核心包映射、禁用全局 virtual store、从 npm 物化外部生产依赖并禁用生命周期脚本、删除 `node_modules` 以及所有临时 pnpm cache、config 和 state,证明完整依赖图可以离线安装并包含私有 Host 的入口与 overlay,在适用时执行 macOS 重写,再通过一次离线安装证明重写后的 store,删除临时 pnpm 项目注册,然后把松散 store 替换为 16 个确定性的未压缩 tar 分片。它会解包这些最终分片,并在生成清单前验证每个内嵌 macOS 签名。后续 GUI 插件操作保留本地核心包映射,同时从固定的 Desktop npm registry 解析插件包及其外部依赖。`electron-builder` 把各目标的平台产物写到 `apps/desktop/.desktop-build/targets//artifacts`;后续版本会保留不同名称的不可变安装包与 blockmap,但会替换该目标的未打包应用、诊断文件、完成记录与频道元数据。 +每条打包命令都会构建仓库,打包以 dsh 和私有 Desktop Host 为根的第一方生产依赖闭包,并准备目标专用的 Node 与 pnpm 可执行文件。`prepare:dsh` 在构建时安装一次生产依赖图,把物化包复制到 `extraResources/dsh`,移除包管理器元数据,并生成包含共享包版本和最终文件哈希的 `desktop-runtime.json`。在 macOS 上,它先签名并验证原生文件,再生成清单;electron-builder 不对已签名的此目录重复进行嵌套签名。资源映射明确包含默认根目录过滤器会忽略的 `dsh/node_modules`;复制后的清单在签名前及签名后分别验证。签名安装包、公证、已安装应用升级和各目标原生模块的验收需要发布环境。 -未压缩产物包含四块相互独立的体积:Electron、离线 seed store 分片与本地 dsh tarball、上游 Node.js 与 pnpm 运行时,以及很小的桌面壳应用。分片不压缩,使外层 DMG、ZIP 或 NSIS 压缩器与差分更新器可以处理稳定的数据区间。文件系统占用不等于安装包下载大小,因此必须分别测量。打包应用首次启动时还会先把 seed store 解包到 `$DSH_HOME/desktop/pnpm/store`,再安装可写 profile,因此发布验证必须同时测量应用与 Harness home 的磁盘占用。 +未压缩产物包含 Electron、物化后的 dsh 生产依赖树、上游 Node.js 与 pnpm,以及壳应用。安装包大小与文件系统占用不同;发布验收需要测量两者,以及 profile 插件存储和首次启动耗时。此布局用更多应用内文件换取消除用户机器上的核心包安装过程。 ## 更新 -打包应用会在主窗口打开十秒后检查目标专用的发布流;本地化的 **检查更新…** 菜单项会手动触发同一检查。发现可用版本时,应用打开一个原生确认弹窗。用户确认后,应用等待正在进行的检查完成,下载并验证已签名的 Desktop 发布、停止 dsh 子进程,并把安装与重启交给 electron-updater。下次启动会先校准版本绑定的 seed,再重新打开产品窗口。 +打包应用会在主窗口打开十秒后检查目标专用的发布流;本地化的 **检查更新…** 菜单项会手动触发同一检查。发现可用版本时,应用打开一个原生确认弹窗。用户确认后,应用等待正在进行的检查完成,下载并验证已签名的 Desktop 发布、停止 dsh 子进程,并把安装与重启交给 electron-updater。下次启动会先校准版本绑定的运行时,再重新打开产品窗口。 -Electron-builder 始终为 `DSH_DESKTOP_AUTO_UPDATE_ENV` 选择的部署生成 generic-provider 频道元数据。NSIS 差分包与 macOS ZIP 目标让 electron-updater 可以复用未变化的数据块;供手动安装的 DMG 经过公证,但不生成 blockmap,因为它不是 macOS updater 的载荷。Seed 与桌面壳仍属于同一个签名 Desktop 发布。macOS 签名与公证凭据使用 electron-builder 的标准环境变量;Windows EV 签名使用上文所述的公开证书、已验证 SignTool、SafeNet 容器和 runner PIN。必填 Desktop 发布环境选择构建所验证的应用身份与平台签名身份。 +Electron-builder 始终为 `DSH_DESKTOP_AUTO_UPDATE_ENV` 选择的部署生成 generic-provider 频道元数据。NSIS 差分包与 macOS ZIP 目标让 electron-updater 可以复用未变化的数据块;供手动安装的 DMG 经过公证,但不生成 blockmap,因为它不是 macOS updater 的载荷。运行时与桌面壳仍属于同一个签名 Desktop 发布。macOS 签名与公证凭据使用 electron-builder 的标准环境变量;Windows EV 签名使用上文所述的公开证书、已验证 SignTool、SafeNet 容器和 runner PIN。必填 Desktop 发布环境选择构建所验证的应用身份与平台签名身份。 ## 底层开发覆盖项 -`DSH_DESKTOP_NODE_BINARY`、`DSH_DESKTOP_PNPM_ENTRY`、`DSH_DESKTOP_SEED_DIR` 和 `DSH_DESKTOP_DEV_PROJECT_DIR` 可以为未打包 Electron 进程选择明确的资源。打包应用会忽略这些变量,并从 `process.resourcesPath` 解析签名资源。 +`DSH_DESKTOP_NODE_BINARY`、`DSH_DESKTOP_PNPM_ENTRY`、`DSH_DESKTOP_DSH_DIR` 和 `DSH_DESKTOP_DEV_PROJECT_DIR` 可以为未打包 Electron 进程选择明确的资源。打包应用会忽略这些变量,并从 `process.resourcesPath` 解析签名资源。 ## 已知限制 diff --git a/apps/desktop/electron-builder.config.d.mts b/apps/desktop/electron-builder.config.d.mts index 2f4b88de64..760f8cb8a1 100644 --- a/apps/desktop/electron-builder.config.d.mts +++ b/apps/desktop/electron-builder.config.d.mts @@ -6,12 +6,14 @@ export interface DesktopElectronBuilderConfig { } readonly extraResources: readonly [ { readonly from: string, readonly to: 'runtime' }, - { readonly from: string, readonly to: 'seed' }, + { readonly from: string, readonly to: 'dsh' }, + { readonly from: string, readonly to: 'dsh/node_modules' }, ] readonly mac: { readonly identity: string | undefined readonly forceCodeSigning: boolean readonly notarize: boolean + readonly signIgnore: readonly string[] } readonly dmg: { readonly sign: boolean diff --git a/apps/desktop/electron-builder.config.mjs b/apps/desktop/electron-builder.config.mjs index c47bd6d7a9..d082658695 100644 --- a/apps/desktop/electron-builder.config.mjs +++ b/apps/desktop/electron-builder.config.mjs @@ -1,3 +1,4 @@ +import { join } from 'node:path' import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, @@ -59,13 +60,17 @@ export function createElectronBuilderConfig( ], extraResources: [ { from: buildPaths.runtime, to: 'runtime' }, - { from: buildPaths.seed, to: 'seed' }, + { from: buildPaths.dsh, to: 'dsh' }, + // electron-builder excludes a source directory's root node_modules. + { from: join(buildPaths.dsh, 'node_modules'), to: 'dsh/node_modules' }, ], mac: { category: 'public.app-category.developer-tools', identity: macOSSigning?.signingIdentity, forceCodeSigning: true, hardenedRuntime: true, + // Runtime files are signed before their integrity inventory is sealed. + signIgnore: ['/Contents/Resources/dsh(?:/|$)'], notarize: true, target: ['dmg', 'zip'], }, @@ -73,8 +78,16 @@ export function createElectronBuilderConfig( sign: true, writeUpdateInfo: false, }, - afterSign: context => { + afterPack: async context => { + const { verifyDesktopRuntime } = await import('./lib/types/runtime-tree.js') + verifyDesktopRuntime(join(context.packager.getResourcesDir(context.appOutDir), 'dsh'), + context.packager.appInfo.version, { platform: resolvedPlatform, arch: resolvedArch }) + }, + afterSign: async context => { if (context.electronPlatformName !== 'darwin') return + const { verifyDesktopRuntime } = await import('./lib/types/runtime-tree.js') + verifyDesktopRuntime(join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`, 'Contents', 'Resources', 'dsh'), + context.packager.appInfo.version, { platform: 'darwin', arch: resolvedArch }) verifyMacOSSignatureAfterSign(context, macOSSigning ?? resolveMacOSSigningEnvironment(env)) }, artifactBuildCompleted: artifact => { diff --git a/apps/desktop/package.json b/apps/desktop/package.json index ec0b802a17..e8d38981c5 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-desktop", - "description": "Electron desktop shell for an isolated pnpm-installed dsh runtime", + "description": "Electron desktop shell for a bundled dsh runtime and external plugins", "version": "0.1.3-alpha.2", "private": true, "license": "MIT", @@ -12,7 +12,7 @@ "start": "tsx scripts/dev.ts --skip-build", "prepare:runtime": "tsx scripts/prepare-runtime.ts", "prepare:packages": "tsx scripts/prepare-package-set.ts", - "prepare:seed": "tsx scripts/prepare-seed.ts", + "prepare:dsh": "tsx scripts/prepare-dsh.ts", "prepare:package": "tsx scripts/package-target.ts --prepare-only", "verify:mac-signature": "node scripts/verify-macos-signature.mjs", "package": "tsx scripts/package-target.ts", @@ -43,7 +43,6 @@ "electron-builder": "^26.15.3", "extract-zip": "^2.0.1", "js-yaml": "^4.2.0", - "msgpackr": "2.0.4", "pnpm": "11.7.0", "tar": "^7.5.0", "typescript": "^6.0.3" diff --git a/apps/desktop/renderer/plugin-manager.html b/apps/desktop/renderer/plugin-manager.html index 03fbb4b8aa..112fd1825f 100644 --- a/apps/desktop/renderer/plugin-manager.html +++ b/apps/desktop/renderer/plugin-manager.html @@ -16,6 +16,12 @@ +
diff --git a/apps/desktop/renderer/plugin-manager.js b/apps/desktop/renderer/plugin-manager.js index a50de3a825..6599c5b9d5 100644 --- a/apps/desktop/renderer/plugin-manager.js +++ b/apps/desktop/renderer/plugin-manager.js @@ -14,6 +14,10 @@ async function main() { document.querySelector('#installed-heading').textContent = messages.installed document.querySelector('#empty').textContent = messages.noPlugins + document.querySelector('#recovery-description').textContent = messages.recoveryDescription + document.querySelector('#retry').textContent = messages.retry + document.querySelector('#disable-all').textContent = messages.disableAll + const list = document.querySelector('#plugins') const empty = document.querySelector('#empty') const status = document.querySelector('#status') @@ -27,13 +31,16 @@ async function main() { } async function render() { + const backend = await api.backend.status() + document.querySelector('#recovery').hidden = backend.ready + document.querySelector('#startup-error').textContent = backend.error ?? '' const plugins = await api.plugins.list() list.replaceChildren(...plugins.map(plugin => { const item = document.createElement('li') const identity = document.createElement('span') const version = document.createElement('span') version.className = 'package-version' - version.textContent = plugin.version + version.textContent = plugin.enabled ? plugin.version : `${plugin.version} · ${messages.disabled}` identity.append(document.createTextNode(plugin.name), version) const remove = document.createElement('button') remove.type = 'button' @@ -52,7 +59,13 @@ async function main() { }) const actions = document.createElement('span') actions.className = 'package-actions' - actions.append(update, remove) + const toggle = document.createElement('button') + toggle.type = 'button' + toggle.textContent = plugin.enabled ? messages.disable : messages.enable + toggle.addEventListener('click', () => void run( + () => api.plugins.toggle(plugin.name, !plugin.enabled), messages.changingActivation, + )) + actions.append(toggle, update, remove) item.append(identity, actions) return item })) @@ -93,6 +106,8 @@ async function main() { input.value = '' }, message('installing', { spec })) }) + document.querySelector('#retry').addEventListener('click', () => void run(() => api.backend.retry(), messages.retry)) + document.querySelector('#disable-all').addEventListener('click', () => void run(() => api.plugins.disableAll(), messages.changingActivation)) refresh.addEventListener('click', () => void load(messages.refreshing, messages.refreshed)) await load(messages.loadingPlugins, '') diff --git a/apps/desktop/scripts/desktop-build-paths.d.mts b/apps/desktop/scripts/desktop-build-paths.d.mts index 423e017b15..add677f668 100644 --- a/apps/desktop/scripts/desktop-build-paths.d.mts +++ b/apps/desktop/scripts/desktop-build-paths.d.mts @@ -6,8 +6,8 @@ export interface DesktopTargetBuildPaths { readonly artifacts: string readonly runtime: string readonly packageSet: string - readonly seed: string - readonly seedPnpm: string + readonly dsh: string + readonly dshPnpm: string readonly nodeExtract: string readonly packedDsh: string readonly packedVendor: string diff --git a/apps/desktop/scripts/desktop-build-paths.mjs b/apps/desktop/scripts/desktop-build-paths.mjs index 504136e1db..770b3333e3 100644 --- a/apps/desktop/scripts/desktop-build-paths.mjs +++ b/apps/desktop/scripts/desktop-build-paths.mjs @@ -31,7 +31,7 @@ export function resolveDesktopBuildTarget( /** * Return the mutable preparation and artifact directories owned by one release target. * @param {'mac-arm64' | 'mac-x64' | 'win-x64'} target - Supported Desktop target name. - * @returns {{ root: string, artifacts: string, runtime: string, packageSet: string, seed: string, seedPnpm: string, nodeExtract: string, packedDsh: string, packedVendor: string, packedLandlock: string, downloads: string }} Target paths plus the shared immutable download cache. + * @returns {{ root: string, artifacts: string, runtime: string, packageSet: string, dsh: string, dshPnpm: string, nodeExtract: string, packedDsh: string, packedVendor: string, packedLandlock: string, downloads: string }} Target paths plus the shared immutable download cache. */ export function desktopTargetBuildPaths(target) { if (!SUPPORTED_TARGETS.has(target)) { @@ -44,8 +44,8 @@ export function desktopTargetBuildPaths(target) { artifacts: join(root, 'artifacts'), runtime: join(root, 'runtime'), packageSet: join(root, 'package-set'), - seed: join(root, 'seed'), - seedPnpm: join(root, 'seed-pnpm'), + dsh: join(root, 'dsh'), + dshPnpm: join(root, 'dsh-pnpm'), nodeExtract: join(root, 'node-extract'), packedDsh: join(packed, 'dsh'), packedVendor: join(packed, 'vendor'), diff --git a/apps/desktop/scripts/macos-runtime.ts b/apps/desktop/scripts/macos-runtime.ts new file mode 100644 index 0000000000..313c9cdf11 --- /dev/null +++ b/apps/desktop/scripts/macos-runtime.ts @@ -0,0 +1,43 @@ +/** Sign final native runtime files before the enclosing Desktop application is signed. */ + +import { createHash } from 'node:crypto' +import { closeSync, openSync, readSync } from 'node:fs' +import { join } from 'node:path' +import { inventoryDesktopRuntime } from '../src/runtime-tree.ts' +import type { MacOSSigningEnvironment } from './desktop-release-environment.mjs' +import { signMacOSRuntimeCode, verifyMacOSRuntimeCode } from './verify-macos-signature.mjs' + +const MACH_O_MAGICS = new Set(['cafebabe', 'cafebabf', 'cefaedfe', 'cffaedfe', 'feedface', 'feedfacf', 'bebafeca', 'bfbafeca']) + +function isMachO(path: string): boolean { + const descriptor = openSync(path, 'r') + try { + const header = Buffer.alloc(4) + return readSync(descriptor, header, 0, 4, 0) === 4 && MACH_O_MAGICS.has(header.toString('hex')) + } finally { closeSync(descriptor) } +} + +/** + * Sign and verify every materialized Mach-O file, awaiting all signers on failure. + * @param root - Self-contained production runtime without symlinks. + * @param appId - Release application identifier. + * @param expected - Required signing identity. + * @returns Number of signed native files. + */ +export async function signMacOSRuntime(root: string, appId: string, expected: MacOSSigningEnvironment): Promise { + const files = inventoryDesktopRuntime(root).map(file => file.path).filter(path => isMachO(join(root, path))) + let next = 0 + const workers = Array.from({ length: Math.min(4, files.length) }, async () => { + for (;;) { + const path = files[next++] + if (path === undefined) return + const identifier = `${appId}.runtime.${createHash('sha256').update(path).digest('hex')}` + await signMacOSRuntimeCode(join(root, path), identifier, expected) + verifyMacOSRuntimeCode(join(root, path), expected) + } + }) + const results = await Promise.allSettled(workers) + const errors = results.filter(result => result.status === 'rejected').map(result => result.reason as unknown) + if (errors.length > 0) throw new AggregateError(errors, 'desktop runtime: native signing failed') + return files.length +} diff --git a/apps/desktop/scripts/macos-seed-store.ts b/apps/desktop/scripts/macos-seed-store.ts deleted file mode 100644 index 1a02dfd5cc..0000000000 --- a/apps/desktop/scripts/macos-seed-store.ts +++ /dev/null @@ -1,413 +0,0 @@ -/** Sign Mach-O content in a pnpm CAS without invalidating the store index. */ - -import { createHash } from 'node:crypto' -import { - chmodSync, - closeSync, - copyFileSync, - existsSync, - mkdirSync, - mkdtempSync, - openSync, - readFileSync, - readSync, - readdirSync, - rmSync, - unlinkSync, - writeFileSync, -} from 'node:fs' -import { availableParallelism, tmpdir } from 'node:os' -import { basename, dirname, join, relative, sep } from 'node:path' -import { DatabaseSync } from 'node:sqlite' -import { Packr } from 'msgpackr' -import type { MacOSSigningEnvironment } from './desktop-release-environment.mjs' -import { signMacOSSeedCode, verifyMacOSSeedCode } from './verify-macos-signature.mjs' - -const MACH_O_MAGICS = new Set([ - 'cafebabe', - 'cafebabf', - 'cefaedfe', - 'cffaedfe', - 'feedface', - 'feedfacf', - 'bebafeca', - 'bfbafeca', -]) -const CAS_PATH_PATTERN = /^([0-9a-f]{2})\/([0-9a-f]{126})(-exec)?$/u -const MAX_CONCURRENT_CODE_SIGNERS = 4 -const packr = new Packr({ moreTypes: true, useRecords: true }) - -interface PnpmStoreFileRecord { - checkedAt: number - digest: string - mode: number - size: number -} - -interface PnpmSideEffectsRecord { - readonly added?: Map -} - -interface PnpmPackageIndexRecord { - readonly algo?: string - readonly files?: Map - readonly sideEffects?: Map -} - -interface DecodedIndexRow { - readonly key: string - readonly value: PnpmPackageIndexRecord - changed: boolean -} - -interface CasFile { - readonly path: string - readonly digest: string - readonly executable: boolean -} - -interface FileReference { - readonly row: DecodedIndexRow - readonly record: PnpmStoreFileRecord -} - -interface SigningWork { - readonly file: CasFile - readonly references: readonly FileReference[] - readonly temporaryPath: string -} - -/** Summary of native code rewritten in one pnpm store. */ -export interface MacOSSeedStoreSigningResult { - readonly signedFiles: number - readonly prunedOrphans: number - readonly updatedIndexRows: number -} - -/** A signer used to make one writable Mach-O copy release-valid. */ -export type MacOSSeedCodeSigner = (path: string, identifier: string) => Promise - -/** A verifier used to check one Mach-O file after packaging transport. */ -export type MacOSSeedCodeVerifier = (path: string) => void - -/** Optional execution controls for seed-store code signing. */ -export interface MacOSSeedStoreSigningOptions { - readonly signer?: MacOSSeedCodeSigner - readonly concurrency?: number -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} - -function isStoreFileRecord(value: unknown): value is PnpmStoreFileRecord { - if (!isRecord(value)) return false - return typeof value.checkedAt === 'number' - && typeof value.digest === 'string' - && /^[0-9a-f]{128}$/u.test(value.digest) - && Number.isSafeInteger(value.mode) - && Number.isSafeInteger(value.size) -} - -function packageFileMaps(value: unknown, key: string): readonly Map[] { - if (!isRecord(value)) throw new Error(`desktop seed signing: invalid pnpm index record ${key}`) - const record = value as PnpmPackageIndexRecord - if (record.algo !== undefined && record.algo !== 'sha512') { - throw new Error(`desktop seed signing: unsupported pnpm index algorithm in ${key}`) - } - const maps: Map[] = [] - if (record.files !== undefined) { - if (!(record.files instanceof Map)) throw new Error(`desktop seed signing: invalid pnpm file map in ${key}`) - maps.push(record.files) - } - if (record.sideEffects !== undefined) { - if (!(record.sideEffects instanceof Map)) { - throw new Error(`desktop seed signing: invalid pnpm side-effects map in ${key}`) - } - for (const effect of record.sideEffects.values()) { - if (!isRecord(effect)) throw new Error(`desktop seed signing: invalid pnpm side effect in ${key}`) - if (effect.added === undefined) continue - if (!(effect.added instanceof Map)) { - throw new Error(`desktop seed signing: invalid pnpm side-effect file map in ${key}`) - } - maps.push(effect.added) - } - } - for (const files of maps) { - for (const file of files.values()) { - if (!isStoreFileRecord(file)) throw new Error(`desktop seed signing: invalid pnpm file record in ${key}`) - } - } - return maps -} - -function isExecutableMode(mode: number): boolean { - return (mode & 0o111) !== 0 -} - -function referenceKey(digest: string, executable: boolean): string { - return `${digest}:${executable ? 'exec' : 'nonexec'}` -} - -function isMachO(path: string): boolean { - const descriptor = openSync(path, 'r') - try { - const header = Buffer.alloc(4) - return readSync(descriptor, header, 0, header.length, 0) === header.length - && MACH_O_MAGICS.has(header.toString('hex')) - } finally { - closeSync(descriptor) - } -} - -function visitFiles(root: string): readonly string[] { - const files: string[] = [] - const visit = (directory: string): void => { - for (const entry of readdirSync(directory, { withFileTypes: true })) { - const path = join(directory, entry.name) - if (entry.isSymbolicLink()) { - throw new Error(`desktop seed signing: pnpm store contains a symbolic link: ${relative(root, path)}`) - } - if (entry.isDirectory()) visit(path) - else if (entry.isFile()) files.push(path) - else throw new Error(`desktop seed signing: unsupported pnpm store entry: ${relative(root, path)}`) - } - } - visit(root) - return files.sort((left, right) => left.localeCompare(right)) -} - -function versionRoots(storeRoot: string): readonly string[] { - return readdirSync(storeRoot, { withFileTypes: true }) - .filter(entry => entry.isDirectory() && /^v\d+$/u.test(entry.name)) - .map(entry => join(storeRoot, entry.name)) - .filter(root => existsSync(join(root, 'files'))) - .sort((left, right) => left.localeCompare(right)) -} - -function casFiles(versionRoot: string): readonly CasFile[] { - const filesRoot = join(versionRoot, 'files') - const result: CasFile[] = [] - for (const path of visitFiles(filesRoot)) { - if (!isMachO(path)) continue - const normalized = relative(filesRoot, path).split(sep).join('/') - const match = CAS_PATH_PATTERN.exec(normalized) - if (match === null) { - throw new Error(`desktop seed signing: Mach-O content has an unsupported pnpm CAS path: ${normalized}`) - } - result.push({ - path, - digest: `${match[1]}${match[2]}`, - executable: match[3] !== undefined, - }) - } - return result -} - -function readIndexRows(database: DatabaseSync): readonly DecodedIndexRow[] { - const rows: DecodedIndexRow[] = [] - for (const row of database.prepare('SELECT key, data FROM package_index').iterate() as Iterable<{ - key: string - data: Uint8Array - }>) { - rows.push({ key: row.key, value: packr.unpack(row.data) as PnpmPackageIndexRecord, changed: false }) - } - return rows -} - -function fileReferences(rows: readonly DecodedIndexRow[]): ReadonlyMap { - const references = new Map() - for (const row of rows) { - for (const files of packageFileMaps(row.value, row.key)) { - for (const record of files.values()) { - const key = referenceKey(record.digest, isExecutableMode(record.mode)) - const values = references.get(key) ?? [] - values.push({ row, record }) - references.set(key, values) - } - } - } - return references -} - -function writeCasFile(path: string, body: Buffer, mode: number): void { - mkdirSync(dirname(path), { recursive: true }) - try { - writeFileSync(path, body, { flag: 'wx', mode }) - } catch (error) { - if (!isRecord(error) || error.code !== 'EEXIST' || !readFileSync(path).equals(body)) throw error - } - chmodSync(path, mode) -} - -function signedCasPath(versionRoot: string, digest: string, executable: boolean): string { - return join( - versionRoot, - 'files', - digest.slice(0, 2), - `${digest.slice(2)}${executable ? '-exec' : ''}`, - ) -} - -async function runConcurrent( - values: readonly T[], - concurrency: number, - run: (value: T) => Promise, -): Promise { - let next = 0 - const failure: { error?: unknown; failed: boolean } = { failed: false } - const worker = async (): Promise => { - while (!failure.failed) { - const index = next - if (index >= values.length) return - next += 1 - try { - await run(values[index] as T) - } catch (error) { - if (!failure.failed) { - failure.failed = true - failure.error = error - } - } - } - } - const workers = Array.from( - { length: Math.min(concurrency, values.length) }, - async () => worker(), - ) - await Promise.all(workers) - if (failure.failed) throw failure.error -} - -async function rewriteVersionStore( - versionRoot: string, - appId: string, - signer: MacOSSeedCodeSigner, - concurrency: number, -): Promise { - const databasePath = join(versionRoot, 'index.db') - if (!existsSync(databasePath)) { - throw new Error(`desktop seed signing: pnpm store has no package index: ${databasePath}`) - } - const database = new DatabaseSync(databasePath) - const workRoot = mkdtempSync(join(tmpdir(), 'dsh-desktop-seed-signing-')) - const obsoleteFiles = new Set() - let prunedOrphans = 0 - let rows: readonly DecodedIndexRow[] = [] - try { - rows = readIndexRows(database) - const references = fileReferences(rows) - const signingWork: SigningWork[] = [] - for (const file of casFiles(versionRoot)) { - const body = readFileSync(file.path) - const actualDigest = createHash('sha512').update(body).digest('hex') - if (actualDigest !== file.digest) { - throw new Error(`desktop seed signing: pnpm CAS digest mismatch at ${file.path}`) - } - const fileReferences = references.get(referenceKey(file.digest, file.executable)) ?? [] - if (fileReferences.length === 0) { - obsoleteFiles.add(file.path) - prunedOrphans += 1 - continue - } - const temporary = join(workRoot, `${signingWork.length.toString().padStart(4, '0')}-${basename(file.path)}`) - copyFileSync(file.path, temporary) - chmodSync(temporary, 0o755) - signingWork.push({ file, references: fileReferences, temporaryPath: temporary }) - } - await runConcurrent(signingWork, concurrency, async (work) => { - await signer(work.temporaryPath, `${appId}.seed.${work.file.digest.slice(0, 32)}`) - }) - for (const work of signingWork) { - const signedBody = readFileSync(work.temporaryPath) - if (!isMachO(work.temporaryPath)) { - throw new Error(`desktop seed signing: signer produced non-Mach-O content for ${work.file.path}`) - } - const signedDigest = createHash('sha512').update(signedBody).digest('hex') - const mode = work.file.executable ? 0o755 : 0o644 - const destination = signedCasPath(versionRoot, signedDigest, work.file.executable) - writeCasFile(destination, signedBody, mode) - const checkedAt = Date.now() - for (const reference of work.references) { - reference.record.checkedAt = checkedAt - reference.record.digest = signedDigest - reference.record.mode = mode - reference.record.size = signedBody.length - reference.row.changed = true - } - if (destination !== work.file.path) obsoleteFiles.add(work.file.path) - } - const changedRows = rows.filter(row => row.changed) - database.exec('BEGIN IMMEDIATE') - let committed = false - try { - const statement = database.prepare('INSERT OR REPLACE INTO package_index (key, data) VALUES (?, ?)') - for (const row of changedRows) statement.run(row.key, packr.pack(row.value)) - database.exec('COMMIT') - committed = true - } finally { - if (!committed) database.exec('ROLLBACK') - } - for (const path of obsoleteFiles) unlinkSync(path) - database.exec('VACUUM') - return { signedFiles: signingWork.length, prunedOrphans, updatedIndexRows: changedRows.length } - } finally { - database.close() - rmSync(workRoot, { recursive: true, force: true }) - } -} - -/** - * Replace every Mach-O CAS object with a Developer ID signed object and update pnpm's SHA-512 index. - * A signer rejection leaves the original CAS objects and package index unchanged. - * @param storeRoot - Loose pnpm store prepared for the packaged seed. - * @param appId - Electron application ID used as the signing identifier prefix. - * @param expected - Company Developer ID identity and Team ID. - * @param options - Optional signer and worker bound used by focused tests. - * @returns Counts for release diagnostics after every signer completes and the index transaction commits. - */ -export async function signMacOSSeedStore( - storeRoot: string, - appId: string, - expected: MacOSSigningEnvironment, - options: MacOSSeedStoreSigningOptions = {}, -): Promise { - const roots = versionRoots(storeRoot) - if (roots.length === 0) throw new Error(`desktop seed signing: no pnpm store versions found in ${storeRoot}`) - const concurrency = options.concurrency ?? Math.min(MAX_CONCURRENT_CODE_SIGNERS, availableParallelism()) - if (!Number.isSafeInteger(concurrency) || concurrency < 1) { - throw new Error(`desktop seed signing: concurrency must be a positive integer; received ${String(concurrency)}`) - } - const signer = options.signer ?? (async (path, identifier) => { - await signMacOSSeedCode(path, identifier, expected) - }) - const results: MacOSSeedStoreSigningResult[] = [] - for (const root of roots) results.push(await rewriteVersionStore(root, appId, signer, concurrency)) - return results.reduce((total, current) => ({ - signedFiles: total.signedFiles + current.signedFiles, - prunedOrphans: total.prunedOrphans + current.prunedOrphans, - updatedIndexRows: total.updatedIndexRows + current.updatedIndexRows, - }), { signedFiles: 0, prunedOrphans: 0, updatedIndexRows: 0 }) -} - -/** - * Verify that every Mach-O CAS object has the expected Developer ID, timestamp, and hardened runtime. - * @param storeRoot - Loose or extracted pnpm store. - * @param expected - Company Developer ID identity and Team ID. - * @param verifier - Injectable signature verifier used by focused tests. - * @returns Number of verified Mach-O files. - */ -export function verifyMacOSSeedStore( - storeRoot: string, - expected: MacOSSigningEnvironment, - verifier: MacOSSeedCodeVerifier = (path) => { verifyMacOSSeedCode(path, expected) }, -): number { - let count = 0 - for (const root of versionRoots(storeRoot)) { - for (const file of casFiles(root)) { - verifier(file.path) - count += 1 - } - } - return count -} diff --git a/apps/desktop/scripts/package-target.ts b/apps/desktop/scripts/package-target.ts index 1f32123ec0..c5b0bc2667 100644 --- a/apps/desktop/scripts/package-target.ts +++ b/apps/desktop/scripts/package-target.ts @@ -1,4 +1,4 @@ -/** Build one release target with matching Electron, Node.js, and seed architecture. */ +/** Build one release target with matching Electron, Node.js, and dsh architecture. */ import { spawn } from 'node:child_process' import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' @@ -276,7 +276,7 @@ async function main(): Promise { ], buildEnv, REPOSITORY_ROOT) await runPnpm(['run', 'prepare:runtime'], targetEnv) await runPnpm(['run', 'prepare:packages'], targetEnv) - await runPnpm(['run', 'prepare:seed'], targetEnv) + await runPnpm(['run', 'prepare:dsh'], targetEnv) if (invocation.prepareOnly) return await runPnpm(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv) if (!invocation.directory) writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts) diff --git a/apps/desktop/scripts/prepare-dsh.ts b/apps/desktop/scripts/prepare-dsh.ts new file mode 100644 index 0000000000..d030a05e1a --- /dev/null +++ b/apps/desktop/scripts/prepare-dsh.ts @@ -0,0 +1,150 @@ +/** Materialize the complete production runtime before publishing Desktop resources. */ + +import { spawn } from 'node:child_process' +import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { delimiter, dirname, join, resolve } from 'node:path' +import { createRuntimeProjectMetadata } from '../src/project-manager.ts' +import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts' +import { parseDesktopRelease, type DesktopRelease } from '../src/release.ts' +import { + DESKTOP_HOST_PACKAGE, + DESKTOP_HOST_RUNTIME_FILES, + DESKTOP_PACKAGES_DIR, + DESKTOP_PACKAGE_SET_FILE, + readDesktopCorePackageSet, + verifyDesktopCoreLockfile, +} from '../src/core-package-set.ts' +import { smokeDesktopRuntime } from './smoke-runtime.ts' +import { writeDesktopRuntime, verifyDesktopRuntime } from '../src/runtime-tree.ts' +import { + resolveDesktopAppId, + resolveMacOSSigningEnvironment, +} from './desktop-release-environment.mjs' +import { + signMacOSRuntime, +} from './macos-runtime.ts' +import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' + +const APP_ROOT = resolve(import.meta.dirname, '..') +const BUILD_PATHS = resolveDesktopTargetBuildPaths() +const DSH_OUTPUT_ROOT = BUILD_PATHS.dsh +const BUILD_ROOT = mkdtempSync(join(tmpdir(), 'dsh-desktop-runtime-')) +const STORE_ROOT = join(BUILD_ROOT, 'store') +const RUNTIME_ROOT = BUILD_PATHS.runtime +const PNPM_BUILD_STATE = BUILD_PATHS.dshPnpm +const PACKAGE_SET_ROOT = BUILD_PATHS.packageSet +const NODE = join(RUNTIME_ROOT, 'node', process.platform === 'win32' ? 'node.exe' : 'node') +const PNPM = join(RUNTIME_ROOT, 'pnpm', 'bin', 'pnpm.mjs') + +function manifestVersion(path: string, subject: string): string { + const manifest = JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown } + if (typeof manifest.version !== 'string') throw new Error(`desktop runtime: ${subject} has no version`) + return manifest.version +} + +function desktopRelease(): DesktopRelease { + const version = manifestVersion(join(APP_ROOT, 'package.json'), 'desktop package') + const dshVersion = manifestVersion(resolve(APP_ROOT, '..', '..', 'package.json'), 'root dsh package') + if (version !== dshVersion) { + throw new Error(`desktop runtime: Electron ${version} must bind the same version of @deepseek-ai/dsh, found ${dshVersion}`) + } + const runtime = JSON.parse(readFileSync(join(RUNTIME_ROOT, 'versions.json'), 'utf8')) as Record + return parseDesktopRelease({ + schemaVersion: 1, + version, + hostProtocolVersion: DESKTOP_HOST_PROTOCOL_VERSION, + nodeVersion: runtime.node, + pnpmVersion: runtime.pnpm, + }) +} + +function runPnpm(args: readonly string[]): Promise { + return new Promise((resolvePromise, reject) => { + const [command, ...commandArgs] = args + if (command === undefined) throw new Error('desktop runtime: pnpm command is required') + const config = join(PNPM_BUILD_STATE, 'config') + const userConfig = join(config, 'npmrc') + mkdirSync(config, { recursive: true }) + writeFileSync(userConfig, '') + const child = spawn(NODE, [ + PNPM, + '--config.registry=https://registry.npmjs.org/', + `--config.store-dir=${STORE_ROOT}`, + '--config.enable-global-virtual-store=false', + `--config.userconfig=${userConfig}`, + command, + ...commandArgs, + ], { + cwd: BUILD_ROOT, + env: { + ...Object.fromEntries(Object.entries(process.env).filter(([name]) => ( + name !== 'NODE_OPTIONS' && name !== 'NODE_PATH' && !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name) + ))), + NPM_CONFIG_REGISTRY: 'https://registry.npmjs.org/', + NPM_CONFIG_STORE_DIR: STORE_ROOT, + NPM_CONFIG_USERCONFIG: userConfig, + PATH: `${dirname(NODE)}${delimiter}${process.env.PATH ?? ''}`, + XDG_CACHE_HOME: join(PNPM_BUILD_STATE, 'cache'), + XDG_CONFIG_HOME: config, + XDG_STATE_HOME: join(PNPM_BUILD_STATE, 'state'), + }, + stdio: 'inherit', + }) + child.once('error', reject) + child.once('close', (code, signal) => { + if (code === 0) resolvePromise() + else reject(new Error(`desktop runtime: pnpm exited with ${String(code ?? signal)}`)) + }) + }) +} + +async function main(): Promise { + rmSync(DSH_OUTPUT_ROOT, { recursive: true, force: true }) + rmSync(PNPM_BUILD_STATE, { recursive: true, force: true }) + mkdirSync(STORE_ROOT, { recursive: true }) + try { + const release = desktopRelease() + 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']) + verifyDesktopCoreLockfile( + readFileSync(join(BUILD_ROOT, 'pnpm-lock.yaml'), 'utf8'), + readDesktopCorePackageSet(BUILD_ROOT, release.version), + ) + await runPnpm(['install', '--prod', '--frozen-lockfile', '--trust-lockfile']) + const packageSet = readDesktopCorePackageSet(BUILD_ROOT, release.version) + mkdirSync(DSH_OUTPUT_ROOT, { recursive: true }) + cpSync(join(BUILD_ROOT, 'node_modules'), join(DSH_OUTPUT_ROOT, 'node_modules'), { + recursive: true, dereference: true, + filter: source => !source.split(/[\\/]/u).some(part => part === '.bin' || part === '.pnpm' || part === '.modules.yaml' || part === '.pnpm-workspace-state-v1.json'), + }) + writeFileSync(join(DSH_OUTPUT_ROOT, 'package.json'), `${JSON.stringify({ + name: '@deepseek-ai/dsh-desktop-runtime', private: true, version: release.version, type: 'module', + dependencies: Object.fromEntries(packageSet.packages.map(entry => [entry.name, entry.version])), + }, undefined, 2)}\n`) + for (const file of DESKTOP_HOST_RUNTIME_FILES) { + if (!existsSync(join(DSH_OUTPUT_ROOT, 'node_modules', DESKTOP_HOST_PACKAGE, file))) { + throw new Error(`desktop runtime: missing private Host file ${file}`) + } + } + if (process.platform === 'darwin') { + await signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env)) + } + const targetName = resolveDesktopBuildTarget() + const target = { platform: process.platform, arch: targetName.endsWith('arm64') ? 'arm64' : 'x64' } + writeDesktopRuntime(DSH_OUTPUT_ROOT, release, packageSet.packages.map(entry => entry.name), target) + const descriptor = verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target) + await smokeDesktopRuntime(DSH_OUTPUT_ROOT, NODE, descriptor) + verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target) + } catch (error) { + rmSync(DSH_OUTPUT_ROOT, { recursive: true, force: true }) + throw error + } finally { + rmSync(BUILD_ROOT, { recursive: true, force: true }) + rmSync(PNPM_BUILD_STATE, { recursive: true, force: true }) + } +} + +await main() diff --git a/apps/desktop/scripts/prepare-seed.ts b/apps/desktop/scripts/prepare-seed.ts deleted file mode 100644 index 73da078ef2..0000000000 --- a/apps/desktop/scripts/prepare-seed.ts +++ /dev/null @@ -1,200 +0,0 @@ -/** Build the release seed through the same embedded pnpm used on first launch. */ - -import { spawn } from 'node:child_process' -import { createHash } from 'node:crypto' -import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { delimiter, dirname, join, relative, resolve, sep } from 'node:path' -import { createSeedMetadata } from '../src/project-manager.ts' -import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts' -import { parseDesktopRelease, type DesktopRelease } from '../src/release.ts' -import { - DESKTOP_HOST_PACKAGE, - DESKTOP_HOST_RUNTIME_FILES, - DESKTOP_PACKAGES_DIR, - DESKTOP_PACKAGE_SET_FILE, - readDesktopCorePackageSet, - verifyDesktopCoreLockfile, -} from '../src/core-package-set.ts' -import { - archivePnpmStore, - extractPnpmStoreArchives, - removePnpmProjectRegistrations, -} from '../src/seed-store.ts' -import { - resolveDesktopAppId, - resolveMacOSSigningEnvironment, -} from './desktop-release-environment.mjs' -import { - signMacOSSeedStore, - verifyMacOSSeedStore, -} from './macos-seed-store.ts' -import { resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' - -const APP_ROOT = resolve(import.meta.dirname, '..') -const BUILD_PATHS = resolveDesktopTargetBuildPaths() -const SEED_OUTPUT_ROOT = BUILD_PATHS.seed -const SEED_ROOT = mkdtempSync(join(tmpdir(), 'dsh-desktop-seed-')) -const STORE_ROOT = join(SEED_ROOT, 'store') -const RUNTIME_ROOT = BUILD_PATHS.runtime -const PNPM_BUILD_STATE = BUILD_PATHS.seedPnpm -const PACKAGE_SET_ROOT = BUILD_PATHS.packageSet -const NODE = join(RUNTIME_ROOT, 'node', process.platform === 'win32' ? 'node.exe' : 'node') -const PNPM = join(RUNTIME_ROOT, 'pnpm', 'bin', 'pnpm.mjs') - -function manifestVersion(path: string, subject: string): string { - const manifest = JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown } - if (typeof manifest.version !== 'string') throw new Error(`desktop seed: ${subject} has no version`) - return manifest.version -} - -function desktopRelease(): DesktopRelease { - const version = manifestVersion(join(APP_ROOT, 'package.json'), 'desktop package') - const dshVersion = manifestVersion(resolve(APP_ROOT, '..', '..', 'package.json'), 'root dsh package') - if (version !== dshVersion) { - throw new Error(`desktop seed: Electron ${version} must bind the same version of @deepseek-ai/dsh, found ${dshVersion}`) - } - const runtime = JSON.parse(readFileSync(join(RUNTIME_ROOT, 'versions.json'), 'utf8')) as Record - return parseDesktopRelease({ - schemaVersion: 1, - version, - hostProtocolVersion: DESKTOP_HOST_PROTOCOL_VERSION, - nodeVersion: runtime.node, - pnpmVersion: runtime.pnpm, - }) -} - -function runPnpm(args: readonly string[]): Promise { - return new Promise((resolvePromise, reject) => { - const [command, ...commandArgs] = args - if (command === undefined) throw new Error('desktop seed: pnpm command is required') - const config = join(PNPM_BUILD_STATE, 'config') - const userConfig = join(config, 'npmrc') - mkdirSync(config, { recursive: true }) - writeFileSync(userConfig, '') - const child = spawn(NODE, [ - PNPM, - '--config.registry=https://registry.npmjs.org/', - `--config.store-dir=${STORE_ROOT}`, - '--config.enable-global-virtual-store=false', - `--config.userconfig=${userConfig}`, - command, - ...commandArgs, - ], { - cwd: SEED_ROOT, - env: { - ...Object.fromEntries(Object.entries(process.env).filter(([name]) => ( - !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name) - ))), - NPM_CONFIG_REGISTRY: 'https://registry.npmjs.org/', - NPM_CONFIG_STORE_DIR: STORE_ROOT, - NPM_CONFIG_USERCONFIG: userConfig, - PATH: `${dirname(NODE)}${delimiter}${process.env.PATH ?? ''}`, - XDG_CACHE_HOME: join(PNPM_BUILD_STATE, 'cache'), - XDG_CONFIG_HOME: config, - XDG_STATE_HOME: join(PNPM_BUILD_STATE, 'state'), - }, - stdio: 'inherit', - }) - child.once('error', reject) - child.once('close', (code, signal) => { - if (code === 0) resolvePromise() - else reject(new Error(`desktop seed: pnpm exited with ${String(code ?? signal)}`)) - }) - }) -} - -function inventory(root: string): readonly { path: string; bytes: number; sha256: string }[] { - const files: string[] = [] - const visit = (dir: string): void => { - for (const entry of readdirSync(dir, { withFileTypes: true })) { - const path = join(dir, entry.name) - if (entry.isDirectory()) visit(path) - else if (entry.isFile()) files.push(path) - else throw new Error(`desktop seed: unsupported filesystem entry ${relative(root, path)}`) - } - } - visit(root) - return files.sort().map((path) => { - const body = readFileSync(path) - return { - path: relative(root, path).split(sep).join('/'), - bytes: statSync(path).size, - sha256: createHash('sha256').update(body).digest('hex'), - } - }) -} - -async function verifyOfflineInstallation(release: DesktopRelease): Promise { - const installedModules = join(SEED_ROOT, 'node_modules') - try { - await runPnpm(['install', '--offline', '--frozen-lockfile', '--trust-lockfile']) - const hostRoot = join(installedModules, ...DESKTOP_HOST_PACKAGE.split('/')) - for (const file of DESKTOP_HOST_RUNTIME_FILES) { - if (!existsSync(join(hostRoot, file))) { - throw new Error(`desktop seed: local ${DESKTOP_HOST_PACKAGE}@${release.version} does not contain ${file}`) - } - } - } finally { - rmSync(installedModules, { recursive: true, force: true }) - } -} - -async function main(): Promise { - rmSync(SEED_OUTPUT_ROOT, { recursive: true, force: true }) - rmSync(PNPM_BUILD_STATE, { recursive: true, force: true }) - mkdirSync(STORE_ROOT, { recursive: true }) - try { - const release = desktopRelease() - copyFileSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGE_SET_FILE), join(SEED_ROOT, DESKTOP_PACKAGE_SET_FILE)) - cpSync(join(PACKAGE_SET_ROOT, DESKTOP_PACKAGES_DIR), join(SEED_ROOT, DESKTOP_PACKAGES_DIR), { recursive: true }) - createSeedMetadata(SEED_ROOT, release) - await runPnpm(['install', '--lockfile-only']) - verifyDesktopCoreLockfile( - readFileSync(join(SEED_ROOT, 'pnpm-lock.yaml'), 'utf8'), - readDesktopCorePackageSet(SEED_ROOT, release.version), - ) - const installedModules = join(SEED_ROOT, 'node_modules') - await runPnpm(['install', '--prod', '--frozen-lockfile', '--trust-lockfile', '--ignore-scripts']) - rmSync(installedModules, { recursive: true, force: true }) - rmSync(PNPM_BUILD_STATE, { recursive: true, force: true }) - await verifyOfflineInstallation(release) - const targetPlatform = process.env.DSH_DESKTOP_TARGET_PLATFORM ?? process.platform - let signedMachOFiles: number | undefined - let macOSSigning: ReturnType | undefined - if (targetPlatform === 'darwin') { - macOSSigning = resolveMacOSSigningEnvironment(process.env) - const signing = await signMacOSSeedStore( - STORE_ROOT, - resolveDesktopAppId(process.env), - macOSSigning, - ) - signedMachOFiles = signing.signedFiles - process.stdout.write( - `desktop seed: signed ${signing.signedFiles} Mach-O files, updated ${signing.updatedIndexRows} pnpm index records, and pruned ${signing.prunedOrphans} native orphans\n`, - ) - await verifyOfflineInstallation(release) - } - removePnpmProjectRegistrations(STORE_ROOT) - archivePnpmStore(SEED_ROOT, STORE_ROOT) - if (macOSSigning !== undefined && signedMachOFiles !== undefined) { - const extractedStore = mkdtempSync(join(tmpdir(), 'dsh-desktop-seed-verification-')) - try { - extractPnpmStoreArchives(SEED_ROOT, extractedStore) - const verified = verifyMacOSSeedStore(extractedStore, macOSSigning) - if (verified !== signedMachOFiles) { - throw new Error(`desktop seed: archived store contains ${verified} signed Mach-O files; expected ${signedMachOFiles}`) - } - } finally { - rmSync(extractedStore, { recursive: true, force: true }) - } - } - const records = inventory(SEED_ROOT).filter(entry => entry.path !== 'integrity.json') - writeFileSync(join(SEED_ROOT, 'integrity.json'), `${JSON.stringify({ schemaVersion: 2, files: records }, undefined, 2)}\n`) - cpSync(SEED_ROOT, SEED_OUTPUT_ROOT, { recursive: true }) - } finally { - rmSync(SEED_ROOT, { recursive: true, force: true }) - } -} - -await main() diff --git a/apps/desktop/scripts/smoke-runtime.ts b/apps/desktop/scripts/smoke-runtime.ts new file mode 100644 index 0000000000..4b4103e534 --- /dev/null +++ b/apps/desktop/scripts/smoke-runtime.ts @@ -0,0 +1,58 @@ +/** Boot the materialized target runtime without access to a user's Harness profile. */ + +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { DesktopHostProcess } from '../src/host-process.ts' +import { createPluginProfile } from '../src/project-manager.ts' +import { linkDesktopHostPackages, validateDesktopPluginGraph } from '../src/profile-packages.ts' +import type { DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' + +/** + * Prove the final resource tree boots and serves its matching Web frontend. + * @param root - Materialized dsh resources. + * @param node - Prepared target Node executable. + * @param runtime - Verified resource descriptor. + */ +export async function smokeDesktopRuntime(root: string, node: string, runtime: DesktopRuntimeDescriptor): Promise { + const home = mkdtempSync(join(tmpdir(), 'dsh-desktop-smoke-')) + const profile = join(home, 'profiles', 'desktop') + const host = new DesktopHostProcess(node, root, profile, undefined, { ...process.env, DSH_HOME: home }) + try { + createPluginProfile(profile) + const pluginName = 'desktop-runtime-smoke-plugin' + const plugin = join(profile, 'node_modules', pluginName) + mkdirSync(plugin, { recursive: true }) + const cordis = runtime.sharedPackages.find(entry => entry.name === '@deepseek-ai/cordis') + if (cordis === undefined) throw new Error('desktop runtime: missing shared Cordis package') + writeFileSync(join(plugin, 'package.json'), JSON.stringify({ + name: pluginName, version: '1.0.0', type: 'module', exports: './index.js', + peerDependencies: { '@deepseek-ai/cordis': cordis.version }, dsh: { bundle: { patch: './bundle.yml' } }, + })) + writeFileSync(join(plugin, 'index.js'), ` +import { Context } from '@deepseek-ai/cordis' +export function apply(ctx) { + if (!(ctx instanceof Context)) throw new Error('desktop runtime: external plugin loaded another Cordis instance') +} +`) + writeFileSync(join(plugin, 'bundle.yml'), '- insert:\n - id: desktop-runtime-smoke-plugin\n name: desktop-runtime-smoke-plugin\n') + const manifest = JSON.parse(readFileSync(join(profile, 'package.json'), 'utf8')) as { + dependencies: Record + dsh: { profile: { bundles: string[] } } + } + manifest.dependencies[pluginName] = '1.0.0' + manifest.dsh.profile.bundles.push(pluginName) + writeFileSync(join(profile, 'package.json'), JSON.stringify(manifest)) + linkDesktopHostPackages(profile, root, runtime) + validateDesktopPluginGraph(profile, root, runtime, [pluginName]) + const ready = await host.start() + if (ready.dshVersion !== runtime.release.version) throw new Error('desktop runtime: Host reported another dsh release') + const response = await host.fetch(new Request('dsh-app://app/')) + if (response.status !== 200 || !(await response.text()).includes(' /** - * Verify one Mach-O file embedded in the seed store. + * Verify one Mach-O file embedded in the runtime tree. * @param path - Mach-O file to inspect. * @param expected - Public release identity. */ -export function verifyMacOSSeedCode(path: string, expected: MacOSSigningEnvironment): void +export function verifyMacOSRuntimeCode(path: string, expected: MacOSSigningEnvironment): void /** * Verify the full application signature and its release owner. diff --git a/apps/desktop/scripts/verify-macos-signature.mjs b/apps/desktop/scripts/verify-macos-signature.mjs index 48b254dedd..af0d6196ae 100644 --- a/apps/desktop/scripts/verify-macos-signature.mjs +++ b/apps/desktop/scripts/verify-macos-signature.mjs @@ -1,4 +1,4 @@ -/** Sign seed code and verify that packaged macOS artifacts carry the company release identity. */ +/** Sign runtime code and verify that packaged macOS artifacts carry the company release identity. */ import { spawn, spawnSync } from 'node:child_process' import { resolve } from 'node:path' @@ -21,19 +21,19 @@ export function assertMacOSSignatureDetails(details, expected) { } /** - * Require the signature properties Apple validates for executable seed content. + * Require the signature properties Apple validates for executable runtime content. * @param {string} details - Output from `codesign --display --verbose=4`. * @param {{ signingIdentity: string, teamId: string }} expected - Public release identity. * @returns {void} */ -export function assertMacOSSeedSignatureDetails(details, expected) { +export function assertMacOSRuntimeSignatureDetails(details, expected) { assertMacOSSignatureDetails(details, expected) const fields = details.split(/\r?\n/u).map(line => line.trim()) if (!fields.some(line => /^Timestamp=.+/u.test(line))) { - throw new Error('desktop macOS signing: seed signature has no secure timestamp') + throw new Error('desktop macOS signing: runtime signature has no secure timestamp') } if (!fields.some(line => /\bflags=0x[0-9a-f]+\(runtime\)(?:\s|$)/iu.test(line))) { - throw new Error('desktop macOS signing: seed signature does not enable hardened runtime') + throw new Error('desktop macOS signing: runtime signature does not enable hardened runtime') } } @@ -60,7 +60,7 @@ function runAppleCommand(command, args, label) { } /** - * Execute one Apple release tool without blocking other independent seed signers. + * Execute one Apple release tool without blocking other independent runtime signers. * @param {string} command - Absolute executable path. * @param {readonly string[]} args - Tool arguments. * @param {string} label - Stable diagnostic name. @@ -106,13 +106,13 @@ function runCodeSign(args) { } /** - * Sign one Mach-O file embedded in the seed store. + * Sign one Mach-O file embedded in the runtime tree. * @param {string} path - Writable standalone Mach-O file. * @param {string} identifier - Stable code-signing identifier derived from the release app ID and CAS digest. * @param {{ signingIdentity: string, teamId: string }} expected - Public release identity. * @returns {Promise} Resolves after codesign exits successfully. */ -export async function signMacOSSeedCode(path, identifier, expected) { +export async function signMacOSRuntimeCode(path, identifier, expected) { await runAppleCommandAsync('/usr/bin/codesign', [ '--force', '--sign', expected.signingIdentity, @@ -124,15 +124,15 @@ export async function signMacOSSeedCode(path, identifier, expected) { } /** - * Verify one Mach-O file embedded in the seed store. + * Verify one Mach-O file embedded in the runtime tree. * @param {string} path - Mach-O file to inspect. * @param {{ signingIdentity: string, teamId: string }} expected - Public release identity. * @returns {void} */ -export function verifyMacOSSeedCode(path, expected) { +export function verifyMacOSRuntimeCode(path, expected) { runCodeSign(['--verify', '--strict', '--verbose=2', path]) const details = runCodeSign(['--display', '--verbose=4', path]) - assertMacOSSeedSignatureDetails(details, expected) + assertMacOSRuntimeSignatureDetails(details, expected) } /** diff --git a/apps/desktop/src/core-package-set.ts b/apps/desktop/src/core-package-set.ts index ff93bd5605..249057d647 100644 --- a/apps/desktop/src/core-package-set.ts +++ b/apps/desktop/src/core-package-set.ts @@ -124,7 +124,7 @@ export function desktopDshPackageSpec(packageSet: DesktopCorePackageSet): string /** * Verify every local tarball and reject extra package files before pnpm executes them. - * @param projectDir - Seed or profile directory containing the package set. + * @param projectDir - Build directory containing the package set. * @param expectedReleaseVersion - Exact dsh and Desktop Host version bound to Electron. * @returns The verified package set. */ diff --git a/apps/desktop/src/host-process.ts b/apps/desktop/src/host-process.ts index ed18d0c7d6..20c59cf7e1 100644 --- a/apps/desktop/src/host-process.ts +++ b/apps/desktop/src/host-process.ts @@ -86,28 +86,33 @@ export class DesktopHostProcess { /** * @param node - absolute bundled upstream Node.js executable. - * @param projectDir - active or staged desktop npm project. + * @param runtimeDir - immutable packages carried by the current application. + * @param projectDir - active or staged desktop plugin profile. * @param inspectPort - optional loopback inspector port for workspace development. + * @param environment - Child environment; runtime and package-manager overrides are removed. */ constructor( private readonly node: string, + private readonly runtimeDir: string, private readonly projectDir: string, private readonly inspectPort?: number, + private readonly environment: NodeJS.ProcessEnv = process.env, ) {} /** Start the child once and resolve only after its complete composition is active. */ async start(): Promise { if (this.child !== undefined) return this.readyPromise - const entry = join(this.projectDir, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'index.js') + const entry = join(this.runtimeDir, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'index.js') const child = spawn(this.node, [ ...(this.inspectPort === undefined ? [] : [`--inspect=127.0.0.1:${String(this.inspectPort)}`]), entry, + this.runtimeDir, this.projectDir, ...(this.inspectPort === undefined ? [] : ['--allow-linked-profile']), ], { cwd: this.projectDir, - env: Object.fromEntries(Object.entries(process.env).filter(([name]) => ( - name !== 'NODE_OPTIONS' && !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name) + env: Object.fromEntries(Object.entries(this.environment).filter(([name]) => ( + name !== 'NODE_OPTIONS' && name !== 'NODE_PATH' && !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name) ))), stdio: ['ignore', 'pipe', 'pipe', 'pipe', 'pipe', 'ipc'], }) diff --git a/apps/desktop/src/ipc.ts b/apps/desktop/src/ipc.ts index 4fb946a2a5..f98bf22902 100644 --- a/apps/desktop/src/ipc.ts +++ b/apps/desktop/src/ipc.ts @@ -10,6 +10,10 @@ export const DESKTOP_IPC = { pluginsAdd: 'dsh-desktop:plugins-add', pluginsRemove: 'dsh-desktop:plugins-remove', pluginsUpdate: 'dsh-desktop:plugins-update', + pluginsToggle: 'dsh-desktop:plugins-toggle', + pluginsDisableAll: 'dsh-desktop:plugins-disable-all', + backendStatus: 'dsh-desktop:backend-status', + backendRetry: 'dsh-desktop:backend-retry', updatesCheck: 'dsh-desktop:updates-check', updatesInstall: 'dsh-desktop:updates-install', updatesState: 'dsh-desktop:updates-state', @@ -31,6 +35,12 @@ export interface DshDesktopApi { add(spec: string): Promise remove(name: string): Promise update(name: string, version: string): Promise + toggle(name: string, enabled: boolean): Promise + disableAll(): Promise + } + readonly backend: { + status(): Promise<{ readonly ready: boolean; readonly error?: string }> + retry(): Promise } readonly updates: { check(): Promise diff --git a/apps/desktop/src/locale.ts b/apps/desktop/src/locale.ts index b666cfd559..65e5083313 100644 --- a/apps/desktop/src/locale.ts +++ b/apps/desktop/src/locale.ts @@ -20,6 +20,13 @@ export const en = { pluginWindowTitle: 'DeepSeek Harness — Desktop Plugins', pluginManagerDescription: 'Plugins are installed only in the Desktop node_modules and are managed by the bundled pnpm.', refresh: 'Refresh', + enable: 'Enable', + disable: 'Disable', + disabled: 'Disabled', + retry: 'Retry startup', + disableAll: 'Disable all plugins and retry', + recoveryDescription: 'The backend could not start. Update or disable incompatible plugins, then retry. Installed plugins and configuration are retained.', + changingActivation: 'Changing plugin activation…', npmPackage: 'npm package', install: 'Install', installed: 'Installed', @@ -59,6 +66,13 @@ export const zh = { pluginWindowTitle: 'DeepSeek Harness — 桌面插件', pluginManagerDescription: '插件只安装到桌面端自己的 node_modules,并由内置 pnpm 管理。', refresh: '刷新', + enable: '启用', + disable: '禁用', + disabled: '已禁用', + retry: '重试启动', + disableAll: '禁用全部插件并重试', + recoveryDescription: '后端无法启动。请更新或禁用不兼容插件,然后重试。已安装插件和配置会保留。', + changingActivation: '正在更改插件启用状态…', npmPackage: 'npm 包', install: '安装', installed: '已安装', diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 8bc9fdcefd..a995d6818e 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -49,7 +49,7 @@ const MIME: Readonly> = { interface RuntimeResources { readonly node: string readonly pnpm: string - readonly seed: string + readonly dsh: string } function runtimeResources(): RuntimeResources { @@ -58,8 +58,8 @@ function runtimeResources(): RuntimeResources { ?? join(process.resourcesPath, 'runtime', 'node', process.platform === 'win32' ? 'node.exe' : 'node') const pnpm = (development ? process.env.DSH_DESKTOP_PNPM_ENTRY : undefined) ?? join(process.resourcesPath, 'runtime', 'pnpm', 'bin', 'pnpm.mjs') - const seed = (development ? process.env.DSH_DESKTOP_SEED_DIR : undefined) ?? join(process.resourcesPath, 'seed') - return { node, pnpm, seed } + const dsh = (development ? process.env.DSH_DESKTOP_DSH_DIR : undefined) ?? join(process.resourcesPath, 'dsh') + return { node, pnpm, dsh } } function developmentProject(): string | undefined { @@ -137,8 +137,8 @@ async function main(): Promise { const activeProject = development ?? paths.profile const hostInspectPort = developmentHostInspectPort(development !== undefined) const manager = new DesktopProjectManager(paths, resources) - if (development === undefined) manager.recover() let host: DesktopHostProcess | undefined + let startupError: string | undefined let mainWindow: BrowserWindow | undefined let pluginWindow: BrowserWindow | undefined let shellInstallerOwnsQuit = false @@ -157,9 +157,15 @@ async function main(): Promise { } const startHost = async (projectDir = activeProject): Promise => { - const next = new DesktopHostProcess(resources.node, projectDir, hostInspectPort) - await next.start() - return next + if (development === undefined) manager.assertProfileRuntime(projectDir) + const next = new DesktopHostProcess(resources.node, development ?? resources.dsh, projectDir, hostInspectPort) + try { + await next.start() + return next + } catch (error) { + await next.stop() + throw error + } } const hooks: DesktopProjectHooks = { healthCheck: async (projectDir) => { @@ -202,14 +208,18 @@ async function main(): Promise { }, } - if (development === undefined) { - await manager.applyRelease(resources.seed, app.getVersion(), { - ...hooks, - beforeActivate: async () => {}, - afterActivate: async () => {}, - }) + const reconcileBackend = async (): Promise => { + try { + if (development === undefined) { + await manager.applyRelease(app.getVersion(), { ...hooks, beforeActivate: async () => {}, afterActivate: async () => {} }) + } + host = await startHost() + startupError = undefined + } catch (error) { + startupError = errorOf(error, messages.startupFailed).message + throw error + } } - host = await startHost() const updates = new DesktopUpdateCoordinator( publishUpdate, @@ -236,7 +246,9 @@ async function main(): Promise { throw new Error('dsh desktop: plugin package changes require a packaged application') } await manager.mutate(mutation, hooks) + startupError = undefined if (mainWindow !== undefined && !mainWindow.isDestroyed()) mainWindow.webContents.reload() + else focusPrimaryWindow() } ipcMain.handle(DESKTOP_IPC.localeGet, (event) => { assertDesktopSender(event, ['shell']) @@ -261,6 +273,20 @@ async function main(): Promise { } return mutate(event, { type: 'plugin-update', name, version }) }) + ipcMain.handle(DESKTOP_IPC.pluginsToggle, (event, name: unknown, enabled: unknown) => { + if (typeof name !== 'string' || typeof enabled !== 'boolean') throw new Error('dsh desktop: invalid plugin activation request') + return mutate(event, { type: 'plugin-toggle', name, enabled }) + }) + ipcMain.handle(DESKTOP_IPC.pluginsDisableAll, event => mutate(event, { type: 'plugins-disable-all' })) + ipcMain.handle(DESKTOP_IPC.backendStatus, (event) => { + assertDesktopSender(event, ['shell']) + return { ready: host !== undefined, ...(startupError === undefined ? {} : { error: startupError }) } + }) + ipcMain.handle(DESKTOP_IPC.backendRetry, async (event) => { + assertDesktopSender(event, ['shell']) + if (host === undefined) await reconcileBackend() + focusPrimaryWindow() + }) ipcMain.handle(DESKTOP_IPC.updatesCheck, async (event) => { assertDesktopSender(event, ['shell']) return updates.check() @@ -348,6 +374,7 @@ async function main(): Promise { return window } focusPrimaryWindow = () => { + if (host === undefined) { openPluginWindow(); return } const window = mainWindow if (window === undefined || window.isDestroyed()) { const replacement = createMainWindow() @@ -359,9 +386,13 @@ async function main(): Promise { window.focus() } - mainWindow = createMainWindow() - await mainWindow.loadURL(`${SCHEME}://app/index.html`) - if (development !== undefined && process.env.DSH_DESKTOP_OPEN_DEVTOOLS !== '0') { + await reconcileBackend().catch(() => undefined) + if (host === undefined) openPluginWindow() + else { + mainWindow = createMainWindow() + await mainWindow.loadURL(`${SCHEME}://app/index.html`) + } + if (mainWindow !== undefined && development !== undefined && process.env.DSH_DESKTOP_OPEN_DEVTOOLS !== '0') { mainWindow.webContents.openDevTools({ mode: 'detach' }) } publishUpdate(updateState) diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 2fc4dc8ee0..4ad4243bdb 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -10,8 +10,14 @@ const api: DshDesktopApi = { list: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsList) as Promise extends Promise ? T : never>, add: spec => ipcRenderer.invoke(DESKTOP_IPC.pluginsAdd, spec) as Promise, remove: name => ipcRenderer.invoke(DESKTOP_IPC.pluginsRemove, name) as Promise, + toggle: (name, enabled) => ipcRenderer.invoke(DESKTOP_IPC.pluginsToggle, name, enabled) as Promise, + disableAll: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsDisableAll) as Promise, update: (name, version) => ipcRenderer.invoke(DESKTOP_IPC.pluginsUpdate, name, version) as Promise, }, + backend: { + status: () => ipcRenderer.invoke(DESKTOP_IPC.backendStatus) as ReturnType, + retry: () => ipcRenderer.invoke(DESKTOP_IPC.backendRetry) as Promise, + }, updates: { check: () => ipcRenderer.invoke(DESKTOP_IPC.updatesCheck) as Promise, install: () => ipcRenderer.invoke(DESKTOP_IPC.updatesInstall) as Promise, diff --git a/apps/desktop/src/profile-packages.ts b/apps/desktop/src/profile-packages.ts new file mode 100644 index 0000000000..6326747b43 --- /dev/null +++ b/apps/desktop/src/profile-packages.ts @@ -0,0 +1,254 @@ +/** Desktop-owned host links and validation of the external plugin dependency graph. */ + +import { createHash } from 'node:crypto' +import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, readdirSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' +import { satisfies } from 'semver' +import { desktopRuntimeId, runtimePath, type DesktopRuntimeDescriptor } from './runtime-tree.ts' + +/** Applied runtime identity and the only links Desktop may replace. */ +export const DESKTOP_PROFILE_STATE = 'desktop-runtime-state.json' + +/** Durable ownership of a package-directory link. */ +export interface DesktopPackageLink { + readonly name: string + readonly target: string +} + +/** Facts from the last successfully validated profile. */ +export interface DesktopProfileState { + readonly schemaVersion: 1 + readonly runtimeId: string + readonly version: string + readonly nodeVersion: string + readonly platform: string + readonly arch: string + readonly lockHash: string + readonly links: readonly DesktopPackageLink[] +} + +const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/u + +function record(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function stat(path: string): ReturnType | undefined { + try { return lstatSync(path) } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + return undefined + } +} + +function inside(root: string, path: string): boolean { + const child = relative(root, path) + return child === '' || (!isAbsolute(child) && child !== '..' && !child.startsWith(`..${sep}`)) +} + +/** + * Read profile state without interpreting an unpublished predecessor format. + * @param profile - Desktop profile directory. + * @returns Validated state, or undefined for an uninitialized profile. + */ +export function readDesktopProfileState(profile: string): DesktopProfileState | undefined { + const path = join(profile, DESKTOP_PROFILE_STATE) + if (!existsSync(path)) return undefined + const value: unknown = JSON.parse(readFileSync(path, 'utf8')) + if (!record(value) || value.schemaVersion !== 1 || typeof value.runtimeId !== 'string' + || !/^[a-f0-9]{64}$/u.test(value.runtimeId) || typeof value.version !== 'string' + || typeof value.nodeVersion !== 'string' || typeof value.platform !== 'string' || typeof value.arch !== 'string' + || typeof value.lockHash !== 'string' || !Array.isArray(value.links)) { + throw new Error('desktop profile: invalid runtime state') + } + const links = value.links.map((link: unknown): DesktopPackageLink => { + if (!record(link) || typeof link.name !== 'string' || !PACKAGE_NAME.test(link.name) + || typeof link.target !== 'string' || !isAbsolute(link.target)) { + throw new Error('desktop profile: invalid managed link') + } + return { name: link.name, target: link.target } + }) + if (new Set(links.map(link => link.name)).size !== links.length) throw new Error('desktop profile: duplicate managed link') + return { schemaVersion: 1, runtimeId: value.runtimeId, version: value.version, nodeVersion: value.nodeVersion, + platform: value.platform, arch: value.arch, lockHash: value.lockHash, links } +} + +/** + * Hash the plugin lockfile, including the empty-profile case. + * @param profile - Desktop profile directory. + * @returns Lockfile content identity. + */ +export function desktopPluginLockHash(profile: string): string { + const lock = join(profile, 'pnpm-lock.yaml') + return createHash('sha256').update(existsSync(lock) ? readFileSync(lock) : '').digest('hex') +} + +/** + * Remove only recorded host links, without following even broken targets. + * @param profile - Active or copied profile. + */ +export function unlinkDesktopHostPackages(profile: string): void { + for (const link of readDesktopProfileState(profile)?.links ?? []) { + const path = join(profile, 'node_modules', link.name) + const entry = stat(path) + if (entry === undefined) continue + if (!entry.isSymbolicLink() || resolve(dirname(path), readlinkSync(path)) !== resolve(link.target)) { + throw new Error(`desktop profile: refusing to replace unowned package ${link.name}`) + } + unlinkSync(path) + } +} + +/** + * Copy plugin files without copying host packages or sharing writable hardlinks. + * @param source - Active Desktop profile. + * @param target - Empty transaction profile directory. + */ +export function copyDesktopProfile(source: string, target: string): void { + const owned = readDesktopProfileState(source)?.links ?? [] + for (const link of owned) { + const path = join(source, 'node_modules', link.name) + const entry = stat(path) + if (entry !== undefined && (!entry.isSymbolicLink() || resolve(dirname(path), readlinkSync(path)) !== resolve(link.target))) { + throw new Error(`desktop profile: refusing to copy unowned package ${link.name}`) + } + } + const links = new Set(owned.map(link => join(source, 'node_modules', link.name))) + cpSync(source, target, { recursive: true, verbatimSymlinks: true, force: false, errorOnExist: true, + filter: path => !links.has(path) }) +} + +/** + * Bind an external profile to this application's real package directories. + * @param profile - Candidate profile. + * @param root - Current immutable runtime directory. + * @param runtime - Verified release descriptor. + */ +export function linkDesktopHostPackages(profile: string, root: string, runtime: DesktopRuntimeDescriptor): void { + unlinkDesktopHostPackages(profile) + const links = runtime.sharedPackages.map(entry => ({ name: entry.name, target: runtimePath(root, entry.path) })) + for (const link of links) { + const path = join(profile, 'node_modules', link.name) + if (stat(path) !== undefined) throw new Error(`desktop profile: plugin installed reserved host package ${link.name}`) + mkdirSync(dirname(path), { recursive: true }) + symlinkSync(link.target, path, process.platform === 'win32' ? 'junction' : 'dir') + } + const state: DesktopProfileState = { schemaVersion: 1, runtimeId: desktopRuntimeId(runtime), version: runtime.release.version, + nodeVersion: runtime.release.nodeVersion, platform: runtime.platform, arch: runtime.arch, + lockHash: desktopPluginLockHash(profile), links } + writeFileSync(join(profile, DESKTOP_PROFILE_STATE), `${JSON.stringify(state, undefined, 2)}\n`, { mode: 0o600 }) +} + +interface PackageManifest { + readonly name: string + readonly version: string + readonly dependencies: Readonly> + readonly optionalDependencies: Readonly> + readonly peerDependencies: Readonly> + readonly optionalPeers: ReadonlySet +} + +function manifest(path: string): PackageManifest { + const value: unknown = JSON.parse(readFileSync(join(path, 'package.json'), 'utf8')) + if (!record(value) || typeof value.name !== 'string' || typeof value.version !== 'string') { + throw new Error(`desktop profile: invalid package manifest ${path}`) + } + const dependencies = (key: string): Record => { + const field = value[key] + if (field === undefined) return {} + if (!record(field) || Object.entries(field).some(([name, spec]) => !PACKAGE_NAME.test(name) || typeof spec !== 'string')) { + throw new Error(`desktop profile: invalid ${key} in ${path}`) + } + return field as Record + } + const optionalPeers = new Set() + if (record(value.peerDependenciesMeta)) { + for (const [name, meta] of Object.entries(value.peerDependenciesMeta)) { + if (record(meta) && meta.optional === true) optionalPeers.add(name) + } + } + return { name: value.name, version: value.version, dependencies: dependencies('dependencies'), + optionalDependencies: dependencies('optionalDependencies'), peerDependencies: dependencies('peerDependencies'), optionalPeers } +} + +function packageFrom(anchor: string, name: string): string | undefined { + if (!PACKAGE_NAME.test(name)) throw new Error(`desktop profile: invalid package name ${name}`) + for (const modules of createRequire(join(anchor, 'package.json')).resolve.paths(name) ?? []) { + const path = join(modules, name) + if (existsSync(join(path, 'package.json'))) return realpathSync(path) + } + return undefined +} + +/** + * Prove active plugin dependencies stay local and share the host's exact package instances. + * @param profile - Profile with its generated host links present. + * @param root - Immutable runtime directory. + * @param runtime - Verified shared package inventory. + * @param activePlugins - Explicit enabled plugin roots whose peer compatibility is required. + */ +export function validateDesktopPluginGraph( + profile: string, root: string, runtime: DesktopRuntimeDescriptor, activePlugins: readonly string[], +): void { + const profileRoot = realpathSync(profile) + const shared = new Map(runtime.sharedPackages.map(entry => [entry.name, realpathSync(runtimePath(root, entry.path))])) + for (const [name, path] of shared) { + if (packageFrom(profile, name) !== path) throw new Error(`desktop profile: missing or incorrect host link ${name}`) + } + const scanned = new Set() + const scan = (modules: string): void => { + if (!existsSync(modules)) return + if (lstatSync(modules).isSymbolicLink()) throw new Error(`desktop profile: linked package container ${modules}`) + const directory = realpathSync(modules) + if (scanned.has(directory)) return + scanned.add(directory) + for (const entry of readdirSync(modules, { withFileTypes: true })) { + if (entry.name.startsWith('.')) continue + const path = join(modules, entry.name) + if (entry.name.startsWith('@')) { scan(path); continue } + if (!existsSync(join(path, 'package.json'))) throw new Error(`desktop profile: invalid installed package ${path}`) + const canonical = realpathSync(path) + const info = manifest(canonical) + const host = shared.get(info.name) + if (host !== undefined) { + if (canonical !== host || path !== join(profile, 'node_modules', info.name)) { + throw new Error(`desktop profile: duplicate or aliased host package ${info.name} at ${path}`) + } + continue + } + if (entry.isSymbolicLink()) throw new Error(`desktop profile: linked private package ${path}`) + if (!inside(profileRoot, canonical)) throw new Error(`desktop profile: package resolves outside profile: ${path}`) + scan(join(path, 'node_modules')) + } + } + scan(join(profile, 'node_modules')) + const visited = new Set() + const visit = (path: string, chain: string): void => { + if (visited.has(path)) return + visited.add(path) + const info = manifest(path) + const deps = { ...info.dependencies, ...info.optionalDependencies } + for (const [name, range] of Object.entries({ ...deps, ...info.peerDependencies })) { + const peer = name in info.peerDependencies + const optional = peer ? info.optionalPeers.has(name) : name in info.optionalDependencies + const target = packageFrom(path, name) + if (target === undefined && optional) continue + if (target === undefined) throw new Error(`desktop profile: ${chain} requires missing ${name}@${range}`) + const host = shared.get(name) + if (host !== undefined && name in deps) throw new Error(`desktop profile: ${chain} must declare ${name} as a peer dependency`) + if (host !== undefined ? target !== host : !inside(profileRoot, target)) { + throw new Error(`desktop profile: ${chain} resolves ${name} outside its owned packages`) + } + const dependency = manifest(target) + if (peer && !satisfies(dependency.version, range)) { + throw new Error(`desktop profile: ${chain} requires ${name}@${range}, found ${dependency.version}`) + } + if (host === undefined) visit(target, `${chain} -> ${name}`) + } + } + for (const name of activePlugins) { + const path = packageFrom(profile, name) + if (path === undefined || !inside(profileRoot, path)) throw new Error(`desktop profile: missing local plugin ${name}`) + visit(path, name) + } +} diff --git a/apps/desktop/src/project-manager.ts b/apps/desktop/src/project-manager.ts index b9b94f7ac8..89c9e86c73 100644 --- a/apps/desktop/src/project-manager.ts +++ b/apps/desktop/src/project-manager.ts @@ -1,11 +1,9 @@ /** Transactional owner of the reserved desktop profile and its private pnpm state. */ +import { valid } from 'semver' import { spawn } from 'node:child_process' -import { createHash, randomUUID } from 'node:crypto' +import { randomUUID } from 'node:crypto' import { - constants, - copyFileSync, - cpSync, existsSync, fsyncSync, ftruncateSync, @@ -13,7 +11,6 @@ import { mkdirSync, openSync, closeSync, - readdirSync, readFileSync, renameSync, rmSync, @@ -23,31 +20,23 @@ import { } from 'node:fs' import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { - DESKTOP_PACKAGES_DIR, - DESKTOP_PACKAGE_SET_FILE, DESKTOP_HOST_PACKAGE, desktopCorePackageOverrides, - desktopDshPackageSpec, - readDesktopCorePackageSet, verifyDesktopCorePackageSet, } from './core-package-set.ts' import type { DesktopPaths } from './paths.ts' -import { parseDesktopRelease, type DesktopRelease } from './release.ts' -import { extractPnpmStoreArchives, mergePnpmStore } from './seed-store.ts' - -/** Files the package transaction copies between active and staging projects. */ -const DESKTOP_PROJECT_FILES = [ - 'package.json', - 'pnpm-lock.yaml', - 'pnpm-workspace.yaml', - 'desktop-release.json', - DESKTOP_PACKAGE_SET_FILE, -] as const +import type { DesktopRelease } from './release.ts' +import { desktopRuntimeId, verifyDesktopRuntime, type DesktopRuntimeDescriptor } from './runtime-tree.ts' +import { + copyDesktopProfile, desktopPluginLockHash, linkDesktopHostPackages, readDesktopProfileState, + unlinkDesktopHostPackages, validateDesktopPluginGraph, type DesktopProfileState, +} from './profile-packages.ts' /** Desktop plugin record derived from the installed profile. */ export interface DesktopPluginRecord { readonly name: string readonly version: string + readonly enabled: boolean } /** Installed desktop project manifest slice. */ @@ -68,6 +57,8 @@ interface DesktopPendingTransaction { readonly schemaVersion: 1 readonly id: string readonly stagingProfile: string + readonly fromRuntimeId: string | null + readonly toRuntimeId: string readonly step: 'prepared' | 'active-moved' | 'staging-activated' } @@ -75,6 +66,7 @@ interface DesktopPendingTransaction { export interface DesktopRuntimeExecutables { readonly node: string readonly pnpm: string + readonly dsh: string } /** Hooks that bind project replacement to backend lifecycle and health. */ @@ -92,12 +84,8 @@ export type DesktopProjectMutation = | { readonly type: 'plugin-add'; readonly spec: string } | { readonly type: 'plugin-remove'; readonly name: string } | { readonly type: 'plugin-update'; readonly name: string; readonly version: string } - -interface DesktopSeedIntegrityRecord { - readonly path: string - readonly bytes: number - readonly sha256: string -} + | { readonly type: 'plugin-toggle'; readonly name: string; readonly enabled: boolean } + | { readonly type: 'plugins-disable-all' } const PROJECT_NAME = '@deepseek-ai/dsh-desktop-runtime' const DSH_PACKAGE = '@deepseek-ai/dsh' @@ -133,10 +121,6 @@ function workspaceFile(overrides: Readonly> = {}): string return `packages:\n - .\n\n${overrideSection}${WORKSPACE_SETTINGS}allowBuilds:\n node-pty: true\n koffi: true\n fs-ext: true\n ${JSON.stringify(coreBuildKey)}: true\n '@google/genai': false\n protobufjs: false\n node-addon-require-builtin: false\n` } -function releaseFile(projectDir: string): DesktopRelease { - return parseDesktopRelease(readJson(join(projectDir, 'desktop-release.json'))) -} - function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null } @@ -190,83 +174,20 @@ function removeOwnedDirectory(path: string): void { rmSync(path, { recursive: true }) } -function copyMetadata(source: string, target: string): void { - mkdirSync(target, { recursive: true, mode: 0o700 }) - for (const filename of DESKTOP_PROJECT_FILES) { - const from = join(source, filename) - if (existsSync(from)) copyFileSync(from, join(target, filename), constants.COPYFILE_EXCL) - } - cpSync(join(source, DESKTOP_PACKAGES_DIR), join(target, DESKTOP_PACKAGES_DIR), { - recursive: true, - force: false, - errorOnExist: true, - }) -} - -function seedFiles(root: string): readonly DesktopSeedIntegrityRecord[] { - const files: DesktopSeedIntegrityRecord[] = [] - const visit = (directory: string): void => { - for (const entry of readdirSync(directory, { withFileTypes: true })) { - const path = join(directory, entry.name) - const relativePath = path.slice(root.length + 1).split(sep).join('/') - if (relativePath === 'integrity.json') continue - if (entry.isSymbolicLink()) throw new Error(`desktop seed: symbolic link is not allowed: ${relativePath}`) - if (entry.isDirectory()) { - visit(path) - continue - } - if (!entry.isFile()) throw new Error(`desktop seed: unsupported file type: ${relativePath}`) - const body = readFileSync(path) - files.push({ - path: relativePath, - bytes: body.byteLength, - sha256: createHash('sha256').update(body).digest('hex'), - }) - } - } - visit(root) - return files.sort((left, right) => left.path.localeCompare(right.path)) -} - -/** Verify the packaged offline seed before any content enters writable desktop state. */ -export function verifySeedIntegrity(seedDir: string): void { - const integrityPath = join(seedDir, 'integrity.json') - const integrity = readJson(integrityPath) - if (!isRecord(integrity) || integrity.schemaVersion !== 2 || !Array.isArray(integrity.files)) { - throw new Error(`desktop seed: invalid integrity inventory ${integrityPath}`) - } - const expected: DesktopSeedIntegrityRecord[] = integrity.files.map((record) => { - if (!isRecord(record) || typeof record.path !== 'string' || record.path === '' || record.path.startsWith('/') - || record.path.split('/').includes('..') || typeof record.bytes !== 'number' - || !Number.isSafeInteger(record.bytes) || record.bytes < 0 - || typeof record.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(record.sha256)) { - throw new Error(`desktop seed: invalid integrity record in ${integrityPath}`) - } - return { path: record.path, bytes: record.bytes, sha256: record.sha256 } - }).sort((left, right) => left.path.localeCompare(right.path)) - const actual = seedFiles(seedDir) - if (JSON.stringify(actual) !== JSON.stringify(expected)) { - throw new Error('desktop seed: integrity verification failed') - } -} - function projectManifest(projectDir: string): DesktopProjectManifest { const path = join(projectDir, 'package.json') const value = readJson(path) const dsh = isRecord(value) && isRecord(value.dsh) ? value.dsh : undefined const profile = isRecord(dsh?.profile) ? dsh.profile : undefined if (!isRecord(value) || value.name !== PROJECT_NAME || value.private !== true - || typeof value.version !== 'string' || !isRecord(value.dependencies) + || typeof value.version !== 'string' || (value.dependencies !== undefined && !isRecord(value.dependencies)) || !Array.isArray(profile?.bundles) || !profile.bundles.every(bundle => typeof bundle === 'string')) { throw new Error(`desktop project: invalid desktop profile manifest ${path}`) } - const manifest = value as unknown as DesktopProjectManifest - const packageSet = readDesktopCorePackageSet(projectDir, releaseFile(projectDir).version) - const expectedOverrides = desktopCorePackageOverrides(packageSet) - if (manifest.dependencies[DSH_PACKAGE] !== desktopDshPackageSpec(packageSet) - || Object.entries(expectedOverrides).some(([name, spec]) => manifest.dependencies[name] !== spec) - || readFileSync(join(projectDir, 'pnpm-workspace.yaml'), 'utf8') !== workspaceFile(expectedOverrides)) { - throw new Error(`desktop project: core package mapping does not match ${DESKTOP_PACKAGE_SET_FILE}`) + const manifest = { ...value, dependencies: value.dependencies ?? {} } as unknown as DesktopProjectManifest + if (Object.entries(manifest.dependencies).some(([name, version]) => !PACKAGE_NAME_PATTERN.test(name) + || typeof version !== 'string' || valid(version) !== version)) { + throw new Error('desktop project: plugin dependencies must use exact registry versions') } return manifest } @@ -285,7 +206,7 @@ function profilePluginNames(projectDir: string): readonly string[] { } function pluginRecords(projectDir: string): readonly DesktopPluginRecord[] { - return profilePluginNames(projectDir).map(name => inspectPlugin(projectDir, name)) + return Object.keys(projectManifest(projectDir).dependencies).sort().map(name => inspectPlugin(projectDir, name)) } function writeProfilePlugins(projectDir: string, plugins: readonly DesktopPluginRecord[]): void { @@ -296,7 +217,7 @@ function writeProfilePlugins(projectDir: string, plugins: readonly DesktopPlugin ...manifest.dsh, profile: { ...manifest.dsh.profile, - bundles: [...DESKTOP_PROFILE_BUNDLES, ...plugins.map(plugin => plugin.name)], + bundles: [...DESKTOP_PROFILE_BUNDLES, ...plugins.filter(plugin => plugin.enabled).map(plugin => plugin.name)], }, }, } satisfies DesktopProjectManifest) @@ -322,12 +243,13 @@ function inspectPlugin(projectDir: string, requestedName: string): DesktopPlugin if ((patchPath !== packageDir && !patchPath.startsWith(packageDir + sep)) || !existsSync(patchPath)) { throw new Error(`desktop project: ${requestedName}@${manifest.version} declares an invalid bundle patch`) } - return { name: requestedName, version: manifest.version } + return { name: requestedName, version: manifest.version, enabled: profilePluginNames(projectDir).includes(requestedName) } } /** Transactional desktop npm project manager. */ export class DesktopProjectManager { private lockDescriptor: number | undefined + private descriptor: DesktopRuntimeDescriptor | undefined /** * @param paths - Electron-owned package state and reserved desktop profile paths. @@ -345,6 +267,9 @@ export class DesktopProjectManager { if (!isRecord(value) || value.schemaVersion !== 1 || typeof value.id !== 'string' || typeof value.stagingProfile !== 'string' || !isDescendant(this.paths.staging, value.stagingProfile) + || value.stagingProfile !== join(this.paths.staging, value.id, 'profile') + || (value.fromRuntimeId !== null && (typeof value.fromRuntimeId !== 'string' || !/^[a-f0-9]{64}$/u.test(value.fromRuntimeId))) + || typeof value.toRuntimeId !== 'string' || !/^[a-f0-9]{64}$/u.test(value.toRuntimeId) || (value.step !== 'prepared' && value.step !== 'active-moved' && value.step !== 'staging-activated')) { throw new Error(`desktop project: invalid activation journal ${this.paths.pending}`) } @@ -352,9 +277,20 @@ export class DesktopProjectManager { schemaVersion: 1, id: value.id, stagingProfile: value.stagingProfile, + fromRuntimeId: value.fromRuntimeId, + toRuntimeId: value.toRuntimeId, step: value.step, } - if (!existsSync(this.paths.profile) && existsSync(this.paths.rollback)) { + if (pending.step === 'staging-activated' && !existsSync(pending.stagingProfile) && existsSync(this.paths.profile)) { + if (readDesktopProfileState(this.paths.profile)?.runtimeId !== pending.toRuntimeId) { + throw new Error('desktop project: activated profile does not match its journal') + } + removeOwnedDirectory(this.paths.profile) + } + if (!existsSync(this.paths.profile) && pending.fromRuntimeId !== null && existsSync(this.paths.rollback)) { + if (readDesktopProfileState(this.paths.rollback)?.runtimeId !== pending.fromRuntimeId) { + throw new Error('desktop project: rollback profile does not match its journal') + } mkdirSync(dirname(this.paths.profile), { recursive: true }) renameSync(this.paths.rollback, this.paths.profile) } @@ -368,64 +304,59 @@ export class DesktopProjectManager { return pluginRecords(this.paths.profile) } - /** Read the exact dsh version installed in the active desktop project. */ + /** Read the dsh version supplied by this application's verified resources. */ dshVersion(): string { - if (!existsSync(this.paths.profile)) throw new Error('desktop project: active profile is not installed') - return this.installedPackageVersion(DSH_PACKAGE) + return this.currentRuntime().release.version } - private installedPackageVersion(packageName: string): string { - const manifestPath = join(this.paths.profile, 'node_modules', ...packageName.split('/'), 'package.json') - const manifest = readJson(manifestPath) - if (!isRecord(manifest) || typeof manifest.version !== 'string') { - throw new Error(`desktop project: installed ${packageName} package has no version`) - } - assertVersion(manifest.version) - return manifest.version - } - - /** Read the release version applied to the active desktop project. */ + /** Read the release most recently applied to the active profile. */ releaseVersion(): string { - if (!existsSync(this.paths.profile)) throw new Error('desktop project: active profile is not installed') - return releaseFile(this.paths.profile).version + const state = readDesktopProfileState(this.paths.profile) + if (state === undefined) throw new Error('desktop project: active profile has no runtime state') + return state.version } - /** Install or reconcile the active project to the Electron package's exact release. */ - async applyRelease(seedDir: string, electronVersion: string, hooks: DesktopProjectHooks): Promise { + /** Reject a profile whose dependency links were prepared for another runtime. */ + assertProfileRuntime(projectDir: string): void { + if (readDesktopProfileState(projectDir)?.runtimeId !== desktopRuntimeId(this.currentRuntime())) { + throw new Error('desktop project: profile does not match this application runtime') + } + } + + private currentRuntime(): DesktopRuntimeDescriptor { + if (this.descriptor === undefined) throw new Error('desktop project: runtime has not been verified') + return this.descriptor + } + + private prepareProfile(projectDir: string): void { + const runtime = this.currentRuntime() + linkDesktopHostPackages(projectDir, this.runtime.dsh, runtime) + validateDesktopPluginGraph(projectDir, this.runtime.dsh, runtime, profilePluginNames(projectDir)) + } + + /** Verify this release and reconcile its external profile without installing core packages. */ + async applyRelease(electronVersion: string, hooks: DesktopProjectHooks): Promise { return this.withLock(async () => { this.recover() - verifySeedIntegrity(seedDir) - const target = releaseFile(seedDir) - verifyDesktopCorePackageSet(seedDir, target.version) - if (target.version !== electronVersion) { - throw new Error(`desktop project: seed ${target.version} does not match Electron ${electronVersion}`) + const target = verifyDesktopRuntime(this.runtime.dsh, electronVersion) + this.descriptor = target + const previous = readDesktopProfileState(this.paths.profile) + if (existsSync(this.paths.profile) && previous === undefined) { + throw new Error('desktop project: existing profile is not a Desktop plugin profile') } - if (existsSync(this.paths.profile) && this.releaseVersion() === target.version - && this.dshVersion() === target.version - && this.installedPackageVersion(DESKTOP_HOST_PACKAGE) === target.version) { - verifyDesktopCorePackageSet(this.paths.profile, target.version) + if (previous?.runtimeId === desktopRuntimeId(target) + && previous.lockHash === desktopPluginLockHash(this.paths.profile) + && previous.links.length === target.sharedPackages.length + && previous.links.every(link => link.target === join(this.runtime.dsh, 'node_modules', link.name) + && existsSync(join(this.paths.profile, 'node_modules', link.name)))) { + validateDesktopPluginGraph(this.paths.profile, this.runtime.dsh, target, profilePluginNames(this.paths.profile)) return false } - this.mergeSeedPnpmState(seedDir) const stagingProfile = this.newStagingProfile() try { - if (existsSync(this.paths.profile)) { - const plugins = pluginRecords(this.paths.profile) - copyMetadata(seedDir, stagingProfile) - await this.runPnpm(stagingProfile, ['install', '--offline', '--frozen-lockfile', '--trust-lockfile']) - if (plugins.length > 0) { - await this.runPnpm(stagingProfile, [ - 'add', - ...plugins.map(plugin => `${plugin.name}@${plugin.version}`), - '--save-exact', - '--offline', - ]) - writeProfilePlugins(stagingProfile, plugins) - } - } else { - copyMetadata(seedDir, stagingProfile) - await this.runPnpm(stagingProfile, ['install', '--offline', '--frozen-lockfile', '--trust-lockfile']) - } + if (previous === undefined) createPluginProfile(stagingProfile) + else copyDesktopProfile(this.paths.profile, stagingProfile) + await this.reconcileProfile(stagingProfile, previous) await hooks.healthCheck(stagingProfile) await this.activate(stagingProfile, hooks) return true @@ -436,16 +367,18 @@ export class DesktopProjectManager { }) } - /** Apply one exact dependency mutation through a staging project. */ + /** Apply an exact plugin dependency or activation change through a staging project. */ async mutate(mutation: DesktopProjectMutation, hooks: DesktopProjectHooks): Promise { await this.withLock(async () => { this.recover() + this.currentRuntime() if (!existsSync(this.paths.profile)) throw new Error('desktop project: active profile is not installed') - verifyDesktopCorePackageSet(this.paths.profile, this.releaseVersion()) const stagingProfile = this.newStagingProfile() try { - copyMetadata(this.paths.profile, stagingProfile) + copyDesktopProfile(this.paths.profile, stagingProfile) await this.applyMutation(stagingProfile, mutation) + await this.reconcileProfile(stagingProfile, readDesktopProfileState(stagingProfile), + mutation.type !== 'plugin-toggle' && mutation.type !== 'plugins-disable-all') await hooks.healthCheck(stagingProfile) await this.activate(stagingProfile, hooks) } catch (error) { @@ -455,6 +388,25 @@ export class DesktopProjectManager { }) } + private async reconcileProfile(projectDir: string, previous: DesktopProfileState | undefined, packagesChanged = false): Promise { + const target = this.currentRuntime() + this.prepareProfile(projectDir) + const rebuild = previous !== undefined && pluginRecords(projectDir).length > 0 + && (previous.nodeVersion !== target.release.nodeVersion || previous.platform !== target.platform || previous.arch !== target.arch) + if (rebuild) { + unlinkDesktopHostPackages(projectDir) + removeOwnedDirectory(join(projectDir, 'node_modules')) + await this.runPnpm(projectDir, ['install', '--frozen-lockfile', '--ignore-scripts']) + } + if (rebuild || packagesChanged) await this.finishPackageOperation(projectDir) + } + + private async finishPackageOperation(projectDir: string): Promise { + this.prepareProfile(projectDir) + await this.runPnpm(projectDir, ['rebuild', '--pending']) + this.prepareProfile(projectDir) + } + private newStagingProfile(): string { const path = join(this.paths.staging, randomUUID(), 'profile') mkdirSync(path, { recursive: true, mode: 0o700 }) @@ -466,8 +418,11 @@ export class DesktopProjectManager { case 'plugin-add': { const requestedName = packageNameFromSpec(mutation.spec) if (requestedName === undefined) throw new Error('desktop project: plugin package name is required') - await this.runPnpm(projectDir, ['add', mutation.spec, '--save-exact']) - const installed = inspectPlugin(projectDir, requestedName) + if (this.currentRuntime().sharedPackages.some(entry => entry.name === requestedName)) { + throw new Error(`desktop project: cannot install host-owned package ${requestedName}`) + } + await this.runPnpm(projectDir, ['add', mutation.spec, '--save-exact', '--ignore-scripts']) + const installed = { ...inspectPlugin(projectDir, requestedName), enabled: true } const current = pluginRecords(projectDir).filter(plugin => plugin.name !== installed.name) writeProfilePlugins( projectDir, @@ -477,21 +432,21 @@ export class DesktopProjectManager { } case 'plugin-remove': { assertPackageName(mutation.name) - if (!profilePluginNames(projectDir).includes(mutation.name)) { + if (!Object.hasOwn(projectManifest(projectDir).dependencies, mutation.name)) { throw new Error(`desktop project: plugin ${JSON.stringify(mutation.name)} is not installed`) } const remaining = pluginRecords(projectDir).filter(plugin => plugin.name !== mutation.name) - await this.runPnpm(projectDir, ['remove', mutation.name]) + await this.runPnpm(projectDir, ['remove', mutation.name, '--config.ignore-scripts=true']) writeProfilePlugins(projectDir, remaining) return } case 'plugin-update': assertPackageName(mutation.name) assertVersion(mutation.version) - if (!profilePluginNames(projectDir).includes(mutation.name)) { + if (!Object.hasOwn(projectManifest(projectDir).dependencies, mutation.name)) { throw new Error(`desktop project: plugin ${JSON.stringify(mutation.name)} is not installed`) } - await this.runPnpm(projectDir, ['add', `${mutation.name}@${mutation.version}`, '--save-exact']) + await this.runPnpm(projectDir, ['add', `${mutation.name}@${mutation.version}`, '--save-exact', '--ignore-scripts']) { const installed = inspectPlugin(projectDir, mutation.name) writeProfilePlugins( @@ -500,33 +455,37 @@ export class DesktopProjectManager { ) } return + case 'plugins-disable-all': + writeProfilePlugins(projectDir, pluginRecords(projectDir).map(plugin => ({ ...plugin, enabled: false }))) + return + case 'plugin-toggle': { + assertPackageName(mutation.name) + const plugins = pluginRecords(projectDir) + if (!plugins.some(plugin => plugin.name === mutation.name)) throw new Error(`desktop project: plugin ${mutation.name} is not installed`) + writeProfilePlugins(projectDir, plugins.map(plugin => ( + plugin.name === mutation.name ? { ...plugin, enabled: mutation.enabled } : plugin + ))) + return + } default: mutation satisfies never } } - private mergeSeedPnpmState(seedDir: string): void { - const transactionRoot = join(this.paths.staging, randomUUID()) - const extractedStore = join(transactionRoot, 'store') - try { - extractPnpmStoreArchives(seedDir, extractedStore) - mergePnpmStore(extractedStore, this.paths.pnpm.store) - } finally { - removeOwnedDirectory(transactionRoot) - } - } - private async activate(stagingProfile: string, hooks: DesktopProjectHooks): Promise { const pending: DesktopPendingTransaction = { schemaVersion: 1, id: basename(dirname(stagingProfile)), stagingProfile, + fromRuntimeId: readDesktopProfileState(this.paths.profile)?.runtimeId ?? null, + toRuntimeId: desktopRuntimeId(this.currentRuntime()), step: 'prepared', } writeJson(this.paths.pending, pending) - await hooks.beforeActivate() let activeMoved = false + let stagingActivated = false try { + await hooks.beforeActivate() removeOwnedDirectory(this.paths.rollback) mkdirSync(dirname(this.paths.rollback), { recursive: true, mode: 0o700 }) writeJson(this.paths.pending, { ...pending, step: 'active-moved' } satisfies DesktopPendingTransaction) @@ -537,10 +496,11 @@ export class DesktopProjectManager { mkdirSync(dirname(this.paths.profile), { recursive: true, mode: 0o700 }) writeJson(this.paths.pending, { ...pending, step: 'staging-activated' } satisfies DesktopPendingTransaction) renameSync(stagingProfile, this.paths.profile) + stagingActivated = true await hooks.afterActivate() unlinkSync(this.paths.pending) } catch (error) { - if (existsSync(this.paths.profile)) removeOwnedDirectory(this.paths.profile) + if (stagingActivated) removeOwnedDirectory(this.paths.profile) if (activeMoved && existsSync(this.paths.rollback)) renameSync(this.paths.rollback, this.paths.profile) if (existsSync(this.paths.pending)) unlinkSync(this.paths.pending) await hooks.afterActivate().catch(() => undefined) @@ -558,7 +518,7 @@ export class DesktopProjectManager { const npmrc = join(this.paths.pnpm.config, 'npmrc') if (!existsSync(npmrc)) writeFileSync(npmrc, '', { mode: 0o600 }) const inherited = Object.fromEntries(Object.entries(process.env).filter(([name]) => ( - !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name) + name !== 'NODE_OPTIONS' && name !== 'NODE_PATH' && !/^DSH_DESKTOP_/u.test(name) && !/^(?:npm|pnpm|corepack)_/iu.test(name) ))) await new Promise((settle, reject) => { const child = spawn(this.runtime.node, [ @@ -585,19 +545,7 @@ export class DesktopProjectManager { }, stdio: ['ignore', 'pipe', 'pipe'], }) - const childPid = child.pid - if (childPid === undefined) { - child.kill('SIGKILL') - reject(new Error('desktop project: pnpm did not report a process id')) - return - } - try { - this.writeLockOwner(childPid) - } catch (error) { - child.kill('SIGKILL') - reject(errorOf(error, 'desktop project: failed to assign the package transaction lock to pnpm')) - return - } + let failure: Error | undefined let diagnostics = '' let completed = false const appendDiagnostics = (chunk: string): void => { @@ -618,9 +566,10 @@ export class DesktopProjectManager { } settleChild() } - child.once('error', (error) => { complete(() => { reject(error) }) }) + child.once('error', (error) => { failure = error }) child.once('close', (code, signal) => { complete(() => { + if (failure !== undefined) { reject(failure); return } if (code === 0) { settle() return @@ -630,6 +579,13 @@ export class DesktopProjectManager { )) }) }) + try { + if (child.pid === undefined) throw new Error('desktop project: pnpm did not report a process id') + this.writeLockOwner(child.pid) + } catch (error) { + failure = errorOf(error, 'desktop project: failed to assign the package transaction lock to pnpm') + child.kill('SIGKILL') + } }) } @@ -682,10 +638,10 @@ export class DesktopProjectManager { } } -/** Create seed metadata for one exact Electron and dsh release. */ -export function createSeedMetadata(seedDir: string, release: DesktopRelease): void { - mkdirSync(seedDir, { recursive: true, mode: 0o700 }) - const packageSet = verifyDesktopCorePackageSet(seedDir, release.version) +/** Create build-only project metadata for materializing the signed runtime. */ +export function createRuntimeProjectMetadata(projectDir: string, release: DesktopRelease): void { + mkdirSync(projectDir, { recursive: true, mode: 0o700 }) + const packageSet = verifyDesktopCorePackageSet(projectDir, release.version) const manifest: DesktopProjectManifest = { name: PROJECT_NAME, private: true, @@ -693,13 +649,13 @@ export function createSeedMetadata(seedDir: string, release: DesktopRelease): vo dependencies: desktopCorePackageOverrides(packageSet), dsh: { profile: { bundles: [...DESKTOP_PROFILE_BUNDLES] } }, } - writeJson(join(seedDir, 'package.json'), manifest) + writeJson(join(projectDir, 'package.json'), manifest) writeFileSync( - join(seedDir, 'pnpm-workspace.yaml'), + join(projectDir, 'pnpm-workspace.yaml'), workspaceFile(desktopCorePackageOverrides(packageSet)), { mode: 0o600 }, ) - writeJson(join(seedDir, 'desktop-release.json'), release) + writeJson(join(projectDir, 'desktop-release.json'), release) } /** @@ -723,3 +679,13 @@ export function createDevelopmentProjectMetadata(projectDir: string, release: De writeFileSync(join(projectDir, 'pnpm-workspace.yaml'), workspaceFile(), { mode: 0o600 }) writeJson(join(projectDir, 'desktop-release.json'), release) } + +/** Create the first external plugin profile without running a package manager. */ +export function createPluginProfile(projectDir: string): void { + mkdirSync(projectDir, { recursive: true, mode: 0o700 }) + writeJson(join(projectDir, 'package.json'), { + name: PROJECT_NAME, private: true, version: '0.0.0', dependencies: {}, + dsh: { profile: { bundles: [...DESKTOP_PROFILE_BUNDLES] } }, + } satisfies DesktopProjectManifest) + writeFileSync(join(projectDir, 'pnpm-workspace.yaml'), workspaceFile(), { mode: 0o600 }) +} diff --git a/apps/desktop/src/release.ts b/apps/desktop/src/release.ts index f78d922e8c..88050120e5 100644 --- a/apps/desktop/src/release.ts +++ b/apps/desktop/src/release.ts @@ -1,9 +1,9 @@ -/** Immutable version identity shared by one Electron shell and its dsh seed. */ +/** Immutable version identity shared by one Electron shell and its bundled dsh runtime. */ import { valid } from 'semver' import { DESKTOP_HOST_PROTOCOL_VERSION } from './host-protocol.ts' -/** Release facts embedded in the seed and copied into the active desktop project. */ +/** Release facts embedded in the bundled runtime descriptor. */ export interface DesktopRelease { readonly schemaVersion: 1 /** Exact version used by both Electron and `@deepseek-ai/dsh`. */ diff --git a/apps/desktop/src/runtime-tree.ts b/apps/desktop/src/runtime-tree.ts new file mode 100644 index 0000000000..471d603964 --- /dev/null +++ b/apps/desktop/src/runtime-tree.ts @@ -0,0 +1,180 @@ +/** Relocatable, integrity-recorded production packages carried by one Desktop release. */ + +import { createHash } from 'node:crypto' +import { lstatSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' +import { isAbsolute, join, relative, sep } from 'node:path' +import { valid } from 'semver' +import { DESKTOP_HOST_PACKAGE, DESKTOP_HOST_RUNTIME_FILES } from './core-package-set.ts' +import { parseDesktopRelease, type DesktopRelease } from './release.ts' + +/** Descriptor at the root of the immutable Desktop resource tree. */ +export const DESKTOP_RUNTIME_FILE = 'desktop-runtime.json' + +/** Host-owned package available to external plugins through a directory link. */ +export interface DesktopSharedPackage { + readonly name: string + readonly version: string + readonly path: string +} + +/** Final bytes and executable permissions of a runtime file. */ +export interface DesktopRuntimeFile { + readonly path: string + readonly bytes: number + readonly sha256: string + readonly executable: boolean +} + +/** One signed application's production dependency tree. */ +export interface DesktopRuntimeDescriptor { + readonly schemaVersion: 1 + readonly release: DesktopRelease + readonly platform: NodeJS.Platform + readonly arch: string + readonly sharedPackages: readonly DesktopSharedPackage[] + readonly files: readonly DesktopRuntimeFile[] +} + +const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/u + +function record(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** + * Resolve one portable resource path without permitting traversal or absolute paths. + * @param root - Runtime root. + * @param path - Slash-separated relative path from durable metadata. + * @returns Absolute resource path. + */ +export function runtimePath(root: string, path: string): string { + if (path === '' || isAbsolute(path) || path.includes('\\') || path.includes(':') + || path.split('/').some(part => part === '' || part === '.' || part === '..')) { + throw new Error(`desktop runtime: invalid relative path ${JSON.stringify(path)}`) + } + return join(root, ...path.split('/')) +} + +/** + * Inventory a materialized runtime without following links or including its descriptor. + * @param root - Self-contained runtime directory. + * @returns Sorted final-file inventory. + */ +export function inventoryDesktopRuntime(root: string): DesktopRuntimeFile[] { + const files: DesktopRuntimeFile[] = [] + const visit = (directory: string): void => { + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const path = join(directory, entry.name) + const name = relative(root, path).split(sep).join('/') + if (name === DESKTOP_RUNTIME_FILE) continue + if (entry.isDirectory()) visit(path) + else if (entry.isFile()) { + const body = readFileSync(path) + files.push({ path: name, bytes: body.byteLength, sha256: createHash('sha256').update(body).digest('hex'), + executable: (lstatSync(path).mode & 0o111) !== 0 }) + } else throw new Error(`desktop runtime: unsupported filesystem entry ${name}`) + } + } + visit(root) + return files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0) +} + +/** + * Seal the final runtime tree after materialization and native signing. + * @param root - Runtime output directory. + * @param release - Matching shell, dsh, Host, and executable versions. + * @param sharedNames - Release-owned packages supplied to plugins. + * @param target - Platform and architecture selected by runtime preparation. + * @returns Descriptor written beside the production packages. + */ +export function writeDesktopRuntime( + root: string, release: DesktopRelease, sharedNames: readonly string[], + target: { platform: NodeJS.Platform; arch: string } = process, +): DesktopRuntimeDescriptor { + const sharedPackages = [...new Set(sharedNames)].sort().map((name) => { + if (!PACKAGE_NAME.test(name)) throw new Error(`desktop runtime: invalid shared package ${name}`) + const path = `node_modules/${name}` + const manifest = JSON.parse(readFileSync(join(runtimePath(root, path), 'package.json'), 'utf8')) as unknown + if (!record(manifest) || manifest.name !== name || typeof manifest.version !== 'string' || valid(manifest.version) === null) { + throw new Error(`desktop runtime: invalid shared package manifest ${name}`) + } + return { name, version: manifest.version, path } + }) + const descriptor: DesktopRuntimeDescriptor = { + schemaVersion: 1, release, platform: target.platform, arch: target.arch, + sharedPackages, files: inventoryDesktopRuntime(root), + } + writeFileSync(join(root, DESKTOP_RUNTIME_FILE), `${JSON.stringify(descriptor, undefined, 2)}\n`) + return descriptor +} + +/** + * Verify the runtime before linking any of its packages into writable state. + * @param root - Current application's runtime resources. + * @param electronVersion - Expected shell version. + * @param target - Required execution target; defaults to the current process. + * @returns Validated runtime descriptor. + */ +export function verifyDesktopRuntime( + root: string, electronVersion: string, target: { platform: NodeJS.Platform; arch: string } = process, +): DesktopRuntimeDescriptor { + const value: unknown = JSON.parse(readFileSync(join(root, DESKTOP_RUNTIME_FILE), 'utf8')) + if (!record(value) || value.schemaVersion !== 1 || value.platform !== target.platform || value.arch !== target.arch + || !Array.isArray(value.sharedPackages) || !Array.isArray(value.files)) { + throw new Error('desktop runtime: invalid descriptor or incompatible platform/architecture') + } + const release = parseDesktopRelease(value.release) + if (release.version !== electronVersion) throw new Error(`desktop runtime: ${release.version} does not match Electron ${electronVersion}`) + const sharedPackages = value.sharedPackages.map((entry: unknown): DesktopSharedPackage => { + if (!record(entry) || typeof entry.name !== 'string' || !PACKAGE_NAME.test(entry.name) + || typeof entry.version !== 'string' || valid(entry.version) === null || entry.path !== `node_modules/${entry.name}`) { + throw new Error('desktop runtime: invalid shared package record') + } + return { name: entry.name, version: entry.version, path: entry.path } + }) + if (new Set(sharedPackages.map(entry => entry.name)).size !== sharedPackages.length) { + throw new Error('desktop runtime: duplicate shared package') + } + const files = value.files.map((entry: unknown): DesktopRuntimeFile => { + if (!record(entry) || typeof entry.path !== 'string' || typeof entry.bytes !== 'number' + || !Number.isSafeInteger(entry.bytes) || entry.bytes < 0 || typeof entry.executable !== 'boolean' + || typeof entry.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(entry.sha256)) { + throw new Error('desktop runtime: invalid file inventory') + } + runtimePath(root, entry.path) + return { path: entry.path, bytes: entry.bytes, sha256: entry.sha256, executable: entry.executable } + }).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0) + const actual = inventoryDesktopRuntime(root) + // Windows has no portable Unix executable permission bits. + const comparable = (items: readonly DesktopRuntimeFile[]): unknown => process.platform === 'win32' + ? items.map(({ executable: _executable, ...item }) => item) : items + if (JSON.stringify(comparable(files)) !== JSON.stringify(comparable(actual))) { + throw new Error('desktop runtime: integrity verification failed') + } + for (const entry of sharedPackages) { + const manifest: unknown = JSON.parse(readFileSync(join(runtimePath(root, entry.path), 'package.json'), 'utf8')) + if (!record(manifest) || manifest.name !== entry.name || manifest.version !== entry.version) { + throw new Error(`desktop runtime: shared package metadata mismatch for ${entry.name}`) + } + } + for (const name of ['@deepseek-ai/dsh', DESKTOP_HOST_PACKAGE]) { + if (sharedPackages.find(entry => entry.name === name)?.version !== release.version) { + throw new Error(`desktop runtime: missing or mismatched ${name}`) + } + } + for (const file of DESKTOP_HOST_RUNTIME_FILES) { + if (!files.some(entry => entry.path === `node_modules/${DESKTOP_HOST_PACKAGE}/${file}`)) { + throw new Error(`desktop runtime: missing Host file ${file}`) + } + } + return { schemaVersion: 1, release, platform: target.platform, arch: target.arch, sharedPackages, files } +} + +/** + * Identify exact runtime content independently of its installation path. + * @param descriptor - Validated runtime metadata. + * @returns SHA-256 runtime identity. + */ +export function desktopRuntimeId(descriptor: DesktopRuntimeDescriptor): string { + return createHash('sha256').update(JSON.stringify(descriptor)).digest('hex') +} diff --git a/apps/desktop/src/seed-store.ts b/apps/desktop/src/seed-store.ts deleted file mode 100644 index e4b4759fd1..0000000000 --- a/apps/desktop/src/seed-store.ts +++ /dev/null @@ -1,271 +0,0 @@ -/** Deterministic archive transport for the desktop seed's pnpm store. */ - -import { createHash } from 'node:crypto' -import { - chmodSync, - copyFileSync, - cpSync, - existsSync, - mkdirSync, - readdirSync, - readFileSync, - rmSync, - writeFileSync, -} from 'node:fs' -import { join, relative, sep } from 'node:path' -import { DatabaseSync } from 'node:sqlite' -import { create, extract, list } from 'tar' - -/** Directory containing the seed's uncompressed pnpm store archives. */ -export const SEED_STORE_ARCHIVE_DIR = 'store-archives' - -/** Manifest describing the deterministic pnpm store archive set. */ -export const SEED_STORE_ARCHIVE_MANIFEST = 'store-archives.json' - -const DEFAULT_SHARD_COUNT = 16 -const ARCHIVE_NAME_PATTERN = /^store-[0-9a-f]{2}\.tar$/u -const STORE_VERSION_PATTERN = /^v\d+$/u - -interface SeedStoreArchiveRecord { - readonly file: string - readonly entries: number -} - -interface SeedStoreArchiveManifest { - readonly schemaVersion: 1 - readonly shardCount: number - readonly archives: readonly SeedStoreArchiveRecord[] -} - -function storeFiles(storeRoot: string): readonly string[] { - const files: string[] = [] - const visit = (directory: string): void => { - for (const entry of readdirSync(directory, { withFileTypes: true })) { - const path = join(directory, entry.name) - if (entry.isSymbolicLink()) { - throw new Error(`desktop seed: pnpm store contains a symbolic link: ${relative(storeRoot, path)}`) - } - if (entry.isDirectory()) { - visit(path) - continue - } - if (!entry.isFile()) { - throw new Error(`desktop seed: pnpm store contains an unsupported file: ${relative(storeRoot, path)}`) - } - files.push(relative(storeRoot, path).split(sep).join('/')) - } - } - visit(storeRoot) - return files.sort((left, right) => left.localeCompare(right)) -} - -function shardFor(path: string, shardCount: number): number { - return createHash('sha256').update(path).digest().readUInt32BE(0) % shardCount -} - -function readArchiveManifest(seedRoot: string): SeedStoreArchiveManifest { - const path = join(seedRoot, SEED_STORE_ARCHIVE_MANIFEST) - const value = JSON.parse(readFileSync(path, 'utf8')) as unknown - if (typeof value !== 'object' || value === null) { - throw new Error(`desktop seed: invalid pnpm store archive manifest ${path}`) - } - const candidate = value as Record - if (candidate.schemaVersion !== 1 || !Number.isSafeInteger(candidate.shardCount) - || (candidate.shardCount as number) < 1 || (candidate.shardCount as number) > 256 - || !Array.isArray(candidate.archives) || candidate.archives.length === 0) { - throw new Error(`desktop seed: invalid pnpm store archive manifest ${path}`) - } - const names = new Set() - const archives = candidate.archives.map((entry): SeedStoreArchiveRecord => { - if (typeof entry !== 'object' || entry === null) { - throw new Error(`desktop seed: invalid pnpm store archive record in ${path}`) - } - const record = entry as Record - if (typeof record.file !== 'string' || !ARCHIVE_NAME_PATTERN.test(record.file) - || names.has(record.file) || !Number.isSafeInteger(record.entries) || (record.entries as number) < 1) { - throw new Error(`desktop seed: invalid pnpm store archive record in ${path}`) - } - const shard = Number.parseInt(record.file.slice('store-'.length, -'.tar'.length), 16) - if (shard >= (candidate.shardCount as number)) { - throw new Error(`desktop seed: pnpm store archive shard is outside the manifest range in ${path}`) - } - names.add(record.file) - return { file: record.file, entries: record.entries as number } - }) - return { - schemaVersion: 1, - shardCount: candidate.shardCount as number, - archives, - } -} - -function assertArchivePath(path: string): void { - if (path === '' || path.startsWith('/') || path.includes('\\') || path.includes('\0') - || path.split('/').some(part => part === '' || part === '.' || part === '..')) { - throw new Error(`desktop seed: unsafe pnpm store archive path ${JSON.stringify(path)}`) - } -} - -/** - * Remove pnpm's registrations for projects that populated the seed store. - * @param storeRoot - pnpm store directory included in the desktop seed. - */ -export function removePnpmProjectRegistrations(storeRoot: string): void { - for (const entry of readdirSync(storeRoot, { withFileTypes: true })) { - if (!entry.isDirectory() || !/^v\d+$/u.test(entry.name)) continue - rmSync(join(storeRoot, entry.name, 'projects'), { recursive: true, force: true }) - } -} - -function mergeStoreIndex(source: string, destination: string): void { - if (!existsSync(destination)) { - copyFileSync(source, destination) - return - } - const database = new DatabaseSync(destination) - let attached = false - try { - database.exec('PRAGMA busy_timeout=5000') - database.prepare('ATTACH DATABASE ? AS seed').run(source) - attached = true - database.exec('BEGIN IMMEDIATE') - let committed = false - try { - database.exec('INSERT OR REPLACE INTO package_index (key, data) SELECT key, data FROM seed.package_index') - database.exec('COMMIT') - committed = true - } finally { - if (!committed) database.exec('ROLLBACK') - } - } finally { - if (attached) database.exec('DETACH DATABASE seed') - database.close() - } -} - -/** - * Merge a completely extracted seed store into Desktop's persistent pnpm store. - * @param source - Verified temporary store extraction. - * @param destination - Desktop-owned persistent pnpm store. - */ -export function mergePnpmStore(source: string, destination: string): void { - mkdirSync(destination, { recursive: true, mode: 0o700 }) - const indexPaths = readdirSync(source, { withFileTypes: true }) - .filter(entry => entry.isDirectory() && STORE_VERSION_PATTERN.test(entry.name) - && existsSync(join(source, entry.name, 'index.db'))) - .map(entry => `${entry.name}/index.db`) - const indexes = new Set(indexPaths) - cpSync(source, destination, { - recursive: true, - force: true, - filter: path => !indexes.has(relative(source, path).split(sep).join('/')), - }) - for (const path of indexPaths) { - mergeStoreIndex(join(source, ...path.split('/')), join(destination, ...path.split('/'))) - } -} - -/** - * Replace a prepared loose pnpm store with deterministic uncompressed archive shards. - * @param seedRoot - seed directory that owns the archive output. - * @param storeRoot - populated pnpm store to archive and remove after success. - * @param shardCount - stable shard count used to limit update churn. - */ -export function archivePnpmStore( - seedRoot: string, - storeRoot: string, - shardCount = DEFAULT_SHARD_COUNT, -): void { - if (!Number.isSafeInteger(shardCount) || shardCount < 1 || shardCount > 256) { - throw new Error(`desktop seed: invalid pnpm store shard count ${shardCount}`) - } - const archiveRoot = join(seedRoot, SEED_STORE_ARCHIVE_DIR) - const manifestPath = join(seedRoot, SEED_STORE_ARCHIVE_MANIFEST) - rmSync(archiveRoot, { recursive: true, force: true }) - rmSync(manifestPath, { force: true }) - mkdirSync(archiveRoot, { recursive: true }) - const shards = Array.from({ length: shardCount }, (): string[] => []) - for (const path of storeFiles(storeRoot)) (shards[shardFor(path, shardCount)] as string[]).push(path) - const archives: SeedStoreArchiveRecord[] = [] - for (const [index, paths] of shards.entries()) { - if (paths.length === 0) continue - const file = `store-${index.toString(16).padStart(2, '0')}.tar` - create({ - cwd: storeRoot, - file: join(archiveRoot, file), - noDirRecurse: true, - noMtime: true, - portable: true, - sync: true, - }, paths) - chmodSync(join(archiveRoot, file), 0o644) - archives.push({ file, entries: paths.length }) - } - if (archives.length === 0) throw new Error('desktop seed: pnpm store is empty') - writeFileSync(manifestPath, `${JSON.stringify({ schemaVersion: 1, shardCount, archives }, undefined, 2)}\n`) - rmSync(storeRoot, { recursive: true }) -} - -/** - * Validate and extract a packaged pnpm store archive set into an empty directory. - * @param seedRoot - verified packaged seed directory. - * @param destination - empty Desktop-owned temporary extraction directory. - */ -export function extractPnpmStoreArchives(seedRoot: string, destination: string): void { - const manifest = readArchiveManifest(seedRoot) - const archiveRoot = join(seedRoot, SEED_STORE_ARCHIVE_DIR) - const actualFiles = readdirSync(archiveRoot, { withFileTypes: true }).map((entry) => { - if (!entry.isFile() || entry.isSymbolicLink()) { - throw new Error(`desktop seed: invalid pnpm store archive entry ${entry.name}`) - } - return entry.name - }).sort() - const expectedFiles = manifest.archives.map(archive => archive.file).sort() - if (JSON.stringify(actualFiles) !== JSON.stringify(expectedFiles)) { - throw new Error('desktop seed: pnpm store archive set does not match its manifest') - } - if (existsSync(destination) && readdirSync(destination).length !== 0) { - throw new Error(`desktop seed: pnpm store extraction directory is not empty: ${destination}`) - } - mkdirSync(destination, { recursive: true, mode: 0o700 }) - const paths = new Set() - for (const archive of manifest.archives) { - const archivePath = join(archiveRoot, archive.file) - const archiveShard = Number.parseInt(archive.file.slice('store-'.length, -'.tar'.length), 16) - let entries = 0 - list({ - file: archivePath, - onReadEntry: (entry) => { - if (entry.type !== 'File' && entry.type !== 'OldFile') { - throw new Error(`desktop seed: unsupported pnpm store archive entry type ${entry.type}`) - } - assertArchivePath(entry.path) - if (shardFor(entry.path, manifest.shardCount) !== archiveShard) { - throw new Error(`desktop seed: pnpm store path is assigned to the wrong archive shard: ${entry.path}`) - } - if (paths.has(entry.path)) { - throw new Error(`desktop seed: duplicate pnpm store archive path ${entry.path}`) - } - paths.add(entry.path) - entries += 1 - }, - strict: true, - sync: true, - }) - if (entries !== archive.entries) { - throw new Error(`desktop seed: pnpm store archive ${archive.file} has an unexpected entry count`) - } - } - for (const archive of manifest.archives) { - extract({ - chmod: true, - cwd: destination, - file: join(archiveRoot, archive.file), - noMtime: true, - preservePaths: false, - processUmask: 0, - strict: true, - sync: true, - }) - } -} diff --git a/apps/desktop/src/update-coordinator.ts b/apps/desktop/src/update-coordinator.ts index c31dcc3093..be629228d8 100644 --- a/apps/desktop/src/update-coordinator.ts +++ b/apps/desktop/src/update-coordinator.ts @@ -1,4 +1,4 @@ -/** One Electron release stream for the version-bound shell and dsh seed. */ +/** One Electron release stream for the version-bound shell and bundled dsh runtime. */ import { existsSync } from 'node:fs' import { join } from 'node:path' diff --git a/apps/desktop/tests/desktop-build-paths.spec.ts b/apps/desktop/tests/desktop-build-paths.spec.ts index ac1618baef..1a309a2851 100644 --- a/apps/desktop/tests/desktop-build-paths.spec.ts +++ b/apps/desktop/tests/desktop-build-paths.spec.ts @@ -15,8 +15,8 @@ describe('desktop build paths', () => { 'artifacts', 'runtime', 'packageSet', - 'seed', - 'seedPnpm', + 'dsh', + 'dshPnpm', 'nodeExtract', 'packedDsh', 'packedVendor', @@ -27,7 +27,7 @@ describe('desktop build paths', () => { expect(new Set([arm64[key], x64[key], windows[key]]).size).toBe(3) } expect(arm64.artifacts).toContain(join('targets', 'mac-arm64', 'artifacts')) - expect(x64.seed).toContain(join('targets', 'mac-x64', 'seed')) + expect(x64.dsh).toContain(join('targets', 'mac-x64', 'dsh')) expect(windows.runtime).toContain(join('targets', 'win-x64', 'runtime')) }) diff --git a/apps/desktop/tests/host-process.spec.ts b/apps/desktop/tests/host-process.spec.ts index d3a08d78e0..9a9a2d4730 100644 --- a/apps/desktop/tests/host-process.spec.ts +++ b/apps/desktop/tests/host-process.spec.ts @@ -1,4 +1,4 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -75,6 +75,27 @@ afterEach(() => { }) describe('desktop host process', () => { + it('loads the resource entry with a separate profile and scrubs Node resolution overrides', async () => { + const runtime = projectWithHost(` +process.send({ type: 'ready', protocolVersion: 3, dshVersion: 'split-runtime' }) +function onRequestFrame(frame) { + if (frame.type !== 1) return + responseStart(frame.streamId) + responseData(frame.streamId, JSON.stringify({runtime: process.argv[2], profile: process.argv[3], cwd: process.cwd(), nodePath: process.env.NODE_PATH})) + responseEnd(frame.streamId) +} +`) + const profile = mkdtempSync(join(tmpdir(), 'desktop-external-profile-')) + roots.push(profile) + const host = new DesktopHostProcess(process.execPath, runtime, profile, undefined, { + ...process.env, NODE_OPTIONS: '--invalid-desktop-test-option', NODE_PATH: '/unowned', + }) + try { + const response = await host.fetch(new Request('dsh-app://app/environment')) + expect(await response.json()).toEqual({ runtime, profile, cwd: realpathSync(profile) }) + } finally { await host.stop() } + }) + it('carries raw request and response bytes and shuts the child down cleanly', async () => { const project = projectWithHost(` const bodies = new Map() @@ -98,7 +119,7 @@ function answer(streamId) { `) const previous = process.env.NODE_OPTIONS process.env.NODE_OPTIONS = '--require /path/that-must-not-reach-the-child' - const host = new DesktopHostProcess(process.execPath, project) + const host = new DesktopHostProcess(process.execPath, project, project) try { await expect(host.start()).resolves.toMatchObject({ dshVersion: 'clean' }) const response = await host.fetch(new Request('dsh-app://app/example', { method: 'POST', body: 'request' })) @@ -124,7 +145,7 @@ function onRequestFrame(frame) { responseEnd(frame.streamId) } `) - const host = new DesktopHostProcess(process.execPath, project) + const host = new DesktopHostProcess(process.execPath, project, project) try { const response = await host.fetch(new Request('dsh-app://app/large')) const body = new Uint8Array(await response.arrayBuffer()) @@ -151,7 +172,7 @@ function onRequestFrame(frame) { start(controller) { controller.enqueue(Buffer.from('first')) }, cancel() { canceled = true }, }) - const host = new DesktopHostProcess(process.execPath, project) + const host = new DesktopHostProcess(process.execPath, project, project) try { const request = new Request('dsh-app://app/early', { method: 'POST', @@ -184,7 +205,7 @@ function onRequestFrame(frame) { } } `) - const host = new DesktopHostProcess(process.execPath, project) + const host = new DesktopHostProcess(process.execPath, project, project) try { const canceled = await host.fetch(new Request('dsh-app://app/cancel')) await canceled.body?.cancel() @@ -202,7 +223,7 @@ process.send({ type: 'ready', protocolVersion: 3, dshVersion: 'invalid-frame' }) function onRequestFrame(frame) { if (frame.type === 1) responsePipe.write(Buffer.alloc(13)) } -`)) +`), projectWithHost('')) await invalid.start() await expect(invalid.fetch(new Request('dsh-app://app/invalid'))).rejects.toThrow(/invalid Host response frame marker/u) await invalid.stop().catch(() => undefined) @@ -210,7 +231,7 @@ function onRequestFrame(frame) { const earlyExit = new DesktopHostProcess(process.execPath, projectWithHost(` function onRequestFrame() {} process.exit(0) -`)) +`), projectWithHost('')) await expect(earlyExit.start()).rejects.toThrow(/response pipe ended/u) }) }) diff --git a/apps/desktop/tests/macos-runtime.spec.ts b/apps/desktop/tests/macos-runtime.spec.ts new file mode 100644 index 0000000000..c33b8d8cfb --- /dev/null +++ b/apps/desktop/tests/macos-runtime.spec.ts @@ -0,0 +1,48 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { signMacOSRuntime } from '../scripts/macos-runtime.ts' +import { signMacOSRuntimeCode, verifyMacOSRuntimeCode } from '../scripts/verify-macos-signature.mjs' + +vi.mock('../scripts/verify-macos-signature.mjs', () => ({ signMacOSRuntimeCode: vi.fn(), verifyMacOSRuntimeCode: vi.fn() })) +const roots: string[] = [] +function root(): string { + const path = mkdtempSync(join(tmpdir(), 'desktop-signing-')) + roots.push(path) + return path +} +const identity = { signingIdentity: 'Example (TEAMID1234)', teamId: 'TEAMID1234' } +afterEach(() => { + vi.resetAllMocks() + for (const path of roots.splice(0)) rmSync(path, { recursive: true, force: true }) +}) +it('signs Mach-O files in their final locations and verifies each signature', async () => { + const path = root() + writeFileSync(join(path, 'addon.node'), Buffer.from('cffaedfe00000000', 'hex')) + writeFileSync(join(path, 'source.js'), 'export {}') + await expect(signMacOSRuntime(path, 'com.example.app', identity)).resolves.toBe(1) + expect(signMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'addon.node'), expect.stringMatching(/^com\.example\.app\.runtime\.[a-f0-9]{64}$/u), identity) + expect(verifyMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'addon.node'), identity) +}) +it('awaits other signers before rejecting and permitting output cleanup', async () => { + const path = root() + for (const name of ['a.node', 'b.node']) writeFileSync(join(path, name), Buffer.from('cffaedfe00000000', 'hex')) + let release!: () => void + const barrier = new Promise((resolve) => { release = resolve }) + let started!: () => void + const ready = new Promise((resolve) => { started = resolve }) + vi.mocked(signMacOSRuntimeCode).mockImplementation(async (file) => { + if (file.endsWith('a.node')) throw new Error('sign failure') + started() + await barrier + }) + let completed = false + const result = signMacOSRuntime(path, 'com.example.app', identity).catch((error: unknown) => { completed = true; return error }) + try { + await ready + expect(completed).toBe(false) + } finally { release() } + expect(await result).toBeInstanceOf(AggregateError) + expect(verifyMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'b.node'), identity) +}) diff --git a/apps/desktop/tests/macos-seed-store.spec.ts b/apps/desktop/tests/macos-seed-store.spec.ts deleted file mode 100644 index 2155389262..0000000000 --- a/apps/desktop/tests/macos-seed-store.spec.ts +++ /dev/null @@ -1,245 +0,0 @@ -import { createHash } from 'node:crypto' -import { - appendFileSync, - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync, -} from 'node:fs' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { DatabaseSync } from 'node:sqlite' -import { Packr } from 'msgpackr' -import { afterEach, describe, expect, it } from 'vitest' -import { - signMacOSSeedStore, - verifyMacOSSeedStore, -} from '../scripts/macos-seed-store.ts' - -const temporaryRoots: string[] = [] -const packr = new Packr({ moreTypes: true, useRecords: true }) -const SIGNING_ENVIRONMENT = { - signingIdentity: 'Example Company (TEAMID1234)', - teamId: 'TEAMID1234', -} - -function temporaryRoot(): string { - const root = mkdtempSync(join(tmpdir(), 'dsh-desktop-seed-signing-test-')) - temporaryRoots.push(root) - return root -} - -function casPath(store: string, body: Buffer, executable = false): { digest: string; path: string } { - const digest = createHash('sha512').update(body).digest('hex') - return { - digest, - path: join(store, 'v11', 'files', digest.slice(0, 2), `${digest.slice(2)}${executable ? '-exec' : ''}`), - } -} - -function createStoreFile(path: string, body: Buffer): void { - mkdirSync(dirname(path), { recursive: true }) - writeFileSync(path, body) -} - -afterEach(() => { - for (const root of temporaryRoots.splice(0)) rmSync(root, { recursive: true, force: true }) -}) - -describe('desktop macOS seed store signing', () => { - it('rehashes signed Mach-O content, rewrites every package reference, and prunes native orphans', async () => { - const store = temporaryRoot() - const native = Buffer.concat([Buffer.from('cffaedfe', 'hex'), Buffer.from('native-code')]) - const nativeCas = casPath(store, native) - createStoreFile(nativeCas.path, native) - const orphan = Buffer.concat([Buffer.from('cafebabe', 'hex'), Buffer.from('orphan')]) - const orphanCas = casPath(store, orphan) - createStoreFile(orphanCas.path, orphan) - const plain = Buffer.from('plain package content') - const plainCas = casPath(store, plain) - createStoreFile(plainCas.path, plain) - - const database = new DatabaseSync(join(store, 'v11', 'index.db')) - database.exec('CREATE TABLE package_index (key TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID') - const insert = database.prepare('INSERT INTO package_index (key, data) VALUES (?, ?)') - for (const key of ['package-a', 'package-b']) { - insert.run(key, packr.pack({ - algo: 'sha512', - files: new Map([ - ['native.node', { checkedAt: 1, digest: nativeCas.digest, mode: 0o644, size: native.length }], - ['index.js', { checkedAt: 1, digest: plainCas.digest, mode: 0o644, size: plain.length }], - ]), - sideEffects: key === 'package-b' - ? new Map([['build', { added: new Map([ - ['built/native.node', { checkedAt: 1, digest: nativeCas.digest, mode: 0o644, size: native.length }], - ]) }]]) - : undefined, - })) - } - database.close() - - const result = await signMacOSSeedStore( - store, - 'com.example.desktop', - SIGNING_ENVIRONMENT, - { - signer: async (path, identifier) => { - expect(identifier).toBe(`com.example.desktop.seed.${nativeCas.digest.slice(0, 32)}`) - appendFileSync(path, 'signed') - }, - }, - ) - - expect(result).toEqual({ signedFiles: 1, prunedOrphans: 1, updatedIndexRows: 2 }) - expect(existsSync(nativeCas.path)).toBe(false) - expect(existsSync(orphanCas.path)).toBe(false) - expect(readFileSync(plainCas.path)).toEqual(plain) - - const updated = new DatabaseSync(join(store, 'v11', 'index.db'), { readOnly: true }) - const digests = [...updated.prepare('SELECT data FROM package_index').iterate() as Iterable<{ data: Uint8Array }>] - .flatMap((row) => { - const record = packr.unpack(row.data) as { - files: Map - sideEffects?: Map }> - } - return [ - record.files.get('native.node')?.digest, - ...[...(record.sideEffects?.values() ?? [])].map(effect => effect.added.get('built/native.node')?.digest), - ].filter((digest): digest is string => digest !== undefined) - }) - updated.close() - expect(new Set(digests).size).toBe(1) - expect(digests).toHaveLength(3) - expect(digests[0]).not.toBe(nativeCas.digest) - - const verified: string[] = [] - expect(verifyMacOSSeedStore(store, SIGNING_ENVIRONMENT, (path) => { verified.push(path) })).toBe(1) - expect(verified).toHaveLength(1) - }) - - it('bounds concurrent signing while allowing independent Mach-O files to overlap', async () => { - const store = temporaryRoot() - const files = new Map() - for (let index = 0; index < 6; index += 1) { - const body = Buffer.concat([Buffer.from('feedfacf', 'hex'), Buffer.from(`native-${index}`)]) - const nativeCas = casPath(store, body) - createStoreFile(nativeCas.path, body) - files.set(`native-${index}.node`, { - checkedAt: 1, - digest: nativeCas.digest, - mode: 0o644, - size: body.length, - }) - } - const database = new DatabaseSync(join(store, 'v11', 'index.db')) - database.exec('CREATE TABLE package_index (key TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID') - database.prepare('INSERT INTO package_index (key, data) VALUES (?, ?)') - .run('package', packr.pack({ algo: 'sha512', files })) - database.close() - - let started = 0 - let active = 0 - let maximumActive = 0 - let releaseSigning = (): void => {} - const signingReleased = new Promise((resolve) => { releaseSigning = resolve }) - let markFirstWaveReady = (): void => {} - const firstWaveReady = new Promise((resolve) => { markFirstWaveReady = resolve }) - const signing = signMacOSSeedStore(store, 'com.example.desktop', SIGNING_ENVIRONMENT, { - concurrency: 4, - signer: async () => { - started += 1 - active += 1 - maximumActive = Math.max(maximumActive, active) - if (started === 4) markFirstWaveReady() - try { - await signingReleased - } finally { - active -= 1 - } - }, - }) - - await firstWaveReady - expect({ started, active, maximumActive }).toEqual({ started: 4, active: 4, maximumActive: 4 }) - releaseSigning() - await expect(signing).resolves.toMatchObject({ signedFiles: 6, updatedIndexRows: 1 }) - expect({ started, active, maximumActive }).toEqual({ started: 6, active: 0, maximumActive: 4 }) - }) - - it('awaits active signers and preserves the store when one signer fails', async () => { - const store = temporaryRoot() - const originals: { digest: string; path: string }[] = [] - const files = new Map() - for (let index = 0; index < 2; index += 1) { - const body = Buffer.concat([Buffer.from('feedfacf', 'hex'), Buffer.from(`native-${index}`)]) - const nativeCas = casPath(store, body) - originals.push(nativeCas) - createStoreFile(nativeCas.path, body) - files.set(`native-${index}.node`, { - checkedAt: 1, - digest: nativeCas.digest, - mode: 0o644, - size: body.length, - }) - } - const databasePath = join(store, 'v11', 'index.db') - const database = new DatabaseSync(databasePath) - database.exec('CREATE TABLE package_index (key TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID') - database.prepare('INSERT INTO package_index (key, data) VALUES (?, ?)') - .run('package', packr.pack({ algo: 'sha512', files })) - database.close() - const originalIndex = readFileSync(databasePath) - - let started = 0 - let settled = 0 - let releaseSigning = (): void => {} - const signingReleased = new Promise((resolve) => { releaseSigning = resolve }) - let markBothReady = (): void => {} - const bothReady = new Promise((resolve) => { markBothReady = resolve }) - const signing = signMacOSSeedStore(store, 'com.example.desktop', SIGNING_ENVIRONMENT, { - concurrency: 2, - signer: async () => { - started += 1 - const call = started - if (started === 2) markBothReady() - try { - await signingReleased - if (call === 1) throw new Error('signing failed') - } finally { - settled += 1 - } - }, - }) - - await bothReady - releaseSigning() - await expect(signing).rejects.toThrow(/signing failed/u) - expect({ started, settled }).toEqual({ started: 2, settled: 2 }) - expect(readFileSync(databasePath)).toEqual(originalIndex) - for (const original of originals) expect(existsSync(original.path)).toBe(true) - }) - - it('rejects an invalid signing worker bound before starting a signer', async () => { - const store = temporaryRoot() - mkdirSync(join(store, 'v11', 'files'), { recursive: true }) - await expect(signMacOSSeedStore(store, 'com.example.desktop', SIGNING_ENVIRONMENT, { - concurrency: 0, - signer: async () => {}, - })).rejects.toThrow(/positive integer/u) - }) - - it('propagates a signature-verification failure', () => { - const store = temporaryRoot() - const native = Buffer.concat([Buffer.from('feedfacf', 'hex'), Buffer.from('native-code')]) - const nativeCas = casPath(store, native) - createStoreFile(nativeCas.path, native) - - expect(() => { - verifyMacOSSeedStore(store, SIGNING_ENVIRONMENT, () => { - throw new Error('invalid signature') - }) - }).toThrow(/invalid signature/u) - }) -}) diff --git a/apps/desktop/tests/macos-signature.spec.ts b/apps/desktop/tests/macos-signature.spec.ts index 827de532e9..09adb91bf1 100644 --- a/apps/desktop/tests/macos-signature.spec.ts +++ b/apps/desktop/tests/macos-signature.spec.ts @@ -1,3 +1,10 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, relative } from 'node:path' +import { createRequire } from 'node:module' +import { FileMatcher } from 'app-builder-lib/out/fileMatcher.js' +import { runtimeFixture } from './runtime-fixture.ts' +import { verifyDesktopRuntime } from '../src/runtime-tree.ts' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import type { NotarizeOptions } from '@electron/notarize' import { @@ -7,10 +14,15 @@ import { } from '../scripts/desktop-release-environment.mjs' import { notarizeMacOSDiskImageArtifact } from '../scripts/notarize-macos-disk-images.mjs' import { - assertMacOSSeedSignatureDetails, + assertMacOSRuntimeSignatureDetails, assertMacOSSignatureDetails, } from '../scripts/verify-macos-signature.mjs' +// app-builder-lib omits this internal copier from its declarations; the regression exercises its actual file filter. +const { copyFiles } = createRequire(import.meta.url)('app-builder-lib/out/fileMatcher.js') as { + copyFiles: (matchers: FileMatcher[]) => Promise +} + const RELEASE_ENVIRONMENT = { DSH_DESKTOP_APP_ID: 'com.example.desktop', DSH_DESKTOP_TARGET_PLATFORM: 'darwin', @@ -40,17 +52,18 @@ describe('desktop macOS release signature', () => { const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs') const config = createElectronBuilderConfig(RELEASE_ENVIRONMENT, 'darwin', 'arm64') expect(portablePath(config.directories.output)).toContain('/.desktop-build/targets/mac-arm64/artifacts') - expect(config.extraResources).toHaveLength(2) + expect(config.extraResources).toHaveLength(3) expect(config.extraResources[0]?.to).toBe('runtime') - expect(config.extraResources[1]?.to).toBe('seed') + expect(config.extraResources[1]?.to).toBe('dsh') expect(portablePath(config.extraResources[0]?.from ?? '')).toContain('/.desktop-build/targets/mac-arm64/runtime') - expect(portablePath(config.extraResources[1]?.from ?? '')).toContain('/.desktop-build/targets/mac-arm64/seed') + expect(portablePath(config.extraResources[1]?.from ?? '')).toContain('/.desktop-build/targets/mac-arm64/dsh') expect(config).toMatchObject({ appId: RELEASE_ENVIRONMENT.DSH_DESKTOP_APP_ID, mac: { identity: RELEASE_ENVIRONMENT.DSH_DESKTOP_MACOS_SIGNING_IDENTITY, forceCodeSigning: true, notarize: true, + signIgnore: ['/Contents/Resources/dsh(?:/|$)'], }, dmg: { sign: true, @@ -64,6 +77,26 @@ describe('desktop macOS release signature', () => { expect(typeof config.artifactBuildCompleted).toBe('function') }) + it('copies the complete runtime despite electron-builder excluding root node_modules', async () => { + const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs') + const config = createElectronBuilderConfig(RELEASE_ENVIRONMENT, 'darwin', 'arm64') + const root = mkdtempSync(join(tmpdir(), 'desktop-resource-copy-')) + try { + const source = join(root, 'source') + const destination = join(root, 'resources') + runtimeFixture(source) + const sourceRoot = config.extraResources[1].from + const matchers = config.extraResources.slice(1).map(entry => new FileMatcher( + join(source, relative(sourceRoot, entry.from)), join(destination, entry.to), value => value, + )) + await copyFiles(matchers.slice(0, 1)) + expect(() => verifyDesktopRuntime(join(destination, 'dsh'), '1.0.0')).toThrow(/integrity/u) + rmSync(destination, { recursive: true }) + await copyFiles(matchers) + expect(() => verifyDesktopRuntime(join(destination, 'dsh'), '1.0.0')).not.toThrow() + } finally { rmSync(root, { recursive: true, force: true }) } + }) + it('validates Windows signing without requiring macOS identifiers for a Windows target', async () => { const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs') expect(() => createElectronBuilderConfig({ @@ -82,7 +115,7 @@ describe('desktop macOS release signature', () => { }).not.toThrow() }) - it('requires a secure timestamp and hardened runtime for seed code', () => { + it('requires a secure timestamp and hardened runtime for runtime code', () => { const expected = resolveMacOSSigningEnvironment(RELEASE_ENVIRONMENT) const details = [ `Authority=Developer ID Application: ${expected.signingIdentity}`, @@ -90,12 +123,12 @@ describe('desktop macOS release signature', () => { 'Timestamp=31 Aug 2026 at 20:00:00', 'CodeDirectory v=20500 size=773 flags=0x10000(runtime) hashes=13+7 location=embedded', ].join('\n') - expect(() => { assertMacOSSeedSignatureDetails(details, expected) }).not.toThrow() + expect(() => { assertMacOSRuntimeSignatureDetails(details, expected) }).not.toThrow() expect(() => { - assertMacOSSeedSignatureDetails(details.replace(/^Timestamp=.*\n/um, ''), expected) + assertMacOSRuntimeSignatureDetails(details.replace(/^Timestamp=.*\n/um, ''), expected) }).toThrow(/secure timestamp/u) expect(() => { - assertMacOSSeedSignatureDetails(details.replace('flags=0x10000(runtime)', 'flags=0x0(none)'), expected) + assertMacOSRuntimeSignatureDetails(details.replace('flags=0x10000(runtime)', 'flags=0x0(none)'), expected) }).toThrow(/hardened runtime/u) }) diff --git a/apps/desktop/tests/package-target.spec.ts b/apps/desktop/tests/package-target.spec.ts index e822f212f5..ae5e0ca800 100644 --- a/apps/desktop/tests/package-target.spec.ts +++ b/apps/desktop/tests/package-target.spec.ts @@ -56,7 +56,7 @@ describe('desktop package target', () => { expect(desktopElectronBuilderArguments(target, true)).toContain('--dir') }) - it('keeps Windows signing fields out of build and seed preparation subprocesses', () => { + it('keeps Windows signing fields out of build and runtime preparation subprocesses', () => { expect(withoutWindowsSigningEnvironment({ DSH_DESKTOP_WINDOWS_CER_FILE: 'C:\\release\\server.cer', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'token-secret', diff --git a/apps/desktop/tests/plugin-manager.spec.ts b/apps/desktop/tests/plugin-manager.spec.ts new file mode 100644 index 0000000000..376b523f58 --- /dev/null +++ b/apps/desktop/tests/plugin-manager.spec.ts @@ -0,0 +1,33 @@ +import { readFileSync } from 'node:fs' +import { runInContext } from 'node:vm' +import { JSDOM } from 'jsdom' +import { expect, it, vi } from 'vitest' +import { resolveDesktopLocale } from '../src/locale.ts' + +it('keeps disabled packages visible and offers recovery without a running backend', async () => { + const dom = new JSDOM(readFileSync(new URL('../renderer/plugin-manager.html', import.meta.url), 'utf8'), { runScripts: 'outside-only' }) + let enabled = true + let ready = false + const disableAll = vi.fn(async () => { enabled = false; ready = true }) + const toggle = vi.fn(async (_name: string, active: boolean) => { enabled = active }) + const api = { + locale: async () => resolveDesktopLocale('en'), + backend: { status: async () => ({ ready, error: ready ? undefined : 'plugin requires Cordis ^2.0.0' }), retry: vi.fn() }, + plugins: { list: async () => [{ name: 'example-plugin', version: '1.0.0', enabled }], disableAll, toggle }, + } + Object.defineProperty(dom.window, 'dshDesktop', { value: api }) + try { + runInContext(readFileSync(new URL('../renderer/plugin-manager.js', import.meta.url), 'utf8'), dom.getInternalVMContext()) + const document = dom.window.document + await expect.poll(() => document.querySelector('#plugins li')?.textContent).toContain('example-plugin') + expect(document.querySelector('#recovery')?.hidden).toBe(false) + expect(document.querySelector('#startup-error')?.textContent).toBe('plugin requires Cordis ^2.0.0') + document.querySelector('#disable-all')?.click() + await expect.poll(() => document.querySelector('#recovery')?.hidden).toBe(true) + expect(disableAll).toHaveBeenCalledOnce() + expect(document.querySelector('#plugins li')?.textContent).toMatchInlineSnapshot('"example-plugin1.0.0 · DisabledEnableUpdateRemove"') + document.querySelector('#plugins li button')?.click() + await expect.poll(() => toggle.mock.calls).toEqual([['example-plugin', true]]) + await expect.poll(() => document.querySelector('#plugins li')?.textContent).toBe('example-plugin1.0.0DisableUpdateRemove') + } finally { dom.window.close() } +}) diff --git a/apps/desktop/tests/plugin-pnpm.spec.ts b/apps/desktop/tests/plugin-pnpm.spec.ts new file mode 100644 index 0000000000..1a455e3453 --- /dev/null +++ b/apps/desktop/tests/plugin-pnpm.spec.ts @@ -0,0 +1,72 @@ +import { createHash } from 'node:crypto' +import { execFileSync } from 'node:child_process' +import { createServer } from 'node:http' +import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { c } from 'tar' +import { expect, it } from 'vitest' +import { DesktopProjectManager, type DesktopProjectHooks } from '../src/project-manager.ts' +import { resolveDesktopPaths } from '../src/paths.ts' +import { runtimeFixture, writePackage } from './runtime-fixture.ts' + +it('installs a real pnpm graph, then executes approved scripts with the shared host instance', async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), 'desktop-real-pnpm-'))) + const server = createServer() + const archives = new Map() + try { + for (const name of ['fixture-plugin', 'node-pty']) { + const path = writePackage(join(root, 'packages'), name, name === 'fixture-plugin' + ? { dependencies: { 'node-pty': '1.0.0' }, peerDependencies: { '@deepseek-ai/cordis': '^1.0.0' }, dsh: { bundle: { patch: 'bundle.yml' } } } + : { scripts: { install: 'node install.cjs' } }, 'export {identity} from "@deepseek-ai/cordis"') + writeFileSync(join(path, 'bundle.yml'), '[]\n') + writeFileSync(join(path, 'install.cjs'), 'require("node:fs").writeFileSync("built.json", JSON.stringify({node:process.execPath, host:require.resolve("@deepseek-ai/cordis")}))') + const tarball = join(root, `${name}.tgz`) + await c({ file: tarball, cwd: join(path, '..'), gzip: true }, [name]) + archives.set(name, readFileSync(tarball)) + } + await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) }) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('fixture registry has no TCP address') + const origin = `http://127.0.0.1:${address.port}` + server.on('request', (request, response) => { + const name = request.url?.slice(1).replace(/\.tgz$/u, '') ?? '' + const archive = archives.get(name) + if (archive === undefined) { response.writeHead(404); response.end(); return } + if (request.url?.endsWith('.tgz')) { response.end(archive); return } + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify({ name, 'dist-tags': { latest: '1.0.0' }, versions: { '1.0.0': { + name, version: '1.0.0', dist: { tarball: `${origin}/${name}.tgz`, integrity: `sha512-${createHash('sha512').update(archive).digest('base64')}` }, + ...(name === 'fixture-plugin' ? { dependencies: { 'node-pty': '1.0.0' }, peerDependencies: { '@deepseek-ai/cordis': '^1.0.0' } } : {}), + } }, time: { '1.0.0': '2020-01-01T00:00:00.000Z' } })) + }) + const dsh = join(root, 'dsh') + runtimeFixture(dsh) + const pnpm = join(root, 'pnpm.mjs') + const realPnpm = join(import.meta.dirname, '../node_modules/pnpm/bin/pnpm.mjs') + writeFileSync(pnpm, `process.argv = process.argv.map(arg => arg === '--config.registry=https://registry.npmjs.org/' ? ${JSON.stringify(`--config.registry=${origin}`)} : arg); await import(${JSON.stringify(pathToFileURL(realPnpm).href)})`) + const manager = new DesktopProjectManager(resolveDesktopPaths(join(root, '.dsh')), { node: process.execPath, pnpm, dsh }) + const hooks: DesktopProjectHooks = { healthCheck: async () => {}, beforeActivate: async () => {}, afterActivate: async () => {} } + await manager.applyRelease('1.0.0', hooks) + await manager.mutate({ type: 'plugin-add', spec: 'fixture-plugin@1.0.0' }, hooks) + expect(manager.listPlugins()).toEqual([{ name: 'fixture-plugin', version: '1.0.0', enabled: true }]) + const built = JSON.parse(readFileSync(join(manager.paths.profile, 'node_modules/node-pty/built.json'), 'utf8')) as { node: string; host: string } + expect(realpathSync(built.node)).toBe(realpathSync(process.execPath)) + expect(built.host).toBe(join(dsh, 'node_modules/@deepseek-ai/cordis/index.js')) + const entry = join(dsh, 'identity.mjs') + writeFileSync(entry, `import {identity} from '@deepseek-ai/cordis'; import {identity as plugin} from ${JSON.stringify(pathToFileURL(join(manager.paths.profile, 'node_modules/fixture-plugin/index.js')).href)}; console.log(identity === plugin)`) + expect(execFileSync(process.execPath, [entry], { encoding: 'utf8' }).trim()).toBe('true') + await manager.mutate({ type: 'plugin-remove', name: 'fixture-plugin' }, hooks) + expect(manager.listPlugins()).toEqual([]) + } finally { + server.closeAllConnections() + if (server.listening) await new Promise((resolve, reject) => { + server.close((error) => { + if (error !== undefined) reject(error) + else resolve() + }) + }) + rmSync(root, { recursive: true, force: true }) + } +}, 30_000) diff --git a/apps/desktop/tests/profile-packages.spec.ts b/apps/desktop/tests/profile-packages.spec.ts new file mode 100644 index 0000000000..4f3fe1308a --- /dev/null +++ b/apps/desktop/tests/profile-packages.spec.ts @@ -0,0 +1,81 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterEach, expect, it } from 'vitest' +import { createPluginProfile } from '../src/project-manager.ts' +import { copyDesktopProfile, linkDesktopHostPackages, unlinkDesktopHostPackages, validateDesktopPluginGraph } from '../src/profile-packages.ts' +import { runtimeFixture, writePackage } from './runtime-fixture.ts' + +const roots: string[] = [] +function fixture() { + const root = mkdtempSync(join(tmpdir(), 'desktop-profile-')) + roots.push(root) + const dsh = join(root, 'dsh') + const runtime = runtimeFixture(dsh) + const profile = join(root, 'profile') + createPluginProfile(profile) + linkDesktopHostPackages(profile, dsh, runtime) + return { root, dsh, runtime, profile } +} +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) + +it('loads one shared ESM instance from both host and external plugin while keeping ordinary dependencies private', () => { + const { dsh, runtime, profile } = fixture() + writePackage(join(dsh, 'node_modules'), 'ordinary', {}, 'export default "host"') + writePackage(join(profile, 'node_modules'), 'ordinary', {}, 'export default "plugin"') + const plugin = writePackage(join(profile, 'node_modules'), 'plugin', { + peerDependencies: { '@deepseek-ai/cordis': '^1.0.0' }, dependencies: { ordinary: '1.0.0' }, + }, 'export { identity } from "@deepseek-ai/cordis"; export { default as ordinary } from "ordinary"') + validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) + const entry = join(dsh, 'check.mjs') + writeFileSync(entry, `import {identity} from '@deepseek-ai/cordis'; import ordinary from 'ordinary'; import * as plugin from ${JSON.stringify(pathToFileURL(join(plugin, 'index.js')).href)}; console.log(JSON.stringify({same:identity===plugin.identity, host:ordinary, plugin:plugin.ordinary}))`) + const output = execFileSync(process.execPath, [entry], { encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '', NODE_PATH: '' } }) + expect(JSON.parse(output)).toEqual({ same: true, host: 'host', plugin: 'plugin' }) +}) +it.each(['nested', 'alias'])('rejects a %s second copy of a host package', (placement) => { + const { dsh, runtime, profile } = fixture() + const plugin = writePackage(join(profile, 'node_modules'), 'plugin') + if (placement === 'nested') writePackage(join(plugin, 'node_modules'), '@deepseek-ai/cordis') + else writePackage(join(profile, 'node_modules'), 'alias', { name: '@deepseek-ai/cordis' }) + expect(() =>{ validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/duplicate or aliased/u) +}) +it('rejects a host package declared as an ordinary dependency', () => { + const { dsh, runtime, profile } = fixture() + writePackage(join(profile, 'node_modules'), 'plugin', { dependencies: { '@deepseek-ai/cordis': '^1.0.0' } }) + expect(() =>{ validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/peer dependency/u) +}) +it('rejects incompatible peers only when the plugin is enabled', () => { + const { dsh, runtime, profile } = fixture() + writePackage(join(profile, 'node_modules'), 'plugin', { peerDependencies: { '@deepseek-ai/cordis': '^2.0.0' } }) + expect(() =>{ validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/found 1.0.0/u) + expect(() =>{ validateDesktopPluginGraph(profile, dsh, runtime, []) }).not.toThrow() +}) +it('refuses to satisfy a plugin dependency from an ancestor CLI project', () => { + const { root, dsh, runtime, profile } = fixture() + writePackage(join(root, 'node_modules'), 'ambient') + writePackage(join(profile, 'node_modules'), 'plugin', { dependencies: { ambient: '1.0.0' } }) + expect(() =>{ validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/outside its owned packages/u) +}) +it('copies writable plugin bytes independently and removes broken owned links without following them', () => { + const { root, profile } = fixture() + writePackage(join(profile, 'node_modules'), 'plugin') + copyDesktopProfile(profile, join(root, 'copy')) + writeFileSync(join(root, 'copy/node_modules/plugin/index.js'), 'changed') + expect(readFileSync(join(profile, 'node_modules/plugin/index.js'), 'utf8')).toContain('identity') + rmSync(join(root, 'dsh'), { recursive: true }) + expect(() =>{ unlinkDesktopHostPackages(profile) }).not.toThrow() +}) +it('refuses to replace an unowned package at a managed name', () => { + const { profile } = fixture() + unlinkSync(join(profile, 'node_modules/@deepseek-ai/cordis')) + writePackage(join(profile, 'node_modules'), '@deepseek-ai/cordis') + expect(() =>{ unlinkDesktopHostPackages(profile) }).toThrow(/unowned package/u) +}) +it('rejects private package links instead of following cycles or old transaction paths', () => { + const { dsh, runtime, profile } = fixture() + const plugin = writePackage(join(profile, 'node_modules'), 'plugin') + symlinkSync(plugin, join(profile, 'node_modules/alias'), process.platform === 'win32' ? 'junction' : 'dir') + expect(() =>{ validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/linked private package/u) +}) diff --git a/apps/desktop/tests/project-manager.spec.ts b/apps/desktop/tests/project-manager.spec.ts index f5320b47bd..18e5c26c7a 100644 --- a/apps/desktop/tests/project-manager.spec.ts +++ b/apps/desktop/tests/project-manager.spec.ts @@ -1,392 +1,217 @@ -import { createHash } from 'node:crypto' -import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { existsSync, mkdtempSync, mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, realpathSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { dirname, join, relative, sep } from 'node:path' +import { dirname, join } from 'node:path' import { pathToFileURL } from 'node:url' import { afterEach, describe, expect, it } from 'vitest' import { resolveDesktopPaths } from '../src/paths.ts' -import { - createSeedMetadata, - DesktopProjectManager, - packageNameFromSpec, - verifySeedIntegrity, - type DesktopProjectHooks, -} from '../src/project-manager.ts' -import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts' -import { DESKTOP_PACKAGES_DIR, DESKTOP_PACKAGE_SET_FILE } from '../src/core-package-set.ts' -import type { DesktopRelease } from '../src/release.ts' -import { archivePnpmStore } from '../src/seed-store.ts' +import { DesktopProjectManager, packageNameFromSpec, type DesktopProjectHooks } from '../src/project-manager.ts' +import { readDesktopProfileState } from '../src/profile-packages.ts' +import { runtimeFixture } from './runtime-fixture.ts' const roots: string[] = [] - function temporaryRoot(): string { const root = mkdtempSync(join(tmpdir(), 'dsh-desktop-test-')) roots.push(root) return root } - -function writeIntegrity(seed: string): void { - const paths: string[] = [] - const visit = (directory: string): void => { - for (const entry of readdirSync(directory, { withFileTypes: true })) { - const path = join(directory, entry.name) - if (entry.isDirectory()) visit(path) - else if (entry.name !== 'integrity.json') paths.push(path) - } - } - visit(seed) - const files = paths.sort().map((path) => { - const body = readFileSync(path) - return { - path: relative(seed, path).split(sep).join('/'), - bytes: statSync(path).size, - sha256: createHash('sha256').update(body).digest('hex'), - } - }) - writeFileSync(join(seed, 'integrity.json'), `${JSON.stringify({ schemaVersion: 2, files })}\n`) -} - -function archiveStore(seed: string): void { - const store = join(seed, 'store') - mkdirSync(store, { recursive: true }) - if (readdirSync(store).length === 0) writeFileSync(join(store, 'test-entry'), 'content') - archivePnpmStore(seed, store) -} - -function writeCorePackageSet(seed: string, version: string): void { - const packages = [ - { name: '@deepseek-ai/dsh', file: `deepseek-ai-dsh-${version}.tgz`, body: Buffer.from(`dsh-${version}`) }, - { - name: '@deepseek-ai/dsh-desktop-host', - file: `deepseek-ai-dsh-desktop-host-${version}.tgz`, - body: Buffer.from(`desktop-host-${version}`), - }, - ] - mkdirSync(join(seed, DESKTOP_PACKAGES_DIR), { recursive: true }) - for (const entry of packages) writeFileSync(join(seed, DESKTOP_PACKAGES_DIR, entry.file), entry.body) - writeFileSync(join(seed, DESKTOP_PACKAGE_SET_FILE), `${JSON.stringify({ - schemaVersion: 1, - packages: packages.map(({ name, file, body }) => ({ - name, - version, - file, - bytes: body.byteLength, - integrity: `sha512-${createHash('sha512').update(body).digest('base64')}`, - })), - })}\n`) -} - -function createTestSeedMetadata(seed: string, desktopRelease: DesktopRelease): void { - writeCorePackageSet(seed, desktopRelease.version) - createSeedMetadata(seed, desktopRelease) -} - function writeFakePnpm(root: string): string { const path = join(root, 'pnpm.mjs') - writeFileSync(path, String.raw` -import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { dirname, join } from 'node:path' + writeFileSync(path, ` +import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' const args = process.argv.slice(2) const project = process.cwd() -const command = args.find(value => value === 'install' || value === 'add' || value === 'remove') -const manifestPath = join(project, 'package.json') -const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) -const packageName = spec => spec.startsWith('@') - ? spec.slice(0, spec.indexOf('@', spec.indexOf('/') + 1) === -1 ? undefined : spec.indexOf('@', spec.indexOf('/') + 1)) - : spec.split('@')[0] -const packageVersion = spec => { - const index = spec.startsWith('@') ? spec.indexOf('@', spec.indexOf('/') + 1) : spec.indexOf('@') - return index === -1 ? '1.0.0' : spec.slice(index + 1) -} - -if (command === 'add') { - const spec = args[args.indexOf('add') + 1] - manifest.dependencies[packageName(spec)] = packageVersion(spec) -} -if (command === 'remove') delete manifest.dependencies[args[args.indexOf('remove') + 1]] -writeFileSync(manifestPath, JSON.stringify(manifest)) -rmSync(join(project, 'node_modules'), { recursive: true, force: true }) -for (const [name, version] of Object.entries(manifest.dependencies)) { - const packageRoot = join(project, 'node_modules', ...name.split('/')) - mkdirSync(packageRoot, { recursive: true }) - const core = name === '@deepseek-ai/dsh' || name === '@deepseek-ai/dsh-desktop-host' - const plugin = !core - const installedVersion = plugin - ? version - : JSON.parse(readFileSync(join(project, 'desktop-release.json'), 'utf8')).version - writeFileSync(join(packageRoot, 'package.json'), JSON.stringify({ - name, version: installedVersion, - ...(plugin ? { dsh: { bundle: { patch: './bundle.yml' } } } : {}), - })) - if (plugin) writeFileSync(join(packageRoot, 'bundle.yml'), '[]\n') - else if (name === '@deepseek-ai/dsh-desktop-host') { - mkdirSync(join(packageRoot, 'lib'), { recursive: true }) - writeFileSync(join(packageRoot, 'lib', 'index.js'), '') +const command = args.find(value => ['install', 'add', 'remove', 'rebuild'].includes(value)) +appendFileSync(${JSON.stringify(join(root, 'pnpm-log.jsonl'))}, JSON.stringify({args, registry: process.env.NPM_CONFIG_REGISTRY}) + '\\n') +if (command !== 'rebuild') { + const manifestPath = join(project, 'package.json') + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) + if (command === 'add') { + const spec = args[args.indexOf(command) + 1] + const index = spec.lastIndexOf('@') + const name = index > 0 ? spec.slice(0, index) : spec + manifest.dependencies[name] = index > 0 ? spec.slice(index + 1) : '1.0.0' } + if (command === 'remove') delete manifest.dependencies[args[args.indexOf(command) + 1]] + writeFileSync(manifestPath, JSON.stringify(manifest)) + rmSync(join(project, 'node_modules'), { recursive: true, force: true }) + for (const [name, version] of Object.entries(manifest.dependencies)) { + const packageRoot = join(project, 'node_modules', name) + mkdirSync(packageRoot, { recursive: true }) + writeFileSync(join(packageRoot, 'package.json'), JSON.stringify({name, version, + peerDependencies: {'@deepseek-ai/cordis': '^1.0.0'}, dsh: {bundle: {patch: './bundle.yml'}}})) + writeFileSync(join(packageRoot, 'bundle.yml'), '[]\\n') + } + writeFileSync(join(project, 'pnpm-lock.yaml'), JSON.stringify(manifest.dependencies)) } -writeFileSync(join(project, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') -if (process.env.TEST_PNPM_LOG) writeFileSync(process.env.TEST_PNPM_LOG, JSON.stringify({ args, env: process.env })) `) return path } - -function writeBlockingFakePnpm(root: string, ready: string, release: string): string { - const path = join(root, 'blocking-pnpm.mjs') - const delegate = writeFakePnpm(root) - writeFileSync(path, ` -import { existsSync, writeFileSync } from 'node:fs' -import { setTimeout as sleep } from 'node:timers/promises' -writeFileSync(${JSON.stringify(ready)}, String(process.pid)) -while (!existsSync(${JSON.stringify(release)})) await sleep(10) -await import(${JSON.stringify(pathToFileURL(delegate).href)}) -`) - return path -} - function hooks(overrides: Partial = {}): DesktopProjectHooks { - return { - healthCheck: async () => {}, - beforeActivate: async () => {}, - afterActivate: async () => {}, - ...overrides, - } + return { healthCheck: async () => {}, beforeActivate: async () => {}, afterActivate: async () => {}, ...overrides } } - -function release(version = '1.0.0'): DesktopRelease { - return { - schemaVersion: 1, - version, - hostProtocolVersion: DESKTOP_HOST_PROTOCOL_VERSION, - nodeVersion: '24.17.0', - pnpmVersion: '11.7.0', - } +function setup(): { root: string; manager: DesktopProjectManager } { + const root = temporaryRoot() + const dsh = join(root, 'resources', 'dsh') + runtimeFixture(dsh) + return { root, manager: new DesktopProjectManager(resolveDesktopPaths(join(root, '.dsh')), { node: process.execPath, pnpm: writeFakePnpm(root), dsh }) } } +function calls(root: string): { args: string[]; registry: string }[] { + const path = join(root, 'pnpm-log.jsonl') + return existsSync(path) ? readFileSync(path, 'utf8').trim().split('\n').map(line => JSON.parse(line) as { args: string[]; registry: string }) : [] +} +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) -afterEach(() => { - for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) -}) - -describe('desktop package policy', () => { - it('accepts registry package specs but rejects alternate sources and flags', () => { +describe('desktop external plugin profile', () => { + it('accepts registry names and tags but rejects alternate sources and flags', () => { expect(packageNameFromSpec('@scope/plugin@1.2.3')).toBe('@scope/plugin') expect(packageNameFromSpec('plugin@next')).toBe('plugin') - expect(() => packageNameFromSpec('file:../plugin')).toThrow(/unsupported npm package spec/u) - expect(() => packageNameFromSpec('--registry=evil')).toThrow(/unsupported npm package spec/u) - expect(() => packageNameFromSpec('https://example.test/plugin.tgz')).toThrow(/unsupported npm package spec/u) - }) - - it('rejects any seed content changed after release inventory generation', () => { - const seed = join(temporaryRoot(), 'seed') - createTestSeedMetadata(seed, release()) - writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') - writeIntegrity(seed) - expect(() => { verifySeedIntegrity(seed) }).not.toThrow() - writeFileSync(join(seed, 'package.json'), '{}\n') - expect(() => { verifySeedIntegrity(seed) }).toThrow(/integrity verification failed/u) - }) -}) - -describe('desktop project transactions', () => { - it('installs the offline seed and reconciles a mismatched private Host', async () => { - const root = temporaryRoot() - const seed = join(root, 'seed') - const log = join(root, 'pnpm-log.json') - createTestSeedMetadata(seed, release()) - writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') - mkdirSync(join(seed, 'store'), { recursive: true }) - writeFileSync(join(seed, 'store', 'seed-entry'), 'content') - archiveStore(seed) - writeIntegrity(seed) - const paths = resolveDesktopPaths(join(root, '.dsh')) - const manager = new DesktopProjectManager(paths, { node: process.execPath, pnpm: writeFakePnpm(root) }) - const previousLog = process.env.TEST_PNPM_LOG - const previousRegistry = process.env.npm_config_registry - process.env.TEST_PNPM_LOG = log - process.env.npm_config_registry = 'https://user-registry.invalid' - try { - await expect(manager.applyRelease(seed, '2.0.0', hooks())).rejects.toThrow(/does not match Electron/u) - await manager.applyRelease(seed, '1.0.0', hooks()) - writeFileSync( - join(paths.profile, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'package.json'), - '{"name":"@deepseek-ai/dsh-desktop-host","version":"0.9.0"}\n', - ) - await expect(manager.applyRelease(seed, '1.0.0', hooks())).resolves.toBe(true) - } finally { - if (previousLog === undefined) delete process.env.TEST_PNPM_LOG - else process.env.TEST_PNPM_LOG = previousLog - if (previousRegistry === undefined) delete process.env.npm_config_registry - else process.env.npm_config_registry = previousRegistry + for (const spec of ['file:../plugin', '--registry=evil', 'https://example.test/plugin.tgz']) { + expect(() => packageNameFromSpec(spec)).toThrow(/unsupported npm package spec/u) } - expect(manager.dshVersion()).toBe('1.0.0') - expect(manager.releaseVersion()).toBe('1.0.0') - expect(paths.profile).toBe(join(root, '.dsh', 'profiles', 'desktop')) - expect(existsSync(join(paths.profile, 'node_modules', '@deepseek-ai', 'dsh'))).toBe(true) - const installedHost = JSON.parse(readFileSync( - join(paths.profile, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'package.json'), - 'utf8', - )) as { version: string } - expect(installedHost.version).toBe('1.0.0') - expect(existsSync(join(paths.profile, 'desktop-plugins.json'))).toBe(false) - expect(readFileSync(join(paths.pnpm.store, 'seed-entry'), 'utf8')).toBe('content') - const invocation = JSON.parse(readFileSync(log, 'utf8')) as { args: string[]; env: Record } - expect(invocation.args).toContain('--offline') - expect(invocation.args).toContain('--trust-lockfile') - expect(invocation.args).toContain(`--config.store-dir=${paths.pnpm.store}`) - expect(invocation.args).toContain('--config.enable-global-virtual-store=false') - expect(invocation.args).toContain('--config.registry=https://registry.npmjs.org/') - expect(invocation.env.NPM_CONFIG_REGISTRY).toBe('https://registry.npmjs.org/') - expect(invocation.env.NPM_CONFIG_STORE_DIR).toBe(paths.pnpm.store) - expect(invocation.env.NPM_CONFIG_USERCONFIG).toBe(join(paths.pnpm.config, 'npmrc')) - expect(invocation.env.npm_config_registry).toBeUndefined() }) - it('restores the active project when the replacement backend cannot start', async () => { - const root = temporaryRoot() - const seed = join(root, 'seed') - createTestSeedMetadata(seed, release()) - writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') - archiveStore(seed) - writeIntegrity(seed) - const paths = resolveDesktopPaths(join(root, '.dsh')) - const manager = new DesktopProjectManager(paths, { node: process.execPath, pnpm: writeFakePnpm(root) }) - await manager.applyRelease(seed, '1.0.0', hooks()) - let starts = 0 - await expect(manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks({ - afterActivate: async () => { - starts += 1 - if (starts === 1) throw new Error('backend rejected staged graph') - }, - }))).rejects.toThrow(/backend rejected staged graph/u) + it('initializes and restarts offline without executing pnpm', async () => { + const { root, manager } = setup() + await expect(manager.applyRelease('2.0.0', hooks())).rejects.toThrow(/does not match Electron/u) + await expect(manager.applyRelease('1.0.0', hooks())).resolves.toBe(true) + await expect(manager.applyRelease('1.0.0', hooks())).resolves.toBe(false) expect(manager.listPlugins()).toEqual([]) - expect(manager.dshVersion()).toBe('1.0.0') - expect(starts).toBe(2) + expect(calls(root)).toEqual([]) + expect(existsSync(manager.paths.pnpm.store)).toBe(false) + expect(realpathSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis'))).toBe(realpathSync(join(manager.runtime.dsh, 'node_modules/@deepseek-ai/cordis'))) + expect(JSON.parse(readFileSync(join(manager.paths.profile, 'package.json'), 'utf8'))).toMatchObject({ dependencies: {} }) }) - it('restores rollback when the active move completed before its journal update', async () => { - const root = temporaryRoot() - const seed = join(root, 'seed') - createTestSeedMetadata(seed, release()) - writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') - archiveStore(seed) - writeIntegrity(seed) - const paths = resolveDesktopPaths(join(root, '.dsh')) - const manager = new DesktopProjectManager(paths, { node: process.execPath, pnpm: writeFakePnpm(root) }) - await manager.applyRelease(seed, '1.0.0', hooks()) + it('repairs a removed managed link without running pnpm', async () => { + const { root, manager } = setup() + await manager.applyRelease('1.0.0', hooks()) + unlinkSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis')) + await expect(manager.applyRelease('1.0.0', hooks())).resolves.toBe(true) + expect(calls(root)).toEqual([]) + }) + + it('installs only plugins and checks the graph before running lifecycle scripts', async () => { + const { root, manager } = setup() + await manager.applyRelease('1.0.0', hooks()) await manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks()) - const stagingProfile = join(paths.staging, 'interrupted', 'profile') - mkdirSync(stagingProfile, { recursive: true }) - writeFileSync(join(stagingProfile, 'marker'), 'staging') - rmSync(paths.rollback, { recursive: true, force: true }) - mkdirSync(dirname(paths.rollback), { recursive: true }) - renameSync(paths.profile, paths.rollback) - writeFileSync(paths.pending, `${JSON.stringify({ - schemaVersion: 1, - id: 'interrupted', - stagingProfile, - step: 'prepared', - })}\n`) - - manager.recover() - - expect(manager.listPlugins()).toEqual([{ name: '@scope/plugin', version: '2.0.0' }]) - expect(existsSync(stagingProfile)).toBe(false) - expect(existsSync(paths.pending)).toBe(false) - }) - - it('records the live pnpm worker as transaction owner until it exits', async () => { - const root = temporaryRoot() - const seed = join(root, 'seed') - const ready = join(root, 'pnpm-ready') - const releaseWorker = join(root, 'pnpm-release') - createTestSeedMetadata(seed, release()) - writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') - archiveStore(seed) - writeIntegrity(seed) - const paths = resolveDesktopPaths(join(root, '.dsh')) - const runtime = { node: process.execPath, pnpm: writeBlockingFakePnpm(root, ready, releaseWorker) } - const manager = new DesktopProjectManager(paths, runtime) - const installing = manager.applyRelease(seed, '1.0.0', hooks()) - await expect.poll(() => existsSync(ready)).toBe(true) - const workerPid = Number.parseInt(readFileSync(ready, 'utf8'), 10) - expect(readFileSync(paths.lock, 'utf8')).toBe(`${String(workerPid)}\n`) - const competing = new DesktopProjectManager(paths, runtime) - await expect(competing.applyRelease(seed, '1.0.0', hooks())).rejects.toThrow(/another package transaction is active/u) - writeFileSync(releaseWorker, 'continue') - await expect(installing).resolves.toBe(true) - expect(existsSync(paths.lock)).toBe(false) - }) - - it('keeps core packages local while installing plugins from the desktop registry', async () => { - const root = temporaryRoot() - const seed = join(root, 'seed') - const log = join(root, 'pnpm-log.json') - createTestSeedMetadata(seed, release()) - writeFileSync(join(seed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') - archiveStore(seed) - writeIntegrity(seed) - const paths = resolveDesktopPaths(join(root, '.dsh')) - const manager = new DesktopProjectManager(paths, { node: process.execPath, pnpm: writeFakePnpm(root) }) - await manager.applyRelease(seed, '1.0.0', hooks()) - const previousLog = process.env.TEST_PNPM_LOG - process.env.TEST_PNPM_LOG = log - try { - await manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks()) - } finally { - if (previousLog === undefined) delete process.env.TEST_PNPM_LOG - else process.env.TEST_PNPM_LOG = previousLog - } - - const manifest = JSON.parse(readFileSync(join(paths.profile, 'package.json'), 'utf8')) as { - dependencies: Record - } - const coreSpec = manifest.dependencies['@deepseek-ai/dsh'] - expect(coreSpec).toMatch(/^file:\.\/desktop-packages\//u) - expect(readFileSync(join(paths.profile, 'pnpm-workspace.yaml'), 'utf8')) - .toContain(`${JSON.stringify('@deepseek-ai/dsh')}: ${JSON.stringify(coreSpec)}`) - expect(manifest.dependencies['@scope/plugin']).toBe('2.0.0') - const invocation = JSON.parse(readFileSync(log, 'utf8')) as { args: string[]; env: Record } - expect(invocation.args).toContain('add') - expect(invocation.args).toContain('@scope/plugin@2.0.0') - expect(invocation.args).toContain('--config.registry=https://registry.npmjs.org/') - expect(invocation.env.NPM_CONFIG_REGISTRY).toBe('https://registry.npmjs.org/') - }) - - it('reconciles dsh to the packaged release without removing desktop plugins', async () => { - const root = temporaryRoot() - const paths = resolveDesktopPaths(join(root, '.dsh')) - const manager = new DesktopProjectManager(paths, { node: process.execPath, pnpm: writeFakePnpm(root) }) - const firstSeed = join(root, 'seed-1') - createTestSeedMetadata(firstSeed, release('1.0.0')) - writeFileSync(join(firstSeed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') - mkdirSync(join(firstSeed, 'store'), { recursive: true }) - writeFileSync(join(firstSeed, 'store', 'release-1'), 'one') - archiveStore(firstSeed) - writeIntegrity(firstSeed) - await manager.applyRelease(firstSeed, '1.0.0', hooks()) - await manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks()) - - const nextSeed = join(root, 'seed-2') - createTestSeedMetadata(nextSeed, release('1.1.0')) - writeFileSync(join(nextSeed, 'pnpm-lock.yaml'), 'lockfileVersion: 9\n') - mkdirSync(join(nextSeed, 'store'), { recursive: true }) - writeFileSync(join(nextSeed, 'store', 'release-2'), 'two') - archiveStore(nextSeed) - writeIntegrity(nextSeed) - - await expect(manager.applyRelease(nextSeed, '1.1.0', hooks())).resolves.toBe(true) - expect(manager.releaseVersion()).toBe('1.1.0') - expect(manager.dshVersion()).toBe('1.1.0') - expect(manager.listPlugins()).toEqual([{ name: '@scope/plugin', version: '2.0.0' }]) - const profile = JSON.parse(readFileSync(join(paths.profile, 'package.json'), 'utf8')) as { - dsh: { profile: { bundles: string[] } } - } - expect(profile.dsh.profile.bundles).toEqual([ - '@deepseek-ai/dsh-base', - '@deepseek-ai/dsh-web-app', - '@scope/plugin', + expect(manager.listPlugins()).toEqual([{ name: '@scope/plugin', version: '2.0.0', enabled: true }]) + expect(calls(root).map(call => call.args.filter(arg => !arg.startsWith('--config.')))).toEqual([ + ['add', '@scope/plugin@2.0.0', '--save-exact', '--ignore-scripts'], ['rebuild', '--pending'], ]) - expect(readFileSync(join(paths.pnpm.store, 'release-1'), 'utf8')).toBe('one') - expect(readFileSync(join(paths.pnpm.store, 'release-2'), 'utf8')).toBe('two') - await expect(manager.applyRelease(nextSeed, '1.1.0', hooks())).resolves.toBe(false) + expect(calls(root).every(call => call.registry === 'https://registry.npmjs.org/')).toBe(true) + expect(JSON.parse(readFileSync(join(manager.paths.profile, 'package.json'), 'utf8'))).toMatchObject({ dependencies: { '@scope/plugin': '2.0.0' } }) + await expect(manager.mutate({ type: 'plugin-add', spec: '@deepseek-ai/cordis' }, hooks())).rejects.toThrow(/host-owned/u) + }) + + it('retains disabled plugin versions through updates and enables them explicitly', async () => { + const { root, manager } = setup() + await manager.applyRelease('1.0.0', hooks()) + await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + await manager.mutate({ type: 'plugins-disable-all' }, hooks()) + expect(calls(root)).toHaveLength(2) + expect(manager.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: false }]) + await manager.mutate({ type: 'plugin-update', name: 'plugin', version: '1.1.0' }, hooks()) + expect(manager.listPlugins()).toEqual([{ name: 'plugin', version: '1.1.0', enabled: false }]) + await manager.mutate({ type: 'plugin-toggle', name: 'plugin', enabled: true }, hooks()) + expect(manager.listPlugins()[0]?.enabled).toBe(true) + await manager.mutate({ type: 'plugin-remove', name: 'plugin' }, hooks()) + expect(manager.listPlugins()).toEqual([]) + }) + + it('keeps plugin files and patches through a compatible release and application relocation', async () => { + const { root, manager } = setup() + await manager.applyRelease('1.0.0', hooks()) + await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + writeFileSync(join(manager.paths.profile, 'cordis.patch.yml'), '[]\n') + const nextRoot = join(root, 'relocated', 'dsh') + runtimeFixture(nextRoot, '1.1.0') + const next = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh: nextRoot }) + await expect(next.applyRelease('1.1.0', hooks())).resolves.toBe(true) + expect(next.listPlugins()).toEqual(manager.listPlugins()) + expect(next.releaseVersion()).toBe('1.1.0') + expect(readFileSync(join(manager.paths.profile, 'cordis.patch.yml'), 'utf8')).toBe('[]\n') + expect(calls(root)).toHaveLength(2) + expect(realpathSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis'))).toBe(realpathSync(join(nextRoot, 'node_modules/@deepseek-ai/cordis'))) + writeFileSync(join(manager.paths.rollback, 'node_modules/plugin/bundle.yml'), 'rollback only') + expect(readFileSync(join(manager.paths.profile, 'node_modules/plugin/bundle.yml'), 'utf8')).toBe('[]\n') + }) + + it('reinstalls the locked plugin graph when bundled Node changes', async () => { + const { root, manager } = setup() + await manager.applyRelease('1.0.0', hooks()) + await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + const dsh = join(root, 'new-node') + runtimeFixture(dsh, '1.1.0', '24.18.0') + const next = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh }) + await next.applyRelease('1.1.0', hooks()) + expect(calls(root).slice(2).map(call => call.args.filter(arg => !arg.startsWith('--config.')))).toEqual([ + ['install', '--frozen-lockfile', '--ignore-scripts'], ['rebuild', '--pending'], + ]) + expect(next.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: true }]) + }) + + it('allows incompatible plugins to be disabled in recovery without deleting them', async () => { + const { root, manager } = setup() + await manager.applyRelease('1.0.0', hooks()) + await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + const dsh = join(root, 'next-major') + runtimeFixture(dsh, '2.0.0') + const next = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh }) + await expect(next.applyRelease('2.0.0', hooks())).rejects.toThrow(/requires @deepseek-ai\/cordis/u) + expect(next.releaseVersion()).toBe('1.0.0') + expect(() =>{ next.assertProfileRuntime(manager.paths.profile) }).toThrow(/does not match/u) + await next.mutate({ type: 'plugins-disable-all' }, hooks()) + expect(next.releaseVersion()).toBe('2.0.0') + expect(next.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: false }]) + }) + + it.each(['health', 'before', 'after'] as const)('keeps the active profile when %s activation fails', async (phase) => { + const { manager } = setup() + await manager.applyRelease('1.0.0', hooks()) + let starts = 0 + await expect(manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks({ + healthCheck: async () => { if (phase === 'health') throw new Error('health failed') }, + beforeActivate: async () => { if (phase === 'before') throw new Error('before failed') }, + afterActivate: async () => { if (phase === 'after' && starts++ === 0) throw new Error('after failed') }, + }))).rejects.toThrow(`${phase} failed`) + expect(manager.listPlugins()).toEqual([]) + expect(existsSync(manager.paths.pending)).toBe(false) + }) + + it('recovers a directory move using recorded runtime identities', async () => { + const { manager } = setup() + await manager.applyRelease('1.0.0', hooks()) + const id = readDesktopProfileState(manager.paths.profile)?.runtimeId + const stagingProfile = join(manager.paths.staging, 'interrupted', 'profile') + mkdirSync(stagingProfile, { recursive: true }) + mkdirSync(dirname(manager.paths.rollback), { recursive: true }) + renameSync(manager.paths.profile, manager.paths.rollback) + writeFileSync(manager.paths.pending, JSON.stringify({ schemaVersion: 1, id: 'interrupted', stagingProfile, fromRuntimeId: id, toRuntimeId: id, step: 'active-moved' })) + manager.recover() + expect(manager.releaseVersion()).toBe('1.0.0') + expect(existsSync(stagingProfile)).toBe(false) + expect(existsSync(manager.paths.pending)).toBe(false) + }) + + it('holds the transaction lock until the pnpm worker exits', async () => { + const { root, manager } = setup() + await manager.applyRelease('1.0.0', hooks()) + const ready = join(root, 'ready') + const release = join(root, 'release') + const blocker = join(root, 'blocking.mjs') + writeFileSync(blocker, `import {existsSync, writeFileSync} from 'node:fs'; import {setTimeout as sleep} from 'node:timers/promises'; writeFileSync(${JSON.stringify(ready)}, String(process.pid)); while (!existsSync(${JSON.stringify(release)})) await sleep(10); await import(${JSON.stringify(pathToFileURL(manager.runtime.pnpm).href)})`) + const worker = new DesktopProjectManager(manager.paths, { ...manager.runtime, pnpm: blocker }) + await worker.applyRelease('1.0.0', hooks()) + const pending = worker.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + try { + await expect.poll(() => existsSync(ready)).toBe(true) + expect(readFileSync(manager.paths.lock, 'utf8').trim()).toBe(readFileSync(ready, 'utf8')) + await expect(manager.applyRelease('1.0.0', hooks())).rejects.toThrow(/another package transaction/u) + } finally { + writeFileSync(release, 'continue') + await pending + } + expect(existsSync(manager.paths.lock)).toBe(false) }) }) diff --git a/apps/desktop/tests/runtime-fixture.ts b/apps/desktop/tests/runtime-fixture.ts new file mode 100644 index 0000000000..81648dfc5f --- /dev/null +++ b/apps/desktop/tests/runtime-fixture.ts @@ -0,0 +1,42 @@ +/** Temporary materialized packages for Desktop resource and profile behavior tests. */ + +import { mkdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { DESKTOP_HOST_RUNTIME_FILES } from '../src/core-package-set.ts' +import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts' +import { writeDesktopRuntime, type DesktopRuntimeDescriptor } from '../src/runtime-tree.ts' + +/** + * Write a package fixture with explicit runtime exports. + * @param modules - Owning node_modules directory. + * @param name - Package name. + * @param fields - Manifest fields. + * @param source - ESM entry contents. + * @returns Installed package directory. + */ +export function writePackage(modules: string, name: string, fields: Record = {}, source = 'export const identity = {}\n'): string { + const path = join(modules, name) + mkdirSync(path, { recursive: true }) + writeFileSync(join(path, 'package.json'), JSON.stringify({ name, version: '1.0.0', type: 'module', exports: './index.js', ...fields })) + writeFileSync(join(path, 'index.js'), source) + return path +} + +/** + * Seal a minimal release containing Host entry files and a shared Cordis package. + * @param root - New runtime directory. + * @param version - Shell and dsh version. + * @param nodeVersion - Bundled Node version used for native rebuild selection. + * @returns Sealed runtime metadata. + */ +export function runtimeFixture(root: string, version = '1.0.0', nodeVersion = '24.17.0'): DesktopRuntimeDescriptor { + const names = ['@deepseek-ai/dsh', '@deepseek-ai/dsh-desktop-host', '@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@deepseek-ai/cordis'] + for (const name of names) writePackage(join(root, 'node_modules'), name, { version }) + for (const file of DESKTOP_HOST_RUNTIME_FILES) { + const path = join(root, 'node_modules', '@deepseek-ai/dsh-desktop-host', file) + mkdirSync(join(path, '..'), { recursive: true }) + writeFileSync(path, '') + } + writeFileSync(join(root, 'package.json'), '{"type":"module"}\n') + return writeDesktopRuntime(root, { schemaVersion: 1, version, nodeVersion, pnpmVersion: '11.7.0', hostProtocolVersion: DESKTOP_HOST_PROTOCOL_VERSION }, names) +} diff --git a/apps/desktop/tests/runtime-tree.spec.ts b/apps/desktop/tests/runtime-tree.spec.ts new file mode 100644 index 0000000000..4c4dddf52e --- /dev/null +++ b/apps/desktop/tests/runtime-tree.spec.ts @@ -0,0 +1,46 @@ +import { cpSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { DESKTOP_RUNTIME_FILE, desktopRuntimeId, runtimePath, verifyDesktopRuntime } from '../src/runtime-tree.ts' +import { runtimeFixture } from './runtime-fixture.ts' + +const roots: string[] = [] +function fixture(): string { + const root = mkdtempSync(join(tmpdir(), 'desktop-runtime-')) + roots.push(root) + runtimeFixture(join(root, 'dsh')) + return root +} +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) + +it('verifies a runtime after relocation without depending on build paths', () => { + const root = fixture() + const before = verifyDesktopRuntime(join(root, 'dsh'), '1.0.0') + cpSync(join(root, 'dsh'), join(root, 'moved'), { recursive: true }) + expect(desktopRuntimeId(verifyDesktopRuntime(join(root, 'moved'), '1.0.0'))).toBe(desktopRuntimeId(before)) +}) +it.each(['changed', 'extra', 'missing'])('rejects %s runtime bytes', (operation) => { + const dsh = join(fixture(), 'dsh') + if (operation === 'changed') writeFileSync(join(dsh, 'package.json'), '{}') + if (operation === 'extra') writeFileSync(join(dsh, 'extra'), '') + if (operation === 'missing') rmSync(join(dsh, 'package.json')) + expect(() => verifyDesktopRuntime(dsh, '1.0.0')).toThrow(/integrity/u) +}) +it('rejects filesystem links and incompatible targets', () => { + const dsh = join(fixture(), 'dsh') + expect(() => verifyDesktopRuntime(dsh, '1.0.0', { platform: process.platform, arch: 'wrong' })).toThrow(/incompatible/u) + symlinkSync(join(dsh, 'node_modules'), join(dsh, 'outside'), process.platform === 'win32' ? 'junction' : 'dir') + expect(() => verifyDesktopRuntime(dsh, '1.0.0')).toThrow(/unsupported filesystem/u) +}) +it('rejects a descriptor that maps a shared package outside node_modules', () => { + const dsh = join(fixture(), 'dsh') + const path = join(dsh, DESKTOP_RUNTIME_FILE) + const descriptor = JSON.parse(readFileSync(path, 'utf8')) as { sharedPackages: { path: string }[] } + descriptor.sharedPackages[0]!.path = '../outside' + writeFileSync(path, JSON.stringify(descriptor)) + expect(() => verifyDesktopRuntime(dsh, '1.0.0')).toThrow(/shared package record/u) +}) +it.each(['../outside', '/absolute', 'C:/absolute', 'a\\b', 'a//b', './a'])('rejects nonportable path %s', (path) => { + expect(() => runtimePath('/runtime', path)).toThrow(/invalid relative path/u) +}) diff --git a/apps/desktop/tests/seed-store.spec.ts b/apps/desktop/tests/seed-store.spec.ts deleted file mode 100644 index b2f5fc614a..0000000000 --- a/apps/desktop/tests/seed-store.spec.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { - chmodSync, - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - readdirSync, - rmSync, - statSync, - utimesSync, - writeFileSync, -} from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { DatabaseSync } from 'node:sqlite' -import { afterEach, describe, expect, it } from 'vitest' -import { - archivePnpmStore, - extractPnpmStoreArchives, - mergePnpmStore, - removePnpmProjectRegistrations, - SEED_STORE_ARCHIVE_DIR, - SEED_STORE_ARCHIVE_MANIFEST, -} from '../src/seed-store.ts' - -const temporaryRoots: string[] = [] - -function temporaryRoot(): string { - const root = mkdtempSync(join(tmpdir(), 'dsh-desktop-store-')) - temporaryRoots.push(root) - return root -} - -function archiveBytes(seed: string): readonly { path: string; body: Buffer }[] { - return [SEED_STORE_ARCHIVE_MANIFEST, ...readdirSync(join(seed, SEED_STORE_ARCHIVE_DIR))] - .map(path => ({ - path, - body: readFileSync(path === SEED_STORE_ARCHIVE_MANIFEST - ? join(seed, path) - : join(seed, SEED_STORE_ARCHIVE_DIR, path)), - })) -} - -afterEach(() => { - for (const root of temporaryRoots.splice(0)) rmSync(root, { recursive: true, force: true }) -}) - -describe('desktop seed store cleanup', () => { - it('removes project registrations without removing package data', () => { - const storeRoot = temporaryRoot() - mkdirSync(join(storeRoot, 'v11', 'projects', 'temporary-project'), { recursive: true }) - mkdirSync(join(storeRoot, 'v12', 'projects'), { recursive: true }) - mkdirSync(join(storeRoot, 'metadata', 'projects'), { recursive: true }) - writeFileSync(join(storeRoot, 'v11', 'package-data'), 'package') - - removePnpmProjectRegistrations(storeRoot) - - expect(existsSync(join(storeRoot, 'v11', 'projects'))).toBe(false) - expect(existsSync(join(storeRoot, 'v12', 'projects'))).toBe(false) - expect(existsSync(join(storeRoot, 'v11', 'package-data'))).toBe(true) - expect(existsSync(join(storeRoot, 'metadata', 'projects'))).toBe(true) - }) -}) - -describe('desktop seed store merge', () => { - it('preserves installed package records while the verified seed replaces matching records and files', () => { - const root = temporaryRoot() - const source = join(root, 'source') - const destination = join(root, 'destination') - for (const store of [source, destination]) { - mkdirSync(join(store, 'v11', 'files'), { recursive: true }) - const database = new DatabaseSync(join(store, 'v11', 'index.db')) - database.exec('CREATE TABLE package_index (key TEXT PRIMARY KEY, data BLOB NOT NULL) WITHOUT ROWID') - const insert = database.prepare('INSERT INTO package_index (key, data) VALUES (?, ?)') - if (store === source) { - insert.run('seed-only', Buffer.from('seed')) - insert.run('shared', Buffer.from('new')) - } else { - insert.run('plugin-only', Buffer.from('plugin')) - insert.run('shared', Buffer.from('old')) - } - database.close() - } - writeFileSync(join(source, 'v11', 'files', 'shared'), 'new') - writeFileSync(join(destination, 'v11', 'files', 'shared'), 'old') - writeFileSync(join(destination, 'v11', 'files', 'plugin'), 'plugin') - - mergePnpmStore(source, destination) - - const database = new DatabaseSync(join(destination, 'v11', 'index.db'), { readOnly: true }) - const records = database.prepare('SELECT key, data FROM package_index ORDER BY key').all() as { - key: string - data: Uint8Array - }[] - database.close() - expect(records.map(record => [record.key, Buffer.from(record.data).toString()])).toEqual([ - ['plugin-only', 'plugin'], - ['seed-only', 'seed'], - ['shared', 'new'], - ]) - expect(readFileSync(join(destination, 'v11', 'files', 'shared'), 'utf8')).toBe('new') - expect(readFileSync(join(destination, 'v11', 'files', 'plugin'), 'utf8')).toBe('plugin') - }) -}) - -describe('desktop seed store archives', () => { - it('extracts package bytes and executable modes without retaining loose seed files', () => { - const root = temporaryRoot() - const seed = join(root, 'seed') - const store = join(seed, 'store') - const executable = join(store, 'v10', 'files', 'native-addon') - mkdirSync(join(store, 'v10', 'files'), { recursive: true }) - writeFileSync(executable, 'native') - chmodSync(executable, 0o755) - writeFileSync(join(store, 'v10', 'files', 'package-data'), 'package') - - archivePnpmStore(seed, store) - const destination = join(root, 'extracted') - extractPnpmStoreArchives(seed, destination) - - expect(existsSync(store)).toBe(false) - expect(readFileSync(join(destination, 'v10', 'files', 'package-data'), 'utf8')).toBe('package') - if (process.platform !== 'win32') { - expect(statSync(join(destination, 'v10', 'files', 'native-addon')).mode & 0o111).toBe(0o111) - } - }) - - it('produces identical shards for identical paths, bytes, and modes', () => { - const root = temporaryRoot() - const seeds = [join(root, 'first'), join(root, 'second')] - for (const [index, seed] of seeds.entries()) { - const store = join(seed, 'store') - mkdirSync(join(store, 'nested'), { recursive: true }) - const paths = index === 0 ? ['alpha', 'nested/beta'] : ['nested/beta', 'alpha'] - for (const path of paths) { - const target = join(store, path) - writeFileSync(target, path) - utimesSync(target, new Date(index * 10_000), new Date(index * 20_000)) - } - archivePnpmStore(seed, store) - } - - const first = archiveBytes(seeds[0] as string) - const second = archiveBytes(seeds[1] as string) - expect(second.map(entry => entry.path)).toEqual(first.map(entry => entry.path)) - expect(second.map(entry => entry.body)).toEqual(first.map(entry => entry.body)) - }) - - it('rejects an archive whose entry count differs from the manifest', () => { - const root = temporaryRoot() - const seed = join(root, 'seed') - const store = join(seed, 'store') - mkdirSync(store, { recursive: true }) - writeFileSync(join(store, 'package-data'), 'package') - archivePnpmStore(seed, store) - const manifestPath = join(seed, SEED_STORE_ARCHIVE_MANIFEST) - const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { - archives: { entries: number }[] - } - const archive = manifest.archives[0] - if (archive === undefined) throw new Error('test seed has no archive') - archive.entries += 1 - writeFileSync(manifestPath, JSON.stringify(manifest)) - - expect(() => { extractPnpmStoreArchives(seed, join(root, 'extracted')) }).toThrow(/unexpected entry count/u) - }) -}) diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index fd58c7ae00..be8ba71a94 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.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 docs/architecture.md -architecture.md: a77dfd06c61cbb12d7008133a7e8d515a3449a02 -architecture.zh.md: 83fa958609500cc85af9c0d1f7e339104f6c18c7 +architecture.md: cdd9686261221ffcba7e4991ec4f93bc4e4559f1 +architecture.zh.md: 2cd1b0781e1a56f05d53ba9035542102b15971a9 diff --git a/docs/architecture.md b/docs/architecture.md index a77dfd06c6..cdd9686261 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -48,9 +48,9 @@ The Python SDK follows the same application architecture. Its runtime wheel pack ## Desktop application -The [Electron desktop application](../apps/desktop/README.md) owns the reserved `$DSH_HOME/profiles/desktop` npm project. Each signed Electron release binds one exact dsh version and carries a first-party offline seed; startup installs that version into the writable profile with the bundled pnpm, while retaining exact desktop-plugin versions from the previous profile. CLI profiles share supported product data under `$DSH_HOME`, but never executable packages, plugin activation, lockfiles, or `node_modules` with Desktop. +The [Electron desktop application](../apps/desktop/README.md) carries its exact dsh production runtime in signed application resources. The reserved `$DSH_HOME/profiles/desktop` contains external plugins and links to host-owned packages; compatible upgrades retain plugin files and refresh these links without installing core dependencies. CLI profiles share supported product data under `$DSH_HOME`, while executable packages, plugin activation, lockfiles, and package-manager state remain separate. -Electron starts the private Desktop Host package under its bundled upstream Node.js process; that package loads the installed dsh backend and matching client graph from the reserved profile. Unary RPC, Remote streams, and version-matched client assets cross versioned framed byte pipes with Node IPC reserved for lifecycle control, then reach the renderer through the secure `dsh-app://` protocol; the desktop composition opens no Web server or loopback port. Only shell-owned UI can run plugin transactions through the bundled pnpm and its private `$DSH_HOME/desktop/pnpm/store`. +Electron starts the private Desktop Host package under its bundled upstream Node.js process; that package loads the bundled dsh backend and matching client graph together with enabled profile plugins. Unary RPC, Remote streams, and version-matched client assets cross versioned framed byte pipes with Node IPC reserved for lifecycle control, then reach the renderer through the secure `dsh-app://` protocol; the desktop composition opens no Web server or loopback port. Only shell-owned UI can run plugin transactions through the bundled pnpm and its private `$DSH_HOME/desktop/pnpm/store`. ## Core packages diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 83fa958609..2cd1b0781e 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -48,9 +48,9 @@ Python SDK 遵循相同的应用架构。其运行时 wheel 把普通 `dsh` CLI ## 桌面应用 -[Electron 桌面应用](../apps/desktop/README.zh.md)持有保留的 `$DSH_HOME/profiles/desktop` npm 项目。每个签名 Electron 发行版绑定一个确切 dsh 版本并携带第一方离线 seed;启动时通过内置 pnpm 把该版本安装进可写 profile,同时保留旧 profile 中桌面插件的确切版本。CLI profile 与 Desktop 共享 `$DSH_HOME` 下受支持的产品数据,但绝不共享可执行包、插件激活、lockfile 或 `node_modules`。 +[Electron 桌面应用](../apps/desktop/README.zh.md)在签名应用资源中携带精确版本的 dsh 生产运行时。保留的 `$DSH_HOME/profiles/desktop` 保存外部插件和指向宿主拥有包的链接;兼容升级保留插件文件并刷新这些链接,无需安装核心依赖。CLI profile 共享 `$DSH_HOME` 下受支持的产品数据,而可执行包、插件激活、锁文件和包管理器状态保持独立。 -Electron 通过内置的上游 Node.js 进程启动私有 Desktop Host 包;该包从保留 profile 加载已安装的 dsh 后端与匹配的客户端图。一元 RPC、Remote stream 与版本匹配的客户端资源经带版本的分帧字节管道传输,Node IPC 只保留生命周期控制,再通过安全的 `dsh-app://` 协议到达渲染进程;因此桌面组合不会开放 Web server 或 loopback 端口。只有壳自有 UI 能通过内置 pnpm 及其私有 `$DSH_HOME/desktop/pnpm/store` 执行插件事务。 +Electron 通过内置的上游 Node.js 进程启动私有 Desktop Host 包;该包加载内置 dsh 后端、匹配的客户端图和已启用的 profile 插件。一元 RPC、Remote stream 与版本匹配的客户端资源经带版本的分帧字节管道传输,Node IPC 只保留生命周期控制,再通过安全的 `dsh-app://` 协议到达渲染进程;因此桌面组合不会开放 Web server 或 loopback 端口。只有壳自有 UI 能通过内置 pnpm 及其私有 `$DSH_HOME/desktop/pnpm/store` 执行插件事务。 ## 核心包 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3dc0fc3a72..a2c6b9edb8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -525,9 +525,6 @@ importers: js-yaml: specifier: ^4.2.0 version: 4.3.1 - msgpackr: - specifier: 2.0.4 - version: 2.0.4 pnpm: specifier: 11.7.0 version: 11.7.0 @@ -12688,36 +12685,6 @@ packages: resolution: {integrity: sha512-Mmjg4anFBD5OzbPnGJOA0jPPN8645ERhQk38HQLpSenx1ox9bfdPkmAzUnNjeQtqQGFLtKe13J20RtLBmUKMZA==} hasBin: true - '@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4': - resolution: {integrity: sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ==} - cpu: [arm64] - os: [darwin] - - '@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4': - resolution: {integrity: sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w==} - cpu: [x64] - os: [darwin] - - '@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4': - resolution: {integrity: sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw==} - cpu: [arm64] - os: [linux] - - '@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4': - resolution: {integrity: sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw==} - cpu: [arm] - os: [linux] - - '@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4': - resolution: {integrity: sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ==} - cpu: [x64] - os: [linux] - - '@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4': - resolution: {integrity: sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ==} - cpu: [x64] - os: [win32] - '@napi-rs/wasm-runtime@1.1.5': resolution: {integrity: sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==} peerDependencies: @@ -16331,13 +16298,6 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - msgpackr-extract@3.0.4: - resolution: {integrity: sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==} - hasBin: true - - msgpackr@2.0.4: - resolution: {integrity: sha512-o1C5KRmuRt+apqMr1HuGSqWStZoRBUpEsCsl15uM9VdAF1qHLtvMOU2En747EnTyEl6c4pzPewRMFF31s1CNbA==} - multistream@4.1.0: resolution: {integrity: sha512-J1XDiAmmNpRCBfIWJv+n0ymC4ABcf/Pl+5YvC5B/D2f/2+8PtHvCNxMPKiQcZyi922Hq69J2YOpb1pTywfifyw==} @@ -16438,10 +16398,6 @@ packages: resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - node-gyp-build-optional-packages@5.2.2: - resolution: {integrity: sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==} - hasBin: true - node-gyp@12.4.0: resolution: {integrity: sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==} engines: {node: ^20.17.0 || >=22.9.0} @@ -17149,13 +17105,13 @@ packages: stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + standardwebhooks@1.1.1: + resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==} + stat-mode@1.0.0: resolution: {integrity: sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==} engines: {node: '>= 6'} - standardwebhooks@1.1.1: - resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==} - statuses@2.0.2: resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} engines: {node: '>= 0.8'} @@ -19433,24 +19389,6 @@ snapshots: - supports-color - zod - '@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4': - optional: true - - '@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4': - optional: true - - '@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4': - optional: true - - '@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4': - optional: true - - '@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4': - optional: true - - '@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4': - optional: true - '@napi-rs/wasm-runtime@1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': dependencies: '@emnapi/core': 1.10.0 @@ -23321,22 +23259,6 @@ snapshots: ms@2.1.3: {} - msgpackr-extract@3.0.4: - dependencies: - node-gyp-build-optional-packages: 5.2.2 - optionalDependencies: - '@msgpackr-extract/msgpackr-extract-darwin-arm64': 3.0.4 - '@msgpackr-extract/msgpackr-extract-darwin-x64': 3.0.4 - '@msgpackr-extract/msgpackr-extract-linux-arm': 3.0.4 - '@msgpackr-extract/msgpackr-extract-linux-arm64': 3.0.4 - '@msgpackr-extract/msgpackr-extract-linux-x64': 3.0.4 - '@msgpackr-extract/msgpackr-extract-win32-x64': 3.0.4 - optional: true - - msgpackr@2.0.4: - optionalDependencies: - msgpackr-extract: 3.0.4 - multistream@4.1.0: dependencies: once: 1.4.0 @@ -23425,11 +23347,6 @@ snapshots: fetch-blob: 3.2.0 formdata-polyfill: 4.0.10 - node-gyp-build-optional-packages@5.2.2: - dependencies: - detect-libc: 2.1.2 - optional: true - node-gyp@12.4.0: dependencies: env-paths: 2.2.1 From 8874a23b9eaa93d2ed39effdce1dfbef0cf6b376 Mon Sep 17 00:00:00 2001 From: 07akioni <07akioni2@gmail.com> Date: Tue, 8 Sep 2026 17:44:05 +0800 Subject: [PATCH 05/52] =?UTF-8?q?feat:=20=E5=8A=A0=E9=80=9F=20mac=20sign?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...on-desktop-packaging-and-updates.i18n.yaml | 4 +-- ...-electron-desktop-packaging-and-updates.md | 2 ++ ...ectron-desktop-packaging-and-updates.zh.md | 2 ++ apps/desktop/README.i18n.yaml | 4 +-- apps/desktop/README.md | 2 ++ apps/desktop/README.zh.md | 2 ++ apps/desktop/electron-builder.config.mjs | 4 +-- apps/desktop/tests/macos-signature.spec.ts | 17 ++++++++- apps/desktop/tests/macos-signing-walk.spec.ts | 36 +++++++++++++++++++ patches/@electron__osx-sign@1.3.3.patch | 26 ++++++++++++++ pnpm-lock.yaml | 5 +-- pnpm-workspace.yaml | 1 + 12 files changed, 96 insertions(+), 9 deletions(-) create mode 100644 apps/desktop/tests/macos-signing-walk.spec.ts create mode 100644 patches/@electron__osx-sign@1.3.3.patch diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml index e0081b64f5..fe1bf84c1b 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.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-25-electron-desktop-packaging-and-updates.md -2026-08-25-electron-desktop-packaging-and-updates.md: fea2c419d73e4eff66de08483733cbc336b6f9af -2026-08-25-electron-desktop-packaging-and-updates.zh.md: 88e2875cd35909c0111926377df83c9fe21841dc +2026-08-25-electron-desktop-packaging-and-updates.md: d7d41aa4d6154f251b56faaa29065db3ee71071f +2026-08-25-electron-desktop-packaging-and-updates.zh.md: 952ed4fc5546524bc088f58e62faccd576194bc7 diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md index fea2c419d7..d7d41aa4d6 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md @@ -85,6 +85,8 @@ Core dsh and the private Desktop Host come only from the signed application reso Electron artifacts are signed; macOS artifacts are notarized. Release automation must supply the application ID, macOS Developer ID qualifier, expected Team ID, and one complete notarytool credential strategy through explicit environment variables. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS packaging requires signing so certificate discovery cannot silently select another installed identity or emit an unsigned release. Runtime preparation verifies the exact Authority and Team ID plus the timestamp and hardened-runtime flags on every embedded Mach-O file. An after-sign hook performs Apple's deep strict application verification and requires the same leaf Authority and Team ID before artifact creation continues. Electron-builder then notarizes and staples the application and signs the DMG. The DMG artifact-completion hook separately notarizes and staples every DMG before requiring the configured identity, a valid ticket, and Gatekeeper acceptance; the upload event runs only after that hook succeeds. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. +The [pinned osx-sign patch](../../../../patches/@electron__osx-sign@1.3.3.patch) uses `lstat` in both published module builds, so Framework file and directory aliases do not trigger duplicate signing. The patch remains necessary until the selected upstream release skips those aliases. PAK files are resources sealed by the enclosing bundle; individual signatures add serial timestamp requests without additional resource integrity. Desktop preserves all locale files and skips only their standalone signatures. Executable code retains Developer ID signatures, secure timestamps, and hardened runtime. The [signer traversal regression](../../../../apps/desktop/tests/macos-signing-walk.spec.ts) exercises the installed dependency with real Framework aliases; release qualification still requires strict application verification, notarization, and startup. + Windows release packaging supplies the public EV leaf certificate named by `DSH_DESKTOP_WINDOWS_CER_FILE` to the configured SafeNet-compatible SignTool through `/f` and identifies its matching private key through the required `DSH_DESKTOP_WINDOWS_KEY_CONTAINER`. The certificate file remains outside source control, and the private key remains on the USB token. The electron-builder hook passes each artifact to the CRLF `windows-sign.cmd`, whose single SignTool invocation uses the SafeNet `/kc "[{{PIN}}]=container"` value and CSP, a SHA-256 file digest, and a DigiCert SHA-256 RFC 3161 timestamp. The hook never substitutes another SignTool and never retries a failed request. Package orchestration withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation children and passes only the certificate path, SignTool path, key container, and PIN into electron-builder. The signer supplies only validated signing fields in an otherwise scrubbed CMD environment; the CMD disables delayed expansion, clears those fields before SignTool starts, and preserves the PIN only in the required SignTool command line. Every surfaced diagnostic replaces the PIN, and only the dedicated build account and administrators may inspect the runner. The signer signs electron-builder's temporary NSIS bootstrap before enterprise Code Integrity evaluates that executable and clears a generated executable's certificate-table entry only when it points beyond the file before applying the final signature. Packaging fails before producing unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. Packaged applications ignore development resource and project environment overrides. Only an unpackaged Electron process can replace the Node.js binary, pnpm entry, dsh resources, or active project. diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md index 88e2875cd3..952ed4fc55 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md @@ -85,6 +85,8 @@ Electron 更新只使用一个 `electron-updater` 发布流和签名 `electron-b Electron 产物必须签名;macOS 产物必须公证。发布自动化必须通过明确的环境变量提供应用 ID、macOS Developer ID 限定名、预期 Team ID 与一套完整的 notarytool 凭据。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。运行时准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。Electron-builder 随后公证应用并钉票、签署 DMG。DMG 的 artifact-completion hook 会单独公证每个 DMG 并钉票,再要求其使用配置的身份、具备有效票据并通过 Gatekeeper;只有该 hook 成功,上传事件才会执行。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 拥有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 +[固定版本的 osx-sign 补丁](../../../../patches/@electron__osx-sign@1.3.3.patch)在两种已发布模块构建中使用 `lstat`,因此 Framework 的文件和目录别名不会触发重复签名。选定的上游版本能够跳过这些别名前,仍需保留该补丁。PAK 文件由外层 bundle 签名记录完整性;逐个签名会增加串行时间戳请求,但不会增加资源完整性保护。Desktop 保留全部语言文件,只跳过其单独签名。可执行代码仍使用 Developer ID 签名、安全时间戳和 hardened runtime。[签名器遍历回归测试](../../../../apps/desktop/tests/macos-signing-walk.spec.ts)使用真实 Framework 别名执行已安装依赖;发布验收仍要求严格应用验证、公证和启动。 + Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool 提供 `DSH_DESKTOP_WINDOWS_CER_FILE` 指定的公开 EV 叶证书,并通过必需的 `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` 标识匹配的私钥。证书文件保留在源码仓库之外,私钥仍留在 USB Token 上。electron-builder hook 把每个产物交给采用 CRLF 的 `windows-sign.cmd`;该 CMD 只调用一次 SignTool,并指定 SafeNet `/kc "[{{PIN}}]=容器"` 值与 CSP、SHA-256 文件摘要和 DigiCert SHA-256 RFC 3161 时间戳。hook 不会改用其他 SignTool,也不会重试失败的请求。打包编排不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程,只会把证书路径、SignTool 路径、密钥容器和 PIN 传入 electron-builder。签名器在已清理的 CMD 环境中只提供经过校验的签名字段;CMD 会禁用延迟展开,在 SignTool 启动前清除这些字段,并仅在 SignTool 必需的命令行中保留 PIN。所有对外诊断都会替换 PIN,而且只能允许专用构建账号和管理员检查该 runner。签名器会在企业 Code Integrity 检查 electron-builder 的临时 NSIS bootstrap 前先为该可执行文件签名;对于生成的可执行文件,只有证书表条目指向文件末尾之外时,才会在最终签名前清除该条目。SignTool、证书、容器、PIN、Token 或签名不可用时,打包会在产生未签名产物前失败。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 持有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 打包应用会忽略开发资源和项目环境变量覆盖。只有未打包的 Electron 进程可以替换 Node.js 可执行文件、pnpm 入口、dsh 资源 或活跃项目。 diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 123b44f866..30b7fcabe7 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: b2a51010dc37bcca7c7846819b72ababdc227496 -README.zh.md: 241a1e1d900fef49042a7526d29fc473ef568088 +README.md: 6ef18d302531beb80877f23d657d8524ff396b2b +README.zh.md: 94669b2697af894f91f33068526a0c61d6ed7a8f diff --git a/apps/desktop/README.md b/apps/desktop/README.md index b2a51010dc..6ef18d3025 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -117,6 +117,8 @@ Set `DSH_DESKTOP_AUTO_UPDATE_ENV=production` before packaging, then provide `DOW The macOS configuration uses the required release environment instead of accepting whichever certificate appears first in a keychain. It rejects empty values, a malformed Team ID, a signing identity that includes electron-builder's unsupported `Developer ID Application:` prefix, and incomplete notarization credentials. macOS packaging requires the configured identity and its private key. Runtime preparation applies that identity, a secure timestamp, and hardened runtime to every embedded Mach-O file; after signing the application, a deep strict check rejects any other leaf authority or Team ID before artifact creation. Electron-builder notarizes and staples the application before packaging and signs the DMG. The DMG artifact-completion hook then notarizes and staples it before requiring its exact identity, ticket, and Gatekeeper acceptance; only after the hook succeeds can electron-builder publish the file. The private key can come from the login keychain or electron-builder's standard `CSC_LINK` input; ambient `CSC_NAME` and certificate discovery order do not select the release owner. Notary credentials may instead use electron-builder's complete Apple ID or keychain-profile strategy. The two macOS identity variables are also required when repeating the application check manually with `pnpm --dir apps/desktop run verify:mac-signature -- `. +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. + ### Windows EV signing Windows release packaging requires `DSH_DESKTOP_WINDOWS_CER_FILE` to identify the public GlobalSign EV leaf certificate, `DSH_DESKTOP_WINDOWS_SIGNTOOL` to identify the SafeNet-compatible SignTool executable, `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` to identify the matching private-key container, and `DSH_DESKTOP_WINDOWS_TOKEN_PIN` to contain the SafeNet Token Password. The certificate file remains outside source control, and the matching private key stays on the USB token. Set the four inputs before running the fixed Windows target: diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 241a1e1d90..94669b2697 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -117,6 +117,8 @@ pnpm run upload:mac:arm64 macOS 配置使用必填发布环境,不会接受钥匙串中最先发现的证书。空值、格式错误的 Team ID、包含 electron-builder 不支持的 `Developer ID Application:` 前缀的签名身份,以及不完整的公证凭据都会被拒绝。macOS 打包要求已配置的身份及其私钥可用。运行时准备会把该身份、安全时间戳与 hardened runtime 应用到每个内嵌 Mach-O 文件;应用签名完成后,深度严格检查会拒绝其他叶证书 Authority 或 Team ID,验证通过才生成发布产物。Electron-builder 会在封装前公证应用并钉票,然后签署 DMG。DMG 的 artifact-completion hook 随后会公证它并钉票,再要求其身份、票据与 Gatekeeper 验证全部通过;只有 hook 成功,electron-builder 才能发布该文件。私钥可以来自登录钥匙串或 electron-builder 的标准 `CSC_LINK` 输入;环境中的 `CSC_NAME` 与证书发现顺序都不能选择发布所有者。公证凭据也可以使用 electron-builder 支持的完整 Apple ID 或钥匙串 profile 方式。手动执行 `pnpm --dir apps/desktop run verify:mac-signature -- ` 重复应用检查时,也必须提供两个 macOS 身份变量。 +macOS 签名遍历真实文件,不跟随 Framework 的软链接别名。PAK 资源保留全部随附语言,由外层 Framework 或应用签名记录完整性,不逐个签名。[发布策略](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)负责依赖补丁和验证要求。 + ### Windows EV 签名 Windows 发布打包要求 `DSH_DESKTOP_WINDOWS_CER_FILE` 标识公开的 GlobalSign EV 叶证书,要求 `DSH_DESKTOP_WINDOWS_SIGNTOOL` 标识与 SafeNet 兼容的 SignTool 可执行文件,要求 `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` 标识匹配的私钥容器,并要求 `DSH_DESKTOP_WINDOWS_TOKEN_PIN` 包含 SafeNet Token Password。证书文件保留在源码仓库之外,匹配的私钥仍位于 USB Token。运行固定 Windows 目标前设置这四个输入: diff --git a/apps/desktop/electron-builder.config.mjs b/apps/desktop/electron-builder.config.mjs index d082658695..aee7a5b375 100644 --- a/apps/desktop/electron-builder.config.mjs +++ b/apps/desktop/electron-builder.config.mjs @@ -69,8 +69,8 @@ export function createElectronBuilderConfig( identity: macOSSigning?.signingIdentity, forceCodeSigning: true, hardenedRuntime: true, - // Runtime files are signed before their integrity inventory is sealed. - signIgnore: ['/Contents/Resources/dsh(?:/|$)'], + // Native runtime files are pre-signed; PAK resources are sealed by their enclosing bundle. + signIgnore: ['/Contents/Resources/dsh(?:/|$)', '\\.pak$'], notarize: true, target: ['dmg', 'zip'], }, diff --git a/apps/desktop/tests/macos-signature.spec.ts b/apps/desktop/tests/macos-signature.spec.ts index 09adb91bf1..ada386cc38 100644 --- a/apps/desktop/tests/macos-signature.spec.ts +++ b/apps/desktop/tests/macos-signature.spec.ts @@ -63,7 +63,7 @@ describe('desktop macOS release signature', () => { identity: RELEASE_ENVIRONMENT.DSH_DESKTOP_MACOS_SIGNING_IDENTITY, forceCodeSigning: true, notarize: true, - signIgnore: ['/Contents/Resources/dsh(?:/|$)'], + signIgnore: ['/Contents/Resources/dsh(?:/|$)', '\\.pak$'], }, dmg: { sign: true, @@ -77,6 +77,21 @@ describe('desktop macOS release signature', () => { expect(typeof config.artifactBuildCompleted).toBe('function') }) + it('seals PAK resources with their enclosing bundle while signing executable code', async () => { + const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs') + const config = createElectronBuilderConfig(RELEASE_ENVIRONMENT, 'darwin', 'arm64') + const ignored = (path: string): boolean => config.mac.signIgnore.some(pattern => new RegExp(pattern).test(path)) + expect(ignored('/App.app/Contents/Frameworks/Electron.framework/Versions/A/Resources/en.lproj/locale.pak')).toBe(true) + expect(ignored('/App.app/Contents/Frameworks/Electron.framework/Versions/A/Resources/resources.pak')).toBe(true) + for (const path of [ + '/App.app/Contents/Resources/runtime/node/node', + '/App.app/Contents/Resources/runtime/pnpm/addon.node', + '/App.app/Contents/Frameworks/Electron.framework/Versions/A/library.dylib', + '/App.app/Contents/Frameworks/Electron.framework', + '/App.app', + ]) expect(ignored(path)).toBe(false) + }) + it('copies the complete runtime despite electron-builder excluding root node_modules', async () => { const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs') const config = createElectronBuilderConfig(RELEASE_ENVIRONMENT, 'darwin', 'arm64') diff --git a/apps/desktop/tests/macos-signing-walk.spec.ts b/apps/desktop/tests/macos-signing-walk.spec.ts new file mode 100644 index 0000000000..8dccc4645b --- /dev/null +++ b/apps/desktop/tests/macos-signing-walk.spec.ts @@ -0,0 +1,36 @@ +/** Exercise the installed macOS signer against Framework file and directory aliases. */ + +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { expect, it } from 'vitest' + +const builderRequire = createRequire(createRequire(import.meta.url).resolve('app-builder-lib')) +const { walkAsync } = builderRequire(join(dirname(builderRequire.resolve('@electron/osx-sign')), 'util.js')) as { + walkAsync: (path: string) => Promise +} + +// macOS Framework aliases use POSIX file and directory symlinks, unavailable on unprivileged Windows runners. +it.skipIf(process.platform === 'win32')('signs each real Framework file once and retains nested bundle signing', async () => { + const root = mkdtempSync(join(tmpdir(), 'desktop-signing-walk-')) + try { + const contents = join(root, 'Contents') + const framework = join(contents, 'Frameworks', 'Test.framework') + const version = join(framework, 'Versions', 'A') + const resource = join(version, 'Resources', 'en.lproj', 'locale.pak') + const library = join(version, 'library.dylib') + const helper = join(contents, 'Frameworks', 'Helper.app') + const executable = join(helper, 'Contents', 'MacOS', 'helper') + for (const file of [resource, library, executable]) { + mkdirSync(dirname(file), { recursive: true }) + writeFileSync(file, Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0, 0, 0, 0])) + } + symlinkSync('A', join(framework, 'Versions', 'Current')) + symlinkSync('Versions/Current/Resources', join(framework, 'Resources')) + symlinkSync('Versions/Current/library.dylib', join(framework, 'library.dylib')) + const files = await walkAsync(contents) + expect(files.sort()).toEqual([resource, library, executable, framework, helper].sort()) + expect(new Set(files.map(file => realpathSync(file))).size).toBe(files.length) + } finally { rmSync(root, { recursive: true, force: true }) } +}) diff --git a/patches/@electron__osx-sign@1.3.3.patch b/patches/@electron__osx-sign@1.3.3.patch new file mode 100644 index 0000000000..791434536c --- /dev/null +++ b/patches/@electron__osx-sign@1.3.3.patch @@ -0,0 +1,26 @@ +diff --git a/dist/cjs/util.js b/dist/cjs/util.js +index 77e64b56872bc65bcb0f60ecfbec84eb3da02c6f..8d5b81eea636c3f1672cfe2c66602078bda1e847 100644 +--- a/dist/cjs/util.js ++++ b/dist/cjs/util.js +@@ -153,7 +153,7 @@ async function walkAsync(dirPath) { + const children = await fs.readdir(dirPath); + return await Promise.all(children.map(async (child) => { + const filePath = path.resolve(dirPath, child); +- const stat = await fs.stat(filePath); ++ const stat = await fs.lstat(filePath); + if (stat.isFile()) { + switch (path.extname(filePath)) { + case '.cstemp': // Temporary file generated from past codesign +diff --git a/dist/esm/util.js b/dist/esm/util.js +index d3f66d54b1a88e7410d78affe17de87302db02a3..e86b066d1d21628908ecc848f5bb29a7598605a7 100644 +--- a/dist/esm/util.js ++++ b/dist/esm/util.js +@@ -117,7 +117,7 @@ export async function walkAsync(dirPath) { + const children = await fs.readdir(dirPath); + return await Promise.all(children.map(async (child) => { + const filePath = path.resolve(dirPath, child); +- const stat = await fs.stat(filePath); ++ const stat = await fs.lstat(filePath); + if (stat.isFile()) { + switch (path.extname(filePath)) { + case '.cstemp': // Temporary file generated from past codesign diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a2c6b9edb8..3610e0fe2b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,6 +9,7 @@ overrides: '@deepseek-ai/schemastery': link:vendor/schemastery patchedDependencies: + '@electron/osx-sign@1.3.3': 280e7b2816caf01423097d24e79107a66afeb563a348630ce9928ae8499a5861 '@yao-pkg/pkg@6.21.0': 28edd2180c36691c481522ef81f6f6614505f45e491aad542ac4663d4e6b3ff8 node-pty@1.2.0-beta.15: b40ae545608897914bd25fb009c97eeac478c34e8a910298ddcb01b746534bb0 @@ -18637,7 +18638,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@electron/osx-sign@1.3.3': + '@electron/osx-sign@1.3.3(patch_hash=280e7b2816caf01423097d24e79107a66afeb563a348630ce9928ae8499a5861)': dependencies: compare-version: 0.1.2 debug: 4.4.3(supports-color@9.4.0) @@ -20811,7 +20812,7 @@ snapshots: '@electron/fuses': 1.8.0 '@electron/get': 3.1.0 '@electron/notarize': 2.5.0 - '@electron/osx-sign': 1.3.3 + '@electron/osx-sign': 1.3.3(patch_hash=280e7b2816caf01423097d24e79107a66afeb563a348630ce9928ae8499a5861) '@electron/rebuild': 4.2.0 '@electron/universal': 2.0.3 '@malept/flatpak-bundler': 0.4.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 7cb1746e11..d0b4c0a6e5 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -87,5 +87,6 @@ minimumReleaseAgeExclude: - '@openai/codex@0.149.1||0.149.1-darwin-arm64||0.149.1-darwin-x64||0.149.1-linux-arm64||0.149.1-linux-x64||0.149.1-win32-arm64||0.149.1-win32-x64' patchedDependencies: + '@electron/osx-sign@1.3.3': patches/@electron__osx-sign@1.3.3.patch '@yao-pkg/pkg@6.21.0': patches/@yao-pkg__pkg@6.21.0.patch node-pty@1.2.0-beta.15: patches/node-pty@1.2.0-beta.15.patch From 00c2c47e19f6f5af388712c0c6b75447e99fc860 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 9 Sep 2026 12:52:09 +0800 Subject: [PATCH 06/52] fix(web): key the claim hint on the command name, not the claim token MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A localized claim token (/目标 ) made the composer look up hint.目标, miss the dictionary, and fall back to the Host's usage string. CommandClaim now carries the catalog name beside the display token, the state projection keeps it, and the hint lookup reads it. --- .../client/ui-commands/src/client/service.ts | 1 + .../ui-commands/tests/service.client.spec.ts | 1 + .../src/client/contract/input.ts | 5 ++++- .../src/client/input/machine.ts | 1 + .../src/client/skeleton/InputBar.tsx | 3 +-- .../tests/input-bar.client.spec.tsx | 19 ++++++++++++++++--- .../tests/input-matrix.client.spec.tsx | 6 +++--- .../tests/input-scenarios.client.spec.tsx | 1 + .../tests/submit-machine.client.spec.ts | 1 + .../tests/service.client.spec.ts | 2 +- 10 files changed, 30 insertions(+), 10 deletions(-) diff --git a/packages/client/ui-commands/src/client/service.ts b/packages/client/ui-commands/src/client/service.ts index c186b439ea..bf5e992c81 100644 --- a/packages/client/ui-commands/src/client/service.ts +++ b/packages/client/ui-commands/src/client/service.ts @@ -353,6 +353,7 @@ export class CommandUiRuntime extends Service implements CommandUiContract { const token = `/${shown} ` const line = `/${desc.name} ` return { + name: desc.name, token, ...(desc.input !== undefined ? { hint: desc.input.hint } : {}), ...(desc.input?.attachments === true ? { attachments: true } : {}), diff --git a/packages/client/ui-commands/tests/service.client.spec.ts b/packages/client/ui-commands/tests/service.client.spec.ts index 5ee855f9db..526f0efdaf 100644 --- a/packages/client/ui-commands/tests/service.client.spec.ts +++ b/packages/client/ui-commands/tests/service.client.spec.ts @@ -403,6 +403,7 @@ describe('candidates', () => { // The claim keeps the typed spelling (the draft carries it and the // arguments are read after it); the submission sends the catalog name. expect(space.claim.token).toBe('/计划 ') + expect(space.claim.name).toBe('plan') const enter = await source.matchEnter!(proj('s1'), '/目标 ship it', new AbortController().signal, { attachments: 0 }) if (enter === undefined || enter === 'handled' || !('claim' in enter)) throw new Error('expected the goal claim') expect(enter.claim.attachments).toBe(true) diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index 8dc4ba66e1..d050533950 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -43,6 +43,9 @@ export interface SubmitOutcome { /** Command-mode credential supplied by one input-trigger source. */ export interface CommandClaim { + /** Catalog command name without the leading slash (the key of per-command composer copy such as `hint.*`). */ + readonly name: string + /** The text the draft carries for the claim (`/name ` in English, a localized token elsewhere). */ readonly token: string readonly hint?: string readonly attachments?: boolean @@ -348,7 +351,7 @@ export interface InputState { readonly draftRev: number readonly phase: 'plain' | 'adjudicating' | 'claimed' | 'submitting' /** Present exactly while claimed/submitting (claim snapshot during flight; submit closure withheld). */ - readonly claim?: { readonly token: string; readonly hint?: string; readonly attachments?: boolean } + readonly claim?: { readonly name: string; readonly token: string; readonly hint?: string; readonly attachments?: boolean } /** Reference occurrence view of the editor's chips, sorted by offset. */ readonly occurrences: readonly Occurrence[] /** Read-only transient inbox projection from Session control, including pending steering. */ diff --git a/packages/client/ui-conversation/src/client/input/machine.ts b/packages/client/ui-conversation/src/client/input/machine.ts index 899da6f996..81aa519346 100644 --- a/packages/client/ui-conversation/src/client/input/machine.ts +++ b/packages/client/ui-conversation/src/client/input/machine.ts @@ -53,6 +53,7 @@ export class SubmitMachine { ...(c ? { claim: { + name: c.name, token: c.token, ...(c.hint !== undefined ? { hint: c.hint } : {}), ...(c.attachments === true ? { attachments: true } : {}), diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index f669c491d3..31bde384f0 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -391,8 +391,7 @@ export const InputBar = memo(function InputBar({ : null const hint = ((): string | null => { if (rawHint === null) return null - // Claim tokens have the `/name ` format (trailing space); trim to the bare name. - const commandName = input?.claim?.token.slice(1).trim() ?? '' + const commandName = input?.claim?.name ?? '' const hintKey = `hint.${commandName === 'goal' && hasGoal ? 'goal.active' : commandName}` // Dynamic lookup by claimed command name: unknown commands miss the // dictionary and keep the machine's own hint, so the call is wide. diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index f1b95dc84d..9275745e61 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -803,7 +803,7 @@ describe('running and lock semantics', () => { act(() => { claimed.shell.setDraft('/goal ') claimed.shell.beginCommand( - { token: '/goal ', submit: () => Promise.resolve({ kind: 'success' }) }, + { name: 'goal', token: '/goal ', submit: () => Promise.resolve({ kind: 'success' }) }, { start: 0, end: 6, draftRev: claimed.shell.snapshot.draftRev }, ) }) @@ -1201,6 +1201,7 @@ describe('machine pending lock', () => { shell.setDraft('/goal ') shell.beginCommand( { + name: 'goal', token: '/goal ', submit: () => new Promise(() => {}), // never settles: stays submitting }, @@ -1227,7 +1228,7 @@ describe('decorations', () => { act(() => { shell.setDraft('/goal ') shell.beginCommand( - { token: '/goal ', hint: '目标内容', submit: () => Promise.resolve({ kind: 'success' as const }) }, + { name: 'goal', token: '/goal ', hint: '目标内容', submit: () => Promise.resolve({ kind: 'success' as const }) }, { start: 0, end: 6, draftRev: shell.snapshot.draftRev }, ) shell.editor.update(() => {}, { discrete: true }) // flush the queued decoration refresh @@ -1246,13 +1247,25 @@ describe('decorations', () => { act(() => { shell.setDraft('/goal ') shell.beginCommand( - { token: '/goal ', hint: '[|clear|edit |pause|resume]', submit: () => Promise.resolve({ kind: 'success' as const }) }, + { name: 'goal', token: '/goal ', hint: '[|clear|edit |pause|resume]', submit: () => Promise.resolve({ kind: 'success' as const }) }, { start: 0, end: 6, draftRev: shell.snapshot.draftRev }, ) }) expect(textarea.style.getPropertyValue('--dsh-composer-hint')).toBe(JSON.stringify('输入目标,智能体将持续执行')) }) + it('the hint lookup keys on the claim name, so a localized claim token keeps the locale entry', () => { + const { shell, textarea } = bench() + act(() => { + shell.setDraft('/目标 ') + shell.beginCommand( + { name: 'goal', token: '/目标 ', hint: '[|clear|edit |pause|resume]', submit: () => Promise.resolve({ kind: 'success' as const }) }, + { start: 0, end: 4, draftRev: shell.snapshot.draftRev }, + ) + }) + expect(textarea.style.getPropertyValue('--dsh-composer-hint')).toBe(JSON.stringify('输入目标,智能体将持续执行')) + }) + it('an inserted reference renders a real chip capsule with its icon and label', () => { const { view, shell } = bench() const reference = { diff --git a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx index 5533c236a5..67e0b6895c 100644 --- a/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.client.spec.tsx @@ -111,7 +111,7 @@ function bench(over?: { shell.setDraft(token) shell.beginCommand( { - token, hint, + name: token.slice(1).trim(), token, hint, ...(attachments === true ? { attachments: true } : {}), submit: over?.submit ?? (() => Promise.resolve({ kind: 'success' as const, source: 'command', name: 'goal' })), }, @@ -141,7 +141,7 @@ describe('matrix row: claimed', () => { const { view, textarea, shell, claim } = bench() claim() act(() => { shell.editor.update(() => {}, { discrete: true }) }) // flush the queued decoration refresh - expect(shell.snapshot.claim).toEqual({ token: '/goal ', hint: '目标' }) + expect(shell.snapshot.claim).toEqual({ name: 'goal', token: '/goal ', hint: '目标' }) expect(view.container.querySelector('[data-lexical-text][style*="warn-label"]')?.textContent).toBe('/goal ') // The zh dictionary owns a hint.goal entry, which overrides the raw claim hint (production behavior). expect(textarea.style.getPropertyValue('--dsh-composer-hint')).toBe(JSON.stringify('输入目标,智能体将持续执行')) @@ -201,7 +201,7 @@ describe('matrix row: claimed with attachments', () => { const { textarea, shell, claim, serialize, release } = bench({ submit, serialize: () => Promise.resolve([png, file]) }) claim('/goal ', '目标', true) // The claim currency carries the acceptance flag the pre-gate reads. - expect(shell.snapshot.claim).toEqual({ token: '/goal ', hint: '目标', attachments: true }) + expect(shell.snapshot.claim).toEqual({ name: 'goal', token: '/goal ', hint: '目标', attachments: true }) act(() => { shell.addAttachments([img]) }) fireEvent.keyDown(textarea, { key: 'Enter' }) await vi.waitFor(() => { expect(submit).toHaveBeenCalledWith('', SCTX, [png, file]) }) diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index 88ab3a809f..226671eaa4 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -58,6 +58,7 @@ function commandSource( ) { const resolve = (name: string): FakeCommand | undefined => commands.find(c => c.name === name) const leadingClaim = (desc: FakeCommand): CommandClaim => ({ + name: desc.name, token: `/${desc.name} `, ...(desc.input !== undefined ? { hint: desc.input.hint } : {}), ...(desc.input?.attachments === true ? { attachments: true } : {}), diff --git a/packages/client/ui-conversation/tests/submit-machine.client.spec.ts b/packages/client/ui-conversation/tests/submit-machine.client.spec.ts index 73d16d0235..563079ef9e 100644 --- a/packages/client/ui-conversation/tests/submit-machine.client.spec.ts +++ b/packages/client/ui-conversation/tests/submit-machine.client.spec.ts @@ -13,6 +13,7 @@ import { scanTextRefs } from '../src/client/input/decorations.ts' function claimOf(name: string, hint?: string): CommandClaim { return { + name, token: `/${name} `, ...(hint !== undefined ? { hint } : {}), submit: async () => ({ kind: 'success' }), diff --git a/packages/client/ui-input-trigger/tests/service.client.spec.ts b/packages/client/ui-input-trigger/tests/service.client.spec.ts index 563d5f8a92..640ff0d8c2 100644 --- a/packages/client/ui-input-trigger/tests/service.client.spec.ts +++ b/packages/client/ui-input-trigger/tests/service.client.spec.ts @@ -63,7 +63,7 @@ function readySource( } const claimOf = (token: string): CommandClaim => - ({ token, submit: () => Promise.resolve({ kind: 'success' }) }) + ({ name: token.slice(1).trim(), token, submit: () => Promise.resolve({ kind: 'success' }) }) /** One microtask hop: lets settled candidate promises flow into the store. */ const tick = () => Promise.resolve() From a4954e1bd2c41c2ffe9fb4baff171aa1c4d93908 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 9 Sep 2026 12:58:11 +0800 Subject: [PATCH 07/52] test(web): follow the renamed launcher and capitalized rows in CI gates Registers slash/input-pick-files with the cordis catalog walk exemptions beside its sibling slash-input events, and points the web e2e at the 'Add files or run commands' launcher and the capitalized row titles the paperclip removal and the menu presentation introduced. --- apps/web/tests/agent-preset-selection.e2e.ts | 5 +++-- apps/web/tests/feedback-command.e2e.ts | 2 +- apps/web/tests/navigation-panes.e2e.ts | 2 +- apps/web/tests/seeded-history.e2e.ts | 2 +- scripts/gen-cordis-catalog.ts | 1 + 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/apps/web/tests/agent-preset-selection.e2e.ts b/apps/web/tests/agent-preset-selection.e2e.ts index 8f1bf2033a..8207a98261 100644 --- a/apps/web/tests/agent-preset-selection.e2e.ts +++ b/apps/web/tests/agent-preset-selection.e2e.ts @@ -312,7 +312,8 @@ describe('web e2e: agent-preset selection', () => { await writeComposerDraft(page, composer, '/') await expect.poll(() => menuOptions(page), { timeout: 15_000 }) .not.toEqual(expect.arrayContaining([expect.stringContaining(SKILL_NAME)])) - const onMinimal = await menuOptions(page) + // Rows read as `Title Description`; the title is the capitalized command name. + const onMinimal = (await menuOptions(page)).map(option => option.toLowerCase()) expect(onMinimal.some(option => option.startsWith('compact'))).toBe(false) expect(onMinimal.some(option => option.startsWith('plan'))).toBe(false) // Preset-scoped commands follow the switch; the client's own model command @@ -332,7 +333,7 @@ describe('web e2e: agent-preset selection', () => { await writeComposerDraft(page, composer, '/') await expect.poll(() => menuOptions(page), { timeout: 15_000 }) .toEqual(expect.arrayContaining([expect.stringContaining(SKILL_NAME)])) - const onStandard = await menuOptions(page) + const onStandard = (await menuOptions(page)).map(option => option.toLowerCase()) expect(onStandard.some(option => option.startsWith('compact'))).toBe(true) expect(onStandard.some(option => option.startsWith('goal'))).toBe(true) expect(onStandard.some(option => option.startsWith('plan'))).toBe(true) diff --git a/apps/web/tests/feedback-command.e2e.ts b/apps/web/tests/feedback-command.e2e.ts index a2946223dc..7eabc3502f 100644 --- a/apps/web/tests/feedback-command.e2e.ts +++ b/apps/web/tests/feedback-command.e2e.ts @@ -82,7 +82,7 @@ describe('web e2e: /feedback command acknowledgement', () => { await page.getByText(/Feedback recorded for session/).waitFor({ timeout: 10_000 }) expect(await page.getByText(/Anonymous user: [0-9a-f-]+\.$/i).count()).toBe(1) await expect.poll(() => input.textContent(), { timeout: 10_000 }).toBe('') - await expect.poll(() => page.getByRole('button', { name: 'Add attachment' }).isEnabled(), { timeout: 10_000 }).toBe(true) + await expect.poll(() => page.getByRole('button', { name: 'Add files or run commands' }).isEnabled(), { timeout: 10_000 }).toBe(true) const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd) await compareOrRefreshGolden(ACK_EXPECTED, snapshot, MODE) const expanded = await captureExpandedTurnProcessAria( diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index d51e08bb49..32def9e0a3 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -335,7 +335,7 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { const input = page.locator('[data-composer-input]').first() const slashDownloadPromise = page.waitForEvent('download', { timeout: 30_000 }) await input.fill('/export') - await page.getByRole('option', { name: /export/u }).waitFor({ timeout: 10_000 }) + await page.getByRole('option', { name: /^Export/u }).waitFor({ timeout: 10_000 }) await input.press('Enter') const slashDownload = await slashDownloadPromise expect(slashDownload.suggestedFilename()).toBe(download.suggestedFilename()) diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts index 84096583f9..6dd59379c1 100644 --- a/apps/web/tests/seeded-history.e2e.ts +++ b/apps/web/tests/seeded-history.e2e.ts @@ -506,7 +506,7 @@ describe('web e2e: seeded history renders through cold resume', () => { // command/done can arrive before the submit reply releases the composer. await expect.poll(() => input.textContent(), { timeout: 10_000 }).toBe('') - await expect.poll(() => page.getByRole('button', { name: 'Add attachment' }).isEnabled(), { timeout: 10_000 }).toBe(true) + await expect.poll(() => page.getByRole('button', { name: 'Add files or run commands' }).isEnabled(), { timeout: 10_000 }).toBe(true) const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)) .split(SEED_ID).join('{{seededId}}') .split(userId).join('{{userId}}') diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index f1c1462d2f..cafca07464 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -233,6 +233,7 @@ export const EVENT_WALK_EXEMPTIONS: Record = { 'slash/input-consume-token': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', 'slash/input-insert-reference': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', 'slash/input-insert-text': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', + 'slash/input-pick-files': 'client-face slash-input protocol — packages/client/ui-input-trigger/README.md owns the API', 'slots/changed': 'client-face slot invalidation signal — packages/client/ui-renderer/README.md owns the API', 'theme/change': 'client-face theme switch signal — packages/client/ui-theme/README.md owns the API', } From eff482c46b8df11eb2baa26e807ba3fe5629bf91 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 9 Sep 2026 14:27:51 +0800 Subject: [PATCH 08/52] fix(web): stabilize composer command editing and scrolling --- ...menu-sections-and-localized-rows.i18n.yaml | 4 +- ...mposer-menu-sections-and-localized-rows.md | 6 ++ ...ser-menu-sections-and-localized-rows.zh.md | 6 ++ apps/web/tests/lifecycle-chrome.e2e.ts | 62 ++++++++++++++++ apps/web/tests/sidebar-scrollbar.e2e.ts | 2 +- .../client/ui-conversation/README.i18n.yaml | 4 +- packages/client/ui-conversation/README.md | 2 + packages/client/ui-conversation/README.zh.md | 2 + .../src/client/contract/input.ts | 2 +- .../src/client/input/editor/claim-decor.ts | 3 +- .../src/client/input/editor/keymap.ts | 16 +++++ .../src/client/input/editor/text-ref.ts | 2 +- .../src/client/input/machine.ts | 11 ++- .../src/client/skeleton/InputBar.module.css | 8 +++ .../tests/input-bar.client.spec.tsx | 31 ++++++++ .../tests/input-scenarios.client.spec.tsx | 29 ++++++++ .../tests/keymap-routing.client.spec.tsx | 35 +++++++++- .../tests/lexical-editor-core.client.spec.tsx | 10 +-- .../tests/submit-machine.client.spec.ts | 29 +++++++- .../src/client/MenuView.module.css | 25 ++++++- .../ui-input-trigger/src/client/MenuView.tsx | 26 +++++-- .../tests/menu-view.client.spec.tsx | 19 ++++- packages/client/ui-theme/README.i18n.yaml | 4 +- packages/client/ui-theme/README.md | 2 +- packages/client/ui-theme/README.zh.md | 2 +- .../client/ui-theme/src/styles/scrollbar.css | 19 +++-- .../tests/scrollbar-styles.client.spec.ts | 70 ++++++++++--------- 27 files changed, 359 insertions(+), 72 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.i18n.yaml b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.i18n.yaml index fd023c5ddc..af47bdd3ec 100644 --- a/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.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-composer-menu-sections-and-localized-rows.md -2026-09-08-composer-menu-sections-and-localized-rows.md: c8fc2226a15828de14f623fc582473e72e3ec1f1 -2026-09-08-composer-menu-sections-and-localized-rows.zh.md: 5905c872ab583294aabf15a1b69f2dfe1312e4ba +2026-09-08-composer-menu-sections-and-localized-rows.md: ab381d2e3ab62cc272a3984468163a657b717da1 +2026-09-08-composer-menu-sections-and-localized-rows.zh.md: 8fe15119ac96ac7d1aac6206a7c423ef35d72fd2 diff --git a/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.md b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.md index c8fc2226a1..ab381d2e3a 100644 --- a/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.md +++ b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.md @@ -20,8 +20,14 @@ The File row is an `action` contribution, a new `CommandUiSpec` kind whose bare `ui-input-trigger` renders the new row anatomy: `InputTriggerCandidate.label` is the title and a second search key of the shared `rankByName`, the name renders as a trailing alias when the label differs from it, `icon` accepts an icon component beside the reference glyph tokens, and the description is right-aligned. `ui-primitives` gains the Plan glyph from the design doc, a static ring for Compact, and the permission shield contour. +The menu uses a 400 px border-box height cap, which fits both headings and the eight built-in rows before the viewport clamp reduces it. A real overflow keeps a 10 px draggable WebKit rail around a 4 px visible thumb, insets the track from the rounded ends, and shows a bottom fade until the viewport reaches the final row; Firefox keeps its standard thin scrollbar. + ## Alternatives considered +**Release a claim when its separator is deleted.** The complete command name still identifies the selected command. Keeping the claim until the name changes preserves its highlight through argument replacement and avoids relying on an IME-generated space to run ordinary keydown adjudication. The shared input machine applies this rule to every command token, including failure recovery; neither the command name nor the locale selects a separate implementation. + +**Restore placeholders directly on native composition end.** Browsers can deliver that event before Lexical reconciles the final text. The shared editor binding keeps command hints and ordinary placeholders hidden while either native or editor composition remains active, and reevaluates visibility after an editor commit, including a cancellation that changes no text. Keyboard submit guards retain their separate post-composition window. + **Localize descriptions on the Host.** The Host has no locale and its catalog is shared by every client; the client already owns product copy for every other surface (the locale-owned client UI copy decision), and the equality guard keeps a scoped or third-party descriptor verbatim. **Keep sections under a typed query.** Ranking inside sections put a prefix hit in Commands below weaker matches in Add (typing `e` listed Feedback and File above Export); a flat ranking keeps the best match first, and the headings only carry information while the list is complete. diff --git a/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.zh.md b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.zh.md index 5905c872ab..8fe15119ac 100644 --- a/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.zh.md +++ b/.agents/notes/implemented/feature/2026-09-08-composer-menu-sections-and-localized-rows.zh.md @@ -20,8 +20,14 @@ composer 的 `+` 按钮与键入的 `/` 按宿主注册顺序把每个命令列 `ui-input-trigger` 渲染新的行结构:`InputTriggerCandidate.label` 是标题,也是共享 `rankByName` 的第二个搜索键;label 与名字不同时名字渲染为尾随别名;`icon` 在引用图标 token 之外接受图标组件;说明右对齐。`ui-primitives` 新增设计稿给出的计划图标、压缩用的静态环形,以及权限盾形轮廓。 +菜单采用 400 px 的 border-box 高度上限,在视口限制缩小高度前可容纳两个小节标题与八个内置入口。内容确实溢出时,WebKit 系浏览器用 10 px 的可拖动区域承载 4 px 的可见滑块,轨道避开圆角两端,视口抵达最后一行前显示底部渐隐;Firefox 保留标准细滚动条。 + ## 考虑过的替代方案 +**删除分隔空格时释放命令认领。** 完整命令名仍能标识已选命令。保留认领直到命令名改变,可以在替换参数时保持高亮,也无需依赖输入法生成的空格触发普通按键裁决。共享输入状态机对所有命令 token 使用这个规则,提交失败后的恢复也相同;命令名和界面语言都不选择另一套实现。 + +**在原生组合输入结束事件中直接恢复占位文字。** 浏览器可能先发送该事件,Lexical 随后才完成最终文字更新。共享编辑器绑定在原生输入法或编辑器仍处于组合输入时隐藏命令提示和普通占位文字,并在编辑器提交更新后重新判断显隐,包括没有文字变化的取消操作。键盘提交保护保留独立的组合输入结束后保护时段。 + **在宿主侧本地化说明。** 宿主没有语言设置,目录又被所有客户端共享;客户端已经拥有其他所有界面的产品文案(客户端界面文案归语言所有的决策),相等性判断还能让作用域覆盖或第三方描述符原样保留。 **输入查询后保留小节。** 在小节内排序会把「指令」里的前缀命中排在「添加」里较弱的匹配之下(输入 `e` 时反馈与文件排在导出之上);平铺排序让最佳匹配始终靠前,小节标题只在列表完整时才有信息量。 diff --git a/apps/web/tests/lifecycle-chrome.e2e.ts b/apps/web/tests/lifecycle-chrome.e2e.ts index 07a5095eba..1ebdb03002 100644 --- a/apps/web/tests/lifecycle-chrome.e2e.ts +++ b/apps/web/tests/lifecycle-chrome.e2e.ts @@ -133,6 +133,68 @@ describe('web e2e: lifecycle & chrome (workspace flow / reload / dark mode)', () } }) + it.skipIf(MODE === 'record').each([ + { locale: 'en-US', token: '/goal', row: 'Goal Set or view the goal for a long-running task', hint: 'describe the objective for a long-running task' }, + { locale: 'en-US', token: '/plan', row: 'Plan Enter or leave plan mode', hint: 'describe your task to generate plan' }, + { locale: ZH_BROWSER_LOCALE, token: '/目标', row: '目标 goal 设置或查看长期任务目标', hint: '输入目标,智能体将持续执行' }, + { locale: ZH_BROWSER_LOCALE, token: '/计划', row: '计划 plan 进入或退出计划模式', hint: '描述你的任务以生成计划' }, + ])('keeps $token claimed across separator edits and hides hints during IME composition', async ({ locale, token, row, hint }) => { + const inputPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale }) + const inputTripwire = watchConsole(inputPage) + onTestFailed(() => saveFailureShot(inputPage, `web-e2e-command-input-${locale}-${token.slice(1)}`)) + try { + await inputPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await inputPage.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + const input = inputPage.locator('[data-composer-input]').first() + await writeComposerDraft(inputPage, input, '/') + await inputPage.getByRole('listbox').getByRole('option', { name: row, exact: true }).click() + await expect.poll(() => input.textContent()).toBe(`${token} `) + await input.press('End') + await inputPage.keyboard.insertText('这是任务') + await expect.poll(() => input.textContent()).toBe(`${token} 这是任务`) + for (let i = 0; i < 5; i++) await input.press('Backspace') + const tokenText = () => input.locator('[data-lexical-text][style*="warn-label"]').textContent() + await expect.poll(() => input.textContent()).toBe(token) + await expect.poll(() => input.getAttribute('data-phase')).toBe('claimed') + await expect.poll(tokenText).toBe(token) + await input.press('Space') + await expect.poll(() => input.getAttribute('data-phase')).toBe('claimed') + await expect.poll(() => input.textContent()).toBe(`${token} `) + await expect.poll(async () => (await tokenText())?.trimEnd()).toBe(token) + const shownHint = () => input.locator('p').last().evaluate(element => getComputedStyle(element, '::after').content) + await expect.poll(shownHint).toBe(JSON.stringify(hint)) + const cdp = await inputPage.context().newCDPSession(inputPage) + await cdp.send('Input.imeSetComposition', { text: 'z', selectionStart: 1, selectionEnd: 1 }) + await expect.poll(shownHint).toBe('none') + await cdp.send('Input.imeSetComposition', { text: 'zh', selectionStart: 2, selectionEnd: 2 }) + await expect.poll(shownHint).toBe('none') + await cdp.send('Input.insertText', { text: '这' }) + await expect.poll(() => input.textContent()).toBe(`${token} 这`) + await expect.poll(shownHint).toBe('none') + await input.press('Backspace') + await expect.poll(shownHint).toBe(JSON.stringify(hint)) + await cdp.send('Input.imeSetComposition', { text: 'z', selectionStart: 1, selectionEnd: 1 }) + await expect.poll(shownHint).toBe('none') + await cdp.send('Input.imeSetComposition', { text: '', selectionStart: 0, selectionEnd: 0 }) + await expect.poll(shownHint).toBe(JSON.stringify(hint)) + await input.press('Backspace') + await input.press('Backspace') + await expect.poll(() => input.getAttribute('data-phase')).toBe('plain') + await writeComposerDraft(inputPage, input, '') + const placeholder = inputPage.locator('[data-composer-placeholder]').first() + await expect.poll(() => placeholder.isVisible()).toBe(true) + await cdp.send('Input.imeSetComposition', { text: 'z', selectionStart: 1, selectionEnd: 1 }) + await expect.poll(() => placeholder.isVisible()).toBe(false) + await cdp.send('Input.imeSetComposition', { text: '', selectionStart: 0, selectionEnd: 0 }) + await expect.poll(() => placeholder.isVisible()).toBe(true) + await cdp.detach() + expect(inputTripwire.pageErrors).toEqual([]) + expect(inputTripwire.warnings).toEqual([]) + } finally { + await inputPage.close() + } + }) + it.skipIf(MODE === 'record')('shows active Plan as the warn-state status action', async () => { const activeScaffold = await launchWebScaffold() const activePage = await newEnglishPage(browser) diff --git a/apps/web/tests/sidebar-scrollbar.e2e.ts b/apps/web/tests/sidebar-scrollbar.e2e.ts index 0f1443c8d9..b8d8d36ebe 100644 --- a/apps/web/tests/sidebar-scrollbar.e2e.ts +++ b/apps/web/tests/sidebar-scrollbar.e2e.ts @@ -83,7 +83,7 @@ function measureList(page: Page): Promise { }) .filter((rule): rule is CSSStyleRule => rule instanceof CSSStyleRule) .filter(rule => rule.selectorText === '::-webkit-scrollbar-thumb:hover') - .map(rule => rule.style.getPropertyValue('background')) + .map(rule => rule.style.getPropertyValue('background-color')) const style = getComputedStyle(list) const pseudoWidth = getComputedStyle(list, '::-webkit-scrollbar').width const barWidth = pseudoWidth === 'auto' ? 15 : Number.parseFloat(pseudoWidth) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 6346973dc8..195b7fb645 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/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-conversation/README.md -README.md: 4793373df94e2b7c617c1f44dd74d2b32bd86d6f -README.zh.md: 463b9bff010fee7d29cad46828dc1caff8b22fff +README.md: 6a953a0f099d5205da683d81a1390a05b5159209 +README.zh.md: 612a7ca72787a4199207ad5fd0ac6846024e1d6e diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 4793373df9..6a953a0f09 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -36,6 +36,8 @@ Target packages declaration-merge their snapshot and Location data maps, then re ## Shell and standard props +Claimed commands retain their identity and highlight when only their arguments and trailing separator are deleted; editing the command name releases the claim. The same rules apply to every command and locale, including `/goal`, `/目标`, `/plan`, and `/计划`. Command hints and ordinary placeholders remain hidden throughout IME composition and reappear only after the editor commits the final text and the corresponding input is empty. + Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and commit navigation. Draft text and attachments move in its synchronous preparation callback only while that request is current; later navigation or owner disposal leaves the original draft intact. The package occupies the root-scoped `main` key `conversation`, whose wrapper declares the optional-Session `main.conversation` shell. It registers strict Session header/body entries, View list, composer chain and bar, input regions, Hero regions, queue dock, draft persistence, and phase calculation. `ctx.uiSession.provide()` materializes the Conversation and input sources from the same Session binding and supplies `inputActions` as a stable standard prop. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index 463b9bff01..612a7ca727 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -36,6 +36,8 @@ target package 通过 declaration merge 扩展 snapshot 与 Location data map, ## Shell 与标准 props +已认领的命令在仅删除参数和末尾分隔空格时保留身份与高亮,改动命令名才会释放认领。所有命令和语言使用相同规则,包括 `/goal`、`/目标`、`/plan` 和 `/计划`。输入法组合输入期间,命令提示和普通占位文字持续隐藏,直到编辑器提交最终文字且对应输入为空时才重新显示。 + 工作区选择使用 `uiWorkspace.openWorkspace` 准备目标并提交导航。草稿文字和附件仅在请求仍有效时,通过它的同步准备回调搬移;后续导航或所有者释放会保留原草稿。 本包占据 root 作用域 `main` 中的 `conversation` key,其包装层声明 optional-Session `main.conversation` shell。本包注册strict Session header/body、View list、composer chain 与 bar、输入区域、Hero 区域、queue dock、草稿持久化和 phase 计算。`ctx.uiSession.provide()` 从同一个 Session binding 物化 Conversation 与 input source,并将 `inputActions` 作为稳定标准 prop 提供。 diff --git a/packages/client/ui-conversation/src/client/contract/input.ts b/packages/client/ui-conversation/src/client/contract/input.ts index d050533950..26fe962bf6 100644 --- a/packages/client/ui-conversation/src/client/contract/input.ts +++ b/packages/client/ui-conversation/src/client/contract/input.ts @@ -45,7 +45,7 @@ export interface SubmitOutcome { export interface CommandClaim { /** Catalog command name without the leading slash (the key of per-command composer copy such as `hint.*`). */ readonly name: string - /** The text the draft carries for the claim (`/name ` in English, a localized token elsewhere). */ + /** Inserted command text with its argument separator; the bare complete name also retains the claim. */ readonly token: string readonly hint?: string readonly attachments?: boolean diff --git a/packages/client/ui-conversation/src/client/input/editor/claim-decor.ts b/packages/client/ui-conversation/src/client/input/editor/claim-decor.ts index 09ef7b6727..7f2bec56ee 100644 --- a/packages/client/ui-conversation/src/client/input/editor/claim-decor.ts +++ b/packages/client/ui-conversation/src/client/input/editor/claim-decor.ts @@ -34,8 +34,9 @@ export function registerClaimDecoration(editor: LexicalEditor, activeToken: () = if (node.getStyle() === TOKEN_STYLE) node.setStyle('') return } - const token = activeToken() const text = node.getTextContent() + const active = activeToken() + const token = text === active?.trimEnd() ? text : active if (token === null || !text.startsWith(token)) { if (node.getStyle() === TOKEN_STYLE) node.setStyle('') return diff --git a/packages/client/ui-conversation/src/client/input/editor/keymap.ts b/packages/client/ui-conversation/src/client/input/editor/keymap.ts index 492aba62df..f11592ba5a 100644 --- a/packages/client/ui-conversation/src/client/input/editor/keymap.ts +++ b/packages/client/ui-conversation/src/client/input/editor/keymap.ts @@ -11,6 +11,8 @@ * keydown AFTER compositionend, so a root-element composition watch holds the * guard for 10ms more (the old textarea's proven window); keyCode * 229 is the legacy signal engines emit without isComposing. + * The root's composition attribute suppresses placeholders until both the + * native composition and the editor's final text reconciliation finish. */ import type { LexicalEditor } from 'lexical' import { @@ -57,12 +59,20 @@ export function registerComposerKeymap(editor: LexicalEditor, handlers: Composer // root element and re-arms on root swaps. let composing = false let composingUntil = 0 + let rootElement: HTMLElement | null = null + const syncComposition = (): void => { + rootElement?.toggleAttribute('data-composer-composing', composing || editor.isComposing()) + } const onCompositionStart = (): void => { composing = true + syncComposition() } const onCompositionEnd = (): void => { composing = false composingUntil = Date.now() + 10 + // The native event can precede the committed draft, including an empty + // cancellation. The callback also runs when no document text changed. + editor.update(() => {}, { onUpdate: syncComposition }) } const recentlyComposing = (): boolean => composing || Date.now() < composingUntil @@ -79,9 +89,15 @@ export function registerComposerKeymap(editor: LexicalEditor, handlers: Composer editor.registerRootListener((root, prevRoot) => { prevRoot?.removeEventListener('compositionstart', onCompositionStart) prevRoot?.removeEventListener('compositionend', onCompositionEnd) + prevRoot?.removeAttribute('data-composer-composing') + composing = false + composingUntil = 0 + rootElement = root root?.addEventListener('compositionstart', onCompositionStart) root?.addEventListener('compositionend', onCompositionEnd) + syncComposition() }), + editor.registerUpdateListener(syncComposition), editor.registerCommand(KEY_ARROW_UP_COMMAND, arrow('up'), COMMAND_PRIORITY_CRITICAL), editor.registerCommand(KEY_ARROW_DOWN_COMMAND, arrow('down'), COMMAND_PRIORITY_CRITICAL), // Tab acts only when the trigger menu has a highlighted completion; diff --git a/packages/client/ui-conversation/src/client/input/editor/text-ref.ts b/packages/client/ui-conversation/src/client/input/editor/text-ref.ts index 3a72a2a189..74ca400217 100644 --- a/packages/client/ui-conversation/src/client/input/editor/text-ref.ts +++ b/packages/client/ui-conversation/src/client/input/editor/text-ref.ts @@ -96,7 +96,7 @@ export function registerTextRefDecoration( const getMatch = (text: string): { start: number; end: number } | null => { const claim = activeToken() for (const range of scanTextRefs(text, lexiconOf())) { - if (claim !== null && range.start === 0 && text.slice(range.start, range.end) === claim) continue + if (claim !== null && range.start === 0 && text.slice(range.start, range.end) === claim.trimEnd()) continue return { start: range.start, end: range.end } } return null diff --git a/packages/client/ui-conversation/src/client/input/machine.ts b/packages/client/ui-conversation/src/client/input/machine.ts index 81aa519346..7d1e503777 100644 --- a/packages/client/ui-conversation/src/client/input/machine.ts +++ b/packages/client/ui-conversation/src/client/input/machine.ts @@ -27,6 +27,11 @@ function argsAfter(draft: string, token: string): string { return '' } +/** A claimed name may stand alone; arguments require the token's separator. */ +function retainsClaim(draft: string, token: string): boolean { + return draft.startsWith(token) || draft === token.trimEnd() +} + /** The submit-plane slice of the published InputState. */ export interface SubmitSnapshot { readonly phase: InputState['phase'] @@ -83,9 +88,9 @@ export class SubmitMachine { } } - /** Claimed integrity watch: a draft that breaks the token prefix releases the claim. */ + /** The complete command name retains its claim with or without the argument separator. */ private onDraftChanged(draft: string): readonly InputEffect[] { - if (this.phase === 'claimed' && this.claim !== undefined && !draft.startsWith(this.claim.token)) { + if (this.phase === 'claimed' && this.claim !== undefined && !retainsClaim(draft, this.claim.token)) { this.phase = 'plain' this.claim = undefined } @@ -200,7 +205,7 @@ export class SubmitMachine { } const text = ev.message ?? ev.outcome?.text if (ev.draft === flight.attempt.draftSnapshot - && this.claim !== undefined && ev.draft.startsWith(this.claim.token)) { + && this.claim !== undefined && retainsClaim(ev.draft, this.claim.token)) { this.phase = 'claimed' return text === undefined ? [] : [{ type: 'notice', level: 'error', text }] } diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css b/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css index abd5911c90..6369e5728d 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css @@ -195,6 +195,14 @@ color: var(--dsw-alias-label-caption); } +.input[data-composer-composing] p:last-child::after { + content: none; +} + +.input[data-composer-composing] + .placeholder { + visibility: hidden; +} + /* figma 34:10434: #ADB2B8 light / #81858C dark — the caption pair exactly. Insets mirror .input's pads (the other right 4px sits on .scroll). One ellipsized line: a wrapped second line would clip against the docked diff --git a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx index c017da7073..6476e83878 100644 --- a/packages/client/ui-conversation/tests/input-bar.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.client.spec.tsx @@ -1266,6 +1266,37 @@ describe('decorations', () => { expect(textarea.style.getPropertyValue('--dsh-composer-hint')).toBe(JSON.stringify('输入目标,智能体将持续执行')) }) + it('suppresses placeholders throughout native composition, including a temporarily empty draft', async () => { + const { shell, textarea, view } = bench() + expect(view.container.querySelector('[data-composer-placeholder]')).not.toBeNull() + fireEvent.compositionStart(textarea) + expect(textarea.hasAttribute('data-composer-composing')).toBe(true) + act(() => { shell.setDraft('z') }) + act(() => { shell.setDraft('') }) + expect(textarea.hasAttribute('data-composer-composing')).toBe(true) + fireEvent.compositionEnd(textarea, { data: '' }) + expect(textarea.hasAttribute('data-composer-composing')).toBe(true) + await act(async () => {}) + expect(textarea.hasAttribute('data-composer-composing')).toBe(false) + + act(() => { + shell.setDraft('/目标 ') + shell.beginCommand( + { name: 'goal', token: '/目标 ', hint: '目标内容', submit: () => Promise.resolve({ kind: 'success' as const }) }, + { start: 0, end: 4, draftRev: shell.snapshot.draftRev }, + ) + }) + fireEvent.compositionStart(textarea) + act(() => { shell.setDraft('/目标 z') }) + act(() => { shell.setDraft('/目标 ') }) + expect(textarea.hasAttribute('data-composer-composing')).toBe(true) + fireEvent.compositionEnd(textarea, { data: '这' }) + act(() => { shell.setDraft('/目标 这') }) + await act(async () => {}) + expect(textarea.hasAttribute('data-composer-composing')).toBe(false) + expect(textarea.style.getPropertyValue('--dsh-composer-hint')).toBe('') + }) + it('an inserted reference renders a real chip capsule with its icon and label', () => { const { view, shell } = bench() const reference = { diff --git a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx index 94e34ed2c6..42bf54913c 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.client.spec.tsx @@ -28,6 +28,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { DraftAttachmentId } from '../src/client/contract/input.ts' import { SessionInputShell } from '../src/client/input/facade.ts' +import { $replaceDetectSpanWithText } from '../src/client/input/editor/span-map.ts' import { InputBar } from '../src/client/skeleton/InputBar.tsx' import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import { zh } from '../src/client/locales.ts' @@ -306,6 +307,34 @@ describe('scenario: images ride an accepting command through the real pipeline', }) describe('scenario H: backspace breaks the token', () => { + it.each(['goal', '目标', 'plan', '计划', 'feedback', '反馈'])('keeps /%s claimed when its arguments and separator are deleted', async (name) => { + const { source } = commandSource([{ name, description: name, input: { hint: '目标内容' } }], + () => Promise.resolve({ kind: 'success' })) + const b = await scopedBench((triggers) => { triggers.registerSource(source) }) + b.type(`/${name}`) + fireEvent.keyDown(b.textarea, { key: ' ', keyCode: 32 }) + expect(b.shell.snapshot.phase).toBe('claimed') + b.type(`/${name} 这是目标`) + for (let i = 0; i < 5; i++) { + act(() => { + b.shell.editor.update(() => { + const end = b.shell.snapshot.draft.length + $replaceDetectSpanWithText({ start: end - 1, end }, '') + }, { discrete: true }) + }) + } + expect(b.shell.snapshot.draft).toBe(`/${name}`) + expect(b.shell.snapshot.phase).toBe('claimed') + expect(b.view.container.querySelector('[data-lexical-text][style*="warn-label"]')?.textContent).toBe(`/${name}`) + b.type(`/${name} `) + await act(async () => {}) + expect(b.shell.snapshot.phase).toBe('claimed') + expect(b.shell.snapshot.draft).toBe(`/${name} `) + expect(b.view.container.querySelector('[data-lexical-text][style*="warn-label"]')?.textContent).toBe(`/${name} `) + b.type(`/${name}x`) + expect(b.shell.snapshot.phase).toBe('plain') + }) + it('claim releases automatically; the enter after that goes through adjudication again', async () => { const b = await bench() b.type('/goal') diff --git a/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx b/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx index ea577859ef..daca265a89 100644 --- a/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx +++ b/packages/client/ui-conversation/tests/keymap-routing.client.spec.tsx @@ -4,13 +4,46 @@ * contenteditable reach the registered composer commands (the jsdom lane's * gesture entry, below the full component bench). */ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it, onTestFinished, vi } from 'vitest' import { fireEvent } from '@testing-library/react' import { createEditor } from 'lexical' import { registerPlainText } from '@lexical/plain-text' import { registerComposerKeymap } from '../src/client/input/editor/keymap.ts' describe('keymap keydown routing', () => { + it('clears composition presentation on root swaps and unregisters pending callbacks', async () => { + const editor = createEditor({ namespace: 'composition-root', onError: (e) => { throw e } }) + const first = document.createElement('div') + const second = document.createElement('div') + document.body.append(first, second) + onTestFinished(() => { + editor.setRootElement(null) + first.remove() + second.remove() + }) + editor.setRootElement(first) + const unregister = registerComposerKeymap(editor, { + arbitrate: () => 'pass', space: () => false, dismissPopup: () => {}, + canSubmit: () => false, submit: () => {}, intakeFiles: () => {}, pasteText: () => {}, + }) + onTestFinished(unregister) + fireEvent.compositionStart(first) + expect(first.hasAttribute('data-composer-composing')).toBe(true) + editor.setRootElement(second) + expect(first.hasAttribute('data-composer-composing')).toBe(false) + expect(second.hasAttribute('data-composer-composing')).toBe(false) + fireEvent.compositionStart(first) + expect(first.hasAttribute('data-composer-composing')).toBe(false) + fireEvent.compositionStart(second) + expect(second.hasAttribute('data-composer-composing')).toBe(true) + fireEvent.compositionEnd(second, { data: '' }) + unregister() + await Promise.resolve() + expect(second.hasAttribute('data-composer-composing')).toBe(false) + fireEvent.compositionStart(second) + expect(second.hasAttribute('data-composer-composing')).toBe(false) + }) + it('routes Enter to the keymap submit handler', () => { const editor = createEditor({ namespace: 'keymap-routing', onError: (e) => { throw e } }) const root = document.createElement('div') diff --git a/packages/client/ui-conversation/tests/lexical-editor-core.client.spec.tsx b/packages/client/ui-conversation/tests/lexical-editor-core.client.spec.tsx index 1fb06b9b25..92bfa3ce15 100644 --- a/packages/client/ui-conversation/tests/lexical-editor-core.client.spec.tsx +++ b/packages/client/ui-conversation/tests/lexical-editor-core.client.spec.tsx @@ -429,9 +429,9 @@ describe('claim precedence over text-ref entities', () => { const TOKEN_STYLE = 'color: var(--dsw-alias-state-warn-label)' const LEXICON: ReadonlyMap<'/' | '@', readonly string[]> = new Map([['/', ['plan']]]) - it('keeps a claimed lexicon-listed token plain and warn-styled until release', () => { + it.each(['/plan', '/plan '])('keeps the lexicon-listed %j claim plain and warn-styled until release', (token) => { const editor = makeEditor() - let claim: string | null = '/plan' + let claim: string | null = token registerClaimDecoration(editor, () => claim) registerTextRefDecoration(editor, () => LEXICON, () => claim) editor.update(() => { @@ -449,7 +449,7 @@ describe('claim precedence over text-ref entities', () => { } }) // Claimed: the entity transform yields the seat, the claim transform styles it. - expect(leaf()).toEqual({ type: 'text', style: TOKEN_STYLE, text: '/plan' }) + expect(leaf()).toEqual({ type: 'text', style: TOKEN_STYLE, text: token }) // Released (the shell's refresh nudges the seat dirty): the entity captures it. claim = null editor.update(() => { @@ -458,11 +458,11 @@ describe('claim precedence over text-ref entities', () => { }, { discrete: true }) expect(leaf()).toEqual({ type: 'composer-text-ref', style: '', text: '/plan' }) // Re-claimed: the entity reverts to plain text and the warn style returns. - claim = '/plan' + claim = token editor.update(() => { const first = ($getRoot().getFirstChild() as ParagraphNode).getFirstChild() if ($isTextNode(first)) first.markDirty() }, { discrete: true }) - expect(leaf()).toEqual({ type: 'text', style: TOKEN_STYLE, text: '/plan' }) + expect(leaf()).toEqual({ type: 'text', style: TOKEN_STYLE, text: token }) }) }) diff --git a/packages/client/ui-conversation/tests/submit-machine.client.spec.ts b/packages/client/ui-conversation/tests/submit-machine.client.spec.ts index 563079ef9e..575c568c97 100644 --- a/packages/client/ui-conversation/tests/submit-machine.client.spec.ts +++ b/packages/client/ui-conversation/tests/submit-machine.client.spec.ts @@ -192,7 +192,7 @@ describe('submit-machine: claimed lifecycle', () => { expect(m.state.phase).toBe('submitting') }) - it('breaking startsWith(token) auto-releases back to plain', () => { + it('editing the command name releases back to plain', () => { const m = new SubmitMachine() m.dispatch({ type: 'claim', claim: claimOf('goal') }) m.dispatch({ type: 'draft-changed', draft: '/goal args fine' }) @@ -202,6 +202,33 @@ describe('submit-machine: claimed lifecycle', () => { expect(m.state.claim).toBeUndefined() }) + it.each([ + ['goal', '/goal '], ['goal', '/目标 '], ['plan', '/plan '], ['plan', '/计划 '], + ['feedback', '/feedback '], ['feedback', '/反馈 '], + ])('retains %s as %s without its separator and submits an empty argument', (name, token) => { + const m = new SubmitMachine() + m.dispatch({ type: 'claim', claim: { ...claimOf(name), token } }) + for (const draft of [token + '这是目标', token, token.trimEnd(), token, token.trimEnd()]) { + m.dispatch({ type: 'draft-changed', draft }) + expect(m.state.phase).toBe('claimed') + expect(m.state.claim?.name).toBe(name) + } + const fx = m.dispatch({ type: 'enter', mode: 'queue', draft: token.trimEnd() }) + const begin = effectAt(fx, 0, 'begin-submit') + expect(begin.args).toBe('') + m.dispatch({ type: 'submit-settled', attempt: begin.attempt, ok: false, draft: token.trimEnd() }) + expect(m.state.phase).toBe('claimed') + expect(m.state.claim?.name).toBe(name) + }) + + it.each(['/目', '/目标x', '/目标/文件', '', '看看 /目标'])('releases a goal claim for %j', (draft) => { + const m = new SubmitMachine() + m.dispatch({ type: 'claim', claim: { ...claimOf('goal'), token: '/目标 ' } }) + m.dispatch({ type: 'draft-changed', draft }) + expect(m.state.phase).toBe('plain') + expect(m.state.claim).toBeUndefined() + }) + it('explicit release returns to plain when nothing is in flight', () => { const m = new SubmitMachine() m.dispatch({ type: 'claim', claim: claimOf('goal') }) diff --git a/packages/client/ui-input-trigger/src/client/MenuView.module.css b/packages/client/ui-input-trigger/src/client/MenuView.module.css index 4b9280fd4f..cb6ff3ec3a 100644 --- a/packages/client/ui-input-trigger/src/client/MenuView.module.css +++ b/packages/client/ui-input-trigger/src/client/MenuView.module.css @@ -6,14 +6,20 @@ left: 0; right: 0; z-index: 100; - /* Height cap: the 320px design maximum, clamped at runtime to the space - * above the composer (inline max-height set in MenuView.tsx). */ - max-height: 320px; + box-sizing: border-box; + /* Fits the built-in rows without scrolling and still clamps at runtime to + * the space above the composer (inline max-height set in MenuView.tsx). */ + max-height: 400px; overflow: hidden; /* Elevated surface: the scrollbar thumb takes the l2 elevation tokens (see ui-theme styles/scrollbar.css for the rebinding contract). */ --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); + /* A 10px draggable rail carries a quiet 4px thumb, inset from the card's + rounded ends. ui-theme's global scrollbar sheet renders these values. */ + --dsh-scrollbar-width: 10px; + --dsh-scrollbar-thumb-border: 3px; + --dsh-scrollbar-track-margin: 12px; padding: 4px; display: flex; flex-direction: column; @@ -24,6 +30,19 @@ box-shadow: var(--dsw-elevation-prominent); } +/* The hint covers content, not the scrollbar rail, and disappears once the + viewport reaches the final row. */ +.menu[data-overflow-below]::after { + content: ''; + position: absolute; + right: 14px; + bottom: 4px; + left: 4px; + height: 16px; + background: linear-gradient(to bottom, transparent, var(--dsw-specific-menu)); + pointer-events: none; +} + .viewport { display: flex; flex-direction: column; diff --git a/packages/client/ui-input-trigger/src/client/MenuView.tsx b/packages/client/ui-input-trigger/src/client/MenuView.tsx index 2c0fe990a4..fc2bdc7cd1 100644 --- a/packages/client/ui-input-trigger/src/client/MenuView.tsx +++ b/packages/client/ui-input-trigger/src/client/MenuView.tsx @@ -12,7 +12,7 @@ * (a localized title), then the description right-aligned. A source publishing crumbs gets a breadcrumb * header pinned above the scrolling list. */ -import { Fragment, useEffect, useRef, useSyncExternalStore } from 'react' +import { Fragment, useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react' import clsx from 'clsx' import { IconChevronRightOutline14, ReferenceIcon, useAnchoredMaxHeight } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' @@ -23,8 +23,8 @@ import type { MenuKey } from './locales.ts' /** Full menu props: injected face + the locale seat. */ export type MenuViewProps = MenuViewInjected & PropsLocale<'slash.menu'> -/** Design cap on the list height (figma SLASH 39:26572 MenuDropdown). */ -const MAX_HEIGHT = 320 +/** Height cap that fits the two headings and eight built-in command rows. */ +const MAX_HEIGHT = 400 /** DOM id of one option row (the aria-activedescendant target). */ function optionId(source: string, index: number): string { @@ -46,10 +46,20 @@ export function MenuView({ menu, headers, onPick, onCrumb, onHover, onDismiss, t () => headers.getSnapshot(), ) const listRef = useRef(null) + const viewportRef = useRef(null) + const [hasOverflowBelow, setHasOverflowBelow] = useState(false) // The list is bottom-anchored above the composer; clamp the design cap to // the space above it, re-measured on every store update (the anchor moves // when the composer grows). const maxHeight = useAnchoredMaxHeight(listRef, MAX_HEIGHT, state) + const updateOverflowHint = useCallback(() => { + const viewport = viewportRef.current + setHasOverflowBelow(viewport !== null + && viewport.scrollTop + viewport.clientHeight < viewport.scrollHeight - 1) + }, []) + useLayoutEffect(() => { + updateOverflowHint() + }, [state, maxHeight, updateOverflowHint]) const highlight = state.open ? state.highlight : null // Focus stays in the textarea (combobox pattern), so the browser never // scrolls the active option into view on keyboard moves — do it here. @@ -76,7 +86,13 @@ export function MenuView({ menu, headers, onPick, onCrumb, onHover, onDismiss, t return ( // The listbox role sits on the scrolling viewport, not this shell: a // breadcrumb header is not an option, and a listbox may not carry one. -
+
{state.groups.map((group) => { const trail = crumbs.get(group.source) return trail === undefined ? null : ( @@ -103,10 +119,12 @@ export function MenuView({ menu, headers, onPick, onCrumb, onHover, onDismiss, t ) })}
{state.groups.map(group => (group.status === 'ready' && group.items.length === 0) ? null diff --git a/packages/client/ui-input-trigger/tests/menu-view.client.spec.tsx b/packages/client/ui-input-trigger/tests/menu-view.client.spec.tsx index 13fe143544..e2430f5670 100644 --- a/packages/client/ui-input-trigger/tests/menu-view.client.spec.tsx +++ b/packages/client/ui-input-trigger/tests/menu-view.client.spec.tsx @@ -238,7 +238,7 @@ describe('MenuView', () => { it('caps the list height at the design maximum when the composer sits low enough', () => { vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({ bottom: 800 } as DOMRect) mount(openState()) - expect(menuShell().style.maxHeight).toBe('320px') + expect(menuShell().style.maxHeight).toBe('400px') }) it('clamps the list height to the space above the composer minus the safe margin', () => { @@ -251,12 +251,27 @@ describe('MenuView', () => { const rect = vi.spyOn(Element.prototype, 'getBoundingClientRect') rect.mockReturnValue({ bottom: 800 } as DOMRect) mount(openState()) - expect(menuShell().style.maxHeight).toBe('320px') + expect(menuShell().style.maxHeight).toBe('400px') rect.mockReturnValue({ bottom: 100 } as DOMRect) act(() => { window.dispatchEvent(new Event('resize')) }) expect(menuShell().style.maxHeight).toBe('88px') }) + it('shows the bottom overflow hint until the list reaches its final row', () => { + mount(openState()) + const listbox = screen.getByRole('listbox') + Object.defineProperties(listbox, { + clientHeight: { configurable: true, value: 320 }, + scrollHeight: { configurable: true, value: 392 }, + scrollTop: { configurable: true, value: 0, writable: true }, + }) + fireEvent.scroll(listbox) + expect(menuShell().hasAttribute('data-overflow-below')).toBe(true) + listbox.scrollTop = 72 + fireEvent.scroll(listbox) + expect(menuShell().hasAttribute('data-overflow-below')).toBe(false) + }) + it('pointerdown outside the menu (no composer card ancestor) dismisses', () => { const { onDismiss } = mount(openState()) fireEvent.pointerDown(document.body) diff --git a/packages/client/ui-theme/README.i18n.yaml b/packages/client/ui-theme/README.i18n.yaml index e023867f5b..c8a96f84b6 100644 --- a/packages/client/ui-theme/README.i18n.yaml +++ b/packages/client/ui-theme/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-theme/README.md -README.md: 7c5ba6541601bbe506a0707e3ebfd75a1f30ade9 -README.zh.md: 6c82a1be39fff0ff827d515e870775aa9571ad2c +README.md: 291492b9b41df6570722fb2dbd14565c660ec350 +README.zh.md: 2883dd50ef6c70b2229b98c7434ca5317c5debe9 diff --git a/packages/client/ui-theme/README.md b/packages/client/ui-theme/README.md index 7c5ba65416..291492b9b4 100644 --- a/packages/client/ui-theme/README.md +++ b/packages/client/ui-theme/README.md @@ -59,7 +59,7 @@ The service owns theme and font-size state and publishes snapshots. The ui-layou ### Scrollbar rebinding -`scrollbar.css` binds `--dsh-scrollbar-thumb` and `--dsh-scrollbar-thumb-hover` on `body` to the l1 base-surface tokens; an elevated surface (menu, popover, dialog) rebinds them to the l2 tokens on its own container, and the pair's other legal target is `transparent` (ui-sidebar rebinds its column that way while the pointer is elsewhere). `--dsh-scrollbar-width` mirrors the WebKit bar's layout width for surfaces that align beside a space-consuming bar. The two rendering paths are mutually exclusive by construction: Firefox takes the standard properties inside `@supports not selector(::-webkit-scrollbar)`, and WebKit-based engines take the pseudo-elements, so the hover token only ever renders through the pseudo-element path. +`scrollbar.css` binds `--dsh-scrollbar-thumb` and `--dsh-scrollbar-thumb-hover` on `body` to the l1 base-surface tokens; an elevated surface (menu, popover, dialog) rebinds them to the l2 tokens on its own container, and the pair's other legal target is `transparent` (ui-sidebar rebinds its column that way while the pointer is elsewhere). WebKit-based browsers also read `--dsh-scrollbar-width`, `--dsh-scrollbar-thumb-border`, and `--dsh-scrollbar-track-margin`; a scroll surface may rebind them to keep a wide draggable rail around a narrower visible thumb or to inset the track from rounded ends. The two rendering paths are mutually exclusive by construction: Firefox takes the standard thin scrollbar inside `@supports not selector(::-webkit-scrollbar)`, and WebKit-based engines take the pseudo-elements, so geometry and hover customization apply only through the pseudo-element path. ### Preference persistence diff --git a/packages/client/ui-theme/README.zh.md b/packages/client/ui-theme/README.zh.md index 6c82a1be39..2883dd50ef 100644 --- a/packages/client/ui-theme/README.zh.md +++ b/packages/client/ui-theme/README.zh.md @@ -59,7 +59,7 @@ kind: "package-reference" ### 滚动条重新绑定 -`scrollbar.css` 在 `body` 上把 `--dsh-scrollbar-thumb` 与 `--dsh-scrollbar-thumb-hover` 绑定到 l1 基础表面 token;高层级表面(菜单、浮层、对话框)在自己的容器上把它们重新绑定为 l2 token;这组变量的另一个合法目标是 `transparent`(ui-sidebar 在指针不在栏内时就这样重新绑定自己的列)。`--dsh-scrollbar-width` 镜像 WebKit 滚动条的布局宽度,供需要与占布局宽度的滚动条对齐的表面使用。两条渲染路径在构造上互斥:Firefox 走 `@supports not selector(::-webkit-scrollbar)` 内的标准属性,WebKit 系引擎走伪元素,因此 hover token 只经由伪元素这条路径渲染。 +`scrollbar.css` 在 `body` 上把 `--dsh-scrollbar-thumb` 与 `--dsh-scrollbar-thumb-hover` 绑定到 l1 基础表面 token;高层级表面(菜单、浮层、对话框)在自己的容器上把它们重新绑定为 l2 token;这组变量的另一个合法目标是 `transparent`(ui-sidebar 在指针不在栏内时就这样重新绑定自己的列)。WebKit 系浏览器还会读取 `--dsh-scrollbar-width`、`--dsh-scrollbar-thumb-border` 与 `--dsh-scrollbar-track-margin`;滚动表面可重新绑定它们,在较窄的可见滑块外保留较宽的拖动区域,或让轨道避开圆角两端。两条渲染路径在构造上互斥:Firefox 走 `@supports not selector(::-webkit-scrollbar)` 内的标准细滚动条,WebKit 系引擎走伪元素,因此几何与 hover 定制只经由伪元素路径生效。 ### 偏好持久化 diff --git a/packages/client/ui-theme/src/styles/scrollbar.css b/packages/client/ui-theme/src/styles/scrollbar.css index 71f67d4f57..d61bcbcedb 100644 --- a/packages/client/ui-theme/src/styles/scrollbar.css +++ b/packages/client/ui-theme/src/styles/scrollbar.css @@ -10,13 +10,14 @@ * * Surfaces pick their elevation by rebinding --dsh-scrollbar-thumb{,-hover}: * the l1 pair here is the base-surface default, and an elevated surface - * (menu, popover, dialog) rebinds to the l2 pair on its own container. Both - * rendering paths below read the indirection, so one rebind reaches whichever - * path the engine took. */ + * (menu, popover, dialog) rebinds to the l2 pair on its own container. A + * scroll container may also rebind the three geometry variables below. */ body { --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l1); --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l1); + --dsh-scrollbar-thumb-border: 0px; + --dsh-scrollbar-track-margin: 0px; /* The WebKit bar's layout width, mirrored by the ::-webkit-scrollbar rule below. A surface that must align itself beside a space-consuming bar (ConversationRoot's overlay composer seat) reads this instead of @@ -64,23 +65,27 @@ body { selector matching already does. Not inherited either, hence the unscoped selectors. */ ::-webkit-scrollbar { - width: 8px; - height: 8px; + width: var(--dsh-scrollbar-width); + height: var(--dsh-scrollbar-width); } /* Track stays transparent so the thumb reads against whatever surface scrolls under it; only the thumb carries a token colour. */ ::-webkit-scrollbar-track { + margin-block: var(--dsh-scrollbar-track-margin); background: transparent; } ::-webkit-scrollbar-thumb { - border-radius: 4px; + border: var(--dsh-scrollbar-thumb-border) solid transparent; + border-radius: 999px; + corner-shape: round; background: var(--dsh-scrollbar-thumb); + background-clip: content-box; } ::-webkit-scrollbar-thumb:hover { - background: var(--dsh-scrollbar-thumb-hover); + background-color: var(--dsh-scrollbar-thumb-hover); } /* Both scrollbars meeting in a corner: no separate token, so the corner diff --git a/packages/client/ui-theme/tests/scrollbar-styles.client.spec.ts b/packages/client/ui-theme/tests/scrollbar-styles.client.spec.ts index c772bc92d5..9682bdeb3c 100644 --- a/packages/client/ui-theme/tests/scrollbar-styles.client.spec.ts +++ b/packages/client/ui-theme/tests/scrollbar-styles.client.spec.ts @@ -2,9 +2,9 @@ * Scrollbar stylesheet contract, asserted against the CSS text on disk: every * --dsw-alias-scrollbar-* token design-platform.css defines has a consumer, * scrollbar.css binds the base-surface pair through the rebindable - * indirection, the width variable mirrors the ::-webkit-scrollbar rule for - * consumers that align beside the bar, and elevated surfaces rebind that - * indirection in complete pairs. The expected token set is scanned out of + * indirection, the WebKit geometry reads the shared width, thumb-border, and + * track-margin variables, and elevated surfaces rebind the colour indirection + * in complete pairs. The expected token set is scanned out of * design-platform.css, so adding, renaming, or dropping a scrollbar token * moves these assertions with it. */ @@ -25,6 +25,11 @@ const DARK_ATTRIBUTE = '[data-ds-dark-theme]' const TOKEN_PREFIX = '--dsw-alias-scrollbar-' /** Prefix of the rebindable indirection scrollbar.css owns. */ const INDIRECTION_PREFIX = '--dsh-scrollbar-' +/** The elevation-aware colour variables surfaces rebind as one pair. */ +const COLOUR_INDIRECTIONS = new Set([ + `${INDIRECTION_PREFIX}thumb`, + `${INDIRECTION_PREFIX}thumb-hover`, +]) /** The one non-token rebind value: a surface that draws no thumb at all. */ const HIDDEN_THUMB = 'transparent' /** The elevation rebind, spelled per property: value-wholeness, not token shape. */ @@ -68,6 +73,14 @@ const platformRules = parseRules(platformCss) const scrollbarRules = parseRules(scrollbarCss) const sorted = (names: Iterable): string[] => [...names].sort() +/** Last value one selector declares for a property. */ +function declaration(rules: CssRule[], property: string, selectorPart: string): string | undefined { + return rules + .filter(rule => rule.selectors.includes(selectorPart)) + .flatMap(rule => rule.declarations) + .findLast(([name]) => name === property)?.[1] +} + /** * Scrollbar tokens defined by the rules whose selectors carry (or do not * carry) the dark palette attribute. @@ -175,7 +188,7 @@ for (const file of packageStylesheets()) { let rebindsElevation = false const ruleSurfaces: string[] = [] for (const [property, value] of rule.declarations) { - if (property.startsWith(INDIRECTION_PREFIX) && file !== fileURLToPath(new URL('scrollbar.css', STYLES))) { + if (COLOUR_INDIRECTIONS.has(property) && file !== fileURLToPath(new URL('scrollbar.css', STYLES))) { rebinds = true if (value !== HIDDEN_THUMB) rebindsElevation = true } @@ -248,48 +261,39 @@ describe('scrollbar.css base-surface binding', () => { it('routes the standard property and the WebKit thumb through the same indirection', () => { // A rebind on an elevated container has to move the Firefox and the WebKit // rendering together, which only holds while both read the same variable. - const declaration = (property: string, selectorPart: string): string | undefined => scrollbarRules - .filter(rule => rule.selectors.includes(selectorPart)) - .flatMap(rule => rule.declarations) - .findLast(([name]) => name === property)?.[1] - const thumbColor = declaration('scrollbar-color', 'body') + const thumbColor = declaration(scrollbarRules, 'scrollbar-color', 'body') expect(thumbColor).toBeDefined() const indirection = varReferences(thumbColor!)[0] expect(indirection).toBe(`${INDIRECTION_PREFIX}thumb`) - expect(varReferences(declaration('background', '::-webkit-scrollbar-thumb')!)).toEqual([indirection]) + expect(varReferences(declaration(scrollbarRules, 'background', '::-webkit-scrollbar-thumb')!)).toEqual([indirection]) }) }) -describe('scrollbar.css width variable', () => { +describe('scrollbar.css geometry variables', () => { const WIDTH_VARIABLE = `${INDIRECTION_PREFIX}width` + const THUMB_BORDER_VARIABLE = `${INDIRECTION_PREFIX}thumb-border` + const TRACK_MARGIN_VARIABLE = `${INDIRECTION_PREFIX}track-margin` + const GEOMETRY_VARIABLES = [WIDTH_VARIABLE, THUMB_BORDER_VARIABLE, TRACK_MARGIN_VARIABLE] - it('defines the width variable on body as a static length', () => { - // The overlay seat compensation reads a fixed number, not a second - // indirection: the mirror check below compares the WebKit rule against - // this value, so a var()-to-var() chain would compare one indirection to - // another instead of pinning the number. - const value = scrollbarRules + it('defines each geometry variable on body as a static length', () => { + const definitions = new Map(scrollbarRules .filter(rule => rule.selectors.includes('body')) .flatMap(rule => rule.declarations) - .findLast(([property]) => property === WIDTH_VARIABLE)?.[1] - expect(value, WIDTH_VARIABLE).toBeDefined() - expect(value, WIDTH_VARIABLE).toMatch(/^\d+(?:\.\d+)?px$/) + .filter(([property]) => GEOMETRY_VARIABLES.includes(property))) + for (const property of GEOMETRY_VARIABLES) { + expect(definitions.get(property), property).toMatch(/^\d+(?:\.\d+)?px$/) + } }) - it('mirrors the ::-webkit-scrollbar width rule with the variable value', () => { - // The compensation stays aligned with the WebKit bar only while both read - // the same number. A change to one side without the other puts the overlay - // seat a band off from Chat on WebKit engines. - const variableValue = scrollbarRules - .filter(rule => rule.selectors.includes('body')) - .flatMap(rule => rule.declarations) - .findLast(([property]) => property === WIDTH_VARIABLE)?.[1] + it('routes WebKit scrollbar geometry through those variables', () => { const webkitWidth = scrollbarRules .filter(rule => rule.selectors.includes('::-webkit-scrollbar')) .flatMap(rule => rule.declarations) .findLast(([property]) => property === 'width')?.[1] expect(webkitWidth, '::-webkit-scrollbar width').toBeDefined() - expect(webkitWidth).toBe(variableValue) + expect(varReferences(webkitWidth!)).toEqual([WIDTH_VARIABLE]) + expect(varReferences(declaration(scrollbarRules, 'border', '::-webkit-scrollbar-thumb')!)).toEqual([THUMB_BORDER_VARIABLE]) + expect(varReferences(declaration(scrollbarRules, 'margin-block', '::-webkit-scrollbar-track')!)).toEqual([TRACK_MARGIN_VARIABLE]) }) it('every reader of the width variable outside ui-theme references a defined variable', () => { @@ -422,10 +426,8 @@ describe('elevated surface rebinds', () => { // A surface rebinding only the resting colour keeps the l1 hover colour, // so the elevation is wrong only while the pointer is over the thumb. for (const { file, rule } of rebindRules) { - const properties = rule.declarations.map(([property]) => property).filter(property => property.startsWith(INDIRECTION_PREFIX)) - expect(sorted(properties), `${file} ${rule.selectors.join(', ')}`).toEqual([ - `${INDIRECTION_PREFIX}thumb-hover`, `${INDIRECTION_PREFIX}thumb`, - ].sort()) + const properties = rule.declarations.map(([property]) => property).filter(property => COLOUR_INDIRECTIONS.has(property)) + expect(sorted(properties), `${file} ${rule.selectors.join(', ')}`).toEqual(sorted(COLOUR_INDIRECTIONS)) } }) @@ -459,7 +461,7 @@ describe('elevated surface rebinds', () => { // white)` and a crossed pair (the hover token bound to the resting // property); neither is what the contract says. for (const { file, rule } of rebindRules) { - const rebinds = rule.declarations.filter(([property]) => property.startsWith(INDIRECTION_PREFIX)) + const rebinds = rule.declarations.filter(([property]) => COLOUR_INDIRECTIONS.has(property)) const where = `${file} ${rule.selectors.join(', ')}` if (rebinds.every(([, value]) => value === HIDDEN_THUMB)) continue expect(rebinds.some(([, value]) => value === HIDDEN_THUMB), `${where}: mixes ${HIDDEN_THUMB} with an elevation`).toBe(false) From 5a878f7c3e1485acdcce4e20b6017bb278c7909f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 9 Sep 2026 15:24:56 +0800 Subject: [PATCH 09/52] test(web): await restored theme before changing preference --- apps/web/tests/settings-chrome.e2e.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/web/tests/settings-chrome.e2e.ts b/apps/web/tests/settings-chrome.e2e.ts index 55d64f199f..739d01ce18 100644 --- a/apps/web/tests/settings-chrome.e2e.ts +++ b/apps/web/tests/settings-chrome.e2e.ts @@ -262,6 +262,9 @@ describe('web e2e: settings modal and General preferences', () => { await page.getByRole('button', { name: '设置', exact: true }).click() const restoredDialog = page.getByRole('dialog', { name: '设置' }) const systemCube = restoredDialog.getByRole('button', { name: '跟随系统' }) + // The boot palette precedes the settings mirror's saved preference. + const restoredDarkCube = restoredDialog.getByRole('button', { name: '深色' }) + await expect.poll(() => restoredDarkCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true') await selectTheme(systemCube, 'system') await expect.poll(() => systemCube.getAttribute('aria-pressed'), { timeout: 5_000 }).toBe('true') await expect.poll(() => page.evaluate(() => document.body.hasAttribute('data-ds-dark-theme')), { From a43fa81f82ec383cc878a775c0cb95b0e19e7a34 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 9 Sep 2026 16:08:19 +0800 Subject: [PATCH 10/52] test: respect startup and teardown budgets in Windows fixtures --- ...9-08-ci-readiness-and-completion.i18n.yaml | 4 +- .../2026-09-08-ci-readiness-and-completion.md | 4 + ...26-09-08-ci-readiness-and-completion.zh.md | 4 + .../inspector/tests/cordis-tree.host.spec.ts | 78 ++++++++++++++++--- .../tests/subagent-dsh-sdk.spec.ts | 12 ++- 5 files changed, 82 insertions(+), 20 deletions(-) diff --git a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.i18n.yaml b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.i18n.yaml index dbbc4ea266..f96c72c081 100644 --- a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.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/testing/2026-09-08-ci-readiness-and-completion.md -2026-09-08-ci-readiness-and-completion.md: 2249df5467189975aca2d73ec56c6cf82ec7b62f -2026-09-08-ci-readiness-and-completion.zh.md: ccf8e7c16903b66e39bc48e99460e5c5179ab51b +2026-09-08-ci-readiness-and-completion.md: c72048ef90b987e7d27992b1754736b2ce895093 +2026-09-08-ci-readiness-and-completion.zh.md: 1188d66249b3092416435da2e8496a657ad00677 diff --git a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.md b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.md index 2249df5467..c72048ef90 100644 --- a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.md +++ b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.md @@ -14,6 +14,8 @@ The [ACP coverage run](https://github.com/deepseek-harness/deepseek-harness/acti A [worker-runtime coverage failure](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34248221544/job/102135631932) exhausts the slow-binding fixture's one-second compute allowance. Concurrent native Windows reproductions exceed that allowance before calling the binding. Worker initialization contributes measured active time; the delayed binding contributes idle time. +The [Windows coverage run](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34324325375/job/102377982193) reports an SDK subprocess exit beyond a fixture's 200 ms confirmation window and an Inspector Worker startup beyond its ten-second default. Neither the protocol-error routing case nor the Cordis tree projection case measures those latency guarantees. + ## Decision The [webhook browser test](../../../../apps/web/tests/github-ready-review.e2e.ts) observes the model request caused by delivery before checking Session registration. The [feedback test](../../../../apps/web/tests/feedback-command.e2e.ts) waits for the empty composer and enabled attachment control before comparing ARIA output. Matching consecutive snapshots cannot prove that the command RPC has settled: its event stream can publish the acknowledgement first. @@ -28,6 +30,8 @@ The [subagent teardown decision](2026-09-07-subagent-teardown-test-budgets.md) o The [worker-runtime binding test](../../../../packages/code-runtime/code-runtime-worker-thread/tests/runtime.spec.ts) allows five seconds of compute for source-worker initialization and delays the binding for 6.5 seconds. Charging that idle delay would still exceed the entire compute allowance. The case retains its 15-second test limit and 30-second wall ceiling, registers Context and reply-timer cleanup, and leaves the hot-loop, decoy-dispatch, wall-ceiling, and abort controls at their existing limits. Production budgets remain unchanged. +The [SDK subagent protocol-error test](../../../../packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts) uses the provider's normal shutdown and exit grace periods and registers disposal before its assertions. The [Inspector tree tests](../../../../packages/experimental/inspector/tests/cordis-tree.host.spec.ts) pass the active test budget to Worker startup and register cleanup while startup is still pending. A cancelled test cannot receive a late-ready handle; cleanup awaits initialization and closes a successfully started Worker. Failed initialization already terminates the Worker before rejecting. A controlled late-start test verifies cancellation and closure through the real Worker's HTTP endpoint. Production defaults remain unchanged. + ## Alternatives considered **Larger independent waits.** Rejected where a completion promise already exists. A separate polling deadline continues to compete with the execution lane's budget. diff --git a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.zh.md b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.zh.md index ccf8e7c169..1188d66249 100644 --- a/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.zh.md +++ b/.agents/notes/implemented/testing/2026-09-08-ci-readiness-and-completion.zh.md @@ -14,6 +14,8 @@ Status: implemented 一次 [worker runtime coverage 失败](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34248221544/job/102135631932)耗尽了慢 binding 夹具的一秒计算额度。原生 Windows 并发复现在调用 binding 前已超过该额度。Worker 初始化会累计所测的活跃时间;延迟的 binding 累计空闲时间。 +[Windows 覆盖率运行](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34324325375/job/102377982193)报告了 SDK 子进程退出超过测试设置的 200 毫秒确认期限,以及 Inspector Worker 启动超过十秒默认期限。协议错误转发用例和 Cordis 树投影用例都不衡量这些延迟保证。 + ## 决策 [Webhook 浏览器测试](../../../../apps/web/tests/github-ready-review.e2e.ts)观察投递触发的模型请求后再检查 Session 注册。[反馈测试](../../../../apps/web/tests/feedback-command.e2e.ts)在比较 ARIA 输出前等待输入框清空且附件按钮启用。连续两次快照相同不能证明命令 RPC 已完成:事件流可能先发布确认消息。 @@ -28,6 +30,8 @@ Status: implemented [Worker runtime binding 测试](../../../../packages/code-runtime/code-runtime-worker-thread/tests/runtime.spec.ts)为源码 worker 初始化保留五秒计算额度,并将 binding 延迟设为 6.5 秒。若将该空闲延迟计费,仍会超过整个计算额度。用例保留 15 秒测试期限与 30 秒墙钟上限,登记 Context 和回复定时器的清理,并保持热循环、诱饵 dispatch、墙钟上限及取消控制用例的原有限制。生产预算不变。 +[SDK 子 Agent 协议错误测试](../../../../packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts)使用提供方正常的关闭和退出等待时间,并在断言前登记清理。[Inspector 树测试](../../../../packages/experimental/inspector/tests/cordis-tree.host.spec.ts)将当前测试预算传给 Worker 启动,并在启动尚未完成时登记清理。取消后的测试不会收到随后才就绪的实例;清理等待初始化完成,并关闭成功启动的 Worker。初始化失败时,启动操作会在拒绝前终止 Worker。受控的延迟启动测试通过真实 Worker 的 HTTP 端点验证取消和关闭。生产默认值不变。 + ## 考虑过的替代方案 **增大独立等待时限。** 已有完成 Promise 时不采用。独立轮询期限仍会与执行通道的预算竞争。 diff --git a/packages/experimental/inspector/tests/cordis-tree.host.spec.ts b/packages/experimental/inspector/tests/cordis-tree.host.spec.ts index 46bbad99be..9cabf89f48 100644 --- a/packages/experimental/inspector/tests/cordis-tree.host.spec.ts +++ b/packages/experimental/inspector/tests/cordis-tree.host.spec.ts @@ -2,10 +2,11 @@ import { Context } from '@deepseek-ai/cordis' import WebSocket, { type RawData } from 'ws' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi, type TestContext } from 'vitest' import { CordisTreeCollector } from '../src/shared/cordis/collector.ts' import { observeCordisTree } from '../src/shared/cordis/observer.ts' -import { startInspector, type InspectorHandle } from '../src/host/bridge/controller.ts' +import * as inspectorBridge from '../src/host/bridge/controller.ts' +import type { InspectorHandle, InspectorOptions } from '../src/host/bridge/controller.ts' import { publishCordisTree as publishHostCordisTree } from '../src/host/inspection/cordis.ts' import { parseCordisTreeSnapshot, type CordisTreeNode } from '../src/shared/cordis/snapshot.ts' import { inspectorId } from '../src/shared/bridge/ids.ts' @@ -76,6 +77,19 @@ class CdpClient { } } +/** Own pending startup through cancellation; tree assertions do not measure Worker cold-start latency. */ +async function startTestInspector(options: InspectorOptions, test: TestContext): Promise { + const pending = inspectorBridge.startInspector({ ...options, startupTimeoutMs: test.task.timeout }) + test.onTestFinished(async () => { + // Failed starts terminate their Worker before rejecting. + const [started] = await Promise.allSettled([pending]) + if (started.status === 'fulfilled') await started.value.close() + }) + const handle = await pending + test.signal.throwIfAborted() + return handle +} + describe('Cordis tree inspection', () => { let inspector: InspectorHandle | undefined let cdp: CdpClient | undefined @@ -84,6 +98,48 @@ describe('Cordis tree inspection', () => { const observers: Array<() => void> = [] const fibers: Array<{ dispose(): Promise }> = [] + it('closes a late-starting Worker after test cancellation without returning its handle', async (test) => { + const release = Promise.withResolvers() + const controller = new AbortController() + const cleanups: Array[0]> = [] + let starting: Promise | undefined + const start = inspectorBridge.startInspector + const spy = vi.spyOn(inspectorBridge, 'startInspector').mockImplementation(async (options) => { + starting = start(options) + const handle = await starting + await release.promise + return handle + }) + test.onTestFinished(async () => { + release.resolve(undefined) + spy.mockRestore() + if (starting === undefined) return + const [started] = await Promise.allSettled([starting]) + if (started.status === 'fulfilled') await started.value.close() + }) + const pending = startTestInspector({ port: 0, captureFetch: false }, { + ...test, + signal: controller.signal, + onTestFinished: (cleanup) => { cleanups.push(cleanup) }, + }) + const result = pending.then( + handle => ({ status: 'fulfilled' as const, handle }), + (reason: unknown) => ({ status: 'rejected' as const, reason }), + ) + if (starting === undefined) throw new Error('Inspector startup was not called') + const handle = await starting + expect(spy).toHaveBeenCalledWith(expect.objectContaining({ startupTimeoutMs: test.task.timeout })) + expect(cleanups).toHaveLength(1) + const cancelled = new Error('test cancelled during startup') + controller.abort(cancelled) + release.resolve(undefined) + const outcome = await result + expect(outcome.status).toBe('rejected') + expect('reason' in outcome ? outcome.reason : undefined).toBe(cancelled) + await cleanups[0]!(test) + await expect(fetch(handle.endpoint.httpUrl)).rejects.toThrow() + }) + afterEach(async () => { for (const dispose of observers.splice(0).reverse()) dispose() for (const fiber of fibers.splice(0).reverse()) await fiber.dispose() @@ -362,8 +418,8 @@ describe('Cordis tree inspection', () => { backend.close() }) - it('projects Host and Client trees and resolves both node kinds to RemoteObjects', async () => { - inspector = await startInspector({ port: 0, captureFetch: false, maxCordisNodes: 100 }) + it('projects Host and Client trees and resolves both node kinds to RemoteObjects', async (test) => { + inspector = await startTestInspector({ port: 0, captureFetch: false, maxCordisNodes: 100 }, test) const host = new Context() const hostFiber = host.plugin({ name: 'host-child', apply() {} }) fibers.push(hostFiber) @@ -540,8 +596,8 @@ describe('Cordis tree inspection', () => { expect(disconnectedTree.clients[0]?.connection.state).toBe('disconnected') }) - it('emits only node-level DOM changes for Client snapshots', async () => { - inspector = await startInspector({ port: 0, captureFetch: false, maxCordisNodes: 100 }) + it('emits only node-level DOM changes for Client snapshots', async (test) => { + inspector = await startTestInspector({ port: 0, captureFetch: false, maxCordisNodes: 100 }, test) cdp = await CdpClient.connect(inspector.endpoint.webSocketDebuggerUrl) const initialDocument = (await cdp.call('DOM.getDocument')).result?.root as CdpNode const clientsNode = initialDocument.children?.find(node => node.localName === 'clients') @@ -598,8 +654,8 @@ describe('Cordis tree inspection', () => { }) }) - it('serves three document levels by default and withheld levels on demand', async () => { - inspector = await startInspector({ port: 0, captureFetch: false, maxCordisNodes: 100 }) + it('serves three document levels by default and withheld levels on demand', async (test) => { + inspector = await startTestInspector({ port: 0, captureFetch: false, maxCordisNodes: 100 }, test) const host = new Context() let innerFiber: { uid: number | null } | undefined const outer = host.plugin({ @@ -680,14 +736,14 @@ describe('Cordis tree inspection', () => { expect(secondCdp.events.slice(offset).some(event => event.method === 'DOM.setChildNodes')).toBe(false) }) - it('restores a disconnected Client tree from a new transport generation', async () => { - inspector = await startInspector({ + it('restores a disconnected Client tree from a new transport generation', async (test) => { + inspector = await startTestInspector({ port: 0, captureFetch: false, maxCordisNodes: 100, clientReconnectBaseMs: 10, clientReconnectMaxMs: 20, - }) + }, test) clientSource = await InspectorClientFixture.start(inspector.endpoint.client, { label: 'Reconnect Client' }) cdp = await CdpClient.connect(inspector.endpoint.webSocketDebuggerUrl) await cdp.call('Runtime.enable') diff --git a/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts b/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts index b9fa8c55c0..ba26c0c69c 100644 --- a/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts +++ b/packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts @@ -6,7 +6,7 @@ * quiescent disposal are all exercised end to end. No model, no key. */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -751,19 +751,17 @@ describe('dsh-subagent-dsh-sdk provider', () => { cwd: process.cwd(), provider: 'p', model: 'm', - // The fake dies as soon as the prompt arrives: FAKE_HANG_PROMPT plus a - // short-lived process is simulated by killing via dispose below instead; - // here use FAKE_MALFORMED to make the prompt reply violate the protocol. env: { FAKE_MALFORMED_PROMPT: '1' }, - shutdownTimeoutMs: 100, - disposeEofGraceMs: 200, - disposeGraceMs: 200, + shutdownTimeoutMs: DEFAULT_SHUTDOWN_TIMEOUT_MS, + disposeEofGraceMs: DEFAULT_DISPOSE_EOF_GRACE_MS, + disposeGraceMs: DEFAULT_DISPOSE_GRACE_MS, onError: (error) => { seen.push(error.message) throw new Error('sink failure must be contained') }, } const run = await startSdkRun(request(), spec) + onTestFinished(() => run.dispose()) const result = await run.result expect(result.stopReason).toBe('error') expect(result.diagnostic).toBe( From 9bae613128a725cc44dc140cf629a57f74524f94 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Wed, 9 Sep 2026 17:31:16 +0800 Subject: [PATCH 11/52] ci: add an opt-in canary value to the CI pool failover switches The per-platform failover repository variables (DSH_CI_FAILOVER_LINUX and DSH_CI_FAILOVER_WINDOWS) accept a third value alongside the existing selfhosted routing. Set by a repository writer, the value retargets the always-on pull-request and master lanes onto the matching hosted-runner labels (16-core pools map to the 16-vCPU tier, standard legs to 4-vCPU); unset or any other value keeps today's runners, so the leg is dormant until a writer opts in - a canary path for capacity fallback, never the default. Participating jobs: the three enterprise Linux workers, the node-compat legs, the four Windows lanes, and the all-checks-passed verdict in ci.yml; expected-filenames; the sandbox bwrap leg; and the two manual benchmark matrices (4-32 vCPU tiers map to equivalents; 64/96-core rows keep the fleet labels). Everything pinned to its own runner by spec, credential, or host capability keeps it under every value, and the release-shaped chains stay entirely hosted. request-review.yml was retired on master while this work was in flight and the branch takes the deletion. Specs pin the new branches: ci-workflow.spec.ts asserts the labels appear in the extended selectors, and ci-compatible-selfhosted.spec.ts evaluates the routing mode. --- .github/workflows/ci-master.yml | 44 +++++++++++++++- .github/workflows/ci.yml | 41 ++++++++++----- .github/workflows/expected-filenames.yml | 4 +- .github/workflows/sandbox.yml | 11 +++- scripts/ci-compatible-selfhosted.spec.ts | 3 ++ scripts/ci-workflow.spec.ts | 64 ++++++++++++++++++++++++ 6 files changed, 151 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci-master.yml b/.github/workflows/ci-master.yml index df9f7f2bcc..daf8a6cb80 100644 --- a/.github/workflows/ci-master.yml +++ b/.github/workflows/ci-master.yml @@ -284,7 +284,15 @@ jobs: # The named pools are restricted at the organization level to this repository. larger-runner-benchmark: if: github.event_name == 'workflow_dispatch' && inputs.suite == 'larger-runner-benchmark' - runs-on: ${{ matrix.runner }} + # Default measures the repository's own fleet tiers; under the matching + # platform's blacksmith failover value the tiers Blacksmith offers (up to + # 32 vCPU) move onto their Blacksmith equivalents, while the 64/96-core + # rows keep the fleet labels because Blacksmith has no such tier. + runs-on: >- + ${{ (matrix.platform == 'linux' && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' + || matrix.platform == 'windows' && vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith') + && matrix.blacksmith + || matrix.runner }} timeout-minutes: 15 strategy: fail-fast: false @@ -294,50 +302,62 @@ jobs: - platform: linux cores: '4' runner: dsh-ubuntu-24-04-4core + blacksmith: blacksmith-4vcpu-ubuntu-2404 workload: typecheck - platform: linux cores: '8' runner: dsh-ubuntu-24-04-8core + blacksmith: blacksmith-8vcpu-ubuntu-2404 workload: typecheck - platform: linux cores: '16' runner: dsh-ubuntu-24-04-16core + blacksmith: blacksmith-16vcpu-ubuntu-2404 workload: typecheck - platform: linux cores: '32' runner: dsh-ubuntu-24-04-32core + blacksmith: blacksmith-32vcpu-ubuntu-2404 workload: typecheck - platform: linux cores: '64' runner: dsh-ubuntu-24-04-64core + blacksmith: '' workload: typecheck - platform: linux cores: '96' runner: dsh-ubuntu-24-04-96core + blacksmith: '' workload: typecheck - platform: windows cores: '4' runner: dsh-windows-2025-4core + blacksmith: blacksmith-4vcpu-windows-2025 workload: production-site - platform: windows cores: '8' runner: dsh-windows-2025-8core + blacksmith: blacksmith-8vcpu-windows-2025 workload: production-site - platform: windows cores: '16' runner: dsh-windows-2025-16core + blacksmith: blacksmith-16vcpu-windows-2025 workload: production-site - platform: windows cores: '32' runner: dsh-windows-2025-32core + blacksmith: blacksmith-32vcpu-windows-2025 workload: production-site - platform: windows cores: '64' runner: dsh-windows-2025-64core + blacksmith: '' workload: production-site - platform: windows cores: '96' runner: dsh-windows-2025-96core + blacksmith: '' workload: production-site steps: - uses: actions/checkout@v6 @@ -375,7 +395,15 @@ jobs: # Windows runs both blocking build targets concurrently through run-gates. consolidated-runner-benchmark: if: github.event_name == 'workflow_dispatch' && inputs.suite == 'consolidated-runner-benchmark' - runs-on: ${{ matrix.runner }} + # Default measures the repository's own fleet tiers; under the matching + # platform's blacksmith failover value the tiers Blacksmith offers (up to + # 32 vCPU) move onto their Blacksmith equivalents, while the 64/96-core + # rows keep the fleet labels because Blacksmith has no such tier. + runs-on: >- + ${{ (matrix.platform == 'linux' && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' + || matrix.platform == 'windows' && vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith') + && matrix.blacksmith + || matrix.runner }} timeout-minutes: 15 strategy: fail-fast: false @@ -385,50 +413,62 @@ jobs: - platform: linux cores: '4' runner: dsh-ubuntu-24-04-4core + blacksmith: blacksmith-4vcpu-ubuntu-2404 workers: '4' - platform: linux cores: '8' runner: dsh-ubuntu-24-04-8core + blacksmith: blacksmith-8vcpu-ubuntu-2404 workers: '8' - platform: linux cores: '16' runner: dsh-ubuntu-24-04-16core + blacksmith: blacksmith-16vcpu-ubuntu-2404 workers: '16' - platform: linux cores: '32' runner: dsh-ubuntu-24-04-32core + blacksmith: blacksmith-32vcpu-ubuntu-2404 workers: '32' - platform: linux cores: '64' runner: dsh-ubuntu-24-04-64core + blacksmith: '' workers: '32' - platform: linux cores: '96' runner: dsh-ubuntu-24-04-96core + blacksmith: '' workers: '32' - platform: windows cores: '4' runner: dsh-windows-2025-4core + blacksmith: blacksmith-4vcpu-windows-2025 workers: '2' - platform: windows cores: '8' runner: dsh-windows-2025-8core + blacksmith: blacksmith-8vcpu-windows-2025 workers: '2' - platform: windows cores: '16' runner: dsh-windows-2025-16core + blacksmith: blacksmith-16vcpu-windows-2025 workers: '2' - platform: windows cores: '32' runner: dsh-windows-2025-32core + blacksmith: blacksmith-32vcpu-windows-2025 workers: '2' - platform: windows cores: '64' runner: dsh-windows-2025-64core + blacksmith: '' workers: '2' - platform: windows cores: '96' runner: dsh-windows-2025-96core + blacksmith: '' workers: '2' steps: - uses: actions/checkout@v6 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4e05b444a4..04639ea7fe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,10 @@ jobs: # repository state — not PR-editable, no merge required) retargets all # three onto the in-house # vm-backup pool and re-running the failed jobs is the entire switch — - # see .agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md. The + # see .agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md. + # Setting the variable to 'blacksmith' instead routes the same jobs onto + # Blacksmith's hosted runners at the matching vCPU size (see + # .agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md). The # in-house pool's readiness is re-proven on every master push by the # serial-linux-selfhosted standby lane in ci-master.yml. The Windows failover # switch is the separate DSH_CI_FAILOVER_WINDOWS variable on the windows-native @@ -39,7 +42,8 @@ jobs: node-24: if: github.event_name == 'pull_request' runs-on: >- - ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'dsh-ubuntu-24-04-16core' }} @@ -105,7 +109,8 @@ jobs: node-24-coverage: if: github.event_name == 'pull_request' runs-on: >- - ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'dsh-ubuntu-24-04-16core' }} @@ -226,7 +231,8 @@ jobs: node-24-consumers: if: github.event_name == 'pull_request' runs-on: >- - ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-16vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'dsh-ubuntu-24-04-16core' }} @@ -327,9 +333,12 @@ jobs: node-compat: if: github.event_name == 'pull_request' - # This job admits only repository-owned PR code to the persistent shared VM. + # Under the selfhosted leg this job admits only repository-owned PR code + # to the persistent shared VM; the blacksmith branch targets ephemeral + # runners and carries none of those predicates. runs-on: >- - ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.head.repo.fork == false && github.event.pull_request.user.login != 'dependabot[bot]' @@ -451,7 +460,8 @@ jobs: windows-build: if: github.event_name == 'pull_request' runs-on: >- - ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') || 'dsh-windows-2025-16core' }} @@ -495,7 +505,8 @@ jobs: windows-coverage: if: github.event_name == 'pull_request' runs-on: >- - ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') || 'dsh-windows-2025-16core' }} @@ -571,7 +582,8 @@ jobs: windows-native-tests: if: github.event_name == 'pull_request' runs-on: >- - ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') || 'dsh-windows-2025-16core' }} @@ -620,7 +632,8 @@ jobs: if: github.event_name == 'pull_request' continue-on-error: true runs-on: >- - ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' + ${{ vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-16vcpu-windows-2025' + || vars.DSH_CI_FAILOVER_WINDOWS == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "dsh-win-ci", "windows"]') || 'dsh-windows-2025-16core' }} @@ -677,9 +690,13 @@ jobs: # the worker jobs it aggregates, so a standard-hosted outage cannot strand # the branch-protection verdict either. It retargets with the Linux switch # (DSH_CI_FAILOVER_LINUX), not the Windows one, because it aggregates the - # required Linux workers and runs on the vm-backup pool. + # required Linux workers and runs on the vm-backup pool. Under the + # 'blacksmith' value the verdict shares Blacksmith's pool with its workers + # through the same selector, so a Blacksmith outage strands both together — + # the accepted consequence of the explicit opt-in switch. runs-on: >- - ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' && github.event.pull_request.user.login != 'dependabot[bot]' && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') || 'ubuntu-latest' }} diff --git a/.github/workflows/expected-filenames.yml b/.github/workflows/expected-filenames.yml index 59320b9261..99c9886e35 100644 --- a/.github/workflows/expected-filenames.yml +++ b/.github/workflows/expected-filenames.yml @@ -18,7 +18,9 @@ env: jobs: expected-filenames: name: no golden filenames - runs-on: ubuntu-latest + runs-on: >- + ${{ vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-4vcpu-ubuntu-2404' + || 'ubuntu-latest' }} steps: - uses: actions/checkout@v6 diff --git a/.github/workflows/sandbox.yml b/.github/workflows/sandbox.yml index 97b7e298d7..713616f3b6 100644 --- a/.github/workflows/sandbox.yml +++ b/.github/workflows/sandbox.yml @@ -44,6 +44,12 @@ jobs: fail-fast: false matrix: include: + # Only the bwrap leg has a Blacksmith equivalent: the earlier + # migration dispatch runs measured that Blacksmith's Linux images do + # not enforce Landlock (the run-guard would turn the leg red) and + # its macOS image is unverified, so those legs stay on GitHub's + # images under every failover value — see + # .agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md. - os: ubuntu-latest runner: bwrap - os: ubuntu-24.04 @@ -53,7 +59,10 @@ jobs: - os: macos-latest runner: seatbelt name: sandbox e2e (${{ matrix.runner }}, ${{ matrix.os }}) - runs-on: ${{ matrix.os }} + runs-on: >- + ${{ matrix.runner == 'bwrap' && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' + && 'blacksmith-4vcpu-ubuntu-2404' + || matrix.os }} timeout-minutes: 20 steps: - uses: actions/checkout@v6 diff --git a/scripts/ci-compatible-selfhosted.spec.ts b/scripts/ci-compatible-selfhosted.spec.ts index 3ef7a8b813..619ae192f9 100644 --- a/scripts/ci-compatible-selfhosted.spec.ts +++ b/scripts/ci-compatible-selfhosted.spec.ts @@ -57,6 +57,9 @@ describe('Node compatibility self-hosted routing', () => { it('uses the Linux pool only for opted-in repository-owned PRs', () => { expect(route()).toEqual(labels) for (const mode of ['', 'hosted', 'unexpected']) expect(route({ mode })).toBe('ubuntu-latest') + // The blacksmith value routes the compatibility legs onto Blacksmith's + // standard Linux runner regardless of PR ownership (ephemeral runners). + expect(route({ mode: 'blacksmith' })).toBe('blacksmith-4vcpu-ubuntu-2404') expect(route({ author: 'dependabot[bot]', actor: 'maintainer' })).toBe('ubuntu-latest') expect(route({ repository: 'outsider/fork', fork: true })).toBe('ubuntu-latest') expect(route({ repository: 'outsider/fork', fork: false })).toBe('ubuntu-latest') diff --git a/scripts/ci-workflow.spec.ts b/scripts/ci-workflow.spec.ts index 46177da403..bfe95f28ef 100644 --- a/scripts/ci-workflow.spec.ts +++ b/scripts/ci-workflow.spec.ts @@ -1,5 +1,6 @@ import { readFileSync } from 'node:fs' import { resolve } from 'node:path' +import { runInNewContext } from 'node:vm' import * as yaml from 'js-yaml' import { describe, expect, it } from 'vitest' @@ -135,6 +136,7 @@ describe('CI workflow', () => { expect(job['runs-on']).toContain('self-hosted') expect(job['runs-on']).toContain('dsh-win-ci') expect(job['runs-on']).toContain('dsh-windows-2025-16core') + expect(job['runs-on']).toContain('blacksmith-16vcpu-windows-2025') expect(job.if).toBe("github.event_name == 'pull_request'") } @@ -273,10 +275,43 @@ describe('CI workflow', () => { expect(job['runs-on'], `${jobName} runs-on must use the Linux failover switch`).toContain('DSH_CI_FAILOVER_LINUX') expect(job['runs-on'], `${jobName} runs-on must not use the Windows failover switch`).not.toContain('DSH_CI_FAILOVER_WINDOWS') expect(job['runs-on']).toContain('vm-backup') + expect(job['runs-on']).toContain('blacksmith-16vcpu-ubuntu-2404') } expect(aggregate['runs-on']).toContain('DSH_CI_FAILOVER_LINUX') expect(aggregate['runs-on']).not.toContain('DSH_CI_FAILOVER_WINDOWS') expect(aggregate['runs-on']).toContain('vm-backup') + expect(aggregate['runs-on']).toContain('blacksmith-4vcpu-ubuntu-2404') + + // Evaluating the full selector, not just substring containment, proves the + // blacksmith branch is standalone: it must not fall through to the + // self-hosted pool when the two values are mutually exclusive. + const selectors = { + linux: node24['runs-on'] as string, + linuxAggregate: aggregate['runs-on'] as string, + windows: windowsBuild['runs-on'] as string, + } + const evaluate = (expression: string, vars: Record, login = 'maintainer'): unknown => { + const body = expression.trim().slice(3, -2) + return runInNewContext(body, { + vars, + fromJSON: JSON.parse, + github: { event: { pull_request: { user: { login } } } }, + }, { timeout: 1000 }) + } + for (const [name, selector, variable, pool, hosted] of [ + ['linux gates', selectors.linux, 'DSH_CI_FAILOVER_LINUX', ['self-hosted', 'linux', 'x64', 'vm-backup'], 'dsh-ubuntu-24-04-16core'], + ['linux aggregate', selectors.linuxAggregate, 'DSH_CI_FAILOVER_LINUX', ['self-hosted', 'linux', 'x64', 'vm-backup'], 'ubuntu-latest'], + ['windows lanes', selectors.windows, 'DSH_CI_FAILOVER_WINDOWS', ['self-hosted', 'dsh-win-ci', 'windows'], 'dsh-windows-2025-16core'], + ] as const) { + expect(evaluate(selector, { [variable]: 'blacksmith' }), `${name} blacksmith value`).toMatch(/^blacksmith-/) + expect(evaluate(selector, { [variable]: 'selfhosted' }), `${name} selfhosted value`).toEqual(pool) + // The blacksmith branch must not capture the selfhosted pool, and the + // dependabot exclusion applies to the pool, not to the blacksmith tier. + expect(evaluate(selector, { [variable]: 'selfhosted' }, 'dependabot[bot]'), `${name} dependabot on selfhosted`).toBe(hosted) + for (const mode of ['', 'hosted', 'unexpected']) { + expect(evaluate(selector, { [variable]: mode }), `${name} default on ${mode}`).toBe(hosted) + } + } // The run-gates aggregate lanes stop at the first blocking gate failure so // a red aggregate does not keep burning runner time on the remaining @@ -299,6 +334,35 @@ describe('CI workflow', () => { expect(windowsObservational.env).not.toMatchObject({ DSH_GATE_FAIL_FAST: '1' }) }) + it('gates standalone keyless blacksmith jobs and benchmark tiers on the failover variables', () => { + const expectedFilenames = workflowJob(loadWorkflow('.github/workflows/expected-filenames.yml'), 'expected-filenames') + const sandbox = workflowJob(loadWorkflow('.github/workflows/sandbox.yml'), 'sandbox-e2e') + expect(expectedFilenames['runs-on']).toContain('DSH_CI_FAILOVER_LINUX') + expect(expectedFilenames['runs-on']).toContain("== 'blacksmith'") + expect(expectedFilenames['runs-on']).toContain('blacksmith-4vcpu-ubuntu-2404') + expect(expectedFilenames['runs-on']).toContain("'ubuntu-latest'") + expect(sandbox['runs-on']).toContain("matrix.runner == 'bwrap'") + expect(sandbox['runs-on']).toContain('DSH_CI_FAILOVER_LINUX') + expect(sandbox['runs-on']).toContain('blacksmith-4vcpu-ubuntu-2404') + for (const name of ['larger-runner-benchmark', 'consolidated-runner-benchmark'] as const) { + const benchmark = workflowJob(loadWorkflow('.github/workflows/ci-master.yml'), name) + if (!isRecord(benchmark.strategy) || !isRecord(benchmark.strategy.matrix) || !Array.isArray(benchmark.strategy.matrix.include)) { + throw new TypeError(`${name} must define a matrix include list`) + } + expect(benchmark['runs-on']).toContain('matrix.blacksmith') + expect(benchmark['runs-on']).toContain('DSH_CI_FAILOVER_LINUX') + expect(benchmark['runs-on']).toContain('DSH_CI_FAILOVER_WINDOWS') + for (const row of benchmark.strategy.matrix.include as Array>) { + expect(typeof row.blacksmith, `${name} ${row.cores}-core row must declare a blacksmith label`).toBe('string') + if (row.cores === '64' || row.cores === '96') { + expect(row.blacksmith, `${name} ${row.cores}-core row has no Blacksmith tier`).toBe('') + } else { + expect(row.blacksmith).toContain(`blacksmith-${row.cores}vcpu`) + } + } + } + }) + it('runs required benchmarks on standard hosted Linux independently of failover', () => { const workflow = loadWorkflow('.github/workflows/ci.yml') const benchmark = workflowJob(workflow, 'node-24-bench') From fc7abdcfb51bba72930920774d995ef90b363852 Mon Sep 17 00:00:00 2001 From: 07akioni <07akioni2@gmail.com> Date: Wed, 9 Sep 2026 19:18:34 +0800 Subject: [PATCH 12/52] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96=20windows=20?= =?UTF-8?q?=E5=AE=89=E8=A3=85=E5=8C=85=E6=89=93=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...on-desktop-packaging-and-updates.i18n.yaml | 4 +- ...-electron-desktop-packaging-and-updates.md | 28 ++- ...ectron-desktop-packaging-and-updates.zh.md | 28 ++- ...led-runtime-and-external-plugins.i18n.yaml | 4 +- ...op-bundled-runtime-and-external-plugins.md | 14 +- ...bundled-runtime-and-external-plugins.zh.md | 14 +- ...mmediate-window-and-direct-start.i18n.yaml | 6 + ...sktop-immediate-window-and-direct-start.md | 29 +++ ...op-immediate-window-and-direct-start.zh.md | 29 +++ apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 44 ++-- apps/desktop/README.zh.md | 44 ++-- apps/desktop/electron-builder.config.d.mts | 5 +- apps/desktop/electron-builder.config.mjs | 25 ++- apps/desktop/package.json | 1 + apps/desktop/renderer/plugin-manager.js | 4 +- apps/desktop/renderer/startup.css | 16 ++ apps/desktop/renderer/startup.html | 23 ++ apps/desktop/renderer/startup.js | 37 ++++ apps/desktop/scripts/installer.nsh | 17 ++ apps/desktop/scripts/package-target.ts | 32 ++- apps/desktop/scripts/prepare-dsh.ts | 16 +- apps/desktop/scripts/runtime-file-policy.ts | 40 ++++ apps/desktop/src/backend-controller.ts | 146 +++++++++++++ apps/desktop/src/host-process.ts | 13 +- apps/desktop/src/ipc.ts | 11 +- apps/desktop/src/locale.ts | 8 + apps/desktop/src/main.ts | 192 ++++++++--------- apps/desktop/src/owned-directory.ts | 26 +++ apps/desktop/src/preload-app.ts | 24 ++- apps/desktop/src/preload.ts | 6 + apps/desktop/src/profile-packages.ts | 10 +- apps/desktop/src/project-manager.ts | 33 +-- apps/desktop/src/runtime-tree.ts | 96 +++++++-- apps/desktop/tests/backend-controller.spec.ts | 170 +++++++++++++++ .../fixtures/installer-cleanup-smoke.nsi | 70 ++++++ .../installer-write-failure-smoke.nsi | 55 +++++ .../tests/fixtures/owned-directory-smoke.mjs | 29 +++ .../tests/fixtures/runtime-payload-smoke.mjs | 138 ++++++++++++ apps/desktop/tests/host-process.spec.ts | 26 ++- apps/desktop/tests/macos-signature.spec.ts | 27 ++- apps/desktop/tests/main-startup.spec.ts | 200 ++++++++++++++++++ apps/desktop/tests/owned-directory.spec.ts | 53 +++++ apps/desktop/tests/package-target.spec.ts | 40 ++++ apps/desktop/tests/plugin-manager.spec.ts | 2 +- apps/desktop/tests/plugin-pnpm.spec.ts | 2 +- apps/desktop/tests/preload-app.spec.ts | 37 ++++ apps/desktop/tests/project-manager.spec.ts | 35 ++- .../desktop/tests/runtime-file-policy.spec.ts | 81 +++++++ .../tests/runtime-tree-read-failure.spec.ts | 49 +++++ apps/desktop/tests/runtime-tree.spec.ts | 52 +++-- apps/desktop/tests/startup-renderer.spec.ts | 134 ++++++++++++ apps/desktop/tsdown.config.ts | 13 +- package.json | 1 + 54 files changed, 1984 insertions(+), 259 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md create mode 100644 .agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md create mode 100644 apps/desktop/renderer/startup.css create mode 100644 apps/desktop/renderer/startup.html create mode 100644 apps/desktop/renderer/startup.js create mode 100644 apps/desktop/scripts/installer.nsh create mode 100644 apps/desktop/scripts/runtime-file-policy.ts create mode 100644 apps/desktop/src/backend-controller.ts create mode 100644 apps/desktop/src/owned-directory.ts create mode 100644 apps/desktop/tests/backend-controller.spec.ts create mode 100644 apps/desktop/tests/fixtures/installer-cleanup-smoke.nsi create mode 100644 apps/desktop/tests/fixtures/installer-write-failure-smoke.nsi create mode 100644 apps/desktop/tests/fixtures/owned-directory-smoke.mjs create mode 100644 apps/desktop/tests/fixtures/runtime-payload-smoke.mjs create mode 100644 apps/desktop/tests/main-startup.spec.ts create mode 100644 apps/desktop/tests/owned-directory.spec.ts create mode 100644 apps/desktop/tests/preload-app.spec.ts create mode 100644 apps/desktop/tests/runtime-file-policy.spec.ts create mode 100644 apps/desktop/tests/runtime-tree-read-failure.spec.ts create mode 100644 apps/desktop/tests/startup-renderer.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml index fe1bf84c1b..d182ff8d4a 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.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-25-electron-desktop-packaging-and-updates.md -2026-08-25-electron-desktop-packaging-and-updates.md: d7d41aa4d6154f251b56faaa29065db3ee71071f -2026-08-25-electron-desktop-packaging-and-updates.zh.md: 952ed4fc5546524bc088f58e62faccd576194bc7 +2026-08-25-electron-desktop-packaging-and-updates.md: f6aa73d6e708db04c6978690b8fc2b7eb70f270b +2026-08-25-electron-desktop-packaging-and-updates.zh.md: 00c1346ab9b0bca1f704d74e7792acd03c5df9bf diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md index d7d41aa4d6..f6aa73d6e7 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md @@ -65,30 +65,38 @@ The renderer uses `nodeIntegration: false`, `contextIsolation: true`, and `sandb ## Installation and resolution -The installer never mutates the active profile in place. It copies profile metadata into a transaction staging directory and applies an exact dependency change with the bundled pnpm. Before testing staging, Electron stops the active backend; it starts and stops the staged backend alone, then restores the active backend before activation, so two Desktop backends never concurrently share `.dsh` state. Activation stops the backend again, persists each next `pending.json` phase before its corresponding filesystem move, moves the active profile to `rollback/profile`, moves staging into `.dsh/profiles/desktop`, and restarts. Recovery combines the write-ahead phase with the actual active, rollback, and staging directories so either write-to-move interruption retains or restores a complete profile. +The installer never mutates the active profile in place. It copies profile metadata into a transaction staging directory and applies an exact dependency change with the bundled pnpm. Activation stops the active backend, persists each next `pending.json` phase before its corresponding filesystem move, moves the active profile to `rollback/profile`, moves staging into `.dsh/profiles/desktop`, and restarts. Recovery combines the write-ahead phase with the actual active, rollback, and staging directories so either write-to-move interruption retains or restores a complete profile. The process-lifetime Electron lock is the authoritative Desktop owner. The package transaction lock is depth defense and records the process that can still mutate package state: Electron between package operations and the spawned pnpm PID while pnpm runs. The owner change is truncated, written, and synchronized through the already-open exclusive lock file. If Electron terminates during pnpm execution, a later process observes the live worker and refuses to start a competing store or staging transaction; after that worker exits, the stale PID can be recovered. -Core materialization, first launch, plugin installation, and shared-module resolution follow the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). A desktop plugin contributing `dsh.client` code enters the client graph only after the complete profile passes health checking. +Core materialization, first launch, plugin installation, and shared-module resolution follow the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). The actual Host composes enabled desktop plugins contributing `dsh.client` code when it starts. ## Updates and recovery Electron update uses one `electron-updater` release stream and signed `electron-builder` artifacts. Its version is the Desktop release version; there is no independent dsh manifest, compatibility range, or dsh-only update operation. A foreground install waits for an in-flight background check rather than reusing its result as an install result. The update dialog downloads and installs the Electron artifact, then restarts into the new release. -Before opening the product window, startup validates the current bundled runtime and reconciles external plugins according to the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). Backend failure opens the Electron-owned recovery window instead of booting a mismatched dsh release. +The [immediate-window decision](2026-09-09-desktop-immediate-window-and-direct-start.md) owns the local loading page, direct Host startup, and recovery in the main window. Profile reconciliation follows the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). `DSH_DESKTOP_AUTO_UPDATE_ENV` selects the test deployment by default or the production deployment for both the target-specific generic-provider URL and COS destination. Release automation supplies the test HTTPS origin through `DOWNLOAD_TEST_ORIGIN` and each deployment's bucket through `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`; keeping mutable test routing and COS storage identities out of source lets deployment infrastructure change without a code release, while the public production origin remains fixed. Packaging resolves only the public updater URL, disables electron-builder publishing, removes every COS credential field from its subprocess environment, and writes a completion record only after electron-builder and every signing or notarization hook succeeds. Target upload additionally requires the selected bucket, then requires the completion record, root dsh version, Desktop version, version-derived channel metadata, artifact names, sizes, and SHA-512 values to agree before it reads the selected credentials or sends data. It uploads immutable versioned updater payloads and any separate blockmaps before replacing the channel metadata emitted by electron-builder, and it never deletes historical objects. Stable versions use the `latest` metadata name; prereleases use the first semantic-version prerelease identifier. NSIS embeds its blockmap in the signed executable; the macOS ZIP carries a separate blockmap. Both let electron-updater download changed blocks when supported, while application replacement and the local pnpm staging transaction remain separate operations. ## Security and release policy -Core dsh and the private Desktop Host come only from the signed application resource tree. Plugin installation accepts registry package specs allowed by desktop policy but never raw pnpm commands. Exact versions, lockfile integrity, a reviewed `allowBuilds` set, user-only directory permissions, and health checking are required before activation. +Core dsh and the private Desktop Host come only from the signed application resource tree. Plugin installation accepts registry package specs allowed by desktop policy but never raw pnpm commands. Exact versions, lockfile integrity, a reviewed `allowBuilds` set, and user-only directory permissions are required before activation. -Electron artifacts are signed; macOS artifacts are notarized. Release automation must supply the application ID, macOS Developer ID qualifier, expected Team ID, and one complete notarytool credential strategy through explicit environment variables. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS packaging requires signing so certificate discovery cannot silently select another installed identity or emit an unsigned release. Runtime preparation verifies the exact Authority and Team ID plus the timestamp and hardened-runtime flags on every embedded Mach-O file. An after-sign hook performs Apple's deep strict application verification and requires the same leaf Authority and Team ID before artifact creation continues. Electron-builder then notarizes and staples the application and signs the DMG. The DMG artifact-completion hook separately notarizes and staples every DMG before requiring the configured identity, a valid ticket, and Gatekeeper acceptance; the upload event runs only after that hook succeeds. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. +Electron release artifacts are signed; macOS artifacts are notarized. Release automation must supply the application ID, macOS Developer ID qualifier, expected Team ID, and one complete notarytool credential strategy through explicit environment variables. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS packaging requires signing so certificate discovery cannot silently select another installed identity or emit an unsigned release. Runtime preparation verifies the exact Authority and Team ID plus the timestamp and hardened-runtime flags on every embedded Mach-O file. An after-sign hook performs Apple's deep strict application verification and requires the same leaf Authority and Team ID before artifact creation continues. Electron-builder then notarizes and staples the application and signs the DMG. The DMG artifact-completion hook separately notarizes and staples every DMG before requiring the configured identity, a valid ticket, and Gatekeeper acceptance; the upload event runs only after that hook succeeds. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. The [pinned osx-sign patch](../../../../patches/@electron__osx-sign@1.3.3.patch) uses `lstat` in both published module builds, so Framework file and directory aliases do not trigger duplicate signing. The patch remains necessary until the selected upstream release skips those aliases. PAK files are resources sealed by the enclosing bundle; individual signatures add serial timestamp requests without additional resource integrity. Desktop preserves all locale files and skips only their standalone signatures. Executable code retains Developer ID signatures, secure timestamps, and hardened runtime. The [signer traversal regression](../../../../apps/desktop/tests/macos-signing-walk.spec.ts) exercises the installed dependency with real Framework aliases; release qualification still requires strict application verification, notarization, and startup. Windows release packaging supplies the public EV leaf certificate named by `DSH_DESKTOP_WINDOWS_CER_FILE` to the configured SafeNet-compatible SignTool through `/f` and identifies its matching private key through the required `DSH_DESKTOP_WINDOWS_KEY_CONTAINER`. The certificate file remains outside source control, and the private key remains on the USB token. The electron-builder hook passes each artifact to the CRLF `windows-sign.cmd`, whose single SignTool invocation uses the SafeNet `/kc "[{{PIN}}]=container"` value and CSP, a SHA-256 file digest, and a DigiCert SHA-256 RFC 3161 timestamp. The hook never substitutes another SignTool and never retries a failed request. Package orchestration withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation children and passes only the certificate path, SignTool path, key container, and PIN into electron-builder. The signer supplies only validated signing fields in an otherwise scrubbed CMD environment; the CMD disables delayed expansion, clears those fields before SignTool starts, and preserves the PIN only in the required SignTool command line. Every surfaced diagnostic replaces the PIN, and only the dedicated build account and administrators may inspect the runner. The signer signs electron-builder's temporary NSIS bootstrap before enterprise Code Integrity evaluates that executable and clears a generated executable's certificate-table entry only when it points beyond the file before applying the final signature. Packaging fails before producing unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. The custom protocol serves the installed frontend distribution plus client files named by the active module graph and rejects traversal or access outside those roots. The plugin installer API is available only to the Electron-owned management GUI and is absent from the browser application and backend RPC. +Windows package invocations force `ELECTRON_BUILDER_7Z_FILTER=BCJ`. The bundled 7-Zip 24.09 encoder automatically selects ARM64 filters for ARM64 PE files, but the NSIS decoder from `nsis-resources-3.4.1` omits those entries during extraction. A native extraction probe with the actual NSIS plugin loses both `node-pty` ARM64 binaries under automatic filtering and restores both byte-for-byte with BCJ. Keeping a compatible filter preserves dependency contents and runtime integrity instead of removing architecture-specific files or weakening verification. + +Local Windows installation testing uses an explicit `--unsigned` package invocation with the same build and runtime preparation. It strips certificate inputs, isolates artifacts in `unsigned-artifacts`, and omits updater configuration and the release completion record. The regular package command explicitly selects signed mode even when its parent environment requests unsigned mode. This separation permits installation diagnosis without an EV token while preventing local test output from qualifying for release upload. + +NSIS extracts into its private `7z-out` directory before copying files into the application directory. Its default exit cleanup can overlap the backend's file reads after Finish launches the application. The [installer hook](../../../../apps/desktop/scripts/installer.nsh) removes only that extraction directory during `customInstall`, before interactive and silent launch branches. It preserves package archives, plugin DLLs, rollback directories, registers, and error status; the [native cleanup smoke](../../../../apps/desktop/tests/fixtures/installer-cleanup-smoke.nsi) checks these constraints. Moving cleanup into installation does not remove filesystem work, so total installation time and Finish-to-window time require separate measurements. + +Direct `Nsis7z::Extract` into the application directory is not enabled. A native [locked-file probe](../../../../apps/desktop/tests/fixtures/installer-write-failure-smoke.nsi) leaves an old locked file beside a new asset while reporting no error; the staged `CopyFiles` operation sets the error flag for the same failed replacement. An unchanged 737,557,488-byte payload on Windows took 172.625 seconds through extraction, copying, and cleanup versus 28.031 seconds through direct extraction, but that single sample per path does not justify losing failure detection. The clocks exclude registry changes, old-version removal, and post-extraction verification; system caches were not cleared. Desktop-specific payload filtering reduces the copied file set while retaining the installer's replacement-error handling. This handling is not a promise of complete installation rollback. + Packaged applications ignore development resource and project environment overrides. Only an unpackaged Electron process can replace the Node.js binary, pnpm entry, dsh resources, or active project. The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compressed and 120–165 MB installed before the dsh production tree. Architecture-specific builds must report actual component-level size deltas. @@ -135,8 +143,8 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr - The Electron-only GUI installs, removes, and updates ordinary npm plugin packages without exposing raw pnpm arguments. - The backend and browser application cannot mutate desktop packages. - npm/CLI dsh and Electron never resolve or install plugins from each other's `node_modules`. -- The active backend and Web UI report the same dsh version and a compatible shell API before the product window opens. -- Failed installation, health checking, or update leaves the current profile usable or restores `rollback/profile` after restart. +- The active backend and Web UI report the same dsh version and a compatible shell API before the product UI loads. +- Failed installation, backend activation, or update leaves the current profile usable or restores `rollback/profile` after restart. - One Desktop version binds Electron and dsh; every dsh update arrives through one Electron update dialog and one user-visible restart. - Shared `.dsh` data rejects incompatible readers before migration or mutation. - No loopback listener is opened, and the sandboxed renderer cannot access arbitrary filesystem or Electron APIs. @@ -149,10 +157,10 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr | Decision | Recommendation | |---|---| -| First launch | Validate bundled production packages and create profile links without installing core dependencies | +| First launch | Check bundled release metadata and create profile links without installing core dependencies | | Desktop profile | One Electron-owned reserved profile for external plugins and shared package links | | Plugin management | Electron-only GUI and package service; no CLI, backend, or browser installation path | -| Activation | Staging project, complete health check, journaled directory replacement, one rollback copy | +| Activation | Staging project, journaled directory replacement, actual Host startup, one rollback copy | | Initial platforms | macOS arm64/x64 and Windows x64; Linux has no supported release target | | Update behavior | Background check, explicit confirmation before differential download and restart, startup dsh reconciliation | @@ -160,7 +168,7 @@ The bundled upstream Node.js and pnpm are expected to add about 35–50 MB compr Plugin lifecycle scripts execute third-party code. The allowed registry, package policy, exact versions, integrity, `allowBuilds`, and diagnostics require security review before GUI installation ships. -Updating the bound dsh can invalidate plugin peer dependencies or native modules. pnpm resolution and full-project health checking must reject the staged project before replacing the active one. +Updating the bound dsh can invalidate plugin peer dependencies or native modules. Dependency validation rejects incompatible metadata before replacement; actual Host startup can fail after replacement and trigger profile rollback. An npm-installed dsh and desktop dsh may have different versions while sharing durable data. Each shared owner must enforce its format version and process lock before reading, migrating, or writing. diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md index 952ed4fc55..00c1346ab9 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md @@ -65,30 +65,38 @@ Electron 拥有 `.dsh/profiles/desktop` 保留 profile。[内置运行时决策] ## 安装与解析 -安装器绝不原地修改活跃 profile。它把 profile 元数据复制到事务暂存目录,并使用内置 pnpm 应用精确依赖变更。测试 staging 前,Electron 会停止活跃后端;它单独启动并停止 staging 后端,再在激活前恢复活跃后端,因此两个 Desktop 后端绝不会并发共享 `.dsh` 状态。激活过程再次停止后端,在对应目录移动前先持久化 `pending.json` 的每个下一阶段,把活跃 profile 移到 `rollback/profile`,把暂存 profile 移到 `.dsh/profiles/desktop`,然后重启。恢复过程会结合预写阶段与真实的 active、rollback 和 staging 目录,因此任一个写入与移动间隙中断后仍会保留或恢复一个完整 profile。 +安装器绝不原地修改活跃 profile。它把 profile 元数据复制到事务暂存目录,并使用内置 pnpm 应用精确依赖变更。激活过程停止活跃后端,在对应目录移动前先持久化 `pending.json` 的每个下一阶段,把活跃 profile 移到 `rollback/profile`,把暂存 profile 移到 `.dsh/profiles/desktop`,然后重启。恢复过程会结合预写阶段与真实的 active、rollback 和 staging 目录,因此任一个写入与移动间隙中断后仍会保留或恢复一个完整 profile。 进程生命周期 Electron 锁是 Desktop 的权威 owner。包事务锁用于纵深防御,并记录仍能修改包状态的进程:包操作之间记录 Electron,pnpm 运行期间记录已生成的 pnpm PID。Owner 变更通过已经打开的排他锁文件完成截断、写入与同步。如果 Electron 在 pnpm 执行期间终止,后续进程会发现仍存活的 worker,并拒绝启动并发的 store 或 staging 事务;该 worker 退出后,陈旧 PID 才可以恢复。 -核心物化、首次启动、插件安装和共享模块解析遵循[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)。提供 `dsh.client` 代码的桌面插件只有在完整 profile 通过健康检查后才会进入客户端依赖图。 +核心物化、首次启动、插件安装和共享模块解析遵循[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)。实际 Host 启动时会组合已启用且提供 `dsh.client` 代码的桌面插件。 ## 更新与恢复 Electron 更新只使用一个 `electron-updater` 发布流和签名 `electron-builder` 产物。该版本就是 Desktop 发布版本;不存在独立 dsh manifest、兼容范围或仅更新 dsh 的操作。前台安装会等待正在进行的后台检查,而不会把检查结果复用成安装结果。更新弹窗下载并安装 Electron 产物,然后重启进入新发布。 -打开产品窗口前,启动过程会验证当前内置运行时,并根据[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)协调外部插件。后端失败会打开 Electron 拥有的恢复窗口,不会启动版本不匹配的 dsh。 +[立即显示窗口决策](2026-09-09-desktop-immediate-window-and-direct-start.zh.md)负责本地加载页、直接启动 Host 和主窗口恢复。profile 协调遵循[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)。 `DSH_DESKTOP_AUTO_UPDATE_ENV` 默认为测试部署,也可以选择生产部署,并同时决定目标专用的 generic-provider URL 与 COS 目标。发布自动化通过 `DOWNLOAD_TEST_ORIGIN` 提供测试 HTTPS origin,并通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供各部署的 bucket;可变的测试路由与 COS 存储身份不写入源码,部署基础设施变更时无需发布新代码,而公开的生产 origin 仍固定。打包只解析公开更新 URL、禁止 electron-builder 发布、从子进程环境中删除每个 COS 凭据字段,并且只有在 electron-builder 以及每个签名或公证 hook 成功后才写入完成记录。目标上传还必须提供所选 bucket,随后会先要求完成记录、根 dsh 版本、Desktop 版本、根据版本得出的频道元数据、产物名称、大小与 SHA-512 全部一致,再读取所选凭据或发送数据。它先上传不可变且带版本的更新载荷与所有独立 blockmap,最后替换 electron-builder 生成的频道元数据,并且不会删除历史对象。稳定版本使用 `latest` 元数据名称,预发布版本则使用语义化版本的第一个预发布标识符。NSIS 把 blockmap 嵌入已签名的可执行文件,macOS ZIP 则使用独立 blockmap;两者都让 electron-updater 在平台支持时只下载变化的数据块,而应用替换与本地 pnpm staging 事务仍是两个独立操作。 ## 安全与发布策略 -核心 dsh 和私有 Desktop Host 只来自签名应用的资源树。插件安装接受桌面策略允许的 registry 包规格,不接受原始 pnpm 命令。激活前要求精确版本、锁文件完整性、经过审查的 `allowBuilds` 集合、仅限用户访问的目录权限和健康检查。 +核心 dsh 和私有 Desktop Host 只来自签名应用的资源树。插件安装接受桌面策略允许的 registry 包规格,不接受原始 pnpm 命令。激活前要求精确版本、锁文件完整性、经过审查的 `allowBuilds` 集合和仅限用户访问的目录权限。 -Electron 产物必须签名;macOS 产物必须公证。发布自动化必须通过明确的环境变量提供应用 ID、macOS Developer ID 限定名、预期 Team ID 与一套完整的 notarytool 凭据。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。运行时准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。Electron-builder 随后公证应用并钉票、签署 DMG。DMG 的 artifact-completion hook 会单独公证每个 DMG 并钉票,再要求其使用配置的身份、具备有效票据并通过 Gatekeeper;只有该 hook 成功,上传事件才会执行。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 拥有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 +Electron 发布产物必须签名;macOS 产物必须公证。发布自动化必须通过明确的环境变量提供应用 ID、macOS Developer ID 限定名、预期 Team ID 与一套完整的 notarytool 凭据。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。运行时准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。Electron-builder 随后公证应用并钉票、签署 DMG。DMG 的 artifact-completion hook 会单独公证每个 DMG 并钉票,再要求其使用配置的身份、具备有效票据并通过 Gatekeeper;只有该 hook 成功,上传事件才会执行。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 拥有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 [固定版本的 osx-sign 补丁](../../../../patches/@electron__osx-sign@1.3.3.patch)在两种已发布模块构建中使用 `lstat`,因此 Framework 的文件和目录别名不会触发重复签名。选定的上游版本能够跳过这些别名前,仍需保留该补丁。PAK 文件由外层 bundle 签名记录完整性;逐个签名会增加串行时间戳请求,但不会增加资源完整性保护。Desktop 保留全部语言文件,只跳过其单独签名。可执行代码仍使用 Developer ID 签名、安全时间戳和 hardened runtime。[签名器遍历回归测试](../../../../apps/desktop/tests/macos-signing-walk.spec.ts)使用真实 Framework 别名执行已安装依赖;发布验收仍要求严格应用验证、公证和启动。 Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool 提供 `DSH_DESKTOP_WINDOWS_CER_FILE` 指定的公开 EV 叶证书,并通过必需的 `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` 标识匹配的私钥。证书文件保留在源码仓库之外,私钥仍留在 USB Token 上。electron-builder hook 把每个产物交给采用 CRLF 的 `windows-sign.cmd`;该 CMD 只调用一次 SignTool,并指定 SafeNet `/kc "[{{PIN}}]=容器"` 值与 CSP、SHA-256 文件摘要和 DigiCert SHA-256 RFC 3161 时间戳。hook 不会改用其他 SignTool,也不会重试失败的请求。打包编排不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程,只会把证书路径、SignTool 路径、密钥容器和 PIN 传入 electron-builder。签名器在已清理的 CMD 环境中只提供经过校验的签名字段;CMD 会禁用延迟展开,在 SignTool 启动前清除这些字段,并仅在 SignTool 必需的命令行中保留 PIN。所有对外诊断都会替换 PIN,而且只能允许专用构建账号和管理员检查该 runner。签名器会在企业 Code Integrity 检查 electron-builder 的临时 NSIS bootstrap 前先为该可执行文件签名;对于生成的可执行文件,只有证书表条目指向文件末尾之外时,才会在最终签名前清除该条目。SignTool、证书、容器、PIN、Token 或签名不可用时,打包会在产生未签名产物前失败。自定义协议提供已安装的前端分发目录和活跃模块图点名的客户端文件,并拒绝路径穿越或访问这些根目录之外的内容。插件安装器 API 只对 Electron 持有的管理 GUI 可用,不存在于浏览器应用或后端 RPC 中。 +Windows 打包调用强制设置 `ELECTRON_BUILDER_7Z_FILTER=BCJ`。内置的 7-Zip 24.09 编码器会为 ARM64 PE 文件自动选择 ARM64 过滤器,但 `nsis-resources-3.4.1` 中的 NSIS 解码器会在解压时遗漏这些条目。使用实际 NSIS 插件的原生解压验证表明,自动过滤会丢失两个 `node-pty` ARM64 二进制文件,而 BCJ 可以逐字节还原二者。使用兼容的过滤器能够保留依赖内容与运行时完整性,无需删除特定架构的文件或削弱校验。 + +本地 Windows 安装测试使用显式的 `--unsigned` 打包调用,并执行相同的构建和运行时准备。它清除证书输入,将产物隔离到 `unsigned-artifacts`,并省略更新器配置和发布完成记录。即使父进程环境请求未签名模式,常规打包命令也会显式选择签名模式。这样既能在没有 EV Token 时诊断安装问题,也能防止本地测试产物通过发布上传校验。 + +NSIS 先解压到私有的 `7z-out` 目录,再把文件复制到应用目录。Finish 启动应用后,默认退出清理可能与后端的文件读取重叠。[安装器 hook](../../../../apps/desktop/scripts/installer.nsh) 在 `customInstall` 阶段仅删除该解压目录,早于交互和静默启动分支。它保留包归档、插件 DLL、回滚目录、寄存器和错误状态;[原生清理 smoke](../../../../apps/desktop/tests/fixtures/installer-cleanup-smoke.nsi) 检查这些约束。把清理移入安装阶段并不会减少文件系统工作,因此必须分别测量安装总耗时与点击 Finish 到窗口出现的耗时。 + +安装器不开启直接向应用目录执行 `Nsis7z::Extract`。原生[文件占用探针](../../../../apps/desktop/tests/fixtures/installer-write-failure-smoke.nsi)会在未报错的情况下留下被占用的旧文件和新资源;暂存后执行的 `CopyFiles` 在相同替换失败时会设置错误标志。Windows 上同一份 737,557,488 字节载荷经过解压、复制和清理耗时 172.625 秒,直接解压耗时 28.031 秒,但每条路径的单次样本不足以支持放弃失败检测。计时不包括注册表修改、旧版删除及解压后的验证,也没有清空系统缓存。桌面专用载荷过滤减少需要复制的文件,同时保留安装器的替换错误处理。这种处理并不承诺完整的安装回滚。 + 打包应用会忽略开发资源和项目环境变量覆盖。只有未打包的 Electron 进程可以替换 Node.js 可执行文件、pnpm 入口、dsh 资源 或活跃项目。 在种子 store 子集之外,内置上游 Node.js 与 pnpm 预计增加约 35–50 MB 压缩体积和 120–165 MB 安装体积。分架构构建必须报告实际组件级体积增量。 @@ -135,8 +143,8 @@ Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool - Electron-only GUI 安装、删除和更新普通 npm 插件包,而不暴露原始 pnpm 参数。 - 后端与浏览器应用不能修改桌面包。 - npm/CLI dsh 与 Electron 绝不从对方的 `node_modules` 解析或安装插件。 -- 在产品窗口打开前,活跃后端与 Web UI 报告相同 dsh 版本和兼容壳 API。 -- 安装、健康检查或更新失败后,当前 profile 仍然可用,或在重启后恢复 `rollback/profile`。 +- 在产品 UI 加载前,活跃后端与 Web UI 报告相同 dsh 版本和兼容壳 API。 +- 安装、后端激活或更新失败后,当前 profile 仍然可用,或在重启后恢复 `rollback/profile`。 - 一个 Desktop 版本绑定 Electron 与 dsh;每次 dsh 更新都通过一个 Electron 更新弹窗交付,并产生一次用户可见的重启。 - 共享 `.dsh` 数据在迁移或修改前拒绝不兼容的读取方。 - 不打开回环监听端口,沙箱渲染进程不能访问任意文件系统或 Electron API。 @@ -149,10 +157,10 @@ Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool | 决策 | 建议 | |---|---| -| 首次启动 | 验证内置生产包并创建 profile 链接,不安装核心依赖 | +| 首次启动 | 检查内置发布元数据并创建 profile 链接,不安装核心依赖 | | 桌面 profile | 一个由 Electron 拥有的保留 profile,保存外部插件和共享包链接 | | 插件管理 | Electron-only GUI 与包服务;没有 CLI、后端或浏览器安装路径 | -| 激活 | 暂存项目、完整健康检查、记录式目录替换和一个回滚副本 | +| 激活 | 暂存项目、记录式目录替换、实际 Host 启动和一个回滚副本 | | 初始平台 | macOS arm64/x64 与 Windows x64;Linux 尚无受支持的发布目标 | | 更新行为 | 后台检查,差分下载与重启前显式确认,启动时校准 dsh | @@ -160,7 +168,7 @@ Windows 发布打包通过 `/f` 向已配置且与 SafeNet 兼容的 SignTool 插件生命周期脚本会执行第三方代码。在 GUI 安装功能交付前,获准 registry、包策略、精确版本、完整性、`allowBuilds` 和诊断都需要安全评审。 -更新绑定的 dsh 可能使插件 peer dependency 或原生模块失效。pnpm 解析与完整项目健康检查必须在替换活跃项目前拒绝暂存项目。 +更新绑定的 dsh 可能使插件 peer dependency 或原生模块失效。依赖验证在替换前拒绝不兼容的元数据;实际 Host 启动可能在替换后失败,并触发 profile 回滚。 通过 npm 安装的 dsh 与桌面 dsh 可能在共享持久化数据时使用不同版本。每个共享 owner 都必须在读取、迁移或写入前执行格式版本与进程锁。 diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml index 9729df077f..8c5be1e7e1 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.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-09-08-desktop-bundled-runtime-and-external-plugins.md -2026-09-08-desktop-bundled-runtime-and-external-plugins.md: 8278107fb3c37aca909541886d9379a1bfd64bac -2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md: b29eb1e6cbe19d4a5b4ea23a5d6159cfd3973bcd +2026-09-08-desktop-bundled-runtime-and-external-plugins.md: a662af570c017d6fd3d38cf066c0a02e0049a84f +2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md: 6284949f6747cbe47a5de149ff598354c9b9cc58 diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md index 8278107fb3..a662af570c 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md @@ -20,6 +20,10 @@ Desktop has not been released. This is its first installation format; there are The resource descriptor records the exact release, Node version, platform, architecture, shared package versions, and final file hashes. The runtime tree contains ordinary files and directories, without links back to pnpm’s build store. Native Mach-O files are signed before hashing; the application signer preserves their bytes and checks the inventory after signing. An explicit `dsh/node_modules` resource mapping bypasses electron-builder’s root `node_modules` exclusion, and the copied tree is verified before any signing or notarization. +The [Desktop file policy](../../../../apps/desktop/scripts/runtime-file-policy.ts) applies after production npm installation and before native signing or descriptor generation. npm publication lists serve library consumers and can include declarations, maps, tests, and native build inputs; they do not identify the files needed by the Desktop process. The Desktop copy omits declarations and recognized source maps because Host execution uses JavaScript and generated Typert artifacts, clears inherited `NODE_OPTIONS`, and does not enable source mapping. Reviewed plugin lifecycle builds cover native dependencies, not arbitrary TypeScript compilation. Published npm packages and external plugin directories retain their own files. Source debugger navigation is a development-package capability. + +Package-specific exclusions remove Domino tests, fs-ext compilation outputs, Koffi's Windows import library, and non-target node-pty prebuilds and debug symbols. The policy retains native executable dependencies, node-pty's ConPTY source distribution, licenses, and unrecognized assets; broad `src`, `test`, `.ts`, or `.map` exclusions could remove executable code or runtime data. Copy tests preserve sentinel assets and seal the filtered inventory; the bundled-Node [payload smoke](../../../../apps/desktop/tests/fixtures/runtime-payload-smoke.mjs) verifies PTY output, native file seeking, FFI, image conversion, and HTML parsing. Runtime preparation still verifies every retained byte and boots the complete Host with an external plugin. + Every first-party package in the dsh and private Host production closures is shared. The profile contains directory symlinks to those resource packages, or junctions on Windows. Links resolve to real host package directories under normal Node resolution. Host and plugin imports therefore share the same module instance for each resolved export. Distinct ESM and CommonJS conditional exports remain distinct entry points; a link cannot merge a package’s dual implementations. External plugins declare shared host packages as peers. Ordinary dependencies remain plugin-owned and may differ from the versions used by dsh. Validation rejects incompatible enabled peers, nested or aliased copies of shared packages, private package links, and dependency resolution through CLI or other ancestor directories. A third-party package requiring host-wide instance identity must be explicitly added to the runtime’s shared inventory; matching version numbers alone are insufficient. @@ -28,16 +32,20 @@ The profile manifest records exact installed plugin dependencies separately from ## Transactions and upgrades -First launch creates profile metadata and host links without running pnpm. A compatible release change or application relocation copies plugin files into staging, refreshes links, validates enabled peers, and boots the staged backend. Node version, platform, or architecture changes reinstall the locked plugin graph before activation. Writable staging and rollback files are independent copies, never hardlinks into the active profile. +First launch creates profile metadata and host links without running pnpm. A compatible release change or application relocation copies plugin files into staging, refreshes links, and validates enabled peers. Node version, platform, or architecture changes reinstall the locked plugin graph before activation. Writable staging and rollback files are independent copies, never hardlinks into the active profile. + +Native canonical paths identify shared package directories. Windows launchers can vary path casing without moving the application; string equality would trigger unnecessary staging and backend replacement. Transaction cleanup explicitly unlinks every nested directory link before removing real directories. A Windows fixture under Electron 44 reproduces recursive `fs.rmSync` deleting files through a nested junction, while bundled upstream Node 24.17 preserves them. Cleanup qualification therefore includes the real Electron runtime; Node-only tests do not establish target preservation. Dependency mutations install with scripts disabled, validate the plugin graph and host links, run the reviewed pending lifecycle builds, and validate again. This permits approved native dependencies to resolve host peers while preventing accidental duplicate host packages from reaching startup. The `allowBuilds` policy remains explicit; unsupported build-requiring dependencies fail the transaction. The transaction journal records source and target runtime identities and directory-move phases. Desktop waits for pnpm exit and stops the active backend before replacement. A failed or interrupted activation restores a complete profile. A runtime identity mismatch prevents the restored profile from booting under a different application release. The journal covers profile files, not arbitrary plugin startup effects or durable Session writes. -An Electron-owned recovery window remains available when the backend cannot start. Users can update, remove, disable, or re-enable plugins and retry startup. Incompatible plugins are not silently deleted or automatically downgraded. Application rollback and profile rollback are separate operations; each backend launch requires the current runtime identity. +The [immediate-window decision](2026-09-09-desktop-immediate-window-and-direct-start.md) owns direct Host startup and recovery in the main window, replacing staged backend probes. Users can open plugin management to update, remove, disable, or re-enable plugins and retry startup. Incompatible plugins are not silently deleted or automatically downgraded. Application rollback and profile rollback are separate operations; each backend launch requires the current runtime identity. ## Alternatives considered +Full runtime verification belongs to packaging. Startup reads the descriptor, validates release and target compatibility, checks shared manifests and required Host entries, and uses the recorded runtime identity for profile reuse. It neither enumerates nor hashes installed runtime files, including on first launch or after an upgrade. Reading every file before backend loading adds startup I/O proportional to the distribution size. Installed content changes therefore are not detected by a startup checksum comparison; unusable modules fail when loaded. Build-time verification still rejects changed, missing, extra, or linked files against the recorded inventory. + - **Install the bundled offline seed at startup.** This preserves an ordinary pnpm installation procedure but repeats core extraction and installation on every affected machine. Materialized resources remove that work at the cost of more application files and release-builder responsibility. - **Link all host dependencies into plugins.** This unnecessarily couples ordinary plugin dependencies to the host. Only the explicit shared inventory is linked; private packages retain independent versions. - **Use hardlinks.** They cannot represent directories, may not cross volumes, share writable bytes, and retain old inodes after application replacement. Directory symlinks and Windows junctions express the intended package target. @@ -46,6 +54,6 @@ An Electron-owned recovery window remains available when the backend cannot star ## Consequences -Core package installation is absent from first launch and compatible upgrades. Runtime integrity verification and a complete backend health check still cost startup time; no release latency or download-size improvement is claimed without measurement. Plugin preservation is conditional on host API and native runtime compatibility, with a visible recovery path when that condition fails. +Core package installation is absent from first launch and compatible upgrades. Metadata checks and backend loading still cost startup time; no release latency or download-size improvement is claimed without measurement. Plugin preservation is conditional on host API and native runtime compatibility, with a visible recovery path when that condition fails. The [Desktop README](../../../../apps/desktop/README.md) owns operational guidance. Focused tests cover real pnpm installation and approved builds, shared ESM instance identity, private dependency versions, relocation, disabled plugins, native rebuild selection, activation failures, and transaction locking. Signed installed-artifact upgrades, macOS notarization, Windows junction/native behavior, release size and startup benchmarks, and real-model GUI recordings remain release-environment qualification requirements; unit fixtures do not substitute for them. diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md index b29eb1e6cb..6284949f67 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md @@ -20,6 +20,10 @@ Desktop 尚未发布。这是它的第一种安装格式;不提供未发布 se 资源描述文件记录精确发布版本、Node 版本、平台、架构、共享包版本和最终文件哈希。运行时树包含普通文件和目录,不包含指回 pnpm 构建 store 的链接。原生 Mach-O 文件先签名再哈希;应用签名器保留其字节,并在签名后检查清单。明确的 `dsh/node_modules` 资源映射绕过 electron-builder 对根 `node_modules` 的排除,并在任何签名或公证前验证复制后的依赖树。 +[桌面文件规则](../../../../apps/desktop/scripts/runtime-file-policy.ts)在生产 npm 依赖安装之后、原生签名或描述文件生成之前执行。npm 发布列表服务于库的使用者,可以包含声明、map、测试和原生构建输入,不能直接表示桌面进程需要哪些文件。桌面副本排除声明和已识别的 source map,因为 Host 执行 JavaScript 和生成的 Typert 产物,清除继承的 `NODE_OPTIONS`,且不开启源码映射。经过审核的插件生命周期构建面向原生依赖,不执行任意 TypeScript 编译。已发布的 npm 包和外部插件目录保留各自的文件。源码调试导航由开发包提供。 + +包专用排除项包括 Domino 测试、fs-ext 编译产物、Koffi 的 Windows 导入库,以及非目标平台的 node-pty 预构建文件和调试符号。规则保留原生可执行依赖、node-pty 的 ConPTY 源分发内容、许可证和未知资源;宽泛排除 `src`、`test`、`.ts` 或 `.map` 可能移除可执行代码或运行时数据。复制测试保留哨兵资源并封存过滤后的清单;内置 Node 的[产物 smoke](../../../../apps/desktop/tests/fixtures/runtime-payload-smoke.mjs)验证 PTY 输出、原生文件定位、FFI、图像转换和 HTML 解析。运行时准备仍会验证每个保留字节,并携带外部插件启动完整 Host。 + dsh 与私有 Host 生产闭包中的每个第一方包都共享。profile 包含指向这些资源包的目录软链接,在 Windows 上使用 junction。正常 Node 解析会把链接解析到实际宿主包目录。因此,宿主与插件对每个已解析导出的导入共享同一模块实例。不同的 ESM 与 CommonJS 条件导出仍是不同入口;链接不能合并包的两套实现。 外部插件把共享宿主包声明为 peer。普通依赖由插件拥有,可以不同于 dsh 使用的版本。验证拒绝已启用插件的不兼容 peer、共享包的嵌套或别名副本、私有包链接,以及通过 CLI 或其他祖先目录解析依赖。如果第三方包需要宿主范围的实例身份,必须明确加入运行时共享清单;版本号相同并不足够。 @@ -28,16 +32,20 @@ profile manifest 分别记录精确的已安装插件依赖和已启用 bundle ## 事务与升级 -首次启动创建 profile 元数据和宿主链接,不运行 pnpm。兼容的发布变化或应用移动会把插件文件复制到 staging,刷新链接,验证已启用的 peer,并启动 staging 后端。Node 版本、平台或架构变化时,激活前会重新安装锁定的插件依赖图。可写 staging 与回滚文件使用独立副本,不使用指向活动 profile 的硬链接。 +首次启动创建 profile 元数据和宿主链接,不运行 pnpm。兼容的发布变化或应用移动会把插件文件复制到 staging,刷新链接,并验证已启用的 peer。Node 版本、平台或架构变化时,激活前会重新安装锁定的插件依赖图。可写 staging 与回滚文件使用独立副本,不使用指向活动 profile 的硬链接。 + +共享包目录使用原生规范路径识别。Windows 启动器可能改变路径大小写而不移动应用;字符串相等判断会触发不必要的 staging 和后端替换。事务清理在移除真实目录前,显式解除每一个嵌套目录链接。Windows 夹具在 Electron 44 下复现了递归 `fs.rmSync` 沿嵌套 junction 删除目标文件,而内置上游 Node 24.17 会保留它们。因此清理验收包含真实 Electron 运行时;仅在 Node 下测试不能证明目标文件会保留。 依赖修改先禁用脚本安装,验证插件依赖图和宿主链接,运行经过审查的待执行生命周期构建,再次验证。这允许已批准的原生依赖解析宿主 peer,同时阻止意外的重复宿主包进入启动过程。`allowBuilds` 策略保持明确;不受支持且需要构建的依赖会使事务失败。 事务日志记录源与目标运行时身份以及目录移动阶段。Desktop 等待 pnpm 退出,并在替换前停止活动后端。失败或中断的激活会恢复完整 profile。运行时身份不匹配会阻止恢复的 profile 在其他应用版本下启动。事务日志覆盖 profile 文件,不覆盖任意插件启动副作用或持久 Session 写入。 -后端无法启动时,Electron 拥有的恢复窗口仍可使用。用户可以更新、移除、停用或重新启用插件,并重试启动。不兼容插件不会被静默删除或自动降级。应用回滚与 profile 回滚是独立操作;每次后端启动都要求当前运行时身份。 +[立即显示窗口决策](2026-09-09-desktop-immediate-window-and-direct-start.zh.md)负责直接启动 Host 和主窗口恢复,取代 staging 后端探针。用户可以打开插件管理,更新、移除、停用或重新启用插件,并重试启动。不兼容插件不会被静默删除或自动降级。应用回滚与 profile 回滚是独立操作;每次后端启动都要求当前运行时身份。 ## 考虑过的替代方案 +完整运行时验证属于打包流程。启动读取描述文件,验证发布版本与目标平台的兼容性,检查共享包 manifest 和必要的 Host 入口,并使用记录的运行时身份复用 profile。首次启动和升级后启动都不枚举已安装运行时文件或计算其哈希。在后端加载前读取每个文件,会增加与分发体积成正比的启动 I/O。因此,启动不会通过校验和比较检测已安装内容的变化;不可用模块在加载时失败。构建时验证仍按记录的清单拒绝内容变化、缺失、多余或链接文件。 + - **启动时安装内置离线 seed。** 这保留普通 pnpm 安装流程,但会在每台受影响机器上重复核心解压与安装。物化资源消除了这部分工作,代价是更多应用文件和发布构建器责任。 - **把所有宿主依赖链接给插件。** 这会让普通插件依赖与宿主产生不必要的耦合。只链接明确的共享清单;私有包保留独立版本。 - **使用硬链接。** 它不能表示目录,可能无法跨卷,共享可写字节,并在应用替换后保留旧 inode。目录软链接和 Windows junction 能表达预期的包目标。 @@ -46,6 +54,6 @@ profile manifest 分别记录精确的已安装插件依赖和已启用 bundle ## 影响 -首次启动和兼容升级不安装核心包。运行时完整性验证和完整后端健康检查仍需要启动时间;没有测量前,不声称发布启动延迟或下载体积改善。插件保留以宿主 API 和原生运行时兼容为条件,条件不满足时提供可见的恢复入口。 +首次启动和兼容升级不安装核心包。元数据检查和后端加载仍需要启动时间;没有测量前,不声称发布启动延迟或下载体积改善。插件保留以宿主 API 和原生运行时兼容为条件,条件不满足时提供可见的恢复入口。 [Desktop README](../../../../apps/desktop/README.zh.md)负责操作说明。定向测试覆盖真实 pnpm 安装与已批准构建、共享 ESM 实例身份、私有依赖版本、应用移动、停用插件、原生重建选择、激活失败和事务锁。签名安装产物升级、macOS 公证、Windows junction 与原生行为、发布体积与启动基准,以及真实模型 GUI 录制仍是发布环境验收要求;单元夹具不能替代这些验证。 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.i18n.yaml new file mode 100644 index 0000000000..9a562164c3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.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-09-desktop-immediate-window-and-direct-start.md +2026-09-09-desktop-immediate-window-and-direct-start.md: 19443bb22e5fa3e50ce027b474cd439928db9992 +2026-09-09-desktop-immediate-window-and-direct-start.zh.md: 0d79638d331bb8b66a80f37f532b36ebb1e65316 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md new file mode 100644 index 0000000000..19443bb22e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md @@ -0,0 +1,29 @@ +# Agent Note: Show the Desktop window before starting the Host + +Status: implemented + +English | [中文](2026-09-09-desktop-immediate-window-and-direct-start.zh.md) + +## Problem + +Waiting for backend readiness leaves users without a window during profile preparation and module loading. A complete staged health-check process repeats backend startup before the application starts its serving process, while plugin startup can still fail in the serving process. + +## Decision + +Electron creates the main window with a local loading page before profile reconciliation or Host startup. The page depends only on packaged shell assets and receives starting, ready, or error state through the owned preload. Readiness loads the product UI in that window; an actual startup failure displays its diagnostic, retry, and plugin-management actions there. Closing during loading cancels further startup work and waits for the pending child to exit. + +Profile activation starts the actual Host after journaled directory replacement. Desktop does not boot and stop a separate health-check backend. Dependency metadata and graph validation, reviewed lifecycle builds, runtime identity checks, transaction locking, and profile rollback remain in place. A failed actual startup can restore the previous profile; rollback cannot undo plugin side effects or durable Session writes. + +This partially supersedes staged backend probes and waiting to create the main window in the [packaging decision](2026-08-25-electron-desktop-packaging-and-updates.md) and [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). Those notes retain release, signing, transport, resource ownership, and dependency-transaction rationale. Full runtime file verification remains a packaging operation. + +## Alternatives considered + +**Keep a complete staged health check.** It can reject a startup failure before replacing the active profile, but executes plugin initialization twice and cannot guarantee that the subsequent serving process will start. The actual startup result and journaled rollback provide recovery without the extra probe. + +**Keep the main window hidden until readiness.** This avoids presenting a loading page but gives users no visible progress or interaction while the backend loads. A shell-owned page can remain available when Host startup fails. + +## Consequences + +Users can see startup progress and recover from failures before the product UI is available. A responsive window does not imply that the backend is ready, and startup latency still requires installed-artifact measurement. Activation can fail after profile replacement; the journal retains recovery for profile files. + +Verification covers a delayed Host with a visible loading page, one serving startup for a fresh profile, failure and retry in the same window, plugin management during recovery, and closing while a child is starting. Installed GUI evidence complements lifecycle and transaction tests. diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md new file mode 100644 index 0000000000..0d79638d33 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md @@ -0,0 +1,29 @@ +# Agent Note: Show the Desktop window before starting the Host + +Status: implemented + +[English](2026-09-09-desktop-immediate-window-and-direct-start.md) | 中文 + +## 问题 + +等待后端就绪会让用户在准备 profile 和加载模块期间看不到窗口。完整的 staging 健康检查进程会在应用启动服务进程前重复启动后端,而插件在实际服务进程中仍然可能启动失败。 + +## 决策 + +Electron 在协调 profile 或启动 Host 前,先创建显示本地加载页的主窗口。该页面只依赖打包的壳资源,并通过受控 preload 接收 starting、ready 或 error 状态。就绪后在同一窗口加载产品 UI;实际启动失败时,在其中显示诊断、重试和插件管理操作。加载期间关闭应用会取消后续启动工作,并等待正在启动的子进程退出。 + +profile 激活在记录式目录替换后启动实际 Host。Desktop 不会另行启动并停止一个健康检查后端。依赖元数据与依赖图验证、经过审查的生命周期构建、运行时身份检查、事务锁和 profile 回滚仍然保留。实际启动失败可以恢复旧 profile;回滚不能撤销插件副作用或持久 Session 写入。 + +本决策部分取代[打包决策](2026-08-25-electron-desktop-packaging-and-updates.zh.md)和[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)中的 staging 后端探针与延迟创建主窗口。这两份记录仍保留发布、签名、传输、资源归属与依赖事务的理由。完整运行时文件验证仍属于打包操作。 + +## 考虑过的替代方案 + +**保留完整 staging 健康检查。** 它可以在替换活动 profile 前拒绝启动失败,但会执行两次插件初始化,也不能保证后续服务进程能够启动。实际启动结果与记录式回滚无需额外探针即可提供恢复能力。 + +**在就绪前隐藏主窗口。** 这避免显示加载页,但后端加载期间用户看不到进度,也无法交互。壳拥有的页面可以在 Host 启动失败时继续使用。 + +## 后果 + +产品 UI 可用前,用户就能看到启动进度并从失败中恢复。窗口可响应并不表示后端已就绪,启动延迟仍需测量安装产物。激活可能在替换 profile 后失败;事务日志保留 profile 文件的恢复能力。 + +验证覆盖 Host 延迟时可见的加载页、新 profile 只启动一次服务进程、同一窗口中的失败与重试、恢复期间的插件管理,以及子进程正在启动时关闭应用。安装后 GUI 证据补充生命周期与事务测试。 diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 30b7fcabe7..c2b596749a 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: 6ef18d302531beb80877f23d657d8524ff396b2b -README.zh.md: 94669b2697af894f91f33068526a0c61d6ed7a8f +README.md: 86ef7d9eb63f3b7aee89a86b5c3a4866af034ac5 +README.zh.md: ea8976b880a5d5a3df5932c700237505d5f19d5a diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 6ef18d3025..86ef7d9eb6 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -14,7 +14,7 @@ The desktop application is an Electron shell around the dsh Web UI. It opens no | Shared modules | Host APIs can depend on module identity. | Desktop links every bundled first-party package into the profile using directory symlinks, or Windows junctions; ordinary plugin dependencies remain local. | | State ownership | Sharing executable dependency graphs would let CLI and Desktop change each other's dsh, Cordis, plugin, or native-module versions, while two desktop processes could race on the same profile. | Electron acquires its process-lifetime single-instance lock before any profile access and exclusively owns `$DSH_HOME/profiles/desktop` plus its package-manager state. CLI and Desktop share supported product data under `$DSH_HOME`, but never executable packages, plugin activation, lockfiles, or `node_modules`. | | Transport | A listening Web service adds port ownership, authentication, CORS, and exposure concerns; Electron and upstream Node.js also need an explicit cross-process protocol. | The application opens no Web port. `dsh-app://` carries Web assets and Fetch traffic; framed byte pipes carry bounded request and response chunks with backpressure, while Node IPC carries only child lifecycle control. | -| Activation | Dependency resolution, lifecycle scripts, native modules, and plugin startup can fail, and a process can stop during directory replacement. | Release and plugin changes install in staging, boot a complete backend health check, and replace the active profile only after success; a journal and one rollback profile cover interrupted replacement. | +| Activation | Dependency resolution, lifecycle scripts, native modules, and plugin startup can fail, and a process can stop during directory replacement. | Release and plugin changes prepare in staging and start the actual backend after profile replacement; a journal and one rollback profile cover failed or interrupted activation. | | Updates | Independent shell and dsh updates would recreate version splits, while unchanged shell blocks should not require a complete transfer. | The Electron shell, matching dsh runtime, Node.js, and pnpm form one signed update unit. Platform update artifacts may reuse unchanged blocks, but runtime version selection never splits from the Desktop release. | The [Electron packaging and update Agent Note](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) owns the rationale, alternatives, security constraints, and release qualification requirements behind these decisions. @@ -23,23 +23,23 @@ The [Electron packaging and update Agent Note](../../.agents/notes/implemented/a Electron owns `$DSH_HOME/profiles/desktop`. Its `dependencies` contains only installed external plugins at exact versions; `dsh.profile.bundles` contains the built-in bundles followed by enabled plugins. The signed application supplies dsh, the private Desktop Host, and their production packages from `resources/dsh`. Shared package links resolve to those actual directories. Both host and plugins execute in the same bundled upstream Node process, with normal realpath resolution; Desktop does not enable `--preserve-symlinks`. The CLI cannot boot or mutate this profile. -The main dsh renderer receives only the desktop protocol marker. The separate plugin window receives structured list, install, remove, update, and update-check operations; neither renderer receives filesystem access, raw Electron IPC, a shell, or arbitrary pnpm arguments. +The local startup page exposes startup status, retry, and plugin-management actions; the loaded dsh renderer receives only the desktop protocol marker. The separate plugin window receives structured list, install, remove, update, and update-check operations; neither renderer receives filesystem access, raw Electron IPC, a shell, or arbitrary pnpm arguments. -Electron chooses typed English or Chinese shell copy from its application locale and falls back to English. Menus, native dialogs, and the plugin-management renderer use the same locale payload; the repository Client UI i18n gate checks these desktop sources. +Electron chooses typed English or Chinese shell copy from its application locale and falls back to English. Menus, native dialogs, the startup page, and the plugin-management renderer use the same locale payload; the repository Client UI i18n gate checks these desktop sources. ### Runtime and plugin activation -The signed `resources/dsh/desktop-runtime.json` binds the shell version, bundled Node version, platform, architecture, shared package versions, and final file inventory. Startup verifies the tree before creating host links. Core packages are never copied into profile storage or installed by pnpm at first launch. +The signed `resources/dsh/desktop-runtime.json` binds the shell version, bundled Node version, platform, architecture, shared package versions, and final file inventory. Startup checks release metadata, shared package manifests, and required Host entry files without enumerating or hashing the runtime tree. Full file integrity verification runs during packaging. Core packages are never copied into profile storage or installed by pnpm at first launch. -1. A fresh profile creates its manifest and shared package links, then boots and stops the complete backend before activation. -2. A compatible application upgrade copies plugin files and configuration into staging, refreshes shared links, checks enabled plugins’ peer requirements, and runs the same backend health check. Plugin versions and lockfile remain unchanged; pnpm does not run. +1. The main window displays a local loading page before profile preparation or backend startup. A fresh profile creates its manifest and shared package links, then activates and starts the actual backend once. +2. A compatible application upgrade copies plugin files and configuration into staging, refreshes shared links, and checks enabled plugins’ peer requirements. Plugin versions and lockfile remain unchanged; pnpm does not run. 3. A changed bundled Node version, platform, or architecture reinstalls the locked plugin graph with scripts disabled, validates and links host packages, then runs approved pending builds and validates again. 4. Plugin add, update, and remove operations use bundled pnpm and Desktop-owned package-manager state. Reserved host packages must be peers; nested copies and aliases of shared packages fail validation. Ordinary plugin dependencies must resolve inside the profile. -5. Activation stops the active backend, records runtime identities and the next directory move, and replaces the profile while retaining one rollback copy. Copies do not share writable hardlinks. A failed activation restores the previous profile; a profile belonging to another runtime cannot boot under the current shell. +5. Activation stops the active backend, records runtime identities and the next directory move, and replaces the profile while retaining one rollback copy. Copies do not share writable hardlinks. The actual backend starts after replacement; failed activation restores the previous profile; a profile belonging to another runtime cannot boot under the current shell. -The Electron-owned plugin window remains available when backend startup fails. Disable one plugin or all plugins to retry with their files, exact versions, and configuration retained. Disabling removes only activation entries. Updating or removing an installed plugin remains available while it is disabled. Application rollback and profile rollback are separate; runtime compatibility is checked before any backend starts. +The loading page does not depend on the Host. Startup failures appear in the same main window with retry and plugin-management actions. Closing during loading waits for the pending child to exit. The Electron-owned plugin window remains available when backend startup fails. Disable one plugin or all plugins to retry with their files, exact versions, and configuration retained. Disabling removes only activation entries. Updating or removing an installed plugin remains available while it is disabled. Application rollback and profile rollback are separate; runtime compatibility is checked before any backend starts. -Package transactions hold an exclusive lock through pnpm process exit. Shared links use directory symlinks on macOS/Linux and junctions on Windows; hardlinks are unsuitable because they cannot represent package directories and would retain old file content after application replacement. Native builds follow the profile’s reviewed `allowBuilds` list; installing a new build-requiring package without approval in that list fails the transaction. +Package transactions hold an exclusive lock through pnpm process exit. Shared links use directory symlinks on macOS/Linux and junctions on Windows; cleanup removes links without deleting their targets. Canonical filesystem paths identify shared packages, so Windows path casing alone does not trigger profile activation. Native builds follow the profile’s reviewed `allowBuilds` list; installing a new build-requiring package without approval in that list fails the transaction. ## Develop @@ -90,6 +90,12 @@ The macOS arm64 command requires Apple Silicon. The macOS x64 command runs on In Each target owns its packed package inputs, prepared runtime, package set, dsh tree, pnpm preparation state, unpacked application, update metadata, and final artifacts under `apps/desktop/.desktop-build/targets//`. The Node.js archive cache remains shared under `.desktop-build/downloads` because every archive name includes its version, platform, and architecture and is verified before extraction. A target build never consumes another target's mutable preparation state. +### Runtime file selection + +Production packages first pass through npm's publication rules and dependency installation. [Desktop's file policy](scripts/runtime-file-policy.ts) then filters the immutable `resources/dsh/node_modules` copy before signing and integrity sealing. It omits TypeScript declarations, recognized JavaScript/CSS/TypeScript source maps, TypeScript build caches, Domino's test directory, selected native compiler outputs, and node-pty prebuilds for other platforms. It preserves runtime JavaScript, native modules and their DLL/EXE helpers, WASM, unknown assets, licenses, and notices. The policy does not alter npm tarballs, the bundled package manager, or user-installed plugin files. + +The packaged application runs compiled JavaScript and pre-generated Typert metadata; it does not compile TypeScript plugins. Source-level debugger navigation and editor declarations remain available in development packages. [Copy-policy tests](tests/runtime-file-policy.spec.ts) cover exclusions and retained assets; the [payload smoke](tests/fixtures/runtime-payload-smoke.mjs) exercises the resulting native modules and HTML converter under the bundled Node. + ### Upload updates `DSH_DESKTOP_AUTO_UPDATE_ENV` selects `test` or `production` for both the URL embedded during packaging and the later COS upload; an absent value selects `test`. Test packaging requires its HTTPS origin in `DOWNLOAD_TEST_ORIGIN`, while the production origin remains `https://download.deepseek.com`. Upload additionally requires the selected deployment's COS bucket in `DOWNLOAD_TEST_COS_BUCKET` or `DOWNLOAD_PROD_COS_BUCKET`. The target path is `_/harness/desktop/stable//`, where `target` is `mac-arm64`, `mac-x64`, or `win-x64`. @@ -119,8 +125,22 @@ 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. +### Unsigned Windows test installer + +On Windows x64, use the complete unsigned packaging command for local installation testing: + +```sh +pnpm run package:desktop:win:x64:unsigned +``` + +The command requires `DSH_DESKTOP_APP_ID` and the normal build dependencies, including Python and Visual C++ build tools for native modules. Set `PYTHON` to the Python executable when it is absent from `PATH`. It writes the installer to `.desktop-build/targets/win-x64/unsigned-artifacts/`, omits automatic-update configuration, strips signing credentials, and creates no release completion record. It does not require EV credentials or an update origin. The signed packaging and upload commands retain their release requirements. + ### Windows EV signing +Windows packaging fixes the 7-Zip filter to `BCJ` for compatibility with the bundled NSIS decoder. This preserves ARM64 binaries carried by dependencies in x64 installers; automatic ARM64 filtering produces entries that this decoder cannot extract. + +NSIS removes its temporary extraction tree during installation, before the completion page or an automatic launch. The installed production packages remain ordinary files; startup does not extract them again. Installation still writes the complete application tree. + Windows release packaging requires `DSH_DESKTOP_WINDOWS_CER_FILE` to identify the public GlobalSign EV leaf certificate, `DSH_DESKTOP_WINDOWS_SIGNTOOL` to identify the SafeNet-compatible SignTool executable, `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` to identify the matching private-key container, and `DSH_DESKTOP_WINDOWS_TOKEN_PIN` to contain the SafeNet Token Password. The certificate file remains outside source control, and the matching private key stays on the USB token. Set the four inputs before running the fixed Windows target: ```powershell @@ -131,7 +151,7 @@ $env:DSH_DESKTOP_WINDOWS_TOKEN_PIN = '' pnpm run package:desktop:win:x64 ``` -Insert and unlock the token before packaging. The electron-builder hook passes each artifact to the CRLF `scripts/windows-sign.cmd`, which invokes the configured SignTool once with `/f`, SafeNet `/kc "[{{PIN}}]=container"`, `/csp "eToken Base Cryptographic Provider"`, a SHA-256 file digest, and a DigiCert SHA-256 RFC 3161 timestamp. The hook never substitutes electron-builder's bundled SignTool and never retries a failed signing request. Windows packaging fails instead of emitting unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. +Insert and unlock the token before packaging. The electron-builder hook passes each artifact to the CRLF `scripts/windows-sign.cmd`, which invokes the configured SignTool once with `/f`, SafeNet `/kc "[{{PIN}}]=container"`, `/csp "eToken Base Cryptographic Provider"`, a SHA-256 file digest, and a DigiCert SHA-256 RFC 3161 timestamp. The hook never substitutes electron-builder's bundled SignTool and never retries a failed signing request. Windows release packaging fails instead of emitting unsigned artifacts when the SignTool, certificate, container, PIN, token, or signature is unavailable. The PIN cannot contain `]`, a quote, or a line break because those characters delimit the SafeNet `/kc` value or its CMD argument. The CMD disables delayed expansion so a PIN containing `!` reaches SafeNet unchanged. Packaging withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation subprocesses, gives electron-builder only the four configured inputs, gives the signing CMD only the validated signing fields in an otherwise scrubbed environment, clears those fields before SignTool starts, and redacts SignTool diagnostics. SafeNet still requires the PIN in the SignTool process command line. Inject it as an ephemeral secret only on a controlled self-hosted Windows runner with the physical token attached; never commit it, put it in `.env`, or persist it as a Windows user or system environment variable. @@ -156,9 +176,9 @@ An unpacked artifact contains Electron, the materialized dsh production tree, up ## Updates -A packaged application checks its target-specific release stream ten seconds after the main window opens; the localized **Check for Updates…** menu item triggers the same check manually. An available release opens one native confirmation dialog. Accepting it waits for an in-flight check, downloads and verifies the signed Desktop release, stops the dsh child, and hands installation plus restart to electron-updater. The next launch reconciles the version-bound runtime before reopening the product window. +A packaged application checks its target-specific release stream ten seconds after the main window opens; the localized **Check for Updates…** menu item triggers the same check manually. An available release opens one native confirmation dialog. Accepting it waits for an in-flight check, downloads and verifies the signed Desktop release, stops the dsh child, and hands installation plus restart to electron-updater. The next launch displays the local loading page while reconciling the version-bound runtime. -Electron-builder always emits generic-provider channel metadata for the deployment selected by `DSH_DESKTOP_AUTO_UPDATE_ENV`. NSIS differential packages and the macOS ZIP target allow electron-updater to reuse unchanged blocks; the manually installed DMG is notarized without a blockmap because it is not a macOS updater payload. The runtime and shell still form one signed Desktop release. macOS signing and notarization credentials use electron-builder's standard environment; Windows EV signing uses the public certificate, validated SignTool, SafeNet container, and runner PIN described above. The required Desktop release environment selects the application and platform signature identities that the build verifies. +Signed packaging emits generic-provider channel metadata for the deployment selected by `DSH_DESKTOP_AUTO_UPDATE_ENV`. NSIS differential packages and the macOS ZIP target allow electron-updater to reuse unchanged blocks; the manually installed DMG is notarized without a blockmap because it is not a macOS updater payload. The runtime and shell still form one signed Desktop release. macOS signing and notarization credentials use electron-builder's standard environment; Windows EV signing uses the public certificate, validated SignTool, SafeNet container, and runner PIN described above. The required Desktop release environment selects the application and platform signature identities that the build verifies. ## Low-level development overrides diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 94669b2697..ea8976b880 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -14,7 +14,7 @@ | 共享模块 | 宿主 API 可能依赖模块实例身份。 | Desktop 用目录软链接或 Windows junction 把每个内置第一方包连接到 profile;普通插件依赖保留在本地。 | | 状态归属 | 共享可执行依赖图会让 CLI 与 Desktop 相互改变 dsh、Cordis、插件或原生模块版本,而两个桌面进程还可能争用同一个 profile。 | Electron 在访问任何 profile 前获取进程生命周期单实例锁,并独占 `$DSH_HOME/profiles/desktop` 及其包管理器状态。CLI 与 Desktop 共享 `$DSH_HOME` 下受支持的产品数据,但绝不共享可执行包、插件激活、锁文件或 `node_modules`。 | | 通信 | 监听 Web 服务会引入端口归属、认证、CORS 与暴露风险;Electron 与上游 Node.js 之间也需要明确的跨进程协议。 | 应用不打开 Web 端口。`dsh-app://` 承载 Web 资源和 Fetch 流量;分帧字节管道以背压传输有界请求与响应分块,Node IPC 只承载子进程生命周期控制。 | -| 激活 | 依赖解析、生命周期脚本、原生模块与插件启动都可能失败,目录替换期间进程也可能中断。 | 发布与插件变更先安装到 staging,并启动完整后端执行健康检查;只有成功后才替换活跃 profile,中断替换由事务日志和一个 rollback profile 恢复。 | +| 激活 | 依赖解析、生命周期脚本、原生模块与插件启动都可能失败,目录替换期间进程也可能中断。 | 发布与插件变更先在 staging 准备,替换 profile 后启动实际后端;失败或中断的激活由事务日志和一个 rollback profile 恢复。 | | 更新 | 桌面壳与 dsh 独立更新会重新产生版本分裂,而桌面壳未变化的数据块不应强制完整传输。 | Electron 壳、匹配的 dsh 运行时、Node.js 与 pnpm 组成一个已签名更新单元。平台更新产物可以复用未变化的数据块,但运行时版本选择绝不脱离 Desktop 发布。 | [Electron 打包与更新 Agent Note](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)记录了这些决策背后的理由、替代方案、安全约束和发布验证要求。 @@ -23,23 +23,23 @@ Electron 拥有 `$DSH_HOME/profiles/desktop`。其 `dependencies` 只包含已安装外部插件的精确版本;`dsh.profile.bundles` 包含内置 bundle,后接已启用插件。签名应用从 `resources/dsh` 提供 dsh、私有 Desktop Host 及其生产依赖。共享包链接解析到这些实际目录。宿主与插件在同一个内置上游 Node 进程中执行,使用正常的 realpath 解析;Desktop 不启用 `--preserve-symlinks`。CLI 不能启动或修改此 profile。 -dsh 主渲染进程只获得桌面协议标记。独立插件窗口获得结构化的列出、安装、移除、更新和更新检查操作;两个渲染进程都拿不到文件系统、原始 Electron IPC、shell 或任意 pnpm 参数。 +本地启动页提供启动状态、重试和插件管理操作;加载后的 dsh 渲染进程只获得桌面协议标记。独立插件窗口获得结构化的列出、安装、移除、更新和更新检查操作;两个渲染进程都拿不到文件系统、原始 Electron IPC、shell 或任意 pnpm 参数。 -Electron 根据应用 locale 选择类型化的中英文字典,并以英文作为 fallback。菜单、原生对话框与插件管理渲染进程使用同一 locale 数据;仓库的 Client UI i18n gate 会检查这些桌面源文件。 +Electron 根据应用 locale 选择类型化的中英文字典,并以英文作为 fallback。菜单、原生对话框、启动页与插件管理渲染进程使用同一 locale 数据;仓库的 Client UI i18n gate 会检查这些桌面源文件。 ### 运行时与插件激活 -签名资源中的 `resources/dsh/desktop-runtime.json` 绑定 shell 版本、内置 Node 版本、平台、架构、共享包版本和最终文件清单。启动会先验证依赖树,再创建宿主链接。首次启动不会把核心包复制到 profile 存储或通过 pnpm 安装核心包。 +签名资源中的 `resources/dsh/desktop-runtime.json` 绑定 shell 版本、内置 Node 版本、平台、架构、共享包版本和最终文件清单。启动检查发布元数据、共享包 manifest 和必要的 Host 入口文件,不枚举运行时目录树或计算其文件哈希。完整的文件完整性验证在打包时执行。首次启动不会把核心包复制到 profile 存储或通过 pnpm 安装核心包。 -1. 新 profile 创建 manifest 和共享包链接,然后启动并停止完整后端,通过后才激活。 -2. 兼容的应用升级把插件文件和配置复制到 staging,刷新共享链接,检查已启用插件的 peer 要求,并执行相同的后端健康检查。插件版本和锁文件保持不变;不运行 pnpm。 +1. 主窗口在准备 profile 或启动后端前显示本地加载页。新 profile 创建 manifest 和共享包链接,然后激活并启动一次实际后端。 +2. 兼容的应用升级把插件文件和配置复制到 staging,刷新共享链接,并检查已启用插件的 peer 要求。插件版本和锁文件保持不变;不运行 pnpm。 3. 内置 Node 版本、平台或架构变化时,禁用脚本重新安装锁定的插件依赖图,验证并链接宿主包,然后运行已批准的待执行构建并再次验证。 4. 插件添加、更新和删除使用内置 pnpm 及 Desktop 独有的包管理器状态。保留的宿主包必须声明为 peer;共享包的嵌套副本和别名会被验证拒绝。普通插件依赖必须解析到 profile 内部。 -5. 激活会停止活动后端,记录运行时身份和下一次目录移动,并替换 profile,同时保留一个回滚副本。复制不共享可写硬链接。激活失败会恢复旧 profile;属于其他运行时的 profile 不能在当前 shell 下启动。 +5. 激活会停止活动后端,记录运行时身份和下一次目录移动,并替换 profile,同时保留一个回滚副本。复制不共享可写硬链接。替换后启动实际后端;激活失败会恢复旧 profile;属于其他运行时的 profile 不能在当前 shell 下启动。 -后端启动失败时,Electron 拥有的插件窗口仍然可用。可以停用一个或全部插件后重试,同时保留其文件、精确版本和配置。停用只移除激活条目。已停用插件仍可更新或删除。应用回滚和 profile 回滚分别处理;每次启动后端前都会检查运行时兼容性。 +加载页不依赖 Host。启动失败在同一个主窗口显示,并提供重试和插件管理操作。加载期间关闭应用会等待正在启动的子进程退出。后端启动失败时,Electron 拥有的插件窗口仍然可用。可以停用一个或全部插件后重试,同时保留其文件、精确版本和配置。停用只移除激活条目。已停用插件仍可更新或删除。应用回滚和 profile 回滚分别处理;每次启动后端前都会检查运行时兼容性。 -包事务持有独占锁直到 pnpm 进程退出。共享链接在 macOS/Linux 使用目录软链接,在 Windows 使用 junction;硬链接无法表示包目录,而且应用替换后仍会保留旧文件内容,因此不适合此用途。原生构建遵循 profile 中经过审查的 `allowBuilds` 列表;新安装的包如果需要构建但未在列表中获准,事务会失败。 +包事务持有独占锁直到 pnpm 进程退出。共享链接在 macOS/Linux 使用目录软链接,在 Windows 使用 junction;清理只移除链接,不删除其目标。共享包使用文件系统的规范路径识别,因此 Windows 路径大小写变化不会单独触发 profile 激活。原生构建遵循 profile 中经过审查的 `allowBuilds` 列表;新安装的包如果需要构建但未在列表中获准,事务会失败。 ## 开发 @@ -90,6 +90,12 @@ macOS arm64 命令要求 Apple Silicon。macOS x64 命令可以在 Intel macOS 每个目标都在 `apps/desktop/.desktop-build/targets//` 下持有自己的打包输入、已准备运行时、包集合、dsh 依赖树、pnpm 准备状态、未打包应用、更新元数据和最终产物。Node.js 归档缓存继续由 `.desktop-build/downloads` 共享,因为每个归档文件名都包含版本、平台和架构,并且在解包前经过验证。目标构建绝不读取其他目标的可变准备状态。 +### 运行时文件筛选 + +生产包首先经过 npm 发布规则和依赖安装。[桌面文件规则](scripts/runtime-file-policy.ts)随后在签名和完整性封存之前过滤不可变的 `resources/dsh/node_modules` 副本。它排除 TypeScript 声明、明确属于 JavaScript/CSS/TypeScript 的 source map、TypeScript 构建缓存、Domino 测试目录、指定的原生编译产物,以及其他平台的 node-pty 预构建文件。它保留运行时 JavaScript、原生模块及其 DLL/EXE 辅助程序、WASM、未知资源、许可证和声明。规则不会修改 npm tarball、内置包管理器或用户安装的插件文件。 + +打包应用运行编译后的 JavaScript 和预生成的 Typert 元数据,不编译 TypeScript 插件。源码级调试导航和编辑器声明仍可从开发包中获取。[复制规则测试](tests/runtime-file-policy.spec.ts)覆盖排除项和保留资源;[产物 smoke](tests/fixtures/runtime-payload-smoke.mjs)使用内置 Node 验证过滤后的原生模块和 HTML 转换器。 + ### 上传更新 `DSH_DESKTOP_AUTO_UPDATE_ENV` 同时选择打包时写入的更新 URL 与后续 COS 上传目标,可取 `test` 或 `production`;未设置时使用 `test`。测试打包必须通过 `DOWNLOAD_TEST_ORIGIN` 提供 HTTPS origin,生产 origin 仍为 `https://download.deepseek.com`。上传还必须通过 `DOWNLOAD_TEST_COS_BUCKET` 或 `DOWNLOAD_PROD_COS_BUCKET` 提供所选环境的 COS bucket。目标路径为 `_/harness/desktop/stable//`,其中 `target` 为 `mac-arm64`、`mac-x64` 或 `win-x64`。 @@ -119,8 +125,22 @@ macOS 配置使用必填发布环境,不会接受钥匙串中最先发现的 macOS 签名遍历真实文件,不跟随 Framework 的软链接别名。PAK 资源保留全部随附语言,由外层 Framework 或应用签名记录完整性,不逐个签名。[发布策略](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)负责依赖补丁和验证要求。 +### 未签名 Windows 测试安装包 + +在 Windows x64 上,使用完整的未签名打包命令进行本地安装测试: + +```sh +pnpm run package:desktop:win:x64:unsigned +``` + +该命令要求设置 `DSH_DESKTOP_APP_ID` 并具备常规构建依赖,包括编译原生模块所需的 Python 和 Visual C++ 构建工具。Python 不在 `PATH` 中时,将 `PYTHON` 设置为其可执行文件路径。命令将安装包写入 `.desktop-build/targets/win-x64/unsigned-artifacts/`,省略自动更新配置,清除签名凭据,且不生成发布完成记录。它不需要 EV 凭据或更新源地址。签名打包和上传命令仍遵循正式发布要求。 + ### Windows EV 签名 +Windows 打包将 7-Zip 过滤器固定为 `BCJ`,以兼容内置的 NSIS 解码器。这样可以保留 x64 安装包中由依赖携带的 ARM64 二进制文件;自动 ARM64 过滤会生成该解码器无法解压的条目。 + +NSIS 在安装阶段清理临时解压目录,完成后才显示完成页或自动启动应用。已安装的生产依赖保持为普通文件;启动时不会再次解压。安装仍会写入完整的应用目录树。 + Windows 发布打包要求 `DSH_DESKTOP_WINDOWS_CER_FILE` 标识公开的 GlobalSign EV 叶证书,要求 `DSH_DESKTOP_WINDOWS_SIGNTOOL` 标识与 SafeNet 兼容的 SignTool 可执行文件,要求 `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` 标识匹配的私钥容器,并要求 `DSH_DESKTOP_WINDOWS_TOKEN_PIN` 包含 SafeNet Token Password。证书文件保留在源码仓库之外,匹配的私钥仍位于 USB Token。运行固定 Windows 目标前设置这四个输入: ```powershell @@ -131,7 +151,7 @@ $env:DSH_DESKTOP_WINDOWS_TOKEN_PIN = '' pnpm run package:desktop:win:x64 ``` -打包前插入并解锁 Token。electron-builder hook 把每个产物交给采用 CRLF 的 `scripts/windows-sign.cmd`;该 CMD 只调用一次已配置的 SignTool,并指定 `/f`、SafeNet `/kc "[{{PIN}}]=容器"`、`/csp "eToken Base Cryptographic Provider"`、SHA-256 文件摘要和 DigiCert SHA-256 RFC 3161 时间戳。hook 不会改用 electron-builder 内置的 SignTool,也不会重试失败的签名请求。SignTool、证书、容器、PIN、Token 或签名不可用时,Windows 打包会失败,不会生成未签名产物。 +打包前插入并解锁 Token。electron-builder hook 把每个产物交给采用 CRLF 的 `scripts/windows-sign.cmd`;该 CMD 只调用一次已配置的 SignTool,并指定 `/f`、SafeNet `/kc "[{{PIN}}]=容器"`、`/csp "eToken Base Cryptographic Provider"`、SHA-256 文件摘要和 DigiCert SHA-256 RFC 3161 时间戳。hook 不会改用 electron-builder 内置的 SignTool,也不会重试失败的签名请求。SignTool、证书、容器、PIN、Token 或签名不可用时,Windows 发布打包会失败,不会生成未签名产物。 PIN 不能包含 `]`、引号或换行,因为这些字符用于分隔 SafeNet `/kc` 值或对应的 CMD 参数。CMD 会禁用延迟展开,因此包含 `!` 的 PIN 可以原样到达 SafeNet。打包流程不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程;它只向 electron-builder 提供四个配置输入,在其他字段已经清理的环境中只向签名 CMD 提供经过校验的签名字段,在 SignTool 启动前清除这些字段,并遮盖 SignTool 诊断。SafeNet 仍要求 PIN 出现在 SignTool 进程命令行中。只能在连接了物理 Token 的受控 self-hosted Windows runner 上把它注入为临时 secret;绝不能提交该值、把它写进 `.env`,或持久保存为 Windows 用户或系统环境变量。 @@ -156,9 +176,9 @@ pnpm run prepare:desktop ## 更新 -打包应用会在主窗口打开十秒后检查目标专用的发布流;本地化的 **检查更新…** 菜单项会手动触发同一检查。发现可用版本时,应用打开一个原生确认弹窗。用户确认后,应用等待正在进行的检查完成,下载并验证已签名的 Desktop 发布、停止 dsh 子进程,并把安装与重启交给 electron-updater。下次启动会先校准版本绑定的运行时,再重新打开产品窗口。 +打包应用会在主窗口打开十秒后检查目标专用的发布流;本地化的 **检查更新…** 菜单项会手动触发同一检查。发现可用版本时,应用打开一个原生确认弹窗。用户确认后,应用等待正在进行的检查完成,下载并验证已签名的 Desktop 发布、停止 dsh 子进程,并把安装与重启交给 electron-updater。下次启动在显示本地加载页的同时校准版本绑定的运行时。 -Electron-builder 始终为 `DSH_DESKTOP_AUTO_UPDATE_ENV` 选择的部署生成 generic-provider 频道元数据。NSIS 差分包与 macOS ZIP 目标让 electron-updater 可以复用未变化的数据块;供手动安装的 DMG 经过公证,但不生成 blockmap,因为它不是 macOS updater 的载荷。运行时与桌面壳仍属于同一个签名 Desktop 发布。macOS 签名与公证凭据使用 electron-builder 的标准环境变量;Windows EV 签名使用上文所述的公开证书、已验证 SignTool、SafeNet 容器和 runner PIN。必填 Desktop 发布环境选择构建所验证的应用身份与平台签名身份。 +签名打包为 `DSH_DESKTOP_AUTO_UPDATE_ENV` 选择的部署生成 generic-provider 频道元数据。NSIS 差分包与 macOS ZIP 目标让 electron-updater 可以复用未变化的数据块;供手动安装的 DMG 经过公证,但不生成 blockmap,因为它不是 macOS updater 的载荷。运行时与桌面壳仍属于同一个签名 Desktop 发布。macOS 签名与公证凭据使用 electron-builder 的标准环境变量;Windows EV 签名使用上文所述的公开证书、已验证 SignTool、SafeNet 容器和 runner PIN。必填 Desktop 发布环境选择构建所验证的应用身份与平台签名身份。 ## 底层开发覆盖项 diff --git a/apps/desktop/electron-builder.config.d.mts b/apps/desktop/electron-builder.config.d.mts index 760f8cb8a1..8a78f3a68a 100644 --- a/apps/desktop/electron-builder.config.d.mts +++ b/apps/desktop/electron-builder.config.d.mts @@ -19,8 +19,11 @@ export interface DesktopElectronBuilderConfig { readonly sign: boolean readonly writeUpdateInfo: boolean } + readonly nsis: { + readonly include: string + } readonly artifactBuildCompleted: (artifact: { readonly file: string }) => Promise | undefined - readonly publish: readonly [{ readonly provider: 'generic', readonly url: string }] + readonly publish: readonly [{ readonly provider: 'generic', readonly url: string }] | null } /** diff --git a/apps/desktop/electron-builder.config.mjs b/apps/desktop/electron-builder.config.mjs index aee7a5b375..4dfb363693 100644 --- a/apps/desktop/electron-builder.config.mjs +++ b/apps/desktop/electron-builder.config.mjs @@ -1,4 +1,5 @@ import { join } from 'node:path' +import { fileURLToPath } from 'node:url' import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, @@ -11,7 +12,7 @@ import { installWindowsNsisBootstrapSigner, } from './scripts/windows-sign.mjs' import { resolveDesktopAutoUpdateConfig } from './scripts/desktop-auto-update-environment.mjs' -import { desktopTargetBuildPaths } from './scripts/desktop-build-paths.mjs' +import { desktopTargetBuildPaths, resolveDesktopBuildTarget } from './scripts/desktop-build-paths.mjs' /** * Create electron-builder configuration from one release environment. @@ -29,11 +30,16 @@ export function createElectronBuilderConfig( const targetPlatform = env.DSH_DESKTOP_TARGET_PLATFORM const resolvedPlatform = targetPlatform ?? hostPlatform const resolvedArch = env.DSH_DESKTOP_TARGET_ARCH ?? hostArch + if (env.DSH_DESKTOP_UNSIGNED !== undefined && !['0', '1'].includes(env.DSH_DESKTOP_UNSIGNED)) { + throw new Error('desktop package: DSH_DESKTOP_UNSIGNED must be 0 or 1') + } + const unsigned = env.DSH_DESKTOP_UNSIGNED === '1' + if (unsigned && resolvedPlatform !== 'win32') throw new Error('desktop package: unsigned builds require Windows') const packagesMacOS = targetPlatform === 'darwin' || (targetPlatform === undefined && hostPlatform === 'darwin') const packagesWindows = targetPlatform === 'win32' const macOSSigning = packagesMacOS ? resolveMacOSSigningEnvironment(env) : undefined if (packagesMacOS) resolveMacOSNotarizationEnvironment(env) - const windowsSigner = packagesWindows + const windowsSigner = packagesWindows && !unsigned ? createWindowsTokenSigner({ certificateFile: env.DSH_DESKTOP_WINDOWS_CER_FILE, signTool: env.DSH_DESKTOP_WINDOWS_SIGNTOOL, @@ -44,13 +50,13 @@ export function createElectronBuilderConfig( if (windowsSigner !== undefined) { installWindowsNsisBootstrapSigner({ sign: windowsSigner }) } - const update = resolveDesktopAutoUpdateConfig(env, resolvedPlatform, resolvedArch) - const buildPaths = desktopTargetBuildPaths(update.target) + const update = unsigned ? undefined : resolveDesktopAutoUpdateConfig(env, resolvedPlatform, resolvedArch) + const buildPaths = desktopTargetBuildPaths(resolveDesktopBuildTarget(env, hostPlatform, hostArch)) return { appId, productName: 'DeepSeek Harness', artifactName: 'deepseek-harness-${version}-${os}-${arch}.${ext}', - directories: { output: buildPaths.artifacts }, + directories: { output: unsigned ? join(buildPaths.root, 'unsigned-artifacts') : buildPaths.artifacts }, asar: true, files: [ 'lib/*.js', @@ -80,13 +86,13 @@ export function createElectronBuilderConfig( }, afterPack: async context => { const { verifyDesktopRuntime } = await import('./lib/types/runtime-tree.js') - verifyDesktopRuntime(join(context.packager.getResourcesDir(context.appOutDir), 'dsh'), + await verifyDesktopRuntime(join(context.packager.getResourcesDir(context.appOutDir), 'dsh'), context.packager.appInfo.version, { platform: resolvedPlatform, arch: resolvedArch }) }, afterSign: async context => { if (context.electronPlatformName !== 'darwin') return const { verifyDesktopRuntime } = await import('./lib/types/runtime-tree.js') - verifyDesktopRuntime(join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`, 'Contents', 'Resources', 'dsh'), + await verifyDesktopRuntime(join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`, 'Contents', 'Resources', 'dsh'), context.packager.appInfo.version, { platform: 'darwin', arch: resolvedArch }) verifyMacOSSignatureAfterSign(context, macOSSigning ?? resolveMacOSSigningEnvironment(env)) }, @@ -99,7 +105,7 @@ export function createElectronBuilderConfig( ) }, win: { - forceCodeSigning: true, + forceCodeSigning: !unsigned, signtoolOptions: { sign: windowsSigner, signingHashAlgorithms: ['sha256'], @@ -111,11 +117,12 @@ export function createElectronBuilderConfig( target: ['AppImage'], }, nsis: { + include: fileURLToPath(new URL('./scripts/installer.nsh', import.meta.url)), oneClick: false, allowToChangeInstallationDirectory: true, differentialPackage: true, }, - publish: [{ provider: 'generic', url: update.publicUrl }], + publish: update === undefined ? null : [{ provider: 'generic', url: update.publicUrl }], } } diff --git a/apps/desktop/package.json b/apps/desktop/package.json index e8d38981c5..240644a84f 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -22,6 +22,7 @@ "package:mac:x64": "tsx scripts/package-target.ts mac-x64", "package:mac:x64:dir": "tsx scripts/package-target.ts mac-x64 --dir", "package:win:x64": "tsx scripts/package-target.ts win-x64", + "package:win:x64:unsigned": "tsx scripts/package-target.ts win-x64 --unsigned", "package:win:x64:dir": "tsx scripts/package-target.ts win-x64 --dir", "upload:mac:arm64": "tsx scripts/upload-target.ts mac-arm64", "upload:mac:x64": "tsx scripts/upload-target.ts mac-x64", diff --git a/apps/desktop/renderer/plugin-manager.js b/apps/desktop/renderer/plugin-manager.js index 6599c5b9d5..c87460a49f 100644 --- a/apps/desktop/renderer/plugin-manager.js +++ b/apps/desktop/renderer/plugin-manager.js @@ -32,8 +32,8 @@ async function main() { async function render() { const backend = await api.backend.status() - document.querySelector('#recovery').hidden = backend.ready - document.querySelector('#startup-error').textContent = backend.error ?? '' + document.querySelector('#recovery').hidden = backend.phase !== 'error' + document.querySelector('#startup-error').textContent = backend.phase === 'error' ? backend.message : '' const plugins = await api.plugins.list() list.replaceChildren(...plugins.map(plugin => { const item = document.createElement('li') diff --git a/apps/desktop/renderer/startup.css b/apps/desktop/renderer/startup.css new file mode 100644 index 0000000000..a15f246ee3 --- /dev/null +++ b/apps/desktop/renderer/startup.css @@ -0,0 +1,16 @@ +:root { color-scheme: light dark; font-family: system-ui, sans-serif; color: #202124; background: #fafafa; } +body { margin: 0; min-height: 100vh; display: grid; place-items: center; } +main { width: min(560px, calc(100vw - 64px)); padding: 40px 0; text-align: center; } +h1 { margin: 24px 0 12px; font-size: 22px; font-weight: 600; } +p { color: #666; line-height: 1.6; } +#spinner { width: 32px; height: 32px; margin: auto; border: 3px solid #dedee3; border-top-color: #4d6bfe; border-radius: 50%; animation: spin 0.9s linear infinite; } +#error { padding: 16px; border: 1px solid #e0e0e5; border-radius: 10px; max-height: 220px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; text-align: left; font: 13px/1.6 ui-monospace, monospace; } +#actions { margin-top: 24px; } +button { margin: 4px; padding: 10px 18px; border: 1px solid transparent; border-radius: 8px; color: #fff; background: #4d6bfe; font: inherit; cursor: pointer; } +button.secondary { color: inherit; background: transparent; border-color: #c8c8d0; } +button:disabled { opacity: 0.5; cursor: default; } +button:focus-visible { outline: 2px solid #4d6bfe; outline-offset: 3px; } +[hidden] { display: none !important; } +@keyframes spin { to { transform: rotate(360deg); } } +@media (prefers-color-scheme: dark) { :root { color: #ededf0; background: #171719; } p { color: #aaaab3; } #error { border-color: #38383f; } #spinner { border-color: #38383f; border-top-color: #6a85ff; } } +@media (prefers-reduced-motion: reduce) { #spinner { animation: none; } } diff --git a/apps/desktop/renderer/startup.html b/apps/desktop/renderer/startup.html new file mode 100644 index 0000000000..e0980a5b49 --- /dev/null +++ b/apps/desktop/renderer/startup.html @@ -0,0 +1,23 @@ + + + + + + + + + + +
+ +

+

+ + +
+ + + diff --git a/apps/desktop/renderer/startup.js b/apps/desktop/renderer/startup.js new file mode 100644 index 0000000000..ce8c64361a --- /dev/null +++ b/apps/desktop/renderer/startup.js @@ -0,0 +1,37 @@ +const api = window.dshDesktop + +async function main() { + const { id, messages } = await api.locale() + document.documentElement.lang = id + document.querySelector('#page-title').textContent = messages.startupLoading + document.querySelector('#retry').textContent = messages.retry + document.querySelector('#plugins').textContent = messages.managePlugins + function render(state) { + const failed = state.phase === 'error' + document.querySelector('main').setAttribute('aria-busy', String(!failed)) + document.querySelector('#spinner').hidden = failed + document.querySelector('#title').textContent = failed ? messages.startupFailed : messages.startupLoading + document.querySelector('#description').textContent = failed ? messages.startupErrorDescription : messages.startupLoadingDescription + document.querySelector('#error').hidden = !failed + document.querySelector('#error').textContent = failed ? state.message : '' + document.querySelector('#actions').hidden = !failed + document.querySelector('#retry').disabled = !failed + document.querySelector('#plugins').disabled = !failed + } + let changed = false + const unsubscribe = api.backend.subscribe(state => { changed = true; render(state) }) + window.addEventListener('pagehide', unsubscribe, { once: true }) + const initial = await api.backend.status() + if (!changed) render(initial) + document.querySelector('#retry').addEventListener('click', async () => { + render({ phase: 'starting' }) + try { await api.backend.retry() } + catch (error) { render({ phase: 'error', message: error instanceof Error ? error.message : String(error) }) } + }) + document.querySelector('#plugins').addEventListener('click', async () => { + try { await api.openPlugins() } + catch (error) { render({ phase: 'error', message: error instanceof Error ? error.message : String(error) }) } + }) +} + +void main() diff --git a/apps/desktop/scripts/installer.nsh b/apps/desktop/scripts/installer.nsh new file mode 100644 index 0000000000..3bd8622c72 --- /dev/null +++ b/apps/desktop/scripts/installer.nsh @@ -0,0 +1,17 @@ +!include "LogicLib.nsh" + +!macro customInstall + Push $0 + StrCpy $0 0 + ${If} ${Errors} + StrCpy $0 1 + ${EndIf} + ; Finish can launch the app while NSIS removes its remaining plugin directory. + RMDir /r "$PLUGINSDIR\7z-out" + ${If} $0 == 1 + SetErrors + ${Else} + ClearErrors + ${EndIf} + Pop $0 +!macroend diff --git a/apps/desktop/scripts/package-target.ts b/apps/desktop/scripts/package-target.ts index c5b0bc2667..cdbe8d167a 100644 --- a/apps/desktop/scripts/package-target.ts +++ b/apps/desktop/scripts/package-target.ts @@ -72,6 +72,25 @@ export function withoutWindowsSigningEnvironment(environment: NodeJS.ProcessEnv) .filter(([name]) => !name.startsWith(WINDOWS_SIGNING_ENV_PREFIX))) } +/** + * Select signing and NSIS-compatible archive filters for electron-builder. + * @param environment - Target packaging environment. + * @param unsigned - Whether to create a local unsigned Windows artifact. + * @returns Packaging environment without certificate inputs for unsigned builds. + */ +export function desktopElectronBuilderEnvironment(environment: NodeJS.ProcessEnv, unsigned: boolean): NodeJS.ProcessEnv { + const selected: NodeJS.ProcessEnv = { ...environment, DSH_DESKTOP_UNSIGNED: unsigned ? '1' : '0' } + // The bundled NSIS decoder cannot extract 7-Zip's automatic ARM64-filtered entries. + if (environment.DSH_DESKTOP_TARGET_PLATFORM === 'win32') selected.ELECTRON_BUILDER_7Z_FILTER = 'BCJ' + if (!unsigned) return selected + return { + ...Object.fromEntries(Object.entries(withoutWindowsSigningEnvironment(selected)) + .filter(([name]) => !/^(?:WIN_)?CSC_/iu.test(name))), + CSC_IDENTITY_AUTO_DISCOVERY: 'false', + DSH_DESKTOP_UNSIGNED: '1', + } +} + /** * Remove upload-only COS credentials from every packaging subprocess. * @param environment - Packaging command environment. @@ -152,6 +171,7 @@ interface DesktopPackageInvocation { readonly target: DesktopPackageTarget readonly directory: boolean readonly prepareOnly: boolean + readonly unsigned: boolean } function hostTargetName(platform: NodeJS.Platform, arch: string): DesktopPackageTargetName { @@ -178,14 +198,18 @@ export function parseDesktopPackageInvocation( options: { dir: { type: 'boolean', default: false }, 'prepare-only': { type: 'boolean', default: false }, + unsigned: { type: 'boolean', default: false }, }, }) if (positionals.length > 1) throw new Error('desktop package: expected at most one target') const name = positionals[0] ?? hostTargetName(hostPlatform, hostArch) + if (values.unsigned && name !== 'win-x64') throw new Error('desktop package: --unsigned requires win-x64') + if (values.unsigned && values['prepare-only']) throw new Error('desktop package: --unsigned cannot use --prepare-only') return { target: resolveDesktopPackageTarget(name, hostPlatform, hostArch), directory: values.dir, prepareOnly: values['prepare-only'], + unsigned: values.unsigned, } } @@ -240,7 +264,7 @@ async function main(): Promise { const { target } = invocation const buildPaths = desktopTargetBuildPaths(target.name) const releaseRecordPath = join(buildPaths.artifacts, desktopBuildRecordFilename(target.name)) - if (!invocation.prepareOnly) { + if (!invocation.prepareOnly && !invocation.unsigned) { rmSync(releaseRecordPath, { force: true }) rmSync(`${releaseRecordPath}.tmp`, { force: true }) } @@ -250,9 +274,9 @@ async function main(): Promise { DSH_DESKTOP_TARGET_PLATFORM: target.platform, DSH_DESKTOP_TARGET_ARCH: target.arch, } - const electronBuilderEnv = { ...targetEnv } + const electronBuilderEnv = desktopElectronBuilderEnvironment(targetEnv, invocation.unsigned) for (const name of WINDOWS_SIGNING_ENV_NAMES) { - if (process.env[name] !== undefined) electronBuilderEnv[name] = process.env[name] + if (!invocation.unsigned && process.env[name] !== undefined) electronBuilderEnv[name] = process.env[name] } await runPnpm(['run', 'build:official'], buildEnv, REPOSITORY_ROOT) await runPnpm(['run', 'release:pack', '--family', 'dsh', '--out', buildPaths.packedDsh], buildEnv, REPOSITORY_ROOT) @@ -279,7 +303,7 @@ async function main(): Promise { await runPnpm(['run', 'prepare:dsh'], targetEnv) if (invocation.prepareOnly) return await runPnpm(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv) - if (!invocation.directory) writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts) + if (!invocation.directory && !invocation.unsigned) writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts) } if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) await main() diff --git a/apps/desktop/scripts/prepare-dsh.ts b/apps/desktop/scripts/prepare-dsh.ts index d030a05e1a..eb223fbc7e 100644 --- a/apps/desktop/scripts/prepare-dsh.ts +++ b/apps/desktop/scripts/prepare-dsh.ts @@ -3,7 +3,7 @@ import { spawn } from 'node:child_process' import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { delimiter, dirname, join, resolve } from 'node:path' +import { delimiter, dirname, join, relative, resolve } from 'node:path' import { createRuntimeProjectMetadata } from '../src/project-manager.ts' import { DESKTOP_HOST_PROTOCOL_VERSION } from '../src/host-protocol.ts' import { parseDesktopRelease, type DesktopRelease } from '../src/release.ts' @@ -25,6 +25,7 @@ import { signMacOSRuntime, } from './macos-runtime.ts' import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' +import { desktopRuntimeFileExclusion } from './runtime-file-policy.ts' const APP_ROOT = resolve(import.meta.dirname, '..') const BUILD_PATHS = resolveDesktopTargetBuildPaths() @@ -115,10 +116,13 @@ async function main(): Promise { ) await 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' } + const modules = join(BUILD_ROOT, 'node_modules') mkdirSync(DSH_OUTPUT_ROOT, { recursive: true }) - cpSync(join(BUILD_ROOT, 'node_modules'), join(DSH_OUTPUT_ROOT, 'node_modules'), { + cpSync(modules, join(DSH_OUTPUT_ROOT, 'node_modules'), { recursive: true, dereference: true, - filter: source => !source.split(/[\\/]/u).some(part => part === '.bin' || part === '.pnpm' || part === '.modules.yaml' || part === '.pnpm-workspace-state-v1.json'), + filter: source => desktopRuntimeFileExclusion(relative(modules, source), target) === undefined, }) writeFileSync(join(DSH_OUTPUT_ROOT, 'package.json'), `${JSON.stringify({ name: '@deepseek-ai/dsh-desktop-runtime', private: true, version: release.version, type: 'module', @@ -132,12 +136,10 @@ async function main(): Promise { if (process.platform === 'darwin') { await signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env)) } - const targetName = resolveDesktopBuildTarget() - const target = { platform: process.platform, arch: targetName.endsWith('arm64') ? 'arm64' : 'x64' } writeDesktopRuntime(DSH_OUTPUT_ROOT, release, packageSet.packages.map(entry => entry.name), target) - const descriptor = verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target) + const descriptor = await verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target) await smokeDesktopRuntime(DSH_OUTPUT_ROOT, NODE, descriptor) - verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target) + await verifyDesktopRuntime(DSH_OUTPUT_ROOT, release.version, target) } catch (error) { rmSync(DSH_OUTPUT_ROOT, { recursive: true, force: true }) throw error diff --git a/apps/desktop/scripts/runtime-file-policy.ts b/apps/desktop/scripts/runtime-file-policy.ts new file mode 100644 index 0000000000..9e6722009d --- /dev/null +++ b/apps/desktop/scripts/runtime-file-policy.ts @@ -0,0 +1,40 @@ +/** Desktop-only omissions from already installed production npm packages. */ + +/** + * Identify build and diagnostic files omitted from the immutable Desktop runtime. + * Unrecognized assets and target runtime binaries are retained. Paths name the copied + * node_modules tree, including nested package containers. + * @param path - Path relative to the production node_modules directory. + * @param target - Platform and architecture of the bundled Node executable. + * @returns Omission reason, or undefined when the entry must be copied. + */ +export function desktopRuntimeFileExclusion( + path: string, target: { platform: NodeJS.Platform; arch: string }, +): string | undefined { + const parts = path.split(/[\\/]/u) + if (parts.some(part => ['.bin', '.pnpm', '.modules.yaml', '.pnpm-workspace-state-v1.json'].includes(part))) { + return 'package-manager metadata' + } + const file = parts.at(-1) ?? '' + if (/\.(?:[cm]?[jt]s|css)\.map$/u.test(file)) return 'source map' + if (/\.d\.[cm]?ts$/u.test(file)) return 'TypeScript declaration' + if (/\.tsbuildinfo$/u.test(file)) return 'TypeScript build cache' + const packageParts = parts.slice(parts.lastIndexOf('node_modules') + 1) + const nameParts = packageParts[0]?.startsWith('@') ? 2 : 1 + const name = packageParts.slice(0, nameParts).join('/') + const entry = packageParts.slice(nameParts).join('/') + if (name === 'fs-ext' && /^build\/(?:Release|Debug)\/(?:obj(?:\/|$)|fs_ext\.(?:exp|lib|pdb|iobj|ipdb)$)/u.test(entry)) { + return 'fs-ext compiler output' + } + if (name === 'fs-ext' && /^build\/(?:binding\.sln|config\.gypi|fs_ext\.vcxproj(?:\.filters)?)$/u.test(entry)) { + return 'fs-ext build configuration' + } + if (name === '@mixmark-io/domino' && (entry === 'test' || entry.startsWith('test/'))) return 'Domino test fixtures' + if (name === 'node-pty' && entry.startsWith('prebuilds/')) { + const platform = packageParts[nameParts + 1] + if (platform !== undefined && platform !== `${target.platform}-${target.arch}`) return 'node-pty other platform' + if (file.endsWith('.pdb')) return 'node-pty debug symbols' + } + if (name === '@koromix/koffi-win32-x64' && entry === 'win32_x64/koffi.lib') return 'Koffi import library' + return undefined +} diff --git a/apps/desktop/src/backend-controller.ts b/apps/desktop/src/backend-controller.ts new file mode 100644 index 0000000000..03c49369ab --- /dev/null +++ b/apps/desktop/src/backend-controller.ts @@ -0,0 +1,146 @@ +/** Owns one backend startup and its quiescent teardown independently of windows. */ + +/** Backend availability presented by the desktop window. */ +export type DesktopBackendState = { readonly phase: 'starting' } | { readonly phase: 'ready' } | { readonly phase: 'error'; readonly message: string } + +/** Child lifecycle owned by the desktop backend controller. */ +export interface DesktopBackendHost { + /** @returns Readiness after the child accepts application requests. */ + start(): Promise + /** @returns Completion of child exit. */ + stop(): Promise +} + +interface Attempt { + cancelled: boolean + failure?: Error + host?: Host + cleanup?: Promise +} + +/** Serializes retries and prevents children from outliving a closed window. */ +export class DesktopBackendController { + private current: DesktopBackendState = { phase: 'starting' } + private attempt: Attempt | undefined + private pending: Promise | undefined + private stopping: Promise | undefined + private closed = false + + /** + * @param createHost - Allocate a child and route its fatal failures to the supplied callback. + * @param publish - Receive availability changes until the controller closes. + */ + constructor( + private readonly createHost: (onFailure: (error: Error) => void) => Host, + private readonly publish: (state: DesktopBackendState) => void, + ) {} + + /** Current availability, including the last startup or child failure. */ + get state(): DesktopBackendState { return this.current } + + /** Child available to application requests; absent during startup and teardown. */ + get host(): Host | undefined { return !this.closed && !this.attempt?.cancelled && this.current.phase === 'ready' ? this.attempt?.host : undefined } + + /** + * Prepare the profile and start one child; concurrent callers share the attempt. + * @param prepare - Profile preparation that must finish before spawning. + * @returns Completion of startup, rejecting on preparation, startup, or cleanup failure. + */ + start(prepare: () => Promise): Promise { + if (this.closed) return Promise.reject(new Error('desktop backend is closed')) + if (this.stopping !== undefined) return Promise.reject(new Error('desktop backend is stopping')) + if (this.pending !== undefined) return this.pending + if (this.current.phase === 'ready') return Promise.resolve() + const previous = this.attempt + const attempt: Attempt = { cancelled: false, ...(previous?.cleanup === undefined ? {} : { cleanup: previous.cleanup }) } + this.attempt = attempt + this.update({ phase: 'starting' }) + const pending = Promise.resolve().then(async () => { + try { + await previous?.cleanup + delete attempt.cleanup + if (attempt.cancelled) return + await prepare() + // stop() can cancel this attempt while preparation is pending. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (attempt.cancelled) return + const host = this.createHost((error) => { this.failed(attempt, error) }) + attempt.host = host + await host.start() + if (attempt.failure !== undefined) throw attempt.failure + // stop() can cancel this attempt while the child starts. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (!attempt.cancelled) this.update({ phase: 'ready' }) + } catch (error) { + const cancelled = attempt.cancelled + attempt.cancelled = true + let failure = error + try { await this.cleanup(attempt) } catch (cleanupError) { + if (cleanupError !== error) failure = new AggregateError([error, cleanupError], 'desktop backend startup and cleanup failed') + } + if (!cancelled) this.update({ phase: 'error', message: failure instanceof Error ? failure.message : String(failure) }) + throw failure + } + }).finally(() => { if (this.pending === pending) this.pending = undefined }) + this.pending = pending + return pending + } + + /** + * Stop pending preparation and the child before allowing another start. + * @returns Completion of pending work and child exit; rejects if cleanup fails. + */ + stop(): Promise { + if (this.stopping !== undefined) return this.stopping + const attempt = this.attempt + if (attempt !== undefined) attempt.cancelled = true + if (!this.closed) this.update({ phase: 'starting' }) + const pending = this.pending + const stopping = Promise.allSettled([ + attempt === undefined ? Promise.resolve() : this.cleanup(attempt), + pending, + ]).then((results) => { + const cleanup = results[0] + if (cleanup.status === 'rejected') throw cleanup.reason + if (this.attempt === attempt) this.attempt = undefined + }).finally(() => { if (this.stopping === stopping) this.stopping = undefined }) + this.stopping = stopping + return stopping + } + + /** + * Permanently prevent startup and suppress further availability notifications. + * @returns Completion of pending work and child exit; rejects if cleanup fails. + */ + close(): Promise { + this.closed = true + return this.stop() + } + + private cleanup(attempt: Attempt): Promise { + if (attempt.cleanup === undefined) { + attempt.cleanup = Promise.resolve().then(async () => { await attempt.host?.stop() }) + } + return attempt.cleanup + } + + private failed(attempt: Attempt, error: Error): void { + if (this.attempt !== attempt || attempt.cancelled) return + attempt.failure = error + if (this.current.phase !== 'ready') return + attempt.cancelled = true + const cleanup = this.cleanup(attempt) + this.update({ phase: 'error', message: error.message }) + void cleanup.catch((cleanupError: unknown) => { + if (this.attempt === attempt) this.update({ phase: 'error', message: cleanupError instanceof Error ? cleanupError.message : String(cleanupError) }) + }) + } + + private update(state: DesktopBackendState): void { + if (this.closed) return + this.current = state + try { this.publish(state) } catch (error) { + console.error('desktop backend state listener failed', error) + } + } +} diff --git a/apps/desktop/src/host-process.ts b/apps/desktop/src/host-process.ts index 20c59cf7e1..7442c71172 100644 --- a/apps/desktop/src/host-process.ts +++ b/apps/desktop/src/host-process.ts @@ -83,6 +83,7 @@ export class DesktopHostProcess { }) private exitPromise: Promise | undefined private stderr = '' + private failureReported = false /** * @param node - absolute bundled upstream Node.js executable. @@ -90,6 +91,7 @@ export class DesktopHostProcess { * @param projectDir - active or staged desktop plugin profile. * @param inspectPort - optional loopback inspector port for workspace development. * @param environment - Child environment; runtime and package-manager overrides are removed. + * @param onFailure - Receives the first fatal child or transport failure, including after readiness. */ constructor( private readonly node: string, @@ -97,6 +99,7 @@ export class DesktopHostProcess { private readonly projectDir: string, private readonly inspectPort?: number, private readonly environment: NodeJS.ProcessEnv = process.env, + private readonly onFailure?: (error: Error) => void, ) {} /** Start the child once and resolve only after its complete composition is active. */ @@ -149,7 +152,7 @@ export class DesktopHostProcess { }) child.once('error', (error) => { this.fail(error) }) this.exitPromise = new Promise((resolve) => { - child.once('exit', (code) => { + child.once('close', (code) => { const suffix = this.stderr.trim() === '' ? '' : `: ${this.stderr.trim()}` if (code !== 0 && code !== null) this.fail(new Error(`dsh desktop host exited with ${String(code)}${suffix}`)) else this.fail(new Error(`dsh desktop host stopped${suffix}`)) @@ -278,7 +281,7 @@ export class DesktopHostProcess { private send(message: DesktopHostCommand): void { const child = this.child if (child === undefined || !child.connected) throw new Error('dsh desktop host IPC is unavailable') - child.send(message) + child.send(message, (error) => { if (error !== null) this.fail(error) }) } private acceptResponseBytes(chunk: Buffer): void { @@ -405,6 +408,12 @@ export class DesktopHostProcess { private fail(error: Error): void { this.readyReject(error) + if (!this.failureReported) { + this.failureReported = true + try { this.onFailure?.(error) } catch (listenerError) { + console.error('desktop host failure listener failed', listenerError) + } + } for (const pending of this.pending.values()) { void pending.requestReader?.cancel(error).catch(() => undefined) if (pending.controller === undefined) pending.reject(error) diff --git a/apps/desktop/src/ipc.ts b/apps/desktop/src/ipc.ts index f98bf22902..7ac65344ea 100644 --- a/apps/desktop/src/ipc.ts +++ b/apps/desktop/src/ipc.ts @@ -2,11 +2,13 @@ import type { DesktopPluginRecord } from './project-manager.ts' import type { DesktopLocale } from './locale.ts' +import type { DesktopBackendState } from './backend-controller.ts' /** IPC channel names kept private to the desktop application bundle. */ export const DESKTOP_IPC = { localeGet: 'dsh-desktop:locale-get', pluginsList: 'dsh-desktop:plugins-list', + pluginsOpen: 'dsh-desktop:plugins-open', pluginsAdd: 'dsh-desktop:plugins-add', pluginsRemove: 'dsh-desktop:plugins-remove', pluginsUpdate: 'dsh-desktop:plugins-update', @@ -14,6 +16,7 @@ export const DESKTOP_IPC = { pluginsDisableAll: 'dsh-desktop:plugins-disable-all', backendStatus: 'dsh-desktop:backend-status', backendRetry: 'dsh-desktop:backend-retry', + backendState: 'dsh-desktop:backend-state', updatesCheck: 'dsh-desktop:updates-check', updatesInstall: 'dsh-desktop:updates-install', updatesState: 'dsh-desktop:updates-state', @@ -39,8 +42,9 @@ export interface DshDesktopApi { disableAll(): Promise } readonly backend: { - status(): Promise<{ readonly ready: boolean; readonly error?: string }> + status(): Promise retry(): Promise + subscribe(listener: (state: DesktopBackendState) => void): () => void } readonly updates: { check(): Promise @@ -48,3 +52,8 @@ export interface DshDesktopApi { subscribe(listener: (state: DesktopUpdateState) => void): () => void } } + +/** Startup-page controls, unavailable to backend-provided application documents. */ +export interface DshDesktopStartupApi extends Pick { + openPlugins(): Promise +} diff --git a/apps/desktop/src/locale.ts b/apps/desktop/src/locale.ts index 65e5083313..c937474beb 100644 --- a/apps/desktop/src/locale.ts +++ b/apps/desktop/src/locale.ts @@ -3,6 +3,10 @@ export const en = { application: 'Application', startupFailed: 'DeepSeek Harness could not start', + startupLoading: 'Starting DeepSeek Harness…', + startupLoadingDescription: 'Your workspace will open when it is ready.', + startupErrorDescription: 'The application could not start. Retry or manage Desktop plugins to resolve the problem.', + managePlugins: 'Manage plugins', pluginsMenu: 'Desktop Plugins…', pluginsMenuPackagedOnly: 'Desktop Plugins… (available in packaged applications)', checkUpdatesMenu: 'Check for Updates…', @@ -49,6 +53,10 @@ export type DesktopMessages = { readonly [Key in keyof typeof en]: string } export const zh = { application: '应用', startupFailed: 'DeepSeek Harness 无法启动', + startupLoading: '正在启动 DeepSeek Harness…', + startupLoadingDescription: '准备就绪后将自动打开工作区。', + startupErrorDescription: '应用未能启动。你可以重试,或管理桌面插件以解决问题。', + managePlugins: '管理插件', pluginsMenu: '桌面插件…', pluginsMenuPackagedOnly: '桌面插件…(打包应用中可用)', checkUpdatesMenu: '检查更新…', diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index a995d6818e..f132afb3b2 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -15,6 +15,7 @@ import { import { resolveDesktopPaths } from './paths.ts' import { DesktopProjectManager, type DesktopProjectHooks } from './project-manager.ts' import { DesktopHostProcess } from './host-process.ts' +import { DesktopBackendController, type DesktopBackendState } from './backend-controller.ts' import { DESKTOP_IPC, type DesktopUpdateState } from './ipc.ts' import { formatDesktopMessage, resolveDesktopLocale } from './locale.ts' import { claimDesktopSingleInstance } from './single-instance.ts' @@ -79,13 +80,13 @@ function developmentHostInspectPort(enabled: boolean): number | undefined { return port } -function createWindow(preload: string): BrowserWindow { +function createWindow(preload: string, show = false): BrowserWindow { const window = new BrowserWindow({ width: 1280, height: 840, minWidth: 880, minHeight: 600, - show: false, + show, webPreferences: { preload, nodeIntegration: false, @@ -137,8 +138,9 @@ async function main(): Promise { const activeProject = development ?? paths.profile const hostInspectPort = developmentHostInspectPort(development !== undefined) const manager = new DesktopProjectManager(paths, resources) - let host: DesktopHostProcess | undefined - let startupError: string | undefined + let pageError: string | undefined + let quitting = false + let startup: Promise | undefined let mainWindow: BrowserWindow | undefined let pluginWindow: BrowserWindow | undefined let shellInstallerOwnsQuit = false @@ -147,6 +149,38 @@ async function main(): Promise { const messages = locale.messages const appPreload = fileURLToPath(new URL('./preload-app.cjs', import.meta.url)) const managementPreload = fileURLToPath(new URL('./preload.cjs', import.meta.url)) + const startupUrl = `${SCHEME}://shell/startup.html` + const applicationUrl = `${SCHEME}://app/index.html` + let navigation: { window: BrowserWindow; url: string; promise: Promise } | undefined + + const navigateMain = (url: string): Promise => { + const window = mainWindow + if (quitting || window === undefined || window.isDestroyed()) return Promise.resolve() + if (navigation?.window === window && navigation.url === url) return navigation.promise + const next = { window, url, promise: Promise.resolve() } + next.promise = window.loadURL(url).catch((error: unknown) => { + if (quitting || window.isDestroyed() || navigation !== next) return + navigation = undefined + throw error + }) + navigation = next + return next.promise + } + const backendState = (): DesktopBackendState => pageError === undefined + ? backend.state : { phase: 'error', message: pageError } + const publishBackend = (state: DesktopBackendState): void => { + for (const window of BrowserWindow.getAllWindows()) { + window.webContents.send(DESKTOP_IPC.backendState, state) + } + } + const backend = new DesktopBackendController((onFailure) => { + if (development === undefined) manager.assertProfileRuntime(activeProject) + return new DesktopHostProcess(resources.node, development ?? resources.dsh, activeProject, hostInspectPort, process.env, onFailure) + }, (state) => { + if (state.phase === 'starting') pageError = undefined + publishBackend(backendState()) + if (state.phase === 'error') void navigateMain(startupUrl).catch((error: unknown) => { console.error(error) }) + }) const publishUpdate = (state: DesktopUpdateState): DesktopUpdateState => { updateState = state @@ -156,78 +190,39 @@ async function main(): Promise { return state } - const startHost = async (projectDir = activeProject): Promise => { - if (development === undefined) manager.assertProfileRuntime(projectDir) - const next = new DesktopHostProcess(resources.node, development ?? resources.dsh, projectDir, hostInspectPort) - try { - await next.start() - return next - } catch (error) { - await next.stop() - throw error - } - } const hooks: DesktopProjectHooks = { - healthCheck: async (projectDir) => { - const active = host - host = undefined - await active?.stop() - let healthFailure: unknown - let probe: DesktopHostProcess | undefined - try { - probe = await startHost(projectDir) - await probe.stop() - } catch (error) { - healthFailure = error - await probe?.stop().catch(() => undefined) - } - let restartFailure: unknown - if (active !== undefined) { - try { - host = await startHost() - } catch (error) { - restartFailure = error - } - } - if (healthFailure !== undefined && restartFailure !== undefined) { - throw new AggregateError([ - errorOf(healthFailure, 'desktop project: staged health check failed'), - errorOf(restartFailure, 'desktop project: active backend restart failed'), - ], 'desktop project: staged health check and active backend restart failed') - } - if (healthFailure !== undefined) throw errorOf(healthFailure, 'desktop project: staged health check failed') - if (restartFailure !== undefined) throw errorOf(restartFailure, 'desktop project: active backend restart failed') - }, - beforeActivate: async () => { - const active = host - host = undefined - await active?.stop() - }, - afterActivate: async () => { - host = await startHost() - }, + beforeActivate: () => backend.stop(), + afterActivate: () => backend.start(async () => {}), } - const reconcileBackend = async (): Promise => { - try { - if (development === undefined) { - await manager.applyRelease(app.getVersion(), { ...hooks, beforeActivate: async () => {}, afterActivate: async () => {} }) - } - host = await startHost() - startupError = undefined - } catch (error) { - startupError = errorOf(error, messages.startupFailed).message + const showStartupError = async (error: unknown): Promise => { + if (quitting) return + pageError = errorOf(error, messages.startupFailed).message + await navigateMain(startupUrl) + publishBackend(backendState()) + } + const reconcileBackend = (): Promise => { + startup ??= (async () => { + pageError = undefined + await navigateMain(startupUrl) + await backend.start(async () => { + if (development === undefined) { + await manager.applyRelease(app.getVersion(), { beforeActivate: async () => {}, afterActivate: async () => {} }) + } + }) + if (backend.host !== undefined) await navigateMain(applicationUrl) + })().catch(async (error: unknown) => { + await showStartupError(error) throw error - } + }).finally(() => { startup = undefined }) + return startup } const updates = new DesktopUpdateCoordinator( publishUpdate, async () => { shellInstallerOwnsQuit = true - const active = host - host = undefined - await active?.stop() + await backend.stop() }, ) @@ -235,7 +230,7 @@ async function main(): Promise { const url = new URL(request.url) if (url.hostname === 'shell') return serveShellAsset(request) if (url.hostname !== 'app') return Promise.resolve(new Response(null, { status: 404 })) - const active = host + const active = backend.host if (active === undefined) return Promise.resolve(new Response('backend unavailable', { status: 503 })) return active.fetch(request) }) @@ -245,10 +240,16 @@ async function main(): Promise { if (development !== undefined) { throw new Error('dsh desktop: plugin package changes require a packaged application') } - await manager.mutate(mutation, hooks) - startupError = undefined - if (mainWindow !== undefined && !mainWindow.isDestroyed()) mainWindow.webContents.reload() - else focusPrimaryWindow() + await startup?.catch(() => undefined) + pageError = undefined + await navigateMain(startupUrl) + try { + await manager.mutate(mutation, hooks) + await navigateMain(applicationUrl) + } catch (error) { + await showStartupError(error) + throw error + } } ipcMain.handle(DESKTOP_IPC.localeGet, (event) => { assertDesktopSender(event, ['shell']) @@ -280,11 +281,11 @@ async function main(): Promise { ipcMain.handle(DESKTOP_IPC.pluginsDisableAll, event => mutate(event, { type: 'plugins-disable-all' })) ipcMain.handle(DESKTOP_IPC.backendStatus, (event) => { assertDesktopSender(event, ['shell']) - return { ready: host !== undefined, ...(startupError === undefined ? {} : { error: startupError }) } + return backendState() }) ipcMain.handle(DESKTOP_IPC.backendRetry, async (event) => { assertDesktopSender(event, ['shell']) - if (host === undefined) await reconcileBackend() + await reconcileBackend() focusPrimaryWindow() }) ipcMain.handle(DESKTOP_IPC.updatesCheck, async (event) => { @@ -350,6 +351,10 @@ async function main(): Promise { pluginWindow.once('closed', () => { pluginWindow = undefined }) void pluginWindow.loadURL(`${SCHEME}://shell/plugin-manager.html`) } + ipcMain.handle(DESKTOP_IPC.pluginsOpen, (event) => { + assertDesktopSender(event, ['shell']) + openPluginWindow() + }) Menu.setApplicationMenu(Menu.buildFromTemplate([{ label: process.platform === 'darwin' ? app.name : messages.application, @@ -367,18 +372,17 @@ async function main(): Promise { }])) const createMainWindow = (): BrowserWindow => { - const window = createWindow(appPreload) + const window = createWindow(appPreload, true) mainWindow = window - window.once('ready-to-show', () => { if (!window.isDestroyed()) window.show() }) window.on('closed', () => { if (mainWindow === window) mainWindow = undefined }) return window } focusPrimaryWindow = () => { - if (host === undefined) { openPluginWindow(); return } const window = mainWindow if (window === undefined || window.isDestroyed()) { - const replacement = createMainWindow() - void replacement.loadURL(`${SCHEME}://app/index.html`) + createMainWindow() + void navigateMain(backendState().phase === 'ready' ? applicationUrl : startupUrl) + .catch((error: unknown) => { console.error(error) }) return } if (window.isMinimized()) window.restore() @@ -386,18 +390,6 @@ async function main(): Promise { window.focus() } - await reconcileBackend().catch(() => undefined) - if (host === undefined) openPluginWindow() - else { - mainWindow = createMainWindow() - await mainWindow.loadURL(`${SCHEME}://app/index.html`) - } - if (mainWindow !== undefined && development !== undefined && process.env.DSH_DESKTOP_OPEN_DEVTOOLS !== '0') { - mainWindow.webContents.openDevTools({ mode: 'detach' }) - } - publishUpdate(updateState) - setTimeout(() => { void checkAndPrompt(false) }, 10_000) - app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) focusPrimaryWindow() }) @@ -405,13 +397,23 @@ async function main(): Promise { if (process.platform !== 'darwin') app.quit() }) app.on('before-quit', (event) => { - if (shellInstallerOwnsQuit) return - if (host === undefined) return + if (shellInstallerOwnsQuit || quitting) return event.preventDefault() - const active = host - host = undefined - void active.stop().finally(() => { app.quit() }) + quitting = true + void backend.close().catch((error: unknown) => { console.error(error) }).finally(() => { app.quit() }) }) + + mainWindow = createMainWindow() + await reconcileBackend().catch(() => undefined) + // Window lifecycle callbacks run while backend startup is pending. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (quitting) return + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (mainWindow !== undefined && development !== undefined && process.env.DSH_DESKTOP_OPEN_DEVTOOLS !== '0') { + mainWindow.webContents.openDevTools({ mode: 'detach' }) + } + publishUpdate(updateState) + setTimeout(() => { void checkAndPrompt(false) }, 10_000) } const ownsDesktopInstance = claimDesktopSingleInstance(app, () => { focusPrimaryWindow() }) diff --git a/apps/desktop/src/owned-directory.ts b/apps/desktop/src/owned-directory.ts new file mode 100644 index 0000000000..0caad07ca8 --- /dev/null +++ b/apps/desktop/src/owned-directory.ts @@ -0,0 +1,26 @@ +/** Desktop transaction cleanup that unlinks directory links without visiting their targets. */ + +import { lstatSync, readdirSync, rmdirSync, unlinkSync } from 'node:fs' +import { join } from 'node:path' + +/** + * Remove an owned directory and its contents, unlinking root and nested links. + * Missing roots are ignored; existing roots must be directories or links. + * @param path - Owned directory or link to remove; link targets are preserved. + */ +export function removeOwnedDirectory(path: string): void { + const stat = lstatSync(path, { throwIfNoEntry: false }) + if (stat === undefined) return + if (stat.isSymbolicLink()) { + unlinkSync(path) + return + } + if (!stat.isDirectory()) throw new Error(`desktop project: owned directory path is not a directory: ${path}`) + // Electron's recursive rm follows nested Windows junctions into installed resources. + for (const entry of readdirSync(path, { withFileTypes: true })) { + const child = join(path, entry.name) + if (entry.isDirectory()) removeOwnedDirectory(child) + else unlinkSync(child) + } + rmdirSync(path) +} diff --git a/apps/desktop/src/preload-app.ts b/apps/desktop/src/preload-app.ts index c6a839aba6..140a7369a4 100644 --- a/apps/desktop/src/preload-app.ts +++ b/apps/desktop/src/preload-app.ts @@ -1,5 +1,23 @@ -/** Minimal marker that selects the desktop custom-protocol API carrier. */ +/** Startup controls for shell documents; application documents receive only the carrier marker. */ -import { contextBridge } from 'electron' +import { contextBridge, ipcRenderer } from 'electron' +import { DESKTOP_IPC, type DshDesktopStartupApi } from './ipc.ts' +import type { DesktopBackendState } from './backend-controller.ts' -contextBridge.exposeInMainWorld('dshDesktop', { protocolVersion: 1 }) +const startup: DshDesktopStartupApi = { + protocolVersion: 1, + locale: () => ipcRenderer.invoke(DESKTOP_IPC.localeGet) as ReturnType, + backend: { + status: () => ipcRenderer.invoke(DESKTOP_IPC.backendStatus) as ReturnType, + retry: () => ipcRenderer.invoke(DESKTOP_IPC.backendRetry) as Promise, + subscribe(listener) { + const handle = (_event: Electron.IpcRendererEvent, state: DesktopBackendState): void => { listener(state) } + ipcRenderer.on(DESKTOP_IPC.backendState, handle) + return () => { ipcRenderer.off(DESKTOP_IPC.backendState, handle) } + }, + }, + openPlugins: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsOpen) as Promise, +} + +contextBridge.exposeInMainWorld('dshDesktop', location.protocol === 'dsh-app:' && location.hostname === 'shell' + ? startup : { protocolVersion: 1 }) diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 4ad4243bdb..b9c04bd40a 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer } from 'electron' import { DESKTOP_IPC, type DshDesktopApi, type DesktopUpdateState } from './ipc.ts' +import type { DesktopBackendState } from './backend-controller.ts' const api: DshDesktopApi = { protocolVersion: 1, @@ -17,6 +18,11 @@ const api: DshDesktopApi = { backend: { status: () => ipcRenderer.invoke(DESKTOP_IPC.backendStatus) as ReturnType, retry: () => ipcRenderer.invoke(DESKTOP_IPC.backendRetry) as Promise, + subscribe(listener) { + const handle = (_event: Electron.IpcRendererEvent, state: DesktopBackendState): void => { listener(state) } + ipcRenderer.on(DESKTOP_IPC.backendState, handle) + return () => { ipcRenderer.off(DESKTOP_IPC.backendState, handle) } + }, }, updates: { check: () => ipcRenderer.invoke(DESKTOP_IPC.updatesCheck) as Promise, diff --git a/apps/desktop/src/profile-packages.ts b/apps/desktop/src/profile-packages.ts index 6326747b43..0ec5ca573e 100644 --- a/apps/desktop/src/profile-packages.ts +++ b/apps/desktop/src/profile-packages.ts @@ -175,7 +175,7 @@ function packageFrom(anchor: string, name: string): string | undefined { if (!PACKAGE_NAME.test(name)) throw new Error(`desktop profile: invalid package name ${name}`) for (const modules of createRequire(join(anchor, 'package.json')).resolve.paths(name) ?? []) { const path = join(modules, name) - if (existsSync(join(path, 'package.json'))) return realpathSync(path) + if (existsSync(join(path, 'package.json'))) return realpathSync.native(path) } return undefined } @@ -190,8 +190,8 @@ function packageFrom(anchor: string, name: string): string | undefined { export function validateDesktopPluginGraph( profile: string, root: string, runtime: DesktopRuntimeDescriptor, activePlugins: readonly string[], ): void { - const profileRoot = realpathSync(profile) - const shared = new Map(runtime.sharedPackages.map(entry => [entry.name, realpathSync(runtimePath(root, entry.path))])) + const profileRoot = realpathSync.native(profile) + const shared = new Map(runtime.sharedPackages.map(entry => [entry.name, realpathSync.native(runtimePath(root, entry.path))])) for (const [name, path] of shared) { if (packageFrom(profile, name) !== path) throw new Error(`desktop profile: missing or incorrect host link ${name}`) } @@ -199,7 +199,7 @@ export function validateDesktopPluginGraph( const scan = (modules: string): void => { if (!existsSync(modules)) return if (lstatSync(modules).isSymbolicLink()) throw new Error(`desktop profile: linked package container ${modules}`) - const directory = realpathSync(modules) + const directory = realpathSync.native(modules) if (scanned.has(directory)) return scanned.add(directory) for (const entry of readdirSync(modules, { withFileTypes: true })) { @@ -207,7 +207,7 @@ export function validateDesktopPluginGraph( const path = join(modules, entry.name) if (entry.name.startsWith('@')) { scan(path); continue } if (!existsSync(join(path, 'package.json'))) throw new Error(`desktop profile: invalid installed package ${path}`) - const canonical = realpathSync(path) + const canonical = realpathSync.native(path) const info = manifest(canonical) const host = shared.get(info.name) if (host !== undefined) { diff --git a/apps/desktop/src/project-manager.ts b/apps/desktop/src/project-manager.ts index 89c9e86c73..f6759775e1 100644 --- a/apps/desktop/src/project-manager.ts +++ b/apps/desktop/src/project-manager.ts @@ -12,8 +12,8 @@ import { openSync, closeSync, readFileSync, + realpathSync, renameSync, - rmSync, unlinkSync, writeFileSync, writeSync, @@ -25,8 +25,9 @@ import { verifyDesktopCorePackageSet, } from './core-package-set.ts' import type { DesktopPaths } from './paths.ts' +import { removeOwnedDirectory } from './owned-directory.ts' import type { DesktopRelease } from './release.ts' -import { desktopRuntimeId, verifyDesktopRuntime, type DesktopRuntimeDescriptor } from './runtime-tree.ts' +import { desktopRuntimeId, readDesktopRuntime, type DesktopRuntimeDescriptor } from './runtime-tree.ts' import { copyDesktopProfile, desktopPluginLockHash, linkDesktopHostPackages, readDesktopProfileState, unlinkDesktopHostPackages, validateDesktopPluginGraph, type DesktopProfileState, @@ -69,10 +70,8 @@ export interface DesktopRuntimeExecutables { readonly dsh: string } -/** Hooks that bind project replacement to backend lifecycle and health. */ +/** Hooks that bind project replacement to the active backend lifecycle. */ export interface DesktopProjectHooks { - /** Prove the staged dependency graph while the active backend is stopped. */ - healthCheck(projectDir: string): Promise /** Stop the active backend and await process exit before directory moves. */ beforeActivate(): Promise /** Start the selected active project after commit or rollback. */ @@ -163,17 +162,6 @@ export function packageNameFromSpec(spec: string): string | undefined { return name } -function removeOwnedDirectory(path: string): void { - if (!existsSync(path)) return - const stat = lstatSync(path) - if (stat.isSymbolicLink()) { - unlinkSync(path) - return - } - if (!stat.isDirectory()) throw new Error(`desktop project: owned directory path is not a directory: ${path}`) - rmSync(path, { recursive: true }) -} - function projectManifest(projectDir: string): DesktopProjectManifest { const path = join(projectDir, 'package.json') const value = readJson(path) @@ -324,7 +312,7 @@ export class DesktopProjectManager { } private currentRuntime(): DesktopRuntimeDescriptor { - if (this.descriptor === undefined) throw new Error('desktop project: runtime has not been verified') + if (this.descriptor === undefined) throw new Error('desktop project: runtime metadata has not been loaded') return this.descriptor } @@ -334,11 +322,11 @@ export class DesktopProjectManager { validateDesktopPluginGraph(projectDir, this.runtime.dsh, runtime, profilePluginNames(projectDir)) } - /** Verify this release and reconcile its external profile without installing core packages. */ + /** Read release metadata and reconcile its external profile without installing core packages. */ async applyRelease(electronVersion: string, hooks: DesktopProjectHooks): Promise { return this.withLock(async () => { this.recover() - const target = verifyDesktopRuntime(this.runtime.dsh, electronVersion) + const target = readDesktopRuntime(this.runtime.dsh, electronVersion) this.descriptor = target const previous = readDesktopProfileState(this.paths.profile) if (existsSync(this.paths.profile) && previous === undefined) { @@ -347,8 +335,9 @@ export class DesktopProjectManager { if (previous?.runtimeId === desktopRuntimeId(target) && previous.lockHash === desktopPluginLockHash(this.paths.profile) && previous.links.length === target.sharedPackages.length - && previous.links.every(link => link.target === join(this.runtime.dsh, 'node_modules', link.name) - && existsSync(join(this.paths.profile, 'node_modules', link.name)))) { + && previous.links.every(link => existsSync(link.target) + && existsSync(join(this.paths.profile, 'node_modules', link.name)) + && realpathSync.native(link.target) === realpathSync.native(join(this.runtime.dsh, 'node_modules', link.name)))) { validateDesktopPluginGraph(this.paths.profile, this.runtime.dsh, target, profilePluginNames(this.paths.profile)) return false } @@ -357,7 +346,6 @@ export class DesktopProjectManager { if (previous === undefined) createPluginProfile(stagingProfile) else copyDesktopProfile(this.paths.profile, stagingProfile) await this.reconcileProfile(stagingProfile, previous) - await hooks.healthCheck(stagingProfile) await this.activate(stagingProfile, hooks) return true } catch (error) { @@ -379,7 +367,6 @@ export class DesktopProjectManager { await this.applyMutation(stagingProfile, mutation) await this.reconcileProfile(stagingProfile, readDesktopProfileState(stagingProfile), mutation.type !== 'plugin-toggle' && mutation.type !== 'plugins-disable-all') - await hooks.healthCheck(stagingProfile) await this.activate(stagingProfile, hooks) } catch (error) { removeOwnedDirectory(stagingProfile) diff --git a/apps/desktop/src/runtime-tree.ts b/apps/desktop/src/runtime-tree.ts index 471d603964..8f02a46497 100644 --- a/apps/desktop/src/runtime-tree.ts +++ b/apps/desktop/src/runtime-tree.ts @@ -1,8 +1,9 @@ /** Relocatable, integrity-recorded production packages carried by one Desktop release. */ import { createHash } from 'node:crypto' -import { lstatSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' +import { existsSync, lstatSync, readdirSync, readFile, readFileSync, writeFileSync } from 'node:fs' import { isAbsolute, join, relative, sep } from 'node:path' +import { promisify } from 'node:util' import { valid } from 'semver' import { DESKTOP_HOST_PACKAGE, DESKTOP_HOST_RUNTIME_FILES } from './core-package-set.ts' import { parseDesktopRelease, type DesktopRelease } from './release.ts' @@ -36,6 +37,7 @@ export interface DesktopRuntimeDescriptor { } const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/u +const readRuntimeFile = promisify(readFile) function record(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) @@ -55,27 +57,59 @@ export function runtimePath(root: string, path: string): string { return join(root, ...path.split('/')) } -/** - * Inventory a materialized runtime without following links or including its descriptor. - * @param root - Self-contained runtime directory. - * @returns Sorted final-file inventory. - */ -export function inventoryDesktopRuntime(root: string): DesktopRuntimeFile[] { - const files: DesktopRuntimeFile[] = [] +function runtimeFiles(root: string): { path: string; name: string }[] { + const files: { path: string; name: string }[] = [] const visit = (directory: string): void => { for (const entry of readdirSync(directory, { withFileTypes: true })) { const path = join(directory, entry.name) const name = relative(root, path).split(sep).join('/') if (name === DESKTOP_RUNTIME_FILE) continue if (entry.isDirectory()) visit(path) - else if (entry.isFile()) { - const body = readFileSync(path) - files.push({ path: name, bytes: body.byteLength, sha256: createHash('sha256').update(body).digest('hex'), - executable: (lstatSync(path).mode & 0o111) !== 0 }) - } else throw new Error(`desktop runtime: unsupported filesystem entry ${name}`) + else if (entry.isFile()) files.push({ path, name }) + else throw new Error(`desktop runtime: unsupported filesystem entry ${name}`) } } visit(root) + return files +} + +function runtimeFile(path: string, name: string, body: Buffer): DesktopRuntimeFile { + return { path: name, bytes: body.byteLength, sha256: createHash('sha256').update(body).digest('hex'), + // Windows has no portable Unix executable permission bits. + executable: process.platform !== 'win32' && (lstatSync(path).mode & 0o111) !== 0 } +} + +/** + * Inventory a materialized runtime without following links or including its descriptor. + * @param root - Self-contained runtime directory. + * @returns Sorted final-file inventory; executable permissions are false on Windows. + */ +export function inventoryDesktopRuntime(root: string): DesktopRuntimeFile[] { + return runtimeFiles(root).map(({ path, name }) => runtimeFile(path, name, readFileSync(path))) + .sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0) +} + +async function inventoryRuntimeForVerification(root: string): Promise { + const entries = runtimeFiles(root) + const files: DesktopRuntimeFile[] = [] + const remaining = entries.values() + let failed = false + const workers = Array.from({ length: Math.min(8, entries.length) }, async () => { + while (!failed) { + const next = remaining.next() + if (next.done) return + const { path, name } = next.value + try { + files.push(runtimeFile(path, name, await readRuntimeFile(path))) + } catch (error) { + failed = true + throw error + } + } + }) + // Failure returns only after every outstanding file read has closed its descriptor. + const results = await Promise.allSettled(workers) + for (const result of results) if (result.status === 'rejected') throw result.reason return files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0) } @@ -109,13 +143,13 @@ export function writeDesktopRuntime( } /** - * Verify the runtime before linking any of its packages into writable state. + * Read release metadata and check shared manifests and Host entries without scanning runtime contents. * @param root - Current application's runtime resources. * @param electronVersion - Expected shell version. * @param target - Required execution target; defaults to the current process. * @returns Validated runtime descriptor. */ -export function verifyDesktopRuntime( +export function readDesktopRuntime( root: string, electronVersion: string, target: { platform: NodeJS.Platform; arch: string } = process, ): DesktopRuntimeDescriptor { const value: unknown = JSON.parse(readFileSync(join(root, DESKTOP_RUNTIME_FILE), 'utf8')) @@ -144,13 +178,6 @@ export function verifyDesktopRuntime( runtimePath(root, entry.path) return { path: entry.path, bytes: entry.bytes, sha256: entry.sha256, executable: entry.executable } }).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0) - const actual = inventoryDesktopRuntime(root) - // Windows has no portable Unix executable permission bits. - const comparable = (items: readonly DesktopRuntimeFile[]): unknown => process.platform === 'win32' - ? items.map(({ executable: _executable, ...item }) => item) : items - if (JSON.stringify(comparable(files)) !== JSON.stringify(comparable(actual))) { - throw new Error('desktop runtime: integrity verification failed') - } for (const entry of sharedPackages) { const manifest: unknown = JSON.parse(readFileSync(join(runtimePath(root, entry.path), 'package.json'), 'utf8')) if (!record(manifest) || manifest.name !== entry.name || manifest.version !== entry.version) { @@ -163,13 +190,36 @@ export function verifyDesktopRuntime( } } for (const file of DESKTOP_HOST_RUNTIME_FILES) { - if (!files.some(entry => entry.path === `node_modules/${DESKTOP_HOST_PACKAGE}/${file}`)) { + const path = `node_modules/${DESKTOP_HOST_PACKAGE}/${file}` + if (!files.some(entry => entry.path === path) || !existsSync(runtimePath(root, path)) + || !lstatSync(runtimePath(root, path)).isFile()) { throw new Error(`desktop runtime: missing Host file ${file}`) } } return { schemaVersion: 1, release, platform: target.platform, arch: target.arch, sharedPackages, files } } +/** + * Verify every packaged runtime file against its recorded bytes and permissions at build time. + * @param root - Materialized runtime resources. + * @param electronVersion - Expected shell version. + * @param target - Required execution target; defaults to the current process. + * @returns Validated runtime descriptor. + */ +export async function verifyDesktopRuntime( + root: string, electronVersion: string, target: { platform: NodeJS.Platform; arch: string } = process, +): Promise { + const descriptor = readDesktopRuntime(root, electronVersion, target) + const actual = await inventoryRuntimeForVerification(root) + // Windows has no portable Unix executable permission bits. + const comparable = (items: readonly DesktopRuntimeFile[]): unknown => process.platform === 'win32' + ? items.map(({ executable: _executable, ...item }) => item) : items + if (JSON.stringify(comparable(descriptor.files)) !== JSON.stringify(comparable(actual))) { + throw new Error('desktop runtime: integrity verification failed') + } + return descriptor +} + /** * Identify exact runtime content independently of its installation path. * @param descriptor - Validated runtime metadata. diff --git a/apps/desktop/tests/backend-controller.spec.ts b/apps/desktop/tests/backend-controller.spec.ts new file mode 100644 index 0000000000..abdc78a9e7 --- /dev/null +++ b/apps/desktop/tests/backend-controller.spec.ts @@ -0,0 +1,170 @@ +import { describe, expect, it, vi } from 'vitest' +import { DesktopBackendController, type DesktopBackendState } from '../src/backend-controller.ts' + +function deferred() { + let resolve!: () => void + let reject!: (error: Error) => void + const promise = new Promise((accept, decline) => { resolve = accept; reject = decline }) + return { promise, resolve, reject } +} + +function fixture() { + const started = deferred() + const ready = deferred() + const stopping = deferred() + const exited = deferred() + const states: DesktopBackendState[] = [] + let fail!: (error: Error) => void + const host = { + start: vi.fn(() => { started.resolve(); return ready.promise }), + stop: vi.fn(() => { stopping.resolve(); return exited.promise }), + } + const create = vi.fn((onFailure: (error: Error) => void) => { fail = onFailure; return host }) + const controller = new DesktopBackendController(create, state => states.push(state)) + return { controller, host, create, states, started, ready, stopping, exited, fail: (error: Error) => { fail(error) } } +} + +describe('desktop backend controller', () => { + it('shares preparation and startup between concurrent retries', async () => { + const f = fixture() + const prepare = vi.fn(async () => {}) + const first = f.controller.start(prepare) + expect(f.controller.start(prepare)).toBe(first) + await f.started.promise + expect(f.controller.host).toBeUndefined() + expect(f.states).toEqual([{ phase: 'starting' }]) + f.ready.resolve() + await first + expect(f.controller.host).toBe(f.host) + await f.controller.start(prepare) + expect(prepare).toHaveBeenCalledTimes(1) + expect(f.host.start).toHaveBeenCalledTimes(1) + f.exited.resolve() + await f.controller.close() + }) + + it('waits for pending preparation on close and never spawns afterward', async () => { + const f = fixture() + const preparing = deferred() + const prepared = deferred() + const start = f.controller.start(() => { preparing.resolve(); return prepared.promise }) + await preparing.promise + let closed = false + const close = f.controller.close().then(() => { closed = true }) + await Promise.resolve() + expect(closed).toBe(false) + prepared.resolve() + await Promise.all([start, close]) + expect(f.create).not.toHaveBeenCalled() + expect(f.states).toEqual([{ phase: 'starting' }]) + await expect(f.controller.start(async () => {})).rejects.toThrow('closed') + }) + + it('stops a pending child once and waits for startup and child exit on close', async () => { + const f = fixture() + const start = f.controller.start(async () => {}) + const rejected = expect(start).rejects.toThrow('stopped') + await f.started.promise + const close = f.controller.close() + expect(f.controller.close()).toBe(close) + await f.stopping.promise + let closed = false + void close.then(() => { closed = true }) + f.ready.reject(new Error('stopped')) + await Promise.resolve() + expect(closed).toBe(false) + f.exited.resolve() + await Promise.all([rejected, close]) + expect(f.host.stop).toHaveBeenCalledTimes(1) + expect(f.states).toEqual([{ phase: 'starting' }]) + expect(f.controller.host).toBeUndefined() + }) + + it('publishes preparation errors and permits retry', async () => { + const f = fixture() + await expect(f.controller.start(async () => { throw new Error('invalid profile') })).rejects.toThrow('invalid profile') + expect(f.controller.state).toEqual({ phase: 'error', message: 'invalid profile' }) + expect(f.create).not.toHaveBeenCalled() + f.ready.resolve() + await f.controller.start(async () => {}) + expect(f.controller.state).toEqual({ phase: 'ready' }) + f.exited.resolve() + await f.controller.close() + }) + + it('cleans up a failed startup before rejecting and displays the actual failure', async () => { + const f = fixture() + const start = f.controller.start(async () => {}) + const rejected = expect(start).rejects.toThrow('plugin failed') + await f.started.promise + f.ready.reject(new Error('plugin failed')) + await f.stopping.promise + f.exited.resolve() + await rejected + expect(f.controller.state).toEqual({ phase: 'error', message: 'plugin failed' }) + expect(f.host.stop).toHaveBeenCalledTimes(1) + await f.controller.close() + }) + + it('waits for failed ready child cleanup before preparing a retry', async () => { + const f = fixture() + f.ready.resolve() + await f.controller.start(async () => {}) + f.fail(new Error('transport failed')) + expect(f.controller.state).toEqual({ phase: 'error', message: 'transport failed' }) + expect(f.controller.host).toBeUndefined() + await f.stopping.promise + const prepare = vi.fn(async () => {}) + const retry = f.controller.start(prepare) + await Promise.resolve() + expect(prepare).not.toHaveBeenCalled() + f.exited.resolve() + await retry + expect(prepare).toHaveBeenCalledTimes(1) + expect(f.create).toHaveBeenCalledTimes(2) + await f.controller.close() + }) + + it('does not publish ready when the child fails as readiness settles', async () => { + const f = fixture() + const start = f.controller.start(async () => {}) + const rejected = expect(start).rejects.toThrow('immediate failure') + await f.started.promise + f.ready.resolve() + f.fail(new Error('immediate failure')) + await f.stopping.promise + f.exited.resolve() + await rejected + expect(f.states).toEqual([{ phase: 'starting' }, { phase: 'error', message: 'immediate failure' }]) + await f.controller.close() + }) + + it('ignores failure callbacks caused by intentional stop and permits subsequent start', async () => { + const f = fixture() + f.ready.resolve() + await f.controller.start(async () => {}) + const stop = f.controller.stop() + await f.stopping.promise + f.fail(new Error('stopped')) + await expect(f.controller.start(async () => {})).rejects.toThrow('stopping') + expect(f.controller.state).toEqual({ phase: 'starting' }) + f.exited.resolve() + await stop + await f.controller.start(async () => {}) + expect(f.create).toHaveBeenCalledTimes(2) + await f.controller.close() + }) + + it('propagates cleanup failure and prevents retry from overlapping the remaining child', async () => { + const f = fixture() + f.ready.resolve() + await f.controller.start(async () => {}) + f.fail(new Error('fatal')) + await f.stopping.promise + f.exited.reject(new Error('child did not exit')) + await expect(f.controller.start(async () => {})).rejects.toThrow('child did not exit') + await expect(f.controller.start(async () => {})).rejects.toThrow('child did not exit') + expect(f.create).toHaveBeenCalledTimes(1) + await expect(f.controller.close()).rejects.toThrow('child did not exit') + }) +}) diff --git a/apps/desktop/tests/fixtures/installer-cleanup-smoke.nsi b/apps/desktop/tests/fixtures/installer-cleanup-smoke.nsi new file mode 100644 index 0000000000..2c1c47ae34 --- /dev/null +++ b/apps/desktop/tests/fixtures/installer-cleanup-smoke.nsi @@ -0,0 +1,70 @@ +; Compile with OUTPUT_FILE and RESULT_FILE in a private test directory, then run silently. +Unicode true +RequestExecutionLevel user +SilentInstall silent +Name "Desktop installer cleanup smoke" +OutFile "${OUTPUT_FILE}" +!include "..\..\scripts\installer.nsh" + +Section + InitPluginsDir + SetOutPath "$PLUGINSDIR" + CreateDirectory "$PLUGINSDIR\7z-out\nested" + FileOpen $1 "$PLUGINSDIR\7z-out\nested\extracted-file" w + FileWrite $1 "remove" + FileClose $1 + FileOpen $1 "$PLUGINSDIR\archive.7z" w + FileWrite $1 "archive sentinel" + FileClose $1 + FileOpen $1 "$PLUGINSDIR\plugin.dll" w + FileWrite $1 "plugin sentinel" + FileClose $1 + CreateDirectory "$PLUGINSDIR\old-install" + FileOpen $1 "$PLUGINSDIR\old-install\sentinel" w + FileWrite $1 "rollback sentinel" + FileClose $1 + + StrCpy $0 "register sentinel" + ClearErrors + !insertmacro customInstall + IfErrors failed + StrCmp $0 "register sentinel" 0 failed + StrCmp $OUTDIR $PLUGINSDIR 0 failed + IfFileExists "$PLUGINSDIR\7z-out\*.*" failed + + FileOpen $1 "$PLUGINSDIR\archive.7z" r + FileRead $1 $2 + FileClose $1 + StrCmp $2 "archive sentinel" 0 failed + FileOpen $1 "$PLUGINSDIR\plugin.dll" r + FileRead $1 $2 + FileClose $1 + StrCmp $2 "plugin sentinel" 0 failed + FileOpen $1 "$PLUGINSDIR\old-install\sentinel" r + FileRead $1 $2 + FileClose $1 + StrCmp $2 "rollback sentinel" 0 failed + + CreateDirectory "$PLUGINSDIR\7z-out" + SetErrors + !insertmacro customInstall + IfErrors +2 + Goto failed + IfFileExists "$PLUGINSDIR\7z-out\*.*" failed + + ClearErrors + !insertmacro customInstall + IfErrors failed + FileOpen $1 "${RESULT_FILE}" w + FileWrite $1 "scratch removed; archive, plugin, rollback, registers and error flags preserved" + FileClose $1 + SetErrorLevel 0 + Quit + + failed: + FileOpen $1 "${RESULT_FILE}" w + FileWrite $1 "cleanup smoke failed" + FileClose $1 + SetErrorLevel 1 + Quit +SectionEnd diff --git a/apps/desktop/tests/fixtures/installer-write-failure-smoke.nsi b/apps/desktop/tests/fixtures/installer-write-failure-smoke.nsi new file mode 100644 index 0000000000..d7976e51ad --- /dev/null +++ b/apps/desktop/tests/fixtures/installer-write-failure-smoke.nsi @@ -0,0 +1,55 @@ +; Compile with OUTPUT_FILE, RESULT_FILE, PAYLOAD_FILE, TARGET_DIR and PLUGIN_DIR. +; All paths must belong to a private test directory, except the NSIS plugin directory. +; PAYLOAD_FILE contains locked.txt="new runtime" and asset.txt="new asset". +; Before running /S, create TARGET_DIR\locked.txt="old runtime" and hold it open +; for reading with FileShare.Read until the native process exits. asset.txt is absent. +; Define DIRECT for direct extraction; otherwise extract to temporary files and copy. +; Both modes retain "old runtime" and write "new asset" under that lock. The copy +; sets errorFlag=true; direct extraction reports false despite the mixed versions. +; Exit code 0 alone cannot establish successful extraction; inspect RESULT_FILE. +Unicode true +RequestExecutionLevel user +SilentInstall silent +Name "Desktop occupied-file extraction smoke" +OutFile "${OUTPUT_FILE}" +!addplugindir /x86-unicode "${PLUGIN_DIR}" + +Section + InitPluginsDir + SetOutPath "${TARGET_DIR}" + !ifdef DIRECT + ClearErrors + Nsis7z::Extract "${PAYLOAD_FILE}" + !else + SetOutPath "$PLUGINSDIR\7z-out" + Nsis7z::Extract "${PAYLOAD_FILE}" + SetOutPath "${TARGET_DIR}" + ClearErrors + CopyFiles /SILENT "$PLUGINSDIR\7z-out\*" $OUTDIR + !endif + + StrCpy $0 "false" + IfErrors 0 +2 + StrCpy $0 "true" + ClearErrors + FileOpen $1 "${RESULT_FILE}" w + IfErrors failed + FileWrite $1 "errorFlag=$0$\r$\n" + FileOpen $2 "${TARGET_DIR}\locked.txt" r + IfErrors failed + FileRead $2 $3 + FileClose $2 + FileWrite $1 "locked=$3$\r$\n" + FileOpen $2 "${TARGET_DIR}\asset.txt" r + IfErrors failed + FileRead $2 $3 + FileClose $2 + FileWrite $1 "asset=$3$\r$\n" + FileClose $1 + SetErrorLevel 0 + Quit + + failed: + SetErrorLevel 1 + Quit +SectionEnd diff --git a/apps/desktop/tests/fixtures/owned-directory-smoke.mjs b/apps/desktop/tests/fixtures/owned-directory-smoke.mjs new file mode 100644 index 0000000000..52315992ba --- /dev/null +++ b/apps/desktop/tests/fixtures/owned-directory-smoke.mjs @@ -0,0 +1,29 @@ +/** Built Desktop cleanup smoke; run with Electron and ELECTRON_RUN_AS_NODE=1. */ + +import assert from 'node:assert/strict' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { removeOwnedDirectory } from '../../lib/types/owned-directory.js' +import { inventoryDesktopRuntime } from '../../lib/types/runtime-tree.js' + +assert.ok(process.versions.electron, 'This regression must run under Electron') +const root = mkdtempSync(join(tmpdir(), 'desktop-electron-cleanup-')) +try { + const resources = join(root, 'resources') + mkdirSync(resources) + writeFileSync(join(resources, 'sentinel'), 'installed runtime bytes') + const inventory = inventoryDesktopRuntime(resources) + const profile = join(root, 'rollback-profile') + const packages = join(profile, 'node_modules', '@unknown') + mkdirSync(packages, { recursive: true }) + symlinkSync(resources, join(packages, 'host-package'), process.platform === 'win32' ? 'junction' : 'dir') + writeFileSync(join(packages, 'private-file'), 'removed') + removeOwnedDirectory(profile) + assert.equal(existsSync(profile), false) + assert.deepEqual(inventoryDesktopRuntime(resources), inventory) + assert.equal(readFileSync(join(resources, 'sentinel'), 'utf8'), 'installed runtime bytes') + console.log(JSON.stringify({ electron: process.versions.electron, node: process.version, preservedLinkTarget: true })) +} finally { + removeOwnedDirectory(root) +} diff --git a/apps/desktop/tests/fixtures/runtime-payload-smoke.mjs b/apps/desktop/tests/fixtures/runtime-payload-smoke.mjs new file mode 100644 index 0000000000..da2d5c478d --- /dev/null +++ b/apps/desktop/tests/fixtures/runtime-payload-smoke.mjs @@ -0,0 +1,138 @@ +/** Exercise filtered Desktop native and HTML dependencies under its bundled Node. */ + +import assert from 'node:assert/strict' +import { closeSync, mkdtempSync, openSync, readFileSync, readSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' + +const runtime = process.argv[2] +assert.ok(runtime, 'Pass the filtered resources/dsh directory') +const root = resolve(runtime) +const descriptor = JSON.parse(readFileSync(join(root, 'desktop-runtime.json'), 'utf8')) +assert.equal(process.versions.node, descriptor.release.nodeVersion, 'Run with the bundled Node version') +assert.equal(process.platform, descriptor.platform) +assert.equal(process.arch, descriptor.arch) +const requireRuntime = createRequire(join(root, 'package.json')) +const scratch = mkdtempSync(join(tmpdir(), 'dsh-runtime-payload-')) + +/** Spawn only a fixed Node program and await the terminal's drained exit event. */ +async function checkPty() { + const pty = requireRuntime('node-pty') + const script = join(scratch, 'pty.cjs') + writeFileSync(script, "process.stdout.write('runtime-payload-pty-ok\\n')\n", { flag: 'wx', mode: 0o600 }) + const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => ( + /^(?:path|systemroot|windir|comspec)$/iu.test(name) + ))) + Object.assign(env, { HOME: scratch, USERPROFILE: scratch, TMP: scratch, TEMP: scratch, TMPDIR: scratch }) + const terminal = pty.spawn(process.execPath, [script], { cwd: scratch, env, cols: 80, rows: 24 }) + let output = '' + let exited = false + let timedOut = false + let exitSubscription + const exit = new Promise(resolveExit => { + exitSubscription = terminal.onExit(event => { + exited = true + resolveExit(event) + }) + }) + const dataSubscription = terminal.onData(data => { output += data }) + let timer + try { + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => { + timedOut = true + reject(new Error('Packaged PTY did not exit within 45 seconds')) + }, 45_000) + }) + const result = await Promise.race([exit, deadline]) + assert.equal(timedOut, false) + assert.ok(result.signal === undefined || result.signal === 0, 'PTY exited without a signal') + assert.equal(result.exitCode, 0) + assert.match(output, /runtime-payload-pty-ok/u) + } finally { + clearTimeout(timer) + dataSubscription.dispose() + try { + // node-pty's Windows natural-exit event closes output but leaves its ConPTY worker owned by kill(). + if (!exited || process.platform === 'win32') terminal.kill() + await exit + } finally { + exitSubscription.dispose() + } + } +} + +/** fs-ext implements seek on Windows through SetFilePointerEx and on POSIX through lseek. */ +function checkFsExt() { + const fsExt = requireRuntime('fs-ext') + const file = join(scratch, 'seek.txt') + writeFileSync(file, 'abcdef', { flag: 'wx', mode: 0o600 }) + const fd = openSync(file, 'r') + try { + assert.equal(fsExt.seekSync(fd, 2, fsExt.constants.SEEK_SET), 2) + const bytes = Buffer.alloc(4) + assert.equal(readSync(fd, bytes, 0, bytes.length, null), 4) + assert.equal(bytes.toString(), 'cdef') + } finally { + closeSync(fd) + } +} + +/** Resolve one system function through Koffi's packaged native module. */ +function checkKoffi() { + const koffi = requireRuntime('koffi') + const library = koffi.load(process.platform === 'win32' ? 'kernel32.dll' : null) + try { + const getPid = process.platform === 'win32' + ? library.func('uint32_t __stdcall GetCurrentProcessId(void)') + : library.func('int getpid(void)') + assert.equal(getPid(), process.pid) + } finally { + library.unload() + } +} + +/** Encode and decode a pixel through the packaged libvips binary. */ +async function checkSharp() { + const sharp = requireRuntime('sharp') + const pixel = Buffer.from([17, 103, 231]) + const png = await sharp(pixel, { raw: { width: 1, height: 1, channels: 3 } }).png().toBuffer() + const decoded = await sharp(png).raw().toBuffer({ resolveWithObject: true }) + assert.equal(decoded.info.width, 1) + assert.equal(decoded.info.height, 1) + assert.equal(decoded.info.channels, 3) + assert.deepEqual(decoded.data, pixel) +} + +/** Exercise Domino parsing through the HTML converter and GFM plugin used by web_fetch. */ +function checkHtml() { + const Turndown = requireRuntime('turndown') + const { gfm } = requireRuntime('@joplin/turndown-plugin-gfm') + const converter = new Turndown({ bulletListMarker: '-' }) + converter.use(gfm) + const markdown = converter.turndown('

A & B ©

  • first
  • second
' + + '
NameValue
x7
') + assert.match(markdown, /A & B ©/u) + assert.match(markdown, /-\s+first\n-\s+second/u) + assert.match(markdown, /\| Name \| Value \|/u) + assert.match(markdown, /\| x\s+\| 7\s+\|/u) +} + +try { + checkFsExt() + checkKoffi() + await checkSharp() + checkHtml() + await checkPty() +} finally { + // This private tree contains only fixture files; Windows may release handles after terminal exit. + await rm(scratch, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 }) +} + +// Natural event-loop drain includes node-pty's worker and console-list helper teardown. +process.once('beforeExit', () => { + console.log(JSON.stringify({ node: process.versions.node, platform: process.platform, arch: process.arch, + fsExt: true, koffi: true, sharp: true, html: true, pty: true })) +}) diff --git a/apps/desktop/tests/host-process.spec.ts b/apps/desktop/tests/host-process.spec.ts index 9a9a2d4730..f41650c26e 100644 --- a/apps/desktop/tests/host-process.spec.ts +++ b/apps/desktop/tests/host-process.spec.ts @@ -1,7 +1,7 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { DesktopHostProcess } from '../src/host-process.ts' const roots: string[] = [] @@ -75,6 +75,30 @@ afterEach(() => { }) describe('desktop host process', () => { + it('reports a fatal event after readiness once and stops the child', async () => { + const runtime = projectWithHost(` +process.send({ type: 'ready', protocolVersion: 3, dshVersion: '1.0.0' }) +function onRequestFrame(frame) { + if (frame.type === 1) process.send({ type: 'fatal', message: 'plugin unavailable' }) +} +`) + const failure = vi.fn() + const host = new DesktopHostProcess(process.execPath, runtime, runtime, undefined, process.env, failure) + try { + await host.start() + await expect(host.fetch(new Request('dsh-app://app/'))).rejects.toThrow('plugin unavailable') + await host.stop() + expect(failure).toHaveBeenCalledTimes(1) + expect(failure).toHaveBeenCalledWith(new Error('plugin unavailable')) + } finally { await host.stop() } + }) + + it('settles teardown when the executable cannot be spawned', async () => { + const runtime = projectWithHost('function onRequestFrame() {}') + const host = new DesktopHostProcess(join(runtime, 'missing-node'), runtime, runtime) + try { await expect(host.start()).rejects.toThrow() } finally { await host.stop() } + }) + it('loads the resource entry with a separate profile and scrubs Node resolution overrides', async () => { const runtime = projectWithHost(` process.send({ type: 'ready', protocolVersion: 3, dshVersion: 'split-runtime' }) diff --git a/apps/desktop/tests/macos-signature.spec.ts b/apps/desktop/tests/macos-signature.spec.ts index ada386cc38..e481d9a9f0 100644 --- a/apps/desktop/tests/macos-signature.spec.ts +++ b/apps/desktop/tests/macos-signature.spec.ts @@ -105,10 +105,10 @@ describe('desktop macOS release signature', () => { join(source, relative(sourceRoot, entry.from)), join(destination, entry.to), value => value, )) await copyFiles(matchers.slice(0, 1)) - expect(() => verifyDesktopRuntime(join(destination, 'dsh'), '1.0.0')).toThrow(/integrity/u) + await expect(verifyDesktopRuntime(join(destination, 'dsh'), '1.0.0')).rejects.toThrow(/ENOENT/u) rmSync(destination, { recursive: true }) await copyFiles(matchers) - expect(() => verifyDesktopRuntime(join(destination, 'dsh'), '1.0.0')).not.toThrow() + await expect(verifyDesktopRuntime(join(destination, 'dsh'), '1.0.0')).resolves.toMatchObject({ release: { version: '1.0.0' } }) } finally { rmSync(root, { recursive: true, force: true }) } }) @@ -120,6 +120,29 @@ describe('desktop macOS release signature', () => { }, 'win32')).toThrow(/DSH_DESKTOP_WINDOWS_CER_FILE/u) }) + it('isolates unsigned Windows artifacts and omits updater metadata without release credentials', async () => { + const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs') + const config = createElectronBuilderConfig({ + DSH_DESKTOP_APP_ID: RELEASE_ENVIRONMENT.DSH_DESKTOP_APP_ID, + DSH_DESKTOP_TARGET_PLATFORM: 'win32', + DSH_DESKTOP_UNSIGNED: '1', + }, 'win32', 'x64') + expect(portablePath(config.directories.output)).toContain('/targets/win-x64/unsigned-artifacts') + expect(portablePath(config.nsis.include)).toMatch(/\/scripts\/installer\.nsh$/u) + expect(config).toMatchObject({ + win: { forceCodeSigning: false, signtoolOptions: { sign: undefined } }, + publish: null, + }) + }) + + it('rejects unsigned macOS builds and malformed signing modes', async () => { + const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs') + expect(() => createElectronBuilderConfig({ ...RELEASE_ENVIRONMENT, DSH_DESKTOP_UNSIGNED: '1' })) + .toThrow(/unsigned builds require Windows/u) + expect(() => createElectronBuilderConfig({ ...RELEASE_ENVIRONMENT, DSH_DESKTOP_UNSIGNED: 'yes' })) + .toThrow(/must be 0 or 1/u) + }) + it('accepts the configured authority and team', () => { const expected = resolveMacOSSigningEnvironment(RELEASE_ENVIRONMENT) expect(() => { diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts new file mode 100644 index 0000000000..252db0a18c --- /dev/null +++ b/apps/desktop/tests/main-startup.spec.ts @@ -0,0 +1,200 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { DESKTOP_IPC } from '../src/ipc.ts' + +const harness = await vi.hoisted(async () => { + const { EventEmitter } = await import('node:events') + function deferred() { + let resolve!: () => void + let reject!: (error: Error) => void + const promise = new Promise((accept, decline) => { resolve = accept; reject = decline }) + return { promise, resolve, reject } + } + const windows: FakeWindow[] = [] + const hosts: FakeHost[] = [] + const handlers = new Map unknown>() + let preparing = deferred() + let prepared = deferred() + let hostStarted = deferred() + let navigated = deferred() + let errorPublished = deferred() + let quitCompleted = deferred() + class FakeWindow extends EventEmitter { + destroyed = false + readonly urls: string[] = [] + readonly webContents = Object.assign(new EventEmitter(), { + setWindowOpenHandler: vi.fn(), + openDevTools: vi.fn(), + send: vi.fn((channel: string, state: { phase?: string }) => { + if (channel === 'dsh-desktop:backend-state' && state.phase === 'error') errorPublished.resolve() + }), + }) + readonly show = vi.fn() + readonly focus = vi.fn() + readonly restore = vi.fn() + constructor(readonly options: { show: boolean }) { super(); windows.push(this) } + isDestroyed() { return this.destroyed } + isMinimized() { return false } + async loadURL(url: string) { + this.urls.push(url) + if (url === 'dsh-app://app/index.html') navigated.resolve() + } + static getAllWindows() { return windows.filter(window => !window.destroyed) } + close() { this.destroyed = true; this.emit('closed') } + } + class FakeHost { + readonly ready = deferred() + readonly exited = deferred() + readonly stopping = deferred() + readonly start = vi.fn(() => { hostStarted.resolve(); return this.ready.promise }) + readonly stop = vi.fn(() => { + this.stopping.resolve() + this.ready.reject(new Error('child stopped')) + return this.exited.promise + }) + constructor(..._args: unknown[]) { hosts.push(this) } + } + const app = Object.assign(new EventEmitter(), { + isPackaged: false, + name: 'Desktop test', + whenReady: () => Promise.resolve(), + getLocale: () => 'en-US', + getVersion: () => '1.0.0', + requestSingleInstanceLock: () => true, + exit: vi.fn(), + quit: vi.fn(() => { + const event = { preventDefault: vi.fn() } + app.emit('before-quit', event) + if (event.preventDefault.mock.calls.length === 0) quitCompleted.resolve() + }), + }) + return { + windows, hosts, handlers, app, FakeWindow, FakeHost, + dialog: { showErrorBox: vi.fn(), showMessageBox: vi.fn() }, + applyRelease: vi.fn(() => { preparing.resolve(); return prepared.promise }), + get preparing() { return preparing }, get prepared() { return prepared }, + get hostStarted() { return hostStarted }, get navigated() { return navigated }, + get errorPublished() { return errorPublished }, get quitCompleted() { return quitCompleted }, + nextHostStart() { hostStarted = deferred(); return hostStarted.promise }, + reset() { + windows.length = 0; hosts.length = 0; handlers.clear(); app.removeAllListeners() + preparing = deferred(); prepared = deferred(); hostStarted = deferred() + navigated = deferred(); errorPublished = deferred(); quitCompleted = deferred() + }, + } +}) + +vi.mock('electron', () => ({ + app: harness.app, + BrowserWindow: harness.FakeWindow, + dialog: harness.dialog, + ipcMain: { + handle: (channel: string, handler: (event: { senderFrame: { url: string } }) => unknown) => { harness.handlers.set(channel, handler) }, + }, + Menu: { setApplicationMenu: vi.fn(), buildFromTemplate: vi.fn() }, + protocol: { registerSchemesAsPrivileged: vi.fn(), handle: vi.fn() }, +})) +vi.mock('../src/paths.ts', () => ({ resolveDesktopPaths: () => ({ profile: 'desktop-test-profile' }) })) +vi.mock('../src/project-manager.ts', () => ({ + DesktopProjectManager: class { + readonly applyRelease = harness.applyRelease + readonly assertProfileRuntime = vi.fn() + }, +})) +vi.mock('../src/host-process.ts', () => ({ DesktopHostProcess: harness.FakeHost })) +vi.mock('../src/update-coordinator.ts', () => ({ DesktopUpdateCoordinator: vi.fn() })) + +function invoke(channel: string): unknown { + const handler = harness.handlers.get(channel) + if (handler === undefined) throw new Error(`missing handler ${channel}`) + return handler({ senderFrame: { url: 'dsh-app://shell/startup.html' } }) +} + +beforeEach(() => { + vi.resetModules() + vi.clearAllMocks() + vi.useFakeTimers() + harness.reset() + vi.stubEnv('DSH_DESKTOP_NODE_BINARY', 'test-node') + vi.stubEnv('DSH_DESKTOP_PNPM_ENTRY', 'test-pnpm') + vi.stubEnv('DSH_DESKTOP_DSH_DIR', 'test-runtime') + vi.stubEnv('DSH_DESKTOP_DEV_PROJECT_DIR', undefined) +}) + +afterEach(async () => { + harness.prepared.resolve() + for (const host of harness.hosts) { host.ready.resolve(); host.exited.resolve() } + harness.app.quit() + await harness.quitCompleted.promise + vi.clearAllTimers() + vi.useRealTimers() + vi.unstubAllEnvs() +}) + +describe('desktop main startup', () => { + it('shows the loading window before profile preparation and starts one actual Host', async () => { + await import('../src/main.ts') + await harness.preparing.promise + expect(harness.windows).toHaveLength(1) + const window = harness.windows[0]! + expect(window.options.show).toBe(true) + expect(window.urls).toEqual(['dsh-app://shell/startup.html']) + expect(harness.hosts).toHaveLength(0) + const retry = invoke(DESKTOP_IPC.backendRetry) + const secondRetry = invoke(DESKTOP_IPC.backendRetry) + harness.prepared.resolve() + await harness.hostStarted.promise + expect(harness.hosts).toHaveLength(1) + expect(window.urls).toEqual(['dsh-app://shell/startup.html']) + harness.hosts[0]!.ready.resolve() + await Promise.all([retry, secondRetry, harness.navigated.promise]) + expect(harness.applyRelease).toHaveBeenCalledTimes(1) + expect(harness.hosts[0]!.start).toHaveBeenCalledTimes(1) + expect(harness.windows).toHaveLength(1) + expect(window.urls).toEqual(['dsh-app://shell/startup.html', 'dsh-app://app/index.html']) + expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'ready' }) + }) + + it('keeps startup errors and a successful retry in the same window', async () => { + await import('../src/main.ts') + await harness.preparing.promise + harness.prepared.resolve() + await harness.hostStarted.promise + const first = harness.hosts[0]! + const failedRetry = expect(Promise.resolve(invoke(DESKTOP_IPC.backendRetry))).rejects.toThrow('plugin composition failed') + first.exited.resolve() + first.ready.reject(new Error('plugin composition failed')) + await harness.errorPublished.promise + await failedRetry + expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'error', message: 'plugin composition failed' }) + expect(harness.windows[0]!.urls).toEqual(['dsh-app://shell/startup.html']) + const nextStarted = harness.nextHostStart() + const retry = Promise.resolve(invoke(DESKTOP_IPC.backendRetry)) + await nextStarted + expect(harness.hosts).toHaveLength(2) + harness.hosts[1]!.ready.resolve() + await retry + expect(harness.windows).toHaveLength(1) + expect(harness.windows[0]!.urls.at(-1)).toBe('dsh-app://app/index.html') + expect(harness.dialog.showErrorBox).not.toHaveBeenCalled() + }) + + it('waits for a pending child to exit on quit without late window navigation', async () => { + await import('../src/main.ts') + await harness.preparing.promise + harness.prepared.resolve() + await harness.hostStarted.promise + const window = harness.windows[0]! + const host = harness.hosts[0]! + host.stop.mockImplementation(() => { host.stopping.resolve(); return host.exited.promise }) + window.close() + harness.app.quit() + await host.stopping.promise + expect(harness.app.quit).toHaveBeenCalledTimes(1) + host.ready.resolve() + host.exited.resolve() + await harness.quitCompleted.promise + expect(host.stop).toHaveBeenCalledTimes(1) + expect(window.urls).toEqual(['dsh-app://shell/startup.html']) + expect(harness.windows).toHaveLength(1) + }) +}) diff --git a/apps/desktop/tests/owned-directory.spec.ts b/apps/desktop/tests/owned-directory.spec.ts new file mode 100644 index 0000000000..081e5adc76 --- /dev/null +++ b/apps/desktop/tests/owned-directory.spec.ts @@ -0,0 +1,53 @@ +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { removeOwnedDirectory } from '../src/owned-directory.ts' + +const roots: string[] = [] +function fixture(): string { + const root = mkdtempSync(join(tmpdir(), 'desktop-owned-directory-')) + roots.push(root) + return root +} + +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) + +it('removes nested files and directories while preserving unknown directory-link targets', () => { + const root = fixture() + const target = join(root, 'target') + mkdirSync(target) + writeFileSync(join(target, 'sentinel'), 'preserved') + const owned = join(root, 'owned') + const nested = join(owned, 'node_modules', '@unknown', 'private') + mkdirSync(nested, { recursive: true }) + writeFileSync(join(nested, 'file'), 'remove') + symlinkSync(target, join(nested, 'link'), process.platform === 'win32' ? 'junction' : 'dir') + symlinkSync(join(root, 'missing-target'), join(owned, 'broken'), process.platform === 'win32' ? 'junction' : 'dir') + removeOwnedDirectory(owned) + expect(existsSync(owned)).toBe(false) + expect(readFileSync(join(target, 'sentinel'), 'utf8')).toBe('preserved') +}) + +it.each([false, true])('unlinks a root directory link with missing target: %s', (missing) => { + const root = fixture() + const target = join(root, 'target') + if (!missing) { + mkdirSync(target) + writeFileSync(join(target, 'sentinel'), 'preserved') + } + const link = join(root, 'link') + symlinkSync(target, link, process.platform === 'win32' ? 'junction' : 'dir') + removeOwnedDirectory(link) + expect(lstatSync(link, { throwIfNoEntry: false })).toBeUndefined() + if (!missing) expect(readFileSync(join(target, 'sentinel'), 'utf8')).toBe('preserved') +}) + +it('ignores a missing root and refuses to delete a regular-file root', () => { + const root = fixture() + expect(() => { removeOwnedDirectory(join(root, 'missing')) }).not.toThrow() + const file = join(root, 'file') + writeFileSync(file, 'preserved') + expect(() => { removeOwnedDirectory(file) }).toThrow(/not a directory/u) + expect(readFileSync(file, 'utf8')).toBe('preserved') +}) diff --git a/apps/desktop/tests/package-target.spec.ts b/apps/desktop/tests/package-target.spec.ts index ae5e0ca800..d284747e86 100644 --- a/apps/desktop/tests/package-target.spec.ts +++ b/apps/desktop/tests/package-target.spec.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { desktopElectronBuilderArguments, + desktopElectronBuilderEnvironment, parseDesktopPackageInvocation, resolveDesktopPackageTarget, withoutDesktopUploadCredentials, @@ -56,6 +57,45 @@ describe('desktop package target', () => { expect(desktopElectronBuilderArguments(target, true)).toContain('--dir') }) + it('accepts unsigned Windows artifacts and rejects other targets or preparation-only use', () => { + expect(parseDesktopPackageInvocation(['win-x64', '--unsigned'], 'win32', 'x64').unsigned).toBe(true) + expect(parseDesktopPackageInvocation(['win-x64'], 'win32', 'x64').unsigned).toBe(false) + expect(parseDesktopPackageInvocation(['--unsigned', '--dir'], 'win32', 'x64')).toMatchObject({ + unsigned: true, directory: true, + }) + expect(() => parseDesktopPackageInvocation(['mac-arm64', '--unsigned'], 'darwin', 'arm64')) + .toThrow(/requires win-x64/u) + expect(() => parseDesktopPackageInvocation(['--unsigned', '--prepare-only'], 'win32', 'x64')) + .toThrow(/cannot use --prepare-only/u) + }) + + it('removes ambient certificate inputs for unsigned builds and overrides an inherited signing mode', () => { + const environment = { + DSH_DESKTOP_APP_ID: 'com.example.desktop', + DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'token-secret', + CSC_LINK: 'private.pfx', + CSC_KEY_PASSWORD: 'secret', + WIN_CSC_LINK: 'windows.pfx', + CSC_IDENTITY_AUTO_DISCOVERY: 'true', + DSH_DESKTOP_UNSIGNED: '1', + } + expect(desktopElectronBuilderEnvironment(environment, true)).toEqual({ + DSH_DESKTOP_APP_ID: 'com.example.desktop', + CSC_IDENTITY_AUTO_DISCOVERY: 'false', + DSH_DESKTOP_UNSIGNED: '1', + }) + expect(desktopElectronBuilderEnvironment(environment, false)).toEqual({ ...environment, DSH_DESKTOP_UNSIGNED: '0' }) + }) + + it.each([false, true])('pins the Windows archive filter for the NSIS decoder (unsigned: %s)', (unsigned) => { + expect(desktopElectronBuilderEnvironment({ + DSH_DESKTOP_TARGET_PLATFORM: 'win32', ELECTRON_BUILDER_7Z_FILTER: 'ARM64', + }, unsigned).ELECTRON_BUILDER_7Z_FILTER).toBe('BCJ') + expect(desktopElectronBuilderEnvironment({ + DSH_DESKTOP_TARGET_PLATFORM: 'darwin', ELECTRON_BUILDER_7Z_FILTER: 'ARM', + }, unsigned).ELECTRON_BUILDER_7Z_FILTER).toBe('ARM') + }) + it('keeps Windows signing fields out of build and runtime preparation subprocesses', () => { expect(withoutWindowsSigningEnvironment({ DSH_DESKTOP_WINDOWS_CER_FILE: 'C:\\release\\server.cer', diff --git a/apps/desktop/tests/plugin-manager.spec.ts b/apps/desktop/tests/plugin-manager.spec.ts index 376b523f58..d870b7ecc7 100644 --- a/apps/desktop/tests/plugin-manager.spec.ts +++ b/apps/desktop/tests/plugin-manager.spec.ts @@ -12,7 +12,7 @@ it('keeps disabled packages visible and offers recovery without a running backen const toggle = vi.fn(async (_name: string, active: boolean) => { enabled = active }) const api = { locale: async () => resolveDesktopLocale('en'), - backend: { status: async () => ({ ready, error: ready ? undefined : 'plugin requires Cordis ^2.0.0' }), retry: vi.fn() }, + backend: { status: async () => ready ? { phase: 'ready' } : { phase: 'error', message: 'plugin requires Cordis ^2.0.0' }, retry: vi.fn() }, plugins: { list: async () => [{ name: 'example-plugin', version: '1.0.0', enabled }], disableAll, toggle }, } Object.defineProperty(dom.window, 'dshDesktop', { value: api }) diff --git a/apps/desktop/tests/plugin-pnpm.spec.ts b/apps/desktop/tests/plugin-pnpm.spec.ts index 1a455e3453..f565967cee 100644 --- a/apps/desktop/tests/plugin-pnpm.spec.ts +++ b/apps/desktop/tests/plugin-pnpm.spec.ts @@ -47,7 +47,7 @@ it('installs a real pnpm graph, then executes approved scripts with the shared h const realPnpm = join(import.meta.dirname, '../node_modules/pnpm/bin/pnpm.mjs') writeFileSync(pnpm, `process.argv = process.argv.map(arg => arg === '--config.registry=https://registry.npmjs.org/' ? ${JSON.stringify(`--config.registry=${origin}`)} : arg); await import(${JSON.stringify(pathToFileURL(realPnpm).href)})`) const manager = new DesktopProjectManager(resolveDesktopPaths(join(root, '.dsh')), { node: process.execPath, pnpm, dsh }) - const hooks: DesktopProjectHooks = { healthCheck: async () => {}, beforeActivate: async () => {}, afterActivate: async () => {} } + const hooks: DesktopProjectHooks = { beforeActivate: async () => {}, afterActivate: async () => {} } await manager.applyRelease('1.0.0', hooks) await manager.mutate({ type: 'plugin-add', spec: 'fixture-plugin@1.0.0' }, hooks) expect(manager.listPlugins()).toEqual([{ name: 'fixture-plugin', version: '1.0.0', enabled: true }]) diff --git a/apps/desktop/tests/preload-app.spec.ts b/apps/desktop/tests/preload-app.spec.ts new file mode 100644 index 0000000000..81eac02cc3 --- /dev/null +++ b/apps/desktop/tests/preload-app.spec.ts @@ -0,0 +1,37 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { DESKTOP_IPC, type DshDesktopStartupApi } from '../src/ipc.ts' + +const electron = vi.hoisted(() => ({ + contextBridge: { exposeInMainWorld: vi.fn() }, + ipcRenderer: { invoke: vi.fn(), on: vi.fn(), off: vi.fn() }, +})) +vi.mock('electron', () => electron) + +afterEach(() => { vi.unstubAllGlobals(); vi.clearAllMocks(); vi.resetModules() }) + +it.each(['dsh-app://app/index.html', 'https://shell/startup.html'])('exposes only the carrier marker to %s', async (url) => { + vi.stubGlobal('location', new URL(url)) + await import('../src/preload-app.ts') + expect(electron.contextBridge.exposeInMainWorld).toHaveBeenCalledWith('dshDesktop', { protocolVersion: 1 }) +}) + +it('provides startup controls and a removable state subscription to shell documents', async () => { + vi.stubGlobal('location', new URL('dsh-app://shell/startup.html')) + await import('../src/preload-app.ts') + const api = electron.contextBridge.exposeInMainWorld.mock.calls[0]?.[1] as DshDesktopStartupApi + await api.locale() + await api.backend.status() + await api.backend.retry() + await api.openPlugins() + expect(electron.ipcRenderer.invoke.mock.calls).toEqual([ + [DESKTOP_IPC.localeGet], [DESKTOP_IPC.backendStatus], [DESKTOP_IPC.backendRetry], [DESKTOP_IPC.pluginsOpen], + ]) + const listener = vi.fn() + const dispose = api.backend.subscribe(listener) + const handler = electron.ipcRenderer.on.mock.calls[0]?.[1] as (event: unknown, state: unknown) => void + handler({}, { phase: 'error', message: 'startup failed' }) + expect(listener).toHaveBeenCalledWith({ phase: 'error', message: 'startup failed' }) + dispose() + expect(electron.ipcRenderer.off).toHaveBeenCalledWith(DESKTOP_IPC.backendState, handler) + expect(api).not.toHaveProperty('plugins') +}) diff --git a/apps/desktop/tests/project-manager.spec.ts b/apps/desktop/tests/project-manager.spec.ts index 18e5c26c7a..9d141efa2d 100644 --- a/apps/desktop/tests/project-manager.spec.ts +++ b/apps/desktop/tests/project-manager.spec.ts @@ -48,7 +48,7 @@ if (command !== 'rebuild') { return path } function hooks(overrides: Partial = {}): DesktopProjectHooks { - return { healthCheck: async () => {}, beforeActivate: async () => {}, afterActivate: async () => {}, ...overrides } + return { beforeActivate: async () => {}, afterActivate: async () => {}, ...overrides } } function setup(): { root: string; manager: DesktopProjectManager } { const root = temporaryRoot() @@ -91,6 +91,36 @@ describe('desktop external plugin profile', () => { expect(calls(root)).toEqual([]) }) + it.skipIf(process.platform !== 'win32')('reuses the profile when the launch path changes only Windows letter casing', async () => { + const { manager } = setup() + await manager.applyRelease('1.0.0', hooks()) + const relaunched = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh: manager.runtime.dsh.toUpperCase() }) + let started = false + await expect(relaunched.applyRelease('1.0.0', hooks({ + afterActivate: async () => { started = true }, + }))).resolves.toBe(false) + expect(started).toBe(false) + }) + + it.each(['changed', 'same-size', 'extra', 'missing'])('starts and reuses a profile without checking %s runtime bytes', async (operation) => { + const { root, manager } = setup() + if (operation === 'changed') writeFileSync(join(manager.runtime.dsh, 'package.json'), '{}') + if (operation === 'same-size') writeFileSync(join(manager.runtime.dsh, 'package.json'), '{"type":"Module"}\n') + if (operation === 'extra') writeFileSync(join(manager.runtime.dsh, 'extra'), '') + if (operation === 'missing') unlinkSync(join(manager.runtime.dsh, 'package.json')) + let starts = 0 + await expect(manager.applyRelease('1.0.0', hooks({ + afterActivate: async () => { starts++ }, + }))).resolves.toBe(true) + const relaunched = new DesktopProjectManager(manager.paths, manager.runtime) + await expect(relaunched.applyRelease('1.0.0', hooks({ + afterActivate: async () => { starts++ }, + }))).resolves.toBe(false) + expect(starts).toBe(1) + expect(existsSync(manager.paths.profile)).toBe(true) + expect(calls(root)).toEqual([]) + }) + it('installs only plugins and checks the graph before running lifecycle scripts', async () => { const { root, manager } = setup() await manager.applyRelease('1.0.0', hooks()) @@ -166,12 +196,11 @@ describe('desktop external plugin profile', () => { expect(next.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: false }]) }) - it.each(['health', 'before', 'after'] as const)('keeps the active profile when %s activation fails', async (phase) => { + it.each(['before', 'after'] as const)('keeps the active profile when %s activation fails', async (phase) => { const { manager } = setup() await manager.applyRelease('1.0.0', hooks()) let starts = 0 await expect(manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks({ - healthCheck: async () => { if (phase === 'health') throw new Error('health failed') }, beforeActivate: async () => { if (phase === 'before') throw new Error('before failed') }, afterActivate: async () => { if (phase === 'after' && starts++ === 0) throw new Error('after failed') }, }))).rejects.toThrow(`${phase} failed`) diff --git a/apps/desktop/tests/runtime-file-policy.spec.ts b/apps/desktop/tests/runtime-file-policy.spec.ts new file mode 100644 index 0000000000..837fd54bf1 --- /dev/null +++ b/apps/desktop/tests/runtime-file-policy.spec.ts @@ -0,0 +1,81 @@ +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, relative } from 'node:path' +import { expect, it } from 'vitest' +import { desktopRuntimeFileExclusion } from '../scripts/runtime-file-policy.ts' +import { verifyDesktopRuntime, writeDesktopRuntime } from '../src/runtime-tree.ts' +import { runtimeFixture } from './runtime-fixture.ts' + +const windows = { platform: 'win32' as const, arch: 'x64' } + +it('omits development artifacts while preserving executable modules, assets and license files', async () => { + const root = mkdtempSync(join(tmpdir(), 'desktop-file-policy-')) + const source = join(root, 'source') + const output = join(root, 'output') + const removed = [ + 'example/index.d.ts', 'example/index.d.mts', 'example/index.d.cts', + 'example/index.js.map', 'example/index.mjs.map', 'example/index.cjs.map', + 'example/style.css.map', 'example/index.d.ts.map', 'example/index.d.mts.map', + 'example/index.d.cts.map', 'example/tsconfig.tsbuildinfo', + 'fs-ext/build/Release/obj/fs_ext/native.obj', 'fs-ext/build/Release/fs_ext.pdb', + 'fs-ext/build/Release/fs_ext.lib', 'fs-ext/build/Release/fs_ext.exp', + 'fs-ext/build/Release/fs_ext.iobj', 'fs-ext/build/Release/fs_ext.ipdb', + 'fs-ext/build/binding.sln', 'fs-ext/build/config.gypi', + 'fs-ext/build/fs_ext.vcxproj', 'fs-ext/build/fs_ext.vcxproj.filters', + 'node-pty/prebuilds/win32-arm64/conpty.node', + 'node-pty/prebuilds/linux-x64/pty.node', 'node-pty/prebuilds/darwin-x64/pty.node', + 'node-pty/prebuilds/win32-x64/conpty.pdb', + '@koromix/koffi-win32-x64/win32_x64/koffi.lib', + '@mixmark-io/domino/test/entities.html', + '.modules.yaml', '.pnpm-workspace-state-v1.json', '.bin/tool', '.pnpm/cache', + ] + const retained = [ + 'example/index.js', 'example/index.cjs', 'example/index.mjs', 'example/worker.js', + 'example/source.ts', 'example/src/entry.ts', 'example/test/runtime-fixture.json', + 'example/locale.json', 'example/data.map', 'example/module.wasm', + 'example/package.json', 'example/LICENSE', 'example/NOTICE', 'example/README.md', + 'example/native.lib', 'example/native.obj', 'example/symbols.pdb', + 'fs-ext/build/Release/fs_ext.node', 'fs-ext/build/Release/runtime.dll', + 'node-pty/prebuilds/win32-x64/conpty.node', + 'node-pty/prebuilds/win32-x64/conpty_console_list.node', + 'node-pty/prebuilds/win32-x64/conpty/conpty.dll', + 'node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe', + 'node-pty/third_party/conpty/win10-x64/OpenConsole.exe', + '@koromix/koffi-win32-x64/win32_x64/koffi.node', + '@mixmark-io/domino/lib/HTMLParser.js', '@mixmark-io/domino/lib/EntityParser.js', + '@img/sharp-win32-x64/lib/libvips-42.dll', + ] + try { + const runtime = runtimeFixture(source) + const modules = join(source, 'node_modules') + for (const path of [...removed, ...retained]) { + mkdirSync(join(modules, path, '..'), { recursive: true }) + writeFileSync(join(modules, path), `payload:${path}`) + } + cpSync(modules, join(output, 'node_modules'), { + recursive: true, dereference: true, + filter: path => desktopRuntimeFileExclusion(relative(modules, path), windows) === undefined, + }) + for (const path of removed) expect(existsSync(join(output, 'node_modules', path)), path).toBe(false) + for (const path of retained) expect(readFileSync(join(output, 'node_modules', path), 'utf8'), path).toBe(`payload:${path}`) + const sealed = writeDesktopRuntime(output, runtime.release, runtime.sharedPackages.map(entry => entry.name)) + expect(await verifyDesktopRuntime(output, runtime.release.version)).toEqual(sealed) + expect(readFileSync(join(modules, removed[0]!), 'utf8')).toBe(`payload:${removed[0]}`) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +it('applies package-specific rules inside scoped and nested dependency containers', () => { + expect(desktopRuntimeFileExclusion('outer/node_modules/@mixmark-io/domino/test/data.html', windows)).toBeDefined() + expect(desktopRuntimeFileExclusion('outer\\node_modules\\node-pty\\prebuilds\\win32-arm64\\conpty.node', windows)).toBeDefined() + expect(desktopRuntimeFileExclusion('outer/node_modules/unrelated/test/data.html', windows)).toBeUndefined() + expect(desktopRuntimeFileExclusion('outer/fs-ext/build/Release/fs_ext.lib', windows)).toBeUndefined() +}) + +it('retains native prebuilds for the selected macOS architecture', () => { + const mac = { platform: 'darwin' as const, arch: 'arm64' } + expect(desktopRuntimeFileExclusion('node-pty/prebuilds/darwin-arm64/pty.node', mac)).toBeUndefined() + expect(desktopRuntimeFileExclusion('node-pty/prebuilds/darwin-x64/pty.node', mac)).toBeDefined() + expect(desktopRuntimeFileExclusion('node-pty/prebuilds/win32-x64/conpty.node', mac)).toBeDefined() +}) diff --git a/apps/desktop/tests/runtime-tree-read-failure.spec.ts b/apps/desktop/tests/runtime-tree-read-failure.spec.ts new file mode 100644 index 0000000000..042ff77c6d --- /dev/null +++ b/apps/desktop/tests/runtime-tree-read-failure.spec.ts @@ -0,0 +1,49 @@ +import { mkdtempSync, readFile, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { setImmediate } from 'node:timers/promises' +import { expect, it, vi } from 'vitest' +import { verifyDesktopRuntime } from '../src/runtime-tree.ts' +import { runtimeFixture } from './runtime-fixture.ts' + +vi.mock('node:fs', async importOriginal => ({ + ...await importOriginal(), + readFile: vi.fn(), +})) + +it('drains outstanding reads before rejecting and stops scheduling after a read failure', async () => { + const root = mkdtempSync(join(tmpdir(), 'desktop-runtime-read-failure-')) + const pending: ((error?: Error) => void)[] = [] + vi.mocked(readFile).mockImplementation((...args: unknown[]) => { + const path = args[0] + const callback = args.at(-1) + if (typeof path !== 'string' || typeof callback !== 'function') throw new Error('unexpected readFile arguments') + const complete = callback as (error: Error | null, body: Buffer | undefined) => void + pending.push((error) => { complete(error ?? null, error === undefined ? readFileSync(path) : undefined) }) + }) + let outcome: Promise | undefined + try { + runtimeFixture(root) + let settled = false + outcome = verifyDesktopRuntime(root, '1.0.0').finally(() => { settled = true }).catch((error: unknown) => error) + const inFlight = pending.length + expect(inFlight).toBeGreaterThan(1) + const failure = new Error('runtime read failed') + pending.shift()!(failure) + try { + // Pending callbacks keep the reads open across a complete event-loop turn. + await setImmediate() + expect(settled).toBe(false) + expect(pending).toHaveLength(inFlight - 1) + } finally { + for (const complete of pending.splice(0)) complete() + } + expect(await outcome).toBe(failure) + expect(pending).toHaveLength(0) + } finally { + for (const complete of pending.splice(0)) complete(new Error('test cleanup')) + await outcome + vi.mocked(readFile).mockReset() + rmSync(root, { recursive: true, force: true }) + } +}) diff --git a/apps/desktop/tests/runtime-tree.spec.ts b/apps/desktop/tests/runtime-tree.spec.ts index 4c4dddf52e..20bfa289a2 100644 --- a/apps/desktop/tests/runtime-tree.spec.ts +++ b/apps/desktop/tests/runtime-tree.spec.ts @@ -1,8 +1,9 @@ -import { cpSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { DESKTOP_RUNTIME_FILE, desktopRuntimeId, runtimePath, verifyDesktopRuntime } from '../src/runtime-tree.ts' +import { DESKTOP_HOST_PACKAGE, DESKTOP_HOST_RUNTIME_FILES } from '../src/core-package-set.ts' +import { DESKTOP_RUNTIME_FILE, desktopRuntimeId, readDesktopRuntime, runtimePath, verifyDesktopRuntime } from '../src/runtime-tree.ts' import { runtimeFixture } from './runtime-fixture.ts' const roots: string[] = [] @@ -14,32 +15,59 @@ function fixture(): string { } afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) -it('verifies a runtime after relocation without depending on build paths', () => { +it('verifies a runtime after relocation without depending on build paths', async () => { const root = fixture() - const before = verifyDesktopRuntime(join(root, 'dsh'), '1.0.0') + const before = await verifyDesktopRuntime(join(root, 'dsh'), '1.0.0') cpSync(join(root, 'dsh'), join(root, 'moved'), { recursive: true }) - expect(desktopRuntimeId(verifyDesktopRuntime(join(root, 'moved'), '1.0.0'))).toBe(desktopRuntimeId(before)) + expect(desktopRuntimeId(await verifyDesktopRuntime(join(root, 'moved'), '1.0.0'))).toBe(desktopRuntimeId(before)) }) -it.each(['changed', 'extra', 'missing'])('rejects %s runtime bytes', (operation) => { +it.each(['changed', 'same-size', 'extra', 'missing'])('checks %s runtime bytes only during build verification', async (operation) => { const dsh = join(fixture(), 'dsh') + const before = readDesktopRuntime(dsh, '1.0.0') if (operation === 'changed') writeFileSync(join(dsh, 'package.json'), '{}') + if (operation === 'same-size') writeFileSync(join(dsh, 'package.json'), '{"type":"Module"}\n') if (operation === 'extra') writeFileSync(join(dsh, 'extra'), '') if (operation === 'missing') rmSync(join(dsh, 'package.json')) - expect(() => verifyDesktopRuntime(dsh, '1.0.0')).toThrow(/integrity/u) + expect(readDesktopRuntime(dsh, '1.0.0')).toEqual(before) + await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/integrity/u) }) -it('rejects filesystem links and incompatible targets', () => { +it('rejects filesystem links and incompatible targets', async () => { const dsh = join(fixture(), 'dsh') - expect(() => verifyDesktopRuntime(dsh, '1.0.0', { platform: process.platform, arch: 'wrong' })).toThrow(/incompatible/u) + await expect(verifyDesktopRuntime(dsh, '1.0.0', { platform: process.platform, arch: 'wrong' })).rejects.toThrow(/incompatible/u) symlinkSync(join(dsh, 'node_modules'), join(dsh, 'outside'), process.platform === 'win32' ? 'junction' : 'dir') - expect(() => verifyDesktopRuntime(dsh, '1.0.0')).toThrow(/unsupported filesystem/u) + expect(readDesktopRuntime(dsh, '1.0.0').release.version).toBe('1.0.0') + await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/unsupported filesystem/u) }) -it('rejects a descriptor that maps a shared package outside node_modules', () => { +it.each(['missing', 'directory'])('rejects a %s Host entry during startup metadata loading', (operation) => { + const dsh = join(fixture(), 'dsh') + const path = join(dsh, 'node_modules', DESKTOP_HOST_PACKAGE, DESKTOP_HOST_RUNTIME_FILES[0]) + rmSync(path) + if (operation === 'directory') mkdirSync(path) + expect(() => readDesktopRuntime(dsh, '1.0.0')).toThrow(/missing Host file/u) +}) +it('rejects incompatible targets and shared package metadata during startup metadata loading', () => { + const dsh = join(fixture(), 'dsh') + expect(() => readDesktopRuntime(dsh, '2.0.0')).toThrow(/does not match Electron/u) + expect(() => readDesktopRuntime(dsh, '1.0.0', { platform: process.platform, arch: 'wrong' })).toThrow(/incompatible/u) + writeFileSync(join(dsh, 'node_modules', DESKTOP_HOST_PACKAGE, 'package.json'), '{}') + expect(() => readDesktopRuntime(dsh, '1.0.0')).toThrow(/shared package metadata mismatch/u) +}) +it('rejects a descriptor that maps a shared package outside node_modules', async () => { const dsh = join(fixture(), 'dsh') const path = join(dsh, DESKTOP_RUNTIME_FILE) const descriptor = JSON.parse(readFileSync(path, 'utf8')) as { sharedPackages: { path: string }[] } descriptor.sharedPackages[0]!.path = '../outside' writeFileSync(path, JSON.stringify(descriptor)) - expect(() => verifyDesktopRuntime(dsh, '1.0.0')).toThrow(/shared package record/u) + await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/shared package record/u) +}) +it('verifies recorded executable permissions only on Unix', async () => { + const dsh = join(fixture(), 'dsh') + const path = join(dsh, DESKTOP_RUNTIME_FILE) + const descriptor = JSON.parse(readFileSync(path, 'utf8')) as { files: { executable: boolean }[] } + descriptor.files[0]!.executable = !descriptor.files[0]!.executable + writeFileSync(path, JSON.stringify(descriptor)) + if (process.platform === 'win32') await expect(verifyDesktopRuntime(dsh, '1.0.0')).resolves.toMatchObject(descriptor) + else await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/integrity/u) }) it.each(['../outside', '/absolute', 'C:/absolute', 'a\\b', 'a//b', './a'])('rejects nonportable path %s', (path) => { expect(() => runtimePath('/runtime', path)).toThrow(/invalid relative path/u) diff --git a/apps/desktop/tests/startup-renderer.spec.ts b/apps/desktop/tests/startup-renderer.spec.ts new file mode 100644 index 0000000000..dbbb180ca9 --- /dev/null +++ b/apps/desktop/tests/startup-renderer.spec.ts @@ -0,0 +1,134 @@ +import { readFileSync } from 'node:fs' +import { runInContext } from 'node:vm' +import { JSDOM } from 'jsdom' +import { expect, it, onTestFinished, vi } from 'vitest' +import type { DesktopBackendState } from '../src/backend-controller.ts' +import type { DshDesktopStartupApi } from '../src/ipc.ts' +import { resolveDesktopLocale } from '../src/locale.ts' + +function startup(locale = 'en', status: Promise = Promise.resolve({ phase: 'starting' })) { + const dom = new JSDOM(readFileSync(new URL('../renderer/startup.html', import.meta.url), 'utf8'), { runScripts: 'outside-only' }) + onTestFinished(() => { + dom.window.dispatchEvent(new dom.window.Event('pagehide')) + dom.window.close() + }) + const listeners = new Set<(state: DesktopBackendState) => void>() + const unsubscribe = vi.fn(() => { listeners.clear() }) + const retry = vi.fn(async () => {}) + const openPlugins = vi.fn(async () => {}) + const queried = Promise.withResolvers() + const api: DshDesktopStartupApi = { + protocolVersion: 1, + locale: async () => resolveDesktopLocale(locale), + backend: { + status: () => { queried.resolve(undefined); return status }, + retry, + subscribe: (listener) => { listeners.add(listener); return unsubscribe }, + }, + openPlugins, + } + Object.defineProperty(dom.window, 'dshDesktop', { value: api }) + runInContext(readFileSync(new URL('../renderer/startup.js', import.meta.url), 'utf8'), dom.getInternalVMContext()) + const document = dom.window.document + const element = (selector: string): HTMLElement => { + const result = document.querySelector(selector) + if (result === null) throw new Error(`Missing startup element: ${selector}`) + return result + } + const button = (selector: string): HTMLButtonElement => { + const result = document.querySelector(selector) + if (result === null) throw new Error(`Missing startup button: ${selector}`) + return result + } + const publish = (state: DesktopBackendState): void => { for (const listener of listeners) listener(state) } + const copy = (): string => [element('#title').textContent, element('#description').textContent, + ...['#error', '#actions'].filter(selector => !element(selector).hidden) + .flatMap(selector => selector === '#actions' + ? [button('#retry').textContent, button('#plugins').textContent] + : [element(selector).textContent]), + ].join('\n') + return { dom, document, element, button, publish, copy, retry, openPlugins, unsubscribe, queried: queried.promise } +} + +it('shows English loading and recovery actions without a Host document', async () => { + const page = startup() + await expect.poll(() => page.element('#title').textContent).not.toBe('') + expect(page.copy()).toMatchInlineSnapshot(` + "Starting DeepSeek Harness… + Your workspace will open when it is ready." + `) + expect(page.element('main').getAttribute('aria-busy')).toBe('true') + expect(page.element('#spinner').hidden).toBe(false) + expect(page.element('#actions').hidden).toBe(true) + expect(page.button('#retry').disabled).toBe(true) + expect(page.button('#plugins').disabled).toBe(true) + page.publish({ phase: 'error', message: 'Plugin failed to load' }) + expect(page.copy()).toMatchInlineSnapshot(` + "DeepSeek Harness could not start + The application could not start. Retry or manage Desktop plugins to resolve the problem. + Plugin failed to load + Retry startup + Manage plugins" + `) + expect(page.element('main').getAttribute('aria-busy')).toBe('false') + expect(page.element('#spinner').hidden).toBe(true) + page.button('#plugins').click() + expect(page.openPlugins).toHaveBeenCalledOnce() + page.button('#retry').click() + expect(page.retry).toHaveBeenCalledOnce() + expect(page.element('#actions').hidden).toBe(true) + expect(page.element('#error').textContent).toBe('') + expect(page.element('main').getAttribute('aria-busy')).toBe('true') +}) + +it('shows Chinese loading and recovery copy', async () => { + const page = startup('zh-CN') + await expect.poll(() => page.element('#title').textContent).not.toBe('') + expect(page.document.documentElement.lang).toBe('zh-CN') + expect(page.copy()).toMatchInlineSnapshot(` + "正在启动 DeepSeek Harness… + 准备就绪后将自动打开工作区。" + `) + page.publish({ phase: 'error', message: '插件加载失败' }) + expect(page.copy()).toMatchInlineSnapshot(` + "DeepSeek Harness 无法启动 + 应用未能启动。你可以重试,或管理桌面插件以解决问题。 + 插件加载失败 + 重试启动 + 管理插件" + `) +}) + +it('renders diagnostic markup as text and exposes failures from recovery actions', async () => { + const page = startup() + await expect.poll(() => page.element('#title').textContent).not.toBe('') + const diagnostic = '' + page.publish({ phase: 'error', message: diagnostic }) + expect(page.element('#error').textContent).toBe(diagnostic) + expect(page.element('#error').childElementCount).toBe(0) + page.openPlugins.mockRejectedValueOnce(new page.dom.window.Error('Cannot open plugin manager')) + page.button('#plugins').click() + await expect.poll(() => page.element('#error').textContent).toBe('Cannot open plugin manager') + page.retry.mockRejectedValueOnce(new page.dom.window.Error('Retry failed')) + page.button('#retry').click() + await expect.poll(() => page.element('#error').textContent).toBe('Retry failed') + expect(page.button('#retry').disabled).toBe(false) + expect(page.button('#plugins').disabled).toBe(false) +}) + +it('keeps subscribed state when initial status arrives late and detaches on pagehide', async () => { + const initial = Promise.withResolvers() + const page = startup('en', initial.promise) + await page.queried + page.publish({ phase: 'error', message: 'Fresh startup failure' }) + initial.resolve({ phase: 'starting' }) + await initial.promise + expect(page.element('#error').textContent).toBe('Fresh startup failure') + expect(page.element('#actions').hidden).toBe(false) + page.dom.window.dispatchEvent(new page.dom.window.Event('pagehide')) + expect(page.unsubscribe).toHaveBeenCalledOnce() + page.publish({ phase: 'starting' }) + expect(page.element('#error').textContent).toBe('Fresh startup failure') + page.dom.window.dispatchEvent(new page.dom.window.Event('pagehide')) + expect(page.unsubscribe).toHaveBeenCalledOnce() +}) diff --git a/apps/desktop/tsdown.config.ts b/apps/desktop/tsdown.config.ts index 6f7fa58c8d..d34cf1bf26 100644 --- a/apps/desktop/tsdown.config.ts +++ b/apps/desktop/tsdown.config.ts @@ -12,19 +12,16 @@ export default defineConfig([ clean: false, deps: { neverBundle: ['electron'] }, }, - { + ...(['preload', 'preload-app'] as const).map(name => ({ // Sandboxed Electron preloads run as CommonJS even though the application package is ESM. - entry: { - preload: 'lib/types/preload.js', - 'preload-app': 'lib/types/preload-app.js', - }, + entry: { [name]: `lib/types/${name}.js` }, outDir: 'lib', - format: ['cjs'], - platform: 'node', + format: ['cjs'] as const, + platform: 'node' as const, target: 'es2024', fixedExtension: false, dts: false, clean: false, deps: { neverBundle: ['electron'] }, - }, + })), ]) diff --git a/package.json b/package.json index 1c4c8f6f86..662e7f8935 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "package:desktop:mac:x64": "pnpm --filter @deepseek-ai/dsh-desktop run package:mac:x64", "package:desktop:mac:x64:dir": "pnpm --filter @deepseek-ai/dsh-desktop run package:mac:x64:dir", "package:desktop:win:x64": "pnpm --filter @deepseek-ai/dsh-desktop run package:win:x64", + "package:desktop:win:x64:unsigned": "pnpm --filter @deepseek-ai/dsh-desktop run package:win:x64:unsigned", "package:desktop:win:x64:dir": "pnpm --filter @deepseek-ai/dsh-desktop run package:win:x64:dir", "upload:mac:arm64": "pnpm --filter @deepseek-ai/dsh-desktop run upload:mac:arm64", "upload:mac:x64": "pnpm --filter @deepseek-ai/dsh-desktop run upload:mac:x64", From d79294f23a2fd62d37f7c997ec97e51fec9d905a Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Wed, 9 Sep 2026 17:31:28 +0800 Subject: [PATCH 13/52] fix(scripts): enumerate repo files with a dirent walker instead of node fs.glob Node's internal fs.glob, from some 24.x releases, lstat-probes / while expanding a ** pattern over a symlinked file and throws ENOTDIR instead of skipping (observed on node 24.13.0 scanning snapshots/acp/image-compaction's symlinked system-prompt.expected.md, which failed verify-md-wrap inside check:ci:static). uniqueRepoFiles now walks with dirent types, never probing a path under a file, and mirrors fs.glob's dot:false and follow:false semantics: the four repo-files gate pattern sets enumerate identically. Broken or cyclic symlinks fail loudly in the caller's realpathSync, and pattern forms the walker does not model (metacharacters, a trailing **, empty segments) are rejected up front. repo-files.spec.ts pins the symlink, broken-link, and rejection behavior. --- scripts/repo-files.spec.ts | 176 +++++++++++++++++++++++++++++++++++++ scripts/repo-files.ts | 174 +++++++++++++++++++++++++++++++++++- 2 files changed, 346 insertions(+), 4 deletions(-) create mode 100644 scripts/repo-files.spec.ts diff --git a/scripts/repo-files.spec.ts b/scripts/repo-files.spec.ts new file mode 100644 index 0000000000..60875341d7 --- /dev/null +++ b/scripts/repo-files.spec.ts @@ -0,0 +1,176 @@ +import { mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, relative } from 'node:path' +import { describe, expect, it } from 'vitest' +import { uniqueRepoFiles } from './repo-files.ts' + +interface Tree { + root: string + clean: () => void +} + +function makeTree(): Tree { + const parent = mkdtempSync(join(tmpdir(), 'repo-files-')) + const root = join(parent, 'root') + const outside = join(parent, 'outside') // reachable only through a symlinked dir + mkdirSync(join(root, 'a'), { recursive: true }) + writeFileSync(join(root, 'a', 'snap.md'), 'real\n') + mkdirSync(join(root, 'd'), { recursive: true }) + symlinkSync(join(root, 'a', 'snap.md'), join(root, 'd', 'snap.md')) + mkdirSync(outside, { recursive: true }) + writeFileSync(join(outside, 'snap.md'), 'behind a symlinked dir\n') + symlinkSync(outside, join(root, 'linked-dir')) + mkdirSync(join(root, '.hidden'), { recursive: true }) + writeFileSync(join(root, '.hidden', 'snap.md'), 'hidden by dot\n') + return { root, clean: () => { rmSync(parent, { recursive: true, force: true }) } } +} + +describe('uniqueRepoFiles', () => { + it('enumerates ** matches without probing a symlinked file as a directory', () => { + const tree = makeTree() + try { + // Node's internal glob (from some 24.x releases) lstat-probes + // /snap.md while expanding `**/snap.md` and throws ENOTDIR. + // The walker must return the real files, deduplicated by canonical + // target, without throwing on any node version. + const files = uniqueRepoFiles(tree.root, ['**/snap.md']) + const rootReal = realpathSync(tree.root) + const reals = files.map(file => relative(rootReal, file.real)).sort() + expect(reals).toEqual([join('a', 'snap.md')]) + } finally { + tree.clean() + } + }) + + it('does not follow symlinked directories under ** or wildcard-match dot names', () => { + const tree = makeTree() + try { + const files = uniqueRepoFiles(tree.root, ['**/*.md']) + const paths = files.map(file => relative(tree.root, file.abs)).sort() + // The symlinked d/snap.md dedupes onto its a/snap.md target; the + // linked-dir and .hidden targets must not appear at all. + expect(paths).toEqual([join('a', 'snap.md')]) + } finally { + tree.clean() + } + }) + + it('follows a literal segment that names a symlinked directory', () => { + const tree = makeTree() + try { + // Node glob resolves literal segments with stat, so `linked-dir/**` and + // `linked-dir/*` enter the symlinked directory's target; `**` and + // wildcard segments resolve with dirent types and do not. + const files = uniqueRepoFiles(tree.root, ['linked-dir/**/*.md']) + expect(files.map(file => relative(tree.root, file.abs))).toEqual([join('linked-dir', 'snap.md')]) + expect(uniqueRepoFiles(tree.root, ['linked-dir/*.md']).map(file => relative(tree.root, file.abs))) + .toEqual([join('linked-dir', 'snap.md')]) + // A wildcard first segment never enters the symlinked directory. + expect(uniqueRepoFiles(tree.root, ['*/snap.md']).map(file => relative(tree.root, file.abs))) + .toEqual([join('a', 'snap.md')]) + } finally { + tree.clean() + } + }) + + it('follows repeated literal symlinked directories like node glob and terminates', () => { + const parent = mkdtempSync(join(tmpdir(), 'repo-files-cycle-')) + try { + const root = join(parent, 'root') + mkdirSync(join(root, 'a'), { recursive: true }) + writeFileSync(join(root, 'a', 'snap.md'), 'x\n') + symlinkSync(root, join(root, 'cyc')) + // Each literal `cyc` segment resolves through stat and enters the + // symlinked directory again, exactly as node glob does for a repeated + // literal; recursion stays bounded because each literal consumes one + // pattern segment and `**` only enters real directories. + expect(uniqueRepoFiles(root, ['cyc/**/snap.md']).map(file => relative(root, file.abs))) + .toEqual([join('cyc', 'a', 'snap.md')]) + expect(uniqueRepoFiles(root, ['cyc/cyc/**/snap.md']).map(file => relative(root, file.abs))) + .toEqual([join('cyc', 'cyc', 'a', 'snap.md')]) + expect(uniqueRepoFiles(root, ['cyc/cyc/cyc/**/snap.md']).map(file => relative(root, file.abs))) + .toEqual([join('cyc', 'cyc', 'cyc', 'a', 'snap.md')]) + } finally { + rmSync(parent, { recursive: true, force: true }) + } + }) + + it('reports a matched file canonical target for downstream existence checks', () => { + const tree = makeTree() + try { + const files = uniqueRepoFiles(tree.root, ['a/*.md']) + expect(files).toHaveLength(1) + expect(files[0]!.real).toBe(join(realpathSync(tree.root), 'a', 'snap.md')) + } finally { + tree.clean() + } + }) + + it('fails loudly on a broken symlink instead of shrinking the corpus', () => { + const tree = makeTree() + try { + // A healthy tree with symlinked files must not throw. + expect(() => uniqueRepoFiles(tree.root, ['a/*.md'])).not.toThrow() + } finally { + tree.clean() + } + const parent = mkdtempSync(join(tmpdir(), 'repo-files-broken-')) + try { + const root = join(parent, 'root') + mkdirSync(root, { recursive: true }) + writeFileSync(join(root, 'gone.md'), 'x\n') + symlinkSync(join(root, 'gone.md'), join(root, 'broken-link.md')) + rmSync(join(root, 'gone.md')) + // realpathSync on the matched broken link must throw, exactly as it did + // under the node-glob implementation, instead of silently shrinking the + // scanned corpus. + expect(() => uniqueRepoFiles(root, ['*.md'])).toThrow() + // A broken symlink under a literal non-final segment matches nothing, + // again as node glob silently returns no match for it. + symlinkSync(join(root, 'gone-dir'), join(root, 'broken-dir')) + expect(uniqueRepoFiles(root, ['broken-dir/*.md'])).toEqual([]) + } finally { + rmSync(parent, { recursive: true, force: true }) + } + }) + + it('rejects glob syntax the walker does not model instead of matching nothing', () => { + const tree = makeTree() + try { + // Node glob would interpret the bracket class; the walker must fail + // loudly rather than expand the pattern as a literal and quietly match + // nothing. + expect(() => uniqueRepoFiles(tree.root, ['**/*.[cm]d'])).toThrow(/does not model glob syntax/) + } finally { + tree.clean() + } + }) + + it('rejects a trailing ** segment instead of silently returning nothing', () => { + const tree = makeTree() + try { + expect(() => uniqueRepoFiles(tree.root, ['a/**'])).toThrow(/trailing \*\*/) + // A trailing slash yields an empty final segment that can never match. + expect(() => uniqueRepoFiles(tree.root, ['a/**/'])).toThrow(/empty segments/) + } finally { + tree.clean() + } + }) + + it('folds a . segment and rejects a .. segment like node glob semantics', () => { + const tree = makeTree() + try { + // Node glob normalizes a `.` segment away, so `./a/snap.md` matches + // a/snap.md instead of looking for a directory named `.`. + expect(uniqueRepoFiles(tree.root, ['./a/snap.md']).map(file => relative(tree.root, file.abs))) + .toEqual([join('a', 'snap.md')]) + expect(uniqueRepoFiles(tree.root, ['a/./snap.md']).map(file => relative(tree.root, file.abs))) + .toEqual([join('a', 'snap.md')]) + // A `..` segment escapes the scanned root; the walker must fail loudly + // rather than silently match nothing. + expect(() => uniqueRepoFiles(tree.root, ['a/../snap.md'])).toThrow(/does not model \.\. segments/) + } finally { + tree.clean() + } + }) +}) diff --git a/scripts/repo-files.ts b/scripts/repo-files.ts index 7c7aca276d..56d9cbf9f7 100644 --- a/scripts/repo-files.ts +++ b/scripts/repo-files.ts @@ -1,7 +1,7 @@ /** Shared repository file discovery and line-oriented reference scanning. */ -import { globSync, readFileSync, realpathSync } from 'node:fs' -import { relative, resolve, sep } from 'node:path' +import { readdirSync, readFileSync, realpathSync, statSync } from 'node:fs' +import { join, relative, resolve, sep } from 'node:path' /** One authored path plus its canonical target for symlink deduplication. */ export interface RepoFile { @@ -26,6 +26,173 @@ export function isArchivedAgentNotePath(path: string): boolean { return path.replaceAll('\\', '/').startsWith('.agents/notes/archived/') } +/** + * Whether a pattern segment matches a directory or file name. Supports `*` and + * `?` inside a segment and mirrors node's glob `dot: false`: a segment whose + * first character is a wildcard does not match dot names. `**` is handled as a + * whole segment by the walker, never here. + */ +function segmentMatches(pattern: string, name: string): boolean { + if (name.startsWith('.') && (pattern.startsWith('*') || pattern.startsWith('?'))) return false + let expression = '' + for (const character of pattern) { + if (character === '*') expression += '.*' + else if (character === '?') expression += '.' + else expression += character.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + } + return new RegExp(`^${expression}$`).test(name) +} + +/** + * Reject glob syntax the walker does not model. Node's `fs.glob` understands + * character classes, brace alternation, and extglobs; expanding those + * silently as literals would match nothing and quietly shrink a gate's + * corpus, so a pattern segment using them fails loudly instead. Pure literal + * segments must therefore contain none of the rejected metacharacters + * either, even where node glob would read them literally. + */ +const UNSUPPORTED_GLOB = /[[\]{}()!+@\\]/ + +function assertSupportedSegment(segment: string): void { + if (UNSUPPORTED_GLOB.test(segment)) { + throw new TypeError(`repo-files walker does not model glob syntax in segment: ${segment}`) + } +} + +/** + * Walk `root` matching one repository-relative glob without node's `fs.glob`. + * The repository's own walker exists because node's internal glob, from some + * 24.x releases, lstat-probes `/` for symlinked files + * while expanding `**` and throws ENOTDIR instead of skipping (observed on + * node 24.13.0 scanning `snapshots/acp/image-compaction`'s symlinked + * `system-prompt.expected.md`). The walker decides directoryhood from dirent + * types and stat results, never by probing a path under a file, so the same + * tree enumerates identically on every node version. + * + * Segment semantics: literal segments resolve through `stat`, so a literal + * naming a symlinked directory enters that directory exactly as node glob + * does — including a literal repeated across segments, which node glob + * resolves each time; wildcard segments and `**` resolve through dirent + * types, so they never enter symlinked directories and never match dot + * names. Node documents `follow: false` only for `**` expansion, so the + * wildcard-side behavior is this walker's own contract, pinned by + * repo-files.spec.ts, rather than a cross-version node guarantee; the four + * consuming gates' current patterns contain no wildcard segment over a + * symlinked directory, so the corpus is unchanged. `**` spans zero or more + * directories. The final segment matches files and symlinks; a broken or + * cyclic symlink then fails loudly in the caller's realpathSync rather than + * shrinking the scanned corpus, while a broken symlink under a literal + * non-final segment matches nothing, again as node glob does. Traversal + * terminates without a visited set: each literal segment consumes one pattern + * segment per recursion, and `**` recurses only into real directories, which + * form a finite tree because symlinked directories are never expanded by it. + * Pattern segments support `*`, `?`, and literals that contain none of + * `[]{}()!+@\`; other node-glob syntax, including a trailing `**`, `..`, and + * empty segments, is rejected loudly up front, while a `.` segment is folded + * away exactly as node glob normalizes it. Returns repository-relative slash + * paths, sorted. + */ +function expandGlob(root: string, pattern: string): string[] { + const segments: string[] = [] + for (const segment of pattern.split('/')) { + if (segment === '.') { + // Node glob normalizes a `.` segment away; dropping it here keeps + // `./README.md` and `a/./b` matching exactly as node glob does instead + // of silently matching nothing. + continue + } + if (segment === '..') { + // A `..` segment escapes the scanned root and interacts with `**` in + // ways node glob special-cases; no gate pattern uses one, so the walker + // rejects the form loudly instead of silently matching nothing. + throw new TypeError(`repo-files walker does not model .. segments in pattern: ${pattern}`) + } + if (segment === '') { + // A leading, doubled, or trailing slash yields an empty segment that + // can never match an entry; node glob would tolerate the form, so the + // walker must reject it loudly instead of silently returning nothing. + throw new TypeError(`repo-files walker does not model empty segments in pattern: ${pattern}`) + } + segments.push(segment) + } + if (segments.length === 0) { + throw new TypeError(`repo-files walker does not model a pattern with no segments: ${pattern}`) + } + for (const segment of segments) { + if (segment !== '**') assertSupportedSegment(segment) + } + // A trailing `**` would match files, directories, and symlinks below the + // prefix; the walker models `**` only as a directory-spanning segment, so + // it must reject the form loudly instead of silently returning nothing. + if (segments[segments.length - 1] === '**') { + throw new TypeError(`repo-files walker does not model a trailing ** segment in pattern: ${pattern}`) + } + const out: string[] = [] + + const visit = (dirAbs: string, dirRel: string, index: number): void => { + if (index >= segments.length) return + if (segments[index] !== '**') { + visitSegment(dirAbs, dirRel, index) + return + } + // `**` consumes zero directories here and one directory per recursion. + visitSegment(dirAbs, dirRel, index + 1) + for (const entry of readdirSync(dirAbs, { withFileTypes: true })) { + if (entry.name.startsWith('.') || !entry.isDirectory()) continue + visit(join(dirAbs, entry.name), dirRel === '.' ? entry.name : `${dirRel}/${entry.name}`, index) + } + } + + const visitSegment = (dirAbs: string, dirRel: string, index: number): void => { + if (index >= segments.length) return + const segment = segments[index] + if (segment === undefined) return + if (segment === '**') { + visit(dirAbs, dirRel, index) + return + } + const last = index === segments.length - 1 + for (const entry of readdirSync(dirAbs, { withFileTypes: true })) { + if (!segmentMatches(segment, entry.name)) continue + const childAbs = join(dirAbs, entry.name) + const childRel = dirRel === '.' ? entry.name : `${dirRel}/${entry.name}` + if (last) { + // Files and symlinks match; a broken or cyclic symlink then fails + // loudly in the caller's realpathSync exactly as node glob did, + // rather than silently shrinking the scanned corpus. + if (entry.isFile() || entry.isSymbolicLink()) out.push(childRel) + continue + } + if (entry.isDirectory()) { + visitSegment(childAbs, childRel, index + 1) + continue + } + // A literal non-final segment resolves through stat like node glob's, + // so it enters a symlinked directory; wildcard segments never reach + // this branch because they are matched from dirent types above. + if (!entry.isSymbolicLink() || hasWildcard(segment)) continue + let target: ReturnType + try { + target = statSync(childAbs) + } catch { + // A broken symlink matches nothing under a literal segment, as node + // glob silently returns no match for it. + continue + } + if (!target.isDirectory()) continue + visitSegment(childAbs, childRel, index + 1) + } + } + + visit(root, '.', 0) + return out.sort() +} + +/** Whether a pattern segment contains `*` or `?` and is therefore wildcard. */ +function hasWildcard(segment: string): boolean { + return segment.includes('*') || segment.includes('?') +} + /** * Expand repository-relative globs and deduplicate symlinked files. * @param root - absolute repository root. @@ -41,8 +208,7 @@ export function uniqueRepoFiles( const seen = new Set() const files: RepoFile[] = [] for (const pattern of patterns) { - for (const match of globSync(pattern, { cwd: root })) { - const repoPath = match.split(sep).join('/') + for (const repoPath of expandGlob(root, pattern)) { if (isExcluded(repoPath)) continue const abs = resolve(root, repoPath) const real = realpathSync(abs) From acc8535390e9e74f4be33b66298b7dfd28c618e0 Mon Sep 17 00:00:00 2001 From: Chinesezjc Date: Wed, 9 Sep 2026 17:31:36 +0800 Subject: [PATCH 14/52] docs(ci): record the canary failover value and the glob fix across internal notes The failover runbook, the node-compatibility note, the native-Windows note, and the serial-reference note record the third variable value's scope and exclusions (bilingual, pairing re-recorded); a new implemented process note owns the value's participating set, the dormant-by-default canary posture, and the walker-fix rationale. .github/AGENTS.md points at both notes. --- ...rial-cross-platform-ci-reference.i18n.yaml | 4 +-- ...7-21-serial-cross-platform-ci-reference.md | 2 +- ...1-serial-cross-platform-ci-reference.zh.md | 2 +- .../2026-07-26-ci-failover-runbook.i18n.yaml | 4 +-- .../process/2026-07-26-ci-failover-runbook.md | 10 +++---- .../2026-07-26-ci-failover-runbook.zh.md | 10 +++---- ...8-native-windows-pull-request-ci.i18n.yaml | 4 +-- ...26-08-08-native-windows-pull-request-ci.md | 2 +- ...08-08-native-windows-pull-request-ci.zh.md | 2 +- ...06-node-compatibility-selfhosted.i18n.yaml | 4 +-- ...026-09-06-node-compatibility-selfhosted.md | 2 +- ...-09-06-node-compatibility-selfhosted.zh.md | 2 +- ...26-09-09-blacksmith-failover-leg.i18n.yaml | 6 +++++ .../2026-09-09-blacksmith-failover-leg.md | 27 +++++++++++++++++++ .../2026-09-09-blacksmith-failover-leg.zh.md | 27 +++++++++++++++++++ .github/AGENTS.md | 2 +- 16 files changed, 85 insertions(+), 25 deletions(-) create mode 100644 .agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.i18n.yaml create mode 100644 .agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md create mode 100644 .agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.zh.md diff --git a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.i18n.yaml b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.i18n.yaml index 889010ca8d..2ce7922815 100644 --- a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md -2026-07-21-serial-cross-platform-ci-reference.md: edb81b643d0cef2e5bc807005a9016324b8430ab -2026-07-21-serial-cross-platform-ci-reference.zh.md: 41fd9c032038f2a312978acf995febfdab34aeaa +2026-07-21-serial-cross-platform-ci-reference.md: 24022fea271d677a4588bd5dc9c7cb5b417ca8b7 +2026-07-21-serial-cross-platform-ci-reference.zh.md: c9fbc84d8ff91803acc6bcd008607fc03136b832 diff --git a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md index edb81b643d..24022fea27 100644 --- a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md +++ b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.md @@ -28,7 +28,7 @@ The standalone [Sandbox](../../../../.github/workflows/sandbox.yml) workflow bel Master reference jobs are diagnostic and do not participate in the pull request's required `all checks passed` result. The ci-master and Sandbox workflows keep their cross-platform references on master pushes. Performance is evaluated from completed hosted-job timestamps and reported as a measurement; it is not encoded as a `timeout-minutes` value. -The active serial references run on the self-hosted `vm-backup` (`serial / linux`) and `dsh-win-ci` (`serial / windows`) pools; the one remaining disabled hosted serial reference (`serial-macos`) uses `macos-latest`, and there is no standard-hosted `serial / linux` label. The master-only Wine job runs on `ubuntu-latest`, while the pull-request native jobs use the hosted `dsh-windows-2025-16core` runner under normal operation and the self-hosted `[self-hosted, dsh-win-ci, windows]` pool under failover (see the [failover runbook](2026-07-26-ci-failover-runbook.md)), with build and targeted process checks required under the [native Windows decision](2026-08-08-native-windows-pull-request-ci.md). Required pull-request jobs use portable standard capacity under the [required-CI decision](../../archived/process/2026-07-23-portable-required-pull-request-ci.md). Higher-core hosted runners remain manual benchmarks because a correctness path must remain runnable without repository-external runner configuration. +The active serial references run on the self-hosted `vm-backup` (`serial / linux`) and `dsh-win-ci` (`serial / windows`) pools; the one remaining disabled hosted serial reference (`serial-macos`) uses `macos-latest`, and there is no standard-hosted `serial / linux` label. The master-only Wine job runs on `ubuntu-latest`, while the pull-request native jobs use the hosted `dsh-windows-2025-16core` runner under normal operation, the self-hosted `[self-hosted, dsh-win-ci, windows]` pool under the `selfhosted` failover value, and Blacksmith's Windows runners under the `blacksmith` value (see the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md); see the [failover runbook](2026-07-26-ci-failover-runbook.md)), with build and targeted process checks required under the [native Windows decision](2026-08-08-native-windows-pull-request-ci.md). Required pull-request jobs use portable standard capacity under the [required-CI decision](../../archived/process/2026-07-23-portable-required-pull-request-ci.md). Higher-core hosted runners remain manual benchmarks because a correctness path must remain runnable without repository-external runner configuration. ## Alternatives considered diff --git a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md index 41fd9c0320..c9fbc84d8f 100644 --- a/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md +++ b/.agents/notes/implemented/process/2026-07-21-serial-cross-platform-ci-reference.zh.md @@ -28,7 +28,7 @@ macOS 参考流程使用 fork 进程运行常规 Vitest 项目。macOS arm64 上 master 分支的参考作业仅用于诊断,不参与拉取请求所要求的 `all checks passed` 结果。ci-master 与 Sandbox 工作流把跨平台参考流程保留在 master 推送上。系统根据已完成托管作业的时间戳评估性能,并将其报告为测量结果,而不是写成 `timeout-minutes` 值。 -当前启用的参考流程运行在公司自有 `vm-backup`(`serial / linux`)与 `dsh-win-ci`(`serial / windows`)自托管池上;唯一剩余的禁用托管参考作业(`serial-macos`)使用 `macos-latest`,且不存在标准托管的 `serial / linux` 标签。仅 master 触发的 Wine 作业在 `ubuntu-latest` 上运行,而拉取请求原生作业在正常运行下使用托管的 `dsh-windows-2025-16core` 运行器,故障切换时使用自托管 `[self-hosted, dsh-win-ci, windows]` 池(参见[故障切换手册](2026-07-26-ci-failover-runbook.zh.md)),依据[原生 Windows 决策](2026-08-08-native-windows-pull-request-ci.zh.md),其中构建与定向进程检查参与必需聚合流程。依据[必需 CI 决策](../../archived/process/2026-07-23-portable-required-pull-request-ci.md),拉取请求必需作业使用可移植的标准容量。更高核心数的托管运行器仍仅用于手动基准测试,因为正确性路径必须无需仓库外部的运行器配置即可运行。 +当前启用的参考流程运行在公司自有 `vm-backup`(`serial / linux`)与 `dsh-win-ci`(`serial / windows`)自托管池上;唯一剩余的禁用托管参考作业(`serial-macos`)使用 `macos-latest`,且不存在标准托管的 `serial / linux` 标签。仅 master 触发的 Wine 作业在 `ubuntu-latest` 上运行,而拉取请求原生作业在正常运行下使用托管的 `dsh-windows-2025-16core` 运行器,在 `selfhosted` 故障切换取值下使用自托管 `[self-hosted, dsh-win-ci, windows]` 池,在 `blacksmith` 取值下使用 Blacksmith 的 Windows 运行器(见 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md);另见[故障切换手册](2026-07-26-ci-failover-runbook.zh.md)),依据[原生 Windows 决策](2026-08-08-native-windows-pull-request-ci.zh.md),其中构建与定向进程检查参与必需聚合流程。依据[必需 CI 决策](../../archived/process/2026-07-23-portable-required-pull-request-ci.md),拉取请求必需作业使用可移植的标准容量。更高核心数的托管运行器仍仅用于手动基准测试,因为正确性路径必须无需仓库外部的运行器配置即可运行。 ## 曾考虑的替代方案 diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml index 90fdf49b49..ed606bb0ef 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md -2026-07-26-ci-failover-runbook.md: f24cb8b8239141cd1ccf468a566dba620dd3cfdd -2026-07-26-ci-failover-runbook.zh.md: 57c4a92a3af720d9b11b7a1ce7a1515b83c77339 +2026-07-26-ci-failover-runbook.md: a114d9bd25b2d07c51205f91b175eaa6f498c0e8 +2026-07-26-ci-failover-runbook.zh.md: 677e757d55307e2f07de7fb139ec95206c908066 diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md index f24cb8b823..a114d9bd25 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md @@ -10,7 +10,7 @@ The three required Linux worker jobs in [CI](../../../../.github/workflows/ci.ym ## Decision -The three primary Linux jobs (`node-24`, `node-24-coverage`, `node-24-consumers`), the three `node-compat` matrix entries, and `all-checks-passed` resolve through `DSH_CI_FAILOVER_LINUX`; the native Windows jobs resolve through `DSH_CI_FAILOVER_WINDOWS`. A platform switch does not redirect the other platform. Set to `selfhosted` by a repository writer, the applicable trusted jobs select `vm-backup` or `dsh-win-ci`; otherwise they retain their workflow-defined hosted fallbacks. Node compatibility jobs require a same-repository, non-fork head and a non-Dependabot author, use isolated runtime setup, and retain `ubuntu-latest` fallback. Linux failover bounds snapshot concurrency and skips hosted package-cache restores. The verdict follows its workers so it does not remain queued on an unavailable hosted pool. Each switch is writer-manageable repository state, not a merge, so it works while checks are red. The `serial / linux (self-hosted standby)` and `serial / windows (self-hosted standby)` lanes re-prove the complete unsharded aggregates on master pushes. +The three primary Linux jobs (`node-24`, `node-24-coverage`, `node-24-consumers`), the three `node-compat` matrix entries, and `all-checks-passed` resolve through `DSH_CI_FAILOVER_LINUX`; the native Windows jobs resolve through `DSH_CI_FAILOVER_WINDOWS`. A platform switch does not redirect the other platform. Set to `selfhosted` by a repository writer, the applicable trusted jobs select `vm-backup` or `dsh-win-ci`; the `blacksmith` value routes the participating jobs per the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md); unset or any other value retains the workflow-defined hosted fallbacks. Node compatibility jobs require a same-repository, non-fork head and a non-Dependabot author, use isolated runtime setup, and retain the `ubuntu-latest` fallback under unset and non-special values; the blacksmith branch carries none of those predicates. Under the `selfhosted` value, Linux failover bounds snapshot concurrency and skips hosted package-cache restores. The verdict follows its workers so it does not remain queued on an unavailable hosted pool. Each switch is writer-manageable repository state, not a merge, so it works while checks are red. The `serial / linux (self-hosted standby)` and `serial / windows (self-hosted standby)` lanes re-prove the complete unsharded aggregates on master pushes. `ci-master.yml` exempts exactly one event from `cancel-in-progress` (`${{ github.event_name != 'push' }}`), so one master push does not cancel the drill still running from the previous one. Each drill runs its complete unsharded aggregate with one gate worker, which takes longer than the interval between master merges; under unconditional cancellation a drill is superseded before reaching a verdict and the lane yields no readiness evidence for a responder to check. @@ -36,9 +36,9 @@ The two switches are independent: flip only the one whose platform is degraded. 1. Repository **Settings → Secrets and variables → Actions → Variables → New repository variable**: name `DSH_CI_FAILOVER_LINUX` (Linux pool outage) or `DSH_CI_FAILOVER_WINDOWS` (Windows pool outage), value `selfhosted`. 2. Retrigger the required jobs so they re-resolve their pool. Jobs already **queued** for the hosted labels do not retarget and cannot be re-run in place, so for the documented indefinite-queue outage, cancel the stuck run and re-run all jobs, or push a new commit; "Re-run failed jobs" only helps once a job has actually failed rather than queued. -3. That is the entire switch. Under Linux failover the workflow also drops `DSH_SNAPSHOT_MAX_CONCURRENCY` to 12 for the shared VM and skips the hosted-path pnpm cache restores because the VM's persistent store serves warm installs. Coverage uses the same four single-worker instrumented partitions and two exempt workers on both Linux pools. The Windows switch has no concurrency or cache branches; it only retargets the native Windows jobs' pool. +3. That is the entire switch. Under the `selfhosted` Linux failover value the workflow also drops `DSH_SNAPSHOT_MAX_CONCURRENCY` to 12 for the shared VM and skips the hosted-path pnpm cache restores because the VM's persistent store serves warm installs. Coverage uses the same four single-worker instrumented partitions and two exempt workers on both Linux pools. The Windows switch has no concurrency or cache branches; it only retargets the native Windows jobs' pool. -**Dependabot exception.** Both switches' selectors deliberately exclude `dependabot[bot]`: under failover, Dependabot PRs stay queued for the hosted pool rather than executing dependency-supplied code on the persistent VMs. A Dependabot PR that remains queued during an outage is expected behavior, not a failed switch; it completes when the hosted pool recovers. +**Dependabot exception.** Both switches' `selfhosted` legs deliberately exclude `dependabot[bot]`: under self-hosted failover, Dependabot PRs stay queued for the hosted pool rather than executing dependency-supplied code on the persistent VMs. A Dependabot PR that remains queued during an outage is expected behavior, not a failed switch; it completes when the hosted pool recovers. The `blacksmith` value's branches carry no such exclusion, because Blacksmith runners are ephemeral (see the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md)). **Who can flip the variable.** GitHub's API lets any collaborator with write access manage repository variables, so each switch is writer-level, not strictly admin-only. In this repository's trust model that is not an escalation: the runner groups admit all workflows of this private, fork-disabled repository (a deliberate trade to make PR-ref failover possible at all), so any writer could already reach the VMs by pushing a branch workflow. The boundary against untrusted code is repository membership; the variables only route work for members. @@ -49,11 +49,11 @@ Capacity includes the master standby, main-CI jobs, and three release-rehearsal ### Switch back -Delete the `DSH_CI_FAILOVER_LINUX` or `DSH_CI_FAILOVER_WINDOWS` variable (or set it to anything other than `selfhosted`). New runs resolve back to their hosted pools. Remove any extra instances that were registered during the incident. +Delete the `DSH_CI_FAILOVER_LINUX` or `DSH_CI_FAILOVER_WINDOWS` variable (or set it to any value other than `selfhosted` or `blacksmith`). New runs resolve back to their hosted pools. Setting it to `blacksmith` keeps the jobs on Blacksmith until the value changes. Remove any extra instances that were registered during the incident. ### Trust boundary -The variables are writer-manageable repository state; a pull request event itself can neither set them nor read a different value into effect, and the selector expressions live in workflow definitions. Note that under failover, `pull_request` runs execute the PR merge ref's own workflow definition — the boundary against untrusted code is repository membership (private, forking disabled, Dependabot excluded by the selectors), not the variable. Note on runner-group policy: pinning the runner group to the master-ref workflow is **incompatible** with this failover — the failover jobs, including the Node compatibility matrix, are `pull_request` runs evaluated from PR merge refs, and a master-pinned group leaves them queued (observed live on 2026-07-27; the group was widened to all workflows of this repository to unblock the switch). A stricter runner-side policy therefore costs PR failover; the shipped posture accepts repository-scoped, all-workflow group access. +The variables are writer-manageable repository state; a pull request event itself can neither set them nor read a different value into effect, and the selector expressions live in workflow definitions. Note that under failover, `pull_request` runs execute the PR merge ref's own workflow definition — the boundary against untrusted code is repository membership (private, forking disabled, Dependabot excluded by the `selfhosted` legs; the `blacksmith` legs carry no exclusion), not the variable. Note on runner-group policy: pinning the runner group to the master-ref workflow is **incompatible** with this failover — the failover jobs, including the Node compatibility matrix, are `pull_request` runs evaluated from PR merge refs, and a master-pinned group leaves them queued (observed live on 2026-07-27; the group was widened to all workflows of this repository to unblock the switch). A stricter runner-side policy therefore costs PR failover; the shipped posture accepts repository-scoped, all-workflow group access. ## Alternatives considered diff --git a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md index 57c4a92a3a..677e757d55 100644 --- a/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md +++ b/.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -三个主要 Linux 作业(`node-24`、`node-24-coverage`、`node-24-consumers`)、三个 `node-compat` 矩阵条目和 `all-checks-passed` 通过 `DSH_CI_FAILOVER_LINUX` 解析;原生 Windows 作业通过 `DSH_CI_FAILOVER_WINDOWS` 解析。一个平台的开关不会重定向另一个平台。仓库写者将变量设为 `selfhosted` 时,适用的可信作业选择 `vm-backup` 或 `dsh-win-ci`;否则保留工作流定义的托管回退。Node 兼容性作业要求同仓库且非 fork 的头部以及非 Dependabot 作者,使用隔离运行时设置,并保留 `ubuntu-latest` 回退。Linux 故障切换限制快照并发,并跳过托管软件包缓存恢复。判定作业跟随工作作业,避免继续在不可用的托管池排队。每个开关都是写者可管理的仓库状态而非一次合并,因此在检查失败时仍然有效。`serial / linux (self-hosted standby)` 与 `serial / windows (self-hosted standby)` 通道在 master 推送上重新验证完整的未分片聚合流程。 +三个主要 Linux 作业(`node-24`、`node-24-coverage`、`node-24-consumers`)、三个 `node-compat` 矩阵条目和 `all-checks-passed` 通过 `DSH_CI_FAILOVER_LINUX` 解析;原生 Windows 作业通过 `DSH_CI_FAILOVER_WINDOWS` 解析。一个平台的开关不会重定向另一个平台。仓库写者将变量设为 `selfhosted` 时,适用的可信作业选择 `vm-backup` 或 `dsh-win-ci`;`blacksmith` 取值按 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md) 路由参与切换的作业;未设置或任何其它值保留工作流定义的托管回退。Node 兼容性作业要求同仓库且非 fork 的头部以及非 Dependabot 作者,使用隔离运行时设置,并在未设置与非特殊值下保留 `ubuntu-latest` 回退;blacksmith 分支不带上述任何条件。在 `selfhosted` 取值下,Linux 故障切换会限制快照并发,并跳过托管软件包缓存恢复。判定作业跟随工作作业,避免继续在不可用的托管池排队。每个开关都是写者可管理的仓库状态而非一次合并,因此在检查失败时仍然有效。`serial / linux (self-hosted standby)` 与 `serial / windows (self-hosted standby)` 通道在 master 推送上重新验证完整的未分片聚合流程。 `ci-master.yml` 只豁免一个事件不做取消(`${{ github.event_name != 'push' }}`),因此一次 master 推送不会取消上一次推送留下的、仍在运行的演练。每次演练以单门禁工作进程执行完整的未分片聚合流程,耗时长于 master 合并的间隔;在无条件取消下,演练会在得出结论前被后续运行取代,该通道无法产出供响应者查看的就绪证据。 @@ -36,9 +36,9 @@ Status: implemented 1. 仓库 **Settings → Secrets and variables → Actions → Variables → New repository variable**:名称 `DSH_CI_FAILOVER_LINUX`(Linux 池故障)或 `DSH_CI_FAILOVER_WINDOWS`(Windows 池故障),值 `selfhosted`。 2. 重新触发必需作业,使其重新解析运行器池。已经为托管标签**排队**的作业不会重定向,也无法原地 re-run,因此对于本手册所述的无限排队故障,应取消卡住的运行并 re-run all jobs,或推送一个新提交;“Re-run failed jobs”只有在作业真正失败(而非仍在排队)时才有用。 -3. 切换到此完成。Linux 故障切换状态下,工作流还会把 `DSH_SNAPSHOT_MAX_CONCURRENCY` 降为 12,以限制共享虚拟机上的争抢,并跳过托管路径的 pnpm 缓存恢复,因为虚拟机的持久 store 会直接提供热安装。覆盖率在两个 Linux 池上都使用 4 个单 worker 插桩分区与 2 个豁免 worker。Windows 开关没有并发或缓存分支;它只重定向原生 Windows 作业的运行器池。 +3. 切换到此完成。在 `selfhosted` 的 Linux 故障切换取值下,工作流还会把 `DSH_SNAPSHOT_MAX_CONCURRENCY` 降为 12,以限制共享虚拟机上的争抢,并跳过托管路径的 pnpm 缓存恢复,因为虚拟机的持久 store 会直接提供热安装。覆盖率在两个 Linux 池上都使用 4 个单 worker 插桩分区与 2 个豁免 worker。Windows 开关没有并发或缓存分支;它只重定向原生 Windows 作业的运行器池。 -**Dependabot 例外。**两个开关的选择器都刻意排除了 `dependabot[bot]`:故障切换期间,Dependabot 拉取请求继续在托管池排队,而不是把依赖项提供的代码放到持久化虚拟机上执行。故障期间 Dependabot PR 持续排队是预期行为而非切换失败;托管池恢复后它会自行完成。 +**Dependabot 例外。**两个开关的 `selfhosted` 腿都刻意排除 `dependabot[bot]`:自托管故障切换期间,Dependabot 拉取请求继续在托管池排队,而不是把依赖项提供的代码放到持久化虚拟机上执行。故障期间 Dependabot PR 持续排队是预期行为而非切换失败;托管池恢复后它会自行完成。`blacksmith` 取值下的分支不带此类排除,因为 Blacksmith 运行器是临时的(见 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md))。 **谁能扳动这个变量。**GitHub 的 API 允许任何具有写权限的协作者管理仓库变量,因此每个开关实际是写者级而非严格的管理员级。在本仓库的信任模型下这并不构成升权:runner group 接纳本私有、禁 fork 仓库的全部工作流(这是让 PR 引用的故障切换得以成立的刻意取舍),因此任何写者本就可以通过推送分支工作流触达这台虚拟机。抵御不可信代码的边界是仓库成员资格;变量只是为成员路由工作。 @@ -49,11 +49,11 @@ Linux 开关启用期间,容量需覆盖 master 热备、主 CI 作业,以 ### 切回 -删除 `DSH_CI_FAILOVER_LINUX` 或 `DSH_CI_FAILOVER_WINDOWS` 变量(或改为 `selfhosted` 以外的任何值),新的运行即解析回各自的托管池。若故障期间追加注册过实例,将其移除。 +删除 `DSH_CI_FAILOVER_LINUX` 或 `DSH_CI_FAILOVER_WINDOWS` 变量(或改为 `selfhosted` 与 `blacksmith` 之外的任何值),新的运行即解析回各自的托管池。设为 `blacksmith` 会让作业留在 Blacksmith,直到该值改变。若故障期间追加注册过实例,将其移除。 ### 信任边界 -这些变量是写者可管理的仓库状态;`pull_request` 事件本身既不能设置它们,也不能让不同的值生效,选择器表达式存在于工作流定义中。需要注意:故障切换期间,`pull_request` 运行执行的是 PR merge 引用自带的工作流定义——抵御不可信代码的边界是仓库成员资格(私有、禁 fork、选择器排除 Dependabot),而非该变量。关于 runner group 策略的说明:把 runner group 绑定到 master 引用的工作流与本故障切换机制**不兼容**——包括 Node 兼容性矩阵在内的故障切换作业是从 PR merge 引用求值的 `pull_request` 运行,master 绑定的组会让它们持续排队(2026-07-27 实际故障中亲历;当时将组放宽为本仓库全部工作流才疏通了切换)。更严格的运行器侧策略以牺牲 PR 故障切换为代价;当前采用的形态是仓库范围、全工作流的组访问。 +这些变量是写者可管理的仓库状态;`pull_request` 事件本身既不能设置它们,也不能让不同的值生效,选择器表达式存在于工作流定义中。需要注意:故障切换期间,`pull_request` 运行执行的是 PR merge 引用自带的工作流定义——抵御不可信代码的边界是仓库成员资格(私有、禁 fork、Dependabot 由 `selfhosted` 腿排除;`blacksmith` 腿不带排除),而非该变量。关于 runner group 策略的说明:把 runner group 绑定到 master 引用的工作流与本故障切换机制**不兼容**——包括 Node 兼容性矩阵在内的故障切换作业是从 PR merge 引用求值的 `pull_request` 运行,master 绑定的组会让它们持续排队(2026-07-27 实际故障中亲历;当时将组放宽为本仓库全部工作流才疏通了切换)。更严格的运行器侧策略以牺牲 PR 故障切换为代价;当前采用的形态是仓库范围、全工作流的组访问。 ## 曾考虑的替代方案 diff --git a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.i18n.yaml b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.i18n.yaml index 56858d05b2..a542599011 100644 --- a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.i18n.yaml +++ b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.md -2026-08-08-native-windows-pull-request-ci.md: 690f8e6f9b13fa7e72240a42ff482bd83f9088b0 -2026-08-08-native-windows-pull-request-ci.zh.md: 9efa3cbcf33b6c12e4eed253b6a0546c79b768fe +2026-08-08-native-windows-pull-request-ci.md: e4fc7cab8c274148191632e8cc125ac75f2ec1d5 +2026-08-08-native-windows-pull-request-ci.zh.md: 27ad602c3748f2920e6b63f271a6a38b11c0ab77 diff --git a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.md b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.md index 690f8e6f9b..e4fc7cab8c 100644 --- a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.md +++ b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.md @@ -14,7 +14,7 @@ A coverage audit found that stale branch state had restored temporary exclusions The master-only `windows` job in [ci-master.yml](../../../../.github/workflows/ci-master.yml) runs `windows node 24 / wine` on `ubuntu-latest`. It retains the checksum-verified Windows Node, Wine apt and pnpm caches, a hoisted install confined to a workspace snapshot, and the [shared Wine gate script](../../../../scripts/wine-windows-gates.sh) that runs the workspace build and production site. Node distribution transfers use bounded retries; when nodejs.org stalls on the large archive, a range-capable transport mirror resumes the same bytes, but nodejs.org remains the version and SHA-256 authority and the archive is never promoted before that checksum passes. Wine is outside the PR aggregate under the [master-only platform policy](2026-09-06-master-only-platform-ci.md). The [archived Wine experiment](../../archived/process/2026-07-27-wine-windows-gates-experiment.md) preserves its measured trade-offs, while this note owns the current dual topology. -Every pull request also starts four independent native jobs on the organization-owned `dsh-windows-2025-16core` runner: `windows-build`, `windows-coverage`, `windows-native-tests`, and `windows-observational`. Each job enables Developer Mode for workspace symlinks, provisions the repository-pinned pnpm through `pnpm/action-setup`, performs an immutable install without a transferred store archive, and runs its inventory under native PowerShell. The Windows failover variable retargets all four jobs to the in-house pool. Per-job deadlines range from 60 to 120 minutes and bound stuck work without treating a performance target as a correctness deadline. +Every pull request also starts four independent native jobs on the organization-owned `dsh-windows-2025-16core` runner: `windows-build`, `windows-coverage`, `windows-native-tests`, and `windows-observational`. Each job enables Developer Mode for workspace symlinks, provisions the repository-pinned pnpm through `pnpm/action-setup`, performs an immutable install without a transferred store archive, and runs its inventory under native PowerShell. The Windows failover variable (`DSH_CI_FAILOVER_WINDOWS`) retargets all four jobs to the in-house pool under `selfhosted` and to Blacksmith's Windows runners under `blacksmith` (see the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md)). Per-job deadlines range from 60 to 120 minutes and bound stuck work without treating a performance target as a correctness deadline. `windows-build` and `windows-native-tests` are dependencies of `all checks passed`; their workspace-build and targeted native-process results are blocking. `windows-coverage` remains an ordinary job but is absent from aggregate `needs`, so its 100%-per-file result stays red and visible without delaying the required verdict. `windows-observational` is also absent from aggregate `needs` and uses `continue-on-error` because Linux owns the blocking static, documentation, package, and built-artifact verdicts. diff --git a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.zh.md b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.zh.md index 9efa3cbcf3..27ad602c37 100644 --- a/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.zh.md +++ b/.agents/notes/implemented/process/2026-08-08-native-windows-pull-request-ci.zh.md @@ -14,7 +14,7 @@ Wine 在 Linux 内核与区分大小写的 ext4 之上采用 hoisted 依赖布 [ci-master.yml](../../../../.github/workflows/ci-master.yml) 中仅 master 触发的 `windows` 作业在 `ubuntu-latest` 上运行 `windows node 24 / wine`。它保留经过校验和验证的 Windows Node、Wine apt 与 pnpm 缓存、仅限工作区快照的 hoisted 安装,以及运行工作区构建与生产网站的[共享 Wine 门禁脚本](../../../../scripts/wine-windows-gates.sh)。Node 分发文件传输采用有界重试;nodejs.org 的大文件传输停滞时,由支持范围请求的传输镜像续传相同字节,但版本和 SHA-256 权威仍属于 nodejs.org,归档通过该校验前绝不会投入使用。根据[仅 master 平台策略](2026-09-06-master-only-platform-ci.zh.md),Wine 不参与 PR 聚合。[已归档的 Wine 实验](../../archived/process/2026-07-27-wine-windows-gates-experiment.md)保留其实测取舍,而本文负责当前双通道拓扑。 -每个拉取请求还会在组织自有的 `dsh-windows-2025-16core` 运行器上启动 4 个相互独立的原生作业:`windows-build`、`windows-coverage`、`windows-native-tests` 与 `windows-observational`。每个作业都会为工作区符号链接启用开发人员模式,通过 `pnpm/action-setup` 提供仓库固定版本的 pnpm,在不传输 store 归档的情况下执行不可变安装,并在原生 PowerShell 下运行自己的清单。Windows 故障切换变量会把这 4 个作业全部重定向到公司内部运行器池。各作业采用 60 至 120 分钟的截止时间,以约束卡住的工作,同时不把性能目标当作正确性截止时间。 +每个拉取请求还会在组织自有的 `dsh-windows-2025-16core` 运行器上启动 4 个相互独立的原生作业:`windows-build`、`windows-coverage`、`windows-native-tests` 与 `windows-observational`。每个作业都会为工作区符号链接启用开发人员模式,通过 `pnpm/action-setup` 提供仓库固定版本的 pnpm,在不传输 store 归档的情况下执行不可变安装,并在原生 PowerShell 下运行自己的清单。Windows 故障切换变量(`DSH_CI_FAILOVER_WINDOWS`)在 `selfhosted` 下把这 4 个作业全部重定向到公司内部运行器池,在 `blacksmith` 下重定向到 Blacksmith 的 Windows 运行器(见 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md))。各作业采用 60 至 120 分钟的截止时间,以约束卡住的工作,同时不把性能目标当作正确性截止时间。 `windows-build` 与 `windows-native-tests` 是 `all checks passed` 的依赖项;其工作区构建和定向原生进程结果具有阻断性。`windows-coverage` 仍是常规作业,但不在聚合流程的 `needs` 中,因此逐文件 100% 覆盖率结果会保持红灯并可见,却不会延迟必需判定。`windows-observational` 同样不在聚合流程的 `needs` 中,并使用 `continue-on-error`,因为静态检查、文档、包与构建产物的阻断性判定由 Linux 负责。 diff --git a/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.i18n.yaml b/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.i18n.yaml index 1cde51d814..397723916f 100644 --- a/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.i18n.yaml +++ b/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.md -2026-09-06-node-compatibility-selfhosted.md: c78092834123b837d100814be9beba52c1a41397 -2026-09-06-node-compatibility-selfhosted.zh.md: 6dcff8aa197c0995e4e90d2d56179340a41bc783 +2026-09-06-node-compatibility-selfhosted.md: c361d21d3e1093dd5c87bf2ba085bdd1acacb5d8 +2026-09-06-node-compatibility-selfhosted.zh.md: 80a9d8519d6084f5e01944b277882a51b2291e94 diff --git a/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.md b/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.md index c780928341..c361d21d3e 100644 --- a/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.md +++ b/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.md @@ -10,7 +10,7 @@ The Node 22.19, 24.9, and 26 compatibility jobs consume hosted Linux minutes eve ## Decision -[CI](../../../../.github/workflows/ci.yml) applies the Linux failover variable to these three jobs, requiring a non-Dependabot author and a non-fork head repository matching the current repository. The standard hosted fallback remains available. These predicates constrain this job, not every workflow admitted to the pool. Both repository identity and fork status remain explicit to preserve its trust restriction if repository settings change; existing sibling selectors are outside this migration. +[CI](../../../../.github/workflows/ci.yml) applies the Linux failover variable to these three jobs, requiring a non-Dependabot author and a non-fork head repository matching the current repository. The standard hosted fallback remains available. These predicates constrain this job, not every workflow admitted to the pool. Both repository identity and fork status remain explicit to preserve its trust restriction if repository settings change; existing sibling selectors are outside this migration. The `blacksmith` failover value's branch drops those predicates: it targets ephemeral Blacksmith runners, so repository identity and fork status do not gate it (see the [blacksmith failover leg note](2026-09-09-blacksmith-failover-leg.md)). The temporary tool cache trades repeated Node downloads for isolation across concurrent runners and Node versions. A setup-node-only [ESM preload](../../../../scripts/ci-compatible-toolcache.mjs) assigns the cache inside the action process: the Actions runner overwrites reserved environment variables after reading step configuration. An executed path check rejects installations outside runner temp; compatibility processes do not inherit the preload. pnpm keeps its existing private setup destination and persistent content-addressed store. Compile caches and node-gyp headers use runner temp before the first pnpm invocation. No global Node symlink or system package changes are introduced. Hosted jobs retain their tool and package caching; self-hosted jobs do not restore or upload hosted package caches. The runner owns temporary-directory cleanup between jobs, and the shared image supplies native npm packages’ compiler and Python prerequisites. diff --git a/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.zh.md b/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.zh.md index 6dcff8aa19..80a9d8519d 100644 --- a/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.zh.md +++ b/.agents/notes/implemented/process/2026-09-06-node-compatibility-selfhosted.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -[CI](../../../../.github/workflows/ci.yml) 将 Linux 故障切换变量应用于这三个作业,要求作者不是 Dependabot,且非 fork 的头部仓库与当前仓库相同。标准托管回退仍然可用。这些条件约束本作业,而非所有可进入该池的工作流。仓库身份和 fork 状态均显式保留,以便在仓库设置改变时保持本作业的信任限制;现有兄弟选择器不属于本次迁移范围。 +[CI](../../../../.github/workflows/ci.yml) 将 Linux 故障切换变量应用于这三个作业,要求作者不是 Dependabot,且非 fork 的头部仓库与当前仓库相同。标准托管回退仍然可用。这些条件约束本作业,而非所有可进入该池的工作流。仓库身份和 fork 状态均显式保留,以便在仓库设置改变时保持本作业的信任限制;现有兄弟选择器不属于本次迁移范围。`blacksmith` 故障切换取值下的分支放弃这些条件:它面向临时的 Blacksmith 运行器,因此仓库身份与 fork 状态不参与门控(见 [blacksmith 故障切换支路笔记](2026-09-09-blacksmith-failover-leg.zh.md))。 临时工具缓存以重复下载 Node 为代价,换取并发运行器与 Node 版本之间的隔离。仅用于 setup-node 的 [ESM 预加载模块](../../../../scripts/ci-compatible-toolcache.mjs) 在 action 进程内指定缓存:Actions 运行器在读取步骤配置后会覆盖保留的环境变量。实际执行的路径检查拒绝运行器临时目录之外的安装;兼容性进程不继承预加载设置。pnpm 保留现有的私有安装目录和持久化内容寻址 store。编译缓存与 node-gyp 头文件在首次调用 pnpm 前就使用运行器临时目录。不引入全局 Node 符号链接或系统软件包变更。托管作业保留其工具与软件包缓存;自托管作业不恢复或上传托管软件包缓存。运行器负责作业之间的临时目录清理,共享镜像提供原生 npm 软件包所需的编译器和 Python 前置依赖。 diff --git a/.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.i18n.yaml b/.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.i18n.yaml new file mode 100644 index 0000000000..cc535290ee --- /dev/null +++ b/.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.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/process/2026-09-09-blacksmith-failover-leg.md +2026-09-09-blacksmith-failover-leg.md: eaaa6f4d5c8326ae7686dc9f485143781d065313 +2026-09-09-blacksmith-failover-leg.zh.md: 562aed96327a86c24e38b502f2ef4756a11b91e1 diff --git a/.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md b/.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md new file mode 100644 index 0000000000..eaaa6f4d5c --- /dev/null +++ b/.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md @@ -0,0 +1,27 @@ +# Agent Note: Blacksmith as a failover leg for CI pools + +Status: implemented + +English | [中文](2026-09-09-blacksmith-failover-leg.zh.md) + +## Problem + +The [failover runbook](2026-07-26-ci-failover-runbook.md) routes degraded enterprise-pool traffic onto the in-house `vm-backup` and `dsh-win-ci` pools, which are proven but bounded standbys. Blacksmith sells GitHub-hosted-style runners on demand, and its migration wizard proposed replacing the repository's `runs-on` labels wholesale, which would put credential-holding, benchmark, and spec-pinned jobs on third-party infrastructure as the default. The wholesale replacement is not acceptable as a default: it breaks the workflow contract specs, distorts benchmark and performance-budget measurements, and moves trust-boundary jobs without a decision record. + +## Decision + +`DSH_CI_FAILOVER_LINUX` and `DSH_CI_FAILOVER_WINDOWS` additionally accept the value `blacksmith`. When any repository writer sets it, the platform's participating jobs retarget onto Blacksmith's hosted runners at the vCPU size matching the pool each job replaces; any other value (or unset) keeps today's runner, and `selfhosted` keeps routing to the in-house pools. Like the existing values this is writer-manageable repository state — no merge, re-run the affected jobs — and it costs money only while set, which is why it is an explicit outage or experiment choice, never the default. + +Participating jobs under `blacksmith`: the three enterprise Linux workers, the `node-compat` legs, the `all-checks-passed` verdict, and the four Windows lanes in [ci.yml](../../../../.github/workflows/ci.yml) (16-core pools map to `blacksmith-16vcpu-ubuntu-2404` and `blacksmith-16vcpu-windows-2025`, standard-hosted legs to `blacksmith-4vcpu-ubuntu-2404`); `expected-filenames`; the sandbox bwrap leg; and the two manual benchmark matrices, whose 4-32 vCPU tiers map to Blacksmith equivalents while the 64/96-core rows keep the fleet labels because Blacksmith offers no such tier. The blacksmith branches carry no Dependabot exclusion: Blacksmith runners are ephemeral, so the persistent-VM rationale that keeps Dependabot on the hosted pool does not apply. The python-runtime builder stays hosted in full: its PR and master callers (`ci.yml`'s and `ci-master.yml`'s `python-runtime` jobs) pass real-API credentials (`DEEPSEEK_API_KEY_EXTERNAL`) into the reusable workflow, its macOS and arm64 single-exe legs need GitHub's images, and its wheel output feeds the PyPI publication chain. The docs-pages workflow is a tag-dispatched release publication, so it stays hosted too. + +Everything else keeps its own runner under every value: jobs pinned to standard hosted runners by workflow spec (`node-24-bench`, `python-sdk`, the master Wine gate, `release-publish` and `release-vendor-publish`, the Cloudflare preview, the weighted-approval pair); jobs that hold credentials (the real-API e2e lanes, the issue App-token jobs, the npm and PyPI publishers); jobs that need a host capability Blacksmith lacks (the Landlock legs and their pack verification, the Seatbelt leg, the linux-arm64 single-exe leg); and the release-shaped chains — the npm publishers, the PyPI publishers, the node-addon-system release chain, and the Pages deployment workflow — which stay entirely hosted because their artifacts feed published registry output. The release rehearsal jobs in `release.yml` and `release-vendor.yml` (`dependencies`, `pack`) keep their existing pre-change routing unchanged: they carry only the pre-existing `selfhosted` branch, so under `blacksmith` they fall back to their hosted `ubuntu-24.04` default exactly as under an unset variable, and they gain no `blacksmith` branch. + +## Alternatives considered + +Adopting the migration wizard wholesale. Rejected because it breaks the workflow contract specs, changes benchmark semantics and performance-budget calibration, and moves credential-holding and trust-boundary jobs to third-party infrastructure as the default; the earlier wizard migration (closed PR #3053) was rejected for cost and the same review findings. + +Keeping the in-house pools as the only failover target. Rejected as the sole option because they are a bounded standby; Blacksmith adds elastic capacity for the outage and experiment cases where the fleet itself is the degraded resource. + +## Consequences + +The blacksmith legs stay dormant until the value is set, so they are exercised only during an actual failover or an explicit experiment. The mirror trial ([PR #3841](https://github.com/deepseek-harness/deepseek-harness/pull/3841), closed) ran the participating set hardcoded onto the Blacksmith labels and confirmed that `blacksmith-4vcpu-ubuntu-2404`, `blacksmith-16vcpu-ubuntu-2404`, and `blacksmith-16vcpu-windows-2025` schedule and execute. Blacksmith registers its runners as self-hosted, so under the `blacksmith` value the `node-compat` legs run their toolcache-isolation and isolated-installation verification steps (gated on `runner.environment == 'self-hosted'`) rather than skipping them; all three legs passed on the trial image ([run 34322356689](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34322356689)). The same trial surfaced one environment finding that this change fixes: while expanding `**`, node 24.13's internal `fs.glob` lstat-probes `/` for a symlinked file and throws ENOTDIR instead of skipping ([run 34319926270](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34319926270)), failing `verify-md-wrap` inside `check:ci:static` on Blacksmith until [repo-files.ts](../../../../scripts/repo-files.ts) replaced `globSync` with a dirent walker; the fixed static lane is green on the same image. The trigger is the lstat-probe of a path beneath a matched symlink, not `**` over symlinked trees in general: the other `globSync` `**` call sites that scan symlink-bearing trees stayed green on the same run and needed no change. The benchmark matrices' 8 and 32 vCPU labels (ubuntu-2404 and windows-2025) were not part of the trial and are inferred by naming symmetry from the verified 4 and 16 vCPU labels; confirm with a manual dispatch before first use. The Landlock, Seatbelt, and linux-arm64 exclusions still rest on the prose dispatch measurements of the earlier migration attempt (closed PR #3053), recorded here as a known gap; the trial could not exercise those legs by design. Workflow specs pin the new branches — `ci-workflow.spec.ts` asserts the Blacksmith labels appear in the extended selectors, and `ci-compatible-selfhosted.spec.ts` evaluates the `blacksmith` routing mode — so a future rewrite of the selectors fails the unit gates. Default cost posture is unchanged: nothing runs on Blacksmith unless the variable says so. diff --git a/.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.zh.md b/.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.zh.md new file mode 100644 index 0000000000..562aed9632 --- /dev/null +++ b/.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.zh.md @@ -0,0 +1,27 @@ +# Agent Note: Blacksmith 作为 CI 池的故障切换支路 + +Status: implemented + +[English](2026-09-09-blacksmith-failover-leg.md) | 中文 + +## 问题 + +[故障切换手册](2026-07-26-ci-failover-runbook.zh.md)把降级的企业池流量路由到自有的 `vm-backup` 与 `dsh-win-ci` 池——它们是经过验证但容量有界的备用池。Blacksmith 按需出售类似 GitHub 托管的运行器,其迁移向导提议整体替换仓库的 `runs-on` 标签,这会把持有凭据、基准与 spec 钉死的作业默认放到第三方基础设施上。整体替换不适合作为默认:它会打破 workflow 契约 spec、扭曲基准与性能预算测量,并在没有决策记录的情况下搬动信任边界作业。 + +## 决策 + +`DSH_CI_FAILOVER_LINUX` 与 `DSH_CI_FAILOVER_WINDOWS` 额外接受值 `blacksmith`。任何仓库写者设置它时,该平台参与切换的作业按与被替换池匹配的 vCPU 档位重定向到 Blacksmith 托管运行器;任何其它值(或未设置)保持今天的运行器,`selfhosted` 继续路由到自有池。与既有取值一样,这是写者可管理的仓库状态——无需合并,重跑受影响的作业即可——并且只在设置期间产生费用,这正是它作为明确的故障或实验选择、而非默认的原因。 + +`blacksmith` 下参与切换的作业:[ci.yml](../../../../.github/workflows/ci.yml) 中三个企业级 Linux 工作作业、`node-compat` 各腿、`all-checks-passed` 判定作业与四条 Windows 通道(16 核池映射到 `blacksmith-16vcpu-ubuntu-2404` 与 `blacksmith-16vcpu-windows-2025`,标准托管腿映射到 `blacksmith-4vcpu-ubuntu-2404`);`expected-filenames`;sandbox 的 bwrap 腿;以及两个手动基准矩阵——其 4-32 vCPU 档位映射到 Blacksmith 等价档,64/96 核行保留自有池标签,因为 Blacksmith 没有对应档位。blacksmith 分支不带 Dependabot 排除:Blacksmith 运行器是临时的,因此把 Dependabot 留在托管池的持久虚拟机理由不适用。python-runtime 构建器整体保持托管:其 PR 与 master 调用方(`ci.yml` 与 `ci-master.yml` 的 `python-runtime` 作业)会把真实 API 凭据(`DEEPSEEK_API_KEY_EXTERNAL`)传入该可复用工作流,其 macOS 与 arm64 单文件分支需要 GitHub 镜像,且其 wheel 产物供给 PyPI 发布链。docs-pages 工作流是 tag 派发的发布,因此同样保持托管。 + +其余作业在任何取值下都保留自己的运行器:被 workflow spec 钉死在标准托管运行器上的作业(`node-24-bench`、`python-sdk`、master 的 Wine 门禁、`release-publish` 与 `release-vendor-publish`、Cloudflare preview、weighted-approval 一对);持有凭据的作业(真实 API 的 e2e 通道、issue App token 作业、npm 与 PyPI 发布作业);需要 Blacksmith 缺失的宿主能力的作业(Landlock 各腿及其打包校验、Seatbelt 腿、linux-arm64 单文件分支);以及发布形态的链——npm 发布、PyPI 发布、node-addon-system 发布链与 Pages 部署工作流——它们整体保持托管,因为其产物供给已发布的 registry 输出。`release.yml` 与 `release-vendor.yml` 中的发布演练作业(`dependencies`、`pack`)保持改动前既有的路由不变:它们只带既有的 `selfhosted` 分支,因此在 `blacksmith` 取值下与变量未设置时一样回落到托管的 `ubuntu-24.04` 默认,并不新增 `blacksmith` 分支。 + +## 备选方案 + +整体采纳迁移向导。否决,因为它打破 workflow 契约 spec、改变基准语义与性能预算校准,并默认把持有凭据与信任边界的作业搬到第三方基础设施;更早的向导迁移(已关闭的 PR #3053)因成本与同样的 review 结论被否决。 + +只把自有池作为唯一故障切换目标。作为唯一选项被否决,因为它是容量有界的备用;Blacksmith 为「故障对象正是自有池本身」的故障与实验场景提供弹性容量。 + +## 后果 + +blacksmith 各腿在有人设置该值前保持休眠,因此只在真实故障切换或明确实验期间被使用。镜像试运行([PR #3841](https://github.com/deepseek-harness/deepseek-harness/pull/3841),已关闭)把参与集硬编码到 Blacksmith 标签上跑过,确认 `blacksmith-4vcpu-ubuntu-2404`、`blacksmith-16vcpu-ubuntu-2404` 与 `blacksmith-16vcpu-windows-2025` 可调度可执行。Blacksmith 将其运行器注册为 self-hosted,因此在 `blacksmith` 取值下 `node-compat` 各腿会真实执行 toolcache 隔离与隔离安装校验步骤(以 `runner.environment == 'self-hosted'` 为条件),而非全部跳过;三条腿都在试运行镜像上通过([run 34322356689](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34322356689))。同一试运行还暴露了一个由本改动修复的环境发现:在 `**` 展开中遇到 symlink 文件时,node 24.13 的内部 `fs.glob` 会 lstat-probe `/<下一段>` 并抛 ENOTDIR 而非跳过([run 34319926270](https://github.com/deepseek-harness/deepseek-harness/actions/runs/34319926270)),使 `check:ci:static` 内的 `verify-md-wrap` 在 Blacksmith 上失败,直到 [repo-files.ts](../../../../scripts/repo-files.ts) 用 dirent walker 替换 `globSync`;修复后的 static 通道在同一镜像上转绿。触发条件是 probe 已匹配 symlink 之下的路径,而非笼统的「`**` 扫过含 symlink 的树」:同一 run 中其它扫描含 symlink 树的 `globSync` `**` 调用点保持绿色,无需改动。两个基准矩阵的 8 与 32 vCPU 标签(ubuntu-2404 与 windows-2025)不在试运行范围内,是按已实测的 4/16 vCPU 标签命名对称推定的;首次使用前请用一次手动 dispatch 确认。Landlock、Seatbelt 与 linux-arm64 的排除仍基于更早迁移尝试(已关闭的 PR #3053)的散文式 dispatch 实测,此处记录为已知缺口;试运行按设计无法触发这几条腿。workflow spec 钉住了新分支——`ci-workflow.spec.ts` 断言扩展后的 selector 中出现 Blacksmith 标签,`ci-compatible-selfhosted.spec.ts` 求值 `blacksmith` 路由模式——因此未来重写 selector 会使单元门禁变红。默认成本姿态不变:除非变量指明,否则没有任何东西跑在 Blacksmith 上。 diff --git a/.github/AGENTS.md b/.github/AGENTS.md index 100385608f..f4f3c5d555 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -1,3 +1,3 @@ # AGENTS.md — GitHub Actions -Run jobs on Windows runners (`windows-*` labels) under native `pwsh`. Native Windows build and process checks contribute to the pull-request `all checks passed` verdict; Wine runs Windows Node on hosted Linux only in `ci-master.yml`. Python runtime CI checks Linux/Windows x64 on pull requests and Linux ARM64 plus both macOS architectures on master pushes; releases retain all five targets ([platform policy](../.agents/notes/implemented/process/2026-09-06-master-only-platform-ci.md)). `ci.yml` is pull-request-only. Master-only platform checks, Linux/Windows self-hosted standbys, and manual runner benchmarks live in `ci-master.yml`, which listens to master pushes and `workflow_dispatch`, not `pull_request`; separating workflow triggers keeps master-only jobs out of PR check panels. The master standbys validate the self-hosted failover targets; preserve the existing per-platform switches and Dependabot hosted fallback ([failover runbook](../.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md)). +Run jobs on Windows runners (`windows-*` labels) under native `pwsh`. Native Windows build and process checks contribute to the pull-request `all checks passed` verdict; Wine runs Windows Node on hosted Linux only in `ci-master.yml`. Python runtime CI checks Linux/Windows x64 on pull requests and Linux ARM64 plus both macOS architectures on master pushes; releases retain all five targets ([platform policy](../.agents/notes/implemented/process/2026-09-06-master-only-platform-ci.md)). `ci.yml` is pull-request-only. Master-only platform checks, Linux/Windows self-hosted standbys, and manual runner benchmarks live in `ci-master.yml`, which listens to master pushes and `workflow_dispatch`, not `pull_request`; separating workflow triggers keeps master-only jobs out of PR check panels. The master standbys validate the self-hosted failover targets; preserve the existing per-platform switches (values `selfhosted` for the in-house standbys and `blacksmith` for Blacksmith's hosted runners) and the Dependabot hosted fallback under the `selfhosted` values ([failover runbook](../.agents/notes/implemented/process/2026-07-26-ci-failover-runbook.md), [blacksmith failover leg note](../.agents/notes/implemented/process/2026-09-09-blacksmith-failover-leg.md)). From 220678e57d135e21817dc31bc621e6b8111005e3 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Wed, 9 Sep 2026 21:03:44 +0800 Subject: [PATCH 15/52] feat(manifest): declare plugin format, tags, and host compatibility --- .../2026-09-05-package-manifest-types.i18n.yaml | 4 ++-- .../2026-09-05-package-manifest-types.md | 4 ++++ .../2026-09-05-package-manifest-types.zh.md | 4 ++++ packages/util/package-manifest/README.i18n.yaml | 4 ++-- packages/util/package-manifest/README.md | 16 +++++++++++++++- packages/util/package-manifest/README.zh.md | 16 +++++++++++++++- packages/util/package-manifest/src/index.ts | 1 + packages/util/package-manifest/src/types.ts | 12 ++++++++++++ 8 files changed, 55 insertions(+), 6 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.i18n.yaml index c4907f9030..a15fd90d6d 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.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-09-05-package-manifest-types.md -2026-09-05-package-manifest-types.md: 94317a9317ba12059e726612840e4a001be2a892 -2026-09-05-package-manifest-types.zh.md: 2c40facd2591921123b5eae71b80c516f3b1f697 +2026-09-05-package-manifest-types.md: 5e9834583a75a3fd4f1ec69379628c49d264e05b +2026-09-05-package-manifest-types.zh.md: 8a2399a19a097113d45f4915631d36ca30191dd5 diff --git a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.md b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.md index 94317a9317..5e9834583a 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.md +++ b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.md @@ -12,6 +12,8 @@ External packages need Harness manifest types without depending on boot or clien [`@deepseek-ai/dsh-package-manifest`](../../../../packages/util/package-manifest/README.md) owns `DshManifest` and its member declarations in one type-only file. The package belongs to the existing utility group and exports no runtime values. Author declarations and launcher-generated module fallback metadata are explicitly distinguished. +Author metadata stays under `package.json.dsh`: optional `manifestVersion` identifies format `1`, `categories` carries free-form discovery tags, and `engines.dsh` declares compatible host versions as a SemVer range. Npm package identity and Node requirements retain their top-level fields. Categories are extensible tags rather than a closed role enum, so labels such as `skills` and `tools` do not constrain package composition. + Readers import the shared declarations directly. Boot retains profile loading, raw JSON checks, defaults, and resolved runtime data. Client modules retain their normalized boot graph. The image packer resolves declared paths into directories. The Session catalog generator derives a read-only validated entry with a resolved import path; raw inputs and discovery rules remain local. App-boot declares a production dependency because its published declarations reference the shared types. Client modules, the private packer, and root scripts use development dependencies because their published APIs do not expose these types. Every package consumer has a TypeScript project reference. External authors import from the utility package; app-boot provides no compatibility re-exports. @@ -29,3 +31,5 @@ App-boot declares a production dependency because its published declarations ref Authors gain one public import path at the cost of a published package and explicit dependency edges. Existing app-boot manifest type imports must use the new package. The [profile composition design](2026-08-05-profile-plugin-bundles.md) continues to own runtime semantics; type extraction does not change configuration acceptance or model-visible behavior. Compiler and packaged NodeNext consumer checks cover public imports. Existing profile, client, image configuration, and Session catalog tests cover reader behavior; documentation checks cover the utility classification and generated package catalogs. Optional declaration fields still require deliberate consumer updates when added. + +Manifest format and host compatibility declarations have no enforcement in current installers or loaders. The type-only package supplies neither a SemVer parser nor an installation policy; its README records that limitation so an author declaration is not mistaken for a compatibility check. diff --git a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.zh.md b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.zh.md index 2c40facd25..8a2399a19a 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.zh.md @@ -12,6 +12,8 @@ Status: implemented [`@deepseek-ai/dsh-package-manifest`](../../../../packages/util/package-manifest/README.zh.md) 在一个纯类型文件中拥有 `DshManifest` 及其成员声明。本包属于现有工具库分组,不导出运行时值。作者声明与启动器生成的模块后备元数据有明确区分。 +作者元数据保留在 `package.json.dsh` 下:可选的 `manifestVersion` 标识格式 `1`,`categories` 承载自由发现标签,`engines.dsh` 以 SemVer 范围声明兼容的宿主版本。npm 包身份和 Node 要求沿用顶层字段。Categories 是可扩展标签,而非封闭的角色枚举,因此 `skills`、`tools` 等标签不限制包的组合。 + 各读取方直接导入共享声明。启动器保留 profile 加载、原始 JSON 检查、默认值和解析后的运行时数据。客户端模块保留归一化的启动图。镜像打包器将声明路径解析为目录。Session 目录生成器派生带有已解析导入路径的只读校验结果;原始输入和发现规则仍由本地负责。 App-boot 声明生产依赖,因为其发布的声明文件引用共享类型。客户端模块、私有打包器和根脚本使用开发依赖,因为其发布 API 不暴露这些类型。每个包消费方都有 TypeScript 项目引用。外部作者从工具包导入;app-boot 不提供兼容性再导出。 @@ -29,3 +31,5 @@ App-boot 声明生产依赖,因为其发布的声明文件引用共享类型 作者获得统一的公共导入路径,代价是一个发布包和明确的依赖边。已有的 app-boot manifest 类型导入需要改用新包。[Profile 组合设计](2026-08-05-profile-plugin-bundles.zh.md) 继续负责运行时语义;类型提取不改变配置接受范围或模型可见行为。 编译器与打包后的 NodeNext 消费方检查覆盖公共导入。已有 profile、客户端、镜像配置和 Session 目录测试覆盖读取行为;文档检查覆盖工具库分类与生成的包目录。新增可选声明字段时,仍需主动更新消费方。 + +当前安装器和加载器不强制检查 manifest 格式或宿主兼容性声明。纯类型包既不提供 SemVer 解析器,也不提供安装策略;其 README 记录此限制,避免将作者声明误认为兼容性检查。 diff --git a/packages/util/package-manifest/README.i18n.yaml b/packages/util/package-manifest/README.i18n.yaml index 6a8cad4326..f25db6d863 100644 --- a/packages/util/package-manifest/README.i18n.yaml +++ b/packages/util/package-manifest/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/util/package-manifest/README.md -README.md: 971df84d7db3205eb8be75ba895046d4151780d2 -README.zh.md: 8989cbe9bc29bbf8112d5465eac9806c211fa88d +README.md: 428ed05af9856d4a1a77be9c152130fa26464bb9 +README.zh.md: cdf6302b537a458c010f5cd8b3531131fc6a21ac diff --git a/packages/util/package-manifest/README.md b/packages/util/package-manifest/README.md index 971df84d7d..428ed05af9 100644 --- a/packages/util/package-manifest/README.md +++ b/packages/util/package-manifest/README.md @@ -32,12 +32,25 @@ import type { DshClientManifest, DshManifest } from '@deepseek-ai/dsh-package-ma const client: DshClientManifest = { platform: 'web' } const dsh: DshManifest = { + manifestVersion: 1, + categories: ['skills', 'tools'], + engines: { dsh: '0.1.5-alpha.1' }, bundle: { patch: './cordis.patch.yml' }, client, } ``` -`DshManifest` describes `bundle`, `profile`, `client`, `configTrees`, `sessionFormatMigration`, and `moduleFallback`, not the surrounding npm manifest. `moduleFallback` is launcher-generated metadata and is not an author configuration entry. TypeScript checks this object and erases `import type` during compilation; JSON files cannot import types, and this example does not write a `package.json`. See [`src/types.ts`](src/types.ts) for the declarations. +`DshManifest` describes `package.json.dsh`; npm fields such as `name`, `version`, and `engines.node` stay at the package root. TypeScript checks this object and erases `import type` during compilation; JSON files cannot import types, and this example does not write a `package.json`. + +All three author metadata fields are optional. Omitting them leaves the format version, tags, or compatible host versions undeclared; readers do not infer defaults. + +| Field | Meaning | +|---|---| +| `manifestVersion` | Manifest format identifier; the declared format is `1`, independent of the npm package version and Session format version. | +| `categories` | Free-form discovery tags such as `skills` and `tools`, with no fixed taxonomy or effect on plugin loading. | +| `engines.dsh` | Author-declared compatible DSH versions as a SemVer range. An exact prerelease version is valid; the `dsh` member is required when `engines` is present. | + +Composition and build declarations are defined in [`src/types.ts`](src/types.ts). `moduleFallback` is launcher-generated metadata and is not an author configuration entry. ----- @@ -73,6 +86,7 @@ Type declarations add no model input, so provider cache reuse is unaffected. - **Static typing only.** These declarations do not validate JSON, check file existence, or supply defaults. `configTrees` serves the experimental image packer, and `sessionFormatMigration` is discovered only for workspace migration packages; declaring them does not register external plugin behavior. +- **Compatibility is declarative.** Current installers and loaders do not enforce `manifestVersion` or `engines.dsh`; declaring a range does not reject incompatible hosts or validate SemVer syntax. ### Dev Note diff --git a/packages/util/package-manifest/README.zh.md b/packages/util/package-manifest/README.zh.md index 8989cbe9bc..cdf6302b53 100644 --- a/packages/util/package-manifest/README.zh.md +++ b/packages/util/package-manifest/README.zh.md @@ -32,12 +32,25 @@ import type { DshClientManifest, DshManifest } from '@deepseek-ai/dsh-package-ma const client: DshClientManifest = { platform: 'web' } const dsh: DshManifest = { + manifestVersion: 1, + categories: ['skills', 'tools'], + engines: { dsh: '0.1.5-alpha.1' }, bundle: { patch: './cordis.patch.yml' }, client, } ``` -`DshManifest` 描述 `bundle`、`profile`、`client`、`configTrees`、`sessionFormatMigration` 和 `moduleFallback`,不包含外层 npm manifest。`moduleFallback` 是启动器生成的元数据,不是作者配置项。TypeScript 检查该对象,并在编译时删除 `import type`;JSON 文件不能导入类型,此示例也不会写入 `package.json`。声明见 [`src/types.ts`](src/types.ts)。 +`DshManifest` 描述 `package.json.dsh`;`name`、`version`、`engines.node` 等 npm 字段仍位于包的顶层。TypeScript 检查该对象,并在编译时删除 `import type`;JSON 文件不能导入类型,此示例也不会写入 `package.json`。 + +这三个作者元数据字段均可选。省略时,格式版本、标签或兼容的宿主版本保持未声明状态;读取方不推断默认值。 + +| 字段 | 含义 | +|---|---| +| `manifestVersion` | manifest(元数据清单)格式标识;声明的格式为 `1`,独立于 npm 包版本和 Session 格式版本。 | +| `categories` | `skills`、`tools` 等自由发现标签,无固定分类体系,不影响插件加载。 | +| `engines.dsh` | 作者声明的兼容 DSH 版本,使用 SemVer 范围。可填写精确的预发布版本;存在 `engines` 时,必须填写 `dsh` 成员。 | + +组合与构建声明定义在 [`src/types.ts`](src/types.ts) 中。`moduleFallback` 是启动器生成的元数据,不是作者配置项。 ----- @@ -73,6 +86,7 @@ const dsh: DshManifest = { - **仅提供静态类型。** 这些声明不校验 JSON、不检查文件存在性,也不提供默认值。`configTrees` 服务于实验性镜像打包器,`sessionFormatMigration` 仅从工作区迁移包中发现;声明它们不会注册外部插件行为。 +- **兼容性仅作声明。** 当前安装器和加载器不强制检查 `manifestVersion` 或 `engines.dsh`;声明范围不会拒绝不兼容的宿主,也不会校验 SemVer 语法。 ### 开发备注 diff --git a/packages/util/package-manifest/src/index.ts b/packages/util/package-manifest/src/index.ts index 2ea0cfd07f..a13bb94274 100644 --- a/packages/util/package-manifest/src/index.ts +++ b/packages/util/package-manifest/src/index.ts @@ -7,6 +7,7 @@ export type { DshBundleManifest, DshClientManifest, DshConfigTreeDeclaration, + DshEnginesManifest, DshManifest, DshModuleFallbackManifest, DshProfileManifest, diff --git a/packages/util/package-manifest/src/types.ts b/packages/util/package-manifest/src/types.ts index 2c98c63dc3..0528f2c167 100644 --- a/packages/util/package-manifest/src/types.ts +++ b/packages/util/package-manifest/src/types.ts @@ -6,6 +6,12 @@ /** The `dsh` property of an npm manifest; a package may declare several roles. */ export interface DshManifest { + /** Manifest format version, independent of the npm package and Session format versions. */ + manifestVersion?: 1 + /** Free-form discovery tags, such as `skills` or `tools`; do not affect plugin loading. */ + categories?: string[] + /** Declared host compatibility; current readers do not enforce version ranges. */ + engines?: DshEnginesManifest /** Bundle metadata consumed by the profile launcher. */ bundle?: DshBundleManifest /** Profile metadata consumed by the profile launcher. */ @@ -23,6 +29,12 @@ export interface DshManifest { moduleFallback?: DshModuleFallbackManifest } +/** Host version requirements declared by the package author. */ +export interface DshEnginesManifest { + /** Compatible DSH versions as a SemVer range, including an exact version. */ + dsh: string +} + /** The configuration layer exported by a bundle package. */ export interface DshBundleManifest { /** Patch file path relative to the declaring package root. */ From d09b4accd31ccd1d19b62ae9c5881d41de0270e2 Mon Sep 17 00:00:00 2001 From: 07akioni <07akioni2@gmail.com> Date: Wed, 9 Sep 2026 21:10:02 +0800 Subject: [PATCH 16/52] =?UTF-8?q?feat:=20=E6=89=93=E5=8C=85=20+=20?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E5=A4=84=E7=90=86=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...on-desktop-packaging-and-updates.i18n.yaml | 4 +- ...-electron-desktop-packaging-and-updates.md | 2 + ...ectron-desktop-packaging-and-updates.zh.md | 2 + ...led-runtime-and-external-plugins.i18n.yaml | 4 +- ...op-bundled-runtime-and-external-plugins.md | 4 +- ...bundled-runtime-and-external-plugins.zh.md | 4 +- ...desktop-build-release-validation.i18n.yaml | 6 + ...-09-09-desktop-build-release-validation.md | 23 ++ ...-09-desktop-build-release-validation.zh.md | 23 ++ ...mmediate-window-and-direct-start.i18n.yaml | 4 +- ...sktop-immediate-window-and-direct-start.md | 4 + ...op-immediate-window-and-direct-start.zh.md | 6 +- ...6-09-09-desktop-in-place-profile.i18n.yaml | 6 + .../2026-09-09-desktop-in-place-profile.md | 25 ++ .../2026-09-09-desktop-in-place-profile.zh.md | 25 ++ apps/desktop/README.i18n.yaml | 4 +- apps/desktop/README.md | 18 +- apps/desktop/README.zh.md | 18 +- apps/desktop/renderer/startup.html | 7 +- apps/desktop/renderer/startup.js | 30 ++- apps/desktop/scripts/dev.ts | 7 +- apps/desktop/src/backend-controller.ts | 10 +- apps/desktop/src/ipc.ts | 7 + apps/desktop/src/locale.ts | 20 +- apps/desktop/src/main.ts | 153 ++++++++++-- apps/desktop/src/paths.ts | 8 +- apps/desktop/src/preload-app.ts | 4 + apps/desktop/src/profile-packages.ts | 45 ++-- apps/desktop/src/project-manager.ts | 221 +++++++----------- apps/desktop/src/runtime-tree.ts | 64 +++-- apps/desktop/src/startup-document.ts | 25 ++ apps/desktop/src/startup-error.ts | 31 +++ apps/desktop/tests/backend-controller.spec.ts | 8 +- .../expected/startup-en-configuration.txt | 8 + .../tests/expected/startup-en-plugins.txt | 8 + .../tests/expected/startup-en-reinstall.txt | 8 + .../tests/expected/startup-en-restart.txt | 8 + .../expected/startup-zh-CN-configuration.txt | 8 + .../tests/expected/startup-zh-CN-plugins.txt | 8 + .../expected/startup-zh-CN-reinstall.txt | 8 + .../tests/expected/startup-zh-CN-restart.txt | 8 + apps/desktop/tests/main-startup.spec.ts | 138 ++++++++++- apps/desktop/tests/plugin-pnpm.spec.ts | 4 +- apps/desktop/tests/preload-app.spec.ts | 5 + apps/desktop/tests/profile-packages.spec.ts | 9 +- apps/desktop/tests/project-manager.spec.ts | 188 ++++++++++----- apps/desktop/tests/runtime-tree.spec.ts | 53 ++++- apps/desktop/tests/startup-renderer.spec.ts | 84 +++++-- 48 files changed, 979 insertions(+), 388 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.md create mode 100644 .agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.zh.md create mode 100644 .agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md create mode 100644 .agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md create mode 100644 apps/desktop/src/startup-document.ts create mode 100644 apps/desktop/src/startup-error.ts create mode 100644 apps/desktop/tests/expected/startup-en-configuration.txt create mode 100644 apps/desktop/tests/expected/startup-en-plugins.txt create mode 100644 apps/desktop/tests/expected/startup-en-reinstall.txt create mode 100644 apps/desktop/tests/expected/startup-en-restart.txt create mode 100644 apps/desktop/tests/expected/startup-zh-CN-configuration.txt create mode 100644 apps/desktop/tests/expected/startup-zh-CN-plugins.txt create mode 100644 apps/desktop/tests/expected/startup-zh-CN-reinstall.txt create mode 100644 apps/desktop/tests/expected/startup-zh-CN-restart.txt diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml index d182ff8d4a..494f94041f 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.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-25-electron-desktop-packaging-and-updates.md -2026-08-25-electron-desktop-packaging-and-updates.md: f6aa73d6e708db04c6978690b8fc2b7eb70f270b -2026-08-25-electron-desktop-packaging-and-updates.zh.md: 00c1346ab9b0bca1f704d74e7792acd03c5df9bf +2026-08-25-electron-desktop-packaging-and-updates.md: 2e266b74c2c1a5de62312ddce2c43de0908b2675 +2026-08-25-electron-desktop-packaging-and-updates.zh.md: 0a48e80b47450db7e45ab96f3a7b6e465ca271b6 diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md index f6aa73d6e7..2e266b74c2 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md @@ -4,6 +4,8 @@ Status: implemented English | [中文](2026-08-25-electron-desktop-packaging-and-updates.zh.md) +Profile staging, directory-swap recovery, and automatic rollback described here are superseded by the [in-place profile decision](2026-09-09-desktop-in-place-profile.md). Other decisions remain active. + ## Problem DeepSeek Harness needs an Electron desktop application that reuses the Web UI, works without system Node.js or pnpm, installs dsh and desktop plugins through an application-bundled pnpm, and updates the complete desktop release through one user-facing flow. diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md index 00c1346ab9..0a48e80b47 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md @@ -4,6 +4,8 @@ Status: implemented [English](2026-08-25-electron-desktop-packaging-and-updates.md) | 中文 +本记录中的 profile staging、目录切换恢复和自动回滚由[直接修改 profile 决策](2026-09-09-desktop-in-place-profile.zh.md)取代。其他决策继续有效。 + ## 问题 DeepSeek Harness 需要一个复用 Web UI 的 Electron 桌面应用。该应用无需系统 Node.js 或 pnpm 即可工作,通过应用内置 pnpm 安装 dsh 与桌面插件,并通过一个面向用户的流程更新完整桌面发布。 diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml index 8c5be1e7e1..5c992fd72d 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.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-09-08-desktop-bundled-runtime-and-external-plugins.md -2026-09-08-desktop-bundled-runtime-and-external-plugins.md: a662af570c017d6fd3d38cf066c0a02e0049a84f -2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md: 6284949f6747cbe47a5de149ff598354c9b9cc58 +2026-09-08-desktop-bundled-runtime-and-external-plugins.md: 9fcee1d49d4d2595fa9dfc929b58ee3e5262ac54 +2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md: f448029cbf840e8003ce26d67788663168629da4 diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md index a662af570c..9fcee1d49d 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.md @@ -4,6 +4,8 @@ Status: implemented English | [中文](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md) +Profile staging, directory-swap recovery, and automatic rollback described here are superseded by the [in-place profile decision](2026-09-09-desktop-in-place-profile.md). Other decisions remain active. + ## Problem Installing the core dependency graph during Desktop initialization repeats work already done by the release builder. An offline store eliminates downloads but retains extraction, package-manager startup, and installation costs. Users need the application to start with its production packages present while retaining ordinary npm plugin installation and plugin state across application upgrades. @@ -44,7 +46,7 @@ The [immediate-window decision](2026-09-09-desktop-immediate-window-and-direct-s ## Alternatives considered -Full runtime verification belongs to packaging. Startup reads the descriptor, validates release and target compatibility, checks shared manifests and required Host entries, and uses the recorded runtime identity for profile reuse. It neither enumerates nor hashes installed runtime files, including on first launch or after an upgrade. Reading every file before backend loading adds startup I/O proportional to the distribution size. Installed content changes therefore are not detected by a startup checksum comparison; unusable modules fail when loaded. Build-time verification still rejects changed, missing, extra, or linked files against the recorded inventory. +Full runtime verification belongs to packaging. Startup reads the descriptor, checks shared package records and required Host entries, and uses the recorded runtime identity for profile reuse. The [release-validation decision](2026-09-09-desktop-build-release-validation.md) assigns release and target compatibility checks to packaging. It neither enumerates nor hashes installed runtime files, including on first launch or after an upgrade. Reading every file before backend loading adds startup I/O proportional to the distribution size. Installed content changes therefore are not detected by a startup checksum comparison; unusable modules fail when loaded. Build-time verification still rejects changed, missing, extra, or linked files against the recorded inventory. - **Install the bundled offline seed at startup.** This preserves an ordinary pnpm installation procedure but repeats core extraction and installation on every affected machine. Materialized resources remove that work at the cost of more application files and release-builder responsibility. - **Link all host dependencies into plugins.** This unnecessarily couples ordinary plugin dependencies to the host. Only the explicit shared inventory is linked; private packages retain independent versions. diff --git a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md index 6284949f67..f448029cbf 100644 --- a/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md @@ -4,6 +4,8 @@ Status: implemented [English](2026-09-08-desktop-bundled-runtime-and-external-plugins.md) | 中文 +本记录中的 profile staging、目录切换恢复和自动回滚由[直接修改 profile 决策](2026-09-09-desktop-in-place-profile.zh.md)取代。其他决策继续有效。 + ## 问题 Desktop 初始化时安装核心依赖图,会重复发布构建器已经完成的工作。离线 store 消除了下载,但仍有解压、包管理器启动和安装成本。用户需要应用在生产依赖已就绪时启动,同时保留普通 npm 插件安装能力,以及跨应用升级的插件状态。 @@ -44,7 +46,7 @@ profile manifest 分别记录精确的已安装插件依赖和已启用 bundle ## 考虑过的替代方案 -完整运行时验证属于打包流程。启动读取描述文件,验证发布版本与目标平台的兼容性,检查共享包 manifest 和必要的 Host 入口,并使用记录的运行时身份复用 profile。首次启动和升级后启动都不枚举已安装运行时文件或计算其哈希。在后端加载前读取每个文件,会增加与分发体积成正比的启动 I/O。因此,启动不会通过校验和比较检测已安装内容的变化;不可用模块在加载时失败。构建时验证仍按记录的清单拒绝内容变化、缺失、多余或链接文件。 +完整运行时验证属于打包流程。启动读取描述文件,检查共享包记录和必要的 Host 入口,并使用记录的运行时身份复用 profile。[发布验证决策](2026-09-09-desktop-build-release-validation.zh.md)把发布与目标兼容性检查交给打包流程。首次启动和升级后启动都不枚举已安装运行时文件或计算其哈希。在后端加载前读取每个文件,会增加与分发体积成正比的启动 I/O。因此,启动不会通过校验和比较检测已安装内容的变化;不可用模块在加载时失败。构建时验证仍按记录的清单拒绝内容变化、缺失、多余或链接文件。 - **启动时安装内置离线 seed。** 这保留普通 pnpm 安装流程,但会在每台受影响机器上重复核心解压与安装。物化资源消除了这部分工作,代价是更多应用文件和发布构建器责任。 - **把所有宿主依赖链接给插件。** 这会让普通插件依赖与宿主产生不必要的耦合。只链接明确的共享清单;私有包保留独立版本。 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.i18n.yaml new file mode 100644 index 0000000000..c41d31830d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.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-09-desktop-build-release-validation.md +2026-09-09-desktop-build-release-validation.md: 23aeeaa98d2647f8b9f54e94ea2aedaa82b19e55 +2026-09-09-desktop-build-release-validation.zh.md: 266bca5bbd593907c9a8fadd43050113ede94100 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.md new file mode 100644 index 0000000000..23aeeaa98d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.md @@ -0,0 +1,23 @@ +# Agent Note: Verify Desktop release compatibility during packaging + +Status: implemented + +English | [中文](2026-09-09-desktop-build-release-validation.zh.md) + +## Problem + +The shell and runtime descriptor ship together. Comparing their release facts on every launch repeats packaging checks without proving that installed executable bytes match the descriptor. + +## Decision + +The packaging verifier owns descriptor schema, shell version, platform, architecture, declared Host protocol version, and Node/pnpm semver validation. Startup reads the fields needed for profile preparation and retains shared-package record and Host-entry checks. The actual Host ready message still validates its protocol version. + +This partially supersedes startup release compatibility checks in the [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). That note retains package ownership and distribution rationale. + +## Alternatives considered + +Repeating descriptor comparisons can diagnose a mixed installation earlier, but cannot establish executable integrity. Reintroducing them requires a concrete installation failure that packaging validation and actual Host diagnostics cannot adequately explain. + +## Consequences + +Startup does not reject a descriptor solely because its declared release schema, target, or Host protocol differs, or its Node/pnpm version strings are not semver. Packaging still rejects these cases and shell-version mismatch. Tests distinguish startup reads from packaging verification. diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.zh.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.zh.md new file mode 100644 index 0000000000..266bca5bbd --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-build-release-validation.zh.md @@ -0,0 +1,23 @@ +# Agent Note: 在打包时验证 Desktop 发布兼容性 + +Status: implemented + +[English](2026-09-09-desktop-build-release-validation.md) | 中文 + +## 问题 + +壳与运行时描述文件一起发布。每次启动比较其中的发布信息会重复打包检查,却不能证明已安装的可执行文件字节与描述文件一致。 + +## 决策 + +打包验证器负责描述文件 schema、shell 版本、平台、架构、声明的 Host 协议版本,以及 Node/pnpm semver 验证。启动读取准备 profile 所需的字段,并保留共享包记录和 Host 入口检查。实际 Host ready 消息仍然验证其协议版本。 + +本决策部分取代[内置运行时决策](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md)中的启动发布兼容性检查。该记录继续负责包归属与分发的理由。 + +## 考虑过的替代方案 + +重复比较描述文件能更早诊断混装,但不能证明可执行文件完整性。重新引入这些比较需要具体的安装故障,且打包验证和实际 Host 诊断无法充分解释该故障。 + +## 后果 + +启动不会仅因描述文件声明的发布 schema、目标或 Host 协议不同,或 Node/pnpm 版本字符串不是 semver 而拒绝运行。打包仍拒绝这些情况和 shell 版本不匹配。测试区分启动读取与打包验证。 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.i18n.yaml index 9a562164c3..e26d213c6e 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.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-09-09-desktop-immediate-window-and-direct-start.md -2026-09-09-desktop-immediate-window-and-direct-start.md: 19443bb22e5fa3e50ce027b474cd439928db9992 -2026-09-09-desktop-immediate-window-and-direct-start.zh.md: 0d79638d331bb8b66a80f37f532b36ebb1e65316 +2026-09-09-desktop-immediate-window-and-direct-start.md: 7491e4cedf058bee4dc81b7734f54bc4caf6aa72 +2026-09-09-desktop-immediate-window-and-direct-start.zh.md: 37ec49e737cd5f765ab97de8c534bb08b230a45d diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md index 19443bb22e..7491e4cedf 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.md @@ -4,6 +4,8 @@ Status: implemented English | [中文](2026-09-09-desktop-immediate-window-and-direct-start.zh.md) +Profile staging, directory-swap recovery, and automatic rollback described here are superseded by the [in-place profile decision](2026-09-09-desktop-in-place-profile.md). Other decisions remain active. + ## Problem Waiting for backend readiness leaves users without a window during profile preparation and module loading. A complete staged health-check process repeats backend startup before the application starts its serving process, while plugin startup can still fail in the serving process. @@ -12,6 +14,8 @@ Waiting for backend readiness leaves users without a window during profile prepa Electron creates the main window with a local loading page before profile reconciliation or Host startup. The page depends only on packaged shell assets and receives starting, ready, or error state through the owned preload. Readiness loads the product UI in that window; an actual startup failure displays its diagnostic, retry, and plugin-management actions there. Closing during loading cancels further startup work and waits for the pending child to exit. +The main window owns recovery because the failed Host cannot supply its own controls. Every error page retains diagnostics and exposes restart, disable-third-party-plugins, and reset-Desktop actions, plus reinstallation guidance. The actions remain available regardless of error classification. Reset removes all profile contents except its held lock, without a backup; shared product data and the Harness-home environment file remain intact. The lock lives inside the profile, and reset preserves its directory so another transaction cannot acquire a replacement lock during cleanup. Disabled third-party package files cannot block startup when no third-party bundles are enabled. Self-contained shell recovery controls use intercepted form navigation so a failed preload cannot disable them. + Profile activation starts the actual Host after journaled directory replacement. Desktop does not boot and stop a separate health-check backend. Dependency metadata and graph validation, reviewed lifecycle builds, runtime identity checks, transaction locking, and profile rollback remain in place. A failed actual startup can restore the previous profile; rollback cannot undo plugin side effects or durable Session writes. This partially supersedes staged backend probes and waiting to create the main window in the [packaging decision](2026-08-25-electron-desktop-packaging-and-updates.md) and [bundled-runtime decision](2026-09-08-desktop-bundled-runtime-and-external-plugins.md). Those notes retain release, signing, transport, resource ownership, and dependency-transaction rationale. Full runtime file verification remains a packaging operation. diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md index 0d79638d33..37ec49e737 100644 --- a/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-immediate-window-and-direct-start.zh.md @@ -4,13 +4,17 @@ Status: implemented [English](2026-09-09-desktop-immediate-window-and-direct-start.md) | 中文 +本记录中的 profile staging、目录切换恢复和自动回滚由[直接修改 profile 决策](2026-09-09-desktop-in-place-profile.zh.md)取代。其他决策继续有效。 + ## 问题 等待后端就绪会让用户在准备 profile 和加载模块期间看不到窗口。完整的 staging 健康检查进程会在应用启动服务进程前重复启动后端,而插件在实际服务进程中仍然可能启动失败。 ## 决策 -Electron 在协调 profile 或启动 Host 前,先创建显示本地加载页的主窗口。该页面只依赖打包的壳资源,并通过受控 preload 接收 starting、ready 或 error 状态。就绪后在同一窗口加载产品 UI;实际启动失败时,在其中显示诊断、重试和插件管理操作。加载期间关闭应用会取消后续启动工作,并等待正在启动的子进程退出。 +Electron 在协调 profile 或启动 Host 前,先创建显示本地加载页的主窗口。该页面只依赖打包的壳资源,并通过受控 preload 接收 starting、ready 或 error 状态。就绪后在同一窗口加载产品 UI;实际启动失败时,在其中显示诊断和恢复操作。加载期间关闭应用会取消后续启动工作,并等待正在启动的子进程退出。 + +主窗口负责恢复,因为故障 Host 无法提供自己的操作界面。每个错误页保留诊断,提供重启、禁用第三方插件和重置 Desktop 三个操作,以及重装提示。所有操作均不依赖错误分类而保持可用。重置删除 profile 内除当前持有的锁之外的全部内容,不留备份;共享产品数据和 Harness home 环境文件保持不变。锁位于 profile 内,重置保留目录,防止其他事务在清理期间取得替代锁。没有启用第三方 bundle 时,已禁用插件的文件不能阻止启动。独立内嵌错误页通过拦截表单导航执行恢复,因此 preload 故障不会使按钮失效。 profile 激活在记录式目录替换后启动实际 Host。Desktop 不会另行启动并停止一个健康检查后端。依赖元数据与依赖图验证、经过审查的生命周期构建、运行时身份检查、事务锁和 profile 回滚仍然保留。实际启动失败可以恢复旧 profile;回滚不能撤销插件副作用或持久 Session 写入。 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.i18n.yaml new file mode 100644 index 0000000000..25f423496f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.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-09-desktop-in-place-profile.md +2026-09-09-desktop-in-place-profile.md: c83bb9826a4068f699e330f911c52064790b08b6 +2026-09-09-desktop-in-place-profile.zh.md: 481dcc11d6c4dcc033f68186c88bfd96028fdbe8 diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md new file mode 100644 index 0000000000..c83bb9826a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.md @@ -0,0 +1,25 @@ +# Agent Note: Modify the Desktop profile in place + +Status: implemented + +English | [中文](2026-09-09-desktop-in-place-profile.zh.md) + +## Problem + +Staging preserves an old plugin installation but adds profile copying, directory moves, a recovery journal, and rollback state. Local plugin changes accept explicit repair after failure instead of this complexity. + +## Decision + +Desktop stops the Host and modifies the current profile directly. Shared host links are detached for package changes and restored when the operation settles. Package locking, dependency validation, and approved native builds remain. Compatible upgrades refresh links without copying plugin files. + +Package or Host failures retain partial changes for repair and retry. There is no staging profile, activation journal, directory-swap recovery, or automatic rollback. Existing scratch directories are not interpreted or deleted. + +This supersedes staging and rollback in [2026-08-25-electron-desktop-packaging-and-updates](2026-08-25-electron-desktop-packaging-and-updates.md), [2026-09-08-desktop-bundled-runtime-and-external-plugins](2026-09-08-desktop-bundled-runtime-and-external-plugins.md), [2026-09-09-desktop-immediate-window-and-direct-start](2026-09-09-desktop-immediate-window-and-direct-start.md). Other release, module-identity, and window-lifecycle decisions remain active. + +## Alternatives considered + +Staging protects the previous installation at the cost of copying and crash recovery. Versioned directories still need preparation, selection, and cleanup. Direct writes give up automatic recovery; reintroduction requires an unattended-recovery product requirement that justifies these costs. + +## Consequences + +Tests cover offline initialization, in-place upgrades, failure before writes, retained changes after Host failure, partial pnpm failure, restored host links, and exclusive package ownership. Signed application and GUI acceptance remain release-environment checks. diff --git a/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md new file mode 100644 index 0000000000..481dcc11d6 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-09-desktop-in-place-profile.zh.md @@ -0,0 +1,25 @@ +# Agent Note: 直接修改 Desktop profile + +Status: implemented + +[English](2026-09-09-desktop-in-place-profile.md) | 中文 + +## 问题 + +staging 能保留旧插件安装,但增加 profile 复制、目录移动、恢复日志和回滚状态。本地插件变更接受失败后显式修复,以避免这些复杂度。 + +## 决策 + +Desktop 停止 Host 后直接修改当前 profile。修改包前解除宿主共享链接,操作结束后恢复链接。保留包锁、依赖验证和已批准的原生构建。兼容升级只刷新链接,不复制插件文件。 + +包操作或 Host 失败会保留部分修改,供修复和重试。不使用 staging profile、激活日志、目录切换恢复或自动回滚。已有临时目录不会被解释或删除。 + +本决策取代以下记录中的 staging 和回滚:[2026-08-25-electron-desktop-packaging-and-updates](2026-08-25-electron-desktop-packaging-and-updates.zh.md), [2026-09-08-desktop-bundled-runtime-and-external-plugins](2026-09-08-desktop-bundled-runtime-and-external-plugins.zh.md), [2026-09-09-desktop-immediate-window-and-direct-start](2026-09-09-desktop-immediate-window-and-direct-start.zh.md)。其他发布、模块实例和窗口生命周期决策继续有效。 + +## 考虑过的替代方案 + +staging 以复制和崩溃恢复为代价保护旧安装。版本化目录仍需要准备、选择和清理。直接写入放弃自动恢复;只有无人值守恢复的产品要求能证明这些成本合理时,才重新引入。 + +## 后果 + +测试覆盖离线初始化、原地升级、写入前失败、Host 失败后保留修改、pnpm 部分失败、宿主链接恢复及独占包操作。签名应用和 GUI 验收仍由发布环境负责。 diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index c2b596749a..007cd91375 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: 86ef7d9eb63f3b7aee89a86b5c3a4866af034ac5 -README.zh.md: ea8976b880a5d5a3df5932c700237505d5f19d5a +README.md: 91cdd6d4ea0e001dd9ae81dc9f8e64aa5a912879 +README.zh.md: bd1381eb08477b1541b584eca7c5c5cb7c3f1cac diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 86ef7d9eb6..91cdd6d4ea 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -14,7 +14,7 @@ The desktop application is an Electron shell around the dsh Web UI. It opens no | Shared modules | Host APIs can depend on module identity. | Desktop links every bundled first-party package into the profile using directory symlinks, or Windows junctions; ordinary plugin dependencies remain local. | | State ownership | Sharing executable dependency graphs would let CLI and Desktop change each other's dsh, Cordis, plugin, or native-module versions, while two desktop processes could race on the same profile. | Electron acquires its process-lifetime single-instance lock before any profile access and exclusively owns `$DSH_HOME/profiles/desktop` plus its package-manager state. CLI and Desktop share supported product data under `$DSH_HOME`, but never executable packages, plugin activation, lockfiles, or `node_modules`. | | Transport | A listening Web service adds port ownership, authentication, CORS, and exposure concerns; Electron and upstream Node.js also need an explicit cross-process protocol. | The application opens no Web port. `dsh-app://` carries Web assets and Fetch traffic; framed byte pipes carry bounded request and response chunks with backpressure, while Node IPC carries only child lifecycle control. | -| Activation | Dependency resolution, lifecycle scripts, native modules, and plugin startup can fail, and a process can stop during directory replacement. | Release and plugin changes prepare in staging and start the actual backend after profile replacement; a journal and one rollback profile cover failed or interrupted activation. | +| Plugin changes | Package installation and Host startup can fail. | Desktop stops the Host and modifies the current profile directly. Failures retain partial changes for explicit repair; there is no automatic profile rollback. | | Updates | Independent shell and dsh updates would recreate version splits, while unchanged shell blocks should not require a complete transfer. | The Electron shell, matching dsh runtime, Node.js, and pnpm form one signed update unit. Platform update artifacts may reuse unchanged blocks, but runtime version selection never splits from the Desktop release. | The [Electron packaging and update Agent Note](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md) owns the rationale, alternatives, security constraints, and release qualification requirements behind these decisions. @@ -29,17 +29,19 @@ Electron chooses typed English or Chinese shell copy from its application locale ### Runtime and plugin activation -The signed `resources/dsh/desktop-runtime.json` binds the shell version, bundled Node version, platform, architecture, shared package versions, and final file inventory. Startup checks release metadata, shared package manifests, and required Host entry files without enumerating or hashing the runtime tree. Full file integrity verification runs during packaging. Core packages are never copied into profile storage or installed by pnpm at first launch. +The signed `resources/dsh/desktop-runtime.json` binds the shell version, bundled Node version, platform, architecture, shared package versions, and final file inventory. Startup reads the metadata and checks shared package records. Release schema, shell version, target compatibility, and file integrity are verified during packaging. Core packages are never copied into profile storage or installed by pnpm at first launch. 1. The main window displays a local loading page before profile preparation or backend startup. A fresh profile creates its manifest and shared package links, then activates and starts the actual backend once. -2. A compatible application upgrade copies plugin files and configuration into staging, refreshes shared links, and checks enabled plugins’ peer requirements. Plugin versions and lockfile remain unchanged; pnpm does not run. +2. A compatible application upgrade refreshes shared links in the current profile and checks enabled plugins’ peer requirements. Plugin files, configuration, versions, and lockfile remain in place; pnpm does not run. 3. A changed bundled Node version, platform, or architecture reinstalls the locked plugin graph with scripts disabled, validates and links host packages, then runs approved pending builds and validates again. 4. Plugin add, update, and remove operations use bundled pnpm and Desktop-owned package-manager state. Reserved host packages must be peers; nested copies and aliases of shared packages fail validation. Ordinary plugin dependencies must resolve inside the profile. -5. Activation stops the active backend, records runtime identities and the next directory move, and replaces the profile while retaining one rollback copy. Copies do not share writable hardlinks. The actual backend starts after replacement; failed activation restores the previous profile; a profile belonging to another runtime cannot boot under the current shell. +5. Plugin changes stop the backend before modifying the current profile. Successful preparation starts the Host. Package or Host startup failures retain modified files and report the error; repair the installation and retry. Desktop creates no staging directories, activation journals, or rollback copies. -The loading page does not depend on the Host. Startup failures appear in the same main window with retry and plugin-management actions. Closing during loading waits for the pending child to exit. The Electron-owned plugin window remains available when backend startup fails. Disable one plugin or all plugins to retry with their files, exact versions, and configuration retained. Disabling removes only activation entries. Updating or removing an installed plugin remains available while it is disabled. Application rollback and profile rollback are separate; runtime compatibility is checked before any backend starts. +The loading page does not depend on the Host. Every startup and backend error page retains diagnostics and offers three actions: restart the application, disable all third-party plugins and restart the Host, or reset Desktop and restart the Host. Reinstallation guidance is always visible for missing or damaged application files. Disabling plugins retains their files and skips their installation graph when none are enabled. The plugin manager remains available through the application menu. Runtime compatibility is checked before any backend starts; plugin changes have no automatic rollback. -Package transactions hold an exclusive lock through pnpm process exit. Shared links use directory symlinks on macOS/Linux and junctions on Windows; cleanup removes links without deleting their targets. Canonical filesystem paths identify shared packages, so Windows path casing alone does not trigger profile activation. Native builds follow the profile’s reviewed `allowBuilds` list; installing a new build-requiring package without approval in that list fails the transaction. +Reset deletes every entry in `$DSH_HOME/profiles/desktop` except the held transaction lock, then initializes the built-in profile. It removes Desktop configuration and installed third-party packages without a backup. Shared tasks, settings, and the Harness-home `.env` are untouched. Shell resource and preload failures use a self-contained document with the same three actions and diagnostics; its controls do not require preload. + +Package transactions hold `$DSH_HOME/profiles/desktop/lock` exclusively through pnpm process exit. Reset preserves the directory and its lock until initialization and Host startup finish. Shared links use directory symlinks on macOS/Linux and junctions on Windows; cleanup removes links without deleting their targets. Canonical filesystem paths identify shared packages, so Windows path casing alone does not trigger profile activation. Native builds follow the profile’s reviewed `allowBuilds` list; installing a new build-requiring package without approval in that list fails the transaction. ## Develop @@ -57,7 +59,7 @@ After an explicit build, `start:desktop` reconstructs the disposable project and pnpm run start:desktop ``` -Workspace development runs the current CLI and private Desktop Host packages under the invoking Node.js and disables desktop package mutations. Its explicitly linked disposable profile is the only mode allowed to resolve bundles outside its own directory. Use an unpacked application to exercise the bundled Node.js, bundled pnpm, bundled dsh resources, plugin installation, staging, and rollback paths. +Workspace development runs the current CLI and private Desktop Host packages under the invoking Node.js and disables desktop package mutations. Its explicitly linked disposable profile is the only mode allowed to resolve bundles outside its own directory. Use an unpacked application to exercise the bundled Node.js, bundled pnpm, bundled dsh resources, plugin installation and repair paths. ## Package @@ -182,7 +184,7 @@ Signed packaging emits generic-provider channel metadata for the deployment sele ## Low-level development overrides -`DSH_DESKTOP_NODE_BINARY`, `DSH_DESKTOP_PNPM_ENTRY`, `DSH_DESKTOP_DSH_DIR`, and `DSH_DESKTOP_DEV_PROJECT_DIR` select explicit resources for an unpackaged Electron process. Packaged applications ignore these variables and resolve signed resources from `process.resourcesPath`. +An unpackaged Electron process uses `.desktop-build/development/project` under its application directory as its development project. `DSH_DESKTOP_NODE_BINARY`, `DSH_DESKTOP_PNPM_ENTRY`, and `DSH_DESKTOP_DSH_DIR` select explicit runtime resources. Packaged applications ignore these variables, resolve signed resources from `process.resourcesPath`, and use the managed Desktop profile. ## Known limitations diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index ea8976b880..bd1381eb08 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -14,7 +14,7 @@ | 共享模块 | 宿主 API 可能依赖模块实例身份。 | Desktop 用目录软链接或 Windows junction 把每个内置第一方包连接到 profile;普通插件依赖保留在本地。 | | 状态归属 | 共享可执行依赖图会让 CLI 与 Desktop 相互改变 dsh、Cordis、插件或原生模块版本,而两个桌面进程还可能争用同一个 profile。 | Electron 在访问任何 profile 前获取进程生命周期单实例锁,并独占 `$DSH_HOME/profiles/desktop` 及其包管理器状态。CLI 与 Desktop 共享 `$DSH_HOME` 下受支持的产品数据,但绝不共享可执行包、插件激活、锁文件或 `node_modules`。 | | 通信 | 监听 Web 服务会引入端口归属、认证、CORS 与暴露风险;Electron 与上游 Node.js 之间也需要明确的跨进程协议。 | 应用不打开 Web 端口。`dsh-app://` 承载 Web 资源和 Fetch 流量;分帧字节管道以背压传输有界请求与响应分块,Node IPC 只承载子进程生命周期控制。 | -| 激活 | 依赖解析、生命周期脚本、原生模块与插件启动都可能失败,目录替换期间进程也可能中断。 | 发布与插件变更先在 staging 准备,替换 profile 后启动实际后端;失败或中断的激活由事务日志和一个 rollback profile 恢复。 | +| 插件变更 | 包安装和 Host 启动可能失败。 | Desktop 停止 Host 后直接修改当前 profile。失败保留部分修改供用户修复,不自动回滚 profile。 | | 更新 | 桌面壳与 dsh 独立更新会重新产生版本分裂,而桌面壳未变化的数据块不应强制完整传输。 | Electron 壳、匹配的 dsh 运行时、Node.js 与 pnpm 组成一个已签名更新单元。平台更新产物可以复用未变化的数据块,但运行时版本选择绝不脱离 Desktop 发布。 | [Electron 打包与更新 Agent Note](../../.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md)记录了这些决策背后的理由、替代方案、安全约束和发布验证要求。 @@ -29,17 +29,19 @@ Electron 根据应用 locale 选择类型化的中英文字典,并以英文作 ### 运行时与插件激活 -签名资源中的 `resources/dsh/desktop-runtime.json` 绑定 shell 版本、内置 Node 版本、平台、架构、共享包版本和最终文件清单。启动检查发布元数据、共享包 manifest 和必要的 Host 入口文件,不枚举运行时目录树或计算其文件哈希。完整的文件完整性验证在打包时执行。首次启动不会把核心包复制到 profile 存储或通过 pnpm 安装核心包。 +签名资源中的 `resources/dsh/desktop-runtime.json` 绑定 shell 版本、内置 Node 版本、平台、架构、共享包版本和最终文件清单。启动读取元数据,并检查共享包记录。发布 schema、shell 版本、目标兼容性和文件完整性在打包时验证。首次启动不会把核心包复制到 profile 存储或通过 pnpm 安装核心包。 1. 主窗口在准备 profile 或启动后端前显示本地加载页。新 profile 创建 manifest 和共享包链接,然后激活并启动一次实际后端。 -2. 兼容的应用升级把插件文件和配置复制到 staging,刷新共享链接,并检查已启用插件的 peer 要求。插件版本和锁文件保持不变;不运行 pnpm。 +2. 兼容的应用升级在当前 profile 中刷新共享链接,并检查已启用插件的 peer 要求。插件文件、配置、版本和锁文件留在原处;不运行 pnpm。 3. 内置 Node 版本、平台或架构变化时,禁用脚本重新安装锁定的插件依赖图,验证并链接宿主包,然后运行已批准的待执行构建并再次验证。 4. 插件添加、更新和删除使用内置 pnpm 及 Desktop 独有的包管理器状态。保留的宿主包必须声明为 peer;共享包的嵌套副本和别名会被验证拒绝。普通插件依赖必须解析到 profile 内部。 -5. 激活会停止活动后端,记录运行时身份和下一次目录移动,并替换 profile,同时保留一个回滚副本。复制不共享可写硬链接。替换后启动实际后端;激活失败会恢复旧 profile;属于其他运行时的 profile 不能在当前 shell 下启动。 +5. 插件变更在修改当前 profile 前停止后端。准备成功后启动 Host。包操作或 Host 启动失败保留已修改文件并报告错误;修复安装后重试。Desktop 不创建 staging 目录、激活日志或回滚副本。 -加载页不依赖 Host。启动失败在同一个主窗口显示,并提供重试和插件管理操作。加载期间关闭应用会等待正在启动的子进程退出。后端启动失败时,Electron 拥有的插件窗口仍然可用。可以停用一个或全部插件后重试,同时保留其文件、精确版本和配置。停用只移除激活条目。已停用插件仍可更新或删除。应用回滚和 profile 回滚分别处理;每次启动后端前都会检查运行时兼容性。 +加载页不依赖 Host。每个启动和后端错误页均保留诊断,并提供三个操作:重启应用、禁用全部第三方插件并重启 Host、重置 Desktop 并重启 Host。页面始终显示应用文件缺失或损坏时的重装提示。禁用插件会保留文件;没有启用的第三方插件时,不再检查它们的安装依赖图。插件管理仍可从应用菜单打开。每次启动后端前都会检查运行时兼容性;插件变更不自动回滚。 -包事务持有独占锁直到 pnpm 进程退出。共享链接在 macOS/Linux 使用目录软链接,在 Windows 使用 junction;清理只移除链接,不删除其目标。共享包使用文件系统的规范路径识别,因此 Windows 路径大小写变化不会单独触发 profile 激活。原生构建遵循 profile 中经过审查的 `allowBuilds` 列表;新安装的包如果需要构建但未在列表中获准,事务会失败。 +重置会删除 `$DSH_HOME/profiles/desktop` 内除当前持有的事务锁之外的全部内容,再初始化内置 profile。Desktop 配置和已安装第三方插件会被删除,不保留备份。共享任务、设置和 Harness home 的 `.env` 不受影响。壳资源或 preload 故障使用独立内嵌页面,保留相同的三个操作和诊断;其按钮不依赖 preload。 + +包事务独占持有 `$DSH_HOME/profiles/desktop/lock`,直到 pnpm 进程退出。重置保留目录及其锁,直到初始化和 Host 启动完成。共享链接在 macOS/Linux 使用目录软链接,在 Windows 使用 junction;清理只移除链接,不删除其目标。共享包使用文件系统的规范路径识别,因此 Windows 路径大小写变化不会单独触发 profile 激活。原生构建遵循 profile 中经过审查的 `allowBuilds` 列表;新安装的包如果需要构建但未在列表中获准,事务会失败。 ## 开发 @@ -57,7 +59,7 @@ pnpm run dev:desktop pnpm run start:desktop ``` -Workspace 开发使用调用命令的 Node.js 运行当前 CLI 与私有 Desktop Host 包,并禁用桌面包修改;只有该模式明确链接的一次性 profile 可以从自身目录外解析 bundle。需要验证内置 Node.js、内置 pnpm、内置 dsh 资源、插件安装、staging 和 rollback 时,应运行未封装安装器的应用目录。 +Workspace 开发使用调用命令的 Node.js 运行当前 CLI 与私有 Desktop Host 包,并禁用桌面包修改;只有该模式明确链接的一次性 profile 可以从自身目录外解析 bundle。需要验证内置 Node.js、内置 pnpm、内置 dsh 资源、插件安装和修复时,应运行未封装安装器的应用目录。 ## 打包 @@ -182,7 +184,7 @@ pnpm run prepare:desktop ## 底层开发覆盖项 -`DSH_DESKTOP_NODE_BINARY`、`DSH_DESKTOP_PNPM_ENTRY`、`DSH_DESKTOP_DSH_DIR` 和 `DSH_DESKTOP_DEV_PROJECT_DIR` 可以为未打包 Electron 进程选择明确的资源。打包应用会忽略这些变量,并从 `process.resourcesPath` 解析签名资源。 +未打包的 Electron 进程使用应用目录下的 `.desktop-build/development/project` 作为开发项目。`DSH_DESKTOP_NODE_BINARY`、`DSH_DESKTOP_PNPM_ENTRY` 和 `DSH_DESKTOP_DSH_DIR` 用于选择明确的运行时资源。打包应用会忽略这些变量,从 `process.resourcesPath` 解析签名资源,并使用受管 Desktop profile。 ## 已知限制 diff --git a/apps/desktop/renderer/startup.html b/apps/desktop/renderer/startup.html index e0980a5b49..098efb4f92 100644 --- a/apps/desktop/renderer/startup.html +++ b/apps/desktop/renderer/startup.html @@ -12,10 +12,13 @@

+ + diff --git a/apps/desktop/renderer/startup.js b/apps/desktop/renderer/startup.js index ce8c64361a..036b950b0a 100644 --- a/apps/desktop/renderer/startup.js +++ b/apps/desktop/renderer/startup.js @@ -4,8 +4,11 @@ async function main() { const { id, messages } = await api.locale() document.documentElement.lang = id document.querySelector('#page-title').textContent = messages.startupLoading - document.querySelector('#retry').textContent = messages.retry - document.querySelector('#plugins').textContent = messages.managePlugins + document.querySelector('#restart').textContent = messages.restartApplication + document.querySelector('#disable-plugins').textContent = messages.disableThirdPartyPlugins + document.querySelector('#reset-configuration').textContent = messages.resetConfiguration + document.querySelector('#reset-advice').textContent = messages.startupConfigurationAdvice + document.querySelector('#reinstall-advice').textContent = messages.startupReinstallAdvice function render(state) { const failed = state.phase === 'error' document.querySelector('main').setAttribute('aria-busy', String(!failed)) @@ -15,23 +18,26 @@ async function main() { document.querySelector('#error').hidden = !failed document.querySelector('#error').textContent = failed ? state.message : '' document.querySelector('#actions').hidden = !failed - document.querySelector('#retry').disabled = !failed - document.querySelector('#plugins').disabled = !failed + for (const button of document.querySelectorAll('#actions button')) button.disabled = !failed + document.querySelector('#reset-advice').hidden = !failed + document.querySelector('#reinstall-advice').hidden = !failed } let changed = false const unsubscribe = api.backend.subscribe(state => { changed = true; render(state) }) window.addEventListener('pagehide', unsubscribe, { once: true }) const initial = await api.backend.status() if (!changed) render(initial) - document.querySelector('#retry').addEventListener('click', async () => { + async function recover(operation) { render({ phase: 'starting' }) - try { await api.backend.retry() } - catch (error) { render({ phase: 'error', message: error instanceof Error ? error.message : String(error) }) } - }) - document.querySelector('#plugins').addEventListener('click', async () => { - try { await api.openPlugins() } - catch (error) { render({ phase: 'error', message: error instanceof Error ? error.message : String(error) }) } - }) + try { await operation() } + catch (error) { + const current = await api.backend.status().catch(() => undefined) + render(current?.phase === 'error' ? current : { phase: 'error', message: error instanceof Error ? error.message : String(error) }) + } + } + document.querySelector('#disable-plugins').addEventListener('click', () => { void recover(() => api.disablePlugins()) }) + document.querySelector('#reset-configuration').addEventListener('click', () => { void recover(() => api.resetConfiguration()) }) + document.querySelector('#restart').addEventListener('click', () => { void recover(() => api.restart()) }) } void main() diff --git a/apps/desktop/scripts/dev.ts b/apps/desktop/scripts/dev.ts index 3ae65d12aa..85bea68633 100644 --- a/apps/desktop/scripts/dev.ts +++ b/apps/desktop/scripts/dev.ts @@ -53,7 +53,7 @@ async function runPackageScript(script: string, cwd: string): Promise { await run(process.execPath, [packageManager, 'run', script], cwd) } -async function launchElectron(projectDir: string): Promise { +async function launchElectron(): Promise { const require = createRequire(import.meta.url) const electron: unknown = require('electron') if (typeof electron !== 'string') throw new Error('desktop development: electron executable is unavailable') @@ -65,7 +65,6 @@ async function launchElectron(projectDir: string): Promise { const environment: NodeJS.ProcessEnv = { ...process.env, DSH_HOME: home, - DSH_DESKTOP_DEV_PROJECT_DIR: projectDir, DSH_DESKTOP_HOST_INSPECT_PORT: String(hostPort), DSH_DESKTOP_NODE_BINARY: process.execPath, DSH_DESKTOP_OPEN_DEVTOOLS: process.env.DSH_DESKTOP_OPEN_DEVTOOLS ?? '1', @@ -102,14 +101,14 @@ async function main(): Promise { nodeVersion: process.versions.node, pnpmVersion, } - const projectDir = prepareDevelopmentProject({ + prepareDevelopmentProject({ projectDir: join(DEVELOPMENT_ROOT, 'project'), cliDir: join(REPOSITORY_ROOT, 'apps', 'cli'), hostDir: join(REPOSITORY_ROOT, 'apps', 'desktop-host'), dependencyDir: join(REPOSITORY_ROOT, 'node_modules', '.pnpm', 'node_modules'), release, }) - await launchElectron(projectDir) + await launchElectron() } main().catch((error: unknown) => { diff --git a/apps/desktop/src/backend-controller.ts b/apps/desktop/src/backend-controller.ts index 03c49369ab..91850ef926 100644 --- a/apps/desktop/src/backend-controller.ts +++ b/apps/desktop/src/backend-controller.ts @@ -1,7 +1,9 @@ /** Owns one backend startup and its quiescent teardown independently of windows. */ +import { desktopErrorState, type DesktopRecovery } from './startup-error.ts' + /** Backend availability presented by the desktop window. */ -export type DesktopBackendState = { readonly phase: 'starting' } | { readonly phase: 'ready' } | { readonly phase: 'error'; readonly message: string } +export type DesktopBackendState = { readonly phase: 'starting' } | { readonly phase: 'ready' } | { readonly phase: 'error'; readonly message: string; readonly recovery?: DesktopRecovery } /** Child lifecycle owned by the desktop backend controller. */ export interface DesktopBackendHost { @@ -78,7 +80,7 @@ export class DesktopBackendController { try { await this.cleanup(attempt) } catch (cleanupError) { if (cleanupError !== error) failure = new AggregateError([error, cleanupError], 'desktop backend startup and cleanup failed') } - if (!cancelled) this.update({ phase: 'error', message: failure instanceof Error ? failure.message : String(failure) }) + if (!cancelled) this.update(desktopErrorState(failure)) throw failure } }).finally(() => { if (this.pending === pending) this.pending = undefined }) @@ -130,9 +132,9 @@ export class DesktopBackendController { if (this.current.phase !== 'ready') return attempt.cancelled = true const cleanup = this.cleanup(attempt) - this.update({ phase: 'error', message: error.message }) + this.update(desktopErrorState(error)) void cleanup.catch((cleanupError: unknown) => { - if (this.attempt === attempt) this.update({ phase: 'error', message: cleanupError instanceof Error ? cleanupError.message : String(cleanupError) }) + if (this.attempt === attempt) this.update(desktopErrorState(new AggregateError([error, cleanupError], 'Desktop backend failed and could not stop'))) }) } diff --git a/apps/desktop/src/ipc.ts b/apps/desktop/src/ipc.ts index 7ac65344ea..88735a2ad4 100644 --- a/apps/desktop/src/ipc.ts +++ b/apps/desktop/src/ipc.ts @@ -16,6 +16,9 @@ export const DESKTOP_IPC = { pluginsDisableAll: 'dsh-desktop:plugins-disable-all', backendStatus: 'dsh-desktop:backend-status', backendRetry: 'dsh-desktop:backend-retry', + applicationRestart: 'dsh-desktop:application-restart', + applicationClose: 'dsh-desktop:application-close', + configurationReset: 'dsh-desktop:configuration-reset', backendState: 'dsh-desktop:backend-state', updatesCheck: 'dsh-desktop:updates-check', updatesInstall: 'dsh-desktop:updates-install', @@ -56,4 +59,8 @@ export interface DshDesktopApi { /** Startup-page controls, unavailable to backend-provided application documents. */ export interface DshDesktopStartupApi extends Pick { openPlugins(): Promise + disablePlugins(): Promise + restart(): Promise + close(): Promise + resetConfiguration(): Promise } diff --git a/apps/desktop/src/locale.ts b/apps/desktop/src/locale.ts index c937474beb..142d263d3c 100644 --- a/apps/desktop/src/locale.ts +++ b/apps/desktop/src/locale.ts @@ -5,7 +5,15 @@ export const en = { startupFailed: 'DeepSeek Harness could not start', startupLoading: 'Starting DeepSeek Harness…', startupLoadingDescription: 'Your workspace will open when it is ready.', - startupErrorDescription: 'The application could not start. Retry or manage Desktop plugins to resolve the problem.', + startupErrorDescription: 'Choose a recovery action below. Disabling third-party plugins retains their files.', + startupRestartAdvice: 'Close and restart the application. If the problem continues, keep the error details for troubleshooting.', + startupReinstallAdvice: 'If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately.', + startupPluginsAdvice: 'A third-party plugin may be preventing startup. Disable all third-party plugins and try again. Plugin files and tasks are retained.', + startupConfigurationAdvice: 'Reset Desktop deletes all Desktop profile configuration and third-party plugins without a backup, then starts a fresh profile. Shared tasks and settings are retained.', + restartApplication: 'Close and restart', + closeApplication: 'Close application', + resetConfiguration: 'Reset Desktop and retry', + disableThirdPartyPlugins: 'Disable all third-party plugins and retry', managePlugins: 'Manage plugins', pluginsMenu: 'Desktop Plugins…', pluginsMenuPackagedOnly: 'Desktop Plugins… (available in packaged applications)', @@ -55,7 +63,15 @@ export const zh = { startupFailed: 'DeepSeek Harness 无法启动', startupLoading: '正在启动 DeepSeek Harness…', startupLoadingDescription: '准备就绪后将自动打开工作区。', - startupErrorDescription: '应用未能启动。你可以重试,或管理桌面插件以解决问题。', + startupErrorDescription: '请选择下方的恢复操作。禁用第三方插件会保留插件文件。', + startupRestartAdvice: '请关闭并重启应用。如果问题持续出现,请保留错误详情以便排查。', + startupReinstallAdvice: '如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。', + startupPluginsAdvice: '第三方插件可能导致应用无法启动。请禁用全部第三方插件后重试。插件文件和任务数据会保留。', + startupConfigurationAdvice: '重置 Desktop 会删除桌面端的全部 profile 配置和第三方插件,不保留备份,然后重新初始化并启动。共享任务和设置会保留。', + restartApplication: '关闭并重启', + closeApplication: '关闭应用', + resetConfiguration: '重置 Desktop 并重试', + disableThirdPartyPlugins: '禁用全部第三方插件并重试', managePlugins: '管理插件', pluginsMenu: '桌面插件…', pluginsMenuPackagedOnly: '桌面插件…(打包应用中可用)', diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index f132afb3b2..012f444e03 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -20,9 +20,26 @@ import { DESKTOP_IPC, type DesktopUpdateState } from './ipc.ts' import { formatDesktopMessage, resolveDesktopLocale } from './locale.ts' import { claimDesktopSingleInstance } from './single-instance.ts' import { DesktopUpdateCoordinator } from './update-coordinator.ts' +import { desktopErrorState, DesktopStartupError } from './startup-error.ts' +import { startupFailureDocument } from './startup-document.ts' const SCHEME = 'dsh-app' let focusPrimaryWindow = (): void => {} +type RecoveryAction = 'restart' | 'plugins' | 'reset' +const emergencyPages = new WeakMap() +let recoverApplication = (action: RecoveryAction): Promise => { + if (action !== 'restart') return Promise.reject(new Error('Desktop recovery could not initialize; reinstall the application')) + app.relaunch() + app.quit() + return Promise.resolve() +} + +async function showEmergencyDocument(window: BrowserWindow, message: string): Promise { + const document = startupFailureDocument(resolveDesktopLocale(app.getLocale()), message) + const url = `data:text/html;charset=utf-8,${encodeURIComponent(document)}` + emergencyPages.set(window, { url, message, busy: false }) + await window.loadURL(url) +} function errorOf(reason: unknown, fallback: string): Error { return reason instanceof Error ? reason : new Error(fallback) @@ -63,13 +80,6 @@ function runtimeResources(): RuntimeResources { return { node, pnpm, dsh } } -function developmentProject(): string | undefined { - const configured = process.env.DSH_DESKTOP_DEV_PROJECT_DIR - if (configured === undefined || configured === '') return undefined - if (app.isPackaged) throw new Error('dsh desktop: development project override is unavailable in packaged applications') - return resolve(configured) -} - function developmentHostInspectPort(enabled: boolean): number | undefined { const configured = process.env.DSH_DESKTOP_HOST_INSPECT_PORT if (!enabled || configured === undefined || configured === '') return undefined @@ -98,6 +108,14 @@ function createWindow(preload: string, show = false): BrowserWindow { window.webContents.setWindowOpenHandler(() => ({ action: 'deny' })) window.webContents.on('will-navigate', (event, url) => { if (new URL(url).protocol !== `${SCHEME}:`) event.preventDefault() + const page = emergencyPages.get(window) + if (page === undefined || page.busy || window.webContents.getURL() !== page.url) return + const action = new URL(url) + if (action.protocol !== 'dsh-recovery:' || !['restart', 'plugins', 'reset'].includes(action.hostname)) return + page.busy = true + void recoverApplication(action.hostname as RecoveryAction).catch(async (error: unknown) => { + if (!window.isDestroyed()) await showEmergencyDocument(window, `${page.message}\n${desktopErrorState(error).message}`) + }).catch((error: unknown) => { console.error(error) }).finally(() => { page.busy = false }) }) return window } @@ -134,11 +152,10 @@ async function serveShellAsset(request: Request): Promise { async function main(): Promise { const resources = runtimeResources() const paths = resolveDesktopPaths() - const development = developmentProject() + const development = app.isPackaged ? undefined : join(app.getAppPath(), '.desktop-build', 'development', 'project') const activeProject = development ?? paths.profile - const hostInspectPort = developmentHostInspectPort(development !== undefined) const manager = new DesktopProjectManager(paths, resources) - let pageError: string | undefined + let pageError: Extract | undefined let quitting = false let startup: Promise | undefined let mainWindow: BrowserWindow | undefined @@ -152,10 +169,19 @@ async function main(): Promise { const startupUrl = `${SCHEME}://shell/startup.html` const applicationUrl = `${SCHEME}://app/index.html` let navigation: { window: BrowserWindow; url: string; promise: Promise } | undefined + let emergencyDocument = false + + const showEmergencyError = async (error: unknown): Promise => { + if (quitting || emergencyDocument) return + emergencyDocument = true + const diagnostic = desktopErrorState(error).message + pageError = { phase: 'error', message: diagnostic, recovery: 'reinstall' } + if (mainWindow !== undefined) await showEmergencyDocument(mainWindow, diagnostic) + } const navigateMain = (url: string): Promise => { const window = mainWindow - if (quitting || window === undefined || window.isDestroyed()) return Promise.resolve() + if (quitting || emergencyDocument || window === undefined || window.isDestroyed()) return Promise.resolve() if (navigation?.window === window && navigation.url === url) return navigation.promise const next = { window, url, promise: Promise.resolve() } next.promise = window.loadURL(url).catch((error: unknown) => { @@ -167,7 +193,7 @@ async function main(): Promise { return next.promise } const backendState = (): DesktopBackendState => pageError === undefined - ? backend.state : { phase: 'error', message: pageError } + ? backend.state : pageError const publishBackend = (state: DesktopBackendState): void => { for (const window of BrowserWindow.getAllWindows()) { window.webContents.send(DESKTOP_IPC.backendState, state) @@ -175,9 +201,32 @@ async function main(): Promise { } const backend = new DesktopBackendController((onFailure) => { if (development === undefined) manager.assertProfileRuntime(activeProject) - return new DesktopHostProcess(resources.node, development ?? resources.dsh, activeProject, hostInspectPort, process.env, onFailure) + const hostInspectPort = developmentHostInspectPort(development !== undefined) + const pluginsEnabled = development === undefined && manager.hasEnabledPlugins() + const classify = (error: Error): Error => { + if (error instanceof DesktopStartupError) return error + if ((error.message.includes(resources.node) || error.message.includes(resources.dsh)) + && /ENOENT|Cannot find|failed to (?:read|parse) overlay/u.test(error.message)) { + return new DesktopStartupError('reinstall', error) + } + if (error.message.includes('only the launching environment may set') + || /failed to (?:read|parse) (?:overlay|patches)|must be a top-level YAML array|patchReload must be/u.test(error.message)) { + return new DesktopStartupError('configuration', error) + } + return pluginsEnabled ? new DesktopStartupError('plugins', error) : error + } + const host = new DesktopHostProcess(resources.node, development ?? resources.dsh, activeProject, hostInspectPort, process.env, + (error) => { onFailure(classify(error)) }) + return { + async start() { + try { return await host.start() } + catch (error) { throw classify(errorOf(error, messages.startupFailed)) } + }, + stop: () => host.stop(), + fetch: (request: Request) => host.fetch(request), + } }, (state) => { - if (state.phase === 'starting') pageError = undefined + if (state.phase === 'starting' && !emergencyDocument) pageError = undefined publishBackend(backendState()) if (state.phase === 'error') void navigateMain(startupUrl).catch((error: unknown) => { console.error(error) }) }) @@ -191,14 +240,34 @@ async function main(): Promise { } const hooks: DesktopProjectHooks = { - beforeActivate: () => backend.stop(), - afterActivate: () => backend.start(async () => {}), + beforeChange: () => backend.stop(), + afterChange: () => backend.start(async () => {}), + } + + recoverApplication = async (action): Promise => { + await startup?.catch(() => undefined) + await backend.stop() + if (action === 'restart') { + app.relaunch() + app.quit() + return + } + if (development !== undefined) throw new Error('Desktop profile recovery requires a packaged application') + if (action === 'reset') await manager.resetConfiguration(hooks) + else await manager.mutate({ type: 'plugins-disable-all' }, hooks) + emergencyDocument = false + pageError = undefined + navigation = undefined + await navigateMain(applicationUrl) } const showStartupError = async (error: unknown): Promise => { if (quitting) return - pageError = errorOf(error, messages.startupFailed).message - await navigateMain(startupUrl) + pageError = desktopErrorState(error) + try { await navigateMain(startupUrl) } + catch (navigationError) { + await showEmergencyError(new AggregateError([error, navigationError], messages.startupFailed)) + } publishBackend(backendState()) } const reconcileBackend = (): Promise => { @@ -207,7 +276,7 @@ async function main(): Promise { await navigateMain(startupUrl) await backend.start(async () => { if (development === undefined) { - await manager.applyRelease(app.getVersion(), { beforeActivate: async () => {}, afterActivate: async () => {} }) + await manager.applyRelease() } }) if (backend.host !== undefined) await navigateMain(applicationUrl) @@ -228,7 +297,13 @@ async function main(): Promise { protocol.handle(SCHEME, (request) => { const url = new URL(request.url) - if (url.hostname === 'shell') return serveShellAsset(request) + if (url.hostname === 'shell') return serveShellAsset(request).then((response) => { + if (response.status >= 400 && ['/startup.html', '/startup.js', '/startup.css'].includes(url.pathname)) { + void showEmergencyError(new Error(`Desktop recovery resource could not be loaded: ${url.pathname} (HTTP ${response.status})`)) + .catch((error: unknown) => { console.error(error) }) + } + return response + }) if (url.hostname !== 'app') return Promise.resolve(new Response(null, { status: 404 })) const active = backend.host if (active === undefined) return Promise.resolve(new Response('backend unavailable', { status: 503 })) @@ -288,6 +363,32 @@ async function main(): Promise { await reconcileBackend() focusPrimaryWindow() }) + ipcMain.handle(DESKTOP_IPC.applicationClose, (event) => { + assertDesktopSender(event, ['shell']) + app.quit() + }) + ipcMain.handle(DESKTOP_IPC.applicationRestart, async (event) => { + assertDesktopSender(event, ['shell']) + try { + await recoverApplication('restart') + } catch (error) { + await showStartupError(error) + } + }) + ipcMain.handle(DESKTOP_IPC.configurationReset, async (event) => { + assertDesktopSender(event, ['shell']) + if (development !== undefined) throw new Error('Desktop configuration reset requires a packaged application') + const failure = backendState() + if (failure.phase !== 'error') { + throw new Error('Desktop profile reset requires a startup failure') + } + await startup?.catch(() => undefined) + try { + await recoverApplication('reset') + } catch (error) { + await showStartupError(error) + } + }) ipcMain.handle(DESKTOP_IPC.updatesCheck, async (event) => { assertDesktopSender(event, ['shell']) return updates.check() @@ -375,6 +476,13 @@ async function main(): Promise { const window = createWindow(appPreload, true) mainWindow = window window.on('closed', () => { if (mainWindow === window) mainWindow = undefined }) + window.webContents.on('preload-error', (_event, _path, error) => { + void showEmergencyError(error).catch((failure: unknown) => { console.error(failure) }) + }) + window.webContents.on('render-process-gone', (_event, details) => { + void showStartupError(new Error(`Desktop renderer exited: ${details.reason}`)) + .catch((failure: unknown) => { console.error(failure) }) + }) return window } focusPrimaryWindow = () => { @@ -425,6 +533,7 @@ if (ownsDesktopInstance) void app.whenReady().then(main).catch(async (error: unk if (diagnosticFile !== undefined) { await writeFile(diagnosticFile, `${error instanceof Error ? error.stack ?? message : message}\n`).catch(() => undefined) } - dialog.showErrorBox(resolveDesktopLocale(app.getLocale()).messages.startupFailed, message) - app.exit(1) + const window = BrowserWindow.getAllWindows()[0] ?? createWindow(fileURLToPath(new URL('./preload-app.cjs', import.meta.url)), true) + window.once('closed', () => { app.quit() }) + await showEmergencyDocument(window, message) }) diff --git a/apps/desktop/src/paths.ts b/apps/desktop/src/paths.ts index 4f883929db..5727e5c013 100644 --- a/apps/desktop/src/paths.ts +++ b/apps/desktop/src/paths.ts @@ -7,9 +7,6 @@ import { resolveDshHome } from '@deepseek-ai/dsh-home-paths' export interface DesktopPaths { readonly root: string readonly profile: string - readonly staging: string - readonly rollback: string - readonly pending: string readonly lock: string readonly pnpm: { readonly root: string @@ -32,10 +29,7 @@ export function resolveDesktopPaths(dshHome: string = resolveDshHome()): Desktop return { root, profile: join(dshHome, 'profiles', 'desktop'), - staging: join(root, 'staging'), - rollback: join(root, 'rollback', 'profile'), - pending: join(root, 'pending.json'), - lock: join(root, 'lock'), + lock: join(dshHome, 'profiles', 'desktop', 'lock'), pnpm: { root: pnpm, store: join(pnpm, 'store'), diff --git a/apps/desktop/src/preload-app.ts b/apps/desktop/src/preload-app.ts index 140a7369a4..65c55ccf11 100644 --- a/apps/desktop/src/preload-app.ts +++ b/apps/desktop/src/preload-app.ts @@ -17,6 +17,10 @@ const startup: DshDesktopStartupApi = { }, }, openPlugins: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsOpen) as Promise, + disablePlugins: () => ipcRenderer.invoke(DESKTOP_IPC.pluginsDisableAll) as Promise, + restart: () => ipcRenderer.invoke(DESKTOP_IPC.applicationRestart) as Promise, + close: () => ipcRenderer.invoke(DESKTOP_IPC.applicationClose) as Promise, + resetConfiguration: () => ipcRenderer.invoke(DESKTOP_IPC.configurationReset) as Promise, } contextBridge.exposeInMainWorld('dshDesktop', location.protocol === 'dsh-app:' && location.hostname === 'shell' diff --git a/apps/desktop/src/profile-packages.ts b/apps/desktop/src/profile-packages.ts index 0ec5ca573e..18aa4ffaf6 100644 --- a/apps/desktop/src/profile-packages.ts +++ b/apps/desktop/src/profile-packages.ts @@ -1,10 +1,11 @@ /** Desktop-owned host links and validation of the external plugin dependency graph. */ import { createHash } from 'node:crypto' -import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, readdirSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' +import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, readdirSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' import { createRequire } from 'node:module' import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { satisfies } from 'semver' +import { DesktopStartupError } from './startup-error.ts' import { desktopRuntimeId, runtimePath, type DesktopRuntimeDescriptor } from './runtime-tree.ts' /** Applied runtime identity and the only links Desktop may replace. */ @@ -52,6 +53,11 @@ function inside(root: string, path: string): boolean { * @returns Validated state, or undefined for an uninitialized profile. */ export function readDesktopProfileState(profile: string): DesktopProfileState | undefined { + try { return readProfileState(profile) } + catch (error) { throw new DesktopStartupError('configuration', error) } +} + +function readProfileState(profile: string): DesktopProfileState | undefined { const path = join(profile, DESKTOP_PROFILE_STATE) if (!existsSync(path)) return undefined const value: unknown = JSON.parse(readFileSync(path, 'utf8')) @@ -85,7 +91,7 @@ export function desktopPluginLockHash(profile: string): string { /** * Remove only recorded host links, without following even broken targets. - * @param profile - Active or copied profile. + * @param profile - Desktop profile. */ export function unlinkDesktopHostPackages(profile: string): void { for (const link of readDesktopProfileState(profile)?.links ?? []) { @@ -99,25 +105,6 @@ export function unlinkDesktopHostPackages(profile: string): void { } } -/** - * Copy plugin files without copying host packages or sharing writable hardlinks. - * @param source - Active Desktop profile. - * @param target - Empty transaction profile directory. - */ -export function copyDesktopProfile(source: string, target: string): void { - const owned = readDesktopProfileState(source)?.links ?? [] - for (const link of owned) { - const path = join(source, 'node_modules', link.name) - const entry = stat(path) - if (entry !== undefined && (!entry.isSymbolicLink() || resolve(dirname(path), readlinkSync(path)) !== resolve(link.target))) { - throw new Error(`desktop profile: refusing to copy unowned package ${link.name}`) - } - } - const links = new Set(owned.map(link => join(source, 'node_modules', link.name))) - cpSync(source, target, { recursive: true, verbatimSymlinks: true, force: false, errorOnExist: true, - filter: path => !links.has(path) }) -} - /** * Bind an external profile to this application's real package directories. * @param profile - Candidate profile. @@ -191,10 +178,14 @@ export function validateDesktopPluginGraph( profile: string, root: string, runtime: DesktopRuntimeDescriptor, activePlugins: readonly string[], ): void { const profileRoot = realpathSync.native(profile) - const shared = new Map(runtime.sharedPackages.map(entry => [entry.name, realpathSync.native(runtimePath(root, entry.path))])) + const shared = new Map(runtime.sharedPackages.map((entry) => { + try { return [entry.name, realpathSync.native(runtimePath(root, entry.path))] as const } + catch (error) { throw new DesktopStartupError('reinstall', error) } + })) for (const [name, path] of shared) { if (packageFrom(profile, name) !== path) throw new Error(`desktop profile: missing or incorrect host link ${name}`) } + if (activePlugins.length === 0) return const scanned = new Set() const scan = (modules: string): void => { if (!existsSync(modules)) return @@ -247,8 +238,12 @@ export function validateDesktopPluginGraph( } } for (const name of activePlugins) { - const path = packageFrom(profile, name) - if (path === undefined || !inside(profileRoot, path)) throw new Error(`desktop profile: missing local plugin ${name}`) - visit(path, name) + try { + const path = packageFrom(profile, name) + if (path === undefined || !inside(profileRoot, path)) throw new Error(`desktop profile: missing local plugin ${name}`) + visit(path, name) + } catch (error) { + throw new DesktopStartupError('plugins', error) + } } } diff --git a/apps/desktop/src/project-manager.ts b/apps/desktop/src/project-manager.ts index f6759775e1..d87623dcba 100644 --- a/apps/desktop/src/project-manager.ts +++ b/apps/desktop/src/project-manager.ts @@ -1,8 +1,7 @@ -/** Transactional owner of the reserved desktop profile and its private pnpm state. */ +/** In-place owner of the reserved desktop profile and its private pnpm state. */ import { valid } from 'semver' import { spawn } from 'node:child_process' -import { randomUUID } from 'node:crypto' import { existsSync, fsyncSync, @@ -12,13 +11,13 @@ import { openSync, closeSync, readFileSync, + readdirSync, realpathSync, - renameSync, unlinkSync, writeFileSync, writeSync, } from 'node:fs' -import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' +import { delimiter, dirname, join, resolve, sep } from 'node:path' import { DESKTOP_HOST_PACKAGE, desktopCorePackageOverrides, @@ -27,9 +26,10 @@ import { import type { DesktopPaths } from './paths.ts' import { removeOwnedDirectory } from './owned-directory.ts' import type { DesktopRelease } from './release.ts' +import { DesktopStartupError } from './startup-error.ts' import { desktopRuntimeId, readDesktopRuntime, type DesktopRuntimeDescriptor } from './runtime-tree.ts' import { - copyDesktopProfile, desktopPluginLockHash, linkDesktopHostPackages, readDesktopProfileState, + desktopPluginLockHash, linkDesktopHostPackages, readDesktopProfileState, unlinkDesktopHostPackages, validateDesktopPluginGraph, type DesktopProfileState, } from './profile-packages.ts' @@ -53,16 +53,6 @@ interface DesktopProjectManifest { } } -/** Journaled activation step used for crash recovery. */ -interface DesktopPendingTransaction { - readonly schemaVersion: 1 - readonly id: string - readonly stagingProfile: string - readonly fromRuntimeId: string | null - readonly toRuntimeId: string - readonly step: 'prepared' | 'active-moved' | 'staging-activated' -} - /** Exact executables the desktop shell bundles. */ export interface DesktopRuntimeExecutables { readonly node: string @@ -70,12 +60,12 @@ export interface DesktopRuntimeExecutables { readonly dsh: string } -/** Hooks that bind project replacement to the active backend lifecycle. */ +/** Hooks that stop the backend before profile writes and restart it after success. */ export interface DesktopProjectHooks { - /** Stop the active backend and await process exit before directory moves. */ - beforeActivate(): Promise - /** Start the selected active project after commit or rollback. */ - afterActivate(): Promise + /** Stop the active backend and await process exit before modifying its files. */ + beforeChange(): Promise + /** Start the modified profile after package preparation succeeds. */ + afterChange(): Promise } /** Supported dependency mutation. */ @@ -124,11 +114,6 @@ function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null } -function isDescendant(root: string, target: string): boolean { - const child = relative(root, target) - return child !== '' && child !== '..' && !child.startsWith(`..${sep}`) && !isAbsolute(child) -} - function assertPackageName(name: string): void { if (!PACKAGE_NAME_PATTERN.test(name)) throw new Error(`desktop project: invalid npm package name ${JSON.stringify(name)}`) } @@ -163,6 +148,11 @@ export function packageNameFromSpec(spec: string): string | undefined { } function projectManifest(projectDir: string): DesktopProjectManifest { + try { return readProjectManifest(projectDir) } + catch (error) { throw new DesktopStartupError('configuration', error) } +} + +function readProjectManifest(projectDir: string): DesktopProjectManifest { const path = join(projectDir, 'package.json') const value = readJson(path) const dsh = isRecord(value) && isRecord(value.dsh) ? value.dsh : undefined @@ -183,11 +173,11 @@ function projectManifest(projectDir: string): DesktopProjectManifest { function profilePluginNames(projectDir: string): readonly string[] { const bundles = projectManifest(projectDir).dsh.profile.bundles if (!DESKTOP_PROFILE_BUNDLES.every((bundle, index) => bundles[index] === bundle)) { - throw new Error('desktop project: profile must begin with the built-in desktop bundle list') + throw new DesktopStartupError('configuration', new Error('desktop project: profile must begin with the built-in desktop bundle list')) } const plugins = bundles.slice(DESKTOP_PROFILE_BUNDLES.length) if (new Set(bundles).size !== bundles.length) { - throw new Error('desktop project: profile bundle list contains a duplicate package') + throw new DesktopStartupError('configuration', new Error('desktop project: profile bundle list contains a duplicate package')) } for (const plugin of plugins) assertPackageName(plugin) return plugins @@ -234,7 +224,7 @@ function inspectPlugin(projectDir: string, requestedName: string): DesktopPlugin return { name: requestedName, version: manifest.version, enabled: profilePluginNames(projectDir).includes(requestedName) } } -/** Transactional desktop npm project manager. */ +/** Desktop npm project manager with direct writes and no rollback. */ export class DesktopProjectManager { private lockDescriptor: number | undefined private descriptor: DesktopRuntimeDescriptor | undefined @@ -248,50 +238,38 @@ export class DesktopProjectManager { readonly runtime: DesktopRuntimeExecutables, ) {} - /** Recover an interrupted directory replacement before reading the active project. */ - recover(): void { - if (!existsSync(this.paths.pending)) return - const value = readJson(this.paths.pending) - if (!isRecord(value) || value.schemaVersion !== 1 - || typeof value.id !== 'string' || typeof value.stagingProfile !== 'string' - || !isDescendant(this.paths.staging, value.stagingProfile) - || value.stagingProfile !== join(this.paths.staging, value.id, 'profile') - || (value.fromRuntimeId !== null && (typeof value.fromRuntimeId !== 'string' || !/^[a-f0-9]{64}$/u.test(value.fromRuntimeId))) - || typeof value.toRuntimeId !== 'string' || !/^[a-f0-9]{64}$/u.test(value.toRuntimeId) - || (value.step !== 'prepared' && value.step !== 'active-moved' && value.step !== 'staging-activated')) { - throw new Error(`desktop project: invalid activation journal ${this.paths.pending}`) - } - const pending: DesktopPendingTransaction = { - schemaVersion: 1, - id: value.id, - stagingProfile: value.stagingProfile, - fromRuntimeId: value.fromRuntimeId, - toRuntimeId: value.toRuntimeId, - step: value.step, - } - if (pending.step === 'staging-activated' && !existsSync(pending.stagingProfile) && existsSync(this.paths.profile)) { - if (readDesktopProfileState(this.paths.profile)?.runtimeId !== pending.toRuntimeId) { - throw new Error('desktop project: activated profile does not match its journal') - } - removeOwnedDirectory(this.paths.profile) - } - if (!existsSync(this.paths.profile) && pending.fromRuntimeId !== null && existsSync(this.paths.rollback)) { - if (readDesktopProfileState(this.paths.rollback)?.runtimeId !== pending.fromRuntimeId) { - throw new Error('desktop project: rollback profile does not match its journal') - } - mkdirSync(dirname(this.paths.profile), { recursive: true }) - renameSync(this.paths.rollback, this.paths.profile) - } - removeOwnedDirectory(pending.stagingProfile) - unlinkSync(this.paths.pending) - } - /** Read the active desktop plugin inventory. */ listPlugins(): readonly DesktopPluginRecord[] { if (!existsSync(this.paths.profile)) return [] return pluginRecords(this.paths.profile) } + /** @returns Whether the profile enables any third-party bundle, without loading plugin files. */ + hasEnabledPlugins(): boolean { + return existsSync(this.paths.profile) && profilePluginNames(this.paths.profile).length > 0 + } + + /** + * Reinitialize the profile, deleting configuration and third-party packages without a backup. + * @param hooks - Stop the Host before resetting files; restart after preparation succeeds. + * @returns Completion of reset; the held lock and shared product data are preserved. + */ + async resetConfiguration(hooks: DesktopProjectHooks): Promise { + await this.withLock(async () => { + await hooks.beforeChange() + this.descriptor = this.readRuntime() + for (const entry of readdirSync(this.paths.profile, { withFileTypes: true })) { + const path = join(this.paths.profile, entry.name) + if (path === this.paths.lock) continue + if (entry.isDirectory()) removeOwnedDirectory(path) + else unlinkSync(path) + } + createPluginProfile(this.paths.profile) + this.prepareProfile(this.paths.profile) + await hooks.afterChange() + }) + } + /** Read the dsh version supplied by this application's verified resources. */ dshVersion(): string { return this.currentRuntime().release.version @@ -316,6 +294,11 @@ export class DesktopProjectManager { return this.descriptor } + private readRuntime(): DesktopRuntimeDescriptor { + try { return readDesktopRuntime(this.runtime.dsh) } + catch (error) { throw new DesktopStartupError('reinstall', error) } + } + private prepareProfile(projectDir: string): void { const runtime = this.currentRuntime() linkDesktopHostPackages(projectDir, this.runtime.dsh, runtime) @@ -323,14 +306,13 @@ export class DesktopProjectManager { } /** Read release metadata and reconcile its external profile without installing core packages. */ - async applyRelease(electronVersion: string, hooks: DesktopProjectHooks): Promise { + async applyRelease(): Promise { return this.withLock(async () => { - this.recover() - const target = readDesktopRuntime(this.runtime.dsh, electronVersion) + const target = this.readRuntime() this.descriptor = target const previous = readDesktopProfileState(this.paths.profile) - if (existsSync(this.paths.profile) && previous === undefined) { - throw new Error('desktop project: existing profile is not a Desktop plugin profile') + if (previous === undefined && readdirSync(this.paths.profile).some(name => join(this.paths.profile, name) !== this.paths.lock)) { + throw new DesktopStartupError('configuration', new Error('desktop project: existing profile is not a Desktop plugin profile')) } if (previous?.runtimeId === desktopRuntimeId(target) && previous.lockHash === desktopPluginLockHash(this.paths.profile) @@ -341,37 +323,38 @@ export class DesktopProjectManager { validateDesktopPluginGraph(this.paths.profile, this.runtime.dsh, target, profilePluginNames(this.paths.profile)) return false } - const stagingProfile = this.newStagingProfile() - try { - if (previous === undefined) createPluginProfile(stagingProfile) - else copyDesktopProfile(this.paths.profile, stagingProfile) - await this.reconcileProfile(stagingProfile, previous) - await this.activate(stagingProfile, hooks) - return true - } catch (error) { - removeOwnedDirectory(stagingProfile) - throw error - } + if (previous === undefined) createPluginProfile(this.paths.profile) + await this.reconcileProfile(this.paths.profile, previous) + return true }) } - /** Apply an exact plugin dependency or activation change through a staging project. */ + /** Modify the current profile while its backend is stopped; failures retain partial changes. */ async mutate(mutation: DesktopProjectMutation, hooks: DesktopProjectHooks): Promise { await this.withLock(async () => { - this.recover() this.currentRuntime() if (!existsSync(this.paths.profile)) throw new Error('desktop project: active profile is not installed') - const stagingProfile = this.newStagingProfile() - try { - copyDesktopProfile(this.paths.profile, stagingProfile) - await this.applyMutation(stagingProfile, mutation) - await this.reconcileProfile(stagingProfile, readDesktopProfileState(stagingProfile), - mutation.type !== 'plugin-toggle' && mutation.type !== 'plugins-disable-all') - await this.activate(stagingProfile, hooks) - } catch (error) { - removeOwnedDirectory(stagingProfile) - throw error + await hooks.beforeChange() + if (mutation.type === 'plugins-disable-all') { + const manifest = projectManifest(this.paths.profile) + writeJson(join(this.paths.profile, 'package.json'), { + ...manifest, + dsh: { ...manifest.dsh, profile: { ...manifest.dsh.profile, bundles: [...DESKTOP_PROFILE_BUNDLES] } }, + }) + this.prepareProfile(this.paths.profile) + await hooks.afterChange() + return } + const previous = readDesktopProfileState(this.paths.profile) + const packagesChanged = mutation.type !== 'plugin-toggle' + if (packagesChanged) unlinkDesktopHostPackages(this.paths.profile) + try { + await this.applyMutation(this.paths.profile, mutation) + } finally { + if (packagesChanged) linkDesktopHostPackages(this.paths.profile, this.runtime.dsh, this.currentRuntime()) + } + await this.reconcileProfile(this.paths.profile, previous, packagesChanged) + await hooks.afterChange() }) } @@ -394,13 +377,7 @@ export class DesktopProjectManager { this.prepareProfile(projectDir) } - private newStagingProfile(): string { - const path = join(this.paths.staging, randomUUID(), 'profile') - mkdirSync(path, { recursive: true, mode: 0o700 }) - return path - } - - private async applyMutation(projectDir: string, mutation: DesktopProjectMutation): Promise { + private async applyMutation(projectDir: string, mutation: Exclude): Promise { switch (mutation.type) { case 'plugin-add': { const requestedName = packageNameFromSpec(mutation.spec) @@ -442,9 +419,6 @@ export class DesktopProjectManager { ) } return - case 'plugins-disable-all': - writeProfilePlugins(projectDir, pluginRecords(projectDir).map(plugin => ({ ...plugin, enabled: false }))) - return case 'plugin-toggle': { assertPackageName(mutation.name) const plugins = pluginRecords(projectDir) @@ -459,42 +433,6 @@ export class DesktopProjectManager { } } - private async activate(stagingProfile: string, hooks: DesktopProjectHooks): Promise { - const pending: DesktopPendingTransaction = { - schemaVersion: 1, - id: basename(dirname(stagingProfile)), - stagingProfile, - fromRuntimeId: readDesktopProfileState(this.paths.profile)?.runtimeId ?? null, - toRuntimeId: desktopRuntimeId(this.currentRuntime()), - step: 'prepared', - } - writeJson(this.paths.pending, pending) - let activeMoved = false - let stagingActivated = false - try { - await hooks.beforeActivate() - removeOwnedDirectory(this.paths.rollback) - mkdirSync(dirname(this.paths.rollback), { recursive: true, mode: 0o700 }) - writeJson(this.paths.pending, { ...pending, step: 'active-moved' } satisfies DesktopPendingTransaction) - if (existsSync(this.paths.profile)) { - renameSync(this.paths.profile, this.paths.rollback) - activeMoved = true - } - mkdirSync(dirname(this.paths.profile), { recursive: true, mode: 0o700 }) - writeJson(this.paths.pending, { ...pending, step: 'staging-activated' } satisfies DesktopPendingTransaction) - renameSync(stagingProfile, this.paths.profile) - stagingActivated = true - await hooks.afterActivate() - unlinkSync(this.paths.pending) - } catch (error) { - if (stagingActivated) removeOwnedDirectory(this.paths.profile) - if (activeMoved && existsSync(this.paths.rollback)) renameSync(this.paths.rollback, this.paths.profile) - if (existsSync(this.paths.pending)) unlinkSync(this.paths.pending) - await hooks.afterActivate().catch(() => undefined) - throw error - } - } - private async runPnpm(projectDir: string, args: readonly string[]): Promise { const [command, ...commandArgs] = args if (command === undefined) throw new Error('desktop project: pnpm command is required') @@ -586,7 +524,8 @@ export class DesktopProjectManager { } private async withLock(operation: () => Promise): Promise { - mkdirSync(this.paths.root, { recursive: true, mode: 0o700 }) + mkdirSync(this.paths.profile, { recursive: true, mode: 0o700 }) + if (lstatSync(this.paths.profile).isSymbolicLink()) throw new Error('desktop project: profile directory must not be a link') let descriptor: number try { descriptor = openSync(this.paths.lock, 'wx', 0o600) diff --git a/apps/desktop/src/runtime-tree.ts b/apps/desktop/src/runtime-tree.ts index 8f02a46497..30b083bbbb 100644 --- a/apps/desktop/src/runtime-tree.ts +++ b/apps/desktop/src/runtime-tree.ts @@ -1,11 +1,11 @@ /** Relocatable, integrity-recorded production packages carried by one Desktop release. */ import { createHash } from 'node:crypto' -import { existsSync, lstatSync, readdirSync, readFile, readFileSync, writeFileSync } from 'node:fs' +import { lstatSync, readdirSync, readFile, readFileSync, writeFileSync } from 'node:fs' import { isAbsolute, join, relative, sep } from 'node:path' import { promisify } from 'node:util' import { valid } from 'semver' -import { DESKTOP_HOST_PACKAGE, DESKTOP_HOST_RUNTIME_FILES } from './core-package-set.ts' +import { DESKTOP_HOST_PACKAGE } from './core-package-set.ts' import { parseDesktopRelease, type DesktopRelease } from './release.ts' /** Descriptor at the root of the immutable Desktop resource tree. */ @@ -143,22 +143,21 @@ export function writeDesktopRuntime( } /** - * Read release metadata and check shared manifests and Host entries without scanning runtime contents. + * Read packaged metadata and check shared package records. * @param root - Current application's runtime resources. - * @param electronVersion - Expected shell version. - * @param target - Required execution target; defaults to the current process. - * @returns Validated runtime descriptor. + * @returns Runtime metadata whose release compatibility is verified during packaging. */ -export function readDesktopRuntime( - root: string, electronVersion: string, target: { platform: NodeJS.Platform; arch: string } = process, -): DesktopRuntimeDescriptor { +export function readDesktopRuntime(root: string): DesktopRuntimeDescriptor { const value: unknown = JSON.parse(readFileSync(join(root, DESKTOP_RUNTIME_FILE), 'utf8')) - if (!record(value) || value.schemaVersion !== 1 || value.platform !== target.platform || value.arch !== target.arch + if (!record(value) || typeof value.platform !== 'string' || typeof value.arch !== 'string' || !Array.isArray(value.sharedPackages) || !Array.isArray(value.files)) { - throw new Error('desktop runtime: invalid descriptor or incompatible platform/architecture') + throw new Error('desktop runtime: invalid descriptor') } - const release = parseDesktopRelease(value.release) - if (release.version !== electronVersion) throw new Error(`desktop runtime: ${release.version} does not match Electron ${electronVersion}`) + if (!record(value.release) || typeof value.release.version !== 'string' + || typeof value.release.nodeVersion !== 'string' || typeof value.release.pnpmVersion !== 'string') { + throw new Error('desktop runtime: invalid release fields') + } + const release = value.release as unknown as DesktopRelease const sharedPackages = value.sharedPackages.map((entry: unknown): DesktopSharedPackage => { if (!record(entry) || typeof entry.name !== 'string' || !PACKAGE_NAME.test(entry.name) || typeof entry.version !== 'string' || valid(entry.version) === null || entry.path !== `node_modules/${entry.name}`) { @@ -169,34 +168,14 @@ export function readDesktopRuntime( if (new Set(sharedPackages.map(entry => entry.name)).size !== sharedPackages.length) { throw new Error('desktop runtime: duplicate shared package') } - const files = value.files.map((entry: unknown): DesktopRuntimeFile => { - if (!record(entry) || typeof entry.path !== 'string' || typeof entry.bytes !== 'number' - || !Number.isSafeInteger(entry.bytes) || entry.bytes < 0 || typeof entry.executable !== 'boolean' - || typeof entry.sha256 !== 'string' || !/^[a-f0-9]{64}$/u.test(entry.sha256)) { - throw new Error('desktop runtime: invalid file inventory') - } - runtimePath(root, entry.path) - return { path: entry.path, bytes: entry.bytes, sha256: entry.sha256, executable: entry.executable } - }).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0) - for (const entry of sharedPackages) { - const manifest: unknown = JSON.parse(readFileSync(join(runtimePath(root, entry.path), 'package.json'), 'utf8')) - if (!record(manifest) || manifest.name !== entry.name || manifest.version !== entry.version) { - throw new Error(`desktop runtime: shared package metadata mismatch for ${entry.name}`) - } - } + const files = value.files as DesktopRuntimeFile[] for (const name of ['@deepseek-ai/dsh', DESKTOP_HOST_PACKAGE]) { if (sharedPackages.find(entry => entry.name === name)?.version !== release.version) { throw new Error(`desktop runtime: missing or mismatched ${name}`) } } - for (const file of DESKTOP_HOST_RUNTIME_FILES) { - const path = `node_modules/${DESKTOP_HOST_PACKAGE}/${file}` - if (!files.some(entry => entry.path === path) || !existsSync(runtimePath(root, path)) - || !lstatSync(runtimePath(root, path)).isFile()) { - throw new Error(`desktop runtime: missing Host file ${file}`) - } - } - return { schemaVersion: 1, release, platform: target.platform, arch: target.arch, sharedPackages, files } + return { schemaVersion: value.schemaVersion as 1, release, platform: value.platform as NodeJS.Platform, + arch: value.arch, sharedPackages, files } } /** @@ -209,7 +188,18 @@ export function readDesktopRuntime( export async function verifyDesktopRuntime( root: string, electronVersion: string, target: { platform: NodeJS.Platform; arch: string } = process, ): Promise { - const descriptor = readDesktopRuntime(root, electronVersion, target) + const descriptor = readDesktopRuntime(root) + if (descriptor.schemaVersion !== 1 || descriptor.platform !== target.platform || descriptor.arch !== target.arch) { + throw new Error('desktop runtime: invalid descriptor or incompatible platform/architecture') + } + const release = parseDesktopRelease(descriptor.release) + if (release.version !== electronVersion) throw new Error(`desktop runtime: ${release.version} does not match Electron ${electronVersion}`) + for (const entry of descriptor.sharedPackages) { + const manifest: unknown = JSON.parse(readFileSync(join(runtimePath(root, entry.path), 'package.json'), 'utf8')) + if (!record(manifest) || manifest.name !== entry.name || manifest.version !== entry.version) { + throw new Error(`desktop runtime: shared package metadata mismatch for ${entry.name}`) + } + } const actual = await inventoryRuntimeForVerification(root) // Windows has no portable Unix executable permission bits. const comparable = (items: readonly DesktopRuntimeFile[]): unknown => process.platform === 'win32' diff --git a/apps/desktop/src/startup-document.ts b/apps/desktop/src/startup-document.ts new file mode 100644 index 0000000000..65245649e2 --- /dev/null +++ b/apps/desktop/src/startup-document.ts @@ -0,0 +1,25 @@ +/** Self-contained recovery document for an unavailable shell renderer or preload. */ + +import type { DesktopLocale } from './locale.ts' + +/** + * Render escaped diagnostics without depending on application resource files. + * @param locale - Shell-owned translations. + * @param message - Failure details displayed as plain text. + * @returns An HTML document suitable for an isolated emergency window. + */ +export function startupFailureDocument(locale: DesktopLocale, message: string): string { + const escape = (value: string): string => value.replaceAll('&', '&').replaceAll('<', '<') + .replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''') + return ` + +${escape(locale.messages.startupFailed)} + +

${escape(locale.messages.startupFailed)}

${escape(locale.messages.startupReinstallAdvice)}

+

${escape(locale.messages.startupConfigurationAdvice)}

+
${escape(message)}
+ +
+
+
` +} diff --git a/apps/desktop/src/startup-error.ts b/apps/desktop/src/startup-error.ts new file mode 100644 index 0000000000..feb19c0dda --- /dev/null +++ b/apps/desktop/src/startup-error.ts @@ -0,0 +1,31 @@ +/** Recovery guidance attached by the owner of a failed Desktop startup operation. */ + +/** Actions that can restore an unavailable Desktop backend. */ +export type DesktopRecovery = 'restart' | 'reinstall' | 'plugins' | 'configuration' + +/** An operation failure with recovery guidance independent of its diagnostic wording. */ +export class DesktopStartupError extends Error { + /** + * @param recovery - Recovery supported by the failed operation. + * @param cause - Original diagnostic, retained for troubleshooting. + */ + constructor(readonly recovery: DesktopRecovery, cause: unknown) { + super(cause instanceof Error ? cause.message : String(cause), { cause }) + } +} + +/** + * Preserve diagnostics and recovery guidance when sending failures to a renderer. + * @param error - Startup or runtime failure. + * @returns Serializable error state; unclassified failures suggest restarting. + */ +export function desktopErrorState(error: unknown): { + phase: 'error' + message: string + recovery: DesktopRecovery +} { + const message = error instanceof AggregateError + ? [error.message, ...error.errors.map(item => desktopErrorState(item).message)].join('\n') + : error instanceof Error ? error.message : String(error) + return { phase: 'error', message, recovery: error instanceof DesktopStartupError ? error.recovery : 'restart' } +} diff --git a/apps/desktop/tests/backend-controller.spec.ts b/apps/desktop/tests/backend-controller.spec.ts index abdc78a9e7..c955ddc1e3 100644 --- a/apps/desktop/tests/backend-controller.spec.ts +++ b/apps/desktop/tests/backend-controller.spec.ts @@ -83,7 +83,7 @@ describe('desktop backend controller', () => { it('publishes preparation errors and permits retry', async () => { const f = fixture() await expect(f.controller.start(async () => { throw new Error('invalid profile') })).rejects.toThrow('invalid profile') - expect(f.controller.state).toEqual({ phase: 'error', message: 'invalid profile' }) + expect(f.controller.state).toEqual({ phase: 'error', message: 'invalid profile', recovery: 'restart' }) expect(f.create).not.toHaveBeenCalled() f.ready.resolve() await f.controller.start(async () => {}) @@ -101,7 +101,7 @@ describe('desktop backend controller', () => { await f.stopping.promise f.exited.resolve() await rejected - expect(f.controller.state).toEqual({ phase: 'error', message: 'plugin failed' }) + expect(f.controller.state).toEqual({ phase: 'error', message: 'plugin failed', recovery: 'restart' }) expect(f.host.stop).toHaveBeenCalledTimes(1) await f.controller.close() }) @@ -111,7 +111,7 @@ describe('desktop backend controller', () => { f.ready.resolve() await f.controller.start(async () => {}) f.fail(new Error('transport failed')) - expect(f.controller.state).toEqual({ phase: 'error', message: 'transport failed' }) + expect(f.controller.state).toEqual({ phase: 'error', message: 'transport failed', recovery: 'restart' }) expect(f.controller.host).toBeUndefined() await f.stopping.promise const prepare = vi.fn(async () => {}) @@ -135,7 +135,7 @@ describe('desktop backend controller', () => { await f.stopping.promise f.exited.resolve() await rejected - expect(f.states).toEqual([{ phase: 'starting' }, { phase: 'error', message: 'immediate failure' }]) + expect(f.states).toEqual([{ phase: 'starting' }, { phase: 'error', message: 'immediate failure', recovery: 'restart' }]) await f.controller.close() }) diff --git a/apps/desktop/tests/expected/startup-en-configuration.txt b/apps/desktop/tests/expected/startup-en-configuration.txt new file mode 100644 index 0000000000..29bfba4506 --- /dev/null +++ b/apps/desktop/tests/expected/startup-en-configuration.txt @@ -0,0 +1,8 @@ +DeepSeek Harness could not start +Choose a recovery action below. Disabling third-party plugins retains their files. +Reset Desktop deletes all Desktop profile configuration and third-party plugins without a backup, then starts a fresh profile. Shared tasks and settings are retained. +If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately. +Failure details +Close and restart +Disable all third-party plugins and retry +Reset Desktop and retry diff --git a/apps/desktop/tests/expected/startup-en-plugins.txt b/apps/desktop/tests/expected/startup-en-plugins.txt new file mode 100644 index 0000000000..29bfba4506 --- /dev/null +++ b/apps/desktop/tests/expected/startup-en-plugins.txt @@ -0,0 +1,8 @@ +DeepSeek Harness could not start +Choose a recovery action below. Disabling third-party plugins retains their files. +Reset Desktop deletes all Desktop profile configuration and third-party plugins without a backup, then starts a fresh profile. Shared tasks and settings are retained. +If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately. +Failure details +Close and restart +Disable all third-party plugins and retry +Reset Desktop and retry diff --git a/apps/desktop/tests/expected/startup-en-reinstall.txt b/apps/desktop/tests/expected/startup-en-reinstall.txt new file mode 100644 index 0000000000..29bfba4506 --- /dev/null +++ b/apps/desktop/tests/expected/startup-en-reinstall.txt @@ -0,0 +1,8 @@ +DeepSeek Harness could not start +Choose a recovery action below. Disabling third-party plugins retains their files. +Reset Desktop deletes all Desktop profile configuration and third-party plugins without a backup, then starts a fresh profile. Shared tasks and settings are retained. +If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately. +Failure details +Close and restart +Disable all third-party plugins and retry +Reset Desktop and retry diff --git a/apps/desktop/tests/expected/startup-en-restart.txt b/apps/desktop/tests/expected/startup-en-restart.txt new file mode 100644 index 0000000000..29bfba4506 --- /dev/null +++ b/apps/desktop/tests/expected/startup-en-restart.txt @@ -0,0 +1,8 @@ +DeepSeek Harness could not start +Choose a recovery action below. Disabling third-party plugins retains their files. +Reset Desktop deletes all Desktop profile configuration and third-party plugins without a backup, then starts a fresh profile. Shared tasks and settings are retained. +If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately. +Failure details +Close and restart +Disable all third-party plugins and retry +Reset Desktop and retry diff --git a/apps/desktop/tests/expected/startup-zh-CN-configuration.txt b/apps/desktop/tests/expected/startup-zh-CN-configuration.txt new file mode 100644 index 0000000000..f37bdf417f --- /dev/null +++ b/apps/desktop/tests/expected/startup-zh-CN-configuration.txt @@ -0,0 +1,8 @@ +DeepSeek Harness 无法启动 +请选择下方的恢复操作。禁用第三方插件会保留插件文件。 +重置 Desktop 会删除桌面端的全部 profile 配置和第三方插件,不保留备份,然后重新初始化并启动。共享任务和设置会保留。 +如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。 +Failure details +关闭并重启 +禁用全部第三方插件并重试 +重置 Desktop 并重试 diff --git a/apps/desktop/tests/expected/startup-zh-CN-plugins.txt b/apps/desktop/tests/expected/startup-zh-CN-plugins.txt new file mode 100644 index 0000000000..f37bdf417f --- /dev/null +++ b/apps/desktop/tests/expected/startup-zh-CN-plugins.txt @@ -0,0 +1,8 @@ +DeepSeek Harness 无法启动 +请选择下方的恢复操作。禁用第三方插件会保留插件文件。 +重置 Desktop 会删除桌面端的全部 profile 配置和第三方插件,不保留备份,然后重新初始化并启动。共享任务和设置会保留。 +如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。 +Failure details +关闭并重启 +禁用全部第三方插件并重试 +重置 Desktop 并重试 diff --git a/apps/desktop/tests/expected/startup-zh-CN-reinstall.txt b/apps/desktop/tests/expected/startup-zh-CN-reinstall.txt new file mode 100644 index 0000000000..f37bdf417f --- /dev/null +++ b/apps/desktop/tests/expected/startup-zh-CN-reinstall.txt @@ -0,0 +1,8 @@ +DeepSeek Harness 无法启动 +请选择下方的恢复操作。禁用第三方插件会保留插件文件。 +重置 Desktop 会删除桌面端的全部 profile 配置和第三方插件,不保留备份,然后重新初始化并启动。共享任务和设置会保留。 +如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。 +Failure details +关闭并重启 +禁用全部第三方插件并重试 +重置 Desktop 并重试 diff --git a/apps/desktop/tests/expected/startup-zh-CN-restart.txt b/apps/desktop/tests/expected/startup-zh-CN-restart.txt new file mode 100644 index 0000000000..f37bdf417f --- /dev/null +++ b/apps/desktop/tests/expected/startup-zh-CN-restart.txt @@ -0,0 +1,8 @@ +DeepSeek Harness 无法启动 +请选择下方的恢复操作。禁用第三方插件会保留插件文件。 +重置 Desktop 会删除桌面端的全部 profile 配置和第三方插件,不保留备份,然后重新初始化并启动。共享任务和设置会保留。 +如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。 +Failure details +关闭并重启 +禁用全部第三方插件并重试 +重置 Desktop 并重试 diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index 252db0a18c..65a651d45e 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { join } from 'node:path' import { DESKTOP_IPC } from '../src/ipc.ts' const harness = await vi.hoisted(async () => { @@ -12,6 +13,7 @@ const harness = await vi.hoisted(async () => { const windows: FakeWindow[] = [] const hosts: FakeHost[] = [] const handlers = new Map unknown>() + let pluginsEnabled = false let preparing = deferred() let prepared = deferred() let hostStarted = deferred() @@ -24,6 +26,7 @@ const harness = await vi.hoisted(async () => { readonly webContents = Object.assign(new EventEmitter(), { setWindowOpenHandler: vi.fn(), openDevTools: vi.fn(), + getURL: () => this.urls.at(-1) ?? '', send: vi.fn((channel: string, state: { phase?: string }) => { if (channel === 'dsh-desktop:backend-state' && state.phase === 'error') errorPublished.resolve() }), @@ -51,16 +54,18 @@ const harness = await vi.hoisted(async () => { this.ready.reject(new Error('child stopped')) return this.exited.promise }) - constructor(..._args: unknown[]) { hosts.push(this) } + constructor(readonly node: string, readonly runtime: string, readonly profile: string) { hosts.push(this) } } const app = Object.assign(new EventEmitter(), { - isPackaged: false, + isPackaged: true, name: 'Desktop test', whenReady: () => Promise.resolve(), getLocale: () => 'en-US', getVersion: () => '1.0.0', + getAppPath: () => 'desktop-test-app', requestSingleInstanceLock: () => true, exit: vi.fn(), + relaunch: vi.fn(), quit: vi.fn(() => { const event = { preventDefault: vi.fn() } app.emit('before-quit', event) @@ -71,12 +76,17 @@ const harness = await vi.hoisted(async () => { windows, hosts, handlers, app, FakeWindow, FakeHost, dialog: { showErrorBox: vi.fn(), showMessageBox: vi.fn() }, applyRelease: vi.fn(() => { preparing.resolve(); return prepared.promise }), + assertProfileRuntime: vi.fn(), get preparing() { return preparing }, get prepared() { return prepared }, get hostStarted() { return hostStarted }, get navigated() { return navigated }, get errorPublished() { return errorPublished }, get quitCompleted() { return quitCompleted }, nextHostStart() { hostStarted = deferred(); return hostStarted.promise }, + get pluginsEnabled() { return pluginsEnabled }, + set pluginsEnabled(value: boolean) { pluginsEnabled = value }, reset() { windows.length = 0; hosts.length = 0; handlers.clear(); app.removeAllListeners() + app.isPackaged = true + pluginsEnabled = false preparing = deferred(); prepared = deferred(); hostStarted = deferred() navigated = deferred(); errorPublished = deferred(); quitCompleted = deferred() }, @@ -97,7 +107,16 @@ vi.mock('../src/paths.ts', () => ({ resolveDesktopPaths: () => ({ profile: 'desk vi.mock('../src/project-manager.ts', () => ({ DesktopProjectManager: class { readonly applyRelease = harness.applyRelease - readonly assertProfileRuntime = vi.fn() + readonly assertProfileRuntime = harness.assertProfileRuntime + hasEnabledPlugins() { return harness.pluginsEnabled } + async mutate(_mutation: unknown, hooks: { beforeChange(): Promise; afterChange(): Promise }) { + await hooks.beforeChange() + harness.pluginsEnabled = false + await hooks.afterChange() + } + async resetConfiguration(hooks: { beforeChange(): Promise; afterChange(): Promise }) { + await this.mutate(undefined, hooks) + } }, })) vi.mock('../src/host-process.ts', () => ({ DesktopHostProcess: harness.FakeHost })) @@ -117,7 +136,8 @@ beforeEach(() => { vi.stubEnv('DSH_DESKTOP_NODE_BINARY', 'test-node') vi.stubEnv('DSH_DESKTOP_PNPM_ENTRY', 'test-pnpm') vi.stubEnv('DSH_DESKTOP_DSH_DIR', 'test-runtime') - vi.stubEnv('DSH_DESKTOP_DEV_PROJECT_DIR', undefined) + vi.stubGlobal('process', { ...process, resourcesPath: 'desktop-test-resources' }) + vi.stubEnv('DSH_DESKTOP_HOST_INSPECT_PORT', undefined) }) afterEach(async () => { @@ -128,9 +148,98 @@ afterEach(async () => { vi.clearAllTimers() vi.useRealTimers() vi.unstubAllEnvs() + vi.unstubAllGlobals() }) describe('desktop main startup', () => { + it.each(['plugins', 'reset'])('runs %s recovery from a document with a broken preload', async (action) => { + await import('../src/main.ts') + await harness.preparing.promise + const window = harness.windows[0]! + window.webContents.emit('preload-error', {}, 'preload-app.cjs', new Error('preload unavailable')) + harness.prepared.resolve() + await harness.hostStarted.promise + harness.hosts[0]!.ready.resolve() + await Promise.resolve(invoke(DESKTOP_IPC.backendRetry)) + const started = harness.nextHostStart() + const event = { preventDefault: vi.fn() } + window.webContents.emit('will-navigate', event, `dsh-recovery://${action}/?`) + await harness.hosts[0]!.stopping.promise + harness.hosts[0]!.exited.resolve() + await started + harness.hosts[1]!.ready.resolve() + await harness.navigated.promise + expect(event.preventDefault).toHaveBeenCalled() + expect(window.urls.at(-1)).toBe('dsh-app://app/index.html') + }) + + it('allows a full profile reset for an unclassified startup failure', async () => { + await import('../src/main.ts') + await harness.preparing.promise + harness.prepared.resolve() + await harness.hostStarted.promise + harness.hosts[0]!.exited.resolve() + harness.hosts[0]!.ready.reject(new Error('Unknown startup failure')) + await harness.errorPublished.promise + const started = harness.nextHostStart() + const reset = Promise.resolve(invoke(DESKTOP_IPC.configurationReset)) + await started + harness.hosts[1]!.ready.resolve() + await reset + expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'ready' }) + }) + + it('keeps a self-contained reinstall document in the main window after preload failure', async () => { + await import('../src/main.ts') + await harness.preparing.promise + const window = harness.windows[0]! + window.webContents.emit('preload-error', {}, 'preload-app.cjs', new Error('preload unavailable')) + expect(window.urls.at(-1)).toContain('data:text/html') + expect(decodeURIComponent(window.urls.at(-1)!)).toContain('preload unavailable') + harness.prepared.resolve() + await harness.hostStarted.promise + harness.hosts[0]!.ready.resolve() + await Promise.resolve(invoke(DESKTOP_IPC.backendRetry)) + expect(harness.windows).toHaveLength(1) + expect(window.urls.at(-1)).toContain('data:text/html') + expect(harness.dialog.showErrorBox).not.toHaveBeenCalled() + }) + + it('offers plugin recovery and disables plugins before restarting in the same window', async () => { + harness.pluginsEnabled = true + await import('../src/main.ts') + await harness.preparing.promise + harness.prepared.resolve() + await harness.hostStarted.promise + harness.hosts[0]!.exited.resolve() + harness.hosts[0]!.ready.reject(new Error('Plugin initialization failed')) + await harness.errorPublished.promise + expect(invoke(DESKTOP_IPC.backendStatus)).toMatchObject({ recovery: 'plugins' }) + const nextStarted = harness.nextHostStart() + const recovery = Promise.resolve(invoke(DESKTOP_IPC.pluginsDisableAll)) + await nextStarted + expect(harness.pluginsEnabled).toBe(false) + harness.hosts[1]!.ready.resolve() + await recovery + expect(harness.windows).toHaveLength(1) + expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'ready' }) + }) + + it('waits for Host exit before relaunching the application', async () => { + await import('../src/main.ts') + await harness.preparing.promise + harness.prepared.resolve() + await harness.hostStarted.promise + harness.hosts[0]!.ready.resolve() + await harness.navigated.promise + const restart = Promise.resolve(invoke(DESKTOP_IPC.applicationRestart)) + await harness.hosts[0]!.stopping.promise + expect(harness.app.relaunch).not.toHaveBeenCalled() + harness.hosts[0]!.exited.resolve() + await restart + expect(harness.app.relaunch).toHaveBeenCalledOnce() + }) + it('shows the loading window before profile preparation and starts one actual Host', async () => { await import('../src/main.ts') await harness.preparing.promise @@ -148,12 +257,31 @@ describe('desktop main startup', () => { harness.hosts[0]!.ready.resolve() await Promise.all([retry, secondRetry, harness.navigated.promise]) expect(harness.applyRelease).toHaveBeenCalledTimes(1) + expect(harness.assertProfileRuntime).toHaveBeenCalledWith('desktop-test-profile') + expect(harness.hosts[0]).toMatchObject({ + node: join('desktop-test-resources', 'runtime', 'node', process.platform === 'win32' ? 'node.exe' : 'node'), + runtime: join('desktop-test-resources', 'dsh'), + profile: 'desktop-test-profile', + }) expect(harness.hosts[0]!.start).toHaveBeenCalledTimes(1) expect(harness.windows).toHaveLength(1) expect(window.urls).toEqual(['dsh-app://shell/startup.html', 'dsh-app://app/index.html']) expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'ready' }) }) + it('starts the unpackaged Host from the application development directory', async () => { + harness.app.isPackaged = false + await import('../src/main.ts') + await harness.hostStarted.promise + const project = join(harness.app.getAppPath(), '.desktop-build', 'development', 'project') + expect(harness.hosts[0]).toMatchObject({ node: 'test-node', runtime: project, profile: project }) + expect(harness.applyRelease).not.toHaveBeenCalled() + expect(harness.assertProfileRuntime).not.toHaveBeenCalled() + harness.hosts[0]!.ready.resolve() + await harness.navigated.promise + expect(harness.dialog.showErrorBox).not.toHaveBeenCalled() + }) + it('keeps startup errors and a successful retry in the same window', async () => { await import('../src/main.ts') await harness.preparing.promise @@ -165,7 +293,7 @@ describe('desktop main startup', () => { first.ready.reject(new Error('plugin composition failed')) await harness.errorPublished.promise await failedRetry - expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'error', message: 'plugin composition failed' }) + expect(invoke(DESKTOP_IPC.backendStatus)).toEqual({ phase: 'error', message: 'plugin composition failed', recovery: 'restart' }) expect(harness.windows[0]!.urls).toEqual(['dsh-app://shell/startup.html']) const nextStarted = harness.nextHostStart() const retry = Promise.resolve(invoke(DESKTOP_IPC.backendRetry)) diff --git a/apps/desktop/tests/plugin-pnpm.spec.ts b/apps/desktop/tests/plugin-pnpm.spec.ts index f565967cee..351387160e 100644 --- a/apps/desktop/tests/plugin-pnpm.spec.ts +++ b/apps/desktop/tests/plugin-pnpm.spec.ts @@ -47,8 +47,8 @@ it('installs a real pnpm graph, then executes approved scripts with the shared h const realPnpm = join(import.meta.dirname, '../node_modules/pnpm/bin/pnpm.mjs') writeFileSync(pnpm, `process.argv = process.argv.map(arg => arg === '--config.registry=https://registry.npmjs.org/' ? ${JSON.stringify(`--config.registry=${origin}`)} : arg); await import(${JSON.stringify(pathToFileURL(realPnpm).href)})`) const manager = new DesktopProjectManager(resolveDesktopPaths(join(root, '.dsh')), { node: process.execPath, pnpm, dsh }) - const hooks: DesktopProjectHooks = { beforeActivate: async () => {}, afterActivate: async () => {} } - await manager.applyRelease('1.0.0', hooks) + const hooks: DesktopProjectHooks = { beforeChange: async () => {}, afterChange: async () => {} } + await manager.applyRelease() await manager.mutate({ type: 'plugin-add', spec: 'fixture-plugin@1.0.0' }, hooks) expect(manager.listPlugins()).toEqual([{ name: 'fixture-plugin', version: '1.0.0', enabled: true }]) const built = JSON.parse(readFileSync(join(manager.paths.profile, 'node_modules/node-pty/built.json'), 'utf8')) as { node: string; host: string } diff --git a/apps/desktop/tests/preload-app.spec.ts b/apps/desktop/tests/preload-app.spec.ts index 81eac02cc3..d6e7a63b07 100644 --- a/apps/desktop/tests/preload-app.spec.ts +++ b/apps/desktop/tests/preload-app.spec.ts @@ -23,8 +23,13 @@ it('provides startup controls and a removable state subscription to shell docume await api.backend.status() await api.backend.retry() await api.openPlugins() + await api.disablePlugins() + await api.resetConfiguration() + await api.restart() + await api.close() expect(electron.ipcRenderer.invoke.mock.calls).toEqual([ [DESKTOP_IPC.localeGet], [DESKTOP_IPC.backendStatus], [DESKTOP_IPC.backendRetry], [DESKTOP_IPC.pluginsOpen], + [DESKTOP_IPC.pluginsDisableAll], [DESKTOP_IPC.configurationReset], [DESKTOP_IPC.applicationRestart], [DESKTOP_IPC.applicationClose], ]) const listener = vi.fn() const dispose = api.backend.subscribe(listener) diff --git a/apps/desktop/tests/profile-packages.spec.ts b/apps/desktop/tests/profile-packages.spec.ts index 4f3fe1308a..d419c962f2 100644 --- a/apps/desktop/tests/profile-packages.spec.ts +++ b/apps/desktop/tests/profile-packages.spec.ts @@ -1,11 +1,11 @@ import { execFileSync } from 'node:child_process' -import { mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { afterEach, expect, it } from 'vitest' import { createPluginProfile } from '../src/project-manager.ts' -import { copyDesktopProfile, linkDesktopHostPackages, unlinkDesktopHostPackages, validateDesktopPluginGraph } from '../src/profile-packages.ts' +import { linkDesktopHostPackages, unlinkDesktopHostPackages, validateDesktopPluginGraph } from '../src/profile-packages.ts' import { runtimeFixture, writePackage } from './runtime-fixture.ts' const roots: string[] = [] @@ -58,12 +58,9 @@ it('refuses to satisfy a plugin dependency from an ancestor CLI project', () => writePackage(join(profile, 'node_modules'), 'plugin', { dependencies: { ambient: '1.0.0' } }) expect(() =>{ validateDesktopPluginGraph(profile, dsh, runtime, ['plugin']) }).toThrow(/outside its owned packages/u) }) -it('copies writable plugin bytes independently and removes broken owned links without following them', () => { +it('removes broken owned links without following them', () => { const { root, profile } = fixture() writePackage(join(profile, 'node_modules'), 'plugin') - copyDesktopProfile(profile, join(root, 'copy')) - writeFileSync(join(root, 'copy/node_modules/plugin/index.js'), 'changed') - expect(readFileSync(join(profile, 'node_modules/plugin/index.js'), 'utf8')).toContain('identity') rmSync(join(root, 'dsh'), { recursive: true }) expect(() =>{ unlinkDesktopHostPackages(profile) }).not.toThrow() }) diff --git a/apps/desktop/tests/project-manager.spec.ts b/apps/desktop/tests/project-manager.spec.ts index 9d141efa2d..cb4fee6389 100644 --- a/apps/desktop/tests/project-manager.spec.ts +++ b/apps/desktop/tests/project-manager.spec.ts @@ -1,11 +1,10 @@ -import { existsSync, mkdtempSync, mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, realpathSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, unlinkSync, realpathSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' +import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { afterEach, describe, expect, it } from 'vitest' import { resolveDesktopPaths } from '../src/paths.ts' import { DesktopProjectManager, packageNameFromSpec, type DesktopProjectHooks } from '../src/project-manager.ts' -import { readDesktopProfileState } from '../src/profile-packages.ts' import { runtimeFixture } from './runtime-fixture.ts' const roots: string[] = [] @@ -48,7 +47,7 @@ if (command !== 'rebuild') { return path } function hooks(overrides: Partial = {}): DesktopProjectHooks { - return { beforeActivate: async () => {}, afterActivate: async () => {}, ...overrides } + return { beforeChange: async () => {}, afterChange: async () => {}, ...overrides } } function setup(): { root: string; manager: DesktopProjectManager } { const root = temporaryRoot() @@ -63,6 +62,85 @@ function calls(root: string): { args: string[]; registry: string }[] { afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) describe('desktop external plugin profile', () => { + it('starts with disabled plugins even when their installed manifests are corrupt', async () => { + const { manager } = setup() + await manager.applyRelease() + await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + const manifest = join(manager.paths.profile, 'node_modules/plugin/package.json') + writeFileSync(manifest, '{broken') + await expect(manager.applyRelease()).rejects.toThrow() + await manager.mutate({ type: 'plugins-disable-all' }, hooks()) + await expect(manager.applyRelease()).resolves.toBe(false) + expect(readFileSync(manifest, 'utf8')).toBe('{broken') + await manager.resetConfiguration(hooks()) + expect(existsSync(manifest)).toBe(false) + await expect(manager.applyRelease()).resolves.toBe(false) + }) + + it('disables every third-party bundle without reading a broken plugin patch declaration', async () => { + const { root, manager } = setup() + await manager.applyRelease() + await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + const patch = join(manager.paths.profile, 'node_modules/plugin/bundle.yml') + unlinkSync(patch) + await manager.mutate({ type: 'plugins-disable-all' }, hooks({ afterChange: async () => { + expect(manager.hasEnabledPlugins()).toBe(false) + } })) + expect(manager.hasEnabledPlugins()).toBe(false) + expect(existsSync(join(manager.paths.profile, 'node_modules/plugin/package.json'))).toBe(true) + expect(calls(root)).toHaveLength(2) + await expect(manager.applyRelease()).resolves.toBe(false) + }) + + it('resets the entire profile without backups while retaining its lock and shared data', async () => { + const { root, manager } = setup() + await manager.applyRelease() + await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) + const profile = manager.paths.profile + expect(manager.paths.lock).toBe(join(profile, 'lock')) + const task = join(root, '.dsh', 'task-sentinel') + const homeEnvironment = join(root, '.dsh', '.env') + writeFileSync(homeEnvironment, 'HOME_SETTING=retained') + writeFileSync(task, 'retained task') + writeFileSync(join(profile, 'desktop-runtime-state.json'), '{broken') + writeFileSync(join(profile, 'cordis.patch.yml'), ': broken') + writeFileSync(join(profile, '.env'), 'NODE_OPTIONS=--bad') + mkdirSync(join(profile, '.extra')) + writeFileSync(join(profile, '.extra', 'custom-file'), 'remove') + const shared = join(root, 'shared-data') + mkdirSync(shared) + writeFileSync(join(shared, 'sentinel'), 'preserve') + symlinkSync(shared, join(profile, 'external-link'), process.platform === 'win32' ? 'junction' : 'dir') + await expect(manager.applyRelease()).rejects.toMatchObject({ recovery: 'configuration' }) + await manager.resetConfiguration(hooks({ + beforeChange: async () => { expect(readFileSync(join(profile, 'cordis.patch.yml'), 'utf8')).toBe(': broken') }, + afterChange: async () => { + manager.assertProfileRuntime(profile) + expect(readFileSync(manager.paths.lock, 'utf8').trim()).toBe(String(process.pid)) + await expect(manager.applyRelease()).rejects.toThrow('another package transaction is active') + }, + })) + expect(manager.listPlugins()).toEqual([]) + expect(existsSync(join(profile, 'node_modules/plugin'))).toBe(false) + expect(existsSync(join(profile, 'cordis.patch.yml'))).toBe(false) + expect(existsSync(join(profile, '.env'))).toBe(false) + expect(existsSync(join(profile, '.extra'))).toBe(false) + expect(existsSync(join(profile, 'external-link'))).toBe(false) + expect(readFileSync(join(shared, 'sentinel'), 'utf8')).toBe('preserve') + expect(readFileSync(task, 'utf8')).toBe('retained task') + expect(readFileSync(homeEnvironment, 'utf8')).toBe('HOME_SETTING=retained') + expect(readdirSync(profile).some(name => name.includes('backup'))).toBe(false) + expect(calls(root)).toHaveLength(2) + await expect(manager.applyRelease()).resolves.toBe(false) + expect(existsSync(homeEnvironment)).toBe(true) + }) + + it('reports damaged application metadata as a reinstall failure', async () => { + const { manager } = setup() + writeFileSync(join(manager.runtime.dsh, 'desktop-runtime.json'), '{broken') + await expect(manager.applyRelease()).rejects.toMatchObject({ recovery: 'reinstall' }) + }) + it('accepts registry names and tags but rejects alternate sources and flags', () => { expect(packageNameFromSpec('@scope/plugin@1.2.3')).toBe('@scope/plugin') expect(packageNameFromSpec('plugin@next')).toBe('plugin') @@ -73,9 +151,8 @@ describe('desktop external plugin profile', () => { it('initializes and restarts offline without executing pnpm', async () => { const { root, manager } = setup() - await expect(manager.applyRelease('2.0.0', hooks())).rejects.toThrow(/does not match Electron/u) - await expect(manager.applyRelease('1.0.0', hooks())).resolves.toBe(true) - await expect(manager.applyRelease('1.0.0', hooks())).resolves.toBe(false) + await expect(manager.applyRelease()).resolves.toBe(true) + await expect(manager.applyRelease()).resolves.toBe(false) expect(manager.listPlugins()).toEqual([]) expect(calls(root)).toEqual([]) expect(existsSync(manager.paths.pnpm.store)).toBe(false) @@ -85,21 +162,17 @@ describe('desktop external plugin profile', () => { it('repairs a removed managed link without running pnpm', async () => { const { root, manager } = setup() - await manager.applyRelease('1.0.0', hooks()) + await manager.applyRelease() unlinkSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis')) - await expect(manager.applyRelease('1.0.0', hooks())).resolves.toBe(true) + await expect(manager.applyRelease()).resolves.toBe(true) expect(calls(root)).toEqual([]) }) it.skipIf(process.platform !== 'win32')('reuses the profile when the launch path changes only Windows letter casing', async () => { const { manager } = setup() - await manager.applyRelease('1.0.0', hooks()) + await manager.applyRelease() const relaunched = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh: manager.runtime.dsh.toUpperCase() }) - let started = false - await expect(relaunched.applyRelease('1.0.0', hooks({ - afterActivate: async () => { started = true }, - }))).resolves.toBe(false) - expect(started).toBe(false) + await expect(relaunched.applyRelease()).resolves.toBe(false) }) it.each(['changed', 'same-size', 'extra', 'missing'])('starts and reuses a profile without checking %s runtime bytes', async (operation) => { @@ -108,22 +181,16 @@ describe('desktop external plugin profile', () => { if (operation === 'same-size') writeFileSync(join(manager.runtime.dsh, 'package.json'), '{"type":"Module"}\n') if (operation === 'extra') writeFileSync(join(manager.runtime.dsh, 'extra'), '') if (operation === 'missing') unlinkSync(join(manager.runtime.dsh, 'package.json')) - let starts = 0 - await expect(manager.applyRelease('1.0.0', hooks({ - afterActivate: async () => { starts++ }, - }))).resolves.toBe(true) + await expect(manager.applyRelease()).resolves.toBe(true) const relaunched = new DesktopProjectManager(manager.paths, manager.runtime) - await expect(relaunched.applyRelease('1.0.0', hooks({ - afterActivate: async () => { starts++ }, - }))).resolves.toBe(false) - expect(starts).toBe(1) + await expect(relaunched.applyRelease()).resolves.toBe(false) expect(existsSync(manager.paths.profile)).toBe(true) expect(calls(root)).toEqual([]) }) it('installs only plugins and checks the graph before running lifecycle scripts', async () => { const { root, manager } = setup() - await manager.applyRelease('1.0.0', hooks()) + await manager.applyRelease() await manager.mutate({ type: 'plugin-add', spec: '@scope/plugin@2.0.0' }, hooks()) expect(manager.listPlugins()).toEqual([{ name: '@scope/plugin', version: '2.0.0', enabled: true }]) expect(calls(root).map(call => call.args.filter(arg => !arg.startsWith('--config.')))).toEqual([ @@ -136,7 +203,7 @@ describe('desktop external plugin profile', () => { it('retains disabled plugin versions through updates and enables them explicitly', async () => { const { root, manager } = setup() - await manager.applyRelease('1.0.0', hooks()) + await manager.applyRelease() await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) await manager.mutate({ type: 'plugins-disable-all' }, hooks()) expect(calls(root)).toHaveLength(2) @@ -151,30 +218,29 @@ describe('desktop external plugin profile', () => { it('keeps plugin files and patches through a compatible release and application relocation', async () => { const { root, manager } = setup() - await manager.applyRelease('1.0.0', hooks()) + await manager.applyRelease() await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) writeFileSync(join(manager.paths.profile, 'cordis.patch.yml'), '[]\n') const nextRoot = join(root, 'relocated', 'dsh') runtimeFixture(nextRoot, '1.1.0') const next = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh: nextRoot }) - await expect(next.applyRelease('1.1.0', hooks())).resolves.toBe(true) + await expect(next.applyRelease()).resolves.toBe(true) expect(next.listPlugins()).toEqual(manager.listPlugins()) expect(next.releaseVersion()).toBe('1.1.0') expect(readFileSync(join(manager.paths.profile, 'cordis.patch.yml'), 'utf8')).toBe('[]\n') expect(calls(root)).toHaveLength(2) expect(realpathSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis'))).toBe(realpathSync(join(nextRoot, 'node_modules/@deepseek-ai/cordis'))) - writeFileSync(join(manager.paths.rollback, 'node_modules/plugin/bundle.yml'), 'rollback only') expect(readFileSync(join(manager.paths.profile, 'node_modules/plugin/bundle.yml'), 'utf8')).toBe('[]\n') }) it('reinstalls the locked plugin graph when bundled Node changes', async () => { const { root, manager } = setup() - await manager.applyRelease('1.0.0', hooks()) + await manager.applyRelease() await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) const dsh = join(root, 'new-node') runtimeFixture(dsh, '1.1.0', '24.18.0') const next = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh }) - await next.applyRelease('1.1.0', hooks()) + await next.applyRelease() expect(calls(root).slice(2).map(call => call.args.filter(arg => !arg.startsWith('--config.')))).toEqual([ ['install', '--frozen-lockfile', '--ignore-scripts'], ['rebuild', '--pending'], ]) @@ -183,60 +249,70 @@ describe('desktop external plugin profile', () => { it('allows incompatible plugins to be disabled in recovery without deleting them', async () => { const { root, manager } = setup() - await manager.applyRelease('1.0.0', hooks()) + await manager.applyRelease() await manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) const dsh = join(root, 'next-major') runtimeFixture(dsh, '2.0.0') const next = new DesktopProjectManager(manager.paths, { ...manager.runtime, dsh }) - await expect(next.applyRelease('2.0.0', hooks())).rejects.toThrow(/requires @deepseek-ai\/cordis/u) - expect(next.releaseVersion()).toBe('1.0.0') - expect(() =>{ next.assertProfileRuntime(manager.paths.profile) }).toThrow(/does not match/u) + await expect(next.applyRelease()).rejects.toThrow(/requires @deepseek-ai\/cordis/u) + expect(next.releaseVersion()).toBe('2.0.0') await next.mutate({ type: 'plugins-disable-all' }, hooks()) expect(next.releaseVersion()).toBe('2.0.0') expect(next.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: false }]) }) - it.each(['before', 'after'] as const)('keeps the active profile when %s activation fails', async (phase) => { + it.each(['before', 'after'] as const)('retains direct writes when the %s change hook fails', async (phase) => { const { manager } = setup() - await manager.applyRelease('1.0.0', hooks()) + await manager.applyRelease() let starts = 0 await expect(manager.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks({ - beforeActivate: async () => { if (phase === 'before') throw new Error('before failed') }, - afterActivate: async () => { if (phase === 'after' && starts++ === 0) throw new Error('after failed') }, + beforeChange: async () => { + expect(manager.listPlugins()).toEqual([]) + if (phase === 'before') throw new Error('before failed') + }, + afterChange: async () => { starts++; throw new Error('after failed') }, }))).rejects.toThrow(`${phase} failed`) - expect(manager.listPlugins()).toEqual([]) - expect(existsSync(manager.paths.pending)).toBe(false) + expect(manager.listPlugins()).toEqual(phase === 'before' ? [] : [{ name: 'plugin', version: '1.0.0', enabled: true }]) + expect(starts).toBe(phase === 'before' ? 0 : 1) + expect(existsSync(join(manager.paths.root, 'staging'))).toBe(false) + expect(existsSync(join(manager.paths.root, 'rollback'))).toBe(false) + expect(existsSync(join(manager.paths.root, 'pending.json'))).toBe(false) }) - it('recovers a directory move using recorded runtime identities', async () => { - const { manager } = setup() - await manager.applyRelease('1.0.0', hooks()) - const id = readDesktopProfileState(manager.paths.profile)?.runtimeId - const stagingProfile = join(manager.paths.staging, 'interrupted', 'profile') - mkdirSync(stagingProfile, { recursive: true }) - mkdirSync(dirname(manager.paths.rollback), { recursive: true }) - renameSync(manager.paths.profile, manager.paths.rollback) - writeFileSync(manager.paths.pending, JSON.stringify({ schemaVersion: 1, id: 'interrupted', stagingProfile, fromRuntimeId: id, toRuntimeId: id, step: 'active-moved' })) - manager.recover() - expect(manager.releaseVersion()).toBe('1.0.0') - expect(existsSync(stagingProfile)).toBe(false) - expect(existsSync(manager.paths.pending)).toBe(false) + it('keeps partial package changes and restores host links after pnpm fails', async () => { + const { root, manager } = setup() + await manager.applyRelease() + const failingPnpm = join(root, 'failing.mjs') + writeFileSync(failingPnpm, `await import(${JSON.stringify(pathToFileURL(manager.runtime.pnpm).href)}); process.exitCode = 1`) + const worker = new DesktopProjectManager(manager.paths, { ...manager.runtime, pnpm: failingPnpm }) + await worker.applyRelease() + let starts = 0 + await expect(worker.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks({ + afterChange: async () => { starts++ }, + }))).rejects.toThrow(/pnpm exited with 1/u) + expect(worker.listPlugins()).toEqual([{ name: 'plugin', version: '1.0.0', enabled: false }]) + expect(starts).toBe(0) + expect(existsSync(manager.paths.lock)).toBe(false) + expect(realpathSync(join(manager.paths.profile, 'node_modules/@deepseek-ai/cordis'))) + .toBe(realpathSync(join(manager.runtime.dsh, 'node_modules/@deepseek-ai/cordis'))) + await manager.mutate({ type: 'plugin-remove', name: 'plugin' }, hooks()) + expect(manager.listPlugins()).toEqual([]) }) it('holds the transaction lock until the pnpm worker exits', async () => { const { root, manager } = setup() - await manager.applyRelease('1.0.0', hooks()) + await manager.applyRelease() const ready = join(root, 'ready') const release = join(root, 'release') const blocker = join(root, 'blocking.mjs') writeFileSync(blocker, `import {existsSync, writeFileSync} from 'node:fs'; import {setTimeout as sleep} from 'node:timers/promises'; writeFileSync(${JSON.stringify(ready)}, String(process.pid)); while (!existsSync(${JSON.stringify(release)})) await sleep(10); await import(${JSON.stringify(pathToFileURL(manager.runtime.pnpm).href)})`) const worker = new DesktopProjectManager(manager.paths, { ...manager.runtime, pnpm: blocker }) - await worker.applyRelease('1.0.0', hooks()) + await worker.applyRelease() const pending = worker.mutate({ type: 'plugin-add', spec: 'plugin@1.0.0' }, hooks()) try { await expect.poll(() => existsSync(ready)).toBe(true) expect(readFileSync(manager.paths.lock, 'utf8').trim()).toBe(readFileSync(ready, 'utf8')) - await expect(manager.applyRelease('1.0.0', hooks())).rejects.toThrow(/another package transaction/u) + await expect(manager.applyRelease()).rejects.toThrow(/another package transaction/u) } finally { writeFileSync(release, 'continue') await pending diff --git a/apps/desktop/tests/runtime-tree.spec.ts b/apps/desktop/tests/runtime-tree.spec.ts index 20bfa289a2..04a5145d00 100644 --- a/apps/desktop/tests/runtime-tree.spec.ts +++ b/apps/desktop/tests/runtime-tree.spec.ts @@ -23,34 +23,67 @@ it('verifies a runtime after relocation without depending on build paths', async }) it.each(['changed', 'same-size', 'extra', 'missing'])('checks %s runtime bytes only during build verification', async (operation) => { const dsh = join(fixture(), 'dsh') - const before = readDesktopRuntime(dsh, '1.0.0') + const before = readDesktopRuntime(dsh) if (operation === 'changed') writeFileSync(join(dsh, 'package.json'), '{}') if (operation === 'same-size') writeFileSync(join(dsh, 'package.json'), '{"type":"Module"}\n') if (operation === 'extra') writeFileSync(join(dsh, 'extra'), '') if (operation === 'missing') rmSync(join(dsh, 'package.json')) - expect(readDesktopRuntime(dsh, '1.0.0')).toEqual(before) + expect(readDesktopRuntime(dsh)).toEqual(before) await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/integrity/u) }) it('rejects filesystem links and incompatible targets', async () => { const dsh = join(fixture(), 'dsh') await expect(verifyDesktopRuntime(dsh, '1.0.0', { platform: process.platform, arch: 'wrong' })).rejects.toThrow(/incompatible/u) symlinkSync(join(dsh, 'node_modules'), join(dsh, 'outside'), process.platform === 'win32' ? 'junction' : 'dir') - expect(readDesktopRuntime(dsh, '1.0.0').release.version).toBe('1.0.0') + expect(readDesktopRuntime(dsh).release.version).toBe('1.0.0') await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/unsupported filesystem/u) }) -it.each(['missing', 'directory'])('rejects a %s Host entry during startup metadata loading', (operation) => { +it('reads file inventory records unchanged during startup', () => { + const dsh = join(fixture(), 'dsh') + const path = join(dsh, DESKTOP_RUNTIME_FILE) + const descriptor = JSON.parse(readFileSync(path, 'utf8')) as { files: unknown[] } + descriptor.files.unshift({ path: '../outside', bytes: -1.5, sha256: 'unchecked', executable: 'unchecked' }) + writeFileSync(path, JSON.stringify(descriptor)) + expect(readDesktopRuntime(dsh).files).toEqual(descriptor.files) +}) +it.each(['missing', 'directory'])('checks a %s Host entry only during build verification', async (operation) => { const dsh = join(fixture(), 'dsh') const path = join(dsh, 'node_modules', DESKTOP_HOST_PACKAGE, DESKTOP_HOST_RUNTIME_FILES[0]) rmSync(path) if (operation === 'directory') mkdirSync(path) - expect(() => readDesktopRuntime(dsh, '1.0.0')).toThrow(/missing Host file/u) + expect(readDesktopRuntime(dsh).release.version).toBe('1.0.0') + await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/integrity/u) }) -it('rejects incompatible targets and shared package metadata during startup metadata loading', () => { +it('checks the shell version only during build verification', async () => { const dsh = join(fixture(), 'dsh') - expect(() => readDesktopRuntime(dsh, '2.0.0')).toThrow(/does not match Electron/u) - expect(() => readDesktopRuntime(dsh, '1.0.0', { platform: process.platform, arch: 'wrong' })).toThrow(/incompatible/u) - writeFileSync(join(dsh, 'node_modules', DESKTOP_HOST_PACKAGE, 'package.json'), '{}') - expect(() => readDesktopRuntime(dsh, '1.0.0')).toThrow(/shared package metadata mismatch/u) + expect(readDesktopRuntime(dsh).release.version).toBe('1.0.0') + await expect(verifyDesktopRuntime(dsh, '2.0.0')).rejects.toThrow(/does not match Electron/u) +}) +it.each([ + { schemaVersion: 2 }, + { platform: 'other' }, + { arch: 'other' }, + { release: { schemaVersion: 2 } }, + { release: { hostProtocolVersion: 999 } }, + { release: { nodeVersion: 'invalid' } }, + { release: { pnpmVersion: 'invalid' } }, +])('checks release compatibility only during build verification: %j', async (patch) => { + const dsh = join(fixture(), 'dsh') + const path = join(dsh, DESKTOP_RUNTIME_FILE) + const original = readDesktopRuntime(dsh) + const descriptor = { ...original, ...patch, release: { ...original.release, ...patch.release } } + writeFileSync(path, JSON.stringify(descriptor)) + expect(readDesktopRuntime(dsh)).toEqual(descriptor) + await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow(/invalid|incompatible/u) +}) +it.each(['missing', 'invalid-json', 'mismatched'])('checks %s shared manifests only during build verification', async (operation) => { + const dsh = join(fixture(), 'dsh') + const before = readDesktopRuntime(dsh) + const path = join(dsh, 'node_modules', DESKTOP_HOST_PACKAGE, 'package.json') + if (operation === 'missing') rmSync(path) + else writeFileSync(path, operation === 'invalid-json' ? '{' : '{}') + expect(readDesktopRuntime(dsh)).toEqual(before) + await expect(verifyDesktopRuntime(dsh, '1.0.0')).rejects.toThrow() }) it('rejects a descriptor that maps a shared package outside node_modules', async () => { const dsh = join(fixture(), 'dsh') diff --git a/apps/desktop/tests/startup-renderer.spec.ts b/apps/desktop/tests/startup-renderer.spec.ts index dbbb180ca9..584c9f9587 100644 --- a/apps/desktop/tests/startup-renderer.spec.ts +++ b/apps/desktop/tests/startup-renderer.spec.ts @@ -1,10 +1,12 @@ import { readFileSync } from 'node:fs' import { runInContext } from 'node:vm' +import { fileURLToPath } from 'node:url' import { JSDOM } from 'jsdom' import { expect, it, onTestFinished, vi } from 'vitest' import type { DesktopBackendState } from '../src/backend-controller.ts' import type { DshDesktopStartupApi } from '../src/ipc.ts' import { resolveDesktopLocale } from '../src/locale.ts' +import { startupFailureDocument } from '../src/startup-document.ts' function startup(locale = 'en', status: Promise = Promise.resolve({ phase: 'starting' })) { const dom = new JSDOM(readFileSync(new URL('../renderer/startup.html', import.meta.url), 'utf8'), { runScripts: 'outside-only' }) @@ -16,6 +18,10 @@ function startup(locale = 'en', status: Promise = Promise.r const unsubscribe = vi.fn(() => { listeners.clear() }) const retry = vi.fn(async () => {}) const openPlugins = vi.fn(async () => {}) + const disablePlugins = vi.fn(async () => {}) + const resetConfiguration = vi.fn(async () => {}) + const restart = vi.fn(async () => {}) + const close = vi.fn(async () => {}) const queried = Promise.withResolvers() const api: DshDesktopStartupApi = { protocolVersion: 1, @@ -26,6 +32,7 @@ function startup(locale = 'en', status: Promise = Promise.r subscribe: (listener) => { listeners.add(listener); return unsubscribe }, }, openPlugins, + disablePlugins, resetConfiguration, restart, close, } Object.defineProperty(dom.window, 'dshDesktop', { value: api }) runInContext(readFileSync(new URL('../renderer/startup.js', import.meta.url), 'utf8'), dom.getInternalVMContext()) @@ -42,12 +49,13 @@ function startup(locale = 'en', status: Promise = Promise.r } const publish = (state: DesktopBackendState): void => { for (const listener of listeners) listener(state) } const copy = (): string => [element('#title').textContent, element('#description').textContent, - ...['#error', '#actions'].filter(selector => !element(selector).hidden) + ...['#reset-advice', '#reinstall-advice', '#error', '#actions'].filter(selector => !element(selector).hidden) .flatMap(selector => selector === '#actions' - ? [button('#retry').textContent, button('#plugins').textContent] + ? [...document.querySelectorAll('#actions button')].filter(button => !button.hidden).map(button => button.textContent) : [element(selector).textContent]), ].join('\n') - return { dom, document, element, button, publish, copy, retry, openPlugins, unsubscribe, queried: queried.promise } + return { dom, document, element, button, publish, copy, retry, openPlugins, + disablePlugins, resetConfiguration, restart, close, unsubscribe, queried: queried.promise } } it('shows English loading and recovery actions without a Host document', async () => { @@ -60,22 +68,23 @@ it('shows English loading and recovery actions without a Host document', async ( expect(page.element('main').getAttribute('aria-busy')).toBe('true') expect(page.element('#spinner').hidden).toBe(false) expect(page.element('#actions').hidden).toBe(true) - expect(page.button('#retry').disabled).toBe(true) - expect(page.button('#plugins').disabled).toBe(true) + expect(page.button('#restart').disabled).toBe(true) + expect(page.button('#disable-plugins').disabled).toBe(true) page.publish({ phase: 'error', message: 'Plugin failed to load' }) expect(page.copy()).toMatchInlineSnapshot(` "DeepSeek Harness could not start - The application could not start. Retry or manage Desktop plugins to resolve the problem. + Choose a recovery action below. Disabling third-party plugins retains their files. + Reset Desktop deletes all Desktop profile configuration and third-party plugins without a backup, then starts a fresh profile. Shared tasks and settings are retained. + If application files are missing or damaged, close the application and reinstall it. Your tasks are stored separately. Plugin failed to load - Retry startup - Manage plugins" + Close and restart + Disable all third-party plugins and retry + Reset Desktop and retry" `) expect(page.element('main').getAttribute('aria-busy')).toBe('false') expect(page.element('#spinner').hidden).toBe(true) - page.button('#plugins').click() - expect(page.openPlugins).toHaveBeenCalledOnce() - page.button('#retry').click() - expect(page.retry).toHaveBeenCalledOnce() + page.button('#restart').click() + expect(page.restart).toHaveBeenCalledOnce() expect(page.element('#actions').hidden).toBe(true) expect(page.element('#error').textContent).toBe('') expect(page.element('main').getAttribute('aria-busy')).toBe('true') @@ -92,10 +101,13 @@ it('shows Chinese loading and recovery copy', async () => { page.publish({ phase: 'error', message: '插件加载失败' }) expect(page.copy()).toMatchInlineSnapshot(` "DeepSeek Harness 无法启动 - 应用未能启动。你可以重试,或管理桌面插件以解决问题。 + 请选择下方的恢复操作。禁用第三方插件会保留插件文件。 + 重置 Desktop 会删除桌面端的全部 profile 配置和第三方插件,不保留备份,然后重新初始化并启动。共享任务和设置会保留。 + 如果应用文件缺失或损坏,请关闭应用并重新安装。任务数据存储在独立位置。 插件加载失败 - 重试启动 - 管理插件" + 关闭并重启 + 禁用全部第三方插件并重试 + 重置 Desktop 并重试" `) }) @@ -106,14 +118,11 @@ it('renders diagnostic markup as text and exposes failures from recovery actions page.publish({ phase: 'error', message: diagnostic }) expect(page.element('#error').textContent).toBe(diagnostic) expect(page.element('#error').childElementCount).toBe(0) - page.openPlugins.mockRejectedValueOnce(new page.dom.window.Error('Cannot open plugin manager')) - page.button('#plugins').click() - await expect.poll(() => page.element('#error').textContent).toBe('Cannot open plugin manager') - page.retry.mockRejectedValueOnce(new page.dom.window.Error('Retry failed')) - page.button('#retry').click() + page.restart.mockRejectedValueOnce(new page.dom.window.Error('Retry failed')) + page.button('#restart').click() await expect.poll(() => page.element('#error').textContent).toBe('Retry failed') - expect(page.button('#retry').disabled).toBe(false) - expect(page.button('#plugins').disabled).toBe(false) + expect(page.button('#restart').disabled).toBe(false) + expect(page.button('#disable-plugins').disabled).toBe(false) }) it('keeps subscribed state when initial status arrives late and detaches on pagehide', async () => { @@ -132,3 +141,34 @@ it('keeps subscribed state when initial status arrives late and detaches on page page.dom.window.dispatchEvent(new page.dom.window.Event('pagehide')) expect(page.unsubscribe).toHaveBeenCalledOnce() }) + +it.each(['en', 'zh-CN'])('offers recovery actions with %s guidance and preserves diagnostic text', async (locale) => { + const page = startup(locale) + await expect.poll(() => page.button('#restart').disabled).toBe(true) + for (const recovery of ['plugins', 'configuration', 'reinstall', 'restart'] as const) { + page.publish({ phase: 'error', recovery, message: 'Failure details' }) + await expect(`${page.copy()}\n`).toMatchFileSnapshot(fileURLToPath(new URL(`./expected/startup-${locale}-${recovery}.txt`, import.meta.url))) + expect(page.button('#disable-plugins').hidden).toBe(false) + expect(page.button('#reset-configuration').hidden).toBe(false) + const action = recovery === 'plugins' ? '#disable-plugins' : recovery === 'configuration' + ? '#reset-configuration' : '#restart' + page.button(action).click() + expect(page.element('#actions').hidden).toBe(true) + } + expect(page.disablePlugins).toHaveBeenCalledOnce() + expect(page.resetConfiguration).toHaveBeenCalledOnce() + expect(page.close).not.toHaveBeenCalled() + expect(page.restart).toHaveBeenCalledTimes(2) +}) + +it('keeps emergency diagnostics inert without shell assets', () => { + const html = startupFailureDocument(resolveDesktopLocale('zh-CN'), '') + const dom = new JSDOM(html) + expect(dom.window.document.querySelector('script')).toBeNull() + expect(dom.window.document.querySelector('pre')?.textContent).toBe('') + expect(dom.window.document.querySelector('p')?.textContent).toContain('重新安装') + expect([...dom.window.document.querySelectorAll('form')].map(form => form.action)).toEqual([ + 'dsh-recovery://restart', 'dsh-recovery://plugins', 'dsh-recovery://reset', + ]) + dom.window.close() +}) From 5c82aa9371124a3a07eed26c8d93d180513094b3 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Thu, 10 Sep 2026 10:28:47 +0800 Subject: [PATCH 17/52] refactor(manifest): separate package metadata from public DSH fields --- ...026-09-05-package-manifest-types.i18n.yaml | 4 +- .../2026-09-05-package-manifest-types.md | 6 +- .../2026-09-05-package-manifest-types.zh.md | 6 +- ...26-09-10-public-package-manifest.i18n.yaml | 6 ++ .../2026-09-10-public-package-manifest.md | 35 ++++++++ .../2026-09-10-public-package-manifest.zh.md | 35 ++++++++ package.json | 1 - packages/boot/app-boot/README.i18n.yaml | 4 +- packages/boot/app-boot/README.md | 2 +- packages/boot/app-boot/README.zh.md | 2 +- packages/boot/app-boot/src/profile.ts | 13 +-- .../webworker-packer/README.i18n.yaml | 4 +- .../experimental/webworker-packer/README.md | 2 +- .../webworker-packer/README.zh.md | 2 +- .../webworker-packer/package.json | 3 +- .../webworker-packer/src/repository.ts | 13 ++- .../webworker-packer/tsconfig.json | 3 - .../util/package-manifest/README.i18n.yaml | 4 +- packages/util/package-manifest/README.md | 40 +++++---- packages/util/package-manifest/README.zh.md | 40 +++++---- packages/util/package-manifest/src/index.ts | 4 +- packages/util/package-manifest/src/types.ts | 87 +++++++------------ pnpm-lock.yaml | 6 -- scripts/gen-session-format-catalog.ts | 25 +++++- 24 files changed, 205 insertions(+), 142 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-09-10-public-package-manifest.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-10-public-package-manifest.md create mode 100644 .agents/notes/implemented/architecture/2026-09-10-public-package-manifest.zh.md diff --git a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.i18n.yaml index a15fd90d6d..1e9e2e658d 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.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-09-05-package-manifest-types.md -2026-09-05-package-manifest-types.md: 5e9834583a75a3fd4f1ec69379628c49d264e05b -2026-09-05-package-manifest-types.zh.md: 8a2399a19a097113d45f4915631d36ca30191dd5 +2026-09-05-package-manifest-types.md: dc018ba019028b942a17cd016c8670f2405c3bc7 +2026-09-05-package-manifest-types.zh.md: 8fd323bfe6058a6a062e3834a8630c0181a203fc diff --git a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.md b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.md index 5e9834583a..dc018ba019 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.md +++ b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.md @@ -10,13 +10,11 @@ External packages need Harness manifest types without depending on boot or clien ## Decision -[`@deepseek-ai/dsh-package-manifest`](../../../../packages/util/package-manifest/README.md) owns `DshManifest` and its member declarations in one type-only file. The package belongs to the existing utility group and exports no runtime values. Author declarations and launcher-generated module fallback metadata are explicitly distinguished. - -Author metadata stays under `package.json.dsh`: optional `manifestVersion` identifies format `1`, `categories` carries free-form discovery tags, and `engines.dsh` declares compatible host versions as a SemVer range. Npm package identity and Node requirements retain their top-level fields. Categories are extensible tags rather than a closed role enum, so labels such as `skills` and `tools` do not constrain package composition. +[`@deepseek-ai/dsh-package-manifest`](../../../../packages/util/package-manifest/README.md) owns `DshManifest` and its member declarations in one type-only file. The package belongs to the existing utility group and exports no runtime values. The [public package metadata decision](2026-09-10-public-package-manifest.md) owns the public field set and the separation from internal tool metadata. Readers import the shared declarations directly. Boot retains profile loading, raw JSON checks, defaults, and resolved runtime data. Client modules retain their normalized boot graph. The image packer resolves declared paths into directories. The Session catalog generator derives a read-only validated entry with a resolved import path; raw inputs and discovery rules remain local. -App-boot declares a production dependency because its published declarations reference the shared types. Client modules, the private packer, and root scripts use development dependencies because their published APIs do not expose these types. Every package consumer has a TypeScript project reference. External authors import from the utility package; app-boot provides no compatibility re-exports. +App-boot declares a production dependency because its published declarations reference the shared types. Client modules use a development dependency because their published APIs do not expose these types. Internal image-packer and Session catalog declarations stay with their readers. Every package consumer has a TypeScript project reference. External authors import from the utility package; app-boot provides no compatibility re-exports. ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.zh.md b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.zh.md index 8a2399a19a..8fd323bfe6 100644 --- a/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-05-package-manifest-types.zh.md @@ -10,13 +10,11 @@ Status: implemented ## 决策 -[`@deepseek-ai/dsh-package-manifest`](../../../../packages/util/package-manifest/README.zh.md) 在一个纯类型文件中拥有 `DshManifest` 及其成员声明。本包属于现有工具库分组,不导出运行时值。作者声明与启动器生成的模块后备元数据有明确区分。 - -作者元数据保留在 `package.json.dsh` 下:可选的 `manifestVersion` 标识格式 `1`,`categories` 承载自由发现标签,`engines.dsh` 以 SemVer 范围声明兼容的宿主版本。npm 包身份和 Node 要求沿用顶层字段。Categories 是可扩展标签,而非封闭的角色枚举,因此 `skills`、`tools` 等标签不限制包的组合。 +[`@deepseek-ai/dsh-package-manifest`](../../../../packages/util/package-manifest/README.zh.md) 在一个纯类型文件中拥有 `DshManifest` 及其成员声明。本包属于现有工具库分组,不导出运行时值。[公共包元数据决策](2026-09-10-public-package-manifest.zh.md) 拥有公共字段范围及其与内部工具元数据的划分。 各读取方直接导入共享声明。启动器保留 profile 加载、原始 JSON 检查、默认值和解析后的运行时数据。客户端模块保留归一化的启动图。镜像打包器将声明路径解析为目录。Session 目录生成器派生带有已解析导入路径的只读校验结果;原始输入和发现规则仍由本地负责。 -App-boot 声明生产依赖,因为其发布的声明文件引用共享类型。客户端模块、私有打包器和根脚本使用开发依赖,因为其发布 API 不暴露这些类型。每个包消费方都有 TypeScript 项目引用。外部作者从工具包导入;app-boot 不提供兼容性再导出。 +App-boot 声明生产依赖,因为其发布的声明文件引用共享类型。客户端模块使用开发依赖,因为其发布 API 不暴露这些类型。内部镜像打包器和 Session 目录声明保留在各自读取方。每个包消费方都有 TypeScript 项目引用。外部作者从工具包导入;app-boot 不提供兼容性再导出。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/architecture/2026-09-10-public-package-manifest.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-10-public-package-manifest.i18n.yaml new file mode 100644 index 0000000000..2dbaeb2625 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-10-public-package-manifest.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-10-public-package-manifest.md +2026-09-10-public-package-manifest.md: 222cdb58af580678136f269b60aa8271024dc8ca +2026-09-10-public-package-manifest.zh.md: c3659586f340dfb5bcfbbd0cc8266772207e63de diff --git a/.agents/notes/implemented/architecture/2026-09-10-public-package-manifest.md b/.agents/notes/implemented/architecture/2026-09-10-public-package-manifest.md new file mode 100644 index 0000000000..222cdb58af --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-10-public-package-manifest.md @@ -0,0 +1,35 @@ +# Agent Note: Public package manifest fields + +Status: implemented + +English | [中文](2026-09-10-public-package-manifest.zh.md) + +## Problem + +Plugin authors need npm identity, runtime requirements, and DSH declarations from one public import. Internal image-packaging, Session catalog, and generated proxy metadata do not define extension points for community plugins. Exposing those fields together makes internal mechanisms appear available to external authors. + +## Decision + +[`DshPackageManifest`](../../../../packages/util/package-manifest/src/types.ts) describes the package.json fields DSH uses, with required `name` and `version`. Its optional `dsh` member uses `DshManifest` for public composition and author metadata. The type is a selected npm field set, not a complete package.json schema. App-boot adapts it with `Partial` for local profiles, which need no published identity. + +Runtime requirements live at top-level `engines`: `dsh`, `node`, and `npm` are optional version strings, and other engine names are allowed. `dsh.manifestVersion` identifies declaration format `1`; `dsh.categories` carries free-form discovery tags without restricting package composition. Format and DSH compatibility declarations are not enforced by current installers or loaders. + +The image packer owns `configTrees`, the workspace catalog generator owns Session migration declarations, and app-boot owns generated module-fallback metadata. Their existing on-disk keys remain readable by those internal tools, but the public manifest types do not expose them. This scope refines the [shared declaration ownership decision](2026-09-05-package-manifest-types.md), whose package placement and dependency rules remain active. + +Each consumer owns JSON parsing, field validation, default resolution, and adaptation to runtime data. Interfaces do not validate parsed JSON. A helper belongs in the shared package only when multiple consumers need the same validation or normalization; getters that repeat property access add no shared policy. + +## Alternatives considered + +**Keep internal metadata in the public declaration.** A workspace-only migration catalog and an experimental image packer cannot offer public plugin behavior merely because their metadata is discoverable. + +**Put DSH compatibility under `dsh.engines`.** [VS Code](https://code.visualstudio.com/api/references/extension-manifest) places its host requirement in top-level `engines.vscode`. Top-level `engines.dsh` gives authors one location for runtime requirements; DSH still owns enforcement of its custom key. + +**Use peer dependencies as the sole host requirement.** Peer dependencies constrain installed npm packages, including the CLI package `@deepseek-ai/dsh`. They do not identify the currently running DSH process when plugins live in a separate profile project. + +**Parse every domain through one mandatory parser.** Existing readers consume different subsets and own different errors and defaults. Combining them would make a client reader validate unrelated profile declarations. The public types remain independent of filesystem access and parsing policy. + +## Consequences + +External authors gain a complete package-level declaration and a smaller DSH author API. Consumers of removed internal types must use their owning implementations. The packer and repository catalog no longer depend on the public declaration package; app-boot retains a production dependency because its published profile type references it. + +Compiler and built NodeNext import checks verify required package identity, partial profiles, top-level engine declarations, and the absence of internal fields from the public API. Existing profile, packer, and Session catalog tests retain coverage of their accepted files and malformed declarations. No Session format, plugin loading rule, or model-visible behavior changes. diff --git a/.agents/notes/implemented/architecture/2026-09-10-public-package-manifest.zh.md b/.agents/notes/implemented/architecture/2026-09-10-public-package-manifest.zh.md new file mode 100644 index 0000000000..c3659586f3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-10-public-package-manifest.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 公共 package manifest 字段 + +Status: implemented + +[English](2026-09-10-public-package-manifest.md) | 中文 + +## 问题 + +插件作者需要从统一的公共导入路径获取 npm 身份、运行时要求和 DSH 声明。内部镜像打包、Session 目录和生成的代理元数据不定义社区插件扩展点。将这些字段一起暴露,会让外部作者误以为内部机制也可供使用。 + +## 决策 + +[`DshPackageManifest`](../../../../packages/util/package-manifest/src/types.ts) 描述 DSH 使用的 package.json 字段,其中 `name` 和 `version` 必填。其可选的 `dsh` 成员使用 `DshManifest` 描述公共组合与作者元数据。该类型只选取所需 npm 字段,不是完整的 package.json schema(模式)。App-boot 通过 `Partial` 适配无需发布身份的本地 profile。 + +运行时要求位于顶层 `engines`:`dsh`、`node` 和 `npm` 均为可选版本字符串,也允许其他 engine 名称。`dsh.manifestVersion` 标识声明格式 `1`;`dsh.categories` 承载自由发现标签,不限制包的组合。当前安装器和加载器不强制检查格式与 DSH 兼容性声明。 + +镜像打包器拥有 `configTrees`,工作区目录生成器拥有 Session 迁移声明,app-boot 拥有生成的模块后备元数据。这些内部工具仍可读取既有磁盘字段,但公共 manifest 类型不暴露这些字段。此范围细化了[共享声明归属决策](2026-09-05-package-manifest-types.zh.md),后者的包位置与依赖规则仍然有效。 + +各消费方负责 JSON 解析、字段校验、默认值解析和运行时数据适配。接口不会校验已解析的 JSON。只有多个消费方需要相同校验或归一化时,helper 才属于共享包;重复属性访问的 getter 不提供共享策略。 + +## 考虑过的替代方案 + +**将内部元数据保留在公共声明中。** 仅限工作区的迁移目录和实验性镜像打包器,不会因为其元数据可被发现就提供公共插件行为。 + +**将 DSH 兼容性放在 `dsh.engines` 下。** [VS Code](https://code.visualstudio.com/api/references/extension-manifest) 将宿主要求放在顶层 `engines.vscode`。顶层 `engines.dsh` 让作者在同一位置声明运行时要求;自定义键的检查仍由 DSH 负责。 + +**仅用 peer dependency 声明宿主要求。** Peer dependency 约束已安装的 npm 包,包括 CLI 包 `@deepseek-ai/dsh`。插件位于独立 profile 项目时,它们无法标识当前运行的 DSH 进程。 + +**通过统一的强制解析器解析所有领域。** 现有读取方消费不同字段子集,并各自拥有错误与默认值。合并它们会让客户端读取方校验无关的 profile 声明。公共类型保持独立于文件系统访问和解析策略。 + +## 后果 + +外部作者获得完整的包级声明和更小的 DSH 作者 API。已移除内部类型的消费方必须使用各自负责的实现。打包器与仓库目录不再依赖公共声明包;app-boot 保留生产依赖,因为其发布的 profile 类型引用该包。 + +编译器和构建后的 NodeNext 导入检查验证包身份必填、部分 profile、顶层 engine 声明,以及公共 API 不含内部字段。现有 profile、打包器和 Session 目录测试继续覆盖其接受的文件与畸形声明。Session 格式、插件加载规则和模型可见行为均不改变。 diff --git a/package.json b/package.json index a09fa3f997..6bf6dea6c9 100644 --- a/package.json +++ b/package.json @@ -184,7 +184,6 @@ }, "devDependencies": { "@deepseek-ai/dsh-agent": "workspace:^", - "@deepseek-ai/dsh-package-manifest": "workspace:^", "@deepseek-ai/dsh-tool-session-query": "workspace:^", "@deepseek-ai/dsh-web-fetch-http": "workspace:^", "@stylistic/eslint-plugin": "^5.10.0", diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index 3d4666ea0d..3d70dc1c39 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/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/boot/app-boot/README.md -README.md: df386b64089f962960b09538381e9d4b4905feb0 -README.zh.md: 5a7246c52ea5bcc8d5322d9fac4a87ec2e2ef4cc +README.md: a525440f20879314bd8d12b647830f2c541f59b3 +README.zh.md: d194f191374e50811d4831933bf8e8b2b831cd40 diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index df386b6408..a525440f20 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -45,7 +45,7 @@ With that entry point, success looks like a running app with every plugin active ### Profiles -Import profile and bundle declaration types from [`@deepseek-ai/dsh-package-manifest`](../../util/package-manifest/README.md). App-boot owns profile loading, JSON validation, and resolved runtime data. +Import profile and bundle declaration types from [`@deepseek-ai/dsh-package-manifest`](../../util/package-manifest/README.md). App-boot adapts `DshPackageManifest` to `ProfileManifest` with optional package identity because local profiles need no published version. App-boot owns profile loading, JSON validation, and resolved runtime data. A profile is how one dsh installation ships different app surfaces: `web`, `headless`, `acp`, `sdk`, and `sdk-minimal` start distinct compositions from the same launcher. A profile lives at `$DSH_HOME/profiles/` and combines installable bundles, its own `cordis.patch.yml`, and `patchReload: live | startup`; omitted reload policy keeps the historical `live` default for custom profiles. The shipped `web` template uses live reload, while the other shipped templates apply patches only at startup. `sdk-minimal` names only its standalone bundle; the other templates retain base-plus-mode stacks. `dsh --profile --from-default-profile