@linxin666/dsh-client-ui-plugin-manager 0.4.13 → 0.4.15

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
@@ -1392,6 +1416,58 @@ function findDshBinary(env = process.env, platform = process.platform, exists =
1392
1416
  for (const candidate of candidates) if (exists(candidate)) return candidate;
1393
1417
  return null;
1394
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
+ }
1395
1471
  /**
1396
1472
  * Append bounded CLI output (stdout + stderr interleaved is not preserved;
1397
1473
  * tail wins). Bytes are accumulated and decoded once at read time: a Windows
@@ -1965,15 +2041,17 @@ var CliGateway = class {
1965
2041
  output: add.output
1966
2042
  };
1967
2043
  if (add.code !== 0 && tolerated === void 0) {
1968
- await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled);
1969
- job.error = `plugin-manager: 迁移安装 ${targetSpec} 失败${add.output === "" ? "" : `:\n${add.output}`}`;
2044
+ if (await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled)) job.error = `plugin-manager: 迁移安装 ${targetSpec} 失败${add.output === "" ? "" : `:\n${add.output}`}`;
1970
2045
  return;
1971
2046
  }
1972
2047
  after = await this.capture();
1973
2048
  }
1974
2049
  if (!after.dependencies.includes(targetId)) {
1975
- await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled);
1976
- job.error = tolerated === void 0 ? `plugin-manager: dsh plugin add 报告成功,但 ${targetId} 未出现在 profile 中` : `plugin-manager: 迁移安装 ${targetSpec} 失败${tolerated.output === "" ? "" : `:\n${tolerated.output}`}`;
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);
1977
2055
  return;
1978
2056
  }
1979
2057
  const stripped = await this.stripDuplicateMounts(job, before, after);
@@ -1998,16 +2076,14 @@ var CliGateway = class {
1998
2076
  "--dump-config"
1999
2077
  ], 9e4);
2000
2078
  if (verify.code !== 0) {
2001
- await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled);
2002
- 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}`}`;
2003
2080
  return;
2004
2081
  }
2005
2082
  if (await this.pruneOrphanOverrides(job, verify.output) === void 0) return;
2006
2083
  const manifest = await readProfileManifest(this.facts.packageJsonPath);
2007
2084
  const updated = await buildPluginRow(this.facts, targetId, manifest.dependencies[targetId] ?? targetSpec, after.layer.rows);
2008
2085
  if (!/^(?:link:|file:)/.test(targetSpec) && updated.version !== targetVersion) {
2009
- await this.rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled);
2010
- 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}`;
2011
2087
  return;
2012
2088
  }
2013
2089
  job.plugin = updated;
@@ -2020,28 +2096,52 @@ var CliGateway = class {
2020
2096
  if (tolerated !== void 0) this.recordToleratedExit(job, tolerated);
2021
2097
  job.phase = "done";
2022
2098
  }
2023
- /** 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
+ */
2024
2117
  async rollbackMigration(job, sourceId, targetId, oldSpec, oldIndex, targetPreviouslyInstalled) {
2025
2118
  const binary = this.binary();
2026
2119
  if (binary === null) {
2027
2120
  job.phase = "error";
2028
2121
  job.error = "plugin-manager: 迁移失败且无法回滚:dsh CLI not found on PATH";
2029
- return;
2122
+ return false;
2030
2123
  }
2031
2124
  const current = await this.capture();
2032
- if (!targetPreviouslyInstalled && current.dependencies.includes(targetId)) await this.runCli(binary, [
2033
- "plugin",
2034
- "--profile",
2035
- this.facts.profileName,
2036
- "remove",
2037
- targetId
2038
- ], 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
+ }
2039
2140
  if (targetPreviouslyInstalled) {
2040
2141
  job.phase = "error";
2041
2142
  job.error = "plugin-manager: 聚合包迁移失败,已保留当前聚合包并移除旧包";
2042
- return;
2143
+ return true;
2043
2144
  }
2044
- const restoreOld = this.restoreSpec(sourceId, oldSpec);
2045
2145
  const restored = await this.runCli(binary, [
2046
2146
  "plugin",
2047
2147
  "--profile",
@@ -2052,11 +2152,34 @@ var CliGateway = class {
2052
2152
  if (restored.code !== 0) {
2053
2153
  job.phase = "error";
2054
2154
  job.error = `plugin-manager: 迁移失败且回滚到 ${restoreOld} 失败${restored.output === "" ? "" : `:\n${restored.output}`}`;
2055
- return;
2155
+ return false;
2056
2156
  }
2057
2157
  if (oldIndex >= 0) await reorderProfileBundle(this.facts.packageJsonPath, sourceId, oldIndex).catch(() => void 0);
2058
2158
  job.phase = "error";
2059
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");
2060
2183
  }
2061
2184
  /** Spawn the CLI, through the test seam when present. */
2062
2185
  spawnCli(binary, args) {
@@ -2583,6 +2706,42 @@ var CliGateway = class {
2583
2706
  warnings: job.warnings === void 0 ? void 0 : [...job.warnings]
2584
2707
  };
2585
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
+ }
2586
2745
  /** Capture the layer snapshot and the dependency names (tolerant parse). */
2587
2746
  async capture() {
2588
2747
  const rows = /* @__PURE__ */ new Map();
@@ -2667,6 +2826,7 @@ var CliGateway = class {
2667
2826
  return;
2668
2827
  }
2669
2828
  let after = await this.capture();
2829
+ const reconciledBundles = after.bundles;
2670
2830
  const stripped = await this.stripDuplicateMounts(job, before, after);
2671
2831
  if (stripped === void 0) return;
2672
2832
  if (stripped.length > 0) {
@@ -2686,6 +2846,11 @@ var CliGateway = class {
2686
2846
  job.error = tolerated?.output ?? "plugin-manager: dsh plugin add 报告成功,但 profile 未新增任何依赖(安装未生效)";
2687
2847
  return;
2688
2848
  }
2849
+ if (await this.bundleSelectionMissing(name, reconciledBundles)) {
2850
+ job.phase = "error";
2851
+ job.error = this.halfMountError(name, "dsh plugin add 只写入了依赖,", tolerated);
2852
+ return;
2853
+ }
2689
2854
  const duplicate = await this.detectDuplicateClaims(before, after);
2690
2855
  if (duplicate !== void 0) {
2691
2856
  await this.rollbackInstall(job, name, `与现有插件的入口 id 冲突(${duplicate.ids.join(", ")})`, conflicts);
@@ -2713,6 +2878,11 @@ var CliGateway = class {
2713
2878
  job.error = tolerated?.output ?? `plugin-manager: dsh plugin add 报告成功,但 ${targetId} 仍为 ${updated.version},预期 ${targetVersion}(更新未生效)`;
2714
2879
  return;
2715
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);
2884
+ return;
2885
+ }
2716
2886
  job.plugin = updated;
2717
2887
  const dump = await this.verifyBoot(job, before, after, conflicts);
2718
2888
  if (job.phase === "error") return;
@@ -2808,7 +2978,7 @@ var CliGateway = class {
2808
2978
  }
2809
2979
  /**
2810
2980
  * The entry ids a user-layer override may still point at: the composed ids
2811
- * plus every id the profile's own bundle layers still declare.
2981
+ * plus every id the bundles the profile lists still declare.
2812
2982
  *
2813
2983
  * The composition alone does not prove a row is retired. A host that
2814
2984
  * composes while a bundle is being replaced — the remove-then-install half of
@@ -2817,6 +2987,11 @@ var CliGateway = class {
2817
2987
  * gone, and pruning on that probe deletes the user's override for a row that
2818
2988
  * still exists (0.4.7 lost `web-ui-remote-web-ui` and `ui-schedule` this
2819
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}).
2820
2995
  * @param composed - the entry ids of the composition probe.
2821
2996
  * @returns the ids to keep, or undefined when a declared layer cannot be
2822
2997
  * read, which proves nothing either way and must leave the file alone.
@@ -2829,13 +3004,10 @@ var CliGateway = class {
2829
3004
  } catch {
2830
3005
  return;
2831
3006
  }
3007
+ const binary = this.binary();
2832
3008
  for (const name of manifest.bundles) {
2833
- const dir = join(this.facts.profileDir, "node_modules", ...name.split("/"));
2834
- try {
2835
- await readFile(join(dir, "package.json"), "utf8");
2836
- } catch {
2837
- return;
2838
- }
3009
+ const dir = await this.bundleLayerDir(name, manifest.dependencies, binary);
3010
+ if (dir === void 0) return void 0;
2839
3011
  let text;
2840
3012
  try {
2841
3013
  text = await readFile(join(dir, "cordis.patch.yml"), "utf8");
@@ -2852,6 +3024,39 @@ var CliGateway = class {
2852
3024
  return live;
2853
3025
  }
2854
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
+ /**
2855
3060
  * The entry names the installed bundles' own rows carry, by entry id.
2856
3061
  *
2857
3062
  * The loader inserts one row per id and takes that row's name from the
@@ -3053,6 +3258,44 @@ var CliGateway = class {
3053
3258
  newDependency(before, after) {
3054
3259
  return after.dependencies.find((name) => !before.dependencies.includes(name));
3055
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
+ }
3056
3299
  /** The claimed entry ids of one installed dependency (its own bundle patch, or its name). */
3057
3300
  claimedEntriesOf(name) {
3058
3301
  return claimedEntryIdsOf(this.facts, name);
@@ -3428,6 +3671,156 @@ const DETACHED = new AsyncResource("dsh-web:detached-work", { triggerAsyncId: 0
3428
3671
  function runDetached(work) {
3429
3672
  return DETACHED.runInAsyncScope(work);
3430
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
+ }
3431
3824
  /**
3432
3825
  * Environment marker a Desktop shell sets when it guarantees that a host which
3433
3826
  * exits is replaced by a fresh host (rather than reported as stopped).
@@ -3456,10 +3849,15 @@ function isReusableExecArg(argument) {
3456
3849
  /**
3457
3850
  * Decide how a restart request is carried out.
3458
3851
  * @param facts - the running process's launch facts.
3459
- * @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.
3460
3854
  */
3461
3855
  function planRestart(facts) {
3462
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
+ };
3463
3861
  if (!facts.interactive) return { mode: "manual" };
3464
3862
  const script = facts.argv[0];
3465
3863
  if (script === void 0 || script === "") return { mode: "manual" };
@@ -3545,31 +3943,114 @@ function startRelaunchHelper(command, logPath = restartLogPath()) {
3545
3943
  });
3546
3944
  helper.unref();
3547
3945
  helper.on("error", (error) => {
3548
- try {
3549
- appendFileSync(logPath, (/* @__PURE__ */ new Date()).toISOString() + " helper spawn error: " + error.message + "\n");
3550
- } catch {}
3946
+ appendRestartLog(logPath, `helper spawn error: ${error.message}`);
3551
3947
  });
3552
3948
  return helper.pid !== void 0;
3553
3949
  } catch (error) {
3554
- try {
3555
- appendFileSync(logPath, `${(/* @__PURE__ */ new Date()).toISOString()} helper failed: ${String(error)}\n`);
3556
- } 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)}`);
3557
4020
  return false;
4021
+ } finally {
4022
+ if (journal !== void 0) try {
4023
+ closeSync(journal);
4024
+ } catch {}
3558
4025
  }
3559
4026
  }
3560
4027
  /**
3561
4028
  * Carry out one restart plan.
3562
4029
  * @param plan - the verdict from {@link planRestart}.
3563
- * @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.
3564
4032
  * @returns the mode actually used: 'relaunch' degrades to 'manual' when the
3565
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.
3566
4036
  */
3567
4037
  function performRestart(plan, runtime = {}) {
3568
4038
  if (plan.mode === "manual") return "manual";
3569
- const startHelper = runtime.startHelper ?? ((command) => startRelaunchHelper(command));
3570
4039
  const schedule = runtime.schedule ?? ((run, delayMs) => {
3571
4040
  setTimeout(run, delayMs);
3572
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));
3573
4054
  const exit = runtime.exit ?? (() => {
3574
4055
  process.exit(0);
3575
4056
  });
@@ -3897,7 +4378,7 @@ function makeGatewayRoutes(deps) {
3897
4378
  status: 502,
3898
4379
  error: unsafeLatest
3899
4380
  };
3900
- if (row.version === latest) return {
4381
+ if (row.version === latest && !gateway.lastUpdateFailed(target, latest)) return {
3901
4382
  status: 409,
3902
4383
  error: `plugin-manager: ${target} is already at ${latest}`
3903
4384
  };
@@ -4068,8 +4549,9 @@ function makeGatewayRoutes(deps) {
4068
4549
  };
4069
4550
  /**
4070
4551
  * The running process's own launch facts, read once per request: the desktop
4071
- * verdict comes from the profile facts (packaged Desktop launcher), the rest
4072
- * 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.
4073
4555
  */
4074
4556
  const liveRestartFacts = () => ({
4075
4557
  desktop: facts.desktop,
@@ -4078,18 +4560,24 @@ function makeGatewayRoutes(deps) {
4078
4560
  argv: process.argv.slice(1),
4079
4561
  execArgv: process.execArgv,
4080
4562
  cwd: process.cwd(),
4081
- interactive: process.stdin.isTTY === true || process.stdout.isTTY === true
4563
+ interactive: process.stdin.isTTY === true || process.stdout.isTTY === true,
4564
+ systemd: readSystemdFacts()
4082
4565
  });
4083
4566
  /**
4084
4567
  * Restart the host so an applied plugin update is loaded. The route answers
4085
4568
  * with the mode it actually used (see host/restart.ts): 'relaunch' when this
4086
4569
  * process re-executes itself, 'shell' when the packaged Desktop shell owns
4087
- * 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.
4088
4573
  */
4089
4574
  const restartHandler = async (req, res) => {
4090
4575
  const plan = planRestart((deps.restartFacts ?? liveRestartFacts)());
4091
4576
  if (req.method === "GET" || req.method === "HEAD") {
4092
- 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
+ } });
4093
4581
  return;
4094
4582
  }
4095
4583
  if (req.method !== "POST") {