@linxin666/dsh-client-ui-plugin-manager 0.4.16 → 0.4.18

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
@@ -674,7 +674,7 @@ function desktopSelectedProfile(env = process.env) {
674
674
  function launchedInstallAnchor(launched) {
675
675
  const anchor = launched === void 0 || typeof launched.installAnchor !== "string" ? "" : launched.installAnchor.trim();
676
676
  if (anchor === "") return void 0;
677
- if (!isAbsolute(anchor) || anchor.split(/[\/\\]/).includes("..")) return void 0;
677
+ if (!isAbsolute(anchor) || anchor.split(/[/\\]/).includes("..")) return void 0;
678
678
  return anchor;
679
679
  }
680
680
  /**
@@ -792,8 +792,9 @@ function launchedFacts(launched, desktopLauncher, env) {
792
792
  if (name !== "") assertSafeProfileName(name);
793
793
  const profileRoot = join(resolveDshHome(env), "profiles");
794
794
  const profileDir = dir !== "" ? dir : join(profileRoot, name);
795
- if (!isAbsolute(profileDir) || profileDir.split(/[\/\\]/).includes("..")) throw new Error(`plugin-manager: published profile directory is not a safe absolute path ${JSON.stringify(launched.dir ?? "")}`);
796
- const dirBase = profileDir.split(/[\/\\]/).filter(Boolean).pop() ?? basename(profileDir);
795
+ if (!isAbsolute(profileDir) || profileDir.split(/[/\\]/).includes("..")) throw new Error(`plugin-manager: published profile directory is not a safe absolute path ${JSON.stringify(launched.dir ?? "")}`);
796
+ const baseSegments = profileDir.split(/[/\\]/).filter(Boolean);
797
+ const dirBase = baseSegments[baseSegments.length - 1] ?? basename(profileDir);
797
798
  if (name !== "" && name !== dirBase) throw new Error(`plugin-manager: published profile name and directory disagree ${JSON.stringify(name)} vs ${JSON.stringify(profileDir)}`);
798
799
  const isPosixLiteral = profileDir.includes("/") && !profileDir.includes("\\");
799
800
  const ownPatchPath = isPosixLiteral ? `${profileDir}/cordis.patch.yml` : join(profileDir, "cordis.patch.yml");
@@ -1888,6 +1889,65 @@ function nativeManagerRestartRequired(outcome) {
1888
1889
  if (typeof outcome !== "object" || outcome === null) return false;
1889
1890
  return outcome.application === "restart-required";
1890
1891
  }
1892
+ /** The phase an update ended on, named for the person reading the failure. */
1893
+ const NATIVE_UPDATE_STEP_LABELS = {
1894
+ check: "检查新版本时被拒",
1895
+ remove: "移除已安装版本时被拒",
1896
+ install: "安装新版本时失败"
1897
+ };
1898
+ /**
1899
+ * What one official `updateBundle` run reported as its failure, or undefined
1900
+ * when the target landed.
1901
+ *
1902
+ * The verdict of the phase that ended the run is the only place the reason
1903
+ * lives — the manager folds a refused run into the resolved value instead of
1904
+ * rejecting it — so the phase is named beside the manager's own words: a
1905
+ * refusal to remove is a different fact from a refusal to install.
1906
+ * @param outcome - the resolved value of `updateBundle`.
1907
+ * @returns the failure text to report, or undefined for a run that landed.
1908
+ */
1909
+ function nativeUpdateFailure(outcome) {
1910
+ if (typeof outcome !== "object" || outcome === null) return void 0;
1911
+ const value = outcome;
1912
+ const failure = nativeManagerFailure(value.result);
1913
+ if (failure === void 0) return void 0;
1914
+ return `${NATIVE_UPDATE_STEP_LABELS[value.step ?? ""] ?? "更新未完成"}(${failure})`;
1915
+ }
1916
+ /**
1917
+ * The official manager's refusal code for one update, or undefined when the
1918
+ * target landed. {@link nativeUpdateFailure} renders that verdict for the
1919
+ * person; this is the same verdict read for a decision, which is how the update
1920
+ * path recognises a `bundle-in-use` removal it answers with one retry.
1921
+ * @param outcome - the resolved value of `updateBundle`.
1922
+ */
1923
+ function nativeUpdateRefusalCode(outcome) {
1924
+ if (typeof outcome !== "object" || outcome === null) return void 0;
1925
+ return nativeManagerRefusalCode(outcome.result);
1926
+ }
1927
+ /**
1928
+ * Whether one update landed on disk but is not loaded in this process: the
1929
+ * phase that ended it answered `application: 'restart-required'`.
1930
+ * @param outcome - the resolved value of `updateBundle`.
1931
+ */
1932
+ function nativeUpdateRestartRequired(outcome) {
1933
+ if (typeof outcome !== "object" || outcome === null) return false;
1934
+ return nativeManagerRestartRequired(outcome.result);
1935
+ }
1936
+ /**
1937
+ * How a failed update left the version it removed, as a clause appended to the
1938
+ * failure: the official manager reinstalls that version itself, so the report
1939
+ * says whether the plugin is back or the person has to reinstall it by hand.
1940
+ * @param outcome - the resolved value of `updateBundle`.
1941
+ * @returns the clause, or an empty string when no reinstallation ran.
1942
+ */
1943
+ function nativeUpdateRestoreNote(outcome) {
1944
+ if (typeof outcome !== "object" || outcome === null) return "";
1945
+ const value = outcome;
1946
+ if (value.restore === void 0) return "";
1947
+ const from = typeof value.from === "string" && value.from !== "" ? value.from : "更新前的版本";
1948
+ const failure = nativeManagerFailure(value.restore);
1949
+ return failure === void 0 ? `;已装回 ${from}` : `;装回 ${from} 也失败:${failure},请手动重新安装`;
1950
+ }
1891
1951
  /** The gateway: serializes CLI operations through one job table and one mutation queue. */
1892
1952
  var CliGateway = class {
1893
1953
  facts;
@@ -2227,37 +2287,135 @@ var CliGateway = class {
2227
2287
  * contract the browser half drives is identical either way.
2228
2288
  */
2229
2289
  update(id, version) {
2230
- const spec = `${id}@${version}`;
2231
- const job = {
2290
+ const job = this.newUpdateJob(id, version);
2291
+ this.jobs.set(job.id, job);
2292
+ const unsafe = unsafeSpecReason(job.spec);
2293
+ if (unsafe !== void 0) {
2294
+ job.phase = "error";
2295
+ job.error = unsafe;
2296
+ this.retainFinished(job.id);
2297
+ return { jobId: job.id };
2298
+ }
2299
+ this.enqueue(() => this.settleUpdateJob(job));
2300
+ return { jobId: job.id };
2301
+ }
2302
+ /**
2303
+ * One update job, registered but not yet queued.
2304
+ *
2305
+ * Both the single-plugin update and the batch runner settle this same shape,
2306
+ * so a batch row is applied by exactly the code an update from the plugin's
2307
+ * own page runs: the official in-process manager on an application-owned
2308
+ * profile, the CLI everywhere else.
2309
+ * @param id - installed package name.
2310
+ * @param version - the exact version the update must land on.
2311
+ */
2312
+ newUpdateJob(id, version) {
2313
+ return {
2232
2314
  id: `job-${++this.counter}`,
2233
2315
  action: "update",
2234
- spec,
2316
+ spec: `${id}@${version}`,
2235
2317
  targetId: id,
2236
2318
  targetVersion: version,
2237
2319
  phase: "running"
2238
2320
  };
2321
+ }
2322
+ /**
2323
+ * Apply a whole batch of updates in one run.
2324
+ *
2325
+ * The official manager only replaces one bundle at a time (`updateBundle`), and
2326
+ * the CLI only adds one spec at a time, so a batch is this host's sequence over
2327
+ * that single-plugin primitive rather than a second writer: one job, one
2328
+ * mutation-lock slot, one poll. Rows are applied in the order given, and a row
2329
+ * that cannot be applied — refused by the route's own gate before the run, or
2330
+ * by the writer during it — is recorded and skipped instead of ending the run,
2331
+ * because every managed writer below is atomic per plugin.
2332
+ *
2333
+ * The batch job settles `done` once the last row is answered: the rows carry
2334
+ * the failures, and a run that failed every row is not a failed job but a job
2335
+ * whose every row failed, which is what the caller renders.
2336
+ * @param entries - the rows to apply, in order, each already resolved to the
2337
+ * version it must land on or to the reason it was refused.
2338
+ */
2339
+ updateAll(entries) {
2340
+ const job = {
2341
+ id: `job-${++this.counter}`,
2342
+ action: "update-all",
2343
+ spec: "",
2344
+ phase: "running",
2345
+ results: entries.map((entry) => {
2346
+ if (entry.kind === "refused") return {
2347
+ id: entry.id,
2348
+ phase: "error",
2349
+ error: entry.error
2350
+ };
2351
+ const unsafe = entry.kind === "migrate" ? unsafeSpecReason(entry.id) ?? unsafeSpecReason(entry.targetId) ?? unsafeSpecReason(entry.targetSpec) : unsafeSpecReason(`${entry.id}@${entry.version}`);
2352
+ if (unsafe !== void 0) return {
2353
+ id: entry.id,
2354
+ phase: "error",
2355
+ error: unsafe
2356
+ };
2357
+ const targetVersion = entry.kind === "migrate" ? entry.targetVersion : entry.version;
2358
+ return {
2359
+ id: entry.id,
2360
+ targetVersion,
2361
+ phase: "pending"
2362
+ };
2363
+ })
2364
+ };
2239
2365
  this.jobs.set(job.id, job);
2240
- const unsafe = unsafeSpecReason(spec);
2241
- if (unsafe !== void 0) {
2242
- job.phase = "error";
2243
- job.error = unsafe;
2366
+ this.enqueue(async () => {
2367
+ const native = this.nativeManager();
2368
+ const results = job.results ?? [];
2369
+ for (const [index, entry] of entries.entries()) {
2370
+ const row = results[index];
2371
+ if (row === void 0 || row.phase === "error" || entry.kind === "refused") continue;
2372
+ job.current = entry.id;
2373
+ row.phase = "running";
2374
+ const child = entry.kind === "migrate" ? this.newMigrationJob(entry.id, entry.targetId, entry.targetVersion, entry.targetSpec) : this.newUpdateJob(entry.id, entry.version);
2375
+ this.jobs.set(child.id, child);
2376
+ if (entry.kind === "migrate") await this.settleMigrationJob(child);
2377
+ else await this.settleUpdateJob(child, native);
2378
+ if (child.phase === "done") {
2379
+ row.phase = "done";
2380
+ row.landed = child.plugin?.version ?? (entry.kind === "migrate" ? entry.targetVersion : entry.version);
2381
+ if (child.restartRequired !== void 0 && child.restartRequired.length > 0) row.restartRequired = true;
2382
+ } else {
2383
+ row.phase = "error";
2384
+ row.error = child.error ?? "plugin-manager: 更新失败";
2385
+ }
2386
+ }
2387
+ job.current = void 0;
2388
+ job.phase = "done";
2244
2389
  this.retainFinished(job.id);
2245
- return { jobId: job.id };
2246
- }
2247
- const native = this.nativeManager();
2248
- if (native !== void 0) {
2249
- this.enqueueNativeUpdate(job, native);
2250
- return { jobId: job.id };
2251
- }
2252
- this.enqueue(() => this.run(job, [
2253
- "plugin",
2254
- "--profile",
2255
- this.facts.profileName,
2256
- "add",
2257
- spec
2258
- ], ADD_TIMEOUT_MS));
2390
+ });
2259
2391
  return { jobId: job.id };
2260
2392
  }
2393
+ /**
2394
+ * Run one update job to settlement through whichever writer owns this profile.
2395
+ *
2396
+ * An application-owned profile takes the official in-process manager, which is
2397
+ * the only writer the CLI accepts there; every other runtime keeps the CLI,
2398
+ * whose reconciliation guards this gateway compensates for (see {@link runInner}).
2399
+ * @param job - the update job being settled.
2400
+ * @param native - the official manager, or undefined when the CLI is the writer.
2401
+ */
2402
+ async settleUpdateJob(job, native = this.nativeManager()) {
2403
+ try {
2404
+ if (native !== void 0) await this.runNativeUpdate(job, native);
2405
+ else await this.runInner(job, [
2406
+ "plugin",
2407
+ "--profile",
2408
+ this.facts.profileName,
2409
+ "add",
2410
+ job.spec
2411
+ ], ADD_TIMEOUT_MS);
2412
+ } catch (error) {
2413
+ const reason = error instanceof Error ? error.message : String(error);
2414
+ job.phase = "error";
2415
+ job.error = native !== void 0 ? `plugin-manager: 官方插件管理器更新失败:${reason}` : `plugin-manager: unexpected gateway failure: ${reason}`;
2416
+ }
2417
+ this.retainFinished(job.id);
2418
+ }
2261
2419
  /** Start an install through the official in-process manager. */
2262
2420
  enqueueNativeInstall(job, native) {
2263
2421
  this.enqueue(async () => {
@@ -2314,36 +2472,33 @@ var CliGateway = class {
2314
2472
  }));
2315
2473
  job.phase = "done";
2316
2474
  }
2317
- /** Start an in-place update through the official in-process manager. */
2318
- enqueueNativeUpdate(job, native) {
2319
- this.enqueue(async () => {
2320
- try {
2321
- await this.runNativeUpdate(job, native);
2322
- } catch (error) {
2323
- job.phase = "error";
2324
- job.error = `plugin-manager: 官方插件管理器更新失败:${error instanceof Error ? error.message : String(error)}`;
2325
- }
2326
- this.retainFinished(job.id);
2327
- });
2328
- }
2329
2475
  /**
2330
2476
  * Run one update through the official in-process manager (an application-owned
2331
- * profile, where the CLI refuses to write). The manager resolves the registry,
2332
- * runs pnpm with the launcher's bundled toolchain and applies the bundle, then
2333
- * this reads the profile the same way the CLI path does: the dependency must
2334
- * still be there and the installed version must be the one the route resolved,
2335
- * so a green manager call that changed nothing is still reported as a failure.
2336
- * Its resolved verdict is read first ({@link nativeManagerFailure}): a refused
2337
- * run (pnpm exited non-zero, an incompatible version, a cancellation) resolves
2338
- * with `application: 'failed'`, and only that verdict carries the reason — the
2339
- * profile re-read can only show that the version did not move.
2477
+ * profile, where the CLI refuses to write).
2478
+ *
2479
+ * Since 0.2.2-rc.1 the manager owns the whole replacement: `updateBundle` checks
2480
+ * the target on the registry first (it must exist, declare a bundle and accept
2481
+ * the running DSH version), removes the installed version while the host mounts
2482
+ * `hmr`, installs the target with the selection it found, and reinstalls the
2483
+ * version it removed when that installation fails or is cancelled. This path
2484
+ * therefore no longer sequences those phases itself, and no longer has to
2485
+ * recognise the `already-installed` guard that made an in-place install
2486
+ * impossible. It adds only the two facts the official call does not cover:
2487
+ *
2488
+ * - **The bundle keeps its layer index.** The official removal drops the name
2489
+ * from `dsh.profile.bundles` and the reinstall appends it, and that array is
2490
+ * the layer order the loader applies patches in, so a batch would drift every
2491
+ * row's inheritance ({@link restoreBundleIndex} puts the name back).
2492
+ * - **A `bundle-in-use` refusal is answered once, not repeated** (issue #1905):
2493
+ * the official guard deselects the bundle and reloads before it judges whether
2494
+ * the rows still run, so the retry reads the state that reload left on disk
2495
+ * ({@link applyNativeUpdate}). A second refusal is final and names the restart.
2340
2496
  *
2341
- * An `already-installed` refusal is answered by {@link replaceInstalled}: the
2342
- * manager refuses to install a dependency the profile already carries while the
2343
- * host mounts `hmr` (0.2.1-rc.2, and dsh-base mounts that service on every
2344
- * profile host), so an in-place update there is only expressible as its two
2345
- * phases. The single call stays first so the day the manager accepts an
2346
- * in-place update this path needs no change.
2497
+ * The verdict is read first ({@link nativeUpdateFailure}): a refused run
2498
+ * resolves instead of rejecting, and only that verdict carries the reason — the
2499
+ * profile re-read can only show that the version did not move. The version
2500
+ * verification below is unchanged, so a green run that landed nothing is still
2501
+ * reported as 更新未生效.
2347
2502
  * @param job - the update job being settled.
2348
2503
  * @param native - the official manager.
2349
2504
  */
@@ -2355,28 +2510,27 @@ var CliGateway = class {
2355
2510
  job.error = "plugin-manager: update job is missing the target id or version";
2356
2511
  return;
2357
2512
  }
2358
- const before = await this.capture();
2359
- const carried = await readProfileManifest(this.facts.packageJsonPath);
2360
- const first = await native.installBundle(job.spec, {
2361
- enabled: true,
2362
- requestId: job.id
2363
- });
2364
- let refusal = nativeManagerFailure(first);
2365
- let restartRequired = nativeManagerRestartRequired(first);
2366
- if (refusal !== void 0 && nativeManagerRefusalCode(first) === "already-installed") {
2367
- const replacement = await this.replaceInstalled(job, native, targetId, carried.dependencies[targetId]);
2368
- refusal = replacement.failure;
2369
- restartRequired = replacement.restartRequired;
2513
+ const updateBundle = native.updateBundle?.bind(native);
2514
+ if (updateBundle === void 0) {
2515
+ job.phase = "error";
2516
+ job.error = `plugin-manager: 官方插件管理器没有提供 updateBundle(需要 DSH >= 0.2.2-rc.1),无法在该 profile 上更新 ${targetId}`;
2517
+ return;
2370
2518
  }
2519
+ const before = await this.capture();
2520
+ const previousSpec = (await readProfileManifest(this.facts.packageJsonPath)).dependencies[targetId];
2521
+ const index = await this.bundleIndexOf(targetId);
2522
+ const attempt = await this.applyNativeUpdate(updateBundle, targetId, targetVersion, job.id);
2523
+ const refusal = nativeUpdateFailure(attempt.outcome);
2371
2524
  if (refusal !== void 0) {
2525
+ if (await this.bundleSelectionLost(targetId)) await this.restoreBundleSelection(native, targetId);
2372
2526
  job.phase = "error";
2373
- job.error = `plugin-manager: 官方插件管理器更新失败:${refusal}`;
2527
+ job.error = `plugin-manager: 官方插件管理器更新失败:${refusal}${attempt.remedy}${nativeUpdateRestoreNote(attempt.outcome)}`;
2374
2528
  return;
2375
2529
  }
2376
2530
  const after = await this.capture();
2377
2531
  if (!after.dependencies.includes(targetId)) {
2378
2532
  job.phase = "error";
2379
- job.error = `plugin-manager: 官方插件管理器报告成功,但目标插件未保留在 profile 中(更新未生效)`;
2533
+ job.error = "plugin-manager: 官方插件管理器报告成功,但目标插件未保留在 profile 中(更新未生效)";
2380
2534
  return;
2381
2535
  }
2382
2536
  const manifest = await readProfileManifest(this.facts.packageJsonPath);
@@ -2386,6 +2540,8 @@ var CliGateway = class {
2386
2540
  job.error = `plugin-manager: 官方插件管理器报告成功,但 ${targetId} 仍为 ${updated.version},预期 ${targetVersion}(更新未生效)`;
2387
2541
  return;
2388
2542
  }
2543
+ if (nativeUpdateRestartRequired(attempt.outcome)) job.restartRequired = [targetId];
2544
+ if (previousSpec !== void 0) await this.restoreBundleIndex(targetId, previousSpec, index);
2389
2545
  if (await this.pruneOrphanOverrides(job) === void 0) return;
2390
2546
  job.plugin = updated;
2391
2547
  job.conflicts = significantChanges(diffLayer(before.layer, after.layer)).map((change) => ({
@@ -2394,82 +2550,39 @@ var CliGateway = class {
2394
2550
  from: change.from,
2395
2551
  to: change.to
2396
2552
  }));
2397
- if (restartRequired) job.restartRequired = [targetId];
2398
2553
  job.phase = "done";
2399
2554
  }
2400
2555
  /**
2401
- * Replace an installed bundle with the update job's target spec through the
2402
- * official manager, the only writer an application-owned profile accepts.
2403
- * Removing first is what makes the install possible: the manager's
2404
- * `already-installed` guard reads the profile, so the same name is a fresh
2405
- * dependency once the old one is gone.
2556
+ * Run one official update, answering its `bundle-in-use` removal refusal once.
2406
2557
  *
2407
- * A failed second phase reinstalls the spec the profile carried before the run,
2408
- * so an update that cannot land leaves a working plugin behind instead of an
2409
- * empty slot; the report says which of the two happened.
2410
- *
2411
- * Two facts make the replacement safe to repeat in one session:
2412
- *
2413
- * - **The bundle keeps its layer index.** A removal drops the name from
2414
- * `dsh.profile.bundles` and the reinstall appends it, so a plain
2415
- * remove-then-install moves the bundle behind every bundle that followed it
2416
- * and its patch layer starts overriding rows it never overrode
2417
- * ({@link restoreBundleIndex} puts it back).
2418
- * - **A `bundle-in-use` refusal is answered once, not repeated.** The
2419
- * official guard deselects the bundle and reloads before it checks whether
2420
- * the bundle's rows still run, so a real occupant cleared by that reload is
2421
- * gone on the second call: the update is retried exactly once against that
2422
- * settled state, and a second refusal restores the selection and names the
2423
- * restart the person has to do ({@link removeForReplacement}).
2424
- * - **A landed replacement can still need a restart.** The guard answers
2425
- * `application: 'restart-required'` when the removal applied and the
2426
- * replaced bundle's rows are already gone from the running process (issue
2427
- * #1905). The version does land, so that is a fact to report, not a failure:
2428
- * the update is `done` and names what only a restart loads.
2429
- *
2430
- * @param job - the update job whose spec is installed.
2431
- * @param native - the official manager.
2558
+ * The official guard deselects the bundle, reloads the profile and only then
2559
+ * checks whether the bundle's rows still hold a running fiber. A refusal is
2560
+ * therefore answered against the state that reload left on disk, which covers a
2561
+ * real occupant the reload cleared. It does not cover a reload that rebuilds
2562
+ * the very rows it just unloaded — the fresh fiber matches the guard again — so
2563
+ * the retry is worth exactly one call and never a loop, and a second refusal is
2564
+ * returned with the restart the person has to do.
2565
+ * @param updateBundle - the official manager's update primitive.
2432
2566
  * @param targetId - the installed bundle being replaced.
2433
- * @param previousSpec - the dependency spec the profile carried before the run.
2434
- * @returns the failure to report, or the restart fact once the target landed.
2567
+ * @param targetVersion - the exact version the update must land on.
2568
+ * @param requestId - the job id the run's progress and logs are tracked under.
2569
+ * @returns the manager's verdict for the run that decided the outcome, plus the
2570
+ * remedy text a refusal a retry could not clear needs.
2435
2571
  */
2436
- async replaceInstalled(job, native, targetId, previousSpec) {
2437
- if (previousSpec === void 0) return {
2438
- failure: `${targetId} 不在 profile 依赖中,无法替换已安装版本`,
2439
- restartRequired: false
2572
+ async applyNativeUpdate(updateBundle, targetId, targetVersion, requestId) {
2573
+ const first = await updateBundle(targetId, targetVersion, { requestId });
2574
+ if (nativeUpdateRefusalCode(first) !== "bundle-in-use") return {
2575
+ outcome: first,
2576
+ remedy: ""
2440
2577
  };
2441
- const index = await this.bundleIndexOf(targetId);
2442
- const removal = await this.removeForReplacement(native, targetId);
2443
- if (removal.failure !== void 0) {
2444
- if (removal.deselected) await this.restoreBundleSelection(native, targetId);
2445
- return {
2446
- failure: `已安装版本无法移除(${removal.failure}),本次更新未做改动${removal.remedy}`,
2447
- restartRequired: false
2448
- };
2449
- }
2450
- const installVerdict = await native.installBundle(job.spec, {
2451
- enabled: true,
2452
- requestId: job.id
2453
- });
2454
- const refusal = nativeManagerFailure(installVerdict);
2455
- const restartRequired = removal.restartRequired || nativeManagerRestartRequired(installVerdict);
2456
- if (refusal === void 0) {
2457
- await this.restoreBundleIndex(targetId, previousSpec, index);
2458
- return { restartRequired };
2459
- }
2460
- const restoreSpec = `${targetId}@${previousSpec}`;
2461
- const restoreFailure = nativeManagerFailure(await native.installBundle(restoreSpec, {
2462
- enabled: true,
2463
- requestId: job.id
2464
- }));
2465
- if (restoreFailure !== void 0) return {
2466
- failure: `${refusal};装回 ${restoreSpec} 也失败:${restoreFailure},请手动重新安装`,
2467
- restartRequired: false
2578
+ const second = await updateBundle(targetId, targetVersion, { requestId });
2579
+ if (nativeUpdateRefusalCode(second) !== "bundle-in-use") return {
2580
+ outcome: second,
2581
+ remedy: ""
2468
2582
  };
2469
- await this.restoreBundleIndex(targetId, previousSpec, index);
2470
2583
  return {
2471
- failure: `${refusal};已装回 ${restoreSpec}`,
2472
- restartRequired: false
2584
+ outcome: second,
2585
+ remedy: ";该插件仍由当前 DSH 进程加载,重启 DSH 后再执行本次更新即可"
2473
2586
  };
2474
2587
  }
2475
2588
  /**
@@ -2510,56 +2623,6 @@ var CliGateway = class {
2510
2623
  console.warn(`[plugin-manager] 未能恢复 ${name} 的 bundle 顺序(${spec}):${error instanceof Error ? error.message : String(error)}`);
2511
2624
  }
2512
2625
  }
2513
- /**
2514
- * Remove a bundle for the two-phase replacement, answering the official
2515
- * manager's in-use refusal instead of repeating it.
2516
- *
2517
- * Read the official `removeBundle` guard in order: it deselects the bundle,
2518
- * reloads the profile, and only then checks whether the bundle's own rows
2519
- * still hold a running fiber, which it reports as `bundle-in-use`. A refusal
2520
- * is therefore answered exactly once, against the state that reload left on
2521
- * disk: that covers a real occupant whose fiber the reload did clear.
2522
- *
2523
- * It does not cover a reload that rebuilds the very rows it just unloaded —
2524
- * the fresh fiber matches the guard again — so the retry is worth exactly one
2525
- * call and never a loop, and the second refusal names the restart instead of
2526
- * a bare code. A removal the guard does apply while the rows are already gone
2527
- * resolves as `application: 'restart-required'`; that is a success carrying a
2528
- * restart fact, which is reported as such rather than as a refusal.
2529
- * @param native - the official manager.
2530
- * @param name - the bundle to remove.
2531
- * @returns the refusal to report, whether the profile lost the selection on the
2532
- * way, the remedy text for that refusal, and whether the applied removal still
2533
- * needs a restart to load.
2534
- */
2535
- async removeForReplacement(native, name) {
2536
- const first = await native.removeBundle(name);
2537
- const failure = nativeManagerFailure(first);
2538
- if (failure === void 0) return {
2539
- deselected: false,
2540
- remedy: "",
2541
- restartRequired: nativeManagerRestartRequired(first)
2542
- };
2543
- if (nativeManagerRefusalCode(first) !== "bundle-in-use") return {
2544
- failure,
2545
- deselected: await this.bundleSelectionLost(name),
2546
- remedy: "",
2547
- restartRequired: false
2548
- };
2549
- const second = await native.removeBundle(name);
2550
- const retryFailure = nativeManagerFailure(second);
2551
- if (retryFailure === void 0) return {
2552
- deselected: false,
2553
- remedy: "",
2554
- restartRequired: nativeManagerRestartRequired(second)
2555
- };
2556
- return {
2557
- failure: retryFailure,
2558
- deselected: await this.bundleSelectionLost(name),
2559
- remedy: ";该插件仍由当前 DSH 进程加载,重启 DSH 后再执行本次更新即可",
2560
- restartRequired: false
2561
- };
2562
- }
2563
2626
  /** Whether a bundle is still an installed dependency but no longer selected. */
2564
2627
  async bundleSelectionLost(name) {
2565
2628
  try {
@@ -2580,7 +2643,21 @@ var CliGateway = class {
2580
2643
  }
2581
2644
  /** Start a deterministic legacy aggregate migration. */
2582
2645
  migrate(sourceId, targetId, targetVersion, targetSpec) {
2583
- const job = {
2646
+ const job = this.newMigrationJob(sourceId, targetId, targetVersion, targetSpec);
2647
+ this.jobs.set(job.id, job);
2648
+ const unsafe = unsafeSpecReason(sourceId) ?? unsafeSpecReason(targetId) ?? unsafeSpecReason(targetSpec);
2649
+ if (unsafe !== void 0) {
2650
+ job.phase = "error";
2651
+ job.error = unsafe;
2652
+ this.retainFinished(job.id);
2653
+ return { jobId: job.id };
2654
+ }
2655
+ this.enqueue(() => this.settleMigrationJob(job));
2656
+ return { jobId: job.id };
2657
+ }
2658
+ /** One legacy aggregate migration job, registered but not yet queued. */
2659
+ newMigrationJob(sourceId, targetId, targetVersion, targetSpec) {
2660
+ return {
2584
2661
  id: `job-${++this.counter}`,
2585
2662
  action: "migrate",
2586
2663
  spec: targetSpec,
@@ -2590,26 +2667,22 @@ var CliGateway = class {
2590
2667
  targetSpec,
2591
2668
  phase: "running"
2592
2669
  };
2593
- this.jobs.set(job.id, job);
2594
- const unsafe = unsafeSpecReason(sourceId) ?? unsafeSpecReason(targetId) ?? unsafeSpecReason(targetSpec);
2595
- if (unsafe !== void 0) {
2596
- job.phase = "error";
2597
- job.error = unsafe;
2598
- this.retainFinished(job.id);
2599
- return { jobId: job.id };
2600
- }
2601
- this.enqueue(async () => {
2602
- try {
2603
- await this.runMigration(job);
2604
- } catch (error) {
2605
- if (job.phase !== "error") {
2606
- job.phase = "error";
2607
- job.error = `plugin-manager: unexpected migration failure: ${error instanceof Error ? error.message : String(error)}`;
2608
- }
2670
+ }
2671
+ /**
2672
+ * Run one migration job to settlement; an unexpected failure settles the job
2673
+ * as an error without overwriting a verdict the run already recorded.
2674
+ * @param job - the migration job being settled.
2675
+ */
2676
+ async settleMigrationJob(job) {
2677
+ try {
2678
+ await this.runMigration(job);
2679
+ } catch (error) {
2680
+ if (job.phase !== "error") {
2681
+ job.phase = "error";
2682
+ job.error = `plugin-manager: unexpected migration failure: ${error instanceof Error ? error.message : String(error)}`;
2609
2683
  }
2610
- this.retainFinished(job.id);
2611
- });
2612
- return { jobId: job.id };
2684
+ }
2685
+ this.retainFinished(job.id);
2613
2686
  }
2614
2687
  /**
2615
2688
  * Start a removal; the caller polls {@link status}. An application-owned
@@ -2703,7 +2776,8 @@ var CliGateway = class {
2703
2776
  conflicts: job.conflicts === void 0 ? void 0 : [...job.conflicts],
2704
2777
  notices: job.notices === void 0 ? void 0 : [...job.notices],
2705
2778
  restartRequired: job.restartRequired === void 0 ? void 0 : [...job.restartRequired],
2706
- warnings: job.warnings === void 0 ? void 0 : [...job.warnings]
2779
+ warnings: job.warnings === void 0 ? void 0 : [...job.warnings],
2780
+ results: job.results === void 0 ? void 0 : job.results.map((row) => ({ ...row }))
2707
2781
  };
2708
2782
  }
2709
2783
  /**
@@ -4070,6 +4144,8 @@ const REGISTRY_TIMEOUT_MS = 3e4;
4070
4144
  const VERSION_TIMEOUT_MS = 1e4;
4071
4145
  /** Bounded capture of the version probe output, counted in bytes. */
4072
4146
  const VERSION_MAX_OUTPUT_BYTES = 4096;
4147
+ /** How many plugins one batch update may carry (a page's worth of installed plugins, not a queue). */
4148
+ const MAX_BATCH_UPDATES = 50;
4073
4149
  /** Grace period after SIGTERM before a stuck probe child is SIGKILLed. */
4074
4150
  const VERSION_ESCALATION_TIMEOUT_MS = 5e3;
4075
4151
  /** Successful probe freshness window before the host version is re-read. */
@@ -4303,6 +4379,94 @@ function makeGatewayRoutes(deps) {
4303
4379
  }
4304
4380
  writeJson(res, 200, gateway.install(installSpec));
4305
4381
  };
4382
+ /**
4383
+ * Resolve one update request against the live profile: the exact version to
4384
+ * install, the migration it needs instead, or the refusal that stops it.
4385
+ *
4386
+ * Every answer the update route gives before a job exists — not installed, not
4387
+ * a direct registry plugin, unresolvable version, already at it, a DSH minimum
4388
+ * this host does not satisfy — is produced here, so the single update and the
4389
+ * batch resolve a row by exactly the same rules. A batch turns a refusal into
4390
+ * that row's answer instead of dropping the whole run.
4391
+ * @param target - the installed package name.
4392
+ */
4393
+ const planUpdate = async (target) => {
4394
+ const patchText = await readPatchText(facts.patchPath);
4395
+ const row = (await snapshotGateway(facts, patchText)).plugins.find((plugin) => plugin.id === target);
4396
+ if (row === void 0) return {
4397
+ status: 404,
4398
+ error: `plugin-manager: plugin ${target} is not installed`
4399
+ };
4400
+ const migration = legacyMigrationFor(target);
4401
+ if (migration !== void 0) {
4402
+ const targetManifest = await fetchManifest(migration.to).catch(() => void 0);
4403
+ if (targetManifest === void 0 || targetManifest.version === "") return {
4404
+ status: 502,
4405
+ error: `plugin-manager: cannot resolve the migration target ${migration.to}`
4406
+ };
4407
+ const targetSpec = targetSpecForLegacy(row.source.spec, targetManifest.version);
4408
+ if (targetSpec === void 0) return {
4409
+ status: 400,
4410
+ error: `plugin-manager: cannot derive the migration target spec for ${target}`
4411
+ };
4412
+ const unsafeTarget = unsafeSpecReason(targetSpec);
4413
+ if (unsafeTarget !== void 0) return {
4414
+ status: 400,
4415
+ error: unsafeTarget
4416
+ };
4417
+ const requiresDsh = dshRequirementOf(targetManifest);
4418
+ if (requiresDsh !== void 0) {
4419
+ const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
4420
+ if (!compatible) return {
4421
+ status: 412,
4422
+ error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${migration.to} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before migrating` : `plugin-manager: ${migration.to} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before migrating`
4423
+ };
4424
+ }
4425
+ return {
4426
+ status: 200,
4427
+ kind: "migrate",
4428
+ targetId: migration.to,
4429
+ targetVersion: targetManifest.version,
4430
+ targetSpec
4431
+ };
4432
+ }
4433
+ if (row.source.kind !== "npm" || !isDirectRegistrySpec(row.source.spec)) return {
4434
+ status: 400,
4435
+ error: `plugin-manager: ${target} is not a direct npm registry plugin`
4436
+ };
4437
+ const manifest = await fetchManifest(target).catch(() => void 0);
4438
+ if (manifest === void 0) return {
4439
+ status: 502,
4440
+ error: `plugin-manager: cannot resolve the latest version for ${target}`
4441
+ };
4442
+ const latest = manifest.version;
4443
+ if (latest === "") return {
4444
+ status: 502,
4445
+ error: `plugin-manager: cannot resolve the latest version for ${target}`
4446
+ };
4447
+ const unsafeLatest = unsafeSpecReason(`${target}@${latest}`);
4448
+ if (unsafeLatest !== void 0) return {
4449
+ status: 502,
4450
+ error: unsafeLatest
4451
+ };
4452
+ if (row.version === latest && !gateway.lastUpdateFailed(target, latest)) return {
4453
+ status: 409,
4454
+ error: `plugin-manager: ${target} is already at ${latest}`
4455
+ };
4456
+ const requiresDsh = dshRequirementOf(manifest);
4457
+ if (requiresDsh !== void 0) {
4458
+ const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
4459
+ if (!compatible) return {
4460
+ status: 412,
4461
+ error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${target} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before updating` : `plugin-manager: ${target} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before updating`
4462
+ };
4463
+ }
4464
+ return {
4465
+ status: 200,
4466
+ kind: "update",
4467
+ version: latest
4468
+ };
4469
+ };
4306
4470
  const updateHandler = async (req, res) => {
4307
4471
  const id = (await readJsonBody(req, {
4308
4472
  maxBytes: 64 * 1024,
@@ -4323,76 +4487,14 @@ function makeGatewayRoutes(deps) {
4323
4487
  return;
4324
4488
  }
4325
4489
  const outcome = await gateway.withMutationLock(async () => {
4326
- const patchText = await readPatchText(facts.patchPath);
4327
- const row = (await snapshotGateway(facts, patchText)).plugins.find((plugin) => plugin.id === target);
4328
- if (row === void 0) return {
4329
- status: 404,
4330
- error: `plugin-manager: plugin ${target} is not installed`
4331
- };
4332
- const migration = legacyMigrationFor(target);
4333
- if (migration !== void 0) {
4334
- const targetManifest = await fetchManifest(migration.to).catch(() => void 0);
4335
- if (targetManifest === void 0 || targetManifest.version === "") return {
4336
- status: 502,
4337
- error: `plugin-manager: cannot resolve the migration target ${migration.to}`
4338
- };
4339
- const targetSpec = targetSpecForLegacy(row.source.spec, targetManifest.version);
4340
- if (targetSpec === void 0) return {
4341
- status: 400,
4342
- error: `plugin-manager: cannot derive the migration target spec for ${target}`
4343
- };
4344
- const unsafeTarget = unsafeSpecReason(targetSpec);
4345
- if (unsafeTarget !== void 0) return {
4346
- status: 400,
4347
- error: unsafeTarget
4348
- };
4349
- const requiresDsh = dshRequirementOf(targetManifest);
4350
- if (requiresDsh !== void 0) {
4351
- const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
4352
- if (!compatible) return {
4353
- status: 412,
4354
- error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${migration.to} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before migrating` : `plugin-manager: ${migration.to} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before migrating`
4355
- };
4356
- }
4357
- return {
4358
- status: 200,
4359
- job: gateway.migrate(target, migration.to, targetManifest.version, targetSpec)
4360
- };
4361
- }
4362
- if (row.source.kind !== "npm" || !isDirectRegistrySpec(row.source.spec)) return {
4363
- status: 400,
4364
- error: `plugin-manager: ${target} is not a direct npm registry plugin`
4365
- };
4366
- const manifest = await fetchManifest(target).catch(() => void 0);
4367
- if (manifest === void 0) return {
4368
- status: 502,
4369
- error: `plugin-manager: cannot resolve the latest version for ${target}`
4370
- };
4371
- const latest = manifest.version;
4372
- if (latest === "") return {
4373
- status: 502,
4374
- error: `plugin-manager: cannot resolve the latest version for ${target}`
4375
- };
4376
- const unsafeLatest = unsafeSpecReason(`${target}@${latest}`);
4377
- if (unsafeLatest !== void 0) return {
4378
- status: 502,
4379
- error: unsafeLatest
4380
- };
4381
- if (row.version === latest && !gateway.lastUpdateFailed(target, latest)) return {
4382
- status: 409,
4383
- error: `plugin-manager: ${target} is already at ${latest}`
4384
- };
4385
- const requiresDsh = dshRequirementOf(manifest);
4386
- if (requiresDsh !== void 0) {
4387
- const { hostVersion, compatible } = await compatibleVerdict(requiresDsh);
4388
- if (!compatible) return {
4389
- status: 412,
4390
- error: hostVersion === void 0 ? `plugin-manager: cannot verify the running DSH version for ${target} against the declared requirement ${requiresDsh}; check the declaration and the DSH runtime before updating` : `plugin-manager: ${target} requires DSH ${requiresDsh} (current DSH ${hostVersion}); upgrade DSH before updating`
4391
- };
4392
- }
4393
- return {
4394
- status: 200,
4395
- job: gateway.update(target, latest)
4490
+ const plan = await planUpdate(target);
4491
+ if ("error" in plan) return plan;
4492
+ return plan.kind === "migrate" ? {
4493
+ status: plan.status,
4494
+ job: gateway.migrate(target, plan.targetId, plan.targetVersion, plan.targetSpec)
4495
+ } : {
4496
+ status: plan.status,
4497
+ job: gateway.update(target, plan.version)
4396
4498
  };
4397
4499
  });
4398
4500
  if ("error" in outcome) {
@@ -4401,6 +4503,74 @@ function makeGatewayRoutes(deps) {
4401
4503
  }
4402
4504
  writeJson(res, outcome.status, outcome.job);
4403
4505
  };
4506
+ /**
4507
+ * Apply every listed plugin update in one run.
4508
+ *
4509
+ * The official manager updates one bundle at a time and the CLI adds one spec
4510
+ * at a time, so the batch is this gateway's sequence over that single-plugin
4511
+ * primitive: one job, one mutation-lock slot, one poll, and one ledger of rows.
4512
+ * Each id is resolved here first, exactly as a single update is, and a row that
4513
+ * cannot be resolved is carried into the job as its own answer rather than
4514
+ * failing the request — one plugin already at its newest version must not stop
4515
+ * the eight behind it.
4516
+ */
4517
+ const updatesHandler = async (req, res) => {
4518
+ const listed = (await readJsonBody(req, {
4519
+ maxBytes: 64 * 1024,
4520
+ objectOnly: true
4521
+ }) ?? {})["ids"];
4522
+ if (!Array.isArray(listed) || listed.length === 0) {
4523
+ writeJson(res, 400, { error: "plugin-manager: updates needs a non-empty ids array" });
4524
+ return;
4525
+ }
4526
+ if (listed.length > MAX_BATCH_UPDATES) {
4527
+ writeJson(res, 400, { error: `plugin-manager: updates accepts at most ${String(MAX_BATCH_UPDATES)} ids` });
4528
+ return;
4529
+ }
4530
+ const targets = [];
4531
+ for (const value of listed) {
4532
+ if (typeof value !== "string" || value.trim() === "") {
4533
+ writeJson(res, 400, { error: "plugin-manager: updates needs string ids" });
4534
+ return;
4535
+ }
4536
+ const target = value.trim();
4537
+ const unsafe = unsafeSpecReason(target);
4538
+ if (unsafe !== void 0) {
4539
+ writeJson(res, 400, { error: unsafe });
4540
+ return;
4541
+ }
4542
+ if (!targets.includes(target)) targets.push(target);
4543
+ }
4544
+ if (!deps.cliAvailable() && !gateway.usesNativeWriter()) {
4545
+ writeJson(res, 500, { error: "plugin-manager: dsh CLI not found on PATH" });
4546
+ return;
4547
+ }
4548
+ const entries = await gateway.withMutationLock(async () => {
4549
+ const plan = [];
4550
+ for (const target of targets) {
4551
+ const row = await planUpdate(target);
4552
+ if ("error" in row) plan.push({
4553
+ kind: "refused",
4554
+ id: target,
4555
+ error: row.error
4556
+ });
4557
+ else if (row.kind === "migrate") plan.push({
4558
+ kind: "migrate",
4559
+ id: target,
4560
+ targetId: row.targetId,
4561
+ targetVersion: row.targetVersion,
4562
+ targetSpec: row.targetSpec
4563
+ });
4564
+ else plan.push({
4565
+ kind: "apply",
4566
+ id: target,
4567
+ version: row.version
4568
+ });
4569
+ }
4570
+ return plan;
4571
+ });
4572
+ writeJson(res, 200, gateway.updateAll(entries));
4573
+ };
4404
4574
  const removeHandler = async (req, res) => {
4405
4575
  const id = (await readJsonBody(req, {
4406
4576
  maxBytes: 64 * 1024,
@@ -4602,6 +4772,11 @@ function makeGatewayRoutes(deps) {
4602
4772
  path: `${GATEWAY_PREFIX}/update`,
4603
4773
  handler: guard(updateHandler)
4604
4774
  },
4775
+ {
4776
+ kind: "exact",
4777
+ path: `${GATEWAY_PREFIX}/updates`,
4778
+ handler: guard(updatesHandler)
4779
+ },
4605
4780
  {
4606
4781
  kind: "exact",
4607
4782
  path: `${GATEWAY_PREFIX}/remove`,