@nimoxie/dsh-ui-tweaks 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,1214 +1,1330 @@
1
- /**
2
- * dsh-ui-tweaks host half.
3
- *
4
- * 回环路由(只放行 127.0.0.1 / ::1;写操作集中在这里,客户端半区调它们):
5
- * - GET /local-plugins:profile 里非 registry 直装的包名 + 运行中的 DSH 版本。
6
- * 客户端据此把「本地链接 / Git 直装」标出来并跳过 registry 比对,也用来判「DSH 不符」。
7
- * - POST /normalize-excludes:手动归并豁免表(加载时也会静默跑一次)。
8
- * - POST /precheck-exempt:强制更新前的预检(列出仍在冷静期、会拦住这次安装的包)。
9
- * - POST /force-exempt:把 name@version 写成豁免表里该包生效的第一条。
10
- * - POST /schedule-exempt-cleanup:登记「到期自动删豁免」(版本满 24h 后清掉)。
11
- * - POST /open-path:打开 / 显示位置 / 用指定应用打开(会话释放后改动卡的动作补位);
12
- * action:"probe" 只诊断子进程能不能起,不弹窗。
13
- * - POST /open-apps:系统文件关联枚举(同上,供「打开方式」菜单)。
14
- * - GET|POST /restart:GET 只读重启方案(shell / relaunch / manual),POST 才执行。
15
- * 故意拆两个方法:GET 无副作用,预取或直粘 URL 都不会把宿主停掉(见文末「模块 7」)。
16
- *
17
- * profile 的 pnpm-workspace.yaml 写入(全文件只此一处):归并 minimumReleaseAgeExclude
18
- * 序列。为什么必须收敛:
19
- * DSH 给自带 pnpm 11.7.0 注入供应链策略 minimumReleaseAge=1440(分钟,不在任何配置文件里),
20
- * pnpm 在解析之前先校验磁盘上现有的 lockfile,任一 entry 未成熟即整体中止安装并报
21
- * ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION(exit 1);而该白名单按包名匹配,同一个包名出现
22
- * 多条时「文件中靠前的那条生效」。于是同包重复/陈旧条目会静默抵消掉真正需要的豁免
23
- * (例:dsh-context@0.61.0 陈旧条排在 dsh-context@0.69.0 前面,后者从未生效),
24
- * 之后 profile 的每一次安装都失败;而一次成功的「未成熟版本」安装又会把新条目追加到
25
- * 末尾,让旧条重新变成靠前那条 —— 紧接着的下一次安装立刻 FAIL。所以这必须常态化自动收敛。
26
- * 安全约束:只改这一个序列,其余字节逐字节保持原样;写前备份
27
- * pnpm-workspace.yaml.bak-<时间戳>;同目录临时文件 + renameSync 原子替换;写后重读校验;
28
- * 无变化不写文件;幂等;结果永远是原条目的子集(绝不比现状更宽松);陈旧剪除只针对
29
- * profile dependencies 里的受管包名,重复折叠适用于任何包名;裸名(不带 @版本)豁免该包
30
- * 全部版本,永不视为陈旧。整个过程不外抛异常。仅回环访问放行。
31
- *
32
- * 模块 6:官方桌面客户端的窗口记忆(记住主窗口上次的大小/位置/最大化状态)。
33
- * 官方主进程写死 1280x820 且无任何窗口状态持久化;渲染层被官方沙箱焊死
34
- * (contextIsolation+sandbox,dshDesktop 桥只暴露给 dsh-app://app 主框架),
35
- * 页面里拿不到任何窗口能力,所以这条路走插件服务端 + 进程外 Win32:
36
- * spawn 一个隐藏 PowerShell helper(lib/window-helper.ps1),沿父进程链找到
37
- * DeepSeek Harness.exe 的主窗口。实测客户端在插件加载前就已把窗口 show 出来,
38
- * 隐藏期无感还原做不到,可达的是窗口出现后 ~0.2s 内归位(肉眼基本无感,且
39
- * 先于任何插件 UI 打开);之后每秒采样 GetWindowPlacement 持久化。
40
- * 仅 Windows + ELECTRON_RUN_AS_NODE=1(官方客户端内的 dsh 运行时)时激活;
41
- * web profile / dsh-web-shell 下自动不动作。文件落 profile 的 ui-tweaks/ 子目录。
42
- *
43
- * 模块 7:立即重启(让刚装上的插件代码在下一次启动被加载)。
44
- * 参考 @linxin666/dsh-client-ui-plugin-manager 的三段式:只读方案 → 二次确认 → 执行。
45
- * 复用它的三条经验(都是真机踩出来的):① 方案按运行形态分三种 —— 打包桌面端由
46
- * Electron 外壳管进程树,插件重启不了它,只能自己退出、等外壳弹它自己的重启对话框
47
- * (shell);终端里跑的 dsh 用 detached 助手按原命令行重拉(relaunch,剔除 --inspect
48
- * 之类会重新绑定端口的开关);被监督/无 TTY 的进程不动,如实报 manual。② relaunch 起
49
- * 不了助手时退化为 manual —— 绝不在无法重拉的情况下把进程停掉。③ 重启前先 GET 读方案,
50
- * 让确认面板说的后果与实际执行一致。
51
- */
52
- import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
53
- import { homedir, tmpdir } from "node:os";
54
- import { dirname, join, basename } from "node:path";
55
- import { fileURLToPath, pathToFileURL } from "node:url";
56
- import { spawn, spawnSync } from "node:child_process";
57
-
58
- export const name = "ui-tweaks";
59
- export const inject = ["webServer"];
60
-
61
- const SELF = "@nimoxie/dsh-ui-tweaks";
62
- const LOCAL_SPEC_RE = /^(link:|file:)/; // 本地路径(link:→按包名查 node_modules)
63
- const REMOTE_SPEC_RE = /^(git[+:@]|github:|git:|http)/; // Git 仓库 / URL 直装
64
- const LOOPBACK_RE = /^(127\.|::1$|::ffff:127\.)/;
65
- const EXCLUDE_KEY = "minimumReleaseAgeExclude";
66
- const WORKSPACE_FILE = "pnpm-workspace.yaml";
67
-
68
- function readJson(p) {
69
- try { return JSON.parse(readFileSync(p, "utf8")); } catch { return null; }
70
- }
71
-
72
- function hasUs(m) {
73
- return !!(m && m.dsh && m.dsh.profile && Array.isArray(m.dsh.profile.bundles) && m.dsh.profile.bundles.includes(SELF));
74
- }
75
-
76
- function findProfileDir() {
77
- // ① npm 直装:包物理位于 profile/node_modules 内,向上走必经 profile 根
78
- // (profile 根 package.json 的判据是 dsh.profile.bundles 且包含本插件)。
79
- let dir = dirname(dirname(fileURLToPath(import.meta.url)));
80
- for (let depth = 0; depth < 8; depth++) {
81
- const m = readJson(join(dir, "package.json"));
82
- if (hasUs(m)) { return dir; }
83
- const parent = dirname(dir);
84
- if (parent === dir) { break; }
85
- dir = parent;
86
- }
87
- // ② link: 软链安装:Node 默认把 ESM 模块解析到真实路径,import.meta.url
88
- // 指向 profile 外的仓库目录,①必然失败。退回扫描 profiles/*:
89
- // DSH_HOME 环境变量 → 用户主目录默认 .dsh(dsh 未设环境变量时的标准位置)。
90
- // 多个 profile 都装了本插件时按 host 进程形态二选一
91
- // (桌面 host 跑在 ELECTRON_RUN_AS_NODE=1 的 Electron Node 下)。
92
- const homes = [process.env.DSH_HOME, join(homedir(), ".dsh")].filter(Boolean);
93
- let hits = [];
94
- for (const home of homes) {
95
- try {
96
- for (const entry of readdirSync(join(home, "profiles"))) {
97
- const dir2 = join(home, "profiles", entry);
98
- if (hasUs(readJson(join(dir2, "package.json")))) { hits.push(dir2); }
99
- }
100
- } catch { /* 该 home 不存在或不可读,试下一个 */ }
101
- if (hits.length) { break; }
102
- }
103
- if (hits.length === 0) { return null; }
104
- if (hits.length === 1) { return hits[0]; }
105
- const wanted = process.env.ELECTRON_RUN_AS_NODE === "1" ? "desktop" : "web";
106
- return hits.find((d) => new RegExp(wanted + "$").test(d)) || hits[0];
107
- }
108
-
109
- // ---------- minimumReleaseAgeExclude 归并 ----------
110
-
111
- /** yaml 标量去引号:'x' / "x" → x,其余原样 */
112
- function unquote(s) {
113
- const m = /^(['"])([\s\S]*)\1$/.exec(s);
114
- return m ? m[2] : s;
115
- }
116
-
117
- /**
118
- * YAML 标量输出:plain scalar **不能**以 `@` / `` ` `` 等指示符开头,而 scoped 包名
119
- * (@scope/pkg@1.2.3)全以 @ 开头 —— 直接裸写会让整个 pnpm-workspace.yaml 解析失败
120
- * (pnpm 报 bad indentation of a sequence entry),profile 里所有 pnpm 操作全挂。
121
- * 安全字符集以外的值一律用单引号包起来(内部单引号翻倍)。
122
- */
123
- function yamlScalar(value) {
124
- const s = String(value);
125
- if (/^[A-Za-z0-9_][A-Za-z0-9._~\/@+-]*$/.test(s)) { return s; }
126
- return "'" + s.replace(/'/g, "''") + "'";
127
- }
128
-
129
- /** 条目原文 → 裸值:去空白、去行尾注释、去引号 */
130
- function entryValue(raw) {
131
- const s = String(raw).trim();
132
- const quoted = unquote(s);
133
- if (quoted !== s) { return quoted; } // 整段就是带引号的标量
134
- const i = s.indexOf(" #"); // 裸标量后跟注释
135
- return i < 0 ? s : unquote(s.slice(0, i).trim());
136
- }
137
-
138
- /** 版本键里的 'name@version' → {name, version}(scoped 与裸名都要能分) */
139
- function splitNameVersion(s) {
140
- const at = s.startsWith("@") ? s.indexOf("@", 1) : s.indexOf("@");
141
- if (at <= 0) { return { name: s, version: null }; }
142
- return { name: s.slice(0, at), version: s.slice(at + 1) || null };
143
- }
144
-
145
- /** '1.2.3(peer@x)' → '1.2.3';link:/file:/workspace: 协议没有版本概念 → undefined */
146
- function cleanVersion(v) {
147
- const s = String(v || "").trim().replace(/\([\s\S]*$/, "").replace(/^['"]|['"]$/g, "");
148
- if (!s || /^(link:|file:|workspace:)/.test(s)) { return undefined; }
149
- return s;
150
- }
151
-
152
- /**
153
- * 从 pnpm-lock.yaml 取两张表:
154
- * importers = profile 自己声明的直连依赖(面板管的那些插件)
155
- * all = importers 覆盖后的全量(含传递依赖)
156
- * link:/file:/workspace: 这类没有发布版本的条目不进表(查询得到 undefined = 未锁定)。
157
- */
158
- function parseLockMaps(text) {
159
- const fromImporters = new Map();
160
- const fromPackages = new Map();
161
- let section = null;
162
- let inImporterDeps = false;
163
- let pendingName = null;
164
- for (const line of String(text).split(/\r?\n/)) {
165
- const top = /^([A-Za-z][\w-]*):\s*$/.exec(line); // 缩进 0 的顶层段落
166
- if (top) { section = top[1]; inImporterDeps = false; pendingName = null; continue; }
167
- if (section === "importers") {
168
- if (/^ {4}(?:dependencies|devDependencies|optionalDependencies):\s*$/.test(line)) { inImporterDeps = true; continue; }
169
- if (/^ {2,4}\S/.test(line)) { inImporterDeps = false; continue; } // 换 importer / 换字段
170
- if (inImporterDeps) {
171
- const k = /^ {6}(\S[\s\S]*?):\s*$/.exec(line);
172
- if (k) { pendingName = unquote(k[1]); continue; }
173
- const v = /^ {8}version:\s*(\S+)\s*$/.exec(line);
174
- if (v && pendingName) {
175
- const ver = cleanVersion(v[1]);
176
- if (ver) { fromImporters.set(pendingName, ver); }
177
- pendingName = null;
178
- continue;
179
- }
180
- }
181
- } else if (section === "packages") {
182
- const k = /^ {2}(\S[\s\S]*?):\s*$/.exec(line); // 'name@version':
183
- if (k) {
184
- const p = splitNameVersion(unquote(k[1]));
185
- const ver = p.version && cleanVersion(p.version);
186
- if (ver) { fromPackages.set(p.name, ver); }
187
- }
188
- }
189
- }
190
- const out = new Map(fromPackages);
191
- for (const [k, v] of fromImporters) { out.set(k, v); }
192
- return { all: out, importers: fromImporters };
193
- }
194
-
195
- /** 兼容入口:全量映射(归并器用) */
196
- function parseLockVersions(text) {
197
- return parseLockMaps(text).all;
198
- }
199
-
200
- /**
201
- * 归并 profile pnpm-workspace.yaml 的 minimumReleaseAgeExclude 序列。
202
- * 只重排这一段的条目行,其余字节逐字节保留;无变化不写盘。
203
- * 任何异常都被吞掉,返回 {ok:false, code}。
204
- * dirOverride 只给测试用(指向临时目录),生产走 findProfileDir()。
205
- */
206
- export function normalizeReleaseAgeExcludes(dirOverride) {
207
- let backup = null;
208
- try {
209
- const dir = dirOverride || findProfileDir();
210
- if (!dir) { return { ok: false, code: "profile-not-found" }; }
211
- const wsPath = join(dir, WORKSPACE_FILE);
212
- let raw;
213
- try { raw = readFileSync(wsPath, "utf8"); }
214
- catch (e) { return { ok: false, code: "workspace-unreadable: " + String((e && e.code) || e) }; }
215
-
216
- // 受管包名:profile dependencies 的键
217
- const manifest = readJson(join(dir, "package.json"));
218
- const managed = new Set(Object.keys((manifest && manifest.dependencies) || {}));
219
-
220
- // 锁定版本:lockfile 不可读/不存在时留空表,陈旧剪除据此退化为「无版本可依」
221
- let locked = new Map();
222
- let lockKnown = false;
223
- try { locked = parseLockVersions(readFileSync(join(dir, "pnpm-lock.yaml"), "utf8")); lockKnown = true; } catch { /* 无 lockfile */ }
224
-
225
- // 段落解析与强制豁免共用 excludeBlockOf:两个写者(自动归并 / 手动强制)必须对
226
- // 「这个块从哪到哪」有一致判断,否则会出现遮蔽条(旧笔记里踩过的坑)。
227
- const blk = excludeBlockOf(raw);
228
- const lines = blk.lines;
229
- const keyLine = blk.keyLine;
230
- // 没有这个键不是错误:profile 本来就没有待归并的条目(或已被清理干净),按「无变化」回。
231
- if (keyLine < 0) { return { ok: true, changed: false, kept: [], removed: [], path: wsPath }; }
232
- const entries = blk.entries;
233
- // 键在但一条条目都没有,同样按「无变化」回(客户端是 fire-and-forget,500 只会变成日志噪声)。
234
- if (entries.length === 0) { return { ok: true, changed: false, kept: [], removed: [], path: wsPath }; }
235
-
236
- const groups = new Map(); // name → [entry…](保序)
237
- for (const e of entries) {
238
- if (!groups.has(e.name)) { groups.set(e.name, []); }
239
- groups.get(e.name).push(e);
240
- }
241
-
242
- const keep = new Set(); // 保留的条目行号
243
- const removed = [];
244
- for (const [pkg, group] of groups) {
245
- if (group.length >= 2) {
246
- // 重复折叠:优先保留「版本 == lockfile 锁定版本」的那条,否则保留文件中第一条
247
- // (与 pnpm「靠前者生效」的现行语义一致,且结果永远是原并集的子集)。
248
- const want = locked.get(pkg);
249
- const chosen = (want && group.find((e) => e.version === want)) || group[0];
250
- keep.add(chosen.idx);
251
- for (const e of group) { if (e !== chosen) { removed.push(e.value); } }
252
- continue;
253
- }
254
- const e = group[0];
255
- // 陈旧剪除:只碰受管包名;裸名豁免全部版本,永不视为陈旧。
256
- // lockfile 整个缺失时不剪除(此时「锁定版本」无从谈起,剪掉受管条可能把
257
- // 尚未安装的 profile 卡死 —— 宁可不动,提交集方向也依然安全)。
258
- if (lockKnown && managed.has(pkg) && e.version !== null && e.version !== locked.get(pkg)) {
259
- removed.push(e.value);
260
- continue;
261
- }
262
- keep.add(e.idx);
263
- }
264
-
265
- const entryIdx = new Set(entries.map((e) => e.idx));
266
- const keptInOrder = entries.filter((e) => keep.has(e.idx)).map((e) => e.value);
267
- const byIdx = new Map(entries.map((e) => [e.idx, e]));
268
- const newRaw = lines.map((line, i) => {
269
- if (!entryIdx.has(i)) { return line; }
270
- if (!keep.has(i)) { return ""; }
271
- /* 顺手修掉历史上「以 @/` 开头的裸标量」:scoped 包名做 plain scalar 会让整个
272
- pnpm-workspace.yaml 解析失败(pnpm: bad indentation of a sequence entry),
273
- 一坏就是 profile 里所有 pnpm 操作全挂。只改确实不安全的那几行,其余保持原字节。 */
274
- if (!/^\s*-\s+['"]/.test(line) && /^\s*-\s+[@`]/.test(line)) {
275
- const e = byIdx.get(i);
276
- const indent = (/^\s*/.exec(line) || [""])[0];
277
- return indent + "- " + yamlScalar(e.value) + "\n";
278
- }
279
- return line;
280
- }).join("");
281
-
282
- if (newRaw === raw) { return { ok: true, changed: false, kept: keptInOrder, removed: [], path: wsPath }; }
283
-
284
- // 备份 + 原子替换 + 写后重读校验(与强制豁免共用同一套,含 .bak 只留最近几份)
285
- const w = atomicWriteWorkspace(dir, wsPath, raw, newRaw);
286
- backup = w.backup;
287
- if (!w.ok) { return { ok: false, code: w.code, path: wsPath, backup }; }
288
-
289
- return { ok: true, changed: true, kept: keptInOrder, removed, path: wsPath, backup };
290
- } catch (e) {
291
- return { ok: false, code: String((e && e.message) || e) };
292
- }
293
- }
294
-
295
- /**
296
- * 模块 6:官方桌面客户端的窗口记忆(见文件头注释)。
297
- * 只在 Windows + 官方客户端内的 dsh 运行时里动作;其它环境静默返回。
298
- */
299
- function startWindowState(ctx) {
300
- if (process.platform !== "win32") { return; }
301
- if (process.env.ELECTRON_RUN_AS_NODE !== "1") { return; } // 仅官方客户端内的 dsh 运行时
302
- try {
303
- const dir = join(findProfileDir() || join(tmpdir(), "dsh-ui-tweaks"), "ui-tweaks");
304
- mkdirSync(dir, { recursive: true });
305
- // helper 落在 profile 子目录:.cs/.dll/.ps1 路径按 profile 唯一,仓库被删/移动后
306
- // 已启动的 helper 不受影响,编译缓存也跟 profile 走。
307
- const srcName = "window-helper.cs";
308
- const csPath = join(dir, srcName);
309
- const dllPath = join(dir, "window-helper.dll");
310
- // 内容没变就不重写 .cs:mtime 稳定才能让下面的 staleness 判断跳过重编译,
311
- // 否则每次客户端启动都白白同步编译 1~3s(阻塞 runtime 启动)。
312
- const srcContent = "\ufeff" + readFileSync(join(dirname(fileURLToPath(import.meta.url)), srcName), "utf8");
313
- let curContent = null;
314
- try { curContent = readFileSync(csPath, "utf8"); } catch { }
315
- if (curContent !== srcContent) { writeFileSync(csPath, srcContent); }
316
- const statePath = join(dir, "window-state.json");
317
- const logPath = join(dir, "window-helper.log");
318
-
319
- // Win32 interop 预编译成 DLL(系统 csc,仅首次/插件更新后一次,1~3s)。
320
- // 关键:绝不走独立 exe —— 本地编译的无签名 exe 会被 Windows/安全软件以
321
- // 「无法验证发布者」反复拦截(实测);DLL 由 PowerShell 进程内加载,
322
- // 不触发任何安全提示,且免去 exe 的启动开销。
323
- let stale = true;
324
- try { stale = statSync(dllPath).mtimeMs < statSync(csPath).mtimeMs; } catch { }
325
- if (stale) {
326
- const csc = ["/Microsoft.NET/Framework64/v4.0.30319/csc.exe", "/Microsoft.NET/Framework/v4.0.30319/csc.exe"]
327
- .map((p) => join(process.env.SystemRoot || "C:\\Windows", p))
328
- .find((p) => { try { return statSync(p).isFile(); } catch { return false; } });
329
- if (!csc) {
330
- try { console.warn("[ui-tweaks] 未找到 csc.exe(.NET Framework),窗口记忆不可用"); } catch { }
331
- return;
332
- }
333
- const r = spawnSync(csc, ["-nologo", "-target:library", "-optimize+", `-out:${dllPath}`, csPath], { timeout: 30000 });
334
- if (!existsSync(dllPath)) {
335
- try { console.warn("[ui-tweaks] window-helper.dll 编译失败:" + String(r.stderr || r.stdout || "").slice(-300)); } catch { }
336
- return;
337
- }
338
- }
339
-
340
- const helperPath = join(dir, "window-helper.ps1");
341
- // 必须 UTF-8 BOM:PS 5.1 对无 BOM 脚本按 ANSI 解析,非 ASCII 内容会吞掉
342
- // 换行、静默吞掉下一行代码(实测踩过三次)。
343
- writeFileSync(helperPath, "\ufeff" + readFileSync(join(dirname(fileURLToPath(import.meta.url)), "window-helper.ps1"), "utf8"));
344
- const ps = join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
345
- const child = spawn(ps, [
346
- "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden",
347
- "-File", helperPath,
348
- "-DshPid", String(process.pid),
349
- "-StateFile", statePath,
350
- "-LogPath", logPath,
351
- ], { stdio: "ignore", windowsHide: true });
352
- child.on("error", (e) => {
353
- try { console.warn("[ui-tweaks] window-state helper 启动失败:" + ((e && e.message) || e)); } catch { }
354
- });
355
- ctx.effect(() => () => { try { child.kill(); } catch { } }, "ui-tweaks: window-state helper");
356
- } catch (e) {
357
- try { console.warn("[ui-tweaks] window-state 初始化失败:" + ((e && e.message) || e)); } catch { }
358
- }
359
- }
360
-
361
- /**
362
- * 解析 minimumReleaseAgeExclude 段落 → { keyLine, lines, entries }。
363
- * 与归并器共用同一套「序列条目必须缩进」的语义;未找到键时 keyLine = -1。
364
- */
365
- function excludeBlockOf(raw) {
366
- const lines = String(raw).split(/(?<=\n)/); // 每行带着自己的换行符,join 即还原
367
- const keyRe = new RegExp("^" + EXCLUDE_KEY + "\\s*:\\s*(?:#[\\s\\S]*)?$");
368
- let keyLine = -1;
369
- for (let i = 0; i < lines.length; i++) {
370
- if (keyRe.test(lines[i].replace(/\r?\n$/, ""))) { keyLine = i; break; }
371
- }
372
- const entries = [];
373
- if (keyLine >= 0) {
374
- for (let i = keyLine + 1; i < lines.length; i++) {
375
- const body = lines[i].replace(/\r?\n$/, "");
376
- const m = /^(\s*)-\s+(\S[\s\S]*)$/.exec(body);
377
- if (!m || m[1].length === 0) { break; }
378
- const value = entryValue(m[2]);
379
- const nv = splitNameVersion(value);
380
- entries.push({ idx: i, line: lines[i], value, name: nv.name, version: nv.version });
381
- }
382
- }
383
- return { keyLine, lines, entries };
384
- }
385
-
386
- /** 每包的「生效豁免」:同包多条只有靠前那条生效(实测);裸名 = 豁免该包全部版本 → null */
387
- function effectiveExemptions(raw) {
388
- const out = new Map();
389
- for (const e of excludeBlockOf(raw).entries) {
390
- if (out.has(e.name)) { continue; }
391
- out.set(e.name, e.version === null ? null : e.version);
392
- }
393
- return out;
394
- }
395
-
396
- /** 备份 + 同目录临时文件 + renameSync 原子替换 + 写后重读校验(归并器与强制豁免共用)。
397
- * .bak 只保留最近 KEEP_BAK 份:归并器每次插件加载都会跑,长期下来旧备份会无限堆积。 */
398
- const KEEP_BAK = 3;
399
- function atomicWriteWorkspace(dir, wsPath, raw, newRaw) {
400
- const stamp = new Date().toISOString().replace(/[:.]/g, "-");
401
- const backup = wsPath + ".bak-" + stamp;
402
- writeFileSync(backup, raw, "utf8");
403
- try {
404
- const hits = readdirSync(dir).filter((n) => n.startsWith(WORKSPACE_FILE + ".bak-")).sort();
405
- for (const old of hits.slice(0, Math.max(0, hits.length - KEEP_BAK))) {
406
- try { unlinkSync(join(dir, old)); } catch { /* 删不掉就留着,不影响主流程 */ }
407
- }
408
- } catch { /* 目录读不了就算了 */ }
409
- const tmp = join(dir, "." + WORKSPACE_FILE + ".tmp-" + process.pid + "-" + Date.now());
410
- try {
411
- writeFileSync(tmp, newRaw, "utf8");
412
- renameSync(tmp, wsPath);
413
- } catch (e) {
414
- try { unlinkSync(tmp); } catch { /* 临时文件可能未创建 */ }
415
- throw e;
416
- }
417
- const after = readFileSync(wsPath, "utf8");
418
- if (after !== newRaw) { return { ok: false, code: "verify-mismatch", path: wsPath, backup }; }
419
- return { ok: true, path: wsPath, backup };
420
- }
421
-
422
- /**
423
- * 强制豁免:让 `name@version` 成为豁免表的**第一条**(pnpm 按「同包名靠前者生效」匹配,
424
- * 实测 [陈旧条, 未成熟条] 失败、[未成熟条, 陈旧条] 通过)。其余条目逐字节不动,
425
- * 只在块首插入/移动一行;同包旧条目留在后面,之后由归并器收敛成一条。
426
- */
427
- export function forceExemptVersion(name, version, dirOverride) {
428
- try {
429
- const dir = dirOverride || findProfileDir();
430
- if (!dir) { return { ok: false, code: "profile-not-found" }; }
431
- const wsPath = join(dir, WORKSPACE_FILE);
432
- let raw;
433
- try { raw = readFileSync(wsPath, "utf8"); }
434
- catch (e) { return { ok: false, code: "workspace-unreadable: " + String((e && e.code) || e) }; }
435
-
436
- const value = String(name) + "@" + String(version);
437
- const blk = excludeBlockOf(raw);
438
- let newRaw;
439
- if (blk.keyLine < 0) {
440
- // 没有这个键:文件末尾追加一段(原字节全部保留)
441
- const sep = raw.length === 0 || raw.endsWith("\n") ? "" : "\n";
442
- newRaw = raw + sep + EXCLUDE_KEY + ":\n - " + yamlScalar(value) + "\n";
443
- } else {
444
- const first = blk.entries[0];
445
- const indent = first ? (/^(\s*)-/.exec(first.line) || [])[1] || " " : " ";
446
- const insert = indent + "- " + yamlScalar(value) + "\n";
447
- const dup = blk.entries.find((e) => e.value === value);
448
- const lines = blk.lines.slice();
449
- if (dup) { lines.splice(dup.idx, 1); } // 已有同值条目:移到块首
450
- const at = blk.keyLine + 1;
451
- newRaw = lines.slice(0, at).join("") + insert + lines.slice(at).join("");
452
- }
453
-
454
- if (newRaw === raw) { return { ok: true, changed: false, path: wsPath, entry: value }; }
455
- const w = atomicWriteWorkspace(dir, wsPath, raw, newRaw);
456
- if (!w.ok) { return { ok: false, code: w.code, path: wsPath, backup: w.backup }; }
457
- return { ok: true, changed: true, path: wsPath, backup: w.backup, entry: value };
458
- } catch (e) {
459
- return { ok: false, code: String((e && e.message) || e) };
460
- }
461
- }
462
-
463
- /**
464
- * 到期清理:把 `name@version` 这一条从豁免表里删掉(幂等:没有就 no-op)。
465
- * 用于强制更新的「装完不删、到期再删」—— 见 apply 里的 scheduleCleanup。
466
- */
467
- export function dropExemptVersion(name, version, dirOverride) {
468
- try {
469
- const dir = dirOverride || findProfileDir();
470
- if (!dir) { return { ok: false, code: "profile-not-found" }; }
471
- const wsPath = join(dir, WORKSPACE_FILE);
472
- let raw;
473
- try { raw = readFileSync(wsPath, "utf8"); }
474
- catch (e) { return { ok: false, code: "workspace-unreadable: " + String((e && e.code) || e) }; }
475
- const value = String(name) + "@" + String(version);
476
- const blk = excludeBlockOf(raw);
477
- const hit = blk.entries.find((e) => e.value === value);
478
- if (!hit) { return { ok: true, changed: false, path: wsPath, entry: value }; }
479
- const lines = blk.lines.slice();
480
- lines.splice(hit.idx, 1);
481
- const newRaw = lines.join("");
482
- if (newRaw === raw) { return { ok: true, changed: false, path: wsPath, entry: value }; }
483
- const w = atomicWriteWorkspace(dir, wsPath, raw, newRaw);
484
- if (!w.ok) { return { ok: false, code: w.code, path: wsPath, backup: w.backup }; }
485
- return { ok: true, changed: true, path: wsPath, backup: w.backup, entry: value };
486
- } catch (e) {
487
- return { ok: false, code: String((e && e.message) || e) };
488
- }
489
- }
490
-
491
- /**
492
- * Explorer 只认「编码过的 file URI」:它在自己的命令行里按逗号/等号切字段,
493
- * 裸路径遇到分隔符会把后半截丢掉(官方 dsh-native-command 同款处理)。
494
- * 非 ASCII 的百分号转义要还原(Explorer 拒绝百分号编码的非 ASCII,会打开「文档」目录)。
495
- */
496
- export function explorerTargetOf(windowsPath) {
497
- let uri;
498
- try { uri = pathToFileURL(windowsPath, { windows: true }).href; }
499
- catch { return windowsPath; }
500
- return uri
501
- .replace(/(?:%[89A-F][0-9A-F])+/gi, (escaped) => { try { return decodeURIComponent(escaped); } catch { return escaped; } })
502
- .replace(/,/g, "%2C")
503
- .replace(/=/g, "%3D");
504
- }
505
-
506
- /**
507
- * 纯函数:把「路径 + 动作」翻成一条原生命令(便于离线单测,不 spawn)。
508
- * 只负责「打开 / 定位」这两种;用指定应用打开由官方 native-command 负责。
509
- * @returns {{cmd: string, args: string[]} | null} 路径不合法时 null。
510
- */
511
- export function nativeOpenCommand(targetPath, action) {
512
- const p = String(targetPath || "");
513
- const act = action === "reveal" ? "reveal" : "open";
514
- if (!p) { return null; }
515
- const windowsAbs = /^[A-Za-z]:[\\/]/.test(p) || p.slice(0, 2) === "\\\\";
516
- const posixAbs = p.charAt(0) === "/";
517
- if (!windowsAbs && !posixAbs) { return null; }
518
- if (process.platform === "win32") {
519
- if (act === "reveal") { return { cmd: "explorer.exe", args: ["/select,", explorerTargetOf(p)] }; }
520
- return { cmd: "explorer.exe", args: [explorerTargetOf(p)] };
521
- }
522
- if (process.platform === "darwin") {
523
- if (act === "reveal") { return { cmd: "open", args: ["-R", p] }; }
524
- return { cmd: "open", args: [p] };
525
- }
526
- if (act === "reveal") { return { cmd: "xdg-open", args: [dirname(p)] }; }
527
- return { cmd: "xdg-open", args: [p] };
528
- }
529
-
530
- /* ========================================================================
531
- * 复用官方 @deepseek-ai/dsh-native-command(会话释放后补位的「打开方式」)
532
- *
533
- * 会话释放后官方 /api/changes.open 只回 404,但「枚举系统关联 + 打开/定位」
534
- * 本身是那个包里与 Session 无关的纯工具函数,就住在同一个 Host 进程里。
535
- * 这里按 Electron 布局定位到 app.asar 里的那份,动态 import 后直接复用:
536
- * 应用列表、默认打开、显示位置、用指定应用打开,全部与官方一致;取不到模块
537
- * 才退回本文件自带的 explorer 实现(nativeOpenCommand)。
538
- * ===================================================================== */
539
- const NATIVE_CMD_REL = join("node_modules", "@deepseek-ai", "dsh-native-command", "lib", "index.js");
540
- let nativeCmdPromise = null;
541
-
542
- function officialNativeCommand() {
543
- if (nativeCmdPromise !== null) { return nativeCmdPromise; }
544
- nativeCmdPromise = (async () => {
545
- const exeDir = dirname(process.execPath);
546
- const roots = [
547
- join(exeDir, "resources", "app.asar", "dsh"),
548
- join(exeDir, "resources", "app", "dsh"),
549
- ];
550
- for (const root of roots) {
551
- const file = join(root, NATIVE_CMD_REL);
552
- try {
553
- if (!existsSync(file)) { continue; }
554
- const mod = await import(pathToFileURL(file).href);
555
- if (mod && typeof mod.nativeFileApplications === "function") { return mod; }
556
- } catch { /* 试下一个布局 */ }
557
- }
558
- return null;
559
- })().catch(() => null);
560
- return nativeCmdPromise;
561
- }
562
-
563
- /** 官方应用条目 → 客户端 validator 能接受的形状(icon 只留 data:image,其余置 null)。 */
564
- function nativeAppEntry(app) {
565
- if (!app || typeof app.id !== "string" || !app.id) { return null; }
566
- const name = typeof app.name === "string" && app.name ? app.name : app.id;
567
- const icon = typeof app.icon === "string" && /^data:image\//.test(app.icon) ? app.icon : null;
568
- return { id: app.id, name: name, default: app.default === true, icon: icon };
569
- }
570
-
571
- /** spawn 一个 GUI 启动器:等到 spawn/error 落定再回,别让 ENOENT 静默吞掉。 */
572
- function spawnGui(cmd, args) {
573
- return new Promise((resolve) => {
574
- let settled = false;
575
- const done = (r) => { if (!settled) { settled = true; resolve(r); } };
576
- let child;
577
- try {
578
- /* windowsHide 必须为 false:GUI 启动器一旦带上 CREATE_NO_WINDOW/SW_HIDE,
579
- 由它拉起的窗口会继承「隐藏」,看起来就像点了没反应(DSH 自己也用 visible)。 */
580
- child = spawn(cmd, args, { detached: true, windowsHide: false, stdio: "ignore" });
581
- } catch (e) {
582
- done({ ok: false, code: String((e && e.code) || (e && e.message) || e), detail: String((e && e.message) || e) });
583
- return;
584
- }
585
- child.on("error", (e) => done({ ok: false, code: String((e && e.code) || (e && e.message) || e), detail: String((e && e.message) || e) }));
586
- child.on("spawn", () => { try { child.unref(); } catch { } done({ ok: true, pid: child.pid }); });
587
- const timer = setTimeout(() => done({ ok: false, code: "spawn-timeout" }), 4000);
588
- if (timer && typeof timer.unref === "function") { timer.unref(); }
589
- });
590
- }
591
-
592
- /**
593
- * 「打开方式」的应用列表(给客户端合成 GET /api/changes.open 用)。
594
- * 口径与官方完全一致:**只列系统关联里的真实应用**,不再发「系统默认应用」
595
- * 「选择其他应用…」这类自造项 —— 官方控件的规则是「主按钮=列表第一个应用、
596
- * chevron 菜单列出全部、底部固定一条『显示文件位置』」,喂真实清单即可对齐。
597
- * 枚举不出来就回空数组:控件会退化成「只有显示文件位置」的形态,绝不编造应用。
598
- */
599
- export async function listOpenApplications(targetPath) {
600
- const p = String(targetPath || "");
601
- if (!p) { return { ok: true, source: "fallback", apps: [] }; }
602
- const mod = await officialNativeCommand();
603
- if (!mod) { return { ok: true, source: "fallback", code: "native-command-unavailable", apps: [] }; }
604
- const ctl = new AbortController();
605
- const timer = setTimeout(() => { try { ctl.abort(); } catch { } }, 15000);
606
- try {
607
- const list = await mod.nativeFileApplications(p, ctl.signal);
608
- const apps = [], seen = new Set();
609
- for (const raw of Array.isArray(list) ? list : []) {
610
- const entry = nativeAppEntry(raw);
611
- if (entry && !seen.has(entry.id)) { seen.add(entry.id); apps.push(entry); }
612
- }
613
- return { ok: true, source: "native", count: apps.length, apps: apps };
614
- } catch (e) {
615
- return { ok: true, source: "fallback", code: String((e && e.code) || (e && e.message) || e), apps: [] };
616
- } finally {
617
- clearTimeout(timer);
618
- }
619
- }
620
-
621
- /**
622
- * 打开 / 定位 / 用指定应用打开。优先用官方实现(与线上会话完全一致),
623
- * 失败时把错误码带回去(客户端只看到失败,但日志与本机探测能看到真因)。
624
- */
625
- export async function openNativeTarget(targetPath, action, application) {
626
- const p = String(targetPath || "");
627
- const act = action === "reveal" ? "reveal" : "open";
628
- const app = String(application || "");
629
- if (!p) { return { ok: false, code: "path required" }; }
630
- const windowsAbs = /^[A-Za-z]:[\\/]/.test(p) || p.slice(0, 2) === "\\\\";
631
- const posixAbs = p.charAt(0) === "/";
632
- if (!windowsAbs && !posixAbs) { return { ok: false, code: "absolute-path required" }; }
633
- if (!existsSync(p)) { return { ok: false, code: "path-not-found", path: p }; }
634
- const mod = await officialNativeCommand();
635
- if (mod) {
636
- const ctl = new AbortController();
637
- const timer = setTimeout(() => { try { ctl.abort(); } catch { } }, 20000);
638
- try {
639
- if (act === "reveal") {
640
- await mod.revealNativePath(p, ctl.signal);
641
- } else if (app) {
642
- await mod.openNativeFileApplication(p, app, ctl.signal);
643
- } else {
644
- await mod.openNativePath(p, ctl.signal);
645
- }
646
- return { ok: true, source: "native", action: act, application: app || null, path: p };
647
- } catch (e) {
648
- return { ok: false, source: "native", code: String((e && e.code) || (e && e.message) || e), action: act, application: app || null, path: p };
649
- } finally {
650
- clearTimeout(timer);
651
- }
652
- }
653
- const command = nativeOpenCommand(p, act);
654
- if (command === null) { return { ok: false, code: "absolute-path required" }; }
655
- const r = await spawnGui(command.cmd, command.args);
656
- if (!r.ok) { return { ok: false, source: "spawn", code: r.code, detail: r.detail, action: act, application: app || null, path: p }; }
657
- return { ok: true, source: "spawn", action: act, application: app || null, path: p, pid: r.pid };
658
- }
659
-
660
- /** 只诊断、不弹窗:Host 进程能不能真正拉起子进程(cmd 输出 "probe" 即算通过)。 */
661
- export async function probeNativeLaunch() {
662
- const out = { ok: false };
663
- try {
664
- out.nativeCommand = !!(await officialNativeCommand());
665
- out.child = await new Promise((resolve) => {
666
- let settled = false;
667
- const done = (r) => { if (!settled) { settled = true; resolve(r); } };
668
- let child;
669
- try { child = spawn("cmd.exe", ["/c", "echo", "probe"], { windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }); }
670
- catch (e) { done({ spawn: false, code: String((e && e.code) || (e && e.message) || e) }); return; }
671
- let stdout = "";
672
- if (child.stdout) { child.stdout.on("data", (c) => { stdout += String(c); }); }
673
- child.on("error", (e) => done({ spawn: false, code: String((e && e.code) || (e && e.message) || e) }));
674
- child.on("close", (code) => done({ spawn: true, exitCode: code, stdout: stdout.trim() }));
675
- const timer = setTimeout(() => done({ spawn: false, code: "timeout" }), 5000);
676
- if (timer && typeof timer.unref === "function") { timer.unref(); }
677
- });
678
- out.ok = out.child.spawn === true && out.child.stdout === "probe";
679
- return out;
680
- } catch (e) {
681
- out.code = String((e && e.message) || e);
682
- return out;
683
- }
684
- }
685
-
686
- // 发布时长缓存:预检要查多个包,10 分钟内复用(发布时刻不会变,缓存只为省流量)
687
- const PUB_TIME_CACHE = new Map();
688
- const PUB_TIME_TTL_MS = 10 * 60 * 1000;
689
-
690
- async function publishedAtOf(name, version) {
691
- const key = String(name) + "@" + String(version);
692
- const hit = PUB_TIME_CACHE.get(key);
693
- if (hit && Date.now() - hit.at < PUB_TIME_TTL_MS) { return hit.publishedAt; }
694
- let val = null;
695
- try {
696
- const path = String(name).split("/").map(encodeURIComponent).join("/");
697
- const res = await fetch("https://registry.npmjs.org/" + path, {
698
- headers: { accept: "application/json" },
699
- signal: AbortSignal.timeout(15000),
700
- });
701
- if (res.ok) {
702
- const txt = await res.text();
703
- if (txt.length <= 8 * 1024 * 1024) {
704
- const doc = JSON.parse(txt);
705
- const t = doc && doc.time && doc.time[version];
706
- const ms = t ? Date.parse(t) : NaN;
707
- if (isFinite(ms)) { val = ms; }
708
- }
709
- }
710
- } catch { /* 查不到就返回 null,调用方按「未知」处理,不拦 */ }
711
- PUB_TIME_CACHE.set(key, { at: Date.now(), publishedAt: val });
712
- // TTL 只决定「要不要复用」,不回收条目;预检目前只扫直连依赖(几条),但若以后
713
- // 扩到全量 lockfile 就会长期增长 —— 超过上限时清掉已过期项。
714
- if (PUB_TIME_CACHE.size > 500) {
715
- const now = Date.now();
716
- for (const [k, v] of PUB_TIME_CACHE) {
717
- if (now - v.at >= PUB_TIME_TTL_MS) { PUB_TIME_CACHE.delete(k); }
718
- }
719
- }
720
- return val;
721
- }
722
-
723
- /**
724
- * 预检:这次强制更新会不会被别的包拦住。
725
- * 只看 profile 的**直连依赖**(pnpm-lock 的 importers 段=面板管的那些插件;传递依赖不扫,
726
- * 那要几百次网络查询),逐个判断「锁定版本是否已生效豁免」;没豁免的查发布时间,
727
- * 仍在窗口内的列为拦路者。目标包自己跳过(强制流程会先给它写豁免)。
728
- * 注意:门禁校验的是整个 lockfile,传递依赖或漏判的情况由安装失败时的反应式报错兜底
729
- * (pnpm 的报错会点名违规条目)。
730
- */
731
- export async function precheckExempt(name, version, opts) {
732
- const o = opts || {};
733
- try {
734
- const dir = o.dir || findProfileDir();
735
- if (!dir) { return { ok: false, code: "profile-not-found" }; }
736
- const windowMs = isFinite(o.windowMs) && o.windowMs > 0 ? o.windowMs : 1440 * 60000;
737
- let importerVersions;
738
- try { importerVersions = parseLockMaps(readFileSync(join(dir, "pnpm-lock.yaml"), "utf8")).importers; }
739
- catch (e) { return { ok: false, code: "lockfile-unreadable: " + String((e && e.code) || e) }; }
740
- let eff = new Map();
741
- try { eff = effectiveExemptions(readFileSync(join(dir, WORKSPACE_FILE), "utf8")); } catch { /* 无 workspace 文件=无豁免 */ }
742
-
743
- const now = Date.now();
744
- const blocked = [];
745
- let checked = 0;
746
- for (const [pkg, ver] of importerVersions) {
747
- if (pkg === name) { continue; }
748
- if (!ver) { continue; }
749
- if (eff.has(pkg)) {
750
- const e = eff.get(pkg);
751
- if (e === null || e === ver) { continue; } // 裸名豁免全部版本 / 精确命中锁定版本
752
- }
753
- const pub = await publishedAtOf(pkg, ver);
754
- checked++;
755
- if (pub !== null && pub + windowMs > now) {
756
- blocked.push({ name: pkg, version: ver, publishedAt: pub, matureAt: pub + windowMs });
757
- }
758
- }
759
- blocked.sort((a, b) => a.matureAt - b.matureAt);
760
- return { ok: true, blocked, checked, windowMs };
761
- } catch (e) {
762
- return { ok: false, code: String((e && e.message) || e) };
763
- }
764
- }
765
-
766
- // ---------- 自更新(模块 3 边角):面板不能卸载自己 ----------
767
-
768
- /**
769
- * 自更新所需的环境事实(profile 名 / 是否桌面端 / 客户端自带 CLI 的绝对路径)。
770
- * CLI 的 `plugin add` 把参数原样转给 pnpm(`runPlugin` → `runProfilePnpm`,带
771
- * `withFileLock(profile/package.json)`),**不经过** plugin-manager 的安装/卸载守卫,
772
- * 所以既不会撞 `already-installed`,也不必先卸载自己(面板的「卸载 → 安装」会把
773
- * 正在执行更新的插件本体卸掉,第二步随之消失 —— 真机上用户看到的就是「卸完就结束了」)。
774
- *
775
- * 桌面端必须用客户端自带的 CLI:PATH 上那份 npm 全局 dsh 会拒绝 desktop
776
- * profile(`managed exclusively by the Electron application`)。web profile 用
777
- * PATH 上的 dsh。路径由 process.execPath 推导,不硬编码、不随包分发。
778
- *
779
- * @param override 仅测试用:{ desktop, dir, execPath } 覆盖运行时探测。
780
- */
781
- export function selfUpdateInfo(override) {
782
- const o = override || {};
783
- const desktop = o.desktop !== undefined ? o.desktop === true : isDesktopRuntime();
784
- const dir = o.dir !== undefined ? o.dir : findProfileDir();
785
- const execPath = o.execPath || process.execPath;
786
- const profile = dir ? basename(dir) : "";
787
- if (desktop) {
788
- const cli = join(dirname(execPath), "resources", "runtime", "cli", "bin", "dsh.cmd");
789
- let present = false;
790
- try { present = existsSync(cli); } catch { present = false; }
791
- return { desktop: true, profile: profile || "desktop", cli: present ? cli : "" };
792
- }
793
- return { desktop: false, profile: profile || "web", cli: "" };
794
- }
795
-
796
- // ---------- 运行中的 DSH 版本(更新前的兼容门禁用) ----------
797
-
798
- /** 缓存:同一进程里版本不会变;读不到也缓存 null,避免每次检查都重试 */
799
- let dshVersionCache;
800
-
801
- /**
802
- * 运行中的 DSH 版本。首选宿主在 `profileContext` 上发布的 installAnchor(一个指向
803
- * 运行中 @deepseek-ai/dsh 清单的绝对路径)—— 打包桌面端唯一答得上的来源;兜底读
804
- * profile 自己装的 @deepseek-ai/dsh(npm 运行时)。
805
- * 读不到返回 null:调用方据此**不做**兼容门禁(宁可漏拦,不误伤正常更新)。
806
- */
807
- function dshVersionOf(ctx) {
808
- if (dshVersionCache !== undefined) { return dshVersionCache; }
809
- dshVersionCache = null;
810
- try {
811
- const launched = ctx && typeof ctx.get === "function" ? ctx.get("profileContext") : null;
812
- const anchor = launched && typeof launched.installAnchor === "string" ? launched.installAnchor.trim() : "";
813
- if (anchor) {
814
- const m = readJson(anchor);
815
- if (m && typeof m.version === "string" && m.version.trim()) { dshVersionCache = m.version.trim(); return dshVersionCache; }
816
- }
817
- } catch { /* 没发布 anchor 的运行时 */ }
818
- try {
819
- const dir = findProfileDir();
820
- const m = dir ? readJson(join(dir, "node_modules", "@deepseek-ai", "dsh", "package.json")) : null;
821
- if (m && typeof m.version === "string" && m.version.trim()) { dshVersionCache = m.version.trim(); }
822
- } catch { /* 读不到就算了 */ }
823
- return dshVersionCache;
824
- }
825
-
826
- // ---------- 模块 7:立即重启 ----------
827
-
828
- /** 重启助手等待旧进程退出的上限(毫秒);超时就照拉,避免助手永远等下去 */
829
- const RESTART_WAIT_MS = 30000;
830
-
831
- /** --inspect 系列会让新进程重新绑定固定端口,重拉时必须剔除 */
832
- function isReusableExecArg(a) {
833
- return !/^--(?:inspect|inspect-brk|inspect-port|debug|debug-brk)(?:=|$)/.test(String(a));
834
- }
835
-
836
- /** 是否跑在官方桌面客户端里(进程树归 Electron 外壳,插件重启不了它) */
837
- function isDesktopRuntime(env) {
838
- const e = env || process.env || {};
839
- return String(e.ELECTRON_RUN_AS_NODE || "") === "1" || !!(process.versions && process.versions.electron);
840
- }
841
-
842
- /**
843
- * 重启方案(纯函数,便于隔离测试):
844
- * shell —— 桌面客户端:只退出,重启交给外壳自己的对话框
845
- * relaunch —— 终端里跑起来的 dsh:detached 助手按原命令行重拉
846
- * manual —— 无 TTY / 被别的程序托管:不动,如实告诉用户手动重启
847
- */
848
- export function planRestart(facts) {
849
- const f = facts || {};
850
- if (f.desktop === true) { return { mode: "shell" }; }
851
- if (!f.interactive) { return { mode: "manual" }; }
852
- const script = f.argv && f.argv[0];
853
- if (!script) { return { mode: "manual" }; }
854
- return {
855
- mode: "relaunch",
856
- command: {
857
- execPath: f.execPath,
858
- argv: (f.execArgv || []).filter(isReusableExecArg).concat([script], (f.argv || []).slice(1)),
859
- cwd: f.cwd,
860
- env: f.env || process.env,
861
- },
862
- };
863
- }
864
-
865
- /** 重启日志:与 dsh 自己的日志同处 $DSH_HOME/logs 下 */
866
- function restartLogPath() {
867
- const home = process.env.DSH_HOME || join(homedir(), ".dsh");
868
- return join(home, "logs", "ui-tweaks-restart.log");
869
- }
870
-
871
- /**
872
- * 重拉助手:作为 `node -e <源码> <job-json>` 运行,必须自包含、无依赖。
873
- * 先等旧进程消失(或等满 waitMs),再按原命令行把 dsh 拉起来;新进程若 3 秒内
874
- * 就退出,最多重试 5 次(端口还没释放这类瞬时失败很常见),日志落盘。
875
- */
876
- const RELAUNCH_HELPER = [
877
- "const fs=require('node:fs'),cp=require('node:child_process');",
878
- "const job=JSON.parse(process.argv[1]);",
879
- "fs.mkdirSync(job.logDir,{recursive:true});",
880
- "const fd=fs.openSync(job.logPath,'a');",
881
- "const log=(l)=>{try{fs.appendFileSync(job.logPath,new Date().toISOString()+' '+l+'\\n')}catch{}};",
882
- "const alive=(pid)=>{try{process.kill(pid,0);return true}catch{return false}};",
883
- "const launch=(n)=>{",
884
- " if(n>0)log('relaunch attempt '+(n+1));",
885
- " const ch=cp.spawn(job.execPath,job.argv,{cwd:job.cwd,env:process.env,detached:true,stdio:['ignore',fd,fd]});",
886
- " ch.unref();let code=null;ch.on('exit',(v)=>{code=v});",
887
- " setTimeout(()=>{if(code===null){log('relaunch started (pid '+ch.pid+')');fs.closeSync(fd);return}"
888
- + "if(n<4){log('relaunch exited with '+code+'; retrying');launch(n+1);return}"
889
- + "log('relaunch gave up after exit '+code);fs.closeSync(fd)},3000)};",
890
- "const wait=(dl)=>{if(!alive(job.parentPid)||Date.now()>=dl){setTimeout(()=>launch(0),300);return}setTimeout(()=>wait(dl),200)};",
891
- "wait(Date.now()+job.waitMs);",
892
- ].join("\n");
893
-
894
- /** 起一个 detached 重拉助手;起不来返回 false(调用方据此退化为 manual) */
895
- export function startRelaunchHelper(command, logPath) {
896
- const file = logPath || restartLogPath();
897
- const job = {
898
- parentPid: process.pid,
899
- execPath: command.execPath,
900
- argv: command.argv,
901
- cwd: command.cwd,
902
- logDir: dirname(file),
903
- logPath: file,
904
- waitMs: RESTART_WAIT_MS,
905
- };
906
- try {
907
- mkdirSync(dirname(file), { recursive: true });
908
- const helper = spawn(command.execPath, ["-e", RELAUNCH_HELPER, JSON.stringify(job)], {
909
- cwd: command.cwd,
910
- env: command.env || process.env,
911
- detached: true,
912
- stdio: "ignore",
913
- });
914
- helper.unref();
915
- return helper.pid !== undefined;
916
- } catch (e) {
917
- try { appendFileSync(file, new Date().toISOString() + " helper failed: " + String((e && e.message) || e) + "\n"); } catch { /* 日志写不了就算了 */ }
918
- return false;
919
- }
920
- }
921
-
922
- /**
923
- * 执行方案:先安排退出(0.4s 后,够响应写回浏览器),再让进程消失。
924
- * relaunch 起不了助手 → manual:进程留在原地,不把用户丢在没有服务的状态。
925
- * runtime 只为隔离测试注入(默认就是真的起助手 / 真的退出)。
926
- */
927
- export function performRestart(plan, runtime) {
928
- const rt = runtime || {};
929
- if (plan.mode === "manual") { return "manual"; }
930
- if (plan.mode === "relaunch") {
931
- const start = rt.startHelper || ((command) => startRelaunchHelper(command));
932
- if (!plan.command || !start(plan.command)) { return "manual"; }
933
- }
934
- const schedule = rt.schedule || ((run, ms) => { setTimeout(run, ms); });
935
- const exit = rt.exit || (() => { process.exit(0); });
936
- schedule(exit, 400);
937
- return plan.mode;
938
- }
939
-
940
- /** 本进程自己的启动事实(只读,每次请求现取) */
941
- function liveRestartFacts() {
942
- return {
943
- desktop: isDesktopRuntime(process.env),
944
- interactive: process.stdin.isTTY === true || process.stdout.isTTY === true,
945
- execPath: process.execPath,
946
- argv: process.argv.slice(1),
947
- execArgv: process.execArgv,
948
- cwd: process.cwd(),
949
- env: process.env,
950
- };
951
- }
952
-
953
- export function apply(ctx) {
954
- const respond = (res) => (code, body) => {
955
- res.writeHead(code, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
956
- res.end(body);
957
- };
958
- const isLoopback = (req) => LOOPBACK_RE.test(String((req.socket && req.socket.remoteAddress) || ""));
959
-
960
- // 小体积 JSON body 读取(只给下面几条强制更新路由用;上限 8KB,超了当非法)
961
- const readJsonBody = (req, cb) => {
962
- let buf = "";
963
- let bad = false;
964
- req.on("data", (c) => { if (bad) { return; } buf += c; if (buf.length > 8192) { bad = true; } });
965
- req.on("end", () => {
966
- if (bad) { cb({}); return; }
967
- try { cb(buf ? JSON.parse(buf) : {}); } catch { cb({}); }
968
- });
969
- req.on("error", () => cb({}));
970
- };
971
-
972
- /* ---- 强制更新豁免的到期清理 ----------------------------------------------
973
- * 「装完立刻删豁免」是错的:pnpm 每次安装都会拿**整个 lockfile** 去校验供应链策略,
974
- * 被强制装上的版本还没满 24 小时时删掉豁免,接下来几小时里游 profile 的**所有** pnpm
975
- * 操作都会被整体拒绝(ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION),比留着更糟。
976
- * 正确时机是「该版本成熟之后」:客户端在强制更新时把到期时刻登记过来,这里落盘 +
977
- * 到点删表项;宿重启后按文件记录重新排期(到期未处理的立刻删)。 */
978
- const cleanupTimers = new Map(); // name@version → timer
979
- const cleanupFile = () => {
980
- const dir = findProfileDir();
981
- return dir ? join(dir, "ui-tweaks", "exempt-pending.json") : null;
982
- };
983
- const readCleanupList = () => {
984
- const f = cleanupFile();
985
- if (!f) { return []; }
986
- try {
987
- const list = JSON.parse(readFileSync(f, "utf8"));
988
- return Array.isArray(list) ? list.filter((it) => it && typeof it.name === "string" && typeof it.version === "string" && isFinite(it.dropAt)) : [];
989
- } catch { return []; }
990
- };
991
- const writeCleanupList = (list) => {
992
- const f = cleanupFile();
993
- if (!f) { return; }
994
- try {
995
- mkdirSync(dirname(f), { recursive: true });
996
- writeFileSync(f, JSON.stringify(list, null, 2) + "\n", "utf8");
997
- } catch { /* 写不了就只在内存里生效 */ }
998
- };
999
- const runCleanup = (item) => {
1000
- const key = item.name + "@" + item.version;
1001
- const timer = cleanupTimers.get(key);
1002
- if (timer) { try { clearTimeout(timer); } catch { } cleanupTimers.delete(key); }
1003
- const r = dropExemptVersion(item.name, item.version);
1004
- const rest = readCleanupList().filter((it) => !(it.name === item.name && it.version === item.version));
1005
- if (!r.ok) {
1006
- // 删失败(文件被占用等):10 分钟后再试,别把记录丢了
1007
- writeCleanupList(rest.concat([{ name: item.name, version: item.version, dropAt: Date.now() + 10 * 60 * 1000 }]));
1008
- return;
1009
- }
1010
- writeCleanupList(rest);
1011
- };
1012
- const armCleanup = (item) => {
1013
- const key = item.name + "@" + item.version;
1014
- const prev = cleanupTimers.get(key);
1015
- if (prev) { try { clearTimeout(prev); } catch { } cleanupTimers.delete(key); }
1016
- const delay = Math.max(0, Number(item.dropAt) - Date.now());
1017
- if (!isFinite(delay) || delay > 2147483000) { return; }
1018
- const timer = setTimeout(() => runCleanup(item), delay);
1019
- if (timer && typeof timer.unref === "function") { timer.unref(); }
1020
- cleanupTimers.set(key, timer);
1021
- };
1022
- const scheduleCleanup = (item) => {
1023
- writeCleanupList(readCleanupList().filter((it) => !(it.name === item.name && it.version === item.version)).concat([item]));
1024
- armCleanup(item);
1025
- };
1026
-
1027
- const routes = [
1028
- {
1029
- kind: "exact",
1030
- path: "/api/ui-tweaks/local-plugins",
1031
- handler: (req, res) => {
1032
- const done = respond(res);
1033
- try {
1034
- if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1035
- if (req.method !== "GET") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1036
- const dir = findProfileDir();
1037
- const manifest = dir ? readJson(join(dir, "package.json")) : null;
1038
- const deps = (manifest && manifest.dependencies) || {};
1039
- const local = []; // link:/file: —— 本地路径
1040
- const remote = []; // git/github/http —— 仓库或 URL 直装
1041
- for (const [n, spec] of Object.entries(deps)) {
1042
- const s = String(spec);
1043
- if (LOCAL_SPEC_RE.test(s)) { local.push(n); }
1044
- else if (REMOTE_SPEC_RE.test(s)) { remote.push(n); }
1045
- }
1046
- done(200, JSON.stringify({ ok: true, local, remote, profile: (manifest && manifest.name) || "", dsh: dshVersionOf(ctx) || "", selfUpdate: selfUpdateInfo() }));
1047
- } catch (e) {
1048
- done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) }));
1049
- }
1050
- }
1051
- },
1052
- {
1053
- kind: "exact",
1054
- path: "/api/ui-tweaks/normalize-excludes",
1055
- handler: (req, res) => {
1056
- const done = respond(res);
1057
- try {
1058
- if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1059
- if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1060
- const r = normalizeReleaseAgeExcludes();
1061
- if (!r.ok) { done(500, JSON.stringify({ ok: false, code: r.code })); return; }
1062
- done(200, JSON.stringify({ ok: true, changed: r.changed, kept: r.kept, removed: r.removed }));
1063
- } catch (e) {
1064
- done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) }));
1065
- }
1066
- }
1067
- },
1068
- {
1069
- /* 强制更新·第一步:预检会不会被别的包拦住(只扫直连依赖 + 豁免表 + 发布时长) */
1070
- kind: "exact",
1071
- path: "/api/ui-tweaks/precheck-exempt",
1072
- handler: (req, res) => {
1073
- const done = respond(res);
1074
- if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1075
- if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1076
- readJsonBody(req, (body) => {
1077
- const name = body && typeof body.name === "string" ? body.name : "";
1078
- const version = body && typeof body.version === "string" ? body.version : "";
1079
- if (!name || !version) { done(400, JSON.stringify({ ok: false, code: "name/version required" })); return; }
1080
- const windowMs = body && isFinite(body.windowMs) && body.windowMs > 0 ? Number(body.windowMs) : 0;
1081
- precheckExempt(name, version, { windowMs })
1082
- .then((r) => done(r.ok ? 200 : 500, JSON.stringify(r)))
1083
- .catch((e) => done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) })));
1084
- });
1085
- }
1086
- },
1087
- {
1088
- /* 强制更新·第二步:把 name@version 写成豁免表里该包生效的第一条 */
1089
- kind: "exact",
1090
- path: "/api/ui-tweaks/force-exempt",
1091
- handler: (req, res) => {
1092
- const done = respond(res);
1093
- if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1094
- if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1095
- readJsonBody(req, (body) => {
1096
- const name = body && typeof body.name === "string" ? body.name : "";
1097
- const version = body && typeof body.version === "string" ? body.version : "";
1098
- if (!name || !version) { done(400, JSON.stringify({ ok: false, code: "name/version required" })); return; }
1099
- const r = forceExemptVersion(name, version);
1100
- done(r.ok ? 200 : 500, JSON.stringify(r));
1101
- });
1102
- }
1103
- },
1104
- {
1105
- /* 改动卡补位的「打开 / 显示位置 / 选择应用」:会话释放后官方 /api/changes.open
1106
- 只回 404,这里交给 Host 桌面接手(官方 native-command 优先,见 openNativeTarget)。
1107
- action 还可以是 "probe":只诊断子进程能不能跑,不弹任何窗口。 */
1108
- kind: "exact",
1109
- path: "/api/ui-tweaks/open-path",
1110
- handler: (req, res) => {
1111
- const done = respond(res);
1112
- if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1113
- if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1114
- readJsonBody(req, (body) => {
1115
- const target = body && typeof body.path === "string" ? body.path : "";
1116
- const action = body && (body.action === "reveal" || body.action === "probe") ? body.action : "open";
1117
- const application = body && typeof body.application === "string" ? body.application : "";
1118
- if (action === "probe") {
1119
- probeNativeLaunch().then(
1120
- (r) => done(200, JSON.stringify(r)),
1121
- (e) => done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) })));
1122
- return;
1123
- }
1124
- openNativeTarget(target, action, application).then((r) => {
1125
- if (r.ok) { done(200, JSON.stringify(r)); return; }
1126
- const status = r.code === "path-not-found" ? 404
1127
- : (r.code === "path required" || r.code === "absolute-path required") ? 400 : 500;
1128
- done(status, JSON.stringify(r));
1129
- }, (e) => done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) })));
1130
- });
1131
- }
1132
- },
1133
- {
1134
- /* 官方 /api/changes.open 的 GET(应用列表)补位:复用官方 native-command 枚举系统关联 */
1135
- kind: "exact",
1136
- path: "/api/ui-tweaks/open-apps",
1137
- handler: (req, res) => {
1138
- const done = respond(res);
1139
- if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1140
- if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1141
- readJsonBody(req, (body) => {
1142
- const target = body && typeof body.path === "string" ? body.path : "";
1143
- listOpenApplications(target).then(
1144
- (r) => done(200, JSON.stringify(r)),
1145
- (e) => done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) })));
1146
- });
1147
- }
1148
- },
1149
- {
1150
- /* 登记「强行装上的版本到期后清掉它的豁免」;客户端在强制更新成功后调用 */
1151
- kind: "exact",
1152
- path: "/api/ui-tweaks/schedule-exempt-cleanup",
1153
- handler: (req, res) => {
1154
- const done = respond(res);
1155
- if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1156
- if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1157
- readJsonBody(req, (body) => {
1158
- const name = body && typeof body.name === "string" ? body.name : "";
1159
- const version = body && typeof body.version === "string" ? body.version : "";
1160
- const dropAt = body && isFinite(body.dropAt) ? Number(body.dropAt) : 0;
1161
- if (!name || !version || !(dropAt > 0)) { done(400, JSON.stringify({ ok: false, code: "name/version/dropAt required" })); return; }
1162
- try {
1163
- scheduleCleanup({ name, version, dropAt });
1164
- done(200, JSON.stringify({ ok: true, name, version, dropAt, at: new Date(dropAt).toISOString() }));
1165
- } catch (e) {
1166
- done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) }));
1167
- }
1168
- });
1169
- }
1170
- },
1171
- {
1172
- /* 立即重启:GET 只读方案(无副作用),POST 才执行;无法重拉时如实回 manual */
1173
- kind: "exact",
1174
- path: "/api/ui-tweaks/restart",
1175
- handler: (req, res) => {
1176
- const done = respond(res);
1177
- if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1178
- try {
1179
- const plan = planRestart(liveRestartFacts());
1180
- if (req.method === "GET" || req.method === "HEAD") { done(200, JSON.stringify({ ok: true, mode: plan.mode })); return; }
1181
- if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1182
- const mode = performRestart(plan);
1183
- done(202, JSON.stringify({ ok: true, mode }));
1184
- } catch (e) {
1185
- done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) }));
1186
- }
1187
- }
1188
- }
1189
- ];
1190
-
1191
- ctx.effect(() => {
1192
- const disposes = routes.map((r) => ctx.webServer.register(r));
1193
- return () => { for (const d of disposes) { try { d(); } catch { /* 已释放 */ } } };
1194
- }, "ui-tweaks: loopback routes");
1195
-
1196
- // 加载时静默收敛一次(fire-and-forget:异常绝不影响插件加载)
1197
- try { normalizeReleaseAgeExcludes(); } catch { /* 归并自身已吞异常,这里只兜底 */ }
1198
-
1199
- /* 恢复上次没清完的豁免清理:已到期的立刻删,其余重新排期。
1200
- 清单在 profile/ui-tweaks/exempt-pending.json(跨客户端重启有效)。 */
1201
- try {
1202
- for (const it of readCleanupList()) {
1203
- if (Number(it.dropAt) <= Date.now()) { runCleanup(it); }
1204
- else { armCleanup(it); }
1205
- }
1206
- } catch { /* 记录坏了就当没有 */ }
1207
- ctx.effect(() => () => {
1208
- for (const t of cleanupTimers.values()) { try { clearTimeout(t); } catch { } }
1209
- cleanupTimers.clear();
1210
- }, "ui-tweaks: exempt cleanup timers");
1211
-
1212
- // 桌面客户端:拉起窗口记忆 helper(非桌面环境内部自动不动作)
1213
- startWindowState(ctx);
1214
- }
1
+ /**
2
+ * dsh-ui-tweaks host half.
3
+ *
4
+ * 回环路由(只放行 127.0.0.1 / ::1;写操作集中在这里,客户端半区调它们):
5
+ * - GET /local-plugins:profile 里非 registry 直装的包名 + 运行中的 DSH 版本。
6
+ * 客户端据此把「本地链接 / Git 直装」标出来并跳过 registry 比对,也用来判「DSH 不符」。
7
+ * - POST /normalize-excludes:手动归并豁免表(加载时也会静默跑一次)。
8
+ * - POST /precheck-exempt:强制更新前的预检(列出仍在冷静期、会拦住这次安装的包)。
9
+ * - POST /force-exempt:把 name@version 写成豁免表里该包生效的第一条。
10
+ * - POST /schedule-exempt-cleanup:登记「到期自动删豁免」(版本满 24h 后清掉)。
11
+ * - POST /open-path:打开 / 显示位置 / 用指定应用打开(会话释放后改动卡的动作补位);
12
+ * action:"probe" 只诊断子进程能不能起,不弹窗。
13
+ * - POST /open-apps:系统文件关联枚举(同上,供「打开方式」菜单)。
14
+ * - POST /read-text:只读取回文件文本(限 4MB,供补位 diff 对齐真实行号)。
15
+ * - POST /preflight-source:两步法更新前的来源预检(目标版本是否存在于 registry、tarball 能否取到),
16
+ * 失败则客户端不卸载 —— 避免「卸载成功、安装失败」把插件弄丢(0.2.4 加)。
17
+ * - GET|POST /restart:GET 只读重启方案(shell / relaunch / manual),POST 才执行。
18
+ * 故意拆两个方法:GET 无副作用,预取或直粘 URL 都不会把宿主停掉(见文末「模块 7」)。
19
+ *
20
+ * profile 的 pnpm-workspace.yaml 写入(全文件只此一处):归并 minimumReleaseAgeExclude
21
+ * 序列。为什么必须收敛:
22
+ * DSH 给自带 pnpm 11.7.0 注入供应链策略 minimumReleaseAge=1440(分钟,不在任何配置文件里),
23
+ * pnpm 在解析之前先校验磁盘上现有的 lockfile,任一 entry 未成熟即整体中止安装并报
24
+ * ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION(exit 1);而该白名单按包名匹配,同一个包名出现
25
+ * 多条时「文件中靠前的那条生效」。于是同包重复/陈旧条目会静默抵消掉真正需要的豁免
26
+ * (例:dsh-context@0.61.0 陈旧条排在 dsh-context@0.69.0 前面,后者从未生效),
27
+ * 之后 profile 的每一次安装都失败;而一次成功的「未成熟版本」安装又会把新条目追加到
28
+ * 末尾,让旧条重新变成靠前那条 —— 紧接着的下一次安装立刻 FAIL。所以这必须常态化自动收敛。
29
+ * 安全约束:只改这一个序列,其余字节逐字节保持原样;写前备份
30
+ * pnpm-workspace.yaml.bak-<时间戳>;同目录临时文件 + renameSync 原子替换;写后重读校验;
31
+ * 无变化不写文件;幂等;结果永远是原条目的子集(绝不比现状更宽松);陈旧剪除只针对
32
+ * profile dependencies 里的受管包名,重复折叠适用于任何包名;裸名(不带 @版本)豁免该包
33
+ * 全部版本,永不视为陈旧。整个过程不外抛异常。仅回环访问放行。
34
+ *
35
+ * 模块 6:官方桌面客户端的窗口记忆(记住主窗口上次的大小/位置/最大化状态)。
36
+ * 官方主进程写死 1280x820 且无任何窗口状态持久化;渲染层被官方沙箱焊死
37
+ * (contextIsolation+sandbox,dshDesktop 桥只暴露给 dsh-app://app 主框架),
38
+ * 页面里拿不到任何窗口能力,所以这条路走插件服务端 + 进程外 Win32:
39
+ * spawn 一个隐藏 PowerShell helper(lib/window-helper.ps1),沿父进程链找到
40
+ * DeepSeek Harness.exe 的主窗口。实测客户端在插件加载前就已把窗口 show 出来,
41
+ * 隐藏期无感还原做不到,可达的是窗口出现后 ~0.2s 内归位(肉眼基本无感,且
42
+ * 先于任何插件 UI 打开);之后每秒采样 GetWindowPlacement 持久化。
43
+ * 仅 Windows + ELECTRON_RUN_AS_NODE=1(官方客户端内的 dsh 运行时)时激活;
44
+ * web profile / dsh-web-shell 下自动不动作。文件落 profile 的 ui-tweaks/ 子目录。
45
+ *
46
+ * 模块 7:立即重启(让刚装上的插件代码在下一次启动被加载)。
47
+ * 参考 @linxin666/dsh-client-ui-plugin-manager 的三段式:只读方案 → 二次确认 → 执行。
48
+ * 复用它的三条经验(都是真机踩出来的):① 方案按运行形态分三种 —— 打包桌面端由
49
+ * Electron 外壳管进程树,插件重启不了它,只能自己退出、等外壳弹它自己的重启对话框
50
+ * (shell);终端里跑的 dsh 用 detached 助手按原命令行重拉(relaunch,剔除 --inspect
51
+ * 之类会重新绑定端口的开关);被监督/无 TTY 的进程不动,如实报 manual。② relaunch 起
52
+ * 不了助手时退化为 manual —— 绝不在无法重拉的情况下把进程停掉。③ 重启前先 GET 读方案,
53
+ * 让确认面板说的后果与实际执行一致。
54
+ */
55
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
56
+ import { homedir, tmpdir } from "node:os";
57
+ import { dirname, join, basename } from "node:path";
58
+ import { fileURLToPath, pathToFileURL } from "node:url";
59
+ import { spawn, spawnSync } from "node:child_process";
60
+
61
+ export const name = "ui-tweaks";
62
+ export const inject = ["webServer"];
63
+
64
+ const SELF = "@nimoxie/dsh-ui-tweaks";
65
+ const LOCAL_SPEC_RE = /^(link:|file:)/; // 本地路径(link:→按包名查 node_modules)
66
+ const REMOTE_SPEC_RE = /^(git[+:@]|github:|git:|http)/; // Git 仓库 / URL 直装
67
+ const LOOPBACK_RE = /^(127\.|::1$|::ffff:127\.)/;
68
+ const EXCLUDE_KEY = "minimumReleaseAgeExclude";
69
+ const WORKSPACE_FILE = "pnpm-workspace.yaml";
70
+
71
+ function readJson(p) {
72
+ try { return JSON.parse(readFileSync(p, "utf8")); } catch { return null; }
73
+ }
74
+
75
+ function hasUs(m) {
76
+ return !!(m && m.dsh && m.dsh.profile && Array.isArray(m.dsh.profile.bundles) && m.dsh.profile.bundles.includes(SELF));
77
+ }
78
+
79
+ function findProfileDir() {
80
+ // ① npm 直装:包物理位于 profile/node_modules 内,向上走必经 profile 根
81
+ // (profile 根 package.json 的判据是 dsh.profile.bundles 且包含本插件)。
82
+ let dir = dirname(dirname(fileURLToPath(import.meta.url)));
83
+ for (let depth = 0; depth < 8; depth++) {
84
+ const m = readJson(join(dir, "package.json"));
85
+ if (hasUs(m)) { return dir; }
86
+ const parent = dirname(dir);
87
+ if (parent === dir) { break; }
88
+ dir = parent;
89
+ }
90
+ // ② link: 软链安装:Node 默认把 ESM 模块解析到真实路径,import.meta.url
91
+ // 指向 profile 外的仓库目录,①必然失败。退回扫描 profiles/*:
92
+ // DSH_HOME 环境变量 → 用户主目录默认 .dsh(dsh 未设环境变量时的标准位置)。
93
+ // 多个 profile 都装了本插件时按 host 进程形态二选一
94
+ // (桌面 host 跑在 ELECTRON_RUN_AS_NODE=1 的 Electron Node 下)。
95
+ const homes = [process.env.DSH_HOME, join(homedir(), ".dsh")].filter(Boolean);
96
+ let hits = [];
97
+ for (const home of homes) {
98
+ try {
99
+ for (const entry of readdirSync(join(home, "profiles"))) {
100
+ const dir2 = join(home, "profiles", entry);
101
+ if (hasUs(readJson(join(dir2, "package.json")))) { hits.push(dir2); }
102
+ }
103
+ } catch { /* 该 home 不存在或不可读,试下一个 */ }
104
+ if (hits.length) { break; }
105
+ }
106
+ if (hits.length === 0) { return null; }
107
+ if (hits.length === 1) { return hits[0]; }
108
+ const wanted = process.env.ELECTRON_RUN_AS_NODE === "1" ? "desktop" : "web";
109
+ return hits.find((d) => new RegExp(wanted + "$").test(d)) || hits[0];
110
+ }
111
+
112
+ // ---------- minimumReleaseAgeExclude 归并 ----------
113
+
114
+ /** yaml 标量去引号:'x' / "x" → x,其余原样 */
115
+ function unquote(s) {
116
+ const m = /^(['"])([\s\S]*)\1$/.exec(s);
117
+ return m ? m[2] : s;
118
+ }
119
+
120
+ /**
121
+ * YAML 标量输出:plain scalar **不能**以 `@` / `` ` `` 等指示符开头,而 scoped 包名
122
+ * (@scope/pkg@1.2.3)全以 @ 开头 —— 直接裸写会让整个 pnpm-workspace.yaml 解析失败
123
+ * (pnpm 报 bad indentation of a sequence entry),profile 里所有 pnpm 操作全挂。
124
+ * 安全字符集以外的值一律用单引号包起来(内部单引号翻倍)。
125
+ */
126
+ function yamlScalar(value) {
127
+ const s = String(value);
128
+ if (/^[A-Za-z0-9_][A-Za-z0-9._~\/@+-]*$/.test(s)) { return s; }
129
+ return "'" + s.replace(/'/g, "''") + "'";
130
+ }
131
+
132
+ /** 条目原文 → 裸值:去空白、去行尾注释、去引号 */
133
+ function entryValue(raw) {
134
+ const s = String(raw).trim();
135
+ const quoted = unquote(s);
136
+ if (quoted !== s) { return quoted; } // 整段就是带引号的标量
137
+ const i = s.indexOf(" #"); // 裸标量后跟注释
138
+ return i < 0 ? s : unquote(s.slice(0, i).trim());
139
+ }
140
+
141
+ /** 版本键里的 'name@version' → {name, version}(scoped 与裸名都要能分) */
142
+ function splitNameVersion(s) {
143
+ const at = s.startsWith("@") ? s.indexOf("@", 1) : s.indexOf("@");
144
+ if (at <= 0) { return { name: s, version: null }; }
145
+ return { name: s.slice(0, at), version: s.slice(at + 1) || null };
146
+ }
147
+
148
+ /** '1.2.3(peer@x)' → '1.2.3';link:/file:/workspace: 协议没有版本概念 → undefined */
149
+ function cleanVersion(v) {
150
+ const s = String(v || "").trim().replace(/\([\s\S]*$/, "").replace(/^['"]|['"]$/g, "");
151
+ if (!s || /^(link:|file:|workspace:)/.test(s)) { return undefined; }
152
+ return s;
153
+ }
154
+
155
+ /**
156
+ * 从 pnpm-lock.yaml 取两张表:
157
+ * importers = profile 自己声明的直连依赖(面板管的那些插件)
158
+ * all = importers 覆盖后的全量(含传递依赖)
159
+ * link:/file:/workspace: 这类没有发布版本的条目不进表(查询得到 undefined = 未锁定)。
160
+ */
161
+ function parseLockMaps(text) {
162
+ const fromImporters = new Map();
163
+ const fromPackages = new Map();
164
+ let section = null;
165
+ let inImporterDeps = false;
166
+ let pendingName = null;
167
+ for (const line of String(text).split(/\r?\n/)) {
168
+ const top = /^([A-Za-z][\w-]*):\s*$/.exec(line); // 缩进 0 的顶层段落
169
+ if (top) { section = top[1]; inImporterDeps = false; pendingName = null; continue; }
170
+ if (section === "importers") {
171
+ if (/^ {4}(?:dependencies|devDependencies|optionalDependencies):\s*$/.test(line)) { inImporterDeps = true; continue; }
172
+ if (/^ {2,4}\S/.test(line)) { inImporterDeps = false; continue; } // 换 importer / 换字段
173
+ if (inImporterDeps) {
174
+ const k = /^ {6}(\S[\s\S]*?):\s*$/.exec(line);
175
+ if (k) { pendingName = unquote(k[1]); continue; }
176
+ const v = /^ {8}version:\s*(\S+)\s*$/.exec(line);
177
+ if (v && pendingName) {
178
+ const ver = cleanVersion(v[1]);
179
+ if (ver) { fromImporters.set(pendingName, ver); }
180
+ pendingName = null;
181
+ continue;
182
+ }
183
+ }
184
+ } else if (section === "packages") {
185
+ const k = /^ {2}(\S[\s\S]*?):\s*$/.exec(line); // 'name@version':
186
+ if (k) {
187
+ const p = splitNameVersion(unquote(k[1]));
188
+ const ver = p.version && cleanVersion(p.version);
189
+ if (ver) { fromPackages.set(p.name, ver); }
190
+ }
191
+ }
192
+ }
193
+ const out = new Map(fromPackages);
194
+ for (const [k, v] of fromImporters) { out.set(k, v); }
195
+ return { all: out, importers: fromImporters };
196
+ }
197
+
198
+ /** 兼容入口:全量映射(归并器用) */
199
+ function parseLockVersions(text) {
200
+ return parseLockMaps(text).all;
201
+ }
202
+
203
+ /**
204
+ * 归并 profile pnpm-workspace.yaml 的 minimumReleaseAgeExclude 序列。
205
+ * 只重排这一段的条目行,其余字节逐字节保留;无变化不写盘。
206
+ * 任何异常都被吞掉,返回 {ok:false, code}。
207
+ * dirOverride 只给测试用(指向临时目录),生产走 findProfileDir()。
208
+ */
209
+ export function normalizeReleaseAgeExcludes(dirOverride) {
210
+ let backup = null;
211
+ try {
212
+ const dir = dirOverride || findProfileDir();
213
+ if (!dir) { return { ok: false, code: "profile-not-found" }; }
214
+ const wsPath = join(dir, WORKSPACE_FILE);
215
+ let raw;
216
+ try { raw = readFileSync(wsPath, "utf8"); }
217
+ catch (e) { return { ok: false, code: "workspace-unreadable: " + String((e && e.code) || e) }; }
218
+
219
+ // 受管包名:profile dependencies 的键
220
+ const manifest = readJson(join(dir, "package.json"));
221
+ const managed = new Set(Object.keys((manifest && manifest.dependencies) || {}));
222
+
223
+ // 锁定版本:lockfile 不可读/不存在时留空表,陈旧剪除据此退化为「无版本可依」
224
+ let locked = new Map();
225
+ let lockKnown = false;
226
+ try { locked = parseLockVersions(readFileSync(join(dir, "pnpm-lock.yaml"), "utf8")); lockKnown = true; } catch { /* 无 lockfile */ }
227
+
228
+ // 段落解析与强制豁免共用 excludeBlockOf:两个写者(自动归并 / 手动强制)必须对
229
+ // 「这个块从哪到哪」有一致判断,否则会出现遮蔽条(旧笔记里踩过的坑)。
230
+ const blk = excludeBlockOf(raw);
231
+ const lines = blk.lines;
232
+ const keyLine = blk.keyLine;
233
+ // 没有这个键不是错误:profile 本来就没有待归并的条目(或已被清理干净),按「无变化」回。
234
+ if (keyLine < 0) { return { ok: true, changed: false, kept: [], removed: [], path: wsPath }; }
235
+ const entries = blk.entries;
236
+ // 键在但一条条目都没有,同样按「无变化」回(客户端是 fire-and-forget,500 只会变成日志噪声)。
237
+ if (entries.length === 0) { return { ok: true, changed: false, kept: [], removed: [], path: wsPath }; }
238
+
239
+ const groups = new Map(); // name → [entry…](保序)
240
+ for (const e of entries) {
241
+ if (!groups.has(e.name)) { groups.set(e.name, []); }
242
+ groups.get(e.name).push(e);
243
+ }
244
+
245
+ const keep = new Set(); // 保留的条目行号
246
+ const removed = [];
247
+ for (const [pkg, group] of groups) {
248
+ if (group.length >= 2) {
249
+ // 重复折叠:优先保留「版本 == lockfile 锁定版本」的那条,否则保留文件中第一条
250
+ // (与 pnpm「靠前者生效」的现行语义一致,且结果永远是原并集的子集)。
251
+ const want = locked.get(pkg);
252
+ const chosen = (want && group.find((e) => e.version === want)) || group[0];
253
+ keep.add(chosen.idx);
254
+ for (const e of group) { if (e !== chosen) { removed.push(e.value); } }
255
+ continue;
256
+ }
257
+ const e = group[0];
258
+ // 陈旧剪除:只碰受管包名;裸名豁免全部版本,永不视为陈旧。
259
+ // lockfile 整个缺失时不剪除(此时「锁定版本」无从谈起,剪掉受管条可能把
260
+ // 尚未安装的 profile 卡死 —— 宁可不动,提交集方向也依然安全)。
261
+ if (lockKnown && managed.has(pkg) && e.version !== null && e.version !== locked.get(pkg)) {
262
+ removed.push(e.value);
263
+ continue;
264
+ }
265
+ keep.add(e.idx);
266
+ }
267
+
268
+ const entryIdx = new Set(entries.map((e) => e.idx));
269
+ const keptInOrder = entries.filter((e) => keep.has(e.idx)).map((e) => e.value);
270
+ const byIdx = new Map(entries.map((e) => [e.idx, e]));
271
+ const newRaw = lines.map((line, i) => {
272
+ if (!entryIdx.has(i)) { return line; }
273
+ if (!keep.has(i)) { return ""; }
274
+ /* 顺手修掉历史上「以 @/` 开头的裸标量」:scoped 包名做 plain scalar 会让整个
275
+ pnpm-workspace.yaml 解析失败(pnpm: bad indentation of a sequence entry),
276
+ 一坏就是 profile 里所有 pnpm 操作全挂。只改确实不安全的那几行,其余保持原字节。 */
277
+ if (!/^\s*-\s+['"]/.test(line) && /^\s*-\s+[@`]/.test(line)) {
278
+ const e = byIdx.get(i);
279
+ const indent = (/^\s*/.exec(line) || [""])[0];
280
+ return indent + "- " + yamlScalar(e.value) + "\n";
281
+ }
282
+ return line;
283
+ }).join("");
284
+
285
+ if (newRaw === raw) { return { ok: true, changed: false, kept: keptInOrder, removed: [], path: wsPath }; }
286
+
287
+ // 备份 + 原子替换 + 写后重读校验(与强制豁免共用同一套,含 .bak 只留最近几份)
288
+ const w = atomicWriteWorkspace(dir, wsPath, raw, newRaw);
289
+ backup = w.backup;
290
+ if (!w.ok) { return { ok: false, code: w.code, path: wsPath, backup }; }
291
+
292
+ return { ok: true, changed: true, kept: keptInOrder, removed, path: wsPath, backup };
293
+ } catch (e) {
294
+ return { ok: false, code: String((e && e.message) || e) };
295
+ }
296
+ }
297
+
298
+ /**
299
+ * 模块 6:官方桌面客户端的窗口记忆(见文件头注释)。
300
+ * 只在 Windows + 官方客户端内的 dsh 运行时里动作;其它环境静默返回。
301
+ */
302
+ function startWindowState(ctx) {
303
+ if (process.platform !== "win32") { return; }
304
+ if (process.env.ELECTRON_RUN_AS_NODE !== "1") { return; } // 仅官方客户端内的 dsh 运行时
305
+ try {
306
+ const dir = join(findProfileDir() || join(tmpdir(), "dsh-ui-tweaks"), "ui-tweaks");
307
+ mkdirSync(dir, { recursive: true });
308
+ // helper 落在 profile 子目录:.cs/.dll/.ps1 路径按 profile 唯一,仓库被删/移动后
309
+ // 已启动的 helper 不受影响,编译缓存也跟 profile 走。
310
+ const srcName = "window-helper.cs";
311
+ const csPath = join(dir, srcName);
312
+ const dllPath = join(dir, "window-helper.dll");
313
+ // 内容没变就不重写 .cs:mtime 稳定才能让下面的 staleness 判断跳过重编译,
314
+ // 否则每次客户端启动都白白同步编译 1~3s(阻塞 runtime 启动)。
315
+ const srcContent = "\ufeff" + readFileSync(join(dirname(fileURLToPath(import.meta.url)), srcName), "utf8");
316
+ let curContent = null;
317
+ try { curContent = readFileSync(csPath, "utf8"); } catch { }
318
+ if (curContent !== srcContent) { writeFileSync(csPath, srcContent); }
319
+ const statePath = join(dir, "window-state.json");
320
+ const logPath = join(dir, "window-helper.log");
321
+
322
+ // Win32 interop 预编译成 DLL(系统 csc,仅首次/插件更新后一次,1~3s)。
323
+ // 关键:绝不走独立 exe —— 本地编译的无签名 exe 会被 Windows/安全软件以
324
+ // 「无法验证发布者」反复拦截(实测);DLL 由 PowerShell 进程内加载,
325
+ // 不触发任何安全提示,且免去 exe 的启动开销。
326
+ let stale = true;
327
+ try { stale = statSync(dllPath).mtimeMs < statSync(csPath).mtimeMs; } catch { }
328
+ if (stale) {
329
+ const csc = ["/Microsoft.NET/Framework64/v4.0.30319/csc.exe", "/Microsoft.NET/Framework/v4.0.30319/csc.exe"]
330
+ .map((p) => join(process.env.SystemRoot || "C:\\Windows", p))
331
+ .find((p) => { try { return statSync(p).isFile(); } catch { return false; } });
332
+ if (!csc) {
333
+ try { console.warn("[ui-tweaks] 未找到 csc.exe(.NET Framework),窗口记忆不可用"); } catch { }
334
+ return;
335
+ }
336
+ const r = spawnSync(csc, ["-nologo", "-target:library", "-optimize+", `-out:${dllPath}`, csPath], { timeout: 30000 });
337
+ if (!existsSync(dllPath)) {
338
+ try { console.warn("[ui-tweaks] window-helper.dll 编译失败:" + String(r.stderr || r.stdout || "").slice(-300)); } catch { }
339
+ return;
340
+ }
341
+ }
342
+
343
+ const helperPath = join(dir, "window-helper.ps1");
344
+ // 必须 UTF-8 BOM:PS 5.1 对无 BOM 脚本按 ANSI 解析,非 ASCII 内容会吞掉
345
+ // 换行、静默吞掉下一行代码(实测踩过三次)。
346
+ writeFileSync(helperPath, "\ufeff" + readFileSync(join(dirname(fileURLToPath(import.meta.url)), "window-helper.ps1"), "utf8"));
347
+ const ps = join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
348
+ const child = spawn(ps, [
349
+ "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden",
350
+ "-File", helperPath,
351
+ "-DshPid", String(process.pid),
352
+ "-StateFile", statePath,
353
+ "-LogPath", logPath,
354
+ ], { stdio: "ignore", windowsHide: true });
355
+ child.on("error", (e) => {
356
+ try { console.warn("[ui-tweaks] window-state helper 启动失败:" + ((e && e.message) || e)); } catch { }
357
+ });
358
+ ctx.effect(() => () => { try { child.kill(); } catch { } }, "ui-tweaks: window-state helper");
359
+ } catch (e) {
360
+ try { console.warn("[ui-tweaks] window-state 初始化失败:" + ((e && e.message) || e)); } catch { }
361
+ }
362
+ }
363
+
364
+ /**
365
+ * 解析 minimumReleaseAgeExclude 段落 → { keyLine, lines, entries }。
366
+ * 与归并器共用同一套「序列条目必须缩进」的语义;未找到键时 keyLine = -1。
367
+ */
368
+ function excludeBlockOf(raw) {
369
+ const lines = String(raw).split(/(?<=\n)/); // 每行带着自己的换行符,join 即还原
370
+ const keyRe = new RegExp("^" + EXCLUDE_KEY + "\\s*:\\s*(?:#[\\s\\S]*)?$");
371
+ let keyLine = -1;
372
+ for (let i = 0; i < lines.length; i++) {
373
+ if (keyRe.test(lines[i].replace(/\r?\n$/, ""))) { keyLine = i; break; }
374
+ }
375
+ const entries = [];
376
+ if (keyLine >= 0) {
377
+ for (let i = keyLine + 1; i < lines.length; i++) {
378
+ const body = lines[i].replace(/\r?\n$/, "");
379
+ const m = /^(\s*)-\s+(\S[\s\S]*)$/.exec(body);
380
+ if (!m || m[1].length === 0) { break; }
381
+ const value = entryValue(m[2]);
382
+ const nv = splitNameVersion(value);
383
+ entries.push({ idx: i, line: lines[i], value, name: nv.name, version: nv.version });
384
+ }
385
+ }
386
+ return { keyLine, lines, entries };
387
+ }
388
+
389
+ /** 每包的「生效豁免」:同包多条只有靠前那条生效(实测);裸名 = 豁免该包全部版本 → null */
390
+ function effectiveExemptions(raw) {
391
+ const out = new Map();
392
+ for (const e of excludeBlockOf(raw).entries) {
393
+ if (out.has(e.name)) { continue; }
394
+ out.set(e.name, e.version === null ? null : e.version);
395
+ }
396
+ return out;
397
+ }
398
+
399
+ /** 备份 + 同目录临时文件 + renameSync 原子替换 + 写后重读校验(归并器与强制豁免共用)。
400
+ * .bak 只保留最近 KEEP_BAK 份:归并器每次插件加载都会跑,长期下来旧备份会无限堆积。 */
401
+ const KEEP_BAK = 3;
402
+ function atomicWriteWorkspace(dir, wsPath, raw, newRaw) {
403
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
404
+ const backup = wsPath + ".bak-" + stamp;
405
+ writeFileSync(backup, raw, "utf8");
406
+ try {
407
+ const hits = readdirSync(dir).filter((n) => n.startsWith(WORKSPACE_FILE + ".bak-")).sort();
408
+ for (const old of hits.slice(0, Math.max(0, hits.length - KEEP_BAK))) {
409
+ try { unlinkSync(join(dir, old)); } catch { /* 删不掉就留着,不影响主流程 */ }
410
+ }
411
+ } catch { /* 目录读不了就算了 */ }
412
+ const tmp = join(dir, "." + WORKSPACE_FILE + ".tmp-" + process.pid + "-" + Date.now());
413
+ try {
414
+ writeFileSync(tmp, newRaw, "utf8");
415
+ renameSync(tmp, wsPath);
416
+ } catch (e) {
417
+ try { unlinkSync(tmp); } catch { /* 临时文件可能未创建 */ }
418
+ throw e;
419
+ }
420
+ const after = readFileSync(wsPath, "utf8");
421
+ if (after !== newRaw) { return { ok: false, code: "verify-mismatch", path: wsPath, backup }; }
422
+ return { ok: true, path: wsPath, backup };
423
+ }
424
+
425
+ /**
426
+ * 强制豁免:让 `name@version` 成为豁免表的**第一条**(pnpm 按「同包名靠前者生效」匹配,
427
+ * 实测 [陈旧条, 未成熟条] 失败、[未成熟条, 陈旧条] 通过)。其余条目逐字节不动,
428
+ * 只在块首插入/移动一行;同包旧条目留在后面,之后由归并器收敛成一条。
429
+ */
430
+ export function forceExemptVersion(name, version, dirOverride) {
431
+ try {
432
+ const dir = dirOverride || findProfileDir();
433
+ if (!dir) { return { ok: false, code: "profile-not-found" }; }
434
+ const wsPath = join(dir, WORKSPACE_FILE);
435
+ let raw;
436
+ try { raw = readFileSync(wsPath, "utf8"); }
437
+ catch (e) { return { ok: false, code: "workspace-unreadable: " + String((e && e.code) || e) }; }
438
+
439
+ const value = String(name) + "@" + String(version);
440
+ const blk = excludeBlockOf(raw);
441
+ let newRaw;
442
+ if (blk.keyLine < 0) {
443
+ // 没有这个键:文件末尾追加一段(原字节全部保留)
444
+ const sep = raw.length === 0 || raw.endsWith("\n") ? "" : "\n";
445
+ newRaw = raw + sep + EXCLUDE_KEY + ":\n - " + yamlScalar(value) + "\n";
446
+ } else {
447
+ const first = blk.entries[0];
448
+ const indent = first ? (/^(\s*)-/.exec(first.line) || [])[1] || " " : " ";
449
+ const insert = indent + "- " + yamlScalar(value) + "\n";
450
+ const dup = blk.entries.find((e) => e.value === value);
451
+ const lines = blk.lines.slice();
452
+ if (dup) { lines.splice(dup.idx, 1); } // 已有同值条目:移到块首
453
+ const at = blk.keyLine + 1;
454
+ newRaw = lines.slice(0, at).join("") + insert + lines.slice(at).join("");
455
+ }
456
+
457
+ if (newRaw === raw) { return { ok: true, changed: false, path: wsPath, entry: value }; }
458
+ const w = atomicWriteWorkspace(dir, wsPath, raw, newRaw);
459
+ if (!w.ok) { return { ok: false, code: w.code, path: wsPath, backup: w.backup }; }
460
+ return { ok: true, changed: true, path: wsPath, backup: w.backup, entry: value };
461
+ } catch (e) {
462
+ return { ok: false, code: String((e && e.message) || e) };
463
+ }
464
+ }
465
+
466
+ /**
467
+ * 到期清理:把 `name@version` 这一条从豁免表里删掉(幂等:没有就 no-op)。
468
+ * 用于强制更新的「装完不删、到期再删」—— 见 apply 里的 scheduleCleanup。
469
+ */
470
+ export function dropExemptVersion(name, version, dirOverride) {
471
+ try {
472
+ const dir = dirOverride || findProfileDir();
473
+ if (!dir) { return { ok: false, code: "profile-not-found" }; }
474
+ const wsPath = join(dir, WORKSPACE_FILE);
475
+ let raw;
476
+ try { raw = readFileSync(wsPath, "utf8"); }
477
+ catch (e) { return { ok: false, code: "workspace-unreadable: " + String((e && e.code) || e) }; }
478
+ const value = String(name) + "@" + String(version);
479
+ const blk = excludeBlockOf(raw);
480
+ const hit = blk.entries.find((e) => e.value === value);
481
+ if (!hit) { return { ok: true, changed: false, path: wsPath, entry: value }; }
482
+ const lines = blk.lines.slice();
483
+ lines.splice(hit.idx, 1);
484
+ const newRaw = lines.join("");
485
+ if (newRaw === raw) { return { ok: true, changed: false, path: wsPath, entry: value }; }
486
+ const w = atomicWriteWorkspace(dir, wsPath, raw, newRaw);
487
+ if (!w.ok) { return { ok: false, code: w.code, path: wsPath, backup: w.backup }; }
488
+ return { ok: true, changed: true, path: wsPath, backup: w.backup, entry: value };
489
+ } catch (e) {
490
+ return { ok: false, code: String((e && e.message) || e) };
491
+ }
492
+ }
493
+
494
+ /**
495
+ * Explorer 只认「编码过的 file URI」:它在自己的命令行里按逗号/等号切字段,
496
+ * 裸路径遇到分隔符会把后半截丢掉(官方 dsh-native-command 同款处理)。
497
+ * 非 ASCII 的百分号转义要还原(Explorer 拒绝百分号编码的非 ASCII,会打开「文档」目录)。
498
+ */
499
+ export function explorerTargetOf(windowsPath) {
500
+ let uri;
501
+ try { uri = pathToFileURL(windowsPath, { windows: true }).href; }
502
+ catch { return windowsPath; }
503
+ return uri
504
+ .replace(/(?:%[89A-F][0-9A-F])+/gi, (escaped) => { try { return decodeURIComponent(escaped); } catch { return escaped; } })
505
+ .replace(/,/g, "%2C")
506
+ .replace(/=/g, "%3D");
507
+ }
508
+
509
+ /**
510
+ * 纯函数:把「路径 + 动作」翻成一条原生命令(便于离线单测,不 spawn)。
511
+ * 只负责「打开 / 定位」这两种;用指定应用打开由官方 native-command 负责。
512
+ * @returns {{cmd: string, args: string[]} | null} 路径不合法时 null。
513
+ */
514
+ export function nativeOpenCommand(targetPath, action) {
515
+ const p = String(targetPath || "");
516
+ const act = action === "reveal" ? "reveal" : "open";
517
+ if (!p) { return null; }
518
+ const windowsAbs = /^[A-Za-z]:[\\/]/.test(p) || p.slice(0, 2) === "\\\\";
519
+ const posixAbs = p.charAt(0) === "/";
520
+ if (!windowsAbs && !posixAbs) { return null; }
521
+ if (process.platform === "win32") {
522
+ if (act === "reveal") { return { cmd: "explorer.exe", args: ["/select,", explorerTargetOf(p)] }; }
523
+ return { cmd: "explorer.exe", args: [explorerTargetOf(p)] };
524
+ }
525
+ if (process.platform === "darwin") {
526
+ if (act === "reveal") { return { cmd: "open", args: ["-R", p] }; }
527
+ return { cmd: "open", args: [p] };
528
+ }
529
+ if (act === "reveal") { return { cmd: "xdg-open", args: [dirname(p)] }; }
530
+ return { cmd: "xdg-open", args: [p] };
531
+ }
532
+
533
+ /* ========================================================================
534
+ * 复用官方 @deepseek-ai/dsh-native-command(会话释放后补位的「打开方式」)
535
+ *
536
+ * 会话释放后官方 /api/changes.open 只回 404,但「枚举系统关联 + 打开/定位」
537
+ * 本身是那个包里与 Session 无关的纯工具函数,就住在同一个 Host 进程里。
538
+ * 这里按 Electron 布局定位到 app.asar 里的那份,动态 import 后直接复用:
539
+ * 应用列表、默认打开、显示位置、用指定应用打开,全部与官方一致;取不到模块
540
+ * 才退回本文件自带的 explorer 实现(nativeOpenCommand)。
541
+ * ===================================================================== */
542
+ const NATIVE_CMD_REL = join("node_modules", "@deepseek-ai", "dsh-native-command", "lib", "index.js");
543
+ let nativeCmdPromise = null;
544
+
545
+ function officialNativeCommand() {
546
+ if (nativeCmdPromise !== null) { return nativeCmdPromise; }
547
+ nativeCmdPromise = (async () => {
548
+ const exeDir = dirname(process.execPath);
549
+ const roots = [
550
+ join(exeDir, "resources", "app.asar", "dsh"),
551
+ join(exeDir, "resources", "app", "dsh"),
552
+ ];
553
+ for (const root of roots) {
554
+ const file = join(root, NATIVE_CMD_REL);
555
+ try {
556
+ if (!existsSync(file)) { continue; }
557
+ const mod = await import(pathToFileURL(file).href);
558
+ if (mod && typeof mod.nativeFileApplications === "function") { return mod; }
559
+ } catch { /* 试下一个布局 */ }
560
+ }
561
+ return null;
562
+ })().catch(() => null);
563
+ return nativeCmdPromise;
564
+ }
565
+
566
+ /** 官方应用条目 → 客户端 validator 能接受的形状(icon 只留 data:image,其余置 null)。 */
567
+ function nativeAppEntry(app) {
568
+ if (!app || typeof app.id !== "string" || !app.id) { return null; }
569
+ const name = typeof app.name === "string" && app.name ? app.name : app.id;
570
+ const icon = typeof app.icon === "string" && /^data:image\//.test(app.icon) ? app.icon : null;
571
+ return { id: app.id, name: name, default: app.default === true, icon: icon };
572
+ }
573
+
574
+ /** spawn 一个 GUI 启动器:等到 spawn/error 落定再回,别让 ENOENT 静默吞掉。 */
575
+ function spawnGui(cmd, args) {
576
+ return new Promise((resolve) => {
577
+ let settled = false;
578
+ const done = (r) => { if (!settled) { settled = true; resolve(r); } };
579
+ let child;
580
+ try {
581
+ /* windowsHide 必须为 false:GUI 启动器一旦带上 CREATE_NO_WINDOW/SW_HIDE,
582
+ 由它拉起的窗口会继承「隐藏」,看起来就像点了没反应(DSH 自己也用 visible)。 */
583
+ child = spawn(cmd, args, { detached: true, windowsHide: false, stdio: "ignore" });
584
+ } catch (e) {
585
+ done({ ok: false, code: String((e && e.code) || (e && e.message) || e), detail: String((e && e.message) || e) });
586
+ return;
587
+ }
588
+ child.on("error", (e) => done({ ok: false, code: String((e && e.code) || (e && e.message) || e), detail: String((e && e.message) || e) }));
589
+ child.on("spawn", () => { try { child.unref(); } catch { } done({ ok: true, pid: child.pid }); });
590
+ const timer = setTimeout(() => done({ ok: false, code: "spawn-timeout" }), 4000);
591
+ if (timer && typeof timer.unref === "function") { timer.unref(); }
592
+ });
593
+ }
594
+
595
+ /**
596
+ * 「打开方式」的应用列表(给客户端合成 GET /api/changes.open 用)。
597
+ * 口径与官方完全一致:**只列系统关联里的真实应用**,不再发「系统默认应用」
598
+ * 「选择其他应用…」这类自造项 —— 官方控件的规则是「主按钮=列表第一个应用、
599
+ * chevron 菜单列出全部、底部固定一条『显示文件位置』」,喂真实清单即可对齐。
600
+ * 枚举不出来就回空数组:控件会退化成「只有显示文件位置」的形态,绝不编造应用。
601
+ */
602
+ export async function listOpenApplications(targetPath) {
603
+ const p = String(targetPath || "");
604
+ if (!p) { return { ok: true, source: "fallback", apps: [] }; }
605
+ const mod = await officialNativeCommand();
606
+ if (!mod) { return { ok: true, source: "fallback", code: "native-command-unavailable", apps: [] }; }
607
+ const ctl = new AbortController();
608
+ const timer = setTimeout(() => { try { ctl.abort(); } catch { } }, 15000);
609
+ try {
610
+ const list = await mod.nativeFileApplications(p, ctl.signal);
611
+ const apps = [], seen = new Set();
612
+ for (const raw of Array.isArray(list) ? list : []) {
613
+ const entry = nativeAppEntry(raw);
614
+ if (entry && !seen.has(entry.id)) { seen.add(entry.id); apps.push(entry); }
615
+ }
616
+ return { ok: true, source: "native", count: apps.length, apps: apps };
617
+ } catch (e) {
618
+ return { ok: true, source: "fallback", code: String((e && e.code) || (e && e.message) || e), apps: [] };
619
+ } finally {
620
+ clearTimeout(timer);
621
+ }
622
+ }
623
+
624
+ /**
625
+ * 打开 / 定位 / 用指定应用打开。优先用官方实现(与线上会话完全一致),
626
+ * 失败时把错误码带回去(客户端只看到失败,但日志与本机探测能看到真因)。
627
+ */
628
+ export async function openNativeTarget(targetPath, action, application) {
629
+ const p = String(targetPath || "");
630
+ const act = action === "reveal" ? "reveal" : "open";
631
+ const app = String(application || "");
632
+ if (!p) { return { ok: false, code: "path required" }; }
633
+ const windowsAbs = /^[A-Za-z]:[\\/]/.test(p) || p.slice(0, 2) === "\\\\";
634
+ const posixAbs = p.charAt(0) === "/";
635
+ if (!windowsAbs && !posixAbs) { return { ok: false, code: "absolute-path required" }; }
636
+ if (!existsSync(p)) { return { ok: false, code: "path-not-found", path: p }; }
637
+ const mod = await officialNativeCommand();
638
+ if (mod) {
639
+ const ctl = new AbortController();
640
+ const timer = setTimeout(() => { try { ctl.abort(); } catch { } }, 20000);
641
+ try {
642
+ if (act === "reveal") {
643
+ await mod.revealNativePath(p, ctl.signal);
644
+ } else if (app) {
645
+ await mod.openNativeFileApplication(p, app, ctl.signal);
646
+ } else {
647
+ await mod.openNativePath(p, ctl.signal);
648
+ }
649
+ return { ok: true, source: "native", action: act, application: app || null, path: p };
650
+ } catch (e) {
651
+ return { ok: false, source: "native", code: String((e && e.code) || (e && e.message) || e), action: act, application: app || null, path: p };
652
+ } finally {
653
+ clearTimeout(timer);
654
+ }
655
+ }
656
+ const command = nativeOpenCommand(p, act);
657
+ if (command === null) { return { ok: false, code: "absolute-path required" }; }
658
+ const r = await spawnGui(command.cmd, command.args);
659
+ if (!r.ok) { return { ok: false, source: "spawn", code: r.code, detail: r.detail, action: act, application: app || null, path: p }; }
660
+ return { ok: true, source: "spawn", action: act, application: app || null, path: p, pid: r.pid };
661
+ }
662
+
663
+ /** 只诊断、不弹窗:Host 进程能不能真正拉起子进程(cmd 输出 "probe" 即算通过)。 */
664
+ export async function probeNativeLaunch() {
665
+ const out = { ok: false };
666
+ try {
667
+ out.nativeCommand = !!(await officialNativeCommand());
668
+ out.child = await new Promise((resolve) => {
669
+ let settled = false;
670
+ const done = (r) => { if (!settled) { settled = true; resolve(r); } };
671
+ let child;
672
+ try { child = spawn("cmd.exe", ["/c", "echo", "probe"], { windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }); }
673
+ catch (e) { done({ spawn: false, code: String((e && e.code) || (e && e.message) || e) }); return; }
674
+ let stdout = "";
675
+ if (child.stdout) { child.stdout.on("data", (c) => { stdout += String(c); }); }
676
+ child.on("error", (e) => done({ spawn: false, code: String((e && e.code) || (e && e.message) || e) }));
677
+ child.on("close", (code) => done({ spawn: true, exitCode: code, stdout: stdout.trim() }));
678
+ const timer = setTimeout(() => done({ spawn: false, code: "timeout" }), 5000);
679
+ if (timer && typeof timer.unref === "function") { timer.unref(); }
680
+ });
681
+ out.ok = out.child.spawn === true && out.child.stdout === "probe";
682
+ return out;
683
+ } catch (e) {
684
+ out.code = String((e && e.message) || e);
685
+ return out;
686
+ }
687
+ }
688
+
689
+ // 发布时长缓存:预检要查多个包,10 分钟内复用(发布时刻不会变,缓存只为省流量)
690
+ const PUB_TIME_CACHE = new Map();
691
+ const PUB_TIME_TTL_MS = 10 * 60 * 1000;
692
+
693
+ async function publishedAtOf(name, version) {
694
+ const key = String(name) + "@" + String(version);
695
+ const hit = PUB_TIME_CACHE.get(key);
696
+ if (hit && Date.now() - hit.at < PUB_TIME_TTL_MS) { return hit.publishedAt; }
697
+ let val = null;
698
+ try {
699
+ const path = String(name).split("/").map(encodeURIComponent).join("/");
700
+ const res = await fetch("https://registry.npmjs.org/" + path, {
701
+ headers: { accept: "application/json" },
702
+ signal: AbortSignal.timeout(15000),
703
+ });
704
+ if (res.ok) {
705
+ const txt = await res.text();
706
+ if (txt.length <= 8 * 1024 * 1024) {
707
+ const doc = JSON.parse(txt);
708
+ const t = doc && doc.time && doc.time[version];
709
+ const ms = t ? Date.parse(t) : NaN;
710
+ if (isFinite(ms)) { val = ms; }
711
+ }
712
+ }
713
+ } catch { /* 查不到就返回 null,调用方按「未知」处理,不拦 */ }
714
+ PUB_TIME_CACHE.set(key, { at: Date.now(), publishedAt: val });
715
+ // TTL 只决定「要不要复用」,不回收条目;预检目前只扫直连依赖(几条),但若以后
716
+ // 扩到全量 lockfile 就会长期增长 —— 超过上限时清掉已过期项。
717
+ if (PUB_TIME_CACHE.size > 500) {
718
+ const now = Date.now();
719
+ for (const [k, v] of PUB_TIME_CACHE) {
720
+ if (now - v.at >= PUB_TIME_TTL_MS) { PUB_TIME_CACHE.delete(k); }
721
+ }
722
+ }
723
+ return val;
724
+ }
725
+
726
+ /**
727
+ * pnpm 实际会用的 registry:环境变量 > profile/.npmrc > ~/.npmrc > npm 默认。
728
+ * 预检必须问**同一个源**——面板比对直连 npmjs,但安装走 .npmrc(常见是 npmmirror),
729
+ * 镜像没同步的版本「npmjs 有、pnpm 装不上」,只问 npmjs 就等于没预检。
730
+ */
731
+ function resolveRegistry() {
732
+ const fromEnv = process.env.NPM_CONFIG_REGISTRY || process.env.npm_config_registry;
733
+ if (fromEnv) { return String(fromEnv).replace(/\/+$/, ""); }
734
+ const files = [];
735
+ const profile = findProfileDir();
736
+ if (profile) { files.push(join(profile, ".npmrc")); }
737
+ files.push(join(homedir(), ".npmrc"));
738
+ for (const f of files) {
739
+ try {
740
+ const m = readFileSync(f, "utf8").match(/^\s*registry\s*=\s*(\S+)\s*$/m);
741
+ if (m && m[1]) { return m[1].replace(/\/+$/, ""); }
742
+ } catch { /* 没有这个文件就试下一个 */ }
743
+ }
744
+ return "https://registry.npmjs.org";
745
+ }
746
+
747
+ /**
748
+ * 更新前连通性预检:目标版本在 registry 上存在、tarball 能取到首字节。
749
+ * 用途只有一个 —— 「先卸载再安装」的两步法更新前,先证明装得回来,
750
+ * 避免卸载成功、安装却因网络/版本问题失败,把插件弄丢(0.2.4 加)。
751
+ */
752
+ async function preflightSource(name, version) {
753
+ const out = { ok: false, code: "", detail: "", version: "", tarball: "", registry: "" };
754
+ const pkg = String(name || "").trim();
755
+ if (!pkg) { out.code = "name-required"; return out; }
756
+ try {
757
+ const registry = resolveRegistry();
758
+ out.registry = registry;
759
+ const path = pkg.split("/").map(encodeURIComponent).join("/");
760
+ const res = await fetch(registry + "/" + path, {
761
+ headers: { accept: "application/vnd.npm.install-v1+json, application/json" },
762
+ signal: AbortSignal.timeout(15000),
763
+ });
764
+ if (!res.ok) { out.code = "registry-" + res.status; return out; }
765
+ const txt = await res.text();
766
+ if (txt.length > 16 * 1024 * 1024) { out.code = "registry-too-large"; return out; }
767
+ const doc = JSON.parse(txt);
768
+ const want = String(version || (doc && doc["dist-tags"] && doc["dist-tags"].latest) || "");
769
+ const item = doc && doc.versions && doc.versions[want];
770
+ if (!item) { out.code = "version-missing"; out.version = want; return out; }
771
+ const tarball = (item.dist && item.dist.tarball) || "";
772
+ if (!tarball) { out.code = "tarball-missing"; out.version = want; return out; }
773
+ const head = await fetch(tarball, {
774
+ headers: { range: "bytes=0-0" },
775
+ signal: AbortSignal.timeout(15000),
776
+ });
777
+ if (!head.ok && head.status !== 206) {
778
+ out.code = "tarball-" + head.status;
779
+ out.version = want;
780
+ out.tarball = tarball;
781
+ return out;
782
+ }
783
+ out.ok = true; out.version = want; out.tarball = tarball;
784
+ return out;
785
+ } catch (e) {
786
+ out.code = "network";
787
+ out.detail = String((e && e.name) || (e && e.message) || e).slice(0, 160);
788
+ return out;
789
+ }
790
+ }
791
+
792
+ /**
793
+ * 预检:这次强制更新会不会被别的包拦住。
794
+ * 只看 profile 的**直连依赖**(pnpm-lock 的 importers 段=面板管的那些插件;传递依赖不扫,
795
+ * 那要几百次网络查询),逐个判断「锁定版本是否已生效豁免」;没豁免的查发布时间,
796
+ * 仍在窗口内的列为拦路者。目标包自己跳过(强制流程会先给它写豁免)。
797
+ * 注意:门禁校验的是整个 lockfile,传递依赖或漏判的情况由安装失败时的反应式报错兜底
798
+ * (pnpm 的报错会点名违规条目)。
799
+ */
800
+ export async function precheckExempt(name, version, opts) {
801
+ const o = opts || {};
802
+ try {
803
+ const dir = o.dir || findProfileDir();
804
+ if (!dir) { return { ok: false, code: "profile-not-found" }; }
805
+ const windowMs = isFinite(o.windowMs) && o.windowMs > 0 ? o.windowMs : 1440 * 60000;
806
+ let importerVersions;
807
+ try { importerVersions = parseLockMaps(readFileSync(join(dir, "pnpm-lock.yaml"), "utf8")).importers; }
808
+ catch (e) { return { ok: false, code: "lockfile-unreadable: " + String((e && e.code) || e) }; }
809
+ let eff = new Map();
810
+ try { eff = effectiveExemptions(readFileSync(join(dir, WORKSPACE_FILE), "utf8")); } catch { /* 无 workspace 文件=无豁免 */ }
811
+
812
+ const now = Date.now();
813
+ const blocked = [];
814
+ let checked = 0;
815
+ for (const [pkg, ver] of importerVersions) {
816
+ if (pkg === name) { continue; }
817
+ if (!ver) { continue; }
818
+ if (eff.has(pkg)) {
819
+ const e = eff.get(pkg);
820
+ if (e === null || e === ver) { continue; } // 裸名豁免全部版本 / 精确命中锁定版本
821
+ }
822
+ const pub = await publishedAtOf(pkg, ver);
823
+ checked++;
824
+ if (pub !== null && pub + windowMs > now) {
825
+ blocked.push({ name: pkg, version: ver, publishedAt: pub, matureAt: pub + windowMs });
826
+ }
827
+ }
828
+ blocked.sort((a, b) => a.matureAt - b.matureAt);
829
+ return { ok: true, blocked, checked, windowMs };
830
+ } catch (e) {
831
+ return { ok: false, code: String((e && e.message) || e) };
832
+ }
833
+ }
834
+
835
+ // ---------- 自更新(模块 3 边角):面板不能卸载自己 ----------
836
+
837
+ /**
838
+ * 自更新所需的环境事实(profile 名 / 是否桌面端 / 客户端自带 CLI 的绝对路径)。
839
+ * CLI 的 `plugin add` 把参数原样转给 pnpm(`runPlugin` → `runProfilePnpm`,带
840
+ * `withFileLock(profile/package.json)`),**不经过** plugin-manager 的安装/卸载守卫,
841
+ * 所以既不会撞 `already-installed`,也不必先卸载自己(面板的「卸载 → 安装」会把
842
+ * 正在执行更新的插件本体卸掉,第二步随之消失 —— 真机上用户看到的就是「卸完就结束了」)。
843
+ *
844
+ * 桌面端必须用客户端自带的 CLI:PATH 上那份 npm 全局 dsh 会拒绝 desktop
845
+ * profile(`managed exclusively by the Electron application`)。web profile 用
846
+ * PATH 上的 dsh。路径由 process.execPath 推导,不硬编码、不随包分发。
847
+ *
848
+ * @param override 仅测试用:{ desktop, dir, execPath } 覆盖运行时探测。
849
+ */
850
+ export function selfUpdateInfo(override) {
851
+ const o = override || {};
852
+ const desktop = o.desktop !== undefined ? o.desktop === true : isDesktopRuntime();
853
+ const dir = o.dir !== undefined ? o.dir : findProfileDir();
854
+ const execPath = o.execPath || process.execPath;
855
+ const profile = dir ? basename(dir) : "";
856
+ if (desktop) {
857
+ const cli = join(dirname(execPath), "resources", "runtime", "cli", "bin", "dsh.cmd");
858
+ let present = false;
859
+ try { present = existsSync(cli); } catch { present = false; }
860
+ return { desktop: true, profile: profile || "desktop", cli: present ? cli : "" };
861
+ }
862
+ return { desktop: false, profile: profile || "web", cli: "" };
863
+ }
864
+
865
+ // ---------- 运行中的 DSH 版本(更新前的兼容门禁用) ----------
866
+
867
+ /** 缓存:同一进程里版本不会变;读不到也缓存 null,避免每次检查都重试 */
868
+ let dshVersionCache;
869
+
870
+ /**
871
+ * 运行中的 DSH 版本。首选宿主在 `profileContext` 上发布的 installAnchor(一个指向
872
+ * 运行中 @deepseek-ai/dsh 清单的绝对路径)—— 打包桌面端唯一答得上的来源;兜底读
873
+ * profile 自己装的 @deepseek-ai/dsh(npm 运行时)。
874
+ * 读不到返回 null:调用方据此**不做**兼容门禁(宁可漏拦,不误伤正常更新)。
875
+ */
876
+ function dshVersionOf(ctx) {
877
+ if (dshVersionCache !== undefined) { return dshVersionCache; }
878
+ dshVersionCache = null;
879
+ try {
880
+ const launched = ctx && typeof ctx.get === "function" ? ctx.get("profileContext") : null;
881
+ const anchor = launched && typeof launched.installAnchor === "string" ? launched.installAnchor.trim() : "";
882
+ if (anchor) {
883
+ const m = readJson(anchor);
884
+ if (m && typeof m.version === "string" && m.version.trim()) { dshVersionCache = m.version.trim(); return dshVersionCache; }
885
+ }
886
+ } catch { /* 没发布 anchor 的运行时 */ }
887
+ try {
888
+ const dir = findProfileDir();
889
+ const m = dir ? readJson(join(dir, "node_modules", "@deepseek-ai", "dsh", "package.json")) : null;
890
+ if (m && typeof m.version === "string" && m.version.trim()) { dshVersionCache = m.version.trim(); }
891
+ } catch { /* 读不到就算了 */ }
892
+ return dshVersionCache;
893
+ }
894
+
895
+ // ---------- 模块 7:立即重启 ----------
896
+
897
+ /** 重启助手等待旧进程退出的上限(毫秒);超时就照拉,避免助手永远等下去 */
898
+ const RESTART_WAIT_MS = 30000;
899
+
900
+ /** --inspect 系列会让新进程重新绑定固定端口,重拉时必须剔除 */
901
+ function isReusableExecArg(a) {
902
+ return !/^--(?:inspect|inspect-brk|inspect-port|debug|debug-brk)(?:=|$)/.test(String(a));
903
+ }
904
+
905
+ /** 是否跑在官方桌面客户端里(进程树归 Electron 外壳,插件重启不了它) */
906
+ function isDesktopRuntime(env) {
907
+ const e = env || process.env || {};
908
+ return String(e.ELECTRON_RUN_AS_NODE || "") === "1" || !!(process.versions && process.versions.electron);
909
+ }
910
+
911
+ /**
912
+ * 重启方案(纯函数,便于隔离测试):
913
+ * shell —— 桌面客户端:只退出,重启交给外壳自己的对话框
914
+ * relaunch —— 终端里跑起来的 dsh:detached 助手按原命令行重拉
915
+ * manual —— 无 TTY / 被别的程序托管:不动,如实告诉用户手动重启
916
+ */
917
+ export function planRestart(facts) {
918
+ const f = facts || {};
919
+ if (f.desktop === true) { return { mode: "shell" }; }
920
+ if (!f.interactive) { return { mode: "manual" }; }
921
+ const script = f.argv && f.argv[0];
922
+ if (!script) { return { mode: "manual" }; }
923
+ return {
924
+ mode: "relaunch",
925
+ command: {
926
+ execPath: f.execPath,
927
+ argv: (f.execArgv || []).filter(isReusableExecArg).concat([script], (f.argv || []).slice(1)),
928
+ cwd: f.cwd,
929
+ env: f.env || process.env,
930
+ },
931
+ };
932
+ }
933
+
934
+ /** 重启日志:与 dsh 自己的日志同处 $DSH_HOME/logs 下 */
935
+ function restartLogPath() {
936
+ const home = process.env.DSH_HOME || join(homedir(), ".dsh");
937
+ return join(home, "logs", "ui-tweaks-restart.log");
938
+ }
939
+
940
+ /**
941
+ * 重拉助手:作为 `node -e <源码> <job-json>` 运行,必须自包含、无依赖。
942
+ * 先等旧进程消失(或等满 waitMs),再按原命令行把 dsh 拉起来;新进程若 3 秒内
943
+ * 就退出,最多重试 5 次(端口还没释放这类瞬时失败很常见),日志落盘。
944
+ */
945
+ const RELAUNCH_HELPER = [
946
+ "const fs=require('node:fs'),cp=require('node:child_process');",
947
+ "const job=JSON.parse(process.argv[1]);",
948
+ "fs.mkdirSync(job.logDir,{recursive:true});",
949
+ "const fd=fs.openSync(job.logPath,'a');",
950
+ "const log=(l)=>{try{fs.appendFileSync(job.logPath,new Date().toISOString()+' '+l+'\\n')}catch{}};",
951
+ "const alive=(pid)=>{try{process.kill(pid,0);return true}catch{return false}};",
952
+ "const launch=(n)=>{",
953
+ " if(n>0)log('relaunch attempt '+(n+1));",
954
+ " const ch=cp.spawn(job.execPath,job.argv,{cwd:job.cwd,env:process.env,detached:true,stdio:['ignore',fd,fd]});",
955
+ " ch.unref();let code=null;ch.on('exit',(v)=>{code=v});",
956
+ " setTimeout(()=>{if(code===null){log('relaunch started (pid '+ch.pid+')');fs.closeSync(fd);return}"
957
+ + "if(n<4){log('relaunch exited with '+code+'; retrying');launch(n+1);return}"
958
+ + "log('relaunch gave up after exit '+code);fs.closeSync(fd)},3000)};",
959
+ "const wait=(dl)=>{if(!alive(job.parentPid)||Date.now()>=dl){setTimeout(()=>launch(0),300);return}setTimeout(()=>wait(dl),200)};",
960
+ "wait(Date.now()+job.waitMs);",
961
+ ].join("\n");
962
+
963
+ /** 起一个 detached 重拉助手;起不来返回 false(调用方据此退化为 manual) */
964
+ export function startRelaunchHelper(command, logPath) {
965
+ const file = logPath || restartLogPath();
966
+ const job = {
967
+ parentPid: process.pid,
968
+ execPath: command.execPath,
969
+ argv: command.argv,
970
+ cwd: command.cwd,
971
+ logDir: dirname(file),
972
+ logPath: file,
973
+ waitMs: RESTART_WAIT_MS,
974
+ };
975
+ try {
976
+ mkdirSync(dirname(file), { recursive: true });
977
+ const helper = spawn(command.execPath, ["-e", RELAUNCH_HELPER, JSON.stringify(job)], {
978
+ cwd: command.cwd,
979
+ env: command.env || process.env,
980
+ detached: true,
981
+ stdio: "ignore",
982
+ });
983
+ helper.unref();
984
+ return helper.pid !== undefined;
985
+ } catch (e) {
986
+ try { appendFileSync(file, new Date().toISOString() + " helper failed: " + String((e && e.message) || e) + "\n"); } catch { /* 日志写不了就算了 */ }
987
+ return false;
988
+ }
989
+ }
990
+
991
+ /**
992
+ * 执行方案:先安排退出(0.4s 后,够响应写回浏览器),再让进程消失。
993
+ * relaunch 起不了助手 → manual:进程留在原地,不把用户丢在没有服务的状态。
994
+ * runtime 只为隔离测试注入(默认就是真的起助手 / 真的退出)。
995
+ */
996
+ export function performRestart(plan, runtime) {
997
+ const rt = runtime || {};
998
+ if (plan.mode === "manual") { return "manual"; }
999
+ if (plan.mode === "relaunch") {
1000
+ const start = rt.startHelper || ((command) => startRelaunchHelper(command));
1001
+ if (!plan.command || !start(plan.command)) { return "manual"; }
1002
+ }
1003
+ const schedule = rt.schedule || ((run, ms) => { setTimeout(run, ms); });
1004
+ const exit = rt.exit || (() => { process.exit(0); });
1005
+ schedule(exit, 400);
1006
+ return plan.mode;
1007
+ }
1008
+
1009
+ /** 本进程自己的启动事实(只读,每次请求现取) */
1010
+ function liveRestartFacts() {
1011
+ return {
1012
+ desktop: isDesktopRuntime(process.env),
1013
+ interactive: process.stdin.isTTY === true || process.stdout.isTTY === true,
1014
+ execPath: process.execPath,
1015
+ argv: process.argv.slice(1),
1016
+ execArgv: process.execArgv,
1017
+ cwd: process.cwd(),
1018
+ env: process.env,
1019
+ };
1020
+ }
1021
+
1022
+ export function apply(ctx) {
1023
+ const respond = (res) => (code, body) => {
1024
+ res.writeHead(code, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
1025
+ res.end(body);
1026
+ };
1027
+ const isLoopback = (req) => LOOPBACK_RE.test(String((req.socket && req.socket.remoteAddress) || ""));
1028
+
1029
+ // 小体积 JSON body 读取(只给下面几条强制更新路由用;上限 8KB,超了当非法)
1030
+ const readJsonBody = (req, cb) => {
1031
+ let buf = "";
1032
+ let bad = false;
1033
+ req.on("data", (c) => { if (bad) { return; } buf += c; if (buf.length > 8192) { bad = true; } });
1034
+ req.on("end", () => {
1035
+ if (bad) { cb({}); return; }
1036
+ try { cb(buf ? JSON.parse(buf) : {}); } catch { cb({}); }
1037
+ });
1038
+ req.on("error", () => cb({}));
1039
+ };
1040
+
1041
+ /* ---- 强制更新豁免的到期清理 ----------------------------------------------
1042
+ * 「装完立刻删豁免」是错的:pnpm 每次安装都会拿**整个 lockfile** 去校验供应链策略,
1043
+ * 被强制装上的版本还没满 24 小时时删掉豁免,接下来几小时里游 profile 的**所有** pnpm
1044
+ * 操作都会被整体拒绝(ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION),比留着更糟。
1045
+ * 正确时机是「该版本成熟之后」:客户端在强制更新时把到期时刻登记过来,这里落盘 +
1046
+ * 到点删表项;宿重启后按文件记录重新排期(到期未处理的立刻删)。 */
1047
+ const cleanupTimers = new Map(); // name@version → timer
1048
+ const cleanupFile = () => {
1049
+ const dir = findProfileDir();
1050
+ return dir ? join(dir, "ui-tweaks", "exempt-pending.json") : null;
1051
+ };
1052
+ const readCleanupList = () => {
1053
+ const f = cleanupFile();
1054
+ if (!f) { return []; }
1055
+ try {
1056
+ const list = JSON.parse(readFileSync(f, "utf8"));
1057
+ return Array.isArray(list) ? list.filter((it) => it && typeof it.name === "string" && typeof it.version === "string" && isFinite(it.dropAt)) : [];
1058
+ } catch { return []; }
1059
+ };
1060
+ const writeCleanupList = (list) => {
1061
+ const f = cleanupFile();
1062
+ if (!f) { return; }
1063
+ try {
1064
+ mkdirSync(dirname(f), { recursive: true });
1065
+ writeFileSync(f, JSON.stringify(list, null, 2) + "\n", "utf8");
1066
+ } catch { /* 写不了就只在内存里生效 */ }
1067
+ };
1068
+ const runCleanup = (item) => {
1069
+ const key = item.name + "@" + item.version;
1070
+ const timer = cleanupTimers.get(key);
1071
+ if (timer) { try { clearTimeout(timer); } catch { } cleanupTimers.delete(key); }
1072
+ const r = dropExemptVersion(item.name, item.version);
1073
+ const rest = readCleanupList().filter((it) => !(it.name === item.name && it.version === item.version));
1074
+ if (!r.ok) {
1075
+ // 删失败(文件被占用等):10 分钟后再试,别把记录丢了
1076
+ writeCleanupList(rest.concat([{ name: item.name, version: item.version, dropAt: Date.now() + 10 * 60 * 1000 }]));
1077
+ return;
1078
+ }
1079
+ writeCleanupList(rest);
1080
+ };
1081
+ const armCleanup = (item) => {
1082
+ const key = item.name + "@" + item.version;
1083
+ const prev = cleanupTimers.get(key);
1084
+ if (prev) { try { clearTimeout(prev); } catch { } cleanupTimers.delete(key); }
1085
+ const delay = Math.max(0, Number(item.dropAt) - Date.now());
1086
+ if (!isFinite(delay) || delay > 2147483000) { return; }
1087
+ const timer = setTimeout(() => runCleanup(item), delay);
1088
+ if (timer && typeof timer.unref === "function") { timer.unref(); }
1089
+ cleanupTimers.set(key, timer);
1090
+ };
1091
+ const scheduleCleanup = (item) => {
1092
+ writeCleanupList(readCleanupList().filter((it) => !(it.name === item.name && it.version === item.version)).concat([item]));
1093
+ armCleanup(item);
1094
+ };
1095
+
1096
+ const routes = [
1097
+ {
1098
+ kind: "exact",
1099
+ path: "/api/ui-tweaks/local-plugins",
1100
+ handler: (req, res) => {
1101
+ const done = respond(res);
1102
+ try {
1103
+ if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1104
+ if (req.method !== "GET") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1105
+ const dir = findProfileDir();
1106
+ const manifest = dir ? readJson(join(dir, "package.json")) : null;
1107
+ const deps = (manifest && manifest.dependencies) || {};
1108
+ const local = []; // link:/file: —— 本地路径
1109
+ const remote = []; // git/github/http —— 仓库或 URL 直装
1110
+ for (const [n, spec] of Object.entries(deps)) {
1111
+ const s = String(spec);
1112
+ if (LOCAL_SPEC_RE.test(s)) { local.push(n); }
1113
+ else if (REMOTE_SPEC_RE.test(s)) { remote.push(n); }
1114
+ }
1115
+ done(200, JSON.stringify({ ok: true, local, remote, profile: (manifest && manifest.name) || "", dsh: dshVersionOf(ctx) || "", selfUpdate: selfUpdateInfo() }));
1116
+ } catch (e) {
1117
+ done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) }));
1118
+ }
1119
+ }
1120
+ },
1121
+ {
1122
+ kind: "exact",
1123
+ path: "/api/ui-tweaks/normalize-excludes",
1124
+ handler: (req, res) => {
1125
+ const done = respond(res);
1126
+ try {
1127
+ if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1128
+ if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1129
+ const r = normalizeReleaseAgeExcludes();
1130
+ if (!r.ok) { done(500, JSON.stringify({ ok: false, code: r.code })); return; }
1131
+ done(200, JSON.stringify({ ok: true, changed: r.changed, kept: r.kept, removed: r.removed }));
1132
+ } catch (e) {
1133
+ done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) }));
1134
+ }
1135
+ }
1136
+ },
1137
+ {
1138
+ /* 强制更新·第一步:预检会不会被别的包拦住(只扫直连依赖 + 豁免表 + 发布时长) */
1139
+ kind: "exact",
1140
+ path: "/api/ui-tweaks/precheck-exempt",
1141
+ handler: (req, res) => {
1142
+ const done = respond(res);
1143
+ if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1144
+ if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1145
+ readJsonBody(req, (body) => {
1146
+ const name = body && typeof body.name === "string" ? body.name : "";
1147
+ const version = body && typeof body.version === "string" ? body.version : "";
1148
+ if (!name || !version) { done(400, JSON.stringify({ ok: false, code: "name/version required" })); return; }
1149
+ const windowMs = body && isFinite(body.windowMs) && body.windowMs > 0 ? Number(body.windowMs) : 0;
1150
+ precheckExempt(name, version, { windowMs })
1151
+ .then((r) => done(r.ok ? 200 : 500, JSON.stringify(r)))
1152
+ .catch((e) => done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) })));
1153
+ });
1154
+ }
1155
+ },
1156
+ {
1157
+ /* 强制更新·第二步:把 name@version 写成豁免表里该包生效的第一条 */
1158
+ kind: "exact",
1159
+ path: "/api/ui-tweaks/force-exempt",
1160
+ handler: (req, res) => {
1161
+ const done = respond(res);
1162
+ if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1163
+ if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1164
+ readJsonBody(req, (body) => {
1165
+ const name = body && typeof body.name === "string" ? body.name : "";
1166
+ const version = body && typeof body.version === "string" ? body.version : "";
1167
+ if (!name || !version) { done(400, JSON.stringify({ ok: false, code: "name/version required" })); return; }
1168
+ const r = forceExemptVersion(name, version);
1169
+ done(r.ok ? 200 : 500, JSON.stringify(r));
1170
+ });
1171
+ }
1172
+ },
1173
+ {
1174
+ /* 改动卡补位的「打开 / 显示位置 / 选择应用」:会话释放后官方 /api/changes.open
1175
+ 只回 404,这里交给 Host 桌面接手(官方 native-command 优先,见 openNativeTarget)。
1176
+ action 还可以是 "probe":只诊断子进程能不能跑,不弹任何窗口。 */
1177
+ kind: "exact",
1178
+ path: "/api/ui-tweaks/open-path",
1179
+ handler: (req, res) => {
1180
+ const done = respond(res);
1181
+ if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1182
+ if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1183
+ readJsonBody(req, (body) => {
1184
+ const target = body && typeof body.path === "string" ? body.path : "";
1185
+ const action = body && (body.action === "reveal" || body.action === "probe") ? body.action : "open";
1186
+ const application = body && typeof body.application === "string" ? body.application : "";
1187
+ if (action === "probe") {
1188
+ probeNativeLaunch().then(
1189
+ (r) => done(200, JSON.stringify(r)),
1190
+ (e) => done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) })));
1191
+ return;
1192
+ }
1193
+ openNativeTarget(target, action, application).then((r) => {
1194
+ if (r.ok) { done(200, JSON.stringify(r)); return; }
1195
+ const status = r.code === "path-not-found" ? 404
1196
+ : (r.code === "path required" || r.code === "absolute-path required") ? 400 : 500;
1197
+ done(status, JSON.stringify(r));
1198
+ }, (e) => done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) })));
1199
+ });
1200
+ }
1201
+ },
1202
+ {
1203
+ /* 读文本文件(只读、限大小):补位 diff 想知道片段在文件里的真实行号时用。
1204
+ 回 {ok, text, bytes} 或 {ok:false, code}(not-a-file / too-large / ENOENT …)。 */
1205
+ kind: "exact",
1206
+ path: "/api/ui-tweaks/read-text",
1207
+ handler: (req, res) => {
1208
+ const done = respond(res);
1209
+ if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1210
+ if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1211
+ readJsonBody(req, (body) => {
1212
+ const target = body && typeof body.path === "string" ? body.path : "";
1213
+ const maxBytes = Math.min(8 * 1024 * 1024, Math.max(4096, Number(body && body.maxBytes) || 4 * 1024 * 1024));
1214
+ if (!target) { done(200, JSON.stringify({ ok: false, code: "path-required" })); return; }
1215
+ (async () => {
1216
+ try {
1217
+ const { readFile, stat } = await import("node:fs/promises");
1218
+ const st = await stat(target);
1219
+ if (!st.isFile()) { return { ok: false, code: "not-a-file" }; }
1220
+ if (st.size > maxBytes) { return { ok: false, code: "too-large", bytes: st.size }; }
1221
+ const text = await readFile(target, "utf8");
1222
+ return { ok: true, text, bytes: st.size };
1223
+ } catch (e) {
1224
+ return { ok: false, code: String((e && e.code) || (e && e.message) || e) };
1225
+ }
1226
+ })().then((r) => done(200, JSON.stringify(r)),
1227
+ (e) => done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) })));
1228
+ });
1229
+ }
1230
+ },
1231
+ {
1232
+ /* 更新前连通性预检:两步法(先卸载再安装)之前,先确认目标版本可下载。
1233
+ 回 {ok, code, version, tarball, detail};网络不通/版本不存在都回 ok:false。 */
1234
+ kind: "exact",
1235
+ path: "/api/ui-tweaks/preflight-source",
1236
+ handler: (req, res) => {
1237
+ const done = respond(res);
1238
+ if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1239
+ if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1240
+ readJsonBody(req, (body) => {
1241
+ const name = body && typeof body.name === "string" ? body.name : "";
1242
+ const version = body && typeof body.version === "string" ? body.version : "";
1243
+ preflightSource(name, version).then(
1244
+ (r) => done(200, JSON.stringify(r)),
1245
+ (e) => done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) })));
1246
+ });
1247
+ }
1248
+ },
1249
+ {
1250
+ /* 官方 /api/changes.open 的 GET(应用列表)补位:复用官方 native-command 枚举系统关联 */
1251
+ kind: "exact",
1252
+ path: "/api/ui-tweaks/open-apps",
1253
+ handler: (req, res) => {
1254
+ const done = respond(res);
1255
+ if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1256
+ if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1257
+ readJsonBody(req, (body) => {
1258
+ const target = body && typeof body.path === "string" ? body.path : "";
1259
+ listOpenApplications(target).then(
1260
+ (r) => done(200, JSON.stringify(r)),
1261
+ (e) => done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) })));
1262
+ });
1263
+ }
1264
+ },
1265
+ {
1266
+ /* 登记「强行装上的版本到期后清掉它的豁免」;客户端在强制更新成功后调用 */
1267
+ kind: "exact",
1268
+ path: "/api/ui-tweaks/schedule-exempt-cleanup",
1269
+ handler: (req, res) => {
1270
+ const done = respond(res);
1271
+ if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1272
+ if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1273
+ readJsonBody(req, (body) => {
1274
+ const name = body && typeof body.name === "string" ? body.name : "";
1275
+ const version = body && typeof body.version === "string" ? body.version : "";
1276
+ const dropAt = body && isFinite(body.dropAt) ? Number(body.dropAt) : 0;
1277
+ if (!name || !version || !(dropAt > 0)) { done(400, JSON.stringify({ ok: false, code: "name/version/dropAt required" })); return; }
1278
+ try {
1279
+ scheduleCleanup({ name, version, dropAt });
1280
+ done(200, JSON.stringify({ ok: true, name, version, dropAt, at: new Date(dropAt).toISOString() }));
1281
+ } catch (e) {
1282
+ done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) }));
1283
+ }
1284
+ });
1285
+ }
1286
+ },
1287
+ {
1288
+ /* 立即重启:GET 只读方案(无副作用),POST 才执行;无法重拉时如实回 manual */
1289
+ kind: "exact",
1290
+ path: "/api/ui-tweaks/restart",
1291
+ handler: (req, res) => {
1292
+ const done = respond(res);
1293
+ if (!isLoopback(req)) { done(403, JSON.stringify({ ok: false, code: "forbidden" })); return; }
1294
+ try {
1295
+ const plan = planRestart(liveRestartFacts());
1296
+ if (req.method === "GET" || req.method === "HEAD") { done(200, JSON.stringify({ ok: true, mode: plan.mode })); return; }
1297
+ if (req.method !== "POST") { done(405, JSON.stringify({ ok: false, code: "method not allowed" })); return; }
1298
+ const mode = performRestart(plan);
1299
+ done(202, JSON.stringify({ ok: true, mode }));
1300
+ } catch (e) {
1301
+ done(500, JSON.stringify({ ok: false, code: String((e && e.message) || e) }));
1302
+ }
1303
+ }
1304
+ }
1305
+ ];
1306
+
1307
+ ctx.effect(() => {
1308
+ const disposes = routes.map((r) => ctx.webServer.register(r));
1309
+ return () => { for (const d of disposes) { try { d(); } catch { /* 已释放 */ } } };
1310
+ }, "ui-tweaks: loopback routes");
1311
+
1312
+ // 加载时静默收敛一次(fire-and-forget:异常绝不影响插件加载)
1313
+ try { normalizeReleaseAgeExcludes(); } catch { /* 归并自身已吞异常,这里只兜底 */ }
1314
+
1315
+ /* 恢复上次没清完的豁免清理:已到期的立刻删,其余重新排期。
1316
+ 清单在 profile/ui-tweaks/exempt-pending.json(跨客户端重启有效)。 */
1317
+ try {
1318
+ for (const it of readCleanupList()) {
1319
+ if (Number(it.dropAt) <= Date.now()) { runCleanup(it); }
1320
+ else { armCleanup(it); }
1321
+ }
1322
+ } catch { /* 记录坏了就当没有 */ }
1323
+ ctx.effect(() => () => {
1324
+ for (const t of cleanupTimers.values()) { try { clearTimeout(t); } catch { } }
1325
+ cleanupTimers.clear();
1326
+ }, "ui-tweaks: exempt cleanup timers");
1327
+
1328
+ // 桌面客户端:拉起窗口记忆 helper(非桌面环境内部自动不动作)
1329
+ startWindowState(ctx);
1330
+ }