dsh-crate 0.5.2 → 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 (46) hide show
  1. package/assets/logo.svg +11 -33
  2. package/client/client.js +2271 -561
  3. package/lib/body-progress.js +4 -3
  4. package/lib/changelog.js +15 -2
  5. package/lib/discovery-cache.js +210 -0
  6. package/lib/discovery-compatibility.js +135 -90
  7. package/lib/drain.js +28 -9
  8. package/lib/dsh-cli.js +36 -6
  9. package/lib/github-install-target.js +53 -0
  10. package/lib/hot.js +400 -33
  11. package/lib/index.js +23 -9
  12. package/lib/install.js +37 -0
  13. package/lib/patch.js +123 -73
  14. package/lib/pending-rows.js +3 -4
  15. package/lib/pnpm-compat.js +234 -2
  16. package/lib/proc-text.js +16 -1
  17. package/lib/profile.js +17 -1
  18. package/lib/recovery.js +2 -1
  19. package/lib/registry.js +24 -16
  20. package/lib/release-candidates.js +4 -0
  21. package/lib/release-updates.js +9 -2
  22. package/lib/routes.js +459 -134
  23. package/lib/themes.js +42 -9
  24. package/lib/types/body-progress.d.ts +2 -1
  25. package/lib/types/changelog.d.ts +10 -1
  26. package/lib/types/discovery-cache.d.ts +38 -0
  27. package/lib/types/discovery-compatibility.d.ts +24 -14
  28. package/lib/types/dsh-cli.d.ts +19 -2
  29. package/lib/types/github-install-target.d.ts +11 -0
  30. package/lib/types/hot.d.ts +91 -7
  31. package/lib/types/index.d.ts +17 -0
  32. package/lib/types/install.d.ts +19 -0
  33. package/lib/types/patch.d.ts +6 -2
  34. package/lib/types/profile.d.ts +4 -1
  35. package/lib/types/registry.d.ts +9 -8
  36. package/lib/types/release-candidates.d.ts +2 -0
  37. package/lib/types/routes.d.ts +2 -2
  38. package/lib/types/themes.d.ts +7 -1
  39. package/lib/types/update-notification-settings.d.ts +5 -0
  40. package/lib/types/update-notifications.d.ts +51 -0
  41. package/lib/types/updates.d.ts +5 -1
  42. package/lib/update-notification-settings.js +6 -0
  43. package/lib/update-notifications.js +166 -0
  44. package/lib/updates.js +41 -11
  45. package/lib/verify.js +24 -2
  46. 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,20 @@ 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;
1015
+ }
1016
+ else if (carrierRowIds(dir, name).length > 0) {
1017
+ // A carrier replaces something: its patch disables stock rows and its
1018
+ // own rows stand in for them, with `disabled: !!js …` guards deciding
1019
+ // which of the two is live on THIS host. Driving those rows up in the
1020
+ // running process clears the guards and mounts the replacement beside
1021
+ // the stock row — a second copy of a module the host already holds
1022
+ // (`storage form 'domain' is already mounted`), which dsh answers by
1023
+ // exiting (#1175). Enabling is the mirror of the disable branch below
1024
+ // (#1010): the swap needs one composition, and a carrier switch is
1025
+ // already reported as "restart to apply" — so nothing is gained by
1026
+ // doing it live, and the host can die trying.
1027
+ ok = true;
968
1028
  }
969
1029
  else if (await themes.setEntryDisabled(name, false)) {
970
1030
  ok = true;
@@ -991,7 +1051,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
991
1051
  // durable layers half-written: the stack entry re-added, the rows
992
1052
  // it owns still disabled, and both the stock UI and the plugin's
993
1053
  // replacement off at the next boot (#1010).
994
- ok = result.ok || result.deferred === true;
1054
+ ok = result.ok || result.deferred === true || result.retained === true;
995
1055
  reason = result.reason ?? undefined;
996
1056
  // Deliberately NOT clearing replacedWhileLive here (#685). This used
997
1057
  // to say "a mount that succeeded imported the module as it is on
@@ -1043,10 +1103,20 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1043
1103
  * every time), and a group "off" wrote no patch row — the official page and
