dsh-crate 0.5.3 → 0.5.4

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.
Files changed (40) hide show
  1. package/client/client.js +2060 -459
  2. package/lib/body-progress.js +4 -3
  3. package/lib/changelog.js +15 -2
  4. package/lib/discovery-cache.js +210 -0
  5. package/lib/discovery-compatibility.js +91 -93
  6. package/lib/dsh-cli.js +36 -6
  7. package/lib/github-install-target.js +53 -0
  8. package/lib/hot.js +361 -27
  9. package/lib/index.js +6 -5
  10. package/lib/install.js +37 -0
  11. package/lib/patch.js +116 -72
  12. package/lib/pending-rows.js +3 -4
  13. package/lib/pnpm-compat.js +79 -1
  14. package/lib/proc-text.js +16 -1
  15. package/lib/recovery.js +2 -1
  16. package/lib/registry.js +24 -16
  17. package/lib/release-candidates.js +4 -0
  18. package/lib/routes.js +390 -131
  19. package/lib/themes.js +24 -8
  20. package/lib/types/body-progress.d.ts +2 -1
  21. package/lib/types/changelog.d.ts +10 -1
  22. package/lib/types/discovery-cache.d.ts +38 -0
  23. package/lib/types/discovery-compatibility.d.ts +16 -12
  24. package/lib/types/dsh-cli.d.ts +19 -2
  25. package/lib/types/github-install-target.d.ts +11 -0
  26. package/lib/types/hot.d.ts +87 -5
  27. package/lib/types/install.d.ts +19 -0
  28. package/lib/types/patch.d.ts +6 -2
  29. package/lib/types/registry.d.ts +9 -8
  30. package/lib/types/release-candidates.d.ts +2 -0
  31. package/lib/types/routes.d.ts +2 -2
  32. package/lib/types/themes.d.ts +7 -1
  33. package/lib/types/update-notification-settings.d.ts +5 -0
  34. package/lib/types/update-notifications.d.ts +51 -0
  35. package/lib/types/updates.d.ts +5 -1
  36. package/lib/update-notification-settings.js +6 -0
  37. package/lib/update-notifications.js +166 -0
  38. package/lib/updates.js +41 -11
  39. package/lib/verify.js +5 -2
  40. package/package.json +1 -1
package/lib/routes.js CHANGED
@@ -7,6 +7,7 @@
7
7
  * Security: the install route executes a shell command, so it accepts only
8
8
  * same-origin POSTs and only sources present in the curated registry.
9
9
  */
10
+ import { createHash } from 'node:crypto';
10
11
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
11
12
  import { dirname, join } from 'node:path';
12
13
  import { Readable } from 'node:stream';
@@ -15,10 +16,10 @@ import { packageFileFromRegistry } from './catalog-npm.js';
15
16
  import { statePath } from './state.js';
16
17
  import { forgetCatalog, loadRegistry, pluginCategories } from './registry.js';
17
18
  import { settingsNamespaceState } from './settings.js';
18
- import { buildEnvFromUnknown, cleanHotDir, hotMount, hotUnmount, listHotMounts, MAX_BLOCKED, MAX_BLOCKED_NAME, MAX_FAVORITES, MAX_NOTE, MAX_UPDATE_EXEMPT, mountClientOnlyDeps, purgeMarketState, readMarketState, writeMarketState, } from './hot.js';
19
+ 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';
19
20
  import { createGroup, deleteGroup, removeFromGroups, renameGroup, setGroupMembers } from './groups.js';
20
21
  import { dshHostInfo, findDshInstallDir } from './dsh-install.js';
21
- import { catalogReleaseManifest, deriveHostCompatibility, DiscoveryManifestIndex, findCompatibleVersion } from './discovery-compatibility.js';
22
+ import { catalogReleaseManifest, deriveHostCompatibility, DiscoveryManifestIndex, findCompatibleVersion, githubCompatibilityRevision } from './discovery-compatibility.js';
22
23
  import { configurePersistentLog, exportLogs, logEvent, readPersistentLog } from './log.js';
23
24
  import { marketFetch } from './net.js';
24
25
  import { catalogReleaseSourceOf, publishedReleaseUpdate } from './release-updates.js';
