@linxin666/dsh-client-ui-plugin-manager 0.4.12 → 0.4.14

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,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync } from "node:fs";
2
+ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, realpathSync } from "node:fs";
3
3
  import { copyFile, readFile, rename, writeFile } from "node:fs/promises";
4
4
  import { basename, dirname, isAbsolute, join, normalize, posix, sep, win32 } from "node:path";
5
5
  import { isMap, isScalar, isSeq, parseDocument } from "yaml";
@@ -595,90 +595,6 @@ function repairStaleRowNames(text, filename, liveNames) {
595
595
  };
596
596
  }
597
597
  //#endregion
598
- //#region src/host/bundle-guard.ts
599
- /**
600
- * Post-mutation duplicate-mount guard for the gateway host half. The official
601
- * CLI's bundle reconciliation appends EVERY dependency that declares
602
- * `dsh.bundle` to the profile manifest's `dsh.profile.bundles` — including
603
- * packages the composition already mounts through a patch row (the family
604
- * aggregate mounts dsh-better-sidebar as the insert row
605
- * `{ id: 'better-sidebar', name: 'dsh-better-sidebar' }` while the package
606
- * also sits in the profile's dependencies). The bundles layer then mounts the
607
- * package a second time and the next boot dies on duplicate routes
608
- * (`webserver: duplicate prefix route "/sidebar/api"`). This module decides,
609
- * from the before-state composition, which newly added bundles entries are
610
- * such duplicate mounts; the gateway strips exactly those entries back out.
611
- * @module @linxin666/dsh-client-ui-plugin-manager/host
612
- */
613
- /**
614
- * The bundles entries a mutation newly added: present after, absent before.
615
- * Entries the user already had are never the guard's business.
616
- * @param before - bundles list before the mutation.
617
- * @param after - bundles list after the mutation.
618
- * @returns the newly added entries, in after-state order.
619
- */
620
- function newlyAddedBundles(before, after) {
621
- return after.filter((name) => !before.includes(name));
622
- }
623
- /**
624
- * Record one candidate row: an enabled row mounts its named package; a row
625
- * the profile layer disables (bare `disabled: true` override matching the
626
- * row id) mounts nothing, so it never justifies stripping a bundles entry.
627
- */
628
- function collectRow(mounted, rowEnabled, row) {
629
- if (row.name === void 0 || row.name === "") return;
630
- if (row.id !== void 0 && rowEnabled.get(row.id) === false) return;
631
- mounted.add(row.name);
632
- }
633
- /**
634
- * The package names the before-state composition already mounts through patch
635
- * rows: the profile patch's own rows (bare and insert-format) plus every
636
- * before-state dependency's own bundle patch insert entries (the aggregate's
637
- * rows section lives there, not in the profile layer). A tolerant read: a
638
- * broken patch file yields no names rather than failing the mutation.
639
- * @param facts - resolved profile locations.
640
- * @param before - the before-state capture.
641
- * @returns the set of row-mounted package names.
642
- */
643
- async function rowMountedPackageNames(facts, before) {
644
- const mounted = /* @__PURE__ */ new Set();
645
- try {
646
- const { root } = parsePatch(before.patchText, facts.patchPath);
647
- for (const item of root.items) {
648
- if (!isMap(item)) continue;
649
- const name = bareRowName(item);
650
- if (name !== void 0 && bareRowEnabled(item)) mounted.add(name);
651
- }
652
- } catch {}
653
- for (const row of insertRowsOf(before.patchText)) collectRow(mounted, before.rowEnabled, row);
654
- for (const dependency of before.dependencies) {
655
- const patchPath = join(facts.profileDir, "node_modules", ...dependency.split("/"), "cordis.patch.yml");
656
- let text;
657
- try {
658
- text = await readFile(patchPath, "utf8");
659
- } catch {
660
- continue;
661
- }
662
- for (const row of insertRowsOf(text)) collectRow(mounted, before.rowEnabled, row);
663
- }
664
- return mounted;
665
- }
666
- /**
667
- * The newly added bundles entries that duplicate an existing row mount and
668
- * must be stripped to keep the next boot alive.
669
- * @param facts - resolved profile locations.
670
- * @param before - the before-state capture.
671
- * @param beforeBundles - the bundles list before the mutation.
672
- * @param afterBundles - the bundles list after the mutation.
673
- * @returns the entries to remove from `dsh.profile.bundles`.
674
- */
675
- async function duplicateMountBundles(facts, before, beforeBundles, afterBundles) {
676
- const added = newlyAddedBundles(beforeBundles, afterBundles);
677
- if (added.length === 0) return [];
678
- const mounted = await rowMountedPackageNames(facts, before);
679
- return added.filter((name) => mounted.has(name));
680
- }
681
- //#endregion
682
598
  //#region src/host/dsh-home.ts
683
599
  /**
684
600
  * DSH_HOME resolution shared by the plugin family's Host halves: the
@@ -994,6 +910,114 @@ function profileExists(profileDir) {
994
910
  return existsSync(join(profileDir, "package.json"));
995
911
  }
996
912
  //#endregion
913
+ //#region src/host/bundle-guard.ts
914
+ /**
915
+ * Post-mutation duplicate-mount guard for the gateway host half. The official
916
+ * CLI's bundle reconciliation appends EVERY dependency that declares
917
+ * `dsh.bundle` to the profile manifest's `dsh.profile.bundles` — including
918
+ * packages the composition already mounts through a patch row (the family
919
+ * aggregate mounts dsh-better-sidebar as the insert row
920
+ * `{ id: 'better-sidebar', name: 'dsh-better-sidebar' }` while the package
921
+ * also sits in the profile's dependencies). The bundles layer then mounts the
922
+ * package a second time and the next boot dies on duplicate routes
923
+ * (`webserver: duplicate prefix route "/sidebar/api"`). This module decides,
924
+ * from the before-state composition, which newly added bundles entries are
925
+ * such duplicate mounts; the gateway strips exactly those entries back out.
926
+ * @module @linxin666/dsh-client-ui-plugin-manager/host
927
+ */
928
+ /**
929
+ * The bundles entries a mutation newly added: present after, absent before.
930
+ * Entries the user already had are never the guard's business.
931
+ * @param before - bundles list before the mutation.
932
+ * @param after - bundles list after the mutation.
933
+ * @returns the newly added entries, in after-state order.
934
+ */
935
+ function newlyAddedBundles(before, after) {
936
+ return after.filter((name) => !before.includes(name));
937
+ }
938
+ /**
939
+ * Record one candidate row: an enabled row mounts its named package; a row
940
+ * the profile layer disables (bare `disabled: true` override matching the
941
+ * row id) mounts nothing, so it never justifies stripping a bundles entry.
942
+ */
943
+ function collectRow(mounted, rowEnabled, row) {
944
+ if (row.name === void 0 || row.name === "") return;
945
+ if (row.id !== void 0 && rowEnabled.get(row.id) === false) return;
946
+ mounted.add(row.name);
947
+ }
948
+ /**
949
+ * The package names the before-state composition already mounts through patch
950
+ * rows: the profile patch's own rows (bare and insert-format) plus every
951
+ * before-state dependency's own bundle patch insert entries (the aggregate's
952
+ * rows section lives there, not in the profile layer). A tolerant read: a
953
+ * broken patch file yields no names rather than failing the mutation.
954
+ * @param facts - resolved profile locations.
955
+ * @param before - the before-state capture.
956
+ * @returns the set of row-mounted package names.
957
+ */
958
+ async function rowMountedPackageNames(facts, before) {
959
+ const mounted = /* @__PURE__ */ new Set();
960
+ try {
961
+ const { root } = parsePatch(before.patchText, facts.patchPath);
962
+ for (const item of root.items) {
963
+ if (!isMap(item)) continue;
964
+ const name = bareRowName(item);
965
+ if (name !== void 0 && bareRowEnabled(item)) mounted.add(name);
966
+ }
967
+ } catch {}
968
+ for (const row of insertRowsOf(before.patchText)) collectRow(mounted, before.rowEnabled, row);
969
+ for (const dependency of before.dependencies) {
970
+ const patchPath = join(facts.profileDir, "node_modules", ...dependency.split("/"), "cordis.patch.yml");
971
+ let text;
972
+ try {
973
+ text = await readFile(patchPath, "utf8");
974
+ } catch {
975
+ continue;
976
+ }
977
+ for (const row of insertRowsOf(text)) collectRow(mounted, before.rowEnabled, row);
978
+ }
979
+ return mounted;
980
+ }
981
+ /**
982
+ * The newly added bundles entries that duplicate an existing row mount and
983
+ * must be stripped to keep the next boot alive.
984
+ * @param facts - resolved profile locations.
985
+ * @param before - the before-state capture.
986
+ * @param beforeBundles - the bundles list before the mutation.
987
+ * @param afterBundles - the bundles list after the mutation.
988
+ * @returns the entries to remove from `dsh.profile.bundles`.
989
+ */
990
+ async function duplicateMountBundles(facts, before, beforeBundles, afterBundles) {
991
+ const added = newlyAddedBundles(beforeBundles, afterBundles);
992
+ if (added.length === 0) return [];
993
+ const mounted = await rowMountedPackageNames(facts, before);
994
+ return added.filter((name) => mounted.has(name));
995
+ }
996
+ /**
997
+ * Whether an installed dependency declares its own bundle patch (`dsh.bundle`
998
+ * in its package.json) — the fact the official CLI's reconciliation selects a
999
+ * dependency on. A package that declares none is a plain dependency of some
1000
+ * mounted bundle and never enters the selection.
1001
+ * @param facts - resolved profile locations.
1002
+ * @param name - dependency name (possibly scoped).
1003
+ * @returns whether the installed package declares `dsh.bundle`; a package that
1004
+ * cannot be read proves nothing and answers false.
1005
+ */
1006
+ async function declaresBundle(facts, name) {
1007
+ let text;
1008
+ try {
1009
+ text = await readFile(join(facts.profileDir, "node_modules", ...name.split("/"), "package.json"), "utf8");
1010
+ } catch {
1011
+ return false;
1012
+ }
1013
+ try {
1014
+ const bundle = JSON.parse(stripBom(text)).dsh?.bundle;
1015
+ return typeof bundle === "object" && bundle !== null;
1016
+ } catch {
1017
+ return false;
1018
+ }
1019
+ }
1020
+ //#endregion
997
1021
  //#region src/host/state.ts
