Merge remote-tracking branch 'origin/master' into feat/dingtalk-plugin
This commit is contained in:
commit
2f4de9acdf
699 files changed
+17410
-2407
No files matched your search
+2
-2
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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 指导的有序前缀/后缀位置。本决策拥有目录状态及其用户上下文位置。
|
||||
|
||||
|
||||
+4
-4
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 仍会改变内容祖先。
|
||||
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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` 之后或读者刷新时才显示。一直可见但没有人看的页面会继续轮询。
|
||||
+19
@@ -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
|
||||
+42
@@ -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.
|
||||
+42
@@ -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 模型上测量过。仍然写出相对目标的模型适用上面的当前目录规则。
|
||||
@@ -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
|
||||
@@ -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.
|
||||
|
||||
@@ -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 视图实例都会渲染侧边层,因此同一会话同时显示在主正文区和嵌入的对话中时,两处都会显示浮层。
|
||||
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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 组合中测量正文列、输入框、宽度手柄、探针和面板,覆盖放得下面板的留白、需要让位的外框、最后一个能让位和第一个不能让位的外框、刷新页面、开关,以及保持、失去和重新获得位置的宽度拖动。
|
||||
@@ -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.
|
||||
|
||||
@@ -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 <base>...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 <file>`, or update it with `gh pr edit <number> --body-file <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 <number> --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.
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
## Changes
|
||||
|
||||
<!-- Interface changes、Behavior changes、Module responsibilities and dependencies 三项;没有就写 None。 -->
|
||||
|
||||
## Testing
|
||||
|
||||
<!-- 测试设计 -->
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
|
||||
@@ -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)负责。
|
||||
|
||||
## 安装包内容
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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": {
|
||||
|
||||
+1
-1
@@ -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"}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
<a id="closing-the-window-and-quitting"></a>
|
||||
|
||||
@@ -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 <brand.bmp> <dpi> <light|dark> <hover-argb> <pressed-argb> [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-<pid>.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.
|
||||
|
||||
<a id="updates"></a>
|
||||
|
||||
|
||||
@@ -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)。
|
||||
|
||||
<a id="closing-the-window-and-quitting"></a>
|
||||
|
||||
@@ -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 <brand.bmp> <dpi> <light|dark> <hover-argb> <pressed-argb> [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-<pid>.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 数据内、主程序占用后重试、注册表失败后继续卸载及另一安装接管的检查。安装超时会先终止并等待夹具进程树退出,再清理测试资源;独立回归覆盖成功、非零退出及带存活子进程的父进程超时。编译本身不能证明已安装卸载行为。
|
||||
|
||||
<a id="updates"></a>
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "アンインストール ウィザードへようこそ",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "Вас приветствует мастер удаления",
|
||||
|
||||
@@ -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": "欢迎",
|
||||
|
||||
@@ -5,6 +5,12 @@
|
||||
#include <vector>
|
||||
|
||||
namespace uninstall_data {
|
||||
struct Failure { std::wstring path; DWORD error; };
|
||||
using Failures = std::vector<Failure>;
|
||||
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<HANDLE> 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.
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
// Manual uninstall diagnostics and native dialogs. The NSIS caller owns one session until process exit.
|
||||
#pragma once
|
||||
#include <commdlg.h>
|
||||
#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<HFONT>(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<UINT>(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<UINT>(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<int>(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<int>(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<TaskDialogFn>(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<LPCWSTR>(&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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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-<timestamp>.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.
|
||||
|
||||
|
||||
@@ -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`。如果恢复失败,安装器会清理未被占用的暂存文件并保留备份。上报此失败后,退出清理不再重试恢复。请保留报告所列的备份目录,并在重新安装前联系支持人员。静默安装保存相同的诊断,不显示弹窗。
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 发布;重跑发布不能使现有产物获得发布资格。
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<string | undefined> {
|
||||
|
||||
async function probeWindowsInstallerToolchain(environment: NodeJS.ProcessEnv): Promise<DesktopToolchainProbeFailure[]> {
|
||||
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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"')
|
||||
}
|
||||
@@ -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
|
||||
@@ -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 ? `<code>${text(value)}</code>` : 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))
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<int, int> ReadParents()
|
||||
{
|
||||
IntPtr snapshot = CreateToolhelp32Snapshot(2, 0);
|
||||
if (snapshot == new IntPtr(-1)) throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
try
|
||||
{
|
||||
var result = new Dictionary<int, int>();
|
||||
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); }
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
+55
-1
@@ -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)
|
||||
}
|
||||
@@ -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))
|
||||
@@ -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}')
|
||||
})
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 | <code>feature/windows</code> |')
|
||||
expect(summary).toContain('| 检出源码 SHA | <code>source-sha</code> |')
|
||||
expect(summary).toContain('| 工作流 SHA | <code>workflow-sha</code> |')
|
||||
expect(summary).toContain('| 版本模式 | <code>default</code> |')
|
||||
expect(summary).toContain('| 解析后的版本号 | <code>0.2.2-rc.1.20261110.1.1</code> |')
|
||||
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: '<script>|\n[link](url)`',
|
||||
DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'private-pin-sentinel',
|
||||
DSH_PACKAGING_CONFIG_DIR: 'private-directory-sentinel',
|
||||
})
|
||||
expect(summary).toContain('<script>| [link](url)`')
|
||||
expect(summary).not.toContain('<script>')
|
||||
expect(summary).not.toContain('sentinel')
|
||||
})
|
||||
|
||||
it('appends a summary using the standalone workflow helper without project dependencies', async (t) => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'windows-summary-'))
|
||||
t.onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
const output = join(root, 'summary.md')
|
||||
const helper = join(root, 'windows-packaging-summary.mjs')
|
||||
await copyFile(join(import.meta.dirname, '../scripts/windows-packaging-summary.mjs'), helper)
|
||||
await writeFile(output, 'Previous summary\n')
|
||||
await promisify(execFile)(process.execPath, [helper], {
|
||||
env: { GITHUB_STEP_SUMMARY: output, PACKAGE_SOURCE_REF: 'test-ref', PACKAGE_SIGNING: 'unsigned' },
|
||||
timeout: 20_000,
|
||||
})
|
||||
expect(await readFile(output, 'utf8')).toMatch(/^Previous summary\n/u)
|
||||
expect(await readFile(output, 'utf8')).toContain('| 签名方式(请求) | <code>unsigned</code> |')
|
||||
})
|
||||
@@ -0,0 +1,265 @@
|
||||
# Inspect real Task Scheduler definitions without registering tasks, passwords, GitHub or signing hardware.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $IsWindows) { throw 'Requires PowerShell 7 on Windows.' }
|
||||
. (Join-Path $PSScriptRoot '../scripts/windows-runner-scheduler.ps1')
|
||||
$scheduler = New-Object -ComObject 'Schedule.Service'
|
||||
$scheduler.Connect()
|
||||
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
||||
$root = Join-Path ([IO.Path]::GetTempPath()) ('dsh-boot-definition-' + [guid]::NewGuid().ToString('N'))
|
||||
$null = New-Item -ItemType Directory -Path $root
|
||||
try {
|
||||
$runner = Join-Path $root 'runner with spaces'
|
||||
$null = New-Item -ItemType Directory -Path $runner
|
||||
Set-Content -LiteralPath (Join-Path $runner '.runner') -Value '{}'
|
||||
$pwsh = Join-Path $PSHOME 'pwsh.exe'
|
||||
foreach ($minutes in @(1, 7, 1440)) {
|
||||
$definition = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh $minutes 'Boot'
|
||||
[xml]$xml = $definition.XmlText
|
||||
$ns = [Xml.XmlNamespaceManager]::new($xml.NameTable)
|
||||
$ns.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task')
|
||||
function Read-Value([string]$Path) { return $xml.SelectSingleNode('/t:Task/' + $Path, $ns).InnerText }
|
||||
if ((Read-Value 't:Principals/t:Principal/t:UserId') -ne $sid -or
|
||||
(Read-Value 't:Principals/t:Principal/t:LogonType') -ne 'Password' -or
|
||||
(Read-Value 't:Principals/t:Principal/t:RunLevel') -ne 'LeastPrivilege') { throw 'Boot account or logon configuration differs.' }
|
||||
if ($xml.SelectNodes('/t:Task/t:Triggers/t:BootTrigger', $ns).Count -ne 1 -or
|
||||
$xml.SelectNodes('/t:Task/t:Triggers/t:LogonTrigger', $ns).Count -ne 0 -or
|
||||
(Read-Value 't:Triggers/t:TimeTrigger/t:Repetition/t:Interval') -ne "PT${minutes}M") { throw 'Boot or recovery trigger differs.' }
|
||||
if ((Read-Value 't:Settings/t:Priority') -ne '4' -or
|
||||
(Read-Value 't:Settings/t:Enabled') -ne 'false' -or
|
||||
(Read-Value 't:Settings/t:MultipleInstancesPolicy') -ne 'IgnoreNew' -or
|
||||
(Read-Value 't:Settings/t:ExecutionTimeLimit') -ne 'PT0S' -or
|
||||
(Read-Value 't:Settings/t:DisallowStartIfOnBatteries') -ne 'false' -or
|
||||
(Read-Value 't:Settings/t:StopIfGoingOnBatteries') -ne 'false') { throw 'Boot task lifetime settings differ.' }
|
||||
if ((Read-Value 't:Actions/t:Exec/t:Command') -ne (Join-Path $runner 'dsh-task/launcher.exe') -or
|
||||
(Read-Value 't:Actions/t:Exec/t:Arguments') -ne ('"' + $pwsh + '"') -or
|
||||
(Read-Value 't:Actions/t:Exec/t:WorkingDirectory') -ne $runner) { throw 'Boot task bypasses the existing launcher.' }
|
||||
# Round-trip through the scheduler's parser, without storing or enabling a task.
|
||||
$parsed = $scheduler.NewTask(0)
|
||||
$parsed.XmlText = $definition.XmlText
|
||||
$parsedSid = ([Security.Principal.NTAccount]::new($parsed.Principal.UserId)).Translate([Security.Principal.SecurityIdentifier]).Value
|
||||
if ($parsedSid -ne $sid -or $parsed.Settings.Enabled) { throw 'Definition did not round-trip.' }
|
||||
}
|
||||
$interactive = New-WindowsRunnerTaskDefinition $scheduler $sid $runner $pwsh 1
|
||||
[xml]$interactiveXml = $interactive.XmlText
|
||||
$interactiveNs = [Xml.XmlNamespaceManager]::new($interactiveXml.NameTable)
|
||||
$interactiveNs.AddNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task')
|
||||
if ($interactive.Principal.LogonType -ne 3 -or $interactive.Principal.RunLevel -ne 0 -or $interactive.Settings.Priority -ne 4 -or $interactive.Settings.Enabled -or $interactiveXml.SelectNodes('/t:Task/t:Triggers/t:LogonTrigger/t:UserId', $interactiveNs).Count -ne 1 -or $interactiveXml.SelectSingleNode('/t:Task/t:Triggers/t:LogonTrigger/t:UserId', $interactiveNs).InnerText -ne $sid -or $interactiveXml.SelectNodes('/t:Task/t:Triggers/t:BootTrigger', $interactiveNs).Count -ne 0) { throw 'Interactive task defaults changed.' }
|
||||
if (Get-WindowsRunnerTask $scheduler ('DSH-absent-' + [guid]::NewGuid().ToString('N'))) { throw 'Missing task lookup returned a task.' }
|
||||
$deniedFolder = [pscustomobject]@{}
|
||||
$deniedFolder | Add-Member ScriptMethod GetTask { param($Name); throw [Runtime.InteropServices.COMException]::new('Injected scheduler access denied', -2147024891) }
|
||||
$deniedScheduler = [pscustomobject]@{ Folder=$deniedFolder }
|
||||
$deniedScheduler | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
|
||||
$denied = $false
|
||||
try { $null = Get-WindowsRunnerTask $deniedScheduler 'fixture' } catch { $denied = $true }
|
||||
if (-not $denied) { throw 'Denied task lookup was treated as a missing task.' }
|
||||
$manager = Join-Path $PSScriptRoot '../scripts/windows-runner-task.ps1'
|
||||
function Reject-Options([string[]]$Options, [string]$Message) {
|
||||
$output = & $pwsh -NoProfile -NonInteractive -File $manager -RunnerRoot $runner @Options 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -eq 0 -or -not $output.Contains($Message)) { throw "Expected rejection: $Message`n$output" }
|
||||
if (Test-Path -LiteralPath (Join-Path $runner 'dsh-task')) { throw 'Rejected options wrote a startup snapshot.' }
|
||||
}
|
||||
Reject-Options @('-Action','register-boot') 'requires -RunAs'
|
||||
Reject-Options @('-Action','install','-StartupMode','Boot','-RunAs','NT AUTHORITY\SYSTEM') 'RunAs applies only to register-boot'
|
||||
Reject-Options @('-Action','install','-RunAs','unused') 'RunAs applies only to register-boot'
|
||||
Reject-Options @('-Action','start','-StartupMode','Boot') 'apply only to install'
|
||||
$processProbe = Join-Path $root 'process-probe.ps1'
|
||||
@'
|
||||
param([string]$Manager, [string]$Runner, [switch]$Unreadable, [switch]$ThrowPath)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Get-Process {
|
||||
param($Name,$ErrorAction)
|
||||
if ($ThrowPath) {
|
||||
$process = [pscustomobject]@{ ProcessName = 'Runner.Worker' }
|
||||
$process | Add-Member ScriptProperty Path { throw [ComponentModel.Win32Exception]::new(5) }
|
||||
return $process
|
||||
}
|
||||
[pscustomobject]@{ ProcessName = 'Runner.Worker'; Path = if ($Unreadable) { $null } else { Join-Path $Runner 'bin/Runner.Worker.exe' } }
|
||||
}
|
||||
& $Manager -Action install -RunnerRoot $Runner
|
||||
'@ | Set-Content -LiteralPath $processProbe
|
||||
foreach ($mode in @('readable','missing','throwing')) {
|
||||
$probeOptions = switch ($mode) { 'missing' { @('-Unreadable') }; 'throwing' { @('-ThrowPath') }; default { @() } }
|
||||
$output = & $pwsh -NoProfile -NonInteractive -File $processProbe -Manager $manager -Runner $runner @probeOptions 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -eq 0 -or -not $output.Contains('A runner process is active or its location is unreadable')) { throw "Live-process installation guard failed: $output" }
|
||||
if (Test-Path -LiteralPath (Join-Path $runner 'dsh-task')) { throw 'Live-process rejection wrote a startup snapshot.' }
|
||||
}
|
||||
Set-Content -LiteralPath (Join-Path $runner '.service') -Value 'fixture'
|
||||
Reject-Options @('-Action','install','-ConfigRoot',$root) 'native runner service is configured'
|
||||
|
||||
Remove-Item -LiteralPath (Join-Path $runner '.service')
|
||||
|
||||
# Exercise preparation with isolated toolchain/network and process-inventory fixtures.
|
||||
$fixture = Join-Path $root 'scripts'
|
||||
$null = New-Item -ItemType Directory -Path $fixture
|
||||
foreach ($name in @('windows-runner-task.ps1','windows-runner-scheduler.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) {
|
||||
Copy-Item -LiteralPath (Join-Path $PSScriptRoot "../scripts/$name") -Destination $fixture
|
||||
}
|
||||
Set-Content -LiteralPath (Join-Path $fixture 'start-windows-packaging-runner.ps1') -Value 'param($RunnerRoot,$ConfigRoot,[switch]$CheckOnly); if (-not $CheckOnly) { throw "Unexpected runner launch" }; exit 0'
|
||||
$prepareProbe = Join-Path $root 'prepare-probe.ps1'
|
||||
@'
|
||||
param($Manager,$Runner,$ConfigRoot)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Get-Process { param($Name,$ErrorAction); return @() }
|
||||
& $Manager -Action install -StartupMode Boot -RunnerRoot $Runner -ConfigRoot $ConfigRoot -RestartMinutes 7 -RestartCount 3
|
||||
'@ | Set-Content -LiteralPath $prepareProbe
|
||||
& $pwsh -NoProfile -NonInteractive -File $prepareProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -ConfigRoot $root
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Boot preparation failed.' }
|
||||
$configFile = Join-Path $runner 'dsh-task/config.json'
|
||||
$config = Get-Content -LiteralPath $configFile -Raw | ConvertFrom-Json
|
||||
if ($config.StartupMode -ne 'Boot' -or $config.AccountSid -ne $sid -or $config.RestartMinutes -ne 7 -or $config.RestartCount -ne 3) { throw 'Preparation lost account or recovery settings.' }
|
||||
if (Get-WindowsRunnerTask $scheduler $config.TaskName) { throw 'Preparation registered a task.' }
|
||||
Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName
|
||||
$expectedTaskName = $config.TaskName
|
||||
foreach ($field in @('StartupMode','AccountSid','RunnerRoot','TaskName','PowerShell','RestartMinutes')) {
|
||||
$saved = $config.$field
|
||||
try {
|
||||
foreach ($invalid in @($null, 'invalid')) {
|
||||
$config.$field = $invalid
|
||||
$failure = $null
|
||||
try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $expectedTaskName } catch { $failure = $_ }
|
||||
if (-not $failure) { throw "Invalid $field was accepted." }
|
||||
}
|
||||
} finally { $config.$field = $saved }
|
||||
}
|
||||
foreach ($invalid in @(0, 1441, 1.5, '7')) {
|
||||
$config.RestartMinutes = $invalid
|
||||
$failure = $null
|
||||
try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName } catch { $failure = $_ }
|
||||
if (-not $failure) { throw 'Invalid restart interval was accepted.' }
|
||||
}
|
||||
$config.RestartMinutes = 7
|
||||
$registrationProbe = Join-Path $root 'register-probe.ps1'
|
||||
@'
|
||||
param($Manager,$Runner,$RunAs,$Result)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
function Get-Process { param($Name,$ErrorAction); return @() }
|
||||
$nativeScheduler = New-Object -ComObject 'Schedule.Service'
|
||||
$nativeScheduler.Connect()
|
||||
$folder = [pscustomobject]@{}
|
||||
$folder | Add-Member ScriptMethod GetTask { param($Name); return $null }
|
||||
$folder | Add-Member ScriptMethod RegisterTaskDefinition {
|
||||
param($Name,$Definition,$Flags,$User,$Password,$Logon,$Sddl)
|
||||
if ($Password -ne 'fake-only-never-authenticated' -or $Flags -ne 2 -or $Logon -ne 1) { throw 'Invalid registration transport.' }
|
||||
@{ Name=$Name; User=$User; Sddl=$Sddl; Xml=$Definition.XmlText } | ConvertTo-Json | Set-Content -LiteralPath $Result
|
||||
}
|
||||
$fake = [pscustomobject]@{ Native=$nativeScheduler; Folder=$folder }
|
||||
$fake | Add-Member ScriptMethod Connect {}
|
||||
$fake | Add-Member ScriptMethod NewTask { param($Flags); return $this.Native.NewTask($Flags) }
|
||||
$fake | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
|
||||
function New-Object { param($ComObject); if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }; return $fake }
|
||||
function Get-Credential { param($UserName,$Message); return [Management.Automation.PSCredential]::new($UserName,(ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force)) }
|
||||
& $Manager -Action register-boot -RunnerRoot $Runner -RunAs $RunAs
|
||||
'@ | Set-Content -LiteralPath $registrationProbe
|
||||
$registrationResult = Join-Path $root 'registration.json'
|
||||
$account = [Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
$elevated = ([Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
||||
$registrationOutput = & $pwsh -NoProfile -NonInteractive -File $registrationProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -RunAs $account -Result $registrationResult 2>&1 | Out-String
|
||||
if ($elevated -and -not $sid.EndsWith('-500')) {
|
||||
if ($LASTEXITCODE -ne 0) { throw "Boot registration entry failed: $registrationOutput" }
|
||||
$submitted = Get-Content -LiteralPath $registrationResult -Raw | ConvertFrom-Json
|
||||
if ($submitted.User -ne $account -or $submitted.Name -ne $config.TaskName -or $submitted.Sddl -notlike "*(A;;GA;;;$sid)*") { throw 'Registration lost prepared account or management access.' }
|
||||
} else {
|
||||
Write-Output 'SKIP: elevated registration entry with substitute transport; unsupported installer context. Real cross-account registration is not tested.'
|
||||
if ($LASTEXITCODE -eq 0 -or (Test-Path -LiteralPath $registrationResult)) { throw 'Boot registration accepted an unsupported installer context.' }
|
||||
}
|
||||
if (Get-WindowsRunnerTask $scheduler $config.TaskName) { throw 'Isolated registration created a real task.' }
|
||||
# Exercise management against a registered-task substitute, without CIM or real scheduler mutation.
|
||||
$managementProbe = Join-Path $root 'manage-probe.ps1'
|
||||
@'
|
||||
param($Manager,$Runner,$Operation,$Result)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path (Split-Path $Manager) 'windows-runner-scheduler.ps1')
|
||||
$native = New-Object -ComObject 'Schedule.Service'
|
||||
$native.Connect()
|
||||
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
||||
$definition = New-WindowsRunnerTaskDefinition $native $sid $Runner (Join-Path $PSHOME 'pwsh.exe') 1 'Boot'
|
||||
$script:enabled = $Operation -ne 'uninstall'
|
||||
$task = [pscustomobject]@{ Definition=$definition; State=$(if ($script:enabled) { 3 } else { 1 }); LastRunTime=[DateTime]::MinValue; LastTaskResult=0 }
|
||||
$task | Add-Member ScriptProperty Enabled { return $script:enabled } {
|
||||
param($Value)
|
||||
$script:enabled = $Value
|
||||
Add-Content -LiteralPath $Result -Value "enabled=$Value"
|
||||
if (-not $Value -and $this.State -ne 4) { $this.State = 1 }
|
||||
}
|
||||
$task | Add-Member ScriptMethod Run { param($Parameters); Add-Content -LiteralPath $Result -Value 'run'; $this.State=4 }
|
||||
$task | Add-Member ScriptMethod Stop { param($Flags); Add-Content -LiteralPath $Result -Value 'stop'; $this.State=1 }
|
||||
$folder = [pscustomobject]@{ Task=$task }
|
||||
$folder | Add-Member ScriptMethod GetTask { param($Name); return $this.Task }
|
||||
$folder | Add-Member ScriptMethod DeleteTask { param($Name,$Flags); Add-Content -LiteralPath $Result -Value 'delete' }
|
||||
$fake = [pscustomobject]@{ Folder=$folder }
|
||||
$fake | Add-Member ScriptMethod Connect {}
|
||||
$fake | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
|
||||
function New-Object { param($ComObject); if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }; return $fake }
|
||||
function Get-Process { param($Name,$ErrorAction); return @() }
|
||||
$status = & $Manager -Action $Operation -RunnerRoot $Runner
|
||||
if ($Operation -eq 'status') { $status | ConvertTo-Json | Set-Content -LiteralPath $Result }
|
||||
'@ | Set-Content -LiteralPath $managementProbe
|
||||
foreach ($operation in @('status','start','stop','uninstall')) {
|
||||
$resultFile = Join-Path $root "manage-$operation.txt"
|
||||
& $pwsh -NoProfile -NonInteractive -File $managementProbe -Manager (Join-Path $fixture 'windows-runner-task.ps1') -Runner $runner -Operation $operation -Result $resultFile
|
||||
if ($LASTEXITCODE -ne 0) { throw "Management failed: $operation" }
|
||||
$result = Get-Content -LiteralPath $resultFile -Raw
|
||||
if ($operation -eq 'status') {
|
||||
$status = $result | ConvertFrom-Json
|
||||
if (-not $status.BootTrigger -or $status.LogonType -ne 'Password' -or $status.State -ne 'Ready' -or $status.RemainingLaunches -ne 4) { throw 'Status lost startup mode or recovery budget.' }
|
||||
} else {
|
||||
$expected = switch ($operation) { 'start' { "enabled=True`nrun" }; 'stop' { "enabled=False`nstop" }; 'uninstall' { 'delete' } }
|
||||
if ($result.Replace("`r`n","`n").Trim() -ne $expected) { throw "Unexpected management effects: $operation" }
|
||||
}
|
||||
}
|
||||
Remove-Item -LiteralPath (Join-Path $runner 'dsh-task/launcher.exe')
|
||||
$failure = $null
|
||||
try { Assert-WindowsRunnerBootConfiguration $config $sid $runner $config.TaskName } catch { $failure = $_ }
|
||||
if (-not $failure) { throw 'Missing launcher was accepted.' }
|
||||
|
||||
# Only the credential dialog and registration transport are replaced; no account authentication occurs.
|
||||
$script:credentialResult = $null
|
||||
$script:credentialThrows = $false
|
||||
$script:registrationCalls = 0
|
||||
$script:registrationFails = $false
|
||||
$script:registrationMismatch = $false
|
||||
function Get-Credential { param($UserName, $Message); if ($script:credentialThrows) { throw 'Prompt unavailable' }; return $script:credentialResult }
|
||||
$fakeFolder = [pscustomobject]@{}
|
||||
$fakeFolder | Add-Member ScriptMethod RegisterTaskDefinition {
|
||||
param($Name, $Definition, $Flags, $User, $Password, $Logon, $Sddl)
|
||||
$script:registrationCalls++
|
||||
if ($Name -ne 'fixture' -or $Flags -ne 2 -or $User -ne 'fixture-user' -or $Logon -ne 1 -or $Sddl -ne "D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;$sid)" -or $Password -ne 'fake-only-never-authenticated') {
|
||||
$script:registrationMismatch = $true; throw 'Unexpected registration request.'
|
||||
}
|
||||
if ($script:registrationFails) { throw [Runtime.InteropServices.COMException]::new('fake-only-never-authenticated', -2147023570) }
|
||||
}
|
||||
$fakeScheduler = [pscustomobject]@{ Folder = $fakeFolder }
|
||||
$fakeScheduler | Add-Member ScriptMethod GetFolder { param($Path); if ($Path -ne '\') { throw 'Unexpected task folder.' }; return $this.Folder }
|
||||
function Reject-Registration([string]$Message) {
|
||||
$failure = $null
|
||||
try { Register-WindowsRunnerBootTask $fakeScheduler 'fixture' $definition $sid 'fixture-user' } catch { $failure = $_ }
|
||||
if (-not $failure -or -not $failure.Exception.Message.Contains($Message) -or $failure.ToString().Contains('fake-only-never-authenticated')) {
|
||||
throw 'Registration failure was not contained or exposed the fake credential.'
|
||||
}
|
||||
}
|
||||
try {
|
||||
$script:credentialThrows = $true
|
||||
Reject-Registration 'Prompt unavailable'
|
||||
$script:credentialThrows = $false
|
||||
Reject-Registration 'Credential entry cancelled'
|
||||
$script:credentialResult = [Management.Automation.PSCredential]::new('other-user', (ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force))
|
||||
Reject-Registration 'Credential entry cancelled'
|
||||
$script:credentialResult = [Management.Automation.PSCredential]::new('fixture-user', [Security.SecureString]::new())
|
||||
Reject-Registration 'Credential entry cancelled'
|
||||
if ($script:registrationCalls -ne 0) { throw 'Invalid credential input reached registration.' }
|
||||
$script:credentialResult = [Management.Automation.PSCredential]::new('fixture-user', (ConvertTo-SecureString 'fake-only-never-authenticated' -AsPlainText -Force))
|
||||
Register-WindowsRunnerBootTask $fakeScheduler 'fixture' $definition $sid 'fixture-user'
|
||||
if ($script:registrationCalls -ne 1) { throw 'Registration was not submitted once.' }
|
||||
$script:registrationFails = $true
|
||||
Reject-Registration '0x8007052E'
|
||||
if ($script:registrationMismatch) { throw 'Unexpected registration request.' }
|
||||
if ($script:registrationCalls -ne 2) { throw 'Failed registration retried authentication.' }
|
||||
} finally {
|
||||
Remove-Item Function:Get-Credential
|
||||
$script:credentialResult = $null
|
||||
}
|
||||
} finally {
|
||||
Remove-Item -LiteralPath $root -Recurse -Force
|
||||
}
|
||||
Write-Output "PASS: boot/password/least-privilege definition, recovery settings, duplicate policy, launcher reuse, XML round-trip, invalid options, credential substitutes and single-attempt registration failure containment. No task registered."
|
||||
exit 0
|
||||
@@ -9,7 +9,7 @@ $pwshLink = Join-Path $root 'tools/pwsh-7.6.6'
|
||||
if ($CheckStartup) { $null = New-Item -ItemType Junction -Path $pwshLink -Target $PSHOME }
|
||||
$server = $null
|
||||
$saved = @{}
|
||||
foreach ($name in @('HTTP_PROXY','HTTPS_PROXY','NO_PROXY','NODE_USE_ENV_PROXY')) { $saved[$name] = [Environment]::GetEnvironmentVariable($name,'Process') }
|
||||
foreach ($name in @('HTTP_PROXY','HTTPS_PROXY','NO_PROXY','NODE_USE_ENV_PROXY','NODE_OPTIONS')) { $saved[$name] = [Environment]::GetEnvironmentVariable($name,'Process') }
|
||||
try {
|
||||
if ($null -ne (Read-RunnerNetwork $root)) { throw 'Absent configuration changed behavior.' }
|
||||
$fixture = Join-Path $root 'proxy.cjs'
|
||||
@@ -41,6 +41,16 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
|
||||
if ($server.HasExited -or [DateTime]::UtcNow -gt $deadline) { throw 'Proxy fixture did not become ready.' }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
# Observe natural event-loop drain in the real redirected probe, without replacing fetch.
|
||||
$lifecycle = Join-Path $root 'probe-lifecycle.cjs'
|
||||
@'
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
if (process.env.DSH_NETWORK_PROBE_URL) {
|
||||
process.once('beforeExit', () => fs.appendFileSync(path.join(__dirname, 'drained'), 'drained\n'));
|
||||
}
|
||||
'@ | Set-Content -LiteralPath $lifecycle
|
||||
$env:NODE_OPTIONS = '--require "' + $lifecycle.Replace('\', '/') + '"'
|
||||
$port = Get-Content (Join-Path $root 'port') -Raw
|
||||
$config = @{proxyUrl="http://127.0.0.1:$port";noProxy='';serviceName='';probeUrl='http://runner-probe.invalid/ready';attempts=2;timeoutSeconds=2;retrySeconds=1}
|
||||
function Write-Config { $config | ConvertTo-Json | Set-Content (Join-Path $root 'runner-network.json') }
|
||||
@@ -48,6 +58,7 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
|
||||
$parsed = Read-RunnerNetwork $root
|
||||
Set-RunnerNetwork $parsed
|
||||
Wait-RunnerNetwork $parsed
|
||||
if (-not (Test-Path (Join-Path $root 'drained')) -or (Get-Content (Join-Path $root 'drained')).Count -ne 1) { throw 'Successful probe bypassed normal Node event-loop drain.' }
|
||||
if ($env:NODE_USE_ENV_PROXY -ne '1' -or $env:HTTP_PROXY -ne $config.proxyUrl -or $env:HTTPS_PROXY -ne $config.proxyUrl) { throw 'Proxy environment was not applied.' }
|
||||
# Full startup requires the operator's installed packaging toolchain and persistent PATH.
|
||||
if ($CheckStartup) {
|
||||
@@ -90,7 +101,19 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
|
||||
$config.timeoutSeconds = 1
|
||||
$failure = $null
|
||||
try { Wait-RunnerNetwork $config } catch { $failure = $_ }
|
||||
if (-not $failure -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Unresponsive endpoint did not terminate its probe.' }
|
||||
if (-not $failure -or -not $failure.Exception.Message.StartsWith('Runner network dependency unavailable;') -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Unresponsive endpoint did not terminate its probe.' }
|
||||
# Retain a bound non-listening socket so no concurrent fixture can claim the refused port.
|
||||
$refused = [Net.Sockets.Socket]::new([Net.Sockets.AddressFamily]::InterNetwork, [Net.Sockets.SocketType]::Stream, [Net.Sockets.ProtocolType]::Tcp)
|
||||
try {
|
||||
$refused.Bind([Net.IPEndPoint]::new([Net.IPAddress]::Loopback, 0))
|
||||
$config.proxyUrl = "http://127.0.0.1:$($refused.LocalEndPoint.Port)"
|
||||
$config.noProxy = ''
|
||||
$config.probeUrl = 'http://runner-probe.invalid/ready'
|
||||
Set-RunnerNetwork $config
|
||||
$failure = $null
|
||||
try { Wait-RunnerNetwork $config } catch { $failure = $_ }
|
||||
if (-not $failure -or -not $failure.Exception.Message.StartsWith('Runner network dependency unavailable;') -or (Get-Content (Join-Path $root 'requests')).Count -ne 6) { throw 'Refused proxy connection admitted startup or reached the HTTP fixture.' }
|
||||
} finally { $refused.Dispose() }
|
||||
foreach ($invalid in @('extra','credential','budget','type','wildcard','malformed')) {
|
||||
$bad = $config.Clone()
|
||||
switch ($invalid) {
|
||||
@@ -106,7 +129,7 @@ server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(root, 'port'), St
|
||||
try { $null = Read-RunnerNetwork $root } catch { $failure = $_ }
|
||||
if (-not $failure -or $failure.ToString().Contains('fake-secret')) { throw 'Invalid configuration accepted or disclosed.' }
|
||||
}
|
||||
Write-Output "PASS: absent config, proxy routing, Node proxy opt-in, service readiness, bounded failure and redacted invalid config; startup integration=$CheckStartup."
|
||||
Write-Output "PASS: absent config, redirected native Node HTTP success, non-2xx, refused proxy, request timeout, proxy routing, Node proxy opt-in, service readiness, bounded failure and redacted invalid config; startup integration=$CheckStartup."
|
||||
} finally {
|
||||
foreach ($name in $saved.Keys) { [Environment]::SetEnvironmentVariable($name,$saved[$name],'Process') }
|
||||
if ($server) { if (-not $server.HasExited) { $server.Kill($true); $server.WaitForExit() }; $server.Dispose() }
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# Verify native parent IDs with an owned process and await its exit; no scheduler or runner is used.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $IsWindows) { throw 'Requires PowerShell 7 on Windows.' }
|
||||
Add-Type -Path (Join-Path $PSScriptRoot '../scripts/windows-runner-processes.cs')
|
||||
$info = [Diagnostics.ProcessStartInfo]::new((Join-Path $PSHOME 'pwsh.exe'))
|
||||
$info.UseShellExecute = $false
|
||||
$info.CreateNoWindow = $true
|
||||
foreach ($argument in @('-NoProfile','-NonInteractive','-Command','Start-Sleep -Seconds 120')) { $info.ArgumentList.Add($argument) }
|
||||
$child = [Diagnostics.Process]::Start($info)
|
||||
try {
|
||||
$parents = [DshRunnerProcesses]::ReadParents()
|
||||
if (-not $parents.ContainsKey($PID) -or -not $parents.ContainsKey($child.Id) -or $parents[$child.Id] -ne $PID) {
|
||||
throw 'Native process snapshot did not identify the owned child and parent.'
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
if (-not $child.HasExited) { $child.Kill($true) }
|
||||
if (-not $child.WaitForExit(30000)) { throw 'Owned process did not exit.' }
|
||||
} finally { $child.Dispose() }
|
||||
}
|
||||
Write-Output 'PASS: native process ancestry and owned child teardown without CIM.'
|
||||
exit 0
|
||||
@@ -0,0 +1,49 @@
|
||||
# Isolated supervisor failures; no scheduler registration, GitHub or signing hardware.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Join-Path ([IO.Path]::GetTempPath()) ('runner-recovery-' + [guid]::NewGuid().ToString('N'))
|
||||
$null = New-Item -ItemType Directory $root
|
||||
$source = Get-Content (Join-Path $PSScriptRoot '../scripts/run-windows-runner-task.ps1') -Raw
|
||||
try {
|
||||
foreach ($case in @('log-failure','counter-failure','exhausted','child-failure','disable-failure')) {
|
||||
$dir = Join-Path $root $case
|
||||
$null = New-Item -ItemType Directory $dir
|
||||
@{RestartCount=1;TaskName='fake';RunnerRoot=$dir;ConfigRoot=$dir} | ConvertTo-Json | Set-Content (Join-Path $dir 'config.json')
|
||||
Set-Content (Join-Path $dir 'attempts.txt') $(if($case -in @('exhausted','disable-failure')){'2'}else{'0'})
|
||||
Set-Content (Join-Path $dir 'start.ps1') 'Set-Content (Join-Path $PSScriptRoot "launched") yes; exit 7'
|
||||
$mocks = @'
|
||||
function New-Object {
|
||||
param($ComObject)
|
||||
if ($ComObject -ne 'Schedule.Service') { throw 'Unexpected COM object.' }
|
||||
$task = [pscustomobject]@{}
|
||||
$task | Add-Member ScriptProperty Enabled { return $true } { param($Value); [IO.File]::WriteAllText((Join-Path $PSScriptRoot 'disabled'),'yes') }
|
||||
$folder = [pscustomobject]@{ Task = $task }
|
||||
$folder | Add-Member ScriptMethod GetTask { param($Name); return $this.Task }
|
||||
$scheduler = [pscustomobject]@{ Folder = $folder }
|
||||
$scheduler | Add-Member ScriptMethod Connect {}
|
||||
$scheduler | Add-Member ScriptMethod GetFolder { param($Path); return $this.Folder }
|
||||
return $scheduler
|
||||
}
|
||||
'@
|
||||
if ($case -eq 'log-failure') { $mocks += "`nfunction Add-Content { throw 'Injected log storage unavailable' }" }
|
||||
if ($case -eq 'counter-failure') { $mocks += "`nfunction Set-Content { throw 'Injected counter storage unavailable' }" }
|
||||
if ($case -eq 'disable-failure') { $mocks = "function New-Object { throw 'Injected access denied' }" }
|
||||
Set-Content (Join-Path $dir 'run.ps1') ($mocks + "`n" + $source)
|
||||
$output = & (Join-Path $PSHOME 'pwsh.exe') -NoProfile -File (Join-Path $dir 'run.ps1') 2>&1 | Out-String
|
||||
if ($LASTEXITCODE -ne 1) { throw "$case must fail visibly" }
|
||||
$disabled = Test-Path (Join-Path $dir 'disabled')
|
||||
if ($disabled -ne ($case -in @('counter-failure','exhausted'))) { throw "$case unexpected task disposition" }
|
||||
if ($case -in @('log-failure','child-failure') -and [int](Get-Content (Join-Path $dir 'attempts.txt')) -ne 1) { throw 'Attempt must be persisted before launch' }
|
||||
if ($case -in @('log-failure','child-failure') -and -not (Test-Path (Join-Path $dir 'launched'))) { throw 'Allowed attempt did not execute the child.' }
|
||||
if ($case -eq 'child-failure' -and -not ((Get-Content (Join-Path $dir 'run-*.log') -Raw) -match 'exited with code 7')) { throw 'Child failure code was not retained.' }
|
||||
if ($case -eq 'log-failure' -and $output -notmatch 'Runner log unavailable') { throw 'Missing stderr fallback' }
|
||||
if ($case -in @('exhausted','disable-failure','counter-failure') -and (Test-Path (Join-Path $dir 'launched'))) { throw 'A blocked attempt launched a runner' }
|
||||
if ($case -eq 'disable-failure') {
|
||||
if ($output -notmatch 'Restart budget exhausted' -or $output -notmatch 'Task disable failed') { throw 'Missing original failure or scheduler disposition' }
|
||||
if ([int](Get-Content (Join-Path $dir 'attempts.txt')) -ne 2) { throw 'Exhausted budget changed' }
|
||||
}
|
||||
Write-Output "PASS: $case"
|
||||
}
|
||||
} finally {
|
||||
if ([IO.Path]::GetFullPath($root).StartsWith([IO.Path]::GetTempPath(),[StringComparison]::OrdinalIgnoreCase)) { Remove-Item -LiteralPath $root -Recurse -Force }
|
||||
}
|
||||
exit 0
|
||||
@@ -7,7 +7,7 @@ $source = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../scripts'))
|
||||
$runner = Join-Path $root 'runner with spaces'
|
||||
$null = New-Item -ItemType Directory -Path $runner
|
||||
Set-Content -LiteralPath (Join-Path $runner '.runner') -Value '{}'
|
||||
foreach ($file in @('windows-runner-task.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $source $file) -Destination $root }
|
||||
foreach ($file in @('windows-runner-task.ps1','windows-runner-scheduler.ps1','run-windows-runner-task.ps1','windows-runner-launcher.cs','windows-runner-processes.cs','windows-runner-network.ps1','run-windows-runner-network-process.ps1')) { Copy-Item -LiteralPath (Join-Path $source $file) -Destination $root }
|
||||
$manager = Join-Path $root 'windows-runner-task.ps1'
|
||||
@'
|
||||
param([string]$RunnerRoot, [string]$ConfigRoot, [switch]$CheckOnly)
|
||||
|
||||
@@ -74,7 +74,7 @@ describe('Windows token signing', () => {
|
||||
} else {
|
||||
expect(options.env.DSH_DESKTOP_WINDOWS_TOKEN_PIN).toBeUndefined()
|
||||
expect(options.env.DSH_DESKTOP_WINDOWS_KEY_CONTAINER).toBeUndefined()
|
||||
if (command === 'powershell.exe') {
|
||||
if (command === 'pwsh') {
|
||||
const timestamped = readFileSync(options.env.DSH_RUNTIME_VERIFY_FILE!, 'utf8').endsWith(':timestamp')
|
||||
if (!timestamped) expect(existsSync(join(stateDirectory, 'attempt.json'))).toBe(true)
|
||||
callback(null, JSON.stringify({ status: mode === 'invalid-primary' ? 'NotTrusted' : 'Valid', timestamped, thumbprint: 'A'.repeat(40) }), '')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Parser fault checks; real-file equivalence is measured separately. */
|
||||
import { it as test } from 'vitest'
|
||||
import assert from 'node:assert/strict'
|
||||
import { copyFile, mkdtemp, rm } from 'node:fs/promises'
|
||||
import { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { parseSignatureRows, inspectSignaturesBatched } from '../scripts/windows-signature-batch.mjs'
|
||||
@@ -33,12 +33,18 @@ test('empty input launches no verifier and returns no rows', async () => {
|
||||
assert.deepEqual(await inspectSignaturesBatched([]), [])
|
||||
})
|
||||
|
||||
test.skipIf(process.platform !== 'win32')('Unicode paths retain the same Windows trust result as individual inspection', async (t) => {
|
||||
test.skipIf(process.platform !== 'win32')('long Unicode paths retain the same Windows trust result as short paths', async (t) => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'signature-batch-'))
|
||||
t.onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
const path = join(root, "验证 ' 文件.exe")
|
||||
await copyFile(join(process.env.SystemRoot!, 'System32', 'cmd.exe'), path)
|
||||
const expected = await inspectWindowsRuntimeSignature(path)
|
||||
const shortPath = join(root, 'short.exe')
|
||||
const directory = join(root, 'nested-'.repeat(15), 'nested-'.repeat(15))
|
||||
await mkdir(directory, { recursive: true })
|
||||
const path = join(directory, "验证 ' 文件.exe")
|
||||
assert.ok(path.length > 260)
|
||||
await copyFile(join(process.env.SystemRoot!, 'System32', 'cmd.exe'), shortPath)
|
||||
await copyFile(shortPath, path)
|
||||
const expected = await inspectWindowsRuntimeSignature(shortPath)
|
||||
assert.deepEqual(await inspectWindowsRuntimeSignature(path), expected)
|
||||
assert.equal(expected.status, 'Valid')
|
||||
assert.deepEqual(await inspectSignaturesBatched([path]), [expected])
|
||||
await signWindowsCode(root, {
|
||||
|
||||
@@ -6,6 +6,13 @@
|
||||
#include <cassert>
|
||||
#include "../installer/uninstall-data.h"
|
||||
|
||||
extern "C" __declspec(dllimport) void* __cdecl UninstallBegin(LPCWSTR);
|
||||
extern "C" __declspec(dllimport) DWORD __cdecl UninstallPrepare(void*, LPCWSTR, LPCWSTR);
|
||||
extern "C" __declspec(dllimport) DWORD __cdecl UninstallPayload(void*, LPCWSTR, LPCWSTR, LPCWSTR);
|
||||
extern "C" __declspec(dllimport) int __cdecl UninstallFinish(void*, LPCWSTR, LPCWSTR);
|
||||
|
||||
extern "C" __declspec(dllimport) void __cdecl UninstallPersist(void*);
|
||||
|
||||
static void File(const std::wstring& path, DWORD attributes = FILE_ATTRIBUTE_NORMAL) {
|
||||
HANDLE file = CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, attributes, nullptr);
|
||||
assert(file != INVALID_HANDLE_VALUE);
|
||||
@@ -46,8 +53,18 @@ int wmain(int argc, wchar_t** argv) {
|
||||
assert(uninstall_data::Remove(cache.c_str(), installation.c_str(), data.c_str()) == ERROR_ACCESS_DENIED);
|
||||
assert(uninstall_data::Remove(data.c_str(), installation.c_str(), cache.c_str()) == ERROR_ACCESS_DENIED);
|
||||
assert(uninstall_data::Remove(cache.c_str(), installation.c_str(), L"relative\\home") == ERROR_INVALID_NAME);
|
||||
std::wstring slashHome = cache;
|
||||
for (auto& character : slashHome) if (character == L'\\') character = L'/';
|
||||
assert(uninstall_data::Remove(data.c_str(), installation.c_str(), slashHome.c_str()) == ERROR_ACCESS_DENIED);
|
||||
assert(Exists(cache + L"\\CURRENT"));
|
||||
|
||||
// Unsupported protection roots stop before deleting any contents, even if they name a shared descendant.
|
||||
for (auto home : {L"\\\\server\\share", L"\\\\server\\share\\home", L"\\\\?\\UNC\\server\\share"}) {
|
||||
assert(uninstall_data::Remove(data.c_str(), installation.c_str(), home) == ERROR_INVALID_NAME);
|
||||
assert(Exists(cache + L"\\CURRENT"));
|
||||
assert(Exists(data + L"\\Local State"));
|
||||
}
|
||||
|
||||
// A pinned directory cannot be renamed or replaced while the helper holds it.
|
||||
{
|
||||
uninstall_data::Handles pinned;
|
||||
@@ -86,6 +103,81 @@ int wmain(int argc, wchar_t** argv) {
|
||||
// A protected root elsewhere does not block removal.
|
||||
assert(uninstall_data::Remove(data.c_str(), installation.c_str(), (root + L"\\elsewhere").c_str()) == ERROR_SUCCESS);
|
||||
assert(!Exists(data));
|
||||
// Exercise the shipped helper: a busy executable keeps the retry entry; auxiliary residue is reportable.
|
||||
const std::wstring report = root + L"\\report.txt";
|
||||
void* session = UninstallBegin(report.c_str());
|
||||
assert(session);
|
||||
assert(UninstallPrepare(session, installation.c_str(), nullptr) == ERROR_SUCCESS);
|
||||
File(installation + L"\\app.exe");
|
||||
File(installation + L"\\uninstall.exe");
|
||||
File(installation + L"\\aux.log");
|
||||
HANDLE mainFile = CreateFileW((installation + L"\\app.exe").c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
assert(mainFile != INVALID_HANDLE_VALUE);
|
||||
assert(UninstallPayload(session, installation.c_str(), L"app.exe", L"uninstall.exe") == 1);
|
||||
assert(Exists(installation + L"\\uninstall.exe"));
|
||||
assert(Exists(installation + L"\\aux.log"));
|
||||
CloseHandle(mainFile);
|
||||
HANDLE auxiliary = CreateFileW((installation + L"\\aux.log").c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
assert(auxiliary != INVALID_HANDLE_VALUE);
|
||||
assert(UninstallPayload(session, installation.c_str(), L"app.exe", L"uninstall.exe") == 0);
|
||||
assert(!Exists(installation + L"\\app.exe"));
|
||||
assert(UninstallFinish(session, installation.c_str(), L"uninstall.exe") == 1);
|
||||
assert(!Exists(installation + L"\\uninstall.exe"));
|
||||
assert(Exists(installation + L"\\aux.log"));
|
||||
HANDLE reportFile = CreateFileW(report.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
assert(reportFile != INVALID_HANDLE_VALUE);
|
||||
char contents[16384]{};
|
||||
DWORD length;
|
||||
assert(ReadFile(reportFile, contents, sizeof(contents) - 1, &length, nullptr));
|
||||
CloseHandle(reportFile);
|
||||
assert(strstr(contents, "aux.log"));
|
||||
assert(strstr(contents, "32"));
|
||||
CloseHandle(auxiliary);
|
||||
assert(DeleteFileW((installation + L"\\aux.log").c_str()));
|
||||
assert(DeleteFileW(report.c_str()));
|
||||
assert(RemoveDirectoryW(installation.c_str()));
|
||||
|
||||
for (auto home : {L"C:/HarnessHome", L"~/.dsh", L"~\\.dsh", L" \t "}) {
|
||||
assert(CreateDirectoryW(installation.c_str(), nullptr));
|
||||
void* alternate = UninstallBegin(report.c_str());
|
||||
assert(alternate);
|
||||
assert(UninstallPrepare(alternate, installation.c_str(), home) == ERROR_SUCCESS);
|
||||
assert(UninstallFinish(alternate, installation.c_str(), L"uninstall.exe") == 0);
|
||||
assert(!Exists(installation));
|
||||
}
|
||||
assert(CreateDirectoryW(installation.c_str(), nullptr));
|
||||
void* protectedSession = UninstallBegin(report.c_str());
|
||||
std::wstring slashInstall = installation;
|
||||
for (auto& character : slashInstall) if (character == L'\\') character = L'/';
|
||||
assert(UninstallPrepare(protectedSession, installation.c_str(), slashInstall.c_str()) == ERROR_ACCESS_DENIED);
|
||||
assert(UninstallPrepare(protectedSession, installation.c_str(), L"relative/home") == ERROR_INVALID_NAME);
|
||||
UninstallPersist(protectedSession);
|
||||
reportFile = CreateFileW(report.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
|
||||
assert(reportFile != INVALID_HANDLE_VALUE);
|
||||
ZeroMemory(contents, sizeof(contents));
|
||||
assert(ReadFile(reportFile, contents, sizeof(contents) - 1, &length, nullptr));
|
||||
CloseHandle(reportFile);
|
||||
assert(strstr(contents, "Validate DSH_HOME"));
|
||||
assert(strstr(contents, "relative/home"));
|
||||
assert(DeleteFileW(report.c_str()));
|
||||
assert(RemoveDirectoryW(installation.c_str()));
|
||||
|
||||
std::vector<std::wstring> longDirectories;
|
||||
std::wstring longDirectory = root;
|
||||
while (longDirectory.size() < 280) {
|
||||
longDirectory += L"\\" + std::wstring(60, L'x');
|
||||
assert(CreateDirectoryW((L"\\\\?\\" + longDirectory).c_str(), nullptr));
|
||||
longDirectories.push_back(longDirectory);
|
||||
}
|
||||
const std::wstring longUninstaller = L"\\\\?\\" + longDirectory + L"\\uninstall.exe";
|
||||
File(longUninstaller);
|
||||
void* longSession = UninstallBegin(report.c_str());
|
||||
assert(UninstallPrepare(longSession, longDirectory.c_str(), nullptr) == ERROR_SUCCESS);
|
||||
assert(UninstallFinish(longSession, longDirectory.c_str(), L"uninstall.exe") == 0);
|
||||
assert(!Exists(longUninstaller));
|
||||
assert(!Exists(L"\\\\?\\" + longDirectory));
|
||||
longDirectories.pop_back();
|
||||
for (auto it = longDirectories.rbegin(); it != longDirectories.rend(); ++it)
|
||||
assert(RemoveDirectoryW((L"\\\\?\\" + *it).c_str()));
|
||||
assert(RemoveDirectoryW(root.c_str()));
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<# Production uninstaller checks with isolated application identity and seeded data. #>
|
||||
<# Production uninstaller checks with isolated application identity and seeded data. #>
|
||||
[CmdletBinding()]
|
||||
param([Parameter(Mandatory)][string]$Installer, [Parameter(Mandatory)][string]$ProductName,
|
||||
[Parameter(Mandatory)][string]$RegistryKey, [Parameter(Mandatory)][string]$OutputDirectory,
|
||||
@@ -7,6 +7,7 @@ $ErrorActionPreference = 'Stop'
|
||||
$copy = (Get-Content (Join-Path $PSScriptRoot "../installer/locales/$Language.json") -Encoding UTF8 -Raw | ConvertFrom-Json).uninstaller
|
||||
$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
|
||||
. (Join-Path $PSScriptRoot 'windows-installer-ui.ps1')
|
||||
. (Join-Path $PSScriptRoot 'windows-installer-process.ps1')
|
||||
[InstallerCapture]::Initialize()
|
||||
$expected = Get-Content (Join-Path $PSScriptRoot 'expected/windows-uninstall.json') -Raw | ConvertFrom-Json
|
||||
$roaming = [Environment]::GetFolderPath('ApplicationData')
|
||||
@@ -20,7 +21,14 @@ $scopePath = Join-Path $roaming $PackageName.Split('/')[0]
|
||||
$userDataPath = Join-Path $roaming ($PackageName -replace '/', '\')
|
||||
$cachePath = Join-Path $local (($PackageName -replace '[/\\?<>:*|"]', '').ToLowerInvariant() + '-updater')
|
||||
$uninstaller = Join-Path $OutputDirectory 'uninstall-copy.exe'
|
||||
$environmentKey = "Software\DSHUninstallTests\$RegistryKey\CommandEnvironment"
|
||||
$ownerKey = "Software\DSHUninstallTests\$RegistryKey\CommandOwner"
|
||||
$protocolKey = "Software\Classes\dsh-test-$RegistryKey"
|
||||
$process = $null
|
||||
$setup = $null
|
||||
$held = $null
|
||||
$originalHome = [Environment]::GetEnvironmentVariable('DSH_HOME', 'Process')
|
||||
$strings = (Get-Content (Join-Path $PSScriptRoot "../installer/locales/$Language.json") -Encoding UTF8 -Raw | ConvertFrom-Json).strings
|
||||
function Wait-Text([string]$Text) {
|
||||
$timer = [Diagnostics.Stopwatch]::StartNew()
|
||||
do {
|
||||
@@ -46,12 +54,14 @@ function Wait-Exit {
|
||||
try {
|
||||
foreach ($mode in $expected.cases) {
|
||||
$setup = Start-Process -FilePath $Installer -ArgumentList ('/S /D=' + $installPath) -PassThru -WindowStyle Hidden
|
||||
try {
|
||||
if (-not $setup.WaitForExit(30000)) { $setup.Kill(); $setup.WaitForExit(); throw 'Setup timed out' }
|
||||
if ($setup.ExitCode -ne 0) { throw "Setup failed: $($setup.ExitCode)" }
|
||||
} finally { $setup.Dispose() }
|
||||
Wait-InstallerProcess $setup
|
||||
$setup.Dispose(); $setup = $null
|
||||
$entry = Get-ItemProperty ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey)
|
||||
if ($entry.InstallLocation.TrimEnd('\') -ne $installPath) { throw 'Uninstall entry lacks InstallLocation' }
|
||||
$deepAsset = Join-Path $installPath (('nested-' * 20) + '\' + ('asset-' * 15) + '.txt')
|
||||
if ($deepAsset.Length -le 260) { throw 'Uninstall fixture must exceed MAX_PATH' }
|
||||
[IO.Directory]::CreateDirectory('\\?\' + [IO.Path]::GetDirectoryName($deepAsset)) | Out-Null
|
||||
[IO.File]::WriteAllText(('\\?\' + $deepAsset), 'long path payload')
|
||||
foreach ($path in @($homePath, $productDataPath, $userDataPath, $cachePath, $externalPath)) { New-Item -ItemType Directory -Force -Path $path | Out-Null }
|
||||
[IO.File]::WriteAllText((Join-Path $externalPath 'keep.txt'), 'outside data root')
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $userDataPath 'linked-project'))) {
|
||||
@@ -62,38 +72,300 @@ try {
|
||||
[IO.File]::WriteAllText((Join-Path $userDataPath 'Local State'), 'chromium profile')
|
||||
[IO.File]::WriteAllText((Join-Path $cachePath 'download.txt'), 'update')
|
||||
Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force
|
||||
$missingLocation = $mode -in @('missing-location', 'missing-location-short', 'missing-location-foreign')
|
||||
$foreign = $mode -eq 'missing-location-foreign'
|
||||
if ($missingLocation) { Remove-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation }
|
||||
$arpKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey
|
||||
if ($mode -eq 'missing-location') {
|
||||
$originalCommand = (Get-ItemProperty $arpKey).UninstallString
|
||||
$alternateCommand = $originalCommand.Replace($installPath + '\', $installPath + '\.\')
|
||||
if ($alternateCommand -ceq $originalCommand -or -not $alternateCommand.Contains($installPath + '\.\')) { throw 'Equivalent-path fixture did not rewrite the uninstall command' }
|
||||
Set-ItemProperty $arpKey UninstallString $alternateCommand
|
||||
}
|
||||
if ($mode -eq 'missing-location-short') {
|
||||
$uninstallFile = Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')
|
||||
$shortFile = (New-Object -ComObject Scripting.FileSystemObject).GetFile($uninstallFile).ShortPath
|
||||
if ($shortFile -ceq $uninstallFile) { throw 'Short-name fixture has no alternate name' }
|
||||
Set-ItemProperty $arpKey UninstallString ('"' + $shortFile + '" /currentuser')
|
||||
}
|
||||
$desktopLink = Join-Path ([Environment]::GetFolderPath('DesktopDirectory')) ($ProductName + '.lnk')
|
||||
$startLink = Join-Path ([Environment]::GetFolderPath('Programs')) ($ProductName + '.lnk')
|
||||
if ($missingLocation) {
|
||||
if (-not (Test-Path -LiteralPath $startLink) -or (New-Object -ComObject WScript.Shell).CreateShortcut($startLink).TargetPath -ne (Join-Path $installPath ($ProductName + '.exe'))) { throw 'Missing A Start menu fixture' }
|
||||
$shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut($desktopLink)
|
||||
$shortcut.TargetPath = Join-Path $installPath ($ProductName + '.exe')
|
||||
$shortcut.Save()
|
||||
if (-not (Test-Path -LiteralPath $desktopLink) -or -not (Test-Path -LiteralPath $arpKey)) { throw 'Missing A uninstall fixtures' }
|
||||
}
|
||||
$integrationRoot = if ($foreign) { $externalPath } else { $installPath }
|
||||
$commandDirectory = Join-Path $integrationRoot 'resources\runtime\cli\bin'
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($environmentKey)
|
||||
try { $key.SetValue('Path', $commandDirectory + ';C:\Windows', [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $key.Dispose() }
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ownerKey)
|
||||
try { $key.SetValue('Directory', $commandDirectory); $key.SetValue('RetainedEntries', 0) } finally { $key.Dispose() }
|
||||
if ($mode -eq 'unowned') {
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($ownerKey, $true)
|
||||
try { $key.DeleteValue('Directory'); $key.DeleteValue('RetainedEntries') } finally { $key.Dispose() }
|
||||
}
|
||||
if ($mode -eq 'owned-retained') {
|
||||
Set-ItemProperty -LiteralPath ('HKCU:\' + $ownerKey) -Name RetainedEntries -Value 1
|
||||
Set-ItemProperty -LiteralPath ('HKCU:\' + $environmentKey) -Name Path -Value ($commandDirectory + ';' + $commandDirectory + ';C:\Windows')
|
||||
}
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command')
|
||||
try { $key.SetValue('', '"' + (Join-Path $integrationRoot ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() }
|
||||
$launchUninstaller = $uninstaller
|
||||
$arguments = '_?=' + $installPath
|
||||
if ($mode -in @('silent', 'home-inside')) { $arguments = '/S ' + $arguments }
|
||||
if ($mode -in @('silent', 'missing-location', 'missing-location-short', 'missing-location-foreign', 'unowned', 'owned-retained', 'home-inside', 'home-slash', 'home-tilde', 'home-slash-inside', 'registration-error', 'main-locked', 'auxiliary-locked', 'unsafe-root')) { $arguments = '/S ' + $arguments }
|
||||
# electron-builder's installUtil.nsh runs an older uninstaller with exactly these flags when replacing it.
|
||||
if ($mode -eq 'upgrade') { $arguments = '/S /KEEP_APP_DATA --updated /currentuser ' + $arguments }
|
||||
if ($mode -eq 'upgrade') {
|
||||
Set-ItemProperty -LiteralPath ('HKCU:\Software\' + $RegistryKey) -Name InstallLocation -Value ($installPath + '\')
|
||||
$arguments = '/S /KEEP_APP_DATA --updated /currentuser ' + $arguments }
|
||||
if ($mode -eq 'replaced') { $arguments = '/S /KEEP_APP_DATA /currentuser ' + $arguments }
|
||||
if ($mode -eq 'self-copy') {
|
||||
$launchUninstaller = Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')
|
||||
$arguments = '/S /KEEP_APP_DATA'
|
||||
}
|
||||
if ($mode -eq 'home-inside') { $env:DSH_HOME = Join-Path $userDataPath 'home' } else { Remove-Item Env:DSH_HOME -ErrorAction SilentlyContinue }
|
||||
$process = Start-Process -FilePath $uninstaller -ArgumentList $arguments -PassThru -WindowStyle ($(if ($mode -eq 'interactive') { 'Normal' } else { 'Hidden' }))
|
||||
if ($mode -eq 'interactive') {
|
||||
if ($mode -eq 'home-slash') { $env:DSH_HOME = $homePath.Replace('\', '/') }
|
||||
if ($mode -eq 'home-tilde') {
|
||||
if (-not $homePath.StartsWith($env:USERPROFILE + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'Tilde fixture must be inside USERPROFILE' }
|
||||
$env:DSH_HOME = '~/' + $homePath.Substring($env:USERPROFILE.Length + 1).Replace('\', '/')
|
||||
}
|
||||
if ($mode -eq 'home-slash-inside') { $env:DSH_HOME = (Join-Path $userDataPath 'home').Replace('\', '/') }
|
||||
if ($mode -in @('registration-error', 'save-report')) {
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($environmentKey, $true)
|
||||
try { $key.SetValue('Path', 42, [Microsoft.Win32.RegistryValueKind]::DWord) } finally { $key.Dispose() }
|
||||
}
|
||||
if ($mode -eq 'auxiliary-locked') {
|
||||
$residual = Join-Path $installPath 'held-log.txt'
|
||||
[IO.File]::WriteAllText($residual, 'held auxiliary data')
|
||||
$held = [IO.File]::Open($residual, 'Open', 'Read', 'Read')
|
||||
}
|
||||
if ($mode -eq 'unsafe-root') {
|
||||
$linked = Join-Path $OutputDirectory 'Linked Install'
|
||||
New-Item -ItemType Junction -Path $linked -Target $externalPath | Out-Null
|
||||
$process = Start-Process -FilePath $launchUninstaller -ArgumentList ('/S _?=' + $linked) -PassThru -WindowStyle Hidden
|
||||
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Linked root was not rejected' }
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $externalPath 'keep.txt'))) { throw 'Unsafe root deleted external files' }
|
||||
$report = Get-Content (Join-Path $env:TEMP ('DeepSeek-Harness-uninstall-' + $process.Id + '.txt')) -Raw
|
||||
if (-not $report.Contains('no deletion started')) { throw 'Unsafe scope missing from report' }
|
||||
$process.Dispose(); $process = $null
|
||||
[IO.Directory]::Delete($linked)
|
||||
}
|
||||
if ($mode -eq 'main-locked') {
|
||||
$held = [IO.File]::Open((Join-Path $installPath ($ProductName + '.exe')), 'Open', 'Read', 'Read')
|
||||
}
|
||||
$process = Start-Process -FilePath $launchUninstaller -ArgumentList $arguments -PassThru -WindowStyle ($(if ($mode -in @('interactive','save-report')) { 'Normal' } else { 'Hidden' }))
|
||||
if ($mode -in @('interactive','save-report')) {
|
||||
$welcomeText = $copy.welcome
|
||||
$welcome = Wait-Text $welcomeText
|
||||
$window = [InstallerCapture]::TopLevel($welcome)
|
||||
[void][InstallerCapture]::SaveNative($window, (Join-Path $OutputDirectory 'uninstall-welcome.png'), $false)
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
|
||||
if ($mode -eq 'save-report') {
|
||||
$save = Wait-Text $strings.INSTALLER_UNINSTALL_SAVE
|
||||
$dialog = [InstallerCapture]::TopLevel($save)
|
||||
[void][InstallerCapture]::SaveNative($dialog, (Join-Path $OutputDirectory 'uninstall-residual.png'), $false)
|
||||
[InstallerCapture]::Click($save)
|
||||
$timer = [Diagnostics.Stopwatch]::StartNew()
|
||||
do {
|
||||
$picker = [InstallerCapture]::FindWindowTitle($process.Id, $strings.INSTALLER_UNINSTALL_SAVE)
|
||||
if ($timer.Elapsed.TotalSeconds -gt 20) { throw 'Save file picker did not appear' }
|
||||
Start-Sleep -Milliseconds 25
|
||||
} while ($picker -eq [IntPtr]::Zero)
|
||||
$filename = [InstallerCapture]::FindClass($picker, 'Edit')
|
||||
if ($filename -eq [IntPtr]::Zero) { throw 'Save filename control missing' }
|
||||
$savedReport = Join-Path $OutputDirectory ('saved-report-' + [Guid]::NewGuid().ToString('N') + '.txt')
|
||||
while ([InstallerCapture]::ControlText($filename) -ne 'DeepSeek-Harness-uninstall-report.txt') {
|
||||
if ($timer.Elapsed.TotalSeconds -gt 20) { throw 'Save filename initialization did not finish' }
|
||||
Start-Sleep -Milliseconds 25
|
||||
}
|
||||
[void][InstallerCapture]::SendMessage($filename, 0xC, [IntPtr]::Zero, $savedReport)
|
||||
if ([InstallerCapture]::ControlText($filename) -ne $savedReport) { throw 'Save filename was not set' }
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($picker, 1))
|
||||
# The native picker briefly creates a probe file; the returning report dialog signals the real write is finished.
|
||||
$save = Wait-Text $strings.INSTALLER_UNINSTALL_SAVE
|
||||
$timer = [Diagnostics.Stopwatch]::StartNew()
|
||||
while (-not (Test-Path -LiteralPath $savedReport)) {
|
||||
if ($timer.Elapsed.TotalSeconds -gt 20) { throw "Save report did not create file: $([InstallerCapture]::VisibleText($process.Id))" }
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
if (-not ([IO.File]::ReadAllText($savedReport).Contains($environmentKey))) { throw 'Saved report omitted registry key' }
|
||||
[void][InstallerCapture]::PostMessage([InstallerCapture]::TopLevel($save), 0x10, [IntPtr]::Zero, [IntPtr]::Zero)
|
||||
}
|
||||
$finishedText = $copy.finished
|
||||
[void](Wait-Text $finishedText)
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
|
||||
}
|
||||
if ($mode -eq 'main-locked') {
|
||||
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Locked main executable did not stop uninstall' }
|
||||
$report = Get-Content (Join-Path $env:TEMP ("DeepSeek-Harness-uninstall-" + $process.Id + '.txt')) -Raw
|
||||
if (-not $report.Contains($ProductName + '.exe') -or -not $report.Contains('32')) { throw 'Locked executable missing from report' }
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')))) { throw 'Retry uninstaller was removed' }
|
||||
if (-not (Test-Path -LiteralPath ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey))) { throw 'Retry uninstall entry was removed' }
|
||||
$held.Dispose(); $held = $null
|
||||
$process.Dispose(); $process = $null
|
||||
$process = Start-Process -FilePath $launchUninstaller -ArgumentList $arguments -PassThru -WindowStyle Hidden
|
||||
}
|
||||
if ($mode -eq 'registration-error') {
|
||||
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 0) { throw 'Registration failure blocked uninstall' }
|
||||
$report = Get-Content (Join-Path $env:TEMP ("DeepSeek-Harness-uninstall-" + $process.Id + '.txt')) -Raw
|
||||
if (-not $report.Contains($environmentKey) -or -not $report.Contains('[Path]')) { throw 'Registry residual missing from report' }
|
||||
}
|
||||
if ($mode -eq 'auxiliary-locked') {
|
||||
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 0) { throw 'Auxiliary failure blocked uninstall' }
|
||||
if (Test-Path -LiteralPath (Join-Path $installPath ($ProductName + '.exe'))) { throw 'Auxiliary failure retained main executable' }
|
||||
$report = Get-Content (Join-Path $env:TEMP ('DeepSeek-Harness-uninstall-' + $process.Id + '.txt')) -Raw
|
||||
if (-not $report.Contains('held-log.txt')) { throw 'Auxiliary file missing from report' }
|
||||
$held.Dispose(); $held = $null
|
||||
Remove-Item -LiteralPath $residual
|
||||
[IO.Directory]::Delete($installPath)
|
||||
}
|
||||
Wait-Exit
|
||||
$retained = $mode -in @('upgrade', 'replaced')
|
||||
$retained = $missingLocation -or $mode -in @('upgrade', 'replaced', 'self-copy')
|
||||
# A DSH_HOME inside the Electron directory protects that directory (and its scope) but not the other roots.
|
||||
$userDataRetained = $retained -or $mode -eq 'home-inside'
|
||||
$userDataRetained = $retained -or $mode -in @('home-inside', 'home-slash-inside')
|
||||
if ([IO.File]::ReadAllText((Join-Path $externalPath 'keep.txt')) -ne 'outside data root') { throw 'Cleanup followed a junction into a project' }
|
||||
if (-not (Test-Path (Join-Path $homePath 'session.txt'))) { throw "Harness home retention failed: $mode" }
|
||||
if ((Test-Path (Join-Path $productDataPath 'state.txt')) -ne $retained) { throw "Product data retention failed: $mode" }
|
||||
if ((Test-Path (Join-Path $userDataPath 'Local State')) -ne $userDataRetained) { throw "Electron user data retention failed: $mode" }
|
||||
if ((Test-Path -LiteralPath $scopePath) -ne $userDataRetained) { throw "Package scope directory retention failed: $mode" }
|
||||
if ((Test-Path (Join-Path $cachePath 'download.txt')) -ne $retained) { throw "Update cache retention failed: $mode" }
|
||||
$integrationsRetained = $foreign -or $mode -in @('upgrade', 'registration-error', 'save-report')
|
||||
$owner = Get-ItemProperty -LiteralPath ('HKCU:\' + $ownerKey)
|
||||
if ([bool]$owner.Directory -ne $integrationsRetained) { throw "Command ownership cleanup failed: $mode" }
|
||||
$path = (Get-ItemProperty -LiteralPath ('HKCU:\' + $environmentKey)).Path
|
||||
$pathRetained = $integrationsRetained -or $mode -eq 'owned-retained'
|
||||
if ($mode -notin @('registration-error', 'save-report') -and ($path.Contains($commandDirectory) -ne $pathRetained -or -not $path.Contains('C:\Windows'))) { throw "PATH cleanup failed: $mode" }
|
||||
if ($mode -eq 'owned-retained' -and $path -ne ($commandDirectory + ';C:\Windows')) { throw 'Owned cleanup removed a pre-existing manual PATH entry' }
|
||||
if ((Test-Path -LiteralPath ('HKCU:\' + $protocolKey)) -ne ($foreign -or $mode -eq 'upgrade')) { throw "Protocol cleanup failed: $mode" }
|
||||
if ($missingLocation -and ((Test-Path -LiteralPath $desktopLink) -or (Test-Path -LiteralPath $startLink) -or (Test-Path -LiteralPath $arpKey))) { throw 'Missing location left an A shortcut or uninstall entry' }
|
||||
Write-Output "passed: $mode"
|
||||
}
|
||||
# Real replacement publishes B after the old A uninstaller has been retained.
|
||||
$setup = Start-Process $Installer -ArgumentList ('/S /D=' + $installPath) -PassThru -WindowStyle Hidden
|
||||
Wait-InstallerProcess $setup
|
||||
$setup.Dispose(); $setup = $null
|
||||
Copy-Item -LiteralPath (Join-Path $installPath ('Uninstall ' + $ProductName + '.exe')) -Destination $uninstaller -Force
|
||||
$oldCommand = Join-Path $installPath 'resources\runtime\cli\bin'
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ownerKey)
|
||||
try { $key.SetValue('Directory', $oldCommand); $key.SetValue('RetainedEntries', 0) } finally { $key.Dispose() }
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($environmentKey)
|
||||
try { $key.SetValue('Path', $oldCommand + ';C:\Windows') } finally { $key.Dispose() }
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command')
|
||||
try { $key.SetValue('', '"' + (Join-Path $installPath ($ProductName + '.exe')) + '" "%1"') } finally { $key.Dispose() }
|
||||
New-Item -ItemType Directory -Force -Path $userDataPath | Out-Null
|
||||
$relocationData = Join-Path $userDataPath 'relocation-state.txt'
|
||||
[IO.File]::WriteAllText($relocationData, 'retained during relocation')
|
||||
$newPath = Join-Path $OutputDirectory 'Replacement App'
|
||||
$env:DSH_HOME = $homePath.Replace('\', '/')
|
||||
$setup = Start-Process $Installer -ArgumentList ('/S /D=' + $newPath) -PassThru -WindowStyle Hidden
|
||||
Wait-InstallerProcess $setup
|
||||
$setup.Dispose(); $setup = $null
|
||||
if ((Get-ItemProperty ('HKCU:\' + $ownerKey)).Directory) { throw 'Relocation retained old command owner' }
|
||||
if ((Get-ItemProperty ('HKCU:\' + $environmentKey)).Path -ne 'C:\Windows') { throw 'Relocation retained old command PATH' }
|
||||
if (Test-Path -LiteralPath ('HKCU:\' + $protocolKey)) { throw 'Relocation retained old protocol' }
|
||||
if ([IO.File]::ReadAllText($relocationData) -ne 'retained during relocation') { throw 'Relocation removed user data' }
|
||||
$newCommand = Join-Path $newPath 'resources\runtime\cli\bin'
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($ownerKey)
|
||||
try { $key.SetValue('Directory', $newCommand) } finally { $key.Dispose() }
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($environmentKey)
|
||||
try { $key.SetValue('Path', $newCommand + ';C:\Windows') } finally { $key.Dispose() }
|
||||
$newProtocol = '"' + (Join-Path $newPath ($ProductName + '.exe')) + '" "%1"'
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($protocolKey + '\shell\open\command')
|
||||
try { $key.SetValue('', $newProtocol) } finally { $key.Dispose() }
|
||||
$process = Start-Process $uninstaller -ArgumentList ('/S /currentuser _?=' + $installPath) -PassThru -WindowStyle Hidden
|
||||
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Stale uninstaller was not rejected' }
|
||||
$process.Dispose(); $process = $null
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $newPath ($ProductName + '.exe')))) { throw 'Stale uninstaller deleted B' }
|
||||
$entry = Get-ItemProperty ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey)
|
||||
if ($entry.InstallLocation.TrimEnd('\') -ne $newPath) { throw 'Stale uninstaller removed B registration' }
|
||||
if ((Get-ItemProperty ('HKCU:\' + $ownerKey)).Directory -ne $newCommand) { throw 'Stale uninstaller changed B command owner' }
|
||||
if ((Get-ItemProperty ('HKCU:\' + $environmentKey)).Path -ne ($newCommand + ';C:\Windows')) { throw 'Stale uninstaller changed B PATH' }
|
||||
if ((Get-Item ('HKCU:\' + $protocolKey + '\shell\open\command')).GetValue('') -ne $newProtocol) { throw 'Stale uninstaller changed B protocol' }
|
||||
New-Item -ItemType Directory -Force -Path $userDataPath | Out-Null
|
||||
$replacementData = Join-Path $userDataPath 'replacement-state.txt'
|
||||
[IO.File]::WriteAllText($replacementData, 'replacement installation data')
|
||||
$replacementLinks = @{}
|
||||
foreach ($folder in @([Environment]::GetFolderPath('DesktopDirectory'), [Environment]::GetFolderPath('Programs'))) {
|
||||
$link = Join-Path $folder ($ProductName + '.lnk')
|
||||
if (Test-Path -LiteralPath $link) { $replacementLinks[$link] = [Convert]::ToBase64String([IO.File]::ReadAllBytes($link)) }
|
||||
}
|
||||
# Keep B's uninstall entry and protocol while the desktop shortcut and CLI still belong to A.
|
||||
$replacementLinks.Remove($desktopLink)
|
||||
$shortcut = (New-Object -ComObject WScript.Shell).CreateShortcut($desktopLink)
|
||||
$shortcut.TargetPath = Join-Path $installPath ($ProductName + '.exe')
|
||||
$shortcut.Save()
|
||||
Set-ItemProperty ('HKCU:\' + $ownerKey) Directory $oldCommand
|
||||
Set-ItemProperty ('HKCU:\' + $environmentKey) Path ($oldCommand + ';C:\Windows')
|
||||
$bUninstall = $entry.UninstallString
|
||||
New-Item -ItemType Directory -Force -Path $installPath | Out-Null
|
||||
Get-ChildItem -LiteralPath $newPath | Copy-Item -Destination $installPath -Recurse
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $installPath ($ProductName + '.exe')))) { throw 'Partial takeover fixture lacks the A executable' }
|
||||
$process = Start-Process $uninstaller -ArgumentList ('/S /currentuser _?=' + $installPath) -PassThru -WindowStyle Hidden
|
||||
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Existing stale directory was not rejected' }
|
||||
$report = Get-Content (Join-Path $env:TEMP ('DeepSeek-Harness-uninstall-' + $process.Id + '.txt')) -Raw
|
||||
if (-not $report.Contains('Removal not confirmed') -or -not $report.Contains($newPath) -or -not $report.Contains($installPath)) { throw 'Silent rejection report lacks reason and both paths' }
|
||||
$process.Dispose(); $process = $null
|
||||
$process = Start-Process $uninstaller -ArgumentList ('/currentuser _?=' + $installPath) -PassThru
|
||||
$welcome = Wait-Text $copy.welcome
|
||||
$window = [InstallerCapture]::TopLevel($welcome)
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
|
||||
$continue = Wait-Text $strings.INSTALLER_UNINSTALL_CONTINUE
|
||||
# TaskDialog common buttons are nested DirectUI controls; use TDM_CLICK_BUTTON with IDCANCEL.
|
||||
if (-not [InstallerCapture]::PostMessage([InstallerCapture]::TopLevel($continue), 0x466, [IntPtr]2, [IntPtr]::Zero)) { throw 'Could not cancel owner dialog' }
|
||||
if (-not $process.WaitForExit(30000) -or $process.ExitCode -ne 2) { throw 'Owner dialog cancellation did not stop uninstall' }
|
||||
$report = Get-Content (Join-Path $env:TEMP ('DeepSeek-Harness-uninstall-' + $process.Id + '.txt')) -Raw
|
||||
if (-not $report.Contains('Removal not confirmed') -or -not $report.Contains($newPath) -or -not $report.Contains($installPath)) { throw 'Cancellation report lacks reason and both paths' }
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $installPath ($ProductName + '.exe')))) { throw 'Cancellation deleted A' }
|
||||
$process.Dispose(); $process = $null
|
||||
$process = Start-Process $uninstaller -ArgumentList ('/currentuser _?=' + $installPath) -PassThru
|
||||
$welcome = Wait-Text $copy.welcome
|
||||
$window = [InstallerCapture]::TopLevel($welcome)
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
|
||||
$continue = Wait-Text $strings.INSTALLER_UNINSTALL_CONTINUE
|
||||
[void][InstallerCapture]::SaveNative([InstallerCapture]::TopLevel($continue), (Join-Path $OutputDirectory 'uninstall-directory-only.png'), $false)
|
||||
[InstallerCapture]::Click($continue)
|
||||
[void](Wait-Text $copy.finished)
|
||||
[InstallerCapture]::Click([InstallerCapture]::GetDlgItem($window, 1))
|
||||
Wait-Exit
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $newPath ($ProductName + '.exe')))) { throw 'Directory-only removal deleted B' }
|
||||
$entry = Get-ItemProperty ('HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\' + $RegistryKey)
|
||||
if ($entry.InstallLocation.TrimEnd('\') -ne $newPath) { throw 'Directory-only removal deleted B registration' }
|
||||
if ((Get-ItemProperty ('HKCU:\' + $environmentKey)).Path -ne 'C:\Windows') { throw 'A PATH entry survived partial takeover' }
|
||||
if ((Get-Item ('HKCU:\' + $protocolKey + '\shell\open\command')).GetValue('') -ne $newProtocol) { throw 'Directory-only removal changed B protocol' }
|
||||
if ([IO.File]::ReadAllText($replacementData) -ne 'replacement installation data') { throw 'Directory-only removal changed shared user data' }
|
||||
foreach ($link in $replacementLinks.Keys) {
|
||||
if ([Convert]::ToBase64String([IO.File]::ReadAllBytes($link)) -ne $replacementLinks[$link]) { throw 'Directory-only removal changed replacement shortcut' }
|
||||
}
|
||||
if ((Get-ItemProperty ('HKCU:\' + $ownerKey)).Directory -or (Test-Path -LiteralPath $desktopLink)) { throw 'A owner or shortcut survived partial takeover' }
|
||||
if ($entry.UninstallString -ne $bUninstall -or $bUninstall -notmatch '^"([^"]+)" (/currentuser)$') { throw 'B uninstall command changed' }
|
||||
$registeredExe = $Matches[1]
|
||||
$registeredArgs = $Matches[2]
|
||||
$installPath = $newPath
|
||||
if ($registeredExe -ne (Join-Path $newPath ('Uninstall ' + $ProductName + '.exe'))) { throw 'B uninstall entry targets another installation' }
|
||||
$process = Start-Process $registeredExe -ArgumentList ($registeredArgs + ' /S') -PassThru -WindowStyle Hidden
|
||||
Wait-Exit
|
||||
foreach ($key in @($arpKey, ('HKCU:\Software\' + $RegistryKey), ('HKCU:\' + $protocolKey))) {
|
||||
if (Test-Path -LiteralPath $key) { throw "B uninstall retained registration: $key" }
|
||||
}
|
||||
foreach ($link in $replacementLinks.Keys) {
|
||||
if (Test-Path -LiteralPath $link) { throw "B uninstall retained shortcut: $link" }
|
||||
}
|
||||
Write-Output 'passed: installation takeover'
|
||||
} finally {
|
||||
Remove-Item Env:DSH_HOME -ErrorAction SilentlyContinue
|
||||
if ($process) { if (-not $process.HasExited) { $process.Kill(); $process.WaitForExit() }; $process.Dispose() }
|
||||
if ($held) { $held.Dispose() }
|
||||
if ($setup) { Stop-InstallerProcess $setup; $setup.Dispose() }
|
||||
if ($process) { Stop-InstallerProcess $process; $process.Dispose() }
|
||||
if ($ProductName -ne ('Harness Installer Test ' + ([Guid]$RegistryKey).ToString('N').Substring(0, 8))) { throw 'Unexpected fixture identity' }
|
||||
foreach ($key in @("Software\DSHUninstallTests\$RegistryKey", $protocolKey, "Software\$RegistryKey", "Software\Microsoft\Windows\CurrentVersion\Uninstall\$RegistryKey")) {
|
||||
[Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($key, $false)
|
||||
}
|
||||
foreach ($folder in @('DesktopDirectory', 'Programs')) {
|
||||
$link = Join-Path ([Environment]::GetFolderPath($folder)) ($ProductName + '.lnk')
|
||||
if (Test-Path -LiteralPath $link) { Remove-Item -LiteralPath $link -Force }
|
||||
}
|
||||
[Environment]::SetEnvironmentVariable('DSH_HOME', $originalHome, 'Process')
|
||||
# Only unique test identities below known application-data parents are removed.
|
||||
foreach ($pair in @(@($productDataPath, $roaming), @($scopePath, $roaming), @($cachePath, $local))) {
|
||||
$target = [IO.Path]::GetFullPath($pair[0])
|
||||
|
||||
@@ -21,14 +21,17 @@
|
||||
en: bb889e9514678d1c
|
||||
zh: 48cbec1e907d6a2b
|
||||
/windows-signing-and-runner-operations/machine-setup-and-runner-startup/supervised-startup:
|
||||
en: cada81c15a20ecc2
|
||||
zh: 80b7a4af7b1e0e5d
|
||||
en: f4fcb23be1f3df4a
|
||||
zh: f3699f0a64a9b94b
|
||||
/windows-signing-and-runner-operations/machine-setup-and-runner-startup/unattended-windows-startup:
|
||||
en: 3b6ae5eb5177dba8
|
||||
zh: 0e7a3edeca2286c6
|
||||
/windows-signing-and-runner-operations/machine-setup-and-runner-startup/optional-network-dependency:
|
||||
en: 60f34f8637b3c252
|
||||
zh: 805435964ab20263
|
||||
en: 31ffd631dd215fc6
|
||||
zh: ebfe8a3a64ed6e02
|
||||
/windows-signing-and-runner-operations/signing-configuration:
|
||||
en: 4b5548818375eb9a
|
||||
zh: 8c975adbb1dca9c8
|
||||
en: b38f6fbfcfd73f7a
|
||||
zh: f3afb7053af7480b
|
||||
/windows-signing-and-runner-operations/signing-and-timestamp-completion:
|
||||
en: a8d23c931cafc236
|
||||
zh: 28fd4860549cdc7b
|
||||
|
||||
@@ -38,28 +38,47 @@ Run `pwsh -NoProfile -File apps/desktop/scripts/setup-windows-packaging.ps1 -Roo
|
||||
|
||||
For the complete registration, label, routing and approval sequence, start with [CI publication setup](../publishing/ci/README.md#setup-sequence). The task installer requires the Windows .NET Framework 4.5+ compiler at `%SystemRoot%/Microsoft.NET/Framework64/v4.0.30319/csc.exe`. It compiles a GUI executable into `runner/dsh-task/launcher.exe`; this executable starts PowerShell with no console and waits for it to exit. The output and errors of `run.ps1` itself go to uniquely named `launcher-*.out.log` and `launcher-*.err.log`; filenames include UTC time, PID and a random identifier. Launcher failures disable periodic starts, including failures before the retry budget can be read. Task result `2` indicates launcher failure; `3` means its error log could not be written; `4` means disabling the task also failed and an operator must disable it in Task Scheduler. After the direct child exits, output draining is limited to five seconds. A timeout returns `5` with a `launcher-*.drain.log` diagnostic: output may be incomplete, but periodic recovery continues within the existing restart budget. Descendant processes may outlive the exited runner; draining logs does not terminate them. The recorded stop target is the launcher process, so stop includes the launcher and its descendants. Normal runner output remains in `run-*.log`.
|
||||
|
||||
Run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging` as the runner's Windows user, using its installed PowerShell 7. The installer checks the environment and copies startup scripts into `runner/dsh-task`; registration, tools and secrets remain separate. It registers a disabled, limited-permission interactive Task Scheduler task without storing an account password. Task priority 4 gives the runner and its children normal CPU, I/O and memory priority; the scheduler default 7 lowers all three and slows dependency installation. Existing tasks retain their settings: while the runner is idle, stop, uninstall and reinstall the task before starting it again. For `-Action start` or `-Action status`, pass only `-RunnerRoot`; configuration and retry options apply only to installation. The task starts after this user's desktop login, including after reboot, and stops on logout. It does not provide unattended boot or unlock a signing Token.
|
||||
Run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging` as the runner's Windows user, using its installed PowerShell 7. The installer checks the environment and copies startup scripts into `runner/dsh-task`; registration, tools and secrets remain separate. It registers a disabled, limited-permission interactive Task Scheduler task without storing an account password. Task priority 4 gives the runner and its children normal CPU, I/O and memory priority; the scheduler default 7 lowers all three and slows dependency installation. Existing tasks retain their settings: while the runner is idle, stop, uninstall and reinstall the task before starting it again. For `-Action start` or `-Action status`, pass only `-RunnerRoot`; configuration and retry options apply only to installation. The task starts after this user's desktop login, including after reboot, and stops on logout. This default `Interactive` mode requires desktop login; neither startup mode unlocks a signing Token.
|
||||
|
||||
The task permits one instance and has no execution time limit. A repeating trigger checks every `-RestartMinutes` minutes (default `1`) and restarts an exited launcher, including an unexpected zero exit. The persisted budget permits the initial launch plus `-RestartCount` restarts (default `10`) between explicit starts. Every desktop login also consumes this budget; `status` shows the remaining launches. After the budget is exhausted, login alone cannot restart the runner. Starting an already running task does not reset the budget. Missing or invalid budget/configuration files disable automatic starts until repaired. GitHub's launcher owns runner updates; task recovery does not rerun a failed workflow or clear signing interlocks. After retries are exhausted, inspect `runner/dsh-task/run-*.log`, the runner's `_diag` logs and `status`, correct the cause, then run `start`. A running task alone does not prove connectivity: verify `Connected to GitHub` and `Listening for Jobs`, then verify assignment in Actions. Both `run-*.log` and `launcher-*.log` are retained for operator-managed cleanup.
|
||||
The task permits one instance and has no execution time limit. A repeating trigger checks every `-RestartMinutes` minutes (default `1`) and restarts an exited launcher, including an unexpected zero exit. The persisted budget permits the initial launch plus `-RestartCount` restarts (default `10`) between explicit starts. Every trigger that launches the task also consumes this budget; `status` shows the remaining launches. After the budget is exhausted, login or reboot alone cannot restart the runner. Starting an already running task does not reset the budget. Missing or invalid budget/configuration files prevent runner launches and request task disabling. If scheduler access is denied, an administrator must disable the triggers. Failures after reserving an attempt retain bounded recovery; unavailable runner logs fall back to launcher stderr. GitHub's launcher owns runner updates; task recovery does not rerun a failed workflow or clear signing interlocks. After retries are exhausted, inspect `runner/dsh-task/run-*.log`, the runner's `_diag` logs and `status`, correct the cause, then run `start`. A running task alone does not prove connectivity: verify `Connected to GitHub` and `Listening for Jobs`, then verify assignment in Actions. Both `run-*.log` and `launcher-*.log` are retained for operator-managed cleanup.
|
||||
|
||||
Before maintenance, pause new workflow dispatch and wait for the runner to become idle. `-Action stop` refuses an active worker for this runner, disables future starts and stops its task process tree; the local check cannot prevent a concurrent GitHub assignment. `-Action uninstall` requires a stopped, disabled task and retains registration, configuration and logs. Pulling repository changes does not update the installed copy. To upgrade it, record the original -ConfigRoot, optional -NetworkRoot and retry settings, then run `stop`, `uninstall`, `install` with those settings, and `start` from the updated checkout. Confirm listening and job assignment again. When migrating a manually launched runner, stop its existing launcher only after it is idle, then start the task; never run both launchers together.
|
||||
Before maintenance, pause new workflow dispatch and wait for the runner to become idle. `-Action stop` refuses an active worker for this runner, disables future starts and stops its task process tree; the local check cannot prevent a concurrent GitHub assignment. `-Action uninstall` requires a stopped, disabled task and retains registration, configuration and logs. Pulling repository changes does not update the installed copy. To upgrade it, record the startup mode, original -ConfigRoot, optional -NetworkRoot and retry settings, then run `stop`, `uninstall`, `install` with those settings, and `start` from the updated checkout; Boot mode also requires `register-boot` before `start`. Confirm listening and job assignment again. When migrating a manually launched runner, stop its existing launcher only after it is idle, then start the task; never run both launchers together.
|
||||
|
||||
Operators can run `pwsh -NoProfile -File apps/desktop/tests/windows-runner-task.ps1` on Windows to exercise installation, console-free initial launch and automatic recovery, duplicate-start prevention, stop, child-process teardown, containment of startup/logging failures and uninstall against an isolated fake runner. This opt-in test creates a temporary task and retains diagnostic files; it does not contact GitHub or access signing hardware. `pwsh -NoProfile -File apps/desktop/tests/windows-runner-launcher.ps1` checks the GUI executable, child console absence, exit status, diagnostic output and bounded draining with an inherited writer without Task Scheduler; Windows CI runs it. Real-machine acceptance additionally checks an idle runner coming online without a visible Terminal window, an Actions job being assigned, and login after an operator-approved reboot. Signed packaging and logout/reboot acceptance require separate operator verification.
|
||||
|
||||
### Unattended Windows startup
|
||||
|
||||
Use `Boot` mode when the runner must accept jobs before desktop login. Prepare files under the existing runner account, which may remain a standard user. Use a separate elevated administrator session only for registration. Run the administrator command from a verified, administrator-owned checkout whose scripts and parent directories are not writable by the runner account; never elevate scripts from its checkout; it reads prepared configuration but does not execute the runner-owned launcher or preflight. The task grants its runner account management access and always runs with limited privileges and priority 4. Management uses Task Scheduler COM and native process snapshots instead of requiring CIM namespace access.
|
||||
|
||||
1. Pause workflow dispatch, wait for idle and stop any existing launcher. For an installed task, run `stop` then `uninstall` as its owner; retain configuration, caches and signing interlocks. Installation rejects active or unreadable runner processes and a native runner `.service` registration.
|
||||
2. As the runner account, run `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -StartupMode Boot -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging`, retaining any `-NetworkRoot` and retry options. This checks tools/network, compiles the launcher and prepares the startup snapshot; it does not register a task.
|
||||
3. In an elevated administrator PowerShell, run `pwsh -NoProfile -File <administrator-owned-checkout>/apps/desktop/scripts/windows-runner-task.ps1 -Action register-boot -RunnerRoot <registered-runner-directory> -RunAs <machine-or-domain\runner-account>`. The account must match preparation. Enter its Windows password in the local prompt, not a Hello PIN or signing PIN. Registration submits credentials once and creates a disabled Password/AtStartup task. On failure, inspect Task Scheduler before retrying because registration may have committed; no automatic authentication retry occurs.
|
||||
4. As the runner account, run the same manager with `-Action start -RunnerRoot <registered-runner-directory>`, then `-Action status`. Check the account, `LogonType=Password`, `BootTrigger=True`, remaining launches and listener logs. To return to login-only startup, stop and uninstall the task, then install without `-StartupMode Boot` and start.
|
||||
|
||||
The administrator must ensure batch-logon permission, no overriding deny policy, and runner access to its tools, private configuration, caches and logs. After an account password change, pause dispatch, wait for idle, run `stop` and `uninstall` as the runner account, repeat administrator `register-boot`, then run `start`; retain the prepared files without repeating `install`. Network dependencies, disk access and signing hardware must be available before login; prevent sleep during service hours. There is no desktop auto-login configuration. Healthy reboots also consume the persisted launch budget; no healthy-runtime reset or exhaustion alert exists. Check `status` and `RemainingLaunches` during maintenance; while idle, `stop` then `start` resets the budget. Recovery cannot clear a signing interlock or retry failed hardware signing.
|
||||
|
||||
Windows CI checks task XML, preparation, invalid configuration, absent/mismatched credentials, prompt errors and single-attempt registration with isolated substitutes; it does not register a real Boot task. Interactive prompt cancellation may terminate through the PowerShell host; substituted credential tests do not qualify that host behavior. Deployment operators must validate registration with separate administrator/standard accounts, task management permissions and a reboot without desktop login, followed by actual job assignment and a signed package on each new machine. Existing machine results do not qualify a new startup snapshot.
|
||||
|
||||
### Optional network dependency
|
||||
|
||||
Choose the network owner before installing Boot startup. An external service is suitable only after its forwarding process and required destinations have been verified after reboot without desktop login. A service reporting `Running`, a saved restore setting or a successful probe after login does not establish this: desktop software may stop its forwarding process and clear recovery state during logout or shutdown. If networking depends on that software, use the dedicated child-process mode below or provision an independently managed pre-login service. `runner-network.json` configures checks and proxy variables; it does not launch the proxy. Omitting `-NetworkRoot` leaves network startup to the external owner.
|
||||
|
||||
Without `runner-network.json` in `ConfigRoot`, startup retains its scrubbed direct-network behavior. To configure a network dependency, create that operator-owned JSON file outside the checkout with exactly `proxyUrl`, `noProxy`, `serviceName`, `probeUrl`, `attempts`, `timeoutSeconds` and `retrySeconds`. The first four fields are strings; the three budgets are integers from 1 through 60. Use an empty `proxyUrl` for direct access and an empty `serviceName` when no Windows service owns the dependency. URLs must use HTTP(S) without credentials, queries or fragments; the proxy URL cannot include a path. Startup applies `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and `NODE_USE_ENV_PROXY` after environment scrubbing, then requires a successful Node HEAD probe before admitting the runner. Service readiness checks never start or stop a Windows service.
|
||||
|
||||
For a dedicated child process, add `-NetworkRoot <absolute-private-network-directory>` to task installation. That directory must contain `launch.json` with exactly an absolute `executable` filename, an `arguments` string array and an integer `restartDelaySeconds` from 1 through 3600. This mode requires `runner-network.json`; set its `serviceName` to empty. Give the child its own data directory, listener bindings and executable identity, distinct from applications managed by desktop software; separate ports alone do not prevent another manager from terminating a process by executable name. The scripts do not alter desktop network settings. Keep actual provider names, paths, addresses, ports and arguments in machine configuration, never in repository files or shared logs. Restrict access to both configuration directories to the runner operator.
|
||||
|
||||
Installation starts the dependency for readiness checking and stops it before registering the task. While the runner lives, the supervisor restarts only an exited owned network process after the configured delay, including repeated launch failures; it does not restart the runner or retry jobs or signing. Exit, restart and launch-failure messages appear in `run-*.log`; provider output is discarded. Restart messages establish process creation, not network availability: confirm reconnection in runner logs. A live but unresponsive dependency requires operator diagnosis. The supervisor exclusively locks `NetworkRoot`, verifies PID, start time and executable before reclaiming a stale child, and stops its child when the runner exits. Unrecoverable supervision errors leave the active runner alive until it exits and report that recovery has stopped. Preserve `NetworkRoot` when reinstalling; pulling changes alone does not replace installed helpers.
|
||||
|
||||
Windows CI runs `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` and `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1` with isolated local fixtures. On a configured packaging machine, add `-CheckStartup` to the first command to verify network configuration after the actual startup environment scrub. These tests use no signing hardware or external network endpoints.
|
||||
Windows CI runs `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` and `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1` with isolated local fixtures. On a configured packaging machine, add `-CheckStartup` to the first command to verify network configuration after the actual startup environment scrub. The readiness probe sets its exit status and lets Node drain normally; response cancellation, request timeout and the outer process deadline remain enforced. Tests cover HTTP success, non-2xx responses, refused proxy connections and request timeout through the real redirected child-process path, without signing hardware or external endpoints.
|
||||
|
||||
For a new machine, keep the runner disabled while preparing and testing network access. A disabled runner task does not launch its owned network child; test that child separately without starting the listener. After an operator-approved reboot, verify the selected proxy and required destinations before any desktop login or manual network-client launch. Record whether a desktop shell was present and which process supplied the proxy. If this fails, inspect the network owner's startup/shutdown logs before retrying. Only after network qualification should an operator enable the runner and validate Boot startup and job assignment; signing qualification remains separate.
|
||||
|
||||
<a id="signing-configuration"></a>
|
||||
|
||||
## Signing configuration
|
||||
|
||||
Windows packaging requires PowerShell 7 (`pwsh`) on `PATH`. The toolchain check verifies Authenticode support before building; runtime signature checks use this engine to handle paths longer than 260 characters.
|
||||
|
||||
The [machine preset configuration](../packaging/README.md#configuration-and-local-builds) selects public settings and the signing file. Without a preset, use the target dotenv file.
|
||||
|
||||
Fill in `.env.windows` with `DSH_DESKTOP_WINDOWS_CER_FILE` (public EV leaf certificate), `DSH_DESKTOP_WINDOWS_SIGNTOOL` (SafeNet-compatible SignTool), `DSH_DESKTOP_WINDOWS_KEY_CONTAINER` (matching private-key container), and `DSH_DESKTOP_WINDOWS_TOKEN_PIN` (Token Password). The private key stays on the USB token; keep the certificate and local credential file out of Git.
|
||||
|
||||
@@ -38,28 +38,47 @@ description: "配置和维护 Windows 打包 runner、签名凭据、EV Token
|
||||
|
||||
完整的注册、标签、路由和审批配置顺序见 [CI 发布配置](../publishing/ci/README.zh.md#setup-sequence)。任务安装器需要 Windows .NET Framework 4.5+ 编译器,路径为 `%SystemRoot%/Microsoft.NET/Framework64/v4.0.30319/csc.exe`。它将 GUI 可执行文件编译到 `runner/dsh-task/launcher.exe`;该程序不分配控制台地启动 PowerShell,并等待其退出。`run.ps1` 自身的输出和错误分别写入名称唯一的 `launcher-*.out.log` 和 `launcher-*.err.log`,文件名包含 UTC 时间、PID 和随机标识。启动器失败时禁用周期启动,包括尚未读取重试预算时发生的失败。任务结果 `2` 表示启动器失败,`3` 表示无法写入错误日志,`4` 表示禁用任务也失败,需要操作者在计划任务中手动禁用。直接子进程退出后,最多等待五秒排空输出;超时返回 `5`,将诊断写入 `launcher-*.drain.log`:输出可能不完整,但周期恢复仍受原有重试预算约束。后代进程可能在 runner 退出后继续运行;日志排空不会终止它们。记录的停止目标是启动器进程,因此 stop 覆盖启动器及其后代。正常 runner 输出仍保存在 `run-*.log`。
|
||||
|
||||
以 runner 的 Windows 用户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging`,使用该机器安装的 PowerShell 7。安装器检查环境,并将启动脚本复制到 `runner/dsh-task`;注册、工具和凭据仍单独管理。它注册一个初始禁用、权限受限的交互式计划任务,不保存账户密码。任务优先级 4 让 runner 及子进程使用普通 CPU、I/O 和内存优先级;计划任务默认值 7 会降低三者的优先级,使依赖安装变慢。已有任务保留原设置:在 runner 空闲时停止、卸载并重新安装任务,再启动。执行 `-Action start` 或 `-Action status` 时只传 `-RunnerRoot`;配置目录及重试选项仅适用于安装。任务在该用户登录桌面后启动,重启后也需要登录,注销时停止。它不提供无人值守开机,也不解锁签名 Token。
|
||||
以 runner 的 Windows 用户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging`,使用该机器安装的 PowerShell 7。安装器检查环境,并将启动脚本复制到 `runner/dsh-task`;注册、工具和凭据仍单独管理。它注册一个初始禁用、权限受限的交互式计划任务,不保存账户密码。任务优先级 4 让 runner 及子进程使用普通 CPU、I/O 和内存优先级;计划任务默认值 7 会降低三者的优先级,使依赖安装变慢。已有任务保留原设置:在 runner 空闲时停止、卸载并重新安装任务,再启动。执行 `-Action start` 或 `-Action status` 时只传 `-RunnerRoot`;配置目录及重试选项仅适用于安装。任务在该用户登录桌面后启动,重启后也需要登录,注销时停止。默认的 `Interactive` 模式需要桌面登录;两种启动模式都不会解锁签名 Token。
|
||||
|
||||
任务只允许一个实例,且没有执行时限。周期触发器每隔 `-RestartMinutes` 分钟(默认 `1`)检查一次,并恢复已退出的启动器,包括意外的零退出码。持久预算允许首次启动及 `-RestartCount` 次重启(默认 `10`),直到再次显式启动。每次桌面登录也会消耗预算,`status` 显示剩余启动次数;预算耗尽后,仅登录不能重启 runner。对正在运行的任务执行 start 不会重置预算。预算或配置文件缺失、无效时,自动启动会禁用,需修复后恢复。GitHub 启动器负责 runner 更新;任务恢复不会重跑失败的 workflow,也不会清除签名互锁。重试耗尽后,检查 `runner/dsh-task/run-*.log`、runner 的 `_diag` 日志和 `status`,修复原因后运行 `start`。任务运行不等于连接成功:确认出现 `Connected to GitHub` 和 `Listening for Jobs`,再到 Actions 确认任务分配。`run-*.log` 和 `launcher-*.log` 均保留,由操作者管理清理。
|
||||
任务只允许一个实例,且没有执行时限。周期触发器每隔 `-RestartMinutes` 分钟(默认 `1`)检查一次,并恢复已退出的启动器,包括意外的零退出码。持久预算允许首次启动及 `-RestartCount` 次重启(默认 `10`),直到再次显式启动。每次触发器启动任务也会消耗预算,`status` 显示剩余启动次数;预算耗尽后,仅登录或重启机器不能重启 runner。对正在运行的任务执行 start 不会重置预算。预算或配置文件缺失、无效时阻止 runner 启动并请求禁用任务;若计划任务访问被拒绝,管理员需禁用触发器。预留启动次数后发生的失败保留有界恢复;runner 日志不可用时回退到启动器 stderr。GitHub 启动器负责 runner 更新;任务恢复不会重跑失败的 workflow,也不会清除签名互锁。重试耗尽后,检查 `runner/dsh-task/run-*.log`、runner 的 `_diag` 日志和 `status`,修复原因后运行 `start`。任务运行不等于连接成功:确认出现 `Connected to GitHub` 和 `Listening for Jobs`,再到 Actions 确认任务分配。`run-*.log` 和 `launcher-*.log` 均保留,由操作者管理清理。
|
||||
|
||||
维护前暂停新 workflow 的触发,等待 runner 空闲。`-Action stop` 在该 runner 存在活跃 worker 时拒绝停止,否则禁用后续启动并停止任务进程树;本地检查无法阻止 GitHub 同时分配任务。`-Action uninstall` 要求任务已停止并禁用,保留注册、配置和日志。拉取仓库更新不会更新已安装的副本。升级时先记录原来的 -ConfigRoot、可选的 -NetworkRoot 和重试设置,再从更新后的 checkout 依次执行 `stop`、`uninstall`、携带原设置的 `install` 和 `start`,最后重新确认监听与 job 分配。迁移手动启动的 runner 时,只在空闲后停止原启动器,再启动计划任务;不要同时运行两个启动器。
|
||||
维护前暂停新 workflow 的触发,等待 runner 空闲。`-Action stop` 在该 runner 存在活跃 worker 时拒绝停止,否则禁用后续启动并停止任务进程树;本地检查无法阻止 GitHub 同时分配任务。`-Action uninstall` 要求任务已停止并禁用,保留注册、配置和日志。拉取仓库更新不会更新已安装的副本。升级时先记录启动模式、原来的 -ConfigRoot、可选的 -NetworkRoot 和重试设置,再从更新后的 checkout 依次执行 `stop`、`uninstall`、携带原设置的 `install` 和 `start`;Boot 模式还需在 `start` 前执行 `register-boot`,最后重新确认监听与 job 分配。迁移手动启动的 runner 时,只在空闲后停止原启动器,再启动计划任务;不要同时运行两个启动器。
|
||||
|
||||
操作者可在 Windows 上运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-task.ps1`,使用隔离的假 runner 验证安装、无控制台的首次启动与自动恢复、防止重复启动、停止、子进程退出、启动/日志失败时的禁用处理和卸载。此显式运行的测试创建临时任务并保留诊断文件,不连接 GitHub 或访问签名硬件。`pwsh -NoProfile -File apps/desktop/tests/windows-runner-launcher.ps1` 无需计划任务,检查 GUI 可执行文件、子进程无控制台、退出状态、诊断输出以及存在继承管道写端时的有界排空;Windows CI 会执行该测试。真实机器验收还需检查空闲 runner 上线且不出现 Terminal 窗口、Actions job 分配,以及经操作者批准的重启后登录。签名打包和注销/重启验收需要操作者单独验证。
|
||||
|
||||
### Windows 无人值守启动
|
||||
|
||||
runner 需要在桌面登录前接单时使用 `Boot` 模式。由原 runner 账户准备文件,该账户可保持标准用户;仅注册步骤使用独立的管理员提权会话。管理员必须从已核验、归管理员所有且 runner 账户无法写入脚本及其父目录的 checkout 执行命令,不得提权执行 runner checkout 中的脚本;该步骤读取已准备的配置,不执行 runner 所属的启动器或预检。任务授予运行账户管理权限,始终以受限权限和优先级 4 运行。管理使用 Task Scheduler COM 和原生进程快照,不要求 CIM 命名空间访问权限。
|
||||
|
||||
1. 暂停 workflow 触发,等待空闲并停止现有启动器。已有任务由所属账户先执行 `stop` 再执行 `uninstall`,保留配置、缓存及签名互锁。安装会拒绝活跃或路径不可读的 runner 进程,以及原生 runner 的 `.service` 注册。
|
||||
2. 以 runner 账户运行 `pwsh -NoProfile -File apps/desktop/scripts/windows-runner-task.ps1 -Action install -StartupMode Boot -RunnerRoot <registered-runner-directory> -ConfigRoot <machine-root>/packaging`,保留原有 `-NetworkRoot` 和重试选项。此步骤检查工具和网络、编译启动器并准备启动快照,不注册任务。
|
||||
3. 在管理员提权 PowerShell 中运行 `pwsh -NoProfile -File <administrator-owned-checkout>/apps/desktop/scripts/windows-runner-task.ps1 -Action register-boot -RunnerRoot <registered-runner-directory> -RunAs <machine-or-domain\runner-account>`。账户必须与准备阶段一致。在本机提示中输入该账户的 Windows 密码,不是 Hello PIN 或签名 PIN。注册只提交一次凭据,创建初始禁用的 Password/AtStartup 任务。失败后先检查计划任务再重试,因为注册可能已经完成;不会自动重试认证。
|
||||
4. 以 runner 账户运行同一管理脚本,传入 `-Action start -RunnerRoot <registered-runner-directory>`,再执行 `-Action status`。核对账户、`LogonType=Password`、`BootTrigger=True`、剩余启动次数和监听日志。恢复登录后启动时,停止并卸载任务,再不带 `-StartupMode Boot` 安装并启动。
|
||||
|
||||
管理员须确保批处理登录权限、没有覆盖它的拒绝策略,以及 runner 对工具、私有配置、缓存和日志的访问权限。账户密码变更后,暂停触发并等待空闲,由 runner 账户执行 `stop`、`uninstall`,管理员重新执行 `register-boot`,再由 runner 账户执行 `start`;保留准备文件,无需再次 `install`。网络依赖、磁盘和签名硬件须在登录前可用,服务时段应避免睡眠。脚本不配置桌面自动登录。正常重启也消耗持久启动预算,没有健康运行后自动重置或耗尽告警;维护时检查 `status` 的 `RemainingLaunches`,空闲时执行 `stop` 再 `start` 可重置预算。恢复不能清除签名互锁或重试失败的硬件签名。
|
||||
|
||||
Windows CI 使用隔离替身检查任务 XML、准备阶段、无效配置、凭据缺失/不匹配及提示抛错和单次注册,不注册真实 Boot 任务。交互式取消可能由 PowerShell 宿主直接终止,凭据替身测试不代表该宿主行为已经验收。部署操作者须在每台新机器验证独立管理员与标准账户的注册、任务管理权限,以及不登录桌面的重启、实际接单和签名打包。旧机器结果不能替代新启动快照的验收。
|
||||
|
||||
### 可选网络依赖
|
||||
|
||||
安装 Boot 启动前,先明确网络进程由谁管理。只有在重启后、不登录桌面的条件下验证转发进程及所需目标地址可用,才能依赖外部服务。服务显示 `Running`、已保存恢复设置或登录后探测成功都不足以证明这一点:桌面软件可能在注销或关机时停止转发进程并清除恢复状态。若网络依赖此类软件,请使用下述专用子进程模式,或部署独立管理的登录前服务。`runner-network.json` 只配置检查和代理变量,不会启动代理;省略 `-NetworkRoot` 就意味着由外部管理者负责网络启动。
|
||||
|
||||
`ConfigRoot` 中没有 `runner-network.json` 时,启动仍使用清理继承环境后的直连行为。要配置网络依赖,请在 checkout 外创建操作者管理的该 JSON 文件,且只包含 `proxyUrl`、`noProxy`、`serviceName`、`probeUrl`、`attempts`、`timeoutSeconds` 和 `retrySeconds`。前四个字段为字符串,后三个预算为 1 至 60 的整数。直连时将 `proxyUrl` 留空,没有 Windows 服务管理依赖时将 `serviceName` 留空。URL 必须使用 HTTP(S),不能包含凭据、查询参数或片段;代理 URL 不能包含路径。启动脚本在清理环境后设置 `HTTP_PROXY`、`HTTPS_PROXY`、`NO_PROXY` 和 `NODE_USE_ENV_PROXY`,并要求 Node HEAD 探测成功才允许启动 runner。服务就绪检查不会启动或停止 Windows 服务。
|
||||
|
||||
若使用专用子进程,在安装任务时添加 `-NetworkRoot <absolute-private-network-directory>`。该目录必须包含 `launch.json`,且只包含绝对路径的 `executable` 文件名、字符串数组 `arguments`,以及 1 至 3600 的整数 `restartDelaySeconds`。此模式要求存在 `runner-network.json`,其中 `serviceName` 应留空。为子进程分配独立的数据目录、监听绑定和可执行文件标识,与桌面软件管理的应用分离;仅使用不同端口无法防止其他管理器按可执行文件名终止进程。脚本不会修改桌面网络设置。实际服务商名称、路径、地址、端口和参数只保存在机器配置中,不得写入仓库文件或共享日志。将两个配置目录的访问权限限制为 runner 操作者。
|
||||
|
||||
安装时会启动依赖进行就绪检查,并在注册任务前停止它。runner 存活期间,守卫仅在自己拥有的网络进程退出后,按配置间隔重新启动它;启动连续失败时仍会重试,但不会重启 runner、重跑任务或重试签名。退出、重启和启动失败消息写入 `run-*.log`,依赖进程的输出会被丢弃。重启消息只表明进程已创建,不代表网络可用;请在 runner 日志中确认重新连接。进程仍存活但无响应时需要操作者排查。守卫独占锁定 `NetworkRoot`,回收残留子进程前核对 PID、启动时间和可执行文件,并在 runner 退出时停止子进程。不可恢复的守卫错误会保留活动 runner 直到其退出,并报告恢复已停止。重新安装时保留 `NetworkRoot`;仅拉取代码不会替换已安装的辅助脚本。
|
||||
|
||||
Windows CI 使用隔离的本地 fixture 运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` 和 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1`。在已配置的打包机器上,给第一条命令添加 `-CheckStartup`,可验证实际启动环境清理后的网络配置。这些测试不会使用签名硬件或外部网络端点。
|
||||
Windows CI 使用隔离的本地 fixture 运行 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network.ps1` 和 `pwsh -NoProfile -File apps/desktop/tests/windows-runner-network-process.ps1`。在已配置的打包机器上,给第一条命令添加 `-CheckStartup`,可验证实际启动环境清理后的网络配置。就绪探测设置退出状态并让 Node 正常完成清理,保留响应体取消、请求超时和外层进程期限保护。测试通过真实重定向子进程路径覆盖 HTTP 成功、非 2xx、代理连接拒绝和请求超时,不使用签名硬件或外部网络端点。
|
||||
|
||||
新机器准备和测试网络时,保持 runner 禁用。禁用的 runner 任务不会启动其托管的网络子进程;应单独测试该子进程,不启动 listener。经操作者批准重启后,在登录桌面或手动打开网络客户端之前,验证所选代理及所需目标地址,记录当时是否存在桌面 Shell,以及由哪个进程提供代理。若失败,先检查网络管理者的启动和关闭日志,再重试。网络验收通过后,才由操作者启用 runner,验证 Boot 启动与任务分配;签名另行验收。
|
||||
|
||||
<a id="signing-configuration"></a>
|
||||
|
||||
## 签名配置
|
||||
|
||||
Windows 打包要求 `PATH` 中提供 PowerShell 7(`pwsh`)。工具链检查在构建前验证 Authenticode 支持;运行时签名检查使用此引擎处理超过 260 个字符的路径。
|
||||
|
||||
通过[机器 preset 配置](../packaging/README.zh.md#configuration-and-local-builds)选择公开设置与签名文件;不选择 preset 时使用目标 dotenv 文件。
|
||||
|
||||
在 `.env.windows` 中填写 `DSH_DESKTOP_WINDOWS_CER_FILE`(公开 EV 叶证书)、`DSH_DESKTOP_WINDOWS_SIGNTOOL`(SafeNet 兼容的 SignTool)、`DSH_DESKTOP_WINDOWS_KEY_CONTAINER`(匹配的私钥容器)和 `DSH_DESKTOP_WINDOWS_TOKEN_PIN`(Token Password)。私钥仍保留在 USB Token;不要把证书或本地凭据文件提交到 Git。
|
||||
|
||||
@@ -627,7 +627,8 @@ describe('web e2e: agent teamwork panel', () => {
|
||||
expect(await panel.count()).toBe(1)
|
||||
await page.mouse.click(2, 2)
|
||||
await panel.waitFor({ state: 'detached' })
|
||||
await page.setViewportSize(viewport)
|
||||
// A width whose transcript cannot move aside for the panel, so the toggle opens it over the conversation.
|
||||
await page.setViewportSize({ width: 1100, height: viewport.height })
|
||||
await trigger.focus()
|
||||
await page.keyboard.press('Enter')
|
||||
await tasksHeading.waitFor()
|
||||
@@ -675,8 +676,9 @@ describe('web e2e: agent teamwork panel', () => {
|
||||
const row = board.locator(`[data-team-task="${task.id}"]`)
|
||||
const emptyRow = board.locator(`[data-team-task="${completed.id}"]`)
|
||||
onTestFinished(() => page.setViewportSize(viewport))
|
||||
// Constrain the panel so closed and expanded task rows both exercise its scrollbar.
|
||||
await page.setViewportSize({ width: viewport.width, height: 500 })
|
||||
// Constrain the panel so closed and expanded task rows both exercise its scrollbar, at a width whose transcript
|
||||
// cannot move aside for it: the panel opens over the conversation and stays mounted as the window narrows below.
|
||||
await page.setViewportSize({ width: 1100, height: 500 })
|
||||
await showSharedTasksSection(page)
|
||||
await row.waitFor()
|
||||
expect(await board.locator('[data-team-task-details], article').count()).toBe(0)
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts,
|
||||
launchWebScaffold, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold,
|
||||
} from './scaffold.ts'
|
||||
import { connectFreshWorkspaceZh, saveFailureShot, ZH_BROWSER_LOCALE } from './support.ts'
|
||||
import { connectFreshWorkspaceZh, saveFailureShot, startWithSessionPanelHidden, ZH_BROWSER_LOCALE } from './support.ts'
|
||||
|
||||
const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/deepseek-messages-chat', import.meta.url))
|
||||
const FIXTURE = join(SNAPSHOT_DIR, 'session.v3.jsonl')
|
||||
@@ -38,6 +38,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek Messages conversation', ()
|
||||
await scaffold.ctx.agentDefaultModel.saveSelection({ provider: 'deepseek-messages', model: 'deepseek-v4-flash' })
|
||||
browser = await chromium.launch()
|
||||
page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
|
||||
await startWithSessionPanelHidden(page)
|
||||
tripwire = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await connectFreshWorkspaceZh(page, scaffold.workspaceCwd)
|
||||
|
||||
@@ -80,7 +80,7 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', '
|
||||
await openSettings(page, 'zh')
|
||||
const dialog = page.getByRole('dialog', { name: '设置' })
|
||||
await dialog.getByRole('button', { name: '模型', exact: true }).click()
|
||||
const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true })
|
||||
const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek API (deepseek-official)' : provider}`, exact: true })
|
||||
await edit.click()
|
||||
// This row's card alone. Between the credential delete and the profile
|
||||
// write that restores native auth, google's row reports no usable
|
||||
@@ -136,7 +136,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki
|
||||
await openSettings(page, 'zh')
|
||||
const dialog = page.getByRole('dialog', { name: '设置' })
|
||||
await dialog.getByRole('button', { name: '模型', exact: true }).click()
|
||||
const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true })
|
||||
const edit = dialog.getByRole('button', { name: '编辑 DeepSeek API (deepseek-official)', exact: true })
|
||||
await edit.click()
|
||||
// This row's card alone: the dialog can show another provider's card,
|
||||
// with its own key field, beside this row.
|
||||
@@ -193,7 +193,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki
|
||||
await openSettings(page, 'zh')
|
||||
const dialog = page.getByRole('dialog', { name: '设置', exact: true })
|
||||
await dialog.getByRole('button', { name: '模型', exact: true }).click()
|
||||
const setup = dialog.getByText('DeepSeek', { exact: true }).locator('xpath=ancestor::li')
|
||||
const setup = dialog.getByText('DeepSeek API', { exact: true }).locator('xpath=ancestor::li')
|
||||
await setup.getByText('自定义设置', { exact: true }).click()
|
||||
await dialog.getByRole('button', { name: '添加模型提供商' }).click()
|
||||
await dialog.getByRole('tab', { name: '自定义模型 API' }).click()
|
||||
@@ -242,7 +242,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
|
||||
|
||||
it('offers one DeepSeek card and saves Messages settings using the existing credential reference', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-deepseek-messages-settings'))
|
||||
expect(scaffold.ctx.llm.listProviders()).toContainEqual({ id: 'deepseek-official', name: 'DeepSeek' })
|
||||
expect(scaffold.ctx.llm.listProviders()).toContainEqual({ id: 'deepseek-official', name: 'DeepSeek API' })
|
||||
expect(scaffold.ctx.llm.listProviders().filter(provider => provider.id === 'deepseek-official')).toHaveLength(1)
|
||||
expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ provider: 'deepseek-official', model: 'deepseek-flash' })
|
||||
await page.getByRole('dialog', { name: '开始使用', exact: true }).getByRole('button', { name: '添加 API Key', exact: true }).click()
|
||||
@@ -253,9 +253,9 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
|
||||
await openSettings(page, 'zh')
|
||||
const dialog = page.getByRole('dialog', { name: '设置', exact: true })
|
||||
await dialog.getByRole('button', { name: '模型', exact: true }).click()
|
||||
await dialog.getByText('DeepSeek', { exact: true }).waitFor()
|
||||
expect(await dialog.getByText('DeepSeek', { exact: true }).count()).toBe(1)
|
||||
await dialog.getByText('DeepSeek', { exact: true }).locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click()
|
||||
await dialog.getByText('DeepSeek API', { exact: true }).waitFor()
|
||||
expect(await dialog.getByText('DeepSeek API', { exact: true }).count()).toBe(1)
|
||||
await dialog.getByText('DeepSeek API', { exact: true }).locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click()
|
||||
const messages = dialog
|
||||
const key = messages.getByLabel('API 密钥', { exact: true })
|
||||
expect(await key.inputValue()).toBe('')
|
||||
@@ -271,7 +271,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
|
||||
expect(await messages.getByLabel('模型 ID 1').inputValue()).toBe('deepseek-flash')
|
||||
await messages.getByLabel('显示名称 1', { exact: true }).fill('Messages Flash')
|
||||
await messages.getByRole('button', { name: '保存', exact: true }).click()
|
||||
await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor()
|
||||
await dialog.getByText('已保存 DeepSeek API (deepseek-official)。', { exact: true }).waitFor()
|
||||
|
||||
const settings = await readFile(join(scaffold.harnessHome, 'profiles', 'scaffold', 'cordis.patch.yml'), 'utf8')
|
||||
expect(settings).toContain('https://messages.example/anthropic')
|
||||
@@ -285,7 +285,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
|
||||
expect(credentials).toContain('DEEPSEEK_API_KEY: sk-e2e-messages')
|
||||
expect(credentials).not.toContain('DEEPSEEK_MESSAGES_API_KEY')
|
||||
expect(await page.locator('body').innerText()).not.toContain('sk-e2e-')
|
||||
await dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }).click()
|
||||
await dialog.getByRole('button', { name: '编辑 DeepSeek API (deepseek-official)', exact: true }).click()
|
||||
expect(await key.inputValue()).toBe('')
|
||||
await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor()
|
||||
expect(await key.getAttribute('type')).toBe('password')
|
||||
|
||||
@@ -84,13 +84,63 @@ describe.skipIf(MODE === 'record')('web e2e: default Workspace', () => {
|
||||
const trigger = page.getByRole('button', { name: 'Choose workspace', exact: true })
|
||||
await trigger.getByText('Default workspace', { exact: true }).waitFor()
|
||||
await trigger.tap()
|
||||
const menu = page.getByRole('menu').filter({ has: page.getByRole('menuitem', { name: 'Default workspace', exact: true }) })
|
||||
await menu.waitFor({ state: 'visible', timeout: 10_000 })
|
||||
const defaultWorkspace = page.getByRole('menuitem', { name: 'Default workspace', exact: true })
|
||||
const singleWorkspaceMenu = page.getByRole('menu').filter({ has: defaultWorkspace })
|
||||
await singleWorkspaceMenu.getByRole('menuitem', { name: 'Add workspace…', exact: true }).waitFor()
|
||||
const search = page.getByRole('searchbox', { name: 'Search workspaces', exact: true })
|
||||
expect(await search.count()).toBe(0)
|
||||
await page.keyboard.press('Escape')
|
||||
await singleWorkspaceMenu.waitFor({ state: 'hidden' })
|
||||
|
||||
const secondWorkspacePath = join(scaffold.workspaceCwd, 'secondary-workspace')
|
||||
await mkdir(secondWorkspacePath)
|
||||
await scaffold.ctx.workspaceRegistry.create(secondWorkspacePath, 'Secondary workspace')
|
||||
await trigger.tap()
|
||||
await search.waitFor({ state: 'visible', timeout: 10_000 })
|
||||
const card = page.locator('[data-menu-material]').filter({ has: search })
|
||||
const menu = card.getByRole('menu')
|
||||
expect(await trigger.getAttribute('aria-expanded')).toBe('true')
|
||||
expect(await trigger.evaluate(node => node.style.anchorName)).toBe(await menu.evaluate(node => node.style.positionAnchor))
|
||||
expect(await trigger.evaluate(node => node.style.anchorName)).toBe(await card.evaluate(node => node.style.positionAnchor))
|
||||
const searchRow = card.locator('[data-search-field]').filter({ has: search })
|
||||
const workspace = menu.getByRole('menuitem', { name: 'Default workspace', exact: true })
|
||||
const add = menu.getByRole('menuitem', { name: 'Add workspace…', exact: true })
|
||||
await expect.poll(async () => {
|
||||
const searchBox = await searchRow.boundingBox()
|
||||
const workspaceBox = await workspace.boundingBox()
|
||||
const addBox = await add.boundingBox()
|
||||
const searchContentHeight = await searchRow.evaluate((element) => {
|
||||
const style = getComputedStyle(element)
|
||||
return element.getBoundingClientRect().height
|
||||
- Number.parseFloat(style.paddingTop) - Number.parseFloat(style.paddingBottom)
|
||||
- Number.parseFloat(style.borderTopWidth) - Number.parseFloat(style.borderBottomWidth)
|
||||
})
|
||||
return searchBox !== null && workspaceBox !== null && addBox !== null
|
||||
&& Math.abs(searchContentHeight - addBox.height) < 1
|
||||
&& searchBox.y + searchBox.height < workspaceBox.y + 1
|
||||
}).toBe(true)
|
||||
expect(await search.evaluate(element => element === document.activeElement)).toBe(false)
|
||||
await search.tap()
|
||||
await expect.poll(() => search.evaluate(element => element === document.activeElement)).toBe(true)
|
||||
await search.fill('default')
|
||||
await workspace.waitFor()
|
||||
expect(await menu.getByRole('menuitem').allTextContents()).toEqual(['Default workspace', 'Add workspace…'])
|
||||
const workspaceHeight = await workspace.evaluate(element => element.getBoundingClientRect().height)
|
||||
await search.fill('missing-workspace-name')
|
||||
const empty = card.getByRole('status').filter({ hasText: 'No matching workspaces' })
|
||||
await expect.poll(() => empty.evaluate(element => element.getBoundingClientRect().height))
|
||||
.toBeCloseTo(workspaceHeight, 0)
|
||||
await page.keyboard.press('Escape')
|
||||
await menu.waitFor({ state: 'hidden' })
|
||||
expect(await trigger.getAttribute('aria-expanded')).toBe('false')
|
||||
|
||||
await trigger.click()
|
||||
await expect.poll(() => search.evaluate(element => element === document.activeElement)).toBe(true)
|
||||
expect(await search.inputValue()).toBe('')
|
||||
await search.press('Escape')
|
||||
await menu.waitFor({ state: 'hidden' })
|
||||
|
||||
await trigger.press('Enter')
|
||||
await expect.poll(() => search.evaluate(element => element === document.activeElement)).toBe(true)
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -1061,7 +1061,7 @@ else process.exit(1);
|
||||
sections.push('## PDF drag selection\n\n- Table selection: forward and backward drags exclude later sections\n- Line-break highlight: transparent\n- Text selection: translucent blue in light and dark themes; canvas text remains visible\n- Mouse release preserves the selected text')
|
||||
|
||||
const pngResponse = page.waitForResponse(response => new URL(response.url()).pathname === '/api/workspaceFiles/readBytes'
|
||||
&& (response.request().postDataJSON() as { payload: { args: { path: string } } }).payload.args.path === 'tiny.png')
|
||||
&& (response.request().postDataJSON() as { payload: { args: { path: string } } }).payload.args.path.endsWith('/tiny.png'))
|
||||
await openFile('tiny.png')
|
||||
const transferred = await pngResponse
|
||||
expect(transferred.headers()['content-type']).toMatch(/^multipart\/form-data;/)
|
||||
@@ -1214,7 +1214,7 @@ else process.exit(1);
|
||||
let waitingForRead = false
|
||||
const readPage = scaffold.ctx.workspaceFiles.read.bind(scaffold.ctx.workspaceFiles)
|
||||
const heldRead = vi.spyOn(scaffold.ctx.workspaceFiles, 'read').mockImplementation(async (agent, path, range, signal) => {
|
||||
if (path === 'pages.ts' && (range.offset ?? 1) === 1) {
|
||||
if (path.endsWith('/pages.ts') && (range.offset ?? 1) === 1) {
|
||||
waitingForRead = true
|
||||
await releaseRead.promise
|
||||
}
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
|
||||
- list:
|
||||
- listitem:
|
||||
- text: DeepSeek
|
||||
- text: DeepSeek API
|
||||
- img "API 密钥已配置"
|
||||
- button "编辑 DeepSeek (deepseek-official)": 编辑
|
||||
- text: DeepSeek deepseek-official API 密钥
|
||||
- button "编辑 DeepSeek API (deepseek-official)": 编辑
|
||||
- text: DeepSeek API deepseek-official API 密钥
|
||||
- button "认证说明": "?"
|
||||
- textbox "API 密钥":
|
||||
- /placeholder: sk-messa••••••••••ding
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
|
||||
- list:
|
||||
- listitem:
|
||||
- text: DeepSeek
|
||||
- text: DeepSeek API
|
||||
- img "API 密钥已配置"
|
||||
- button "编辑 DeepSeek (deepseek-official)": 编辑
|
||||
- text: DeepSeek deepseek-official API 密钥
|
||||
- button "编辑 DeepSeek API (deepseek-official)": 编辑
|
||||
- text: DeepSeek API deepseek-official API 密钥
|
||||
- button "认证说明": "?"
|
||||
- textbox "API 密钥":
|
||||
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
- group "模型与推理等级":
|
||||
- menu "模型":
|
||||
- group "DeepSeek":
|
||||
- text: DeepSeek
|
||||
- group "DeepSeek API":
|
||||
- text: DeepSeek API
|
||||
- menuitemradio "Messages Flash" [checked]
|
||||
- menuitemradio "DeepSeek-V4-Pro"
|
||||
Loaded 100 of 699 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user