dsh-crate 0.5.1 → 0.5.3

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.
@@ -13,6 +13,7 @@ import { dirname } from 'node:path';
13
13
  import { compareSemver, isSemver, satisfiesRange } from './check.js';
14
14
  import { classifyPeer, crossesImplicitCeiling } from './compatibility.js';
15
15
  import { marketFetch } from './net.js';
16
+ import { isStableReleaseVersion } from './release-candidates.js';
16
17
  import { activeRegion, githubRoutesFor, rememberGithubRoute, throughProxy } from './regions.js';
17
18
  import { parseSourceUrl } from './sources.js';
18
19
  const CACHE_SCHEMA = 'dsh-crate/discovery-compatibility-cache/v1';
@@ -21,7 +22,9 @@ const FAILURE_COOLDOWN_MS = 5 * 60 * 1000;
21
22
  const OUTAGE_COOLDOWN_MS = 30 * 1000;
22
23
  const FETCH_TIMEOUT_MS = 8_000;
23
24
  const DEFAULT_CONCURRENCY = 8;
24
- const MAX_CACHE_ENTRIES = 5_000;
25
+ // Larger than the catalog (10k+ and growing). A cap below the catalog size
26
+ // made a full scan evict its own first half, so no scan ever stayed cached (#1170).
27
+ const MAX_CACHE_ENTRIES = 20_000;
25
28
  const MAX_RANGE_LENGTH = 256;
26
29
  /** Reuse catalog facts only for this repository's exact pinned install asset. */
