@linxin666/dsh-client-ui-plugin-manager 0.4.7 → 0.4.9

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
@@ -5,6 +5,7 @@ import { basename, dirname, isAbsolute, join, normalize, posix, sep, win32 } fro
5
5
  import { isMap, isScalar, isSeq, parseDocument } from "yaml";
6
6
  import { homedir } from "node:os";
7
7
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
8
+ import semver from "semver";
8
9
  import { AsyncResource } from "node:async_hooks";
9
10
  //#region src/mount-once.ts
10
11
  /**
@@ -319,6 +320,44 @@ function claimedIdsOf(patchText) {
319
320
  return ids;
320
321
  }
321
322
  /**
323
+ * Every entry id a layer declares: its top-level `- id:` rows (bare override
324
+ * rows and config rows alike) plus the entries of its `- insert:` lists. Ids
325
+ * nested inside a row's own `config:` are composition children of that entry,
326
+ * not layer entries, and are not declared here.
327
+ *
328
+ * This answers "does this layer still declare that row?" without composing, so
329
+ * it stays true in the states where a composition probe is not: a host that
330
+ * composes mid-upgrade, or while a bundle's package is being replaced, drops
331
+ * rows whose layers still exist.
332
+ * @param patchText - a patch layer's text.
333
+ * @param filename - absolute path (diagnostics only).
334
+ * @returns the declared ids, in file order, without duplicates.
335
+ * @throws when the layer does not parse; a caller must then treat this layer's
336
+ * declarations as unknown rather than empty.
337
+ */
338
+ function declaredRowIds(patchText, filename) {
339
+ const { root } = parsePatch(patchText, filename);
340
+ const ids = [];
341
+ const push = (value) => {
342
+ if (value === void 0 || ids.includes(value)) return;
343
+ ids.push(value);
344
+ };
345
+ const idOf = (node) => {
346
+ const id = node.get("id", true);
347
+ return isScalar(id) && typeof id.value === "string" ? id.value : void 0;
348
+ };
349
+ for (const item of root.items) {
350
+ if (!isMap(item)) continue;
351
+ const insert = item.get("insert", true);
352
+ if (isSeq(insert)) {
353
+ for (const entry of insert.items) if (isMap(entry)) push(idOf(entry));
354
+ continue;
355
+ }
356
+ push(idOf(item));
357
+ }
358
+ return ids;
359
+ }
360
+ /**
322
361
  * The insert entries of an installed package's own bundle patch, with both
323
362
  * the claimed id and the entry's own name. The name matters twice: the
324
363
  * loader imports the plugin by it (an unresolvable name is a boot failure),
@@ -506,6 +545,55 @@ function pruneOrphanRowOverrides(text, filename, composedIds) {
506
545
  function appendComment(first, second) {
507
546
  return second === void 0 || second === null || second === "" ? first : `${first}\n${second}`;
508
547
  }
548
+ /**
549
+ * Point the profile's own rows at the packages that now carry those entry ids.
550
+ *
551
+ * The include patch semantics skip a row whose `name` does not match the name
552
+ * of the row a bundle inserted under that id, and the skip takes the whole row
553
+ * with it: a config row stops configuring anything and a `disabled` override
554
+ * stops disabling anything, both without a word in the browser. A package that
555
+ * changes its name — the aggregate's family rows moved from the
556
+ * `@linxin666/dsh-web-all/<family>` subpath to the real package in issue
557
+ * #1901 — therefore leaves every profile row that named it dead.
558
+ *
559
+ * The live names come from the installed bundles' own patch files, which is
560
+ * where the loader takes the row it inserts, so a repaired row names exactly
561
+ * the package the loader mounts under that id. A row whose id no bundle claims
562
+ * is left alone: its package may still be carried by a layer this manager
563
+ * cannot see, and a name it cannot prove is a name it must not write.
564
+ *
565
+ * @param text - current patch file text.
566
+ * @param filename - absolute path (diagnostics only).
567
+ * @param liveNames - the live entry names, by entry id.
568
+ * @returns the rewritten text and the repaired rows.
569
+ */
570
+ function repairStaleRowNames(text, filename, liveNames) {
571
+ const { document, root } = parsePatch(text, filename);
572
+ const repaired = [];
573
+ for (const item of root.items) {
574
+ if (!isBareRow(item)) continue;
575
+ const id = bareRowId(item);
576
+ const from = bareRowName(item);
577
+ if (id === void 0 || from === void 0) continue;
578
+ const to = liveNames.get(id);
579
+ if (to === void 0 || to === from) continue;
580
+ item.set("name", document.createNode(to));
581
+ repaired.push({
582
+ id,
583
+ from,
584
+ to
585
+ });
586
+ }
587
+ if (repaired.length === 0) return {
588
+ text,
589
+ repaired
590
+ };
591
+ const serialized = document.toString({ lineWidth: 0 });
592
+ return {
593
+ text: `${serialized.endsWith("\n") ? serialized.slice(0, -1) : serialized}${text.endsWith("\n") ? "\n" : ""}`,
594
+ repaired
595
+ };
596
+ }
509
597
  //#endregion
510
598
  //#region src/host/bundle-guard.ts
511
599
  /**
@@ -916,19 +1004,22 @@ function profileExists(profileDir) {
916
1004
  */
