Merge master into system input support
This commit is contained in:
commit
b3d5737b49
1094 files changed
+33511
-2501
No files matched your search
+2
-2
@@ -12,8 +12,8 @@
|
||||
en: a15c7c13f167e5ac
|
||||
zh: 63bcc2ef60c2f344
|
||||
/agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/packaging-route-yao-pkg-pkg-s-sea-mode:
|
||||
en: f1c2b60e9474111d
|
||||
zh: 5de398b5e8554429
|
||||
en: da2d0e038a0cab9d
|
||||
zh: 495c770640264c1d
|
||||
/agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/the-serving-interface-is-a-plugin-inside-the-dsh-application:
|
||||
en: 5fdde26e9e8c6108
|
||||
zh: 629559d733c1f0c5
|
||||
|
||||
+2
@@ -25,6 +25,8 @@ The exe is packaged with the **`--sea` (enhanced SEA) mode** of [@yao-pkg/pkg](h
|
||||
|
||||
The same patch makes the SEA bootstrap's native-addon extraction atomic. On the first `dlopen` of an addon inside the VFS, pkg's `patchDlopen` copies the addon's package tree to `$PKG_NATIVE_CACHE_PATH/pkg/<sha256 of the .node file>/` (default `~/.cache/pkg/...`), a per-user directory that every concurrent process of the same executable shares; upstream writes each file straight to its final path with `writeFileSync`, which truncates a file another process may already have mapped and lets that process's `existsSync`/hash check read a half-written file. Concurrent first starts therefore die with SIGBUS on Linux or fail with `ERR_DLOPEN_FAILED: Library not loaded` on sharp's libvips on macOS (#4664). The patch routes the three write sites through a same-directory temporary file and `renameSync`, so a cache path is either absent or complete, every process finishes its own copy pass before it loads, and concurrent renames of identical content need no lock. The cache location, hash keying, and per-file comparison are unchanged, so a consumer that isolates the cache per instance through `PKG_NATIVE_CACHE_PATH` keeps working; worker threads only define the hook and never install it. Measured (linux-x64, node24 target, pkg 6.21.0, a probe that loads sharp with its 18 MB libvips library, 16 concurrent first starts against one empty cache, five rounds): 39 of 80 processes died with SIGBUS before the change and 0 of 80 after it, with no temporary files left behind.
|
||||
|
||||
The same patch makes the VFS honor `{ bigint: true }` in `stat`, `lstat`, their synchronous forms, and `fs.promises`. Upstream returns the same number-valued stats whatever the options, while `dsh-fs-local` and `dsh-fs-sandbox` read VFS paths through BigInt stats, so every `ctx.fs` access to a packaged file failed with `Cannot mix BigInt and other types`: the `read` tool could not open a packaged skill file, and a `skill-filesystem` root inside the VFS made skill discovery incomplete. The patch converts a VFS entry's numbers to the `BigIntStats` fields, including nanosecond times derived from the millisecond values; paths outside the VFS keep Node's own results.
|
||||
|
||||
Terminology reminder: pkg's `/snapshot` VFS has nothing to do with this repo's testing-system "snapshot" (ACP replay expected outputs, `$DSH_SNAPSHOT`); this document says "VFS" for the former.
|
||||
|
||||
### The serving interface is a plugin inside the dsh application
|
||||
|
||||
+2
@@ -25,6 +25,8 @@ exe 使用 [@yao-pkg/pkg](https://github.com/yao-pkg/pkg)(vercel/pkg 归档后
|
||||
|
||||
同一补丁还把 SEA bootstrap 的原生插件解包改成原子写入。VFS 内的插件首次 `dlopen` 时,pkg 的 `patchDlopen` 会把该插件所在的包目录整棵拷到 `$PKG_NATIVE_CACHE_PATH/pkg/<.node 文件的 sha256>/`(默认 `~/.cache/pkg/...`),这是同一个 exe 的所有并发进程共用的按用户目录;上游用 `writeFileSync` 直接写目标路径,会把另一个进程可能已经映射的文件截断,并让该进程的 `existsSync`/哈希比对读到写了一半的文件。因此并发首次启动在 Linux 上以 SIGBUS 崩溃,在 macOS 上对 sharp 的 libvips 报 `ERR_DLOPEN_FAILED: Library not loaded`(#4664)。补丁让三处写入都经过同目录临时文件加 `renameSync`,于是缓存路径要么不存在、要么完整,每个进程都在加载前走完自己的拷贝,相同内容的并发 rename 不需要锁。缓存位置、哈希键与逐文件比对均未改变,通过 `PKG_NATIVE_CACHE_PATH` 按实例隔离缓存的消费方照常工作;worker 线程只定义该钩子而从不安装。 实测(linux-x64、node24 构建目标、pkg 6.21.0,一个加载 sharp 及其 18 MB libvips 库的探针,16 个进程对同一个空缓存并发首次启动,跑五轮):改动前 80 个进程中 39 个以 SIGBUS 崩溃,改动后 80 个全部正常,且无残留临时文件。
|
||||
|
||||
同一补丁还让 VFS 的 `stat`、`lstat`、它们的同步形式以及 `fs.promises` 遵守 `{ bigint: true }`。上游无论选项如何都返回同一份数值型 stats,而 `dsh-fs-local` 与 `dsh-fs-sandbox` 通过 BigInt stats 读取 VFS 路径,因此经 `ctx.fs` 访问打包文件时都会以 `Cannot mix BigInt and other types` 失败:`read` 工具打不开打包的 skill 文件,位于 VFS 内的 `skill-filesystem` 根使 skill 发现不完整。补丁把 VFS 条目的数值转换为 `BigIntStats` 字段,其中纳秒时间由毫秒值换算;VFS 之外的路径仍使用 Node 自身的结果。
|
||||
|
||||
术语提醒:pkg 的 `/snapshot` VFS 与本仓库测试体系的「快照」(ACP(Agent Client Protocol)回放预期输出、`$DSH_SNAPSHOT`)无关,本文用「VFS」指前者。
|
||||
|
||||
### 对外服务接口是 dsh 应用中的插件
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
en: abd0263d14861926
|
||||
zh: e1736cd08e87f795
|
||||
/agent-note-shared-time-vocabulary-for-wall-clock-selectors/decision:
|
||||
en: f1c2b98bf56cdba3
|
||||
zh: 7e9444f8e73a4834
|
||||
en: cf4dc376cbdb0e90
|
||||
zh: 6aea79fb9dfe419d
|
||||
/agent-note-shared-time-vocabulary-for-wall-clock-selectors/alternatives-considered:
|
||||
en: 3964f7d653747b55
|
||||
zh: b50636faea4917ef
|
||||
|
||||
@@ -16,7 +16,7 @@ The library answers discriminated results and carries no failure vocabulary. `pa
|
||||
|
||||
Schedule consumes it and keeps every domain decision. `canonicalizeTimeZone`, `decodeInstant`, `parseAtInput`, and `futureInstant` remain Schedule entry points with their existing codes and diagnostics; they call the shared parser and map its reason. Pure Cron/RRULE parsing and bounded occurrence searches belong to the library, take explicit reference times, and validate committed targets with `fourDigitYearEpoch`. Schedule owns durable records, the fold and transition authority, injection-resistant framing, daily and weekly date walks, delivery limits, and domain errors. The shared values own no task state, wall clock, or timers.
|
||||
|
||||
`dsh-time-context` consumes it too and keeps its stricter policy. `deriveBrowserTimeZoneContext` reads each user-rpc zone through `canonicalizeTimeZone` and refuses an alias whose canonical answer differs from the reported value, so the request boundary still requires an identity another process resolves back to the same name. Time-context owns its three refusals and their messages; the shared entry only answers the canonical name or a reason, and its `unsupported` rejection carries the platform error the library caught, so that refusal keeps its `cause` in both consumers.
|
||||
`dsh-time-context` consumes it too and keeps its stricter policy. `deriveBrowserTimeZoneContext` reads each reported user-message zone through `canonicalizeTimeZone` and refuses an alias whose canonical answer differs from the reported value, so the request boundary still requires an identity another process resolves back to the same name. Time-context owns its three refusals and their messages; the shared entry only answers the canonical name or a reason, and its `unsupported` rejection carries the platform error the library caught, so that refusal keeps its `cause` in both consumers.
|
||||
|
||||
`Duration` holds one span as a single millisecond count, and it is a class rather than a branded number because TypeScript's arithmetic erases a brand: adding two differently branded numbers answers an unbranded `number`, so a brand cannot stop seconds and milliseconds from being mixed, while an instance can. The unit is milliseconds because every producer and consumer in this repository already uses it (`Date.now()`, `SessionEvent.time`, the session log, the client), and because a double holds every millisecond of the whole `Date` range exactly, so no precision is spent on the unit. Instances are frozen, no coercion hook is overridden, and a span is bounded by the exactly representable millisecond range, which is what makes the split exact. The published surface is `fromMilliseconds` and a whole-part `decompose()`, the two entries the migrated consumer calls.
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ Status: implemented
|
||||
|
||||
Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`decodeInstant`、`parseAtInput` 与 `futureInstant` 仍是 Schedule 的入口,保留既有错误码与诊断文案;它们调用共享解析器并映射其原因。纯 Cron/RRULE 解析与有界发生时点搜索归本库所有,接收显式参考时间,并通过 `fourDigitYearEpoch` 校验已提交时点。Schedule 拥有持久记录、折叠与状态转移权威、抗注入的框架文本、每日与每周日期遍历、投递限制及领域错误。共享值不拥有任务状态、墙钟或定时器。
|
||||
|
||||
`dsh-time-context` 同样消费它,并保留自己更严格的策略。`deriveBrowserTimeZoneContext` 通过 `canonicalizeTimeZone` 读取每条 user-rpc 时区,并拒绝规范答案与所报值不同的别名,因此请求边界仍然要求另一个进程能解析回同一名称。三条拒绝与它们的文案归 time-context 所有;共享入口只回答规范名称或一个原因;被拒绝的结果中只有 `unsupported` 会携带本库捕获到的平台错误,使该拒绝在两个消费方都保留其 `cause`。
|
||||
`dsh-time-context` 同样消费它,并保留自己更严格的策略。`deriveBrowserTimeZoneContext` 通过 `canonicalizeTimeZone` 读取每条用户消息上报的时区,并拒绝规范答案与所报值不同的别名,因此请求边界仍然要求另一个进程能解析回同一名称。三条拒绝与它们的文案归 time-context 所有;共享入口只回答规范名称或一个原因;被拒绝的结果中只有 `unsupported` 会携带本库捕获到的平台错误,使该拒绝在两个消费方都保留其 `cause`。
|
||||
|
||||
`Duration` 以单一毫秒计数保存一段时间;它做成类而不是 branded number,是因为 TypeScript 的算术会抹掉 brand:两个不同品牌的数字相加得到的是无品牌的 `number`,所以 brand 挡不住秒与毫秒的混用,而实例可以。单位选毫秒,是因为本仓库的每个生产者与消费者本来就用它(`Date.now()`、`SessionEvent.time`、Session 日志、客户端),也因为 double 能精确表示 `Date` 全范围内的每一个毫秒,这个单位不消耗任何精度。实例被冻结,不覆盖任何强制转换钩子,且时间段受可精确表示的毫秒范围约束——这正是拆分精确的前提。公开面就是 `fromMilliseconds` 与整数量拆解 `decompose()`,即已迁移消费方所调用的两个入口。
|
||||
|
||||
|
||||
+6
-6
@@ -9,11 +9,11 @@
|
||||
en: 755fe8a192cfebe1
|
||||
zh: 855ad2920b33e364
|
||||
/agent-note-runtime-download-of-upstream-skills/decision:
|
||||
en: e601879f83a17cba
|
||||
zh: a5ab03a7804787fc
|
||||
en: 98f6d4a4c6b7849f
|
||||
zh: a361378d5020c954
|
||||
/agent-note-runtime-download-of-upstream-skills/alternatives-considered:
|
||||
en: 3828cc141c037db6
|
||||
zh: 3a164d7a5886cbd2
|
||||
en: 250ab524fc33cd94
|
||||
zh: bc4d8008af1f9d61
|
||||
/agent-note-runtime-download-of-upstream-skills/consequences:
|
||||
en: 124556ff88e9e014
|
||||
zh: d25070f79bb2c726
|
||||
en: 5df2a8d5d5b9fbb6
|
||||
zh: b827f6539833ee87
|
||||
+8
-2
@@ -10,7 +10,7 @@ The WeCom and Tencent Meeting plugins index guides that their vendors publish on
|
||||
|
||||
## Decision
|
||||
|
||||
Each of these plugins keeps only its DSH-authored entry `SKILL.md`, pins the upstream files by repository, commit, kept directory, exclusions, license file, total size, and a digest of the kept files, and registers both with `ctx.upstreamSkills`, the Service of [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.md). The Service downloads the commit archive from GitHub when the plugin loads, keeps the directory and the license file, verifies them, publishes them in `$DSH_HOME/cache/<plugin>`, and lists the entry skill with that directory as its base directory. The plugin shows the download state beside the account state. Its check reads only the account and restarts a failed download without waiting for it: the CLI account runtime runs one operation at a time, so a check that waited for a slow GitHub download would also hold sign-in. Each archive source has `skillsTimeoutMs` to deliver the whole archive, and reading stops once the kept files exceed the pinned size. A plugin's `skillsDir` points at prepared files for tests and offline installations, and the Service's `skillsUrls` replaces the archive host for every plugin.
|
||||
Each of these plugins keeps only its DSH-authored entry `SKILL.md`, pins the upstream files by repository, commit, kept directory, exclusions, license file, total size, and a digest of the kept files, and registers both with `ctx.upstreamSkills`, the Service of [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.md). The Service downloads the commit archive from GitHub when the plugin loads, keeps the directory and the license file, verifies them, publishes them under `$DSH_HOME/cache/<plugin>`, and lists the entry skill with the published directory as its base directory. In a profile the files go to that profile's own directory, `$DSH_HOME/cache/<plugin>/<profile>`, which only that profile's processes read, and each registration deletes the other pins there once, when its own pin first is in place: a plugin update leaves one copy, and an unchanged pin is never downloaded again. The plugin shows the download state beside the account state. Its check reads only the account and restarts a failed download without waiting for it: the CLI account runtime runs one operation at a time, so a check that waited for a slow GitHub download would also hold sign-in. Each archive source has `skillsTimeoutMs` to deliver the whole archive, and reading stops once the kept files exceed the pinned size. A plugin's `skillsDir` points at prepared files for tests and offline installations, and the Service's `skillsUrls` replaces the archive host for every plugin.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -24,8 +24,14 @@ Each of these plugins keeps only its DSH-authored entry `SKILL.md`, pins the ups
|
||||
|
||||
**A digest of the archive bytes.** The files of a commit archive are stable, but GitHub does not keep its compressed bytes stable, so the digest covers the kept files' paths and contents instead.
|
||||
|
||||
**One cache directory shared by every profile.** It saves one download per profile. Two DSH installations of different versions on one `$DSH_HOME` can pin different commits for one plugin, so deleting a replaced pin there deletes files the other installation reads, and keeping every pin leaves a copy per plugin update.
|
||||
|
||||
**Deleting the other pins after every download.** Processes of one profile can run different versions of a plugin at the same time, such as one started before a plugin update and one started after it, and they share the profile's directory. Each would delete the other's pin after each of its downloads and download its own again at its next check, without end. Deleting once per registration ends that: the later process still deletes the earlier one's pin once, the earlier one downloads it again, and both pins stay until another load. A record of the pins in use, or a period during which a replaced pin stays, would also keep the running process's pin, at the price of a protocol between processes or of a second copy for that period.
|
||||
|
||||
**The DSH version in the directory name.** Connector packages carry the DSH version, but a version in the name does not decide which installation may delete which directory, and it downloads the files again at every DSH release although the pin rarely changes.
|
||||
|
||||
**DingTalk's downloader.** DingTalk downloads checksummed release assets together with its executable. WeCom and Tencent Meeting publish no release assets and install their CLIs from npm, so only these two plugins register with this Service, and DingTalk keeps its own downloader.
|
||||
|
||||
## Consequences
|
||||
|
||||
The repository and the plugins' npm packages carry only the entry skills. The first load after a new pin needs GitHub or a configured mirror; until a download succeeds, the entry skill is not listed and the plugin shows the failure, which its next check retries. Tests, recorded Sessions, and Web end-to-end tests set `skillsDir` to fixture files and make no network requests. Published directories are never pruned. Updating a pin is a code change: `scripts/upstream-skills-digest.ts` prints the new pin, and the entry's guide index and a real-model run follow it.
|
||||
The repository and the plugins' npm packages carry only the entry skills. The first load after a new pin needs GitHub or a configured mirror; until a download succeeds, the entry skill is not listed and the plugin shows the failure, which its next check retries. Tests, recorded Sessions, and Web end-to-end tests set `skillsDir` to fixture files and make no network requests. Each profile that loads a plugin downloads its own copy. A process that still runs another version of a plugin loses its pin once to a later process of the same profile and downloads it again at its next check. Removing a plugin leaves its pin in the cache, and without a profile no pin is deleted. Updating a pin is a code change: `scripts/upstream-skills-digest.ts` prints the new pin, and the entry's guide index and a real-model run follow it.
|
||||
+8
-2
@@ -10,7 +10,7 @@ Status: implemented
|
||||
|
||||
## 决策
|
||||
|
||||
这些插件只保留 DSH 自己编写的入口 `SKILL.md`,按仓库、提交、保留的目录、排除项、许可证文件、总大小和保留文件的摘要固定上游文件,并把两者注册到 `ctx.upstreamSkills`,即 [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.zh.md) 的 Service。插件加载时,Service 从 GitHub 下载这个提交的归档,保留该目录和许可证文件,校验后发布到 `$DSH_HOME/cache/<插件>`,再列出入口技能,并把这个目录作为它的基础目录。插件在账号状态旁显示下载状态。它的检查只读取账号,并在不等待的情况下重新开始失败的下载:CLI 账号运行时一次只执行一个操作,检查若等待缓慢的 GitHub 下载,登录也会被占住。每个归档来源要在 `skillsTimeoutMs` 内送达完整归档,保留文件超过固定的大小时停止读取。插件的 `skillsDir` 为测试和离线安装指向准备好的文件,Service 的 `skillsUrls` 为所有插件替换归档主机。
|
||||
这些插件只保留 DSH 自己编写的入口 `SKILL.md`,按仓库、提交、保留的目录、排除项、许可证文件、总大小和保留文件的摘要固定上游文件,并把两者注册到 `ctx.upstreamSkills`,即 [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.zh.md) 的 Service。插件加载时,Service 从 GitHub 下载这个提交的归档,保留该目录和许可证文件,校验后发布到 `$DSH_HOME/cache/<插件>` 下,再列出入口技能,并把发布的目录作为它的基础目录。在 profile 中,文件发布到这个 profile 自己的目录 `$DSH_HOME/cache/<插件>/<profile>`,只有这个 profile 的进程读取它;每次注册在自己的固定提交第一次就位时,删除一次那里其他的固定提交:插件更新后只留下一份,固定提交不变时也不会重新下载。插件在账号状态旁显示下载状态。它的检查只读取账号,并在不等待的情况下重新开始失败的下载:CLI 账号运行时一次只执行一个操作,检查若等待缓慢的 GitHub 下载,登录也会被占住。每个归档来源要在 `skillsTimeoutMs` 内送达完整归档,保留文件超过固定的大小时停止读取。插件的 `skillsDir` 为测试和离线安装指向准备好的文件,Service 的 `skillsUrls` 为所有插件替换归档主机。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
@@ -24,8 +24,14 @@ Status: implemented
|
||||
|
||||
**对归档字节做摘要。** 提交归档中的文件是稳定的,但 GitHub 不保证压缩后的字节稳定,因此摘要覆盖保留文件的路径和内容。
|
||||
|
||||
**所有 profile 共用一个缓存目录。** 它让每个 profile 少下载一次。同一个 `$DSH_HOME` 上两个不同版本的 DSH 安装,可能为同一个插件固定不同的提交,因此在那里删除被替换的固定提交,会删掉另一个安装正在读取的文件;而全部保留,则每次插件更新都多留一份。
|
||||
|
||||
**每次下载完成后都删除其他固定提交。** 同一个 profile 的多个进程可以同时运行同一插件的不同版本,例如一个在插件更新之前启动,另一个在更新之后启动,它们共用这个 profile 的目录。这样每个进程都会在自己每次下载完成后删除对方的固定提交,并在下一次检查时重新下载自己的,没有尽头。每次注册只删除一次就结束了这个循环:后启动的进程仍会删除一次先启动的进程的固定提交,先启动的进程重新下载,此后两个固定提交都保留,直到下一次加载。记录正在使用的固定提交,或让被替换的固定提交保留一段时间,也能保住运行中进程的固定提交,代价是进程之间要有一套约定,或者在这段时间里多留一份。
|
||||
|
||||
**在目录名中加入 DSH 版本。** Connector 包的版本与 DSH 版本一致,但目录名里的版本并不能决定哪个安装可以删除哪个目录,而且固定提交很少变化,每次 DSH 发版却都要重新下载这些文件。
|
||||
|
||||
**钉钉的下载器。** 钉钉把带校验和的发布资产和可执行文件一起下载。企业微信和腾讯会议没有发布资产,CLI 从 npm 安装,因此只有这两个插件注册到这个 Service,钉钉保留自己的下载器。
|
||||
|
||||
## 影响
|
||||
|
||||
仓库和插件的 npm 包里只有入口技能。换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,入口技能不会列出,插件显示失败,下一次检查会重试。测试、录制的 Session 和 Web 端到端测试都把 `skillsDir` 设为夹具文件,不发起网络请求。已发布的目录从不清理。更新固定提交需要改代码:`scripts/upstream-skills-digest.ts` 输出新的固定信息,随后更新入口的子指南索引,并用真实模型运行一次。
|
||||
仓库和插件的 npm 包里只有入口技能。换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,入口技能不会列出,插件显示失败,下一次检查会重试。测试、录制的 Session 和 Web 端到端测试都把 `skillsDir` 设为夹具文件,不发起网络请求。每个加载该插件的 profile 都各自下载一份。仍在运行插件另一个版本的进程,会被同一 profile 后启动的进程删除一次固定提交,并在下一次检查时重新下载。移除插件后,它的固定提交仍留在缓存中;没有 profile 时,任何固定提交都不会被删除。更新固定提交需要改代码:`scripts/upstream-skills-digest.ts` 输出新的固定信息,随后更新入口的子指南索引,并用真实模型运行一次。
|
||||
+12
-12
@@ -9,8 +9,8 @@
|
||||
en: 3f5dacf86015cebb
|
||||
zh: cf0d5bceb9941554
|
||||
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision:
|
||||
en: 0682ebef17f6a5e7
|
||||
zh: 6ea399459262eb0c
|
||||
en: e243a7d535022011
|
||||
zh: fd1dd8634b9603cf
|
||||
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/registered-providers-are-observable-availability-is-not:
|
||||
en: 38ce796dea91fa35
|
||||
zh: d312a9cd29fd5cc9
|
||||
@@ -21,17 +21,17 @@
|
||||
en: dca56d7ced4e5294
|
||||
zh: e984a7fddac3228f
|
||||
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections:
|
||||
en: 5fcd3319fbceed1d
|
||||
zh: 20771646b9c36fa6
|
||||
en: eba9b7ca32681406
|
||||
zh: 7ab74b8054bea720
|
||||
/agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/legacy-messages-search:
|
||||
en: 2c7c84f8fa1e8745
|
||||
zh: 5d0244e4f17ba12a
|
||||
en: 8f3180e3dd327bfc
|
||||
zh: 012b2ebe8d2f5aac
|
||||
/agent-note-web-provider-selection-independent-menus-over-registered-providers/alternatives-considered:
|
||||
en: 2ec7f019ec3ce309
|
||||
zh: a6a5a8db1f1dd682
|
||||
en: d72b359bb9ff9666
|
||||
zh: 33c9a12488a81826
|
||||
/agent-note-web-provider-selection-independent-menus-over-registered-providers/consequences:
|
||||
en: ea4d3f05e8be197a
|
||||
zh: 81faeb3edf122869
|
||||
en: fe529b10fcbb2d0a
|
||||
zh: ed3eabbce90ddb92
|
||||
/agent-note-web-provider-selection-independent-menus-over-registered-providers/verification:
|
||||
en: 0db673b16e4aeda3
|
||||
zh: 3b086edecebdc5b5
|
||||
en: a8f08dc7ec5845fd
|
||||
zh: a491c4a93db41c3f
|
||||
@@ -10,7 +10,7 @@ The web service selects search and fetch providers through two independent field
|
||||
|
||||
## Decision
|
||||
|
||||
Users choose search and fetch providers independently from the Host's registered provider lists. The shipped composition selects the Search API for search and local HTTP fetch for fetch, and the DeepSeek Search and Fetch APIs follow the conversation's DeepSeek credential.
|
||||
Users choose search and fetch providers independently from the Host's registered provider lists. The shipped composition fixes no search provider, so search follows the conversation's model route, and selects local HTTP fetch for fetch; the DeepSeek Search and Fetch APIs follow the conversation's DeepSeek credential.
|
||||
|
||||
### Registered providers are observable; availability is not
|
||||
|
||||
@@ -38,18 +38,24 @@ A capability whose YAML sets a non-empty `searchBaseURL` or `searchApiKeyEnv` (`
|
||||
|
||||
### Defaults and stored selections
|
||||
|
||||
The [base composition](../../../../packages/bundle/base/cordis.patch.yml) sets `searchProvider: deepseek-search-api` and `fetchProvider: http`. Search defaults to the Search API because it returns sources without Harness starting an auxiliary model request. Fetch defaults to local HTTP fetch because it has no per-request API charge, applies Harness's own URL validation and resource limits, and reaches intranet and local addresses. The Fetch API remains one menu choice away.
|
||||
The [base composition](../../../../packages/bundle/base/cordis.patch.yml) sets `fetchProvider: http` and no `searchProvider`. With no search provider configured, `dsh-web` prefers one registered, usable provider per provider route of the model request a search serves: Messages search (`deepseek-official`) on the `deepseek-official` and `deepseek-account` model routes, because DeepSeek makes no per-search charge for the server-side search tool a DeepSeek model request declares, and the Search API (`deepseek-search-api`) on every other route and outside a model request, because it returns sources without an auxiliary model request to a provider the conversation does not use. `dsh-tool-web` puts the route of the calling Session's latest model request into each search request, and `searchReady()` selects with the route of the step being prepared, so readiness and execution name the same provider. The two routes and two provider ids are constants of `dsh-web`: a deployment changes the outcome only by configuring `searchProvider`, and the settings page shows the unconfigured state as **Automatic**. Fetch defaults to local HTTP fetch because it has no per-request API charge, applies Harness's own URL validation and resource limits, and reaches intranet and local addresses. The Fetch API remains one menu choice away.
|
||||
|
||||
A stored selection, whether in the settings document or in a deployment's own composition, wins over the shipped default, and an upgrade does not rewrite it. A selection is never replaced at execution: when the selected provider is missing, unavailable, or fails, the operation fails with its structured error and does not fall back to another search or fetch provider. A fallback would send the query and credential to an endpoint the user did not choose and change billing without notice.
|
||||
|
||||
### Legacy Messages search
|
||||
|
||||
The DeepSeek Messages search provider remains available as **DeepSeek (legacy)**. A stored `web.searchProvider: deepseek-official` (or `DSH_WEB_SEARCH_PROVIDER=deepseek-official`) selects it, so users whose gateways serve Messages search but not `/v1/tools` can retain their working provider.
|
||||
The DeepSeek Messages search provider remains available as **DeepSeek server-side search** and serves unconfigured searches on the DeepSeek model routes. A stored `web.searchProvider: deepseek-official` (or `DSH_WEB_SEARCH_PROVIDER=deepseek-official`) selects it for every route, so users whose gateways serve Messages search but not `/v1/tools` can retain their working provider.
|
||||
|
||||
The Messages provider owns and writes `web/deepseek-search-llm-request`. The declaration and payload retain compatibility with released Sessions; the Search and Fetch API package neither declares nor writes this auxiliary event.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Let each provider declare the routes it is the default for.** A `defaultFor(llmProvider)` member on `WebSearchProvider` keeps `dsh-web` free of DeepSeek ids, but it changes both DeepSeek provider packages for a rule that has one instance.
|
||||
|
||||
**Put the route-to-provider table in `dsh-web` configuration.** A profile patch replaces a row's whole `config`, so a stored provider selection would also store a copy of the table and stop following the shipped one, and the table is not a choice users need: fixing a provider already overrides it.
|
||||
|
||||
**Have the Search API provider delegate to Messages search on DeepSeek routes.** The menu would keep two entries, but the entry named DeepSeek Search API would run another provider, a user could not fix the Search API for a DeepSeek model, and one provider package would depend on the other.
|
||||
|
||||
**Keep one switch for both APIs.** It lets Fetch API adoption need no configuration edit, but it ties fetch billing and target access policy to the search choice, and it cannot express a provider that another plugin registers.
|
||||
|
||||
**Filter the lists by availability, or add availability to each entry.** A filtered list hides a provider while its credential is missing, right when the user needs to choose and configure it. Availability also depends on the request's model route and credential state, so a listed boolean could disagree with execution. The archived [observation-surface decision](../../archived/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md) allows only the smallest signal a consumer reads; the menus read registration only.
|
||||
@@ -76,10 +82,10 @@ The Messages provider owns and writes `web/deepseek-search-llm-request`. The dec
|
||||
|
||||
## Consequences
|
||||
|
||||
Users without a stored search selection search through the Search API: their queries go to the Search endpoint the conversation's DeepSeek credential selects, cost a Search API request each, and send up to 128 characters of the latest human prompt as `ori_question` unless `sendOriginalQuestion` is off. Deployments whose gateway has no `/v1/tools` routes get search failures until they select Messages search or set `searchBaseURL` to a base that serves them. A stored `deepseek-official` selection uses Messages search. Users without a stored fetch selection fetch through local HTTP fetch. A signed-in user without an API key has DeepSeek web search with `auto` billing in every conversation except those on the DeepSeek API-key route; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.md) lists each affected setup.
|
||||
Users without a stored search selection search through Messages search in a conversation on a DeepSeek model route: each search is one auxiliary Messages request billed as model tokens, to Messages search's own endpoint, which does not follow the model provider's base URL, so a deployment whose DeepSeek model provider points at a gateway gets search failures until it saves that gateway as the Messages Base URL or fixes the Search API ([upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.md)). On every other route they search through the Search API: their queries go to the Search endpoint the conversation's DeepSeek credential selects, cost a Search API request each, and send up to 128 characters of the latest human prompt as `ori_question` unless `sendOriginalQuestion` is off. Deployments whose gateway has no `/v1/tools` routes get search failures there until they select Messages search or set `searchBaseURL` to a base that serves them. `dsh-web` names two DeepSeek model routes and two DeepSeek search providers, which a second route-specific default would have to replace with a provider-neutral rule. A stored `deepseek-official` selection uses Messages search. Users without a stored fetch selection fetch through local HTTP fetch. A signed-in user without an API key has DeepSeek web search with `auto` billing in every conversation except those on the DeepSeek API-key route; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.md) lists each affected setup.
|
||||
|
||||
A plugin provider, including one written in creator mode, appears in the matching menu as soon as it registers, under its `title`. The menus can offer a provider that cannot run for the current request; the failure appears when a search or fetch runs. Each registry change costs one forwarded event and one list read in each Client that observes it.
|
||||
|
||||
## Verification
|
||||
|
||||
[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) covers list contents and order, titles, events after registration and disposal, no event for a rejected duplicate, and contained listener failures. [deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) covers the independent Messages provider, and [credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) covers, for both capabilities, the account token on the account route and its invalidation after HTTP 401, the API-key fallback without a sign-in, the route key and endpoint in official, non-DeepSeek, and Session-less conversations, the account fallback without a key outside the DeepSeek routes, account-only and API-key-only billing on every route, own fields over billing, `DEEPSEEK_API_KEY` and the official base without that route, YAML-only own fields that never send the token, independent capabilities, readiness matching each operation, and ignored removed fields; [composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) boots the real model routes through the Loader. [remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) covers event forwarding, and [base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) pins the shipped defaults. The settings page's controller and card specs and the [plugin configuration browser scenario](../../../../apps/web/tests/plugin-config.e2e.ts) cover menu contents, independent Search and Fetch selection, the billing menus of the DeepSeek APIs, and the settings each provider keeps.
|
||||
[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) covers list contents and order, titles, events after registration and disposal, no event for a rejected duplicate, contained listener failures, and the per-route preference with its fallbacks; [tool-web.spec.ts](../../../../packages/web/tool-web/tests/tool-web.spec.ts) covers the route `web_search` sends, and the `web-search-legacy-endpoint-guidance` snapshot runs Messages search on a DeepSeek route with no provider configured. [deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) covers the independent Messages provider, and [credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) covers, for both capabilities, the account token on the account route and its invalidation after HTTP 401, the API-key fallback without a sign-in, the route key and endpoint in official, non-DeepSeek, and Session-less conversations, the account fallback without a key outside the DeepSeek routes, account-only and API-key-only billing on every route, own fields over billing, `DEEPSEEK_API_KEY` and the official base without that route, YAML-only own fields that never send the token, independent capabilities, readiness matching each operation, and ignored removed fields; [composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) boots the real model routes through the Loader. [remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) covers event forwarding, and [base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) pins the shipped defaults. The settings page's controller and card specs and the [plugin configuration browser scenario](../../../../apps/web/tests/plugin-config.e2e.ts) cover menu contents, independent Search and Fetch selection, the billing menus of the DeepSeek APIs, and the settings each provider keeps.
|
||||
@@ -10,7 +10,7 @@ Web 服务通过 `web.searchProvider` 和 `web.fetchProvider` 两个独立字段
|
||||
|
||||
## 决策
|
||||
|
||||
用户从 Host 已注册的提供方列表中分别选择搜索和抓取提供方。内置组合将搜索设为 Search API,将抓取设为本地 HTTP 抓取;DeepSeek Search 与 Fetch API 跟随会话的 DeepSeek 凭据。
|
||||
用户从 Host 已注册的提供方列表中分别选择搜索和抓取提供方。内置组合不固定搜索提供方,搜索因此跟随会话的模型路由,抓取设为本地 HTTP 抓取;DeepSeek Search 与 Fetch API 跟随会话的 DeepSeek 凭据。
|
||||
|
||||
### 已注册的提供方可观察,可用性不可观察
|
||||
|
||||
@@ -38,18 +38,24 @@ Search 与 Fetch 各有一个计费方式设置 `web-deepseek-api.searchBilling`
|
||||
|
||||
### 默认值与已保存的选择
|
||||
|
||||
[base 组合](../../../../packages/bundle/base/cordis.patch.yml)设置 `searchProvider: deepseek-search-api` 和 `fetchProvider: http`。搜索默认使用 Search API,因为它返回来源时无需 Harness 发起辅助模型请求。抓取默认使用本地 HTTP 抓取,因为它没有按次的 API 费用,执行 Harness 自身的 URL 校验和资源限制,并且可以访问内网和本地地址。Fetch API 仍可在下拉框中直接选择。
|
||||
[base 组合](../../../../packages/bundle/base/cordis.patch.yml)设置 `fetchProvider: http`,不设置 `searchProvider`。没有配置搜索提供方时,`dsh-web` 按搜索所服务的模型请求的提供方路由,优先选用一个已注册且可用的提供方:在 `deepseek-official` 与 `deepseek-account` 模型路由上是 Messages 搜索(`deepseek-official`),因为 DeepSeek 不对 DeepSeek 模型请求声明的服务端搜索工具按次收费;在其他路由上以及模型请求之外是 Search API(`deepseek-search-api`),因为它返回来源时无需向会话没有使用的提供方发起辅助模型请求。`dsh-tool-web` 把发起调用的 Session 最近一次模型请求的路由写入每个搜索请求,`searchReady()` 按正在准备的步骤的路由选择,因此就绪判断与执行指向同一个提供方。这两条路由和两个提供方 id 是 `dsh-web` 中的常量:部署只能通过配置 `searchProvider` 改变结果,设置页把未配置的状态显示为**自动选择**。抓取默认使用本地 HTTP 抓取,因为它没有按次的 API 费用,执行 Harness 自身的 URL 校验和资源限制,并且可以访问内网和本地地址。Fetch API 仍可在下拉框中直接选择。
|
||||
|
||||
已保存的选择——无论位于设置文档还是部署自身的组合中——优先于内置默认值,升级不会改写它。执行时从不替换选择:所选提供方缺失、不可用或失败时,操作以结构化错误失败,不会回退到其他搜索或抓取提供方。回退会把查询和凭据发往用户未选择的端点,并在不提示的情况下改变计费。
|
||||
|
||||
### 旧版 Messages 搜索
|
||||
|
||||
DeepSeek Messages 搜索提供方仍以 **DeepSeek(旧版)**提供。已保存的 `web.searchProvider: deepseek-official`(或 `DSH_WEB_SEARCH_PROVIDER=deepseek-official`)会选中它,因此网关支持 Messages 搜索但不提供 `/v1/tools` 的用户可以保留可用的提供方。
|
||||
DeepSeek Messages 搜索提供方仍以 **DeepSeek 服务端搜索**提供,并承担 DeepSeek 模型路由上未配置提供方的搜索。已保存的 `web.searchProvider: deepseek-official`(或 `DSH_WEB_SEARCH_PROVIDER=deepseek-official`)会在所有路由上选中它,因此网关支持 Messages 搜索但不提供 `/v1/tools` 的用户可以保留可用的提供方。
|
||||
|
||||
Messages 提供方负责声明并写入 `web/deepseek-search-llm-request`。声明和载荷保持与已发布会话兼容;Search 与 Fetch API 包既不声明也不写入这一辅助事件。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**让每个提供方声明自己是哪些路由的默认项。** 在 `WebSearchProvider` 上加一个 `defaultFor(llmProvider)` 成员可以让 `dsh-web` 不含 DeepSeek 的 id,但要为只有一个实例的规则修改两个 DeepSeek 提供方包。
|
||||
|
||||
**把路由到提供方的表放进 `dsh-web` 的配置。** profile 补丁会替换条目的整个 `config`,因此已存的提供方选择会连带存下这张表的副本,不再跟随内置的表;而这张表也不是用户需要做的选择:固定提供方已经可以覆盖它。
|
||||
|
||||
**让 Search API 提供方在 DeepSeek 路由上转交给 Messages 搜索。** 菜单可以保持两项,但名为 DeepSeek Search API 的条目会运行另一个提供方,用户无法为 DeepSeek 模型固定 Search API,而且一个提供方包要依赖另一个。
|
||||
|
||||
**保留一个同时切换两个 API 的开关。** 它让使用 Fetch API 无需修改配置,但把抓取的计费和目标访问策略绑在搜索选择上,也无法表达其他插件注册的提供方。
|
||||
|
||||
**按可用性过滤列表,或在每个条目中加入可用性。** 过滤后的列表恰好会在凭据缺失时隐藏提供方,而这正是用户需要选择并配置它的时候。可用性还取决于请求的模型路由和凭据状态,列表中的布尔值可能与实际执行结果不一致。已归档的[观察面决策](../../archived/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md)只允许引入消费方实际读取的最小信号;下拉框只读取注册情况。
|
||||
@@ -76,10 +82,10 @@ Messages 提供方负责声明并写入 `web/deepseek-search-llm-request`。声
|
||||
|
||||
## 影响
|
||||
|
||||
没有已保存搜索选择的用户通过 Search API 搜索:查询发往会话的 DeepSeek 凭据所选的 Search 端点,每次计为一次 Search API 请求,并且除非关闭 `sendOriginalQuestion`,还会把最近一条用户提示的至多 128 个字符作为 `ori_question` 发送。网关没有 `/v1/tools` 路由的部署会遇到搜索失败,直到选择 Messages 搜索,或把 `searchBaseURL` 设为提供这些路由的基础地址。已保存的 `deepseek-official` 选择使用 Messages 搜索。没有已保存抓取选择的用户通过本地 HTTP 抓取。已登录但没有 API 密钥的用户在 `auto` 计费下,除 DeepSeek API 密钥路由上的会话外,都可以使用 DeepSeek 网页搜索;[升级指南](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.zh.md)列出了每种受影响的配置。
|
||||
没有已保存搜索选择的用户在 DeepSeek 模型路由上的会话中通过 Messages 搜索进行搜索:每次搜索是一次按模型 token 计费的辅助 Messages 请求,发往 Messages 搜索自己的端点,该端点不跟随模型提供方的基础地址,因此 DeepSeek 模型提供方指向网关的部署会遇到搜索失败,直到把该网关保存为 Messages Base URL 或固定使用 Search API([升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.zh.md))。在其他路由上他们通过 Search API 搜索:查询发往会话的 DeepSeek 凭据所选的 Search 端点,每次计为一次 Search API 请求,并且除非关闭 `sendOriginalQuestion`,还会把最近一条用户提示的至多 128 个字符作为 `ori_question` 发送。网关没有 `/v1/tools` 路由的部署在这些路由上会遇到搜索失败,直到选择 Messages 搜索,或把 `searchBaseURL` 设为提供这些路由的基础地址。`dsh-web` 点名了两条 DeepSeek 模型路由和两个 DeepSeek 搜索提供方,再出现一个按路由的默认值时须改为提供方无关的规则。已保存的 `deepseek-official` 选择使用 Messages 搜索。没有已保存抓取选择的用户通过本地 HTTP 抓取。已登录但没有 API 密钥的用户在 `auto` 计费下,除 DeepSeek API 密钥路由上的会话外,都可以使用 DeepSeek 网页搜索;[升级指南](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.zh.md)列出了每种受影响的配置。
|
||||
|
||||
插件提供方(包括在创作模式下编写的提供方)一经注册,就会以其 `title` 出现在对应的下拉框中。下拉框可能提供在当前请求中无法运行的提供方;失败会在执行搜索或抓取时出现。每次注册表变更会在每个观察它的 Client 中产生一次转发事件和一次列表读取。
|
||||
|
||||
## 验证
|
||||
|
||||
[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) 覆盖列表内容与顺序、标题、注册与撤销后的事件、重复注册被拒绝时不触发事件,以及监听器失败的隔离。[deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) 覆盖独立的 Messages 提供方,[credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) 针对两个能力覆盖账号路由上的账号令牌及其在 HTTP 401 后被作废、未登录时回退到 API 密钥、官方、非 DeepSeek 和会话之外的操作使用路由密钥与端点、DeepSeek 路由之外没有密钥时回退到账号、在每个路由上只用账号或只用 API 密钥的计费、单独字段优先于计费方式、没有该路由时使用 `DEEPSEEK_API_KEY` 与官方基础地址、从不发送令牌的 YAML 单独字段、两个能力相互独立、就绪判断与每次操作一致,以及被忽略的已移除字段;[composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) 通过 Loader 启动真实的模型路由。[remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) 覆盖事件转发,[base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) 固定内置默认值。设置页的 controller 与 card 测试以及[插件配置浏览器场景](../../../../apps/web/tests/plugin-config.e2e.ts)覆盖下拉框内容、Search 与 Fetch 的分别选择、DeepSeek API 的计费方式下拉框,以及各提供方保留的设置。
|
||||
[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) 覆盖列表内容与顺序、标题、注册与撤销后的事件、重复注册被拒绝时不触发事件、监听器失败的隔离,以及按路由的优先规则及其回退;[tool-web.spec.ts](../../../../packages/web/tool-web/tests/tool-web.spec.ts) 覆盖 `web_search` 发送的路由,`web-search-legacy-endpoint-guidance` 快照在未配置提供方的 DeepSeek 路由上运行 Messages 搜索。[deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) 覆盖独立的 Messages 提供方,[credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) 针对两个能力覆盖账号路由上的账号令牌及其在 HTTP 401 后被作废、未登录时回退到 API 密钥、官方、非 DeepSeek 和会话之外的操作使用路由密钥与端点、DeepSeek 路由之外没有密钥时回退到账号、在每个路由上只用账号或只用 API 密钥的计费、单独字段优先于计费方式、没有该路由时使用 `DEEPSEEK_API_KEY` 与官方基础地址、从不发送令牌的 YAML 单独字段、两个能力相互独立、就绪判断与每次操作一致,以及被忽略的已移除字段;[composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) 通过 Loader 启动真实的模型路由。[remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) 覆盖事件转发,[base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) 固定内置默认值。设置页的 controller 与 card 测试以及[插件配置浏览器场景](../../../../apps/web/tests/plugin-config.e2e.ts)覆盖下拉框内容、Search 与 Fetch 的分别选择、DeepSeek API 的计费方式下拉框,以及各提供方保留的设置。
|
||||
@@ -12,8 +12,8 @@
|
||||
en: 5d2dc730467e4bf3
|
||||
zh: 4aca28691504cd7b
|
||||
/agent-note-change-request-panel-and-worktree-sessions/deferred:
|
||||
en: 32ef8af85f4d2f66
|
||||
zh: b82b67f94346399e
|
||||
en: e76e8129691db30f
|
||||
zh: fd242e67bab2633d
|
||||
/agent-note-change-request-panel-and-worktree-sessions/alternatives-considered:
|
||||
en: e471e16b6b6450ca
|
||||
zh: 5fbc9242edc8d112
|
||||
|
||||
@@ -32,12 +32,7 @@ Review comments capture the file, side, range, complete hunk, and reviewed head
|
||||
|
||||
## Deferred
|
||||
|
||||
A left-navigation review page next to Plugins and Scheduled tasks, listing the user's pull requests or merge requests on the selected provider, is deferred. It attaches without changing this package's Session surfaces:
|
||||
|
||||
- **Provider capability** — an optional `ForgeProvider` method such as `listForViewer(host, filter, signal)` returns change request references; GitHub implements it with `gh search prs --author @me` or the GraphQL `viewer`, and the registry aggregates enabled providers.
|
||||
- **Remote** — a stream like `follow` that is keyed by provider and filter instead of a Session and polls through the same `ctx.forge.watch`.
|
||||
- **Client** — a `sidebar.panellist` entry with a `main` page in this package, as `ui-schedule` does, rendering `ChangeRequestCard`, which takes a change request, its snapshot, and optional actions.
|
||||
- **Settings** — provider choice and hosts on the bundle's configuration page.
|
||||
The left-navigation review page this section deferred is implemented as the [code review page](2026-11-11-forge-review-page.md); its lists come from an optional provider capability and its page reads change requests by URL, so this package's Session surfaces did not change.
|
||||
|
||||
The changes view offers no scope for one commit or for the last turn yet; both would be further `ForgeLocalScope` kinds read through `localDiff`.
|
||||
|
||||
|
||||
@@ -32,12 +32,7 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都
|
||||
|
||||
## Deferred
|
||||
|
||||
在左侧导航“插件”“自动化任务”旁边新增代码审查页、列出用户在所选提供方上的 pull request 或 merge request,这项工作推迟。它的接入不需要改动本包面向 Session 的界面:
|
||||
|
||||
- **提供方能力**——`ForgeProvider` 增加一个可选方法,例如 `listForViewer(host, filter, signal)`,返回变更请求引用;GitHub 用 `gh search prs --author @me` 或 GraphQL `viewer` 实现,注册表汇总已启用的提供方。
|
||||
- **Remote**——一条类似 `follow` 的流,以提供方与筛选条件而不是 Session 为键,通过同一个 `ctx.forge.watch` 轮询。
|
||||
- **客户端**——在本包中以 `sidebar.panellist` 条目加一个 `main` 页面实现(与 `ui-schedule` 相同),渲染接收变更请求、其快照与可选操作的 `ChangeRequestCard`。
|
||||
- **设置**——在套件的配置页中选择提供方与主机。
|
||||
本节曾暂缓的左侧导航代码审查页已实现为[代码评审页](2026-11-11-forge-review-page.zh.md);它的列表来自可选的提供方能力,页面按 URL 读取变更请求,因此本包的会话界面没有改变。
|
||||
|
||||
变更视图目前还没有单个提交与上一轮的范围;两者将是经 `localDiff` 读取的更多 `ForgeLocalScope` 种类。
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
en: 43298ccae4f7a6d4
|
||||
zh: eb7ef46b6f290c15
|
||||
/agent-note-direct-deepseek-search-and-fetch-apis/decision/protocol-selection-and-deployment:
|
||||
en: 90e5031d0d2fa9e4
|
||||
zh: a9c0229b20555d9e
|
||||
en: b07c0667e25927aa
|
||||
zh: 45eda3e151040201
|
||||
/agent-note-direct-deepseek-search-and-fetch-apis/decision/search-results-and-model-input:
|
||||
en: ad7b3e4fbe528cf2
|
||||
zh: 8ab8779bfdaaa4fa
|
||||
@@ -21,14 +21,14 @@
|
||||
en: 7566e400f9ab3a51
|
||||
zh: 118b2e84d0030480
|
||||
/agent-note-direct-deepseek-search-and-fetch-apis/decision/default-migration:
|
||||
en: cb2f0910955b6730
|
||||
zh: 7df057048acd7858
|
||||
en: 9b1e46885451ada3
|
||||
zh: 0deab76a188294dd
|
||||
/agent-note-direct-deepseek-search-and-fetch-apis/decision/legacy-messages-search:
|
||||
en: 0dcc97d8105fab60
|
||||
zh: d80d40ae3a0c601d
|
||||
/agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered:
|
||||
en: e377ad3c0327300e
|
||||
zh: 4b9f7f83f464e657
|
||||
en: da027a3c18b4fa0a
|
||||
zh: a3f0f448a0cae63f
|
||||
/agent-note-direct-deepseek-search-and-fetch-apis/consequences:
|
||||
en: 7ec21c5b1124e5f8
|
||||
zh: af769dbdb4face9f
|
||||
|
||||
@@ -14,7 +14,7 @@ The [DeepSeek Search and Fetch guide](https://api-docs.deepseek.com/zh-cn/guides
|
||||
|
||||
### Protocol selection and deployment
|
||||
|
||||
The APIs register as `deepseek-search-api` and `deepseek-fetch-api`. Messages search remains separately registered as `deepseek-official`. The web service selects each provider through `web.searchProvider` and `web.fetchProvider`, which the Search and Fetch menus on the Web search and fetch page set independently; the shipped composition selects the Search API and local HTTP fetch, as the [selection decision](../architecture/2026-10-29-web-provider-selection.md) records. A saved selection takes effect on the next operation because the web service reads both selections per operation. Each operation resolves one settings snapshot, including its endpoint and credential. Both APIs read the `web-deepseek-api` namespace, and each capability resolves its own endpoint and credential.
|
||||
The APIs register as `deepseek-search-api` and `deepseek-fetch-api`. Messages search remains separately registered as `deepseek-official`. The web service selects each provider through `web.searchProvider` and `web.fetchProvider`, which the Search and Fetch menus on the Web search and fetch page set independently; the shipped composition selects local HTTP fetch and no search provider, which runs the Search API outside the DeepSeek model routes, as the [selection decision](../architecture/2026-10-29-web-provider-selection.md) records. A saved selection takes effect on the next operation because the web service reads both selections per operation. Each operation resolves one settings snapshot, including its endpoint and credential. Both APIs read the `web-deepseek-api` namespace, and each capability resolves its own endpoint and credential.
|
||||
|
||||
Direct retrieval appends `/search` or `/fetch` to an API base. A capability without its own YAML endpoint fields uses the origin of the conversation's DeepSeek model route base URL with `/v1/tools`, which for the public deployment is the guide's `https://api.deepseek.com/v1/tools`; the [selection decision](../architecture/2026-10-29-web-provider-selection.md) owns that derivation and the credential each operation sends. The verified development base is `http://api-dev.deepseek.com:8031/api/v1/tools`; its prefix differs and is never inferred from the hostname, so such a deployment sets the complete base in `searchBaseURL` or `fetchBaseURL`. An unparseable base leaves that capability's provider unavailable.
|
||||
|
||||
@@ -36,7 +36,7 @@ The HTTP provider retains its own URL validation and resource limits. Selecting
|
||||
|
||||
### Default migration
|
||||
|
||||
The shipped composition selects `deepseek-search-api`; the [selection decision](../architecture/2026-10-29-web-provider-selection.md) owns that default and its no-fallback rule. API keys and account tokens both reach the public routes. Deployments behind a gateway without `/v1/tools` routes set `searchBaseURL` to a base that serves them. A stored `web.searchProvider: deepseek-official` selects Messages search, and any other stored selection keeps its provider.
|
||||
The shipped composition fixes no search provider: a search runs Messages search for a model request on a DeepSeek model route and `deepseek-search-api` on every other route; the [selection decision](../architecture/2026-10-29-web-provider-selection.md) owns that default and its no-fallback rule. API keys and account tokens both reach the public routes. Deployments behind a gateway without `/v1/tools` routes set `searchBaseURL` to a base that serves them. A stored `web.searchProvider: deepseek-official` selects Messages search, and any other stored selection keeps its provider.
|
||||
|
||||
### Legacy Messages search
|
||||
|
||||
@@ -48,7 +48,7 @@ The independent `dsh-web-search-deepseek` provider sends Messages search request
|
||||
|
||||
**Reuse the Messages address or infer a route prefix.** The protocols and deployed prefixes differ. Separate bases preserve existing configurations and avoid sending a valid request to the wrong route.
|
||||
|
||||
**Require an explicit Search API base.** The Search API is the shipped search default, and an empty default would leave it unavailable until every user enters an address that the DeepSeek model route already determines. Other deployments still set their own base.
|
||||
**Require an explicit Search API base.** The Search API is the shipped search default outside the DeepSeek model routes, and an empty default would leave it unavailable until every user enters an address that the DeepSeek model route already determines. Other deployments still set their own base.
|
||||
|
||||
**Keep the APIs inside the Messages provider behind a provider-local switch.** A switch inside the Messages provider cannot change fetch routing, so `web_fetch` would stay on HTTP unless the user also edited `web.fetchProvider`; it also ties the APIs' lifecycle to Messages search. Separate registrations let the web service's existing selection choose each provider, without coupling either API to the Messages provider.
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ Status: implemented
|
||||
|
||||
### 协议选择与部署
|
||||
|
||||
两个 API 注册为 `deepseek-search-api` 和 `deepseek-fetch-api`;Messages 搜索仍独立注册为 `deepseek-official`。Web 服务通过 `web.searchProvider` 和 `web.fetchProvider` 选择各个提供方,「网页搜索与获取」页上的 Search 和 Fetch 下拉框分别设置这两项;内置组合选择 Search API 与本地 HTTP 抓取,见[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)。已保存的选择从下一次操作起生效,因为 Web 服务在每次操作时读取两项选择。每次操作解析一份包含端点和凭据的设置快照。两个 API 读取 `web-deepseek-api` namespace,每个能力各自解析端点与凭据。
|
||||
两个 API 注册为 `deepseek-search-api` 和 `deepseek-fetch-api`;Messages 搜索仍独立注册为 `deepseek-official`。Web 服务通过 `web.searchProvider` 和 `web.fetchProvider` 选择各个提供方,「网页搜索与获取」页上的 Search 和 Fetch 下拉框分别设置这两项;内置组合选择本地 HTTP 抓取,不选择搜索提供方,此时 DeepSeek 模型路由之外的搜索使用 Search API,见[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)。已保存的选择从下一次操作起生效,因为 Web 服务在每次操作时读取两项选择。每次操作解析一份包含端点和凭据的设置快照。两个 API 读取 `web-deepseek-api` namespace,每个能力各自解析端点与凭据。
|
||||
|
||||
直接检索在 API 基础地址后追加 `/search` 或 `/fetch`。没有在 YAML 中单独设置端点字段的能力,使用会话的 DeepSeek 模型路由基础地址的 origin 加 `/v1/tools`,公网部署即指南中的 `https://api.deepseek.com/v1/tools`;该推导及每次操作发送的凭据由[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)负责。已验证的开发地址为 `http://api-dev.deepseek.com:8031/api/v1/tools`;其前缀不同,程序不会根据主机名推断,此类部署需在 `searchBaseURL` 或 `fetchBaseURL` 中填写完整基础地址。基础地址无法解析时,该能力的提供方不可用。
|
||||
|
||||
@@ -36,7 +36,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek
|
||||
|
||||
### 默认值迁移
|
||||
|
||||
内置组合选择 `deepseek-search-api`;[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)负责这项默认值及其不回退规则。API 密钥和账号 token 都能访问公网路由。位于没有 `/v1/tools` 路由的网关之后的部署,需把 `searchBaseURL` 设为提供这些路由的基础地址。已保存的 `web.searchProvider: deepseek-official` 会选中 Messages 搜索,其他已保存的选择保持其提供方。
|
||||
内置组合不固定搜索提供方:为 DeepSeek 模型路由上的模型请求发起的搜索运行 Messages 搜索,其他路由上的搜索运行 `deepseek-search-api`;[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)负责这项默认值及其不回退规则。API 密钥和账号 token 都能访问公网路由。位于没有 `/v1/tools` 路由的网关之后的部署,需把 `searchBaseURL` 设为提供这些路由的基础地址。已保存的 `web.searchProvider: deepseek-official` 会选中 Messages 搜索,其他已保存的选择保持其提供方。
|
||||
|
||||
### 旧版 Messages 搜索
|
||||
|
||||
@@ -48,7 +48,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek
|
||||
|
||||
**复用 Messages 地址或推断路由前缀。** 协议与部署前缀不同。分别保存基础地址可保留现有配置,避免把有效请求发往错误路由。
|
||||
|
||||
**要求显式填写 Search API 基础地址。** Search API 是内置的搜索默认值,空默认值会让它在每位用户填写一个 DeepSeek 模型路由已经确定的地址之前都不可用。其他部署仍可设置自己的基础地址。
|
||||
**要求显式填写 Search API 基础地址。** Search API 是 DeepSeek 模型路由之外内置的搜索默认值,空默认值会让它在每位用户填写一个 DeepSeek 模型路由已经确定的地址之前都不可用。其他部署仍可设置自己的基础地址。
|
||||
|
||||
**把两个 API 放在 Messages 提供方内部,由提供方自己的开关切换。** Messages 提供方内的开关无法改变抓取路由,因此除非用户另外修改 `web.fetchProvider`,`web_fetch` 仍会走 HTTP;它还会把两个 API 的生命周期绑在 Messages 搜索上。独立注册让 Web 服务通过现有的提供方选择机制选择各个提供方,不会把任一 API 与 Messages 提供方绑定。
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-09-sdk-prompt-time-zone.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-09-sdk-prompt-time-zone.md
|
||||
/agent-note-per-prompt-sdk-time-zone:
|
||||
en: 44d838b330c01b71
|
||||
zh: 322844db122f305f
|
||||
/agent-note-per-prompt-sdk-time-zone/problem:
|
||||
en: 225547dcc5d63b6e
|
||||
zh: b62fa355a827d662
|
||||
/agent-note-per-prompt-sdk-time-zone/decision:
|
||||
en: be0afd0975a15d3a
|
||||
zh: 91f161bc2f7cd938
|
||||
/agent-note-per-prompt-sdk-time-zone/alternatives-considered:
|
||||
en: b67b2d44aeb2dc6b
|
||||
zh: 69d0356bfe3204a6
|
||||
/agent-note-per-prompt-sdk-time-zone/consequences:
|
||||
en: ec0b5f4a68aaa351
|
||||
zh: 4eb09ed822f456a2
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note: Per-prompt SDK time zone
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-09-sdk-prompt-time-zone.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Web and Desktop prompts carry the browser zone that the Host canonicalizes and records on that user message, and [time-context](../../../../packages/context/time-context/README.md) tells the model to interpret unqualified dates and times in it. SDK prompts recorded `{ kind: 'user' }`, and time-context read a zone only from a user source that also had a Web `rpcId`. Every SDK request therefore showed `Browser time zone for this request: unavailable.`, and the model asked about dates that a Web user would never be asked about. The SDK protocol had no field through which an embedding application could report its user's zone.
|
||||
|
||||
## Decision
|
||||
|
||||
The zone stays request-local message source data, as in the [explicit Schedule time-zone decision](../simplification/2026-08-09-explicit-schedule-time-zone.md); the SDK supplies it per prompt.
|
||||
|
||||
- `session/prompt` and `session/query` accept an optional `timeZone`. The TypeScript client accepts it in `HarnessClient.prompt()` options and `run()` options; the Python client accepts the `time_zone` keyword in `session_prompt()` and `run()`.
|
||||
- The SDK server canonicalizes an explicit value with `canonicalClientTimeZone`, the check the Web Host uses. A rejected value fails that request with a `TypeError`, answered as JSON-RPC `-32603` like the server's other parameter errors, before a Session is created or input is routed.
|
||||
- An omitted value samples `Intl.DateTimeFormat().resolvedOptions().timeZone` when each prompt is accepted. A sampled value that does not canonicalize, such as `+00:00` under `TZ=GMT` or `Etc/Unknown`, records no zone and does not fail the prompt.
|
||||
- The prompt records the `sdk-user` message source `{ kind: 'user', clientTimeZone? }` without `rpcId`. The `rpcId` identifies a Web submission for prompt acknowledgement and attachment reclamation, which the SDK does not have.
|
||||
- `reportedBrowserTimeZone` reads a string `clientTimeZone` from any `user` source. Writers canonicalize before commit, and request preparation still refuses a noncanonical value, so the Web path and the model-visible text stay unchanged.
|
||||
- Native commands record no zone. Web executes slash commands through `commands.execute` without `clientTimeZone`, and SDK `session/query` routes commands to the same handlers, so `/plan <text>` steers a zone-less message on both paths.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Inject one runtime-wide zone into every request.** A process or configuration zone applied by time-context would also cover in-process children and plugin messages, but it would present a deployment fact as user authority. The time-context fallback display zone already exists and deliberately keeps the `unavailable` policy.
|
||||
|
||||
**Write a synthetic `rpcId` on SDK prompts.** This reuses the Web source variant unchanged, but Web clients use `rpcId` to settle submissions and reclaim attachments, so a synthetic identity would claim a Web submission that never existed.
|
||||
|
||||
**Fix the zone at `initialize`.** One value per connection saves a field per prompt, but a long-lived runtime can serve users in different zones and a process zone can change, so the value would become stale. A per-prompt value matches the Web browser sample.
|
||||
|
||||
## Consequences
|
||||
|
||||
- SDK embeddings that pass no zone now report the runtime process zone. In a container this is usually `UTC`, which may differ from the user's zone; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.md) tells consumers to pass `timeZone` or `time_zone`, or to set `TZ`.
|
||||
- SDK subagent children receive prompts without a zone, so they report their own process zone; in-process children see `unavailable`, as on Web.
|
||||
- A reader that predates the relaxed check ignores an SDK prompt zone; the [persistence record](../../../../docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.md) keeps the format version.
|
||||
- `packages/sdk/server/tests/time-zone.spec.ts` pins canonical, rejected, sampled, and unusable zones, the `session/query` route, and matching `/plan` sources on the SDK and native command paths. `apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts` asserts the model-visible line through the shipped `sdk` profile. The SDK snapshot driver sends `timeZone: 'UTC'` and runs with `TZ=UTC`.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Agent Note:SDK prompt 逐条上报时区
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-09-sdk-prompt-time-zone.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
Web 与 Desktop 的 prompt 携带浏览器时区,Host 规范化后把它记录在该条用户消息上,[time-context](../../../../packages/context/time-context/README.zh.md) 随后让模型按该时区解释未限定时区的日期与时间。SDK prompt 记录的是 `{ kind: 'user' }`,而 time-context 只从同时带有 Web `rpcId` 的 user 来源读取时区。因此每个 SDK 请求都显示 `Browser time zone for this request: unavailable.`,模型会就 Web 用户从不会被追问的日期去询问用户。SDK 协议也没有字段让嵌入方应用上报其用户的时区。
|
||||
|
||||
## 决定
|
||||
|
||||
时区仍是请求本地的消息来源数据,与[显式定时任务时区决定](../simplification/2026-08-09-explicit-schedule-time-zone.zh.md)一致;SDK 逐条 prompt 提供它。
|
||||
|
||||
- `session/prompt` 与 `session/query` 接受可选的 `timeZone`。TypeScript 客户端在 `HarnessClient.prompt()` 选项和 `run()` 选项中接受它;Python 客户端在 `session_prompt()` 和 `run()` 中接受 `time_zone` 关键字参数。
|
||||
- SDK server 用 Web Host 所用的同一检查 `canonicalClientTimeZone` 规范化显式值。被拒的值让该请求以 `TypeError` 失败,与 server 的其他参数错误一样应答为 JSON-RPC `-32603`,发生在创建 Session 或路由输入之前。
|
||||
- 省略时,在接受每条 prompt 时采样 `Intl.DateTimeFormat().resolvedOptions().timeZone`。采样值无法规范化时(例如 `TZ=GMT` 下的 `+00:00` 或 `Etc/Unknown`),不记录时区,也不让 prompt 失败。
|
||||
- prompt 记录不带 `rpcId` 的 `sdk-user` 消息来源 `{ kind: 'user', clientTimeZone? }`。`rpcId` 标识一次 Web 提交,用于 prompt 确认和附件回收,SDK 没有这样的提交。
|
||||
- `reportedBrowserTimeZone` 从任何 `user` 来源读取字符串 `clientTimeZone`。写入方在提交前规范化,请求准备阶段仍拒绝非规范值,因此 Web 路径和模型可见文本都不变。
|
||||
- 原生命令不记录时区。Web 通过 `commands.execute` 执行 slash 命令且不带 `clientTimeZone`,SDK `session/query` 把命令路由到同一批 handler,因此两条路径上的 `/plan <text>` 都 steer 一条不带时区的消息。
|
||||
|
||||
## 备选方案
|
||||
|
||||
**向每个请求注入一个运行时级时区。** 由 time-context 应用的进程或配置时区也能覆盖进程内子 agent 与插件消息,但它会把部署事实当作用户依据呈现。time-context 已有回退显示时区,并且有意保留 `unavailable` 策略。
|
||||
|
||||
**在 SDK prompt 上写入合成的 `rpcId`。** 这样可以原样复用 Web 来源变体,但 Web 客户端用 `rpcId` 结算提交并回收附件,合成标识会声称存在一次从未发生的 Web 提交。
|
||||
|
||||
**在 `initialize` 时固定时区。** 每个连接一个值可以省去每条 prompt 的字段,但长期运行的运行时可能服务不同时区的用户,进程时区也可能变化,该值会过时。逐条 prompt 的值与 Web 浏览器采样一致。
|
||||
|
||||
## 影响
|
||||
|
||||
- 不传时区的 SDK 嵌入方现在上报运行时进程时区。容器中通常是 `UTC`,可能与用户时区不同;[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.zh.md)要求使用方传入 `timeZone` 或 `time_zone`,或设置 `TZ`。
|
||||
- SDK subagent 子运行时收到的 prompt 不带时区,因此上报自身进程时区;进程内子 agent 与 Web 上一样看到 `unavailable`。
|
||||
- 早于放宽检查的读取方会忽略 SDK prompt 的时区;[持久化记录](../../../../docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.zh.md)保持格式版本不变。
|
||||
- `packages/sdk/server/tests/time-zone.spec.ts` 固定规范化、拒绝、采样与不可用时区,`session/query` 路由,以及 SDK 与原生命令路径上一致的 `/plan` 来源。`apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts` 通过随发行版交付的 `sdk` profile 断言模型可见的那一行。SDK snapshot 驱动发送 `timeZone: 'UTC'` 并在 `TZ=UTC` 下运行。
|
||||
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-11-forge-review-page.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-11-forge-review-page.md
|
||||
/agent-note-code-review-page:
|
||||
en: 88e0f71d0da6eda5
|
||||
zh: ff17f12fd505c772
|
||||
/agent-note-code-review-page/problem:
|
||||
en: ad1da0c97cfc9c2d
|
||||
zh: f4420c0b004fd189
|
||||
/agent-note-code-review-page/decision:
|
||||
en: b0ba35d7c5818dc3
|
||||
zh: 5414ec6190be0726
|
||||
/agent-note-code-review-page/alternatives-considered:
|
||||
en: 963b1be39a0e4bac
|
||||
zh: 940b86a5e2036477
|
||||
/agent-note-code-review-page/consequences:
|
||||
en: c17a96adbec69d92
|
||||
zh: 06b5f2c28a9ec331
|
||||
@@ -0,0 +1,31 @@
|
||||
# Agent Note: Code review page
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-11-forge-review-page.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
The [forge panel](2026-10-09-forge-panel.md) shows the change requests one Session created or pushed. A reviewer also needs the change requests that ask for their review, that they created, or that involve them, read and reviewed without first finding or creating the Session that owns them, and a conversation with the Agent about one of them that does not mix into an unrelated existing conversation.
|
||||
|
||||
## Decision
|
||||
|
||||
A left-navigation Code review page in [`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) lists three viewer lists and shows one change request in full.
|
||||
|
||||
- **Lists** — an optional `ForgeProvider` capability (`viewer`, `listForViewer`, `countForViewer`) returns summaries of open change requests; GitHub answers each list with one GraphQL search, because one document with several searches times out. The Host reads the lists only while a page or count stream lasts, outside the forge's status polling, since a batch snapshot of dozens of change requests exceeds GitHub's query timeout; only the shown change request is polled through `ForgeService.watch`.
|
||||
- **Reads by URL** — the page's `forgePanel/review*` methods name a change request by URL and no Session; they share the Session-bound methods' implementation and are reachable only by callers that may use the Host's code host credentials.
|
||||
- **Description** — `readDescription` returns the Markdown body, labels, and signed addresses for private attachments, which the page substitutes before rendering with HTML omitted.
|
||||
- **Changes** — the page draws the changes view itself, split from the right-sidebar tab, with a panel state that holds only the shown change request; plugin lenses, annotations, and slots stay with the Session tab, whose extension points name a Session.
|
||||
- **Chat** — the chat tab embeds `conversation.content` for the blank Session `connectWorkspace` resolves in the Workspace named like the repository, and never offers an existing conversation. A Workspace picked in the Hero is handled by the page, as every owner of the content handles its own picks: the page connects that Workspace's blank and shows it in the chat tab, where the main Conversation opens it as the main Session. The change request is bound when the Session's first message enters its inbox, so a blank that is never used stays unbound.
|
||||
- **Hosts** — the page lists every configured host together; choosing among hosts and accounts waits for a second provider that lists change requests.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **A Session per change request for reading** — rejected: reading the description or the diff would create Sessions nobody converses in, and bind them.
|
||||
- **Reviewing in an existing conversation** — rejected by the user: the conversation's context would mix with the review.
|
||||
- **Listing through the status poller** — rejected: the batch snapshot query times out at the list sizes a reviewer has.
|
||||
- **Binding when the chat opens** — rejected: the blank Session is shared with New Session, so it would carry the binding into an unrelated conversation.
|
||||
|
||||
## Consequences
|
||||
|
||||
The forge registry gains a fifth optional capability family and a `rate-limited` failure code, recorded in the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.md). A Host restart before the chat's first message forgets the staged binding.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Agent Note: 代码评审页
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-11-forge-review-page.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
[forge 面板](2026-10-09-forge-panel.zh.md)显示一个会话创建或推送的变更请求。评审者还需要请自己评审的、自己创建的以及与自己有关的变更请求,不必先找到或创建拥有它们的会话就能阅读和评审;也需要就其中一个与 Agent 对话,而且这段对话不能混进无关的已有对话。
|
||||
|
||||
## Decision
|
||||
|
||||
[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 在左侧导航中加入“代码评审”页,列出三个登录用户列表,并完整显示一个变更请求。
|
||||
|
||||
- **列表**——可选的 `ForgeProvider` 能力(`viewer`、`listForViewer`、`countForViewer`)返回未关闭变更请求的摘要;GitHub 每个列表用一次 GraphQL 搜索回答,因为在一个文档中放多个搜索会超时。Host 只在页面流或计数流存在时读取列表,不经过 forge 的状态轮询,因为几十个变更请求的批量快照会超过 GitHub 的查询时限;只有显示中的变更请求经 `ForgeService.watch` 轮询。
|
||||
- **按 URL 读取**——页面的 `forgePanel/review*` 方法以 URL 而不是会话指定变更请求;它们与会话绑定的方法共用实现,只有可以使用 Host 代码托管凭据的调用方能访问。
|
||||
- **描述**——`readDescription` 返回 Markdown 正文、标签以及私有附件的签名地址,页面替换这些地址后以省略 HTML 的方式渲染。
|
||||
- **变更**——页面自己绘制变更视图(从右侧栏标签中拆出),面板状态只含显示中的变更请求;插件的透镜、行注释和插槽仍只在会话标签中,因为这些扩展点以会话为对象。
|
||||
- **对话**——对话标签为 `connectWorkspace` 在与仓库同名的工作区中解析出的空白会话嵌入 `conversation.content`,从不提供已有对话。在 Hero 中选择工作区由页面自己处理,这与内容的每个属主处理各自的选择一致:页面连接该工作区的空白会话并在对话标签中显示它,而主 Conversation 会把它打开为主会话。该会话的首条消息进入收件箱时才绑定变更请求,因此从未使用的空白会话保持未绑定。
|
||||
- **主机**——页面把所有已配置的主机合并列出;在主机与账号之间选择要等到第二个能列出变更请求的提供方。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **每个变更请求用一个会话来阅读**——否决:阅读描述或 diff 会创建无人对话的会话并绑定它们。
|
||||
- **在已有对话中评审**——用户否决:对话上下文会与评审混在一起。
|
||||
- **经状态轮询列出**——否决:在评审者常见的列表规模下,批量快照查询会超时。
|
||||
- **打开对话时就绑定**——否决:空白会话与“新会话”共用,会把绑定带进无关的对话。
|
||||
|
||||
## Consequences
|
||||
|
||||
forge 注册表增加第五组可选能力和 `rate-limited` 失败码,记录在[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.zh.md)中。在对话的首条消息之前重启 Host 会丢失暂存的绑定。
|
||||
+4
-4
@@ -9,8 +9,8 @@
|
||||
en: 4a7e52f6a16dec96
|
||||
zh: d558db30801355d9
|
||||
/agent-note-explicit-schedule-time-zone-boundary/decision:
|
||||
en: 6f233286c95b5294
|
||||
zh: 5a1f4ba6f5ccbd36
|
||||
en: ab632daa5d687c77
|
||||
zh: b406216a5b35e5ac
|
||||
/agent-note-explicit-schedule-time-zone-boundary/alternatives-considered:
|
||||
en: 982fe0b8d24a66ce
|
||||
zh: e6dceee1ce776d21
|
||||
@@ -18,5 +18,5 @@
|
||||
en: 56dcb44f09be3713
|
||||
zh: 59a6814a662458ad
|
||||
/agent-note-explicit-schedule-time-zone-boundary/consequences:
|
||||
en: d9358667c58662e4
|
||||
zh: d536bb0fccd9f0a9
|
||||
en: 43980cd5ebdf6685
|
||||
zh: ed3051f8eb45ead4
|
||||
@@ -12,9 +12,9 @@ Most of that complexity sat outside Schedule. The model already interprets natur
|
||||
|
||||
## Decision
|
||||
|
||||
The browser zone is request-local source data. The Web client samples `Intl.DateTimeFormat().resolvedOptions().timeZone` for every prompt. The Host accepts an optional `clientTimeZone`, validates and canonicalizes `UTC` or an IANA Area/Location at the RPC boundary, and logs it on that exact `user-rpc` message. Invalid values reject prompt admission. Non-browser clients may omit it.
|
||||
The browser zone is request-local source data. The Web client samples `Intl.DateTimeFormat().resolvedOptions().timeZone` for every prompt. The Host accepts an optional `clientTimeZone`, validates and canonicalizes `UTC` or an IANA Area/Location at the RPC boundary, and logs it on that exact `user-rpc` message. Invalid values reject prompt admission. Non-browser clients may omit it; SDK prompts report an explicit or sampled process zone on an `sdk-user` source without `rpcId`, as recorded in [per-prompt SDK time zone](../feature/2026-11-09-sdk-prompt-time-zone.md).
|
||||
|
||||
Time-context derives unique, mixed, or missing browser facts from original user-rpc messages in the open turn. A unique zone formats the clock and tells the model to interpret otherwise-unqualified dates and times in that zone. Mixed or missing browser-zone records tell the model to ask the user. The configured or process zone is only a display fallback and is never presented as user authority.
|
||||
Time-context derives unique, mixed, or missing browser facts from original user messages in the open turn that carry `clientTimeZone`. A unique zone formats the clock and tells the model to interpret otherwise-unqualified dates and times in that zone. Mixed or missing browser-zone records tell the model to ask the user. The configured or process zone is only a display fallback and is never presented as user authority.
|
||||
|
||||
Schedule accepts no implicit local zone. `at` is either a strict offset-bearing RFC 3339 string or exact `{ date, time, time_zone }`. The structured form requires its zone even when time-context just showed the model a browser zone. Schedule does not import time-context, inspect user-message sources, read a Session header, or produce a confirmation error. Its parser validates the explicit value, rejects daylight-saving gaps, chooses the first instant in overlaps, and stores only canonical UTC `scheduledAt`.
|
||||
|
||||
@@ -43,5 +43,5 @@ Source audits reject `SessionHeader.timeZone`, persistence `time_zone` columns,
|
||||
- Browser-local natural language works without a persisted Session-zone subsystem.
|
||||
- Schedule has one explicit, independently testable absolute-time boundary.
|
||||
- Travel and concurrent tabs affect only their own prompts; a turn with mixed browser-zone records asks instead of mutating shared state.
|
||||
- Non-browser clients remain valid but must provide enough natural-language context or explicit tool arguments.
|
||||
- Non-browser clients without a reported zone remain valid but must provide enough natural-language context or explicit tool arguments.
|
||||
- The model may still make an interpretation error; the tool guarantees only that the explicit calendar value is valid and deterministic.
|
||||
+3
-3
@@ -12,9 +12,9 @@ Status: implemented
|
||||
|
||||
## 决策
|
||||
|
||||
浏览器时区是请求本地的来源数据。Web client 会为每条提示词采样 `Intl.DateTimeFormat().resolvedOptions().timeZone`。Host 接受可选的 `clientTimeZone`,在 RPC 边界校验并规范化 `UTC` 或 IANA Area/Location,再将其记录在确切的那条 `user-rpc` 消息上。无效值会使提示词准入被拒绝。非浏览器 client 可以省略它。
|
||||
浏览器时区是请求本地的来源数据。Web client 会为每条提示词采样 `Intl.DateTimeFormat().resolvedOptions().timeZone`。Host 接受可选的 `clientTimeZone`,在 RPC 边界校验并规范化 `UTC` 或 IANA Area/Location,再将其记录在确切的那条 `user-rpc` 消息上。无效值会使提示词准入被拒绝。非浏览器 client 可以省略它;SDK prompt 在不带 `rpcId` 的 `sdk-user` 来源上上报显式或采样的进程时区,见 [SDK prompt 逐条上报时区](../feature/2026-11-09-sdk-prompt-time-zone.zh.md)。
|
||||
|
||||
Time-context 从 open turn 中的原始 user-rpc 消息派生唯一、混合或缺失的浏览器事实。唯一时区会用于格式化时钟,并告诉模型把未明确限定时区的日期和时间解释为该时区。浏览器时区记录混合或缺失时,模型会被告知询问用户。配置或进程时区只作为显示 fallback,绝不会被呈现为用户权威。
|
||||
Time-context 从 open turn 中带 `clientTimeZone` 的原始 user 消息派生唯一、混合或缺失的浏览器事实。唯一时区会用于格式化时钟,并告诉模型把未明确限定时区的日期和时间解释为该时区。浏览器时区记录混合或缺失时,模型会被告知询问用户。配置或进程时区只作为显示 fallback,绝不会被呈现为用户权威。
|
||||
|
||||
Schedule 不接受隐式本地时区。`at` 要么是带显式偏移量且严格符合 RFC 3339 的字符串,要么是精确的 `{ date, time, time_zone }`。即使 time-context 刚向模型展示了浏览器时区,结构化形式仍要求自己的时区。Schedule 不导入 time-context、不检查 user message 来源、不读取 Session header,也不产生确认错误。它的 parser 会校验显式值、拒绝夏令时缺口、在重叠时选择第一个时点,并且只存储规范化后的 UTC `scheduledAt`。
|
||||
|
||||
@@ -43,5 +43,5 @@ Host 测试固定别名的规范化、可省略行为和进入 Agent(智能体
|
||||
- 无需持久 Session 时区子系统,浏览器本地自然语言也能工作。
|
||||
- Schedule 具有一个显式且可独立测试的绝对时间边界。
|
||||
- 旅行与并发 tab 只影响各自的提示词;浏览器时区记录混合的 turn 会询问用户,而不是改变共享状态。
|
||||
- 非浏览器 client 仍然有效,但必须提供足够的自然语言上下文或显式工具参数。
|
||||
- 未上报时区的非浏览器 client 仍然有效,但必须提供足够的自然语言上下文或显式工具参数。
|
||||
- 模型仍可能产生解释错误;工具只保证显式日历值有效且具有确定性。
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
# Bilingual-pair consistency record for 2026-11-18-tool-reachability-and-initial-disclosure.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/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.md
|
||||
/agent-note-tool-reachability-and-initial-disclosure:
|
||||
en: 702b42d555430e20
|
||||
zh: d94f3adf52d9d7cb
|
||||
/agent-note-tool-reachability-and-initial-disclosure/problem:
|
||||
en: 006eb992e4c0dd4d
|
||||
zh: 530d13e4f832653b
|
||||
/agent-note-tool-reachability-and-initial-disclosure/proposal:
|
||||
en: 86ededd59a892229
|
||||
zh: 1ed3ac1f5b160f9d
|
||||
/agent-note-tool-reachability-and-initial-disclosure/proposal/reachability:
|
||||
en: 7e8256e97b924e34
|
||||
zh: be334f4469d0b5e1
|
||||
/agent-note-tool-reachability-and-initial-disclosure/proposal/initial-disclosure:
|
||||
en: 1c2466dff8ba70e1
|
||||
zh: d0e2c35a0e74008f
|
||||
/agent-note-tool-reachability-and-initial-disclosure/alternatives-considered:
|
||||
en: 27bff0dbad805d7a
|
||||
zh: be5b8d1746b5bc02
|
||||
/agent-note-tool-reachability-and-initial-disclosure/acceptance-criteria:
|
||||
en: 099ebf6f7c753286
|
||||
zh: 50e29d2522d7fee9
|
||||
/agent-note-tool-reachability-and-initial-disclosure/risks:
|
||||
en: 9366e2866f4b2555
|
||||
zh: 5d7b94bb85019f58
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
# Agent Note: Tool reachability and initial disclosure
|
||||
|
||||
Status: proposed
|
||||
|
||||
English | [中文](2026-11-18-tool-reachability-and-initial-disclosure.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Both executors disclose every reachable tool in full at every step: `tool-executor-native` through the request `tools` field, `tool-executor-ptc` through the `tools:sdk` section. No per-tool statement exists for how the model may call a tool and how much it receives before any discovery; `ToolSchema.deferLoading` names one provider mechanism instead.
|
||||
|
||||
## Proposal
|
||||
|
||||
Describe every reachable tool with two model-facing dimensions, defined by what the model receives, not by what the host or provider transmits.
|
||||
|
||||
### Reachability
|
||||
|
||||
| Value | Meaning |
|
||||
|---|---|
|
||||
| `native` | Callable only as a provider tool call. |
|
||||
| `program` | Callable only from inside a `run_code` program. |
|
||||
| `both` | Callable either way. |
|
||||
|
||||
Authorization is separate: a tool removed by `restrict()` or an inactive `when` condition is absent from this model; a guard denies one execution and changes neither dimension.
|
||||
|
||||
### Initial disclosure
|
||||
|
||||
| Value | What the model receives before any discovery |
|
||||
|---|---|
|
||||
| `none` | Nothing about this tool. |
|
||||
| `name` | The tool name. |
|
||||
| `summary` | A description without parameters; may be given per namespace. |
|
||||
| `full` | Name, description, parameters, and for `program` reachability the return type. |
|
||||
|
||||
Every reachable tool is searchable; `none` only means absent from the initial disclosure.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**A visibility axis of `invisible`, `discoverable`, `injected`, `system prompt`.** `injected` is the state a tool enters after a search hit, `system prompt` is a channel, and no name-only level exists; the axis mixed policy, state, and channel.
|
||||
|
||||
**A `discoverable` boolean.** Every case that seemed to need an unsearchable tool is authorization, search ranking, an alias, or a runtime builtin that is not a tool; omitting a schema is not enforcement ([packages/AGENTS.md](../../../../packages/AGENTS.md)).
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- Each registered tool resolves to one value per dimension per step, and both executors read the same resolution.
|
||||
- A `none` tool is found through `tool_search` and then called under each executor in a recorded snapshot; a `native` activation projects through [active tool headers](../../implemented/architecture/2026-09-20-dynamic-tool-updates.md).
|
||||
|
||||
## Risks
|
||||
|
||||
- Discovery adds a model round trip, and search quality depends on tool names and descriptions.
|
||||
- Per-step recomputation moves tools between values and changes the declaration prefix the cache relies on.
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
# Agent Note: 工具可达性与初始披露
|
||||
|
||||
Status: proposed
|
||||
|
||||
[English](2026-11-18-tool-reachability-and-initial-disclosure.md) | 中文
|
||||
|
||||
## Problem
|
||||
|
||||
两个执行器在每个步骤都完整披露每个可达工具:`tool-executor-native` 通过请求的 `tools` 字段,`tool-executor-ptc` 通过 `tools:sdk` 章节。没有任何按工具的说明能表达模型可以如何调用某个工具,以及在任何发现之前它能收到多少内容;`ToolSchema.deferLoading` 只是以某一个提供方机制命名。
|
||||
|
||||
## Proposal
|
||||
|
||||
用两个面向模型的维度描述每个可达工具,两者都由模型收到的内容定义,而不是由宿主或提供方传输的内容定义。
|
||||
|
||||
### 可达性
|
||||
|
||||
| 取值 | 含义 |
|
||||
|---|---|
|
||||
| `native` | 只能作为提供方工具调用来调用。 |
|
||||
| `program` | 只能在 `run_code` 程序内部调用。 |
|
||||
| `both` | 两种方式都可调用。 |
|
||||
|
||||
授权是独立的:被 `restrict()` 移除或因 `when` 条件未激活而移除的工具不在此模型之内;guard 拒绝的是一次执行,不改变任何一个维度。
|
||||
|
||||
### 初始披露
|
||||
|
||||
| 取值 | 模型在任何发现之前收到的内容 |
|
||||
|---|---|
|
||||
| `none` | 关于该工具的任何内容都没有。 |
|
||||
| `name` | 工具名称。 |
|
||||
| `summary` | 不含参数的描述;可以按命名空间给出。 |
|
||||
| `full` | 名称、描述、参数,以及 `program` 可达性下的返回类型。 |
|
||||
|
||||
每个可达工具都可被搜索;`none` 只表示不在初始披露中。
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**一个由 `invisible`、`discoverable`、`injected`、`system prompt` 构成的可见性轴。** `injected` 是工具在搜索命中后进入的状态,`system prompt` 是通道,且不存在仅名称级别;该轴混合了策略、状态和通道。
|
||||
|
||||
**一个 `discoverable` 布尔值。** 每个看似需要不可搜索工具的情形都是授权、搜索排序、别名或不是工具的运行时内建函数;省略 schema 不是强制手段([packages/AGENTS.md](../../../../packages/AGENTS.md))。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- 每个已注册工具在每个步骤为每个维度解析出一个取值,两个执行器读取同一次解析。
|
||||
- 在录制快照中,一个 `none` 工具在每个执行器下都通过 `tool_search` 被找到并随后被调用;`native` 激活按[活跃工具请求头](../../implemented/architecture/2026-09-20-dynamic-tool-updates.zh.md)投影。
|
||||
|
||||
## Risks
|
||||
|
||||
- 发现增加一次模型往返,且搜索质量取决于工具名称和描述。
|
||||
- 按步骤重新计算会在取值之间移动工具,并改变缓存所依赖的声明前缀。
|
||||
@@ -44,6 +44,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
|
||||
|
||||
<!-- 测试设计 -->
|
||||
|
||||
@@ -46,6 +46,7 @@ External packages installed for runtime use or embedded in distributed Host or b
|
||||
| [`@joplin/turndown-plugin-gfm`](https://github.com/laurent22/joplin-turndown-plugin-gfm) | MIT |
|
||||
| [`@jridgewell/gen-mapping`](https://github.com/jridgewell/sourcemaps) | MIT |
|
||||
| [`@js-temporal/polyfill`](https://github.com/js-temporal/temporal-polyfill) | ISC |
|
||||
| [`@larksuite/cli`](https://github.com/larksuite/cli) | MIT |
|
||||
| [`@lexical/history`](https://github.com/facebook/lexical) | MIT |
|
||||
| [`@lexical/plain-text`](https://github.com/facebook/lexical) | MIT |
|
||||
| [`@lexical/text`](https://github.com/facebook/lexical) | MIT |
|
||||
@@ -69,8 +70,10 @@ External packages installed for runtime use or embedded in distributed Host or b
|
||||
| [`@shikijs/langs`](https://github.com/shikijs/shiki) | MIT |
|
||||
| [`@standard-schema/spec`](https://github.com/standard-schema/standard-schema) | MIT |
|
||||
| [`@tanstack/react-virtual`](https://github.com/TanStack/virtual) | MIT |
|
||||
| [`@tencentcloud/tmeet`](https://github.com/TencentCloud/tencentmeeting-cli) | MIT |
|
||||
| [`@trycua/cua-driver`](https://github.com/trycua/cua) | MIT |
|
||||
| [`@vscode/ripgrep`](https://github.com/microsoft/vscode-ripgrep) | MIT |
|
||||
| [`@wecom/cli`](https://github.com/WecomTeam/wecom-cli) | MIT |
|
||||
| [`@xterm/addon-fit`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit) | MIT |
|
||||
| [`@xterm/addon-serialize`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-serialize) | MIT |
|
||||
| [`@xterm/headless`](https://github.com/xtermjs/xterm.js) | MIT |
|
||||
@@ -314,6 +317,7 @@ The [shared runtime lock](scripts/primary-runtime/lock.json) records each distri
|
||||
| [`openpyxl`](https://foss.heptapod.net/openpyxl/openpyxl) | 3.1.5 | MIT |
|
||||
| [`pandas`](https://github.com/pandas-dev/pandas) | 3.0.1 | BSD-3-Clause |
|
||||
| [`pillow`](https://github.com/python-pillow/Pillow) | 12.3.0 | MIT-CMU |
|
||||
| [`pypdf`](https://github.com/py-pdf/pypdf) | 6.21.4 | BSD-3-Clause |
|
||||
| [`python-dateutil`](https://github.com/dateutil/dateutil) | 2.9.0.post0 | Apache-2.0 OR BSD-3-Clause |
|
||||
| [`python-docx`](https://github.com/python-openxml/python-docx) | 1.2.0 | MIT |
|
||||
| [`python-pptx`](https://github.com/scanny/python-pptx) | 1.0.2 | MIT |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh",
|
||||
"description": "dsh CLI: profile launch, plugin management, and configuration inspection",
|
||||
"version": "0.2.2-rc.4",
|
||||
"version": "0.2.2-rc.5",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -13,9 +13,9 @@ Setup and discovery:
|
||||
- cua.listApps() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp.
|
||||
- cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches.
|
||||
- cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation.
|
||||
- cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, start a stopped application in the background only where the provider supports launch, and return without reading AX or activating the app.
|
||||
- cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, start a stopped application in the background only where the provider supports launch, and return without reading accessibility state or activating the app.
|
||||
- app.getWindows() -> { windowId: string, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership.
|
||||
- app.getWindow(windowId: string) -> Window — select a window by an ID from getWindows without reading AX. Providers reject closed or foreign windows when operating on them.
|
||||
- app.getWindow(windowId: string) -> Window — select a window by an ID from getWindows without reading accessibility state. Providers reject closed or foreign windows when operating on them.
|
||||
- app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required.
|
||||
- app.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation.
|
||||
- window.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation.
|
||||
@@ -23,9 +23,10 @@ Setup and discovery:
|
||||
## Accessibility tree
|
||||
Available at app or window level depending on the platform.
|
||||
|
||||
Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing.
|
||||
Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current accessibility snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing.
|
||||
- getAccessibilityTree(options?: { includeMenus?: boolean, details?: boolean, maxElements?: number, maxDepth?: number }) -> string — set the node count or depth for one read. Omitted limits use the provider settings. includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names.
|
||||
- listActions(elementId: string) -> string[] — list the actions an element advertises.
|
||||
- getActionSchema(action: string) -> JSON Schema — query the parameter schema for an action.
|
||||
- invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none.
|
||||
- performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument.
|
||||
- setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value.
|
||||
@@ -43,7 +44,7 @@ Use an explicit window for pointer input. Before coordinate input, including rel
|
||||
- scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left.
|
||||
- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window.
|
||||
|
||||
A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry.
|
||||
A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current accessibility observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry.
|
||||
|
||||
## Simulated keyboard
|
||||
Available at app or window level depending on the platform.
|
||||
|
||||
@@ -486,6 +486,87 @@ describe('Python SDK dsh profile keyless smoke', () => {
|
||||
}
|
||||
}, 30_000)
|
||||
|
||||
// TZ belongs to the spawned runtime only; GMT makes ICU report "+00:00", which is not a usable zone name.
|
||||
it.each([
|
||||
{ tz: 'America/New_York', sampled: 'Browser time zone for this request: America/New_York. Interpret otherwise-unqualified dates and times in this zone.' },
|
||||
{ tz: 'GMT', sampled: 'Browser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.' },
|
||||
])('shows the model the reported or sampled prompt time zone (TZ=$tz)', async ({ tz, sampled }) => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-sdk-time-zone-'))
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
const modelRequests: string[] = []
|
||||
const modelServer = createServer((request, response) => {
|
||||
let body = ''
|
||||
request.setEncoding('utf8')
|
||||
request.on('data', (chunk: string) => { body += chunk })
|
||||
request.on('end', () => {
|
||||
modelRequests.push(body)
|
||||
response.writeHead(200, { 'content-type': 'text/event-stream' })
|
||||
response.end(messagesResponse({ type: 'text', text: 'done' }, 'end_turn'))
|
||||
})
|
||||
})
|
||||
onTestFinished(() => new Promise<void>((resolve) => { modelServer.close(() => { resolve() }) }))
|
||||
await new Promise<void>(resolve => modelServer.listen(0, '127.0.0.1', resolve))
|
||||
const address = modelServer.address()
|
||||
if (address === null || typeof address === 'string') throw new Error('model server did not bind a TCP port')
|
||||
const child = execa(launch.command, [...launch.args, '--profile', 'sdk'], {
|
||||
cwd: repoRoot,
|
||||
env: {
|
||||
...launch.env,
|
||||
DSH_HOME: join(root, '.dsh'),
|
||||
DSH_TELEMETRY_DISABLED: '1',
|
||||
DEEPSEEK_API_KEY: 'keyless-smoke-no-call',
|
||||
DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`,
|
||||
TZ: tz,
|
||||
},
|
||||
timeout: 35_000,
|
||||
killSignal: 'SIGKILL',
|
||||
reject: false,
|
||||
})
|
||||
onTestFinished(async () => { child.kill('SIGKILL'); await child })
|
||||
const lines: string[] = []
|
||||
let stdoutBuffer = ''
|
||||
let stderr = ''
|
||||
child.stdout.on('data', (chunk: Buffer) => {
|
||||
stdoutBuffer += chunk.toString('utf8')
|
||||
const parts = stdoutBuffer.split('\n')
|
||||
stdoutBuffer = parts.pop() ?? ''
|
||||
lines.push(...parts)
|
||||
})
|
||||
child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })
|
||||
const send = (id: number, method: string, params?: object) => {
|
||||
child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`)
|
||||
return waitForLine(lines, value => value.id === id, () => stderr)
|
||||
}
|
||||
const promptRequest = async (id: number, sessionId: string, timeZone?: string): Promise<string> => {
|
||||
const requests = modelRequests.length
|
||||
expect(await send(id, 'session/prompt', {
|
||||
sessionId, contentBlocks: [{ type: 'text', text: 'When is noon tomorrow?' }], ...timeZone === undefined ? {} : { timeZone },
|
||||
})).toHaveProperty('result.messageId')
|
||||
await waitForLine(lines, (value) => {
|
||||
const params = value.params as { sessionId?: string; event?: { type?: string } } | undefined
|
||||
return value.method === 'session.event' && params?.sessionId === sessionId && params.event?.type === 'turn/end'
|
||||
}, () => stderr)
|
||||
expect(modelRequests).toHaveLength(requests + 1)
|
||||
return modelRequests.at(-1)!
|
||||
}
|
||||
|
||||
await send(1, 'initialize', { cwd: root, provider: 'deepseek-official', model: 'deepseek-v4-pro' })
|
||||
expect(await promptRequest(2, 'explicit', 'US/Eastern')).toContain(
|
||||
'Browser time zone for this request: America/New_York. Interpret otherwise-unqualified dates and times in this zone.',
|
||||
)
|
||||
expect(await promptRequest(3, 'sampled')).toContain(sampled)
|
||||
expect(await send(4, 'session/prompt', {
|
||||
sessionId: 'invalid', contentBlocks: [{ type: 'text', text: 'When is noon?' }], timeZone: 'CST',
|
||||
})).toMatchObject({
|
||||
error: { code: -32603, message: 'timeZone must be UTC or a valid IANA Area/Location name: "CST"' },
|
||||
})
|
||||
expect(modelRequests).toHaveLength(2)
|
||||
|
||||
await send(5, 'shutdown')
|
||||
const exit = await child
|
||||
expect(exit.exitCode, `signal=${String(exit.signal)}; stderr=${stderr}`).toBe(0)
|
||||
}, 40_000)
|
||||
|
||||
it('rejects an invalid max-token success env value', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-python-sdk-runtime-invalid-'))
|
||||
try {
|
||||
@@ -656,3 +737,64 @@ it.each(['unset', 'empty', 'full', 'python-only', 'python-only-patched', 'wrong-
|
||||
expect(exit.exitCode, stderr).toBe(0)
|
||||
await expect(readFile(join(home, 'dsh-runtimes', 'dsh-primary-runtime', 'runtime.json'))).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
})
|
||||
|
||||
it.each(['standard', 'ptc'] as const)('lists and loads the packaged dsh-doc skill through the SDK profile (%s)', async (mode) => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'sdk-dsh-doc-'))
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
const requests: { tools: { name: string }[]; messages: unknown }[] = []
|
||||
const toolUses = mode === 'standard' ? [{ type: 'tool_use', id: 'dsh-doc', name: 'skill', input: { name: 'dsh-doc' } } as const] : []
|
||||
const server = createServer((request, response) => {
|
||||
let body = ''
|
||||
request.setEncoding('utf8').on('data', (chunk: string) => { body += chunk })
|
||||
request.on('end', () => {
|
||||
requests.push(JSON.parse(body) as { tools: { name: string }[]; messages: unknown })
|
||||
const toolUse = toolUses[requests.length - 1]
|
||||
response.writeHead(200, { 'content-type': 'text/event-stream' })
|
||||
response.end(toolUse === undefined ? messagesResponse({ type: 'text', text: 'done' }, 'end_turn') : messagesResponse(toolUse, 'tool_use'))
|
||||
})
|
||||
})
|
||||
onTestFinished(() => new Promise<void>((resolve) => { server.close(() => { resolve() }) }))
|
||||
await new Promise<void>((resolve) => { server.listen(0, '127.0.0.1', resolve) })
|
||||
const address = server.address()
|
||||
if (address === null || typeof address === 'string') throw new Error('model fixture did not bind')
|
||||
const launch = resolveExampleLaunch({
|
||||
srcBin: fileURLToPath(new URL('../../../src/bin.ts', import.meta.url)), mode: 'lib',
|
||||
configArgs: ['--profile', 'sdk', ...mode === 'ptc' ? ['--patch', join(repoRoot, 'apps/cli/config/examples/ptc.yml')] : []],
|
||||
env: { DSH_HOME: join(root, 'home'), DSH_PRIMARY_RUNTIME: '', DSH_PERMISSION_MODE: 'danger-full-access', DSH_TELEMETRY_DISABLED: '1',
|
||||
DEEPSEEK_API_KEY: 'local-fixture', DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}` },
|
||||
})
|
||||
const child = execa(launch.command, launch.args, { cwd: repoRoot, env: launch.env, timeout: 60_000, reject: false })
|
||||
onTestFinished(async () => { child.kill('SIGKILL'); await child })
|
||||
let buffer = '', stderr = ''
|
||||
const lines: string[] = []
|
||||
child.stdout.on('data', (chunk: Buffer) => {
|
||||
buffer += chunk.toString()
|
||||
const parts = buffer.split('\n')
|
||||
buffer = parts.pop() ?? ''
|
||||
lines.push(...parts)
|
||||
})
|
||||
child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
|
||||
const send = (id: number, method: string, params?: object) => {
|
||||
child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`)
|
||||
return waitForLine(lines, value => value.id === id, () => stderr)
|
||||
}
|
||||
expect(await send(1, 'initialize', { cwd: root, provider: 'deepseek-official', model: 'deepseek-v4-pro' })).toHaveProperty('result')
|
||||
await send(2, 'session/prompt', { sessionId: 'dsh-doc', contentBlocks: [{ type: 'text', text: 'How do DSH presets work?' }] })
|
||||
await waitForLine(lines, (value) => {
|
||||
const params = value.params as { sessionId?: string; event?: { type?: string } } | undefined
|
||||
return value.method === 'session.event' && params?.sessionId === 'dsh-doc' && params.event?.type === 'turn/end'
|
||||
}, () => stderr)
|
||||
expect(requests).toHaveLength(toolUses.length + 1)
|
||||
expect(JSON.stringify(requests[0]!.messages)).toMatch(/- `dsh-doc`: Use when a task needs facts about DeepSeek Harness/)
|
||||
if (mode === 'ptc') expect(requests[0]!.tools.map(tool => tool.name)).toEqual(['run_code'])
|
||||
else {
|
||||
const messages = requests[1]!.messages as { content: { tool_use_id?: string }[] }[]
|
||||
const loaded = JSON.stringify(messages.flatMap(message => message.content).find(block => block.tool_use_id === 'dsh-doc'))
|
||||
const directory = join(repoRoot, 'packages/preset/agent-preset/skills/dsh-doc').split(sep).join('/')
|
||||
expect(loaded).toContain(JSON.stringify(`Base directory for this skill: ${directory}`).slice(1, -1))
|
||||
expect(loaded).toContain('# DeepSeek Harness documentation')
|
||||
}
|
||||
await send(3, 'shutdown')
|
||||
const exit = await child
|
||||
expect(exit.exitCode, stderr).toBe(0)
|
||||
})
|
||||
@@ -995,6 +995,11 @@ describe('the standard preset documentation skill', () => {
|
||||
setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'cordis').then(() => undefined),
|
||||
})
|
||||
expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: creator.agent }))?.path).toBe(definition.path)
|
||||
const ptc = await testCtx.agents.create({
|
||||
sessionId: brandString<SessionId>('standard-doc-ptc'), meta: { cwd: root },
|
||||
setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'ptc').then(() => undefined),
|
||||
})
|
||||
expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: ptc.agent }))?.path).toBe(definition.path)
|
||||
const schemas = testCtx.tools.schemas(standardAgent.agent)
|
||||
expect(schemas).toEqual(testCtx.tools.schemas(baseline.agent))
|
||||
expect(schemas.map(tool => tool.name)).toContain('cordis_inspect')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-desktop-host",
|
||||
"description": "Private Node-mode host process for the Electron desktop application",
|
||||
"version": "0.2.2-rc.4",
|
||||
"version": "0.2.2-rc.5",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-desktop-publisher",
|
||||
"version": "0.2.2-rc.4",
|
||||
"version": "0.2.2-rc.5",
|
||||
"description": "Private Desktop release metadata, rollout and website publisher",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -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: 3a70021830865253
|
||||
zh: 0467be8b505446cb
|
||||
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>
|
||||
|
||||
@@ -261,15 +261,15 @@ During a confirmed Windows update restart, a separate process displays a draggab
|
||||
|
||||
The Windows installer uses native NSIS pages with light and dark palettes, system shadows, an editable installation directory, and a finish page whose launch checkbox is selected by default. Installation is restricted to the current user. Clicking Install or pressing Enter validates the current path; drive roots remain invalid after normalization, including repeated trailing separators. New destinations must be empty, and nonempty destinations must be registered installations. Running executables at the affected installation path produce a native prompt and remain running; same-named applications in other directories do not block installation. Silent updates wait up to ten seconds for the affected application to exit, then stop with exit code 2 if it is still running.
|
||||
|
||||
The theme follows Windows at startup; `/THEME=light`, `/THEME=dark`, and `/THEME=auto` select a palette explicitly. The window appears after its branded controls are ready. When the welcome page first appears, the installer moves above ordinary windows once and flashes its taskbar button if another window has focus; it does not remain always on top. Progress reads the pinned 7-Zip extractor’s percentage; directory promotion, registration, and cleanup retain bounded estimates. The weighted percentage does not predict remaining time. After NSIS reports success, the bar fills over 600 ms and displays 100% briefly before the finish page appears; the transition targets 750 ms. The finish page preserves the window position. Finish dismisses the installer before launching the installed executable; a launch failure restores the page for retry. Directory replacement and failure recovery follow the [installation checks](packaging/README.md#runtime-file-selection). First-launch profile preparation remains a separate Desktop operation.
|
||||
The theme follows Windows at startup; `/THEME=light`, `/THEME=dark`, and `/THEME=auto` select a palette explicitly. The window appears after its branded controls are ready. When the welcome page first appears, the installer moves above ordinary windows once and flashes its taskbar button if another window has focus; it does not remain always on top. Progress reads the pinned 7-Zip extractor’s percentage; directory promotion, registration, and cleanup retain bounded estimates. The weighted percentage does not predict remaining time. After NSIS reports success, the bar fills over 600 ms and displays 100% briefly before the finish page appears; the transition targets 750 ms. Finish controls appear in the existing progress window while a title-bar drag or system menu remains active. Completion flashes the taskbar button three times if the installer is minimized or another window has focus. During installation, the Close button is disabled and dimmed without changing the cursor. On the finish page, Close exits without launching the application. Finish dismisses the installer before launching the installed executable; a launch failure restores the page for retry. Directory replacement and failure recovery follow the [installation checks](packaging/README.md#runtime-file-selection). First-launch profile preparation remains a separate Desktop operation.
|
||||
|
||||
Windows packaging compiles an x86 Win32/GDI+ helper with Visual C++ Build Tools and a Windows SDK; signed builds sign this helper through the configured Windows signer. The progress page keeps one opaque pixel buffer for its lifetime, draws static artwork once, and copies repainted pixels with GDI. The preparation hook leaves production dependency collection to electron-builder on every platform.
|
||||
|
||||
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>
|
||||
|
||||
@@ -261,15 +261,15 @@ Windows 更新确认重启后,独立进程显示可拖动的状态提示,直
|
||||
|
||||
Windows 安装程序使用原生 NSIS 页面,提供亮暗配色、系统阴影、可编辑的安装目录,以及默认勾选立即启动的完成页。安装仅面向当前用户。点击安装或按 Enter 均校验当前路径;路径规范化后仍拒绝磁盘根目录,包括带重复末尾分隔符的写法。新安装位置必须为空,非空位置必须是已登记的安装目录。受影响安装路径中的程序运行时显示系统提示,并保持应用运行;其他目录中的同名应用不阻止安装。静默更新最多等待受影响应用退出十秒,若仍在运行则以退出码 2 结束。
|
||||
|
||||
主题在启动时跟随 Windows;可用 `/THEME=light`、`/THEME=dark` 和 `/THEME=auto` 显式选择配色。窗口在品牌控件准备完成后显示。欢迎页首次出现时,安装窗口会一次性移到普通窗口前方;若焦点在其他窗口,任务栏按钮会闪烁提示,但安装窗口不会始终置顶。进度读取锁定版本的 7-Zip 解压器百分比;目录替换、注册和清理仍使用有界估算。加权百分比不代表剩余时间。NSIS 报告成功后,进度条用 600 毫秒补满并短暂显示 100%,再显示完成页;切换目标时长为 750 毫秒。完成页保留窗口位置。点击完成后,安装程序先隐藏窗口,再启动已安装的可执行文件;启动失败会恢复页面以供重试。目录替换和失败恢复遵循[安装检查](packaging/README.zh.md#runtime-file-selection)。首次启动的配置档案准备仍属于独立的 Desktop 操作。
|
||||
主题在启动时跟随 Windows;可用 `/THEME=light`、`/THEME=dark` 和 `/THEME=auto` 显式选择配色。窗口在品牌控件准备完成后显示。欢迎页首次出现时,安装窗口会一次性移到普通窗口前方;若焦点在其他窗口,任务栏按钮会闪烁提示,但安装窗口不会始终置顶。进度读取锁定版本的 7-Zip 解压器百分比;目录替换、注册和清理仍使用有界估算。加权百分比不代表剩余时间。NSIS 报告成功后,进度条用 600 毫秒补满并短暂显示 100%,再显示完成页;切换目标时长为 750 毫秒。完成按钮与启动复选框在原进度窗口中显示,拖动标题栏或打开系统菜单时也会更新。若安装器已最小化或焦点在其他窗口,安装完成时任务栏按钮会闪烁三次。安装中关闭按钮禁用并变灰,鼠标指针保持不变;完成页的关闭按钮退出安装器且不启动应用。点击完成后,安装程序先隐藏窗口,再启动已安装的可执行文件;启动失败会恢复页面以供重试。目录替换和失败恢复遵循[安装检查](packaging/README.zh.md#runtime-file-selection)。首次启动的配置档案准备仍属于独立的 Desktop 操作。
|
||||
|
||||
Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI+ 辅助库;签名构建通过已配置的 Windows 签名器对该库签名。进度页在其生命周期内保留一个不透明像素缓冲,只绘制一次静态图像,并通过 GDI 复制重绘的像素。准备钩子在所有平台上均由 electron-builder 继续负责收集生产依赖。
|
||||
|
||||
在有交互式桌面的 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>
|
||||
|
||||
|
||||
@@ -24,5 +24,5 @@
|
||||
en: f1c19c1516a51ab6
|
||||
zh: b350f7c18086d274
|
||||
/desktop-recovery-and-diagnostics/collection-and-shutdown:
|
||||
en: bac4a49f63d4aaf8
|
||||
zh: df1ae908ee2148e1
|
||||
en: 67555a4116943e85
|
||||
zh: 451231cb6e28ffe9
|
||||
@@ -67,6 +67,8 @@ The Host announces its run ID before profile loading; reported Host errors carry
|
||||
|
||||
Collection reads only two owned files under `userData/plugin-operations`, at most 64 KiB and 100 records; the complete appended section is limited to 64 KiB.
|
||||
|
||||
Only a predecessor whose handle reports the exact bigint file identity of the segment already read is deduplicated as already collected: the predecessor is skipped, so its records are not collected twice, and records appended to it after it was read are not collected. On Windows, opening a segment retries `EACCES`, `EBUSY` and `EPERM` up to four times with a 10→40 ms backoff before the segment counts as unavailable, cancellation ends those retries, and `filesRead` counts owned segments that yielded bytes.
|
||||
|
||||
The 500 ms collection budget reserves its final 100 ms for cooperative cancellation before requesting forced Worker termination; completion waits for its exit. Application exit, recovery exit or restart, and confirmed update installation also cancel collection and wait at most 500 ms for Worker exit. A rejected shutdown cleanup is logged without skipping the remaining cleanup waits. Shutdown prevents late basic-report saves from starting another collector. An update installation failure permits future collection again.
|
||||
|
||||
Worker messages interrupt collection between bounded records; an in-flight file open, stat, read or close must settle, and synchronous parsing cannot be preempted within one record. The final append uses an abort signal but can leave partial bytes. Forced termination remains the fallback when cooperative cleanup does not finish.
|
||||
|
||||
@@ -67,6 +67,8 @@ Host 在加载 profile 前报告运行 ID;Host 错误中的 `hostRunId` 与该
|
||||
|
||||
收集只读取 `userData/plugin-operations` 下归其管理的两个文件,最多读取 64 KiB 和 100 条记录;完整追加内容不超过 64 KiB。
|
||||
|
||||
只有前驱段的句柄给出与已读段完全相同的 bigint 文件身份时才判为已收集:该前驱段会被跳过,因此它的记录不会被重复收集,但在被读取之后追加到它的记录不会被收集。Windows 上打开文件段遇到 `EACCES`、`EBUSY`、`EPERM` 时最多重试四次,退避 10→40 ms,之后该段才计入不可用;取消会结束这些重试;`filesRead` 统计实际读到字节的所属文件段。
|
||||
|
||||
500 ms 收集预算中的最后 100 ms 用于协作取消,随后才请求强制终止 Worker;只有 Worker 退出后才确认收集结束。应用退出、恢复退出或重启、确认安装更新也会取消收集,并最多等待 500 ms 确认 Worker 退出。退出清理中的拒绝会被记录,但不会跳过其他清理等待。退出过程中,延迟保存完成的基本报告不会再启动收集器。更新安装失败后可再次收集。
|
||||
|
||||
Worker 在有界记录之间处理取消消息;已经发出的文件打开、状态读取、读取或关闭操作必须等待完成,单条记录的同步解析不能被抢占。最后的追加写入传入取消信号,但仍可能留下部分字节。协作清理未及时完成时仍需强制终止。
|
||||
|
||||
@@ -43,78 +43,3 @@ Function InstallerDrawEditFrame
|
||||
System::Call 'gdiplus::GdipDeleteGraphics(p R4)'
|
||||
System::Call 'gdiplus::GdipDisposeImage(p R5)'
|
||||
FunctionEnd
|
||||
|
||||
; BS_AUTOCHECKBOX retains its native state, text, keyboard and accessibility role.
|
||||
Function InstallerPaintCheckbox
|
||||
Pop $R0
|
||||
Pop $R1
|
||||
Pop $R2
|
||||
${If} $R1 != -12
|
||||
Return
|
||||
${EndIf}
|
||||
System::Call '*$R2(p, p, i, i .R3, p .R4, i, i, i, i, p, i .R9)'
|
||||
${If} $R3 != 1
|
||||
Return
|
||||
${EndIf}
|
||||
System::Call 'gdi32::SaveDC(p R4)'
|
||||
System::Alloc 16
|
||||
Pop $R2
|
||||
System::Call 'user32::GetClientRect(p R0, p R2)'
|
||||
System::Call 'gdi32::CreateSolidBrush(i $InstallerBgColorref) p.R3'
|
||||
System::Call 'user32::FillRect(p R4, p R2, p R3)'
|
||||
System::Call 'gdi32::DeleteObject(p R3)'
|
||||
System::Call 'kernel32::MulDiv(i 8, i $InstallerDpi, i 96) i.r2'
|
||||
System::Call 'kernel32::MulDiv(i 7, i $InstallerDpi, i 96) i.r3'
|
||||
System::Call 'gdi32::SetViewportOrgEx(p R4, i r2, i r3, p 0)'
|
||||
System::Call 'gdiplus::GdipCreateFromHDC(p R4, *p .R5)'
|
||||
System::Call 'gdiplus::GdipSetSmoothingMode(p R5, i 4)'
|
||||
System::Call 'kernel32::MulDiv(i 18, i $InstallerDpi, i 96) i.R7'
|
||||
StrCpy $R8 $R7
|
||||
System::Call 'kernel32::MulDiv(i 6, i $InstallerDpi, i 96) i.R3'
|
||||
!insertmacro InstallerRoundPath $R6 $R7 $R8 $R3
|
||||
${NSD_GetState} $R0 $R8
|
||||
StrCpy $R3 $InstallerBgArgb
|
||||
${If} $R8 == ${BST_CHECKED}
|
||||
StrCpy $R3 $InstallerPrimary
|
||||
${EndIf}
|
||||
System::Call 'gdiplus::GdipCreateSolidFill(i R3, *p .R1)'
|
||||
System::Call 'gdiplus::GdipFillPath(p R5, p R1, p R6)'
|
||||
System::Call 'gdiplus::GdipDeleteBrush(p R1)'
|
||||
${If} $R8 != ${BST_CHECKED}
|
||||
System::Call 'gdiplus::GdipCreatePen1(i $InstallerBorder, i 0x40000000, i 2, *p .R1)'
|
||||
System::Call 'gdiplus::GdipDrawPath(p R5, p R1, p R6)'
|
||||
System::Call 'gdiplus::GdipDeletePen(p R1)'
|
||||
${EndIf}
|
||||
System::Call 'gdiplus::GdipDeletePath(p R6)'
|
||||
System::Call 'gdiplus::GdipDeleteGraphics(p R5)'
|
||||
${If} $R8 == ${BST_CHECKED}
|
||||
System::Call 'kernel32::MulDiv(i 2, i $InstallerDpi, i 96) i.r0'
|
||||
System::Call 'gdi32::CreatePen(i 0, i r0, i $InstallerButtonText) p.R1'
|
||||
System::Call 'gdi32::SelectObject(p R4, p R1) p.R3'
|
||||
System::Call 'kernel32::MulDiv(i 4, i $InstallerDpi, i 96) i.r0'
|
||||
System::Call 'kernel32::MulDiv(i 9, i $InstallerDpi, i 96) i.r1'
|
||||
System::Call 'gdi32::MoveToEx(p R4, i r0, i r1, p 0)'
|
||||
System::Call 'kernel32::MulDiv(i 8, i $InstallerDpi, i 96) i.r0'
|
||||
System::Call 'kernel32::MulDiv(i 13, i $InstallerDpi, i 96) i.r1'
|
||||
System::Call 'gdi32::LineTo(p R4, i r0, i r1)'
|
||||
System::Call 'kernel32::MulDiv(i 14, i $InstallerDpi, i 96) i.r0'
|
||||
System::Call 'kernel32::MulDiv(i 5, i $InstallerDpi, i 96) i.r1'
|
||||
System::Call 'gdi32::LineTo(p R4, i r0, i r1)'
|
||||
System::Call 'gdi32::SelectObject(p R4, p R3)'
|
||||
System::Call 'gdi32::DeleteObject(p R1)'
|
||||
${EndIf}
|
||||
System::Call 'gdi32::SetViewportOrgEx(p R4, i 0, i 0, p 0)'
|
||||
System::Call 'kernel32::MulDiv(i 34, i $InstallerDpi, i 96) i.r0'
|
||||
System::Call '*$R2(i r0)'
|
||||
System::Call 'gdi32::SetBkMode(p R4, i 1)'
|
||||
System::Call 'gdi32::SetTextColor(p R4, i $InstallerTextColorref)'
|
||||
System::Call 'gdi32::SelectObject(p R4, p $InstallerSmallFont)'
|
||||
System::Call 'user32::DrawTextW(p R4, w "$(INSTALLER_LAUNCH)", i -1, p R2, i 0x24)'
|
||||
IntOp $R9 $R9 & 16
|
||||
${If} $R9 != 0
|
||||
System::Call 'user32::DrawFocusRect(p R4, p R2)'
|
||||
${EndIf}
|
||||
System::Call 'gdi32::RestoreDC(p R4, i -1)'
|
||||
System::Free $R2
|
||||
${NSD_Return} 4
|
||||
FunctionEnd
|
||||
@@ -54,6 +54,7 @@ Function InstallerBeforeInstall
|
||||
FunctionEnd
|
||||
|
||||
Function InstallerProgressShow
|
||||
StrCpy $InstallerPhase "installing"
|
||||
; Only the stock worker executes installation; this overlay runs on the UI thread.
|
||||
ShowWindow $mui.InstFilesPage 0
|
||||
StrCpy $0 0
|
||||
@@ -79,12 +80,24 @@ Function .onInstFailed
|
||||
Quit
|
||||
FunctionEnd
|
||||
|
||||
Function InstallerFinish
|
||||
System::Call '$PLUGINSDIR\window-frame.dll::InstallerFinishProgress(p $InstallerProgressWindow) i.r0 ?c'
|
||||
${If} $0 == 0
|
||||
Quit
|
||||
Function InstallerProgressLeave
|
||||
IfAbort failed
|
||||
${If} $InstallerPhase == "installing"
|
||||
System::Call '$PLUGINSDIR\window-frame.dll::InstallerFinishProgress(p $InstallerProgressWindow, w "$(INSTALLER_FINISH)", w "$(INSTALLER_LAUNCH)") i.r0 ?c'
|
||||
${If} $0 == 0
|
||||
MessageBox MB_OK|MB_ICONSTOP "$(INSTALLER_UI_ERROR)"
|
||||
SetErrorLevel 2
|
||||
Quit
|
||||
${EndIf}
|
||||
StrCpy $InstallerPhase "success"
|
||||
Abort
|
||||
${EndIf}
|
||||
System::Call 'user32::DestroyWindow(p $InstallerProgressWindow)'
|
||||
StrCpy $InstallerPhase "success"
|
||||
Call InstallerCreate
|
||||
System::Call '$PLUGINSDIR\window-frame.dll::InstallerTakeFinishChoice(p $InstallerProgressWindow) i.r0 ?c'
|
||||
${If} $0 < 0
|
||||
Abort
|
||||
${EndIf}
|
||||
Call InstallerFinishLeave
|
||||
Return
|
||||
failed:
|
||||
; NSIS owns installation failure and its exit code.
|
||||
FunctionEnd
|
||||
@@ -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": "欢迎",
|
||||
|
||||
@@ -16,7 +16,6 @@ Var InstallerChoose
|
||||
Var InstallerEdit
|
||||
Var InstallerEditFrame
|
||||
Var InstallerBrowse
|
||||
Var InstallerLaunch
|
||||
Var InstallerExpanded
|
||||
Var InstallerMinimizeButton
|
||||
Var InstallerCloseButton
|
||||
@@ -137,30 +136,6 @@ Function InstallerCreate
|
||||
!insertmacro InstallerPlace $InstallerBrowse 456 434 80 34
|
||||
${NSD_OnClick} $InstallerBrowse InstallerBrowsePath
|
||||
${NSD_OnNotify} $InstallerBrowse InstallerPaintButton
|
||||
${NSD_CreateCheckbox} 0 0 0 0 "$(INSTALLER_LAUNCH)"
|
||||
Pop $InstallerLaunch
|
||||
SendMessage $InstallerLaunch ${WM_SETFONT} $InstallerSmallFont 1
|
||||
System::Call 'user32::GetDC(p $InstallerLaunch) p.r4'
|
||||
System::Call 'gdi32::SelectObject(p r4, p $InstallerSmallFont) p.r5'
|
||||
StrLen $0 "$(INSTALLER_LAUNCH)"
|
||||
System::Alloc 8
|
||||
Pop $6
|
||||
System::Call 'gdi32::GetTextExtentPoint32W(p r4, w "$(INSTALLER_LAUNCH)", i r0, p r6)'
|
||||
System::Call '*$6(i .r7)'
|
||||
System::Free $6
|
||||
System::Call 'gdi32::SelectObject(p r4, p r5)'
|
||||
System::Call 'user32::ReleaseDC(p $InstallerLaunch, p r4)'
|
||||
System::Call 'kernel32::MulDiv(i 42, i $InstallerDpi, i 96) i.r2'
|
||||
IntOp $2 $2 + $7
|
||||
IntOp $0 $InstallerSize - $2
|
||||
IntOp $0 $0 / 2
|
||||
System::Call 'kernel32::MulDiv(i 438, i $InstallerDpi, i 96) i.r1'
|
||||
System::Call 'kernel32::MulDiv(i 32, i $InstallerDpi, i 96) i.r3'
|
||||
System::Call 'user32::MoveWindow(p $InstallerLaunch, i r0, i r1, i r2, i r3, i 1)'
|
||||
!insertmacro InstallerControlColors $InstallerLaunch
|
||||
${NSD_OnNotify} $InstallerLaunch InstallerPaintCheckbox
|
||||
${NSD_Check} $InstallerLaunch
|
||||
|
||||
${NSD_CreateButton} 0 0 0 0 "$(INSTALLER_INSTALL)"
|
||||
Pop $InstallerButton
|
||||
!insertmacro InstallerPlace $InstallerButton ${INSTALLER_BUTTON_X} ${INSTALLER_BUTTON_Y} ${INSTALLER_BUTTON_WIDTH} ${INSTALLER_BUTTON_HEIGHT}
|
||||
@@ -188,20 +163,13 @@ Function InstallerRender
|
||||
ShowWindow $InstallerEdit 0
|
||||
ShowWindow $InstallerEditFrame 0
|
||||
ShowWindow $InstallerBrowse 0
|
||||
ShowWindow $InstallerLaunch 0
|
||||
ShowWindow $InstallerStatus 0
|
||||
${If} $InstallerPhase == "success"
|
||||
${NSD_SetText} $InstallerButton "$(INSTALLER_FINISH)"
|
||||
ShowWindow $InstallerLaunch 5
|
||||
${If} $InstallerExpanded == 1
|
||||
ShowWindow $InstallerEditFrame 5
|
||||
ShowWindow $InstallerEdit 5
|
||||
ShowWindow $InstallerBrowse 5
|
||||
${Else}
|
||||
${NSD_SetText} $InstallerButton "$(INSTALLER_INSTALL)"
|
||||
${If} $InstallerExpanded == 1
|
||||
ShowWindow $InstallerEditFrame 5
|
||||
ShowWindow $InstallerEdit 5
|
||||
ShowWindow $InstallerBrowse 5
|
||||
${Else}
|
||||
ShowWindow $InstallerChoose 5
|
||||
${EndIf}
|
||||
ShowWindow $InstallerChoose 5
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
@@ -220,8 +188,8 @@ Function InstallerWelcomeLeave
|
||||
${EndIf}
|
||||
FunctionEnd
|
||||
|
||||
; The completed page requests exit with the user's launch choice in $0.
|
||||
Function InstallerFinishLeave
|
||||
${NSD_GetState} $InstallerLaunch $0
|
||||
HideWindow
|
||||
${If} $0 == ${BST_CHECKED}
|
||||
StrCpy $0 ""
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -140,8 +141,14 @@ struct ProgressPage {
|
||||
ARGB controlHover;
|
||||
ARGB controlPressed;
|
||||
WCHAR captions[5][128];
|
||||
HWND finish, launch, minimize, close;
|
||||
bool controlsVisible = false;
|
||||
int finishChoice = -1;
|
||||
HFONT finishFont, launchFont;
|
||||
|
||||
~ProgressPage() {
|
||||
if (finishFont) DeleteObject(finishFont);
|
||||
if (launchFont) DeleteObject(launchFont);
|
||||
delete buffer;
|
||||
delete brand;
|
||||
if (previousBitmap) SelectObject(bufferDc, previousBitmap);
|
||||
@@ -178,13 +185,16 @@ static UINT CaptionCommand(const ProgressPage& page, LPARAM position) {
|
||||
const int x = static_cast<short>(LOWORD(position));
|
||||
const int y = static_cast<short>(HIWORD(position));
|
||||
if (y < 0 || y >= MulDiv(48, page.dpi, 96) || x < MulDiv(504, page.dpi, 96) || x >= MulDiv(600, page.dpi, 96)) return 0;
|
||||
return x >= MulDiv(548, page.dpi, 96) ? SC_CLOSE : SC_MINIMIZE;
|
||||
// Installation cannot be cancelled with the progress page close button.
|
||||
return x >= MulDiv(548, page.dpi, 96) ? 0 : SC_MINIMIZE;
|
||||
}
|
||||
|
||||
static void PaintCaptionButtons(Graphics& graphics, const ProgressPage& page) {
|
||||
SolidBrush background(page.dark ? Color(255, 21, 21, 23) : Color(255, 255, 255, 255));
|
||||
graphics.FillRectangle(&background, 504, 0, 96, 48);
|
||||
SolidBrush ink(page.dark ? Color(255, 255, 255, 255) : Color(255, 15, 17, 21));
|
||||
// Disabled caption uses the same foreground with reduced opacity in both themes.
|
||||
SolidBrush disabledInk(page.dark ? Color(96, 255, 255, 255) : Color(96, 15, 17, 21));
|
||||
FontFamily family(L"Microsoft YaHei UI");
|
||||
Font font(&family, 16, FontStyleRegular, UnitPixel);
|
||||
StringFormat centered;
|
||||
@@ -204,7 +214,7 @@ static void PaintCaptionButtons(Graphics& graphics, const ProgressPage& page) {
|
||||
graphics.FillPath(&fill, &path);
|
||||
}
|
||||
graphics.DrawString(command == SC_MINIMIZE ? L"\x2212" : L"\x00d7", -1,
|
||||
&font, RectF(static_cast<REAL>(x), 8, 40, 32), ¢ered, &ink);
|
||||
&font, RectF(static_cast<REAL>(x), 8, 40, 32), ¢ered, command == SC_CLOSE ? &disabledInk : &ink);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,15 +223,109 @@ static void InvalidateCaptionButtons(HWND window, const ProgressPage& page) {
|
||||
InvalidateRect(window, &bounds, FALSE);
|
||||
}
|
||||
|
||||
// NSIS ui.h: request that the stock instfiles page run its leave callback.
|
||||
constexpr UINT WM_NOTIFY_OUTER_NEXT = WM_USER + 8;
|
||||
|
||||
static void RequestFinish(HWND window, ProgressPage& page, bool launch) {
|
||||
if (!page.controlsVisible || page.finishChoice >= 0) return;
|
||||
if (PostMessageW(GetParent(window), WM_NOTIFY_OUTER_NEXT, 1, 0)) page.finishChoice = launch ? 1 : 0;
|
||||
}
|
||||
|
||||
static void RevealFinish(HWND window, ProgressPage& page) {
|
||||
page.controlsVisible = true;
|
||||
KillTimer(window, 1);
|
||||
SetWindowTextW(window, L"");
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
for (HWND child : {page.finish, page.launch, page.minimize, page.close}) ShowWindow(child, SW_SHOWNA);
|
||||
HWND frame = GetParent(window);
|
||||
if (GetForegroundWindow() != frame || IsIconic(frame)) {
|
||||
FLASHWINFO flash = {sizeof(flash), frame, FLASHW_TRAY, 3, 0};
|
||||
FlashWindowEx(&flash);
|
||||
}
|
||||
}
|
||||
|
||||
static LRESULT DrawFinishControl(const ProgressPage& page, NMCUSTOMDRAW& draw) {
|
||||
if (draw.dwDrawStage != CDDS_PREPAINT) return CDRF_DODEFAULT;
|
||||
const HWND control = draw.hdr.hwndFrom;
|
||||
const bool primary = control == page.finish;
|
||||
const bool checkbox = control == page.launch;
|
||||
const bool pressed = (draw.uItemState & CDIS_SELECTED) != 0;
|
||||
const bool hot = (draw.uItemState & CDIS_HOT) != 0;
|
||||
const Color background = page.dark ? Color(255,21,21,23) : Color(255,255,255,255);
|
||||
const Color foreground = page.dark ? Color(255,255,255,255) : Color(255,15,17,21);
|
||||
const Color accent = page.dark ? Color(255,249,250,251) : Color(255,15,17,21);
|
||||
const Color inverse = page.dark ? Color(255,15,17,21) : Color(255,255,255,255);
|
||||
RECT rect; GetClientRect(control, &rect);
|
||||
HDC dc = draw.hdc;
|
||||
const int saved = SaveDC(dc);
|
||||
{
|
||||
Graphics graphics(dc);
|
||||
graphics.ScaleTransform(page.dpi / 96.0f, page.dpi / 96.0f);
|
||||
graphics.SetSmoothingMode(SmoothingModeAntiAlias);
|
||||
graphics.Clear(background);
|
||||
const bool checked = checkbox && SendMessageW(control, BM_GETCHECK, 0, 0) == BST_CHECKED;
|
||||
Color fill = primary ? accent : background;
|
||||
if (primary && (hot || pressed)) {
|
||||
fill = page.dark ? (pressed ? Color(255,212,219,233) : Color(255,233,236,242))
|
||||
: (pressed ? Color(255,0,0,0) : Color(255,45,49,53));
|
||||
} else if (checkbox) {
|
||||
fill = checked ? accent : background;
|
||||
} else if (hot || pressed) {
|
||||
fill = Color(pressed ? page.controlPressed : page.controlHover);
|
||||
}
|
||||
const REAL x = checkbox ? 8.0f : 0.0f, y = checkbox ? 7.0f : 0.0f;
|
||||
const REAL w = checkbox ? 18.0f : rect.right * 96.0f / page.dpi;
|
||||
const REAL h = checkbox ? 18.0f : rect.bottom * 96.0f / page.dpi;
|
||||
const REAL d = checkbox ? 6.0f : 20.0f;
|
||||
GraphicsPath path;
|
||||
path.AddArc(x,y,d,d,180,90); path.AddArc(x+w-d,y,d,d,270,90);
|
||||
path.AddArc(x+w-d,y+h-d,d,d,0,90); path.AddArc(x,y+h-d,d,d,90,90); path.CloseFigure();
|
||||
SolidBrush brush(fill); graphics.FillPath(&brush,&path);
|
||||
if (checkbox && !checked) {
|
||||
Pen border(page.dark ? Color(255,97,102,107) : Color(255,187,192,200)); graphics.DrawPath(&border,&path);
|
||||
} else if (checked) {
|
||||
Pen pen(inverse,2.0f); Point points[] = {{12,16},{16,20},{22,12}};
|
||||
graphics.DrawLines(&pen,points,3);
|
||||
}
|
||||
}
|
||||
WCHAR caption[256]; GetWindowTextW(control,caption,ARRAYSIZE(caption));
|
||||
const Color text = primary ? inverse : foreground;
|
||||
SetTextColor(dc,RGB(text.GetR(),text.GetG(),text.GetB())); SetBkMode(dc,TRANSPARENT);
|
||||
SelectObject(dc,checkbox ? page.launchFont : page.finishFont);
|
||||
if (checkbox) rect.left += MulDiv(34,page.dpi,96);
|
||||
DrawTextW(dc,caption,-1,&rect,DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX | (checkbox ? DT_LEFT : DT_CENTER));
|
||||
if (draw.uItemState & CDIS_FOCUS) { InflateRect(&rect,-3,-3); DrawFocusRect(dc,&rect); }
|
||||
RestoreDC(dc,saved);
|
||||
return CDRF_SKIPDEFAULT;
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK ProgressProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
auto* page = reinterpret_cast<ProgressPage*>(GetWindowLongPtrW(window, GWLP_USERDATA));
|
||||
if (message == WM_CREATE) {
|
||||
page = static_cast<ProgressPage*>(reinterpret_cast<CREATESTRUCTW*>(lparam)->lpCreateParams);
|
||||
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(page));
|
||||
SetTimer(window, 1, 16, nullptr);
|
||||
}
|
||||
if (message == WM_ERASEBKGND) return 1;
|
||||
if (message == WM_TIMER) { InvalidateRect(window, nullptr, FALSE); return 0; }
|
||||
if (message == WM_TIMER && page && wparam == 1) {
|
||||
if (page->controlsVisible) return 0;
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
if (page->progress.succeeded && GetTickCount64() - page->progress.animationStarted >= 750) {
|
||||
// A covered window may not have painted its final frame on the last tick.
|
||||
UpdateWindow(window);
|
||||
RevealFinish(window, *page);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if (message == WM_NOTIFY && page && reinterpret_cast<NMHDR*>(lparam)->code == NM_CUSTOMDRAW) {
|
||||
return DrawFinishControl(*page, *reinterpret_cast<NMCUSTOMDRAW*>(lparam));
|
||||
}
|
||||
if (message == WM_COMMAND && page && page->controlsVisible && HIWORD(wparam) == BN_CLICKED) {
|
||||
HWND control = reinterpret_cast<HWND>(lparam);
|
||||
if (control == page->finish || control == page->close) {
|
||||
RequestFinish(window, *page, control == page->finish && SendMessageW(page->launch, BM_GETCHECK, 0, 0) == BST_CHECKED);
|
||||
} else if (control == page->minimize) ShowWindow(GetParent(window), SW_MINIMIZE);
|
||||
return 0;
|
||||
}
|
||||
if (message == WM_MOUSEMOVE && page) {
|
||||
TRACKMOUSEEVENT tracking{sizeof(tracking), TME_LEAVE, window, 0};
|
||||
TrackMouseEvent(&tracking);
|
||||
@@ -259,10 +363,7 @@ static LRESULT CALLBACK ProgressProc(HWND window, UINT message, WPARAM wparam, L
|
||||
InvalidateCaptionButtons(window, *page);
|
||||
const bool activate = command && GetCapture() == window && CaptionCommand(*page, lparam) == command;
|
||||
if (GetCapture() == window) ReleaseCapture();
|
||||
if (activate) {
|
||||
if (command == SC_CLOSE) PostMessageW(GetParent(window), WM_CLOSE, 0, 0);
|
||||
else ShowWindow(GetParent(window), SW_MINIMIZE);
|
||||
}
|
||||
if (activate) ShowWindow(GetParent(window), SW_MINIMIZE);
|
||||
return 0;
|
||||
}
|
||||
if ((message == WM_CAPTURECHANGED || message == WM_CANCELMODE) && page) {
|
||||
@@ -284,23 +385,25 @@ static LRESULT CALLBACK ProgressProc(HWND window, UINT message, WPARAM wparam, L
|
||||
PaintCaptionButtons(graphics, *page);
|
||||
SolidBrush background(page->dark ? Color(255, 21, 21, 23) : Color(255, 255, 255, 255));
|
||||
graphics.FillRectangle(&background, 48, 480, 504, 56);
|
||||
const int stage = static_cast<int>(reinterpret_cast<INT_PTR>(GetPropW(GetParent(window), L"HarnessInstaller.Stage")));
|
||||
const double fraction = reinterpret_cast<UINT_PTR>(GetPropW(GetParent(window), L"HarnessInstaller.ExtractProgress")) / 100.0;
|
||||
page->progress.Advance(stage, fraction, GetTickCount64());
|
||||
const int percent = static_cast<int>(page->progress.value);
|
||||
SolidBrush track(page->dark ? Color(255, 97, 102, 107) : Color(255, 233, 236, 242));
|
||||
SolidBrush ink(page->dark ? Color(255, 255, 255, 255) : Color(255, 15, 17, 21));
|
||||
FillProgress(graphics, track, 472.0f);
|
||||
FillProgress(graphics, ink, 472.0f * static_cast<REAL>(page->progress.value) / 100);
|
||||
FontFamily family(L"Microsoft YaHei UI");
|
||||
Font font(&family, 14, FontStyleRegular, UnitPixel);
|
||||
StringFormat centered;
|
||||
centered.SetAlignment(StringAlignmentCenter);
|
||||
centered.SetLineAlignment(StringAlignmentCenter);
|
||||
WCHAR caption[160];
|
||||
wsprintfW(caption, page->captions[page->progress.CaptionStage()], percent);
|
||||
SetWindowTextW(window, caption);
|
||||
graphics.DrawString(caption, -1, &font, RectF(48, 512, 504, 22), ¢ered, &ink);
|
||||
if (!page->controlsVisible) {
|
||||
const int stage = static_cast<int>(reinterpret_cast<INT_PTR>(GetPropW(GetParent(window), L"HarnessInstaller.Stage")));
|
||||
const double fraction = reinterpret_cast<UINT_PTR>(GetPropW(GetParent(window), L"HarnessInstaller.ExtractProgress")) / 100.0;
|
||||
page->progress.Advance(stage, fraction, GetTickCount64());
|
||||
const int percent = static_cast<int>(page->progress.value);
|
||||
SolidBrush track(page->dark ? Color(255, 97, 102, 107) : Color(255, 233, 236, 242));
|
||||
SolidBrush ink(page->dark ? Color(255, 255, 255, 255) : Color(255, 15, 17, 21));
|
||||
FillProgress(graphics, track, 472.0f);
|
||||
FillProgress(graphics, ink, 472.0f * static_cast<REAL>(page->progress.value) / 100);
|
||||
FontFamily family(L"Microsoft YaHei UI");
|
||||
Font font(&family, 14, FontStyleRegular, UnitPixel);
|
||||
StringFormat centered;
|
||||
centered.SetAlignment(StringAlignmentCenter);
|
||||
centered.SetLineAlignment(StringAlignmentCenter);
|
||||
WCHAR caption[160];
|
||||
wsprintfW(caption, page->captions[page->progress.CaptionStage()], percent);
|
||||
SetWindowTextW(window, caption);
|
||||
graphics.DrawString(caption, -1, &font, RectF(48, 512, 504, 22), ¢ered, &ink);
|
||||
}
|
||||
}
|
||||
BitBlt(dc, paint.rcPaint.left, paint.rcPaint.top,
|
||||
paint.rcPaint.right - paint.rcPaint.left, paint.rcPaint.bottom - paint.rcPaint.top,
|
||||
@@ -372,9 +475,10 @@ extern "C" __declspec(dllexport) HWND __cdecl InstallerShowProgress(HWND parent,
|
||||
}
|
||||
delete page->brand;
|
||||
page->brand = nullptr;
|
||||
HWND window = CreateWindowExW(0, type.lpszClassName, L"", WS_CHILD,
|
||||
HWND window = CreateWindowExW(WS_EX_CONTROLPARENT, type.lpszClassName, L"", WS_CHILD | WS_CLIPCHILDREN,
|
||||
0, 0, MulDiv(600, dpi, 96), MulDiv(600, dpi, 96), parent, nullptr, module, page);
|
||||
if (!window) { delete page; return nullptr; }
|
||||
if (!SetTimer(window, 1, 16, nullptr)) { DestroyWindow(window); return nullptr; }
|
||||
// Keep the stock page available until the replacement is fully constructed.
|
||||
HWND stockPage = GetParent(source);
|
||||
if (!SetWindowSubclass(stockPage, HiddenPageProc, 1, 0)) {
|
||||
@@ -385,32 +489,65 @@ extern "C" __declspec(dllexport) HWND __cdecl InstallerShowProgress(HWND parent,
|
||||
return window;
|
||||
}
|
||||
|
||||
// NSIS has already reported success. Pump the UI for the bounded final animation,
|
||||
// including a painted 100% frame, before constructing the interactive finish page.
|
||||
extern "C" __declspec(dllexport) BOOL __cdecl InstallerFinishProgress(HWND window) {
|
||||
// Called from the instfiles leave callback on success. Timer paints finish the
|
||||
// animation while USER32 continues dispatching the current move or menu.
|
||||
extern "C" __declspec(dllexport) BOOL __cdecl InstallerFinishProgress(HWND window, LPCWSTR finish, LPCWSTR launch) {
|
||||
auto* page = reinterpret_cast<ProgressPage*>(GetWindowLongPtrW(window, GWLP_USERDATA));
|
||||
if (!page) return FALSE;
|
||||
const ULONGLONG started = GetTickCount64();
|
||||
if (page->progress.succeeded) return TRUE;
|
||||
const auto scaled = [&](int n) { return MulDiv(n,page->dpi,96); };
|
||||
page->finishFont = CreateFontW(-scaled(16),0,0,0,FW_MEDIUM,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");
|
||||
page->launchFont = CreateFontW(-scaled(14),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI");
|
||||
if (!page->finishFont || !page->launchFont) return FALSE;
|
||||
HDC dc = GetDC(window);
|
||||
if (!dc) return FALSE;
|
||||
HGDIOBJ old = SelectObject(dc,page->launchFont);
|
||||
SIZE size = {};
|
||||
const BOOL measured = GetTextExtentPoint32W(dc,launch,lstrlenW(launch),&size);
|
||||
SelectObject(dc,old); ReleaseDC(window,dc);
|
||||
if (!measured) return FALSE;
|
||||
const int launchWidth = std::min(scaled(600),static_cast<int>(size.cx) + scaled(42));
|
||||
auto button = [&](INT_PTR id, LPCWSTR title, DWORD style, int x, int y, int w, int h, HFONT font) {
|
||||
HWND child = CreateWindowW(L"BUTTON",title,WS_CHILD|WS_TABSTOP|style,x,y,w,h,window,reinterpret_cast<HMENU>(id),GetModuleHandleW(nullptr),nullptr);
|
||||
if (child) SendMessageW(child,WM_SETFONT,reinterpret_cast<WPARAM>(font),FALSE);
|
||||
return child;
|
||||
};
|
||||
page->finish = button(0x6100,finish,BS_DEFPUSHBUTTON,scaled(240),scaled(490),scaled(120),scaled(44),page->finishFont);
|
||||
page->launch = button(0x6101,launch,BS_AUTOCHECKBOX,(scaled(600)-launchWidth)/2,scaled(438),launchWidth,scaled(32),page->launchFont);
|
||||
page->minimize = button(0x6102,L"\x2212",BS_PUSHBUTTON,scaled(504),scaled(8),scaled(40),scaled(32),page->finishFont);
|
||||
page->close = button(0x6103,L"\x00d7",BS_PUSHBUTTON,scaled(548),scaled(8),scaled(40),scaled(32),page->finishFont);
|
||||
if (!page->finish || !page->launch || !page->minimize || !page->close) return FALSE;
|
||||
SendMessageW(page->launch,BM_SETCHECK,BST_CHECKED,0);
|
||||
SetPropW(GetParent(window), L"HarnessInstaller.Succeeded", reinterpret_cast<HANDLE>(1));
|
||||
page->progress.Complete(started);
|
||||
while (IsWindow(window) && GetTickCount64() - started < 750) {
|
||||
MSG message;
|
||||
if (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
|
||||
if (message.message == WM_QUIT) { PostQuitMessage(static_cast<int>(message.wParam)); return FALSE; }
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
} else {
|
||||
MsgWaitForMultipleObjectsEx(0, nullptr, 16, QS_ALLINPUT, MWMO_INPUTAVAILABLE);
|
||||
}
|
||||
}
|
||||
if (!IsWindow(window)) return FALSE;
|
||||
InvalidateRect(window, nullptr, FALSE);
|
||||
UpdateWindow(window);
|
||||
page->progress.Complete(GetTickCount64());
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// Reading consumes one explicit Finish/Close action so a failed launch can retry.
|
||||
extern "C" __declspec(dllexport) int __cdecl InstallerTakeFinishChoice(HWND window) {
|
||||
auto* page = reinterpret_cast<ProgressPage*>(GetWindowLongPtrW(window,GWLP_USERDATA));
|
||||
if (!page) return -1;
|
||||
int choice = page->finishChoice;
|
||||
page->finishChoice = -1;
|
||||
return choice;
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK FrameProc(HWND window, UINT message, WPARAM wparam,
|
||||
LPARAM lparam, UINT_PTR id, DWORD_PTR) {
|
||||
if (message == WM_COMMAND && HIWORD(wparam) == BN_CLICKED) {
|
||||
HWND progress = FindWindowExW(window, nullptr, L"HarnessInstallerProgress", nullptr);
|
||||
auto* page = reinterpret_cast<ProgressPage*>(GetWindowLongPtrW(progress, GWLP_USERDATA));
|
||||
HWND control = reinterpret_cast<HWND>(lparam);
|
||||
if (page && page->controlsVisible) {
|
||||
// IsDialogMessage can route Enter to the outer NSIS dialog.
|
||||
if (control && GetParent(control) == progress)
|
||||
return SendMessageW(progress, WM_COMMAND, wparam, lparam);
|
||||
if (LOWORD(wparam) == IDOK) {
|
||||
RequestFinish(progress, *page, SendMessageW(page->launch, BM_GETCHECK, 0, 0) == BST_CHECKED);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (message == WM_NCCALCSIZE && wparam) return 0;
|
||||
// Activation must not repaint the standard frame over the custom client area.
|
||||
if (message == WM_NCACTIVATE) return DefSubclassProc(window, message, wparam, -1);
|
||||
@@ -419,7 +556,9 @@ static LRESULT CALLBACK FrameProc(HWND window, UINT message, WPARAM wparam,
|
||||
// The installer has a fixed size; its page provides the drag area.
|
||||
return hit >= HTLEFT && hit <= HTBOTTOMRIGHT ? HTCLIENT : hit;
|
||||
}
|
||||
if (message == WM_NCDESTROY) RemoveWindowSubclass(window, FrameProc, id);
|
||||
if (message == WM_NCDESTROY) {
|
||||
RemoveWindowSubclass(window, FrameProc, id);
|
||||
}
|
||||
return DefSubclassProc(window, message, wparam, lparam);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-desktop",
|
||||
"description": "Electron desktop shell for a bundled dsh runtime and external plugins",
|
||||
"version": "0.2.2-rc.4",
|
||||
"version": "0.2.2-rc.5",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"author": {
|
||||
|
||||
@@ -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`。如果恢复失败,安装器会清理未被占用的暂存文件并保留备份。上报此失败后,退出清理不再重试恢复。请保留报告所列的备份目录,并在重新安装前联系支持人员。静默安装保存相同的诊断,不显示弹窗。
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -94,16 +94,19 @@ ManifestDPIAware true
|
||||
!macroend
|
||||
|
||||
!macro customUnInstall
|
||||
Call un.BeginCleanup
|
||||
Call un.CleanRegistration
|
||||
Call un.CleanData
|
||||
!macroend
|
||||
|
||||
!macro customPageAfterChangeDir
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_PRE InstallerBeforeInstall
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_SHOW InstallerProgressShow
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE InstallerProgressLeave
|
||||
!macroend
|
||||
|
||||
!macro customFinishPage
|
||||
Page custom InstallerFinish InstallerFinishLeave
|
||||
; The final instfiles page keeps its controls until the user dismisses it.
|
||||
!macroend
|
||||
|
||||
; Installation work publishes stage changes without disturbing the NSIS caller.
|
||||
@@ -171,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"
|
||||
@@ -199,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) {
|
||||
|
||||
@@ -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"')
|
||||
}
|
||||
@@ -1,9 +1,16 @@
|
||||
/** Bounded, cancellable reads of Desktop-owned plugin operation history. */
|
||||
import { open } from 'node:fs/promises'
|
||||
import type { BigIntStats } from 'node:fs'
|
||||
import { open, type FileHandle } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { setImmediate } from 'node:timers/promises'
|
||||
import { setImmediate, setTimeout as wait } from 'node:timers/promises'
|
||||
import { parsePluginOperationRecord, type PluginOperationRecord } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
|
||||
|
||||
/** Windows reports these while another handle temporarily owns an otherwise readable file. */
|
||||
const WINDOWS_TRANSIENT_OPEN_ERRORS: ReadonlySet<string> = new Set(['EACCES', 'EBUSY', 'EPERM'])
|
||||
const WINDOWS_OPEN_RETRY_INITIAL_MS = 10
|
||||
const WINDOWS_OPEN_RETRY_MAX_MS = 40
|
||||
const WINDOWS_OPEN_RETRY_LIMIT = 4
|
||||
|
||||
/** Resource budgets for auxiliary history collection, independent of basic crash report writing. */
|
||||
export interface OperationHistoryReadLimits {
|
||||
readonly bytes: number
|
||||
@@ -15,7 +22,7 @@ export interface OperationHistoryReadLimits {
|
||||
export interface OperationHistoryReadResult {
|
||||
readonly records: readonly PluginOperationRecord[]
|
||||
readonly bytesRead: number
|
||||
/** Distinct files from which at least one byte was read. */
|
||||
/** Owned history segments from which at least one byte was read. */
|
||||
readonly filesRead: number
|
||||
readonly truncated: boolean
|
||||
readonly invalidRecords: number
|
||||
@@ -23,9 +30,53 @@ export interface OperationHistoryReadResult {
|
||||
readonly cancelled: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact two-name key for one file; BigInt stats keep a Windows 64-bit file ID at its
|
||||
* value instead of the 53-bit Number form, where two adjacent IDs can coincide.
|
||||
* @param info - Stats of the opened history segment.
|
||||
* @returns Device and inode as one comparable string.
|
||||
*/
|
||||
function fileIdentity(info: BigIntStats): string {
|
||||
return `${String(info.dev)}:${String(info.ino)}`
|
||||
}
|
||||
|
||||
/** Whether Windows reported temporary interference with opening a history segment. */
|
||||
function isTransientWindowsOpenError(error: unknown): boolean {
|
||||
if (process.platform !== 'win32') return false
|
||||
return WINDOWS_TRANSIENT_OPEN_ERRORS.has((error as NodeJS.ErrnoException | null)?.code ?? '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Open one segment, retrying the temporary Windows sharing and permission failures a scanner
|
||||
* causes on a freshly written file. One persistent failure would otherwise drop the whole
|
||||
* segment from the report. A signal aborted during the bounded wait ends the retries without
|
||||
* another open.
|
||||
* @param filename - Absolute path of the owned segment.
|
||||
* @param signal - Caller-owned collection deadline or shutdown cancellation.
|
||||
* @returns The opened read handle.
|
||||
*/
|
||||
async function openSegment(filename: string, signal: AbortSignal): Promise<FileHandle> {
|
||||
// A call keeps the post-wait check outside the catch's narrowing to the pre-wait value.
|
||||
const aborted = (): boolean => signal.aborted
|
||||
let delay = WINDOWS_OPEN_RETRY_INITIAL_MS
|
||||
for (let retries = 0;; retries += 1) {
|
||||
try {
|
||||
return await open(filename, 'r')
|
||||
} catch (error) {
|
||||
if (!isTransientWindowsOpenError(error) || retries >= WINDOWS_OPEN_RETRY_LIMIT || aborted()) throw error
|
||||
await wait(delay)
|
||||
if (aborted()) throw error
|
||||
delay = Math.min(delay * 2, WINDOWS_OPEN_RETRY_MAX_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read only the bounded tails of the two owned history files, newest segment first.
|
||||
* Cancellation is observed between bounded records after yielding to Worker messages and stops subsequent I/O and parsing.
|
||||
* A segment is deduplicated as already read when its handle reports the exact bigint identity of
|
||||
* the segment already read; the predecessor is skipped, so its records are not collected twice and
|
||||
* records appended to it after the read are not collected.
|
||||
* An already-issued OS read must settle before its handle closes.
|
||||
* @param directory - Desktop's operation history directory; unrelated files are never enumerated.
|
||||
* @param limits - Positive byte, record-size and record-count budgets.
|
||||
@@ -44,33 +95,35 @@ export async function readOperationHistory(
|
||||
const cancelled = (): boolean => signal.aborted
|
||||
const records: PluginOperationRecord[] = []
|
||||
let bytesRead = 0
|
||||
const seenFiles = new Set<string>()
|
||||
let filesRead = 0
|
||||
let lastReadIdentity: string | undefined
|
||||
let truncated = false
|
||||
let invalidRecords = 0
|
||||
let unavailableFiles = 0
|
||||
for (const name of ['operations.jsonl', 'operations.previous.jsonl']) {
|
||||
if (cancelled()) break
|
||||
try {
|
||||
await using handle = await open(join(directory, name), 'r')
|
||||
await using handle = await openSegment(join(directory, name), signal)
|
||||
if (cancelled()) break
|
||||
const fileStat = await handle.stat()
|
||||
const fileStat = await handle.stat({ bigint: true })
|
||||
if (cancelled()) break
|
||||
if (!fileStat.isFile()) {
|
||||
unavailableFiles++
|
||||
continue
|
||||
}
|
||||
const identity = `${String(fileStat.dev)}:${String(fileStat.ino)}`
|
||||
if (seenFiles.has(identity)) {
|
||||
const identity = fileIdentity(fileStat)
|
||||
const size = Number(fileStat.size)
|
||||
if (lastReadIdentity !== undefined && identity === lastReadIdentity) {
|
||||
truncated = true
|
||||
continue
|
||||
}
|
||||
if (fileStat.size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) {
|
||||
if (size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) {
|
||||
truncated = true
|
||||
break
|
||||
}
|
||||
|
||||
const readLength = Math.min(fileStat.size, limits.bytes - bytesRead)
|
||||
const readStart = fileStat.size - readLength
|
||||
const readLength = Math.min(size, limits.bytes - bytesRead)
|
||||
const readStart = size - readLength
|
||||
const buffer = Buffer.alloc(readLength)
|
||||
let readOffset = 0
|
||||
while (readOffset < readLength && !cancelled()) {
|
||||
@@ -79,7 +132,10 @@ export async function readOperationHistory(
|
||||
if (read.bytesRead === 0) break
|
||||
readOffset += read.bytesRead
|
||||
}
|
||||
if (readOffset > 0) seenFiles.add(identity)
|
||||
if (readOffset > 0) {
|
||||
filesRead++
|
||||
lastReadIdentity = identity
|
||||
}
|
||||
if (cancelled()) break
|
||||
truncated ||= readStart > 0 || readOffset < readLength
|
||||
|
||||
@@ -116,5 +172,5 @@ export async function readOperationHistory(
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') unavailableFiles++
|
||||
}
|
||||
}
|
||||
return { records, bytesRead, filesRead: seenFiles.size, truncated, invalidRecords, unavailableFiles, cancelled: cancelled() }
|
||||
return { records, bytesRead, filesRead, truncated, invalidRecords, unavailableFiles, cancelled: cancelled() }
|
||||
}
|
||||
@@ -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')
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
"welcome-ready-before-first-show",
|
||||
"welcome-presented-on-first-show",
|
||||
"successful-install-paints-100-before-finish",
|
||||
"completion-close-exits-without-launch",
|
||||
"locked-directory-shows-error-and-copy-control-and-preserves-installation",
|
||||
"registered-directory-with-trailing-separators",
|
||||
"registered-directory-and-checked-launch",
|
||||
|
||||
@@ -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}')
|
||||
})
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { mkdtemp, mkdir, open, rename, rm, writeFile } from 'node:fs/promises'
|
||||
import { appendFile, mkdtemp, mkdir, open, rename, rm, writeFile } from 'node:fs/promises'
|
||||
import type { BigIntStats, StatOptions, Stats } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { beforeEach, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { readOperationHistory } from '../src/operation-history.ts'
|
||||
|
||||
vi.mock('node:fs/promises', async (importOriginal) => {
|
||||
@@ -10,6 +11,7 @@ vi.mock('node:fs/promises', async (importOriginal) => {
|
||||
})
|
||||
|
||||
const limits = { bytes: 64 * 1024, recordBytes: 2048, records: 100 }
|
||||
beforeEach(() => { vi.mocked(open).mockClear() })
|
||||
function record(id: string | number) {
|
||||
return { runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0,
|
||||
operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z',
|
||||
@@ -25,11 +27,183 @@ async function fixture() {
|
||||
|
||||
it('collects recent complete records and reports malformed and incomplete entries', async () => {
|
||||
const path = await fixture()
|
||||
await writeFile(join(path, 'operations.jsonl'), line(1) + '{broken}\n' + line(2) + '{"incomplete":')
|
||||
const current = line(1) + '{broken}\n' + line(2) + '{"incomplete":'
|
||||
await writeFile(join(path, 'operations.jsonl'), current)
|
||||
await writeFile(join(path, 'operations.previous.jsonl'), line(0))
|
||||
const result = await readOperationHistory(path, limits, new AbortController().signal)
|
||||
expect(result.records).toEqual([record(2), record(1), record(0)])
|
||||
expect(result).toMatchObject({ invalidRecords: 1, truncated: true, cancelled: false, unavailableFiles: 0 })
|
||||
// The whole result is asserted so a missing record also names the collection facts that caused it.
|
||||
expect(result).toEqual({
|
||||
records: [record(2), record(1), record(0)],
|
||||
bytesRead: Buffer.byteLength(current) + Buffer.byteLength(line(0)),
|
||||
filesRead: 2,
|
||||
truncated: true,
|
||||
invalidRecords: 1,
|
||||
unavailableFiles: 0,
|
||||
cancelled: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('does not collect a rotated predecessor twice after it was appended', async () => {
|
||||
const path = await fixture()
|
||||
const current = join(path, 'operations.jsonl')
|
||||
const previous = join(path, 'operations.previous.jsonl')
|
||||
await writeFile(current, line(1))
|
||||
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
|
||||
const handle = await open(current, 'r')
|
||||
const opener = vi.mocked(open).mockClear()
|
||||
.mockImplementationOnce(async () => handle)
|
||||
.mockImplementationOnce(async () => {
|
||||
// The writer appends one record, then rotates: both names still denote one file.
|
||||
await appendFile(current, line(2))
|
||||
await rename(current, previous)
|
||||
await writeFile(current, line(3))
|
||||
return actualFs.open(previous, 'r')
|
||||
})
|
||||
try {
|
||||
const result = await readOperationHistory(path, limits, new AbortController().signal)
|
||||
expect(result.records).toEqual([record(1)])
|
||||
expect(result).toMatchObject({ filesRead: 1, truncated: true, unavailableFiles: 0 })
|
||||
} finally {
|
||||
opener.mockClear()
|
||||
}
|
||||
})
|
||||
|
||||
it('compares exact bigint identities so two nearby Numbers cannot collapse one segment', async () => {
|
||||
const path = await fixture()
|
||||
const current = join(path, 'operations.jsonl')
|
||||
const previous = join(path, 'operations.previous.jsonl')
|
||||
const currentText = line('current')
|
||||
const previousText = line('old')
|
||||
await writeFile(current, currentText)
|
||||
await writeFile(previous, previousText)
|
||||
const currentHandle = await open(current, 'r')
|
||||
const previousHandle = await open(previous, 'r')
|
||||
onTestFinished(async () => { await currentHandle.close(); await previousHandle.close() })
|
||||
const currentStat = await currentHandle.stat({ bigint: true })
|
||||
const previousStat = await previousHandle.stat({ bigint: true })
|
||||
const currentNumberStat = await currentHandle.stat()
|
||||
const previousNumberStat = await previousHandle.stat()
|
||||
// Adjacent 64-bit file IDs: distinct as bigints, one Number after the 53-bit mantissa.
|
||||
const base = 2n ** 58n + 1000n
|
||||
currentStat.dev = 0n
|
||||
currentStat.ino = base
|
||||
previousStat.dev = 0n
|
||||
previousStat.ino = base + 1n
|
||||
currentNumberStat.dev = 0
|
||||
currentNumberStat.ino = Number(base)
|
||||
previousNumberStat.dev = 0
|
||||
previousNumberStat.ino = Number(base + 1n)
|
||||
expect(currentNumberStat.ino).toBe(previousNumberStat.ino)
|
||||
const optionAware = (exact: BigIntStats, numeric: Stats) =>
|
||||
async (options?: StatOptions): Promise<BigIntStats | Stats> => options?.bigint === true ? exact : numeric
|
||||
const currentStats = vi.spyOn(currentHandle, 'stat').mockImplementation(optionAware(currentStat, currentNumberStat))
|
||||
const previousStats = vi.spyOn(previousHandle, 'stat').mockImplementation(optionAware(previousStat, previousNumberStat))
|
||||
const opener = vi.mocked(open).mockClear().mockResolvedValueOnce(currentHandle).mockResolvedValueOnce(previousHandle)
|
||||
try {
|
||||
const result = await readOperationHistory(path, limits, new AbortController().signal)
|
||||
expect(result.records).toEqual([record('current'), record('old')])
|
||||
expect(result).toMatchObject({ filesRead: 2, unavailableFiles: 0, truncated: false })
|
||||
} finally {
|
||||
currentStats.mockRestore()
|
||||
previousStats.mockRestore()
|
||||
opener.mockClear()
|
||||
}
|
||||
})
|
||||
|
||||
it('retries transient Windows sharing failures while opening a segment', async () => {
|
||||
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
|
||||
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
|
||||
const opener = vi.mocked(open)
|
||||
onTestFinished(async () => {
|
||||
platform.mockRestore()
|
||||
opener.mockReset().mockImplementation(actualFs.open)
|
||||
})
|
||||
const path = await fixture()
|
||||
await writeFile(join(path, 'operations.jsonl'), line(2))
|
||||
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
|
||||
opener.mockRejectedValueOnce(Object.assign(new Error('sharing violation'), { code: 'EBUSY' }))
|
||||
const result = await readOperationHistory(path, limits, new AbortController().signal)
|
||||
expect(result.records).toEqual([record(2), record(1)])
|
||||
expect(result.unavailableFiles).toBe(0)
|
||||
expect(opener).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('counts a segment unavailable after bounded Windows open retries expire', async () => {
|
||||
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
|
||||
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
|
||||
const opener = vi.mocked(open)
|
||||
onTestFinished(async () => {
|
||||
platform.mockRestore()
|
||||
opener.mockReset().mockImplementation(actualFs.open)
|
||||
})
|
||||
const path = await fixture()
|
||||
await writeFile(join(path, 'operations.jsonl'), line(2))
|
||||
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
|
||||
for (let attempt = 0; attempt <= 4; attempt++) {
|
||||
opener.mockRejectedValueOnce(Object.assign(new Error('access denied'), { code: 'EPERM' }))
|
||||
}
|
||||
const result = await readOperationHistory(path, limits, new AbortController().signal)
|
||||
expect(result.records).toEqual([record(1)])
|
||||
expect(result.unavailableFiles).toBe(1)
|
||||
expect(opener).toHaveBeenCalledTimes(6)
|
||||
})
|
||||
|
||||
it('does not retry a Windows transient code outside Windows', async () => {
|
||||
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('linux')
|
||||
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
|
||||
const opener = vi.mocked(open)
|
||||
onTestFinished(async () => {
|
||||
platform.mockRestore()
|
||||
opener.mockReset().mockImplementation(actualFs.open)
|
||||
})
|
||||
const path = await fixture()
|
||||
await writeFile(join(path, 'operations.jsonl'), line(2))
|
||||
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
|
||||
opener.mockRejectedValueOnce(Object.assign(new Error('access denied'), { code: 'EPERM' }))
|
||||
const result = await readOperationHistory(path, limits, new AbortController().signal)
|
||||
expect(result.records).toEqual([record(1)])
|
||||
expect(result.unavailableFiles).toBe(1)
|
||||
expect(opener).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('stops Windows open retries when the collection is already cancelled', async () => {
|
||||
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
|
||||
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
|
||||
const opener = vi.mocked(open)
|
||||
onTestFinished(async () => {
|
||||
platform.mockRestore()
|
||||
opener.mockReset().mockImplementation(actualFs.open)
|
||||
})
|
||||
const path = await fixture()
|
||||
await writeFile(join(path, 'operations.jsonl'), line(2))
|
||||
const controller = new AbortController()
|
||||
opener.mockImplementationOnce(async () => {
|
||||
controller.abort()
|
||||
throw Object.assign(new Error('sharing violation'), { code: 'EBUSY' })
|
||||
})
|
||||
const result = await readOperationHistory(path, limits, controller.signal)
|
||||
expect(result).toMatchObject({ records: [], cancelled: true, unavailableFiles: 1 })
|
||||
expect(opener).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('stops Windows open retries when cancellation lands during the retry wait', async () => {
|
||||
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
|
||||
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
|
||||
const opener = vi.mocked(open)
|
||||
onTestFinished(async () => {
|
||||
platform.mockRestore()
|
||||
opener.mockReset().mockImplementation(actualFs.open)
|
||||
})
|
||||
const path = await fixture()
|
||||
await writeFile(join(path, 'operations.jsonl'), line(2))
|
||||
const controller = new AbortController()
|
||||
opener.mockImplementationOnce(async () => {
|
||||
setImmediate(() => { controller.abort() })
|
||||
throw Object.assign(new Error('sharing violation'), { code: 'EBUSY' })
|
||||
})
|
||||
const result = await readOperationHistory(path, limits, controller.signal)
|
||||
expect(result).toMatchObject({ records: [], cancelled: true, unavailableFiles: 1 })
|
||||
expect(opener).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reads no more than its byte budget from a two GiB file and ignores unrelated history', async () => {
|
||||
@@ -159,6 +333,27 @@ it('does not collect the same open segment twice when it rotates during collecti
|
||||
}
|
||||
})
|
||||
|
||||
it('does not re-collect a rotated segment while the current path is briefly absent', async () => {
|
||||
const path = await fixture()
|
||||
const current = join(path, 'operations.jsonl')
|
||||
await writeFile(current, line(1))
|
||||
const handle = await open(current, 'r')
|
||||
onTestFinished(async () => { await handle.close() })
|
||||
const opener = vi.mocked(open).mockClear().mockImplementationOnce(async () => {
|
||||
await rename(current, join(path, 'operations.previous.jsonl'))
|
||||
return handle
|
||||
})
|
||||
try {
|
||||
const result = await readOperationHistory(path, limits, new AbortController().signal)
|
||||
expect(result.records).toEqual([record(1)])
|
||||
expect(result).toMatchObject({ filesRead: 1, truncated: true })
|
||||
expect(handle.fd).toBe(-1)
|
||||
} finally {
|
||||
opener.mockClear()
|
||||
await handle.close()
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['absent', 'empty', 'nonempty'])('reports omitted bytes at an exact budget: previous segment %s', async (previous) => {
|
||||
const path = await fixture()
|
||||
const current = line(1)
|
||||
|
||||
@@ -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,8 @@ int main() {
|
||||
progress.Complete(done);
|
||||
double previous = progress.value;
|
||||
for (std::uint64_t elapsed = 0; elapsed < 600; elapsed += 16) {
|
||||
// A repeated completion notification must not restart the final animation.
|
||||
if (elapsed == 320) progress.Complete(done + elapsed);
|
||||
progress.Advance(4, 1, done + elapsed);
|
||||
assert(progress.value >= previous && progress.value < 100);
|
||||
previous = progress.value;
|
||||
|
||||
@@ -11,9 +11,67 @@ extern "C" __declspec(dllimport) HRESULT __cdecl InstallerApplyFrame(HWND window
|
||||
extern "C" __declspec(dllimport) HWND __cdecl InstallerShowProgress(HWND parent, HWND source,
|
||||
BOOL dark, UINT dpi, DWORD controlHover, DWORD controlPressed, const WCHAR* brand, const WCHAR* preparing, const WCHAR* extracting,
|
||||
const WCHAR* copying, const WCHAR* registering, const WCHAR* cleaning);
|
||||
extern "C" __declspec(dllimport) BOOL __cdecl InstallerFinishProgress(HWND window);
|
||||
extern "C" __declspec(dllimport) BOOL __cdecl InstallerFinishProgress(HWND window, const WCHAR* finish, const WCHAR* launch);
|
||||
extern "C" __declspec(dllimport) int __cdecl InstallerTakeFinishChoice(HWND window);
|
||||
|
||||
struct CompletionProbe {
|
||||
HWND progress;
|
||||
ULONGLONG deadline;
|
||||
RECT bounds;
|
||||
bool requested = false;
|
||||
bool completedDuringMove = false;
|
||||
};
|
||||
|
||||
static void PollCompletion(HWND window, CompletionProbe& probe) {
|
||||
const HWND finish = FindWindowExW(probe.progress, nullptr, L"Button", L"Finish");
|
||||
const HWND launch = FindWindowExW(probe.progress, nullptr, L"Button", L"Launch");
|
||||
if (finish && launch && IsWindowVisible(finish) && IsWindowVisible(launch)) {
|
||||
GUITHREADINFO input{sizeof(input)};
|
||||
RECT current;
|
||||
probe.completedDuringMove = GetGUIThreadInfo(GetCurrentThreadId(), &input)
|
||||
&& input.hwndMoveSize == window && GetWindowRect(window, ¤t)
|
||||
&& EqualRect(¤t, &probe.bounds) && IsWindowEnabled(finish)
|
||||
&& SendMessageW(launch, BM_GETCHECK, 0, 0) == BST_CHECKED
|
||||
&& GetPropW(window, L"HarnessInstaller.CompletedPercent") == reinterpret_cast<HANDLE>(100);
|
||||
} else if (GetTickCount64() < probe.deadline) {
|
||||
return;
|
||||
}
|
||||
SendMessageW(window, WM_CANCELMODE, 0, 0);
|
||||
}
|
||||
|
||||
static bool CompleteWhileMinimized(HWND window, HWND progress) {
|
||||
ShowWindow(window, SW_MINIMIZE);
|
||||
const HWND foreground = GetForegroundWindow();
|
||||
if (!IsIconic(window) || !InstallerFinishProgress(progress, L"Finish", L"Launch")) return false;
|
||||
const ULONGLONG deadline = GetTickCount64() + 5000;
|
||||
while (GetTickCount64() < deadline) {
|
||||
const HWND finish = FindWindowExW(progress, nullptr, L"Button", L"Finish");
|
||||
if (finish && IsWindowVisible(finish)) {
|
||||
return IsIconic(window) && (foreground == window || GetForegroundWindow() != window)
|
||||
&& GetPropW(window, L"HarnessInstaller.Succeeded") != nullptr;
|
||||
}
|
||||
MSG message;
|
||||
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) DispatchMessageW(&message);
|
||||
MsgWaitForMultipleObjectsEx(0, nullptr, 16, QS_ALLINPUT, MWMO_INPUTAVAILABLE);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static LRESULT CALLBACK WindowProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
auto* probe = reinterpret_cast<CompletionProbe*>(GetWindowLongPtrW(window, GWLP_USERDATA));
|
||||
if (probe && message == WM_ENTERSIZEMOVE) {
|
||||
GetWindowRect(window, &probe->bounds);
|
||||
PostMessageW(window, WM_APP, 0, 0);
|
||||
}
|
||||
if (probe && message == WM_APP) {
|
||||
probe->requested = InstallerFinishProgress(probe->progress, L"Finish", L"Launch") != FALSE;
|
||||
if (!probe->requested || !SetTimer(window, 1, 16, nullptr)) SendMessageW(window, WM_CANCELMODE, 0, 0);
|
||||
return 0;
|
||||
}
|
||||
if (probe && message == WM_TIMER && wparam == 1) {
|
||||
PollCompletion(window, *probe);
|
||||
return 0;
|
||||
}
|
||||
if (message == WM_DESTROY) { PostQuitMessage(0); return 0; }
|
||||
return DefWindowProcW(window, message, wparam, lparam);
|
||||
}
|
||||
@@ -68,10 +126,12 @@ int wmain(int argc, wchar_t** argv) {
|
||||
HWND warmup = createProgress();
|
||||
if (!warmup) { DestroyWindow(window); return 5; }
|
||||
UpdateWindow(warmup);
|
||||
ShowWindow(window, SW_MINIMIZE);
|
||||
const bool minimizedCompletion = CompleteWhileMinimized(window, warmup);
|
||||
ShowWindow(window, SW_RESTORE);
|
||||
UpdateWindow(warmup);
|
||||
DestroyWindow(warmup);
|
||||
RemovePropW(window, L"HarnessInstaller.CompletedPercent");
|
||||
RemovePropW(window, L"HarnessInstaller.Succeeded");
|
||||
const DWORD initialGdi = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS);
|
||||
HWND progress = createProgress();
|
||||
if (!progress) { DestroyWindow(window); return 5; }
|
||||
@@ -124,14 +184,15 @@ int wmain(int argc, wchar_t** argv) {
|
||||
};
|
||||
bool captionStates = true;
|
||||
ShowWindow(progress, SW_HIDE);
|
||||
for (int x : {504, 548}) {
|
||||
{
|
||||
constexpr int x = 504;
|
||||
const LPARAM point = MAKELPARAM(MulDiv(x + 20, dpi, 96), MulDiv(24, dpi, 96));
|
||||
captionStates = expectPixel(x, normalColor) && captionStates;
|
||||
SendMessageW(progress, WM_MOUSEMOVE, 0, point);
|
||||
captionStates = expectPixel(x, hoverColor) && captionStates;
|
||||
SendMessageW(progress, WM_LBUTTONDOWN, MK_LBUTTON, point);
|
||||
captionStates = expectPixel(x, pressedColor) && captionStates;
|
||||
const int other = x == 504 ? 548 : 504;
|
||||
constexpr int other = 548;
|
||||
SendMessageW(progress, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(MulDiv(other + 20, dpi, 96), MulDiv(24, dpi, 96)));
|
||||
captionStates = expectPixel(other, normalColor) && captionStates;
|
||||
captionStates = expectPixel(x, normalColor) && captionStates;
|
||||
@@ -167,12 +228,15 @@ int wmain(int argc, wchar_t** argv) {
|
||||
const LPARAM closePoint = MAKELPARAM(MulDiv(568, dpi, 96), MulDiv(24, dpi, 96));
|
||||
MSG closeMessage;
|
||||
SendMessageW(progress, WM_LBUTTONDOWN, MK_LBUTTON, closePoint);
|
||||
bool closeRelease = !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE);
|
||||
bool closeDisabled = GetCapture() != progress && expectPixel(548, normalColor)
|
||||
&& !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE);
|
||||
SendMessageW(progress, WM_MOUSEMOVE, MK_LBUTTON, closePoint);
|
||||
closeDisabled = closeDisabled && expectPixel(548, normalColor);
|
||||
SendMessageW(progress, WM_LBUTTONUP, 0, minimizePoint);
|
||||
closeRelease = closeRelease && !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE);
|
||||
closeDisabled = closeDisabled && !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE);
|
||||
SendMessageW(progress, WM_LBUTTONDOWN, MK_LBUTTON, closePoint);
|
||||
SendMessageW(progress, WM_LBUTTONUP, 0, closePoint);
|
||||
closeRelease = closeRelease && PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE);
|
||||
closeDisabled = closeDisabled && !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE) && GetCapture() != progress;
|
||||
LARGE_INTEGER frequency, started, finished;
|
||||
QueryPerformanceFrequency(&frequency);
|
||||
std::vector<double> samples;
|
||||
@@ -196,15 +260,45 @@ int wmain(int argc, wchar_t** argv) {
|
||||
std::printf("fixture=standalone-progress dpi=%d dark=%d frames=%d screen=%dx%d foreground=%d mean_ms=%.3f p50_ms=%.3f p95_ms=%.3f max_ms=%.3f\n",
|
||||
dpi, dark, frameCount, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), GetForegroundWindow() == window,
|
||||
total / samples.size(), samples[samples.size() / 2], samples[samples.size() * 95 / 100], samples.back());
|
||||
const bool completed = InstallerFinishProgress(progress) &&
|
||||
GetPropW(window, L"HarnessInstaller.CompletedPercent") == reinterpret_cast<HANDLE>(100);
|
||||
WCHAR caption[160] = {};
|
||||
GetWindowTextW(progress, caption, ARRAYSIZE(caption));
|
||||
const bool finalCaption = wcscmp(caption, L"Extracting 100%") == 0;
|
||||
CompletionProbe probe{progress, GetTickCount64() + 5000, {}};
|
||||
POINT originalCursor{};
|
||||
const bool restoreCursor = GetCursorPos(&originalCursor) != FALSE;
|
||||
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(&probe));
|
||||
SendMessageW(window, WM_SYSCOMMAND, SC_MOVE, 0);
|
||||
if (restoreCursor) SetCursorPos(originalCursor.x, originalCursor.y);
|
||||
KillTimer(window, 1);
|
||||
SetWindowLongPtrW(window, GWLP_USERDATA, 0);
|
||||
const bool completed = probe.requested && probe.completedDuringMove;
|
||||
bool finishActions = completed && InstallerTakeFinishChoice(progress) == -1;
|
||||
bool finishInTabOrder = false, launchInTabOrder = false;
|
||||
if (finishActions) {
|
||||
const HWND finish = FindWindowExW(progress, nullptr, L"Button", L"Finish");
|
||||
const HWND launch = FindWindowExW(progress, nullptr, L"Button", L"Launch");
|
||||
const HWND close = FindWindowExW(progress, nullptr, L"Button", L"\x00d7");
|
||||
const HWND first = GetNextDlgTabItem(window, nullptr, FALSE);
|
||||
HWND tab = first;
|
||||
for (int next = 0; tab && next < 4; ++next) {
|
||||
finishInTabOrder |= tab == finish;
|
||||
launchInTabOrder |= tab == launch;
|
||||
tab = GetNextDlgTabItem(window, tab, FALSE);
|
||||
if (tab == first) break;
|
||||
}
|
||||
SendMessageW(finish, BM_CLICK, 0, 0);
|
||||
finishActions = InstallerTakeFinishChoice(progress) == 1 && InstallerTakeFinishChoice(progress) == -1;
|
||||
SendMessageW(close, BM_CLICK, 0, 0);
|
||||
finishActions = finishActions && InstallerTakeFinishChoice(progress) == 0;
|
||||
SendMessageW(launch, BM_CLICK, 0, 0);
|
||||
SendMessageW(window, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), 0);
|
||||
finishActions = finishActions && InstallerTakeFinishChoice(progress) == 0;
|
||||
}
|
||||
DestroyWindow(progress);
|
||||
const DWORD finalGdi = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS);
|
||||
DestroyWindow(window);
|
||||
std::printf("client_frame=%d stock_preserved=%d completed=%d final_caption=%d caption_states=%d button_release=%d close_release=%d minimized=%d restored=%d gdi_before=%lu gdi_after=%lu\n",
|
||||
clientFrame, failurePreservesStock, completed, finalCaption, captionStates, buttonRelease, closeRelease, minimized, restored, initialGdi, finalGdi);
|
||||
return clientFrame && failurePreservesStock && completed && finalCaption && captionStates && buttonRelease && closeRelease && minimized && restored && finalGdi <= initialGdi ? 0 : 6;
|
||||
std::printf("client_frame=%d stock_preserved=%d completed_during_move=%d caption_states=%d button_release=%d close_disabled=%d minimized=%d restored=%d gdi_before=%lu gdi_after=%lu\n",
|
||||
clientFrame, failurePreservesStock, completed, captionStates, buttonRelease, closeDisabled, minimized, restored, initialGdi, finalGdi);
|
||||
std::printf("minimized_completion=%d finish_actions=%d finish_tab=%d launch_tab=%d\n",
|
||||
minimizedCompletion, finishActions, finishInTabOrder, launchInTabOrder);
|
||||
return clientFrame && failurePreservesStock && completed && minimizedCompletion && finishActions
|
||||
&& finishInTabOrder && launchInTabOrder && captionStates && buttonRelease && closeDisabled
|
||||
&& minimized && restored && finalGdi <= initialGdi ? 0 : 6;
|
||||
}
|
||||
@@ -157,6 +157,14 @@ try {
|
||||
$results.Add('welcome-ready-before-first-show')
|
||||
$results.Add('successful-install-paints-100-before-finish')
|
||||
|
||||
$process = Start-Setup light
|
||||
Click-Control $process $copy.INSTALLER_INSTALL
|
||||
[void](Wait-Control $process $copy.INSTALLER_FINISH)
|
||||
Click-Control $process ([string][char]0xD7)
|
||||
if (-not $process.WaitForExit(10000) -or $process.ExitCode -ne 0) { throw 'Completion close did not exit successfully' }
|
||||
if (Test-Path -LiteralPath (Join-Path $installPath 'launched.txt')) { throw 'Completion close launched the application' }
|
||||
$results.Add('completion-close-exits-without-launch')
|
||||
|
||||
$lockedFile = [IO.File]::Open($appPath, 'Open', 'Read', 'Read')
|
||||
try {
|
||||
$process = Start-Setup light
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-plugin-market-generator",
|
||||
"description": "Reference generator of plugin market index files from a list of npm packages and Git repositories",
|
||||
"version": "0.2.2-rc.4",
|
||||
"version": "0.2.2-rc.5",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-web-frontend",
|
||||
"description": "Web application entry: vite build over the @deepseek-ai/dsh-client-web shell library; dist/ served by apps/cli's dsh web",
|
||||
"version": "0.2.2-rc.4",
|
||||
"version": "0.2.2-rc.5",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
|
||||
@@ -82,7 +82,11 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', '
|
||||
await dialog.getByRole('button', { name: '模型', exact: true }).click()
|
||||
const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true })
|
||||
await edit.click()
|
||||
const key = dialog.getByLabel('API 密钥', { exact: true })
|
||||
// This row's card alone. Between the credential delete and the profile
|
||||
// write that restores native auth, google's row reports no usable
|
||||
// provider and the page mounts the DeepSeek first-run setup card, whose
|
||||
// key field would answer a dialog-wide count.
|
||||
const key = edit.locator('xpath=ancestor::li').getByLabel('API 密钥', { exact: true })
|
||||
await key.press('Delete')
|
||||
expect(await key.getAttribute('placeholder')).toBe(`留空使用环境认证(${envRef})`)
|
||||
await dialog.getByText(`保存以清除已保存的 API key。之后使用环境认证(${envRef})。`, { exact: true }).waitFor()
|
||||
@@ -94,7 +98,7 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', '
|
||||
await edit.click()
|
||||
await key.press('Delete')
|
||||
await dialog.getByRole('button', { name: '保存', exact: true }).click()
|
||||
await expect.poll(() => key.count()).toBe(0)
|
||||
await expect.poll(() => key.count(), { timeout: 10_000 }).toBe(0)
|
||||
await generate()
|
||||
expect(calls).toHaveLength(2)
|
||||
expect(calls[0]?.key).toBe(messages || google ? 'fixture-saved-key' : 'Bearer fixture-saved-key')
|
||||
@@ -134,7 +138,9 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki
|
||||
await dialog.getByRole('button', { name: '模型', exact: true }).click()
|
||||
const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true })
|
||||
await edit.click()
|
||||
const key = dialog.getByLabel('API 密钥', { exact: true })
|
||||
// This row's card alone: the dialog can show another provider's card,
|
||||
// with its own key field, beside this row.
|
||||
const key = edit.locator('xpath=ancestor::li').getByLabel('API 密钥', { exact: true })
|
||||
expect(await key.getAttribute('placeholder')).toBe(`fixture-prote${'•'.repeat(8)}-key`)
|
||||
expect(await key.inputValue()).toBe('')
|
||||
expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0)
|
||||
@@ -155,7 +161,12 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki
|
||||
await expect.poll(() => key.inputValue()).toBe('')
|
||||
await key.fill('fixture-new-key')
|
||||
await dialog.getByRole('button', { name: '保存', exact: true }).click()
|
||||
await expect.poll(() => key.count()).toBe(0)
|
||||
// The editor closes before the save's reload lands, and an Edit press
|
||||
// while the settings snapshot is loading is dropped. The saved notice is
|
||||
// published by that reload's completion, so waiting for it also makes the
|
||||
// reopen below deterministic.
|
||||
await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor()
|
||||
await expect.poll(() => key.count(), { timeout: 10_000 }).toBe(0)
|
||||
await edit.click()
|
||||
expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-new-key'.length))
|
||||
expect(await key.inputValue()).toBe('')
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
// Feishu setup failures and recovery through the real Host/Remote/browser composition.
|
||||
// A stand-in CLI waits for each authorization page visit and keeps account state on disk.
|
||||
import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import type { Browser, BrowserContext, Page } from 'playwright'
|
||||
import { chromium } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
|
||||
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
|
||||
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
|
||||
|
||||
const FEISHU_DIR = fileURLToPath(new URL('../../../packages/connector/feishu', import.meta.url))
|
||||
const SETUP_URL = 'https://open.feishu.cn/page/cli?e2e=1'
|
||||
const SETUP_RETRY_URL = `${SETUP_URL}&retry=1`
|
||||
const SIGN_IN_URL = 'https://accounts.feishu.cn/oauth/device?e2e=1'
|
||||
|
||||
// The stand-in keeps its account in state.json beside itself; app setup and
|
||||
// sign-in wait until the test marks their page visited.
|
||||
const LARK_CLI = `#!/usr/bin/env node
|
||||
const { existsSync, readFileSync, writeFileSync } = require('node:fs')
|
||||
const { join } = require('node:path')
|
||||
const dir = __dirname
|
||||
const statePath = join(dir, 'state.json')
|
||||
const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : { app: false, user: false }
|
||||
const save = () => { writeFileSync(statePath, JSON.stringify(state)) }
|
||||
const visited = (name, done) => {
|
||||
const poll = setInterval(() => {
|
||||
if (!existsSync(join(dir, name))) return
|
||||
clearInterval(poll)
|
||||
done()
|
||||
}, 50)
|
||||
}
|
||||
const line = (value) => { process.stdout.write(JSON.stringify(value) + '\\n') }
|
||||
switch (process.argv.slice(2).join(' ')) {
|
||||
case 'auth status --verify --json':
|
||||
if (!state.app) {
|
||||
process.stderr.write(JSON.stringify({ ok: false, error: { type: 'config', subtype: 'not_configured' } }))
|
||||
process.exitCode = 3
|
||||
} else if (!state.user) line({ appId: 'cli_e2e', identities: { user: { status: 'missing', available: false } } })
|
||||
else line({ appId: 'cli_e2e', identities: { user: { status: 'ready', available: true, verified: true, userName: '测试用户', openId: 'ou_e2e' } } })
|
||||
break
|
||||
case 'config init --new':
|
||||
process.stderr.write('Open this link to create an app:\\n ' + (existsSync(join(dir, 'setup-fails')) ? '${SETUP_URL}' : '${SETUP_RETRY_URL}') + '\\n')
|
||||
visited('setup-visited', () => {
|
||||
if (existsSync(join(dir, 'setup-fails'))) {
|
||||
process.stderr.write('OK: App configured!\\n' + JSON.stringify({ ok: false, error: {
|
||||
type: 'internal', subtype: 'sdk_error',
|
||||
message: 'keychain Set failed: /private/user/appsecret.enc.tmp: operation not permitted; token=fixture-secret',
|
||||
hint: 'https://open.feishu.cn/page/cli?user_code=fixture-code',
|
||||
} }, null, 2) + '\\n')
|
||||
process.exitCode = 5
|
||||
} else { state.app = true; save() }
|
||||
})
|
||||
break
|
||||
case 'auth login --json':
|
||||
line({ event: 'device_authorization', verification_uri_complete: '${SIGN_IN_URL}' })
|
||||
visited('sign-in-visited', () => { state.user = true; save(); line({ event: 'authorization_complete', user_open_id: 'ou_e2e', missing: [] }) })
|
||||
break
|
||||
case 'auth logout --json': state.user = false; save(); line({ ok: true }); break
|
||||
default:
|
||||
process.stderr.write('unexpected lark-cli arguments: ' + process.argv.slice(2).join(' ') + '\\n')
|
||||
process.exitCode = 1
|
||||
}
|
||||
`
|
||||
|
||||
// The stand-in runs through its shebang, which Windows cannot execute.
|
||||
describe.skipIf(process.platform === 'win32')('web e2e: Feishu plugin connection', () => {
|
||||
let binDir: string
|
||||
let scaffold: WebScaffold
|
||||
let browser: Browser
|
||||
let context: BrowserContext
|
||||
let page: Page
|
||||
let tripwire: ReturnType<typeof watchConsole>
|
||||
|
||||
beforeAll(async () => {
|
||||
binDir = await mkdtemp(join(tmpdir(), 'dsh-feishu-e2e-'))
|
||||
await writeFile(join(binDir, 'lark-cli'), LARK_CLI)
|
||||
await chmod(join(binDir, 'lark-cli'), 0o755)
|
||||
const overlay = join(binDir, 'feishu.overlay.yml')
|
||||
await writeFile(overlay, `- id: feishu\n config:\n binDir: ${JSON.stringify(binDir)}\n`)
|
||||
scaffold = await launchWebScaffold({
|
||||
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
|
||||
profile: { packages: [{ dir: FEISHU_DIR, enabled: true }] },
|
||||
})
|
||||
browser = await chromium.launch()
|
||||
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
|
||||
for (const [url, marker] of [[SETUP_URL, 'setup-visited'], [SETUP_RETRY_URL, 'setup-visited'], [SIGN_IN_URL, 'sign-in-visited']] as const) {
|
||||
await context.route(url, async (route) => {
|
||||
await writeFile(join(binDir, marker), '')
|
||||
await route.fulfill({ contentType: 'text/html; charset=utf-8', body: '<!doctype html><title>Feishu</title><p>Feishu stand-in page</p>' })
|
||||
})
|
||||
}
|
||||
page = await context.newPage()
|
||||
tripwire = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await browser?.close()
|
||||
await scaffold?.close()
|
||||
if (binDir !== undefined) await rm(binDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('reports failed local setup, then links an existing app, signs in, and signs out', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-feishu-connection'))
|
||||
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
|
||||
const panel = page.locator('[data-plugin-panel]')
|
||||
await panel.getByRole('button', { name: '查看 飞书插件', exact: true }).click({ timeout: 20_000 })
|
||||
const section = panel.locator('[data-connector-account-key="@deepseek-ai/dsh-feishu"]')
|
||||
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
|
||||
expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2)
|
||||
|
||||
const opened: Page[] = []
|
||||
context.on('page', (popup) => { opened.push(popup) })
|
||||
await writeFile(join(binDir, 'setup-fails'), '')
|
||||
await section.getByRole('button', { name: '关联飞书应用', exact: true }).click()
|
||||
await section.getByRole('alert').waitFor({ timeout: 20_000 })
|
||||
expect(await section.getAttribute('data-connector-account')).toBe('disconnected')
|
||||
expect(await section.getByRole('alert').innerText()).toContain('config-init · exit 5')
|
||||
expect(await section.getByRole('alert').innerText()).toContain('已有应用')
|
||||
expect(await section.innerText()).not.toContain('fixture-secret')
|
||||
expect(await section.innerText()).not.toContain('fixture-code')
|
||||
expect(await section.innerText()).not.toContain('/private/user')
|
||||
await expect(readFile(join(binDir, 'state.json'), 'utf8')).rejects.toMatchObject({ code: 'ENOENT' })
|
||||
await rm(join(binDir, 'setup-fails'))
|
||||
await rm(join(binDir, 'setup-visited'))
|
||||
await section.getByRole('button', { name: '关联飞书应用', exact: true }).click()
|
||||
await page.getByText('飞书应用已关联,下一步登录飞书账号', { exact: true }).waitFor({ timeout: 20_000 })
|
||||
expect(opened.map(popup => popup.url())).toEqual([SETUP_URL, SETUP_RETRY_URL])
|
||||
await section.getByRole('button', { name: '登录飞书账号', exact: true }).click()
|
||||
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
|
||||
expect(opened.map(popup => popup.url())).toEqual([SETUP_URL, SETUP_RETRY_URL, SIGN_IN_URL])
|
||||
await section.getByText('已登录为 测试用户。可以在对话中直接请 Agent 使用飞书。', { exact: true }).waitFor({ timeout: 10_000 })
|
||||
await page.getByText('飞书已连接', { exact: true }).waitFor({ timeout: 10_000 })
|
||||
|
||||
await section.getByRole('button', { name: '退出登录', exact: true }).click()
|
||||
await page.getByRole('dialog', { name: '退出飞书登录?' }).getByRole('button', { name: '退出登录', exact: true }).click()
|
||||
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
|
||||
await page.getByText('已退出飞书登录', { exact: true }).waitFor({ timeout: 10_000 })
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
// Web e2e scenario: connecting the Linear plugin from its page on the Plugins
|
||||
// page. The section reads the MCP manager's real entry, the browser opens the
|
||||
// loopback authorization server's page, the Host callback answers with its
|
||||
// completion page, the connection reaches the manager, and sign-out returns the
|
||||
// section to disconnected. Zero model calls.
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import type { Browser, BrowserContext, Page } from 'playwright'
|
||||
import { chromium } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
|
||||
import { startLinearOAuthFixture, type LinearOAuthFixture } from './linear-oauth-fixture.ts'
|
||||
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
|
||||
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
|
||||
|
||||
const LINEAR_DIR = fileURLToPath(new URL('../../../packages/connector/linear', import.meta.url))
|
||||
|
||||
describe('web e2e: Linear plugin connection', () => {
|
||||
let fixture: LinearOAuthFixture
|
||||
let overlayDir: string
|
||||
let scaffold: WebScaffold
|
||||
let browser: Browser
|
||||
let context: BrowserContext
|
||||
let page: Page
|
||||
let tripwire: ReturnType<typeof watchConsole>
|
||||
|
||||
beforeAll(async () => {
|
||||
fixture = await startLinearOAuthFixture()
|
||||
overlayDir = await mkdtemp(join(tmpdir(), 'dsh-linear-e2e-'))
|
||||
const overlay = join(overlayDir, 'linear.overlay.yml')
|
||||
await writeFile(overlay, `- id: linear\n config:\n url: ${fixture.origin}/mcp\n`)
|
||||
scaffold = await launchWebScaffold({
|
||||
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
|
||||
profile: { packages: [{ dir: LINEAR_DIR, enabled: true }] },
|
||||
})
|
||||
browser = await chromium.launch()
|
||||
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
|
||||
page = await context.newPage()
|
||||
tripwire = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await browser?.close()
|
||||
await scaffold?.close()
|
||||
await fixture?.close()
|
||||
if (overlayDir !== undefined) await rm(overlayDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('connects the account from the plugin page and signs out after confirmation', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-linear-connection'))
|
||||
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
|
||||
const panel = page.locator('[data-plugin-panel]')
|
||||
await panel.getByRole('button', { name: '查看 Linear 插件', exact: true }).click({ timeout: 20_000 })
|
||||
const section = panel.locator('[data-connector-account]')
|
||||
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
|
||||
expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2)
|
||||
|
||||
const opened = context.waitForEvent('page')
|
||||
await section.getByRole('button', { name: '连接 Linear', exact: true }).click()
|
||||
const authorization = await opened
|
||||
await expect.poll(async () => await authorization.locator('body').textContent(), { timeout: 20_000 })
|
||||
.toContain('已收到授权。可以关闭此页,回到 DSH 查看连接结果。')
|
||||
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
|
||||
await page.getByText('Linear 已连接', { exact: true }).waitFor({ timeout: 10_000 })
|
||||
expect(fixture.authorizations()).toBe(1)
|
||||
await authorization.close()
|
||||
|
||||
await section.getByRole('button', { name: '退出登录', exact: true }).click()
|
||||
await page.getByRole('dialog', { name: '退出 Linear 登录?' }).getByRole('button', { name: '退出登录', exact: true }).click()
|
||||
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(fixture.failures()).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Loopback stand-in for Linear's hosted MCP server: OAuth protected-resource
|
||||
* and authorization-server metadata, dynamic client registration, an
|
||||
* authorization endpoint that approves every request by redirecting straight
|
||||
* back to the caller, a token endpoint, and a Streamable HTTP MCP endpoint
|
||||
* that requires a bearer token this fixture issued and answers JSON-RPC with
|
||||
* plain JSON. The `initialize`, `tools/list`, and `ping` answers are written
|
||||
* by hand because `apps/web` carries no MCP SDK dependency; the scenario only
|
||||
* needs the handshake and the tool listing to succeed.
|
||||
*/
|
||||
import { once } from 'node:events'
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
||||
|
||||
/** The running fixture and what the browser and Host asked of it. */
|
||||
export interface LinearOAuthFixture {
|
||||
/** `http://127.0.0.1:<port>`; the MCP endpoint is `<origin>/mcp`. */
|
||||
readonly origin: string
|
||||
/** Authorization pages the browser opened. */
|
||||
authorizations(): number
|
||||
/** Errors thrown while answering requests, each answered with a 500; the scenario expects none. */
|
||||
failures(): readonly unknown[]
|
||||
/** Stop listening and close open connections. */
|
||||
close(): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen on an OS-assigned loopback port.
|
||||
* @returns the running fixture.
|
||||
*/
|
||||
export async function startLinearOAuthFixture(): Promise<LinearOAuthFixture> {
|
||||
let origin = '', authorizations = 0, tokens = 0, registrations = 0
|
||||
const issued = new Set<string>()
|
||||
const failures: unknown[] = []
|
||||
const json =(response: ServerResponse, value: unknown, status = 200): void => {
|
||||
response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(value))
|
||||
}
|
||||
async function text(request: IncomingMessage): Promise<string> {
|
||||
const chunks: Buffer[] = []
|
||||
for await (const chunk of request) {
|
||||
if (!(chunk instanceof Uint8Array)) throw new Error('Expected request bytes')
|
||||
chunks.push(Buffer.from(chunk))
|
||||
}
|
||||
return Buffer.concat(chunks).toString()
|
||||
}
|
||||
async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
||||
const url = new URL(request.url!, origin)
|
||||
if (url.pathname.startsWith('/.well-known/oauth-protected-resource')) {
|
||||
json(response, { resource: origin + '/mcp', authorization_servers: [origin] })
|
||||
} else if (url.pathname === '/.well-known/oauth-authorization-server') {
|
||||
json(response, {
|
||||
issuer: origin, authorization_endpoint: origin + '/authorize', token_endpoint: origin + '/token',
|
||||
registration_endpoint: origin + '/register', response_types_supported: ['code'],
|
||||
grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'],
|
||||
token_endpoint_auth_methods_supported: ['none'], authorization_response_iss_parameter_supported: true,
|
||||
})
|
||||
} else if (url.pathname === '/register') {
|
||||
registrations++
|
||||
const metadata = JSON.parse(await text(request)) as Record<string, unknown>
|
||||
json(response, { ...metadata, client_id: 'linear-client-' + String(registrations), token_endpoint_auth_method: 'none' }, 201)
|
||||
} else if (url.pathname === '/authorize') {
|
||||
authorizations++
|
||||
const callback = new URL(url.searchParams.get('redirect_uri')!)
|
||||
callback.searchParams.set('code', 'linear-code-' + String(authorizations))
|
||||
callback.searchParams.set('state', url.searchParams.get('state')!)
|
||||
callback.searchParams.set('iss', origin)
|
||||
response.writeHead(302, { location: callback.href }).end()
|
||||
} else if (url.pathname === '/token') {
|
||||
await text(request)
|
||||
tokens++
|
||||
const token = 'linear-access-' + String(tokens)
|
||||
issued.add(token)
|
||||
json(response, { access_token: token, refresh_token: 'linear-refresh-' + String(tokens), token_type: 'Bearer', expires_in: 3600 })
|
||||
} else if (url.pathname === '/mcp') {
|
||||
const token = request.headers.authorization?.replace(/^Bearer /u, '')
|
||||
if (token === undefined || !issued.has(token)) {
|
||||
response.writeHead(401, { 'www-authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"` }).end()
|
||||
} else await answerMcp(request, response)
|
||||
} else response.writeHead(404).end()
|
||||
}
|
||||
async function answerMcp(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
||||
if (request.method !== 'POST') { response.writeHead(405).end(); return }
|
||||
const message = JSON.parse(await text(request)) as { id?: number | string; method: string; params?: { protocolVersion?: string } }
|
||||
if (message.id === undefined) { response.writeHead(202).end(); return }
|
||||
const reply = (result: unknown): void => { json(response, { jsonrpc: '2.0', id: message.id, result }) }
|
||||
switch (message.method) {
|
||||
case 'initialize':
|
||||
reply({ protocolVersion: message.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'linear-fixture', version: '1.0.0' } })
|
||||
break
|
||||
case 'tools/list':
|
||||
reply({ tools: [{ name: 'linear-search', description: 'Search the fixture workspace.', inputSchema: { type: 'object', properties: {} } }] })
|
||||
break
|
||||
case 'ping': reply({}); break
|
||||
default: json(response, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } })
|
||||
}
|
||||
}
|
||||
const server = createServer((request, response) => {
|
||||
handle(request, response).catch((error: unknown) => {
|
||||
failures.push(error)
|
||||
if (!response.headersSent) response.writeHead(500).end()
|
||||
})
|
||||
})
|
||||
server.listen(0, '127.0.0.1')
|
||||
await once(server, 'listening')
|
||||
const address = server.address()
|
||||
if (address === null || typeof address === 'string') throw new Error('Linear OAuth fixture did not bind TCP')
|
||||
origin = `http://127.0.0.1:${String(address.port)}`
|
||||
return {
|
||||
origin,
|
||||
authorizations: () => authorizations,
|
||||
failures: () => failures,
|
||||
close: async () => {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => { if (error === undefined) resolve(); else reject(error) })
|
||||
server.closeAllConnections()
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Web e2e scenario: connecting the Notion plugin from its page on the Plugins
|
||||
// page. The section reads the MCP manager's real entry, the browser opens the
|
||||
// loopback authorization server's page, the Host callback answers with its
|
||||
// completion page, the connection reaches the manager, and sign-out returns the
|
||||
// section to disconnected. Zero model calls.
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import type { Browser, BrowserContext, Page } from 'playwright'
|
||||
import { chromium } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
|
||||
import { startNotionOAuthFixture, type NotionOAuthFixture } from './notion-oauth-fixture.ts'
|
||||
import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts'
|
||||
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
|
||||
|
||||
const NOTION_DIR = fileURLToPath(new URL('../../../packages/connector/notion', import.meta.url))
|
||||
|
||||
describe('web e2e: Notion plugin connection', () => {
|
||||
let fixture: NotionOAuthFixture
|
||||
let overlayDir: string
|
||||
let scaffold: WebScaffold
|
||||
let browser: Browser
|
||||
let context: BrowserContext
|
||||
let page: Page
|
||||
let tripwire: ReturnType<typeof watchConsole>
|
||||
|
||||
beforeAll(async () => {
|
||||
fixture = await startNotionOAuthFixture()
|
||||
overlayDir = await mkdtemp(join(tmpdir(), 'dsh-notion-e2e-'))
|
||||
const overlay = join(overlayDir, 'notion.overlay.yml')
|
||||
await writeFile(overlay, `- id: notion\n config:\n url: ${fixture.origin}/mcp\n`)
|
||||
scaffold = await launchWebScaffold({
|
||||
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
|
||||
profile: { packages: [{ dir: NOTION_DIR, enabled: true }] },
|
||||
})
|
||||
browser = await chromium.launch()
|
||||
context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
|
||||
page = await context.newPage()
|
||||
tripwire = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await browser?.close()
|
||||
await scaffold?.close()
|
||||
await fixture?.close()
|
||||
if (overlayDir !== undefined) await rm(overlayDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('connects the account from the plugin page and signs out after confirmation', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-notion-connection'))
|
||||
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
|
||||
const panel = page.locator('[data-plugin-panel]')
|
||||
await panel.getByRole('button', { name: '查看 Notion 插件', exact: true }).click({ timeout: 20_000 })
|
||||
const section = panel.locator('[data-connector-account]')
|
||||
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
|
||||
expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2)
|
||||
|
||||
const opened = context.waitForEvent('page')
|
||||
await section.getByRole('button', { name: '连接 Notion', exact: true }).click()
|
||||
const authorization = await opened
|
||||
await expect.poll(async () => await authorization.locator('body').textContent(), { timeout: 20_000 })
|
||||
.toContain('已收到授权。可以关闭此页,回到 DSH 查看连接结果。')
|
||||
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected')
|
||||
await page.getByText('Notion 已连接', { exact: true }).waitFor({ timeout: 10_000 })
|
||||
expect(fixture.authorizations()).toBe(1)
|
||||
await authorization.close()
|
||||
|
||||
await section.getByRole('button', { name: '退出登录', exact: true }).click()
|
||||
await page.getByRole('dialog', { name: '退出 Notion 登录?' }).getByRole('button', { name: '退出登录', exact: true }).click()
|
||||
await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected')
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Loopback stand-in for Notion's hosted MCP server: OAuth protected-resource
|
||||
* and authorization-server metadata, dynamic client registration, an
|
||||
* authorization endpoint that approves every request by redirecting straight
|
||||
* back to the caller, a token endpoint, and a Streamable HTTP MCP endpoint
|
||||
* that requires the issued bearer token and answers JSON-RPC with plain JSON.
|
||||
*/
|
||||
import { once } from 'node:events'
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
||||
|
||||
/** The running fixture and what the browser and Host asked of it. */
|
||||
export interface NotionOAuthFixture {
|
||||
/** `http://127.0.0.1:<port>`; the MCP endpoint is `<origin>/mcp`. */
|
||||
readonly origin: string
|
||||
/** Authorization pages the browser opened. */
|
||||
authorizations(): number
|
||||
/** Stop listening and close open connections. */
|
||||
close(): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen on an OS-assigned loopback port.
|
||||
* @returns the running fixture.
|
||||
*/
|
||||
export async function startNotionOAuthFixture(): Promise<NotionOAuthFixture> {
|
||||
let origin = '', authorizations = 0, tokens = 0, registrations = 0
|
||||
const json = (response: ServerResponse, value: unknown, status = 200): void => {
|
||||
response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(value))
|
||||
}
|
||||
async function text(request: IncomingMessage): Promise<string> {
|
||||
const chunks: Buffer[] = []
|
||||
for await (const chunk of request) {
|
||||
if (!(chunk instanceof Uint8Array)) throw new Error('Expected request bytes')
|
||||
chunks.push(Buffer.from(chunk))
|
||||
}
|
||||
return Buffer.concat(chunks).toString()
|
||||
}
|
||||
async function handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
||||
const url = new URL(request.url!, origin)
|
||||
if (url.pathname.startsWith('/.well-known/oauth-protected-resource')) {
|
||||
json(response, { resource: origin + '/mcp', authorization_servers: [origin] })
|
||||
} else if (url.pathname === '/.well-known/oauth-authorization-server') {
|
||||
json(response, {
|
||||
issuer: origin, authorization_endpoint: origin + '/authorize', token_endpoint: origin + '/token',
|
||||
registration_endpoint: origin + '/register', response_types_supported: ['code'],
|
||||
grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'],
|
||||
token_endpoint_auth_methods_supported: ['none'], authorization_response_iss_parameter_supported: true,
|
||||
})
|
||||
} else if (url.pathname === '/register') {
|
||||
registrations++
|
||||
const metadata = JSON.parse(await text(request)) as Record<string, unknown>
|
||||
json(response, { ...metadata, client_id: 'notion-client-' + String(registrations), token_endpoint_auth_method: 'none' }, 201)
|
||||
} else if (url.pathname === '/authorize') {
|
||||
authorizations++
|
||||
const callback = new URL(url.searchParams.get('redirect_uri')!)
|
||||
callback.searchParams.set('code', 'notion-code-' + String(authorizations))
|
||||
callback.searchParams.set('state', url.searchParams.get('state')!)
|
||||
callback.searchParams.set('iss', origin)
|
||||
response.writeHead(302, { location: callback.href }).end()
|
||||
} else if (url.pathname === '/token') {
|
||||
await text(request)
|
||||
tokens++
|
||||
json(response, { access_token: 'notion-access-' + String(tokens), refresh_token: 'notion-refresh-' + String(tokens), token_type: 'Bearer', expires_in: 3600 })
|
||||
} else if (url.pathname === '/mcp') {
|
||||
if (request.headers.authorization === undefined) {
|
||||
response.writeHead(401, { 'www-authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"` }).end()
|
||||
} else await answerMcp(request, response)
|
||||
} else response.writeHead(404).end()
|
||||
}
|
||||
async function answerMcp(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
||||
if (request.method !== 'POST') { response.writeHead(405).end(); return }
|
||||
const message = JSON.parse(await text(request)) as { id?: number | string; method: string; params?: { protocolVersion?: string } }
|
||||
if (message.id === undefined) { response.writeHead(202).end(); return }
|
||||
const reply = (result: unknown): void => { json(response, { jsonrpc: '2.0', id: message.id, result }) }
|
||||
switch (message.method) {
|
||||
case 'initialize':
|
||||
reply({ protocolVersion: message.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'notion-fixture', version: '1.0.0' } })
|
||||
break
|
||||
case 'tools/list':
|
||||
reply({ tools: [{ name: 'notion-search', description: 'Search the fixture workspace.', inputSchema: { type: 'object', properties: {} } }] })
|
||||
break
|
||||
case 'ping': reply({}); break
|
||||
default: json(response, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } })
|
||||
}
|
||||
}
|
||||
const server = createServer((request, response) => {
|
||||
handle(request, response).catch(() => { if (!response.headersSent) response.writeHead(500).end() })
|
||||
})
|
||||
server.listen(0, '127.0.0.1')
|
||||
await once(server, 'listening')
|
||||
const address = server.address()
|
||||
if (address === null || typeof address === 'string') throw new Error('Notion OAuth fixture did not bind TCP')
|
||||
origin = `http://127.0.0.1:${String(address.port)}`
|
||||
return {
|
||||
origin,
|
||||
authorizations: () => authorizations,
|
||||
close: async () => {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => { if (error === undefined) resolve(); else reject(error) })
|
||||
server.closeAllConnections()
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -167,18 +167,33 @@ describe('web e2e: plugin configuration pages', () => {
|
||||
await expect.poll(() => page.getByRole('menuitem').count()).toBe(0)
|
||||
return items
|
||||
}
|
||||
// The shipped composition selects the DeepSeek Search API and local fetch, and the page writes nothing on mount.
|
||||
expect(await searchMenu.textContent()).toBe('DeepSeek Search API')
|
||||
// The shipped composition selects no search provider and local fetch, and the page writes nothing on mount.
|
||||
expect(await searchMenu.textContent()).toBe('自动选择')
|
||||
expect(await fetchMenu.textContent()).toBe('本机直接获取')
|
||||
expect(await panel.getByRole('button', { name: '网页搜索提供方 DeepSeek Search API', exact: true }).count()).toBe(1)
|
||||
expect(await panel.getByRole('button', { name: '网页搜索提供方 自动选择', exact: true }).count()).toBe(1)
|
||||
expect(await panel.getByRole('button', { name: '网页获取提供方 本机直接获取', exact: true }).count()).toBe(1)
|
||||
expect(await entries(searchMenu)).toEqual(['DeepSeek Search API', 'DeepSeek(旧版)'])
|
||||
expect(await entries(searchMenu)).toEqual(['自动选择', 'DeepSeek Search API', 'DeepSeek 服务端搜索'])
|
||||
expect(await entries(fetchMenu)).toEqual(['本机直接获取', 'DeepSeek Fetch API'])
|
||||
expect(await settingsDocument()).not.toContain('searchProvider:')
|
||||
// The page fixes the menu order itself; the Loader imports plugins concurrently, so the
|
||||
// Host's registration order is not the YAML row order and only its membership is checked here.
|
||||
const hostWeb = scaffold.ctx.get('web') as { listProviders(): Record<'search' | 'fetch', { id: string }[]> } | undefined
|
||||
expect(hostWeb?.listProviders().search.map(provider => provider.id).sort()).toEqual(['deepseek-official', 'deepseek-search-api'])
|
||||
// Automatic selection states which provider the Host runs for each model and shows no provider panel.
|
||||
expect(await searchSection.getByText(
|
||||
'跟随当前会话的模型:DeepSeek 模型使用 DeepSeek 服务端搜索,搜索不按次收费;其他模型使用 DeepSeek Search API。', { exact: true },
|
||||
).count()).toBe(1)
|
||||
expect(await searchSection.getByRole('link', { name: '网页搜索与获取指南', exact: true }).getAttribute('href'))
|
||||
.toBe('https://api-docs.deepseek.com/zh-cn/guides/search')
|
||||
expect(await searchSection.getByRole('textbox').count()).toBe(0)
|
||||
expect(await save.isDisabled()).toBe(true)
|
||||
|
||||
// The composition names no search provider, so a selected one is stored.
|
||||
await choose(searchMenu, 'DeepSeek Search API')
|
||||
await save.click()
|
||||
await expect.poll(() => save.isDisabled()).toBe(true)
|
||||
await expect.poll(settingsDocument).toContain('searchProvider: deepseek-search-api')
|
||||
expect(await panel.getByRole('button', { name: '网页搜索提供方 DeepSeek Search API', exact: true }).count()).toBe(1)
|
||||
expect(await panel.getByRole('link', { name: '网页搜索与获取指南', exact: true }).getAttribute('href'))
|
||||
.toBe('https://api-docs.deepseek.com/zh-cn/guides/search')
|
||||
// Each section shows the description its selected provider registered with the Host, in the active language.
|
||||
@@ -230,7 +245,7 @@ describe('web e2e: plugin configuration pages', () => {
|
||||
await expect.poll(() => save.isDisabled()).toBe(true)
|
||||
await expect.poll(settingsDocument).not.toContain('fetchProvider: deepseek-fetch-api')
|
||||
|
||||
await choose(searchMenu, 'DeepSeek(旧版)')
|
||||
await choose(searchMenu, 'DeepSeek 服务端搜索')
|
||||
const messagesEndpoint = panel.locator('#plugin-config-web-search-endpoint')
|
||||
expect(await panel.getByLabel('单次请求最多搜索次数', { exact: true }).inputValue()).toBe('5')
|
||||
await messagesEndpoint.fill('https://messages.test/anthropic/v1')
|
||||
@@ -241,17 +256,23 @@ describe('web e2e: plugin configuration pages', () => {
|
||||
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
|
||||
await openPlugins()
|
||||
await openPage(panel, '网页搜索与获取')
|
||||
expect(await searchMenu.textContent()).toBe('DeepSeek(旧版)')
|
||||
expect(await searchMenu.textContent()).toBe('DeepSeek 服务端搜索')
|
||||
expect(await messagesEndpoint.inputValue()).toBe('https://messages.test/anthropic/v1')
|
||||
expect(await entries(searchMenu)).toEqual(['DeepSeek Search API', 'DeepSeek(旧版)'])
|
||||
expect(await entries(searchMenu)).toEqual(['自动选择', 'DeepSeek Search API', 'DeepSeek 服务端搜索'])
|
||||
expect(await save.isDisabled()).toBe(true)
|
||||
expect(await settingsDocument()).toContain('searchProvider: deepseek-official')
|
||||
await choose(searchMenu, 'DeepSeek Search API')
|
||||
await count.fill('20')
|
||||
await save.click()
|
||||
await expect.poll(() => save.isDisabled()).toBe(true)
|
||||
await expect.poll(settingsDocument).not.toContain('searchProvider:')
|
||||
await expect.poll(settingsDocument).toContain('searchProvider: deepseek-search-api')
|
||||
expect(await settingsDocument()).toContain('count: 20')
|
||||
// Automatic selection clears the stored provider.
|
||||
await choose(searchMenu, '自动选择')
|
||||
await save.click()
|
||||
await expect.poll(() => save.isDisabled()).toBe(true)
|
||||
await expect.poll(settingsDocument).not.toContain('searchProvider:')
|
||||
expect(await searchMenu.textContent()).toBe('自动选择')
|
||||
expect(await settingsDocument()).not.toMatch(/ApiKeyEnv:|searchBaseURL:|fetchBaseURL:/)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
})
|
||||
|
||||
@@ -843,7 +843,11 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
|
||||
throw new Error(`web e2e scaffold: the web app requested exit ${String(code)} with no arguments to reject`)
|
||||
},
|
||||
})
|
||||
const resolution = await createRuntimeResolution(resolutionOptions)
|
||||
// Like the launcher, resolve the dependencies of every selected bundle, not only the extra install anchors.
|
||||
const selectedLayers = loadProfileDirectory('dsh', profileDir, INSTALL_ANCHOR).layers
|
||||
const resolution = await createRuntimeResolution({
|
||||
...resolutionOptions, profile: { ...profile, layers: [...profile.layers, ...selectedLayers] },
|
||||
})
|
||||
await ctx.plugin(PluginPackages, {
|
||||
resolution,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
# The replayed conversation runs on a DeepSeek model route, where an unconfigured search selects
|
||||
# legacy Messages search. This scenario exercises the DeepSeek Search API.
|
||||
- id: web
|
||||
config:
|
||||
searchProvider: deepseek-search-api
|
||||
fetchProvider: http
|
||||
Loaded 100 of 1094 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user