@@ -39,15 +40,18 @@ import { createProfileSnapshot, DEFAULT_MAX_SNAPSHOTS, deleteSnapshot, listSnaps
39
40
  import { readHostRecoveryView, restoreHostRecoveryBackup } from './host-recovery.js';
40
41
  import { trialValidate } from './trial.js';
41
42
  import { catalogRepoKey, findCatalogEntryForLocal, findInstalledAlias, gitCommitOfTarget, githubCommitOfTarget, githubTargetAtCommit, gitAllowBuildsKey, gitRefOfTarget, gitTargetAtCommit, gitUpdateTarget, hostedRepoKey, lookupRepoFromUrl, pinnedAllowBuildsKeys, installTargetFor, isGenerationLink, isLocalSpec, NPM_NAME_RE, parseSourceUrl, repoOfTarget, restoreBlockedByWorkspace, restoreTargetForLocal, sourceFallbackFor, workspaceProtocolDeps } from './sources.js';
42
- import { failureDetail, groupConflictsByOwner, installApplied, isHostPortCollision, isStaleUpdate, parseIgnoredBuildEntries, parseIgnoredBuilds, parsePrepareKey, parsePrepareNotAllowed, pnpmBlockedByOpenFiles, pnpmNeverStarted, pnpmRefusedYoungRelease, RELEASE_AGE_OVERRIDE, removeDanglingHostBridge, retargetCollections, updateApplied, validateAddedPlugins, withHoistRecovery } from './install.js';
43
+ import { failureDetail, groupConflictsByOwner, installApplied, isHostPortCollision, isStaleUpdate, parseIgnoredBuildEntries, parseIgnoredBuilds, parsePrepareKey, parsePrepareNotAllowed, pnpmBlockedByOpenFiles, pnpmNeverStarted, pnpmRefusedYoungRelease, RELEASE_AGE_OVERRIDE, removeDanglingHostBridge, removeLeftoverProfileLink, retargetCollections, updateApplied, validateAddedPlugins, withHoistRecovery } from './install.js';
43
44
  import { classifyPnpmFailure } from './pnpm-compat.js';
44
45
  import { asChannel, CHANNELS, DIST_TAG, resolveChannel } from './channels.js';
45
46
  import { asRegion, githubProxyManaged, normalizeGithubProxy, REGIONS, routesFor, setActiveRegion, setCustomGithubProxy, } from './regions.js';
46
47
  import { resolveRegion } from './region-probe.js';
47
48
  import { acceleratedTarget, resolveHeadCommit } from './accelerate.js';
49
+ import { mismatchedWorkspaceRoot } from './github-install-target.js';
48
50
  import { sourceWebUrl, updateNotesFor } from './changelog.js';
49
51
  import { checkUpdates, isUpdatablePlugin, compareVersions, fetchNpmLatest, invalidateUpdates, readVersionMaturity, resolveDesktopMatureUpdate, resolveGitRemoteHead, isUpgrade, latestPublishedRecently, setUpdateRegistry, versionOnChannel } from './updates.js';
50
- import { isStableReleaseVersion } from './release-candidates.js';
52
+ import { isExactReleaseVersion, isStableReleaseVersion } from './release-candidates.js';
53
+ import { createUpdateNotificationMonitor } from './update-notifications.js';
54
+ import { DEFAULT_UPDATE_CHECK_INTERVAL_HOURS, isUpdateCheckIntervalHours } from './update-notification-settings.js';
51
55
  import { createThemeManager } from './themes.js';
52
56
  import { readJsonBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js';
53
57
  import { resolveDshHome } from './home-paths.js';
@@ -58,6 +62,42 @@ import { createProfileBackup, downloadWebdav, MAX_BACKUP_BYTES, mergeRestoreMani
58
62
  import { createGist, fitsGistLimit, GistError, gistErrorCode, parseGistId, readGist, resolveGistTokenSource, updateGist, verifyGistToken, } from './gist.js';
59
63
  import { MAX_UPDATE_OPERATIONS_V1, UpdateOperationStoreV1, UPDATE_API_V1_SCHEMA } from './update-api-v1.js';
60
64
  import { declaredPredecessors, findCatalogRename, findGitToNpmMigration, findNpmTargetEntry, isRegistryRangeSpec, sameLoaderRows } from './source-migration.js';
65
+ const DISCOVERY_RETRY_MS = 30_000;
66
+ /** These revisions describe the server's catalog, independently of what its source includes. */
67
+ const discoveryCatalogs = new WeakMap();
68
+ function discoveryCatalog(registry) {
69
+ const previous = discoveryCatalogs.get(registry);
70
+ if (previous !== undefined)
71
+ return previous;
72
+ const revisions = new Map();
73
+ const plugins = registry.plugins.map((entry) => {
74
+ if ((entry.npm == null || entry.npm === '') && typeof entry.url === 'string' && parseSourceUrl(entry.url) !== null) {
75
+ const revision = githubCompatibilityRevision(entry);
76
+ revisions.set(entry.url, { entry, revision });
77
+ return { ...entry, compatibilityRevision: revision };
78
+ }
79
+ if (!Object.hasOwn(entry, 'compatibilityRevision'))
80
+ return entry;
81
+ const { compatibilityRevision: _sourceRevision, ...plugin } = entry;
82
+ return plugin;
83
+ });
84
+ const snapshot = { revisions, response: { ...registry, plugins } };
85
+ discoveryCatalogs.set(registry, snapshot);
86
+ return snapshot;
87
+ }
88
+ function discoveryHints(value, requested, validValue) {
89
+ if (value === undefined)
90
+ return new Map();
91
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
92
+ return null;
93
+ const hints = new Map();
94
+ for (const [key, hint] of Object.entries(value)) {
95
+ if (!requested.has(key) || !validValue(hint))
96
+ return null;
97
+ hints.set(key, hint);
98
+ }
99
+ return hints;
100
+ }
61
101
  /**
62
102
  * Recognize the documented GitHub Release-download target shape. This does
63
103
  * not authorize a new URL: install trust remains catalog-bound in sources.ts,
@@ -355,7 +395,7 @@ function pnpmFailureMessage(result, profileDirectory) {
355
395
  * Register the market's HTTP routes.
356
396
  * @param host - Acquired webServer + shell services.
357
397
  * @param config - Validated market configuration.
358
- * @returns Disposer removing every registered route.
398
+ * @returns Disposer removing every registered route and draining queued cache writes.
359
399
  */
360
400
  export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, hostActivation) {
361
401
  let disposed = false;
@@ -648,6 +688,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
648
688
  // Same list as blocked: a name written here must survive the next
649
689
  // writer that saves `marketState` whole (#435, #728).
650
690
  marketState.updateExempt = fresh.updateExempt;
691
+ marketState.backgroundUpdateChecks = fresh.backgroundUpdateChecks;
692
+ marketState.backgroundUpdateIntervalHours = fresh.backgroundUpdateIntervalHours;
693
+ // Snapshot restore replaces the persisted choices, so its live scheduler
694
+ // must follow too. An older snapshot has neither choice: off, six hours.
695
+ updateNotifications.setEnabled(fresh.backgroundUpdateChecks === true);
696
+ updateNotifications.setIntervalHours(fresh.backgroundUpdateIntervalHours ?? DEFAULT_UPDATE_CHECK_INTERVAL_HOURS);
651
697
  marketState.githubProxy = fresh.githubProxy;
652
698
  // A restore or an external writer can change these two too; a stale copy
653
699
  // here would put the old answer back on the next whole-state save (#435).
@@ -692,7 +738,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
692
738
  * dropped from the market's disable list.
693
739
  */
694
740
  function followOutsideEnable(name) {
695
- const patch = readUserPatchState(userPatchPath);
741
+ const patch = readUserPatchState(userPatchPath, rowId => composedRowName(host, rowId));
696
742
  const flags = packagePatchFlags(host, activeProfileDir, [name], patch);
697
743
  if (!flags.forced.includes(name) || flags.disabled.includes(name))
698
744
  return false;
@@ -965,6 +1011,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
965
1011
  if (enabled) {
966
1012
  if (listHotMounts().includes(name)) {
967
1013
  ok = true;
1014
+ reason = hotMountFailure(name, dir) ?? undefined;
968
1015
  }
969
1016
  else if (carrierRowIds(dir, name).length > 0) {
970
1017
  // A carrier replaces something: its patch disables stock rows and its
@@ -1004,7 +1051,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1004
1051
  // durable layers half-written: the stack entry re-added, the rows
1005
1052
  // it owns still disabled, and both the stock UI and the plugin's
1006
1053
  // replacement off at the next boot (#1010).
1007
- ok = result.ok || result.deferred === true;
1054
+ ok = result.ok || result.deferred === true || result.retained === true;
1008
1055
  reason = result.reason ?? undefined;
1009
1056
  // Deliberately NOT clearing replacedWhileLive here (#685). This used
1010
1057
  // to say "a mount that succeeded imported the module as it is on
@@ -1056,10 +1103,20 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1056
1103
  * every time), and a group "off" wrote no patch row — the official page and
1057
1104
  * the market disagreed again, one control over (@snmtg1008, #696).
1058
1105
  *
1059
- * @param liveOk - whether the live switch succeeded; a failed ENABLE writes
1106
+ * @param switchLive - perform the runtime switch; a failed ENABLE writes
1060
1107
  * neither layer (#575).
1061
1108
  */
1062
- async function switchPluginLayers(name, enabled, liveOk, liveReason) {
1109
+ async function switchPluginLayers(name, enabled, switchLive = () => setPluginEnabled(name, enabled)) {
1110
+ const packageDir = join(activeProfileDir, 'node_modules', name);
1111
+ // Capture module identity before switching the entry off.
1112
+ const namedRows = new Set();
1113
+ if (!enabled) {
1114
+ for (const id of shippedInsertedRowIds(packageDir)) {
1115
+ if (composedRowName(host, id) === name)
1116
+ namedRows.add(id);
1117
+ }
1118
+ }
1119
+ const { ok: liveOk, reason: liveReason } = await switchLive();
1063
1120
  let ok = liveOk;
1064
1121
  let reason = liveReason;
1065
1122
  // Durable patch-layer write (port of dsh-plugin-hub): the package's
@@ -1076,12 +1133,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1076
1133
  // side effect of a bug fix. Skipped only while something else is left to
1077
1134
  // flip: a package whose rows are ALL opt-in rows still has to be
1078
1135
  // switchable.
1079
- const optOutRows = new Set(bundleOptOutRowIds(join(activeProfileDir, 'node_modules', name)));
1136
+ const optOutRows = new Set(bundleOptOutRowIds(packageDir));
1080
1137
  // Rows the bundle decides itself, by expression (`disabled: !!js …`),
1081
1138
  // are a third shape next to opt-in rows: the market can neither read
1082
1139
  // nor overrule the condition, so enabling the package must leave them
1083
1140
  // exactly as the bundle ships them (#1043).
1084
- const expressionRows = new Set(bundleExpressionRowIds(join(activeProfileDir, 'node_modules', name)));
1141
+ const expressionRows = new Set(bundleExpressionRowIds(packageDir));
1085
1142
  const decided = patchRows.filter(rowId => !optOutRows.has(rowId));
1086
1143
  /** Rows that can carry a USER decision about this package — see above. */
1087
1144
  const userRows = decided.length > 0 ? decided : patchRows;
@@ -1164,7 +1221,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1164
1221
  // The name the loader composed for a row, for the rows whose user-layer
1165
1222
  // entry carries one of its own: the host skips an entry whose `name` is
1166
1223
  // not this one, so its flag is not a decision about the row (#1113).
1167
- const expectedNameFor = (rowId) => composedRowName(host, rowId);
1224
+ const expectedNameFor = (rowId) => namedRows.has(rowId) ? name : composedRowName(host, rowId);
1168
1225
  /** A user-layer flag counts only when the row it names is this entry. */
1169
1226
  const rowIsOurs = (rowId) => prePatch !== null && rowFlagApplies(prePatch, rowId, expectedNameFor(rowId));
1170
1227
  if (patchRows.length > 0 && patchGate && prePatch !== null) {
@@ -1192,11 +1249,15 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1192
1249
  // on that #876/#1043 say must never be forced on.
1193
1250
  const cleanOnly = optOutRows.has(rowId) || expressionRows.has(rowId);
1194
1251
  const expectedName = expectedNameFor(rowId);
1252
+ // DSH drops a simple id/disabled override when enabling would restore
1253
+ // the bundle default. An exact module name keeps the user's enable
1254
+ // in the shared patch layer for followOutsideEnable (#1196).
1255
+ const recordModuleName = stackToggle && !isCarrier && !cleanOnly && namedRows.has(rowId);
1195
1256
  const result = enabled
1196
- ? await enableRow(userPatchPath, rowId, { cleanOnly, expectedName })
1197
- : await disableRow(userPatchPath, rowId, { expectedName });
1257
+ ? await enableRow(userPatchPath, rowId, { cleanOnly, expectedName, packageName: name })
1258
+ : await disableRow(userPatchPath, rowId, { expectedName, recordModuleName, packageName: name });
1198
1259
  if (result.ok) {
1199
- flipped.push(rowId);
1260
+ flipped.push({ rowId, removedMarketName: result.removedMarketName });
1200
1261
  continue;
1201
1262
  }
1202
1263
  patchWrite = result;
@@ -1213,21 +1274,23 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1213
1274
  // disable direction keeps what it got, because a row the patch
1214
1275
  // layer refuses to flip does not make the plugin live again.
1215
1276
  if (enabled) {
1216
- for (const rowId of flipped) {
1277
+ for (const { rowId, removedMarketName } of flipped) {
1217
1278
  // A row that was disabled gets its block back; a row that was
1218
1279
  // not loses the block this enable added. Leaving a
1219
1280
  // `disabled: false` behind would force-enable it in the
1220
1281
  // user's own patch layer — the same disagreement this route
1221
1282
  // exists to end, one row smaller.
1222
- if (prePatch !== null && rowIsOurs(rowId) && prePatch.disables.includes(rowId)) {
1223
- const back = await disableRow(userPatchPath, rowId, { expectedName: expectedNameFor(rowId) });
1283
+ if (removedMarketName !== undefined || (rowIsOurs(rowId) && prePatch.disables.includes(rowId))) {
1284
+ const expectedName = removedMarketName ?? expectedNameFor(rowId);
1285
+ const recordModuleName = removedMarketName !== undefined;
1286
+ const back = await disableRow(userPatchPath, rowId, { expectedName, recordModuleName, packageName: name });
1224
1287
  if (!back.ok)
1225
1288
  logEvent('warn', 'toggle', `${name}: patch row ${rowId} could not be put back — ${back.reason}`);
1226
1289
  }
1227
1290
  else if (prePatch === null || !rowIsOurs(rowId) || !prePatch.forced.includes(rowId)) {
1228
1291
  // A row already forced on before this call got nothing from
1229
1292
  // the enable; that block is the user's to keep.
1230
- const cleanedRow = removeRowBlocks(userPatchPath, [rowId]);
1293
+ const cleanedRow = removeRowBlocks(userPatchPath, [rowId], name);
1231
1294
  if (!cleanedRow.ok)
1232
1295
  logEvent('warn', 'toggle', `patch row could not be cleared — ${cleanedRow.reason}`);
1233
1296
  }
@@ -1306,7 +1369,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1306
1369
  * loader side, every boot-loaded bundle plugin would read as "restart".
1307
1370
  */
1308
1371
  function liveNames() {
1309
- const live = new Set(listHotMounts());
1372
+ const live = new Set(listLiveHotMounts());
1310
1373
  for (const entry of host.loader.entries()) {
1311
1374
  if (entry.fiber === undefined)
1312
1375
  continue;
@@ -1845,6 +1908,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1845
1908
  // #662: the removal is confirmed — drop the host bridge link the boot
1846
1909
  // projection may have left pointing at the now-gone package.
1847
1910
  removeDanglingHostBridge(name, activeProfileDir, config.dshInstallDir ?? findDshInstallDir());
1911
+ // #1191: a `link:` install leaves its junction behind on Windows, and the
1912
+ // next install of the same name then fails renaming over it.
1913
+ removeLeftoverProfileLink(config.profile, name, activeProfileDir);
1848
1914
  // Kept on the host path too, and deliberately: `setEntryDisabled` only
1849
1915
  // scans the entries THIS process can see by name and returns false when
1850
1916
  // none match, so it costs a lookup — and it preserves what #213 is about.
@@ -1856,7 +1922,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1856
1922
  if (native) {
1857
1923
  logEvent('info', 'uninstall', `${name} ships or depends on a native addon; a restart is needed before it can be installed again`);
1858
1924
  }
1859
- const cleanedOwned = removeRowBlocks(userPatchPath, ownedRows);
1925
+ const cleanedOwned = removeRowBlocks(userPatchPath, ownedRows, name);
1860
1926
  if (!cleanedOwned.ok)
1861
1927
  logEvent('warn', 'uninstall', `patch rows could not be cleared — ${cleanedOwned.reason}`);
1862
1928
  else
@@ -1939,6 +2005,16 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1939
2005
  return [];
1940
2006
  }
1941
2007
  }
2008
+ async function refuseWorkspaceRoot(target, name, response) {
2009
+ const root = await mismatchedWorkspaceRoot(target, name, region);
2010
+ if (root === null)
2011
+ return false;
2012
+ logEvent('warn', 'install-rejected', `${name}: ${target} resolves to workspace root ${root}`);
2013
+ sendJson(response, 400, {
2014
+ error: `这条收录链接指向仓库根包「${root}」。请到收录仓库反馈,补上「${name}」的子目录或 npm 来源。 / This entry points to the repository root (${root}). Ask the catalog maintainers to link the subdirectory or npm release for ${name}.`,
2015
+ });
2016
+ return true;
2017
+ }
1942
2018
  /**
1943
2019
  * Whether a `#path:` target still points at a directory that exists.
1944
2020
  *
@@ -2308,6 +2384,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2308
2384
  const target = entry === null ? null : restoreTargetForLocal(entry, evidence.identities);
2309
2385
  return target !== null && NPM_NAME_RE.test(target) ? target : null;
2310
2386
  };
2387
+ // Snapshot reads can resolve blocked catalog aliases using the last
2388
+ // successful catalog lookup, without starting network work of their own.
2389
+ let notificationCatalog = [];
2311
2390
  /**
2312
2391
  * The two inputs `checkUpdates` needs beyond the profile itself: which
2313
2392
  * packages follow a release channel, and which local/generation installs
@@ -2336,8 +2415,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2336
2415
  // empty, and an empty map authorizes nothing.
2337
2416
  const catalogNpmByRepo = new Map();
2338
2417
  const releaseSources = new Map();
2418
+ const sourceMigrationFor = new Map();
2419
+ let lookupFailed = false;
2339
2420
  try {
2340
2421
  const registry = await loadRegistry();
2422
+ notificationCatalog = registry.plugins;
2341
2423
  for (const [name, spec] of Object.entries(installed)) {
2342
2424
  const source = onlineSourceOf(registry.plugins, name, spec);
2343
2425
  if (source !== null)
@@ -2347,6 +2429,17 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2347
2429
  const unique = new Map(releases.map(value => [JSON.stringify(value), value]));
2348
2430
  if (unique.size === 1)
2349
2431
  releaseSources.set(name, [...unique.values()][0]);
2432
+ // Keep migration hints in the shared result: a background refresh
2433
+ // must not erase the action the Installed page already displayed.
2434
+ const migration = findGitToNpmMigration(registry.plugins, spec);
2435
+ if (migration !== null)
2436
+ sourceMigrationFor.set(name, migration);
2437
+ else if (isRegistryRangeSpec(spec)) {
2438
+ const rename = findCatalogRename(registry.plugins, name);
2439
+ if (rename !== null && installed[rename.target] === undefined) {
2440
+ sourceMigrationFor.set(name, { kind: 'npm-rename', from: name, target: rename.target });
2441
+ }
2442
+ }
2350
2443
  }
2351
2444
  for (const plugin of registry.plugins) {
2352
2445
  if (plugin.npm === null || plugin.npm === undefined)
@@ -2357,10 +2450,85 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2357
2450
  }
2358
2451
  }
2359
2452
  catch (error) {
2453
+ lookupFailed = true;
2360
2454
  logEvent('warn', 'updates', `package source lookup failed — ${error instanceof Error ? error.message : String(error)}`);
2361
2455
  }
2362
- return { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources };
2456
+ return { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources, sourceMigrationFor, lookupFailed };
2363
2457
  }
2458
+ /** The host disables a bundle by removing it from the boot composition. */
2459
+ const unbundledPackages = (names, manifests, live) => {
2460
+ const composed = new Set(readProfileBundles(activeProfileDir));
2461
+ return names.filter(name => {
2462
+ if (INBOX_BUNDLES.has(name) || composed.has(name) || live.has(name))
2463
+ return false;
2464
+ const manifest = manifests.get(name);
2465
+ return typeof manifest === 'object' && manifest !== null && manifest.dsh?.bundle !== undefined
2466
+ && !bundlePatchIsEmpty(join(activeProfileDir, 'node_modules', name));
2467
+ });
2468
+ };
2469
+ const updateNotifications = createUpdateNotificationMonitor({
2470
+ boot: BOOT_ID,
2471
+ // Keep read receipts scoped across restarts without sending local paths.
2472
+ profileKey: createHash('sha256').update(activeProfileDir).digest('hex'),
2473
+ enabled: marketState.backgroundUpdateChecks === true,
2474
+ intervalHours: marketState.backgroundUpdateIntervalHours,
2475
+ inventory: () => {
2476
+ const installed = readInstalled(config.profile, activeProfileDir);
2477
+ const commits = readLockCommits(config.profile, activeProfileDir);
2478
+ return {
2479
+ context: JSON.stringify([activeProfileDir, activeChannel(), config.region, marketState.githubProxy]),
2480
+ packages: Object.fromEntries(Object.entries(installed).map(([name, spec]) => [name, JSON.stringify([
2481
+ spec, readInstalledVersion(config.profile, name, activeProfileDir),
2482
+ readGitResolutionCommit(config.profile, spec, activeProfileDir),
2483
+ commits.get(hostedRepoKey(spec) ?? '') ?? null,
2484
+ // A local package can switch forks at the same path and version.
2485
+ // Reuse its manifest/checkout evidence, without scanning a directory
2486
+ // tree or changing the authority of explicit git/npm sources.
2487
+ /^(?:file|link):/i.test(spec)
2488
+ ? readInstalledRepoEvidence(config.profile, name, spec, activeProfileDir) : null,
2489
+ ])])),
2490
+ };
2491
+ },
2492
+ preferences: () => {
2493
+ const state = readMarketState(activeProfileDir);
2494
+ const installed = readInstalled(config.profile, activeProfileDir);
2495
+ const names = Object.keys(installed);
2496
+ const patchFlags = packagePatchFlags(host, activeProfileDir, names, readUserPatchState(userPatchPath));
2497
+ const manifests = new Map(names.map(name => [name, readInstalledManifest(config.profile, name, activeProfileDir)]));
2498
+ const inactive = new Set([...state.disabled, ...patchFlags.disabled, ...unbundledPackages(names, manifests, liveNames())]);
2499
+ const savedBlocked = new Set(state.blocked ?? []);
2500
+ const blocked = new Set(savedBlocked);
2501
+ if (savedBlocked.size > 0) {
2502
+ for (const [name, spec] of Object.entries(installed)) {
2503
+ if (blocked.has(name))
2504
+ continue;
2505
+ // Resolve against the current source, not a stored name-to-name
2506
+ // map: a local package can change its repository at the same path.
2507
+ const evidence = readInstalledRepoEvidence(config.profile, name, spec, activeProfileDir);
2508
+ const entry = findCatalogEntryForLocal(notificationCatalog, name, evidence.identities, evidence.hints);
2509
+ if (entry !== null && savedBlocked.has(entry.npm || entry.name))
2510
+ blocked.add(name);
2511
+ }
2512
+ }
2513
+ return { updateExempt: state.updateExempt ?? [], disabled: [...inactive], blocked: [...blocked] };
2514
+ },
2515
+ check: async (force) => {
2516
+ const installed = readInstalled(config.profile, activeProfileDir);
2517
+ if (Object.keys(installed).length === 0)
2518
+ return { updates: {} };
2519
+ const { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources, sourceMigrationFor, lookupFailed } = await updateCheckInputs();
2520
+ const checked = await checkUpdates(config.profile, force, activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true, releaseSources });
2521
+ const updates = {};
2522
+ for (const [name, status] of Object.entries(checked)) {
2523
+ const sourceMigration = sourceMigrationFor.get(name);
2524
+ updates[name] = { ...status,
2525
+ ...(sourceMigration === undefined ? {} : { sourceMigration }),
2526
+ ...(lookupFailed ? { checkFailed: true, checkError: 'unavailable' } : {}),
2527
+ };
2528
+ }
2529
+ return { updates, ...(lookupFailed ? { error: 'Plugin sources could not be checked. Try again later.' } : {}) };
2530
+ },
2531
+ });
2364
2532
  /**
2365
2533
  * Pre-install host compatibility refusal, shared by the update route and
2366
2534
  * the fresh-install route (#404/#473 convention, extended to installs).
@@ -2450,6 +2618,61 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2450
2618
  });
2451
2619
  };
2452
2620
  const disposers = [
2621
+ registerRoute({
2622
+ kind: 'exact',
2623
+ path: '/dsh-crate/update-notifications',
2624
+ handler: async (request, response) => {
2625
+ if (request.method === 'GET') {
2626
+ sendJson(response, 200, updateNotifications.snapshot());
2627
+ return;
2628
+ }
2629
+ if (request.method !== 'POST') {
2630
+ response.writeHead(405, { allow: 'GET, POST' });
2631
+ response.end();
2632
+ return;
2633
+ }
2634
+ if (!sameOrigin(request)) {
2635
+ sendJson(response, 403, { error: 'untrusted origin' });
2636
+ return;
2637
+ }
2638
+ try {
2639
+ const body = await readJsonBody(request);
2640
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) {
2641
+ sendJson(response, 400, { error: 'expected an update-check setting or check request' });
2642
+ return;
2643
+ }
2644
+ const { enabled, intervalHours, check } = body;
2645
+ if ((enabled !== undefined && typeof enabled !== 'boolean') || (check !== undefined && check !== true)
2646
+ || (intervalHours !== undefined && !isUpdateCheckIntervalHours(intervalHours))
2647
+ || (enabled === undefined && intervalHours === undefined && check === undefined)) {
2648
+ sendJson(response, 400, { error: 'enabled must be a boolean; intervalHours must be 6, 12, 72 or 168; check must be true' });
2649
+ return;
2650
+ }
2651
+ if (typeof enabled === 'boolean' || isUpdateCheckIntervalHours(intervalHours)) {
2652
+ const state = readMarketState(activeProfileDir);
2653
+ if (typeof enabled === 'boolean')
2654
+ state.backgroundUpdateChecks = enabled;
2655
+ if (isUpdateCheckIntervalHours(intervalHours))
2656
+ state.backgroundUpdateIntervalHours = intervalHours;
2657
+ // Validate the complete request, then persist both choices before
2658
+ // changing the live timer. Partial preference writes keep the other.
2659
+ writeMarketState(activeProfileDir, state);
2660
+ marketState.backgroundUpdateChecks = state.backgroundUpdateChecks;
2661
+ marketState.backgroundUpdateIntervalHours = state.backgroundUpdateIntervalHours;
2662
+ if (isUpdateCheckIntervalHours(intervalHours))
2663
+ updateNotifications.setIntervalHours(intervalHours);
2664
+ if (typeof enabled === 'boolean')
2665
+ updateNotifications.setEnabled(enabled);
2666
+ }
2667
+ if (check === true)
2668
+ await updateNotifications.check(true);
2669
+ sendJson(response, 200, updateNotifications.snapshot());
2670
+ }
2671
+ catch {
2672
+ sendJson(response, 400, { error: 'Could not change update checks. Try again.' });
2673
+ }
2674
+ },
2675
+ }),
2453
2676
  registerRoute({
2454
2677
  kind: 'exact',
2455
2678
  path: '/dsh-crate/api/v1/capabilities',
@@ -2515,8 +2738,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2515
2738
  return;
2516
2739
  }
2517
2740
  try {
2518
- const { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources } = await updateCheckInputs();
2519
- const updates = await checkUpdates(config.profile, forceCheckFrom(request), activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true, releaseSources });
2741
+ const updates = await updateNotifications.check(forceCheckFrom(request));
2520
2742
  // `packages` carries the same objects the single-package endpoint
2521
2743
  // returns, so one parser serves both. Only updatable ones: a badge
2522
2744
  // wants the count, a panel wants the rows, and neither wants to
@@ -2562,8 +2784,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2562
2784
  // The same inputs the market page builds, so a generation (#497)
2563
2785
  // or a catalog-matched local package answers here with the
2564
2786
  // release it can be compared against rather than with nothing.
2565
- const { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources } = await updateCheckInputs();
2566
- const update = (await checkUpdates(config.profile, force, activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true, releaseSources }))[name];
2787
+ const update = (await updateNotifications.check(force))[name];
2567
2788
  if (update === undefined) {
2568
2789
  sendJson(response, 404, { schema: UPDATE_API_V1_SCHEMA, error: 'plugin is not installed' });
2569
2790
  return;
@@ -3055,7 +3276,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3055
3276
  try {
3056
3277
  const registry = await loadRegistry();
3057
3278
  sendJson(response, 200, {
3058
- registry,
3279
+ registry: discoveryCatalog(registry).response,
3059
3280
  hostVersion: dshHostInfo()?.version ?? null,
3060
3281
  });
3061
3282
  }
@@ -3141,31 +3362,65 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3141
3362
  sendJson(response, 400, { error: 'entries must be GitHub catalog URLs; at most 64 packages and entries per batch' });
3142
3363
  return;
3143
3364
  }
3144
- const packages = [...new Set(requested)];
3365
+ const packages = new Set(requested);
3366
+ const urls = new Set(requestedEntries);
3367
+ const versions = discoveryHints(body.versions, packages, isExactReleaseVersion);
3368
+ const revisions = discoveryHints(body.githubRevisions, urls, (hint) => typeof hint === 'string' && hint.length === 64 && /^[a-f0-9]+$/.test(hint));
3369
+ if (versions === null || revisions === null) {
3370
+ sendJson(response, 400, { error: 'versions and githubRevisions must match entries in the current batch' });
3371
+ return;
3372
+ }
3145
3373
  try {
3146
- const urls = new Set(requestedEntries);
3147
- const entries = urls.size === 0 ? [] : (await loadRegistry()).plugins.filter(entry => urls.has(entry.url) && (entry.npm == null || entry.npm === ''));
3148
- if (new Set(entries.map(entry => entry.url)).size !== urls.size) {
3149
- sendJson(response, 400, { error: 'entries must name GitHub-only plugins in the current catalog' });
3150
- return;
3151
- }
3152
3374
  const host = dshHostInfo();
3153
3375
  const hostVersion = host?.version ?? null;
3154
3376
  const hostPackages = corePackageNames(host?.directory ?? null);
3155
- const catalogFacts = Object.fromEntries(entries.flatMap(entry => {
3156
- const facts = catalogReleaseManifest(entry);
3157
- return facts === null ? [] : [[entry.url, facts]];
3158
- }));
3159
- const [npmFacts, githubFacts] = await Promise.all([
3160
- discoveryManifests.lookup(packages, routesFor(region).npmRegistry),
3161
- githubDiscoveryManifests.lookupGitHub(entries.filter(entry => catalogFacts[entry.url] === undefined)),
3377
+ const npmRegistry = routesFor(region).npmRegistry;
3378
+ const githubVerdicts = async () => {
3379
+ if (urls.size === 0)
3380
+ return {};
3381
+ const unavailable = deriveHostCompatibility(null, hostVersion, hostPackages);
3382
+ const catalog = await loadRegistry().then(discoveryCatalog).catch(() => null);
3383
+ if (catalog === null) {
3384
+ return Object.fromEntries([...urls].map(url => [url, { ...unavailable, retryAfterMs: DISCOVERY_RETRY_MS }]));
3385
+ }
3386
+ const results = {};
3387
+ const fetchEntries = [];
3388
+ for (const url of urls) {
3389
+ const match = catalog.revisions.get(url);
3390
+ const expected = revisions.get(url);
3391
+ if (match === undefined || (expected !== undefined && expected !== match.revision)) {
3392
+ results[url] = { ...unavailable, catalogChanged: true };
3393
+ continue;
3394
+ }
3395
+ const facts = catalogReleaseManifest(match.entry);
3396
+ if (facts === null)
3397
+ fetchEntries.push(match.entry);
3398
+ else
3399
+ results[url] = deriveHostCompatibility(facts, hostVersion, hostPackages);
3400
+ }
3401
+ if (fetchEntries.length === 0)
3402
+ return results;
3403
+ const factsByUrl = await githubDiscoveryManifests.lookupGitHub(fetchEntries);
3404
+ for (const entry of fetchEntries) {
3405
+ const facts = factsByUrl[entry.url] ?? null;
3406
+ results[entry.url] = facts === null ? { ...unavailable,
3407
+ retryAfterMs: githubDiscoveryManifests.githubRetryAfterMs(entry) || DISCOVERY_RETRY_MS,
3408
+ } : deriveHostCompatibility(facts, hostVersion, hostPackages);
3409
+ }
3410
+ return results;
3411
+ };
3412
+ const [npmFacts, githubPlugins] = await Promise.all([
3413
+ discoveryManifests.lookup([...packages], npmRegistry, { versions }),
3414
+ githubVerdicts(),
3162
3415
  ]);
3163
- const facts = { ...npmFacts, ...githubFacts, ...catalogFacts };
3164
- const plugins = Object.fromEntries([...packages, ...urls].map(name => [
3165
- name,
3166
- deriveHostCompatibility(facts[name] ?? null, hostVersion, hostPackages),
3167
- ]));
3168
- sendJson(response, 200, { hostVersion, plugins });
3416
+ const npmPlugins = Object.fromEntries([...packages].map(name => {
3417
+ const facts = npmFacts[name] ?? null;
3418
+ const verdict = deriveHostCompatibility(facts, hostVersion, hostPackages);
3419
+ return [name, facts === null ? { ...verdict,
3420
+ retryAfterMs: discoveryManifests.npmRetryAfterMs(name, npmRegistry, versions.get(name)) || DISCOVERY_RETRY_MS,
3421
+ } : verdict];
3422
+ }));
3423
+ sendJson(response, 200, { hostVersion, plugins: { ...npmPlugins, ...githubPlugins } });
3169
3424
  }
3170
3425
  catch (error) {
3171
3426
  sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
@@ -3276,6 +3531,16 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3276
3531
  // every other package's manifest.
3277
3532
  const dependencyOwners = readDependencyOwners(config.profile, Object.keys(installed), activeProfileDir);
3278
3533
  const installedManifests = new Map(Object.keys(installed).map(packageName => [packageName, readInstalledManifest(config.profile, packageName, activeProfileDir)]));
3534
+ // Display-only fallback for packages absent from the catalog (#1147).
3535
+ // Reuse these manifests; never use their metadata to infer a source.
3536
+ const descriptions = {};
3537
+ for (const [name, manifest] of installedManifests) {
3538
+ const description = typeof manifest === 'object' && manifest !== null
3539
+ ? manifest.description
3540
+ : undefined;
3541
+ if (typeof description === 'string' && description.trim() !== '')
3542
+ descriptions[name] = description.trim();
3543
+ }
3279
3544
  const declaresDshSurface = (packageName) => {
3280
3545
  const manifest = installedManifests.get(packageName);
3281
3546
  return typeof manifest === 'object' && manifest !== null
@@ -3286,16 +3551,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3286
3551
  // by removing it from that list, and nothing the market recorded
3287
3552
  // says so (#696). Reported as off, unless it is live right now — a
3288
3553
  // hot mount from this session still runs until the next restart.
3289
- const composedBundles = new Set(readProfileBundles(activeProfileDir));
3290
- const unbundled = Object.keys(installed).filter(name => {
3291
- if (INBOX_BUNDLES.has(name) || composedBundles.has(name) || live.has(name))
3292
- return false;
3293
- const manifest = installedManifests.get(name);
3294
- // A bundle whose own patch is empty loads nothing either way, so
3295
- // its absence from the list says nothing about a switch (#813).
3296
- return typeof manifest === 'object' && manifest !== null && manifest.dsh?.bundle !== undefined
3297
- && !bundlePatchIsEmpty(join(activeProfileDir, 'node_modules', name));
3298
- });
3554
+ const unbundled = unbundledPackages(Object.keys(installed), installedManifests, live);
3299
3555
  for (const name of Object.keys(installed)) {
3300
3556
  const manifest = installedManifests.get(name);
3301
3557
  const result = activationAfterReplace(verifyActivation(config.profile, name, live, activeProfileDir, disabled.has(name) || patchFlags.disabled.includes(name) || unbundled.includes(name), undefined, isDeclaredLibraryDsh(manifest?.dsh) && loaderEntryObserved(name), loaderNeverStarted(name)), replacedWhileLive.has(name));
@@ -3350,16 +3606,22 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3350
3606
  sendJson(response, 200, {
3351
3607
  profile: config.profile,
3352
3608
  installed,
3609
+ descriptions,
3353
3610
  repoIdentities,
3354
3611
  repoHints,
3355
3612
  present,
3356
3613
  activation,
3357
3614
  diagnostics,
3358
- live: listHotMounts(),
3615
+ live: listLiveHotMounts(),
3359
3616
  disabled: [...disabled],
3360
3617
  groups,
3361
3618
  groupOrder,
3362
3619
  notes: readMarketState(activeProfileDir).notes ?? {},
3620
+ // When this market installed/updated each package (#1142). Read
3621
+ // from disk like `notes`, not from the boot-time snapshot: an
3622
+ // install in this session must show its date on the very refresh
3623
+ // that follows it.
3624
+ installTimes: readMarketState(activeProfileDir).installTimes ?? {},
3363
3625
  favorites: readMarketState(activeProfileDir).favorites ?? [],
3364
3626
  blocked: readMarketState(activeProfileDir).blocked ?? [],
3365
3627
  updateExempt: readMarketState(activeProfileDir).updateExempt ?? [],
@@ -3780,9 +4042,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3780
4042
  return;
3781
4043
  }
3782
4044
  pendingRollbacks.clear();
3783
- const activated = await themes.activateTheme(name);
4045
+ const { ok: activated, reason } = await themes.activateTheme(name);
3784
4046
  logEvent(activated ? 'info' : 'error', 'use-skin', `${name}: ${activated ? 'active' : 'failed'}`);
3785
- sendJson(response, activated ? 200 : 502, { ok: activated, live: listHotMounts() });
4047
+ sendJson(response, activated ? 200 : 502, {
4048
+ ok: activated, live: listLiveHotMounts(), ...(reason === undefined ? {} : { error: reason }),
4049
+ });
3786
4050
  }
3787
4051
  catch (error) {
3788
4052
  const message = error instanceof Error ? error.message : String(error);
@@ -3850,24 +4114,18 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3850
4114
  }
3851
4115
  }
3852
4116
  pendingRollbacks.clear();
3853
- let ok;
3854
- let reason;
3855
- if (enabled && (await themes.installedThemeNames()).has(name)) {
4117
+ let themeFailure;
4118
+ const layers = enabled && (await themes.installedThemeNames()).has(name)
3856
4119
  // Theme exclusivity stays a Themes-page concern: enabling a theme
3857
4120
  // deactivates the previously active one, so only the last-enabled
3858
4121
  // theme is live (same semantics as use-skin).
3859
- ok = await themes.activateTheme(name);
3860
- if (!ok)
3861
- reason = 'theme activation failed — restart required / 主题启用失败,需要重启';
3862
- }
3863
- else {
3864
- const result = await setPluginEnabled(name, enabled);
3865
- ok = result.ok;
3866
- reason = result.reason;
3867
- }
3868
- const layers = await switchPluginLayers(name, enabled, ok, reason);
3869
- ok = layers.ok;
3870
- reason = layers.reason;
4122
+ ? await switchPluginLayers(name, enabled, async () => {
4123
+ const { ok, reason } = await themes.activateTheme(name);
4124
+ themeFailure = reason;
4125
+ return { ok, reason: reason ?? (ok ? undefined : 'theme activation failed — restart required / 主题启用失败,需要重启') };
4126
+ })
4127
+ : await switchPluginLayers(name, enabled);
4128
+ const { ok, reason } = layers;
3871
4129
  const { patchRows, userRows, patchWrite, carrierRows, isCarrier, bundleSwitch } = layers;
3872
4130
  // Activation reads the post-write truth: the switch state OR the
3873
4131
  // patch layer, so a disabled plugin never reports "restart to
@@ -3880,7 +4138,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3880
4138
  // (enable failed to hot-mount / disable left the fiber up), the
3881
4139
  // change lands on the next boot via the patch layer + state.json —
3882
4140
  // the client reuses the market's pending-restart banner for it.
3883
- const liveAfter = liveNames().has(name);
4141
+ const liveNow = liveNames();
4142
+ const liveAfter = liveNow.has(name);
3884
4143
  // A carrier toggle moves the bundle in/out of dsh.profile.bundles,
3885
4144
  // which only takes effect on the next composition — always a restart.
3886
4145
  // Non-carrier plugins keep the live-mount based decision.
@@ -3891,7 +4150,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3891
4150
  // module-scope version marker). Enabling cannot make it current;
3892
4151
  // only a restart can.
3893
4152
  const staleModule = enabled && replacedWhileLive.has(name);
3894
- const restart = isCarrier || staleModule ? true : enabled ? !liveAfter : liveAfter;
4153
+ const observed = activationAfterReplace(verifyActivation(config.profile, name, liveNow, activeProfileDir, offNow, undefined, loaderEntryObserved(name)), replacedWhileLive.has(name));
4154
+ const reported = themeFailure === undefined
4155
+ ? observed
4156
+ : { ...observed, state: 'failed', hot: false, reasons: [themeFailure] };
4157
+ const restart = !(enabled && reported.state === 'failed')
4158
+ && (isCarrier || staleModule || (enabled ? !liveAfter : liveAfter));
3895
4159
  // A client-part plugin's UI is in the page already — toggling it
3896
4160
  // needs a browser refresh to show the change (same signal the
3897
4161
  // install flow uses for the hot banner).
@@ -3901,14 +4165,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3901
4165
  name,
3902
4166
  enabled,
3903
4167
  disabled: [...disabled],
3904
- live: listHotMounts(),
4168
+ live: listLiveHotMounts(),
3905
4169
  // The same verdict the listing gives (#685): the reply used the
3906
4170
  // loader inventory alone and said `live` for a plugin serving
3907
4171
  // its old build, while a refresh of the listing — which applies
3908
4172
  // activationAfterReplace — said `restart`. One moment, one story.
3909
- activation: {
3910
- [name]: activationAfterReplace(verifyActivation(config.profile, name, liveNames(), activeProfileDir, offNow, undefined, loaderEntryObserved(name)), replacedWhileLive.has(name)),
3911
- },
4173
+ activation: { [name]: reported },
3912
4174
  reason,
3913
4175
  patchRows,
3914
4176
  patchWrite: patchWrite ?? { ok: true, reason: null },
@@ -4240,13 +4502,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4240
4502
  continue;
4241
4503
  let result;
4242
4504
  if (enabled && themeNames.has(member)) {
4243
- result = { ok: await themes.activateTheme(member), reason: undefined };
4505
+ result = await themes.activateTheme(member);
4244
4506
  }
4245
4507
  else {
4246
4508
  // The same two durable layers the single switch writes (#696):
4247
4509
  // which control flipped a plugin must not change what is on disk.
4248
- const live = await setPluginEnabled(member, enabled);
4249
- result = await switchPluginLayers(member, enabled, live.ok, live.reason);
4510
+ result = await switchPluginLayers(member, enabled);
4250
4511
  }
4251
4512
  if (!result.ok)
4252
4513
  failures.push(member);
@@ -4476,43 +4737,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4476
4737
  }
4477
4738
  try {
4478
4739
  const force = (request.url ?? '').includes('force=1');
4479
- const { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources } = await updateCheckInputs();
4480
- // Migration hints are this listing's own business: the market page
4481
- // is where "this could come from npm now" is offered, and no other
4482
- // caller acts on it.
4483
- const sourceMigrationFor = new Map();
4484
- try {
4485
- const registry = await loadRegistry();
4486
- const installed = readInstalled(config.profile, activeProfileDir);
4487
- for (const [name, spec] of Object.entries(installed)) {
4488
- const migration = findGitToNpmMigration(registry.plugins, spec);
4489
- if (migration !== null)
4490
- sourceMigrationFor.set(name, migration);
4491
- }
4492
- // A rename declared by the catalog (#1012, P1). This is the only
4493
- // path that reaches a user whose old range no longer resolves:
4494
- // their update fails before installing anything, so no offer was
4495
- // ever recorded. The catalog states the rename up front, and the
4496
- // row still has to be a plain registry range the transaction can
4497
- // replace — and the successor must not already be installed.
4498
- for (const [name, spec] of Object.entries(installed)) {
4499
- if (sourceMigrationFor.has(name) || !isRegistryRangeSpec(spec))
4500
- continue;
4501
- const rename = findCatalogRename(registry.plugins, name);
4502
- if (rename === null || installed[rename.target] !== undefined)
4503
- continue;
4504
- sourceMigrationFor.set(name, { kind: 'npm-rename', from: name, target: rename.target });
4505
- }
4506
- }
4507
- catch (error) {
4508
- logEvent('warn', 'updates', `package source lookup failed — ${error instanceof Error ? error.message : String(error)}`);
4509
- }
4510
- const updates = await checkUpdates(config.profile, force, activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true, releaseSources });
4511
- for (const [name, migration] of sourceMigrationFor) {
4512
- const status = updates[name];
4513
- if (status !== undefined)
4514
- updates[name] = { ...status, sourceMigration: migration };
4515
- }
4740
+ const updates = await updateNotifications.check(force);
4516
4741
  sendJson(response, 200, { updates });
4517
4742
  }
4518
4743
  catch (error) {
@@ -4541,7 +4766,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4541
4766
  sendJson(response, 400, { error: 'name query parameter is required' });
4542
4767
  return;
4543
4768
  }
4544
- sendJson(response, 200, await updateNotesFor(config.profile, activeProfileDir, name));
4769
+ // The version the Update button installs, when the client knows it
4770
+ // (#1193); anything that is not a plain stable version is ignored.
4771
+ const target = new URL(request.url ?? '/', 'http://localhost').searchParams.get('target');
4772
+ sendJson(response, 200, await updateNotesFor(config.profile, activeProfileDir, name, target !== null && isStableReleaseVersion(target) ? target : undefined));
4545
4773
  }
4546
4774
  catch (error) {
4547
4775
  sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
@@ -4838,7 +5066,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4838
5066
  stateWarning = `市场状态未能持久化:${error instanceof Error ? error.message : String(error)} / Market state could not be persisted: ${error instanceof Error ? error.message : String(error)}`;
4839
5067
  logEvent('warn', 'source-migration', `${name}: ${stateWarning}`);
4840
5068
  }
4841
- const cleanedOld = removeRowBlocks(userPatchPath, oldRows);
5069
+ const cleanedOld = removeRowBlocks(userPatchPath, oldRows, name);
4842
5070
  if (!cleanedOld.ok)
4843
5071
  logEvent('warn', 'install', `patch rows could not be cleared — ${cleanedOld.reason}`);
4844
5072
  const patchDisabled = wasDisabled || patchFlags.disabled.includes(name);
@@ -4847,9 +5075,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4847
5075
  for (const rowId of rowIdsForPackage(host, activeProfileDir, targetName)) {
4848
5076
  const expectedName = composedRowName(host, rowId);
4849
5077
  const changed = patchDisabled
4850
- ? await disableRow(userPatchPath, rowId, { expectedName })
5078
+ ? await disableRow(userPatchPath, rowId, { expectedName, packageName: targetName })
4851
5079
  : patchForced
4852
- ? await enableRow(userPatchPath, rowId, { expectedName })
5080
+ ? await enableRow(userPatchPath, rowId, { expectedName, packageName: targetName })
4853
5081
  : { ok: true, reason: null };
4854
5082
  if (!changed.ok && changed.reason !== null)
4855
5083
  patchWarnings.push(changed.reason);
@@ -6210,6 +6438,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6210
6438
  }
6211
6439
  }
6212
6440
  }
6441
+ // The update landed: stamp it before answering (#1142). `ok` is
6442
+ // final by now — every check that can still turn a run into a
6443
+ // failure (version mismatch, rename, missing entry, trial boot)
6444
+ // has run, so a rejected update never moves the date.
6445
+ if (ok)
6446
+ recordUpdated(activeProfileDir, [name]);
6213
6447
  logEvent(ok || cancelled ? 'info' : 'error', 'update', `${name} -> ${target} exit=${String(result.exitCode)}${result.timedOut ? ' TIMEOUT' : ''}${cancelled ? ' CANCELLED' : ''}${stale ? ` STALE(${staleReason ?? 'unknown'})` : ''}${ok || cancelled ? '' : ` err=${failureDetail(result)}`}`);
6214
6448
  // A user-cancelled run is a quiet outcome, not an error.
6215
6449
  sendJson(response, ok || cancelled ? 200 : result.busy === true ? 409 : 502, {
@@ -6649,7 +6883,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6649
6883
  // button whose failure leaves the user with no other way out of the
6650
6884
  // page they are looking at (#903).
6651
6885
  sendJson(response, 403, {
6652
- error: `不能从这个地址卸载插件市场(只接受本机同源请求)。请在运行 DSH 的机器上执行 \`dsh plugin --profile ${config.profile} remove dsh-crate\`;桌面端也可以在它自己的「设置 → 插件」里移除。 / The market can only be removed from the same machine it runs on. Run \`dsh plugin --profile ${config.profile} remove dsh-crate\` there, or remove it from the desktop app's Settings → Plugins.`,
6886
+ error: `不能从这个地址卸载插件箱子(只接受本机同源请求)。请在运行 DSH 的机器上执行 \`dsh plugin --profile ${config.profile} remove dsh-crate\`;桌面端也可以在它自己的「设置 → 插件」里移除。 / The market can only be removed from the same machine it runs on. Run \`dsh plugin --profile ${config.profile} remove dsh-crate\` there, or remove it from the desktop app's Settings → Plugins.`,
6653
6887
  });
6654
6888
  return;
6655
6889
  }
@@ -6701,7 +6935,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6701
6935
  for (const name of disabled) {
6702
6936
  const ids = rowIdsForPackage(host, activeProfileDir, name);
6703
6937
  if (ids.length > 0) {
6704
- const cleanedIds = removeRowBlocks(userPatchPath, ids);
6938
+ const cleanedIds = removeRowBlocks(userPatchPath, ids, name);
6705
6939
  if (!cleanedIds.ok)
6706
6940
  logEvent('warn', 'patch', `patch rows could not be cleared — ${cleanedIds.reason}`);
6707
6941
  restored.push(name);
@@ -7191,6 +7425,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7191
7425
  // from disk truth) — the host node_modules bridge the boot
7192
7426
  // projection left for this package must not outlive it.
7193
7427
  removeDanglingHostBridge(name, activeProfileDir, config.dshInstallDir ?? findDshInstallDir());
7428
+ // #1191: a `link:` install leaves its junction behind on Windows, and the
7429
+ // next install of the same name then fails renaming over it.
7430
+ removeLeftoverProfileLink(config.profile, name, activeProfileDir);
7194
7431
  // A host that owns the composition replays it: asking first is
7195
7432
  // what keeps the market from looking for an entry it never
7196
7433
  // created, and then telling the user to restart about a plugin
@@ -7228,7 +7465,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7228
7465
  // Patch-layer rows must not survive the remove either: a
7229
7466
  // `- id: X` + `disabled: true` row for a package that no longer
7230
7467
  // mounts is a boot-time orphan (port of dsh-plugin-hub).
7231
- const cleanedOwned = removeRowBlocks(userPatchPath, ownedRows);
7468
+ const cleanedOwned = removeRowBlocks(userPatchPath, ownedRows, name);
7232
7469
  if (!cleanedOwned.ok)
7233
7470
  logEvent('warn', 'uninstall', `patch rows could not be cleared — ${cleanedOwned.reason}`);
7234
7471
  // Either way the record is settled: cleaned means nothing is
@@ -7242,6 +7479,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7242
7479
  disabled.delete(name);
7243
7480
  removeFromGroups({ groups, groupOrder }, name);
7244
7481
  writeMarketState(activeProfileDir, { disabled, groups, groupOrder });
7482
+ // A removed package's stamps must not outlive it (#1142): a
7483
+ // later reinstall is a new install, and keeping the old date
7484
+ // would make the list claim a history the profile no longer has.
7485
+ forgetInstalled(activeProfileDir, name);
7245
7486
  // #1093: pnpm writes a `minimumReleaseAgeExclude` row when it
7246
7487
  // installs a version still inside the wait window, and removing
7247
7488
  // the dependency never touches that file. Left behind, the row
@@ -7572,6 +7813,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7572
7813
  // dialog just found for this host — a loop with the user in it.
7573
7814
  if (npmName !== null && await refuseHostIncompatible(npmName, entry.name, requestedVersion, force, response, region, 'install-compat'))
7574
7815
  return;
7816
+ if (await refuseWorkspaceRoot(target, entry.name, response))
7817
+ return;
7575
7818
  const beforeSpecs = readInstalled(config.profile, activeProfileDir);
7576
7819
  const before = new Set(Object.keys(beforeSpecs));
7577
7820
  if (retryAlias !== null)
@@ -7720,6 +7963,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7720
7963
  if (lockfileBefore.ok)
7721
7964
  restoreProfileLockfile(lockfileBefore.snapshot);
7722
7965
  target = await acceleratedTarget(sourceTarget, region);
7966
+ if (await refuseWorkspaceRoot(target, entry.name, response))
7967
+ return;
7723
7968
  if (!assertDrainMutation(request, response))
7724
7969
  return;
7725
7970
  result = await runPlugin(config.profile, ['add', target]);
@@ -7798,6 +8043,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7798
8043
  const added = Object.keys(installed).filter(name => !before.has(name));
7799
8044
  addedPackages = added;
7800
8045
  if (added.length > 0) {
8046
+ // When the market installed them (#1142): the only moment it
8047
+ // knows a real install time, since nothing on disk carries
8048
+ // one (`node_modules` mtime is rewritten by pnpm).
8049
+ recordInstalled(activeProfileDir, added);
7801
8050
  // Fresh installs start enabled: drop any stale disable flag
7802
8051
  // (e.g. reinstall after an uninstall while this process kept
7803
8052
  // running) and persist before the activation loop.
@@ -7806,6 +8055,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7806
8055
  writeMarketState(activeProfileDir, { disabled, groups, groupOrder });
7807
8056
  // Theme installs auto-activate (and deactivate the previous
7808
8057
  // theme) so the result is visible right after the refresh.
8058
+ const themeFailures = new Map();
7809
8059
  if (hostActivation) {
7810
8060
  // The host's watcher owns the entire composition. Waiting
7811
8061
  // for its replay gives the market a real live/fail verdict
@@ -7873,7 +8123,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7873
8123
  }
7874
8124
  }
7875
8125
  else if (!adopted) {
7876
- live = await themes.activateTheme(name);
8126
+ const result = await themes.activateTheme(name);
8127
+ live = result.ok;
8128
+ if (result.reason !== undefined)
8129
+ themeFailures.set(name, result.reason);
7877
8130
  }
7878
8131
  if (!live)
7879
8132
  hot = false;
@@ -7885,7 +8138,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7885
8138
  // cannot disagree with it within one request.
7886
8139
  const hostFacts = defaultHostRuntimeFacts(activeProfileDir);
7887
8140
  for (const name of added) {
7888
- activation[name] = verifyActivation(config.profile, name, live, activeProfileDir, disabled.has(name), hostFacts);
8141
+ const result = verifyActivation(config.profile, name, live, activeProfileDir, disabled.has(name), hostFacts);
8142
+ const failure = themeFailures.get(name);
8143
+ activation[name] = failure === undefined
8144
+ ? result
8145
+ : { ...result, state: 'failed', hot: false, reasons: [failure] };
7889
8146
  }
7890
8147
  }
7891
8148
  }
@@ -8055,8 +8312,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8055
8312
  },
8056
8313
  })),
8057
8314
  ];
8058
- return () => {
8315
+ return async () => {
8059
8316
  disposed = true;
8317
+ updateNotifications.dispose();
8060
8318
  // Release Agent maintenance holds before the routes disappear. This is the
8061
8319
  // disposer half of the single-finally + disposer guarantee (#411): an
8062
8320
  // unloaded market must never leave an Agent parked behind a hold.
@@ -8065,5 +8323,6 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8065
8323
  configurePersistentLog(null);
8066
8324
  for (const dispose of disposers)
8067
8325
  dispose();
8326
+ await Promise.all([discoveryManifests.dispose(), githubDiscoveryManifests.dispose()]);
8068
8327
  };
8069
8328
  }