917
1005
  /**
918
1006
  * Entry rows that must never carry a disabled override: the manager tab
919
- * itself (the UI performing the write), the family settings surface the tab
920
- * injects into, and the aggregate compat face (disabling it unmounts the
921
- * whole folded client bundle while host rows keep running — a half-dead
922
- * page). Covers both the standalone and the aggregate row ids. The standalone
923
- * id is this package's own `cordis.patch.yml` insert id, never the official
924
- * `ui-plugin-manager` row the DSH web-app bundle already claims.
1007
+ * itself (the UI performing the write) and the family settings surface the
1008
+ * tab injects into. Covers both the standalone and the aggregate row ids. The
1009
+ * standalone id is this package's own `cordis.patch.yml` insert id, never the
1010
+ * official `ui-plugin-manager` row the DSH web-app bundle already claims.
1011
+ *
1012
+ * `web-ui-compat` is deliberately NOT locked (issue #1901). It used to be:
1013
+ * the compat row carried the inlined browser half of every family, so
1014
+ * disabling it blanked the whole page while the host rows kept running. Family
1015
+ * rows mount their own packages now, and the compat row is the optional
1016
+ * compatibility patch layer the issue asks users to be able to turn off.
925
1017
  */
926
1018
  const LOCKED_ENTRY_IDS = /* @__PURE__ */ new Set([
927
1019
  "ui-plugin-manager-update-check",
928
1020
  "web-ui-plugin-manager",
929
1021
  "ui-web-ui-settings",
930
- "web-ui-settings",
931
- "web-ui-compat"
1022
+ "web-ui-settings"
932
1023
  ]);
933
1024
  /** The node_modules path of one (possibly scoped) package name. */
934
1025
  function modulePathOf(profileDir, name) {
@@ -1670,6 +1761,24 @@ function nativeManagerRefusalCode(outcome) {
1670
1761
  const code = verdict.error?.code;
1671
1762
  return typeof code === "string" && code !== "" ? code : void 0;
1672
1763
  }
1764
+ /**
1765
+ * Whether the official manager's verdict says the run landed but this process
1766
+ * does not hold it yet. The manager answers `application: 'restart-required'`
1767
+ * when the profile moved while the running host still carries the old state;
1768
+ * on a two-phase replacement the removal alone can produce it, because the
1769
+ * replaced bundle's rows are already gone from the running fiber tree by the
1770
+ * time the guard reports the removal applied (issue #1905).
1771
+ *
1772
+ * Read as a success that carries a fact, never as a failure: the version did
1773
+ * land on disk, so turning it into an error would send the caller into a
1774
+ * rollback the profile does not need and stop a batch update on its first item.
1775
+ * @param outcome - the resolved value of `installBundle` / `removeBundle`.
1776
+ * @returns true when the run landed and a restart is what loads it.
1777
+ */
1778
+ function nativeManagerRestartRequired(outcome) {
1779
+ if (typeof outcome !== "object" || outcome === null) return false;
1780
+ return outcome.application === "restart-required";
1781
+ }
1673
1782
  /** The gateway: serializes CLI operations through one job table and one mutation queue. */
1674
1783
  var CliGateway = class {
1675
1784
  facts;
@@ -2090,7 +2199,12 @@ var CliGateway = class {
2090
2199
  requestId: job.id
2091
2200
  });
2092
2201
  let refusal = nativeManagerFailure(first);
2093
- if (refusal !== void 0 && nativeManagerRefusalCode(first) === "already-installed") refusal = await this.replaceInstalled(job, native, targetId, carried.dependencies[targetId]);
2202
+ let restartRequired = nativeManagerRestartRequired(first);
2203
+ if (refusal !== void 0 && nativeManagerRefusalCode(first) === "already-installed") {
2204
+ const replacement = await this.replaceInstalled(job, native, targetId, carried.dependencies[targetId]);
2205
+ refusal = replacement.failure;
2206
+ restartRequired = replacement.restartRequired;
2207
+ }
2094
2208
  if (refusal !== void 0) {
2095
2209
  job.phase = "error";
2096
2210
  job.error = `plugin-manager: 官方插件管理器更新失败:${refusal}`;
@@ -2117,6 +2231,7 @@ var CliGateway = class {
2117
2231
  from: change.from,
2118
2232
  to: change.to
2119
2233
  }));
2234
+ if (restartRequired) job.restartRequired = [targetId];
2120
2235
  job.phase = "done";
2121
2236
  }
