dshmarket 1.73.13 → 1.73.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/client/client.js CHANGED
@@ -462,6 +462,10 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
462
462
  hostIncompatibleSearching: "正在查找还兼容当前 DSH 的版本…",
463
463
  hostIncompatibleFoundInstall: "可以装 {version}:它声明兼容当前 DSH。",
464
464
  hostIncompatibleFoundUpdate: "可以更新到 {version}:它声明兼容当前 DSH。",
465
+ hostIncompatibleHeldTarget: "可以选 {version}:它声明兼容当前 DSH,但还在发布等待期——新版本发布后要等 {window} 小时才算稳定,还差约 {hours} 小时。",
466
+ hostIncompatibleHeldTargetUnknown: "可以选 {version}:它声明兼容当前 DSH,但还在发布等待期,暂时算不出还要等多久。",
467
+ hostIncompatibleHeldButton: "还在等待期(约 {hours} 小时)",
468
+ hostIncompatibleHeldButtonUnknown: "还在等待期",
465
469
  hostIncompatibleNoCompat: "没有找到声明兼容当前 DSH 的版本。",
466
470
  hostIncompatibleSearchFailed: "暂时查不到兼容版本。",
467
471
  hostIncompatibleInstallCompat: "安装 {version}",
@@ -1250,6 +1254,10 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
1250
1254
  hostIncompatibleSearching: "Looking for a version that still supports this DSH…",
1251
1255
  hostIncompatibleFoundInstall: "You can install {version} — it declares support for this DSH.",
1252
1256
  hostIncompatibleFoundUpdate: "You can update to {version} — it declares support for this DSH.",
1257
+ hostIncompatibleHeldTarget: "{version} does declare support for this DSH, but it is still inside the release-age wait — a new release has to settle for {window} hours, so about {hours} more to go.",
1258
+ hostIncompatibleHeldTargetUnknown: "{version} does declare support for this DSH, but it is still inside the release-age wait, and this host cannot work out how long is left.",
1259
+ hostIncompatibleHeldButton: "Still waiting ({hours}h)",
1260
+ hostIncompatibleHeldButtonUnknown: "Still waiting",
1253
1261
  hostIncompatibleNoCompat: "No version declares support for this DSH.",
1254
1262
  hostIncompatibleSearchFailed: "Could not look up compatible versions.",
1255
1263
  hostIncompatibleInstallCompat: "Install {version}",
@@ -2038,6 +2046,10 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
2038
2046
  hostIncompatibleSearching: "現在の DSH と互換性のあるバージョンを探しています…",
2039
2047
  hostIncompatibleFoundInstall: "{version} をインストールできます。現在の DSH への対応を宣言しています。",
2040
2048
  hostIncompatibleFoundUpdate: "{version} に更新できます。現在の DSH への対応を宣言しています。",
2049
+ hostIncompatibleHeldTarget: "{version} は現在の DSH への対応を宣言していますが、まだ公開直後の待機期間中です — 新しい版は {window} 時間の経過が必要で、あと約 {hours} 時間です。",
2050
+ hostIncompatibleHeldTargetUnknown: "{version} は現在の DSH への対応を宣言していますが、まだ公開直後の待機期間中です。残り時間はこの環境では判定できません。",
2051
+ hostIncompatibleHeldButton: "待機中(約 {hours} 時間)",
2052
+ hostIncompatibleHeldButtonUnknown: "待機中",
2041
2053
  hostIncompatibleNoCompat: "現在の DSH への対応を宣言しているバージョンは見つかりませんでした。",
2042
2054
  hostIncompatibleSearchFailed: "互換性のあるバージョンを今は確認できません。",
2043
2055
  hostIncompatibleInstallCompat: "{version} をインストール",
