dsh-multipane 1.0.51 → 1.0.53

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,241 +1,529 @@
1
- /**
2
- * Host half of dsh-split-view.
3
- *
4
- * The feature is a pure client-surface extension: it registers a `main` panel
5
- * that renders the existing conversation panel several times, each bound to its
6
- * own session. `apply` therefore has one real job beyond keeping the bundle row
7
- * mountable: keep this plugin installable through the plugin market on THIS
8
- * machine.
9
- *
10
- * pnpm refuses packages younger than the profile's minimumReleaseAge unless that
11
- * exact version is listed under minimumReleaseAgeExclude in
12
- * ~/.dsh/profiles/<profile>/pnpm-workspace.yaml. That list is per-machine and
13
- * per-profile, so every release used to break "update from the settings page" on
14
- * any machine whose list had not been edited by hand — something a user should
15
- * never have to do, and cannot reasonably do without a terminal.
16
- *
17
- * The host half has filesystem access, so it keeps the bookkeeping itself: on
18
- * load, append the running version to the existing dsh-multipane line when it is
19
- * missing. Nothing here may affect plugin loading, so every path is guarded.
20
- */
21
-
22
- import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
23
- import { execFile } from "node:child_process";
24
- import { homedir } from "node:os";
25
- import { join } from "node:path";
26
- import { fileURLToPath } from "node:url";
27
-
28
- /** Cordis plugin name used by the loader row. */
29
- export const name = 'dsh-split-view';
30
-
31
- /** No host services are required. */
32
- export const inject = [];
33
-
34
- /** Package name as published; also the name the market knows. */
35
- const PKG_NAME = "dsh-multipane";
36
-
37
- function readOwnVersion() {
38
- try {
39
- const pkgPath = fileURLToPath(new URL("../package.json", import.meta.url));
40
- const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
41
- return typeof pkg.version === "string" ? pkg.version : "";
42
- } catch {
43
- return "";
44
- }
45
- }
46
-
47
- /**
48
- * Append `version` to the dsh-multipane row of one profile's pnpm-workspace.yaml.
49
- * The row has to be edited in place: pnpm honours only the FIRST rule per package
50
- * name, so appending a second line for the same name is ignored.
51
- *
52
- * @param {string} profileDir absolute path of the profile directory
53
- * @param {string} version version to allow
54
- * @returns boolean whether the file was changed
55
- */
56
- function allowVersionOnThisMachine(profileDir, version) {
57
- const yamlPath = join(profileDir, "pnpm-workspace.yaml");
58
- if (!existsSync(yamlPath)) return false;
59
- const lines = readFileSync(yamlPath, "utf8").split(/\r?\n/);
60
- const index = lines.findIndex((line) => line.indexOf(PKG_NAME + "@") >= 0);
61
- if (index < 0) return false;
62
- const escaped = version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
63
- if (new RegExp("(^|[\\s|])" + escaped + "(\\s|$)").test(lines[index])) return false;
64
- lines[index] = lines[index].trimEnd() + " || " + version;
65
- writeFileSync(yamlPath, lines.join("\n"), "utf8");
66
- return true;
67
- }
68
-
69
- /**
70
- * Try every profile that exists on this machine (desktop is what the app uses,
71
- * web is used by headless checks). Unknown layouts are skipped silently.
72
- */
73
- function ensureMarketInstallable() {
74
- try {
75
- const version = readOwnVersion();
76
- if (version === "") return;
77
- const root = join(homedir(), ".dsh", "profiles");
78
- if (!existsSync(root)) return;
79
- for (const profile of ["desktop", "web"]) {
80
- try {
81
- allowVersionOnThisMachine(join(root, profile), version);
82
- } catch {
83
- /* 单个 profile 失败不影响另一个,也不影响插件加载 */
84
- }
85
- }
86
- } catch {
87
- /* 绝不因为这里失败而挡住插件加载 */
88
- }
89
- }
90
-
91
- /**
92
- * Mount the host half.
93
- *
94
- * @returns void
95
- */
96
- const UPDATE_ROUTE = "/dsh-multipane/update";
97
- const STATUS_ROUTE = "/dsh-multipane/status";
98
-
99
- /**
100
- * Install one published version straight from the npm registry.
101
- *
102
- * Why not the package manager: the market path goes through pnpm, which refuses
103
- * releases younger than the profile's minimumReleaseAge, and the market itself
104
- * syncs its catalog minutes behind the registry. Downloading the published
105
- * tarball and unpacking it is what "update from npm" means here — no pnpm, no
106
- * third-party catalog, no release-age wait.
107
- *
108
- * Safety: copy the current directory aside first, and put it back if anything
109
- * fails, so a half-written plugin can never brick the app.
110
- *
111
- * @param {string} profileDir profile directory that owns node_modules
112
- * @param {string} version version to install
113
- * @returns {Promise<{ok: boolean, message: string}>} result
114
- */
115
- function installFromRegistry(profileDir, version) {
116
- const target = join(profileDir, "node_modules", PKG_NAME);
117
- const staging = join(homedir(), ".dsh", ".dsv-update-" + process.pid);
118
- const backup = join(homedir(), ".dsh", ".dsv-backup-" + process.pid);
119
- const tarball = join(staging, "pkg.tgz");
120
- const url = "https://registry.npmjs.org/" + PKG_NAME + "/-/" + PKG_NAME + "-" + version + ".tgz";
121
- const run = (file, args, options) =>
122
- new Promise((resolve) => {
123
- execFile(file, args, Object.assign({ timeout: 120000, windowsHide: true }, options || {}), (error, stdout, stderr) => {
124
- resolve({ ok: error === null, out: String(stdout || ""), err: String(stderr || (error && error.message) || "") });
125
- });
126
- });
127
- return (async () => {
128
- try {
129
- rmSync(staging, { recursive: true, force: true });
130
- rmSync(backup, { recursive: true, force: true });
131
- mkdirSync(staging, { recursive: true });
132
- const dl = await run("curl", ["-sSL", "--noproxy", "*", "--max-time", "110", "-o", tarball, url]);
133
- if (!dl.ok || !existsSync(tarball)) return { ok: false, message: "下载失败:" + dl.err.slice(0, 200) };
134
- /* 必须用 Windows 自带的 bsdtar:git-bash 里的 GNU tar 会把 "C:/…" 当成
135
- host:path 语法去连远程主机(报 "Cannot connect to C: resolve failed")。 */
136
- const tarExe = existsSync("C:/Windows/System32/tar.exe") ? "C:/Windows/System32/tar.exe" : "tar";
137
- const un = await run(tarExe, ["-xzf", tarball, "-C", staging]);
138
- if (!un.ok) return { ok: false, message: "解压失败:" + un.err.slice(0, 200) };
139
- const unpacked = join(staging, "package");
140
- if (!existsSync(join(unpacked, "package.json"))) return { ok: false, message: "包里没有 package.json" };
141
- const got = JSON.parse(readFileSync(join(unpacked, "package.json"), "utf8")).version;
142
- if (got !== version) return { ok: false, message: "包内版本是 " + got + ",不是 " + version };
143
- if (existsSync(target)) {
144
- cpSync(target, backup, { recursive: true });
145
- }
146
- rmSync(target, { recursive: true, force: true });
147
- cpSync(unpacked, target, { recursive: true });
148
- rmSync(staging, { recursive: true, force: true });
149
- rmSync(backup, { recursive: true, force: true });
150
- return { ok: true, message: "已安装 " + version };
151
- } catch (error) {
152
- try {
153
- if (existsSync(backup)) {
154
- rmSync(target, { recursive: true, force: true });
155
- cpSync(backup, target, { recursive: true });
156
- }
157
- } catch {
158
- /* 回滚失败也不抛出 */
159
- }
160
- return { ok: false, message: String((error && error.message) || error) };
161
- }
162
- })();
163
- }
164
-
165
- function readJsonBody(request, limit, done) {
166
- let body = "";
167
- let aborted = false;
168
- request.on("data", (chunk) => {
169
- body += chunk;
170
- if (body.length > limit) {
171
- aborted = true;
172
- request.destroy();
173
- }
174
- });
175
- request.on("end", () => {
176
- if (!aborted) done(body);
177
- });
178
- request.on("error", () => {
179
- /* 忽略 */
180
- });
181
- }
182
-
183
- export function apply(ctx) {
184
- try {
185
- ensureMarketInstallable();
186
- } catch {
187
- /* 忽略 */
188
- }
189
- try {
190
- ctx.inject(["webServer"], (host) => {
191
- const profileDirOf = () => join(homedir(), ".dsh", "profiles", "desktop");
192
- const routes = [
193
- {
194
- kind: "exact",
195
- path: STATUS_ROUTE,
196
- handler: (request, response) => {
197
- response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
198
- response.end(JSON.stringify({ version: readOwnVersion(), profile: profileDirOf() }));
199
- }
200
- },
201
- {
202
- kind: "exact",
203
- path: UPDATE_ROUTE,
204
- handler: (request, response) => {
205
- if (request.method !== "POST") {
206
- response.writeHead(405, { allow: "POST" });
207
- response.end("");
208
- return;
209
- }
210
- readJsonBody(request, 4096, (body) => {
211
- let version = "";
212
- try {
213
- version = String(JSON.parse(body).version || "");
214
- } catch {
215
- /* 交给下面校验 */
216
- }
217
- if (!/^\d+\.\d+\.\d+$/.test(version)) {
218
- response.writeHead(400, { "content-type": "application/json; charset=utf-8" });
219
- response.end(JSON.stringify({ ok: false, message: "version 参数不合法" }));
220
- return;
221
- }
222
- installFromRegistry(profileDirOf(), version).then((result) => {
223
- response.writeHead(result.ok ? 200 : 500, { "content-type": "application/json; charset=utf-8" });
224
- response.end(JSON.stringify(result));
225
- });
226
- });
227
- }
228
- }
229
- ];
230
- for (const route of routes) {
231
- try {
232
- host.webServer.register(route);
233
- } catch {
234
- /* 单个路由失败不影响另一个 */
235
- }
236
- }
237
- });
238
- } catch {
239
- /* 拿不到 webServer 就只是没有设置页内的更新入口,插件本身照常工作 */
240
- }
241
- }
1
+ /**
2
+ * Host half of dsh-split-view.
3
+ *
4
+ * The feature is a pure client-surface extension: it registers a `main` panel
5
+ * that renders the existing conversation panel several times, each bound to its
6
+ * own session. `apply` therefore has one real job beyond keeping the bundle row
7
+ * mountable: keep this plugin installable through the plugin market on THIS
8
+ * machine.
9
+ *
10
+ * pnpm refuses packages younger than the profile's minimumReleaseAge unless that
11
+ * exact version is listed under minimumReleaseAgeExclude in
12
+ * ~/.dsh/profiles/<profile>/pnpm-workspace.yaml. That list is per-machine and
13
+ * per-profile, so every release used to break "update from the settings page" on
14
+ * any machine whose list had not been edited by hand — something a user should
15
+ * never have to do, and cannot reasonably do without a terminal.
16
+ *
17
+ * The host half has filesystem access, so it keeps the bookkeeping itself: on
18
+ * load, append the running version to the existing dsh-multipane line when it is
19
+ * missing. Nothing here may affect plugin loading, so every path is guarded.
20
+ *
21
+ * The same account has a second half, and skipping it is what made an update look
22
+ * like it never happened: installing the files under node_modules does NOT touch
23
+ * the profile's package.json or pnpm-lock.yaml, which still pin the OLD version.
24
+ * The next `pnpm install` in that profile — installing or removing ANY other
25
+ * plugin — then re-materialises the locked version over the fresh files, silently
26
+ * downgrading this plugin and bringing the "new version available" prompt right
27
+ * back (measured 2026-11-12: 1.0.51 installed, the 9:42 synapse install later,
28
+ * directory 1.0.37 again, settings page still offering 1.0.51). So a successful
29
+ * update now also rewrites both bookkeeping files to the new version and its
30
+ * integrity, and writes neither when either edit cannot be proven exact.
31
+ */
32
+
33
+ import { cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
34
+ import { execFile } from "node:child_process";
35
+ import { createHash } from "node:crypto";
36
+ import { homedir } from "node:os";
37
+ import { join } from "node:path";
38
+ import { fileURLToPath } from "node:url";
39
+
40
+ /** Cordis plugin name used by the loader row. */
41
+ export const name = 'dsh-split-view';
42
+
43
+ /** No host services are required. */
44
+ export const inject = [];
45
+
46
+ /** Package name as published; also the name the market knows. */
47
+ const PKG_NAME = "dsh-multipane";
48
+
49
+ function readOwnVersion() {
50
+ try {
51
+ const pkgPath = fileURLToPath(new URL("../package.json", import.meta.url));
52
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
53
+ return typeof pkg.version === "string" ? pkg.version : "";
54
+ } catch {
55
+ return "";
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Append `version` to the dsh-multipane row of one profile's pnpm-workspace.yaml.
61
+ * The row has to be edited in place: pnpm honours only the FIRST rule per package
62
+ * name, so appending a second line for the same name is ignored.
63
+ *
64
+ * @param {string} profileDir absolute path of the profile directory
65
+ * @param {string} version version to allow
66
+ * @returns boolean whether the file was changed
67
+ */
68
+ function allowVersionOnThisMachine(profileDir, version) {
69
+ const yamlPath = join(profileDir, "pnpm-workspace.yaml");
70
+ if (!existsSync(yamlPath)) return false;
71
+ const lines = readFileSync(yamlPath, "utf8").split(/\r?\n/);
72
+ const index = lines.findIndex((line) => line.indexOf(PKG_NAME + "@") >= 0);
73
+ if (index < 0) return false;
74
+ const escaped = version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
75
+ if (new RegExp("(^|[\\s|])" + escaped + "(\\s|$)").test(lines[index])) return false;
76
+ lines[index] = lines[index].trimEnd() + " || " + version;
77
+ writeFileSync(yamlPath, lines.join("\n"), "utf8");
78
+ return true;
79
+ }
80
+
81
+ /**
82
+ * Escape a literal string so it can be embedded in a RegExp source.
83
+ *
84
+ * @param {string} text literal text
85
+ * @returns string regex-safe text
86
+ */
87
+ function escapeRegex(text) {
88
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
89
+ }
90
+
91
+ /**
92
+ * npm-style sha512 integrity of a file ("sha512-" + base64 of the digest).
93
+ *
94
+ * pnpm stores exactly this string as the lockfile entry's integrity. A stale or
95
+ * invented one makes the next install treat the package as tampered with, which
96
+ * is worse than leaving the old entry alone.
97
+ *
98
+ * @param {string} file absolute path of the tarball
99
+ * @returns {string} integrity string, or "" when the file cannot be read
100
+ */
101
+ function integrityOfFile(file) {
102
+ try {
103
+ return "sha512-" + createHash("sha512").update(readFileSync(file)).digest("base64");
104
+ } catch {
105
+ return "";
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Point the profile's dependency bookkeeping at `version`.
111
+ *
112
+ * Two files decide what the next `pnpm install` believes about this package:
113
+ * package.json (the specifier the profile asks for) and pnpm-lock.yaml (the
114
+ * specifier it expects, plus the version and integrity it will materialise). If
115
+ * both keep naming the old version, the very next install in the profile
116
+ * silently downgrades the files an update just wrote.
117
+ *
118
+ * Both files are edited as text rather than through a JSON/YAML round-trip, so
119
+ * the user's formatting survives. Nothing is written unless both edits are known
120
+ * to be exact: half-updated bookkeeping (new specifier, old lock entry) would
121
+ * make pnpm reject the whole profile instead of merely rolling this one package
122
+ * back — a much worse failure than the bug being fixed.
123
+ *
124
+ * @param {string} profileDir absolute path of the profile directory
125
+ * @param {string} version version that was just installed
126
+ * @param {string} integrity sha512 integrity of the tarball that was installed
127
+ * @returns {{ok: boolean, changed: boolean, problems: string[]}} result
128
+ */
129
+ function syncDependencyBookkeeping(profileDir, version, integrity) {
130
+ const pkgPath = join(profileDir, "package.json");
131
+ const lockPath = join(profileDir, "pnpm-lock.yaml");
132
+ const problems = [];
133
+
134
+ let pkgText = "";
135
+ let lockText = "";
136
+ try {
137
+ if (existsSync(pkgPath)) pkgText = readFileSync(pkgPath, "utf8");
138
+ } catch (error) {
139
+ problems.push("读不了 package.json:" + String((error && error.message) || error));
140
+ }
141
+ try {
142
+ if (existsSync(lockPath)) lockText = readFileSync(lockPath, "utf8");
143
+ } catch (error) {
144
+ problems.push("读不了 pnpm-lock.yaml:" + String((error && error.message) || error));
145
+ }
146
+ if (pkgText === "") problems.push("找不到 profile 的 package.json");
147
+ if (lockText === "") problems.push("找不到 pnpm-lock.yaml");
148
+
149
+ /* 依赖行本就存在的三种形状都认:dependencies、devDependencies、optional… 这里只按
150
+ 「"dsh-multipane": "<spec>"」这一处文本换掉 spec,不关心它在哪个段里。 */
151
+ const depRe = new RegExp('("' + escapeRegex(PKG_NAME) + '"\\s*:\\s*")[^"]*(")');
152
+ if (pkgText !== "" && !depRe.test(pkgText)) problems.push("package.json 里没有 " + PKG_NAME + " 的依赖行");
153
+ if (problems.length > 0) return { ok: false, changed: false, problems };
154
+
155
+ /* importer 块:specifier 与 version 成对出现,两行都要换。前导换行必须在捕获组里,
156
+ 否则替换会把上一行与这一行粘成一行 —— YAML 直接坏掉,pnpm 拒绝整个 profile。 */
157
+ const importerRe = new RegExp("(\\n " + escapeRegex(PKG_NAME) + ":\\n specifier: )([^\\n]*)(\\n version: )([^\\n]*)");
158
+ const hit = lockText.match(importerRe);
159
+ if (hit === null) return { ok: false, changed: false, problems: ["pnpm-lock 里没有 " + PKG_NAME + " 的 importer 块"] };
160
+ /* version 可能带 peer 后缀(1.0.37(@deepseek-ai/dsh@…)),键名里只比裸版本号。 */
161
+ const previous = hit[4].trim().split("(")[0];
162
+ const changed = previous !== version;
163
+
164
+ let nextLock = lockText;
165
+ if (changed) {
166
+ nextLock = nextLock.replace(importerRe, (all, head, spec, mid) => head + version + mid + version);
167
+ /* packages 段与 snapshots 段各有一条键: dsh-multipane@<版本>: */
168
+ const keyRe = new RegExp("(^|\\n)( " + escapeRegex(PKG_NAME) + "@)" + escapeRegex(previous) + "(?=[:(])", "g");
169
+ const keys = (nextLock.match(keyRe) || []).length;
170
+ if (keys < 1) return { ok: false, changed: false, problems: ["pnpm-lock 里找不到 " + PKG_NAME + "@" + previous + " 的条目"] };
171
+ nextLock = nextLock.replace(keyRe, (all, lead, prefix) => lead + prefix + version);
172
+ if (integrity !== "") {
173
+ const resRe = new RegExp("(\\n " + escapeRegex(PKG_NAME) + "@" + escapeRegex(version) + ":\\n resolution: \\{integrity: )[^}\\n]+(\\})");
174
+ if (!resRe.test(nextLock)) return { ok: false, changed: false, problems: ["pnpm-lock 里找不到 " + version + " 的 integrity 行"] };
175
+ nextLock = nextLock.replace(resRe, (all, head, tail) => head + integrity + tail);
176
+ }
177
+ const guard = lockEditProblems(lockText, nextLock, version);
178
+ if (guard.length > 0) {
179
+ return { ok: false, changed: false, problems: guard.map((one) => "pnpm-lock 未写入:" + one) };
180
+ }
181
+ }
182
+ const nextPkg = pkgText.replace(depRe, (all, head, tail) => head + version + tail);
183
+
184
+ try {
185
+ if (changed) writeFileSync(lockPath, nextLock, "utf8");
186
+ writeFileSync(pkgPath, nextPkg, "utf8");
187
+ } catch (error) {
188
+ try {
189
+ if (changed) writeFileSync(lockPath, lockText, "utf8");
190
+ } catch {
191
+ /* 回滚失败也不抛出:调用方拿 problems 里的原因去提示用户 */
192
+ }
193
+ return { ok: false, changed: false, problems: ["写登记文件失败:" + String((error && error.message) || error)] };
194
+ }
195
+ return { ok: true, changed, problems: [] };
196
+ }
197
+
198
+ /**
199
+ * Guard the lockfile edit: only the lines we meant to touch may differ.
200
+ *
201
+ * A text edit that swallows a newline still "looks" fine in the editor but makes
202
+ * the file unparseable, and pnpm then refuses the whole profile instead of merely
203
+ * rolling one package back. Comparing line by line makes that impossible to ship:
204
+ * the edit is accepted only when the line count is unchanged and every changed
205
+ * line is one of the expected shapes.
206
+ *
207
+ * It returns the reasons it refused (empty array = clean) rather than a bare
208
+ * false: a silent rejection is exactly the kind of detail that is impossible to
209
+ * support later, and the caller shows these strings to the user.
210
+ *
211
+ * @param {string} before lock text as read
212
+ * @param {string} after lock text as edited
213
+ * @param {string} version version that was installed
214
+ * @returns {string[]} problems, empty when the edit is clean
215
+ */
216
+ function lockEditProblems(before, after, version) {
217
+ const a = before.split("\n");
218
+ const b = after.split("\n");
219
+ if (a.length !== b.length) return ["行数从 " + a.length + " 变成 " + b.length];
220
+ /* 预期最多 5 行:importer 的 specifier 与 version、packages 键、snapshots 键、
221
+ packages 条目的 integrity。 */
222
+ const maxChanged = 5;
223
+ const allowed = [
224
+ new RegExp("^ specifier: " + escapeRegex(version) + "$"),
225
+ new RegExp("^ version: " + escapeRegex(version) + "(?:\\(.*\\))?$"),
226
+ /* snapshots 的条目带一个空映射: dsh-multipane@1.0.51: {} */
227
+ new RegExp("^ " + escapeRegex(PKG_NAME) + "@" + escapeRegex(version) + "(?:\\(.*\\))?:(?:\\s*\\{\\s*\\})?$"),
228
+ /^ resolution: \{integrity: sha512-[^}]+\}$/
229
+ ];
230
+ const problems = [];
231
+ let changed = 0;
232
+ for (let i = 0; i < a.length; i += 1) {
233
+ if (a[i] === b[i]) continue;
234
+ changed += 1;
235
+ if (changed > maxChanged) {
236
+ problems.push("改了 " + changed + " 行,超过上限 " + maxChanged);
237
+ break;
238
+ }
239
+ if (!allowed.some((rule) => rule.test(b[i]))) {
240
+ problems.push("第 " + (i + 1) + " 行不在预期范围内:" + b[i].trim().slice(0, 60));
241
+ }
242
+ }
243
+ if (problems.length === 0 && changed === 0) problems.push("没有产生任何改动");
244
+ return problems;
245
+ }
246
+
247
+ /**
248
+ * Ask the registry for the integrity of one published version.
249
+ *
250
+ * The lockfile entry needs the sha512 of the tarball. Guessing it (or keeping the
251
+ * previous version's string) makes pnpm reject the package as tampered with, so
252
+ * when this lookup fails the caller simply does not touch the bookkeeping.
253
+ *
254
+ * @param {string} version published version
255
+ * @returns {Promise<string>} integrity string, or "" when unavailable
256
+ */
257
+ async function fetchIntegrity(version) {
258
+ try {
259
+ if (typeof fetch !== "function") return "";
260
+ const response = await fetch("https://registry.npmjs.org/" + PKG_NAME + "/" + version, { cache: "no-store" });
261
+ if (response.ok !== true) return "";
262
+ const data = await response.json();
263
+ const value = data && data.dist && data.dist.integrity;
264
+ return typeof value === "string" ? value : "";
265
+ } catch {
266
+ return "";
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Make the profile's bookkeeping agree with the copy that is actually installed.
272
+ *
273
+ * The update route writes both files, but it can only do that for updates it
274
+ * performs itself. A copy that arrived any other way — an older self-update that
275
+ * predates the bookkeeping sync, a restored backup, an interrupted run — leaves a
276
+ * profile whose lockfile still names the previous version, and the next `pnpm
277
+ * install` (installing or removing ANY other plugin) then rolls this one back.
278
+ * That is the exact symptom users report as "I updated it, the prompt came back".
279
+ *
280
+ * So on load, if the installed version and the lockfile disagree, settle it. Every
281
+ * path is guarded and the run is fire-and-forget: plugin loading never waits on
282
+ * the network, and a failure leaves the profile exactly as it was.
283
+ *
284
+ * @returns {Promise<void>} resolves when the check is done
285
+ */
286
+ async function ensureBookkeepingMatchesInstalled() {
287
+ try {
288
+ const version = readOwnVersion();
289
+ if (version === "") return;
290
+ const root = join(homedir(), ".dsh", "profiles");
291
+ if (!existsSync(root)) return;
292
+ for (const profile of ["desktop", "web"]) {
293
+ try {
294
+ const dir = join(root, profile);
295
+ const lockPath = join(dir, "pnpm-lock.yaml");
296
+ if (!existsSync(lockPath)) continue;
297
+ const lock = readFileSync(lockPath, "utf8");
298
+ const importerRe = new RegExp("\\n( " + escapeRegex(PKG_NAME) + ":\\n specifier: )([^\\n]*)(\\n version: )([^\\n]*)");
299
+ const hit = lock.match(importerRe);
300
+ if (hit === null) continue;
301
+ if (hit[4].trim().split("(")[0] === version) continue;
302
+ const integrity = await fetchIntegrity(version);
303
+ if (integrity === "") continue;
304
+ syncDependencyBookkeeping(dir, version, integrity);
305
+ } catch {
306
+ /* 单个 profile 失败不影响另一个,也不影响插件加载 */
307
+ }
308
+ }
309
+ } catch {
310
+ /* 绝不因为这里失败而挡住插件加载 */
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Try every profile that exists on this machine (desktop is what the app uses,
316
+ * web is used by headless checks). Unknown layouts are skipped silently.
317
+ */
318
+ function ensureMarketInstallable() {
319
+ try {
320
+ const version = readOwnVersion();
321
+ if (version === "") return;
322
+ const root = join(homedir(), ".dsh", "profiles");
323
+ if (!existsSync(root)) return;
324
+ for (const profile of ["desktop", "web"]) {
325
+ try {
326
+ allowVersionOnThisMachine(join(root, profile), version);
327
+ } catch {
328
+ /* 单个 profile 失败不影响另一个,也不影响插件加载 */
329
+ }
330
+ }
331
+ } catch {
332
+ /* 绝不因为这里失败而挡住插件加载 */
333
+ }
334
+ }
335
+
336
+ /**
337
+ * Mount the host half.
338
+ *
339
+ * @returns void
340
+ */
341
+ const UPDATE_ROUTE = "/dsh-multipane/update";
342
+ const STATUS_ROUTE = "/dsh-multipane/status";
343
+
344
+ /**
345
+ * Install one published version straight from the npm registry.
346
+ *
347
+ * Why not the package manager: the market path goes through pnpm, which refuses
348
+ * releases younger than the profile's minimumReleaseAge, and the market itself
349
+ * syncs its catalog minutes behind the registry. Downloading the published
350
+ * tarball and unpacking it is what "update from npm" means here — no pnpm, no
351
+ * third-party catalog, no release-age wait.
352
+ *
353
+ * Safety: copy the current directory aside first, and put it back if anything
354
+ * fails, so a half-written plugin can never brick the app. A successful copy is
355
+ * followed by syncDependencyBookkeeping, which makes the profile's package.json
356
+ * and pnpm-lock.yaml name the same version — without that, the next install in
357
+ * this profile rolls the directory straight back.
358
+ *
359
+ * @param {string} profileDir profile directory that owns node_modules
360
+ * @param {string} version version to install
361
+ * @returns {Promise<{ok: boolean, message: string, warn: string}>} result
362
+ */
363
+ function installFromRegistry(profileDir, version) {
364
+ const target = join(profileDir, "node_modules", PKG_NAME);
365
+ const staging = join(homedir(), ".dsh", ".dsv-update-" + process.pid);
366
+ const backup = join(homedir(), ".dsh", ".dsv-backup-" + process.pid);
367
+ const tarball = join(staging, "pkg.tgz");
368
+ const url = "https://registry.npmjs.org/" + PKG_NAME + "/-/" + PKG_NAME + "-" + version + ".tgz";
369
+ const run = (file, args, options) =>
370
+ new Promise((resolve) => {
371
+ execFile(file, args, Object.assign({ timeout: 120000, windowsHide: true }, options || {}), (error, stdout, stderr) => {
372
+ resolve({ ok: error === null, out: String(stdout || ""), err: String(stderr || (error && error.message) || "") });
373
+ });
374
+ });
375
+ return (async () => {
376
+ try {
377
+ rmSync(staging, { recursive: true, force: true });
378
+ rmSync(backup, { recursive: true, force: true });
379
+ mkdirSync(staging, { recursive: true });
380
+ const dl = await run("curl", ["-sSL", "--noproxy", "*", "--max-time", "110", "-o", tarball, url]);
381
+ if (!dl.ok || !existsSync(tarball)) return { ok: false, message: "下载失败:" + dl.err.slice(0, 200) };
382
+ /* 必须用 Windows 自带的 bsdtar:git-bash 里的 GNU tar 会把 "C:/…" 当成
383
+ host:path 语法去连远程主机(报 "Cannot connect to C: resolve failed")。 */
384
+ const tarExe = existsSync("C:/Windows/System32/tar.exe") ? "C:/Windows/System32/tar.exe" : "tar";
385
+ const un = await run(tarExe, ["-xzf", tarball, "-C", staging]);
386
+ if (!un.ok) return { ok: false, message: "解压失败:" + un.err.slice(0, 200) };
387
+ const unpacked = join(staging, "package");
388
+ if (!existsSync(join(unpacked, "package.json"))) return { ok: false, message: "包里没有 package.json" };
389
+ const got = JSON.parse(readFileSync(join(unpacked, "package.json"), "utf8")).version;
390
+ if (got !== version) return { ok: false, message: "包内版本是 " + got + ",不是 " + version };
391
+ /* integrity 要从解压前的 tgz 算,解压完 staging 就删了。 */
392
+ const integrity = integrityOfFile(tarball);
393
+ /* 新版本先铺进目标同级的临时目录:同盘才能 rename(跨盘 rename 会退化成整次复制)。
394
+ 然后「旧目录改名挪开 → 新目录改名就位」两步换掉正式目录,空窗只剩两次 syscall。
395
+ 这一步是必须的:宿主随时可能来读 client.js —— 15 个插件的 client.js 被打进同一个
396
+ `plugins/??…` 合并请求,复制期间只要有文件读不到,整包就 failed to load,全部插件
397
+ 一起不激活。2026-11-12 11:13 那次 web boot 崩溃就是这么来的(rm 完还没复制完)。 */
398
+ const staged = target + ".next-" + process.pid;
399
+ const retired = target + ".old-" + process.pid;
400
+ rmSync(staged, { recursive: true, force: true });
401
+ rmSync(retired, { recursive: true, force: true });
402
+ cpSync(unpacked, staged, { recursive: true });
403
+ if (existsSync(target)) {
404
+ cpSync(target, backup, { recursive: true });
405
+ }
406
+ try {
407
+ if (existsSync(target)) renameSync(target, retired);
408
+ renameSync(staged, target);
409
+ } catch (error) {
410
+ /* 换名失败:把旧目录放回原位,再如实报错,绝不留半截安装 */
411
+ try {
412
+ if (!existsSync(target) && existsSync(retired)) renameSync(retired, target);
413
+ } catch {
414
+ /* 放不回就只能靠外层从 backup 回滚 */
415
+ }
416
+ rmSync(staged, { recursive: true, force: true });
417
+ return { ok: false, message: "替换目录失败:" + String((error && error.message) || error) };
418
+ }
419
+ rmSync(retired, { recursive: true, force: true });
420
+ rmSync(staging, { recursive: true, force: true });
421
+ rmSync(backup, { recursive: true, force: true });
422
+ /* 文件就位只是前半笔账,还要让 profile 的 package.json / pnpm-lock 也指到新版本,
423
+ 否则下一次任何 pnpm 安装都会按旧 lockfile 把这个目录重铺回旧版本。 */
424
+ try {
425
+ allowVersionOnThisMachine(profileDir, version);
426
+ } catch {
427
+ /* 免查名单只影响「从插件市场更新」,不影响已经装好的文件 */
428
+ }
429
+ const sync = syncDependencyBookkeeping(profileDir, version, integrity);
430
+ if (sync.ok) return { ok: true, message: "已安装 " + version, warn: "" };
431
+ return { ok: true, message: "已安装 " + version, warn: sync.problems.join(";") };
432
+ } catch (error) {
433
+ try {
434
+ if (existsSync(backup)) {
435
+ rmSync(target, { recursive: true, force: true });
436
+ cpSync(backup, target, { recursive: true });
437
+ }
438
+ } catch {
439
+ /* 回滚失败也不抛出 */
440
+ }
441
+ return { ok: false, message: String((error && error.message) || error) };
442
+ }
443
+ })();
444
+ }
445
+
446
+ function readJsonBody(request, limit, done) {
447
+ let body = "";
448
+ let aborted = false;
449
+ request.on("data", (chunk) => {
450
+ body += chunk;
451
+ if (body.length > limit) {
452
+ aborted = true;
453
+ request.destroy();
454
+ }
455
+ });
456
+ request.on("end", () => {
457
+ if (!aborted) done(body);
458
+ });
459
+ request.on("error", () => {
460
+ /* 忽略 */
461
+ });
462
+ }
463
+
464
+ export function apply(ctx) {
465
+ try {
466
+ ensureMarketInstallable();
467
+ } catch {
468
+ /* 忽略 */
469
+ }
470
+ /* 账本自愈:装在盘上的版本与 lockfile 说的不一致时,启动后自己对齐一次。
471
+ 不 await —— 插件加载不允许等网络。 */
472
+ try {
473
+ ensureBookkeepingMatchesInstalled().catch(() => {});
474
+ } catch {
475
+ /* 忽略 */
476
+ }
477
+ try {
478
+ ctx.inject(["webServer"], (host) => {
479
+ const profileDirOf = () => join(homedir(), ".dsh", "profiles", "desktop");
480
+ const routes = [
481
+ {
482
+ kind: "exact",
483
+ path: STATUS_ROUTE,
484
+ handler: (request, response) => {
485
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
486
+ response.end(JSON.stringify({ version: readOwnVersion(), profile: profileDirOf() }));
487
+ }
488
+ },
489
+ {
490
+ kind: "exact",
491
+ path: UPDATE_ROUTE,
492
+ handler: (request, response) => {
493
+ if (request.method !== "POST") {
494
+ response.writeHead(405, { allow: "POST" });
495
+ response.end("");
496
+ return;
497
+ }
498
+ readJsonBody(request, 4096, (body) => {
499
+ let version = "";
500
+ try {
501
+ version = String(JSON.parse(body).version || "");
502
+ } catch {
503
+ /* 交给下面校验 */
504
+ }
505
+ if (!/^\d+\.\d+\.\d+$/.test(version)) {
506
+ response.writeHead(400, { "content-type": "application/json; charset=utf-8" });
507
+ response.end(JSON.stringify({ ok: false, message: "version 参数不合法" }));
508
+ return;
509
+ }
510
+ installFromRegistry(profileDirOf(), version).then((result) => {
511
+ response.writeHead(result.ok ? 200 : 500, { "content-type": "application/json; charset=utf-8" });
512
+ response.end(JSON.stringify(result));
513
+ });
514
+ });
515
+ }
516
+ }
517
+ ];
518
+ for (const route of routes) {
519
+ try {
520
+ host.webServer.register(route);
521
+ } catch {
522
+ /* 单个路由失败不影响另一个 */
523
+ }
524
+ }
525
+ });
526
+ } catch {
527
+ /* 拿不到 webServer 就只是没有设置页内的更新入口,插件本身照常工作 */
528
+ }
529
+ }