998
1022
  /**
999
1023
  * Gateway listing: the installed-plugin inventory read from the profile's
@@ -1279,6 +1303,39 @@ function unsafeSpecReason(spec) {
1279
1303
  return UNSAFE_SPEC_CHARS.test(spec) ? "plugin-manager: spec 含有危险的 shell 元字符或控制字符,已拒绝" : void 0;
1280
1304
  }
1281
1305
  /**
1306
+ * The pnpm diagnostic for a dependency whose build script it skipped, as it
1307
+ * appears in the CLI's captured output:
1308
+ *
1309
+ * [ERR_PNPM_IGNORED_BUILDS] Ignored build scripts: cpu-features@0.0.10
1310
+ *
1311
+ * The code is bracketed and the package list is comma separated, so the bracket
1312
+ * is part of the match, and it stops at the end of that line, so the \r a
1313
+ * Windows console writes before the newline neither hides nor extends it.
1314
+ */
1315
+ const IGNORED_BUILDS_PATTERN = /\[ERR_PNPM_IGNORED_BUILDS\][ \t]*Ignored build scripts:[^\n\r]*/;
1316
+ /**
1317
+ * Whether one CLI run's captured output carries the skipped-build-script
1318
+ * condition.
1319
+ *
1320
+ * `dsh plugin` forwards to pnpm, so a non-zero exit is pnpm's own verdict —
1321
+ * except this one, which pnpm prints *after* it has written the profile: a
1322
+ * dependency that declares a build script is not built until it is approved, and
1323
+ * the unapproved one fails the command while the package is already on disk and
1324
+ * the profile already carries it. Measured 2026-10-31 against the CLI's bundled
1325
+ * pnpm 11.9.0 and against pnpm 11.24.0: `dsh plugin --profile web add
1326
+ * cpu-features` exits 1 with its dependency landed, and the family aggregate
1327
+ * exits the same way naming cloudflared, cpu-features and ssh2.
1328
+ *
1329
+ * The condition is necessary and not sufficient: only the profile can say
1330
+ * whether the change the caller asked for really landed. The job runner reads it
1331
+ * and keeps the exit a failure when it did not.
1332
+ * @param output - the captured stdout and stderr of one CLI run.
1333
+ * @returns true when pnpm named the build scripts it skipped.
1334
+ */
1335
+ function reportsIgnoredBuilds(output) {
1336
+ return IGNORED_BUILDS_PATTERN.test(output);
1337
+ }
1338
+ /**
1282
1339
  * The Electron resource roots a packaged Desktop install may carry, as
1283
1340
  * absolute directories. Two independent launcher facts name them, and either
1284
1341
  * alone is enough:
@@ -1359,6 +1416,58 @@ function findDshBinary(env = process.env, platform = process.platform, exists =
1359
1416
  for (const candidate of candidates) if (exists(candidate)) return candidate;
1360
1417
  return null;
1361
1418
  }
1419
+ /** Ancestor directories {@link hostBundleDir} probes for an installation copy. */
1420
+ const HOST_PROBE_DEPTH = 16;
1421
+ /**
1422
+ * Resolve one path through its symlinks, or undefined when it cannot be read.
1423
+ * @param path - the path to resolve.
1424
+ * @returns the real path, or undefined.
1425
+ */
1426
+ function realpathOf(path) {
1427
+ try {
1428
+ return realpathSync(path);
1429
+ } catch {
1430
+ return;
1431
+ }
1432
+ }
1433
+ /**
1434
+ * The installation copy of one bundle package, when the DSH installation this
1435
+ * runtime runs out of carries it.
1436
+ *
1437
+ * A CLI-created profile names the official bundles in `dsh.profile.bundles`
1438
+ * without ever installing them: `@deepseek-ai/dsh-base` and
1439
+ * `@deepseek-ai/dsh-web-app` are mounted from the DSH installation the loader
1440
+ * runs out of, so no profile copy exists and their rows are declared by the
1441
+ * installation's own package. That copy is the one whose rows mount, so a
1442
+ * missing profile copy is not proof of an unknown declaration set (see
1443
+ * {@link CliGateway.liveOverrideIds}).
1444
+ *
1445
+ * Resolution follows Node's own lookup from the CLI entry: every ancestor
1446
+ * directory contributes `node_modules/<name>`, plus the npm-global and
1447
+ * homebrew `<ancestor>/lib/node_modules/<name>`. The entry is resolved through
1448
+ * its symlinks first, because npm-global and homebrew install the `dsh` shim
1449
+ * as a link into the package tree while the shim's own directory carries no
1450
+ * packages.
1451
+ * @param binary - the resolved dsh CLI path, or null when this runtime has none.
1452
+ * @param name - the bundle package name from `dsh.profile.bundles`.
1453
+ * @param exists - existence probe (test seam).
1454
+ * @param resolveReal - symlink resolver (test seam).
1455
+ * @returns the installation package directory, or undefined when it has none.
1456
+ */
1457
+ function hostBundleDir(binary, name, exists = existsSync, resolveReal = realpathOf) {
1458
+ if (binary === null || binary === "") return void 0;
1459
+ const segments = name.split("/");
1460
+ let current = dirname(resolveReal(binary) ?? binary);
1461
+ for (let depth = 0; depth < HOST_PROBE_DEPTH; depth += 1) {
1462
+ for (const modules of [join(current, "node_modules"), join(current, "lib", "node_modules")]) {
1463
+ const dir = join(modules, ...segments);
1464
+ if (exists(join(dir, "package.json"))) return dir;
1465
+ }
1466
+ const parent = dirname(current);
1467
+ if (parent === current) break;
1468
+ current = parent;
1469
+ }
1470
+ }
1362
1471
  /**
1363
1472
  * Append bounded CLI output (stdout + stderr interleaved is not preserved;
1364
1473
  * tail wins). Bytes are accumulated and decoded once at read time: a Windows
@@ -1917,7 +2026,9 @@ var CliGateway = class {
1917
2026
  return;
1918
2027
  }
1919
2028
  const targetIsLocal = /^(?:link:|file:)/.test(targetSpec);
1920
- if (targetPreviouslyInstalled ? !targetIsLocal : !after.dependencies.includes(targetId)) {
2029
+ const shouldAddTarget = targetPreviouslyInstalled ? !targetIsLocal : !after.dependencies.includes(targetId);
2030
+ let tolerated;
2031
+ if (shouldAddTarget) {
1921
2032
  const add = await this.runCli(binary, [
1922
2033
  "plugin",
1923
2034
  "--profile",
@@ -1925,16 +2036,22 @@ var CliGateway = class {
1925
2036
  "add",
1926
2037
  targetSpec
1927
2038
  ], ADD_TIMEOUT_MS);
1928
- if (add.code !== 0) {
1929
- await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled);
1930
- job.error = `plugin-manager: 迁移安装 ${targetSpec} 失败${add.output === "" ? "" : `:\n${add.output}`}`;
2039
+ if (add.code !== 0 && reportsIgnoredBuilds(add.output)) tolerated = {
2040
+ code: add.code,
2041
+ output: add.output
2042
+ };
2043
+ if (add.code !== 0 && tolerated === void 0) {
2044
+ if (await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled)) job.error = `plugin-manager: 迁移安装 ${targetSpec} 失败${add.output === "" ? "" : `:\n${add.output}`}`;
1931
2045
  return;
1932
2046
  }
1933
2047
  after = await this.capture();
1934
2048
  }
1935
2049
  if (!after.dependencies.includes(targetId)) {
1936
- await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled);
1937
- job.error = `plugin-manager: dsh plugin add 报告成功,但 ${targetId} 未出现在 profile 中`;
2050
+ if (await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled)) job.error = tolerated === void 0 ? `plugin-manager: dsh plugin add 报告成功,但 ${targetId} 未出现在 profile 中` : `plugin-manager: 迁移安装 ${targetSpec} 失败${tolerated.output === "" ? "" : `:\n${tolerated.output}`}`;
2051
+ return;
2052
+ }
2053
+ if (shouldAddTarget && await this.bundleSelectionMissing(targetId, after.bundles, !targetPreviouslyInstalled || before.bundles.includes(targetId))) {
2054
+ if (await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled)) job.error = this.halfMountError(targetId, "迁移安装只写入了依赖,", tolerated);
1938
2055
  return;
1939
2056
  }
1940
2057
  const stripped = await this.stripDuplicateMounts(job, before, after);
@@ -1959,16 +2076,14 @@ var CliGateway = class {
1959
2076
  "--dump-config"
1960
2077
  ], 9e4);
1961
2078
  if (verify.code !== 0) {
1962
- await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled);
1963
- job.error = `plugin-manager: 迁移后的启动预检失败${verify.output === "" ? "" : `:\n${verify.output}`}`;
2079
+ if (await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled)) job.error = `plugin-manager: 迁移后的启动预检失败${verify.output === "" ? "" : `:\n${verify.output}`}`;
1964
2080
  return;
1965
2081
  }
1966
2082
  if (await this.pruneOrphanOverrides(job, verify.output) === void 0) return;
1967
2083
  const manifest = await readProfileManifest(this.facts.packageJsonPath);
1968
2084
  const updated = await buildPluginRow(this.facts, targetId, manifest.dependencies[targetId] ?? targetSpec, after.layer.rows);
1969
2085
  if (!/^(?:link:|file:)/.test(targetSpec) && updated.version !== targetVersion) {
1970
- await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled);
1971
- job.error = `plugin-manager: 迁移后 ${targetId} 版本为 ${updated.version},预期 ${targetVersion}`;
2086
+ if (await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled)) job.error = `plugin-manager: 迁移后 ${targetId} 版本为 ${updated.version},预期 ${targetVersion}`;
1972
2087
  return;
1973
2088
  }
1974
2089
  job.plugin = updated;
@@ -1978,30 +2093,55 @@ var CliGateway = class {
1978
2093
  from: change.from,
1979
2094
  to: change.to
1980
2095
  }));
2096
+ if (tolerated !== void 0) this.recordToleratedExit(job, tolerated);
1981
2097
  job.phase = "done";
1982
2098
  }
1983
- /** Restore the original legacy package after a failed migration. */
2099
+ /**
2100
+ * Restore the original legacy package after a failed migration.
2101
+ *
2102
+ * The forward migration removed the legacy package first, so the way back is
2103
+ * a remove-then-add in the other direction — and each half has to be read, not
2104
+ * assumed. A removal that does not take the new aggregate back out leaves the
2105
+ * profile carrying it with the legacy package gone, and re-adding the legacy
2106
+ * package on top of it is exactly the dual-mount shape this path exists to
2107
+ * avoid: both bundles declare the same row ids, the loader mounts one of them
2108
+ * without a word, and the next update resolves against a profile that no
2109
+ * longer describes itself. Such a rollback is reported as incomplete
2110
+ * ({@link incompleteRollback}) instead of claimed as done.
2111
+ * @returns true when the rollback finished — the legacy package is back, or
2112
+ * the profile deliberately keeps the single current aggregate — and false
2113
+ * when it could not run or could not finish, in which case `job.error`
2114
+ * already carries the report and the caller must not replace it with its
2115
+ * own reason.
2116
+ */
1984
2117
  async rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled) {
1985
2118
  const binary = this.binary();
1986
2119
  if (binary === null) {
1987
2120
  job.phase = "error";
1988
2121
  job.error = "plugin-manager: 迁移失败且无法回滚:dsh CLI not found on PATH";
1989
- return;
2122
+ return false;
1990
2123
  }
1991
2124
  const current = await this.capture();
1992
- if (!targetPreviouslyInstalled && current.dependencies.includes(targetId)) await this.runCli(binary, [
1993
- "plugin",
1994
- "--profile",
1995
- this.facts.profileName,
1996
- "remove",
1997
- targetId
1998
- ], REMOVE_TIMEOUT_MS);
2125
+ const restoreOld = this.restoreSpec(sourceId, oldSpec);
2126
+ if (!targetPreviouslyInstalled && current.dependencies.includes(targetId)) {
2127
+ const removed = await this.runCli(binary, [
2128
+ "plugin",
2129
+ "--profile",
2130
+ this.facts.profileName,
2131
+ "remove",
2132
+ targetId
2133
+ ], REMOVE_TIMEOUT_MS);
2134
+ if (removed.code !== 0) {
2135
+ job.phase = "error";
2136
+ job.error = this.incompleteRollback(targetId, restoreOld, `dsh plugin remove ${targetId} 失败(退出码 ${String(removed.code)})${removed.output === "" ? "" : `:\n${removed.output}`}`);
2137
+ return false;
2138
+ }
2139
+ }
1999
2140
  if (targetPreviouslyInstalled) {
2000
2141
  job.phase = "error";
2001
2142
  job.error = "plugin-manager: 聚合包迁移失败,已保留当前聚合包并移除旧包";
2002
- return;
2143
+ return true;
2003
2144
  }
2004
- const restoreOld = this.restoreSpec(sourceId, oldSpec);
2005
2145
  const restored = await this.runCli(binary, [
2006
2146
  "plugin",
2007
2147
  "--profile",
@@ -2012,11 +2152,34 @@ var CliGateway = class {
2012
2152
  if (restored.code !== 0) {
2013
2153
  job.phase = "error";
2014
2154
  job.error = `plugin-manager: 迁移失败且回滚到 ${restoreOld} 失败${restored.output === "" ? "" : `:\n${restored.output}`}`;
2015
- return;
2155
+ return false;
2016
2156
  }
2017
2157
  if (oldIndex >= 0) await reorderProfileBundle(this.facts.packageJsonPath, sourceId, oldIndex).catch(() => void 0);
2018
2158
  job.phase = "error";
2019
2159
  job.error = "plugin-manager: 聚合包迁移失败,已回滚到旧包";
2160
+ return true;
2161
+ }
2162
+ /**
2163
+ * The report for a rollback that could not take the new aggregate back out.
2164
+ *
2165
+ * The profile is left carrying the new package with the legacy one gone,
2166
+ * which is neither the migration nor a rollback, and it is not a state the
2167
+ * legacy package may be re-added into: both bundles declare the same row ids,
2168
+ * so keeping one of them is the only safe outcome. The message therefore says
2169
+ * what actually happened, never claims a rollback that did not run, and names
2170
+ * the two commands that carry it out by hand.
2171
+ * @param targetId - the new aggregate this migration installed.
2172
+ * @param restoreOld - the exact spec that reinstalls the legacy package.
2173
+ * @param reason - the CLI's own words, or the exit it reported.
2174
+ * @returns the job error text.
2175
+ */
2176
+ incompleteRollback(targetId, restoreOld, reason) {
2177
+ return [
2178
+ `plugin-manager: 迁移失败且回滚未完成:需手工 remove ${targetId}`,
2179
+ `请执行:dsh plugin --profile ${this.facts.profileName} remove ${targetId}`,
2180
+ `如需恢复旧包,再执行:dsh plugin --profile ${this.facts.profileName} add ${restoreOld}`,
2181
+ `原因:${reason}`
2182
+ ].join("\n");
2020
2183
  }
2021
2184
  /** Spawn the CLI, through the test seam when present. */
2022
2185
  spawnCli(binary, args) {
@@ -2539,9 +2702,46 @@ var CliGateway = class {
2539
2702
  ...job,
2540
2703
  conflicts: job.conflicts === void 0 ? void 0 : [...job.conflicts],
2541
2704
  notices: job.notices === void 0 ? void 0 : [...job.notices],
2542
- restartRequired: job.restartRequired === void 0 ? void 0 : [...job.restartRequired]
2705
+ restartRequired: job.restartRequired === void 0 ? void 0 : [...job.restartRequired],
2706
+ warnings: job.warnings === void 0 ? void 0 : [...job.warnings]
2543
2707
  };
2544
2708
  }
2709
+ /**
2710
+ * Whether this gateway's own record says the last in-place update of one
2711
+ * plugin at one version never settled.
2712
+ *
2713
+ * The update path writes the profile before it verifies it: the CLI puts the
2714
+ * target version on disk, and the boot preflight (`--dump-config`, see
2715
+ * {@link verifyBoot}) then decides whether the run is reported as landed. A
2716
+ * preflight failure the plugin is not implicated in settles the job as an
2717
+ * error with the new version already installed, which leaves the profile at
2718
+ * the target version while the update itself failed. That state cannot be
2719
+ * reached again through the update action — the row already carries the
2720
+ * latest version, so the route answers 409 "already at <version>" and the
2721
+ * only way out is a reinstall run by hand. This is the fact that lets that
2722
+ * route tell the state apart from a plugin that is genuinely up to date,
2723
+ * which must keep its 409.
2724
+ *
2725
+ * Only the most recent update of the plugin counts. A settled run — a later
2726
+ * success, or a run that landed nothing and rolled back — is the plugin's
2727
+ * current standing, whatever an older failed attempt said, so the scan starts
2728
+ * at the newest settled job and stops at the first one that is this plugin's
2729
+ * update. Jobs this gateway no longer holds (the ring cap, a restart) are
2730
+ * unknown rather than failed, and answer false.
2731
+ * @param id - the installed package name.
2732
+ * @param version - the version the profile currently carries.
2733
+ * @returns true when the newest recorded update of `id` failed at `version`.
2734
+ */
2735
+ lastUpdateFailed(id, version) {
2736
+ for (let index = this.finishedOrder.length - 1; index >= 0; index -= 1) {
2737
+ const jobId = this.finishedOrder[index];
2738
+ if (jobId === void 0) continue;
2739
+ const job = this.jobs.get(jobId);
2740
+ if (job === void 0 || job.action !== "update" || job.targetId !== id) continue;
2741
+ return job.phase === "error" && job.targetVersion === version;
2742
+ }
2743
+ return false;
2744
+ }
2545
2745
  /** Capture the layer snapshot and the dependency names (tolerant parse). */
2546
2746
  async capture() {
2547
2747
  const rows = /* @__PURE__ */ new Map();
@@ -2615,13 +2815,18 @@ var CliGateway = class {
2615
2815
  capture(chunk, output);
2616
2816
  });
2617
2817
  const code = await awaitCliExit(child, output, timeoutMs);
2618
- if (code !== 0) {
2818
+ const tail = output.read().trim();
2819
+ const tolerated = code !== 0 && reportsIgnoredBuilds(tail) ? {
2820
+ code,
2821
+ output: tail
2822
+ } : void 0;
2823
+ if (code !== 0 && tolerated === void 0) {
2619
2824
  job.phase = "error";
2620
- const tail = output.read().trim();
2621
2825
  job.error = tail === "" ? `plugin-manager: dsh plugin ${job.action} exited with code ${String(code)}` : tail;
2622
2826
  return;
2623
2827
  }
2624
2828
  let after = await this.capture();
2829
+ const reconciledBundles = after.bundles;
2625
2830
  const stripped = await this.stripDuplicateMounts(job, before, after);
2626
2831
  if (stripped === void 0) return;
2627
2832
  if (stripped.length > 0) {
@@ -2638,7 +2843,12 @@ var CliGateway = class {
2638
2843
  const name = this.newDependency(before, after);
2639
2844
  if (name === void 0) {
2640
2845
  job.phase = "error";
2641
- job.error = "plugin-manager: dsh plugin add 报告成功,但 profile 未新增任何依赖(安装未生效)";
2846
+ job.error = tolerated?.output ?? "plugin-manager: dsh plugin add 报告成功,但 profile 未新增任何依赖(安装未生效)";
2847
+ return;
2848
+ }
2849
+ if (await this.bundleSelectionMissing(name, reconciledBundles)) {
2850
+ job.phase = "error";
2851
+ job.error = this.halfMountError(name, "dsh plugin add 只写入了依赖,", tolerated);
2642
2852
  return;
2643
2853
  }
2644
2854
  const duplicate = await this.detectDuplicateClaims(before, after);
@@ -2658,14 +2868,19 @@ var CliGateway = class {
2658
2868
  const targetVersion = job.targetVersion;
2659
2869
  if (targetId === void 0 || targetVersion === void 0 || !after.dependencies.includes(targetId)) {
2660
2870
  job.phase = "error";
2661
- job.error = "plugin-manager: dsh plugin add 报告成功,但目标插件未保留在 profile 中(更新未生效)";
2871
+ job.error = tolerated?.output ?? "plugin-manager: dsh plugin add 报告成功,但目标插件未保留在 profile 中(更新未生效)";
2662
2872
  return;
2663
2873
  }
2664
2874
  const manifest = await readProfileManifest(this.facts.packageJsonPath);
2665
2875
  const updated = await buildPluginRow(this.facts, targetId, manifest.dependencies[targetId] ?? job.spec, after.layer.rows);
2666
2876
  if (updated.version !== targetVersion) {
2667
2877
  job.phase = "error";
2668
- job.error = `plugin-manager: dsh plugin add 报告成功,但 ${targetId} 仍为 ${updated.version},预期 ${targetVersion}(更新未生效)`;
2878
+ job.error = tolerated?.output ?? `plugin-manager: dsh plugin add 报告成功,但 ${targetId} 仍为 ${updated.version},预期 ${targetVersion}(更新未生效)`;
2879
+ return;
2880
+ }
2881
+ if (await this.bundleSelectionMissing(targetId, reconciledBundles, before.bundles.includes(targetId))) {
2882
+ job.phase = "error";
2883
+ job.error = this.halfMountError(targetId, "dsh plugin add 更新了版本,但 ", tolerated);
2669
2884
  return;
2670
2885
  }
2671
2886
  job.plugin = updated;
@@ -2674,7 +2889,7 @@ var CliGateway = class {
2674
2889
  if (await this.pruneOrphanOverrides(job, dump) === void 0) return;
2675
2890
  } else if (before.dependencies.find((candidate) => !after.dependencies.includes(candidate)) === void 0) {
2676
2891
  job.phase = "error";
2677
- job.error = "plugin-manager: dsh plugin remove 报告成功,但依赖仍在 profile 中(卸载未生效)";
2892
+ job.error = tolerated?.output ?? "plugin-manager: dsh plugin remove 报告成功,但依赖仍在 profile 中(卸载未生效)";
2678
2893
  return;
2679
2894
  }
2680
2895
  job.conflicts = conflicts.map((change) => ({
@@ -2684,9 +2899,24 @@ var CliGateway = class {
2684
2899
  to: change.to
2685
2900
  }));
2686
2901
  if (job.action === "install" || job.action === "remove") job.plugin = await this.rowFor(job.action, job.spec, before, after);
2902
+ if (tolerated !== void 0) this.recordToleratedExit(job, tolerated);
2687
2903
  job.phase = "done";
2688
2904
  }
2689
2905
  /**
2906
+ * Carry an accepted non-zero exit to the caller and to the host log.
2907
+ *
2908
+ * Every post-check passed, so the change landed and the job settles `done`;
2909
+ * the pnpm output is kept anyway, because it is the only record that a
2910
+ * dependency was installed without its build script — a fact the next boot
2911
+ * reports as a missing native module, with nothing left to attribute it to.
2912
+ * @param job - the job the run settles.
2913
+ * @param tolerated - the exit the profile overruled.
2914
+ */
2915
+ recordToleratedExit(job, tolerated) {
2916
+ job.warnings = [...job.warnings ?? [], tolerated.output];
2917
+ console.warn(`[plugin-manager] 退出码 ${String(tolerated.code)} 已按完成处理:profile 变更已落地,pnpm 只是跳过了构建脚本(可用 pnpm approve-builds 复核):\n${tolerated.output}`);
2918
+ }
2919
+ /**
2690
2920
  * Post-mutation duplicate-mount safeguard (B9): remove the bundles entries
2691
2921
  * the CLI's reconciliation newly added for packages the before-state
2692
2922
  * composition already mounted through a patch row. The write goes through
@@ -2748,7 +2978,7 @@ var CliGateway = class {
2748
2978
  }
2749
2979
  /**
2750
2980
  * 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.
2981
+ * plus every id the bundles the profile lists still declare.
2752
2982
  *
2753
2983
  * The composition alone does not prove a row is retired. A host that
2754
2984
  * composes while a bundle is being replaced — the remove-then-install half of
@@ -2757,6 +2987,11 @@ var CliGateway = class {
2757
2987
  * gone, and pruning on that probe deletes the user's override for a row that
2758
2988
  * still exists (0.4.7 lost `web-ui-remote-web-ui` and `ui-schedule` this
2759
2989
  * way). Declarations live in the bundle layers, so they survive that window.
2990
+ *
2991
+ * Every listed bundle therefore has to answer with the declarations the
2992
+ * loader will actually mount, which for an installation-provided bundle is
2993
+ * the installation's copy rather than a profile copy that never existed
2994
+ * ({@link bundleLayerDir}).
2760
2995
  * @param composed - the entry ids of the composition probe.
2761
2996
  * @returns the ids to keep, or undefined when a declared layer cannot be
2762
2997
  * read, which proves nothing either way and must leave the file alone.
@@ -2769,13 +3004,10 @@ var CliGateway = class {
2769
3004
  } catch {
2770
3005
  return;
2771
3006
  }
3007
+ const binary = this.binary();
2772
3008
  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
- }
3009
+ const dir = await this.bundleLayerDir(name, manifest.dependencies, binary);
3010
+ if (dir === void 0) return void 0;
2779
3011
  let text;
2780
3012
  try {
2781
3013
  text = await readFile(join(dir, "cordis.patch.yml"), "utf8");
@@ -2792,6 +3024,39 @@ var CliGateway = class {
2792
3024
  return live;
2793
3025
  }
2794
3026
  /**
3027
+ * The directory whose `cordis.patch.yml` declares one listed bundle's rows,
3028
+ * or undefined when those declarations cannot be known.
3029
+ *
3030
+ * The profile's own copy answers whenever it is installed. A profile that
3031
+ * lists a bundle its own `node_modules` does not carry is normally a
3032
+ * CLI-created profile naming the installation's bundles — it never installs
3033
+ * `@deepseek-ai/dsh-base` or `@deepseek-ai/dsh-web-app`, the loader mounts
3034
+ * them out of the DSH installation, and {@link hostBundleDir} names that copy,
3035
+ * whose rows are by construction the ones this boot carries.
3036
+ *
3037
+ * Everything else that reads as missing is a package this profile installs
3038
+ * itself, caught mid-install or mid-replace. Its rows can be declared by the
3039
+ * copy that is gone and by no other, so they are unknown, never empty:
3040
+ * pruning on that guess is how 0.4.7 lost the user's `web-ui-remote-web-ui`
3041
+ * and `ui-schedule` overrides. The profile's own dependency list separates
3042
+ * the two cases, because it is written by the same pnpm call that creates the
3043
+ * directory: a dependency is this profile's package, so a missing directory
3044
+ * there is unfinished work rather than an installation-provided bundle.
3045
+ * @param name - one entry of `dsh.profile.bundles`.
3046
+ * @param dependencies - the profile manifest's dependency map.
3047
+ * @param binary - the dsh CLI path, or null when this runtime has none.
3048
+ * @returns the declaring package directory, or undefined when unknown.
3049
+ */
3050
+ async bundleLayerDir(name, dependencies, binary) {
3051
+ const dir = join(this.facts.profileDir, "node_modules", ...name.split("/"));
3052
+ try {
3053
+ await readFile(join(dir, "package.json"), "utf8");
3054
+ return dir;
3055
+ } catch {}
3056
+ if (Object.hasOwn(dependencies, name)) return void 0;
3057
+ return hostBundleDir(binary, name);
3058
+ }
3059
+ /**
2795
3060
  * The entry names the installed bundles' own rows carry, by entry id.
2796
3061
  *
2797
3062
  * The loader inserts one row per id and takes that row's name from the
@@ -2993,6 +3258,44 @@ var CliGateway = class {
2993
3258
  newDependency(before, after) {
2994
3259
  return after.dependencies.find((name) => !before.dependencies.includes(name));
2995
3260
  }
3261
+ /**
3262
+ * Whether a run wrote a package that declares its own bundle without the
3263
+ * profile selecting it.
3264
+ *
3265
+ * The landing reads in {@link runInner} look at `dependencies` alone, and
3266
+ * pnpm writes that line before the build-script gate decides the exit: a
3267
+ * dependency is not a mount. A package declaring `dsh.bundle` is only
3268
+ * reachable through `dsh.profile.bundles`, so a selection that never landed
3269
+ * (a fresh install) or left with the run (a replacement of a selected
3270
+ * package) is a half mount: the composition carries not one row of it while
3271
+ * every other check passes.
3272
+ * @param name - the dependency the run added or targeted.
3273
+ * @param bundles - the selection the CLI's own run left behind, read before
3274
+ * the duplicate-mount strip can correct its entries.
3275
+ * @param required - whether the selection has to be present: always for a
3276
+ * fresh install, and for a replacement only when the profile already
3277
+ * selected the package (a patch-row mount was never selected to lose).
3278
+ * @returns whether a bundle-declaring package ended up unselected.
3279
+ */
3280
+ async bundleSelectionMissing(name, bundles, required = true) {
3281
+ if (!required || bundles.includes(name)) return false;
3282
+ return declaresBundle(this.facts, name);
3283
+ }
3284
+ /**
3285
+ * The diagnostic for {@link bundleSelectionMissing}: which package the
3286
+ * composition does not mount, and the two steps that repair it. Repeating the
3287
+ * same command cannot — the CLI reconciles only the dependencies it newly
3288
+ * added — so the remedy is an approval followed by remove and add.
3289
+ * @param name - the dependency left unselected.
3290
+ * @param lead - the run's own prefix for the sentence.
3291
+ * @param tolerated - the accepted non-zero exit, whose pnpm tail names the
3292
+ * build scripts it skipped.
3293
+ * @returns the error text.
3294
+ */
3295
+ halfMountError(name, lead, tolerated) {
3296
+ const reason = `${lead}${name} 未进入 dsh.profile.bundles(半挂载:该组合不会挂载它)。请先在 ${join(this.facts.profileDir, "pnpm-workspace.yaml")} 的 allowBuilds 里把要批准的包键写成 \`<包名>: true\` 的映射形式(写成列表会被 pnpm 改写成占位条目),再 dsh plugin --profile ${this.facts.profileName} remove ${name} 后重新 add`;
3297
+ return tolerated === void 0 ? `plugin-manager: ${reason}` : `plugin-manager: ${reason}:\n${tolerated.output}`;
3298
+ }
2996
3299
  /** The claimed entry ids of one installed dependency (its own bundle patch, or its name). */
2997
3300
  claimedEntriesOf(name) {
2998
3301
  return claimedEntryIdsOf(this.facts, name);
@@ -3274,8 +3577,8 @@ function evaluateDshCompatibility(host, range) {
3274
3577
  *
3275
3578
  * The runtime identifiers (web-ui-* rows, settings section, API paths,
3276
3579
  * storage keys) stay frozen; only the npm aggregate package name changes.
3277
- * This module is the single migration map shared by the plugin-manager
3278
- * update job and the Doctor preflight launcher so they never drift.
3580
+ * This module is the single migration map for the plugin-manager update job,
3581
+ * the one official writer that rewrites a user profile.
3279
3582
  */
3280
3583
  /** The previously published aggregate package name. */
3281
3584
  const LEGACY_AGGREGATE = "@linxin666/dsh-web-ui-all";
@@ -3368,6 +3671,156 @@ const DETACHED = new AsyncResource("dsh-web:detached-work", { triggerAsyncId: 0
3368
3671
  function runDetached(work) {
3369
3672
  return DETACHED.runInAsyncScope(work);
3370
3673
  }
3674
+ //#endregion
3675
+ //#region src/core/protocol.ts
3676
+ /**
3677
+ * The unit name shape a systemd restart may name. Deliberately conservative:
3678
+ * the host derives the value from its own cgroup and the browser re-validates
3679
+ * it before the confirmation names a unit, so a value outside this shape is
3680
+ * wire drift rather than a unit worth restarting. The one position that is
3681
+ * refused is a leading `-`: this name travels as the last argv element of
3682
+ * `systemctl --user restart --no-block <unit>`, where a leading `-` reads as
3683
+ * another option instead of a unit. Everything else systemd itself accepts is
3684
+ * kept, including a first `_` or `:` (`_x.service` and `:x.service` are
3685
+ * valid unit names).
3686
+ */
3687
+ const SYSTEMD_UNIT_RE = /^(?!-)[a-zA-Z0-9:_.@-]+\.service$/;
3688
+ /** Whether a value is a systemd unit name this package asks systemd to restart. */
3689
+ function isSystemdUnitName(value) {
3690
+ return SYSTEMD_UNIT_RE.test(value);
3691
+ }
3692
+ //#endregion
3693
+ //#region src/host/restart.ts
3694
+ /**
3695
+ * Restart planning and execution for the plugin-manager gateway.
3696
+ *
3697
+ * The plugin page's restart action exists to make an applied plugin update
3698
+ * effective, which means the DSH host process must come back with the new
3699
+ * packages loaded. How that is achieved depends entirely on who launched this
3700
+ * process, and the host can only tell that from its own facts:
3701
+ *
3702
+ * - A packaged Desktop launch (the Electron shell's child process, see
3703
+ * isPackagedDesktopArgv / ELECTRON_RUN_AS_NODE) cannot be relaunched by a
3704
+ * plugin: Electron owns the process tree, and anything this process spawns
3705
+ * would fight the shell for the same port while Electron reports the host as
3706
+ * crashed. The plugin therefore stops the host and lets the shell run the
3707
+ * restart it already owns (app.relaunch(), the same recovery action the
3708
+ * Desktop app offers after installing a downloaded update). Mode 'shell'.
3709
+ * That only holds for a shell that ACTUALLY restarts a host that exits. A
3710
+ * shell that merely reports the stop leaves a dead window with no host —
3711
+ * strictly worse than not restarting at all — so the shell must announce the
3712
+ * guarantee in {@link SHELL_RESTART_CAPABILITY_ENV}; a host that sees no such
3713
+ * marker answers 'manual' instead of stopping itself (see
3714
+ * {@link shellRestartIsSupported}).
3715
+ * - A host that systemd started is restarted by systemd: the manager owns this
3716
+ * process tree, so asking it to restart the unit is the one action that
3717
+ * survives this process stopping. The host proves that case from its own
3718
+ * cgroup and environment ({@link readSystemdFacts}) and names the unit it
3719
+ * asks; the request goes out after the response, because the stop job starts
3720
+ * the moment the request is queued. Mode 'systemd'. A system unit keeps the
3721
+ * manual answer: restarting it needs privileges this process does not have.
3722
+ * - A host this plugin can prove is a terminal launch (an interactive stdio
3723
+ * pair, no Electron in the environment) is restarted in place: a detached
3724
+ * helper waits for this process to exit and re-executes the same command
3725
+ * line, so the port is free before the replacement binds it. Mode 'relaunch'.
3726
+ * - Everything else — a supervisor-managed launch with piped stdio, a shell
3727
+ * this plugin cannot identify — is left alone: the route answers 'manual'
3728
+ * and this process keeps running rather than dying with no replacement.
3729
+ * Mode 'manual'.
3730
+ *
3731
+ * The decision is pure ({@link planRestart}) so the modes are testable without
3732
+ * spawning anything; {@link performRestart} is the effectful half.
3733
+ * @module @linxin666/dsh-client-ui-plugin-manager/host
3734
+ */
3735
+ /**
3736
+ * The cgroup path of one `/proc/self/cgroup` line: cgroup v1 writes
3737
+ * `<id>:<controllers>:<path>` and v2 writes `0::<path>`. A bare path is
3738
+ * returned unchanged, so the pure parser accepts either form.
3739
+ * @param line - one cgroup line, or a path already stripped of its fields.
3740
+ * @returns the cgroup path.
3741
+ */
3742
+ function cgroupPathOf(line) {
3743
+ const cut = line.indexOf(":", line.indexOf(":") + 1);
3744
+ return cut === -1 ? line : line.slice(cut + 1);
3745
+ }
3746
+ /** The user manager's own unit (`user@1000.service`), the cgroup it runs in. */
3747
+ const USER_MANAGER_UNIT_RE = /^user@\d+\.service$/;
3748
+ /**
3749
+ * Read the systemd-service facts out of a cgroup path and a launch environment,
3750
+ * without touching the system.
3751
+ *
3752
+ * All three markers must hold, and each one is what makes a false positive a
3753
+ * real hazard rather than a wrong label:
3754
+ * - The cgroup's last segment is the decisive one: only a `*.service` unit of
3755
+ * the conservative shape this package accepts on the wire names a service,
3756
+ * while a scope, a session, or a container path is not a unit. A process this
3757
+ * host starts by hand lands in a scope of its own or shares the host's
3758
+ * cgroup, so this segment is what separates a service from what runs inside
3759
+ * one.
3760
+ * - `INVOCATION_ID` rules a launch out but proves nothing on its own: every
3761
+ * process this host starts inherits the host's own marker unchanged, so its
3762
+ * presence is indistinguishable from the host's. It is what rejects a cgroup
3763
+ * path that ends in a service unit only because some other tool put the
3764
+ * process there, which is not a service any manager restarts on request.
3765
+ * - The slice says which manager owns it. Only this user's manager is
3766
+ * reachable without privileges, and it is reachable only through its own
3767
+ * socket ({@link readSystemdFacts} checks that; this parser takes the answer).
3768
+ *
3769
+ * The user manager's own cgroup ends in `user@<uid>.service`. That is a unit
3770
+ * name of this shape, and restarting it takes down every service the manager
3771
+ * runs, so it is refused rather than read as this host's own unit.
3772
+ * @param cgroup - the cgroup path (or a whole `/proc/self/cgroup` line).
3773
+ * @param env - the launch environment.
3774
+ * @param managerSocket - whether this user's systemd manager socket exists.
3775
+ * @returns the unit and its scope, or undefined when this is not a service
3776
+ * this package can ask for a restart.
3777
+ */
3778
+ function parseSystemdFacts(cgroup, env, managerSocket) {
3779
+ const invocation = env.INVOCATION_ID;
3780
+ if (invocation === void 0 || invocation === "") return void 0;
3781
+ const path = cgroupPathOf(cgroup.trim());
3782
+ const scope = path.startsWith("/user.slice/") ? "user" : path.startsWith("/system.slice/") ? "system" : void 0;
3783
+ if (scope === void 0) return void 0;
3784
+ if (scope === "user" && !managerSocket) return void 0;
3785
+ const unit = path.slice(path.lastIndexOf("/") + 1);
3786
+ if (!isSystemdUnitName(unit)) return void 0;
3787
+ if (USER_MANAGER_UNIT_RE.test(unit)) return void 0;
3788
+ return {
3789
+ unit,
3790
+ scope
3791
+ };
3792
+ }
3793
+ /** Whether this user's systemd manager socket exists (the only way to reach it). */
3794
+ function userManagerSocketExists(env) {
3795
+ const runtimeDir = env.XDG_RUNTIME_DIR;
3796
+ if (runtimeDir === void 0 || runtimeDir === "") return false;
3797
+ return existsSync(join(runtimeDir, "systemd", "private"));
3798
+ }
3799
+ /**
3800
+ * Read this process's own systemd-service facts (Linux only).
3801
+ *
3802
+ * Every step is a read that fails on another platform, in a container, or
3803
+ * under an init that is not systemd, and each failure answers "not a systemd
3804
+ * service" instead of throwing: the route that reads this must keep answering
3805
+ * 'manual' rather than turning a restart plan into a 500.
3806
+ * @param env - the launch environment (INVOCATION_ID, XDG_RUNTIME_DIR).
3807
+ * @param cgroupFile - the file carrying this process's cgroup (test seam).
3808
+ * @returns the unit and scope, or undefined when this host is not a service.
3809
+ */
3810
+ function readSystemdFacts(env = process.env, cgroupFile = "/proc/self/cgroup") {
3811
+ if (process.platform !== "linux") return void 0;
3812
+ try {
3813
+ const managerSocket = userManagerSocketExists(env);
3814
+ for (const line of readFileSync(cgroupFile, "utf8").split("\n")) {
3815
+ if (line.trim() === "") continue;
3816
+ const facts = parseSystemdFacts(line, env, managerSocket);
3817
+ if (facts !== void 0) return facts;
3818
+ }
3819
+ return;
3820
+ } catch {
3821
+ return;
3822
+ }
3823
+ }
3371
3824
  /**
3372
3825
  * Environment marker a Desktop shell sets when it guarantees that a host which
3373
3826
  * exits is replaced by a fresh host (rather than reported as stopped).
@@ -3396,10 +3849,15 @@ function isReusableExecArg(argument) {
3396
3849
  /**
3397
3850
  * Decide how a restart request is carried out.
3398
3851
  * @param facts - the running process's launch facts.
3399
- * @returns the planned mode, with the relaunch command when one is used.
3852
+ * @returns the planned mode, with the relaunch command when one is used and
3853
+ * the systemd unit when systemd performs the restart.
3400
3854
  */
3401
3855
  function planRestart(facts) {
3402
3856
  if (facts.desktop === true || facts.env.ELECTRON_RUN_AS_NODE === "1") return shellRestartIsSupported(facts.env) ? { mode: "shell" } : { mode: "manual" };
3857
+ if (facts.systemd?.scope === "user") return {
3858
+ mode: "systemd",
3859
+ unit: facts.systemd.unit
3860
+ };
3403
3861
  if (!facts.interactive) return { mode: "manual" };
3404
3862
  const script = facts.argv[0];
3405
3863
  if (script === void 0 || script === "") return { mode: "manual" };
@@ -3485,31 +3943,114 @@ function startRelaunchHelper(command, logPath = restartLogPath()) {
3485
3943
  });
3486
3944
  helper.unref();
3487
3945
  helper.on("error", (error) => {
3488
- try {
3489
- appendFileSync(logPath, (/* @__PURE__ */ new Date()).toISOString() + " helper spawn error: " + error.message + "\n");
3490
- } catch {}
3946
+ appendRestartLog(logPath, `helper spawn error: ${error.message}`);
3491
3947
  });
3492
3948
  return helper.pid !== void 0;
3493
3949
  } catch (error) {
3494
- try {
3495
- appendFileSync(logPath, `${(/* @__PURE__ */ new Date()).toISOString()} helper failed: ${String(error)}\n`);
3496
- } catch {}
3950
+ appendRestartLog(logPath, `helper failed: ${String(error)}`);
3951
+ return false;
3952
+ }
3953
+ }
3954
+ /** Append one line to the restart journal, ignoring a journal that cannot be written. */
3955
+ function appendRestartLog(logPath, line) {
3956
+ try {
3957
+ appendFileSync(logPath, (/* @__PURE__ */ new Date()).toISOString() + " " + line + "\n");
3958
+ } catch {}
3959
+ }
3960
+ /** Node's `spawn` narrowed to the one overload this module uses. */
3961
+ const spawnDetached = (executable, args, options) => spawn(executable, args, options);
3962
+ /**
3963
+ * Open the restart journal for appending, creating its directory.
3964
+ * @param logPath - journal path.
3965
+ * @returns the open descriptor, or undefined when the journal cannot be opened.
3966
+ */
3967
+ function openRestartJournal(logPath) {
3968
+ try {
3969
+ mkdirSync(dirname(logPath), { recursive: true });
3970
+ return openSync(logPath, "a");
3971
+ } catch {
3972
+ return;
3973
+ }
3974
+ }
3975
+ /**
3976
+ * Ask this user's systemd manager to restart one unit.
3977
+ *
3978
+ * `--no-block` returns as soon as the request is queued, so the caller is never
3979
+ * held by a stop job it just started and the manager owns the rest. What the
3980
+ * command itself says goes to the journal, and so does a deterministic non-zero
3981
+ * exit code; a signal death is not, because it is the stop job this request
3982
+ * queued (the note beside the exit handler spells that out). From here a
3983
+ * refused request looks exactly like a queued one, and the journal is the only
3984
+ * place that difference can be read. Nothing is thrown: by the time
3985
+ * this runs the route has already answered 202, so an exception here would be
3986
+ * an unhandled event in a host nobody is left watching.
3987
+ * @param unit - the unit to restart.
3988
+ * @param logPath - journal that records what the command said and how it ended.
3989
+ * @param runtime - effect seams; the default spawns systemctl detached.
3990
+ * @returns true when a systemctl process was actually created.
3991
+ */
3992
+ function requestUnitRestart(unit, logPath = restartLogPath(), runtime = {}) {
3993
+ const request = `systemctl --user restart ${unit}`;
3994
+ const journal = openRestartJournal(logPath);
3995
+ try {
3996
+ const child = (runtime.spawn ?? spawnDetached)("systemctl", [
3997
+ "--user",
3998
+ "restart",
3999
+ "--no-block",
4000
+ unit
4001
+ ], {
4002
+ detached: true,
4003
+ stdio: journal === void 0 ? "ignore" : [
4004
+ "ignore",
4005
+ journal,
4006
+ journal
4007
+ ]
4008
+ });
4009
+ child.on("error", (error) => {
4010
+ appendRestartLog(logPath, `${request} failed: ${error.message}`);
4011
+ });
4012
+ child.on("exit", (code) => {
4013
+ if (code === null || code === 0) return;
4014
+ appendRestartLog(logPath, `${request} exited with code ${code}`);
4015
+ });
4016
+ child.unref();
4017
+ return child.pid !== void 0;
4018
+ } catch (error) {
4019
+ appendRestartLog(logPath, `${request} failed: ${String(error)}`);
3497
4020
  return false;
4021
+ } finally {
4022
+ if (journal !== void 0) try {
4023
+ closeSync(journal);
4024
+ } catch {}
3498
4025
  }
3499
4026
  }
3500
4027
  /**
3501
4028
  * Carry out one restart plan.
3502
4029
  * @param plan - the verdict from {@link planRestart}.
3503
- * @param runtime - effect seams; the defaults spawn the helper and exit.
4030
+ * @param runtime - effect seams; the defaults spawn the helper, ask systemd,
4031
+ * and exit.
3504
4032
  * @returns the mode actually used: 'relaunch' degrades to 'manual' when the
3505
4033
  * helper could not be started, so a process that cannot be replaced stays up.
4034
+ * A systemd request goes out after the answer and is not awaited, so it keeps
4035
+ * the mode it was planned with; a failed request is journaled, not reported.
3506
4036
  */
3507
4037
  function performRestart(plan, runtime = {}) {
3508
4038
  if (plan.mode === "manual") return "manual";
3509
- const startHelper = runtime.startHelper ?? ((command) => startRelaunchHelper(command));
3510
4039
  const schedule = runtime.schedule ?? ((run, delayMs) => {
3511
4040
  setTimeout(run, delayMs);
3512
4041
  });
4042
+ if (plan.mode === "systemd") {
4043
+ const unit = plan.unit;
4044
+ if (unit === void 0) return "manual";
4045
+ const requestUnit = runtime.requestUnit ?? ((target) => {
4046
+ requestUnitRestart(target);
4047
+ });
4048
+ schedule(() => {
4049
+ requestUnit(unit);
4050
+ }, 400);
4051
+ return "systemd";
4052
+ }
4053
+ const startHelper = runtime.startHelper ?? ((command) => startRelaunchHelper(command));
3513
4054
  const exit = runtime.exit ?? (() => {
3514
4055
  process.exit(0);
3515
4056
  });
@@ -3837,7 +4378,7 @@ function makeGatewayRoutes(deps) {
3837
4378
  status: 502,
3838
4379
  error: unsafeLatest
3839
4380
  };
3840
- if (row.version === latest) return {
4381
+ if (row.version === latest && !gateway.lastUpdateFailed(target, latest)) return {
3841
4382
  status: 409,
3842
4383
  error: `plugin-manager: ${target} is already at ${latest}`
3843
4384
  };
@@ -4008,8 +4549,9 @@ function makeGatewayRoutes(deps) {
4008
4549
  };
4009
4550
  /**
4010
4551
  * The running process's own launch facts, read once per request: the desktop
4011
- * verdict comes from the profile facts (packaged Desktop launcher), the rest
4012
- * from this process.
4552
+ * verdict comes from the profile facts (packaged Desktop launcher), the
4553
+ * systemd facts from this process's own cgroup and environment, the rest from
4554
+ * this process.
4013
4555
  */
4014
4556
  const liveRestartFacts = () => ({
4015
4557
  desktop: facts.desktop,
@@ -4018,18 +4560,24 @@ function makeGatewayRoutes(deps) {
4018
4560
  argv: process.argv.slice(1),
4019
4561
  execArgv: process.execArgv,
4020
4562
  cwd: process.cwd(),
4021
- interactive: process.stdin.isTTY === true || process.stdout.isTTY === true
4563
+ interactive: process.stdin.isTTY === true || process.stdout.isTTY === true,
4564
+ systemd: readSystemdFacts()
4022
4565
  });
4023
4566
  /**
4024
4567
  * Restart the host so an applied plugin update is loaded. The route answers
4025
4568
  * with the mode it actually used (see host/restart.ts): 'relaunch' when this
4026
4569
  * process re-executes itself, 'shell' when the packaged Desktop shell owns
4027
- * the process tree and runs its own restart, 'manual' when neither is safe.
4570
+ * the process tree and runs its own restart, 'systemd' when this host is a
4571
+ * systemd user service that asks its own unit to restart it, 'manual' when
4572
+ * none of these is safe. A systemd plan also names the unit it would restart.
4028
4573
  */
4029
4574
  const restartHandler = async (req, res) => {
4030
4575
  const plan = planRestart((deps.restartFacts ?? liveRestartFacts)());
4031
4576
  if (req.method === "GET" || req.method === "HEAD") {
4032
- writeJson(res, 200, { restart: { mode: plan.mode } });
4577
+ writeJson(res, 200, { restart: {
4578
+ mode: plan.mode,
4579
+ ...plan.unit === void 0 ? {} : { unit: plan.unit }
4580
+ } });
4033
4581
  return;
4034
4582
  }
4035
4583
  if (req.method !== "POST") {