@@ -8463,6 +8475,10 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
8463
8475
  function thumbUrl(src, height, options = {}) {
8464
8476
  let url = `https://images.weserv.nl/?url=${encodeURIComponent(src.replace(/^https?:\/\//, ""))}&h=${String(height)}&fit=inside&we=1`;
8465
8477
  if (options.webp === true && /\.(?:png|jpe?g|webp)(?:$|[?#])/iu.test(src)) url += "&output=webp";
8478
+ else if (/\.gif(?:$|[?#])/iu.test(src)) {
8479
+ const still = `${url}&output=webp`;
8480
+ url = `${url}&n=-1&output=webp&errorredirect=${encodeURIComponent(still)}`;
8481
+ }
8466
8482
  return url;
8467
8483
  }
8468
8484
  /**
@@ -10486,15 +10502,28 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
10486
10502
  return await response.json();
10487
10503
  }).then((data) => {
10488
10504
  if (controller.signal.aborted) return;
10489
- setFindingCompat(typeof data.compatibleVersion === "string" && data.compatibleVersion !== "" ? {
10505
+ if (!(typeof data.compatibleVersion === "string" && data.compatibleVersion !== "")) {
10506
+ setFindingCompat({ status: "not-found" });
10507
+ return;
10508
+ }
10509
+ const maturity = data.maturity !== null && typeof data.maturity === "object" ? data.maturity : null;
10510
+ setFindingCompat({
10490
10511
  status: "found",
10491
- version: data.compatibleVersion
10492
- } : { status: "not-found" });
10512
+ version: data.compatibleVersion,
10513
+ installable: typeof maturity?.installable === "boolean" ? maturity.installable : null,
10514
+ releaseAgeMs: typeof maturity?.releaseAgeMs === "number" ? maturity.releaseAgeMs : null,
10515
+ nextMaturityAt: typeof maturity?.nextMaturityAt === "string" ? maturity.nextMaturityAt : null
10516
+ });
10493
10517
  }).catch(() => {
10494
10518
  if (!controller.signal.aborted) setFindingCompat({ status: "error" });
10495
10519
  });
10496
10520
  return () => controller.abort();
10497
10521
  }, [hostIncompatible, compatRetry]);
10522
+ const hostCompatHeldUpdate = hostIncompatible === null ? void 0 : updates[hostIncompatible.npmName ?? ""];
10523
+ const hostCompatHeld = findingCompat.status === "found" && (findingCompat.installable === false || findingCompat.installable === null && hostCompatHeldUpdate?.heldUpdate !== void 0 && hostCompatHeldUpdate.heldUpdate.latest === findingCompat.version && Date.parse(hostCompatHeldUpdate.heldUpdate.until) > Date.now());
10524
+ const hostCompatNextMaturityAt = findingCompat.status === "found" && findingCompat.installable === null ? hostCompatHeldUpdate?.heldUpdate?.until ?? null : findingCompat.status === "found" ? findingCompat.nextMaturityAt : null;
10525
+ const hostCompatHeldHours = hostCompatHeld && hostCompatNextMaturityAt !== null ? Math.max(1, Math.ceil((Date.parse(hostCompatNextMaturityAt) - Date.now()) / 36e5)) : null;
10526
+ const hostCompatWindowHours = findingCompat.status === "found" && findingCompat.releaseAgeMs !== null ? Math.max(1, Math.round(findingCompat.releaseAgeMs / 36e5)) : 24;
10498
10527
  const [restoreBlocked, setRestoreBlocked] = (0, react.useState)(null);
10499
10528
  const [migrationConfirm, setMigrationConfirm] = (0, react.useState)(null);
10500
10529
  /** Determinate percent parsed from pnpm's Progress line, when available. */
@@ -12427,6 +12456,7 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
12427
12456
  return;
12428
12457
  }
12429
12458
  setRecords((list) => patch(list, updateRecordId, { state: "queued" }));
12459
+ if (body.busy === true) return;
12430
12460
  setInstallError(t("queuedRunBusy"));
12431
12461
  setOperationsOpen(true);
12432
12462
  return;
@@ -17146,16 +17176,16 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
17146
17176
  open: true,
17147
17177
  onClose: () => setHostIncompatible(null),
17148
17178
  title: t("hostIncompatibleTitle"),
17149
- description: [t(hostIncompatible.kind === "install" ? "hostIncompatibleBodyInstall" : "hostIncompatibleBody").replace("{plugin}", `${hostIncompatible.name} ${hostIncompatible.version}`.trim()).replace("{requirement}", hostIncompatible.requirement ?? t("hostIncompatibleUnknown")).replace("{host}", hostIncompatible.hostVersion ?? t("hostIncompatibleUnknown")), hostIncompatible.npmName === null ? null : findingCompat.status === "loading" ? t("hostIncompatibleSearching") : findingCompat.status === "found" ? t(hostIncompatible.kind === "install" ? "hostIncompatibleFoundInstall" : "hostIncompatibleFoundUpdate").replace("{version}", findingCompat.version) : findingCompat.status === "not-found" ? t("hostIncompatibleNoCompat") : findingCompat.status === "error" ? t("hostIncompatibleSearchFailed") : null].filter((line) => line !== null).join("\n"),
17179
+ description: [t(hostIncompatible.kind === "install" ? "hostIncompatibleBodyInstall" : "hostIncompatibleBody").replace("{plugin}", `${hostIncompatible.name} ${hostIncompatible.version}`.trim()).replace("{requirement}", hostIncompatible.requirement ?? t("hostIncompatibleUnknown")).replace("{host}", hostIncompatible.hostVersion ?? t("hostIncompatibleUnknown")), hostIncompatible.npmName === null ? null : findingCompat.status === "loading" ? t("hostIncompatibleSearching") : findingCompat.status === "found" ? hostCompatHeld ? hostCompatHeldHours === null ? t("hostIncompatibleHeldTargetUnknown").replace("{version}", findingCompat.version) : t("hostIncompatibleHeldTarget").replace("{version}", findingCompat.version).replace("{window}", String(hostCompatWindowHours)).replace("{hours}", String(hostCompatHeldHours)) : t(hostIncompatible.kind === "install" ? "hostIncompatibleFoundInstall" : "hostIncompatibleFoundUpdate").replace("{version}", findingCompat.version) : findingCompat.status === "not-found" ? t("hostIncompatibleNoCompat") : findingCompat.status === "error" ? t("hostIncompatibleSearchFailed") : null].filter((line) => line !== null).join("\n"),
17150
17180
  footer: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
17151
17181
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
17152
- variant: findingCompat.status === "found" ? "outline" : "primary",
17182
+ variant: findingCompat.status === "found" && !hostCompatHeld ? "outline" : "primary",
17153
17183
  onClick: () => setHostIncompatible(null),
17154
17184
  children: t(hostIncompatible.kind === "install" ? "hostIncompatibleCancel" : "hostIncompatibleKeep")
17155
17185
  }),
17156
17186
  findingCompat.status === "found" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
17157
17187
  variant: "primary",
17158
- disabled: hostIncompatible.kind === "install" ? busyUrl !== null : updatingName !== null,
17188
+ disabled: hostCompatHeld || (hostIncompatible.kind === "install" ? busyUrl !== null : updatingName !== null),
17159
17189
  onClick: () => {
17160
17190
  const kind = hostIncompatible.kind;
17161
17191
  const target = hostIncompatible.name;
@@ -17166,7 +17196,7 @@ window.__ModuleLoader__.load({ id: "dshmarket", factory: (require) => {
17166
17196
  if (plugin !== null) doInstall(plugin, false, version);
17167
17197
  } else doUpdate(target, false, false, version);
17168
17198
  },
17169
- children: t(hostIncompatible.kind === "install" ? "hostIncompatibleInstallCompat" : "hostIncompatibleUpdateCompat").replace("{version}", findingCompat.version)
17199
+ children: hostCompatHeld ? hostCompatHeldHours === null ? t("hostIncompatibleHeldButtonUnknown") : t("hostIncompatibleHeldButton").replace("{hours}", String(hostCompatHeldHours)) : t(hostIncompatible.kind === "install" ? "hostIncompatibleInstallCompat" : "hostIncompatibleUpdateCompat").replace("{version}", findingCompat.version)
17170
17200
  }),
17171
17201
  findingCompat.status === "error" && hostIncompatible.npmName !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
17172
17202
  variant: "outline",
package/lib/changelog.js CHANGED
@@ -20,7 +20,7 @@
20
20
  * `source` instead: its history is where it came from, and the market says
21
21
  * it has none on hand rather than that the plugin publishes none (#819).
22
22
  */
23
- import { fileFromTarball } from './catalog-npm.js';
23
+ import { absoluteTarballUrl, fileFromTarball } from './catalog-npm.js';
24
24
  import { marketFetch } from './net.js';
25
25
  import { activeRegion, routesFor } from './regions.js';
26
26
  import { profileDir, readGitResolutionCommit, readInstalled, readInstalledRepoEvidence, readInstalledVersion, readLockCommits } from './profile.js';
@@ -61,7 +61,9 @@ export async function loadUpdateNotes(force = false) {
61
61
  const tarball = typeof meta.dist?.tarball === 'string' ? meta.dist.tarball : null;
62
62
  if (tarball === null)
63
63
  throw new Error(`${UPDATES_PACKAGE} names no tarball`);
64
- const tarRes = await marketFetch(tarball, { signal: AbortSignal.timeout(TIMEOUT_MS) });
64
+ // A registry under a path prefix may answer with a relative tarball, the
65
+ // same case the catalog route resolves (#1117).
66
+ const tarRes = await marketFetch(absoluteTarballUrl(tarball, routes.npmRegistry), { signal: AbortSignal.timeout(TIMEOUT_MS) });
65
67
  if (!tarRes.ok)
66
68
  throw new Error(`HTTP ${String(tarRes.status)} reading ${UPDATES_PACKAGE} tarball`);
67
69
  const bytes = fileFromTarball(Buffer.from(await tarRes.arrayBuffer()), UPDATES_FILE);
package/lib/check.js CHANGED
@@ -314,31 +314,61 @@ function parseSemver(value) {
314
314
  };
315
315
  }
316
316
  /**
317
- * Parse a comparator's target the way node-semver does: a PARTIAL version in
318
- * a range is zero-filled, so `<0.3` is `<0.3.0` and `>=2` is `>=2.0.0`.
317
+ * Rewrite a comparator whose target is a PARTIAL version into the full
318
+ * comparators node-semver desugars it to. Anything else comes back as is.
319
319
  *
320
- * Without this, every prerelease floor written as a partial — the
321
- * `@deepseek-ai/dsh-*` peers of a whole family of connector plugins say
322
- * `>=0.1.5 <0.3`, `>=0.1.7-rc <2`, `>=0.2.0-rc.0 <0.3` — parsed as unknown,
323
- * `satisfiesRange` answered null, and the gate stood aside: measured against
324
- * the host's own evaluator over 699 live catalog manifests, those were the
325
- * last 7 of 2796 (package, runtime) pairs where the host refuses a plugin
326
- * and the market still promised a restart would apply it.
320
+ * The `@deepseek-ai/dsh-*` peers of a whole family of connector plugins are
321
+ * written this way (`>=0.1.5 <0.3`, `>=0.1.7-rc <2`, `>=0.2.0-rc.0 <0.3`).
322
+ * Read as unknown, they left the activation gate standing aside: measured
323
+ * against the host's own evaluator over 699 live catalog manifests, those
324
+ * were the last 7 of 2796 (package, runtime) pairs where the host refuses a
325
+ * plugin and the market still promised a restart would apply it.
327
326
  *
328
- * A BARE partial (`1.2`) is a different thing in semver — an x-range that
329
- * means `>=1.2.0 <1.3.0` — so it deliberately stays unknown here rather than
330
- * being mistaken for the exact version `1.2.0`.
327
+ * Zero-filling the target is right for `>=` and wrong for the rest. A partial
328
+ * names a whole release line, so node-semver (`replaceXRange`, `replaceTilde`,
329
+ * `replaceCaret`) moves the bound to the edge of that line:
330
+ *
331
+ * `<0.3` → `<0.3.0-0` `<=0.3` → `<0.4.0-0`
332
+ * `>0.3` → `>=0.4.0` `>1` → `>=2.0.0`
333
+ * `~1` → `>=1.0.0 <2.0.0-0` `^0` → `>=0.0.0 <1.0.0-0`
334
+ * `^0.0` → `>=0.0.0 <0.1.0-0`
335
+ *
336
+ * Comparing against the raw partial string instead ordered `9.1.0` above
337
+ * `10` and `0.10.0` below `0.3`, character by character.
338
+ *
339
+ * A BARE partial (`1.2`) has no operator and is an x-range in semver
340
+ * (`>=1.2.0 <1.3.0`), so it stays as is and parses as unknown below rather
341
+ * than being mistaken for the exact version `1.2.0`.
331
342
  */
332
- function parseComparatorTarget(target, op) {
333
- const direct = parseSemver(target);
334
- if (direct !== null)
335
- return direct;
336
- if (op === '')
337
- return null;
338
- const parts = target.trim().split('.');
339
- if (parts.length > 3 || parts.some(part => !/^\d+$/u.test(part)))
340
- return null;
341
- return parseSemver([...parts, ...Array(3 - parts.length).fill('0')].join('.'));
343
+ function expandPartialComparator(part, includePrerelease) {
344
+ const m = /^(\^|~|>=|<=|>|<)(\d+)(?:\.(\d+))?$/u.exec(part.trim());
345
+ if (m === null)
346
+ return [part];
347
+ const op = m[1];
348
+ const major = Number(m[2]);
349
+ const minor = m[3] === undefined ? null : Number(m[3]);
350
+ // node-semver lowers a desugared floor to `-0` under includePrerelease, so
351
+ // `>=0.3` admits `0.3.0-rc.1` there. Ceilings always carry `-0`.
352
+ const z = includePrerelease ? '-0' : '';
353
+ const floor = `${String(major)}.${String(minor ?? 0)}.0`;
354
+ const nextLine = minor === null ? `${String(major + 1)}.0.0` : `${String(major)}.${String(minor + 1)}.0`;
355
+ switch (op) {
356
+ case '>=':
357
+ return [`>=${floor}${z}`];
358
+ case '>':
359
+ return [`>=${nextLine}${z}`];
360
+ case '<':
361
+ return [`<${exclusiveUpperBound(floor)}`];
362
+ case '<=':
363
+ return [`<${exclusiveUpperBound(nextLine)}`];
364
+ case '~':
365
+ return [`>=${floor}${z}`, `<${exclusiveUpperBound(nextLine)}`];
366
+ default: {
367
+ // `^`: the next major, except inside 0.x where the minor is breaking.
368
+ const ceiling = major > 0 || minor === null ? `${String(major + 1)}.0.0` : `0.${String(minor + 1)}.0`;
369
+ return [`>=${floor}${z}`, `<${exclusiveUpperBound(ceiling)}`];
370
+ }
371
+ }
342
372
  }
343
373
  function comparePre(a, b) {
344
374
  const len = Math.max(a.length, b.length);
@@ -468,7 +498,7 @@ export function satisfiesRange(version, range, options = {}) {
468
498
  const m = /^(\^|~|>=|<=|>|<|=)?(.*)$/.exec(p);
469
499
  const op = m?.[1] === '=' ? '' : (m?.[1] ?? '');
470
500
  const target = (m?.[2] ?? '').trim();
471
- const tv = parseComparatorTarget(target, op);
501
+ const tv = parseSemver(target);
472
502
  if (tv === null)
473
503
  return null;
474
504
  const major = tv.major;
@@ -516,13 +546,14 @@ export function satisfiesRange(version, range, options = {}) {
516
546
  // prerelease admission gate. Otherwise an unknown protocol such as
517
547
  // `workspace:^` or `catalog:default` is misreported as a definite false
518
548
  // whenever the resolved version happens to carry a prerelease tag.
519
- if (parseComparatorTarget(target, op) === null)
549
+ if (parseSemver(target) === null)
520
550
  return null;
521
551
  return { op, target };
522
552
  };
523
553
  /** Evaluate ONE comparator set (a `||` alternative) as a conjunction. */
524
554
  const evaluateSet = (set) => {
525
- const parts = set.trim().split(/\s+/).filter(part => part !== '');
555
+ const parts = set.trim().split(/\s+/).filter(part => part !== '')
556
+ .flatMap(part => expandPartialComparator(part, options.includePrerelease === true));
526
557
  if (parts.length === 0)
527
558
  return true;
528
559
  const parsed = parts.map(part => comparator(part));
package/lib/drain.js CHANGED
@@ -599,6 +599,7 @@ export class DrainCoordinator {
599
599
  */
600
600
  async drainAgents(operation) {
601
601
  operation.state = 'draining';
602
+ let stall = 0;
602
603
  while (!operation.cancelRequested && !this.disposeRequested && !this.barrierBroken) {
603
604
  const live = this.liveAgents();
604
605
  if (live === null)
@@ -613,14 +614,12 @@ export class DrainCoordinator {
613
614
  // turn, while the UI still called them idle. Claim only once nothing is
614
615
  // running, so waiting for one session costs the others nothing.
615
616
  const busy = unheld.some(agent => agent.status === 'running');
616
- let claimed = 0;
617
617
  let waiting = unheld;
618
618
  if (!busy) {
619
619
  for (const agent of unheld) {
620
620
  if (operation.cancelRequested || this.disposeRequested)
621
621
  break;
622
- if (this.claim(agent))
623
- claimed += 1;
622
+ this.claim(agent);
624
623
  }
625
624
  const current = this.liveAgents();
626
625
  if (current === null)
@@ -630,7 +629,8 @@ export class DrainCoordinator {
630
629
  if (waiting.length === 0)
631
630
  return true;
632
631
  }
633
- const waitingForTurn = busy;
632
+ const heldBefore = this.holds.size;
633
+ const signature = waiting.map(agent => `${agent.id}:${String(agent.status)}`).join('\u0000');
634
634
  const activity = this.waitForActivity();
635
635
  try {
636
636
  await Promise.race([
@@ -641,12 +641,38 @@ export class DrainCoordinator {
641
641
  finally {
642
642
  activity.dispose();
643
643
  }
644
- // A claim can fail without the Agent being busy (another maintenance
645
- // task owns it). `whenIdle` then stays pending, so this yield only
646
- // matters for a host that reports idle while refusing the claim. A
647
- // turn that just ended retries immediately.
648
- if (claimed === 0 && !waitingForTurn)
649
- await new Promise(resolve => setTimeout(resolve, 25));
644
+ // A pass can come back with nothing changed — no hold gained and every
645
+ // waited-for Agent in the same state — and then re-entering the loop
646
+ // immediately is a busy loop. Two host shapes do that: a claim refused
647
+ // while the Agent reports idle (another maintenance task owns it, so
648
+ // `whenIdle()` resolves at once), and an Agent whose status still says
649
+ // `running` after its turn is over (sessions left behind by an earlier
650
+ // run), where `whenIdle()` also resolves at once. A profile with 81 such
651
+ // sessions pinned one core at 100% and grew RSS until DSH was restarted
652
+ // (#1134). Pause only when nothing moved: a turn that just ended changes
653
+ // the signature and is retried at once, which is what makes the wait end
654
+ // the moment the Agent is free.
655
+ const moved = this.holds.size !== heldBefore
656
+ || waiting.map(agent => `${agent.id}:${String(agent.status)}`).join('\u0000') !== signature;
657
+ stall = moved ? 0 : stall + 1;
658
+ // One pass without progress is ordinary: `whenIdle()` resolving is what
659
+ // the next pass claims on, and it costs nothing to retry at once. A
660
+ // SECOND consecutive pass with nothing changed means the wake-up came
661
+ // from something that will keep answering instantly — an Agent whose
662
+ // status still says `running` after its turn ended (sessions left behind
663
+ // by an earlier run), or a claim another maintenance task keeps
664
+ // refusing. Looping on that pinned one core at 100% and grew RSS until
665
+ // DSH was restarted (#1134). Pause instead; a status change or any host
666
+ // activity cuts the pause short, so a real turn end is claimed at once.
667
+ if (stall >= 2) {
668
+ const wake = this.waitForActivity();
669
+ try {
670
+ await Promise.race([new Promise(resolve => setTimeout(resolve, 25)), wake.promise]);
671
+ }
672
+ finally {
673
+ wake.dispose();
674
+ }
675
+ }
650
676
  }
651
677
  return false;
652
678
  }
@@ -799,6 +825,10 @@ export class DrainCoordinator {
799
825
  * succeed and hide it, so the transition itself has to stop the command.
800
826
  */
801
827
  onAgentStatus(agent, status) {
828
+ // Any status transition is news to whoever is waiting: a turn ending is
829
+ // exactly the event the drain loop is waiting for, and it also cuts short
830
+ // the no-progress pause (#1134).
831
+ this.notifyActivity();
802
832
  if (status !== 'running')
803
833
  return;
804
834
  const id = agentId(agent);
@@ -27,7 +27,7 @@
27
27
  * to speak up only when the evidence is unambiguous, because a false alarm
28
28
  * here trains the user to ignore the one that matters.
29
29
  */
30
- import { existsSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
30
+ import { existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
31
31
  import { basename, dirname, join } from 'node:path';
32
32
  import { readUserPatchState } from './patch.js';
33
33
  import { createProfileSnapshot, DEFAULT_MAX_SNAPSHOTS } from './snapshot.js';
@@ -99,12 +99,13 @@ export function readHostRecoveryView(patchPath) {
99
99
  *
100
100
  * 1. a profile snapshot, so the restore is undoable the same way every other
101
101
  * write on this page is (issue #98);
102
- * 2. the live patch is RENAMED, never deleted — it is what the app is running
102
+ * 2. the backup's bytes are written to a temp file first, so a write that
103
+ * fails leaves the live patch where it was, and an interrupted one cannot
104
+ * leave a half patch behind, which is the one outcome that would not boot;
105
+ * 3. the live patch is RENAMED, never deleted — it is what the app is running
103
106
  * with right now, and a user who restores the wrong backup must still find
104
- * it there;
105
- * 3. the backup's bytes are written to a temp file and renamed into place, so
106
- * an interrupted write cannot leave a half patch behind, which is the one
107
- * outcome that would not boot at all.
107
+ * it there — and the temp file is renamed into its place. If that last
108
+ * rename fails, the live patch is moved back.
108
109
  *
109
110
  * The backup file itself is left where it is: it is the other copy of the
110
111
  * user's configuration, and this function has no business being the last
@@ -132,21 +133,48 @@ export function restoreHostRecoveryBackup(patchPath, profileDir, name, maxSnapsh
132
133
  // would be the only one on the page with no way back.
133
134
  return { ok: false, error: `恢复前没能存下快照,所以这次没有改动配置:${String(captured.error)} / refused to write without a snapshot: ${String(captured.error)}` };
134
135
  }
136
+ // The temp file is written BEFORE the live patch moves: a write that fails
137
+ // on a full disk or a file held by antivirus must leave the profile with
138
+ // the patch it is running, not with none.
139
+ const temp = `${patchPath}.restore-${process.pid}`;
140
+ const dropTemp = () => {
141
+ try {
142
+ rmSync(temp, { force: true });
143
+ }
144
+ catch { /* not ours to remove (a directory) */ }
145
+ };
146
+ try {
147
+ writeFileSync(temp, contents);
148
+ }
149
+ catch (error) {
150
+ dropTemp();
151
+ return { ok: false, error: `写入失败,所以这次没有改动:${messageOf(error)} / could not write the patch, nothing was changed: ${messageOf(error)}` };
152
+ }
153
+ let movedAside = null;
135
154
  if (existsSync(patchPath)) {
155
+ movedAside = `${patchPath}.bak-${Date.now()}`;
136
156
  try {
137
- renameSync(patchPath, `${patchPath}.bak-${Date.now()}`);
157
+ renameSync(patchPath, movedAside);
138
158
  }
139
159
  catch (error) {
160
+ dropTemp();
140
161
  return { ok: false, error: `当前配置没能先改名保留,所以这次没有改动:${messageOf(error)} / could not move the current patch aside: ${messageOf(error)}` };
141
162
  }
142
163
  }
143
- const temp = `${patchPath}.restore-${process.pid}`;
144
164
  try {
145
- writeFileSync(temp, contents);
146
165
  renameSync(temp, patchPath);
147
166
  }
148
167
  catch (error) {
149
- return { ok: false, error: `写入失败:${messageOf(error)} / could not write the patch: ${messageOf(error)}` };
168
+ dropTemp();
169
+ if (movedAside !== null) {
170
+ try {
171
+ renameSync(movedAside, patchPath);
172
+ }
173
+ catch {
174
+ return { ok: false, error: `写入失败,原配置留在 ${basename(movedAside)}:${messageOf(error)} / could not write the patch; the previous one is at ${basename(movedAside)}: ${messageOf(error)}` };
175
+ }
176
+ }
177
+ return { ok: false, error: `写入失败,所以这次没有改动:${messageOf(error)} / could not write the patch, nothing was changed: ${messageOf(error)}` };
150
178
  }
151
179
  return {
152
180
  ok: true,
package/lib/hot.js CHANGED
@@ -30,7 +30,7 @@ import { pathToFileURL } from 'node:url';
30
30
  import { asChannel } from './channels.js';
31
31
  import { asRegion, normalizeGithubProxy } from './regions.js';
32
32
  import { logEvent } from './log.js';
33
- import { declaredBundlePatchFiles, entryArtifactExists } from './profile.js';
33
+ import { bundlePatchTargets, declaredBundlePatchFiles, entryArtifactExists } from './profile.js';
34
34
  /**
35
35
  * Profile-scoped resolution for hot-mount rows: turn a bare package name into
36
36
  * the absolute `file://` entry URL of the package just installed into
@@ -754,16 +754,19 @@ export async function hotMount(ctx, profileDir, packageName) {
754
754
  */
755
755
  export async function mountClientOnlyDeps(ctx, profileDir) {
756
756
  let deps;
757
+ let bundles;
757
758
  try {
758
759
  const manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8'));
759
- const bundles = new Set(manifest.dsh?.profile?.bundles ?? []);
760
- deps = Object.keys(manifest.dependencies ?? {}).filter(name => !bundles.has(name));
760
+ bundles = manifest.dsh?.profile?.bundles ?? [];
761
+ const bundleSet = new Set(bundles);
762
+ deps = Object.keys(manifest.dependencies ?? {}).filter(name => !bundleSet.has(name));
761
763
  }
762
764
  catch {
763
765
  return [];
764
766
  }
765
767
  const disabled = readDisabled(profileDir);
766
768
  const userManaged = readUserPatchControls(profileDir);
769
+ const hostProvided = bundleLayerTargets(profileDir, bundles);
767
770
  const mounted = [];
768
771
  for (const name of deps) {
769
772
  if (hotHandles.has(name) || disabled.has(name))
@@ -774,6 +777,15 @@ export async function mountClientOnlyDeps(ctx, profileDir) {
774
777
  // every restart (#58 by @vikna919).
775
778
  if (patchLayerManages(userManaged, name))
776
779
  continue;
780
+ // A package the profile's bundle layer ALREADY mounts needs no shim: the
781
+ // entry is live, under a row id only the bundle decides. Sheathing a
782
+ // second fiber over it registers its services again, cordis refuses the
783
+ // duplicate, and the market recorded the shim as live while the host
784
+ // reported the entry as not activated (#1137).
785
+ if (hostProvided.has(name)) {
786
+ logEvent('info', 'boot', `${name}: already mounted by the profile's bundle layer, no client-only shim (#1137)`);
787
+ continue;
788
+ }
777
789
  const dsh = readPkgDsh(profileDir, name);
778
790
  if (dsh === null || dsh.client === undefined || dsh.bundle !== undefined)
779
791
  continue;
@@ -782,6 +794,30 @@ export async function mountClientOnlyDeps(ctx, profileDir) {
782
794
  }
783
795
  return mounted;
784
796
  }
797
+ /**
798
+ * Package names the profile's OWN bundle layer already mounts.
799
+ *
800
+ * The shim predicate reads the profile manifest, so it can only see a package
801
+ * as a dependency; it cannot see that an in-box bundle mounts the same package
802
+ * under a row id of its own — `@deepseek-ai/dsh-web-app` ships
803
+ * `- id: connection` / `name: '@deepseek-ai/dsh-client-connection'` (#1137).
804
+ * Those packages also declare `dsh.client` and no `dsh.bundle`, so every
805
+ * existing predicate says "shim it". Only the row NAMES link the two, and a
806
+ * clean profile's bundles are the only place they are written down.
807
+ *
808
+ * A bundle whose declaration cannot be read contributes nothing, which keeps
809
+ * today's behaviour (shim, possibly duplicated) rather than silently dropping
810
+ * a client bundle that the bundle layer never mounts.
811
+ */
812
+ export function bundleLayerTargets(profileDir, bundles) {
813
+ const targets = new Set();
814
+ for (const bundle of bundles) {
815
+ const dir = join(profileDir, 'node_modules', ...bundle.split('/'));
816
+ for (const name of bundlePatchTargets(dir))
817
+ targets.add(name);
818
+ }
819
+ return targets;
820
+ }
785
821
  /**
786
822
  * Row ids and package names the user's own patch layer (cordis.patch.yml)
787
823
  * already contains. Line-wise scan on purpose: the file may hold structures
package/lib/log.js CHANGED
@@ -62,7 +62,9 @@ export function logEvent(level, event, detail) {
62
62
  try {
63
63
  const line = `${JSON.stringify(entry)}\n`;
64
64
  appendFileSync(persistentFile, line);
65
- persistentBytes += line.length;
65
+ // Bytes, not UTF-16 units: CJK detail is 3 bytes a character on disk,
66
+ // and the counter has to agree with `statSync().size` it started from.
67
+ persistentBytes += Buffer.byteLength(line);
66
68
  // Trimming only on mount left the cap unenforced for the life of a
67
69
  // process: 20k events grew the file to 3.2 MB in a measurement, and a
68
70
  // retry loop is exactly the situation that both logs hardest and never
@@ -87,7 +89,7 @@ function trimPersistentLog(file) {
87
89
  let bytes = 0;
88
90
  for (let index = lines.length - 1; index >= 0 && bytes <= PERSISTENT_MAX_BYTES / 2; index -= 1) {
89
91
  kept.unshift(`${lines[index]}\n`);
90
- bytes += lines[index].length + 1;
92
+ bytes += Buffer.byteLength(lines[index]) + 1;
91
93
  }
92
94
  writeFileSync(file, kept.join(''));
93
95
  persistentBytes = bytes;
@@ -421,6 +421,7 @@ packageManager) {
421
421
  const updateContext = directory === undefined || journal === undefined
422
422
  ? undefined
423
423
  : { profile: profileName, profileDirectory: directory, journal, packageManager };
424
+ const busy = () => active !== undefined || repairing;
424
425
  const runPlugin = (profile, argv) => {
425
426
  if (disposed)
426
427
  return Promise.resolve(failure('official desktop plugin runtime is disposed', 127));
@@ -584,6 +585,7 @@ packageManager) {
584
585
  return {
585
586
  runPlugin,
586
587
  repairPendingUpdates,
588
+ busy,
587
589
  probePnpm: async () => managerLookup() !== undefined,
588
590
  provisionPnpm: async () => ({ ok: managerLookup() !== undefined, hint: 'Use the official desktop plugin manager' }),
589
591
  cancelActive: () => {