dshmarket 1.78.0 → 1.80.0

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/hot.js CHANGED
@@ -507,9 +507,7 @@ export function readMarketState(profileDir) {
507
507
  // this switch is the market's only entry, so "the user turned it off"
508
508
  // must be distinguishable from "nobody has chosen yet" (#846).
509
509
  ...(typeof state.sidebarEntry === 'boolean' ? { sidebarEntry: state.sidebarEntry } : {}),
510
- // Only `false` is a stored answer here: shown is the default, and a
511
- // state file that says anything else reads as "never touched".
512
- ...(state.settingsSection === false ? { settingsSection: false } : {}),
510
+ ...(typeof state.settingsSection === 'boolean' ? { settingsSection: state.settingsSection } : {}),
513
511
  ...(state.pluginsTab === false ? { pluginsTab: false } : {}),
514
512
  buildEnv: buildEnvFromUnknown(state.buildEnv),
515
513
  };
@@ -671,7 +669,7 @@ function writeState(profileDir, state, ownStamps) {
671
669
  ...(typeof sidebarEntry === 'boolean' ? { sidebarEntry } : {}),
672
670
  // Only the OFF is written; `true` means "the default", so re-enabling
673
671
  // clears the field rather than pinning today's default forever (#1015).
674
- ...(settingsSection === false ? { settingsSection: false } : {}),
672
+ ...(typeof settingsSection === 'boolean' ? { settingsSection } : {}),
675
673
  ...(pluginsTab === false ? { pluginsTab: false } : {}),
676
674
  ...(state.region === undefined ? {} : { region: state.region }),
677
675
  ...(state.regionAuto === true ? { regionAuto: true } : {}),
@@ -743,6 +741,24 @@ export function forgetInstalled(profileDir, name) {
743
741
  state.installTimes = trimInstallTimes(map);
744
742
  writeState(profileDir, state, true);
745
743
  }
744
+ /**
745
+ * Forget every hot mount. Called when the market's routes unload.
746
+ *
747
+ * The trees these tables point at hang off the market's own instance, so
748
+ * they go down with it. The tables do not: they are module state, and a
749
+ * module the host did not replace — its file did not change — is still
750
+ * loaded when the next instance starts (src/self-reload.ts). Left as they
751
+ * are, the new instance would believe a plugin is still mounted that its
752
+ * predecessor took down: its shim would never be mounted again, and
753
+ * "switch off" would dispose a handle that is already gone while the plugin,
754
+ * brought back by the host's own composition, kept running.
755
+ */
756
+ export function resetHotState() {
757
+ hotHandles.clear();
758
+ hotTrees.clear();
759
+ hotTreeOf.clear();
760
+ shimNames.clear();
761
+ }
746
762
  /** Package names whose hot-mount trees are still attached and can be removed. */
747
763
  export function listHotMounts() {
748
764
  return [...hotHandles.keys()];
package/lib/routes.js CHANGED
@@ -21,7 +21,7 @@ import { clientPolicy, getPolicy, pinnedVersion } from './policy.js';
21
21
  import { setNpmrcProfileDir } from './npmrc.js';
22
22
  import { BundleError, extractBundle, isInsideOfflineRoot, MAX_BUNDLE_BYTES } from './offline.js';
23
23
  import { settingsNamespaceState } from './settings.js';
24
- import { buildEnvFromUnknown, cleanHotDir, forgetInstalled, hotMount, hotMountFailure, hotUnmount, listHotMounts, listLiveHotMounts, MAX_BLOCKED, MAX_BLOCKED_NAME, MAX_FAVORITES, MAX_NOTE, MAX_UPDATE_EXEMPT, mountClientOnlyDeps, purgeMarketState, readMarketState, recordInstalled, recordUpdated, writeMarketState, } from './hot.js';
24
+ import { buildEnvFromUnknown, cleanHotDir, forgetInstalled, hotMount, hotMountFailure, hotUnmount, listHotMounts, listLiveHotMounts, resetHotState, MAX_BLOCKED, MAX_BLOCKED_NAME, MAX_FAVORITES, MAX_NOTE, MAX_UPDATE_EXEMPT, mountClientOnlyDeps, purgeMarketState, readMarketState, recordInstalled, recordUpdated, writeMarketState, } from './hot.js';
25
25
  import { createGroup, deleteGroup, removeFromGroups, renameGroup, setGroupMembers } from './groups.js';
26
26
  import { dshHostInfo, findDshInstallDir } from './dsh-install.js';
27
27
  import { catalogReleaseManifest, deriveHostCompatibility, DiscoveryManifestIndex, findCompatibleVersion, githubCompatibilityRevision } from './discovery-compatibility.js';
@@ -63,6 +63,7 @@ import { DEFAULT_UPDATE_CHECK_INTERVAL_HOURS, isUpdateCheckIntervalHours } from
63
63
  import { createThemeManager } from './themes.js';
64
64
  import { readJsonBody, readRawBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js';
65
65
  import { resolveDshHome } from './home-paths.js';
66
+ import { asHmr, claimInstance, reloadSelf, selfReloadReply } from './self-reload.js';
66
67
  import { readTelemetryState, sendOpened, setTelemetryEnabled, startHeartbeat } from './telemetry.js';
67
68
  import { clearWebdavSecret, readWebdavSecret, webdavSecretFor, writeWebdavSecret } from './webdav-secret.js';
68
69
  import { detectedDebugger, detectedSupervisor, restartAllowed, scheduleRestart, servingPort, trustedRestartRequest, trustedDownloadRequest, trustedSelfUninstallRequest, selfUninstallReachableFrom, restartReachableFrom } from './restart.js';
@@ -140,6 +141,27 @@ function isGitHubReleaseTarballSpec(spec) {
140
141
  * in frame the first reply always has to ask which one it was.
141
142
  */
142
143
  let cachedVersion = null;
144
+ /**
145
+ * Forget the version read from disk. Called when the routes unload: a module
146
+ * the host did not replace (its file did not change) stays loaded across an
147
+ * in-process reload (src/self-reload.ts), and the instance that comes next
148
+ * must report the package.json that is on disk now, not the one it started
149
+ * beside.
150
+ */
151
+ export function forgetMarketVersion() {
152
+ cachedVersion = null;
153
+ }
154
+ /**
155
+ * True only while this market is asking the host to swap in its own new build.
156
+ *
157
+ * The version a market reports must be the version of the CODE that is
158
+ * running. Any other reason this instance unloads (a settings change makes
159
+ * the host restart the entry) leaves the same code running, so the version
160
+ * read at first use stays true even though a newer package.json is on disk —
161
+ * forgetting it there would report the new version over the old code and
162
+ * hide exactly the mismatch the page needs to see.
163
+ */
164
+ let swappingSelf = false;
143
165
  export function marketVersion() {
144
166
  if (cachedVersion !== null)
145
167
  return cachedVersion;
@@ -618,15 +640,16 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
618
640
  *
619
641
  * The HOST decides which doors exist; this only combines the user's
620
642
  * preferences, because a request handler cannot see the browser's slots.
621
- * `sidebarEntry` defaults off while the two page tabs default on, so
622
- * "every door closed" is expressible — and has to be refused before it
623
- * reaches disk. A market with no entry can only be recovered by editing
643
+ * The Plugins page tab and the sidebar row default on; the settings page
644
+ * entry defaults off (it is the old door, kept for hosts without the other
645
+ * two — the browser shows it there anyway). "Every door closed" is still
646
+ * expressible, and has to be refused before it reaches disk. A market with no entry can only be recovered by editing
624
647
  * state.json or removing the package, which the card must never cause.
625
648
  */
626
649
  const entryDoors = (state = marketState) => ({
627
- settingsSection: state.settingsSection !== false,
650
+ settingsSection: state.settingsSection === true,
628
651
  pluginsTab: state.pluginsTab !== false,
629
- sidebarEntry: state.sidebarEntry === true,
652
+ sidebarEntry: state.sidebarEntry !== false,
630
653
  });
631
654
  const closesEveryDoor = (doors) => !doors.settingsSection && !doors.pluginsTab && !doors.sidebarEntry;
632
655
  /**
@@ -3233,6 +3256,18 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3233
3256
  kind: () => (config.desktopHost === true ? 'desktop' : 'web'),
3234
3257
  region: () => region,
3235
3258
  };
3259
+ /**
3260
+ * In-process reload of the market itself (see src/self-reload.ts).
3261
+ *
3262
+ * Available when the host can replace modules (its HMR service, DSH 0.2.1
3263
+ * and later) and the market is an installed package of this profile — a
3264
+ * development checkout has no newer files on disk to switch to.
3265
+ */
3266
+ const selfPackageName = () => ['dshmarket', 'dsh-market'].find(candidate => readInstalled(config.profile, activeProfileDir)[candidate] !== undefined) ?? null;
3267
+ const hostHmr = () => asHmr(host.get?.('hmr'));
3268
+ const selfReloadAvailable = () => hostHmr() !== undefined && host.get?.('profileContext') !== undefined && selfPackageName() !== null;
3269
+ // Announced once the routes below are up; handlers read it lazily.
3270
+ let instanceClaim;
3236
3271
  const disposers = [
3237
3272
  // The market page was opened. The page says so once per load; the count
3238
3273
  // keeps the first one of each UTC day and ignores the rest. Answered at
@@ -5693,7 +5728,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5693
5728
  // by the user — the card explains a choice it made on their behalf
5694
5729
  // exactly once, so nobody has to wonder why downloads moved.
5695
5730
  regionAuto,
5696
- sidebarEntry: marketState.sidebarEntry === true,
5731
+ sidebarEntry: marketState.sidebarEntry !== false,
5732
+ // Whether DSH Desktop owns this process (the market cannot restart it).
5733
+ desktopHost: config.desktopHost === true,
5697
5734
  restart: restartAllowed(config),
5698
5735
  // Named so the UI can say WHY the button is gone. A blank
5699
5736
  // "no restart button" is the state #229 reported as broken.
@@ -5712,6 +5749,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5712
5749
  // card hides a remove button that could only ever answer 403.
5713
5750
  selfUninstallReachable: selfUninstallReachableFrom(request),
5714
5751
  selfManaged: installed.dshmarket !== undefined || installed['dsh-market'] !== undefined,
5752
+ // Whether POST /dsh-market/reload-self can swap a newer build of the
5753
+ // market in without restarting DSH. The page that has just loaded a
5754
+ // newer client than this server reads it to choose between "reload
5755
+ // the market" and "restart DSH".
5756
+ selfReload: selfReloadAvailable(),
5715
5757
  // Whether the host took the market's settings namespace (#677).
5716
5758
  // `unsupported-by-host` is 0.1.7 and newer, where settings come from
5717
5759
  // a plugin's Config schema and no third-party namespace is served —
@@ -7850,7 +7892,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7850
7892
  handler: async (request, response) => {
7851
7893
  if (request.method === 'GET') {
7852
7894
  sendJson(response, 200, {
7853
- enabled: marketState.sidebarEntry === true,
7895
+ // Shown unless turned off (the default changed from off to on).
7896
+ enabled: marketState.sidebarEntry !== false,
7854
7897
  // Absent means nobody has ever chosen. On a host with no settings
7855
7898
  // page the row is then shown by default, because it is the only
7856
7899
  // way into the market (#846).
@@ -7913,7 +7956,13 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7913
7956
  handler: async (request, response) => {
7914
7957
  if (request.method === 'GET') {
7915
7958
  const doors = entryDoors();
7916
- sendJson(response, 200, { settingsSection: doors.settingsSection, pluginsTab: doors.pluginsTab });
7959
+ sendJson(response, 200, {
7960
+ settingsSection: doors.settingsSection,
7961
+ pluginsTab: doors.pluginsTab,
7962
+ // Unchosen, the browser still shows the settings entry when it is
7963
+ // the host's only door.
7964
+ settingsSectionChosen: typeof marketState.settingsSection === 'boolean',
7965
+ });
7917
7966
  return;
7918
7967
  }
7919
7968
  if (request.method !== 'POST') {
@@ -8174,6 +8223,56 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8174
8223
  }
8175
8224
  },
8176
8225
  }),
8226
+ registerRoute({
8227
+ kind: 'exact',
8228
+ path: '/dsh-market/reload-self',
8229
+ handler: async (request, response) => {
8230
+ if (request.method !== 'POST') {
8231
+ response.writeHead(405, { allow: 'POST' });
8232
+ response.end();
8233
+ return;
8234
+ }
8235
+ if (!sameOrigin(request)) {
8236
+ sendJson(response, 403, { error: 'untrusted origin' });
8237
+ return;
8238
+ }
8239
+ if (restarting) {
8240
+ sendJson(response, 409, { busy: true, error: 'restart already scheduled' });
8241
+ return;
8242
+ }
8243
+ try {
8244
+ // Under the same lock as every other change: a swap ends the instance
8245
+ // that would have finished a running install, so none may be running,
8246
+ // and none may start while it happens. A second request answers 409.
8247
+ const outcome = await withMutationLock(response, 'write', async () => {
8248
+ const name = selfPackageName();
8249
+ swappingSelf = true;
8250
+ try {
8251
+ return await reloadSelf({
8252
+ hmr: hostHmr,
8253
+ runningVersion: marketVersion(),
8254
+ installedVersion: () => name === null ? null : readInstalledVersion(config.profile, name, activeProfileDir),
8255
+ packageDir: () => join(activeProfileDir, 'node_modules', name ?? 'dshmarket'),
8256
+ instanceId: instanceClaim?.id ?? '',
8257
+ log: (level, detail) => logEvent(level, 'reload', detail),
8258
+ });
8259
+ }
8260
+ finally {
8261
+ swappingSelf = false;
8262
+ }
8263
+ });
8264
+ if (outcome === null)
8265
+ return;
8266
+ const reply = selfReloadReply(outcome);
8267
+ sendJson(response, reply.status, reply.body);
8268
+ }
8269
+ catch (error) {
8270
+ const message = error instanceof Error ? error.message : String(error);
8271
+ logEvent('error', 'reload', `route error: ${message}`);
8272
+ sendJson(response, 500, { ok: false, error: message });
8273
+ }
8274
+ },
8275
+ }),
8177
8276
  registerRoute(captureLegacy('/dsh-market/restart', {
8178
8277
  kind: 'exact',
8179
8278
  path: '/dsh-market/restart',
@@ -9525,8 +9624,13 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
9525
9624
  ];
9526
9625
  startCheckoutRepair();
9527
9626
  const stopHeartbeat = startHeartbeat(telemetryOptions);
9627
+ instanceClaim = claimInstance(marketVersion());
9528
9628
  return async () => {
9529
9629
  disposed = true;
9630
+ instanceClaim?.release();
9631
+ if (swappingSelf)
9632
+ forgetMarketVersion();
9633
+ resetHotState();
9530
9634
  stopHeartbeat();
9531
9635
  checkoutRepairRound = undefined;
9532
9636
  if (checkoutRepairTimer !== undefined)
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Reload the market's OWN server half inside the running DSH process.
3
+ *
4
+ * Why this exists: the market updates itself by replacing its files, and the
5
+ * Node module it already imported keeps running. The browser, meanwhile, loads
6
+ * the NEW client bundle, which calls routes the old process does not have (the
7
+ * host answers 405 with an empty body). The only cure used to be a restart,
8
+ * and on DSH Desktop even that is not ours to do (`allowRestart: false`).
9
+ *
10
+ * How: not by re-importing ourselves — Node never re-evaluates a module at a
11
+ * URL it has already loaded, and a cache-busted URL only renews the entry
12
+ * file while every sibling it imports stays the old one. The host already
13
+ * solves exactly this for every plugin: `hmr.reconcileProfile()` (the service
14
+ * `@deepseek-ai/dsh-hmr` publishes as `ctx.hmr`, present from DSH 0.2.1)
15
+ * compares the files of every loaded module with the disk, evicts the ones
16
+ * that changed together with their importers, stops the loader entries that
17
+ * ran them and starts those entries again from the new files. The market is a
18
+ * loader entry like any other, so it is replaced the same way. This module is
19
+ * the orchestration around that one call.
20
+ *
21
+ * The part that is ours, and the reason this is more than one call:
22
+ *
23
+ * - The request that asks for the swap is served by the instance about to be
24
+ * replaced. Its closure outlives its own disposal (the HTTP response object
25
+ * belongs to the web server, not to the plugin), so the SAME request can
26
+ * still report how the swap went.
27
+ * - The host does not restore the old code when the new code cannot start: it
28
+ * evicts the old modules without a backup. So the new build is imported
29
+ * first, from a private copy at a path Node has never seen, and the swap is
30
+ * only asked for when that worked. A build that cannot even load never
31
+ * replaces a market that is running fine.
32
+ * - Which instance is serving is a fact held outside every module — on
33
+ * `globalThis` under a registered symbol — because the module that would
34
+ * hold it is exactly what gets replaced.
35
+ */
36
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
37
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
38
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
39
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
40
+ });
41
+ }
42
+ return path;
43
+ };
44
+ import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from 'node:fs';
45
+ import { basename, dirname, join } from 'node:path';
46
+ import { pathToFileURL } from 'node:url';
47
+ /**
48
+ * The host's HMR service when it can replace modules, otherwise undefined.
49
+ * Checked by shape: DSH 0.2.0 and earlier publish an `hmr` service without
50
+ * `reconcileProfile`, and a call into it would fail after we had decided to
51
+ * go ahead.
52
+ */
53
+ export function asHmr(value) {
54
+ if (value === null || typeof value !== 'object')
55
+ return undefined;
56
+ const candidate = value;
57
+ return typeof candidate.runExclusive === 'function' && typeof candidate.reconcileProfile === 'function'
58
+ ? value
59
+ : undefined;
60
+ }
61
+ // ── Which instance is serving ─────────────────────────────────────────────
62
+ const INSTANCE_KEY = Symbol.for('dsh-market.serving-instance');
63
+ let instanceSequence = 0;
64
+ /**
65
+ * Announce this instance as the one serving. Returns the id to compare
66
+ * against, and a release that only clears the record when it is still this
67
+ * instance's own — a late release from a replaced instance must not erase the
68
+ * record its replacement has already written.
69
+ */
70
+ export function claimInstance(version) {
71
+ instanceSequence += 1;
72
+ const id = `${String(process.pid)}-${String(Date.now())}-${String(instanceSequence)}-${Math.random().toString(16).slice(2, 8)}`;
73
+ const holder = globalThis;
74
+ holder[INSTANCE_KEY] = { id, version };
75
+ return {
76
+ id,
77
+ release: () => {
78
+ if (holder[INSTANCE_KEY]?.id === id)
79
+ delete holder[INSTANCE_KEY];
80
+ },
81
+ };
82
+ }
83
+ /** The instance serving right now, or undefined while none is. */
84
+ export function currentInstance() {
85
+ return globalThis[INSTANCE_KEY];
86
+ }
87
+ let preflightSequence = 0;
88
+ /**
89
+ * Whether the package now on disk can be loaded at all.
90
+ *
91
+ * Imports a private copy of its `lib/` from a path nobody has imported, so
92
+ * the whole module graph is evaluated fresh and any failure — a syntax error,
93
+ * a dependency that is missing, a top-level throw — surfaces here, while the
94
+ * running market is still untouched. The copy sits NEXT TO the package so
95
+ * bare imports resolve through the same `node_modules` chain as the real one,
96
+ * and is deleted again afterwards; the host forgets files that disappeared.
97
+ *
98
+ * What it cannot see: a build that loads fine and then fails inside `apply`.
99
+ * That is only learnable by running it.
100
+ *
101
+ * `checked: false` means the check could not be run (the directory is not
102
+ * writable); the caller proceeds, because refusing every reload on a
103
+ * read-only profile would make the feature useless there.
104
+ */
105
+ export async function preflightBuild(packageDir) {
106
+ let real;
107
+ let main;
108
+ try {
109
+ real = realpathSync(packageDir);
110
+ const manifest = JSON.parse(readFileSync(join(real, 'package.json'), 'utf8'));
111
+ main = typeof manifest.main === 'string' ? manifest.main : 'index.js';
112
+ }
113
+ catch (error) {
114
+ return { ok: false, detail: `the installed package cannot be read — ${messageOf(error)}` };
115
+ }
116
+ if (!existsSync(join(real, main)))
117
+ return { ok: false, detail: `the entry file ${main} is missing` };
118
+ preflightSequence += 1;
119
+ const copy = join(dirname(real), `.dsh-market-reload-${String(process.pid)}-${String(preflightSequence)}`);
120
+ try {
121
+ mkdirSync(copy, { recursive: true });
122
+ cpSync(join(real, 'package.json'), join(copy, 'package.json'));
123
+ cpSync(join(real, dirname(main)), join(copy, dirname(main)), {
124
+ recursive: true,
125
+ // Declarations are not loaded and a second copy of them is dead weight.
126
+ filter: source => {
127
+ const base = basename(source);
128
+ return base !== 'types' && base !== 'node_modules' && !base.endsWith('.d.ts');
129
+ },
130
+ });
131
+ }
132
+ catch {
133
+ rmSync(copy, { recursive: true, force: true });
134
+ return { ok: true, checked: false };
135
+ }
136
+ try {
137
+ const loaded = await import(__rewriteRelativeImportExtension(/* @vite-ignore */ pathToFileURL(join(copy, main)).href));
138
+ if (typeof loaded.apply !== 'function')
139
+ return { ok: false, detail: 'the new build does not export a plugin entry (apply)' };
140
+ return { ok: true, checked: true };
141
+ }
142
+ catch (error) {
143
+ return { ok: false, detail: messageOf(error) };
144
+ }
145
+ finally {
146
+ rmSync(copy, { recursive: true, force: true });
147
+ }
148
+ }
149
+ function messageOf(error) {
150
+ const text = error instanceof Error ? error.message : String(error);
151
+ // The copy's own path means nothing to the reader; the file name does.
152
+ return text.replace(/\.dsh-market-reload-\d+-\d+/g, 'the new build').slice(0, 400);
153
+ }
154
+ const DEFAULT_QUEUE_WAIT_MS = 60_000;
155
+ const DEFAULT_SETTLE_MS = 5_000;
156
+ const sleep = (ms) => new Promise(resolve => { setTimeout(resolve, ms); });
157
+ /**
158
+ * Ask the host to replace this market with the version on disk.
159
+ *
160
+ * The caller has already refused when an operation is running: a swap ends
161
+ * the instance that would have finished it. Nothing here writes a file.
162
+ */
163
+ export async function reloadSelf(deps) {
164
+ const log = deps.log ?? (() => { });
165
+ const serving = deps.serving ?? currentInstance;
166
+ const hmr = deps.hmr();
167
+ if (hmr === undefined)
168
+ return { state: 'unsupported', reason: 'no-hmr' };
169
+ const target = deps.installedVersion();
170
+ if (target === null)
171
+ return { state: 'unsupported', reason: 'not-installed' };
172
+ if (target === deps.runningVersion)
173
+ return { state: 'current', version: target };
174
+ const verdict = await (deps.preflight ?? preflightBuild)(deps.packageDir());
175
+ if (!verdict.ok) {
176
+ log('warn', `reload to ${target} refused, the new build does not load: ${verdict.detail}`);
177
+ return { state: 'refused', detail: verdict.detail };
178
+ }
179
+ if (!verdict.checked)
180
+ log('warn', `reload to ${target}: the new build could not be test-loaded first`);
181
+ log('info', `reloading ${deps.runningVersion} -> ${target}`);
182
+ const queueWaitMs = deps.queueWaitMs ?? DEFAULT_QUEUE_WAIT_MS;
183
+ const swap = hmr.runExclusive(() => hmr.reconcileProfile());
184
+ // The swap itself is never abandoned: it was asked for, and running it a
185
+ // little late is what the user wants. Only the WAITING for it has a limit.
186
+ let timer;
187
+ const waited = await Promise.race([
188
+ swap.then(report => ({ report }), (error) => ({ error })),
189
+ new Promise(resolve => { timer = setTimeout(() => { resolve('queued'); }, queueWaitMs); }),
190
+ ]).finally(() => { clearTimeout(timer); });
191
+ if (waited === 'queued') {
192
+ void swap.catch((error) => { log('warn', `queued reload failed: ${messageOf(error)}`); });
193
+ return { state: 'queued' };
194
+ }
195
+ if ('error' in waited) {
196
+ const detail = messageOf(waited.error);
197
+ const stillOurs = serving()?.id === deps.instanceId;
198
+ log('warn', `reload to ${target} failed${stillOurs ? ' (the running market was not touched)' : ''}: ${detail}`);
199
+ return stillOurs
200
+ ? { state: 'restart-needed', detail }
201
+ : { state: 'failed', detail, serving: serving() !== undefined };
202
+ }
203
+ // The host says it is done. Believe the instance record, not the report: the
204
+ // new instance announces itself when its routes are up, which is the fact
205
+ // that matters.
206
+ const deadline = Date.now() + (deps.settleMs ?? DEFAULT_SETTLE_MS);
207
+ for (;;) {
208
+ const now = serving();
209
+ if (now !== undefined && now.id !== deps.instanceId) {
210
+ log('info', `reloaded to ${now.version}`);
211
+ return { state: 'reloaded', from: deps.runningVersion, to: now.version };
212
+ }
213
+ if (Date.now() >= deadline)
214
+ break;
215
+ await sleep(100);
216
+ }
217
+ const now = serving();
218
+ if (now?.id === deps.instanceId) {
219
+ // Nothing was replaced: the host could not compare or evict the modules
220
+ // (a loader without access to Node's module cache, a host-owned module).
221
+ const why = waited.report.restartReason !== undefined
222
+ ? `the host could not replace modules (${waited.report.restartReason})`
223
+ : waited.report.pending.length > 0
224
+ ? `the host keeps ${String(waited.report.pending.length)} changed module(s) until a restart (${waited.report.pending[0].reason})`
225
+ : 'the host reported done but the old code is still running';
226
+ log('warn', `reload to ${target}: ${why}`);
227
+ return { state: 'restart-needed', detail: why };
228
+ }
229
+ const detail = 'the new version did not start serving';
230
+ log('warn', `reload to ${target}: ${detail}`);
231
+ return { state: 'failed', detail, serving: false };
232
+ }
233
+ /**
234
+ * The HTTP answer for an outcome. Every failure says what happened, why and
235
+ * what to do now, in the project's two-language style; the state code is for
236
+ * the page, which decides what to offer next.
237
+ */
238
+ export function selfReloadReply(outcome) {
239
+ switch (outcome.state) {
240
+ case 'reloaded':
241
+ return { status: 200, body: { ok: true, outcome: 'reloaded', from: outcome.from, to: outcome.to } };
242
+ case 'current':
243
+ return { status: 200, body: { ok: true, outcome: 'current', version: outcome.version } };
244
+ case 'queued':
245
+ return {
246
+ status: 202,
247
+ body: {
248
+ ok: true,
249
+ outcome: 'queued',
250
+ message: 'DSH 正在处理另一项变更,市场会在它结束后自动换成新版。 / DSH is busy with another change. The market will switch to the new version when it finishes.',
251
+ },
252
+ };
253
+ case 'unsupported':
254
+ return {
255
+ status: 501,
256
+ body: {
257
+ ok: false,
258
+ outcome: 'unsupported',
259
+ error: outcome.reason === 'no-hmr'
260
+ ? '这个 DSH 版本不能原地换上新版市场。重启 DSH 就会用上新版。 / This DSH version cannot switch to the new market in place. Restart DSH to use it.'
261
+ : '市场不是作为插件装在这里的,没有新版文件可换。要用磁盘上的文件,请重启 DSH。 / The market is not installed as a plugin here, so there is no new version to switch to. Restart DSH to run what is on disk.',
262
+ },
263
+ };
264
+ case 'refused':
265
+ return {
266
+ status: 422,
267
+ body: {
268
+ ok: false,
269
+ outcome: 'refused',
270
+ detail: outcome.detail,
271
+ error: '新版本没能加载,已保留正在运行的版本,它照常可用。请再更新一次;重启 DSH 能看到具体原因。 / The new version could not load, so the running one was kept and still works. Update again, or restart DSH to see why.',
272
+ },
273
+ };
274
+ case 'restart-needed':
275
+ return {
276
+ status: 502,
277
+ body: {
278
+ ok: false,
279
+ outcome: 'restart-needed',
280
+ detail: outcome.detail,
281
+ error: 'DSH 这次没能换上新版,当前仍是旧版,功能照常。重启 DSH 就会用上新版。 / DSH could not switch to the new version this time. The old one keeps working. Restart DSH to use the new one.',
282
+ },
283
+ };
284
+ case 'failed':
285
+ return {
286
+ status: 502,
287
+ body: {
288
+ ok: false,
289
+ outcome: 'failed',
290
+ serving: outcome.serving,
291
+ detail: outcome.detail,
292
+ error: '切换到新版时出了问题,市场暂时不可用。重启 DSH 即可恢复。 / Switching to the new version went wrong and the market is unavailable. Restart DSH to recover.',
293
+ },
294
+ };
295
+ }
296
+ }
@@ -250,11 +250,10 @@ export interface MarketState {
250
250
  /**
251
251
  * Whether the market still lists its own page in Settings (#1015).
252
252
  *
253
- * Absent means shown. Only an explicit `false` is stored, unlike
254
- * `sidebarEntry`: this entry has always been on, and every host before
255
- * 0.2.1 offers it as the only door, so an absent field is the ordinary
256
- * case rather than an unanswered question. Turning it back on clears the
257
- * field so a later default change still reaches users who never touched it.
253
+ * Absent means "not chosen": hidden wherever the Plugins page tab or the
254
+ * sidebar row is a way in, shown where it is the only one (a host before
255
+ * 0.2.1). Both answers are stored, like `sidebarEntry`, so turning it on
256
+ * keeps it on.
258
257
  */
259
258
  settingsSection?: boolean;
260
259
  /**
@@ -430,6 +429,19 @@ export declare function recordInstalled(profileDir: string, names: readonly stri
430
429
  export declare function recordUpdated(profileDir: string, names: readonly string[], at?: Date): void;
431
430
  /** The package is gone: its stamps must not outlive it. */
432
431
  export declare function forgetInstalled(profileDir: string, name: string): void;
432
+ /**
433
+ * Forget every hot mount. Called when the market's routes unload.
434
+ *
435
+ * The trees these tables point at hang off the market's own instance, so
436
+ * they go down with it. The tables do not: they are module state, and a
437
+ * module the host did not replace — its file did not change — is still
438
+ * loaded when the next instance starts (src/self-reload.ts). Left as they
439
+ * are, the new instance would believe a plugin is still mounted that its
440
+ * predecessor took down: its shim would never be mounted again, and
441
+ * "switch off" would dispose a handle that is already gone while the plugin,
442
+ * brought back by the host's own composition, kept running.
443
+ */
444
+ export declare function resetHotState(): void;
433
445
  /** Package names whose hot-mount trees are still attached and can be removed. */
434
446
  export declare function listHotMounts(): string[];
435
447
  /** Report a failed child only when it belongs to this package's hot-mount tree. */
@@ -33,6 +33,8 @@ export interface MarketHost {
33
33
  dispose(): Promise<unknown> | void;
34
34
  };
35
35
  on?(event: string, callback: (payload: unknown) => void): () => void;
36
+ /** Service lookup; the host context has it, test doubles may not. */
37
+ get?(name: string): unknown;
36
38
  logger?: {
37
39
  info?(message: string): void;
38
40
  warn(message: string): void;
@@ -123,6 +125,14 @@ export interface MarketConfig {
123
125
  launcherNow: () => string;
124
126
  };
125
127
  }
128
+ /**
129
+ * Forget the version read from disk. Called when the routes unload: a module
130
+ * the host did not replace (its file did not change) stays loaded across an
131
+ * in-process reload (src/self-reload.ts), and the instance that comes next
132
+ * must report the package.json that is on disk now, not the one it started
133
+ * beside.
134
+ */
135
+ export declare function forgetMarketVersion(): void;
126
136
  export declare function marketVersion(): string;
127
137
  /**
128
138
  * Register the market's HTTP routes.