dsh-crate 0.5.4 → 0.5.6

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 (44) hide show
  1. package/client/client.js +1832 -617
  2. package/lib/changelog.js +71 -28
  3. package/lib/gist.js +1 -1
  4. package/lib/hot.js +18 -6
  5. package/lib/index.js +10 -3
  6. package/lib/install.js +200 -9
  7. package/lib/official-desktop.js +80 -16
  8. package/lib/patch.js +223 -25
  9. package/lib/pending-checkout-links.js +123 -0
  10. package/lib/pending-updates.js +7 -4
  11. package/lib/profile.js +36 -0
  12. package/lib/registry.js +53 -22
  13. package/lib/release-blockers.js +177 -0
  14. package/lib/release-history.js +149 -0
  15. package/lib/release-updates.js +1 -34
  16. package/lib/routes.js +843 -166
  17. package/lib/sources.js +42 -2
  18. package/lib/startup-repair-report.js +46 -0
  19. package/lib/themes.js +7 -5
  20. package/lib/types/changelog.d.ts +4 -1
  21. package/lib/types/dsh-cli.d.ts +8 -0
  22. package/lib/types/gist.d.ts +1 -1
  23. package/lib/types/hot.d.ts +2 -1
  24. package/lib/types/install.d.ts +22 -4
  25. package/lib/types/official-desktop.d.ts +4 -0
  26. package/lib/types/patch.d.ts +36 -0
  27. package/lib/types/pending-checkout-links.d.ts +35 -0
  28. package/lib/types/pending-updates.d.ts +2 -0
  29. package/lib/types/profile.d.ts +3 -0
  30. package/lib/types/registry.d.ts +6 -8
  31. package/lib/types/release-blockers.d.ts +34 -0
  32. package/lib/types/release-history.d.ts +34 -0
  33. package/lib/types/release-updates.d.ts +2 -11
  34. package/lib/types/routes.d.ts +3 -0
  35. package/lib/types/sources.d.ts +11 -0
  36. package/lib/types/startup-repair-report.d.ts +20 -0
  37. package/lib/types/themes.d.ts +2 -2
  38. package/lib/types/update-notifications.d.ts +6 -0
  39. package/lib/types/updates.d.ts +19 -0
  40. package/lib/update-notifications.js +6 -4
  41. package/lib/updates.js +16 -0
  42. package/locale/en.json +1 -1
  43. package/locale/ja.json +5 -0
  44. package/package.json +2 -2
package/lib/routes.js CHANGED
@@ -8,14 +8,15 @@
8
8
  * same-origin POSTs and only sources present in the curated registry.
9
9
  */
10
10
  import { createHash } from 'node:crypto';
11
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
12
12
  import { dirname, join } from 'node:path';
13
13
  import { Readable } from 'node:stream';
14
+ import { isDeepStrictEqual } from 'node:util';
14
15
  import { load as loadYaml } from 'js-yaml';
15
16
  import { packageFileFromRegistry } from './catalog-npm.js';
16
- import { statePath } from './state.js';
17
17
  import { forgetCatalog, loadRegistry, pluginCategories } from './registry.js';
18
18
  import { settingsNamespaceState } from './settings.js';
19
+ import { statePath } from './state.js';
19
20
  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';
20
21
  import { createGroup, deleteGroup, removeFromGroups, renameGroup, setGroupMembers } from './groups.js';
21
22
  import { dshHostInfo, findDshInstallDir } from './dsh-install.js';
@@ -27,7 +28,8 @@ import { diagnosePackageManifests } from './diagnostics.js';
27
28
  import { BOOT_ID, cancelActive, probePnpm, progress, provisionPnpm, runDshPlugin, setBuildEnvSource, TARGET_RE, } from './dsh-cli.js';
28
29
  import { packageOfEntryName } from './entry-identity.js';
29
30
  import { PendingRowJournal, repairOrphanedRows } from './pending-rows.js';
30
- import { addProfileBundle, bundleExpressionRowIds, bundleOptOutRowIds, bundlePatchInsertedIds, bundlesDroppedFromProfile, declareProfileDependency, dropFromManifest, dropReleaseAgeExcludes, generationManagedNames, hasLoadableEntry, holdsNativeAddon, INBOX_BUNDLES, isDshProfileName, profileDir, readDependencyOwners, readGitResolutionCommit, readInstalled, readInstalledManifest, readInstalledPackageName, readInstalledRepoEvidence, readInstalledVersion, readLockCommits, readProfileBundles, readProfileManifestSnapshot, removeProfileBundle, parsePatchRows, restoreProfileManifest, setAllowBuilds, shippedInsertedRowIds } from './profile.js';
31
+ import { hasUnsettledPackageRun, loadHostProfileLock, PendingCheckoutLinks, withIdleProfile, } from './pending-checkout-links.js';
32
+ import { addProfileBundle, bundleExpressionRowIds, bundleOptOutRowIds, bundlePatchInsertedIds, bundlesDroppedFromProfile, declareProfileDependency, dropFromManifest, dropReleaseAgeExcludes, generationManagedNames, hasLoadableEntry, holdsNativeAddon, INBOX_BUNDLES, isDshProfileName, profileDir, readDependencyOwners, readGitResolutionCommit, readInstalled, readInstalledManifest, readInstalledPackageName, readInstalledRepoEvidence, readInstalledVersion, readLockCommits, readProfileBundles, readProfileManifestSnapshot, removeProfileBundle, parsePatchRows, restoreProfileManifest, restoreRemovedProfileBundle, setAllowBuilds, shippedInsertedRowIds } from './profile.js';
31
33
  import { assessProfile, classifyPeer, introducedDuplicateNames, introducedRisks } from './compatibility.js';
32
34
  import { runningAgentIds } from './agents.js';
33
35
  import { DrainCoordinator, DrainNoop, DrainRefusal } from './drain.js';