2122
2237
  /**
@@ -2129,28 +2244,176 @@ var CliGateway = class {
2129
2244
  * A failed second phase reinstalls the spec the profile carried before the run,
2130
2245
  * so an update that cannot land leaves a working plugin behind instead of an
2131
2246
  * empty slot; the report says which of the two happened.
2247
+ *
2248
+ * Two facts make the replacement safe to repeat in one session:
2249
+ *
2250
+ * - **The bundle keeps its layer index.** A removal drops the name from
2251
+ * `dsh.profile.bundles` and the reinstall appends it, so a plain
2252
+ * remove-then-install moves the bundle behind every bundle that followed it
2253
+ * and its patch layer starts overriding rows it never overrode
2254
+ * ({@link restoreBundleIndex} puts it back).
2255
+ * - **A `bundle-in-use` refusal is answered once, not repeated.** The
2256
+ * official guard deselects the bundle and reloads before it checks whether
2257
+ * the bundle's rows still run, so a real occupant cleared by that reload is
2258
+ * gone on the second call: the update is retried exactly once against that
2259
+ * settled state, and a second refusal restores the selection and names the
2260
+ * restart the person has to do ({@link removeForReplacement}).
2261
+ * - **A landed replacement can still need a restart.** The guard answers
2262
+ * `application: 'restart-required'` when the removal applied and the
2263
+ * replaced bundle's rows are already gone from the running process (issue
2264
+ * #1905). The version does land, so that is a fact to report, not a failure:
2265
+ * the update is `done` and names what only a restart loads.
2266
+ *
2132
2267
  * @param job - the update job whose spec is installed.
2133
2268
  * @param native - the official manager.
2134
2269
  * @param targetId - the installed bundle being replaced.
2135
2270
  * @param previousSpec - the dependency spec the profile carried before the run.
2136
- * @returns the failure to report, or undefined once the target spec landed.
2271
+ * @returns the failure to report, or the restart fact once the target landed.
2137
2272
  */
2138
2273
  async replaceInstalled(job, native, targetId, previousSpec) {
2139
- if (previousSpec === void 0) return `${targetId} 不在 profile 依赖中,无法替换已安装版本`;
2140
- const removalFailure = nativeManagerFailure(await native.removeBundle(targetId));
2141
- if (removalFailure !== void 0) return `已安装版本无法移除(${removalFailure}),本次更新未做改动`;
2142
- const refusal = nativeManagerFailure(await native.installBundle(job.spec, {
2274
+ if (previousSpec === void 0) return {
2275
+ failure: `${targetId} 不在 profile 依赖中,无法替换已安装版本`,
2276
+ restartRequired: false
2277
+ };
2278
+ const index = await this.bundleIndexOf(targetId);
2279
+ const removal = await this.removeForReplacement(native, targetId);
2280
+ if (removal.failure !== void 0) {
2281
+ if (removal.deselected) await this.restoreBundleSelection(native, targetId);
2282
+ return {
2283
+ failure: `已安装版本无法移除(${removal.failure}),本次更新未做改动${removal.remedy}`,
2284
+ restartRequired: false
2285
+ };
2286
+ }
2287
+ const installVerdict = await native.installBundle(job.spec, {
2143
2288
  enabled: true,
2144
2289
  requestId: job.id
2145
- }));
2146
- if (refusal === void 0) return void 0;
2290
+ });
2291
+ const refusal = nativeManagerFailure(installVerdict);
2292
+ const restartRequired = removal.restartRequired || nativeManagerRestartRequired(installVerdict);
2293
+ if (refusal === void 0) {
2294
+ await this.restoreBundleIndex(targetId, previousSpec, index);
2295
+ return { restartRequired };
2296
+ }
2147
2297
  const restoreSpec = `${targetId}@${previousSpec}`;
2148
2298
  const restoreFailure = nativeManagerFailure(await native.installBundle(restoreSpec, {
2149
2299
  enabled: true,
2150
2300
  requestId: job.id
2151
2301
  }));
2152
- if (restoreFailure === void 0) return `${refusal};已装回 ${restoreSpec}`;
2153
- return `${refusal};装回 ${restoreSpec} 也失败:${restoreFailure},请手动重新安装`;
2302
+ if (restoreFailure !== void 0) return {
2303
+ failure: `${refusal};装回 ${restoreSpec} 也失败:${restoreFailure},请手动重新安装`,
2304
+ restartRequired: false
2305
+ };
2306
+ await this.restoreBundleIndex(targetId, previousSpec, index);
2307
+ return {
2308
+ failure: `${refusal};已装回 ${restoreSpec}`,
2309
+ restartRequired: false
2310
+ };
2311
+ }
2312
+ /**
2313
+ * Where a bundle sits in the layer order, read before the removal drops it.
2314
+ * @param name - the installed bundle name.
2315
+ * @returns the index in `dsh.profile.bundles`, or undefined when the profile
2316
+ * does not list it (nothing to restore in that case).
2317
+ */
2318
+ async bundleIndexOf(name) {
2319
+ try {
2320
+ const index = (await readProfileManifest(this.facts.packageJsonPath)).bundles.indexOf(name);
2321
+ return index < 0 ? void 0 : index;
2322
+ } catch {
2323
+ return;
2324
+ }
2325
+ }
2326
+ /**
2327
+ * Put a replaced bundle back at the layer index it had before the removal.
2328
+ *
2329
+ * The loader applies one patch layer per entry of `dsh.profile.bundles`, in
2330
+ * that order, so the index is behavior: a bundle that is removed and
2331
+ * reinstalled without this lands behind every bundle that followed it, and
2332
+ * whole rows start inheriting from a layer that used to come first. The write
2333
+ * is the manifest's own backup + tmp + rename path, and nothing is written
2334
+ * when the profile already lists the bundle where it belongs.
2335
+ * @param name - the reinstalled bundle.
2336
+ * @param spec - the dependency spec the reinstall recorded (unused when the bundle is absent).
2337
+ * @param index - the position captured before the removal.
2338
+ */
2339
+ async restoreBundleIndex(name, spec, index) {
2340
+ if (index === void 0) return;
2341
+ try {
2342
+ const manifest = await readProfileManifest(this.facts.packageJsonPath);
2343
+ if (!Object.hasOwn(manifest.dependencies, name)) return;
2344
+ if (manifest.bundles.indexOf(name) === index) return;
2345
+ await reorderProfileBundle(this.facts.packageJsonPath, name, index);
2346
+ } catch (error) {
2347
+ console.warn(`[plugin-manager] 未能恢复 ${name} 的 bundle 顺序(${spec}):${error instanceof Error ? error.message : String(error)}`);
2348
+ }
2349
+ }
2350
+ /**
2351
+ * Remove a bundle for the two-phase replacement, answering the official
2352
+ * manager's in-use refusal instead of repeating it.
2353
+ *
2354
+ * Read the official `removeBundle` guard in order: it deselects the bundle,
2355
+ * reloads the profile, and only then checks whether the bundle's own rows
2356
+ * still hold a running fiber, which it reports as `bundle-in-use`. A refusal
2357
+ * is therefore answered exactly once, against the state that reload left on
2358
+ * disk: that covers a real occupant whose fiber the reload did clear.
2359
+ *
2360
+ * It does not cover a reload that rebuilds the very rows it just unloaded —
2361
+ * the fresh fiber matches the guard again — so the retry is worth exactly one
2362
+ * call and never a loop, and the second refusal names the restart instead of
2363
+ * a bare code. A removal the guard does apply while the rows are already gone
2364
+ * resolves as `application: 'restart-required'`; that is a success carrying a
2365
+ * restart fact, which is reported as such rather than as a refusal.
2366
+ * @param native - the official manager.
2367
+ * @param name - the bundle to remove.
2368
+ * @returns the refusal to report, whether the profile lost the selection on the
2369
+ * way, the remedy text for that refusal, and whether the applied removal still
2370
+ * needs a restart to load.
2371
+ */
2372
+ async removeForReplacement(native, name) {
2373
+ const first = await native.removeBundle(name);
2374
+ const failure = nativeManagerFailure(first);
2375
+ if (failure === void 0) return {
2376
+ deselected: false,
2377
+ remedy: "",
2378
+ restartRequired: nativeManagerRestartRequired(first)
2379
+ };
2380
+ if (nativeManagerRefusalCode(first) !== "bundle-in-use") return {
2381
+ failure,
2382
+ deselected: await this.bundleSelectionLost(name),
2383
+ remedy: "",
2384
+ restartRequired: false
2385
+ };
2386
+ const second = await native.removeBundle(name);
2387
+ const retryFailure = nativeManagerFailure(second);
2388
+ if (retryFailure === void 0) return {
2389
+ deselected: false,
2390
+ remedy: "",
2391
+ restartRequired: nativeManagerRestartRequired(second)
2392
+ };
2393
+ return {
2394
+ failure: retryFailure,
2395
+ deselected: await this.bundleSelectionLost(name),
2396
+ remedy: ";该插件仍由当前 DSH 进程加载,重启 DSH 后再执行本次更新即可",
2397
+ restartRequired: false
2398
+ };
2399
+ }
2400
+ /** Whether a bundle is still an installed dependency but no longer selected. */
2401
+ async bundleSelectionLost(name) {
2402
+ try {
2403
+ const manifest = await readProfileManifest(this.facts.packageJsonPath);
2404
+ return Object.hasOwn(manifest.dependencies, name) && !manifest.bundles.includes(name);
2405
+ } catch {
2406
+ return false;
2407
+ }
2408
+ }
2409
+ /** Put a selection back after a refused removal, so the profile is as it was found. */
2410
+ async restoreBundleSelection(native, name) {
2411
+ if (native.setBundleEnabled === void 0) return;
2412
+ try {
2413
+ await native.setBundleEnabled(name, true);
2414
+ } catch (error) {
2415
+ console.warn(`[plugin-manager] 未能恢复 ${name} 的 bundle 启用状态:${error instanceof Error ? error.message : String(error)}`);
2416
+ }
2154
2417
  }