1044
1104
  * the market disagreed again, one control over (@snmtg1008, #696).
1045
1105
  *
1046
- * @param liveOk - whether the live switch succeeded; a failed ENABLE writes
1106
+ * @param switchLive - perform the runtime switch; a failed ENABLE writes
1047
1107
  * neither layer (#575).
1048
1108
  */
1049
- 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();
1050
1120
  let ok = liveOk;
1051
1121
  let reason = liveReason;
1052
1122
  // Durable patch-layer write (port of dsh-plugin-hub): the package's
@@ -1063,12 +1133,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1063
1133
  // side effect of a bug fix. Skipped only while something else is left to
1064
1134
  // flip: a package whose rows are ALL opt-in rows still has to be
1065
1135
  // switchable.
1066
- const optOutRows = new Set(bundleOptOutRowIds(join(activeProfileDir, 'node_modules', name)));
1136
+ const optOutRows = new Set(bundleOptOutRowIds(packageDir));
1067
1137
  // Rows the bundle decides itself, by expression (`disabled: !!js …`),
1068
1138
  // are a third shape next to opt-in rows: the market can neither read
1069
1139
  // nor overrule the condition, so enabling the package must leave them
1070
1140
  // exactly as the bundle ships them (#1043).
1071
- const expressionRows = new Set(bundleExpressionRowIds(join(activeProfileDir, 'node_modules', name)));
1141
+ const expressionRows = new Set(bundleExpressionRowIds(packageDir));
1072
1142
  const decided = patchRows.filter(rowId => !optOutRows.has(rowId));
1073
1143
  /** Rows that can carry a USER decision about this package — see above. */
1074
1144
  const userRows = decided.length > 0 ? decided : patchRows;
@@ -1151,7 +1221,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1151
1221
  // The name the loader composed for a row, for the rows whose user-layer
1152
1222
  // entry carries one of its own: the host skips an entry whose `name` is
1153
1223
  // not this one, so its flag is not a decision about the row (#1113).
1154
- const expectedNameFor = (rowId) => composedRowName(host, rowId);
1224
+ const expectedNameFor = (rowId) => namedRows.has(rowId) ? name : composedRowName(host, rowId);
1155
1225
  /** A user-layer flag counts only when the row it names is this entry. */
1156
1226
  const rowIsOurs = (rowId) => prePatch !== null && rowFlagApplies(prePatch, rowId, expectedNameFor(rowId));
1157
1227
  if (patchRows.length > 0 && patchGate && prePatch !== null) {
@@ -1179,11 +1249,15 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1179
1249
  // on that #876/#1043 say must never be forced on.
1180
1250
  const cleanOnly = optOutRows.has(rowId) || expressionRows.has(rowId);
1181
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);
1182
1256
  const result = enabled
1183
- ? await enableRow(userPatchPath, rowId, { cleanOnly, expectedName })
1184
- : await disableRow(userPatchPath, rowId, { expectedName });
1257
+ ? await enableRow(userPatchPath, rowId, { cleanOnly, expectedName, packageName: name })
1258
+ : await disableRow(userPatchPath, rowId, { expectedName, recordModuleName, packageName: name });
1185
1259
  if (result.ok) {
1186
- flipped.push(rowId);
1260
+ flipped.push({ rowId, removedMarketName: result.removedMarketName });
1187
1261
  continue;
1188
1262
  }
1189
1263
  patchWrite = result;
@@ -1200,21 +1274,23 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1200
1274
  // disable direction keeps what it got, because a row the patch
1201
1275
  // layer refuses to flip does not make the plugin live again.
1202
1276
  if (enabled) {
1203
- for (const rowId of flipped) {
1277
+ for (const { rowId, removedMarketName } of flipped) {
1204
1278
  // A row that was disabled gets its block back; a row that was
1205
1279
  // not loses the block this enable added. Leaving a
1206
1280
  // `disabled: false` behind would force-enable it in the
1207
1281
  // user's own patch layer — the same disagreement this route
1208
1282
  // exists to end, one row smaller.
1209
- if (prePatch !== null && rowIsOurs(rowId) && prePatch.disables.includes(rowId)) {
1210
- 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 });
1211
1287
  if (!back.ok)
1212
1288
  logEvent('warn', 'toggle', `${name}: patch row ${rowId} could not be put back — ${back.reason}`);
1213
1289
  }
1214
1290
  else if (prePatch === null || !rowIsOurs(rowId) || !prePatch.forced.includes(rowId)) {
1215
1291
  // A row already forced on before this call got nothing from
1216
1292
  // the enable; that block is the user's to keep.
1217
- const cleanedRow = removeRowBlocks(userPatchPath, [rowId]);
1293
+ const cleanedRow = removeRowBlocks(userPatchPath, [rowId], name);
1218
1294
  if (!cleanedRow.ok)
1219
1295
  logEvent('warn', 'toggle', `patch row could not be cleared — ${cleanedRow.reason}`);
1220
1296
  }
@@ -1293,7 +1369,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1293
1369
  * loader side, every boot-loaded bundle plugin would read as "restart".
1294
1370
  */
1295
1371
  function liveNames() {
1296
- const live = new Set(listHotMounts());
1372
+ const live = new Set(listLiveHotMounts());
1297
1373
  for (const entry of host.loader.entries()) {
1298
1374
  if (entry.fiber === undefined)
1299
1375
  continue;
@@ -1832,6 +1908,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1832
1908
  // #662: the removal is confirmed — drop the host bridge link the boot
1833
1909
  // projection may have left pointing at the now-gone package.
1834
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);
1835
1914
  // Kept on the host path too, and deliberately: `setEntryDisabled` only
1836
1915
  // scans the entries THIS process can see by name and returns false when
1837
1916
  // none match, so it costs a lookup — and it preserves what #213 is about.
@@ -1843,7 +1922,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1843
1922
  if (native) {
1844
1923
  logEvent('info', 'uninstall', `${name} ships or depends on a native addon; a restart is needed before it can be installed again`);
1845
1924
  }
1846
- const cleanedOwned = removeRowBlocks(userPatchPath, ownedRows);
1925
+ const cleanedOwned = removeRowBlocks(userPatchPath, ownedRows, name);
1847
1926
  if (!cleanedOwned.ok)
1848
1927
  logEvent('warn', 'uninstall', `patch rows could not be cleared — ${cleanedOwned.reason}`);
1849
1928
  else
@@ -1926,6 +2005,16 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1926
2005
  return [];
1927
2006
  }
1928
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
+ }
1929
2018
  /**
1930
2019
  * Whether a `#path:` target still points at a directory that exists.
1931
2020
  *
@@ -2295,6 +2384,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2295
2384
  const target = entry === null ? null : restoreTargetForLocal(entry, evidence.identities);
2296
2385
  return target !== null && NPM_NAME_RE.test(target) ? target : null;
2297
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 = [];
2298
2390
  /**
2299
2391
  * The two inputs `checkUpdates` needs beyond the profile itself: which
2300
2392
  * packages follow a release channel, and which local/generation installs
@@ -2323,8 +2415,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2323
2415
  // empty, and an empty map authorizes nothing.
2324
2416
  const catalogNpmByRepo = new Map();
2325
2417
  const releaseSources = new Map();
2418
+ const sourceMigrationFor = new Map();
2419
+ let lookupFailed = false;
2326
2420
  try {
2327
2421
  const registry = await loadRegistry();
2422
+ notificationCatalog = registry.plugins;
2328
2423
  for (const [name, spec] of Object.entries(installed)) {
2329
2424
  const source = onlineSourceOf(registry.plugins, name, spec);
2330
2425
  if (source !== null)
@@ -2334,6 +2429,17 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2334
2429
  const unique = new Map(releases.map(value => [JSON.stringify(value), value]));
2335
2430
  if (unique.size === 1)
2336
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
+ }
2337
2443
  }
2338
2444
  for (const plugin of registry.plugins) {
2339
2445
  if (plugin.npm === null || plugin.npm === undefined)
@@ -2344,10 +2450,85 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2344
2450
  }
2345
2451
  }
2346
2452
  catch (error) {
2453
+ lookupFailed = true;
2347
2454
  logEvent('warn', 'updates', `package source lookup failed — ${error instanceof Error ? error.message : String(error)}`);
2348
2455
  }
2349
- return { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources };
2456
+ return { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources, sourceMigrationFor, lookupFailed };
2350
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
+ });
2351
2532
  /**
2352
2533
  * Pre-install host compatibility refusal, shared by the update route and
2353
2534
  * the fresh-install route (#404/#473 convention, extended to installs).
@@ -2437,6 +2618,61 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2437
2618
  });
2438
2619
  };
2439
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
+ }),
2440
2676
  registerRoute({
2441
2677
  kind: 'exact',
2442
2678
  path: '/dsh-crate/api/v1/capabilities',
@@ -2502,8 +2738,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2502
2738
  return;
2503
2739
  }
2504
2740
  try {
2505
- const { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources } = await updateCheckInputs();
2506
- 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));
2507
2742
  // `packages` carries the same objects the single-package endpoint
2508
2743
  // returns, so one parser serves both. Only updatable ones: a badge
2509
2744
  // wants the count, a panel wants the rows, and neither wants to
@@ -2549,8 +2784,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2549
2784
  // The same inputs the market page builds, so a generation (#497)
2550
2785
  // or a catalog-matched local package answers here with the
2551
2786
  // release it can be compared against rather than with nothing.
2552
- const { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources } = await updateCheckInputs();
2553
- 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];
2554
2788
  if (update === undefined) {
2555
2789
  sendJson(response, 404, { schema: UPDATE_API_V1_SCHEMA, error: 'plugin is not installed' });
2556
2790
  return;
@@ -3042,7 +3276,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3042
3276
  try {
3043
3277
  const registry = await loadRegistry();
3044
3278
  sendJson(response, 200, {
3045
- registry,
3279
+ registry: discoveryCatalog(registry).response,
3046
3280
  hostVersion: dshHostInfo()?.version ?? null,
3047
3281
  });
3048
3282
  }
@@ -3128,31 +3362,65 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3128
3362
  sendJson(response, 400, { error: 'entries must be GitHub catalog URLs; at most 64 packages and entries per batch' });
3129
3363
  return;
3130
3364
  }
3131
- 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
+ }
3132
3373
  try {
3133
- const urls = new Set(requestedEntries);
3134
- const entries = urls.size === 0 ? [] : (await loadRegistry()).plugins.filter(entry => urls.has(entry.url) && (entry.npm == null || entry.npm === ''));
3135
- if (new Set(entries.map(entry => entry.url)).size !== urls.size) {
3136
- sendJson(response, 400, { error: 'entries must name GitHub-only plugins in the current catalog' });
3137
- return;
3138
- }
3139
3374
  const host = dshHostInfo();
3140
3375
  const hostVersion = host?.version ?? null;
3141
3376
  const hostPackages = corePackageNames(host?.directory ?? null);
3142
- const catalogFacts = Object.fromEntries(entries.flatMap(entry => {
3143
- const facts = catalogReleaseManifest(entry);
3144
- return facts === null ? [] : [[entry.url, facts]];
3145
- }));
3146
- const [npmFacts, githubFacts] = await Promise.all([
3147
- discoveryManifests.lookup(packages, routesFor(region).npmRegistry),
3148
- 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(),
3149
3415
  ]);
3150
- const facts = { ...npmFacts, ...githubFacts, ...catalogFacts };
3151
- const plugins = Object.fromEntries([...packages, ...urls].map(name => [
3152
- name,
3153
- deriveHostCompatibility(facts[name] ?? null, hostVersion, hostPackages),
3154
- ]));
3155
- 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 } });
3156
3424
  }
3157
3425
  catch (error) {
3158
3426
  sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
@@ -3213,7 +3481,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3213
3481
  // agrees: the dialog says "update to X", and clicking that used to
3214
3482
  // dead-end on a 409 the log never mentioned. Answer both questions
3215
3483
  // here, where the caller can say "in about N hours" up front.
3216
- const maturity = compatibleVersion === null
3484
+ // An update on a CLI host has the one-shot release-age bypass (#39)
3485
+ // and installs a young release, the same reason checkUpdates holds
3486
+ // young releases on the Desktop only: there "held" would disable an
3487
+ // Update button that works.
3488
+ const ageGated = !upgradeOnly || config.desktopHost === true;
3489
+ const maturity = compatibleVersion === null || !ageGated
3217
3490
  ? null
3218
3491
  : await readVersionMaturity(npmName, compatibleVersion, config.profile, activeProfileDir);
3219
3492
  logEvent('info', 'find-compatible', `${npmName}: host=${host.version}, after=${currentVersion ?? 'none'} → ${compatibleVersion ?? 'none'}`
@@ -3258,6 +3531,16 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3258
3531
  // every other package's manifest.
3259
3532
  const dependencyOwners = readDependencyOwners(config.profile, Object.keys(installed), activeProfileDir);
3260
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
+ }
3261
3544
  const declaresDshSurface = (packageName) => {
3262
3545
  const manifest = installedManifests.get(packageName);
3263
3546
  return typeof manifest === 'object' && manifest !== null
@@ -3268,16 +3551,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3268
3551
  // by removing it from that list, and nothing the market recorded
3269
3552
  // says so (#696). Reported as off, unless it is live right now — a
3270
3553
  // hot mount from this session still runs until the next restart.
3271
- const composedBundles = new Set(readProfileBundles(activeProfileDir));
3272
- const unbundled = Object.keys(installed).filter(name => {
3273
- if (INBOX_BUNDLES.has(name) || composedBundles.has(name) || live.has(name))
3274
- return false;
3275
- const manifest = installedManifests.get(name);
3276
- // A bundle whose own patch is empty loads nothing either way, so
3277
- // its absence from the list says nothing about a switch (#813).
3278
- return typeof manifest === 'object' && manifest !== null && manifest.dsh?.bundle !== undefined
3279
- && !bundlePatchIsEmpty(join(activeProfileDir, 'node_modules', name));
3280
- });
3554
+ const unbundled = unbundledPackages(Object.keys(installed), installedManifests, live);
3281
3555
  for (const name of Object.keys(installed)) {
3282
3556
  const manifest = installedManifests.get(name);
3283
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));
@@ -3332,16 +3606,22 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3332
3606
  sendJson(response, 200, {
3333
3607
  profile: config.profile,
3334
3608
  installed,
3609
+ descriptions,
3335
3610
  repoIdentities,
3336
3611
  repoHints,
3337
3612
  present,
3338
3613
  activation,
3339
3614
  diagnostics,
3340
- live: listHotMounts(),
3615
+ live: listLiveHotMounts(),
3341
3616
  disabled: [...disabled],
3342
3617
  groups,
3343
3618
  groupOrder,
3344
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 ?? {},
3345
3625
  favorites: readMarketState(activeProfileDir).favorites ?? [],
3346
3626
  blocked: readMarketState(activeProfileDir).blocked ?? [],
3347
3627
  updateExempt: readMarketState(activeProfileDir).updateExempt ?? [],
@@ -3762,9 +4042,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3762
4042
  return;
3763
4043
  }
3764
4044
  pendingRollbacks.clear();
3765
- const activated = await themes.activateTheme(name);
4045
+ const { ok: activated, reason } = await themes.activateTheme(name);
3766
4046
  logEvent(activated ? 'info' : 'error', 'use-skin', `${name}: ${activated ? 'active' : 'failed'}`);
3767
- 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
+ });
3768
4050
  }
3769
4051
  catch (error) {
3770
4052
  const message = error instanceof Error ? error.message : String(error);
@@ -3832,24 +4114,18 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3832
4114
  }
3833
4115
  }
3834
4116
  pendingRollbacks.clear();
3835
- let ok;
3836
- let reason;
3837
- if (enabled && (await themes.installedThemeNames()).has(name)) {
4117
+ let themeFailure;
4118
+ const layers = enabled && (await themes.installedThemeNames()).has(name)
3838
4119
  // Theme exclusivity stays a Themes-page concern: enabling a theme
3839
4120
  // deactivates the previously active one, so only the last-enabled
3840
4121
  // theme is live (same semantics as use-skin).
3841
- ok = await themes.activateTheme(name);
3842
- if (!ok)
3843
- reason = 'theme activation failed — restart required / 主题启用失败,需要重启';
3844
- }
3845
- else {
3846
- const result = await setPluginEnabled(name, enabled);
3847
- ok = result.ok;
3848
- reason = result.reason;
3849
- }
3850
- const layers = await switchPluginLayers(name, enabled, ok, reason);
3851
- ok = layers.ok;
3852
- 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;
3853
4129
  const { patchRows, userRows, patchWrite, carrierRows, isCarrier, bundleSwitch } = layers;
3854
4130
  // Activation reads the post-write truth: the switch state OR the
3855
4131
  // patch layer, so a disabled plugin never reports "restart to
@@ -3862,7 +4138,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3862
4138
  // (enable failed to hot-mount / disable left the fiber up), the
3863
4139
  // change lands on the next boot via the patch layer + state.json —
3864
4140
  // the client reuses the market's pending-restart banner for it.
3865
- const liveAfter = liveNames().has(name);
4141
+ const liveNow = liveNames();
4142
+ const liveAfter = liveNow.has(name);
3866
4143
  // A carrier toggle moves the bundle in/out of dsh.profile.bundles,
3867
4144
  // which only takes effect on the next composition — always a restart.
3868
4145
  // Non-carrier plugins keep the live-mount based decision.
@@ -3873,7 +4150,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3873
4150
  // module-scope version marker). Enabling cannot make it current;
3874
4151
  // only a restart can.
3875
4152
  const staleModule = enabled && replacedWhileLive.has(name);
3876
- 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));
3877
4159
  // A client-part plugin's UI is in the page already — toggling it
3878
4160
  // needs a browser refresh to show the change (same signal the
3879
4161
  // install flow uses for the hot banner).
@@ -3883,14 +4165,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3883
4165
  name,
3884
4166
  enabled,
3885
4167
  disabled: [...disabled],
3886
- live: listHotMounts(),
4168
+ live: listLiveHotMounts(),
3887
4169
  // The same verdict the listing gives (#685): the reply used the
3888
4170
  // loader inventory alone and said `live` for a plugin serving
3889
4171
  // its old build, while a refresh of the listing — which applies
3890
4172
  // activationAfterReplace — said `restart`. One moment, one story.
3891
- activation: {
3892
- [name]: activationAfterReplace(verifyActivation(config.profile, name, liveNames(), activeProfileDir, offNow, undefined, loaderEntryObserved(name)), replacedWhileLive.has(name)),
3893
- },
4173
+ activation: { [name]: reported },
3894
4174
  reason,
3895
4175
  patchRows,
3896
4176
  patchWrite: patchWrite ?? { ok: true, reason: null },
@@ -4222,13 +4502,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4222
4502
  continue;
4223
4503
  let result;
4224
4504
  if (enabled && themeNames.has(member)) {
4225
- result = { ok: await themes.activateTheme(member), reason: undefined };
4505
+ result = await themes.activateTheme(member);
4226
4506
  }
4227
4507
  else {
4228
4508
  // The same two durable layers the single switch writes (#696):
4229
4509
  // which control flipped a plugin must not change what is on disk.
4230
- const live = await setPluginEnabled(member, enabled);
4231
- result = await switchPluginLayers(member, enabled, live.ok, live.reason);
4510
+ result = await switchPluginLayers(member, enabled);
4232
4511
  }
4233
4512
  if (!result.ok)
4234
4513
  failures.push(member);
@@ -4458,43 +4737,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4458
4737
  }
4459
4738
  try {
4460
4739
  const force = (request.url ?? '').includes('force=1');
4461
- const { channelFor, onlineSourceFor, catalogNpmByRepo, releaseSources } = await updateCheckInputs();
4462
- // Migration hints are this listing's own business: the market page
4463
- // is where "this could come from npm now" is offered, and no other
4464
- // caller acts on it.
4465
- const sourceMigrationFor = new Map();
4466
- try {
4467
- const registry = await loadRegistry();
4468
- const installed = readInstalled(config.profile, activeProfileDir);
4469
- for (const [name, spec] of Object.entries(installed)) {
4470
- const migration = findGitToNpmMigration(registry.plugins, spec);
4471
- if (migration !== null)
4472
- sourceMigrationFor.set(name, migration);
4473
- }
4474
- // A rename declared by the catalog (#1012, P1). This is the only
4475
- // path that reaches a user whose old range no longer resolves:
4476
- // their update fails before installing anything, so no offer was
4477
- // ever recorded. The catalog states the rename up front, and the
4478
- // row still has to be a plain registry range the transaction can
4479
- // replace — and the successor must not already be installed.
4480
- for (const [name, spec] of Object.entries(installed)) {
4481
- if (sourceMigrationFor.has(name) || !isRegistryRangeSpec(spec))
4482
- continue;
4483
- const rename = findCatalogRename(registry.plugins, name);
4484
- if (rename === null || installed[rename.target] !== undefined)
4485
- continue;
4486
- sourceMigrationFor.set(name, { kind: 'npm-rename', from: name, target: rename.target });
4487
- }
4488
- }
4489
- catch (error) {
4490
- logEvent('warn', 'updates', `package source lookup failed — ${error instanceof Error ? error.message : String(error)}`);
4491
- }
4492
- const updates = await checkUpdates(config.profile, force, activeProfileDir, channelFor, onlineSourceFor, catalogNpmByRepo, { holdYoungReleases: config.desktopHost === true, releaseSources });
4493
- for (const [name, migration] of sourceMigrationFor) {
4494
- const status = updates[name];
4495
- if (status !== undefined)
4496
- updates[name] = { ...status, sourceMigration: migration };
4497
- }
4740
+ const updates = await updateNotifications.check(force);
4498
4741
  sendJson(response, 200, { updates });
4499
4742
  }
4500
4743
  catch (error) {
@@ -4523,7 +4766,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4523
4766
  sendJson(response, 400, { error: 'name query parameter is required' });
4524
4767
  return;
4525
4768
  }
4526
- 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));
4527
4773
  }
4528
4774
  catch (error) {
4529
4775
  sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
@@ -4820,7 +5066,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4820
5066
  stateWarning = `市场状态未能持久化:${error instanceof Error ? error.message : String(error)} / Market state could not be persisted: ${error instanceof Error ? error.message : String(error)}`;
4821
5067
  logEvent('warn', 'source-migration', `${name}: ${stateWarning}`);
4822
5068
  }
4823
- const cleanedOld = removeRowBlocks(userPatchPath, oldRows);
5069
+ const cleanedOld = removeRowBlocks(userPatchPath, oldRows, name);
4824
5070
  if (!cleanedOld.ok)
4825
5071
  logEvent('warn', 'install', `patch rows could not be cleared — ${cleanedOld.reason}`);
4826
5072
  const patchDisabled = wasDisabled || patchFlags.disabled.includes(name);
@@ -4829,9 +5075,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4829
5075
  for (const rowId of rowIdsForPackage(host, activeProfileDir, targetName)) {
4830
5076
  const expectedName = composedRowName(host, rowId);
4831
5077
  const changed = patchDisabled
4832
- ? await disableRow(userPatchPath, rowId, { expectedName })
5078
+ ? await disableRow(userPatchPath, rowId, { expectedName, packageName: targetName })
4833
5079
  : patchForced
4834
- ? await enableRow(userPatchPath, rowId, { expectedName })
5080
+ ? await enableRow(userPatchPath, rowId, { expectedName, packageName: targetName })
4835
5081
  : { ok: true, reason: null };
4836
5082
  if (!changed.ok && changed.reason !== null)
4837
5083
  patchWarnings.push(changed.reason);
@@ -6124,6 +6370,25 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6124
6370
  const ignoredBuilds = ok || cancelled || !failedOnBlockedBuilds(result) ? undefined : blockedBuilds(result);
6125
6371
  if (ok)
6126
6372
  clearBrokenPlugin(name);
6373
+ // #1093: the same leftover rows, on the update side. The old
6374
+ // version's `minimumReleaseAgeExclude` row outlives the update and
6375
+ // points at a build that is no longer on disk. Rows naming the
6376
+ // version that IS installed stay: a fresh release may need exactly
6377
+ // that row at the next install.
6378
+ if (ok && !restore) {
6379
+ try {
6380
+ const installedNow = readInstalledVersion(config.profile, name, activeProfileDir);
6381
+ if (installedNow !== null) {
6382
+ const staleExcludes = dropReleaseAgeExcludes(config.profile, name, activeProfileDir, installedNow);
6383
+ if (staleExcludes.length > 0) {
6384
+ logEvent('info', 'update', `${name}: dropped ${String(staleExcludes.length)} minimumReleaseAgeExclude row(s) for versions no longer installed`);
6385
+ }
6386
+ }
6387
+ }
6388
+ catch (error) {
6389
+ logEvent('warn', 'update', `${name}: could not clear old minimumReleaseAgeExclude rows — ${error instanceof Error ? error.message : String(error)}`);
6390
+ }
6391
+ }
6127
6392
  // A package still installed but no longer in dsh.profile.bundles
6128
6393
  // after this run stops loading and says nothing (#720). The market
6129
6394
  // does not write that list from anything but the current list, so
@@ -6173,6 +6438,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6173
6438
  }
6174
6439
  }
6175
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]);
6176
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)}`}`);
6177
6448
  // A user-cancelled run is a quiet outcome, not an error.
6178
6449
  sendJson(response, ok || cancelled ? 200 : result.busy === true ? 409 : 502, {
@@ -6612,7 +6883,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6612
6883
  // button whose failure leaves the user with no other way out of the
6613
6884
  // page they are looking at (#903).
6614
6885
  sendJson(response, 403, {
6615
- 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.`,
6616
6887
  });
6617
6888
  return;
6618
6889
  }
@@ -6664,7 +6935,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6664
6935
  for (const name of disabled) {
6665
6936
  const ids = rowIdsForPackage(host, activeProfileDir, name);
6666
6937
  if (ids.length > 0) {
6667
- const cleanedIds = removeRowBlocks(userPatchPath, ids);
6938
+ const cleanedIds = removeRowBlocks(userPatchPath, ids, name);
6668
6939
  if (!cleanedIds.ok)
6669
6940
  logEvent('warn', 'patch', `patch rows could not be cleared — ${cleanedIds.reason}`);
6670
6941
  restored.push(name);
@@ -7154,6 +7425,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7154
7425
  // from disk truth) — the host node_modules bridge the boot
7155
7426
  // projection left for this package must not outlive it.
7156
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);
7157
7431
  // A host that owns the composition replays it: asking first is
7158
7432
  // what keeps the market from looking for an entry it never
7159
7433
  // created, and then telling the user to restart about a plugin
@@ -7191,7 +7465,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7191
7465
  // Patch-layer rows must not survive the remove either: a
7192
7466
  // `- id: X` + `disabled: true` row for a package that no longer
7193
7467
  // mounts is a boot-time orphan (port of dsh-plugin-hub).
7194
- const cleanedOwned = removeRowBlocks(userPatchPath, ownedRows);
7468
+ const cleanedOwned = removeRowBlocks(userPatchPath, ownedRows, name);
7195
7469
  if (!cleanedOwned.ok)
7196
7470
  logEvent('warn', 'uninstall', `patch rows could not be cleared — ${cleanedOwned.reason}`);
7197
7471
  // Either way the record is settled: cleaned means nothing is
@@ -7205,6 +7479,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7205
7479
  disabled.delete(name);
7206
7480
  removeFromGroups({ groups, groupOrder }, name);
7207
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);
7208
7486
  // #1093: pnpm writes a `minimumReleaseAgeExclude` row when it
7209
7487
  // installs a version still inside the wait window, and removing
7210
7488
  // the dependency never touches that file. Left behind, the row
@@ -7357,6 +7635,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7357
7635
  sendJson(response, 403, { error: 'untrusted origin' });
7358
7636
  return;
7359
7637
  }
7638
+ // Set once the package is on disk, so a failure after that point is not reported as a failed install.
7639
+ let installLanded = false;
7360
7640
  try {
7361
7641
  const body = (await readJsonBody(request));
7362
7642
  const drainCall = drainCallOf(request);
@@ -7533,6 +7813,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7533
7813
  // dialog just found for this host — a loop with the user in it.
7534
7814
  if (npmName !== null && await refuseHostIncompatible(npmName, entry.name, requestedVersion, force, response, region, 'install-compat'))
7535
7815
  return;
7816
+ if (await refuseWorkspaceRoot(target, entry.name, response))
7817
+ return;
7536
7818
  const beforeSpecs = readInstalled(config.profile, activeProfileDir);
7537
7819
  const before = new Set(Object.keys(beforeSpecs));
7538
7820
  if (retryAlias !== null)
@@ -7681,6 +7963,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7681
7963
  if (lockfileBefore.ok)
7682
7964
  restoreProfileLockfile(lockfileBefore.snapshot);
7683
7965
  target = await acceleratedTarget(sourceTarget, region);
7966
+ if (await refuseWorkspaceRoot(target, entry.name, response))
7967
+ return;
7684
7968
  if (!assertDrainMutation(request, response))
7685
7969
  return;
7686
7970
  result = await runPlugin(config.profile, ['add', target]);
@@ -7755,9 +8039,14 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7755
8039
  let compatibility;
7756
8040
  let addedPackages = [];
7757
8041
  if (ok) {
8042
+ installLanded = true;
7758
8043
  const added = Object.keys(installed).filter(name => !before.has(name));
7759
8044
  addedPackages = added;
7760
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);
7761
8050
  // Fresh installs start enabled: drop any stale disable flag
7762
8051
  // (e.g. reinstall after an uninstall while this process kept
7763
8052
  // running) and persist before the activation loop.
@@ -7766,6 +8055,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7766
8055
  writeMarketState(activeProfileDir, { disabled, groups, groupOrder });
7767
8056
  // Theme installs auto-activate (and deactivate the previous
7768
8057
  // theme) so the result is visible right after the refresh.
8058
+ const themeFailures = new Map();
7769
8059
  if (hostActivation) {
7770
8060
  // The host's watcher owns the entire composition. Waiting
7771
8061
  // for its replay gives the market a real live/fail verdict
@@ -7833,7 +8123,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7833
8123
  }
7834
8124
  }
7835
8125
  else if (!adopted) {
7836
- 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);
7837
8130
  }
7838
8131
  if (!live)
7839
8132
  hot = false;
@@ -7845,7 +8138,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7845
8138
  // cannot disagree with it within one request.
7846
8139
  const hostFacts = defaultHostRuntimeFacts(activeProfileDir);
7847
8140
  for (const name of added) {
7848
- 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] };
7849
8146
  }
7850
8147
  }
7851
8148
  }
@@ -7892,8 +8189,25 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7892
8189
  }
7893
8190
  }
7894
8191
  }
7895
- if (ok)
7896
- clearBrokenPlugin(entry.name);
8192
+ // #1164: brokenPlugins is keyed by the PROFILE DEPENDENCY name —
8193
+ // the update path drops the declaration and records `name` there,
8194
+ // so the notice can be found by the package the user actually has.
8195
+ // A catalog entry is not that key: `entry.name` is the DISPLAY
8196
+ // name (the GitHub repo's casing, e.g. "DSH-better-sidebar") while
8197
+ // the package it installs is `entry.npm`. Clearing by the display
8198
+ // name was a silent no-op for every entry whose two differ, so the
8199
+ // spent notice outlived reloads, restarts and market upgrades
8200
+ // until the user dismissed it by hand. Clear by what this run
8201
+ // actually put into the profile, plus the entry's own package name
8202
+ // (a git-source entry has no `npm`, and `addedPackages` is empty
8203
+ // when the recovery path re-added a name the snapshot already had).
8204
+ if (ok) {
8205
+ const reinstalled = new Set(addedPackages);
8206
+ if (npmName !== null)
8207
+ reinstalled.add(npmName);
8208
+ for (const pkg of reinstalled)
8209
+ clearBrokenPlugin(pkg);
8210
+ }
7897
8211
  logEvent(ok || cancelled ? 'info' : 'error', 'install', `${target} exit=${String(result.exitCode)}${result.timedOut ? ' TIMEOUT' : ''}${cancelled ? ' CANCELLED' : ''}${ok ? ` hot=${String(hot)}` : cancelled ? '' : ` err=${failureDetail(result)}`}`);
7898
8212
  // On success a skipped build is a notice (#6); after a FAILURE the
7899
8213
  // list is what offers the approve-and-retry banner, so it is sent
@@ -7984,13 +8298,23 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7984
8298
  if (!inProbe())
7985
8299
  host.logger?.warn(`[dsh-crate] install failed: ${message}`);
7986
8300
  logEvent('error', 'install', `route error: ${message}`);
8301
+ // A plugin that brings its own host half can make the host reload the
8302
+ // market while this request is still checking the result. The old
8303
+ // instance is gone, so what it throws now says nothing about the
8304
+ // install: the package landed, and the new instance reports the
8305
+ // real state of the plugin on the next refresh.
8306
+ if (installLanded && disposed) {
8307
+ sendJson(response, 200, { ok: true, hot: true, marketReloaded: true });
8308
+ return;
8309
+ }
7987
8310
  sendJson(response, 500, { error: message });
7988
8311
  }
7989
8312
  },
7990
8313
  })),
7991
8314
  ];
7992
- return () => {
8315
+ return async () => {
7993
8316
  disposed = true;
8317
+ updateNotifications.dispose();
7994
8318
  // Release Agent maintenance holds before the routes disappear. This is the
7995
8319
  // disposer half of the single-finally + disposer guarantee (#411): an
7996
8320
  // unloaded market must never leave an Agent parked behind a hold.
@@ -7999,5 +8323,6 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7999
8323
  configurePersistentLog(null);
8000
8324
  for (const dispose of disposers)
8001
8325
  dispose();
8326
+ await Promise.all([discoveryManifests.dispose(), githubDiscoveryManifests.dispose()]);
8002
8327
  };
8003
8328
  }