@@ -40,7 +42,7 @@ import { createProfileSnapshot, DEFAULT_MAX_SNAPSHOTS, deleteSnapshot, listSnaps
40
42
  import { readHostRecoveryView, restoreHostRecoveryBackup } from './host-recovery.js';
41
43
  import { trialValidate } from './trial.js';
42
44
  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';
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';
45
+ import { checkoutSourceExists, detachCheckoutLink, failureDetail, groupConflictsByOwner, installApplied, isHostPortCollision, isStaleUpdate, keepCheckoutDetached, parseIgnoredBuildEntries, parseIgnoredBuilds, parsePrepareKey, parsePrepareNotAllowed, pnpmBlockedByOpenFiles, pnpmNeverStarted, pnpmRefusedYoungRelease, recordedCheckoutLink, RELEASE_AGE_OVERRIDE, removeDanglingHostBridge, removeLeftoverProfileLink, restoreCheckoutLink, retargetCollections, updateApplied, validateAddedPlugins, withHoistRecovery } from './install.js';
44
46
  import { classifyPnpmFailure } from './pnpm-compat.js';
45
47
  import { asChannel, CHANNELS, DIST_TAG, resolveChannel } from './channels.js';
46
48
  import { asRegion, githubProxyManaged, normalizeGithubProxy, REGIONS, routesFor, setActiveRegion, setCustomGithubProxy, } from './regions.js';
@@ -48,7 +50,9 @@ import { resolveRegion } from './region-probe.js';
48
50
  import { acceleratedTarget, resolveHeadCommit } from './accelerate.js';
49
51
  import { mismatchedWorkspaceRoot } from './github-install-target.js';
50
52
  import { sourceWebUrl, updateNotesFor } from './changelog.js';
51
- import { checkUpdates, isUpdatablePlugin, compareVersions, fetchNpmLatest, invalidateUpdates, readVersionMaturity, resolveDesktopMatureUpdate, resolveGitRemoteHead, isUpgrade, latestPublishedRecently, setUpdateRegistry, versionOnChannel } from './updates.js';
53
+ import { isCommitId } from './release-history.js';
54
+ import { activeReleaseBlockers, headlineBlocker, releaseBlockedMessage } from './release-blockers.js';
55
+ import { applyProfileBlockers, checkUpdates, isUpdatablePlugin, compareVersions, fetchNpmLatest, invalidateUpdates, readVersionMaturity, resolveDesktopMatureUpdate, resolveGitRemoteHead, isUpgrade, latestPublishedRecently, setUpdateRegistry, versionOnChannel } from './updates.js';
52
56
  import { isExactReleaseVersion, isStableReleaseVersion } from './release-candidates.js';
53
57
  import { createUpdateNotificationMonitor } from './update-notifications.js';
54
58
  import { DEFAULT_UPDATE_CHECK_INTERVAL_HOURS, isUpdateCheckIntervalHours } from './update-notification-settings.js';
@@ -57,7 +61,7 @@ import { readJsonBody, refuseUnadmitted, sameOrigin, sendJson } from './http.js'
57
61
  import { resolveDshHome } from './home-paths.js';
58
62
  import { detectedDebugger, detectedSupervisor, restartAllowed, scheduleRestart, servingPort, trustedRestartRequest, trustedDownloadRequest, trustedSelfUninstallRequest, selfUninstallReachableFrom, restartReachableFrom } from './restart.js';
59
63
  import { activationAfterReplace, brokenClientBundles, bundlePatchIsEmpty, checkClientBundle, defaultHostRuntimeFacts, findUnservedConfigNamespaces, hasHostHalf, hostPeerGate, isDeclaredLibraryDsh, newlyBrokenBundles, peerGateRemedy, verifyActivation } from './verify.js';
60
- import { carrierRowIds, composedRowName, disableRow, enableRow, findUserPatchPath, foreignRowIds, isProtectedModule, loaderEntryId, packagePatchFlags, rowFlagApplies, readUserPatchState, removeRowBlocks, rowIdsForPackage, userPatchPackageReferences, } from './patch.js';
64
+ import { carrierRowIds, commitComponentSwitchPatch, composedRowName, disableRow, enableRow, findUserPatchPath, foreignRowIds, isProtectedModule, loaderEntryId, packagePatchFlags, rowFlagApplies, readComponentSwitchPatch, readUserPatchState, removeRowBlocks, rollbackComponentSwitchPatch, rowIdsForPackage, userPatchPackageReferences, writeComponentSwitchPatch, } from './patch.js';
61
65
  import { createProfileBackup, downloadWebdav, MAX_BACKUP_BYTES, mergeRestoreManifest, pinRunningDeps, restoreProfileBackup, unportableDeps, uploadWebdav, WebdavUrlError, } from './backup.js';
62
66
  import { createGist, fitsGistLimit, GistError, gistErrorCode, parseGistId, readGist, resolveGistTokenSource, updateGist, verifyGistToken, } from './gist.js';
63
67
  import { MAX_UPDATE_OPERATIONS_V1, UpdateOperationStoreV1, UPDATE_API_V1_SCHEMA } from './update-api-v1.js';
@@ -248,6 +252,9 @@ function declaresBundle(profileDirectory, name) {
248
252
  const PROFILE_HMR_ENTRY = '@deepseek-ai/dsh-hmr';
249
253
  /** How long to wait for that replay before mounting: the same ceiling as #814. */
250
254
  const PROFILE_HMR_REPLAY_WAIT_MS = 8000;
255
+ const ACTIVE_FIBER_STATE = 2;
256
+ const CHECKOUT_REPAIR_WAIT_MS = 30_000;
257
+ const CHECKOUT_REPAIR_INTERVAL_MS = 1_000;
251
258
  /**
252
259
  * The allowBuilds key pnpm itself printed when it refused a build, per package
253
260
  * name — from a prepare refusal that named one, or from an ignored-builds line
@@ -482,6 +489,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
482
489
  // re-applies the same choice on every boot (ported from dsh-plugin-hub).
483
490
  const userPatchPath = findUserPatchPath(host, activeProfileDir);
484
491
  const commands = commandRuntime ?? { runPlugin: runDshPlugin, probePnpm, provisionPnpm, cancelActive };
492
+ const checkoutLinks = new PendingCheckoutLinks(activeProfileDir);
485
493
  const drainCalls = new WeakMap();
486
494
  const drainCallOf = (request) => drainCalls.get(request);
487
495
  const drainPhaseOf = (request) => {
@@ -844,6 +852,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
844
852
  /** Routes currently running a drain probe; `/status.busy` covers them. */
845
853
  let preflightActive = 0;
846
854
  let mutationBusy = false;
855
+ let checkoutRepairTimer;
856
+ let checkoutRepairRound;
857
+ let checkoutRecovery;
858
+ let checkoutHostLock;
859
+ let checkoutHostLockUnavailableLogged = false;
847
860
  /** The shared mutation chain: every mutating operation appends to it. */
848
861
  let mutationChain = Promise.resolve();
849
862
  /**
@@ -999,7 +1012,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
999
1012
  * user asked for OFF, and a failed unmount leaves the plugin live only for
1000
1013
  * this session. There the durable disable is the contract, not an error.
1001
1014
  */
1002
- async function setPluginEnabled(name, enabled) {
1015
+ async function setPluginEnabled(name, enabled, keepOff, hostReplays = false) {
1003
1016
  const dir = activeProfileDir;
1004
1017
  const wasDisabled = disabled.has(name);
1005
1018
  if (enabled)
@@ -1009,7 +1022,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1009
1022
  let ok;
1010
1023
  let reason;
1011
1024
  if (enabled) {
1012
- if (listHotMounts().includes(name)) {
1025
+ if (!hostReplays && listHotMounts().includes(name)) {
1013
1026
  ok = true;
1014
1027
  reason = hotMountFailure(name, dir) ?? undefined;
1015
1028
  }
@@ -1026,7 +1039,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1026
1039
  // doing it live, and the host can die trying.
1027
1040
  ok = true;
1028
1041
  }
1029
- else if (await themes.setEntryDisabled(name, false)) {
1042
+ else if (!hostReplays && await themes.setEntryDisabled(name, false, false, false, keepOff)) {
1030
1043
  ok = true;
1031
1044
  }
1032
1045
  else {
@@ -1043,8 +1056,15 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1043
1056
  ok = false;
1044
1057
  reason = `${name} 新版要求宿主 ${gate.range},当前运行 ${gate.runtimeVersion},开了也不会生效;${remedy.zh} / ${name} needs host ${gate.range} but this host runs ${gate.runtimeVersion} — enabling it now would not take effect; ${remedy.en}`;
1045
1058
  }
1059
+ else if (hostReplays) {
1060
+ // The watcher may coalesce a fast off/on into the original
1061
+ // composition. Resume any entries it still owns and never
1062
+ // create a second tree to race its replay.
1063
+ await themes.setEntryDisabled(name, false, false, false, keepOff);
1064
+ ok = true;
1065
+ }
1046
1066
  else {
1047
- const result = await hotMount(host, dir, name);
1067
+ const result = await hotMount(host, dir, name, keepOff);
1048
1068
  // A package that can only come up on a start (config rows, a
1049
1069
  // carrier's disables) was never tried, so there is no crash to
1050
1070
  // refuse to persist (#575). Failing the enable here left the
@@ -1065,21 +1085,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1065
1085
  }
1066
1086
  }
1067
1087
  }
1068
- else if (carrierRowIds(dir, name).length > 0) {
1069
- // A carrier replaces something: its patch disables stock rows and its
1070
- // own rows stand in for them. Stopping its rows here, while the stock
1071
- // ones are still disabled, leaves a window with neither — the page
1072
- // throws and does not come back (#1010). The swap needs one
1073
- // composition, which only the layers below and a restart provide.
1074
- ok = true;
1075
- }
1076
1088
  else {
1077
- ok = await hotUnmount(name) || await themes.setEntryDisabled(name, true);
1078
- if (!ok) {
1079
- // Nothing was live (boot-skipped client shim, user-patch-managed
1080
- // entry, or already off): the persisted flag is the contract.
1081
- ok = true;
1082
- }
1089
+ await disableLivePlugin(name, carrierRowIds(dir, name).length > 0);
1090
+ // The persisted flag applies on the next composition even if the
1091
+ // unmount did not finish in this process.
1092
+ ok = true;
1083
1093
  }
1084
1094
  if (!ok && enabled) {
1085
1095
  // Put the in-memory view back before persisting: it is the same object
@@ -1092,6 +1102,103 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1092
1102
  writeMarketState(dir, { disabled, groups, groupOrder });
1093
1103
  return { ok, reason };
1094
1104
  }
1105
+ async function disableLivePlugin(name, carrier) {
1106
+ // The carrier and what it replaces must switch in one composition.
1107
+ if (!carrier && !await hotUnmount(name))
1108
+ await themes.setEntryDisabled(name, true);
1109
+ }
1110
+ /** Commit a multi-component OFF before touching the running plugin.
1111
+ * Carriers leave the stack first so their foreign patch stops applying. */
1112
+ async function disableComponentLayers(name, choices, stackToggle, result, keepLegacyPatch) {
1113
+ const commit = () => {
1114
+ let bundleBefore;
1115
+ let patchChange;
1116
+ let stage = 'bundle';
1117
+ const removeFromStack = () => {
1118
+ if (!stackToggle)
1119
+ return;
1120
+ stage = 'bundle';
1121
+ const before = readProfileManifestSnapshot(config.profile, activeProfileDir);
1122
+ if (removeProfileBundle(activeProfileDir, name))
1123
+ bundleBefore = before;
1124
+ };
1125
+ try {
1126
+ if (result.isCarrier)
1127
+ removeFromStack();
1128
+ if (!keepLegacyPatch) {
1129
+ stage = 'patch';
1130
+ const { ok, reason, change } = commitComponentSwitchPatch(userPatchPath, name, choices, false);
1131
+ result.patchWrite = { ok, reason };
1132
+ if (!ok)
1133
+ throw new Error(reason ?? 'could not write the component settings');
1134
+ patchChange = change;
1135
+ }
1136
+ if (!result.isCarrier)
1137
+ removeFromStack();
1138
+ stage = 'state';
1139
+ writeMarketState(activeProfileDir, { disabled: new Set(disabled).add(name), groups, groupOrder });
1140
+ disabled.add(name);
1141
+ }
1142
+ catch (error) {
1143
+ const detail = error instanceof Error ? error.message : String(error);
1144
+ logEvent('warn', 'toggle', name + ': component disable stopped during ' + stage + ' — ' + detail);
1145
+ if (stage === 'bundle') {
1146
+ result.reason = '保存插件列表失败。请检查权限后重试 / Could not save the plugin list. Check permissions and retry.';
1147
+ result.bundleSwitch = { ok: false, reason: result.reason };
1148
+ }
1149
+ else if (stage === 'patch') {
1150
+ result.reason = result.patchWrite?.reason ?? '保存组件设置失败。请检查权限后重试 / Could not save component settings. Check permissions and retry.';
1151
+ }
1152
+ else {
1153
+ result.reason = '保存停用状态失败。请检查权限后重试 / Could not save the disabled state. Check permissions and retry.';
1154
+ }
1155
+ let restored = true;
1156
+ if (bundleBefore !== undefined) {
1157
+ try {
1158
+ restored = restoreRemovedProfileBundle(activeProfileDir, name, bundleBefore);
1159
+ }
1160
+ catch (rollbackError) {
1161
+ restored = false;
1162
+ logEvent('warn', 'toggle', name + ': bundle rollback failed — ' + String(rollbackError));
1163
+ }
1164
+ if (!restored)
1165
+ result.bundleSwitch = { ok: false, reason: '插件列表没能恢复 / The plugin list could not be restored.' };
1166
+ }
1167
+ if (patchChange !== undefined) {
1168
+ const rollback = rollbackComponentSwitchPatch(userPatchPath, patchChange);
1169
+ if (!rollback.ok) {
1170
+ restored = false;
1171
+ result.patchWrite = rollback;
1172
+ logEvent('warn', 'toggle', name + ': component settings rollback failed — ' + rollback.reason);
1173
+ }
1174
+ }
1175
+ if (!restored) {
1176
+ result.reason = '停用失败,配置没能恢复。请到官方插件页检查设置 / Disable failed and settings could not be restored. Check the DSH Plugins page.';
1177
+ logEvent('error', 'toggle', name + ': partial disable, check the plugin settings');
1178
+ }
1179
+ result.ok = false;
1180
+ result.unchanged = true;
1181
+ }
1182
+ };
1183
+ // The official manager uses this lock for its own patch and manifest
1184
+ // changes. Keep the synchronous disk commit and its rollback together.
1185
+ try {
1186
+ if (withIdleProfile(activeProfileDir, commit) === null) {
1187
+ const reason = '插件正在操作中。等操作结束后重试 / A plugin operation is in progress. Try again when it finishes.';
1188
+ return { ...result, ok: false, reason, unchanged: true };
1189
+ }
1190
+ }
1191
+ catch (error) {
1192
+ logEvent('warn', 'toggle', name + ': could not use the profile lock — ' + String(error));
1193
+ const reason = '未能保存停用。检查插件设置后重试 / Could not save this disable. Check the plugin settings and retry.';
1194
+ return { ...result, ok: false, reason, unchanged: true };
1195
+ }
1196
+ if (!result.ok)
1197
+ return result;
1198
+ await disableLivePlugin(name, result.isCarrier);
1199
+ logEvent('info', 'toggle', name + ': off ok=true');
1200
+ return result;
1201
+ }
1095
1202
  /**
1096
1203
  * Write the two durable layers for one plugin switch, after the live switch
1097
1204
  * has run: `dsh.profile.bundles` and the user patch rows (#696).
@@ -1106,17 +1213,96 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1106
1213
  * @param switchLive - perform the runtime switch; a failed ENABLE writes
1107
1214
  * neither layer (#575).
1108
1215
  */
1109
- async function switchPluginLayers(name, enabled, switchLive = () => setPluginEnabled(name, enabled)) {
1216
+ async function switchPluginLayers(name, enabled, switchLive, replayDeadline = Infinity) {
1110
1217
  const packageDir = join(activeProfileDir, 'node_modules', name);
1218
+ const optOutRows = new Set(bundleOptOutRowIds(packageDir));
1219
+ const expressionRows = new Set(bundleExpressionRowIds(packageDir));
1220
+ const wasDisabled = disabled.has(name);
1221
+ const componentRows = rowIdsForPackage(host, activeProfileDir, name);
1222
+ const installed = componentRows.length > 1 ? readInstalled(config.profile, activeProfileDir) : {};
1223
+ const componentNames = new Map();
1224
+ for (const id of componentRows) {
1225
+ const expected = composedRowName(host, id);
1226
+ const owner = expected === null ? null : packageOfEntryName(expected) ?? expected;
1227
+ // The id fallback for carried modules does not make a different
1228
+ // package's live entry ours (#1089).
1229
+ if (owner !== null && owner !== name && Object.hasOwn(installed, owner))
1230
+ continue;
1231
+ componentNames.set(id, expected);
1232
+ }
1233
+ const choices = componentNames.size > 1
1234
+ ? readComponentSwitchPatch(userPatchPath, name, componentNames, new Set([...optOutRows, ...expressionRows]))
1235
+ : null;
1236
+ const carrierRows = carrierRowIds(activeProfileDir, name);
1237
+ const foreignRows = foreignRowIds(activeProfileDir, name);
1238
+ const isCarrier = carrierRows.length > 0;
1239
+ // Both layers, or neither (#696 B). `dsh.profile.bundles` is the
1240
+ // package-level declaration the official plugins page's switch reads
1241
+ // and the loader composes; the patch rows above are the runtime
1242
+ // truth the market's own inference reads. Writing one and not the
1243
+ // other is the whole of that issue — the market said off while the
1244
+ // official page said on, and each layer was right about itself.
1245
+ //
1246
+ // Two shapes stay out of it. An IN-BOX bundle is not the market's to
1247
+ // drop from the stack (order.ts refuses to reorder them for the same
1248
+ // reason). A bundle whose patch names rows it does NOT insert speaks
1249
+ // for a neighbour as well, and leaving the stack would take that
1250
+ // neighbour's configuration with it — the shape #147 and the
1251
+ // fixture-cross e2e exist to prevent.
1252
+ const stackToggle = !INBOX_BUNDLES.has(name) && declaresBundle(activeProfileDir, name)
1253
+ && (isCarrier || foreignRows.length === 0);
1254
+ const allOff = choices !== null && choices.ownOff.size === componentNames.size;
1255
+ // Old market builds stored only a state flag and unmarked, standalone
1256
+ // rows. Keep their ON path for that otherwise indistinguishable format.
1257
+ const userAllOff = allOff && !(wasDisabled && choices.legacyAllOff);
1258
+ const initial = {
1259
+ ok: true, reason: undefined, patchRows: componentRows,
1260
+ patchWrite: null, carrierRows, isCarrier, bundleSwitch: { ok: true, reason: null },
1261
+ };
1262
+ if (userAllOff && enabled) {
1263
+ return {
1264
+ ...initial,
1265
+ ok: false,
1266
+ unchanged: true,
1267
+ reason: '所有组件都已关闭。请到官方插件页开启插件,再选择所需组件 / All components are off. Enable the plugin and turn on the components you want on the DSH Plugins page.',
1268
+ };
1269
+ }
1270
+ if (!enabled && componentNames.size > 1) {
1271
+ // An OFF request against an already-off package must not label the
1272
+ // user's own rows as an old market disable on a later ON.
1273
+ if (allOff && (!stackToggle || !isCarrier || !readProfileBundles(activeProfileDir).includes(name))) {
1274
+ return { ...initial, unchanged: true };
1275
+ }
1276
+ if (choices === null) {
1277
+ const reason = '组件设置读不到。请检查设置后重试 / Could not read component settings. Check them and retry.';
1278
+ return { ...initial, ok: false, reason, unchanged: true, patchWrite: { ok: false, reason } };
1279
+ }
1280
+ return disableComponentLayers(name, choices, stackToggle, initial, allOff && !userAllOff);
1281
+ }
1282
+ const componentPatch = choices !== null && (choices.suspended
1283
+ || (!wasDisabled && choices.customized && choices.keepOff.size > 0 && choices.keepOff.size < componentNames.size))
1284
+ ? choices : null;
1285
+ const keepOff = enabled ? componentPatch?.keepOff : undefined;
1286
+ const reBundle = enabled && !isCarrier && !readProfileBundles(activeProfileDir).includes(name);
1287
+ // A watched profile would compose a newly re-added bundle after the
1288
+ // market mount and run a second copy. Restore the user layer, then
1289
+ // observe that host's own replay of the selected components.
1290
+ const replayWaitMs = reBundle && stackToggle && componentPatch?.suspended === true && switchLive === undefined
1291
+ ? config.hostReplayWaitMs ?? (liveNames().has(PROFILE_HMR_ENTRY) ? PROFILE_HMR_REPLAY_WAIT_MS : 0)
1292
+ : 0;
1111
1293
  // Capture module identity before switching the entry off.
1112
- const namedRows = new Set();
1294
+ const namedRows = new Map();
1113
1295
  if (!enabled) {
1114
1296
  for (const id of shippedInsertedRowIds(packageDir)) {
1115
- if (composedRowName(host, id) === name)
1116
- namedRows.add(id);
1297
+ const moduleName = composedRowName(host, id);
1298
+ if (moduleName === name || (isCarrier && moduleName !== null && packageOfEntryName(moduleName) === name)) {
1299
+ namedRows.set(id, moduleName);
1300
+ }
1117
1301
  }
1118
1302
  }
1119
- const { ok: liveOk, reason: liveReason } = await switchLive();
1303
+ const { ok: liveOk, reason: liveReason } = await (switchLive === undefined
1304
+ ? setPluginEnabled(name, enabled, keepOff, replayWaitMs > 0)
1305
+ : switchLive(keepOff));
1120
1306
  let ok = liveOk;
1121
1307
  let reason = liveReason;
1122
1308
  // Durable patch-layer write (port of dsh-plugin-hub): the package's
@@ -1133,15 +1319,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1133
1319
  // side effect of a bug fix. Skipped only while something else is left to
1134
1320
  // flip: a package whose rows are ALL opt-in rows still has to be
1135
1321
  // switchable.
1136
- const optOutRows = new Set(bundleOptOutRowIds(packageDir));
1137
1322
  // Rows the bundle decides itself, by expression (`disabled: !!js …`),
1138
1323
  // are a third shape next to opt-in rows: the market can neither read
1139
1324
  // nor overrule the condition, so enabling the package must leave them
1140
1325
  // exactly as the bundle ships them (#1043).
1141
- const expressionRows = new Set(bundleExpressionRowIds(packageDir));
1142
- const decided = patchRows.filter(rowId => !optOutRows.has(rowId));
1143
- /** Rows that can carry a USER decision about this package — see above. */
1144
- const userRows = decided.length > 0 ? decided : patchRows;
1145
1326
  // Disable-carrier (#224): a bundle whose patch DISABLES a plugin it
1146
1327
  // does not own (dsh-postgres-backends disables session-persistence-jsonl).
1147
1328
  // Disabling only its inserted rows leaves that foreign disable applying
@@ -1151,30 +1332,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1151
1332
  // A bundle that merely reconfigures a neighbour (config without
1152
1333
  // disabled) is NOT dropped: #147 requires disabling it to leave the
1153
1334
  // neighbour live, and the e2e fixture-cross re-enable breaks otherwise.
1154
- const carrierRows = carrierRowIds(activeProfileDir, name);
1155
- const foreignRows = foreignRowIds(activeProfileDir, name);
1156
- const isCarrier = carrierRows.length > 0;
1157
- // Both layers, or neither (#696 B). `dsh.profile.bundles` is the
1158
- // package-level declaration the official plugins page's switch reads
1159
- // and the loader composes; the patch rows above are the runtime
1160
- // truth the market's own inference reads. Writing one and not the
1161
- // other is the whole of that issue — the market said off while the
1162
- // official page said on, and each layer was right about itself.
1163
- //
1164
- // Two shapes stay out of it. An IN-BOX bundle is not the market's to
1165
- // drop from the stack (order.ts refuses to reorder them for the same
1166
- // reason). A bundle whose patch names rows it does NOT insert speaks
1167
- // for a neighbour as well, and leaving the stack would take that
1168
- // neighbour's configuration with it — the shape #147 and the
1169
- // fixture-cross e2e exist to prevent.
1170
- const stackToggle = !INBOX_BUNDLES.has(name) && declaresBundle(activeProfileDir, name)
1171
- && (isCarrier || foreignRows.length === 0);
1172
1335
  // Enabling something the stack no longer carries (another manager
1173
1336
  // removed it, or this route did when it was last turned off) has to
1174
1337
  // put it back, or the rows flip, the switch reads on and nothing
1175
1338
  // composes it on the next boot. Unlike a carrier this does NOT force
1176
1339
  // a restart: the enable below still brings it up in this process.
1177
- const reBundle = enabled && !isCarrier && !readProfileBundles(activeProfileDir).includes(name);
1178
1340
  let stackChanged = false;
1179
1341
  let bundleSwitch = { ok: true, reason: null };
1180
1342
  // A failed enable leaves the stack as it was, like the row layer below
@@ -1221,7 +1383,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1221
1383
  // The name the loader composed for a row, for the rows whose user-layer
1222
1384
  // entry carries one of its own: the host skips an entry whose `name` is
1223
1385
  // not this one, so its flag is not a decision about the row (#1113).
1224
- const expectedNameFor = (rowId) => namedRows.has(rowId) ? name : composedRowName(host, rowId);
1386
+ const expectedNameFor = (rowId) => namedRows.get(rowId) ?? composedRowName(host, rowId);
1225
1387
  /** A user-layer flag counts only when the row it names is this entry. */
1226
1388
  const rowIsOurs = (rowId) => prePatch !== null && rowFlagApplies(prePatch, rowId, expectedNameFor(rowId));
1227
1389
  if (patchRows.length > 0 && patchGate && prePatch !== null) {
@@ -1237,10 +1399,18 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1237
1399
  // a row the environment keeps off, which then held the package pending
1238
1400
  // at activation — except, again, to clean a block an earlier disable
1239
1401
  // left, which restores the expression's authority, never a forced on.
1240
- const targets = enabled
1241
- ? patchRows.filter(rowId => (!optOutRows.has(rowId) && !expressionRows.has(rowId)) || (rowIsOurs(rowId) && prePatch.disables.includes(rowId)))
1242
- : patchRows;
1402
+ let targets = [];
1243
1403
  const flipped = [];
1404
+ if (componentPatch !== null) {
1405
+ const result = await writeComponentSwitchPatch(userPatchPath, name, componentPatch, enabled);
1406
+ if (!result.ok)
1407
+ patchWrite = result;
1408
+ }
1409
+ else {
1410
+ targets = enabled
1411
+ ? patchRows.filter(rowId => (!optOutRows.has(rowId) && !expressionRows.has(rowId)) || (rowIsOurs(rowId) && prePatch.disables.includes(rowId)))
1412
+ : patchRows;
1413
+ }
1244
1414
  for (const rowId of targets) {
1245
1415
  // #1110: an opt-in or expression row that the user's layer still holds
1246
1416
  // closed can only be CLEANED here. `enableRow`'s force-enable appends
@@ -1251,8 +1421,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1251
1421
  const expectedName = expectedNameFor(rowId);
1252
1422
  // DSH drops a simple id/disabled override when enabling would restore
1253
1423
  // 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);
1424
+ // in the shared patch layer for followOutsideEnable (#1196). A
1425
+ // carrier's own subpath entries need that same evidence (#1242);
1426
+ // its bundle row can also return through recovery, not user intent.
1427
+ const recordModuleName = stackToggle && !cleanOnly && namedRows.has(rowId);
1256
1428
  const result = enabled
1257
1429
  ? await enableRow(userPatchPath, rowId, { cleanOnly, expectedName, packageName: name })
1258
1430
  : await disableRow(userPatchPath, rowId, { expectedName, recordModuleName, packageName: name });
@@ -1305,6 +1477,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1305
1477
  logEvent('warn', 'toggle', `${name}: dsh.profile.bundles rollback failed — ${bundleSwitch.reason}`);
1306
1478
  }
1307
1479
  }
1480
+ if (wasDisabled)
1481
+ await setPluginEnabled(name, false);
1308
1482
  // #575: a failed enable leaves the plugin as it was, and the
1309
1483
  // reply has to say so — otherwise the switch shows a state the
1310
1484
  // rollback just undid.
@@ -1313,8 +1487,41 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1313
1487
  }
1314
1488
  }
1315
1489
  }
1490
+ let replayPending;
1491
+ if (replayWaitMs > 0) {
1492
+ if (!bundleSwitch.ok) {
1493
+ if (wasDisabled)
1494
+ await setPluginEnabled(name, false);
1495
+ ok = false;
1496
+ reason = '保存插件列表失败。请检查权限后重试 / Could not save the plugin list. Check permissions and retry.';
1497
+ }
1498
+ else if (ok) {
1499
+ const remaining = new Set([...componentNames.keys()].filter(id => !keepOff?.has(id)));
1500
+ const waitUntil = Math.min(Date.now() + replayWaitMs, replayDeadline);
1501
+ do {
1502
+ for (const entry of host.loader.entries()) {
1503
+ const id = loaderEntryId(entry).split(':').at(-1) ?? '';
1504
+ const entryName = entry.options.name;
1505
+ if (!remaining.has(id) || (entryName !== name && (entryName === undefined || packageOfEntryName(entryName) !== name)))
1506
+ continue;
1507
+ const fiber = entry.fiber;
1508
+ if (fiber !== undefined && (fiber.state === undefined || fiber.state === ACTIVE_FIBER_STATE)) {
1509
+ remaining.delete(id);
1510
+ }
1511
+ }
1512
+ const waitLeft = waitUntil - Date.now();
1513
+ if (remaining.size === 0 || waitLeft <= 0)
1514
+ break;
1515
+ await new Promise(resolve => setTimeout(resolve, Math.min(250, waitLeft)));
1516
+ } while (!disposed);
1517
+ if (remaining.size > 0) {
1518
+ replayPending = true;
1519
+ reason = '设置已保存,组件尚未加载。请重启 DSH 后查看 / Settings saved. If the components have not started, restart DSH.';
1520
+ }
1521
+ }
1522
+ }
1316
1523
  logEvent(ok ? 'info' : 'error', 'toggle', `${name}: ${enabled ? 'on' : 'off'} ok=${String(ok)}`);
1317
- return { ok, reason, patchRows, userRows, patchWrite, carrierRows, isCarrier, bundleSwitch };
1524
+ return { ok, reason, patchRows, patchWrite, carrierRows, isCarrier, bundleSwitch, replayPending };
1318
1525
  }
1319
1526
  /**
1320
1527
  * The plugin inventory the recovery surface is allowed to switch.
@@ -1482,7 +1689,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1482
1689
  }
1483
1690
  }
1484
1691
  /** Every plugin command goes through the pnpm-drift recovery wrapper (#20). */
1485
- const runPlugin = (profile, args, preserveProfilePolicy = false) => withHoistRecovery(commands.runPlugin, profile, args, activeProfileDir, { marketFlags, preserveProfilePolicy, ...(preserveProfilePolicy ? { releaseAgeBypass: false } : {}) });
1692
+ const runPlugin = (profile, args, preserveProfilePolicy = false, run = commands.runPlugin) => withHoistRecovery(run, profile, args, activeProfileDir, { marketFlags, preserveProfilePolicy, ...(preserveProfilePolicy ? { releaseAgeBypass: false } : {}) });
1486
1693
  /** The same, minus the release-age bypass: for a fresh install pinned to a young release (#594). */
1487
1694
  const runPluginKeepingReleaseAge = (profile, args) => withHoistRecovery(commands.runPlugin, profile, args, activeProfileDir, { releaseAgeBypass: false, marketFlags });
1488
1695
  /** Mature npm updates must preserve both release-age enforcement and profile policy files. */
@@ -1653,22 +1860,30 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1653
1860
  };
1654
1861
  }