27
30
  export function catalogReleaseManifest(source) {
@@ -31,7 +34,12 @@ export function catalogReleaseManifest(source) {
31
34
  if (facts === null || !repository || !release || release[1].toLowerCase() !== repository.toLowerCase()
32
35
  || facts.tarball !== source.tarball || !validFacts(facts))
33
36
  return null;
34
- return { version: facts.version, enginesDsh: facts.enginesDsh, peerDependencies: facts.peerDependencies };
37
+ return {
38
+ version: facts.version,
39
+ enginesDsh: facts.enginesDsh,
40
+ peerDependencies: facts.peerDependencies,
41
+ dependencies: facts.dependencies ?? {},
42
+ };
35
43
  }
36
44
  /** Read the linked package at its selected release, never the repository root by accident. */
37
45
  async function githubManifest(source, fetcher) {
@@ -129,20 +137,35 @@ export function manifestFacts(value) {
129
137
  if (declared !== null)
130
138
  peerDependencies[name] = declared;
131
139
  }
140
+ const dependencies = record(manifest.dependencies);
141
+ const hostDependencies = {};
142
+ for (const [name, raw] of Object.entries(dependencies ?? {})) {
143
+ if (!name.startsWith('@deepseek-ai/'))
144
+ continue;
145
+ const declared = range(raw);
146
+ if (declared !== null)
147
+ hostDependencies[name] = declared;
148
+ }
132
149
  return {
133
150
  version: range(manifest.version),
134
151
  enginesDsh: range(engines?.dsh) ?? range(dshEngines?.dsh),
135
152
  peerDependencies,
153
+ dependencies: hostDependencies,
136
154
  };
137
155
  }
138
156
  function validFacts(value) {
139
157
  const facts = record(value);
140
158
  const peers = record(facts?.peerDependencies);
159
+ // A missing `dependencies` is a pre-upgrade cache entry or catalog manifest,
160
+ // not a malformed one: the durable cache must survive the upgrade rather than
161
+ // be discarded and refetched a thousand packages at once.
162
+ const dependencies = record(facts?.dependencies);
141
163
  return facts !== null
142
164
  && (facts.version === null || range(facts.version) === facts.version)
143
165
  && (facts.enginesDsh === null || range(facts.enginesDsh) === facts.enginesDsh)
144
166
  && peers !== null
145
- && Object.entries(peers).every(([name, item]) => name.startsWith('@deepseek-ai/') && range(item) === item);
167
+ && Object.entries(peers).every(([name, item]) => name.startsWith('@deepseek-ai/') && range(item) === item)
168
+ && (dependencies === null || Object.entries(dependencies).every(([name, item]) => name.startsWith('@deepseek-ai/') && range(item) === item));
146
169
  }
147
170
  function displayRequirement(declarations) {
148
171
  const unique = [...new Set(declarations.map(item => item.range))];
@@ -167,7 +190,12 @@ function rangeResult(hostVersion, declared) {
167
190
  */
168
191
  function declarationResult(declaration, hostVersion) {
169
192
  const satisfied = rangeResult(hostVersion, declaration.range);
170
- if (declaration.kind === 'engine' || satisfied !== false)
193
+ // Only a PEER may be stretched: it is a statement of intent about the host
194
+ // line, and the ecosystem is full of sloppy caret ceilings. An engine is a
195
+ // plain bound, and a DEPENDENCY is an install instruction — pnpm resolves
196
+ // the declared range and hoists the result, so a range that excludes the
197
+ // running version means a second copy shadows the host's.
198
+ if (declaration.kind !== 'peer' || satisfied !== false)
171
199
  return satisfied;
172
200
  if (crossesImplicitCeiling(hostVersion, declaration.range))
173
201
  return false;
@@ -202,6 +230,22 @@ export function deriveHostCompatibility(facts, hostVersion, hostPackages) {
202
230
  continue;
203
231
  declarations.push({ kind: 'peer', package: name, range: declared });
204
232
  }
233
+ for (const [name, declared] of Object.entries(facts.dependencies ?? {})) {
234
+ // The peer filter above restricts itself to DSH's lockstep line because a
235
+ // peer range on cordis or schemastery says nothing about the DSH version.
236
+ // A dependency is different: it names a package the host itself provides,
237
+ // and pnpm will install the declared copy and hoist it over the host's.
238
+ // That is the dsh-qqbot failure — @deepseek-ai/dsh-settings and
239
+ // dsh-credentials as ordinary dependencies at `^0.1.0-rc.5` over a
240
+ // 0.2.2-rc.1 runtime — which the peer-only check could not see.
241
+ // Still only the lockstep line: the range is judged against the DSH
242
+ // version, and cordis (4.x) / schemastery (3.x) are not on it — a plugin
243
+ // that depends on `@deepseek-ai/cordis@^4` would otherwise read as
244
+ // incompatible with every host.
245
+ if (!hostPackages.has(name) || !/^@deepseek-ai\/dsh(?:-|$)/.test(name))
246
+ continue;
247
+ declarations.push({ kind: 'dependency', package: name, range: declared });
248
+ }
205
249
  const requirement = displayRequirement(declarations);
206
250
  if (declarations.length === 0) {
207
251
  return { status: 'unknown', basis: 'undeclared', requirement: null, declarations: [] };
@@ -257,7 +301,11 @@ export class DiscoveryManifestIndex {
257
301
  const entry = record(raw);
258
302
  if (entry === null || typeof entry.checkedAt !== 'number' || !validFacts(entry.facts))
259
303
  continue;
260
- this.entries.set(name, { checkedAt: entry.checkedAt, facts: entry.facts });
304
+ // Normalize the pre-upgrade shape so every consumer sees an object.
305
+ const facts = entry.facts.dependencies === undefined
306
+ ? { ...entry.facts, dependencies: {} }
307
+ : entry.facts;
308
+ this.entries.set(name, { checkedAt: entry.checkedAt, facts });
261
309
  }
262
310
  }
263
311
  catch { /* first run or a truncated cache — fetch fresh */ }
@@ -446,10 +494,14 @@ export class DiscoveryManifestIndex {
446
494
  * installed one, which is what an update needs: suggesting a downgrade is not
447
495
  * an update.
448
496
  *
497
+ * `stableOnly` drops prereleases. The official Desktop refuses to move a
498
+ * stable install onto a prerelease by itself (#991), so offering one there is
499
+ * an enabled button that can only answer 409 (#1161).
500
+ *
449
501
  * @returns the version, or null when the packument cannot be read or nothing
450
502
  * in the history declares itself compatible.
451
503
  */
452
- export async function findCompatibleVersion(npmName, hostVersion, hostPackages, registry, fetcher = marketFetch, minimumVersionExclusive = null) {
504
+ export async function findCompatibleVersion(npmName, hostVersion, hostPackages, registry, fetcher = marketFetch, minimumVersionExclusive = null, stableOnly = false) {
453
505
  let doc;
454
506
  try {
455
507
  const res = await fetcher(`${registry}/${encodeURIComponent(npmName)}`, { signal: AbortSignal.timeout(15_000), headers: { accept: 'application/json', 'user-agent': 'dsh-crate' } });
@@ -465,6 +517,7 @@ export async function findCompatibleVersion(npmName, hostVersion, hostPackages,
465
517
  return null;
466
518
  const candidates = Object.keys(versions)
467
519
  .filter(version => isSemver(version)
520
+ && (!stableOnly || isStableReleaseVersion(version))
468
521
  && (minimumVersionExclusive === null || compareSemver(version, minimumVersionExclusive) > 0))
469
522
  .sort((left, right) => compareSemver(right, left));
470
523
  for (const version of candidates) {
package/lib/drain.js CHANGED
@@ -52,6 +52,15 @@ function record(value) {
52
52
  function text(value) {
53
53
  return typeof value === 'string' && value.trim() !== '' ? value.trim() : null;
54
54
  }
55
+ /** True when the executor reported a completed change. */
56
+ function landed(result) {
57
+ const payload = record(result.payload);
58
+ return result.status >= 200 && result.status < 300 && payload?.ok !== false && payload?.cancelled !== true;
59
+ }
60
+ /** Mark a finished result as having outlived its market instance. */
61
+ function markReloaded(result) {
62
+ return { ...result, payload: { ...(record(result.payload) ?? {}), marketReloaded: true } };
63
+ }
55
64
  /** User-facing failure text, stripped of control characters and home paths. */
56
65
  function safeMessage(value) {
57
66
  const raw = text(value);
@@ -431,7 +440,13 @@ export class DrainCoordinator {
431
440
  if (this.disposeRequested)
432
441
  this.detach();
433
442
  }
434
- if (this.disposeRequested) {
443
+ if (this.disposeRequested && !operation.cancelRequested && !this.barrierBroken && landed(result)) {
444
+ // The executor returned success: the package is on disk. The market being
445
+ // unloaded afterwards does not make that a cancellation (#1151).
446
+ result = markReloaded(result);
447
+ this.finishFromResult(operation, result);
448
+ }
449
+ else if (this.disposeRequested) {
435
450
  result = {
436
451
  status: 503,
437
452
  payload: {
@@ -455,12 +470,12 @@ export class DrainCoordinator {
455
470
  payload: {
456
471
  ok: false,
457
472
  failureCode: 'AGENT_BARRIER_LOST',
458
- error: 'an Agent could not be held at the maintenance boundary; verify the installed files before retrying',
473
+ error: '有会话在操作进行中恢复了活动,文件可能已经改动。先在「已安装」里看看结果,等会话空闲后再试。 / A session became active while the operation ran, so files may have changed. Check Installed for the result, then retry once sessions are idle.',
459
474
  },
460
475
  };
461
476
  this.finish(operation, 'failed', {
462
477
  code: 'AGENT_BARRIER_LOST',
463
- message: 'an Agent could not be held at the maintenance boundary; verify the installed files before retrying',
478
+ message: '有会话在操作进行中恢复了活动,文件可能已经改动。先在「已安装」里看看结果,等会话空闲后再试。 / A session became active while the operation ran, so files may have changed. Check Installed for the result, then retry once sessions are idle.',
464
479
  }, null);
465
480
  }
466
481
  else {
@@ -479,7 +494,7 @@ export class DrainCoordinator {
479
494
  if (this.barrierBroken) {
480
495
  this.finish(operation, 'failed', {
481
496
  code: 'AGENT_BARRIER_LOST',
482
- message: 'an Agent could not be held at the maintenance boundary; the plugin operation was not started',
497
+ message: '有会话恢复了活动,这次没有改任何文件。等会话空闲后再试。 / A session became active; nothing was changed. Retry once sessions are idle.',
483
498
  }, null);
484
499
  return;
485
500
  }
@@ -491,7 +506,7 @@ export class DrainCoordinator {
491
506
  else if (this.barrierBroken) {
492
507
  this.finish(operation, 'failed', {
493
508
  code: 'AGENT_BARRIER_LOST',
494
- message: 'an Agent could not be held at the maintenance boundary; the plugin operation was not started',
509
+ message: '有会话恢复了活动,这次没有改任何文件。等会话空闲后再试。 / A session became active; nothing was changed. Retry once sessions are idle.',
495
510
  }, null);
496
511
  }
497
512
  else {
@@ -544,9 +559,13 @@ export class DrainCoordinator {
544
559
  operation.startedAt = this.now();
545
560
  this.notify(operation);
546
561
  const result = await operation.execute(operation.intent, operation.onPhase);
547
- // The executor can return success after a cancel or unload landed too
548
- // late for its last gate. The Host's state wins: the user asked to stop
549
- // or the market is gone, so this is not reported as a completed change.
562
+ // A cancel wins over a late success: the user asked to stop. An unload
563
+ // does not: a success result means the package command finished and the
564
+ // files are on disk, so it is recorded as done (#1151).
565
+ if (this.disposeRequested && !operation.cancelRequested && !this.barrierBroken && landed(result)) {
566
+ this.finishFromResult(operation, markReloaded(result));
567
+ return;
568
+ }
550
569
  if (this.disposeRequested) {
551
570
  this.finish(operation, 'cancelled', {
552
571
  code: 'MARKET_UNLOADED',
@@ -561,7 +580,7 @@ export class DrainCoordinator {
561
580
  if (this.barrierBroken) {
562
581
  this.finish(operation, 'failed', {
563
582
  code: 'AGENT_BARRIER_LOST',
564
- message: 'an Agent started work while the package operation was running; verify the installed files before retrying',
583
+ message: '有会话在操作进行中恢复了活动,文件可能已经改动。先在「已安装」里看看结果,等会话空闲后再试。 / A session became active while the operation ran, so files may have changed. Check Installed for the result, then retry once sessions are idle.',
565
584
  }, null);
566
585
  return;
567
586
  }
package/lib/dsh-cli.js CHANGED
@@ -479,7 +479,11 @@ export function dshArgv() {
479
479
  // The official bundled CLI inherits the launcher's cwd. Its entry can
480
480
  // live inside app.asar: Electron can read it, but the OS cannot chdir there.
481
481
  // Do not probe that directory through Electron's virtual filesystem.
482
- return { file: nodeExecutable(), args: [...process.execArgv, abs], cwd: desktopCli ? undefined : dirname(abs), viaShell: false };
482
+ // An entry inside an .asar archive carries the same hazard as the desktop
483
+ // CLI above: Electron's fs shim resolves the directory, the OS cannot chdir
484
+ // there, and CreateProcess fails with ENOENT naming an unrelated executable.
485
+ const entryInAsar = /[\\/][^\\/]+\.asar[\\/]/i.test(abs);
486
+ return { file: nodeExecutable(), args: [...process.execArgv, abs], cwd: desktopCli || entryInAsar ? undefined : dirname(abs), viaShell: false };
483
487
  }
484
488
  // Bare `dsh` is a .cmd shim on Windows that only a shell can start (#13).
485
489
  return { file: 'dsh', args: [], cwd: undefined, viaShell: winCmdShim };
package/lib/hot.js CHANGED
@@ -23,12 +23,13 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
23
23
  }
24
24
  return path;
25
25
  };
26
- import { mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
26
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
27
27
  import { createRequire } from 'node:module';
28
28
  import { join } from 'node:path';
29
29
  import { pathToFileURL } from 'node:url';
30
30
  import { asChannel } from './channels.js';
31
31
  import { asRegion, normalizeGithubProxy } from './regions.js';
32
+ import { findDshInstallDir } from './dsh-install.js';
32
33
  import { logEvent } from './log.js';
33
34
  import { bundlePatchTargets, declaredBundlePatchFiles, entryArtifactExists } from './profile.js';
34
35
  import { stateDir, statePath } from './state.js';
@@ -799,7 +800,9 @@ export async function hotMount(ctx, profileDir, packageName) {
799
800
  * in every boot — this is what makes them behave like normal plugins.
800
801
  * @returns names that were mounted.
801
802
  */
802
- export async function mountClientOnlyDeps(ctx, profileDir) {
803
+ export async function mountClientOnlyDeps(ctx, profileDir,
804
+ /** The host's install directory; `undefined` finds it, `null` means "do not look". */
805
+ hostDirectory) {
803
806
  let deps;
804
807
  let bundles;
805
808
  try {
@@ -813,7 +816,7 @@ export async function mountClientOnlyDeps(ctx, profileDir) {
813
816
  }
814
817
  const disabled = readDisabled(profileDir);
815
818
  const userManaged = readUserPatchControls(profileDir);
816
- const hostProvided = bundleLayerTargets(profileDir, bundles);
819
+ const hostProvided = bundleLayerTargets(profileDir, bundles, hostDirectory);
817
820
  const mounted = [];
818
821
  for (const name of deps) {
819
822
  if (hotHandles.has(name) || disabled.has(name))
@@ -856,15 +859,45 @@ export async function mountClientOnlyDeps(ctx, profileDir) {
856
859
  * today's behaviour (shim, possibly duplicated) rather than silently dropping
857
860
  * a client bundle that the bundle layer never mounts.
858
861
  */
859
- export function bundleLayerTargets(profileDir, bundles) {
862
+ export function bundleLayerTargets(profileDir, bundles, hostDirectory) {
860
863
  const targets = new Set();
864
+ // Looked up lazily: a profile with no bundle the host provides never pays.
865
+ let host = hostDirectory;
861
866
  for (const bundle of bundles) {
862
- const dir = join(profileDir, 'node_modules', ...bundle.split('/'));
863
- for (const name of bundlePatchTargets(dir))
867
+ if (host === undefined)
868
+ host = findDshInstallDir();
869
+ for (const name of bundlePatchTargets(bundleDirectory(profileDir, host, bundle)))
864
870
  targets.add(name);
865
871
  }
866
872
  return targets;
867
873
  }
874
+ /**
875
+ * Where the boot reads one bundle from (#1137).
876
+ *
877
+ * The official bundles — `@deepseek-ai/dsh-web-app` and its siblings — ship
878
+ * inside the dsh installation, not in the profile: a plain `dsh web` profile's
879
+ * `node_modules/@deepseek-ai/` holds only the few packages linked into it. The
880
+ * boot (dsh-app-boot's resolveBundleDir) probes Node's search paths from the
881
+ * installation first and the profile second, and so does this; looking only
882
+ * in the profile made every in-box bundle read as empty, which is the one kind
883
+ * of bundle whose rows mount other in-box packages.
884
+ *
885
+ * A host that cannot be read from here (null, or an archive plain Node cannot
886
+ * open) leaves the profile path, which is what this always did.
887
+ */
888
+ function bundleDirectory(profileDir, host, bundle) {
889
+ if (host !== null) {
890
+ try {
891
+ for (const searchPath of createRequire(join(host, 'package.json')).resolve.paths(bundle) ?? []) {
892
+ const candidate = join(searchPath, bundle);
893
+ if (existsSync(join(candidate, 'package.json')))
894
+ return candidate;
895
+ }
896
+ }
897
+ catch { /* an unreadable anchor says nothing: fall back to the profile */ }
898
+ }
899
+ return join(profileDir, 'node_modules', ...bundle.split('/'));
900
+ }
868
901
  /**
869
902
  * Row ids and package names the user's own patch layer (cordis.patch.yml)
870
903
  * already contains. Line-wise scan on purpose: the file may hold structures
package/lib/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
  * dsh-crate host entry: mounts the market's HTTP routes once the profile
3
3
  * composes the webServer and shell services.
4
4
  */
5
+ import z from '@deepseek-ai/schemastery';
5
6
  import { dirname, isAbsolute } from 'node:path';
6
7
  import { createDesktopPluginRuntime, setHostPackageManager } from './dsh-cli.js';
7
8
  import { createOfficialDesktopRuntime } from './official-desktop.js';
@@ -22,6 +23,18 @@ export const name = 'dsh-crate';
22
23
  * (#928). Nothing happens when the journal is empty, which is the normal case.
23
24
  */
24
25
  const PENDING_UPDATE_REPAIR_DELAY_MS = 8_000;
26
+ /** A field the form may edit; newer hosts hand one back as a live reference (#1144). */
27
+ const editable = (schema) => schema.extra('volatile', true);
28
+ const valueOf = (field) => typeof field?.get === 'function' ? field.get() : field;
29
+ /** dsh 0.1.7+ builds its form from `plugin.Config` and writes `simplify(config)` back, so every field the market reads is named here or the first form save deletes it. Each is loose: an older composition still boots, a mistyped value is dropped, and neither editable field takes a default, so "unconfigured" stays distinguishable (#1144, #229). */
30
+ export const Config = z.object({
31
+ profile: z.string().loose(),
32
+ channel: z.string().loose(),
33
+ region: z.string().loose(),
34
+ allowRestart: editable(z.boolean().loose()),
35
+ maxSnapshots: editable(z.number().loose()),
36
+ buildEnv: z.dict(z.any()).loose().extra('default', undefined),
37
+ }).loose();
25
38
  /**
26
39
  * Register the market against the host context.
27
40
  * @param ctx - Host context that may acquire webServer and shell services.
@@ -118,15 +131,18 @@ function hostPackageManagerOf(context) {
118
131
  function agentsLookupOf(ctx) {
119
132
  return () => ctx.get('agents');
120
133
  }
134
+ /** What an all-interfaces listener reports as its bind host; it names no machine. */
135
+ const WILDCARD_BIND_HOSTS = new Set(['0.0.0.0', '::', '[::]']);
121
136
  /**
122
137
  * The deployment's declared authorities, read from the host (#729).
123
138
  *
124
- * DSH's own /api fence accepts loopback OR an authority the operator declared
125
- * (`dsh web --trusted-host <name>`, plus the LAN literals the CLI derives when
126
- * bound to 0.0.0.0). The market's routes are `exact` registrations on the bare
127
- * webServer, and exact matches win over that fence's prefix, so they never
128
- * pass through it — and a loopback-only rule of its own made every mutating
129
- * route 403 on any deployment reached by a name.
139
+ * DSH's own /api fence accepts loopback, the listener's bind IP literal, or an
140
+ * authority the operator declared (`dsh web --trusted-host <name>`). The
141
+ * market's routes are `exact` registrations on the bare webServer, and exact
142
+ * matches win over that fence's prefix, so they never pass through it — and a
143
+ * loopback-only rule of its own made every mutating route 403 on any deployment
144
+ * reached by a name. The source below therefore mirrors the host's fence: the
145
+ * declared `trustedHosts` plus the listener's own bind host from `webServer`.
130
146
  *
131
147
  * The `connection` service is optional: a host without it leaves the fence
132
148
  * exactly as it was, which is the behaviour every release so far has had.
@@ -153,9 +169,29 @@ export function useTrustedHosts(ctx) {
153
169
  warned = true;
154
170
  console.warn('dsh-crate: the host connection service is not available; the origin fence accepts loopback only');
155
171
  }
156
- return Array.isArray(connection?.trustedHosts)
172
+ const hosts = Array.isArray(connection?.trustedHosts)
157
173
  ? connection.trustedHosts.filter((entry) => typeof entry === 'string')
158
174
  : [];
175
+ // The host's own fence accepts the listener's bind IP independently of the
176
+ // declared trustedHosts list, so a deployment reached through its own bind
177
+ // address passed /api yet still 403s here. Mirror that acceptance as a
178
+ // port-less entry, with the same normalization the host applies (the zone
179
+ // id is an interface selector, not address text; a bare IPv6 literal needs
180
+ // brackets to survive the canonical-form parse). The webserver config
181
+ // already rejects anything that is not a concrete, non-wildcard IP literal
182
+ // at load, so the value is safe to trust.
183
+ const bindHost = ctx.get('webServer')?.host;
184
+ // Older hosts bind the all-interfaces literal itself, which no browser
185
+ // sends as a Host and which names no machine in particular: not an
186
+ // authority to trust. Newer ones refuse to load with it.
187
+ if (typeof bindHost === 'string' && bindHost !== '' && !WILDCARD_BIND_HOSTS.has(bindHost)) {
188
+ const zoneAt = bindHost.indexOf('%');
189
+ const address = zoneAt === -1 ? bindHost : bindHost.slice(0, zoneAt);
190
+ const entry = address.includes(':') && !address.startsWith('[') ? `[${address}]` : address;
191
+ if (!hosts.includes(entry))
192
+ hosts.push(entry);
193
+ }
194
+ return hosts;
159
195
  });
160
196
  // The same service carries the host's request gate (#603): its fence plus
161
197
  // its browser login, the check its own API runs. Read per request for the
@@ -266,7 +302,7 @@ export function apply(ctx, config) {
266
302
  },
267
303
  desktopHost: true,
268
304
  allowRestart: false,
269
- maxSnapshots: config?.maxSnapshots,
305
+ maxSnapshots: valueOf(config?.maxSnapshots),
270
306
  // The third construction site, and the one #527's review caught
271
307
  // missing: a `buildEnv` configured in cordis.yml was silently
272
308
  // dropped on the official desktop host — the very host the feature
@@ -319,8 +355,8 @@ export function apply(ctx, config) {
319
355
  // would turn "the operator said nothing" into "the operator said
320
356
  // yes", and restartAllowed() could no longer tell them apart — which
321
357
  // is exactly the distinction supervisor detection needs (#229).
322
- allowRestart: config?.allowRestart,
323
- maxSnapshots: config?.maxSnapshots,
358
+ allowRestart: valueOf(config?.allowRestart),
359
+ maxSnapshots: valueOf(config?.maxSnapshots),
324
360
  // Build-time environment (#336); undefined means "inherit", and the
325
361
  // settings wiring below is what makes it editable at runtime.
326
362
  buildEnv: config?.buildEnv,
@@ -365,7 +401,7 @@ export function apply(ctx, config) {
365
401
  // Relaunching a raw Electron process would bypass Desktop's launcher
366
402
  // lifecycle. The shell remains responsible for restart in this mode.
367
403
  allowRestart: false,
368
- maxSnapshots: config?.maxSnapshots,
404
+ maxSnapshots: valueOf(config?.maxSnapshots),
369
405
  // The operator's pinned build environment applies in Desktop mode
370
406
  // too: Desktop's packaged pnpm still runs plugin build scripts.
371
407
  buildEnv: config?.buildEnv,
package/lib/install.js CHANGED
@@ -1048,7 +1048,7 @@ export function parsePrepareNotAllowed(stdout, stderr) {
1048
1048
  // … git-hosted package \"pkg@1.0.0\" needs to execute build scripts …
1049
1049
  // Unescape before matching, or the ndjson path — the ONLY path in
1050
1050
  // production — silently returns null and the approve banner never shows.
1051
- const text = `${stdout}\n${stderr}`.replace(/\\"/g, '"');
1051
+ const text = unwrapPnpmErrors(`${stdout}\n${stderr}`.replace(/\\"/g, '"'));
1052
1052
  const m = /git-hosted package "([^"]+)" needs to execute build scripts/.exec(text);
1053
1053
  if (m === null)
1054
1054
  return null;
@@ -1057,6 +1057,42 @@ export function parsePrepareNotAllowed(stdout, stderr) {
1057
1057
  const at = raw.lastIndexOf('@');
1058
1058
  return at > 0 ? raw.slice(0, at) : raw;
1059
1059
  }
1060
+ /**
1061
+ * Undo the line wrapping of pnpm 12's boxed error text (#1156).
1062
+ *
1063
+ * pnpm 12 prints a failure as
1064
+ *
1065
+ * Error: ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED
1066
+ *
1067
+ * × adding a new package
1068
+ * ╰─▶ The git-hosted package "x@1.0.0" needs to execute build
1069
+ * scripts but is not in the "allowBuilds" allowlist.
1070
+ * help: …
1071
+ *
1072
+ * and wraps it at about 80 columns — through the middle of a sentence, and
1073
+ * through the middle of a package key at a `/` or `-`. Every sentence this
1074
+ * file matches then has a line break where its single space was, so the
1075
+ * refusal was classified correctly and still yielded no package name, no
1076
+ * key, and therefore no approve-and-retry button. Continuation lines are
1077
+ * indented deeper than the line they continue; join them back, without a
1078
+ * space when the break fell inside a token.
1079
+ *
1080
+ * Output that never wraps this way (pnpm 10/11, ndjson) has no such lines
1081
+ * and comes back unchanged.
1082
+ */
1083
+ export function unwrapPnpmErrors(text) {
1084
+ const out = [];
1085
+ for (const line of text.replace(/\r\n/g, '\n').split('\n')) {
1086
+ const previous = out[out.length - 1];
1087
+ if (previous !== undefined && /^ {2,}\S/.test(previous) && /^ {4,}\S/.test(line)) {
1088
+ out[out.length - 1] = previous + (/[^\s][/-]$/.test(previous) ? '' : ' ') + line.trim();
1089
+ }
1090
+ else {
1091
+ out.push(line);
1092
+ }
1093
+ }
1094
+ return out.join('\n');
1095
+ }
1060
1096
  /**
1061
1097
  * The allowBuilds key pnpm itself printed for a prepare refusal, when it
1062
1098
  * printed one (#698).
@@ -1077,8 +1113,8 @@ export function parsePrepareNotAllowed(stdout, stderr) {
1077
1113
  */
1078
1114
  export function parsePrepareKey(stdout, stderr) {
1079
1115
  // ndjson carries this inside a JSON string: quotes and newlines escaped.
1080
- const text = `${stdout}\n${stderr}`.replace(/\\"/g, '"').replace(/\\n/g, '\n');
1081
- const m = /For example:\s*\n\s*allowBuilds:\s*\n[ \t]+("?)([^\s"]+)\1:\s*true/.exec(text);
1116
+ const text = unwrapPnpmErrors(`${stdout}\n${stderr}`.replace(/\\"/g, '"').replace(/\\n/g, '\n'));
1117
+ const m = /For example:\s*allowBuilds:\s*("?)([^\s"]+)\1:\s*true/.exec(text);
1082
1118
  return m === null ? null : m[2];
1083
1119
  }
1084
1120
  /**
@@ -1118,7 +1154,7 @@ export function allowBuildKeyFromIgnoredBuild(depPath) {
1118
1154
  * path can contain, so the surrounding JSON is not swallowed.
1119
1155
  */
1120
1156
  export function parseIgnoredBuildEntries(stdout, stderr) {
1121
- const m = /Ignored build scripts:?\s*([^\n]+)/i.exec(`${stdout}\n${stderr}`);
1157
+ const m = /Ignored build scripts:?\s*([^\n]+)/i.exec(unwrapPnpmErrors(`${stdout}\n${stderr}`));
1122
1158
  if (m === null)
1123
1159
  return [];
1124
1160
  const found = [];
@@ -241,7 +241,8 @@ async function updateMarketInPlace(spec, name, options, context) {
241
241
  const args = ['add', spec];
242
242
  if (typeof options.registry === 'string' && options.registry !== '')
243
243
  args.push(`--registry=${options.registry}`);
244
- const run = await runHostPnpm(invocation, directory, args);
244
+ context.onOwnChild?.(true);
245
+ const run = await runHostPnpm(invocation, directory, args).finally(() => context.onOwnChild?.(false));
245
246
  const output = `${run.stdout}\n${run.stderr}`.trim();
246
247
  if (run.cancelled) {
247
248
  return { application: 'cancelled', packageResult: { exitCode: run.exitCode, output } };
@@ -384,6 +385,29 @@ async function installOrReinstall(manager, spec, options, context) {
384
385
  throw error;
385
386
  }
386
387
  }
388
+ /**
389
+ * The operation the desktop manager is running, visible to every instance of
390
+ * this runtime in the process (#1151).
391
+ *
392
+ * The host reloads the market while an operation the market started is still
393
+ * inside the manager, so the instance that began it is disposed and a new one
394
+ * is built around it. The new one has no `active` of its own and would call
395
+ * the manager idle: it would start a second operation into the first, and its
396
+ * start-up repair would take the removal in progress for an interrupted one.
397
+ * The slot lives on `globalThis` because a reload may evaluate this module
398
+ * again, which a module-level variable would not survive.
399
+ */
400
+ const OPERATION_SLOT = Symbol.for('dsh-crate.officialDesktop.operation');
401
+ function runningOperation() {
402
+ return globalThis[OPERATION_SLOT];
403
+ }
404
+ function setRunningOperation(operation) {
405
+ const slot = globalThis;
406
+ if (operation === undefined)
407
+ delete slot[OPERATION_SLOT];
408
+ else
409
+ slot[OPERATION_SLOT] = operation;
410
+ }
387
411
  /** Resolve the profile directory without making an invalid name a construction failure. */
388
412
  function safeProfileDirectory(profile, explicit) {
389
413
  if (explicit !== undefined)
@@ -415,13 +439,22 @@ _profileDirectory,
415
439
  packageManager) {
416
440
  let disposed = false;
417
441
  let repairing = false;
442
+ // True only while the self-update overlay runs its own pnpm child: the one
443
+ // operation this instance, and nobody else, has to stop and wait for.
444
+ let ownsChild = false;
418
445
  let active;
419
446
  const directory = safeProfileDirectory(profileName, _profileDirectory);
420
447
  const journal = directory === undefined ? undefined : PendingUpdateJournal.forProfile(directory);
421
448
  const updateContext = directory === undefined || journal === undefined
422
449
  ? undefined
423
- : { profile: profileName, profileDirectory: directory, journal, packageManager };
424
- const busy = () => active !== undefined || repairing;
450
+ : {
451
+ profile: profileName,
452
+ profileDirectory: directory,
453
+ journal,
454
+ packageManager,
455
+ onOwnChild: running => { ownsChild = running; },
456
+ };
457
+ const busy = () => active !== undefined || repairing || runningOperation() !== undefined;
425
458
  const runPlugin = (profile, argv) => {
426
459
  if (disposed)
427
460
  return Promise.resolve(failure('official desktop plugin runtime is disposed', 127));
@@ -429,7 +462,7 @@ packageManager) {
429
462
  return Promise.resolve(failure('refusing to change a different profile', 127));
430
463
  // A repair uses the same manager; overlapping the two would race the
431
464
  // profile's write lock and the route's single-operation rule.
432
- if (active !== undefined || repairing)
465
+ if (busy())
433
466
  return Promise.resolve({ ...failure('another plugin operation is running', 127), busy: true });
434
467
  const manager = managerLookup();
435
468
  if (manager === undefined
@@ -509,6 +542,8 @@ packageManager) {
509
542
  }
510
543
  const current = { requestId, cancelled: false, done: Promise.resolve(failure('not started')) };
511
544
  active = current;
545
+ const flight = { done: current.done };
546
+ setRunningOperation(flight);
512
547
  current.done = operation.then((result) => {
513
548
  // `overridden` is a change the manager KEPT (`changed: true`) whose live
514
549
  // state differs because another layer — a user patch — overrides it.
@@ -560,11 +595,21 @@ packageManager) {
560
595
  progress.cancelling = false;
561
596
  if (active === current)
562
597
  active = undefined;
598
+ if (runningOperation() === flight)
599
+ setRunningOperation(undefined);
563
600
  });
601
+ flight.done = current.done;
564
602
  return current.done;
565
603
  };
566
604
  const repairPendingUpdates = async () => {
567
605
  const empty = { reinstalled: [], finished: [], failed: [], abandoned: [] };
606
+ // An operation a previous instance started is still inside the manager:
607
+ // its journal record is in progress, not interrupted. Let it settle first
608
+ // — it finishes its own record on success, and a failure leaves the
609
+ // record for exactly this repair. The operation is bounded by its own
610
+ // deadline, so this wait is too.
611
+ if (active === undefined)
612
+ await runningOperation()?.done.catch(() => { });
568
613
  if (disposed || repairing || active !== undefined)
569
614
  return empty;
570
615
  const manager = managerLookup();
@@ -607,13 +652,26 @@ packageManager) {
607
652
  acceptsMarketPnpmFlags: false,
608
653
  dispose: async () => {
609
654
  disposed = true;
610
- if (active?.requestId !== undefined) {
655
+ const running = active;
656
+ // An operation inside the host's manager is the host's to finish (#1151).
657
+ // The host reloads the market in the middle of the operation the market
658
+ // started — and its reconciliation waits for this very disposer — so
659
+ // waiting here for the operation, which waits for the reconciliation,
660
+ // is a cycle: the market was already unmounted, the request never
661
+ // answered, the profile lock stayed held. Cancelling would also abort
662
+ // the update the user asked for halfway. Let it run; the next instance
663
+ // sees it through `runningOperation`.
664
+ if (running !== undefined && !ownsChild) {
665
+ void running.done.catch(() => { });
666
+ return;
667
+ }
668
+ if (running?.requestId !== undefined) {
611
669
  const manager = managerLookup();
612
670
  if (manager !== undefined)
613
- void manager.cancelInstall(active.requestId).catch(() => { });
671
+ void manager.cancelInstall(running.requestId).catch(() => { });
614
672
  }
615
673
  cancelHostChild();
616
- await active?.done;
674
+ await running?.done;
617
675
  },
618
676
  };
619
677
  }