2155
2418
  /** Start a deterministic legacy aggregate migration. */
2156
2419
  migrate(sourceId, targetId, targetVersion, targetSpec) {
@@ -2275,7 +2538,8 @@ var CliGateway = class {
2275
2538
  return {
2276
2539
  ...job,
2277
2540
  conflicts: job.conflicts === void 0 ? void 0 : [...job.conflicts],
2278
- notices: job.notices === void 0 ? void 0 : [...job.notices]
2541
+ notices: job.notices === void 0 ? void 0 : [...job.notices],
2542
+ restartRequired: job.restartRequired === void 0 ? void 0 : [...job.restartRequired]
2279
2543
  };
2280
2544
  }
2281
2545
  /** Capture the layer snapshot and the dependency names (tolerant parse). */
@@ -2483,14 +2747,133 @@ var CliGateway = class {
2483
2747
  }
2484
2748
  }
2485
2749
  /**
2750
+ * The entry ids a user-layer override may still point at: the composed ids
2751
+ * plus every id the profile's own bundle layers still declare.
2752
+ *
2753
+ * The composition alone does not prove a row is retired. A host that
2754
+ * composes while a bundle is being replaced — the remove-then-install half of
2755
+ * an application-owned update, or an upgrade whose packages are half
2756
+ * installed — composes *without* the rows of the bundle that is momentarily
2757
+ * gone, and pruning on that probe deletes the user's override for a row that
2758
+ * still exists (0.4.7 lost `web-ui-remote-web-ui` and `ui-schedule` this
2759
+ * way). Declarations live in the bundle layers, so they survive that window.
2760
+ * @param composed - the entry ids of the composition probe.
2761
+ * @returns the ids to keep, or undefined when a declared layer cannot be
2762
+ * read, which proves nothing either way and must leave the file alone.
2763
+ */
2764
+ async liveOverrideIds(composed) {
2765
+ const live = new Set(composed);
2766
+ let manifest;
2767
+ try {
2768
+ manifest = await readProfileManifest(this.facts.packageJsonPath);
2769
+ } catch {
2770
+ return;
2771
+ }
2772
+ for (const name of manifest.bundles) {
2773
+ const dir = join(this.facts.profileDir, "node_modules", ...name.split("/"));
2774
+ try {
2775
+ await readFile(join(dir, "package.json"), "utf8");
2776
+ } catch {
2777
+ return;
2778
+ }
2779
+ let text;
2780
+ try {
2781
+ text = await readFile(join(dir, "cordis.patch.yml"), "utf8");
2782
+ } catch (error) {
2783
+ if (error.code === "ENOENT") continue;
2784
+ return;
2785
+ }
2786
+ try {
2787
+ for (const id of declaredRowIds(text, join(dir, "cordis.patch.yml"))) live.add(id);
2788
+ } catch {
2789
+ return;
2790
+ }
2791
+ }
2792
+ return live;
2793
+ }
2794
+ /**
2795
+ * The entry names the installed bundles' own rows carry, by entry id.
2796
+ *
2797
+ * The loader inserts one row per id and takes that row's name from the
2798
+ * bundle's own patch file, so this map is the very fact the loader composes:
2799
+ * a profile row naming something else is a row the loader skips.
2800
+ *
2801
+ * @returns the live names, or undefined when a bundle's patch cannot be read
2802
+ * (which proves nothing either way and must leave the profile alone).
2803
+ */
2804
+ async liveEntryNames() {
2805
+ const names = /* @__PURE__ */ new Map();
2806
+ let manifest;
2807
+ try {
2808
+ manifest = await readProfileManifest(this.facts.packageJsonPath);
2809
+ } catch {
2810
+ return;
2811
+ }
2812
+ for (const name of manifest.bundles) {
2813
+ const dir = join(this.facts.profileDir, "node_modules", ...name.split("/"));
2814
+ let text;
2815
+ try {
2816
+ text = await readFile(join(dir, "cordis.patch.yml"), "utf8");
2817
+ } catch (error) {
2818
+ if (error.code === "ENOENT") continue;
2819
+ return;
2820
+ }
2821
+ for (const row of insertRowsOf(text)) {
2822
+ if (row.id === void 0 || row.name === void 0) continue;
2823
+ names.set(row.id, row.name);
2824
+ }
2825
+ }
2826
+ return names;
2827
+ }
2828
+ /**
2829
+ * Point the profile's own rows at the packages that now carry those entry ids.
2830
+ *
2831
+ * A bundle that renames a row's package leaves every profile row that named
2832
+ * the old one dead: the include patch semantics skip a row whose name does
2833
+ * not match the inserted row, and the skip takes the whole row with it — a
2834
+ * config row stops configuring and a `disabled` override stops disabling,
2835
+ * both without a word in the browser. Issue #1901 moved the aggregate's
2836
+ * family rows from the `@linxin666/dsh-web-all/<family>` subpath to the
2837
+ * real package, so every profile row written before that upgrade went dead
2838
+ * with it.
2839
+ *
2840
+ * The repair is idempotent and writes only when a row actually changed, so a
2841
+ * healthy profile is never rewritten.
2842
+ *
2843
+ * @returns the repaired rows, in file order.
2844
+ */
2845
+ async repairProfileRowNames() {
2846
+ const names = await this.liveEntryNames();
2847
+ if (names === void 0 || names.size === 0) return [];
2848
+ let text;
2849
+ try {
2850
+ text = await readFile(this.facts.patchPath, "utf8");
2851
+ } catch {
2852
+ return [];
2853
+ }
2854
+ let repaired;
2855
+ try {
2856
+ repaired = repairStaleRowNames(text, this.facts.patchPath, names);
2857
+ } catch {
2858
+ return [];
2859
+ }
2860
+ if (repaired.repaired.length === 0) return [];
2861
+ await writePatchAtomic(this.facts.patchPath, repaired.text);
2862
+ return repaired.repaired;
2863
+ }
2864
+ /**
2486
2865
  * Post-update orphan guard: drop this package's own enablement overrides
2487
- * whose entry id the composed *target* profile no longer carries. The
2488
- * authority is the loader's own composition after the update
2489
- * ({@link composedEntryIdsOf}), not the profile patch and not the source
2490
- * profile: an override is only orphaned once the target composition stops
2491
- * declaring that id, and ids the official base or another bundle still
2492
- * mounts stay valid. A retired row would otherwise leave a stale override
2493
- * that the loader reports on every boot as `patch: entry "<id>" not found`.
2866
+ * whose entry id neither the composed *target* profile nor any bundle layer
2867
+ * still declares. The composition is the loader's own after the update
2868
+ * ({@link composedEntryIdsOf}), widened by the bundle layers' declarations
2869
+ * ({@link liveOverrideIds}) because a composition taken mid-upgrade omits
2870
+ * rows that still exist. A retired row would otherwise leave a stale
2871
+ * override that the loader reports on every boot as
2872
+ * `patch: entry "<id>" not found`.
2873
+ *
2874
+ * The stale-row-name repair ({@link repairProfileRowNames}) runs first and
2875
+ * on its own authority, so a profile whose bundle declarations cannot be
2876
+ * resolved is repaired even though the prune then writes nothing.
2494
2877
  *
2495
2878
  * Nothing is written when nothing is orphaned — a second run over a pruned
2496
2879
  * profile returns the input text untouched, so no write and no second backup
@@ -2503,10 +2886,18 @@ var CliGateway = class {
2503
2886
  * @returns the pruned entry ids, or undefined when the job failed.
2504
2887
  */