1655
1862
  }
1656
- /** Resolved npm version for one dependency in a captured pnpm v9 importer. */
1657
- function capturedNpmVersion(snapshot, name) {
1863
+ function capturedDependencies(snapshot) {
1658
1864
  if (!snapshot.present)
1659
- return null;
1865
+ return undefined;
1660
1866
  try {
1661
1867
  const parsed = loadYaml(snapshot.contents.toString('utf8'));
1662
- const dependency = parsed?.importers?.['.']?.dependencies?.[name];
1663
- const raw = typeof dependency === 'string' ? dependency : dependency?.version;
1664
- if (typeof raw !== 'string')
1665
- return null;
1666
- return /^(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\(|$)/.exec(raw)?.[1] ?? null;
1868
+ return parsed?.importers?.['.']?.dependencies;
1667
1869
  }
1668
1870
  catch {
1669
- return null;
1871
+ return undefined;
1670
1872
  }
1671
1873
  }
1874
+ /** Resolved npm version for one dependency in a captured pnpm v9 importer. */
1875
+ function capturedNpmVersion(snapshot, name) {
1876
+ const dependency = capturedDependencies(snapshot)?.[name];
1877
+ const raw = typeof dependency === 'string' ? dependency : dependency?.version;
1878
+ if (typeof raw !== 'string')
1879
+ return null;
1880
+ return /^(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\(|$)/.exec(raw)?.[1] ?? null;
1881
+ }
1882
+ function lockRecordsRelease(snapshot, name, target) {
1883
+ const dependency = capturedDependencies(snapshot)?.[name];
1884
+ return typeof dependency === 'object' && dependency !== null
1885
+ && dependency.specifier === target && dependency.version === target;
1886
+ }
1672
1887
  /** Restore lockfile bytes atomically, or restore the fact it was absent. */
1673
1888
  function restoreProfileLockfile(snapshot) {
1674
1889
  const file = join(activeProfileDir, 'pnpm-lock.yaml');
@@ -1830,6 +2045,298 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1830
2045
  logEvent('info', 'update-rollback', `${name}: restored git build at ${beforeCommit}`);
1831
2046
  return { ok: true, detail: null };
1832
2047
  }
2048
+ function verifyRestoredCheckout(name) {
2049
+ if (!hasLoadableEntry(activeProfileDir, name, config.dshInstallDir)) {
2050
+ throw new Error('the original checkout has no loadable entry at its saved location');
2051
+ }
2052
+ }
2053
+ function checkingCheckoutRepair(round) {
2054
+ return !disposed && checkoutRepairRound === round && performance.now() < round.deadline;
2055
+ }
2056
+ function reportCheckoutRepair(round, entries) {
2057
+ if (disposed || checkoutRepairRound !== round)
2058
+ return;
2059
+ checkoutRepairRound = undefined;
2060
+ if (checkoutRepairTimer !== undefined)
2061
+ clearTimeout(checkoutRepairTimer);
2062
+ checkoutRepairTimer = undefined;
2063
+ checkoutRecovery = entries.length === 0 ? undefined : { checking: false, entries };
2064
+ }
2065
+ function checkoutRecoveryEntry(record, reason) {
2066
+ let sourceExists = false;
2067
+ try {
2068
+ const link = recordedCheckoutLink(activeProfileDir, record.name, record.spec, record.rawTarget);
2069
+ sourceExists = checkoutSourceExists(link);
2070
+ }
2071
+ catch { /* A moved or inaccessible checkout cannot be confirmed. */ }
2072
+ return { name: record.name, reason, sourceExists };
2073
+ }
2074
+ function checkoutLinkOutstanding(record, manifest) {
2075
+ if (manifest.ok && manifest.snapshot.dependencies[record.name] !== record.spec)
2076
+ return false;
2077
+ try {
2078
+ return lstatSync(join(activeProfileDir, 'node_modules', record.name), { throwIfNoEntry: false }) === undefined;
2079
+ }
2080
+ catch {
2081
+ return true;
2082
+ }
2083
+ }
2084
+ function checkoutCommandBusy() {
2085
+ return mutationBusy || commands.busy?.() === true || commands.packageWritesSettled?.() === false;
2086
+ }
2087
+ function clearCompletedCheckout(record) {
2088
+ if (checkoutCommandBusy() || hasUnsettledPackageRun(activeProfileDir))
2089
+ return;
2090
+ withIdleProfile(activeProfileDir, () => {
2091
+ if (checkoutCommandBusy() || hasUnsettledPackageRun(activeProfileDir))
2092
+ return;
2093
+ const manifest = captureUpdateManifest();
2094
+ if (checkoutLinkOutstanding(record, manifest))
2095
+ return;
2096
+ const latest = checkoutLinks.list();
2097
+ const kept = latest.filter(item => item.name !== record.name || item.spec !== record.spec || item.rawTarget !== record.rawTarget);
2098
+ if (kept.length !== latest.length)
2099
+ checkoutLinks.save(kept);
2100
+ });
2101
+ }
2102
+ function tickCheckoutRepair(round, attempt) {
2103
+ if (disposed || checkoutRepairRound !== round)
2104
+ return;
2105
+ if (performance.now() >= round.deadline) {
2106
+ let records = round.records;
2107
+ try {
2108
+ records = checkoutLinks.list();
2109
+ }
2110
+ catch { /* Report the last readable records. */ }
2111
+ const manifest = captureUpdateManifest();
2112
+ const entries = records
2113
+ .filter(record => checkoutLinkOutstanding(record, manifest))
2114
+ .map(record => checkoutRecoveryEntry(record, round.reason));
2115
+ if (entries.length > 0) {
2116
+ logEvent('warn', 'checkout-recovery', `automatic checkout recovery stopped after 30 seconds (${round.reason})`);
2117
+ }
2118
+ reportCheckoutRepair(round, entries);
2119
+ return;
2120
+ }
2121
+ // The clock also runs while the host helper is pending, so a stalled
2122
+ // import or callback cannot extend the round. Every write checks it again.
2123
+ if (attempt && !round.inFlight) {
2124
+ round.inFlight = true;
2125
+ void repairCheckoutLinks(round).finally(() => { round.inFlight = false; });
2126
+ }
2127
+ if (checkoutRepairRound !== round)
2128
+ return;
2129
+ checkoutRepairTimer = setTimeout(() => {
2130
+ checkoutRepairTimer = undefined;
2131
+ tickCheckoutRepair(round, true);
2132
+ }, Math.min(CHECKOUT_REPAIR_INTERVAL_MS, round.deadline - performance.now()));
2133
+ checkoutRepairTimer.unref?.();
2134
+ }
2135
+ function startCheckoutRepair(switchedName) {
2136
+ if (disposed || checkoutRepairRound !== undefined)
2137
+ return;
2138
+ let records;
2139
+ try {
2140
+ records = checkoutLinks.list();
2141
+ }
2142
+ catch (error) {
2143
+ logEvent('warn', 'checkout-recovery', `could not read pending local checkout links — ${String(error)}`);
2144
+ return;
2145
+ }
2146
+ if (records.length === 0) {
2147
+ checkoutRecovery = undefined;
2148
+ return;
2149
+ }
2150
+ if (switchedName !== undefined) {
2151
+ const switchedRecord = records.find(record => record.name === switchedName);
2152
+ if (switchedRecord === undefined)
2153
+ return;
2154
+ // A successful switch or one whose synchronous rollback reconnected the
2155
+ // link must not reopen some other package's expired recovery.
2156
+ if (!checkoutLinkOutstanding(switchedRecord, captureUpdateManifest())) {
2157
+ try {
2158
+ clearCompletedCheckout(switchedRecord);
2159
+ }
2160
+ catch (error) {
2161
+ logEvent('warn', 'checkout-recovery', `could not clear a completed checkout switch record — ${String(error)}`);
2162
+ }
2163
+ return;
2164
+ }
2165
+ }
2166
+ const round = {
2167
+ deadline: performance.now() + CHECKOUT_REPAIR_WAIT_MS, inFlight: false, reason: 'profile-busy', records,
2168
+ };
2169
+ checkoutRepairRound = round;
2170
+ checkoutRecovery = { checking: true, entries: [] };
2171
+ tickCheckoutRepair(round, switchedName === undefined);
2172
+ }
2173
+ function checkoutRepairBlocked(round) {
2174
+ if (!checkingCheckoutRepair(round))
2175
+ return true;
2176
+ if (checkoutCommandBusy()) {
2177
+ round.reason = 'profile-busy';
2178
+ return true;
2179
+ }
2180
+ if (hasUnsettledPackageRun(activeProfileDir)) {
2181
+ round.reason = 'package-run';
2182
+ return true;
2183
+ }
2184
+ return false;
2185
+ }
2186
+ async function repairCheckoutLinks(round) {
2187
+ try {
2188
+ round.records = checkoutLinks.list();
2189
+ if (round.records.length === 0) {
2190
+ reportCheckoutRepair(round, []);
2191
+ return;
2192
+ }
2193
+ if (checkoutRepairBlocked(round))
2194
+ return;
2195
+ const repairLocked = () => {
2196
+ if (checkoutRepairBlocked(round))
2197
+ return false;
2198
+ const records = checkoutLinks.list();
2199
+ const current = captureUpdateManifest();
2200
+ if (!current.ok)
2201
+ throw new Error(current.detail);
2202
+ const lockfile = captureProfileLockfile();
2203
+ if (!lockfile.ok)
2204
+ throw new Error(lockfile.detail);
2205
+ const lockedDependencies = capturedDependencies(lockfile.snapshot);
2206
+ const kept = [];
2207
+ for (const record of records) {
2208
+ if (current.snapshot.dependencies[record.name] !== record.spec)
2209
+ continue;
2210
+ try {
2211
+ const link = recordedCheckoutLink(activeProfileDir, record.name, record.spec, record.rawTarget);
2212
+ if (lstatSync(link.path, { throwIfNoEntry: false }) !== undefined)
2213
+ continue;
2214
+ const locked = lockedDependencies?.[record.name];
2215
+ if (typeof locked === 'object' && locked !== null && locked.specifier !== record.spec) {
2216
+ throw new Error('the lockfile now records a different source');
2217
+ }
2218
+ restoreCheckoutLink(link, false, () => verifyRestoredCheckout(record.name));
2219
+ logEvent('info', 'update-rollback', `${record.name}: reconnected the local checkout after the source switch`);
2220
+ }
2221
+ catch (error) {
2222
+ kept.push(record);
2223
+ logEvent('warn', 'update-rollback', `${record.name}: could not reconnect the saved local checkout — ${String(error)}`);
2224
+ }
2225
+ }
2226
+ if (kept.length !== records.length)
2227
+ checkoutLinks.save(kept);
2228
+ reportCheckoutRepair(round, kept.map(record => checkoutRecoveryEntry(record, 'check-failed')));
2229
+ return true;
2230
+ };
2231
+ const repaired = withIdleProfile(activeProfileDir, repairLocked);
2232
+ if (repaired === null && !checkoutRepairBlocked(round)) {
2233
+ round.reason = 'writer-lock';
2234
+ checkoutHostLock ??= loadHostProfileLock(config.dshInstallDir ?? findDshInstallDir());
2235
+ const hostLock = await checkoutHostLock;
2236
+ if (checkoutRepairBlocked(round))
2237
+ return;
2238
+ if (hostLock === null) {
2239
+ if (!checkoutHostLockUnavailableLogged) {
2240
+ checkoutHostLockUnavailableLogged = true;
2241
+ logEvent('warn', 'checkout-recovery', 'host checkout lock helper unavailable; only unoccupied profile locks can be used');
2242
+ }
2243
+ }
2244
+ else {
2245
+ try {
2246
+ await hostLock(join(activeProfileDir, 'package.json'), async () => repairLocked(), { waitMs: 0 });
2247
+ }
2248
+ catch (error) {
2249
+ if (!(error instanceof Error) || !error.message.includes('timed out waiting for the writer lock'))
2250
+ throw error;
2251
+ }
2252
+ }
2253
+ }
2254
+ }
2255
+ catch (error) {
2256
+ if (checkingCheckoutRepair(round)) {
2257
+ logEvent('warn', 'checkout-recovery', `could not settle pending local checkout links — ${String(error)}`);
2258
+ reportCheckoutRepair(round, round.records.map(record => checkoutRecoveryEntry(record, 'check-failed')));
2259
+ }
2260
+ }
2261
+ }
2262
+ function entriesExcept(entries, name) {
2263
+ const other = { ...entries };
2264
+ delete other[name];
2265
+ return other;
2266
+ }
2267
+ function bundleRowsExcept(snapshot, name) {
2268
+ if (!snapshot.profileBundles.present)
2269
+ return [];
2270
+ const rows = snapshot.profileBundles.value;
2271
+ return Array.isArray(rows) ? rows.filter(row => row !== name) : rows;
2272
+ }
2273
+ function restoreLinkedUpdate(name, source, restoreProfile) {
2274
+ const busy = { ok: false, detail: 'another plugin operation is running' };
2275
+ if (commands.busy?.() === true || commands.packageWritesSettled?.() === false)
2276
+ return busy;
2277
+ try {
2278
+ return withIdleProfile(activeProfileDir, () => restoreLinkedUpdateLocked(name, source, restoreProfile)) ?? busy;
2279
+ }
2280
+ catch (error) {
2281
+ return { ok: false, detail: error instanceof Error ? error.message : String(error) };
2282
+ }
2283
+ }
2284
+ function restoreLinkedUpdateLocked(name, source, restoreProfile) {
2285
+ const current = captureUpdateManifest();
2286
+ if (!current.ok)
2287
+ return { ok: false, detail: current.detail };
2288
+ const before = source.manifestBefore;
2289
+ const previous = before.dependencies[name];
2290
+ const installed = current.snapshot.dependencies[name];
2291
+ const release = isGitHubReleaseTarballSpec(source.target);
2292
+ const installedReplacement = installed === source.target;
2293
+ if (installed !== previous && (!restoreProfile || !installedReplacement)) {
2294
+ return { ok: false, detail: 'the installed source cannot be attributed to this switch' };
2295
+ }
2296
+ const lockNow = restoreProfile ? captureProfileLockfile() : null;
2297
+ const lockBefore = source.lockfileBefore;
2298
+ if (lockNow !== null) {
2299
+ if (!lockBefore.ok)
2300
+ return { ok: false, detail: lockBefore.detail };
2301
+ if (!lockNow.ok)
2302
+ return { ok: false, detail: lockNow.detail };
2303
+ const dependenciesMatch = isDeepStrictEqual(entriesExcept(before.dependencies, name), entriesExcept(current.snapshot.dependencies, name));
2304
+ const bundleRowsMatch = isDeepStrictEqual(bundleRowsExcept(before, name), bundleRowsExcept(current.snapshot, name));
2305
+ const lockedDependenciesMatch = isDeepStrictEqual(entriesExcept(capturedDependencies(lockBefore.snapshot), name), entriesExcept(capturedDependencies(lockNow.snapshot), name));
2306
+ if (!dependenciesMatch || !bundleRowsMatch || !lockedDependenciesMatch) {
2307
+ return { ok: false, detail: 'other profile dependencies or bundle rows changed during the switch' };
2308
+ }
2309
+ }
2310
+ // pnpm can materialize a release and write its exact URL to the lockfile
2311
+ // before it changes package.json. Require new evidence for this importer
2312
+ // before moving an occupied package slot with the original declaration.
2313
+ const landedRelease = release && lockNow?.ok === true && lockBefore.ok
2314
+ && !lockRecordsRelease(lockBefore.snapshot, name, source.target)
2315
+ && lockRecordsRelease(lockNow.snapshot, name, source.target);
2316
+ restoreCheckoutLink(source.link, restoreProfile && (installedReplacement || landedRelease), () => {
2317
+ verifyRestoredCheckout(name);
2318
+ if (!restoreProfile)
2319
+ return;
2320
+ try {
2321
+ restoreProfileManifest(config.profile, before, activeProfileDir);
2322
+ const restored = captureUpdateManifest();
2323
+ if (!restored.ok || restored.snapshot.dependencies[name] !== previous)
2324
+ throw new Error('could not restore the local dependency declaration');
2325
+ if (lockBefore.ok) {
2326
+ const locked = restoreProfileLockfile(lockBefore.snapshot);
2327
+ if (!locked.ok)
2328
+ throw new Error(locked.detail ?? 'could not restore the previous lockfile');
2329
+ }
2330
+ }
2331
+ catch (error) {
2332
+ restoreProfileManifest(config.profile, current.snapshot, activeProfileDir);
2333
+ if (lockNow?.ok)
2334
+ restoreProfileLockfile(lockNow.snapshot);
2335
+ throw error;
2336
+ }
2337
+ });
2338
+ return { ok: true, detail: null };
2339
+ }
1833
2340
  async function executeUpdateRollback(name, manifestBefore, source, preserveProfilePolicy = false) {
1834
2341
  if (source.kind === 'npm') {
1835
2342
  return rollbackNpmBuild(name, manifestBefore, source.beforeVersion, source.lockfileBefore, preserveProfilePolicy);
@@ -1837,6 +2344,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
1837
2344
  if (source.kind === 'git') {
1838
2345
  return rollbackGitBuild(name, manifestBefore, source.target, source.beforeCommit, source.lockfileBefore, source.keepRepairedLock, preserveProfilePolicy);
1839
2346
  }
2347
+ if (source.kind === 'linked-checkout')
2348
+ return restoreLinkedUpdate(name, source, true);
1840
2349
  return rollbackUpdateBuild(name, manifestBefore, true, preserveProfilePolicy);
1841
2350
  }
1842
2351
  const pendingRollbacks = new Map();
@@ -2042,7 +2551,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2042
2551
  catch {
2043
2552
  return null;
2044
2553
  }
2045
- return `目录条目指向的子目录在仓库里已不存在(${repo} 的 ${subpath}),多半是作者改名或移动了它——这不是你的环境的问题。请到 crate 反馈这条收录已失效。 / This catalog entry points at a subdirectory that no longer exists in the repository (${subpath} in ${repo}); the author most likely renamed or moved it. Nothing is wrong with your setup — please report the stale entry to crate.`;
2554
+ return `目录条目指向的子目录在仓库里已不存在(${repo} 的 ${subpath}),多半是作者改名或移动了它——这不是你的环境的问题。请到 awesome-dsh-plugin 反馈这条收录已失效。 / This catalog entry points at a subdirectory that no longer exists in the repository (${subpath} in ${repo}); the author most likely renamed or moved it. Nothing is wrong with your setup — please report the stale entry to awesome-dsh-plugin.`;
2046
2555
  }
2047
2556
  async function restoreBackup(value) {
2048
2557
  if (!await probePnpm())
@@ -2472,6 +2981,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
2472
2981
  profileKey: createHash('sha256').update(activeProfileDir).digest('hex'),
2473
2982
  enabled: marketState.backgroundUpdateChecks === true,
2474
2983
  intervalHours: marketState.backgroundUpdateIntervalHours,
2984
+ overlay: updates => applyProfileBlockers(updates, activeProfileDir),
2475
2985
  inventory: () => {
2476
2986
  const installed = readInstalled(config.profile, activeProfileDir);
2477
2987
  const commits = readLockCommits(config.profile, activeProfileDir);
@@ -3123,7 +3633,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
3123
3633
  response.writeHead(200, {
3124
3634
  'cache-control': 'no-store',
3125
3635
  'content-type': 'application/json; charset=utf-8',
3126
- 'content-disposition': `attachment; filename="dsh-crate-backup-${timestamp}.json"`,
3636
+ 'content-disposition': `attachment; filename="dsh-dsh-crate-backup-${timestamp}.json"`,
3127
3637
  });
3128
3638
  response.end(backup);
3129
3639
  }
@@ -4073,7 +4583,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4073
4583
  const body = (await readJsonBody(request));
4074
4584
  const name = typeof body.name === 'string' ? body.name : '';
4075
4585
  const enabled = body.enabled === true;
4076
- if (name === 'dsh-crate') {
4586
+ if (name === 'dsh-crate' || name === 'dsh-crate') {
4077
4587
  sendJson(response, 400, { error: 'the market cannot be disabled from its own page; use the dsh CLI' });
4078
4588
  return;
4079
4589
  }
@@ -4119,21 +4629,19 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4119
4629
  // Theme exclusivity stays a Themes-page concern: enabling a theme
4120
4630
  // deactivates the previously active one, so only the last-enabled
4121
4631
  // theme is live (same semantics as use-skin).
4122
- ? await switchPluginLayers(name, enabled, async () => {
4123
- const { ok, reason } = await themes.activateTheme(name);
4632
+ ? await switchPluginLayers(name, enabled, async (keepOff) => {
4633
+ const { ok, reason } = await themes.activateTheme(name, keepOff);
4124
4634
  themeFailure = reason;
4125
4635
  return { ok, reason: reason ?? (ok ? undefined : 'theme activation failed — restart required / 主题启用失败,需要重启') };
4126
4636
  })
4127
4637
  : await switchPluginLayers(name, enabled);
4128
4638
  const { ok, reason } = layers;
4129
- const { patchRows, userRows, patchWrite, carrierRows, isCarrier, bundleSwitch } = layers;
4639
+ const { patchRows, patchWrite, carrierRows, isCarrier, bundleSwitch } = layers;
4130
4640
  // Activation reads the post-write truth: the switch state OR the
4131
4641
  // patch layer, so a disabled plugin never reports "restart to
4132
4642
  // apply".
4133
- const patchNow = readUserPatchState(userPatchPath);
4134
- // Read from userRows, like the listing (#876): a disabled opt-in row is
4135
- // the bundle's own default and does not make the package off.
4136
- const offNow = disabled.has(name) || userRows.some(id => patchNow.disables.includes(id));
4643
+ const patchNow = readUserPatchState(userPatchPath, id => composedRowName(host, id));
4644
+ const offNow = disabled.has(name) || packagePatchFlags(host, activeProfileDir, [name], patchNow).disabled.includes(name);
4137
4645
  // When the live composition does not match the requested state
4138
4646
  // (enable failed to hot-mount / disable left the fiber up), the
4139
4647
  // change lands on the next boot via the patch layer + state.json —
@@ -4151,15 +4659,17 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4151
4659
  // only a restart can.
4152
4660
  const staleModule = enabled && replacedWhileLive.has(name);
4153
4661
  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));
4662
+ const reported = themeFailure !== undefined
4663
+ ? { ...observed, state: 'failed', hot: false, reasons: [themeFailure] }
4664
+ : layers.replayPending === true && observed.state === 'live'
4665
+ ? { ...observed, state: 'restart', hot: false, reasons: reason === undefined ? observed.reasons : [reason] }
4666
+ : observed;
4667
+ const restart = !layers.unchanged && !(enabled && reported.state === 'failed')
4668
+ && (isCarrier || staleModule || layers.replayPending === true || (enabled ? !liveAfter : liveAfter));
4159
4669
  // A client-part plugin's UI is in the page already — toggling it
4160
4670
  // needs a browser refresh to show the change (same signal the
4161
4671
  // install flow uses for the hot banner).
4162
- const refresh = packageHasClientPart(activeProfileDir, name);
4672
+ const refresh = !layers.unchanged && packageHasClientPart(activeProfileDir, name);
4163
4673
  sendJson(response, ok ? 200 : 502, {
4164
4674
  ok,
4165
4675
  name,
@@ -4259,6 +4769,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4259
4769
  }
4260
4770
  if (favorites.length >= MAX_FAVORITES) {
4261
4771
  sendJson(response, 400, {
4772
+ code: 'FAVORITES_LIMIT_REACHED',
4773
+ limit: MAX_FAVORITES,
4262
4774
  error: `favorites limit reached (${String(MAX_FAVORITES)}) / 收藏已达上限(${String(MAX_FAVORITES)})`,
4263
4775
  });
4264
4776
  return;
@@ -4474,77 +4986,101 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4474
4986
  sendJson(response, 400, { ok: false, error: 'unknown group action' });
4475
4987
  return;
4476
4988
  }
4477
- const installed = new Set(Object.keys(readInstalled(config.profile, activeProfileDir)));
4478
- // Theme members follow the global one-active-theme rule: a group
4479
- // holds at most one, and enabling one deactivates every other.
4480
- const themeNames = await themes.installedThemeNames();
4481
- let ok = true;
4482
- let error;
4483
- let restartMembers = [];
4484
- let refreshMembers = [];
4485
- if (action === 'toggle') {
4486
- const name = typeof body.name === 'string' ? body.name : '';
4487
- const enabled = body.enabled === true;
4488
- if (groups[name] === undefined) {
4489
- sendJson(response, 400, { ok: false, error: 'group not found / 分组不存在' });
4490
- return;
4491
- }
4492
- pendingRollbacks.clear();
4493
- // Batch toggle: on = every installed member enabled, off = every
4494
- // member disabled. Each member keeps its own persisted flag, so
4495
- // later individual toggles still work (the group switch itself is
4496
- // derived state and never stored).
4497
- const failures = [];
4498
- for (const member of groups[name]) {
4499
- if (!installed.has(member))
4500
- continue;
4501
- if (isNonToggleableLibrary(member))
4502
- continue;
4503
- let result;
4504
- if (enabled && themeNames.has(member)) {
4505
- result = await themes.activateTheme(member);
4989
+ const applyAction = async () => {
4990
+ const installed = new Set(Object.keys(readInstalled(config.profile, activeProfileDir)));
4991
+ // Theme members follow the global one-active-theme rule: a group
4992
+ // holds at most one, and enabling one deactivates every other.
4993
+ const themeNames = await themes.installedThemeNames();
4994
+ let ok = true;
4995
+ let error;
4996
+ let appliedSome = false;
4997
+ let restartMembers = [];
4998
+ let refreshMembers = [];
4999
+ if (action === 'toggle') {
5000
+ const name = typeof body.name === 'string' ? body.name : '';
5001
+ const enabled = body.enabled === true;
5002
+ if (groups[name] === undefined) {
5003
+ sendJson(response, 400, { ok: false, error: 'group not found / 分组不存在' });
5004
+ return;
4506
5005
  }
4507
- else {
4508
- // The same two durable layers the single switch writes (#696):
4509
- // which control flipped a plugin must not change what is on disk.
4510
- result = await switchPluginLayers(member, enabled);
5006
+ pendingRollbacks.clear();
5007
+ // Batch toggle: on = every installed member enabled, off = every
5008
+ // member disabled. Each member keeps its own persisted flag, so
5009
+ // later individual toggles still work (the group switch itself is
5010
+ // derived state and never stored).
5011
+ const failures = [];
5012
+ let failureReason;
5013
+ const replayDeadline = Date.now() + (config.hostReplayWaitMs ?? PROFILE_HMR_REPLAY_WAIT_MS);
5014
+ for (const member of groups[name]) {
5015
+ if (!installed.has(member))
5016
+ continue;
5017
+ if (isNonToggleableLibrary(member))
5018
+ continue;
5019
+ let result;
5020
+ if (enabled && themeNames.has(member)) {
5021
+ result = await switchPluginLayers(member, enabled, keepOff => themes.activateTheme(member, keepOff), replayDeadline);
5022
+ }
5023
+ else {
5024
+ // The same two durable layers the single switch writes (#696):
5025
+ // which control flipped a plugin must not change what is on disk.
5026
+ result = await switchPluginLayers(member, enabled, undefined, replayDeadline);
5027
+ }
5028
+ if (!result.ok) {
5029
+ failures.push(member);
5030
+ failureReason ??= result.reason;
5031
+ continue;
5032
+ }
5033
+ if (result.unchanged)
5034
+ continue;
5035
+ appliedSome = true;
5036
+ // Same live-mismatch signal as the single toggle: a member
5037
+ // whose fiber did not follow the switch needs a boot.
5038
+ const liveAfter = liveNames().has(member);
5039
+ if (result.replayPending === true || (enabled ? !liveAfter : liveAfter))
5040
+ restartMembers.push(member);
5041
+ // Client-part members need a page refresh to show the change.
5042
+ if (packageHasClientPart(activeProfileDir, member))
5043
+ refreshMembers.push(member);
4511
5044
  }
4512
- if (!result.ok)
4513
- failures.push(member);
4514
- // Same live-mismatch signal as the single toggle: a member
4515
- // whose fiber did not follow the switch needs a boot.
4516
- const liveAfter = liveNames().has(member);
4517
- if ((enabled && !liveAfter) || (!enabled && liveAfter))
4518
- restartMembers.push(member);
4519
- // Client-part members need a page refresh to show the change.
4520
- if (packageHasClientPart(activeProfileDir, member))
4521
- refreshMembers.push(member);
4522
- }
4523
- ok = failures.length === 0;
4524
- if (!ok)
4525
- error = `failed to ${enabled ? 'enable' : 'disable'}: ${failures.join(', ')}`;
5045
+ ok = failures.length === 0;
5046
+ if (!ok) {
5047
+ const names = failures.join(', ');
5048
+ const [zh, en] = failureReason?.split(' / ', 2) ?? [];
5049
+ error = '无法' + (enabled ? '启用 ' : '停用 ') + names + '。' + (zh ?? '检查插件设置后重试。')
5050
+ + ' / Could not ' + (enabled ? 'enable ' : 'disable ') + names + '. ' + (en ?? 'Check the plugin settings and retry.');
5051
+ }
5052
+ }
5053
+ else {
5054
+ const state = { groups, groupOrder };
5055
+ const result = action === 'create' ? createGroup(state, body.name)
5056
+ : action === 'rename' ? renameGroup(state, body.name, body.newName)
5057
+ : action === 'delete' ? deleteGroup(state, body.name)
5058
+ : setGroupMembers(state, body.name, body.members, installed, themeNames);
5059
+ ok = result.ok;
5060
+ error = result.error;
5061
+ }
5062
+ if (ok && action !== 'toggle')
5063
+ writeMarketState(activeProfileDir, { disabled, groups, groupOrder });
5064
+ logEvent(ok ? 'info' : 'warn', 'groups', `${action}${typeof body.name === 'string' ? ' ' + body.name : ''}${ok ? '' : ` — ${error ?? ''}`}`);
5065
+ sendJson(response, ok ? 200 : 400, {
5066
+ ok,
5067
+ error,
5068
+ ...(!ok && appliedSome ? { partial: true } : {}),
5069
+ groups,
5070
+ groupOrder,
5071
+ disabled: [...disabled],
5072
+ restartMembers,
5073
+ refreshMembers,
5074
+ });
5075
+ };
5076
+ if (action === 'toggle') {
5077
+ // Hold the lane before reading state or awaiting theme discovery:
5078
+ // an install rollback must not overwrite a concurrent group switch (#1228).
5079
+ await withMutationLock(response, 'write', applyAction);
4526
5080
  }
4527
5081
  else {
4528
- const state = { groups, groupOrder };
4529
- const result = action === 'create' ? createGroup(state, body.name)
4530
- : action === 'rename' ? renameGroup(state, body.name, body.newName)
4531
- : action === 'delete' ? deleteGroup(state, body.name)
4532
- : setGroupMembers(state, body.name, body.members, installed, themeNames);
4533
- ok = result.ok;
4534
- error = result.error;
5082
+ await applyAction();
4535
5083
  }
4536
- if (ok)
4537
- writeMarketState(activeProfileDir, { disabled, groups, groupOrder });
4538
- logEvent(ok ? 'info' : 'warn', 'groups', `${action}${typeof body.name === 'string' ? ' ' + body.name : ''}${ok ? '' : ` — ${error ?? ''}`}`);
4539
- sendJson(response, ok ? 200 : 400, {
4540
- ok,
4541
- error,
4542
- groups,
4543
- groupOrder,
4544
- disabled: [...disabled],
4545
- restartMembers,
4546
- refreshMembers,
4547
- });
4548
5084
  }
4549
5085
  catch (error) {
4550
5086
  const message = error instanceof Error ? error.message : String(error);
@@ -4601,6 +5137,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4601
5137
  drainActive: drainCoordinator.hasActive(),
4602
5138
  drainOperations: drainCoordinator.list(),
4603
5139
  drainHistory: drainJournal.recent(10),
5140
+ startupRepair: config.startupRepair?.(),
5141
+ checkoutRecovery,
4604
5142
  pnpm: await commands.probePnpm(),
4605
5143
  boot: BOOT_ID,
4606
5144
  agentGuardAvailable: agentsGuardAvailable(),
@@ -4647,7 +5185,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4647
5185
  // Same door, one notch wider for the desktop proxy (#903): the
4648
5186
  // card hides a remove button that could only ever answer 403.
4649
5187
  selfUninstallReachable: selfUninstallReachableFrom(request),
4650
- selfManaged: installed['dsh-crate'] !== undefined,
5188
+ selfManaged: installed['dsh-crate'] !== undefined || installed['dsh-crate'] !== undefined,
4651
5189
  // Whether the host took the market's settings namespace (#677).
4652
5190
  // `unsupported-by-host` is 0.1.7 and newer, where settings come from
4653
5191
  // a plugin's Config schema and no third-party namespace is served —
@@ -4767,9 +5305,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
4767
5305
  return;
4768
5306
  }
4769
5307
  // The version the Update button installs, when the client knows it
4770
- // (#1193); anything that is not a plain stable version is ignored.
5308
+ // (#1193); only exact stable versions or Git SHAs set a boundary.
4771
5309
  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));
5310
+ sendJson(response, 200, await updateNotesFor(config.profile, activeProfileDir, name, target !== null && (isStableReleaseVersion(target) || isCommitId(target)) ? target : undefined));
4773
5311
  }
4774
5312
  catch (error) {
4775
5313
  sendJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
@@ -5119,6 +5657,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5119
5657
  sendJson(response, 403, { error: 'untrusted origin' });
5120
5658
  return;
5121
5659
  }
5660
+ let switchedCheckout;
5122
5661
  try {
5123
5662
  const body = (await readJsonBody(request));
5124
5663
  const name = typeof body.name === 'string' ? body.name : '';
@@ -5173,6 +5712,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5173
5712
  sendJson(response, 400, { error: '市场的本地开发链接不会被线上版本替换。 / The market\'s local development link is never replaced by an online release.' });
5174
5713
  return;
5175
5714
  }
5715
+ const originalLink = restore && spec.toLowerCase().startsWith('link:') ? spec : null;
5176
5716
  if (isLocalSpec(spec)) {
5177
5717
  if (!restore) {
5178
5718
  sendJson(response, 400, { error: 'locally linked plugins update from their checkout' });
@@ -5720,7 +6260,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5720
6260
  const lockfileCapture = captureProfileLockfile();
5721
6261
  const previousVersionZh = beforeVersion === null ? '更新前版本未知' : `更新前版本为 v${beforeVersion}`;
5722
6262
  const previousVersionEn = beforeVersion === null ? 'the previous version is unknown' : `the previous version was v${beforeVersion}`;
5723
- const rollbackPlan = restore
6263
+ let rollbackPlan = restore
5724
6264
  ? { available: true, source: { kind: 'manifest' } }
5725
6265
  : !lockfileCapture.ok
5726
6266
  ? { available: false, detail: lockfileCapture.detail }
@@ -5803,6 +6343,25 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5803
6343
  detail: `更新前的来源 ${spec} 不是受支持的精确回滚目标(${previousVersionZh}),因此自动回滚不可用;需要时请从可信来源手工重新安装先前版本。 / The previous source ${spec} is not a supported exact rollback target (${previousVersionEn}), so automatic rollback is unavailable. Reinstall the prior version manually from a trusted source if needed.`,
5804
6344
  lockfileBefore: lockfileCapture.snapshot,
5805
6345
  };
6346
+ // Another release already in this profile is still inside the safety
6347
+ // wait (#1252). pnpm checks the whole lockfile before any change, so
6348
+ // this update would fail exactly as the last one did — and write
6349
+ // and restore the profile on the way. Where a one-shot bypass is
6350
+ // available the run can still succeed, so only the hosts without
6351
+ // one (the official Desktop, mature-only updates) stop here.
6352
+ if (!marketFlags || enforceMatureReleaseAge) {
6353
+ const blocker = headlineBlocker(activeReleaseBlockers(activeProfileDir));
6354
+ if (blocker !== null) {
6355
+ logEvent('info', 'update-held', `${name}: not started — ${blocker.name}@${blocker.version} in this profile is still inside the safety wait${blocker.readyAt === null ? ' (end unknown)' : ` until ${blocker.readyAt}`} (#1252)`);
6356
+ sendJson(response, 409, {
6357
+ ok: false,
6358
+ failureCode: 'PROFILE_RELEASE_BLOCKED',
6359
+ profileBlocked: { name: blocker.name, version: blocker.version, readyAt: blocker.readyAt },
6360
+ error: releaseBlockedMessage(blocker),
6361
+ });
6362
+ return;
6363
+ }
6364
+ }
5806
6365
  // The desktop host names the package a run installed by diffing the
5807
6366
  // profile manifest before and after pnpm. A floating re-resolve is
5808
6367
  // sent as the bare remote URL, which pnpm writes back byte-for-byte
@@ -5877,8 +6436,88 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5877
6436
  // the registry changes. Never retry this update with an age bypass.
5878
6437
  if (!assertDrainMutation(request, response))
5879
6438
  return;
5880
- const result = await (enforceMatureReleaseAge ? runMaturePluginUpdate : runPlugin)(config.profile, addArgs);
6439
+ let checkoutSource = null;
6440
+ if (originalLink !== null) {
6441
+ if (commands.busy?.() === true || commands.packageWritesSettled?.() === false) {
6442
+ sendJson(response, 409, { busy: true, error: 'another plugin operation is running' });
6443
+ return;
6444
+ }
6445
+ try {
6446
+ const prepared = withIdleProfile(activeProfileDir, () => {
6447
+ const current = captureUpdateManifest();
6448
+ if (!current.ok || current.snapshot.dependencies[name] !== originalLink) {
6449
+ throw new Error('the local dependency changed. Refresh the market before switching');
6450
+ }
6451
+ const lockfileBefore = captureProfileLockfile();
6452
+ const link = detachCheckoutLink(activeProfileDir, name, originalLink, saved => {
6453
+ checkoutLinks.record({ name, spec: originalLink, rawTarget: saved.rawTarget });
6454
+ });
6455
+ return { link, manifestBefore: current.snapshot, lockfileBefore };
6456
+ });
6457
+ if (prepared === null) {
6458
+ sendJson(response, 409, { busy: true, error: 'another plugin operation is running' });
6459
+ return;
6460
+ }
6461
+ if (prepared.link !== null) {
6462
+ checkoutSource = { ...prepared, kind: 'linked-checkout', link: prepared.link, target };
6463
+ switchedCheckout = name;
6464
+ rollbackPlan = { available: true, source: checkoutSource };
6465
+ }
6466
+ }
6467
+ catch (error) {
6468
+ const detail = error instanceof Error ? error.message : String(error);
6469
+ sendJson(response, 409, {
6470
+ targetChanged: true,
6471
+ error: `无法安全断开本地插件链接(${detail})。请检查链接后重试。 / Could not safely disconnect the local plugin link (${detail}). Check the link and try again.`,
6472
+ });
6473
+ return;
6474
+ }
6475
+ }
6476
+ const detachedCheckout = checkoutSource?.link;
6477
+ const runCheckoutSwitch = detachedCheckout === undefined ? undefined : async (profile, args) => {
6478
+ if (args[0] !== 'store') {
6479
+ const prepared = withIdleProfile(activeProfileDir, () => {
6480
+ const current = captureUpdateManifest();
6481
+ const dependency = current.ok ? current.snapshot.dependencies[name] : undefined;
6482
+ if (!current.ok || (dependency !== originalLink && dependency !== target)) {
6483
+ throw new Error('the profile dependency changed after the switch started');
6484
+ }
6485
+ keepCheckoutDetached(detachedCheckout);
6486
+ return true;
6487
+ });
6488
+ if (prepared === null)
6489
+ throw new Error('another plugin operation is running');
6490
+ }
6491
+ return commands.runPlugin(profile, args);
6492
+ };
6493
+ let result;
6494
+ try {
6495
+ result = enforceMatureReleaseAge
6496
+ ? await runMaturePluginUpdate(config.profile, addArgs)
6497
+ : await runPlugin(config.profile, addArgs, false, runCheckoutSwitch);
6498
+ }
6499
+ catch (error) {
6500
+ if (checkoutSource !== null && commands.busy?.() !== true) {
6501
+ const attached = restoreLinkedUpdate(name, checkoutSource, false);
6502
+ if (!attached.ok)
6503
+ logEvent('warn', 'update-rollback', `${name}: could not reconnect the checkout — ${attached.detail}`);
6504
+ }
6505
+ throw error;
6506
+ }
5881
6507
  drainPhaseOf(request)?.('verifying');
6508
+ if (checkoutSource !== null && result.repairOnRestart === true) {
6509
+ // A direct add can time out without a remove/reinstall journal
6510
+ // (#928). Wait for the manager before reattaching a checkout
6511
+ // pnpm might still replace.
6512
+ logEvent('warn', 'update', `${name}: the desktop manager did not settle during the source switch. The checkout is retained.`);
6513
+ sendJson(response, 502, {
6514
+ ok: false,
6515
+ timedOut: result.timedOut,
6516
+ failureCode: result.refusalCode,
6517
+ error: '宿主尚未完成切换,源码仍在。等插件管理器结束后检查当前安装来源。如果 profile 仍指向本地但链接缺失,请完全退出 DSH,再恢复原链接。 / The plugin manager has not settled the switch. Your checkout is intact. Check the installed source once it finishes. If the profile still declares the local checkout and its link is missing, quit DSH before reconnecting the link.',
6518
+ });
6519
+ return;
6520
+ }
5882
6521
  const cancelled = result.cancelled;
5883
6522
  // The pin above is the market's own write, so it is undone whenever
5884
6523
  // pnpm did not replace it. Measured on pnpm 11.7.0 and 12.4.1, a
@@ -5909,6 +6548,17 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
5909
6548
  let rollbackOk = true;
5910
6549
  let rollbackDetail = null;
5911
6550
  let hardFailureRollbackError = null;
6551
+ if (checkoutSource !== null
6552
+ && (cancelled || result.busy === true || result.wroteNothing === true
6553
+ || pnpmNeverStarted(result) || pnpmRefusedYoungRelease(result))) {
6554
+ const restored = restoreLinkedUpdate(name, checkoutSource, cancelled);
6555
+ rollbackOk = restored.ok;
6556
+ rollbackDetail = restored.detail;
6557
+ if (!restored.ok) {
6558
+ hardFailureRollbackError = `${name} 的本地链接未能恢复(${restored.detail})。请检查 profile 的安装记录与链接。 / The local link for ${name} could not be restored (${restored.detail}). Check the profile dependency and link.`;
6559
+ logEvent('warn', 'update-rollback', hardFailureRollbackError);
6560
+ }
6561
+ }
5912
6562
  // Set when this failure made the market drop the plugin's own
5913
6563
  // declaration (#663). The client needs it in the ANSWER as well as
5914
6564
  // in state.json: the notice has to appear on the failure the user
@@ -6044,7 +6694,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6044
6694
  spec,
6045
6695
  explicitDir: activeProfileDir,
6046
6696
  }))) {
6047
- if (pnpmBlockedByOpenFiles(result)) {
6697
+ if (checkoutSource === null && pnpmBlockedByOpenFiles(result)) {
6048
6698
  const kept = keepLockedBuild();
6049
6699
  rollbackOk = kept.ok;
6050
6700
  rollbackDetail = kept.detail;
@@ -6077,7 +6727,9 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6077
6727
  logEvent('warn', 'update', `${name}: failed update command; previous build restored and verified`);
6078
6728
  }
6079
6729
  else {
6080
- hardFailureRollbackError = `${name} 更新失败,且更新前的构建未能验证恢复(${rollback.detail ?? 'unknown'});请先检查该 profile,再重新启动。 / ${name} update failed and restoration of the previous build could not be verified (${rollback.detail ?? 'unknown'}); inspect this profile before restarting.`;
6730
+ hardFailureRollbackError = checkoutSource !== null
6731
+ ? `${name} 换用线上版本失败,源码仍在,但无法恢复 profile 中的链接(${rollback.detail ?? 'unknown'})。请完全退出 DSH 后检查本地插件链接。 / The switch to the online release failed for ${name}. The checkout is intact, but its profile link could not be restored (${rollback.detail ?? 'unknown'}). Quit DSH before inspecting that link.`
6732
+ : `${name} 更新失败,且更新前的构建未能验证恢复(${rollback.detail ?? 'unknown'});请先检查该 profile,再重新启动。 / ${name} update failed and restoration of the previous build could not be verified (${rollback.detail ?? 'unknown'}); inspect this profile before restarting.`;
6081
6733
  logEvent('error', 'update-rollback', `${name}: failed update command and restoration of the previous build could not be verified — ${rollback.detail ?? 'unknown'}`);
6082
6734
  }
6083
6735
  }
@@ -6093,7 +6745,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6093
6745
  // ran. The question it asks does not depend on how the run ended —
6094
6746
  // can this package still load? — so ask it here too. A cancel that
6095
6747
  // left the previous build intact (the common case) is untouched.
6096
- if (cancelled && !hasLoadableEntry(activeProfileDir, name)) {
6748
+ if (checkoutSource === null && cancelled && !hasLoadableEntry(activeProfileDir, name)) {
6097
6749
  const kept = keepLockedBuild();
6098
6750
  if (kept.missingEntry) {
6099
6751
  dropBrokenDeclaration('the update was cancelled while pnpm was replacing the directory, and the previous build is incomplete', 'incomplete-build-cancelled');
@@ -6123,8 +6775,14 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6123
6775
  // the checkout already sat on the same version as latest.
6124
6776
  const afterSpec = readInstalled(config.profile, activeProfileDir)[name];
6125
6777
  const stillLocal = afterSpec !== undefined && isLocalSpec(afterSpec);
6126
- if (stillLocal)
6778
+ if (stillLocal) {
6127
6779
  ok = false;
6780
+ if (checkoutSource !== null) {
6781
+ const restored = await rollbackAttemptBuild();
6782
+ rollbackOk = restored.ok;
6783
+ rollbackDetail = restored.detail;
6784
+ }
6785
+ }
6128
6786
  }
6129
6787
  else {
6130
6788
  stale = isStaleUpdate({
@@ -6359,6 +7017,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6359
7017
  ? `${name} 的上游已把包改名为 ${renamedTo}:新版本会装在旧名字下,DSH 下次启动会拒绝这个 profile,所以本次更新已自动回滚、原版本已恢复。目录如果声明了这次改名,「已安装」里会出现迁移入口。 / ${name} was renamed upstream to ${renamedTo}: the new version would sit under the old name and DSH would refuse to start this profile, so the update was rolled back and the previous build restored. If the catalog declares this rename, the installed list offers the migration.`
6360
7018
  : `${name} 的上游已把包改名为 ${renamedTo},且未能验证恢复原版本(${rollbackDetail ?? 'unknown'})。 / ${name} was renamed upstream to ${renamedTo}, and restoration of the previous build could not be verified (${rollbackDetail ?? 'unknown'}).`;
6361
7019
  const cancelDiff = cancelled ? changedSince(beforeInstalled) : null;
7020
+ if (cancelDiff !== null && checkoutSource !== null && !rollbackOk) {
7021
+ if (!cancelDiff.changed.includes(name))
7022
+ cancelDiff.changed.push(name);
7023
+ cancelDiff.partial = true;
7024
+ }
6362
7025
  // Build-script blocks hit updates too (#69): a leftover invalid
6363
7026
  // allowBuilds entry (pnpm's placeholder bug, #56) or a newly
6364
7027
  // build-required dep fails the add with ERR_PNPM_IGNORED_BUILDS.
@@ -6409,7 +7072,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6409
7072
  // Restore the row, scoped to exactly that refusal and to this
6410
7073
  // operation's own target: the read-only stance in #720/#696
6411
7074
  // still holds for every other way a row can disappear.
6412
- if (!ok && !cancelled && result.refusalCode === 'bundle-in-use') {
7075
+ if (!ok && !cancelled && result.refusalCode === 'bundle-in-use' && (checkoutSource === null || rollbackOk)) {
6413
7076
  const targetRowDropped = bundlesDroppedFromProfile(manifestBefore, config.profile, activeProfileDir, new Set(removedDeclaration === null ? [] : [removedDeclaration.name])).includes(name);
6414
7077
  if (targetRowDropped && addProfileBundle(activeProfileDir, name)) {
6415
7078
  logEvent('warn', 'update-bundles-restored', `${name}: the desktop app removed its bundle row before refusing the update (bundle-in-use) — restored it so the plugin still loads on the next boot (#935)`);
@@ -6429,7 +7092,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6429
7092
  // disk — putting the row back restores what the user had before
6430
7093
  // the operation. A successful update keeps the read-only stance
6431
7094
  // (#720/#696), where a missing row may be a deliberate switch-off.
6432
- if (!ok && !cancelled) {
7095
+ if (!ok && !cancelled && checkoutSource === null) {
6433
7096
  const lostRows = bundlesDroppedFromProfile(manifestBefore, config.profile, activeProfileDir, new Set(removedDeclaration === null ? [] : [removedDeclaration.name])).filter(bundle => bundle !== name
6434
7097
  && existsSync(join(activeProfileDir, 'node_modules', bundle, 'package.json')));
6435
7098
  for (const bundle of lostRows) {
@@ -6445,6 +7108,11 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6445
7108
  if (ok)
6446
7109
  recordUpdated(activeProfileDir, [name]);
6447
7110
  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)}`}`);
7111
+ // The run this update just made is what taught the market which
7112
+ // release is in the way (#1252): say it by name, with the time.
7113
+ const learnedBlocker = !ok && !cancelled && pnpmRefusedYoungRelease(result)
7114
+ ? headlineBlocker(activeReleaseBlockers(activeProfileDir))
7115
+ : null;
6448
7116
  // A user-cancelled run is a quiet outcome, not an error.
6449
7117
  sendJson(response, ok || cancelled ? 200 : result.busy === true ? 409 : 502, {
6450
7118
  ok,
@@ -6464,7 +7132,8 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6464
7132
  // The host's own refusal code when it stopped before pnpm
6465
7133
  // (#909): `market-self-update` tells a client that the button
6466
7134
  // cannot work on this host, not that the update was broken.
6467
- failureCode: versionFailureCode ?? result.refusalCode ?? undefined,
7135
+ failureCode: versionFailureCode ?? (result.needsRestart === true ? 'RESTART_REQUIRED' : undefined) ?? result.refusalCode ?? (learnedBlocker === null ? undefined : 'PROFILE_RELEASE_BLOCKED'),
7136
+ ...(learnedBlocker === null ? {} : { profileBlocked: { name: learnedBlocker.name, version: learnedBlocker.version, readyAt: learnedBlocker.readyAt } }),
6468
7137
  renamedTo: renamedTo ?? undefined,
6469
7138
  removedDeclaration: removedDeclaration ?? undefined,
6470
7139
  // #1047: no version could be pinned, so this is the one pnpm
@@ -6506,6 +7175,10 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6506
7175
  logEvent('error', 'update', `route error: ${message}`);
6507
7176
  sendJson(response, 500, { error: message });
6508
7177
  }
7178
+ finally {
7179
+ if (switchedCheckout !== undefined)
7180
+ startCheckoutRepair(switchedCheckout);
7181
+ }
6509
7182
  },
6510
7183
  })),
6511
7184
  registerRoute({
@@ -6898,7 +7571,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
6898
7571
  return;
6899
7572
  }
6900
7573
  const installed = readInstalled(config.profile, activeProfileDir);
6901
- const selfName = installed['dsh-crate'] !== undefined ? 'dsh-crate' : undefined;
7574
+ const selfName = ['dsh-crate', 'dsh-crate'].find(candidate => installed[candidate] !== undefined);
6902
7575
  if (selfName === undefined) {
6903
7576
  sendJson(response, 400, { error: 'the market is not an installed dependency of this profile' });
6904
7577
  return;
@@ -7271,7 +7944,7 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
7271
7944
  // has a concrete thing to go fix, so an override would only help
7272
7945
  // them break their next boot.
7273
7946
  const force = body.force === true;
7274
- if (name === 'dsh-crate') {
7947
+ if (name === 'dsh-crate' || name === 'dsh-crate') {
7275
7948
  sendJson(response, 400, { error: 'the market cannot uninstall itself; use the dsh CLI' });
7276
7949
  return;
7277
7950
  }
@@ -8312,8 +8985,12 @@ export function mountMarketRoutes(host, config, commandRuntime, agentsLookup, ho
8312
8985
  },
8313
8986
  })),
8314
8987
  ];
8988
+ startCheckoutRepair();
8315
8989
  return async () => {
8316
8990
  disposed = true;
8991
+ checkoutRepairRound = undefined;
8992
+ if (checkoutRepairTimer !== undefined)
8993
+ clearTimeout(checkoutRepairTimer);
8317
8994
  updateNotifications.dispose();
8318
8995
  // Release Agent maintenance holds before the routes disappear. This is the
8319
8996
  // disposer half of the single-finally + disposer guarantee (#411): an