diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml index 97db170db9..3c63acb8dc 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml @@ -9,8 +9,8 @@ en: 31fba384d90ce7d2 zh: f8b814868f3280c3 /agent-note-session-working-directory/decision: - en: 5ff0c24c29c916b9 - zh: bfbb082623c2a86c + en: 7f8ceafccd5951ec + zh: 758ff83ae3fa868a /agent-note-session-working-directory/alternatives-considered: en: f0995feb9b6bcce8 zh: 97417085fd17f70f diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md index 6b8a6c9507..0ceb45fd86 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md @@ -24,7 +24,7 @@ Web sidebar terminal environment lookup reads the workspace root without filesys Playwright MCP and Chrome DevTools MCP validate the effective directory when acquiring a Session's MCP connection and use it to launch the server. Later directory changes do not restart the retained server or change its process directory. -File links and command directory labels use result metadata captured when each operation runs, so historical rows remain correct after later directory changes. +File links and command directory labels use result metadata captured when each operation runs, so historical rows remain correct after later directory changes. References in prose, user mentions, and opened Sidebar tabs follow [conversation file references after directory moves](../bug-fix/2026-11-19-conversation-file-references-after-directory-moves.md). The [prompt-variables note](2026-07-05-prompt-variables-and-tool-guidance-ownership.md) retains strict interpolation, route-variable ownership, and tool-guidance ownership. The [environment-suffix note](../../archived/bug-fix/2026-09-06-environment-prompt-suffix.md) retains ordered prefix/suffix placement for deployment, Harness source, and Web guidance. This decision owns directory state and placement in user context. diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md index 8d99661c89..2ae4e33fdb 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md @@ -24,7 +24,7 @@ Web 侧栏终端的环境查询读取工作区根,不验证文件系统或执 Playwright MCP 和 Chrome DevTools MCP 在获取 Session 的 MCP 连接时验证有效目录,并在该目录启动服务器。后续目录变更不会重启保留的服务器,也不会改变其进程目录。 -文件链接与命令目录标签使用各次操作执行时记录的结果元数据,因此后续目录变更不会使历史记录指向错误的位置。 +文件链接与命令目录标签使用各次操作执行时记录的结果元数据,因此后续目录变更不会使历史记录指向错误的位置。正文里的引用、用户 mention 与已打开的侧边栏 tab 遵循[目录移动后的对话文件引用](../bug-fix/2026-11-19-conversation-file-references-after-directory-moves.zh.md)。 [提示词变量记录](2026-07-05-prompt-variables-and-tool-guidance-ownership.zh.md)保留严格插值、路由变量归属与工具指导归属。[环境后缀记录](../../archived/bug-fix/2026-09-06-environment-prompt-suffix.md)保留部署、Harness 源码与 Web 指导的有序前缀/后缀位置。本决策拥有目录状态及其用户上下文位置。 diff --git a/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.i18n.yaml index 26bf24ff02..339d03fd6d 100644 --- a/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.i18n.yaml @@ -15,14 +15,14 @@ en: 7095df7c949b8e3c zh: e7410e44eaa97797 /agent-note-stable-sidebar-tab-mounting-and-session-retention/decision/session-and-tab-lifetime: - en: 60a4450a1a4f398c - zh: cc0054505b973c91 + en: 14dfb86c9f786a44 + zh: 268bd8bbfdb2a968 /agent-note-stable-sidebar-tab-mounting-and-session-retention/decision/provider-responsibilities: en: a34c228751a1a329 zh: 8e8b962b55e7c68e /agent-note-stable-sidebar-tab-mounting-and-session-retention/decision/retention-versus-recovery: - en: 61e4a975fea17a9a - zh: 911f4d1caab1efd0 + en: 010e66146bcb9f6c + zh: b2714d75ceebbd71 /agent-note-stable-sidebar-tab-mounting-and-session-retention/alternatives-considered: en: 84cfe7613657bfdb zh: 4a0a499eb5d36d22 diff --git a/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.md b/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.md index 574667c79f..96191e1f3c 100644 --- a/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.md +++ b/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.md @@ -22,7 +22,7 @@ Sidebar owns live-body retention, independently of Browser navigation and Worksp ### Session and tab lifetime -`SidebarRightTabDefinition.keepMounted` enables lazy retention for a type. Desktop Browser enables it; other types keep visibility-based body mounting. A retained body is first created on display, then survives hiding until its occurrence or provider lifetime ends. The policy is not persisted and does not select a storage partition. +`SidebarRightTabDefinition.keepMounted` enables lazy retention for a type. Desktop Browser enables it. Each tab opened through `openContent` also retains its visited body for the lifetime of the current window. A retained body is first created on display, then survives hiding until its occurrence or provider lifetime ends. The policy is not persisted and does not select a storage partition. `SidebarSessionView` acquires and releases one `SessionReference` using the independent `sidebarView` source, and owns its committed-mount count and retained-Body holds. `SidebarSessionViews` manages selection, retention policy and view indexes; it delegates lifetime operations to the view rather than mutating its counts or releasing its reference. `RightbarRoot` receives `SidebarSessionViewSnapshot` values and the existing injected callbacks, not resource-owner objects. It renders each through its own explicit `SessionProvider`, with a stable Session key; the renderer's general Session-remount semantics remain unchanged. @@ -48,11 +48,13 @@ The [Desktop Browser decision](../feature/2026-09-20-desktop-browser-webview.md) | Collapse Sidebar | Hide docked cells; foreground floats remain visible. | | Session A → B → A | Hide and reshow A's original tree instead of loading its saved URL. | | Close, provider unload or actual generation termination | Release the body and guest; undo creates a new occurrence. | -| Application restart or window reload | Show the saved title and URL; load only after an explicit restore or address submission. | +| Application restart or window reload | Restore tabs whose content can be reconstructed. Browser shows its saved URL for explicit recovery. Close transient content tabs and their floats before presenting the layout. | | Guest crash | Retry through the provider; page memory and native history are not durable. | [Layout and provider recovery](../../../../packages/client/ui-sidebar-right/README.md) remains independent: persisted tab identity, placement and address support cold starts, not DOM serialization. A hidden page may continue scripts, media and networking. +A tab opened through `openContent` receives its body in window-local navigation parameters. Its reuse key identifies an occurrence within a Session, but cannot recover the body. Restoring that tab would leave an empty viewer and could displace a file or other recoverable tab. Users can reopen the content from its source after reload. + ## Alternatives considered **Hide panes only.** Collapse works, but moving between panes or into another floating portal still changes content ancestors. diff --git a/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.zh.md b/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.zh.md index a2a88a209b..9d1335141f 100644 --- a/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-20-sidebar-retained-tab-layout.zh.md @@ -22,7 +22,7 @@ Sidebar 负责活 Body 的保留,不依赖 Browser 导航和 Workspace 存储 ### 会话与 Tab 生命周期 -`SidebarRightTabDefinition.keepMounted` 为类型启用懒保活。Desktop Browser 启用它,其他类型继续按可见性挂载 Body。保活 Body 在首次显示时创建,随后隐藏不卸载,直到 occurrence 或提供方生命周期结束。该策略不持久化,也不选择存储分区。 +`SidebarRightTabDefinition.keepMounted` 为类型启用懒保活。Desktop Browser 启用它。通过 `openContent` 打开的标签也会在当前窗口的生命周期内保留已查看的正文。保活 Body 在首次显示时创建,随后隐藏不卸载,直到 occurrence 或提供方生命周期结束。该策略不持久化,也不选择存储分区。 `SidebarSessionView` 使用独立的 `sidebarView` 来源申请、释放一个 `SessionReference`,并管理自己的已提交挂载计数和 Body 保活持有。`SidebarSessionViews` 管理选中、保留策略和视图索引,将生命周期操作委托给视图,而不修改其计数或释放其引用。`RightbarRoot` 接收 `SidebarSessionViewSnapshot` 和已有注入回调,不接收资源所有者对象;它为各视图分别渲染显式 `SessionProvider`,保持会话 key 稳定,渲染器通用的会话重挂载语义不变。 @@ -48,11 +48,13 @@ Tab 提供 Body 保活持有,而不独立申请会话引用。View 的稳定 ` | 收起 Sidebar | 隐藏停靠 cell,前台浮窗保持可见。 | | 会话 A → B → A | 隐藏并重新显示 A 的原内容树,而非加载已保存 URL。 | | 关闭、提供方卸载或真实 generation 结束 | 释放 Body 和 guest;撤销关闭创建新 occurrence。 | -| 应用重启或窗口刷新 | 展示保存的标题和 URL,显式恢复或提交地址后才加载。 | +| 应用重启或窗口刷新 | 恢复能够重建正文的标签。Browser 显示已保存的 URL 供用户显式恢复。呈现布局前关闭临时正文标签及其浮窗。 | | guest 崩溃 | 通过提供方重试;页面内存和原生 history 不持久化。 | [布局与提供方恢复](../../../../packages/client/ui-sidebar-right/README.zh.md)仍然独立:持久化的 Tab 身份、位置和地址支持冷启动,而不是序列化 DOM。隐藏页面可能继续执行脚本、播放媒体或联网。 +通过 `openContent` 打开的标签从当前窗口的导航参数取得正文。复用 key 能在会话内定位标签,却无法据此恢复正文。恢复这样的标签会留下空预览,还可能占据文件等可恢复标签的位置。刷新后,用户可从内容来源重新打开。 + ## Alternatives considered **只隐藏 Pane。** 可以覆盖收起,但跨 Pane 移动或进入独立浮动 Portal 仍会改变内容祖先。 diff --git a/.agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.i18n.yaml new file mode 100644 index 0000000000..aa21f76d9b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-12-forge-status-briefs.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.md +/agent-note-forge-status-briefs: + en: 51cd3647298126c4 + zh: 07f18bcd7bd2a7c3 +/agent-note-forge-status-briefs/problem: + en: f99803963e0818f4 + zh: b4aba14e12cdeede +/agent-note-forge-status-briefs/decision: + en: 847ad02b06062771 + zh: ce8747cbc2b15545 +/agent-note-forge-status-briefs/alternatives-considered: + en: 4dfbe3ae83d89e7a + zh: 74ded5f0f1b8c5b3 +/agent-note-forge-status-briefs/consequences: + en: 2b4e5ebfef68df7e + zh: 72e774ad90908f21 diff --git a/.agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.md b/.agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.md new file mode 100644 index 0000000000..73f6a515de --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.md @@ -0,0 +1,67 @@ +# Agent Note: Forge status briefs + +Status: implemented + +English | [中文](2026-11-12-forge-status-briefs.zh.md) + +## Problem + +The Session list shows a state glyph for every change request that a listed Session binds, and read the full snapshot of each one for it: up to 100 check contexts, reviewers, review threads, linked issues, and the repository's merge settings. The registry batches every due change request of a forge, and the GitHub provider put a host's whole batch in one GraphQL query. GitHub ends a request after 10 seconds of processing: a snapshot query of 20 deepseek-harness pull requests took 10.2 s, one of 30 answered HTTP 504, and one of 61 HTTP 502. Every watch of a new list run was due at once, so the list of a user with about 30 bound pull requests failed as a whole and retried as a whole. Opening a Session whose change request the list already watched read nothing, so its panel waited up to one idle interval for a newer status. + +Other reads repeated without need. Change requests shared a fetch only when they became due in the same millisecond, so 14 list watches cost 30 queries an hour while they stayed aligned and 415 once they had drifted apart. Each time a Session's panel was shown again, the Host probed sign-in and looked the branch up again, and the client forced a second status read. Each saved viewed mark made every open changes view read all marks and all review threads again. A push or a `gh pr merge` by the agent started no status read. + +## Decision + +**Two levels of status.** A brief holds what a list shows: title, state, draft flag, mergeability, review decision, and combined check outcome. `ctx.forge.watchBrief` watches it; `ctx.forge.watch` watches the snapshot. A watched change request is polled for its snapshot while it has a snapshot watcher and for its brief otherwise. A snapshot holds a brief, so brief watchers receive every result. Providers read briefs through the optional `fetchBriefs`; the registry reads snapshots from a provider without it. + +**GitHub brief query.** forge-github reads a brief from the pull request's own scalars and the `statusCheckRollup.state` of its head commit, 25 pull requests per query (`briefBatchSize`). Measured on deepseek-harness pull requests through `gh`, a query of 10 took 1.6 to 2.0 s, one of 25 took 2.5 to 3.4 s, and one of 50 took 2.9 to 6.8 s, at a rate-limit cost of 1 point each; 25 leaves a wider margin to GitHub's 10 seconds than 50 does. In a snapshot query the check contexts are the largest part: 174 of 186 KB and 1.4 of 3.8 s for 8 pull requests. + +**GitHub snapshot queries of bounded size.** A Session can bind many pull requests, and its panel watches the snapshot of each. forge-github puts at most 8 pull requests of a host in one snapshot query (`snapshotBatchSize`): measured the same way, a query of 5 took 3.6 s, one of 8 took 4.4 to 6.3 s, and one of 10 took 5.8 s. Queries are sent one after another, because GitHub asks an account to send its requests serially. A query whose `gh` run fails, and one GitHub refuses, fails only its own pull requests. + +**One provider call per query.** A provider may name `snapshotBatchSize` and `briefBatchSize` to the registry, and forge-github does. The registry then calls the provider once per that many due change requests of a host, one call after another, each within its own `fetchTimeoutMs`, and settles the watches of a call when it returns. A call that fails or outlives its deadline fails only its own change requests, and the results of earlier calls stay published. A provider that names no size, as forge-gitlab, is called once with every due change request of the forge. + +**One fetch in flight per forge and level.** A snapshot fetch for an open panel does not wait behind the brief fetch of a long list, and a host sees at most two status requests of one registry at a time. + +**Polls that share a fetch.** A fetch reads the due change requests of its forge and level, and also those past the midpoint of the wait after their latest status. Change requests that became due at different times therefore return to one fetch: the 14 list watches cost 30 queries an hour at the earlier intervals whether they were bound together, one after another, or had checks running for a while. A change request waits out the backoff after a failed read in full. + +**Intervals.** An open change request is polled every 15 seconds while its checks run and every 60 seconds otherwise (`activeIntervalMs`, `idleIntervalMs`), at both levels. A status that first reports an unknown mergeability earns one poll at the active interval; one that reports it again waits the idle interval, because 11 of 98 open pull requests measured, all drafts stacked on another pull request's branch, kept reporting it. + +**What the list already knows.** The list's run passes the state it stored for a change request as `known`. The registry times the first poll as it would after a read at `known.fetchedAt`, so a merged change request is not read again, and a run that follows another in the same process waits for the interval. Read times stay in memory; a state stored by an earlier process counts as read at the epoch. + +**A status newer than the latest one.** A snapshot watcher and `refresh` may pass `maxAgeMs`. The Session panel and the review page pass `statusMaxAgeMs` (10 seconds) when they start, so opening a Session reads its change requests at once unless they were just read; showing the panel again and focusing the window call the `revisit` Remote, which polls with the same bound, while the reader's refresh stays forced. The installed desktop apps of two peer products do the same: Codex refetches a thread's pull request when the thread mounts with data older than 15 seconds, and Claude prefetches a session's pull request when its row is pressed, with a freshness of 10 seconds. + +**Reads after the agent's commands.** After a push result, forge-session calls `ctx.forge.expectChange` for the visible change requests in the pushed repository: a watched one is polled at once and then at the active interval until a status reports running checks, for at most one idle interval. When a turn that had a tool result ends, forge-session refreshes the Session's visible change requests with the age of that result as `maxAgeMs`. + +**Nothing read for a hidden page.** The client closes the panel streams, the list's state stream, and the review count stream once the page has been hidden for 30 seconds, and opens them again when it shows. The Host polls only while a stream is open, so it needs no report of the page's visibility, and it keeps polling while any tab of the page is visible. + +**Panel state kept between followers.** A Session's panel leaves its last state, snapshots, and branch lookup when its last follower leaves, and the next panel of that Session starts from them unless the Session moved to another directory. It repeats neither the sign-in probe of a host found ready nor the branch lookup of a Session that shows a change request; a status read refused as unauthenticated starts one probe. + +**Viewed marks kept on the Host.** The Host keeps the viewed marks read for a change request by head commit, under the bounds of the kept review threads. A saved mark replaces the kept state of its file and leaves the kept threads, so a save costs the provider's write and no further read. + +## Alternatives considered + +**Bounding snapshot queries only** keeps each query short, but a list of 61 pull requests then needs 8 queries and 38 s for fields the list never shows. + +**A longer `fetchTimeoutMs` or concurrent snapshot queries** leave GitHub's processing time per query unchanged, and GitHub allows one account 60 s of GraphQL CPU time per 60 s. + +**REST with conditional requests** returns HTTP 304 without rate-limit cost through `gh`, but takes one `gh` process per pull request, about 1.2 s each, and carries no combined check state. + +**Webhooks** need a server that receives them; the Host is a local process that reads through the user's `gh`. + +**A `level` option on `watch`** would give one method two listener types; two methods keep each listener's update type exact. + +**Storing read times** would save the first brief read after a Host restart only when the restart falls within one poll interval, at the cost of a change to the stored record. + +**A queue per host with a lane for user actions** would let a refresh pass a fetch in flight. The two levels already keep an open panel apart from the list, and a snapshot query takes 2 to 6 s, so the queue would save that much on a refresh at the cost of a second scheduler. + +**A random offset on each interval** spreads requests over time, which is the opposite of what the measured cost needs: it would separate change requests that one query reads together. + +**Pausing a host after a refused read** saves little: 14 change requests that were all refused as unauthenticated backed off together and cost 10 queries in an hour. + +**A budget of one background query per interval** matters only past the size one fetch reads in time; 100 pull requests took two brief queries of 50 and 7.6 s. + +**A faster cadence after a push**, 5 seconds for a minute as one peer product uses, needs two more settings; the active interval shows new checks at most about 10 seconds later. + +## Consequences + +For the case measured, 14 open and 17 merged bound pull requests, a poll of the list is one request of about 1.7 s in place of one query of 31 snapshots, which GitHub answered with HTTP 504, and the merged ones are not read. At the 60-second idle interval that is 59 queries an hour while the page is visible, and none while it is hidden. A change request past the midpoint of its wait is read with any fetch of its lane, so one whose neighbor has running checks is read up to twice as often as its own interval asks; the number of queries does not grow with it. A brief reports GitHub's combined check state, while a snapshot with a complete check list derives its own from the newest run of each check; the two agreed for all 61 open pull requests measured, and nothing reconciles them when they differ. One snapshot query and the continuation pages of its pull requests share one deadline, so a pull request with many review threads can fail the up to 8 pull requests of its query. A viewed mark changed on the code host itself shows after `reviewRefreshMs` or the reader's refresh. A page that stays visible without a reader keeps polling. diff --git a/.agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.zh.md b/.agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.zh.md new file mode 100644 index 0000000000..ad8fd63bf5 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-12-forge-status-briefs.zh.md @@ -0,0 +1,67 @@ +# Agent Note: Forge 状态简报 + +Status: implemented + +[English](2026-11-12-forge-status-briefs.md) | 中文 + +## Problem + +会话列表为每个已列出 Session 绑定的变更请求显示一个状态图标,此前为此读取每个变更请求的完整快照:最多 100 个检查 context、评审人、评审讨论、关联 issue 以及仓库的合并设置。注册表把同一个 forge 所有到期的变更请求合成一批,GitHub 提供方此前把一个主机的整批放进同一个 GraphQL 查询。GitHub 在处理一个请求超过 10 秒后终止它:包含 20 个 deepseek-harness pull request 的快照查询耗时 10.2 s,30 个的返回 HTTP 504,61 个的返回 HTTP 502。列表每次新的运行会让所有监听同时到期,所以绑定了约 30 个 pull request 的用户,列表会整批失败、整批重试。打开一个 Session 时,如果列表已经在监听它的变更请求,就不会触发任何读取,面板最长要等一个空闲间隔才有更新的状态。 + +还有一些读取是不必要的重复。变更请求只有在同一毫秒到期时才共用一次读取,所以 14 个列表监听在保持对齐时每小时 30 个查询,错开之后是 415 个。每次重新显示 Session 的面板,Host 都重新检查登录状态、重新按分支查找,客户端还会强制再读一次状态。每保存一个已审阅标记,所有打开的变更视图都会重读全部标记和全部评审讨论。Agent 的推送或 `gh pr merge` 不会触发状态读取。 + +## Decision + +**两个层级的状态。** 简报包含列表显示的内容:标题、状态、草稿标记、可合并性、评审结论与检查汇总结果。`ctx.forge.watchBrief` 监听简报;`ctx.forge.watch` 监听快照。被监听的变更请求在有快照监听方时轮询快照,否则轮询简报。快照包含简报,所以简报监听方能收到每一次结果。提供方通过可选的 `fetchBriefs` 读取简报;提供方没有该方法时,注册表从它读取快照。 + +**GitHub 简报查询。** forge-github 从 pull request 自身的标量字段和 head 提交的 `statusCheckRollup.state` 读出简报,每个查询 25 个 pull request(`briefBatchSize`)。通过 `gh` 在 deepseek-harness 的 pull request 上实测,10 个的查询用 1.6 至 2.0 s,25 个的用 2.5 至 3.4 s,50 个的用 2.9 至 6.8 s,速率配额各消耗 1 点;25 个比 50 个离 GitHub 的 10 秒上限更远。快照查询里检查 context 占比最大:8 个 pull request 时占 186 KB 中的 174 KB、3.8 s 中的 1.4 s。 + +**大小有上限的 GitHub 快照查询。** 一个 Session 可以绑定多个 pull request,它的面板监听其中每一个的快照。forge-github 在一个快照查询里最多放同一主机的 8 个 pull request(`snapshotBatchSize`):用同样的方式实测,5 个的查询用 3.6 s,8 个的用 4.4 至 6.3 s,10 个的用 5.8 s。查询依次发送,因为 GitHub 要求同一账号串行发送请求。某个查询的 `gh` 运行失败或被 GitHub 拒绝时,只有该查询内的 pull request 失败。 + +**每个查询一次提供方调用。** 提供方可以向注册表声明 `snapshotBatchSize` 与 `briefBatchSize`,forge-github 声明了这两项。这时注册表为同一主机每这么多个到期的变更请求调用提供方一次,依次调用,每次调用有自己的 `fetchTimeoutMs`,并在调用返回时结算它的监听。某次调用失败或超过时限时,只有它读取的变更请求失败,之前各次调用的结果保持已发布。没有声明大小的提供方(如 forge-gitlab)仍然一次调用读取该 forge 所有到期的变更请求。 + +**每个 forge、每个层级同时只有一次读取。** 为打开的面板读取快照,不用排在长列表的简报读取后面;一个主机同时最多看到同一个注册表的两个状态请求。 + +**共用一次读取的轮询。** 一次读取除了读它的 forge 和层级上到期的变更请求,还读距上一次状态的等待已过半的变更请求。所以在不同时刻到期的变更请求会回到同一次读取里:14 个列表监听在此前的间隔下每小时 30 个查询,不论它们是同时绑定、逐个绑定,还是中途有检查运行过一阵。读取失败后的退避时间,变更请求会完整等完。 + +**间隔。** 打开状态的变更请求在检查运行时每 15 秒轮询一次,否则每 60 秒一次(`activeIntervalMs`、`idleIntervalMs`),两个层级相同。状态第一次报告可合并性未知时,按活跃间隔再轮询一次;再次报告未知时等待空闲间隔,因为实测的 98 个打开的 pull request 里有 11 个一直报告未知,它们都是叠在另一个 pull request 分支上的草稿。 + +**列表已经知道的状态。** 列表的运行把它为变更请求存下的状态作为 `known` 传入。注册表按“在 `known.fetchedAt` 读过一次”来安排首次轮询,所以已合并的变更请求不再读取,同一进程里紧接着的下一次运行会等到间隔到期。读取时间只保存在内存中;更早的进程存下的状态按在纪元时刻读取处理。 + +**比最近一次更新的状态。** 快照监听方和 `refresh` 都可以传入 `maxAgeMs`。会话面板和评审页开始时传入 `statusMaxAgeMs`(10 秒),所以打开 Session 会立即读取它的变更请求,除非刚刚读过;再次显示面板和窗口获得焦点时调用 `revisit` Remote,它按同样的上限轮询,读者手动刷新则仍然强制读取。两个同类产品已安装的桌面应用也是这样做的:Codex 在线程挂载且数据超过 15 秒时重新读取它的 pull request,Claude 在会话行被按下时预读它的 pull request,新鲜期为 10 秒。 + +**Agent 的命令之后的读取。** 收到推送结果后,forge-session 为被推送仓库里可见的变更请求调用 `ctx.forge.expectChange`:被监听的变更请求立即轮询,之后按活跃间隔轮询,直到状态报告检查正在运行为止,最长持续一个空闲间隔。有过工具结果的回合结束时,forge-session 刷新该 Session 可见的变更请求,以那个结果距今的时间作为 `maxAgeMs`。 + +**不为隐藏的页面读取。** 页面隐藏满 30 秒后,客户端关闭面板流、列表的状态流和评审计数流,页面再次显示时重新打开。Host 只在有流打开时轮询,所以不需要页面上报可见性;只要页面有一个标签页可见,它就继续轮询。 + +**在关注方之间保留面板状态。** Session 的面板在最后一个关注方离开时留下它最后的状态、快照和分支查找结果,该 Session 的下一个面板从它们开始,除非 Session 换到了其他目录。它不重复已确认就绪的托管平台的登录检查,也不重复已显示变更请求的 Session 的分支查找;状态读取被以未登录拒绝时会触发一次登录检查。 + +**Host 保留已审阅标记。** Host 按 head 提交保留为变更请求读到的已审阅标记,受与所保留评审讨论相同的限制。保存一个标记会替换所保留的对应文件状态,并保留评审讨论,所以一次保存只需要提供方的那次写入,不再读取。 + +## Alternatives considered + +**只限制快照查询的大小**能让每个查询足够短,但 61 个 pull request 的列表仍需要 8 个查询和 38 s,而读回的字段列表根本不显示。 + +**调大 `fetchTimeoutMs` 或并发发送快照查询**不改变 GitHub 处理每个查询的时间,而且 GitHub 只允许一个账号每 60 s 使用 60 s 的 GraphQL CPU 时间。 + +**带条件请求的 REST** 经 `gh` 返回 HTTP 304 时不消耗速率配额,但每个 pull request 要启动一个 `gh` 进程,各约 1.2 s,而且没有检查汇总状态。 + +**Webhook** 需要一个接收它的服务端;Host 是本地进程,通过用户自己的 `gh` 读取。 + +**给 `watch` 加 `level` 选项**会让一个方法有两种监听方类型;分成两个方法,每种监听方的更新类型都是确定的。 + +**存储读取时间**只有在 Host 重启恰好落在一个轮询间隔之内时,才能省下重启后的第一次简报读取,代价是改动已存记录。 + +**每个主机一个队列、用户操作单独一条通道**能让刷新越过正在进行的读取。两个层级已经把打开的面板和列表分开,一个快照查询耗时 2 至 6 s,所以这个队列在一次刷新上最多省下这么多时间,代价是第二套调度。 + +**给每个间隔加随机偏移**会把请求在时间上摊开,这和实测的开销所需要的正相反:它会把一个查询本可以一起读的变更请求分开。 + +**读取被拒绝后暂停整个主机**省不下多少:14 个全部被以未登录拒绝的变更请求一起退避,一小时只花 10 个查询。 + +**每个间隔只发一个后台查询的预算**只在超出一次读取能及时读完的规模时才有意义;100 个 pull request 用了两个各 50 个的简报查询,共 7.6 s。 + +**推送之后用更快的节奏**(一个同类产品用 5 秒、持续一分钟)需要再加两个配置项;按活跃间隔,看到新检查最多晚约 10 秒。 + +## Consequences + +在实测的场景里(绑定了 14 个打开、17 个已合并的 pull request),列表的一次轮询是一个约 1.7 s 的请求,取代原来包含 31 个快照、被 GitHub 以 HTTP 504 拒绝的查询,已合并的不再读取。按 60 秒的空闲间隔,页面可见时每小时 59 个查询,隐藏时没有。等待已过半的变更请求会随它所在通道的任何一次读取一起读,所以相邻的变更请求有检查在运行时,它被读取的频率最高是自身间隔的两倍;查询个数不会因此增加。简报报告 GitHub 的检查汇总状态,检查列表完整的快照则根据每个检查的最新一次运行自行得出结果;实测的 61 个打开的 pull request 两者全部一致,不一致时没有机制去对齐。一个快照查询和它的 pull request 的续页共用一个时限,所以评审讨论很多的 pull request 可能让它所在查询的最多 8 个 pull request 一起失败。在代码托管平台上直接改动的已审阅标记,要等到 `reviewRefreshMs` 之后或读者刷新时才显示。一直可见但没有人看的页面会继续轮询。 diff --git a/.agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.i18n.yaml new file mode 100644 index 0000000000..b7459e68f7 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-19-conversation-file-references-after-directory-moves.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.md +/agent-note-conversation-file-references-after-directory-moves: + en: 7c9b48dfb0ed6d1d + zh: ee798f35eb331fa0 +/agent-note-conversation-file-references-after-directory-moves/problem: + en: 73cba25d5f74c0d0 + zh: bfaf698abaeb9387 +/agent-note-conversation-file-references-after-directory-moves/decision: + en: 17dfb45b8f45c62d + zh: aa9868110a63b921 +/agent-note-conversation-file-references-after-directory-moves/alternatives-considered: + en: 99dc2ca8f3af2c59 + zh: 9f9346a258ddb73c +/agent-note-conversation-file-references-after-directory-moves/consequences: + en: a9acefcc270d69e8 + zh: 90904b444fb060c4 diff --git a/.agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.md b/.agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.md new file mode 100644 index 0000000000..d93a12e006 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.md @@ -0,0 +1,42 @@ +# Agent Note: Conversation file references after directory moves + +Status: implemented + +English | [中文](2026-11-19-conversation-file-references-after-directory-moves.zh.md) + +## Problem + +A Session's directory moves during its life: `enter_worktree`, `exit_worktree`, and Host operations each record a `workspace-root/change` ([Session working directory](../architecture/2026-09-13-session-working-directory.md)). Tool rows, produced-file mentions, presented files, and changed-file cards store the absolute path of the operation that produced them, so they keep naming their file. References that stored only relative text did not: + +- A relative Markdown link in an earlier reply, and a picked `@file` in an earlier message, were resolved against the directory at the click. After a move they opened the same path in another checkout or reported a missing file. +- A relative inline image was resolved against the header directory, so an image written in a worktree did not load even before a later move. +- An opened Sidebar tab stored a relative address for a file inside the Session's directory. After a move and a page reload it showed another file or none. + +## Decision + +**Each reference carries an absolute path from the moment it is written.** No reader reconstructs the directory a reference was written in. + +- The `ui:deliverable-file-references` guidance asks the model for absolute Markdown link and image targets. +- `fileAddressFor` puts the absolute path in the `dsh-resource://file/session/…` address: an absolute path is kept, and a relative path is joined to the directory the caller knows. An opened tab names one file for its lifetime. +- A file or folder picked from the `@` list is written as an absolute mention. A file dropped or pasted in Desktop keeps the absolute path the shell reports. +- A relative path that still reaches the Client resolves against the Session's current directory: one the model wrote despite the guidance, one typed by hand after `@`, or one written before this decision. Links, images, and context-menu actions share that base. + +## Alternatives considered + +**Resolve each relative reference against the directory its message was written in.** A Host projection would list each `workspace-root/change` with its sequence number, and the Client would select the directory by message sequence. It repairs existing conversations and leaves model-visible text unchanged. It adds a projection and a lookup in every reference consumer, and it cannot repair a target the model wrote against the wrong base: in recorded runs with the earlier guidance, a model working in a worktree wrote 7 of 66 link targets relative to the original project. Folding only the loaded events instead of adding a projection misses moves that precede the loaded page of a long conversation. An implementation of this route, a `workingDirectoryHistory` projection with a Markdown path resolver, was merged in #8268 and reverted in #8438. + +**Rewrite relative targets to absolute when the reply is stored.** The stored reply would differ from the text the model produced, and later requests would replay the altered text. None of the eight surveyed agent products rewrites assistant prose; three of them ask for absolute targets in their prompts instead. + +**Keep relative tab addresses and convert them when the directory moves.** Every Client that holds the Session would rewrite its stored tabs on each move, including a Client that is closed when the move happens. + +**Leave picked `@file` mentions relative.** The model reads the mention under the directory of that request, so the request itself is correct. The sent message names another file after a move, and its chip becomes plain text after a reload when the file exists only in the earlier directory. + +## Consequences + +Recorded runs with the absolute-target guidance produced 128 link and image targets in eight Sessions on two DeepSeek models, including project paths with spaces and non-ASCII characters; all were absolute and 127 named an existing file. Link targets averaged 76 characters instead of 19 in a project whose path has 51 characters; output tokens per Session showed no measurable rise. + +A picked or dropped reference carries its absolute path wherever its serialized text appears: the fallback Session title and the turn-navigation preview show the path when a message starts with a reference. The chip label still shows the file name. + +References written before this decision keep their relative text and follow the Session's current directory, and so does a hand-typed `@relative/path`. The `@` list omits `out`, `dist`, `build`, and similar directories, so a file there is reachable only by typing. A tab stored with a relative address keeps following the Session's directory, and opening the same file again adds a second tab under the absolute address. + +Compliance with the guidance was measured on DeepSeek models only. A model that still writes a relative target gets the current-directory rule above. diff --git a/.agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.zh.md b/.agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.zh.md new file mode 100644 index 0000000000..dea041fd4b --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-19-conversation-file-references-after-directory-moves.zh.md @@ -0,0 +1,42 @@ +# Agent Note:目录移动后的对话文件引用 + +Status: implemented + +[English](2026-11-19-conversation-file-references-after-directory-moves.md) | 中文 + +## 问题 + +Session 的目录在其生命周期内会移动:`enter_worktree`、`exit_worktree` 与 Host 操作各自记录一条 `workspace-root/change`([Session 工作目录](../architecture/2026-09-13-session-working-directory.zh.md))。工具行、产出文件提及、交付文件与变更文件卡片保存了产生它们的操作的绝对路径,因此始终指向原来的文件。只保存相对文本的引用则不然: + +- 较早回复里的相对 Markdown 链接,以及较早消息里选中的 `@文件`,按点击时的目录解析。目录移动后,它们打开另一个检出里的同名路径,或报告文件不存在。 +- 相对路径的内联图片按头部目录解析,因此在工作树里写下的图片即使没有之后的移动也无法加载。 +- 已打开的侧边栏 tab 为 Session 目录内的文件保存相对地址。目录移动并刷新页面后,它显示另一个文件,或什么都不显示。 + +## 决策 + +**每个引用从写下时起就携带绝对路径。**读取方不再推断引用写下时所在的目录。 + +- `ui:deliverable-file-references` 指引要求模型为 Markdown 链接与图片的目标使用绝对路径。 +- `fileAddressFor` 把绝对路径写进 `dsh-resource://file/session/…` 地址:绝对路径原样保留,相对路径与调用方已知的目录拼接。已打开的 tab 在其存续期间只指向一个文件。 +- 从 `@` 列表选中的文件或文件夹写成绝对路径的 mention。Desktop 中拖入或粘贴的文件保留 shell 报告的绝对路径。 +- 仍然到达 Client 的相对路径按 Session 的当前目录解析:模型未遵循指引写下的、在 `@` 之后手打的,或在本决策之前写下的。链接、图片与右键菜单动作共用这一基准目录。 + +## 考虑过的替代方案 + +**按消息写下时的目录解析每个相对引用。**由 Host 投影列出每条 `workspace-root/change` 及其序号,Client 按消息序号选择目录。它能修复已有对话,也不改变模型可见文本。但它新增一个投影,并要求每个引用使用方都做一次查找,而且无法修复模型按错误基准写下的目标:在使用旧指引的实测中,一个在工作树里工作的模型把 66 个链接目标中的 7 个写成了相对原项目的路径。若不加投影而只折叠已加载的事件,长对话中早于已加载页的移动会被漏掉。这条路线的一个实现(`workingDirectoryHistory` 投影加 Markdown 路径解析函数)曾在 #8268 合入,并在 #8438 回滚。 + +**在保存回复时把相对目标改写为绝对路径。**保存的回复将不同于模型产生的文本,之后的请求会重放改写后的文本。调研的八个 agent 产品都不改写助手正文;其中三个改为在提示词里要求绝对目标。 + +**保留相对的 tab 地址,在目录移动时转换。**每个持有该 Session 的 Client 都要在每次移动时改写自己保存的 tab,包括移动发生时已关闭的 Client。 + +**让选中的 `@文件` mention 保持相对。**模型按该次请求的目录读取 mention,所以请求本身是正确的。但目录移动后,已发送的消息指向另一个文件;文件只存在于先前目录时,刷新后它的 chip 会变成纯文本。 + +## 影响 + +使用绝对目标指引的实测在两个 DeepSeek 模型的八个 Session 中产生了 128 个链接与图片目标,其中包含带空格与非 ASCII 字符的项目路径;全部为绝对路径,127 个指向存在的文件。在路径长 51 个字符的项目里,链接目标平均为 76 个字符,此前为 19 个;每个 Session 的输出 token 没有可测量的上升。 + +选中或拖入的引用在其序列化文本出现的地方都携带绝对路径:消息以引用开头时,兜底的 Session 标题与轮次导航预览会显示该路径。chip 的标签仍显示文件名。 + +本决策之前写下的引用保留相对文本并跟随 Session 的当前目录,手打的 `@相对/路径` 也是如此。`@` 列表不列出 `out`、`dist`、`build` 等目录,因此其中的文件只能手打引用。以相对地址保存的 tab 继续跟随 Session 的目录,再次打开同一个文件会在绝对地址下新增一个 tab。 + +对指引的遵循程度只在 DeepSeek 模型上测量过。仍然写出相对目标的模型适用上面的当前目录规则。 diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml index 2ef5bf0f10..ab6a3d96bb 100644 --- a/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.i18n.yaml @@ -21,8 +21,8 @@ en: 08e720a4ea75d4d6 zh: 5e2e5b8452f67d36 /agent-note-session-panel-in-the-chat-view-s-end-gutter/alternatives-considered: - en: 6adaf7a36da05668 - zh: c0ace7297995d764 + en: 127de82059f075ff + zh: f605915a6d9964fa /agent-note-session-panel-in-the-chat-view-s-end-gutter/consequences: - en: 0b6e547a08c042bc - zh: 154a69e3f54692cd + en: f68c02110b2d2382 + zh: deb1d49b77387bde diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.md index 7ef1e8f306..6d1bb286f5 100644 --- a/.agents/notes/implemented/feature/2026-11-05-session-panel.md +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.md @@ -39,12 +39,12 @@ The turn rail sits at the scrollport's start edge with its marks, focus ring, an - **The dock kit's floating window.** `FloatLayer` windows are draggable, resizable, and positioned in viewport coordinates; a summary anchored to the transcript gutter needs none of that and would have to fight the window's own placement rules. - **Viewport-width breakpoints.** The transcript width is adaptive and draggable and the right sidebar takes a variable track, so a viewport breakpoint either covers the transcript or hides the panel with room to spare. - **CSS-only hiding with a click-time read.** A container query on the gutter can hide the docked panel, and the toggle could read the computed result when pressed, as the background-job trigger does. The toggle would still render without knowing whether the panel shows, so `aria-expanded` and its tooltip would be wrong whenever the preference says dock but the gutter is too narrow. -- **Squeezing the transcript to make room.** Docking on laptop widths by moving the transcript column aside changes the centered column, the composer, and both width handles; it remains a separate layout decision. +- **Narrowing the transcript to make room.** Docking in narrower frames by narrowing the transcript column changes the reading width without the reader asking. The column moves into its start gutter for the panel and keeps its width ([decision](2026-11-16-session-panel-makes-room.md)). - **A Session-scoped standard hook for the gutter.** Adding a hook to every Session-scoped Slot would make every component fixture in the client restate it; the docking decision has two readers, the panel and the toggle, and both read it from the plugin's own state. ## Consequences -- With the default transcript width, which stops at 880px, the body must be 1576px wide to dock, so laptop widths use the overlay; the panel never covers the transcript unless the user opens it. +- With the default transcript width, which stops at 880px, the body must be 1576px wide to dock in the gutter alone; narrower bodies dock by [moving the transcript aside](2026-11-16-session-panel-makes-room.md), and those too narrow for that use the overlay; the panel never covers the transcript unless the user opens it. - Sections from independent plugins share one surface, ordering, and title style without depending on each other, and an occupied section id can be replaced by a higher-priority registration. - `ui-chat` gained one slot and one custom property on its layer and observes nothing for them. Each mounted panel adds one `ResizeObserver` on its dock probe, which calls back only when the docking decision flips. `ui-conversation` caps the default transcript width at 880px. - The panel shows only in Chat Views; elsewhere the toggle stays in the header, unavailable. Every Chat View occurrence renders the aside, so a Session shown in the main body and in an embedded Conversation at once shows its overlay in both. diff --git a/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md index 5a2a4bada2..95c3fa1d01 100644 --- a/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md +++ b/.agents/notes/implemented/feature/2026-11-05-session-panel.zh.md @@ -39,12 +39,12 @@ Status: implemented - **dock kit 的悬浮窗。** `FloatLayer` 窗口可拖拽、可缩放、按视口坐标定位;锚定在正文留白的摘要用不上这些能力,还要对抗窗口自身的定位规则。 - **按视口宽度断点。** 正文宽度自适应、可拖拽,右侧栏占用可变宽度,视口断点要么遮挡正文,要么在空间充足时也隐藏面板。 - **纯 CSS 隐藏加点击时读取。** 对留白做容器查询可以隐藏停靠面板,开关在按下时读取计算结果,与后台任务按钮的做法相同。但开关渲染时仍不知道面板是否显示,偏好为停靠而留白不足时,`aria-expanded` 与提示文字都会出错。 -- **挤压正文腾出空间。** 在笔记本宽度下把正文列移开来停靠,会改变居中的正文列、composer 和两侧宽度拖拽条;这仍是另一项布局决策。 +- **让正文变窄来腾出空间。** 在更窄的外框里通过收窄正文列来停靠,会在用户没有要求的情况下改变阅读宽度。正文列为面板移入起始留白,宽度不变([决策](2026-11-16-session-panel-makes-room.zh.md))。 - **会话作用域标准 hook。** 给每个会话作用域 Slot 增加一个留白 hook,会让客户端所有组件测试夹具都要补上它;停靠判断只有两个读取方,即面板和开关,两者都从插件自己的状态读取。 ## Consequences -- 默认正文宽度最多 880px,此时对话区要 1576px 宽才能停靠,因此笔记本宽度使用浮层;除非用户主动打开,面板不会遮挡正文。 +- 默认正文宽度最多 880px,此时对话区要 1576px 宽才能只靠留白停靠;更窄的对话区通过[让正文移开](2026-11-16-session-panel-makes-room.zh.md)来停靠,窄到无法移开时使用浮层;除非用户主动打开,面板不会遮挡正文。 - 独立插件的分栏共享同一界面、排序和标题样式,彼此不依赖;已占用的分栏 id 可以被更高优先级的注册替换。 - `ui-chat` 多了一个 slot,侧边层多了一个自定义属性,但不为它们观察任何尺寸。每个已挂载的面板在停靠探针上多一个 `ResizeObserver`,只在停靠判断翻转时回调。`ui-conversation` 把默认正文宽度上限定为 880px。 - 面板只出现在 Chat 视图中;其他视图下开关仍在标题栏中,但不可用。每个 Chat 视图实例都会渲染侧边层,因此同一会话同时显示在主正文区和嵌入的对话中时,两处都会显示浮层。 diff --git a/.agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.i18n.yaml b/.agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.i18n.yaml new file mode 100644 index 0000000000..3be7778956 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.i18n.yaml @@ -0,0 +1,34 @@ +# Bilingual-pair consistency record for 2026-11-16-session-panel-makes-room.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.md +/agent-note-the-transcript-moves-aside-for-the-docked-session-panel: + en: e70c9ec483c744d7 + zh: 022406f7ffae63a1 +/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/problem: + en: 5cab4a0fb9ad60c2 + zh: 074a63beaad1aa55 +/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/decision: + en: 2120aa7bf642ec99 + zh: af7493fa21357df0 +/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/decision/the-body-owns-the-room-and-the-panel-asks-for-it: + en: 133c15546f787723 + zh: 8e8cb9260af14207 +/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/decision/one-probe-whose-answer-does-not-depend-on-the-room-made: + en: 8dc78b8b67322164 + zh: c0f785ab10d9cbf0 +/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/decision/width-handles-beside-the-docked-panel: + en: f474cd213b7d7d90 + zh: c2a67709e43af311 +/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/decision/one-motion-for-the-panel-and-the-transcript: + en: 084f01ca61d03d34 + zh: 6e1dbac9332ecfa4 +/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/alternatives-considered: + en: a3b6a8462b2440e2 + zh: e10fb5a9faf20ec8 +/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/consequences: + en: a9dfb9dc68ab2123 + zh: e94de2ee21482fd3 +/agent-note-the-transcript-moves-aside-for-the-docked-session-panel/testing: + en: ac6c37d6e85c30ba + zh: 4d978cc079f323cc diff --git a/.agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.md b/.agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.md new file mode 100644 index 0000000000..676c2addf4 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.md @@ -0,0 +1,57 @@ +# Agent Note: The transcript moves aside for the docked Session panel + +Status: implemented + +English | [中文](2026-11-16-session-panel-makes-room.zh.md) + +## Problem + +The [Session panel](2026-11-05-session-panel.md) docked only in a 348px end gutter. With the default transcript width that takes a Chat frame 1576px wide, and the left sidebar takes 280px of the window, so no window under about 1860px docks the panel in the gutter alone. On 1440px, 1512px, and 1728px windows it showed only as the overlay, which closes on the next press outside it. A reader who wants running subagents, background jobs, or change requests in view while working could not keep the panel open at those widths. + +## Decision + +While the docking preference is on and the end gutter is narrower than 348px, the Conversation body keeps that gutter free: the transcript column and the composer move toward the start edge by the missing gutter, at their own widths, and the panel docks in it. The body makes no room when that would leave less than the column's 32px side inset before it; the panel then hides, and the toggle opens it as the overlay. The column never narrows for the panel. The header toggle turns the docking preference off, which hides the panel and centers the transcript again. Nothing else opts in: the panel docks wherever it has room. + +### The body owns the room, and the panel asks for it + +[`ui-conversation`](../../../../packages/client/ui-conversation/README.md#end-reserve) owns the transcript's width axis, the scrollport, and the width handles, so it owns the room. A stylesheet asks for it by setting `--dsh-chat-end-reserve` on the Conversation body; the body derives `--dsh-chat-end-inset`, the scrollport's end padding, and `--dsh-chat-end-reserve-max`, the largest reserve the start gutter can give. The panel's stylesheet sets the reserve to 348px through a `:has()` rule that matches while its dock probe carries a mark, so the request needs no Slot prop and no render in the Chat View. + +The body derives those lengths from the scrollport's width, which it measures and publishes as `--dsh-conversation-viewport-width`. Three boxes read the inset: the scrollport for its padding, the width handles in the body, and the [`ui-chat`](../../../../packages/client/ui-chat/README.md#scroll-ownership) aside layer, which reaches back across the inset so the panel sits at the scrollport's end edge. A length written with percentages resolves against a different box in each of them, and the scrollport's own content box changes with the inset. A measured pixel width gives all three the same value and does not change when the inset does. + +### One probe whose answer does not depend on the room made + +The panel's dock probe is 1px wide while the gutter holds the panel, or while the body's largest reserve covers that gutter. The second term reads the scrollport's width and the content width, not the inset, so the answer is the same before and after the transcript moves: the room the transcript makes cannot change the decision that asked for it, and the layout cannot oscillate. The plugin's state, its toggle, and its overlay rules are those of the gutter-only panel; only what its stylesheet counts as room widened. + +### Width handles beside the docked panel + +The handles follow the column: their positions take half the inset, and each takes its width from the gutter on its own side. While the body makes room, the reserve holds the column's end edge, so a drag moves only the start edge, and the width changes by the pointer's travel instead of twice it, on either handle. A column dragged wider than the start gutter can give takes its room back: the panel hides and the column centers, as a column dragged wide already hid the panel docked in the gutter. + +### One motion for the panel and the transcript + +A press that shows or hides the panel plays its entrance or exit, and the transcript moves over the same 160ms and curve: the panel's stylesheet sets `--dsh-chat-end-reserve-transition` on the Conversation body while the animation runs, and the scrollport's padding and the aside layer's margin both take their transition from it. The panel tells a press from a change of room by comparing renders: what it shows changed while its room stayed the same. A change of room shows or hides the panel at once, which covers a mount, a switch to another Session, a resized window, and a dragged transcript width. + +## Alternatives considered + +- **A pin that opts in to making room.** The panel would dock at laptop widths only after the reader found and pressed a pin on it. In a wide window the pin changes nothing visible, and until it is pressed the default at laptop widths stays an overlay that closes on the next press. The panel docks wherever it can instead, and the toggle is the one control that hides it. +- **Narrowing the column for the panel.** A floor such as 480px docks the panel in narrower frames, but it changes the reading width without the reader asking and makes the column's width depend on the panel as well as on the width the reader dragged. The column keeps its width, and a frame that cannot give the room shows the overlay. +- **The docked panel covers the transcript.** It needs no layout change, but on a 1440px window the panel covers about 83px of the transcript column, and the actions at the end of each message, for as long as it shows. +- **A measured reserve passed through Slot props.** The Conversation body, the Chat View, and the aside would each forward a callback for one consumer, and every change of the reserve would render the Chat View. A custom property needs neither. +- **Percentages without a published width.** The inset would differ between the scrollport, the width handles, and the aside layer, and the largest reserve would read a width that the inset itself narrows. +- **A second probe and a room type in the plugin's state.** The plugin would track the gutter and the reserve apart. Nothing reads them apart, so one probe reports their union and the plugin's interfaces stay as they were. +- **No width handles while the transcript makes room.** The handles' positions stay simple, but the panel docks by default at laptop widths, so the reader would lose the width drag there. +- **A transition that is always on.** The inset follows the window and the dragged width every frame, so a standing transition makes the transcript trail the pointer during a resize or a width drag, and it would animate across a Session switch. The transition is on only while a press shows or hides the panel. +- **Animating when the window crosses the width that makes room.** The inset steps there inside the stylesheet, one frame before the panel learns of it, so the transcript would jump while the panel animated. Both change at once instead. +- **Making room in embedded Chat Views.** An embedded transcript's width is a percentage of its frame, so the inset would need that frame's own measure, and embedded frames are rarely wide enough. An embedded Chat View makes no room. + +## Consequences + +- The panel stays beside the transcript at laptop widths without a press. On a 1440px window with the sidebar open, the 742px column keeps its width and sits 143px toward the start edge while the panel is docked. +- A reader who wants the transcript centered hides the panel from the toggle. +- With the default transcript width the panel docks from a Chat frame about 1068px wide; below that, and beside a transcript dragged wide, it is the overlay it was. +- A width drag beside the docked panel moves one edge of the column, not both. +- The transcript's motion re-lays it out on each of about ten frames. Beside the longest recorded Session, 790 elements, no frame took longer than 9.3ms; a much longer transcript has not been measured. +- `ui-conversation` publishes the scrollport's width and two derived lengths, pads its scrollport's end, and moves its width handles; `ui-chat`'s aside layer has an end margin and a gutter that counts the inset. Neither renders or observes anything more for them. + +## Testing + +Unit specs read the three stylesheets and evaluate the reserve, the inset, the gutter, the probe, and the handles around their boundaries, and drive a width drag at both scales. `apps/web/tests/session-panel-layout.e2e.ts` measures the shipped Web composition: the column, the composer, the width handles, the probe, and the panel across the gutter that holds the panel, the frames that make room, the last frame that can and the first that cannot, a reload, the toggle, and width drags that keep, lose, and regain the room. diff --git a/.agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.zh.md b/.agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.zh.md new file mode 100644 index 0000000000..92cb849ae3 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-16-session-panel-makes-room.zh.md @@ -0,0 +1,57 @@ +# Agent Note: 正文为停靠的会话面板移开 + +Status: implemented + +[English](2026-11-16-session-panel-makes-room.md) | 中文 + +## Problem + +[会话面板](2026-11-05-session-panel.zh.md)原先只在 348px 的末端留白里停靠。默认正文宽度下,这要求 Chat 外框宽 1576px,而左侧栏占去窗口 280px,因此约 1860px 以下的窗口都无法只靠留白停靠面板。在 1440px、1512px 和 1728px 的窗口里,面板只能以浮层显示,在面板外按下指针就会关闭。想在工作时一直看到运行中的子智能体、后台任务或变更请求的用户,在这些宽度下无法让面板保持打开。 + +## Decision + +停靠偏好开启、且末端留白窄于 348px 时,Conversation 主体空出这段留白:正文列和输入框保持各自宽度,向起始边缘移动所缺的留白,面板停靠在其中。如果移动后正文列之前剩不下它的 32px 侧边内边距,主体不让位;此时面板隐藏,按开关以浮层打开。正文列不会为面板变窄。标题栏开关关闭停靠偏好,面板随之隐藏,正文恢复居中。除此之外没有别的开关:面板在有位置的地方都会停靠。 + +### 位置归主体所有,面板提出申请 + +[`ui-conversation`](../../../../packages/client/ui-conversation/README.zh.md#end-reserve) 拥有正文的宽度轴、滚动容器和宽度手柄,因此这段位置也归它所有。样式表在 Conversation 主体上设置 `--dsh-chat-end-reserve` 来提出申请;主体据此推出滚动容器的末端内边距 `--dsh-chat-end-inset`,以及起始留白能让出的最大预留 `--dsh-chat-end-reserve-max`。面板的样式表通过一条 `:has()` 规则把预留设为 348px,该规则在停靠探针带有标记时匹配,因此申请不需要 Slot 属性,也不会让 Chat 视图重新渲染。 + +主体从滚动容器的宽度推出这些长度;它测量该宽度并发布为 `--dsh-conversation-viewport-width`。有三个盒子读取内边距:滚动容器用它作内边距,主体中的宽度手柄用它定位,[`ui-chat`](../../../../packages/client/ui-chat/README.zh.md#scroll-ownership) 的侧边层用它越过内边距延伸回去,让面板位于滚动容器的末端边缘。用百分比写出的长度在这三处会按不同的盒子解析,而滚动容器自身的内容盒又随内边距变化。测量得到的像素宽度让三处取得同一个值,并且不随内边距改变。 + +### 一个探针,结果不受让出的位置影响 + +留白放得下面板,或者主体的最大预留覆盖这段留白时,面板的停靠探针宽 1px。第二项读取的是滚动容器的宽度和正文宽度,而不是内边距,因此正文移动前后结果相同:正文让出的位置不会改变提出让位的那项判断,布局也不会来回振荡。插件的状态、开关和浮层规则与只靠留白停靠时相同,只是样式表认定的「有位置」范围变大了。 + +### 停靠面板旁的宽度手柄 + +手柄跟随正文列:它们的位置计入内边距的一半,各自的宽度取自所在一侧的留白。主体让位期间,预留固定了正文列的末端边缘,因此拖动只移动起始边缘,无论拖哪个手柄,宽度的变化都等于指针移动的距离而不是它的两倍。正文列被拖到超过起始留白能让出的宽度时会收回位置:面板隐藏,正文列居中;这与原先把正文拖宽会隐藏停靠在留白里的面板一致。 + +### 面板和正文做同一个动作 + +用户的一次按下让面板显示或隐藏时,面板播放进入或退出动画,正文在同样的 160ms 内按同一条曲线移动:动画期间,面板的样式表在 Conversation 主体上设置 `--dsh-chat-end-reserve-transition`,滚动容器的内边距和侧边层的外边距都从它取得过渡。面板通过比较两次渲染来区分按下和空间变化:显示与否变了,而停靠空间没变。空间变化时面板立即显示或隐藏,这涵盖了挂载、切换到另一个会话、缩放窗口和拖动正文宽度。 + +## Alternatives considered + +- **用图钉选择是否让位。** 用户要先找到并按下面板上的图钉,面板才会在笔记本宽度下停靠。在宽窗口里图钉没有任何可见效果;按下之前,笔记本宽度下的默认状态仍是点一下就关闭的浮层。现在面板在有位置的地方都会停靠,隐藏它只用开关这一个控件。 +- **为面板收窄正文列。** 设一个下限(例如 480px)可以让面板在更窄的外框里停靠,但会在用户没有要求的情况下改变阅读宽度,并且让正文列的宽度既取决于用户拖出的宽度,又取决于面板。正文列保持宽度,给不出位置的外框使用浮层。 +- **停靠的面板盖在正文上。** 不需要改动布局,但在 1440px 的窗口里,只要面板显示,就会一直遮住正文列约 83px 以及每条消息末尾的操作按钮。 +- **通过 Slot 属性传递测量出的预留值。** Conversation 主体、Chat 视图和侧边层都要为这一个使用方转发回调,预留值每次变化还会让 Chat 视图重新渲染。自定义属性两者都不需要。 +- **只用百分比,不发布宽度。** 内边距在滚动容器、宽度手柄和侧边层中会取得不同的值,而最大预留读到的宽度又会被内边距本身收窄。 +- **第二个探针,并在插件状态里区分两种位置。** 插件要分别记录留白和预留。没有任何地方需要区分它们,因此用一个探针报告两者的并集,插件的接口保持不变。 +- **正文让位期间不提供宽度手柄。** 手柄的定位更简单,但面板在笔记本宽度下默认停靠,用户在这些宽度下就无法拖动宽度。 +- **始终开启过渡。** 内边距每一帧都跟随窗口宽度和拖出的正文宽度,常开的过渡会让正文在缩放窗口或拖动宽度时落后于指针,切换会话时也会带上动画。过渡只在一次按下让面板显示或隐藏的期间开启。 +- **窗口越过能让位的宽度时播放动画。** 内边距在样式表里于这个宽度上阶跃,比面板得知这件事早一帧,因此正文会先跳、面板再做动画。现在两者都立即变化。 +- **在嵌入的 Chat 视图中让位。** 嵌入的正文宽度是其外框的百分比,内边距需要该外框自己的测量值,而嵌入的外框很少够宽。嵌入的 Chat 视图不让位。 + +## Consequences + +- 面板在笔记本宽度下无需任何操作就留在正文旁。在侧栏展开的 1440px 窗口里,面板停靠时 742px 的正文列宽度不变,向起始边缘偏移 143px。 +- 希望正文居中的用户用开关隐藏面板。 +- 默认正文宽度下,Chat 外框约 1068px 宽起面板停靠;更窄时,或者正文被拖得很宽时,面板仍是原来的浮层。 +- 在停靠面板旁拖动宽度时,正文列只移动一侧边缘,而不是两侧。 +- 正文的移动在大约十帧里每帧都重新排版。在已录制的最长会话(790 个元素)旁,没有一帧超过 9.3ms;更长的对话没有测量过。 +- `ui-conversation` 发布滚动容器的宽度和两个推出的长度,给滚动容器的末端加内边距,并移动它的宽度手柄;`ui-chat` 的侧边层多了末端外边距,其留白包含内边距。两者都没有为此增加渲染或观察。 + +## Testing + +单元测试读取三份样式表,并在边界附近计算预留、内边距、留白、探针和手柄的取值,还以两种比例驱动一次宽度拖动。`apps/web/tests/session-panel-layout.e2e.ts` 在随产品发布的 Web 组合中测量正文列、输入框、宽度手柄、探针和面板,覆盖放得下面板的留白、需要让位的外框、最后一个能让位和第一个不能让位的外框、刷新页面、开关,以及保持、失去和重新获得位置的宽度拖动。 diff --git a/.agents/skills/dsh-code-review/SKILL.md b/.agents/skills/dsh-code-review/SKILL.md index 406375ff61..14d584c08e 100644 --- a/.agents/skills/dsh-code-review/SKILL.md +++ b/.agents/skills/dsh-code-review/SKILL.md @@ -12,6 +12,7 @@ description: Use when reviewing a pull request in the deepseek-harness repo — ## Sources of truth - [AGENTS.md](../../../AGENTS.md) and [packages/AGENTS.md](../../../packages/AGENTS.md): standing repository and package authoring rules. +- [DSH Core Guidelines](../../../docs/core-guidelines/README.md): numbered design rules every change follows; cite a violated rule by its ID. - [docs/defensive-patterns/](../../../docs/defensive-patterns/README.md): the architecture requirements a change must satisfy and the habits behind them. Each page owns one artifact; read every page the diff touches: - [general.md](../../../docs/defensive-patterns/general.md) — timing, async state, value representation, shared ownership, decentralization, refactors, migrations, performance evidence, disposal, callbacks, subprocesses. - [package-surface.md](../../../docs/defensive-patterns/package-surface.md) — exports, package shape, build faces, dependency declarations, resolve hooks. @@ -44,6 +45,7 @@ description: Use when reviewing a pull request in the deepseek-harness repo — - **Error handling:** apply [dsh-error-handling](../dsh-error-handling/SKILL.md) to changed failure paths, including their state guarantees and final user-visible reports. Flag an expected tool failure that would reach `tool/result` without `error.name`/`error.code`. Reject catch-and-continue unless the state owner establishes that subsequent work's preconditions hold, including after recovery. - **Lifecycle and concurrency:** for async setup, callbacks, processes, or teardown, apply [defensive-patterns/general.md](../../../docs/defensive-patterns/general.md). Check races before publication, cancellation during awaits, independent error reporting, callback containment, ownership before reentry, complete detach cleanup, and quiescent disposal. - **Scope, ownership, and necessity:** first identify the required behavior behind each new distinction, field, adapter, state machine, option, defensive copy, and compatibility path. A requirement, check, or Agent Note introduced by the PR is a design choice to assess, not independent evidence of necessity. Compare existing source fields, discriminants, and their consumers before accepting another representation; distinguish deleting a concept from relocating its declaration. Moving an unnecessary concept closer to its owner is not a simplification. Challenge unrelated features and speculative generality against [the root rules](../../../AGENTS.md#conventions). +- **Module responsibilities and dependencies:** compare the [responsibility table and dependency edges](../dsh-pr-description/SKILL.md#module-responsibilities-and-dependencies) in the PR description with the manifests and imports in the diff; a missing, wrong, or undeclared edge is a finding. Then judge what the description states: each package has one responsibility, that responsibility requires each added edge, and no shared package gains a dependency on one of its consumers. - **Capability and consumer fit:** trace every current consumer, then flag consumer-specific behavior leaking into the interface under [the package rules](../../../packages/AGENTS.md). For required behavior, prefer an existing extension point near its producer or consumer when the local implementation adds little complexity, following [the ownership rule](../../../docs/defensive-patterns/general.md#a-business-capability-owns-itself); compare producer-owned declaration merging with changes to distant core or shared type declarations. Flag the inverse too: a new public method on a generic service (registry, session, agent) whose only caller is one internal consumer is an unnecessary API expansion — require a private capability closure handed to that consumer at construction instead. - **Configuration and public choices:** trace authoritative reads and precedence before accepting another CLI or configuration pass-through; a forwarded value may be shadowed before use. Ask what current-consumer evidence or prior art supports each default, public operation set, format, or imported external concept. Require an explicit choice or deferral when that evidence is absent. - **Model perspective:** inspect the exact prompts, tool schemas, results, and diagnostics the model receives across affected modes. Flag concepts outside the model's task, then verify stable text verbatim and dynamic behavior through snapshots or end-to-end coverage. diff --git a/.agents/skills/dsh-pr-description/SKILL.md b/.agents/skills/dsh-pr-description/SKILL.md index 5841e73f94..d36b7fc357 100644 --- a/.agents/skills/dsh-pr-description/SKILL.md +++ b/.agents/skills/dsh-pr-description/SKILL.md @@ -1,6 +1,6 @@ --- name: dsh-pr-description -description: Use when creating a deepseek-harness pull request, or when updating its description after later changes or a handled review round. Defines each description section, Issue references, test design, change-specific disclosures, and the AI Usage section with its levels, stages, grading rules, AI-DECLARATION badge, and update timing. +description: Use when creating a deepseek-harness pull request, or when updating its description after later changes or a handled review round. Defines each description section, Issue references, module responsibilities and dependency edges, test design, change-specific disclosures, and the AI Usage section with its levels, stages, grading rules, AI-DECLARATION badge, and update timing. user-invocable: false --- @@ -18,7 +18,7 @@ This skill defines what a deepseek-harness PR description contains, how to write The description uses four second-level headings, in this order: `## Motivation`, `## Changes`, `## Testing`, and `## AI Usage`. -Write fixed section headings and labels, such as **Interface changes**, **Behavior changes**, **Test design**, and **Test entries**, in English. Write table headers and the rest of the description in the PR description's language, Chinese unless a human asked for another language. +Write fixed section headings and labels, such as **Interface changes**, **Behavior changes**, **Module responsibilities and dependencies**, **Test design**, and **Test entries**, in English. Write table headers and the rest of the description in the PR description's language, Chinese unless a human asked for another language. ### Motivation @@ -29,8 +29,54 @@ Write fixed section headings and labels, such as **Interface changes**, **Behavi - Interface changes: summarize changes to commands (including repository scripts), flags, configuration keys, environment variables, public exports, plugin registration values, protocols, or persisted formats; write None when there are none. - Behavior changes: summarize results that users, models, developers, or the system can observe, including defaults, performance, timing, and output; write None when there are none. Changes to documentation and agent instructions, such as READMEs, AGENTS.md, and skills, are behavior changes for the readers they guide. +- Module responsibilities and dependencies: state the responsibility of each package that the structural change involves, and every runtime dependency between workspace packages that the PR adds or removes, in the form that [Module responsibilities and dependencies](#module-responsibilities-and-dependencies) defines; write None when the PR adds or removes no package, adds or removes no runtime dependency between workspace packages, and moves no responsibility between packages. - State only behavior that the diff guarantees and the tests cover. +#### Module responsibilities and dependencies + +A reviewer uses this item, before reading the diff, to judge whether each package has one responsibility and whether each added dependency is necessary. A workspace package is a member that `pnpm-workspace.yaml` lists; name it by the `name` in its manifest without the `@deepseek-ai/` scope, which can differ from its directory name. When the item is not None, it has three parts, in this order: + +1. **Responsibility table**: one row for each package that the PR adds or removes, that is the source of an added or removed dependency edge, or that gains or loses a responsibility. The columns are the package, its responsibility in one sentence, and what this PR does to it: added, removed, changed and how, or unchanged and depended on. Packages that have the same role and receive the same change may share a row. A package that the PR does not change and that is only the target of an added edge gets a row when its responsibility explains why the edge is needed; a general utility package, such as `dsh-error`, may be left out. A package whose only change is a composition edge gets no row. +2. **Dependency edges**: a list of every runtime dependency between workspace packages that the PR adds or removes, each written `A → B` for "A depends on B" and marked as added or removed. Take the edges from the diff, never from memory: in `git diff ...HEAD -- '*package.json'`, compare the `dependencies`, `peerDependencies`, and `optionalDependencies` of each workspace package's manifest. Leave out `devDependencies`, the `package.json` files of test fixtures and templates, and dependencies on the vendored packages under `vendor/`. Mark an optional peer dependency or an `optionalDependencies` entry as optional. One list item may hold edges that share a source or a target, but every edge appears. List the edges of a bundle, app, or deploy root that only mounts a plugin or adds a package to its closure in a separate composition item, because they are not runtime calls. End the list with a reverse-edge item: for each added edge `A → B`, check that the runtime dependencies of B do not name A, then state that no added edge has a reverse edge, or list each one that has. +3. **Call flow**: three to six lines of pseudo-code, in a code fence, that show the main call path across the packages. Write it only when the PR adds or changes a call between packages. + +When the edges involve four or more packages, a Mermaid `graph` may follow the list; it never replaces the list. + +Filled in from the manifests, READMEs, and call sites of #8521: + +````markdown +**Module responsibilities and dependencies** + +| 包 | 职责 | 本 PR 的变化 | +|---|---|---| +| `dsh-deepseek-auth` | `ctx.deepseekAuth`:在 API 密钥与账号登录之间选择,把凭据绑定到所属部署,给出请求头 | 新增 | +| `dsh-llm-deepseek-api-key`、`dsh-llm-deepseek-account` | 注册各自的 DeepSeek 模型路由 | 用 `connect()` 登记自己的部署,用 `authorize()` 取请求头 | +| `dsh-web-deepseek-api`、`dsh-web-search-deepseek` | Search / Fetch API 与 Messages 搜索 | 改为向 `ctx.deepseekAuth` 取凭据,不再自己读账号服务和模型路由配置 | +| `dsh-sdk-jsonrpc-server` | SDK JSON-RPC 服务 | 组合里没有 `deepseekAuth` 时自己挂载它 | +| `dsh-credentials`、`dsh-deepseek-account` | 凭据存取、账号登录 | 不变,被 `dsh-deepseek-auth` 读取 | + +依赖边: + +- 新增 `dsh-deepseek-auth → dsh-credentials`、`dsh-error`、`dsh-launch-environment`、`dsh-deepseek-account`(可选) +- 新增 `dsh-llm-deepseek-api-key → dsh-deepseek-auth`、`dsh-llm-deepseek-account → dsh-deepseek-auth` +- 新增 `dsh-web-deepseek-api → dsh-deepseek-auth`、`dsh-web-search-deepseek → dsh-deepseek-auth` +- 新增 `dsh-sdk-jsonrpc-server → dsh-deepseek-auth` +- 删除 `dsh-web-deepseek-api → dsh-deepseek-account`(可选)、`dsh-web-deepseek-api → dsh-launch-environment` +- 删除 `dsh-web-search-deepseek → dsh-llm` +- 组合:`dsh-base`、`dsh-sdk-minimal`、`dsh-python-runtime-closure` 新增 `dsh-deepseek-auth` +- 反向边:无。`dsh-deepseek-auth` 的运行时依赖只有第一条中的四个包,不含任何新依赖它的包;这四个包都不依赖 `dsh-deepseek-auth` + +调用流程: + +```ts +const authorization = await ctx.deepseekAuth.authorize({ + consumer: 'my-plugin', accepts: ['account', 'api-key'], billing: 'auto', + route, destination: { path: '/v1/tools/search' }, +}, signal) +await fetch(authorization.endpoint, { headers: authorization.headers, signal }) // 请求仍由使用方自己发 +``` +```` + ### Testing Testing starts with the test design, followed by the test entries. @@ -201,4 +247,4 @@ Filled in from the session and review records of #6013: 1. Write the description to a file that git ignores, such as `.artifacts/pr/body.md`. Create the PR with `gh pr create --body-file `, or update it with `gh pr edit --body-file `; when the description embeds a GIF, follow [record-browser-gif](../record-browser-gif/SKILL.md) and use `--attach`. 2. Before an update, save the current description with `gh pr view --json body --jq .body`, and change only the sections that need it: keep content and media the author wrote, replace only the contents of an existing `ai-declaration` block, and remove statements that no longer match the code. When the description still has the old `## Human and Agent Roles` heading, replace that heading and its level line with `## AI Usage` and the block; keep only one AI Usage section. -3. After writing, read the description back and confirm that all four sections are present, that AI Usage matches the current code and review state, and that no old `## Human and Agent Roles` section remains. +3. After writing, read the description back and confirm that all four sections are present, that the dependency edges in Changes match the current diff, that AI Usage matches the current code and review state, and that no old `## Human and Agent Roles` section remains. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 3579e77136..91b183cd74 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -6,6 +6,8 @@ ## Changes + + ## Testing diff --git a/.github/workflows/ci-windows.yml b/.github/workflows/ci-windows.yml index c3ea5c58fc..1ef6862c46 100644 --- a/.github/workflows/ci-windows.yml +++ b/.github/workflows/ci-windows.yml @@ -116,12 +116,21 @@ jobs: - name: Parse Windows runner supervision scripts shell: pwsh run: | - foreach ($path in @('apps/desktop/scripts/windows-runner-task.ps1', 'apps/desktop/scripts/run-windows-runner-task.ps1', 'apps/desktop/scripts/start-windows-packaging-runner.ps1', 'apps/desktop/scripts/windows-runner-network.ps1', 'apps/desktop/scripts/run-windows-runner-network-process.ps1', 'apps/desktop/tests/windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-launcher.ps1', 'apps/desktop/tests/windows-runner-network.ps1', 'apps/desktop/tests/windows-runner-network-process.ps1')) { + foreach ($path in @('apps/desktop/scripts/windows-runner-task.ps1', 'apps/desktop/scripts/windows-runner-scheduler.ps1', 'apps/desktop/tests/windows-runner-boot.ps1', 'apps/desktop/tests/windows-runner-processes.ps1', 'apps/desktop/tests/windows-runner-recovery.ps1', 'apps/desktop/scripts/run-windows-runner-task.ps1', 'apps/desktop/scripts/start-windows-packaging-runner.ps1', 'apps/desktop/scripts/windows-runner-network.ps1', 'apps/desktop/scripts/run-windows-runner-network-process.ps1', 'apps/desktop/tests/windows-runner-task.ps1', 'apps/desktop/tests/windows-runner-launcher.ps1', 'apps/desktop/tests/windows-runner-network.ps1', 'apps/desktop/tests/windows-runner-network-process.ps1')) { $tokens = $null $parseErrors = $null $null = [Management.Automation.Language.Parser]::ParseFile((Join-Path $env:GITHUB_WORKSPACE $path), [ref]$tokens, [ref]$parseErrors) if ($parseErrors.Count) { throw ($parseErrors -join "`n") } } + - name: Verify Windows unattended runner definitions and recovery + shell: pwsh + run: | + ./apps/desktop/tests/windows-runner-boot.ps1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + ./apps/desktop/tests/windows-runner-recovery.ps1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + ./apps/desktop/tests/windows-runner-processes.ps1 + exit $LASTEXITCODE - name: Verify windowless Windows runner launcher shell: pwsh run: ./apps/desktop/tests/windows-runner-launcher.ps1 diff --git a/.github/workflows/windows-package.yml b/.github/workflows/windows-package.yml index 405ee6bd29..c54f013a59 100644 --- a/.github/workflows/windows-package.yml +++ b/.github/workflows/windows-package.yml @@ -105,10 +105,11 @@ jobs: ref: ${{ github.workflow_sha }} sparse-checkout: apps/desktop/scripts - name: Stage workflow helpers + id: helpers run: | $helpers = Join-Path $env:RUNNER_TEMP "packaging-helpers-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" New-Item -ItemType Directory -Path $helpers -ErrorAction Stop | Out-Null - foreach ($name in @('windows-packaging-priority.ps1')) { + foreach ($name in @('windows-packaging-priority.ps1', 'windows-packaging-summary.mjs')) { Copy-Item -LiteralPath (Join-Path 'apps/desktop/scripts' $name) -Destination $helpers -ErrorAction Stop } "PACKAGE_CI_HELPERS=$helpers" >> $env:GITHUB_ENV @@ -176,6 +177,14 @@ jobs: env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} run: node apps/desktop/scripts/prepare-windows-ci.mjs + - name: Summarize packaging parameters + if: always() && steps.helpers.outcome == 'success' + env: + PACKAGE_INPUT_VERSION_MODE: ${{ inputs.version_mode }} + PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} + PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} + PACKAGE_VERSION: ${{ steps.settings.outputs.version }} + run: node "$env:PACKAGE_CI_HELPERS/windows-packaging-summary.mjs" - name: Check packaging configuration and toolchain env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} diff --git a/AGENTS.md b/AGENTS.md index f4b150a8df..6a2ccfad64 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,9 +169,11 @@ Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and - TODO markers: `FIXME`/`TODO`/`XXX` by urgency ([semantics](docs/development.md)). - Files end with exactly one trailing newline; `git diff --cached --check` (pre-commit) gates it. -## Defensive patterns +## Review rules -Read [docs/defensive-patterns/README.md](docs/defensive-patterns/README.md) before changing a package surface, remote service, client component or state, conversation or Session behavior, or lifecycle, concurrency, subprocess, and teardown code. Its [review principles](docs/defensive-patterns/README.md#why-these-rules) apply per artifact. +Before finishing, self-review against [DSH Core Guidelines](docs/core-guidelines/README.md). + +Read [docs/defensive-patterns/README.md](docs/defensive-patterns/README.md) before changing a package surface, remote service, client component or state, conversation or Session behavior, or lifecycle, concurrency, subprocess, and teardown code. ## Type safety and documentation @@ -183,7 +185,7 @@ Docs accompany every code change: update affected README and JSDoc contracts tog ## Editing these instructions -`CLAUDE.md` symlinks `AGENTS.md` at root and `packages/`; edit the real file. Keep each rule self-contained while linking high-level docs. Condense when clarity survives; raise a `verify-doc-budgets` ceiling when the required content genuinely needs more space. +`CLAUDE.md` symlinks `AGENTS.md` at root and `packages/`; edit the real file. Keep each rule self-contained while linking high-level docs. Condense when clarity survives; raise a `verify-doc-budgets` ceiling when the required content needs more space. ## Vendoring policy diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index 741c64c21d..f60b605949 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/README.i18n.yaml @@ -15,8 +15,8 @@ en: 85171337ac2fb2ff zh: 705a4eef97d9b519 /deepseek-ai-dsh/optional-overlays: - en: 3a40ddc44e55f79c - zh: 8d3949132e1ef93c + en: bedb55bd3a80599c + zh: a381da5cd5db885b /deepseek-ai-dsh/installed-payload: en: c19f3d56f611f173 zh: 5002a7a318414960 diff --git a/apps/cli/README.md b/apps/cli/README.md index 4a5dd73e04..bf989c919a 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -51,7 +51,7 @@ The [CLI behavior reference](reference/README.md) owns exact layer precedence, f ## Optional overlays -`config/examples/` ships opt-in overlays for GitHub review webhooks, memory MCP servers, and runtime Cordis tools. They are never part of a default profile; the [user guides](../../docs/user/guide/index.md) and [developer practice guides](../../docs/user/develop/practice/index.md) own setup and safety instructions. +`config/examples/` ships opt-in overlays for GitHub review webhooks, memory MCP servers, [cross-Session messages](../../docs/user/session-control.md) in Web profiles, and runtime Cordis tools. They are never part of a default profile; the [user guides](../../docs/user/guide/index.md) and [developer practice guides](../../docs/user/develop/practice/index.md) own setup and safety instructions. ## Installed payload diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 5d0ce78b86..3c62793f4b 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -51,7 +51,7 @@ profile 目录包含一个 `package.json`,其中记录树外插件依赖,以 ## 可选覆盖层 -`config/examples/` 交付 GitHub 评审 webhook、记忆 MCP 服务器与运行时 Cordis 工具的可选覆盖层。它们绝不属于默认 profile;设置与安全说明由[用户指南](../../docs/user/guide/index.zh.md)和[开发实战指南](../../docs/user/develop/practice/index.zh.md)负责。 +`config/examples/` 交付 GitHub 评审 webhook、记忆 MCP 服务器、Web profile 中的[跨 Session 消息](../../docs/user/session-control.zh.md)与运行时 Cordis 工具的可选覆盖层。它们绝不属于默认 profile;设置与安全说明由[用户指南](../../docs/user/guide/index.zh.md)和[开发实战指南](../../docs/user/develop/practice/index.zh.md)负责。 ## 安装包内容 diff --git a/apps/cli/config/examples/session-control.overlay.yml b/apps/cli/config/examples/session-control.overlay.yml new file mode 100644 index 0000000000..6571513a7e --- /dev/null +++ b/apps/cli/config/examples/session-control.overlay.yml @@ -0,0 +1,6 @@ +# Enables the disabled tool-session-control row of the dsh-web-app bundle, so +# Agents in a Web profile can message ordinary Sessions in any Workspace or +# directory. Profiles without that bundle (headless, sdk, sdk-minimal, acp) +# have no such row; the Loader warns and skips this patch there. +- id: tool-session-control + disabled: false diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index cfc0807110..aaa01fc17c 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -55,8 +55,6 @@ Available at app or window level depending on the platform. click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. - AX read defaults: maxElements=2000, maxDepth=25. Maximum click holdMs: 5000 ms. diff --git a/apps/cli/tests/profiles/cua-mcp/expected/tools.json b/apps/cli/tests/profiles/cua-mcp/expected/tools.json index 3b0395878f..d7732d9310 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/tools.json +++ b/apps/cli/tests/profiles/cua-mcp/expected/tools.json @@ -17,7 +17,7 @@ { "name": "cua_run_code", "title": "Computer use program", - "description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.", + "description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Call other session tools directly outside cua_run_code. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.", "inputSchema": { "type": "object", "properties": { diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl index 499bdc083c..4fb3b85a2a 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl @@ -22,7 +22,7 @@ {"type":"session/title","data":{"title":"Start a background job.","messageSeqs":[3],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-once","name":"list_agents","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"list-once","name":"list_agents","args":["{}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-once","name":"list_agents","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":1,"callId":"list-once","name":"list_agents","arguments":"{}"}} -{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-once"},"toolCallId":"list-once","content":[{"type":"text","text":"lead [running] — root agent\n{{sessionId}} [inactive] — descriptorless child"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-once"},"toolCallId":"list-once","content":[{"type":"text","text":"Subagent capacity: running=0, limit=8\nlead [running] — root agent\n{{sessionId}} [inactive] — descriptorless child"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} {"type":"step/start","data":{"turn":2,"step":2}} {"type":"assistant/message","data":{"turn":2,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The catalogued subagent is ready. PARENT_DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["The catalogued subagent is ready. PARENT_DONE"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The catalogued subagent is ready. PARENT_DONE"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 46601acbb9..a146117824 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -18,8 +18,8 @@ en: 7414f87908fbffaf zh: 8ff4fc1d83879c25 /deepseek-harness-desktop/terminal-command: - en: 5f2d25a1d8472647 - zh: 2acb5c5d7d1917e2 + en: 988bf8bb84cf7c9a + zh: 28cefc949c7f52ce /deepseek-harness-desktop/closing-the-window-and-quitting: en: bb35a022c37955c9 zh: ab2ef22d398d83a0 @@ -54,8 +54,8 @@ en: 7200a35dbed997c3 zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: - en: eb9d30bca4134f80 - zh: bf201d18ae5ba697 + en: 80f8f18b571864b6 + zh: 45af1d593b7e1b64 /deepseek-harness-desktop/updates: en: 8b0b9efeb83727ef zh: 5ee95de48ceab392 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 741248a2c9..01bfdd9676 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -67,7 +67,7 @@ The application menu's **Manage dsh Command…** entry, immediately below **Chec On macOS, installation creates `/usr/local/bin/dsh` and requests administrator authentication when the directory requires it. Shell startup files are unchanged. On Windows, the management dialog registers the command in the current user's PATH. A pre-existing command requires confirmation before switching; repairing Desktop's own selected command does not repeat that confirmation. The macOS link preserves and restores the displaced launcher; Windows preserves other PATH entries, including entries that predate registration. A command with higher PATH precedence is reported with its location. After moving the application, use Repair on macOS or Install from the new location on Windows. Remove leaves unrelated installations intact. -Command registration is optional after installing Desktop. Use **Manage dsh Command… → Remove** before uninstalling Desktop to remove its CLI registration; the application uninstaller does not remove it. Finish CLI commands before updating or uninstalling Desktop. The CLI runtime version follows the installed Desktop release. See [bundled command runtime](#bundled-command-runtime) for Desktop plugin commands and runtime limitations. +Command registration is optional after installing Desktop. Windows manual uninstall removes CLI registration owned by that installation; on macOS, use **Manage dsh Command… → Remove** before uninstalling Desktop. Finish CLI commands before updating or uninstalling Desktop. The CLI runtime version follows the installed Desktop release. See [bundled command runtime](#bundled-command-runtime) for Desktop plugin commands and runtime limitations. @@ -267,9 +267,9 @@ Windows packaging compiles an x86 Win32/GDI+ helper with Visual C++ Build Tools Run `pnpm --dir apps/desktop run test:installer` from the repository root on an interactive Windows x64 desktop to build and exercise a small native test payload through the production installer configuration. Each run uses a unique product identity and sequentially exercises English-only and Chinese-only installer variants, selecting test labels from the displayed welcome button. Both variants install into private directories and uninstall after testing; screenshots and results remain under `.desktop-build/installer-tests/`. The checks include restart-notice process cleanup, upgrades to registered paths with trailing separators and rejection of drive roots. The renderer receives caption colors from the NSIS theme; pixel checks print into an off-screen bitmap and also run with the progress child hidden. Native rendering checks cover light/dark palettes at 100% and 200% scale, the painted 100% completion state, caption-button hover/pressed colors and release/cancellation, minimize/restore geometry, and GDI resource release; repaint timings are diagnostics in `render-results.log`, not CI performance limits. Run the generated `ui/render-test.exe [interactive-title]` with a title to inspect the real progress page without installing a payload. The optional `--signed` flag uses the [Windows EV configuration](windows-signing/README.md#signing-configuration) to sign test executables and the helper before embedding them; it does not enable an update feed. -The Windows uninstaller removes the Electron user-data directory (browser storage and caches under `%APPDATA%`, nested under the package scope), the `%APPDATA%` product directory, and the updater download cache under `%LOCALAPPDATA%` together with the application, then removes ordinary empty scope directories below `%APPDATA%`. The Harness home (`~/.dsh` or `DSH_HOME`: sessions, settings, credentials, plugins) is never touched, and a `DSH_HOME` published as a Windows environment variable additionally protects any target overlapping it. Silent uninstalls remove the same data; an uninstaller started with `--updated` or `/KEEP_APP_DATA`, as electron-builder does for in-place updates and for replacing an older installation from another directory, retains it. Removal runs through the native helper, which refuses protected Windows folders and paths overlapping the installation or the home, requires a fixed local drive, leaves a linked root or ancestor in place, unlinks reparse points without entering their targets, clears read-only attributes, and keeps deleting siblings after a locked file; residue never stops uninstallation and is not reported. Installation records `InstallLocation` on the Windows uninstall entry as standard inventory metadata; on Windows 11, Uninstall in the Start menu context menu opens the installed-apps list for every Win32 application, and only MSIX packages uninstall directly from there. The uninstaller declares DPI awareness and uses Microsoft YaHei UI for Chinese. This behavior is Windows-only. +The Windows uninstaller removes the Electron user-data directory (browser storage and caches under `%APPDATA%`, nested under the package scope), the `%APPDATA%` product directory, and the updater download cache under `%LOCALAPPDATA%` together with the application, then removes ordinary empty scope directories below `%APPDATA%`. The Harness home (`~/.dsh` or `DSH_HOME`: sessions, settings, credentials, plugins) is never touched, and a `DSH_HOME` published as a Windows environment variable additionally protects any target overlapping it. Home paths accept `~/`, `~\` and forward slashes, then require an absolute path on a fixed local drive. UNC shares, network mapped drives, removable drives and relative paths are not accepted for deletion-scope validation; validation failure stops before deletion and reports the original `DSH_HOME` value. This restriction also applies to cross-directory replacement. A cancelled or silent refusal for a different registered installation records the reason and both directories in the cleanup report. Silent uninstalls remove the same data; an uninstaller started with `--updated` or `/KEEP_APP_DATA`, as electron-builder does for in-place updates and for replacing an older installation from another directory, retains it. Removal runs through the native helper, which refuses protected Windows folders and paths overlapping the installation or the home, requires a fixed local drive, leaves a linked root or ancestor in place, unlinks reparse points without entering their targets, clears read-only attributes, and keeps deleting siblings after a locked file; auxiliary residue does not stop uninstallation and is included in the cleanup report. Installation records `InstallLocation` on the Windows uninstall entry as standard inventory metadata; on Windows 11, Uninstall in the Start menu context menu opens the installed-apps list for every Win32 application, and only MSIX packages uninstall directly from there. The uninstaller declares DPI awareness and uses Microsoft YaHei UI for Chinese. Manual and silent uninstall also remove the owned command PATH entry and its ownership values, and remove `dsh://` only when its command still names this installation. When command ownership is missing, an additional cleanup removes only PATH entries matching the CLI directory of this installation after confirming the installation directory is absent; existing directories and failed checks retain those entries with a cleanup report. Other command installations are preserved. `--updated` preserves these registrations; `/KEEP_APP_DATA` alone does not. Cross-directory replacement passes only `/KEEP_APP_DATA`, so the old command registration is removed; the command can be enabled again from the new installation. When the installation record points elsewhere, interactive uninstall asks for confirmation and silent uninstall stops. If the location is missing or another installation is registered, cleanup removes commands, protocol handlers, shortcuts and Windows uninstall entries that still point to the directory being removed. Shared user data and shell settings are retained. The main executable is removed first: failure retains the remaining files and uninstall entry, with retry and report-saving actions. Unverifiable directory scope stops before deletion; incomplete removal results stop subsequent cleanup. Registry or auxiliary-file failures allow uninstall to finish with a residual-items notice. Native dialogs measure approximately 40 Chinese characters with the current font and fall back to 240 DLU. Reports list failed or unverified paths, registry key/value names, operations and available error codes, without registry values or the complete PATH. Reports are retained under `%TEMP%/DeepSeek-Harness-uninstall-.txt` when writable; interactive dialogs also offer Save cleanup report, and a failed save allows another location. This behavior is Windows-only. -Use `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` to compile isolated English and Chinese fixtures with a per-run scoped package name. Omit `--compile-only` to run the native remover regression and the interactive, silent, `--updated`, `/KEEP_APP_DATA` and `DSH_HOME`-inside-Electron-data checks against seeded data. Compilation does not establish installed-uninstall behavior. +Use `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` to compile isolated fixtures for all eight installer languages with a per-run scoped package name. Omit `--compile-only` to run the native remover regression and the interactive, silent, `--updated`, `/KEEP_APP_DATA`, `DSH_HOME`-inside-Electron-data, busy-executable retry, registration-error continuation and installation-takeover checks against seeded data. Setup timeouts terminate and wait for the fixture process tree before cleanup; a separate regression covers success, nonzero exit and a timed-out parent with a live child. Compilation does not establish installed-uninstall behavior. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 6fedfb2a5e..22e2edc76f 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -67,7 +67,7 @@ Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform macOS 安装会创建 `/usr/local/bin/dsh`;目录权限需要时,系统会请求管理员认证,不会修改 shell 启动文件。Windows 管理对话框将命令注册到当前用户的 PATH。切换已有命令前会要求确认;修复当前已选中的 Desktop 命令不会重复要求切换确认。macOS 链接会保留并恢复被替换的启动器;Windows 会保留其他 PATH 条目,包括注册前就已存在的条目。若其他命令的 PATH 优先级更高,对话框会显示其位置。移动应用后,macOS 使用“修复”,Windows 从新位置使用“安装”。“移除”不会改动无关安装。 -命令注册是安装 Desktop 后的可选操作。卸载 Desktop 前,请通过**管理 dsh 命令… → 移除**删除其 CLI 注册;应用卸载程序不会移除该注册。更新或卸载 Desktop 前请结束 CLI 命令。CLI 运行时版本随已安装的 Desktop 版本变化。Desktop 插件命令与运行时限制见[内置命令运行时](#bundled-command-runtime)。 +命令注册是安装 Desktop 后的可选操作。Windows 手动卸载会移除属于该安装的 CLI 注册;macOS 卸载前请通过**管理 dsh 命令… → 移除**删除注册。更新或卸载 Desktop 前请结束 CLI 命令。CLI 运行时版本随已安装的 Desktop 版本变化。Desktop 插件命令与运行时限制见[内置命令运行时](#bundled-command-runtime)。 @@ -267,9 +267,9 @@ Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI 在有交互式桌面的 Windows x64 上,从仓库根目录运行 `pnpm --dir apps/desktop run test:installer`,可将小型原生测试载荷接入正式安装配置并执行验证。每次运行使用独立产品身份,依次验证仅英文和仅中文的安装器变体,并根据实际显示的欢迎页按钮选择测试文案。两个变体均安装到私有目录并在测试后卸载;截图和结果保留在 `.desktop-build/installer-tests/` 下。检查包含重启提示窗的进程回收、末尾带分隔符的已登记路径升级,以及磁盘根目录拒绝。绘制器接收 NSIS 主题传入的标题栏颜色;像素检查绘制到离屏位图,并在隐藏进度子窗口时验证。原生绘制检查覆盖 100% 和 200% 缩放下的浅色/深色配色、绘制到 100% 的完成状态、标题栏按钮的悬停/按下颜色和松开触发与取消、最小化恢复后的窗口位置和尺寸,以及 GDI 资源释放;`render-results.log` 中的重绘耗时仅供诊断,不作为 CI 性能阈值。运行生成的 `ui/render-test.exe [interactive-title]` 并指定标题,可在不安装载荷的情况下查看真实进度页。可选的 `--signed` 标志使用[Windows EV 配置](windows-signing/README.zh.md#signing-configuration),在嵌入前对测试程序和辅助库签名;它不会启用更新源。 -Windows 卸载程序会随应用一起删除 Electron 用户数据目录(`%APPDATA%` 下按包作用域嵌套的浏览器存储与缓存)、`%APPDATA%` 下的产品目录,以及 `%LOCALAPPDATA%` 下的更新下载缓存,随后移除 `%APPDATA%` 之下普通且已空的作用域目录。Harness 主目录(`~/.dsh` 或 `DSH_HOME`:会话、设置、凭据、插件)不会被触碰;以 Windows 环境变量发布的 `DSH_HOME` 还会保护所有与其重叠的目标。静默卸载删除相同的数据;以 `--updated` 或 `/KEEP_APP_DATA` 启动的卸载程序保留数据,electron-builder 在原地更新和从其他目录替换旧安装时正是这样启动它。删除通过原生辅助程序执行:它拒绝受保护的 Windows 目录以及与安装目录或主目录重叠的路径,要求固定的本地驱动器,链接的根目录或祖先目录原样保留,遇到重解析点只解除链接而不进入目标,清除只读属性,并在遇到被占用文件后继续删除其余兄弟项;残余不会中止卸载,也不会提示。安装时在 Windows 卸载注册项上记录 `InstallLocation` 作为标准的清单元数据;在 Windows 11 上,开始菜单右键菜单中的“卸载”对所有 Win32 应用都会打开已安装应用列表,只有 MSIX 包能从那里直接卸载。卸载程序声明 DPI 感知,中文使用微软雅黑 UI。此行为仅适用于 Windows。 +Windows 卸载程序会随应用一起删除 Electron 用户数据目录(`%APPDATA%` 下按包作用域嵌套的浏览器存储与缓存)、`%APPDATA%` 下的产品目录,以及 `%LOCALAPPDATA%` 下的更新下载缓存,随后移除 `%APPDATA%` 之下普通且已空的作用域目录。Harness 主目录(`~/.dsh` 或 `DSH_HOME`:会话、设置、凭据、插件)不会被触碰;以 Windows 环境变量发布的 `DSH_HOME` 还会保护所有与其重叠的目标。主目录路径支持 `~/`、`~\` 和正斜杠,转换后仍要求固定本地驱动器上的绝对路径。删除范围校验不接受 UNC 共享、网络映射盘、移动盘和相对路径;校验失败时在删除前停止,并在报告中标明原始 `DSH_HOME` 值。此限制也适用于跨目录替换。因登记指向其他安装而取消或静默拒绝卸载时,清理报告会记录原因和两个目录。静默卸载删除相同的数据;以 `--updated` 或 `/KEEP_APP_DATA` 启动的卸载程序保留数据,electron-builder 在原地更新和从其他目录替换旧安装时正是这样启动它。删除通过原生辅助程序执行:它拒绝受保护的 Windows 目录以及与安装目录或主目录重叠的路径,要求固定的本地驱动器,链接的根目录或祖先目录原样保留,遇到重解析点只解除链接而不进入目标,清除只读属性,并在遇到被占用文件后继续删除其余兄弟项;辅助内容的残余不会中止卸载,并会记录到清理报告中。安装时在 Windows 卸载注册项上记录 `InstallLocation` 作为标准的清单元数据;在 Windows 11 上,开始菜单右键菜单中的“卸载”对所有 Win32 应用都会打开已安装应用列表,只有 MSIX 包能从那里直接卸载。卸载程序声明 DPI 感知,中文使用微软雅黑 UI。手动和静默卸载还会移除属于该安装的命令 PATH 条目和所有权值,仅当 `dsh://` 的命令仍指向该安装时才移除协议注册。命令所有权缺失时,额外清理只移除匹配本安装 CLI 目录的 PATH 条目,并先确认安装目录已不存在;目录仍存在或检查失败时保留条目并生成清理报告。其他命令安装保持不变。`--updated` 保留这些注册;单独使用 `/KEEP_APP_DATA` 不会保留。跨目录替换只传入 `/KEEP_APP_DATA`,因此移除旧命令注册;用户可从新安装中重新启用命令。安装登记指向其他目录时,交互式卸载请求确认,静默卸载停止。安装地址缺失或指向其他位置时,卸载会清理仍指向本目录的命令、协议、快捷方式和 Windows 卸载入口,保留共享用户数据和系统外壳设置。卸载先删除主程序:失败时保留其余文件和卸载入口,提供重试和保存报告。无法确认目录范围时,在删除前停止;删除结果不完整时,停止后续清理。注册表或辅助文件清理失败不阻止卸载完成,但会提示有内容未能清理。原生弹窗按当前字体测量约 40 个汉字的宽度,失败回退到 240 DLU。报告包含失败或结果未确认的路径、注册表键及值名称、操作和可用错误码,不包含注册表值内容或完整 PATH。可写时报告保留在 `%TEMP%/DeepSeek-Harness-uninstall-.txt`;交互弹窗另提供“保存清理报告”,保存失败时可以重新选择位置。此行为仅适用于 Windows。 -使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译独立的中英文夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 和 `DSH_HOME` 位于 Electron 数据内的检查。编译本身不能证明已安装卸载行为。 +使用 `node apps/desktop/scripts/test-windows-installer.mjs --uninstall-only --compile-only` 以每次运行唯一的带作用域包名编译八种安装语言的独立夹具。省略 `--compile-only` 可对预置数据运行原生删除器回归,以及交互、静默、`--updated`、`/KEEP_APP_DATA` 、`DSH_HOME` 位于 Electron 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。安装超时会先终止并等待夹具进程树退出,再清理测试资源;独立回归覆盖成功、非零退出及带存活子进程的父进程超时。编译本身不能证明已安装卸载行为。 diff --git a/apps/desktop/installer/locales/de_DE.json b/apps/desktop/installer/locales/de_DE.json index 595002b284..aefac91fbb 100644 --- a/apps/desktop/installer/locales/de_DE.json +++ b/apps/desktop/installer/locales/de_DE.json @@ -32,7 +32,19 @@ "INSTALLER_EXTRACT_COLLAPSE": "Details ausblenden", "INSTALLER_EXTRACT_SAVED": "Der vollständige Bericht wurde unter %s gespeichert", "INSTALLER_EXTRACT_UNSAVED": "Der vollständige Bericht konnte nicht gespeichert werden. Verwenden Sie „Fehlerdetails kopieren“, um sie beizubehalten.", - "INSTALLER_EXTRACT_COPIED": "Fehlerdetails wurden in die Zwischenablage kopiert." + "INSTALLER_EXTRACT_COPIED": "Fehlerdetails wurden in die Zwischenablage kopiert.", + "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness ist an mehreren Orten installiert", + "INSTALLER_UNINSTALL_REGISTRATION": "Einige Elemente konnten nicht bereinigt werden. Speichern Sie den Bericht für weitere Informationen.", + "INSTALLER_UNINSTALL_REGISTERED": "Registrierter Installationsort:", + "INSTALLER_UNINSTALL_SCOPE": "Auch Befehle, Verknüpfungen und Einträge, die auf dieses Verzeichnis zeigen, werden entfernt:", + "INSTALLER_UNINSTALL_CONTINUE": "Deinstallationsordner weiter bereinigen", + "INSTALLER_UNINSTALL_SAVE": "Bereinigungsbericht speichern…", + "INSTALLER_UNINSTALL_SAVE_FAILED": "Der Bericht konnte nicht gespeichert werden. Wählen Sie einen anderen Speicherort.", + "INSTALLER_UNINSTALL_INCOMPLETE": "Deinstallation nicht abgeschlossen", + "INSTALLER_UNINSTALL_UNSAFE": "Der Löschbereich konnte nicht bestätigt werden. Es wurde nichts gelöscht.", + "INSTALLER_UNINSTALL_UNKNOWN": "Ein Bereinigungsvorgang lieferte kein vollständiges Ergebnis. Weitere Schritte wurden gestoppt.", + "INSTALLER_UNINSTALL_BLOCKED": "Diese Datei konnte nicht gelöscht werden. Schließen Sie Programme, die sie möglicherweise verwenden, prüfen Sie die Zugriffsrechte und versuchen Sie es erneut.", + "INSTALLER_UNINSTALL_COMPLETE": "Deinstallation abgeschlossen" }, "uninstaller": { "welcome": "Willkommen", diff --git a/apps/desktop/installer/locales/en_US.json b/apps/desktop/installer/locales/en_US.json index 73af2ede5e..46473f800e 100644 --- a/apps/desktop/installer/locales/en_US.json +++ b/apps/desktop/installer/locales/en_US.json @@ -32,7 +32,19 @@ "INSTALLER_EXTRACT_COLLAPSE": "Hide details", "INSTALLER_EXTRACT_SAVED": "The full report was saved to %s", "INSTALLER_EXTRACT_UNSAVED": "The full report could not be saved. Use Copy error details to keep it.", - "INSTALLER_EXTRACT_COPIED": "Error details were copied to the clipboard." + "INSTALLER_EXTRACT_COPIED": "Error details were copied to the clipboard.", + "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness is installed in multiple locations", + "INSTALLER_UNINSTALL_REGISTRATION": "Some items could not be cleaned up. Save the report for details.", + "INSTALLER_UNINSTALL_REGISTERED": "Registered installation location:", + "INSTALLER_UNINSTALL_SCOPE": "Continuing removes this directory and commands, shortcuts and registrations pointing to it:", + "INSTALLER_UNINSTALL_CONTINUE": "Continue cleaning uninstall directory", + "INSTALLER_UNINSTALL_SAVE": "Save cleanup report…", + "INSTALLER_UNINSTALL_SAVE_FAILED": "The report could not be saved. Choose another location.", + "INSTALLER_UNINSTALL_INCOMPLETE": "Uninstall did not finish", + "INSTALLER_UNINSTALL_UNSAFE": "The removal scope could not be verified. No deletion was started.", + "INSTALLER_UNINSTALL_UNKNOWN": "A cleanup operation did not return a complete result. Further cleanup was stopped.", + "INSTALLER_UNINSTALL_BLOCKED": "This file could not be deleted. Close programs that may be using it, check access permissions, and retry.", + "INSTALLER_UNINSTALL_COMPLETE": "Uninstall completed" }, "uninstaller": { "welcome": "Welcome", diff --git a/apps/desktop/installer/locales/es_ES.json b/apps/desktop/installer/locales/es_ES.json index 99e5abe63e..9f267f21dc 100644 --- a/apps/desktop/installer/locales/es_ES.json +++ b/apps/desktop/installer/locales/es_ES.json @@ -32,7 +32,19 @@ "INSTALLER_EXTRACT_COLLAPSE": "Ocultar detalles", "INSTALLER_EXTRACT_SAVED": "El informe completo se guardó en %s.", "INSTALLER_EXTRACT_UNSAVED": "No se pudo guardar el informe completo. Utilice Copiar detalles del error para conservarlo.", - "INSTALLER_EXTRACT_COPIED": "Los detalles del error se copiaron al portapapeles." + "INSTALLER_EXTRACT_COPIED": "Los detalles del error se copiaron al portapapeles.", + "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness está instalado en varias ubicaciones", + "INSTALLER_UNINSTALL_REGISTRATION": "No se pudieron limpiar algunos elementos. Guarda el informe para ver los detalles.", + "INSTALLER_UNINSTALL_REGISTERED": "Ubicación de instalación registrada:", + "INSTALLER_UNINSTALL_SCOPE": "Se eliminarán este directorio y los comandos, accesos directos y registros que apunten a él:", + "INSTALLER_UNINSTALL_CONTINUE": "Continuar limpiando el directorio de desinstalación", + "INSTALLER_UNINSTALL_SAVE": "Guardar informe de limpieza…", + "INSTALLER_UNINSTALL_SAVE_FAILED": "No se pudo guardar el informe. Elige otra ubicación.", + "INSTALLER_UNINSTALL_INCOMPLETE": "La desinstalación no se completó", + "INSTALLER_UNINSTALL_UNSAFE": "No se pudo verificar el alcance de la eliminación. No se inició la eliminación.", + "INSTALLER_UNINSTALL_UNKNOWN": "Una operación de limpieza no devolvió un resultado completo. Se detuvo la limpieza posterior.", + "INSTALLER_UNINSTALL_BLOCKED": "No se pudo eliminar este archivo. Cierra los programas que puedan estar usándolo, comprueba los permisos y vuelve a intentarlo.", + "INSTALLER_UNINSTALL_COMPLETE": "Desinstalación completada" }, "uninstaller": { "welcome": "Bienvenido", diff --git a/apps/desktop/installer/locales/fr_FR.json b/apps/desktop/installer/locales/fr_FR.json index 167922256b..40936f4bbf 100644 --- a/apps/desktop/installer/locales/fr_FR.json +++ b/apps/desktop/installer/locales/fr_FR.json @@ -32,7 +32,19 @@ "INSTALLER_EXTRACT_COLLAPSE": "Masquer les détails", "INSTALLER_EXTRACT_SAVED": "Le rapport complet a été enregistré dans %s", "INSTALLER_EXTRACT_UNSAVED": "Le rapport complet n'a pas pu être enregistré. Utilisez Copier les détails de l'erreur pour le conserver.", - "INSTALLER_EXTRACT_COPIED": "Les détails de l'erreur ont été copiés dans le presse-papiers." + "INSTALLER_EXTRACT_COPIED": "Les détails de l'erreur ont été copiés dans le presse-papiers.", + "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness est installé à plusieurs emplacements", + "INSTALLER_UNINSTALL_REGISTRATION": "Certains éléments n’ont pas pu être nettoyés. Enregistrez le rapport pour consulter les détails.", + "INSTALLER_UNINSTALL_REGISTERED": "Emplacement enregistré :", + "INSTALLER_UNINSTALL_SCOPE": "Ce dossier et les commandes, raccourcis et inscriptions qui y renvoient seront supprimés :", + "INSTALLER_UNINSTALL_CONTINUE": "Continuer le nettoyage du dossier de désinstallation", + "INSTALLER_UNINSTALL_SAVE": "Enregistrer le rapport de nettoyage…", + "INSTALLER_UNINSTALL_SAVE_FAILED": "Le rapport n’a pas pu être enregistré. Choisissez un autre emplacement.", + "INSTALLER_UNINSTALL_INCOMPLETE": "La désinstallation n’est pas terminée", + "INSTALLER_UNINSTALL_UNSAFE": "Le périmètre de suppression n’a pas pu être vérifié. Aucune suppression n’a commencé.", + "INSTALLER_UNINSTALL_UNKNOWN": "Une opération de nettoyage n’a pas renvoyé de résultat complet. Les opérations suivantes ont été arrêtées.", + "INSTALLER_UNINSTALL_BLOCKED": "Ce fichier n’a pas pu être supprimé. Fermez les programmes susceptibles de l’utiliser, vérifiez les droits d’accès et réessayez.", + "INSTALLER_UNINSTALL_COMPLETE": "Désinstallation terminée" }, "uninstaller": { "welcome": "Bienvenue", diff --git a/apps/desktop/installer/locales/ja_JP.json b/apps/desktop/installer/locales/ja_JP.json index 72ef1cc641..785bafdd7b 100644 --- a/apps/desktop/installer/locales/ja_JP.json +++ b/apps/desktop/installer/locales/ja_JP.json @@ -32,7 +32,19 @@ "INSTALLER_EXTRACT_COLLAPSE": "詳細を非表示", "INSTALLER_EXTRACT_SAVED": "完全なレポートを %s に保存しました", "INSTALLER_EXTRACT_UNSAVED": "完全なレポートを保存できませんでした。「エラーの詳細をコピー」で保存してください。", - "INSTALLER_EXTRACT_COPIED": "エラーの詳細をクリップボードにコピーしました。" + "INSTALLER_EXTRACT_COPIED": "エラーの詳細をクリップボードにコピーしました。", + "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness が複数の場所にインストールされています", + "INSTALLER_UNINSTALL_REGISTRATION": "一部の項目を削除できませんでした。詳細はレポートを保存して確認できます。", + "INSTALLER_UNINSTALL_REGISTERED": "登録されているインストール先:", + "INSTALLER_UNINSTALL_SCOPE": "続行すると、次のフォルダーと、それを参照するコマンド、ショートカット、登録情報を削除します:", + "INSTALLER_UNINSTALL_CONTINUE": "アンインストール先の削除を続行", + "INSTALLER_UNINSTALL_SAVE": "削除レポートを保存…", + "INSTALLER_UNINSTALL_SAVE_FAILED": "レポートを保存できませんでした。別の保存先を選んでください。", + "INSTALLER_UNINSTALL_INCOMPLETE": "アンインストールは完了していません", + "INSTALLER_UNINSTALL_UNSAFE": "削除範囲を確認できないため、削除を開始しませんでした。", + "INSTALLER_UNINSTALL_UNKNOWN": "削除処理の完全な結果が得られないため、後続の処理を停止しました。", + "INSTALLER_UNINSTALL_BLOCKED": "このファイルを削除できません。使用している可能性のあるプログラムを閉じ、アクセス権を確認して再試行してください。", + "INSTALLER_UNINSTALL_COMPLETE": "アンインストールが完了しました" }, "uninstaller": { "welcome": "アンインストール ウィザードへようこそ", diff --git a/apps/desktop/installer/locales/pt_BR.json b/apps/desktop/installer/locales/pt_BR.json index 93aacd5dc8..90b3ed8b8e 100644 --- a/apps/desktop/installer/locales/pt_BR.json +++ b/apps/desktop/installer/locales/pt_BR.json @@ -32,7 +32,19 @@ "INSTALLER_EXTRACT_COLLAPSE": "Ocultar detalhes", "INSTALLER_EXTRACT_SAVED": "O relatório completo foi salvo em %s", "INSTALLER_EXTRACT_UNSAVED": "Não foi possível salvar o relatório completo. Use Copiar detalhes do erro para mantê-lo.", - "INSTALLER_EXTRACT_COPIED": "Os detalhes do erro foram copiados para a área de transferência." + "INSTALLER_EXTRACT_COPIED": "Os detalhes do erro foram copiados para a área de transferência.", + "INSTALLER_UNINSTALL_OWNER": "O DeepSeek Harness está instalado em vários locais", + "INSTALLER_UNINSTALL_REGISTRATION": "Não foi possível limpar alguns itens. Salve o relatório para ver os detalhes.", + "INSTALLER_UNINSTALL_REGISTERED": "Local de instalação registrado:", + "INSTALLER_UNINSTALL_SCOPE": "Continuar remove este diretório e os comandos, atalhos e registros que apontam para ele:", + "INSTALLER_UNINSTALL_CONTINUE": "Continuar limpando o diretório de desinstalação", + "INSTALLER_UNINSTALL_SAVE": "Salvar relatório de limpeza…", + "INSTALLER_UNINSTALL_SAVE_FAILED": "Não foi possível salvar o relatório. Escolha outro local.", + "INSTALLER_UNINSTALL_INCOMPLETE": "A desinstalação não foi concluída", + "INSTALLER_UNINSTALL_UNSAFE": "Não foi possível verificar o escopo da exclusão. Nenhuma exclusão foi iniciada.", + "INSTALLER_UNINSTALL_UNKNOWN": "Uma operação de limpeza não retornou um resultado completo. As etapas seguintes foram interrompidas.", + "INSTALLER_UNINSTALL_BLOCKED": "Não foi possível excluir este arquivo. Feche programas que possam estar usando-o, verifique as permissões e tente novamente.", + "INSTALLER_UNINSTALL_COMPLETE": "Desinstalação concluída" }, "uninstaller": { "welcome": "Bem-vindo", diff --git a/apps/desktop/installer/locales/ru_RU.json b/apps/desktop/installer/locales/ru_RU.json index 20345ea37c..a1f9957dfd 100644 --- a/apps/desktop/installer/locales/ru_RU.json +++ b/apps/desktop/installer/locales/ru_RU.json @@ -32,7 +32,19 @@ "INSTALLER_EXTRACT_COLLAPSE": "Скрыть детали", "INSTALLER_EXTRACT_SAVED": "Полный отчет сохранен в %s.", "INSTALLER_EXTRACT_UNSAVED": "Полный отчет не удалось сохранить. Используйте Скопировать сведения об ошибке, чтобы сохранить их.", - "INSTALLER_EXTRACT_COPIED": "Подробности об ошибке скопированы в буфер обмена." + "INSTALLER_EXTRACT_COPIED": "Подробности об ошибке скопированы в буфер обмена.", + "INSTALLER_UNINSTALL_OWNER": "DeepSeek Harness установлен в нескольких местах", + "INSTALLER_UNINSTALL_REGISTRATION": "Некоторые элементы не удалось очистить. Сохраните отчёт для просмотра подробностей.", + "INSTALLER_UNINSTALL_REGISTERED": "Зарегистрированное расположение:", + "INSTALLER_UNINSTALL_SCOPE": "Будут удалены этот каталог и указывающие на него команды, ярлыки и записи:", + "INSTALLER_UNINSTALL_CONTINUE": "Продолжить очистку каталога удаления", + "INSTALLER_UNINSTALL_SAVE": "Сохранить отчёт об очистке…", + "INSTALLER_UNINSTALL_SAVE_FAILED": "Не удалось сохранить отчёт. Выберите другое расположение.", + "INSTALLER_UNINSTALL_INCOMPLETE": "Удаление не завершено", + "INSTALLER_UNINSTALL_UNSAFE": "Не удалось проверить область удаления. Удаление не начато.", + "INSTALLER_UNINSTALL_UNKNOWN": "Операция очистки не вернула полный результат. Дальнейшая очистка остановлена.", + "INSTALLER_UNINSTALL_BLOCKED": "Не удалось удалить этот файл. Закройте программы, которые могут его использовать, проверьте права доступа и повторите попытку.", + "INSTALLER_UNINSTALL_COMPLETE": "Удаление завершено" }, "uninstaller": { "welcome": "Вас приветствует мастер удаления", diff --git a/apps/desktop/installer/locales/zh_CN.json b/apps/desktop/installer/locales/zh_CN.json index 7951f34340..2f6a9bbec0 100644 --- a/apps/desktop/installer/locales/zh_CN.json +++ b/apps/desktop/installer/locales/zh_CN.json @@ -32,7 +32,19 @@ "INSTALLER_EXTRACT_COLLAPSE": "隐藏详情", "INSTALLER_EXTRACT_SAVED": "完整错误报告已保存到 %s", "INSTALLER_EXTRACT_UNSAVED": "无法保存完整错误报告,请使用“复制错误信息”保留。", - "INSTALLER_EXTRACT_COPIED": "错误信息已复制到剪贴板。" + "INSTALLER_EXTRACT_COPIED": "错误信息已复制到剪贴板。", + "INSTALLER_UNINSTALL_OWNER": "当前设备在多个位置安装了 DeepSeek Harness", + "INSTALLER_UNINSTALL_REGISTRATION": "部分内容未能清理成功。你可以保存清理报告,查看具体项目和原因。", + "INSTALLER_UNINSTALL_REGISTERED": "系统登记的安装位置:", + "INSTALLER_UNINSTALL_SCOPE": "选择继续,将清理以下目录,以及仍指向它的命令、快捷方式和系统登记:", + "INSTALLER_UNINSTALL_CONTINUE": "继续清理卸载目录", + "INSTALLER_UNINSTALL_SAVE": "保存清理报告…", + "INSTALLER_UNINSTALL_SAVE_FAILED": "报告未能保存,请重新选择保存位置。", + "INSTALLER_UNINSTALL_INCOMPLETE": "卸载未完成", + "INSTALLER_UNINSTALL_UNSAFE": "无法确认删除范围,本次操作未开始删除。", + "INSTALLER_UNINSTALL_UNKNOWN": "清理操作未返回完整结果,后续清理已停止。", + "INSTALLER_UNINSTALL_BLOCKED": "无法删除以下文件。请关闭可能使用该文件的程序,检查访问权限后重试。", + "INSTALLER_UNINSTALL_COMPLETE": "卸载已完成" }, "uninstaller": { "welcome": "欢迎", diff --git a/apps/desktop/installer/uninstall-data.h b/apps/desktop/installer/uninstall-data.h index d582de4c4d..c0e4f23dba 100644 --- a/apps/desktop/installer/uninstall-data.h +++ b/apps/desktop/installer/uninstall-data.h @@ -5,6 +5,12 @@ #include namespace uninstall_data { +struct Failure { std::wstring path; DWORD error; }; +using Failures = std::vector; +inline DWORD Record(Failures* failures, const std::wstring& path, DWORD error) { + if (error && failures) failures->push_back({path, error}); + return error; +} struct Handles { std::vector values; Handles() = default; @@ -39,6 +45,29 @@ inline bool Normalize(LPCWSTR input, std::wstring& result) { return true; } +// DSH_HOME accepts Node's tilde and separator spellings; relative roots remain +// unverifiable because the application's working directory is not available here. +inline bool NormalizeHome(LPCWSTR input, std::wstring& result) { + std::wstring value = input ? input : L""; + if (value.find_first_not_of(L" \t\r\n") == std::wstring::npos) value = L"~/.dsh"; + if (value == L"~" || value.compare(0, 2, L"~/") == 0 || value.compare(0, 2, L"~\\") == 0) { + WCHAR buffer[32768]; + DWORD length = GetEnvironmentVariableW(L"USERPROFILE", buffer, ARRAYSIZE(buffer)); + std::wstring profile; + if (length && length < ARRAYSIZE(buffer)) profile.assign(buffer, length); + else { + if (length) return false; + PWSTR folder = nullptr; + if (FAILED(SHGetKnownFolderPath(FOLDERID_Profile, KF_FLAG_DONT_VERIFY, nullptr, &folder))) return false; + profile = folder; + CoTaskMemFree(folder); + } + value = profile + (value.size() > 1 ? L"\\" + value.substr(2) : L""); + } + for (auto& character : value) if (character == L'/') character = L'\\'; + return Normalize(value.c_str(), result); +} + // Listing access takes part in share checks, so the open handle refuses the DELETE access a rename or removal needs. inline DWORD Pin(const std::wstring& path, Handles& handles) { HANDLE handle = CreateFileW((L"\\\\?\\" + path).c_str(), FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES, @@ -61,49 +90,49 @@ inline DWORD Unlink(const std::wstring& extended, DWORD attributes) { } // Every sibling is attempted; the first error is returned after the whole tree has been visited. -inline DWORD RemoveTree(const std::wstring& path) { +inline DWORD RemoveTree(const std::wstring& path, Failures* failures = nullptr) { const std::wstring extended = L"\\\\?\\" + path; DWORD attributes = GetFileAttributesW(extended.c_str()); if (attributes == INVALID_FILE_ATTRIBUTES) { DWORD error = GetLastError(); - return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? ERROR_SUCCESS : error; + return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? ERROR_SUCCESS : Record(failures, path, error); } DWORD first = ERROR_SUCCESS; if ((attributes & FILE_ATTRIBUTE_DIRECTORY) && !(attributes & FILE_ATTRIBUTE_REPARSE_POINT)) { Handles pinned; DWORD error = Pin(path, pinned); - if (error) return error; + if (error) return Record(failures, path, error); WIN32_FIND_DATAW entry{}; HANDLE search = FindFirstFileW((extended + L"\\*").c_str(), &entry); if (search == INVALID_HANDLE_VALUE) { error = GetLastError(); - if (error != ERROR_FILE_NOT_FOUND) return error; + if (error != ERROR_FILE_NOT_FOUND) return Record(failures, path, error); } else { do { if (wcscmp(entry.cFileName, L".") == 0 || wcscmp(entry.cFileName, L"..") == 0) continue; - error = RemoveTree(path + L"\\" + entry.cFileName); + error = RemoveTree(path + L"\\" + entry.cFileName, failures); if (error && !first) first = error; } while (FindNextFileW(search, &entry)); error = GetLastError(); FindClose(search); - if (error != ERROR_NO_MORE_FILES && !first) first = error; + if (error != ERROR_NO_MORE_FILES && !first) first = Record(failures, path, error); } } - DWORD error = Unlink(extended, attributes); + DWORD error = Record(failures, path, Unlink(extended, attributes)); return first ? first : error; } // Never select a shell folder, its ancestor, Windows/Program Files descendants, // a path overlapping the installation, or a path overlapping the protected root // (the configured Harness home). Linked descendants are unlinked only. -inline DWORD Remove(LPCWSTR input, LPCWSTR installation, LPCWSTR protectedRoot) { +inline DWORD Remove(LPCWSTR input, LPCWSTR installation, LPCWSTR protectedRoot, Failures* failures = nullptr) { std::wstring path, install; if (!Normalize(input, path) || !Normalize(installation, install)) return ERROR_INVALID_NAME; if (Contains(path, install) || Contains(install, path)) return ERROR_ACCESS_DENIED; if (protectedRoot && *protectedRoot) { std::wstring home; // An unusable protected root cannot establish separation from retained data. - if (!Normalize(protectedRoot, home)) return ERROR_INVALID_NAME; + if (!NormalizeHome(protectedRoot, home)) return ERROR_INVALID_NAME; if (Contains(path, home) || Contains(home, path)) return ERROR_ACCESS_DENIED; } struct ComScope { @@ -146,7 +175,7 @@ inline DWORD Remove(LPCWSTR input, LPCWSTR installation, LPCWSTR protectedRoot) if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) return ERROR_SUCCESS; if (error) return error; } - return RemoveTree(path); + return RemoveTree(path, failures); } // Remove the ordinary, empty directories between a removed path and its stop ancestor. diff --git a/apps/desktop/installer/uninstall-report.h b/apps/desktop/installer/uninstall-report.h new file mode 100644 index 0000000000..32c685593d --- /dev/null +++ b/apps/desktop/installer/uninstall-report.h @@ -0,0 +1,306 @@ +// Manual uninstall diagnostics and native dialogs. The NSIS caller owns one session until process exit. +#pragma once +#include +#include "uninstall-data.h" +#include "extract-report.h" + +namespace uninstall_report { +struct Session { + std::wstring text = L"DeepSeek Harness uninstall report\r\n"; + std::wstring path; + bool issues = false; + bool mainBlocked = false; + uninstall_data::Handles pinned; +}; +inline std::wstring Error(DWORD error) { + WCHAR buffer[2048]{}; + FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, error, 0, buffer, ARRAYSIZE(buffer), nullptr); + return std::to_wstring(error) + L" " + buffer; +} +inline void Add(Session& session, LPCWSTR operation, LPCWSTR target, DWORD error) { + session.issues = true; + session.text += std::wstring(L"\r\n[failed] ") + operation + L"\r\nTarget: " + target + L"\r\nWin32: " + Error(error) + L"\r\n"; +} +inline void Collect(Session& session, const uninstall_data::Failures& failures) { + for (const auto& failure : failures) Add(session, L"Remove file/directory", failure.path.c_str(), failure.error); +} +// Width is measured with the dialog font; measurement failure keeps the approved 240-DLU fallback. +inline UINT Width(HWND parent) { + NONCLIENTMETRICSW metrics{}; + metrics.cbSize = sizeof(metrics); + if (!SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof(metrics), &metrics, 0)) return 240; + HFONT font = parent ? reinterpret_cast(SendMessageW(parent, WM_GETFONT, 0, 0)) : nullptr; + const bool owned = !font; + if (owned) font = CreateFontIndirectW(&metrics.lfMessageFont); + HDC dc = GetDC(parent); + UINT width = 240; + if (font && dc) { + HGDIOBJ previous = SelectObject(dc, font); + SIZE alphabet{}, characters{}; + const std::wstring sample(40, L'\x5b57'); + if (GetTextExtentPoint32W(dc, L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 52, &alphabet) + && GetTextExtentPoint32W(dc, sample.c_str(), 40, &characters)) { + const int base = (alphabet.cx / 26 + 1) / 2; + if (base > 0 && characters.cx > 0) { + width = static_cast(MulDiv(characters.cx, 4, base) + 24); + MONITORINFO monitor{sizeof(monitor)}; + if (GetMonitorInfoW(MonitorFromWindow(parent, MONITOR_DEFAULTTONEAREST), &monitor)) { + const int available = monitor.rcWork.right - monitor.rcWork.left - MulDiv(48, GetDeviceCaps(dc, LOGPIXELSX), 96); + if (available > 0) width = std::min(width, static_cast(MulDiv(available, 4, base))); + } + } + } + SelectObject(dc, previous); + } + if (dc) ReleaseDC(parent, dc); + if (owned && font) DeleteObject(font); + return width; +} +inline bool Save(HWND parent, Session& session, LPCWSTR caption, LPCWSTR failed) { + for (;;) { + WCHAR filename[32768] = L"DeepSeek-Harness-uninstall-report.txt"; + OPENFILENAMEW picker{}; + picker.lStructSize = sizeof(picker); + picker.hwndOwner = parent; + picker.lpstrFilter = L"Text (*.txt)\0*.txt\0\0"; + picker.lpstrFile = filename; + picker.nMaxFile = ARRAYSIZE(filename); + picker.lpstrDefExt = L"txt"; + picker.lpstrTitle = caption; + picker.Flags = OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR; + if (!GetSaveFileNameW(&picker)) { + const DWORD error = CommDlgExtendedError(); + if (!error) return false; + Add(session, L"Open save dialog", L"report", error); + } else if (extract_report::WriteUtf8(filename, session.text)) { + return true; + } else { + Add(session, L"Save report", filename, GetLastError()); + } + extract_report::WriteUtf8(session.path.c_str(), session.text); + const std::wstring message = std::wstring(failed) + L"\r\n\r\n" + session.path; + if (MessageBoxW(parent, message.c_str(), caption, MB_RETRYCANCEL | MB_ICONWARNING) != IDRETRY) return false; + } +} +// TaskDialog elides long paths even with soft break opportunities. Insert measured line breaks; +// the report keeps the exact path, and no private TaskDialog controls are resized or subclassed. +inline std::wstring WrapPaths(HWND parent, const std::wstring& text) { + NONCLIENTMETRICSW metrics{}; + metrics.cbSize = sizeof(metrics); + HFONT font = nullptr; + if (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof(metrics), &metrics, 0)) font = CreateFontIndirectW(&metrics.lfMessageFont); + HDC dc = GetDC(parent); + HGDIOBJ previous = font && dc ? SelectObject(dc, font) : nullptr; + SIZE alphabet{}; + int pixels = 0; + if (font && dc && GetTextExtentPoint32W(dc, L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 52, &alphabet)) + pixels = MulDiv(static_cast(Width(parent)) - 32, (alphabet.cx / 26 + 1) / 2, 4); + std::wstring result; + for (size_t start = 0; start < text.size();) { + const size_t newline = text.find(L'\n', start); + const size_t end = newline == std::wstring::npos ? text.size() : newline; + const std::wstring line = text.substr(start, end - start); + if (line.find(L":\\") == std::wstring::npos) result += line; + else { + for (size_t offset = 0; offset < line.size();) { + size_t count = 0, separator = 0; + while (offset + count < line.size()) { + SIZE size{}; + const bool measured = pixels > 0 && GetTextExtentPoint32W(dc, line.c_str() + offset, static_cast(count + 1), &size); + if (count && (measured ? size.cx > pixels : count >= 24)) break; + if (line[offset + count] == L'\\') separator = count + 1; + ++count; + } + if (offset + count < line.size() && separator) count = separator; + if (count > 1 && offset + count < line.size() && IS_HIGH_SURROGATE(line[offset + count - 1])) --count; + result.append(line, offset, count); + offset += count; + if (offset < line.size()) result += L"\r\n"; + } + } + if (newline != std::wstring::npos) result += L'\n'; + start = end + 1; + } + if (previous) SelectObject(dc, previous); + if (dc) ReleaseDC(parent, dc); + if (font) DeleteObject(font); + return result; +} +// mode 1 confirms old-directory cleanup; mode 2 allows retry; other modes only close/save. +inline int Show(HWND parent, Session& session, int mode, LPCWSTR title, LPCWSTR heading, + LPCWSTR body, LPCWSTR primary, LPCWSTR save, LPCWSTR failed) { + const bool persisted = extract_report::WriteUtf8(session.path.c_str(), session.text); + const std::wstring content = WrapPaths(parent, std::wstring(body) + (mode != 1 && persisted ? L"\r\n\r\n" + session.path : L"")); + using TaskDialogFn = HRESULT(WINAPI*)(const TASKDIALOGCONFIG*, int*, int*, BOOL*); + HMODULE library = LoadLibraryW(L"comctl32.dll"); + auto dialog = library ? reinterpret_cast(GetProcAddress(library, "TaskDialogIndirect")) : nullptr; + int pressed = IDCANCEL; + for (;;) { + TASKDIALOG_BUTTON buttons[] = {{1001, primary}, {1002, save}}; + TASKDIALOGCONFIG config{}; + config.cbSize = sizeof(config); + config.hwndParent = parent; + config.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW; + config.dwCommonButtons = mode == 1 ? TDCBF_CANCEL_BUTTON : TDCBF_CLOSE_BUTTON; + if (mode == 2) config.dwCommonButtons |= TDCBF_RETRY_BUTTON; + config.pszWindowTitle = title; + config.pszMainInstruction = heading; + config.pszContent = content.c_str(); + config.cButtons = 1; + config.pButtons = mode == 1 ? buttons : buttons + 1; + config.nDefaultButton = mode == 1 ? IDCANCEL : IDCLOSE; + config.cxWidth = Width(parent); + const HRESULT result = dialog ? dialog(&config, &pressed, nullptr, nullptr) : E_NOTIMPL; + if (FAILED(result)) { + // Failing to create confirmation UI must never grant deletion permission. + if (mode == 1) { MessageBoxW(parent, body, heading, MB_OK | MB_ICONWARNING); pressed = IDCANCEL; } + else { + pressed = MessageBoxW(parent, content.c_str(), heading, mode == 2 ? MB_RETRYCANCEL : MB_OK); + if (pressed != IDRETRY && MessageBoxW(parent, save, title, MB_YESNO | MB_DEFBUTTON2) == IDYES) + Save(parent, session, save, failed); + } + break; + } + if (pressed != 1002) break; + Save(parent, session, save, failed); + } + if (library) FreeLibrary(library); + return pressed; +} + +// Pin every ancestor and reject shell roots/ancestors before any payload removal. +inline DWORD Prepare(Session& session, LPCWSTR directory, LPCWSTR protectedRoot, bool& homeFailure) { + std::wstring path; + if (!uninstall_data::Normalize(directory, path)) return ERROR_INVALID_NAME; + if (protectedRoot && *protectedRoot) { + homeFailure = true; + std::wstring home; + if (!uninstall_data::NormalizeHome(protectedRoot, home)) return ERROR_INVALID_NAME; + if (uninstall_data::Contains(path, home) || uninstall_data::Contains(home, path)) return ERROR_ACCESS_DENIED; + homeFailure = false; + } + const KNOWNFOLDERID* folders[] = {&FOLDERID_Profile, &FOLDERID_RoamingAppData, &FOLDERID_LocalAppData, + &FOLDERID_Desktop, &FOLDERID_Documents, &FOLDERID_Downloads, &FOLDERID_Pictures, &FOLDERID_Music, + &FOLDERID_Videos, &FOLDERID_Public, &FOLDERID_ProgramData, &FOLDERID_Windows, &FOLDERID_ProgramFiles, &FOLDERID_ProgramFilesX86}; + WCHAR nativePrograms[32768]; + DWORD bytes = sizeof(nativePrograms); + if (RegGetValueW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", L"ProgramFilesDir", + RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY, nullptr, nativePrograms, &bytes) != ERROR_SUCCESS) return ERROR_ACCESS_DENIED; + if (uninstall_data::Contains(path, nativePrograms)) return ERROR_ACCESS_DENIED; + for (const auto* id : folders) { + PWSTR value = nullptr; + const HRESULT result = SHGetKnownFolderPath(*id, KF_FLAG_DONT_VERIFY, nullptr, &value); + if (FAILED(result)) return ERROR_ACCESS_DENIED; + const bool unsafe = uninstall_data::Contains(path, value) + || (id == &FOLDERID_Windows && uninstall_data::Contains(value, path)); + CoTaskMemFree(value); + if (unsafe) return ERROR_ACCESS_DENIED; + } + for (size_t end = path.find(L'\\', 3);; end = path.find(L'\\', end + 1)) { + const DWORD error = uninstall_data::Pin(end == std::wstring::npos ? path : path.substr(0, end), session.pinned); + if (error) return error; + if (end == std::wstring::npos) break; + } + return ERROR_SUCCESS; +} +// The executable goes first. A failure leaves every other file, including the retry uninstaller, in place. +inline DWORD Payload(Session& session, LPCWSTR directory, LPCWSTR executable, LPCWSTR uninstaller) { + if (session.mainBlocked) { + session.text += L"\r\nRetrying main executable removal; preceding failure is historical.\r\n"; + session.issues = false; + session.mainBlocked = false; + } + const std::wstring main = std::wstring(directory) + L"\\" + executable; + const DWORD attributes = GetFileAttributesW((L"\\\\?\\" + main).c_str()); + DWORD error = ERROR_SUCCESS; + if (attributes == INVALID_FILE_ATTRIBUTES) { + error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) error = ERROR_SUCCESS; + } else if (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) error = ERROR_ACCESS_DENIED; + else error = uninstall_data::Unlink(L"\\\\?\\" + main, attributes); + if (error) { session.mainBlocked = true; Add(session, L"Remove main executable; remaining cleanup not executed", main.c_str(), error); return error; } + WIN32_FIND_DATAW entry{}; + HANDLE search = FindFirstFileW((std::wstring(L"\\\\?\\") + directory + L"\\*").c_str(), &entry); + if (search == INVALID_HANDLE_VALUE) { error = GetLastError(); Add(session, L"Enumerate payload; result incomplete", directory, error); return error; } + uninstall_data::Failures failures; + do { + if (wcscmp(entry.cFileName, L".") == 0 || wcscmp(entry.cFileName, L"..") == 0 || _wcsicmp(entry.cFileName, uninstaller) == 0) continue; + uninstall_data::RemoveTree(std::wstring(directory) + L"\\" + entry.cFileName, &failures); + } while (FindNextFileW(search, &entry)); + error = GetLastError(); + FindClose(search); + Collect(session, failures); + if (error != ERROR_NO_MORE_FILES) { Add(session, L"Enumerate payload; result incomplete", directory, error); return error; } + return ERROR_SUCCESS; +} +} + +extern "C" __declspec(dllexport) uninstall_report::Session* __cdecl UninstallBegin(LPCWSTR path) { + // Session storage and callbacks must outlive System plug-in calls. + HMODULE module = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + reinterpret_cast(&UninstallBegin), &module)) return nullptr; + auto* session = new (std::nothrow) uninstall_report::Session; + if (session) session->path = path; + return session; +} +extern "C" __declspec(dllexport) DWORD __cdecl UninstallPrepare(uninstall_report::Session* session, LPCWSTR path, LPCWSTR home) { + bool homeFailure = false; + const DWORD error = uninstall_report::Prepare(*session, path, home, homeFailure); + if (error) uninstall_report::Add(*session, homeFailure ? L"Validate DSH_HOME; no deletion started" : L"Validate removal scope; no deletion started", homeFailure ? home : path, error); + return error; +} +extern "C" __declspec(dllexport) DWORD __cdecl UninstallPayload(uninstall_report::Session* session, LPCWSTR path, LPCWSTR executable, LPCWSTR uninstaller) { + const DWORD error = uninstall_report::Payload(*session, path, executable, uninstaller); + return !error ? 0 : session->mainBlocked ? 1 : 2; +} +extern "C" __declspec(dllexport) void __cdecl UninstallData(uninstall_report::Session* session, LPCWSTR path, LPCWSTR installation, LPCWSTR home) { + uninstall_data::Failures failures; + const DWORD error = uninstall_data::Remove(path, installation, home, &failures); + if (error && failures.empty()) uninstall_report::Add(*session, L"Remove data directory", path, error); + uninstall_report::Collect(*session, failures); +} +extern "C" __declspec(dllexport) void __cdecl UninstallNote(uninstall_report::Session* session, LPCWSTR text) { + session->issues = true; + session->text += std::wstring(L"\r\n") + text + L"\r\n"; +} +extern "C" __declspec(dllexport) int __cdecl UninstallShow(uninstall_report::Session* session, HWND parent, int mode, + LPCWSTR title, LPCWSTR heading, LPCWSTR body, LPCWSTR primary, LPCWSTR save, LPCWSTR failed) { + return uninstall_report::Show(parent, *session, mode, title, heading, body, primary, save, failed); +} +extern "C" __declspec(dllexport) int __cdecl UninstallFinish(uninstall_report::Session* session, LPCWSTR directory, LPCWSTR uninstaller) { + const std::wstring file = std::wstring(directory) + L"\\" + uninstaller; + const DWORD attributes = GetFileAttributesW((L"\\\\?\\" + file).c_str()); + if (attributes != INVALID_FILE_ATTRIBUTES) { + const DWORD error = uninstall_data::Unlink(L"\\\\?\\" + file, attributes); + if (error) uninstall_report::Add(*session, L"Remove uninstaller", file.c_str(), error); + } else { + const DWORD error = GetLastError(); + if (error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND) + uninstall_report::Add(*session, L"Inspect uninstaller", file.c_str(), error); + } + for (HANDLE handle : session->pinned.values) CloseHandle(handle); + session->pinned.values.clear(); + if (!RemoveDirectoryW((std::wstring(L"\\\\?\\") + directory).c_str())) { + const DWORD error = GetLastError(); + if (error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND) uninstall_report::Add(*session, L"Remove installation directory", directory, error); + } + session->text += L"\r\nPayload removal completed. Failed or unverified items are listed above.\r\n"; + if (session->issues || GetFileAttributesW(session->path.c_str()) != INVALID_FILE_ATTRIBUTES) extract_report::WriteUtf8(session->path.c_str(), session->text); + return session->issues ? 1 : 0; +} +extern "C" __declspec(dllexport) void __cdecl UninstallPersist(uninstall_report::Session* session) { + extract_report::WriteUtf8(session->path.c_str(), session->text); +} +extern "C" __declspec(dllexport) void __cdecl UninstallImport(uninstall_report::Session* session, LPCWSTR path) { + const std::wstring report = extract_report::ReadOutput(path); + if (!report.empty()) { session->issues = true; session->text += L"\r\n" + report; } +} + +extern "C" __declspec(dllexport) int __cdecl UninstallShowOwner(uninstall_report::Session* session, HWND parent, + LPCWSTR title, LPCWSTR heading, LPCWSTR registered, LPCWSTR directory, LPCWSTR registeredLabel, + LPCWSTR scopeLabel, LPCWSTR primary, LPCWSTR save, LPCWSTR failed) { + const std::wstring body = std::wstring(registeredLabel) + L"\r\n" + registered + L"\r\n\r\n" + + scopeLabel + L"\r\n" + directory; + return uninstall_report::Show(parent, *session, 1, title, heading, body.c_str(), primary, save, failed); +} diff --git a/apps/desktop/installer/uninstall.nsh b/apps/desktop/installer/uninstall.nsh index defdd15923..151d9c7b04 100644 --- a/apps/desktop/installer/uninstall.nsh +++ b/apps/desktop/installer/uninstall.nsh @@ -2,15 +2,121 @@ !include FileFunc.nsh Var UnTarget Var UnHome +Var UnSession +Var UnDirectoryOnly +Var UnReportPath +Var UnHeading +Var UnBody +Var UnMode +Var UnResult +Var UnRegistered +Var UnRegistrationArguments +Var UnRegistrationEligible +Var UnCleanupResult + +Function un.ShowCleanup + System::Call '$PLUGINSDIR\window-frame.dll::UninstallPersist(p $UnSession) ?c' + StrCpy $UnResult 0 + ${IfNot} ${Silent} + ${If} $UnMode == 1 + System::Call '$PLUGINSDIR\window-frame.dll::UninstallShowOwner(p $UnSession, p $HWNDPARENT, w "$(^SetupCaption)", w "$UnHeading", w "$UnRegistered", w "$INSTDIR", w "$(INSTALLER_UNINSTALL_REGISTERED)", w "$(INSTALLER_UNINSTALL_SCOPE)", w "$(INSTALLER_UNINSTALL_CONTINUE)", w "$(INSTALLER_UNINSTALL_SAVE)", w "$(INSTALLER_UNINSTALL_SAVE_FAILED)") i.r0 ?c' + ${Else} + System::Call '$PLUGINSDIR\window-frame.dll::UninstallShow(p $UnSession, p $HWNDPARENT, i $UnMode, w "$(^SetupCaption)", w "$UnHeading", w "$UnBody", w "$(INSTALLER_UNINSTALL_CONTINUE)", w "$(INSTALLER_UNINSTALL_SAVE)", w "$(INSTALLER_UNINSTALL_SAVE_FAILED)") i.r0 ?c' + ${EndIf} + StrCpy $UnResult $0 + ${EndIf} +FunctionEnd + +Function un.BeginCleanup + ${If} ${isUpdated} + Return + ${EndIf} + InitPluginsDir + File "/oname=$PLUGINSDIR\window-frame.dll" "${INSTALLER_BUILD_DIR}\window-frame.dll" + System::Call 'kernel32::GetCurrentProcessId() i.r0' + StrCpy $UnReportPath "$TEMP\DeepSeek-Harness-uninstall-$0.txt" + System::Call '$PLUGINSDIR\window-frame.dll::UninstallBegin(w "$UnReportPath") p.r0 ?c' + StrCpy $UnSession $0 + ${If} $UnSession == 0 + MessageBox MB_OK|MB_ICONEXCLAMATION "$(INSTALLER_UI_ERROR)" /SD IDOK + SetErrorLevel 2 + Quit + ${EndIf} + ReadEnvStr $UnHome DSH_HOME + System::Call '$PLUGINSDIR\window-frame.dll::UninstallPrepare(p $UnSession, w "$INSTDIR", w "$UnHome") i.r0 ?c' + ${If} $0 != 0 + StrCpy $UnMode 4 + StrCpy $UnHeading "$(INSTALLER_UNINSTALL_INCOMPLETE)" + StrCpy $UnBody "$(INSTALLER_UNINSTALL_UNSAFE)$\r$\n$INSTDIR" + Call un.ShowCleanup + SetErrorLevel 2 + Quit + ${EndIf} + ReadRegStr $UnRegistered SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation + ${If} $UnRegistered != "" + GetFullPathName $UnRegistered "$UnRegistered\." + GetFullPathName $0 "$INSTDIR\." + ${If} $UnRegistered != $0 + StrCpy $UnMode 1 + StrCpy $UnHeading "$(INSTALLER_UNINSTALL_OWNER)" + Call un.ShowCleanup + ${If} $UnResult != 1001 + System::Call '$PLUGINSDIR\window-frame.dll::UninstallNote(p $UnSession, w "Removal not confirmed; no deletion started. Registered installation: $UnRegistered. Uninstall directory: $INSTDIR.") ?c' + System::Call '$PLUGINSDIR\window-frame.dll::UninstallPersist(p $UnSession) ?c' + SetErrorLevel 2 + Quit + ${EndIf} + StrCpy $UnDirectoryOnly 1 + ${EndIf} + ${EndIf} + SetOutPath $TEMP + cleanupRetry: + System::Call '$PLUGINSDIR\window-frame.dll::UninstallPayload(p $UnSession, w "$INSTDIR", w "${APP_EXECUTABLE_FILENAME}", w "${UNINSTALL_FILENAME}") i.r0 ?c' + ${If} $0 != 0 + StrCpy $UnMode 4 + StrCpy $UnHeading "$(INSTALLER_UNINSTALL_INCOMPLETE)" + StrCpy $UnBody "$(INSTALLER_UNINSTALL_UNKNOWN)$\r$\n$INSTDIR" + ${If} $0 == 1 + StrCpy $UnMode 2 + StrCpy $UnBody "$(INSTALLER_UNINSTALL_BLOCKED)$\r$\n$INSTDIR\${APP_EXECUTABLE_FILENAME}" + ${EndIf} + Call un.ShowCleanup + ${If} $UnResult == 4 + Goto cleanupRetry + ${EndIf} + SetErrorLevel 2 + Quit + ${EndIf} +FunctionEnd + +Function un.FinishCleanup + ${If} ${isUpdated} + Return + ${EndIf} + System::Call '$PLUGINSDIR\window-frame.dll::UninstallFinish(p $UnSession, w "$INSTDIR", w "${UNINSTALL_FILENAME}") i.r0 ?c' + StrCpy $UnCleanupResult $0 + ${If} $UnRegistrationEligible == 1 + StrCpy $UnRegistrationArguments "-UnownedOnly" + Call un.RunRegistrationCleanup + ${EndIf} + ${If} $UnCleanupResult != 0 + DetailPrint $UnReportPath + StrCpy $UnMode 3 + StrCpy $UnHeading "$(INSTALLER_UNINSTALL_COMPLETE)" + StrCpy $UnBody "$(INSTALLER_UNINSTALL_REGISTRATION)" + Call un.ShowCleanup + ${EndIf} +FunctionEnd ; The helper refuses unsafe roots, the installation and the Harness home, and never descends into reparse points; -; a locked file leaves residue and never fails the uninstall. customCheckAppRunning extracts window-frame.dll first. +; failed auxiliary removals are recorded while other siblings continue. Function un.RemoveData - System::Call '$PLUGINSDIR\window-frame.dll::UninstallRemoveData(w "$UnTarget", w "$INSTDIR", w "$UnHome") ?c' + System::Call '$PLUGINSDIR\window-frame.dll::UninstallData(p $UnSession, w "$UnTarget", w "$INSTDIR", w "$UnHome") ?c' FunctionEnd Function un.CleanData ${If} ${isUpdated} + ${OrIf} $UnDirectoryOnly == 1 Return ${EndIf} ; The installer runs an older uninstaller with /KEEP_APP_DATA when replacing it from another directory. @@ -34,3 +140,59 @@ Function un.CleanData StrCpy $UnTarget "$LOCALAPPDATA\${DSH_UPDATER_CACHE_NAME}" Call un.RemoveData FunctionEnd + +; Upgrade replacement retains integrations; KEEP_APP_DATA controls only user data. +!define /ifndef DSH_COMMAND_ENVIRONMENT_KEY "Environment" +!define /ifndef DSH_COMMAND_OWNER_KEY "Software\DeepSeekHarness\Command" +!define /ifndef DSH_PROTOCOL_KEY "Software\Classes\dsh" +!define /ifndef DSH_COMMAND_MUTEX "default" +Function un.CleanRegistration + ${If} ${isUpdated} + Return + ${EndIf} + ReadRegStr $0 SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}" InstallLocation + ${If} $0 == "" + ; Preserve shared state and check each Windows entry against its own target. + StrCpy $UnDirectoryOnly 1 + ${Else} + GetFullPathName $0 "$0\." + GetFullPathName $1 "$INSTDIR\." + ${If} $0 != $1 + StrCpy $UnDirectoryOnly 1 + ${EndIf} + ${EndIf} + Delete "$PLUGINSDIR\unowned-path" + StrCpy $UnRegistrationArguments "" + ${If} $UnDirectoryOnly == 1 + StrCpy $UnRegistrationArguments '-DesktopLink "$oldDesktopLink" -StartMenuLink "$oldStartMenuLink" -UninstallKey "${UNINSTALL_REGISTRY_KEY}" -UninstallerName "${UNINSTALL_FILENAME}"' + !ifdef UNINSTALL_REGISTRY_KEY_2 + StrCpy $UnRegistrationArguments '$UnRegistrationArguments -LegacyUninstallKey "${UNINSTALL_REGISTRY_KEY_2}"' + !endif + ${EndIf} + Call un.RunRegistrationCleanup + IfFileExists "$PLUGINSDIR\unowned-path" 0 +2 + StrCpy $UnRegistrationEligible 1 +FunctionEnd + +Function un.RunRegistrationCleanup + InitPluginsDir + File /oname=$PLUGINSDIR\command-path.ps1 "${__FILEDIR__}\..\scripts\command-path.ps1" + File /oname=$PLUGINSDIR\uninstall-registration.ps1 "${__FILEDIR__}\..\scripts\uninstall-registration.ps1" + Delete "$PLUGINSDIR\registration-report.txt" + nsExec::ExecToStack '"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$PLUGINSDIR\uninstall-registration.ps1" -Directory "$INSTDIR" -ExecutableName "${APP_EXECUTABLE_FILENAME}" -EnvironmentKey "${DSH_COMMAND_ENVIRONMENT_KEY}" -OwnerKey "${DSH_COMMAND_OWNER_KEY}" -ProtocolKey "${DSH_PROTOCOL_KEY}" -ReportPath "$PLUGINSDIR\registration-report.txt" -MutexName "${DSH_COMMAND_MUTEX}" -UnownedMarker "$PLUGINSDIR\unowned-path" $UnRegistrationArguments' + Pop $0 + Pop $1 + System::Call '$PLUGINSDIR\window-frame.dll::UninstallImport(p $UnSession, w "$PLUGINSDIR\registration-report.txt") ?c' + ${If} $0 != 0 + StrCpy $UnCleanupResult 1 + DetailPrint $1 + ${If} $UnDirectoryOnly == 1 + ${AndIf} $UnRegistrationArguments != "-UnownedOnly" + System::Call '$PLUGINSDIR\window-frame.dll::UninstallNote(p $UnSession, w "[unverified] Registration cleanup targets: HKCU\${UNINSTALL_REGISTRY_KEY}; $oldDesktopLink; $oldStartMenuLink") ?c' + !ifdef UNINSTALL_REGISTRY_KEY_2 + System::Call '$PLUGINSDIR\window-frame.dll::UninstallNote(p $UnSession, w "[unverified] Registration cleanup target: HKCU\${UNINSTALL_REGISTRY_KEY_2}") ?c' + !endif + ${EndIf} + System::Call '$PLUGINSDIR\window-frame.dll::UninstallNote(p $UnSession, w "Registration cleanup failed or did not return a result. Exit: $0. Targets: HKCU\${DSH_COMMAND_ENVIRONMENT_KEY} [Path]; HKCU\${DSH_COMMAND_OWNER_KEY}; HKCU\${DSH_PROTOCOL_KEY}. Unverified registrations may remain.") ?c' + ${EndIf} +FunctionEnd diff --git a/apps/desktop/installer/window-frame.cpp b/apps/desktop/installer/window-frame.cpp index 9e3c760f29..210f11b2f9 100644 --- a/apps/desktop/installer/window-frame.cpp +++ b/apps/desktop/installer/window-frame.cpp @@ -33,6 +33,7 @@ static HRESULT ApplyInstallerDwmFrame(HWND window) { #include "extract-report.h" #include "directory-report.h" #include "uninstall-data.h" +#include "uninstall-report.h" using namespace Gdiplus; diff --git a/apps/desktop/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml index c623d2fb8f..228f07da88 100644 --- a/apps/desktop/packaging/README.i18n.yaml +++ b/apps/desktop/packaging/README.i18n.yaml @@ -45,8 +45,8 @@ en: b42f103358d0dfd7 zh: a534164ad9eb00da /desktop-packaging/runtime-file-selection-and-installation-checks: - en: da4669b98c79ee48 - zh: d007e87f13ff54d3 + en: 1d153e4ba7528414 + zh: cdf15fb80099ce17 /desktop-packaging/desktop-runtime-preparation: en: 84be38ab3136fff7 zh: bb4ed12ee0e1dfa0 diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md index e2619f0237..d8aa7714ee 100644 --- a/apps/desktop/packaging/README.md +++ b/apps/desktop/packaging/README.md @@ -262,7 +262,7 @@ Windows release qualification also runs [directory and replacement checks](../sc pwsh -NoProfile -File apps/desktop/scripts/smoke-windows.ps1 -Makensis $Makensis -SevenZip $SevenZip -PluginDir $PluginDir -FrameLibrary apps/desktop/.desktop-build/targets/win-x64/installer-ui/window-frame.dll ``` -The Windows installer checks for a running application at startup and after destination selection, before extracting the new version beside the installation directory. It checks again before replacing directories through same-volume renames. A running application blocks installation; update launches allow up to ten seconds for it to exit. Same-path upgrades preserve the old directory until promotion succeeds; extraction failure leaves it intact, and promotion failure attempts to restore it. The installer removes the old backup before launch. Forced termination or power loss can leave `.new-*` or `.old-*` directories; installation-location and scope migrations retain electron-builder's old-uninstaller flow. +The Windows installer checks for a running application at startup and after destination selection, before extracting the new version beside the installation directory. It checks again before replacing directories through same-volume renames. A running application blocks installation; update launches allow up to ten seconds for it to exit. Same-path upgrades preserve the old directory until promotion succeeds; extraction failure leaves it intact, and promotion failure attempts to restore it. The installer removes the old backup before launch. Forced termination or power loss can leave `.new-*` or `.old-*` directories; installation-location and scope migrations retain electron-builder's old-uninstaller flow, using extended paths for both file moves and rollback. Directory renames, empty-destination removal, and restoration retry Windows errors 5, 32, and 33 up to ten attempts, with 250 ms increasing delays (11.25 seconds of total waiting per operation). Other errors stop immediately. A replacement failure reports the Windows error, affected paths, and restoration outcome in `directory-failure-.log` beside extraction reports. If restoration fails, the installer removes unlocked staging files and preserves the backup. After reporting that failure, exit cleanup does not retry restoration. Keep the backup path named in the report and contact support before reinstalling. Silent installs save the same diagnostic without a dialog. diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md index cc6da7e75c..bdffd46c99 100644 --- a/apps/desktop/packaging/README.zh.md +++ b/apps/desktop/packaging/README.zh.md @@ -262,7 +262,7 @@ Windows 发布验收还需在 Desktop 构建后手动运行[目录和替换检 pwsh -NoProfile -File apps/desktop/scripts/smoke-windows.ps1 -Makensis $Makensis -SevenZip $SevenZip -PluginDir $PluginDir -FrameLibrary apps/desktop/.desktop-build/targets/win-x64/installer-ui/window-frame.dll ``` -Windows 安装器在启动时和选定目标目录后检查应用是否正在运行,通过检查后才将新版本解压到安装目录旁边。通过同卷目录改名替换前,安装器会再次检查。运行中的应用会阻止安装;更新启动允许等待应用退出,最长十秒。同路径升级在替换成功前保留旧目录;解压失败时旧版不变,替换失败时尝试恢复旧目录。安装器在启动前清理旧版备份。强制结束安装器或断电可能留下 `.new-*` 或 `.old-*` 目录;不同安装位置或安装范围迁移仍使用 electron-builder 的旧卸载器流程。 +Windows 安装器在启动时和选定目标目录后检查应用是否正在运行,通过检查后才将新版本解压到安装目录旁边。通过同卷目录改名替换前,安装器会再次检查。运行中的应用会阻止安装;更新启动允许等待应用退出,最长十秒。同路径升级在替换成功前保留旧目录;解压失败时旧版不变,替换失败时尝试恢复旧目录。安装器在启动前清理旧版备份。强制结束安装器或断电可能留下 `.new-*` 或 `.old-*` 目录;不同安装位置或安装范围迁移仍使用 electron-builder 的旧卸载器流程,文件移动与失败恢复均使用扩展路径。 目录改名、空目标目录删除和旧版恢复遇到 Windows 错误 5、32 或 33 时最多尝试十次,每次等待递增 250 毫秒(每个操作合计等待 11.25 秒)。其他错误立即停止。替换失败时,安装器将 Windows 错误、相关路径和恢复结果写入解压报告旁的 `directory-failure-<时间戳>.log`。如果恢复失败,安装器会清理未被占用的暂存文件并保留备份。上报此失败后,退出清理不再重试恢复。请保留报告所列的备份目录,并在重新安装前联系支持人员。静默安装保存相同的诊断,不显示弹窗。 diff --git a/apps/desktop/publishing/ci/README.i18n.yaml b/apps/desktop/publishing/ci/README.i18n.yaml index 7d9a3d1d4a..0e8c926ed0 100644 --- a/apps/desktop/publishing/ci/README.i18n.yaml +++ b/apps/desktop/publishing/ci/README.i18n.yaml @@ -15,8 +15,8 @@ en: 37d76f8473b967b7 zh: d211cc54af96672d /desktop-ci-publication/setup-sequence: - en: 2be541ef35a092a4 - zh: 77d87c00deb45758 + en: 4a7458326bb10b10 + zh: e48c2345ebd54aac /desktop-ci-publication/runner-labels-and-queue-diagnosis: en: d2195ee7581b74ec zh: 0b9847afe9a2a373 @@ -24,8 +24,8 @@ en: 0f43f2e193e95043 zh: 1c1efb062c06f7b8 /desktop-ci-publication/package-and-publish: - en: 6325c71df74a9915 - zh: edaa8a4502ed80a1 + en: 2b75de75308c7729 + zh: 1b09a6edd8c7e9b0 /desktop-ci-publication/rollout-and-website-publication: en: b6c39cec0946d5f4 zh: 3a6014ffbbec81f1 diff --git a/apps/desktop/publishing/ci/README.md b/apps/desktop/publishing/ci/README.md index 4b65c1eec2..f182d27b4a 100644 --- a/apps/desktop/publishing/ci/README.md +++ b/apps/desktop/publishing/ci/README.md @@ -28,7 +28,7 @@ Use this sequence when onboarding a dedicated machine. The deployment operator o 1. Prepare a runner-owned checkout and an external configuration directory. Follow [Windows machine setup and signing](../../windows-signing/README.md#machine-setup) or [macOS runner and signing setup](../../packaging/README.md#macos-actions) for tools, templates and platform credentials. 2. Register the runner using GitHub **Settings → Actions → Runners**, or the organization's runner administration page. Record its exact registered name, grant this repository access to its runner group, and assign the [required labels](#runner-labels). Keep the default labels during registration. -3. Install and start the platform supervisor described in the platform guide. Windows Task Scheduler and the macOS LaunchAgent require the configured user's login; they do not provide unattended startup before login. Confirm both GitHub connectivity and `Listening for Jobs`, then check the runner is online in GitHub. +3. Install and start the platform supervisor described in the platform guide. Windows supports optional Boot tasks for startup before login; its default Interactive task and the macOS LaunchAgent require the configured user's desktop login. Confirm both GitHub connectivity and `Listening for Jobs`, then check the runner is online in GitHub. 4. Complete [machine publication configuration](#machine-setup), the repository's `DESKTOP_PUBLISH_RUNNERS` variable, and the two deployment Environments. The repository administrator owns routing and reviewers; the COS administrator owns bucket configuration and object read/write permissions; production also needs the configured GitHub App. 5. Run a signed Windows or notarized macOS **test** package using [Package and publish](#package-and-publish). Confirm the packaging job used the intended registered runner and retained its files. Dispatch publication from `master` with that run ID and attempt; confirm `prepare` actually starts on the same machine and produces the approval summary. 6. Inspect the summary's environment, version, channel and URLs before approving the test upload. Verify the publication record, public installer download and update feed. Test acceptance does not establish production permissions: provision and approve production separately. Keep the run/attempt and acceptance results for recovery. @@ -69,6 +69,8 @@ Environment approval gates this workflow, not arbitrary code running under the s ## Package and publish +The Windows packaging run shows a Chinese parameter summary with the requested source, environment, channel, version mode, signing mode, compression, test release ID and cache namespace, plus the workflow identity, checked-out commit, resolved version and runner. Once workflow helpers are staged, earlier failures still produce the summary with unavailable results labeled explicitly. The summary reads no machine configuration; a blank test release ID is shown as machine-default selection, not its resolved value. It does not establish build, signature or publication success. + The publication form accepts an optional `staging_percentage` integer from 0 to 100. It applies to the retained package’s channel (nightly or stable), appears in the approval summary, and is included in the published YAML and audit record without modifying retained artifacts. Leave it blank for the packaged default (normally full rollout). Completed publications cannot change this percentage through a retry; same-version feed conflicts remain errors. For publication to either test or production, choose Windows `signing=signed` or leave macOS **Skip notarization** unchecked. Unsigned and unnotarized packages are only for internal debugging; they cannot publish or provide automatic updates. Before installing dependencies, the hosted routing job rejects debugging artifacts identified by the selected run and attempt. An archive-only rerun retains the original build attempt in artifact names, so this early check can miss it; local manifest qualification still rejects debugging builds before publication. Missing artifact metadata does not establish eligibility: the original machine still validates its retained manifest and signatures. A debugging-package rejection requires a new signed/notarized package and its run ID / attempt; retrying publication cannot qualify the existing bytes. diff --git a/apps/desktop/publishing/ci/README.zh.md b/apps/desktop/publishing/ci/README.zh.md index 097eeb4298..529238486e 100644 --- a/apps/desktop/publishing/ci/README.zh.md +++ b/apps/desktop/publishing/ci/README.zh.md @@ -28,7 +28,7 @@ description: "在专用 macOS 和 Windows runner 上发布留存的 Desktop 安 1. 准备 runner 专用 checkout 和仓库外的配置目录。按 [Windows 机器与签名配置](../../windows-signing/README.zh.md#machine-setup)或 [macOS runner 与签名配置](../../packaging/README.zh.md#macos-actions)准备工具、模板和平台凭据。 2. 通过 GitHub **Settings → Actions → Runners** 或组织的 runner 管理页面注册 runner。记录准确的注册名称,允许本仓库访问其 runner group,并分配[必需标签](#runner-labels)。注册时保留默认标签。 -3. 按平台指南安装并启动守护任务。Windows 计划任务和 macOS LaunchAgent 都要求配置的用户登录,不能在登录前无人值守启动。确认已连接 GitHub 且出现 `Listening for Jobs`,再检查 GitHub 中 runner 在线。 +3. 按平台指南安装并启动守护任务。Windows 可选 Boot 任务支持登录前启动;默认 Interactive 任务和 macOS LaunchAgent 仍要求配置的用户登录桌面。确认已连接 GitHub 且出现 `Listening for Jobs`,再检查 GitHub 中 runner 在线。 4. 完成[本机发布配置](#machine-setup)、仓库变量 `DESKTOP_PUBLISH_RUNNERS` 和两个部署 Environment。仓库管理员负责路由与审批人;COS 管理员负责桶配置及对象读写权限;production 还需要配置 GitHub App。 5. 按[打包与发布](#package-and-publish)完成一次 Windows 已签名或 macOS 已公证的 **test** 打包。确认打包 job 使用预期的注册 runner 并留存文件。从 `master` 发起发布,填写该 run ID 和 attempt;确认 `prepare` 确实在同一台机器上启动并生成审批摘要。 6. 审核摘要中的环境、版本、频道和 URL 后,再批准测试上传。验证发布记录、公开安装包下载和升级 feed。test 验收不能证明 production 权限可用:production 需独立配置与审批。保留 run/attempt 和验收结果,供故障恢复使用。 @@ -69,6 +69,8 @@ Environment 审批限制此工作流,不限制同一机器账户运行的任 ## 打包与发布 +Windows 打包运行会展示中文参数摘要,列出请求的源码、环境、通道、版本模式、签名方式、压缩等级、测试 release ID 和缓存命名空间,以及工作流标识、检出提交、解析版本和 runner。工作流辅助脚本暂存成功后,即使前序步骤失败仍会生成摘要,并明确标记尚未取得的结果。摘要不读取机器配置;测试 release ID 留空时仅显示选择了机器默认值,不展示其解析值。摘要不代表构建、签名或发布成功。 + 发布表单支持可选的 `staging_percentage`,取值为 0 到 100 的整数。该值作用于保留包所属的 nightly 或 stable 渠道,显示在审批摘要中,并写入发布的 YAML 和审计记录,不修改保留产物。留空沿用包内默认值(通常为全量)。已完成的发布不能通过重试修改比例;同版本清单内容冲突仍会报错。 发布到 test 或 production 都必须在 Windows 选择 `signing=signed`,或在 macOS 不勾选**跳过公证**。无签名、无公证的包仅限内部调试,不能发布或用于自动更新。托管路由 job 会在安装依赖前,依据所选 run 和 attempt 对应的 artifact 名称拒绝已标明的调试包。仅重跑归档时,artifact 名称保留原构建 attempt,早期检查可能未识别该包;本地清单资格校验仍会在发布前拒绝调试包。缺少 artifact 元数据不代表允许发布:原机器仍会验证留存清单和签名。遇到调试包拒绝提示时,需重新完成签名或公证,再使用新包的 run ID / attempt 发布;重跑发布不能使现有产物获得发布资格。 diff --git a/apps/desktop/scripts/command-path.ps1 b/apps/desktop/scripts/command-path.ps1 index 4e1da931a3..3b4807cc92 100644 --- a/apps/desktop/scripts/command-path.ps1 +++ b/apps/desktop/scripts/command-path.ps1 @@ -1,6 +1,7 @@ <# Per-user PATH ownership. The worker owns its mutex through registry publication. #> function Invoke-DshCommandPath { - param([hashtable]$Request, [string]$EnvironmentKey, [string]$OwnerKey, [string]$MachinePath, [string]$MutexName) + param([hashtable]$Request, [string]$EnvironmentKey, [string]$OwnerKey, [string]$MachinePath, [string]$MutexName, + [string]$RemovedInstallation) $ErrorActionPreference = 'Stop' function Fail([string]$Code, [string]$Message) { $error = [InvalidOperationException]::new($Message) @@ -50,6 +51,23 @@ function Invoke-DshCommandPath { $current = Comparable $directory $old = if ($owned) { Comparable ([string]$owned) } else { $null } $kept = $parts + # Unowned PATH cleanup is restricted to the exact CLI directory of an absent installation. + if ($RemovedInstallation -and $Request.operation -eq 'remove' -and -not $old) { + if (-not [IO.Path]::IsPathRooted($RemovedInstallation) -or + $current -ne (Comparable (Join-Path $RemovedInstallation 'resources\runtime\cli\bin'))) { + Fail 'EINVAL' 'The command directory does not belong to the removed installation.' + } + $matches = @($parts | Where-Object { (Comparable $_) -eq $current }) + if ($matches.Count) { + $absent = $false + try { [void][IO.File]::GetAttributes($RemovedInstallation) } catch { + $cause = $_.Exception.GetBaseException() + if (($cause.HResult -band 0xffff) -in @(2, 3)) { $absent = $true } else { throw } + } + if (-not $absent) { Fail 'EEXIST' 'The installation directory remains; unowned PATH entries were retained.' } + $kept = @($parts | Where-Object { (Comparable $_) -ne $current }) + } + } if ($old -and ($Request.operation -eq 'install' -or ($Request.operation -eq 'remove' -and $old -eq $current))) { $ownedMatches = @($parts | Where-Object { $_ -ceq $owned }).Count if ($ownedMatches -gt $retained) { diff --git a/apps/desktop/scripts/desktop-toolchain-preflight.ts b/apps/desktop/scripts/desktop-toolchain-preflight.ts index ff855cfd09..da0f06a8ec 100644 --- a/apps/desktop/scripts/desktop-toolchain-preflight.ts +++ b/apps/desktop/scripts/desktop-toolchain-preflight.ts @@ -14,6 +14,8 @@ import { tmpdir } from 'node:os' import { basename, dirname, join } from 'node:path' import { promisify } from 'node:util' +import { scrubWindowsSigningEnvironment } from './windows-sign.mjs' + const run = promisify(execFile) /** One tool the packaging run requires, and what went wrong with it. */ @@ -45,6 +47,14 @@ async function probeTar(): Promise { async function probeWindowsInstallerToolchain(environment: NodeJS.ProcessEnv): Promise { const failures: DesktopToolchainProbeFailure[] = [] + try { + await run('pwsh', ['-NoProfile', '-NonInteractive', '-Command', + '$ErrorActionPreference="Stop"; if ($PSVersionTable.PSVersion.Major -lt 7) { throw "PowerShell 7 or newer is required" }; Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop; Get-Command Get-AuthenticodeSignature -ErrorAction Stop | Out-Null'], + { env: scrubWindowsSigningEnvironment(environment), windowsHide: true, timeout: 20_000 }) + } + catch (error) { + failures.push({ tool: 'pwsh', detail: `PowerShell 7 with Authenticode support must be available on PATH: ${error instanceof Error ? error.message : String(error)}` }) + } const programFiles = environment['ProgramFiles(x86)'] const vswhere = programFiles === undefined ? undefined diff --git a/apps/desktop/scripts/installer.nsh b/apps/desktop/scripts/installer.nsh index 3c4b0f93ed..3504771056 100644 --- a/apps/desktop/scripts/installer.nsh +++ b/apps/desktop/scripts/installer.nsh @@ -94,6 +94,8 @@ ManifestDPIAware true !macroend !macro customUnInstall + Call un.BeginCleanup + Call un.CleanRegistration Call un.CleanData !macroend @@ -172,6 +174,10 @@ ManifestDPIAware true !macroend !macro customCheckAppRunning + !ifdef BUILD_UNINSTALLER + ; Manual uninstall reports deletion errors with retry and a saveable report. + ${If} ${isUpdated} + !endif !ifdef BUILD_UNINSTALLER InitPluginsDir File "/oname=$PLUGINSDIR\window-frame.dll" "${INSTALLER_BUILD_DIR}\window-frame.dll" @@ -200,6 +206,9 @@ ManifestDPIAware true SetErrorLevel 2 Quit ${EndIf} + !ifdef BUILD_UNINSTALLER + ${EndIf} + !endif !macroend !macro customInstallerDirectoryFailed diff --git a/apps/desktop/scripts/prepare-windows-installer.ps1 b/apps/desktop/scripts/prepare-windows-installer.ps1 index 5195891033..e073e16926 100644 --- a/apps/desktop/scripts/prepare-windows-installer.ps1 +++ b/apps/desktop/scripts/prepare-windows-installer.ps1 @@ -1,4 +1,4 @@ -<# Compile the x86 DWM helper and raster assets embedded in the NSIS installer. #> +<# Compile the x86 DWM helper and raster assets embedded in the NSIS installer. #> [CmdletBinding()] param([string]$OutputDirectory, [switch]$TestProgress, [switch]$CompileProgressOnly) $ErrorActionPreference = 'Stop' @@ -14,7 +14,7 @@ $visualStudio = & $vswhere -latest -products '*' -requires Microsoft.VisualStudi if (-not $visualStudio) { throw 'Visual Studio C++ Build Tools are missing.' } $vcvars = Join-Path $visualStudio 'VC/Auxiliary/Build/vcvars32.bat' $compileScript = Join-Path $output 'compile-frame.cmd' -$compileLines = @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /LD /MT /O1 /W4 /WX /EHsc "{0}" /Fo"{1}" /link /OUT:"{2}" /IMPLIB:"{3}" user32.lib gdi32.lib comctl32.lib dwmapi.lib gdiplus.lib ole32.lib shell32.lib uuid.lib advapi32.lib' -f $source, (Join-Path $output 'window-frame.obj'), $library, (Join-Path $output 'window-frame.lib'))) +$compileLines = @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /LD /MT /O1 /W4 /WX /EHsc "{0}" /Fo"{1}" /link /OUT:"{2}" /IMPLIB:"{3}" user32.lib gdi32.lib comdlg32.lib comctl32.lib dwmapi.lib gdiplus.lib ole32.lib shell32.lib uuid.lib advapi32.lib' -f $source, (Join-Path $output 'window-frame.obj'), $library, (Join-Path $output 'window-frame.lib'))) [IO.File]::WriteAllLines($compileScript, $compileLines, [Text.Encoding]::Default) & $env:ComSpec /d /c $compileScript if ($LASTEXITCODE -ne 0) { throw 'Native installer helper compilation failed.' } @@ -23,7 +23,7 @@ if ($TestProgress -or $CompileProgressOnly) { # UAC installer detection demands elevation from unmanifested executables named after installation. $cleanupExecutable = Join-Path $output 'data-cleanup-test.exe' $cleanupScript = Join-Path $output 'compile-data-cleanup-test.cmd' - [IO.File]::WriteAllLines($cleanupScript, @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /MT /W4 /WX /EHsc "{0}" /Fo"{1}" /Fe"{2}" /link shell32.lib ole32.lib uuid.lib advapi32.lib' -f $cleanupSource, (Join-Path $output 'data-cleanup-test.obj'), $cleanupExecutable)), [Text.Encoding]::Default) + [IO.File]::WriteAllLines($cleanupScript, @('@echo off', ('call "{0}" >nul' -f $vcvars), 'if errorlevel 1 exit /b %errorlevel%', ('cl /nologo /MT /W4 /WX /EHsc "{0}" /Fo"{1}" /Fe"{2}" /link "{3}" shell32.lib ole32.lib uuid.lib advapi32.lib' -f $cleanupSource, (Join-Path $output 'data-cleanup-test.obj'), $cleanupExecutable, (Join-Path $output 'window-frame.lib'))), [Text.Encoding]::Default) & $env:ComSpec /d /c $cleanupScript if ($LASTEXITCODE -ne 0) { throw 'Uninstall data test compilation failed.' } if ($TestProgress) { diff --git a/apps/desktop/scripts/run-windows-runner-task.ps1 b/apps/desktop/scripts/run-windows-runner-task.ps1 index 56371e970c..51b8890b97 100644 --- a/apps/desktop/scripts/run-windows-runner-task.ps1 +++ b/apps/desktop/scripts/run-windows-runner-task.ps1 @@ -4,17 +4,17 @@ $runnerRoot = [IO.Path]::GetFullPath((Split-Path -Parent $PSScriptRoot)).TrimEnd $digest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($runnerRoot.ToUpperInvariant()))) $taskName = 'DSH-Packaging-' + $digest.Substring(0,16) $log = Join-Path $PSScriptRoot ('run-' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ') + '-' + $PID + '.log') +$attemptReserved = $false try { $config = Get-Content -LiteralPath (Join-Path $PSScriptRoot 'config.json') -Raw | ConvertFrom-Json $attemptFile = Join-Path $PSScriptRoot 'attempts.txt' $attempts = [int](Get-Content -LiteralPath $attemptFile -Raw) if ($attempts -lt 0 -or $config.RestartCount -lt 1 -or $config.RestartCount -gt 999) { throw 'Invalid restart budget; reinstall the task.' } if ($attempts -gt $config.RestartCount) { - $null = Disable-ScheduledTask -TaskName $config.TaskName -TaskPath '\' - Set-Content -LiteralPath $log -Value 'Restart budget exhausted. Task disabled; inspect runner logs, fix the cause and run start.' - exit 1 + throw 'Restart budget exhausted; inspect runner logs, fix the cause and run start.' } Set-Content -LiteralPath $attemptFile -Value ($attempts + 1) + $attemptReserved = $true $startup = Join-Path $PSScriptRoot 'start.ps1' if ($config.NetworkRoot) { if (-not (Test-Path -LiteralPath (Join-Path $config.ConfigRoot 'runner-network.json') -PathType Leaf)) { throw 'Owned network supervision requires runner-network.json.' } @@ -27,10 +27,25 @@ try { # An unexpected exit is a task failure even when run.cmd hides the listener's nonzero status; the log retains its code. exit 1 } catch { - # A missing or unwritable counter cannot bound retries; the task name must not depend on readable configuration. - $null = Disable-ScheduledTask -TaskName $taskName -TaskPath '\' - $message = 'Runner task failed: ' + $_.Exception.Message + $failure = $_.Exception.Message + $disposition = 'Scheduled recovery remains bounded by the persisted attempt budget.' + # Stop triggers when the budget is exhausted or an attempt could not be persisted. + if (-not $attemptReserved) { + try { + $scheduler = New-Object -ComObject 'Schedule.Service' + $scheduler.Connect() + $scheduler.GetFolder('\').GetTask($taskName).Enabled = $false + $disposition = 'Task disabled; inspect configuration and attempt storage before starting.' + } catch { + # A limited task account may lack permission to change its scheduler registration. + $disposition = 'Task disable failed; an administrator must disable its triggers. No runner was launched.' + } + } + $message = 'Runner task failed: ' + $failure + ' ' + $disposition [Console]::Error.WriteLine($message) - Add-Content -LiteralPath $log -Value $message + try { Add-Content -LiteralPath $log -Value $message } catch { + # The launcher captures stderr independently when the runner log is unavailable. + [Console]::Error.WriteLine('Runner log unavailable: ' + $_.Exception.Message) + } exit 1 } diff --git a/apps/desktop/scripts/test-windows-installer.mjs b/apps/desktop/scripts/test-windows-installer.mjs index 02e356b924..a3a711d76a 100644 --- a/apps/desktop/scripts/test-windows-installer.mjs +++ b/apps/desktop/scripts/test-windows-installer.mjs @@ -55,6 +55,8 @@ try { }) const { createElectronBuilderConfig } = await import('../electron-builder.config.mjs') const childOptions = { env: scrubWindowsSigningEnvironment(process.env), windowsHide: true, maxBuffer: 8 * 1024 * 1024 } + await execute('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', + join(appRoot, 'tests', 'windows-installer-process-test.ps1'), '-OutputDirectory', output], childOptions) await execute('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', join(appRoot, 'scripts', 'prepare-windows-installer.ps1'), '-OutputDirectory', join(output, 'ui'), '-CompileProgressOnly'], childOptions) const progressTest = join(output, 'ui', 'progress-test.exe') @@ -131,11 +133,12 @@ SectionEnd const strings = join(languageOutput, 'strings.nsh') await writeFile(strings, renderInstallerStrings([locale]), 'utf8') const include = join(languageOutput, 'include.nsh') - await writeFile(include, `!define INSTALLER_BUILD_DIR "${join(output, 'ui')}"\n!define INSTALLER_STRINGS_FILE "${strings}"\n!include "${join(appRoot, 'scripts', 'installer.nsh')}"\n`) + await writeFile(include, `!define DSH_COMMAND_MUTEX "Local\\DSHUninstallTests-${guid}"\n!define DSH_COMMAND_ENVIRONMENT_KEY "Software\\DSHUninstallTests\\${guid}\\CommandEnvironment"\n!define DSH_COMMAND_OWNER_KEY "Software\\DSHUninstallTests\\${guid}\\CommandOwner"\n!define DSH_PROTOCOL_KEY "Software\\Classes\\dsh-test-${guid}"\n!define INSTALLER_BUILD_DIR "${join(output, 'ui')}"\n!define INSTALLER_STRINGS_FILE "${strings}"\n!include "${join(appRoot, 'scripts', 'installer.nsh')}"\n`) await build({ projectDir: appRoot, prepackaged: payload, targets: Platform.WINDOWS.createTarget(['nsis'], Arch.x64), publish: 'never', config: { ...config, productName, extraMetadata: { ...config.extraMetadata, name: packageName }, artifactName: 'installer-test.exe', directories: { output: languageOutput }, - nsis: { ...config.nsis, guid, include, installerLanguages: [language] }, beforeBuild: undefined, afterPack: undefined, afterSign: undefined, artifactBuildCompleted: undefined }, + nsis: { ...config.nsis, guid, include, installerSidebar: join(output, 'ui', 'uninstaller-sidebar.bmp'), + uninstallerSidebar: join(output, 'ui', 'uninstaller-sidebar.bmp'), installerLanguages: [language] }, beforeBuild: undefined, afterPack: undefined, afterSign: undefined, artifactBuildCompleted: undefined }, }) if (process.argv.includes('--compile-only')) continue const result = await execute('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', diff --git a/apps/desktop/scripts/uninstall-registration.ps1 b/apps/desktop/scripts/uninstall-registration.ps1 new file mode 100644 index 0000000000..6dd01815d6 --- /dev/null +++ b/apps/desktop/scripts/uninstall-registration.ps1 @@ -0,0 +1,87 @@ +<# Remove only owned registrations; independently failed operations leave a diagnostic report. #> +param([Parameter(Mandatory)][string]$Directory, + [string]$ExecutableName = 'DeepSeek Harness.exe', + [Parameter(Mandatory)][string]$EnvironmentKey, + [Parameter(Mandatory)][string]$OwnerKey, + [Parameter(Mandatory)][string]$ProtocolKey, + [Parameter(Mandatory)][string]$ReportPath, + [string]$MutexName, + [switch]$UnownedOnly, + [string]$UnownedMarker, + [string]$DesktopLink, + [string]$StartMenuLink, + [string]$UninstallKey, + [string]$LegacyUninstallKey, + [string]$UninstallerName) +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'command-path.ps1') +$failures = [Collections.Generic.List[string]]::new() +try { + if (-not $MutexName -or $MutexName -eq 'default') { + $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $MutexName = 'Global\DeepSeekHarness.Command.' + $sid + } + $options = @{ EnvironmentKey=$EnvironmentKey; OwnerKey=$OwnerKey; MachinePath=''; MutexName=$MutexName } + $command = Join-Path $Directory 'resources\runtime\cli\bin' + $state = Invoke-DshCommandPath -Request @{operation='inspect'; directory=$command} @options + if ($UnownedOnly) { + if (-not $state.ownedDirectory) { + [void](Invoke-DshCommandPath -Request @{operation='remove'; directory=$command; expected=$state.fingerprint} @options -RemovedInstallation $Directory) + Send-DshCommandEnvironmentChange + } + } elseif ($state.managed) { + [void](Invoke-DshCommandPath -Request @{operation='remove'; directory=$command; expected=$state.fingerprint} @options) + Send-DshCommandEnvironmentChange + } elseif (-not $state.ownedDirectory -and $UnownedMarker) { + [IO.File]::WriteAllText($UnownedMarker, '') + } +} catch { + $failures.Add("[unverified] Remove owned command registration`r`nHKCU\$EnvironmentKey [Path]`r`nHKCU\$OwnerKey`r`nCode: $($_.Exception.HResult)`r`nReason: $($_.Exception.Message)") +} +if (-not $UnownedOnly) { try { + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($ProtocolKey + '\shell\open\command') + try { $registered = if ($key) { $key.GetValue('') } else { $null } } + finally { if ($key) { $key.Dispose() } } + $expected = '"' + (Join-Path $Directory $ExecutableName) + '" "%1"' + if ($registered -eq $expected) { + [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($ProtocolKey, $false) + } +} catch { + $failures.Add("[unverified] Remove protocol registration`r`nHKCU\$ProtocolKey`r`nCode: $($_.Exception.HResult)`r`nReason: $($_.Exception.Message)") +} } +foreach ($uninstallEntry in @($UninstallKey, $LegacyUninstallKey)) { + if (-not $uninstallEntry) { continue } + try { + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($uninstallEntry) + try { $registered = if ($key) { $key.GetValue('UninstallString') } else { $null } } + finally { if ($key) { $key.Dispose() } } + if ($null -eq $registered) { continue } + if ($registered -isnot [string]) { throw 'UninstallString is not a string' } + # Only the command emitted by the per-user installer is eligible for removal. + if ($registered -match '^\s*"([^"]+)"\s+/currentuser\s*$') { + $target = [IO.Path]::GetFullPath($Matches[1]) + $expected = [IO.Path]::GetFullPath((Join-Path $Directory $UninstallerName)) + if ($target -eq $expected) { + [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($uninstallEntry, $false) + } + } + } catch { + $failures.Add("[unverified] Inspect or remove uninstall entry`r`nHKCU\$uninstallEntry [UninstallString]`r`nCode: $($_.Exception.HResult)`r`nReason: $($_.Exception.Message)") + } +} +foreach ($link in @($DesktopLink, $StartMenuLink)) { + if (-not $link) { continue } + try { + if ([IO.Path]::GetExtension($link) -ne '.lnk' -or -not (Test-Path -LiteralPath $link -PathType Leaf)) { continue } + $shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut($link) + if ($shortcut.TargetPath -eq (Join-Path $Directory $ExecutableName)) { + [IO.File]::Delete($link) + } + } catch { + $failures.Add("[unverified] Remove shortcut: $link`r`nReason: $($_.Exception.Message)") + } +} +if ($failures.Count) { + [IO.File]::WriteAllText($ReportPath, ($failures -join "`r`n`r`n"), [Text.UTF8Encoding]::new($true)) + exit 1 +} diff --git a/apps/desktop/scripts/windows-directory-installer.d.mts b/apps/desktop/scripts/windows-directory-installer.d.mts index a9be087fe6..8038b103de 100644 --- a/apps/desktop/scripts/windows-directory-installer.d.mts +++ b/apps/desktop/scripts/windows-directory-installer.d.mts @@ -15,9 +15,16 @@ export function directoryInstallSection(source: string): string export function directoryInstallerExits(source: string): string /** - * Keep user-data removal in the native helper, which refuses unsafe roots and never follows links. + * Preserve data but clean old registrations when replacing another installation directory. + * @param source Pinned NSIS installUtil.nsh contents. + * @returns Helper reserving --updated for replacement at the same path. + */ +export function directoryInstallUtil(source: string): string + +/** + * Retain the original uninstall directory and bypass shared cleanup for directory-only removal. * @param source - Pinned upstream uninstaller source. - * @returns Uninstaller with long-path application removal and no upstream RMDir data removal. + * @returns Uninstaller with long-path removal, native data cleanup, and upgrade rollback; updated-mode ownership mismatches exit with code 2. */ export function directoryUninstaller(source: string): string diff --git a/apps/desktop/scripts/windows-directory-installer.mjs b/apps/desktop/scripts/windows-directory-installer.mjs index 8508730b47..45c890712c 100644 --- a/apps/desktop/scripts/windows-directory-installer.mjs +++ b/apps/desktop/scripts/windows-directory-installer.mjs @@ -52,6 +52,17 @@ export function directoryInstallerExits(source) { return source.replaceAll(/^(\s*)Quit\s*$/gm, '$1!ifndef BUILD_UNINSTALLER\n$1Call dshCleanupDirectories\n$1!endif\n$1Quit') } +/** + * Preserve data but clean old registrations when replacing another installation directory. + * @param {string} source - Pinned NSIS installUtil.nsh contents. + * @returns {string} Helper reserving --updated for replacement at the same path. + */ +export function directoryInstallUtil(source) { + return replaceOnce(source.replaceAll('\r\n', '\n'), + ' # always pass --updated flag - to ensure that if DELETE_APP_DATA_ON_UNINSTALL is defined, user data will be not removed\n StrCpy $0 "$0 --updated"', + ' # /KEEP_APP_DATA retains data during relocation; old path registrations must be removed.\n ${if} $installationDir == $INSTDIR\n StrCpy $0 "$0 --updated"\n ${endif}') +} + /** Install the build-only NSIS adapter without replacing electron-builder's signed bootstrap path. */ export function installWindowsDirectoryInstaller() { // The package entry initializes the platform classes before their mutually dependent leaves. @@ -74,7 +85,8 @@ export function installWindowsDirectoryInstaller() { let adapted = replaceOnce(source, '!include "installSection.nsh"', `!include "${section}"`) for (const helper of ['allowOnlyOneInstallerInstance.nsh', 'installUtil.nsh']) { const path = join(directory, helper) - await writeFile(path, directoryInstallerExits(await readFile(join(templates, 'include', helper), 'utf8'))) + const original = await readFile(join(templates, 'include', helper), 'utf8') + await writeFile(path, directoryInstallerExits(helper === 'installUtil.nsh' ? directoryInstallUtil(original) : original)) adapted = replaceOnce(adapted, `!include "${helper}"`, `!include "${path}"`) } const uninstaller = join(directory, 'uninstaller.nsh') @@ -85,14 +97,40 @@ export function installWindowsDirectoryInstaller() { } /** - * Keep user-data removal in the native helper, which refuses unsafe roots and never follows links. + * Retain the original uninstall directory and bypass shared cleanup for directory-only removal. * @param {string} source - Pinned upstream uninstaller source. - * @returns {string} Uninstaller with long-path application removal and no upstream RMDir data removal. + * @returns {string} Uninstaller with long-path removal, native data cleanup, and upgrade rollback; updated-mode ownership mismatches exit with code 2. */ export function directoryUninstaller(source) { - const normalized = source.replaceAll('\r\n', '\n') + let normalized = source.replaceAll('\r\n', '\n') + normalized = normalized.replaceAll('"$INSTDIR$R0', '"\\\\?\\$INSTDIR$R0') + .replaceAll('"$PLUGINSDIR\\old-install', '"\\\\?\\$PLUGINSDIR\\old-install') + normalized = replaceOnce(normalized, 'Function un.onInit\n', 'Var dshUninstallDirectory\nFunction un.onInit\n StrCpy $dshUninstallDirectory $INSTDIR\n') + normalized = replaceOnce(normalized, ' !insertmacro initMultiUser', ` !insertmacro initMultiUser + StrCpy $INSTDIR $dshUninstallDirectory + \${If} \${isUpdated} + ReadRegStr $R0 SHELL_CONTEXT "\${INSTALL_REGISTRY_KEY}" InstallLocation + GetFullPathName $R0 "$R0\\." + GetFullPathName $R1 "$INSTDIR\\." + \${If} $R0 != $R1 + SetErrorLevel 2 + Quit + \${EndIf} + \${EndIf}`) + const payloadStart = normalized.indexOf(' # delete the installed files\n') + const payloadEnd = normalized.indexOf(' ${ifNot} ${isKeepShortcuts}', payloadStart) + if (payloadStart < 0 || payloadEnd < 0) throw new Error('NSIS uninstaller payload template changed') + normalized = normalized.slice(0, payloadStart) + ' ${If} ${isUpdated}\n' + + normalized.slice(payloadStart, payloadEnd) + ' ${EndIf}\n' + + ' ${If} $UnDirectoryOnly == 1\n Goto dshUninstallFinished\n ${EndIf}\n' + + normalized.slice(payloadEnd) + normalized = replaceOnce(normalized, ' !ifdef ONE_CLICK\n !insertmacro quitSuccess', + 'dshUninstallFinished:\n Call un.FinishCleanup\n !ifdef ONE_CLICK\n !insertmacro quitSuccess') const start = normalized.indexOf(' Var /GLOBAL isDeleteAppData\n') const end = normalized.indexOf(' DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}"', start) if (start < 0 || end < 0) throw new Error('NSIS uninstaller data removal template changed') - return replaceOnce(normalized.slice(0, start) + normalized.slice(end), 'RMDir /r $INSTDIR', 'RMDir /r "\\\\?\\$INSTDIR"') + normalized = normalized.slice(0, start) + normalized.slice(end) + normalized = normalized.replaceAll(/^(\s*)(DeleteRegKey SHELL_CONTEXT "[^"]+"|Delete "\$old(?:Desktop|StartMenu)Link")$/gm, (_, indent, operation) => + `${indent}ClearErrors\n${indent}${operation}\n${indent}\${If} \${Errors}\n${indent} \${IfNot} \${isUpdated}\n${indent} System::Call '$PLUGINSDIR\\window-frame.dll::UninstallNote(p $UnSession, w "[unverified] ${operation.replaceAll('"', '')}") ?c'\n${indent} \${EndIf}\n${indent}\${EndIf}`) + return replaceOnce(normalized, 'RMDir /r $INSTDIR', 'RMDir /r "\\\\?\\$INSTDIR"') } diff --git a/apps/desktop/scripts/windows-packaging-summary.d.mts b/apps/desktop/scripts/windows-packaging-summary.d.mts new file mode 100644 index 0000000000..d369273144 --- /dev/null +++ b/apps/desktop/scripts/windows-packaging-summary.d.mts @@ -0,0 +1,7 @@ +/** Windows packaging parameter summary without machine configuration access. */ +/** + * Summarize allowlisted workflow inputs and resolved build identity. + * @param environment Workflow inputs and GitHub run identity. + * @returns Markdown tables without a build or signature success claim. + */ +export function windowsPackagingSummary(environment: NodeJS.ProcessEnv): string diff --git a/apps/desktop/scripts/windows-packaging-summary.mjs b/apps/desktop/scripts/windows-packaging-summary.mjs new file mode 100644 index 0000000000..c5f9d2aac4 --- /dev/null +++ b/apps/desktop/scripts/windows-packaging-summary.mjs @@ -0,0 +1,45 @@ +/** Render Windows packaging inputs and resolved build identity without loading machine configuration. */ +import { appendFile } from 'node:fs/promises' +import { realpathSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +function text(value) { + return value.replace(/[&<>"'|`\r\n\\*_\[\]()!~:]/gu, character => `&#${character.charCodeAt(0)};`) +} + +/** + * Summarize allowlisted workflow inputs separately from resolved checkout and version values. + * @param {NodeJS.ProcessEnv} environment Workflow inputs and GitHub run identity. + * @returns {string} Markdown parameter tables; no signature or publication success claim. + */ +export function windowsPackagingSummary(environment) { + const row = (label, value, fallback = '未提供') => `| ${label} | ${value ? `${text(value)}` : fallback} |` + return [ + '## Windows 打包参数', '', + '以下记录输入参数与已解析结果,不代表构建、签名或发布成功;执行结果以各步骤状态为准。', '', + '### 输入参数', '', '| 项目 | 选择值 |', '| --- | --- |', + row('源码 ref', environment.PACKAGE_SOURCE_REF), + row('环境', environment.DSH_PACKAGING_PRESET), + row('升级通道', environment.DSH_DESKTOP_UPDATE_CHANNEL), + row('版本模式', environment.PACKAGE_INPUT_VERSION_MODE), + row('手动版本号', environment.PACKAGE_BUILD_VERSION, '未填写'), + row('签名方式(请求)', environment.PACKAGE_SIGNING), + row('安装器压缩等级', environment.PACKAGE_WINDOWS_COMPRESSION_LEVEL), + row('测试 release ID(输入)', environment.PACKAGE_TEST_RELEASE_ID, '使用机器默认值(本摘要不读取)'), + row('缓存命名空间', environment.PACKAGE_CACHE_NAMESPACE, '共享缓存'), '', + '### 执行信息', '', '| 项目 | 已知值 |', '| --- | --- |', + row('平台', 'win-x64'), + row('工作流 ref', environment.GITHUB_WORKFLOW_REF), + row('工作流 SHA', environment.GITHUB_WORKFLOW_SHA), + row('检出源码 SHA', environment.PACKAGE_SOURCE_SHA, '尚未取得'), + row('解析后的版本号', environment.PACKAGE_VERSION, '尚未解析成功'), + row('Runner', environment.RUNNER_NAME), + row('运行 ID', environment.GITHUB_RUN_ID), + row('尝试次数', environment.GITHUB_RUN_ATTEMPT), '', + ].join('\n') +} + +if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) { + if (!process.env.GITHUB_STEP_SUMMARY) throw new Error('Windows packaging summary requires GITHUB_STEP_SUMMARY') + await appendFile(process.env.GITHUB_STEP_SUMMARY, windowsPackagingSummary(process.env)) +} diff --git a/apps/desktop/scripts/windows-runner-network.ps1 b/apps/desktop/scripts/windows-runner-network.ps1 index 9ab2491901..7112e200fd 100644 --- a/apps/desktop/scripts/windows-runner-network.ps1 +++ b/apps/desktop/scripts/windows-runner-network.ps1 @@ -48,7 +48,7 @@ function Wait-RunnerNetwork($Config) { $info.Environment['DSH_NETWORK_PROBE_TIMEOUT'] = [string]($Config.timeoutSeconds * 1000) $info.ArgumentList.Add('--input-type=module') $info.ArgumentList.Add('-e') - $info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exit(r.ok ? 0 : 1); } catch { process.exit(1); }') + $info.ArgumentList.Add('try { const r = await fetch(process.env.DSH_NETWORK_PROBE_URL, { method: "HEAD", redirect: "error", signal: AbortSignal.timeout(Number(process.env.DSH_NETWORK_PROBE_TIMEOUT)) }); await r.body?.cancel(); process.exitCode = r.ok ? 0 : 1; } catch { process.exitCode = 1; }') for ($attempt = 1; $attempt -le $Config.attempts; $attempt++) { $ready = $true if ($Config.serviceName) { diff --git a/apps/desktop/scripts/windows-runner-processes.cs b/apps/desktop/scripts/windows-runner-processes.cs new file mode 100644 index 0000000000..171f17798a --- /dev/null +++ b/apps/desktop/scripts/windows-runner-processes.cs @@ -0,0 +1,50 @@ +// Toolhelp snapshots expose parent IDs without the WMI namespace permissions required by CIM. +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; + +public static class DshRunnerProcesses +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct Entry + { + public uint Size, Usage, ProcessId; + public UIntPtr DefaultHeapId; + public uint ModuleId, Threads, ParentProcessId; + public int Priority; + public uint Flags; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string Name; + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processId); + [DllImport("kernel32.dll", EntryPoint = "Process32FirstW", SetLastError = true)] + private static extern bool First(IntPtr snapshot, ref Entry entry); + [DllImport("kernel32.dll", EntryPoint = "Process32NextW", SetLastError = true)] + private static extern bool Next(IntPtr snapshot, ref Entry entry); + [DllImport("kernel32.dll")] + private static extern bool CloseHandle(IntPtr handle); + + // These parent IDs select handles to await; taskkill retains termination authority over the live tree. + public static Dictionary ReadParents() + { + IntPtr snapshot = CreateToolhelp32Snapshot(2, 0); + if (snapshot == new IntPtr(-1)) throw new Win32Exception(Marshal.GetLastWin32Error()); + try + { + var result = new Dictionary(); + var entry = new Entry { Size = (uint)Marshal.SizeOf(typeof(Entry)) }; + bool found = First(snapshot, ref entry); + while (found) + { + result.Add((int)entry.ProcessId, (int)entry.ParentProcessId); + found = Next(snapshot, ref entry); + } + int error = Marshal.GetLastWin32Error(); + if (error != 18) throw new Win32Exception(error); + return result; + } + finally { CloseHandle(snapshot); } + } +} diff --git a/apps/desktop/scripts/windows-runner-scheduler.ps1 b/apps/desktop/scripts/windows-runner-scheduler.ps1 new file mode 100644 index 0000000000..4514ffba60 --- /dev/null +++ b/apps/desktop/scripts/windows-runner-scheduler.ps1 @@ -0,0 +1,72 @@ +# Build an unregistered runner task. Credentials are supplied only to the scheduler at installation. +function New-WindowsRunnerTaskDefinition($Scheduler, [string]$Sid, [string]$RunnerRoot, [string]$PowerShell, [int]$RestartMinutes, [ValidateSet('Interactive','Boot')][string]$StartupMode = 'Interactive') { + $definition = $Scheduler.NewTask(0) + $definition.RegistrationInfo.Description = "DSH packaging runner: $RunnerRoot; owner: $Sid" + $definition.Principal.UserId = $Sid + $definition.Principal.LogonType = if ($StartupMode -eq 'Boot') { 1 } else { 3 } # Password or InteractiveToken. + $definition.Principal.RunLevel = 0 # TASK_RUNLEVEL_LUA: the job does not inherit installer elevation. + $definition.Settings.Priority = 4 + $definition.Settings.Enabled = $false + $definition.Settings.MultipleInstances = 2 # TASK_INSTANCES_IGNORE_NEW + $definition.Settings.ExecutionTimeLimit = 'PT0S' + $definition.Settings.DisallowStartIfOnBatteries = $false + $definition.Settings.StopIfGoingOnBatteries = $false + if ($StartupMode -eq 'Boot') { + $null = $definition.Triggers.Create(8) # TASK_TRIGGER_BOOT + } else { + $logon = $definition.Triggers.Create(9) # TASK_TRIGGER_LOGON + $logon.UserId = $Sid + } + $recovery = $definition.Triggers.Create(1) # TASK_TRIGGER_TIME + $recovery.StartBoundary = (Get-Date).AddMinutes($RestartMinutes).ToString('yyyy-MM-ddTHH:mm:ss') + $recovery.Repetition.Interval = "PT${RestartMinutes}M" + $execution = $definition.Actions.Create(0) # TASK_ACTION_EXEC + $execution.Path = Join-Path $RunnerRoot 'dsh-task/launcher.exe' + $execution.Arguments = '"' + $PowerShell + '"' + $execution.WorkingDirectory = $RunnerRoot + return $definition +} + +# Prompt locally and submit once; credential-bearing COM failures must not reach diagnostics. +function Register-WindowsRunnerBootTask($Scheduler, [string]$TaskName, $Definition, [string]$Sid, [string]$RunAs) { + $credential = Get-Credential -UserName $RunAs -Message 'Windows account password for unattended runner startup (not the signing Token PIN)' + if (-not $credential -or $credential.UserName -ne $RunAs -or $credential.Password.Length -eq 0) { + throw 'Credential entry cancelled or account changed; no task was registered.' + } + try { + # COM avoids putting a plaintext password in command arguments or cmdlet parameter logging. + $null = $Scheduler.GetFolder('\').RegisterTaskDefinition($TaskName, $Definition, 2, $RunAs, $credential.GetNetworkCredential().Password, 1, "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$Sid)") + } catch { + # Registration may have committed before an error reached this caller. + $code = '0x{0:X8}' -f $_.Exception.GetBaseException().HResult + throw "Boot task registration failed ($code); registration outcome is unconfirmed. Inspect Task Scheduler, batch-logon policy and account credentials locally before retrying." + } finally { + $credential = $null + } +} + +# Validate machine-owned preparation data before credentials or scheduler registration. +function Assert-WindowsRunnerBootConfiguration($Config, [string]$Sid, [string]$RunnerRoot, [string]$TaskName) { + if ($Config.StartupMode -ne 'Boot' -or $Config.AccountSid -ne $Sid -or $Config.RunnerRoot -ne $RunnerRoot -or $Config.TaskName -ne $TaskName) { + throw 'Prepared Boot configuration does not match RunAs and RunnerRoot; prepare again as the runner account.' + } + if (($Config.RestartMinutes -isnot [int] -and $Config.RestartMinutes -isnot [long]) -or $Config.RestartMinutes -lt 1 -or $Config.RestartMinutes -gt 1440 -or $Config.PowerShell -isnot [string] -or $Config.PowerShell -notmatch '^[A-Za-z]:[\\/]' -or -not (Test-Path -LiteralPath $Config.PowerShell -PathType Leaf) -or -not (Test-Path -LiteralPath (Join-Path $RunnerRoot 'dsh-task/launcher.exe') -PathType Leaf)) { + throw 'Prepared Boot startup files or restart interval are invalid; prepare again as the runner account.' + } +} + +# Missing tasks are distinct from denied or unavailable scheduler access. +function Get-WindowsRunnerTask($Scheduler, [string]$TaskName) { + try { return $Scheduler.GetFolder('\').GetTask($TaskName) } catch { + if ($_.Exception.GetBaseException().HResult -eq -2147024894) { return $null } + throw + } +} + +# Unreadable process locations must reject maintenance just like missing locations. +function Get-WindowsRunnerProcessPath($Process) { + try { return $Process.Path } catch { + # Access-denied and exited-process errors cannot establish an unrelated location. + return $null + } +} diff --git a/apps/desktop/scripts/windows-runner-task.ps1 b/apps/desktop/scripts/windows-runner-task.ps1 index e940eef988..3bb086b9e8 100644 --- a/apps/desktop/scripts/windows-runner-task.ps1 +++ b/apps/desktop/scripts/windows-runner-task.ps1 @@ -1,18 +1,21 @@ -# Manage a registered packaging runner in the current user's interactive Windows session. +# Prepare startup files and manage runner tasks; Boot registration requires an administrator. [CmdletBinding()] param( - [Parameter(Mandatory=$true)][ValidateSet('install','start','stop','status','uninstall')][string]$Action, + [Parameter(Mandatory=$true)][ValidateSet('install','register-boot','start','stop','status','uninstall')][string]$Action, [Parameter(Mandatory=$true)][string]$RunnerRoot, [string]$ConfigRoot, [string]$NetworkRoot, + [ValidateSet('Interactive','Boot')][string]$StartupMode = 'Interactive', + [string]$RunAs, [ValidateRange(1,1440)][int]$RestartMinutes = 1, [ValidateRange(1,999)][int]$RestartCount = 10 ) $ErrorActionPreference = 'Stop' if (-not $IsWindows) { throw 'This command requires PowerShell 7 on Windows.' } -if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) { - throw 'ConfigRoot, NetworkRoot, RestartMinutes and RestartCount apply only to install; reinstall to change them.' +if ($Action -ne 'install' -and @('ConfigRoot','NetworkRoot','StartupMode','RestartMinutes','RestartCount').Where({ $PSBoundParameters.ContainsKey($_) }).Count) { + throw 'Configuration and retry options apply only to install; reinstall to change them.' } +if ($Action -ne 'register-boot' -and $PSBoundParameters.ContainsKey('RunAs')) { throw 'RunAs applies only to register-boot.' } if ($RunnerRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'RunnerRoot must be an absolute local directory.' } $RunnerRoot = [IO.Path]::GetFullPath($RunnerRoot).TrimEnd('\','/') if (-not (Test-Path -LiteralPath (Join-Path $RunnerRoot '.runner') -PathType Leaf)) { throw 'Register the runner before managing its task.' } @@ -23,11 +26,46 @@ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value $digest = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($RunnerRoot.ToUpperInvariant()))) $taskName = 'DSH-Packaging-' + $digest.Substring(0,16) $serviceDir = Join-Path $RunnerRoot 'dsh-task' -$task = Get-ScheduledTask -TaskPath '\' | Where-Object TaskName -eq $taskName -if ($task -and $task.Description -ne "DSH packaging runner: $RunnerRoot; owner: $sid") { throw 'Task ownership differs; inspect it in Task Scheduler.' } +if ($Action -eq 'register-boot') { + if (-not $RunAs) { throw 'Boot registration requires -RunAs with the prepared runner account.' } + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + if (-not ([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + throw 'Boot registration requires an elevated PowerShell; the runner account remains limited.' + } + $sid = ([Security.Principal.NTAccount]::new($RunAs)).Translate([Security.Principal.SecurityIdentifier]).Value + if ($sid -in @('S-1-5-18','S-1-5-19','S-1-5-20') -or $sid.EndsWith('-500')) { throw 'Use a dedicated runner account, not a built-in service or Administrator account.' } +} +. (Join-Path $PSScriptRoot 'windows-runner-scheduler.ps1') +$scheduler = New-Object -ComObject 'Schedule.Service' +$scheduler.Connect() +$task = Get-WindowsRunnerTask $scheduler $taskName +if ($task -and $task.Definition.RegistrationInfo.Description -ne "DSH packaging runner: $RunnerRoot; owner: $sid") { throw 'Task ownership differs; inspect it in Task Scheduler.' } + +if ($Action -in @('install','register-boot')) { + if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' } + # Pause dispatch before migration; never overwrite a live startup snapshot. + foreach ($process in @(Get-Process | Where-Object { $_.ProcessName -in @('Runner.Listener','Runner.Worker') })) { + $path = Get-WindowsRunnerProcessPath $process + if (-not $path -or $path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { + throw 'A runner process is active or its location is unreadable. Pause dispatch and stop its supervisor before installing.' + } + } + if (Test-Path -LiteralPath (Join-Path $RunnerRoot '.service')) { throw 'A native runner service is configured; inspect and remove it before task migration.' } + if ((Test-Path -LiteralPath $serviceDir) -and ((Get-Item -LiteralPath $serviceDir).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Task directory cannot be a link.' } +} +if ($Action -eq 'register-boot') { + # This elevated path only registers a limited task; it never executes runner-owned files. + $configFile = Join-Path $serviceDir 'config.json' + if ((Get-Item -LiteralPath $configFile).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Task configuration cannot be a link.' } + $config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json + Assert-WindowsRunnerBootConfiguration $config $sid $RunnerRoot $taskName + $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $config.PowerShell $config.RestartMinutes 'Boot' + Register-WindowsRunnerBootTask $scheduler $taskName $definition $sid $RunAs + Write-Output "Registered disabled Boot task $taskName. Run start as the runner account. Logs: $serviceDir" + exit 0 +} if ($Action -eq 'install') { - if ($task) { throw 'Task already installed; stop and uninstall before reinstalling.' } if (-not $ConfigRoot -or $ConfigRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'Install requires an absolute ConfigRoot.' } $ConfigRoot = [IO.Path]::GetFullPath($ConfigRoot) $pwsh = Join-Path $PSHOME 'pwsh.exe' @@ -56,46 +94,47 @@ if ($Action -eq 'install') { foreach ($helper in @('windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $PSScriptRoot $helper) -Destination (Join-Path $serviceDir $helper) } - @{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8 + @{ RunnerRoot = $RunnerRoot; ConfigRoot = $ConfigRoot; NetworkRoot = $NetworkRoot; TaskName = $taskName; RestartCount = $RestartCount; StartupMode = $StartupMode; AccountSid = $sid; PowerShell = $pwsh; RestartMinutes = $RestartMinutes } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Encoding utf8 Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0' - $execution = New-ScheduledTaskAction -Execute $launcher -Argument ('"' + $pwsh + '"') -WorkingDirectory $RunnerRoot - $principal = New-ScheduledTaskPrincipal -UserId $sid -LogonType Interactive -RunLevel Limited - $trigger = @( - (New-ScheduledTaskTrigger -AtLogOn -User $sid), - (New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes($RestartMinutes) -RepetitionInterval (New-TimeSpan -Minutes $RestartMinutes)) - ) - $settings = New-ScheduledTaskSettingsSet -Priority 4 -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries - $settings.Enabled = $false - $null = Register-ScheduledTask -TaskName $taskName -TaskPath '\' -Action $execution -Principal $principal -Trigger $trigger -Settings $settings -Description "DSH packaging runner: $RunnerRoot; owner: $sid" + if ($StartupMode -eq 'Boot') { + Write-Output "Prepared Boot startup for account $sid. An administrator must run register-boot with RunnerRoot and RunAs; no task was registered." + exit 0 + } + $definition = New-WindowsRunnerTaskDefinition $scheduler $sid $RunnerRoot $pwsh $RestartMinutes 'Interactive' + $null = $scheduler.GetFolder('\').RegisterTaskDefinition($taskName, $definition, 2, $sid, $null, 3, $null) Write-Output "Installed disabled task $taskName. Run start while logged in; reboot requires desktop login. Logs: $serviceDir" exit 0 } if (-not $task) { throw 'Task is not installed for this runner directory.' } switch ($Action) { 'status' { - $info = Get-ScheduledTaskInfo -InputObject $task + $bootTrigger = $false + for ($index = 1; $index -le $task.Definition.Triggers.Count; $index++) { + if ($task.Definition.Triggers.Item($index).Type -eq 8) { $bootTrigger = $true } + } $launches = [int](Get-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Raw) $config = Get-Content -LiteralPath (Join-Path $serviceDir 'config.json') -Raw | ConvertFrom-Json - [pscustomobject]@{ TaskName = $taskName; State = $task.State; LastRunTime = $info.LastRunTime; LastTaskResult = $info.LastTaskResult; Launches = $launches; RemainingLaunches = [Math]::Max(0, 1 + $config.RestartCount - $launches); Logs = $serviceDir } + [pscustomobject]@{ TaskName = $taskName; State = @('Unknown','Disabled','Queued','Ready','Running')[[int]$task.State]; Account = $task.Definition.Principal.UserId; LogonType = @('None','Password','S4U','Interactive','Group','ServiceAccount','InteractiveOrPassword')[[int]$task.Definition.Principal.LogonType]; BootTrigger = $bootTrigger; LastRunTime = $task.LastRunTime; LastTaskResult = $task.LastTaskResult; Launches = $launches; RemainingLaunches = [Math]::Max(0, 1 + $config.RestartCount - $launches); Logs = $serviceDir } } 'start' { - if ($task.State -eq 'Running') { Write-Output "$taskName is already running."; break } + if ($task.State -eq 4) { Write-Output "$taskName is already running."; break } Set-Content -LiteralPath (Join-Path $serviceDir 'attempts.txt') -Value '0' - $null = Enable-ScheduledTask -InputObject $task - Start-ScheduledTask -InputObject $task + $task.Enabled = $true + $null = $task.Run($null) Write-Output "Start requested for $taskName. Verify Connected to GitHub and Listening for Jobs in $serviceDir." } 'stop' { # Operators pause workflow dispatch first; this local check cannot reserve an idle GitHub runner. - $workers = Get-CimInstance Win32_Process -Filter "Name = 'Runner.Worker.exe'" + $workers = Get-Process | Where-Object ProcessName -eq 'Runner.Worker' foreach ($worker in $workers) { - if (-not $worker.ExecutablePath -or $worker.ExecutablePath.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { + $path = Get-WindowsRunnerProcessPath $worker + if (-not $path -or $path.StartsWith($RunnerRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'A runner job is active or its location is unreadable. Wait for completion before stopping.' } } - $null = Disable-ScheduledTask -InputObject $task - $task = Get-ScheduledTask -TaskName $taskName -TaskPath '\' - if ($task.State -eq 'Running') { + $task.Enabled = $false + $task = Get-WindowsRunnerTask $scheduler $taskName + if ($task.State -eq 4) { $recordFile = Join-Path $serviceDir 'process.json' if (-not (Test-Path -LiteralPath $recordFile)) { throw 'Running task process identity is unavailable. Automatic starts are disabled; inspect the task before stopping it.' } $record = Get-Content -LiteralPath $recordFile -Raw | ConvertFrom-Json @@ -104,13 +143,14 @@ switch ($Action) { throw 'Running task process identity is unavailable. Automatic starts are disabled; inspect the task before stopping it.' } # Parent IDs can be reused; this snapshot supplies wait handles, not termination authority. - $processes = @(Get-CimInstance Win32_Process) + if (-not ('DshRunnerProcesses' -as [type])) { Add-Type -Path (Join-Path $PSScriptRoot 'windows-runner-processes.cs') } + $processes = [DshRunnerProcesses]::ReadParents() $ownedIds = [Collections.Generic.HashSet[int]]::new() $null = $ownedIds.Add($owner.Id) do { $added = $false - foreach ($process in $processes) { - if ($ownedIds.Contains([int]$process.ParentProcessId) -and $ownedIds.Add([int]$process.ProcessId)) { $added = $true } + foreach ($process in $processes.GetEnumerator()) { + if ($ownedIds.Contains([int]$process.Value) -and $ownedIds.Add([int]$process.Key)) { $added = $true } } } while ($added) $owned = @(foreach ($ownedId in $ownedIds) { Get-Process -Id $ownedId -ErrorAction SilentlyContinue }) @@ -120,19 +160,19 @@ switch ($Action) { if (-not $process.WaitForExit(30000)) { throw 'Runner task child remains alive; inspect it before restarting.' } } } - Stop-ScheduledTask -InputObject $task + $task.Stop(0) $deadline = [DateTime]::UtcNow.AddSeconds(30) do { - $state = (Get-ScheduledTask -TaskName $taskName -TaskPath '\').State - if ($state -ne 'Running') { break } + $state = (Get-WindowsRunnerTask $scheduler $taskName).State + if ($state -ne 4) { break } Start-Sleep -Milliseconds 200 } while ([DateTime]::UtcNow -lt $deadline) - if ($state -eq 'Running') { throw 'Task remains running; inspect its processes before further maintenance.' } + if ($state -eq 4) { throw 'Task remains running; inspect its processes before further maintenance.' } Write-Output "Stopped and disabled $taskName. Run start to enable automatic starts again." } 'uninstall' { - if ($task.State -ne 'Disabled') { throw 'Stop the task before uninstalling.' } - Unregister-ScheduledTask -InputObject $task -Confirm:$false + if ($task.State -ne 1) { throw 'Stop the task before uninstalling.' } + $scheduler.GetFolder('\').DeleteTask($taskName, 0) Write-Output "Uninstalled $taskName. Registration, configuration and logs remain in $RunnerRoot." } } diff --git a/apps/desktop/scripts/windows-runtime-signature.mjs b/apps/desktop/scripts/windows-runtime-signature.mjs index 9f79547b34..c85a23fbda 100644 --- a/apps/desktop/scripts/windows-runtime-signature.mjs +++ b/apps/desktop/scripts/windows-runtime-signature.mjs @@ -9,13 +9,12 @@ import { inspectSignaturesBatched } from './windows-signature-batch.mjs' import { packagingStep } from './packaging-step.mjs' /** - * Read Windows trust, timestamp and signer identity using the engine's bundled modules, without accessing the private key. + * Read Windows trust, timestamp and signer identity using PowerShell 7's bundled modules, without accessing the private key. * @param {string} path File to inspect. * @returns {Promise<{status: string, timestamped: boolean, thumbprint: string | null}>} Authenticode verification result. */ export async function inspectWindowsRuntimeSignature(path) { - // Node can inherit PowerShell 7's module search path while launching Windows PowerShell 5. - const { stdout, stderr } = await promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', + const { stdout, stderr } = await promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-Command', '$ErrorActionPreference="Stop"; [Console]::OutputEncoding=[System.Text.UTF8Encoding]::new(); Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1" -ErrorAction Stop; Import-Module "$PSHOME/Modules/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1" -ErrorAction Stop; $s=Get-AuthenticodeSignature -LiteralPath $env:DSH_RUNTIME_VERIFY_FILE; [pscustomobject]@{status=[string]$s.Status;timestamped=($null -ne $s.TimeStamperCertificate);thumbprint=$s.SignerCertificate.Thumbprint}|ConvertTo-Json -Compress'], { env: { ...scrubWindowsSigningEnvironment(process.env), DSH_RUNTIME_VERIFY_FILE: path }, encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024, diff --git a/apps/desktop/scripts/windows-signature-batch.mjs b/apps/desktop/scripts/windows-signature-batch.mjs index cbc37b9d30..4b54428c45 100644 --- a/apps/desktop/scripts/windows-signature-batch.mjs +++ b/apps/desktop/scripts/windows-signature-batch.mjs @@ -1,4 +1,4 @@ -/** Bounded public-key verification batches; every output row must match its requested file. */ +/** Bounded PowerShell 7 public-key verification batches; every output row must match its requested file. */ import { execFile } from 'node:child_process' import { promisify } from 'node:util' import { scrubWindowsSigningEnvironment } from './windows-sign.mjs' @@ -27,7 +27,7 @@ export function parseSignatureRows(stdout, stderr, files) { } async function inspectBatch(files) { - const pending = promisify(execFile)('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', command], { + const pending = promisify(execFile)('pwsh', ['-NoProfile', '-NonInteractive', '-Command', command], { env: scrubWindowsSigningEnvironment(process.env), encoding: 'utf8', windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024 * files.length, }) diff --git a/apps/desktop/tests/command-path.spec.ts b/apps/desktop/tests/command-path.spec.ts index 0b6612fdd0..b528b31f2b 100644 --- a/apps/desktop/tests/command-path.spec.ts +++ b/apps/desktop/tests/command-path.spec.ts @@ -2,6 +2,7 @@ import { execFile } from 'node:child_process' import { mkdtemp, rm } from 'node:fs/promises' +import { createRequire } from 'node:module' import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' @@ -15,6 +16,7 @@ it.skipIf(process.platform !== 'win32')('preserves unrelated PATH entries and re const result = await promisify(execFile)(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'), [ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', join(import.meta.dirname, 'fixtures', 'command-path.ps1'), + '-Electron', createRequire(import.meta.url)('electron') as string, '-Worker', join(import.meta.dirname, '..', 'scripts', 'command-path.ps1'), '-Root', root, ], { timeout: 60000, windowsHide: true }) expect(result.stdout).toContain('WINDOWS_COMMAND_PATH_OK') diff --git a/apps/desktop/tests/desktop-build-commit.spec.ts b/apps/desktop/tests/desktop-build-commit.spec.ts index 57016a5e7e..ab3c252e67 100644 --- a/apps/desktop/tests/desktop-build-commit.spec.ts +++ b/apps/desktop/tests/desktop-build-commit.spec.ts @@ -73,6 +73,18 @@ describe('desktop toolchain preflight', () => { expect(failures.find(failure => failure.tool === 'vswhere')?.detail).toContain('ProgramFiles(x86)') }) + it('reports missing PowerShell before Windows packaging', async () => { + const empty = await mkdtemp(join(tmpdir(), 'dsh-no-pwsh-')) + directories.push(empty) + const failures = await probeDesktopToolchain('win32', { PATH: empty }) + expect(failures.find(failure => failure.tool === 'pwsh')?.detail).toContain('PowerShell 7') + }) + + it.skipIf(process.platform !== 'win32')('accepts the Windows Authenticode toolchain', async () => { + const failures = await probeDesktopToolchain('win32', process.env) + expect(failures.filter(failure => failure.tool === 'pwsh')).toEqual([]) + }) + it('writes nothing into the working directory while probing', async () => { const directory = await mkdtemp(join(tmpdir(), 'dsh-probe-cwd-')) directories.push(directory) diff --git a/apps/desktop/tests/expected/windows-uninstall.json b/apps/desktop/tests/expected/windows-uninstall.json index 8a6a99cc57..b1f147d358 100644 --- a/apps/desktop/tests/expected/windows-uninstall.json +++ b/apps/desktop/tests/expected/windows-uninstall.json @@ -1,3 +1,23 @@ { - "cases": ["interactive", "silent", "upgrade", "replaced", "home-inside"] + "cases": [ + "interactive", + "silent", + "unowned", + "missing-location", + "missing-location-short", + "missing-location-foreign", + "owned-retained", + "upgrade", + "replaced", + "home-inside", + "home-slash", + "home-tilde", + "home-slash-inside", + "registration-error", + "main-locked", + "self-copy", + "auxiliary-locked", + "unsafe-root", + "save-report" + ] } diff --git a/apps/desktop/tests/fixtures/command-path.ps1 b/apps/desktop/tests/fixtures/command-path.ps1 index ef6f15930a..699289bbc7 100644 --- a/apps/desktop/tests/fixtures/command-path.ps1 +++ b/apps/desktop/tests/fixtures/command-path.ps1 @@ -1,4 +1,4 @@ -param([string]$Worker, [string]$Root) +param([string]$Worker, [string]$Root, [Parameter(Mandatory)][string]$Electron) $ErrorActionPreference = 'Stop' [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) . $Worker @@ -92,7 +92,61 @@ try { Require ((UserPath) -eq ($desktop + ';' + $invalidPath)) 'a notification failure changed the committed PATH' [void](Apply 'remove' $desktop) Require ((UserPath) -eq $invalidPath) 'removal changed invalid user PATH entries' + # Uninstalling A must preserve independently registered B integrations. + $app = Join-Path $Root 'Uninstall A' + $bin = Join-Path $app 'resources\runtime\cli\bin' + New-Item -ItemType Directory -Force $bin | Out-Null + [IO.File]::WriteAllText((Join-Path $bin 'dsh.cmd'), 'fixture') + [void](Apply 'install' $other) + $protocolKey = $keyRoot + '\Protocol' + $foreignCommand = '"' + (Join-Path $other 'DeepSeek Harness.exe') + '" "%1"' + $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command') + try { $key.SetValue('', $foreignCommand) } finally { $key.Dispose() } + $helper = Join-Path (Split-Path $Worker) 'uninstall-registration.ps1' + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey -ReportPath (Join-Path $Root 'uninstall-report.txt') -MutexName $options.MutexName + Require ($LASTEXITCODE -eq 0) 'foreign integration cleanup failed' + Require ((State $other).managed) 'uninstall removed foreign command ownership' + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($protocolKey + '\shell\open\command') + try { Require ($key.GetValue('') -eq $foreignCommand) 'uninstall removed foreign protocol' } finally { $key.Dispose() } + [void](Apply 'install' $bin) + $scheme = 'dsh-command-test-' + $identity + $protocolKey = 'Software\Classes\' + $scheme + $launcher = Join-Path $PSScriptRoot 'register-test-protocol.cjs' + $exe = Join-Path $app 'DeepSeek Harness.exe' + $registration = Start-Process $Electron -ArgumentList @(('"' + $launcher + '"'), ('"--user-data-dir=' + $Root + '\profile"'), $scheme, ('"' + $exe + '"')) -PassThru -WindowStyle Hidden + try { + if (-not $registration.WaitForExit(20000)) { $registration.Kill(); $registration.WaitForExit(); throw 'Electron protocol registration timed out' } + Require ($registration.ExitCode -eq 0) 'Electron could not register the test protocol' + } finally { $registration.Dispose() } + Require (Test-Path -LiteralPath ('HKCU:\' + $protocolKey + '\shell\open\command')) 'Electron did not write the protocol command' + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey -ReportPath (Join-Path $Root 'uninstall-report.txt') -MutexName $options.MutexName + Require ($LASTEXITCODE -eq 0) 'owned integration cleanup failed' + Require (-not (State $bin).managed) 'uninstall retained command ownership' + Require (-not (Test-Path -LiteralPath ('HKCU:\' + $protocolKey))) 'uninstall retained protocol' + # Missing ownership does not authorize removal while any of the installation remains. + $orphanPath = $bin + ';"' + $bin.ToUpperInvariant() + '\";C:\Windows;' + $other + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey, $true) + try { $key.SetValue('Path', $orphanPath, [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $key.Dispose() } + $report = Join-Path $Root 'unowned-report.txt' + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey -ReportPath $report -MutexName $options.MutexName -UnownedOnly + Require ($LASTEXITCODE -eq 1) 'unowned cleanup accepted an existing installation' + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey) + try { Require ($key.GetValue('Path') -eq $orphanPath) 'unowned cleanup changed PATH before directory removal' } finally { $key.Dispose() } + Require ([IO.File]::ReadAllText($report).Contains('installation directory remains')) 'unowned refusal lacks a report' + [IO.Directory]::Delete($app, $true) + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey -ReportPath $report -MutexName $options.MutexName -UnownedOnly + Require ($LASTEXITCODE -eq 0) 'unowned cleanup failed after directory removal' + $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey) + try { + Require ($key.GetValue('Path') -eq ('C:\Windows;' + $other)) 'unowned cleanup failed to preserve other PATH entries' + Require ($key.GetValueKind('Path') -eq [Microsoft.Win32.RegistryValueKind]::ExpandString) 'unowned cleanup changed PATH type' + } finally { $key.Dispose() } + [void](Apply 'install' $other) + $foreignState = State $other + & powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File $helper -Directory $app -EnvironmentKey $environmentKey -OwnerKey $ownerKey -ProtocolKey $protocolKey -ReportPath $report -MutexName $options.MutexName -UnownedOnly + Require ($LASTEXITCODE -eq 0 -and (State $other).fingerprint -eq $foreignState.fingerprint) 'unowned cleanup changed a new owner' 'WINDOWS_COMMAND_PATH_OK' } finally { + [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree(('Software\Classes\dsh-command-test-' + $identity), $false) [Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($keyRoot, $false) } diff --git a/apps/desktop/tests/fixtures/register-test-protocol.cjs b/apps/desktop/tests/fixtures/register-test-protocol.cjs new file mode 100644 index 0000000000..59c80ad362 --- /dev/null +++ b/apps/desktop/tests/fixtures/register-test-protocol.cjs @@ -0,0 +1,4 @@ +/** Register an isolated protocol through the Electron version used by Desktop. */ +const { app } = require('electron') +const [scheme, executable] = process.argv.slice(-2) +app.whenReady().then(() => app.exit(app.setAsDefaultProtocolClient(scheme, executable) ? 0 : 1)) diff --git a/apps/desktop/tests/installer-locales.spec.ts b/apps/desktop/tests/installer-locales.spec.ts index be9675184d..b4a8feeca2 100644 --- a/apps/desktop/tests/installer-locales.spec.ts +++ b/apps/desktop/tests/installer-locales.spec.ts @@ -24,7 +24,7 @@ it('generates Japanese NSIS strings from the same files that select packaged lan expect(source).toContain('LangString INSTALLER_NATIVE_PROGRESS ${LANG_JAPANESE} "インストールを準備しています… %d%%"') expect(source).toContain('!ifdef LANG_JAPANESE\n') expect(source.match(/^LangString INSTALLER_UPDATE_WAIT /gmu)).toHaveLength(8) - expect(source.match(/^LangString /gmu)).toHaveLength(256) + expect(source.match(/^LangString /gmu)).toHaveLength(locales.reduce((count, locale) => count + Object.keys(locale.strings).length, 0)) const japanese = locales.filter(locale => locale.id === 'ja_JP') expect(renderInstallerStrings(japanese)).not.toContain('${LANG_ENGLISH}') }) diff --git a/apps/desktop/tests/windows-directory-installer.spec.ts b/apps/desktop/tests/windows-directory-installer.spec.ts index fa3c6b34e9..ccbd392c8d 100644 --- a/apps/desktop/tests/windows-directory-installer.spec.ts +++ b/apps/desktop/tests/windows-directory-installer.spec.ts @@ -3,22 +3,43 @@ import { readFileSync } from 'node:fs' import { createRequire } from 'node:module' import { dirname, join } from 'node:path' import { expect, it } from 'vitest' -import { directoryInstallerExits, directoryInstallSection, directoryUninstaller } from '../scripts/windows-directory-installer.mjs' +import { directoryInstallerExits, directoryInstallSection, directoryInstallUtil, directoryUninstaller } from '../scripts/windows-directory-installer.mjs' const require = createRequire(import.meta.url) const section = readFileSync(join(dirname(require.resolve('app-builder-lib/package.json')), 'templates/nsis/installSection.nsh'), 'utf8') +it('retains data without preserving obsolete registrations when uninstalling another directory', () => { + const source = readFileSync(join(dirname(require.resolve('app-builder-lib/package.json')), 'templates/nsis/include/installUtil.nsh'), 'utf8') + const adapted = directoryInstallUtil(source) + expect(adapted).toContain('${if} $installationDir == $INSTDIR\n StrCpy $0 "$0 --updated"\n ${endif}') + expect(adapted).toContain('"$uninstallerFileNameTemp" /S /KEEP_APP_DATA $0 _?=$installationDir') + expect(adapted).toContain('"$uninstallerFileName" /S /KEEP_APP_DATA $0 _?=$installationDir') + expect(directoryInstallUtil(source.replaceAll('\n', '\r\n'))).toBe(adapted) + expect(() => directoryInstallUtil(source.replace('StrCpy $0 "$0 --updated"', ''))).toThrow('template changed') + expect(() => directoryInstallUtil(source + source)).toThrow('template changed') +}) + it('keeps data cleanup out of the upstream template while retaining application removal and registration cleanup', () => { const source = readFileSync(join(dirname(require.resolve('app-builder-lib/package.json')), 'templates/nsis/uninstaller.nsh'), 'utf8') const adapted = directoryUninstaller(source) expect(adapted).not.toContain('--delete-app-data') + expect(adapted).toContain('Goto dshUninstallFinished') + expect(adapted.indexOf('Goto dshUninstallFinished')).toBeLessThan(adapted.indexOf('WinShell::UninstAppUserModelId')) + expect(adapted).toContain('Call un.FinishCleanup') + expect(adapted).toContain('UninstallNote') expect(adapted).not.toContain('RMDir /r "$APPDATA') expect(adapted).toContain('!insertmacro customUnInstall') + expect(adapted.indexOf('!insertmacro customUnInstall')).toBeLessThan(adapted.indexOf('DeleteRegKey SHELL_CONTEXT "${INSTALL_REGISTRY_KEY}"')) expect(adapted).toContain('DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}"') expect(adapted).toContain('DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY_2}"') expect(directoryUninstaller(source.replaceAll('\n', '\r\n'))).toBe(adapted) expect(adapted).toContain('RMDir /r "\\\\?\\$INSTDIR"') + expect(adapted).toContain('Rename "\\\\?\\$INSTDIR$R0\\$R2" "\\\\?\\$PLUGINSDIR\\old-install$R0\\$R2"') + expect(adapted).toContain('Rename "\\\\?\\$PLUGINSDIR\\old-install$R0\\$R2" "\\\\?\\$INSTDIR$R0\\$R2"') + expect(adapted).not.toContain('"$INSTDIR$R0') + expect(adapted).not.toContain('"$PLUGINSDIR\\old-install') + expect(() => directoryUninstaller(source.replace(' # delete the installed files\n', ''))).toThrow('template changed') expect(() => directoryUninstaller(source.replace(' Var /GLOBAL isDeleteAppData\n', ''))).toThrow('template changed') expect(() => directoryUninstaller(source.replace(' DeleteRegKey SHELL_CONTEXT "${UNINSTALL_REGISTRY_KEY}"', ''))).toThrow('template changed') }) diff --git a/apps/desktop/tests/windows-installer-process-test.ps1 b/apps/desktop/tests/windows-installer-process-test.ps1 new file mode 100644 index 0000000000..7c43d46a0f --- /dev/null +++ b/apps/desktop/tests/windows-installer-process-test.ps1 @@ -0,0 +1,49 @@ +<# Exercise timeout cleanup with a real child that would otherwise outlive setup. #> +[CmdletBinding()] +param([Parameter(Mandatory)][string]$OutputDirectory) +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'windows-installer-process.ps1') +$fixtureBase = [IO.Path]::GetFullPath($OutputDirectory).TrimEnd('\') +$root = Join-Path $fixtureBase ('process-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $root | Out-Null +$ready = Join-Path $root 'child.pid' +$marker = Join-Path $root 'late-write.txt' +$parent = $null +$child = $null +try { + foreach ($exitCode in @(0, 7)) { + $fixture = Start-Process powershell.exe -ArgumentList "-NoProfile -Command exit $exitCode" -WindowStyle Hidden -PassThru + $failure = $null + try { Wait-InstallerProcess $fixture } catch { $failure = $_.Exception.Message } finally { $fixture.Dispose() } + if ($exitCode -eq 0 -and $failure) { throw $failure } + if ($exitCode -eq 7 -and $failure -ne 'Setup failed: 7') { throw "Lost setup exit status: $failure" } + } + $childCode = "Start-Sleep -Seconds 60; [IO.File]::WriteAllText('$($marker.Replace("'", "''"))', 'unexpected')" + $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($childCode)) + $readyLiteral = $ready.Replace("'", "''") + $parentCode = "`$child = Start-Process powershell.exe -ArgumentList '-NoProfile -EncodedCommand $encoded' -WindowStyle Hidden -PassThru; [IO.File]::WriteAllText('$readyLiteral.tmp', [string]`$child.Id); [IO.File]::Move('$readyLiteral.tmp', '$readyLiteral'); `$child.WaitForExit()" + $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($parentCode)) + $parent = Start-Process powershell.exe -ArgumentList "-NoProfile -EncodedCommand $encoded" -WindowStyle Hidden -PassThru + $timer = [Diagnostics.Stopwatch]::StartNew() + while (-not (Test-Path -LiteralPath $ready)) { + if ($parent.HasExited -or $timer.Elapsed.TotalSeconds -gt 30) { throw 'Process fixture did not become ready' } + Start-Sleep -Milliseconds 25 + } + $child = [Diagnostics.Process]::GetProcessById([int][IO.File]::ReadAllText($ready)) + # Observe termination through an independently opened process handle. + $observedParent = [Diagnostics.Process]::GetProcessById($parent.Id) + try { + $failure = $null + try { Wait-InstallerProcess $parent -TimeoutMilliseconds 100 } catch { $failure = $_.Exception.Message } + if ($failure -ne 'Setup timed out') { throw "Unexpected timeout result: $failure" } + if (-not $observedParent.WaitForExit(10000) -or -not $child.WaitForExit(10000)) { throw 'Timed-out setup left a live process' } + if (Test-Path -LiteralPath $marker) { throw 'Timed-out setup continued writing' } + } finally { $observedParent.Dispose() } + Write-Output 'passed: setup success, failure, timeout and child termination' +} finally { + foreach ($fixture in @($parent, $child)) { + if ($fixture) { Stop-InstallerProcess $fixture; $fixture.Dispose() } + } + if ([IO.Path]::GetDirectoryName($root) -ne $fixtureBase) { throw 'Unexpected process fixture cleanup path' } + Remove-Item -LiteralPath $root -Recurse -Force +} diff --git a/apps/desktop/tests/windows-installer-process.ps1 b/apps/desktop/tests/windows-installer-process.ps1 new file mode 100644 index 0000000000..a59eaa8ee3 --- /dev/null +++ b/apps/desktop/tests/windows-installer-process.ps1 @@ -0,0 +1,22 @@ +<# Reap timed-out fixture processes before their registry and filesystem cleanup. #> +function Stop-InstallerProcess([Diagnostics.Process]$Process) { + if ($Process.HasExited) { return } + $previousPreference = $ErrorActionPreference + try { + # A process can exit between HasExited and taskkill; inspect that race after capturing stderr. + $ErrorActionPreference = 'Continue' + $termination = & "$env:SystemRoot\System32\taskkill.exe" /PID $Process.Id /T /F 2>&1 + $terminationCode = $LASTEXITCODE + } finally { $ErrorActionPreference = $previousPreference } + if ($terminationCode -ne 0 -and -not $Process.HasExited) { throw "Cannot terminate fixture process $($Process.Id): $termination" } + if (-not $Process.WaitForExit(30000)) { throw "Fixture process $($Process.Id) remained after termination" } +} + +function Wait-InstallerProcess([Diagnostics.Process]$Process, [int]$TimeoutMilliseconds = 30000) { + try { + if (-not $Process.WaitForExit($TimeoutMilliseconds)) { throw 'Setup timed out' } + if ($Process.ExitCode -ne 0) { throw "Setup failed: $($Process.ExitCode)" } + } finally { + Stop-InstallerProcess $Process + } +} diff --git a/apps/desktop/tests/windows-installer-ui.ps1 b/apps/desktop/tests/windows-installer-ui.ps1 index bf2f6e63e5..3383f51728 100644 --- a/apps/desktop/tests/windows-installer-ui.ps1 +++ b/apps/desktop/tests/windows-installer-ui.ps1 @@ -65,6 +65,26 @@ public static class InstallerCapture { return incomplete; } + [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "SendMessageW")] static extern IntPtr ReadControlText(IntPtr window, uint message, IntPtr count, StringBuilder text); + public static string ControlText(IntPtr window) { + var text = new StringBuilder(32768); + ReadControlText(window, 0xD, new IntPtr(text.Capacity), text); + return text.ToString(); + } + + public static IntPtr FindWindowTitle(int process, string expected) { + IntPtr result = IntPtr.Zero; + EnumWindows(delegate(IntPtr window, IntPtr data) { + uint owner; + GetWindowThreadProcessId(window, out owner); + var title = new StringBuilder(256); + GetWindowText(window, title, title.Capacity); + if (owner == process && IsWindowVisible(window) && title.ToString() == expected) result = window; + return result == IntPtr.Zero; + }, IntPtr.Zero); + return result; + } + public static IntPtr FindClass(IntPtr parent, string name) { IntPtr result = IntPtr.Zero; EnumChildWindows(parent, delegate(IntPtr child, IntPtr unused) { diff --git a/apps/desktop/tests/windows-packaging-summary.spec.ts b/apps/desktop/tests/windows-packaging-summary.spec.ts new file mode 100644 index 0000000000..328cb85d16 --- /dev/null +++ b/apps/desktop/tests/windows-packaging-summary.spec.ts @@ -0,0 +1,58 @@ +/** Workflow summaries distinguish requested options from completed build evidence. */ +import { execFile } from 'node:child_process' +import { copyFile, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { promisify } from 'node:util' +import { expect, it } from 'vitest' +import { windowsPackagingSummary } from '../scripts/windows-packaging-summary.mjs' + +it('separates workflow identity, requested source, and resolved build version', () => { + const summary = windowsPackagingSummary({ + PACKAGE_SOURCE_REF: 'feature/windows', PACKAGE_SOURCE_SHA: 'source-sha', + GITHUB_WORKFLOW_REF: 'repo/.github/workflows/windows-package.yml@refs/heads/master', + GITHUB_WORKFLOW_SHA: 'workflow-sha', PACKAGE_INPUT_VERSION_MODE: 'default', + PACKAGE_VERSION: '0.2.2-rc.1.20261110.1.1', PACKAGE_SIGNING: 'signed', + DSH_PACKAGING_PRESET: 'test', DSH_DESKTOP_UPDATE_CHANNEL: 'nightly', + }) + expect(summary).toContain('| 源码 ref | feature/windows |') + expect(summary).toContain('| 检出源码 SHA | source-sha |') + expect(summary).toContain('| 工作流 SHA | workflow-sha |') + expect(summary).toContain('| 版本模式 | default |') + expect(summary).toContain('| 解析后的版本号 | 0.2.2-rc.1.20261110.1.1 |') + expect(summary).toContain('不代表构建、签名或发布成功') +}) + +it('retains unresolved and machine-default labels after an earlier failure', () => { + const summary = windowsPackagingSummary({ PACKAGE_SOURCE_REF: 'bad-source' }) + expect(summary).toContain('| 检出源码 SHA | 尚未取得 |') + expect(summary).toContain('| 解析后的版本号 | 尚未解析成功 |') + expect(summary).toContain('使用机器默认值(本摘要不读取)') + expect(summary).toContain('| 缓存命名空间 | 共享缓存 |') +}) + +it('escapes input markup and excludes unrelated environment and private configuration', () => { + const summary = windowsPackagingSummary({ + PACKAGE_SOURCE_REF: '