2505
2888
  async pruneOrphanOverrides(job, dumpText) {
2889
+ try {
2890
+ const repaired = await this.repairProfileRowNames();
2891
+ if (repaired.length > 0) console.warn("[plugin-manager] 已修复 profile 中失效的行名:" + repaired.map((row) => `${row.id}(${row.from} → ${row.to})`).join("、"));
2892
+ } catch (error) {
2893
+ console.warn("[plugin-manager] profile 行名修复失败:" + (error instanceof Error ? error.message : String(error)));
2894
+ }
2506
2895
  const dump = dumpText ?? await this.compositionOf();
2507
2896
  if (dump === void 0) return [];
2508
2897
  const composed = composedEntryIdsOf(dump);
2509
2898
  if (composed === void 0) return [];
2899
+ const live = await this.liveOverrideIds(composed);
2900
+ if (live === void 0) return [];
2510
2901
  let text;
2511
2902
  try {
2512
2903
  text = await readFile(this.facts.patchPath, "utf8");
@@ -2515,7 +2906,7 @@ var CliGateway = class {
2515
2906
  }
2516
2907
  let pruned;
2517
2908
  try {
2518
- pruned = pruneOrphanRowOverrides(text, this.facts.patchPath, composed);
2909
+ pruned = pruneOrphanRowOverrides(text, this.facts.patchPath, live);
2519
2910
  } catch {
2520
2911
  return [];
2521
2912
  }
@@ -2767,12 +3158,26 @@ function isLoopbackHostname(hostname) {
2767
3158
  return isIPv4Loopback(hostname);
2768
3159
  }
2769
3160
  /**
3161
+ * Whether a reverse proxy stood between the client and this host: the request
3162
+ * carries CF-Connecting-IP or X-Forwarded-For. Either header is stamped by a
3163
+ * hop that forwards traffic, so the request did not originate on this machine.
3164
+ * @param request - node HTTP request.
3165
+ * @returns true when a forwarding header is present.
3166
+ */
3167
+ function isProxiedRequest(request) {
3168
+ return request.headers["cf-connecting-ip"] !== void 0 || request.headers["x-forwarded-for"] !== void 0;
3169
+ }
3170
+ /**
2770
3171
  * Request-level trust fence: a loopback socket address AND a loopback Host
2771
3172
  * header, plus browser same-origin markers. The socket address is
2772
- * authoritative; X-Forwarded-For is never trusted.
3173
+ * authoritative for a direct connection; a request that carries a forwarding
3174
+ * header is refused outright, because a proxy in front of the host makes both
3175
+ * the socket address and the Host header describe the proxy rather than the
3176
+ * client. X-Forwarded-For is therefore never evidence *for* loopback.
2773
3177
  */
2774
3178
  function isLoopbackRequest(request) {
2775
3179
  if (!isLoopbackAddress(request.socket.remoteAddress)) return false;
3180
+ if (isProxiedRequest(request)) return false;
2776
3181
  const host = request.headers.host;
2777
3182
  if (typeof host !== "string") return false;
2778
3183
  let hostUrl;
@@ -2812,62 +3217,6 @@ function parseDshVersion(value) {
2812
3217
  };
2813
3218
  }
2814
3219
  /**
2815
- * Compare two version strings by semver order (a release is newer than any
2816
- * prerelease of the same tuple).
2817
- * @returns -1 / 0 / 1, or undefined when either side is malformed.
2818
- */
2819
- function compareVersions(left, right) {
2820
- const a = parseDshVersion(left);
2821
- const b = parseDshVersion(right);
2822
- if (a === void 0 || b === void 0) return void 0;
2823
- for (const key of [
2824
- "major",
2825
- "minor",
2826
- "patch"
2827
- ]) if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1;
2828
- return comparePrerelease(a.prerelease, b.prerelease);
2829
- }
2830
- /**
2831
- * Semver prerelease ordering: numeric identifiers compare numerically,
2832
- * numeric identifiers rank below alphanumeric ones, alphanumeric identifiers
2833
- * compare lexically, and a longer list wins when the shared prefix is equal.
2834
- */
2835
- function comparePrerelease(left, right) {
2836
- if (left.length === 0 && right.length === 0) return 0;
2837
- if (left.length === 0) return 1;
2838
- if (right.length === 0) return -1;
2839
- const length = Math.max(left.length, right.length);
2840
- for (let index = 0; index < length; index += 1) {
2841
- const a = left[index];
2842
- const b = right[index];
2843
- if (a === void 0) return -1;
2844
- if (b === void 0) return 1;
2845
- if (typeof a === "number" && typeof b === "number") {
2846
- if (a !== b) return a < b ? -1 : 1;
2847
- } else if (typeof a === "number") return -1;
2848
- else if (typeof b === "number") return 1;
2849
- else if (a !== b) return a < b ? -1 : 1;
2850
- }
2851
- return 0;
2852
- }
2853
- const MINIMUM_RANGE_PATTERN = /^>=\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/;
2854
- /**
2855
- * Whether a host version satisfies a declared `>=X.Y.Z[-prerelease]` minimum.
2856
- * @param host - the running DSH host version.
2857
- * @param minimum - the declared minimum; any form other than `>=<semver>`
2858
- * (plain semver, `^`, `~`, multi-comparator ranges, empty) returns undefined.
2859
- * @returns true / false, or undefined when the host version is malformed or
2860
- * the minimum uses an unsupported form — callers treat undefined as
2861
- * "cannot verify" and fail closed for declared requirements.
2862
- */
2863
- function meetsMinimumDsh(host, minimum) {
2864
- const match = MINIMUM_RANGE_PATTERN.exec(minimum.trim());
2865
- if (match === null) return void 0;
2866
- const compared = compareVersions(host, match[1]);
2867
- if (compared === void 0) return void 0;
2868
- return compared >= 0;
2869
- }
2870
- /**
2871
3220
  * Read the declared DSH minimum from a published registry manifest:
2872
3221
  * `dsh.engines.dsh` first, top-level `engines.dsh` next, and
2873
3222
  * `peerDependencies["@deepseek-ai/dsh"]` last, which is where a package that
@@ -2885,6 +3234,40 @@ function dshRequirementOf(manifest) {
2885
3234
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
2886
3235
  }
2887
3236
  //#endregion
3237
+ //#region src/host/dsh-compat.ts
3238
+ /**
3239
+ * The DSH runtime compatibility verdict for one declared plugin requirement,
3240
+ * evaluated the way the official boot gate evaluates it
3241
+ * (`evaluatePluginCompatibility` in app-boot's `plugin-compatibility.ts`):
3242
+ * the requirement is a node-semver range and the host satisfies it when
3243
+ * `semver.satisfies(host, range, { includePrerelease: true })` holds. Every
3244
+ * legal range form therefore decides: `||` alternatives, `^` and `~`,
3245
+ * whitespace-separated comparators, x-ranges, and prerelease tags compared as
3246
+ * ordinary versions.
3247
+ *
3248
+ * The requirement itself comes from `dshRequirementOf` in
3249
+ * `../core/version.ts`, which owns the field priority (this module only
3250
+ * decides the verdict). Host-only on purpose: `semver` is a node package and
3251
+ * must never be reachable from the browser half, which renders the same
3252
+ * declaration through the regex-only `displayMinimumVersion`.
3253
+ * @module @linxin666/dsh-client-ui-plugin-manager/host
3254
+ */
3255
+ /**
3256
+ * Decide whether the running DSH host satisfies a declared requirement range.
3257
+ * @param host - the running DSH host version.
3258
+ * @param range - the declared requirement, in any node-semver range form.
3259
+ * @returns `satisfied` when the host satisfies the declaration,
3260
+ * `host-too-low` when it was compared and does not, and `unverifiable` when
3261
+ * no comparison could be made. Callers fail closed on the last two (issue
3262
+ * #754) but must not describe them with the same words.
3263
+ */
3264
+ function evaluateDshCompatibility(host, range) {
3265
+ if (range.trim() === "") return { verdict: "unverifiable" };
3266
+ if (semver.validRange(range) === null) return { verdict: "unverifiable" };
3267
+ if (semver.valid(host) === null) return { verdict: "unverifiable" };
3268
+ return semver.satisfies(host, range, { includePrerelease: true }) ? { verdict: "satisfied" } : { verdict: "host-too-low" };
3269
+ }
3270
+ //#endregion
2888
3271
  //#region src/host/legacy-migration.ts
2889
3272
  /**
2890
3273
  * Deterministic mapping for the dsh-web aggregate package rename.
@@ -2985,6 +3368,25 @@ const DETACHED = new AsyncResource("dsh-web:detached-work", { triggerAsyncId: 0
2985
3368
  function runDetached(work) {
2986
3369
  return DETACHED.runInAsyncScope(work);
2987
3370
  }
3371
+ /**
3372
+ * Environment marker a Desktop shell sets when it guarantees that a host which
3373
+ * exits is replaced by a fresh host (rather than reported as stopped).
3374
+ *
3375
+ * The packaged Desktop shell owns the process tree but has no obligation to
3376
+ * respawn it: the shipped shell in this repository's compat matrix answers a
3377
+ * host exit with `desktop host stopped` and an error page. Stopping ourselves
3378
+ * under such a shell turns the restart button into "kill the app", so the mode
3379
+ * requires proof of the opposite behaviour.
3380
+ */
3381
+ const SHELL_RESTART_CAPABILITY_ENV = "DSH_SHELL_RESTARTS_HOST";
3382
+ /**
3383
+ * Whether the launching shell promises to bring the host back after it exits.
3384
+ * @param env - the environment the host was launched with.
3385
+ * @returns true only for an opt-in marker value of `1`.
3386
+ */
3387
+ function shellRestartIsSupported(env) {
3388
+ return env[SHELL_RESTART_CAPABILITY_ENV] === "1";
3389
+ }
2988
3390
  /** How long the helper waits for this process to disappear before giving up on the wait. */
2989
3391
  const RESTART_WAIT_MS = 3e4;
2990
3392
  /** Exit/interpreter arguments a relaunch must not repeat (they re-bind fixed ports). */
@@ -2997,7 +3399,7 @@ function isReusableExecArg(argument) {
2997
3399
  * @returns the planned mode, with the relaunch command when one is used.
2998
3400
  */
2999
3401
  function planRestart(facts) {
3000
- if (facts.desktop === true || facts.env.ELECTRON_RUN_AS_NODE === "1") return { mode: "shell" };
3402
+ if (facts.desktop === true || facts.env.ELECTRON_RUN_AS_NODE === "1") return shellRestartIsSupported(facts.env) ? { mode: "shell" } : { mode: "manual" };
3001
3403
  if (!facts.interactive) return { mode: "manual" };
3002
3404
  const script = facts.argv[0];
3003
3405
  if (script === void 0 || script === "") return { mode: "manual" };
@@ -3284,17 +3686,27 @@ function makeGatewayRoutes(deps) {
3284
3686
  return dshVersionPending;
3285
3687
  };
3286
3688
  /**
3287
- * Compat verdict for one declared requirement. Unverified (unknown host,
3288
- * malformed host output, unsupported range) is incompatible so an update
3289
- * can never run against a runtime we cannot prove compatible (issue #754);
3290
- * only absent metadata keeps the update fail-open.
3689
+ * Compat verdict for one declared requirement, plus the running version the
3690
+ * verdict was made from. Unverified (unknown host, malformed host output, a
3691
+ * range node-semver rejects) is incompatible so an update can never run
3692
+ * against a runtime we cannot prove compatible (issue #754); only absent
3693
+ * metadata keeps the update fail-open.
3694
+ *
3695
+ * `hostVersion` is reported only for a verdict that really compared the
3696
+ * running version and lost it. Its absence is the wire's way of saying "this
3697
+ * declaration could not be checked", which is what the browser reads to tell
3698
+ * "your DSH is too old" from "we could not verify" (issues #1819 and #1899):
3699
+ * a blocked row with no version must never be described as below the
3700
+ * minimum, because nothing was compared.
3291
3701
  */
3292
3702
  const compatibleVerdict = async (requiresDsh) => {
3293
3703
  const hostVersion = await resolveDshVersion();
3294
3704
  if (hostVersion === void 0) return { compatible: false };
3705
+ const compatibility = evaluateDshCompatibility(hostVersion, requiresDsh);
3706
+ if (compatibility.verdict === "unverifiable") return { compatible: false };
3295
3707
  return {
3296
3708
  hostVersion,
3297
- compatible: meetsMinimumDsh(hostVersion, requiresDsh) === true
3709
+ compatible: compatibility.verdict === "satisfied"
3298
3710
  };
3299
3711
  };
3300
3712
  /** Wrap a handler with the loopback fence and JSON error reporting. */
@@ -3398,7 +3810,7 @@ function makeGatewayRoutes(deps) {
3398
3810
  const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
3399
3811
  if (!compatible) return {
3400
3812
  status: 412,
3401
- error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${migration.to}; check the DSH runtime before migrating` : `plugin-manager: ${migration.to} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before migrating`
3813
+ error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${migration.to} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before migrating` : `plugin-manager: ${migration.to} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before migrating`
3402
3814
  };
3403
3815
  }
3404
3816
  return {
@@ -3434,7 +3846,7 @@ function makeGatewayRoutes(deps) {
3434
3846
  const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
3435
3847
  if (!compatible) return {
3436
3848
  status: 412,
3437
- error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${target}; check the DSH runtime before updating` : `plugin-manager: ${target} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before updating`
3849
+ error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${target} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before updating` : `plugin-manager: ${target} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before updating`
3438
3850
  };
3439
3851
  }
3440
3852
  return {
@@ -3747,6 +4159,19 @@ function applyImpl(ctx) {
3747
4159
  for (const dispose of disposers) dispose();
3748
4160
  };
3749
4161
  }, "plugin-manager: gateway routes");
4162
+ ctx.effect(() => {
4163
+ const timer = setTimeout(() => {
4164
+ gateway.repairProfileRowNames().then((repaired) => {
4165
+ if (repaired.length === 0) return;
4166
+ console.warn("[plugin-manager] 已修复 profile 中失效的行名:" + repaired.map((row) => `${row.id}(${row.from} → ${row.to})`).join("、"));
4167
+ }).catch((error) => {
4168
+ console.error("[plugin-manager] profile 行名修复失败:" + (error instanceof Error ? error.message : String(error)));
4169
+ });
4170
+ }, 1500);
4171
+ return () => {
4172
+ clearTimeout(timer);
4173
+ };
4174
+ }, "plugin-manager: stale row name repair");
3750
4175
  }
3751
4176
  //#endregion
3752
4177
  export { apply, inject, name };