dsh-config-manager 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/lib/adapters/test-helpers.d.ts +7 -0
  2. package/lib/adapters/test-helpers.js +11 -0
  3. package/lib/cli/actions.js +1 -1
  4. package/lib/client.d.ts +9 -2
  5. package/lib/client.js +685 -649
  6. package/lib/core/backup.d.ts +9 -1
  7. package/lib/core/backup.js +21 -0
  8. package/lib/core/messages-core.d.ts +3 -0
  9. package/lib/core/messages-core.js +6 -0
  10. package/lib/core/messages.d.ts +5 -0
  11. package/lib/core/messages.js +10 -0
  12. package/lib/core/model-tools.js +2 -0
  13. package/lib/core/phase4-crash-child.js +1 -1
  14. package/lib/core/plugin-cli.d.ts +11 -0
  15. package/lib/core/plugin-cli.js +30 -0
  16. package/lib/core/restore-wal.d.ts +2 -0
  17. package/lib/core/restore-wal.js +11 -6
  18. package/lib/core/restore.d.ts +15 -2
  19. package/lib/core/restore.js +65 -3
  20. package/lib/core/snapshot-diff.js +2 -1
  21. package/lib/core/types.d.ts +32 -0
  22. package/lib/index.d.ts +6 -1
  23. package/lib/index.js +17 -16
  24. package/lib/routes/route-support.d.ts +5 -0
  25. package/lib/routes/route-support.js +28 -2
  26. package/lib/routes/sync.js +3 -0
  27. package/lib/sync/merge-preview-view.d.ts +78 -0
  28. package/lib/sync/merge-preview-view.js +46 -0
  29. package/lib/sync/merge.d.ts +2 -1
  30. package/lib/sync/merge.js +9 -4
  31. package/lib/sync/plugin-removal-apply.d.ts +95 -0
  32. package/lib/sync/plugin-removal-apply.js +158 -0
  33. package/lib/sync/plugin-removals.d.ts +90 -0
  34. package/lib/sync/plugin-removals.js +167 -0
  35. package/lib/sync/sync-engine.d.ts +34 -43
  36. package/lib/sync/sync-engine.js +50 -42
  37. package/lib/sync/sync-selection.d.ts +8 -0
  38. package/lib/sync/sync-selection.js +6 -0
  39. package/lib/sync/workspace-merge.d.ts +8 -1
  40. package/lib/ui/restore-plan-view.js +1 -0
  41. package/lib/ui/sync-settings-view.d.ts +10 -0
  42. package/lib/ui/sync-settings-view.js +2 -0
  43. package/package.json +1 -1
  44. package/src/adapters/test-helpers.ts +10 -0
  45. package/src/cli/actions.ts +1 -1
  46. package/src/client/common/info-hint-guard.test.ts +2 -1
  47. package/src/client/run-store.test.ts +7 -5
  48. package/src/client/run-store.ts +4 -5
  49. package/src/client/sync/SyncPanel.tsx +10 -0
  50. package/src/client/sync/SyncSectionPickerDialog.tsx +17 -1
  51. package/src/client/sync/sync-locales.ts +4 -0
  52. package/src/client/sync/sync-view.ts +6 -0
  53. package/src/core/backup.ts +21 -1
  54. package/src/core/messages-core.ts +6 -0
  55. package/src/core/messages.ts +10 -0
  56. package/src/core/model-tools.ts +2 -0
  57. package/src/core/phase4-crash-child.ts +1 -1
  58. package/src/core/plugin-cli.ts +37 -0
  59. package/src/core/restore-plugin-install.test.ts +116 -0
  60. package/src/core/restore-wal.ts +12 -6
  61. package/src/core/restore.ts +79 -4
  62. package/src/core/smoke.test.ts +5 -0
  63. package/src/core/snapshot-diff.test.ts +1 -1
  64. package/src/core/snapshot-diff.ts +2 -1
  65. package/src/core/types.ts +31 -0
  66. package/src/index.ts +21 -21
  67. package/src/routes/route-support.ts +27 -2
  68. package/src/routes/sync.ts +3 -0
  69. package/src/security/security.test.ts +1 -0
  70. package/src/sync/merge-preview-view.ts +97 -0
  71. package/src/sync/merge.test.ts +17 -15
  72. package/src/sync/merge.ts +10 -3
  73. package/src/sync/plugin-removal-apply.ts +198 -0
  74. package/src/sync/plugin-removals.test.ts +221 -0
  75. package/src/sync/plugin-removals.ts +208 -0
  76. package/src/sync/sync-engine.test.ts +251 -1
  77. package/src/sync/sync-engine.ts +84 -83
  78. package/src/sync/sync-selection.test.ts +29 -7
  79. package/src/sync/sync-selection.ts +13 -0
  80. package/src/sync/workspace-merge.ts +9 -0
  81. package/src/ui/restore-plan-view.test.ts +1 -1
  82. package/src/ui/restore-plan-view.ts +1 -0
  83. package/src/ui/snapshots-view.test.ts +1 -1
  84. package/src/ui/sync-settings-view.test.ts +20 -0
  85. package/src/ui/sync-settings-view.ts +12 -0
@@ -34,7 +34,7 @@ import {
34
34
  classifyDshPluginFailure, readInstalled, readInstalledVersion, resolveProfileDir, runDshPlugin,
35
35
  } from './plugin-cli.ts';
36
36
  import {
37
- collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps,
37
+ collectRestoreWalEntries, createRestoreWal, isExternalPluginKind, restoreActionStepId, restoreWalHandlesFromSteps,
38
38
  } from './restore-wal.ts';
39
39
  import type { RestoreJournalPort, RestoreWalHandle, RestoreWalSettleStatus } from './restore-wal.ts';
40
40
  import type { RestoreResumeHint } from './restore-resume.ts';
@@ -50,6 +50,7 @@ export type RestoreActionKind =
50
50
  | 'hostFileRestore' // 宿主整文件 blob → 写回 $DSH_HOME
51
51
  | 'hostFileRemove' // 快照时不存在、现已出现的宿主文件 → 删除
52
52
  | 'pluginRemove' // 导入期间新增插件 → dsh plugin remove
53
+ | 'pluginInstall' // 跟远端删插件的反向:快照记录了删过、本机现在缺 → dsh plugin add 装回
53
54
  | 'fileRestore' // file 类条目 blob → 写回原路径
54
55
  | 'fileRemove' // file 类条目快照时不存在 → 删除导入写入的文件
55
56
  | 'credentialHint' // 凭据值不可回读 → 人工补录提示(无自动动作)
@@ -63,8 +64,10 @@ export interface RestoreAction {
63
64
  target?: string;
64
65
  /** hostFileRestore/fileRestore:快照内 blob 相对路径(相对 snapshotDir) */
65
66
  blobPath?: string;
66
- /** pluginRemove:插件包名 */
67
+ /** pluginRemove / pluginInstall:插件包名 */
67
68
  pluginName?: string;
69
+ /** pluginInstall:重装目标(name@version;版本未知时就是裸包名) */
70
+ pluginTarget?: string;
68
71
  /** credentialHint:人工提示文本 */
69
72
  manualHint?: string;
70
73
  /** 附加说明(旧快照缺基线 / 离线无法恢复等) */
@@ -82,6 +85,7 @@ export interface RestorePlan {
82
85
  hostFileRestores: number;
83
86
  hostFileRemoves: number;
84
87
  pluginRemoves: number;
88
+ pluginInstalls: number;
85
89
  fileRestores: number;
86
90
  fileRemoves: number;
87
91
  credentialHints: number;
@@ -122,6 +126,13 @@ export interface RestoreOptions {
122
126
  pluginUninstaller?: (
123
127
  name: string, profileDir: string, profile: string,
124
128
  ) => Promise<{ ok: boolean; message?: string }>;
129
+ /**
130
+ * 注入式插件重装器(issue #132 undo;测试用)。缺省走官方 `dsh plugin add <name>@<version>`。
131
+ * 只用于「快照记录过跟删、本机现在缺失」的插件;未记录过的插件绝不重装。
132
+ */
133
+ pluginInstaller?: (
134
+ name: string, target: string, profileDir: string, profile: string,
135
+ ) => Promise<{ ok: boolean; message?: string }>;
125
136
  /** 每项动作执行回调(宿主路由埋点:更新 RunRegistry 进度;index/1-based、total=计划动作数、
126
137
  * detail=动作描述。dry-run/planRestore 不触发) */
127
138
  onAction?: (info: { index: number; total: number; detail: string }) => void;
@@ -163,6 +174,8 @@ export interface RestoreReport {
163
174
  restored: string[];
164
175
  /** 已卸载的插件名 */
165
176
  removedPlugins: string[];
177
+ /** 已按 undo 记录装回的插件目标(name@version;issue #132) */
178
+ installedPlugins: string[];
166
179
  /** 需人工处理的提示(凭据补录等) */
167
180
  manualHints: string[];
168
181
  /** 失败清单 */
@@ -440,6 +453,26 @@ async function defaultPluginUninstaller(
440
453
  return { ok: false, message: msg('restore.uninstallFailedExit', { name, code: String(result.exitCode), tail }) };
441
454
  }
442
455
 
456
+ /**
457
+ * 默认插件重装器(issue #132 undo):官方 dsh plugin add 通道 + 失败分类诊断。
458
+ *
459
+ * 与卸载器同口径:非 0 退出先归类(已知失败码给准确文案),否则回落到退出码 + 输出尾部。
460
+ * 绝不在这里做版本回退/猜测 —— target 就是快照里记下的 `name@version`。
461
+ */
462
+ async function defaultPluginInstaller(
463
+ name: string, target: string, profileDir: string, profile: string, msg: MsgFunc,
464
+ ): Promise<{ ok: boolean; message?: string }> {
465
+ const result = await runDshPlugin(profileDir, profile, ['add', target]);
466
+ if (result.exitCode === 0) return { ok: true };
467
+ const output = `${result.stderr}\n${result.stdout}`.trim();
468
+ const failure = classifyDshPluginFailure(output);
469
+ if (failure !== null) {
470
+ return { ok: false, message: msg('restore.installFailedCode', { name, code: failure.code, message: failure.message }) };
471
+ }
472
+ const tail = output.split('\n').slice(-8).join('\n') || msg('restore.noOutput');
473
+ return { ok: false, message: msg('restore.installFailedExit', { name, code: String(result.exitCode), tail }) };
474
+ }
475
+
443
476
  /* -------------------------------------------------- 统一恢复校验(Phase 4 F8/F9/F25) */
444
477
 
445
478
  /**
@@ -704,6 +737,30 @@ export async function planRestore(opts: RestoreOptions): Promise<RestorePlan> {
704
737
  }
705
738
  }
706
739
 
740
+ // 2') 插件重装(issue #132 跟远端删插件的反向):只认快照里**明确记录过**的跟删项。
741
+ // 为什么不按 beforePlugins 反推「缺了就是被删了」:手动卸载/换包也会让基线里的名字消失,
742
+ // 那种情况下重装是替用户改主意。记录过的才装回;现在已存在的直接跳过。
743
+ const recordedRemovals = snapshot.pluginRemovals ?? [];
744
+ if (recordedRemovals.length > 0) {
745
+ const installed = readInstalled(profileDir);
746
+ for (const removal of recordedRemovals) {
747
+ if (Object.hasOwn(installed, removal.name)) {
748
+ actions.push({
749
+ kind: 'skip',
750
+ description: msg('restore.pluginInstallAlreadyPresent', { name: removal.name }),
751
+ });
752
+ continue;
753
+ }
754
+ actions.push({
755
+ kind: 'pluginInstall',
756
+ description: msg('restore.pluginInstall', { name: removal.name, version: removal.version }),
757
+ target: removal.name,
758
+ pluginName: removal.name,
759
+ pluginTarget: removal.target,
760
+ });
761
+ }
762
+ }
763
+
707
764
  // 3) file 类条目补偿 + credentials 提示(聚合计数供报告)
708
765
  let namespaceCount = 0;
709
766
  let patchLineCount = 0;
@@ -860,7 +917,7 @@ export async function planRestore(opts: RestoreOptions): Promise<RestorePlan> {
860
917
 
861
918
  function summarizeActions(actions: RestoreAction[]): RestorePlan['summary'] {
862
919
  const summary: RestorePlan['summary'] = {
863
- hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0,
920
+ hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0, pluginInstalls: 0,
864
921
  fileRestores: 0, fileRemoves: 0, credentialHints: 0, skips: 0,
865
922
  };
866
923
  for (const a of actions) {
@@ -868,6 +925,7 @@ function summarizeActions(actions: RestoreAction[]): RestorePlan['summary'] {
868
925
  case 'hostFileRestore': summary.hostFileRestores += 1; break;
869
926
  case 'hostFileRemove': summary.hostFileRemoves += 1; break;
870
927
  case 'pluginRemove': summary.pluginRemoves += 1; break;
928
+ case 'pluginInstall': summary.pluginInstalls += 1; break;
871
929
  case 'fileRestore': summary.fileRestores += 1; break;
872
930
  case 'fileRemove': summary.fileRemoves += 1; break;
873
931
  case 'credentialHint': summary.credentialHints += 1; break;
@@ -892,11 +950,14 @@ export async function restore(opts: RestoreOptions): Promise<RestoreReport> {
892
950
  const profileDir = resolveProfileDir(homeDir, profile);
893
951
  const uninstaller = opts.pluginUninstaller
894
952
  ?? ((name: string, dir: string, prof: string) => defaultPluginUninstaller(name, dir, prof, msg));
953
+ const installer = opts.pluginInstaller
954
+ ?? ((name: string, target: string, dir: string, prof: string) => defaultPluginInstaller(name, target, dir, prof, msg));
895
955
 
896
956
  const report: RestoreReport = {
897
957
  snapshotId: plan.snapshotId,
898
958
  restored: [],
899
959
  removedPlugins: [],
960
+ installedPlugins: [],
900
961
  manualHints: [],
901
962
  failed: [],
902
963
  skipped: [],
@@ -936,7 +997,7 @@ export async function restore(opts: RestoreOptions): Promise<RestoreReport> {
936
997
  }
937
998
  /** 文件类动作的绝对目标(reconcile 直接拿它读盘算指纹);插件卸载/越界目标 → null(不可指纹)。 */
938
999
  function walAbsOf(action: RestoreAction): string | null {
939
- if (action.kind === 'pluginRemove' || action.target === undefined) return null;
1000
+ if (isExternalPluginKind(action.kind) || action.target === undefined) return null;
940
1001
  try {
941
1002
  return homeAbs(homeDir, action.target, msg);
942
1003
  } catch {
@@ -1013,6 +1074,20 @@ export async function restore(opts: RestoreOptions): Promise<RestoreReport> {
1013
1074
  }
1014
1075
  break;
1015
1076
  }
1077
+ case 'pluginInstall': {
1078
+ const target = action.pluginTarget ?? action.pluginName!;
1079
+ const result = await installer(action.pluginName!, target, profileDir, profile);
1080
+ if (result.ok) {
1081
+ report.installedPlugins.push(target);
1082
+ } else {
1083
+ const reason = result.message ?? msg('restore.pluginInstallFailed');
1084
+ report.failed.push({ item: `plugin:${action.pluginName}`, reason });
1085
+ // 同卸载分支:外部副作用没做成 → attention(绝不记 done)
1086
+ settleStatus = 'attention';
1087
+ settleMessage = reason;
1088
+ }
1089
+ break;
1090
+ }
1016
1091
  case 'credentialHint':
1017
1092
  report.manualHints.push(action.manualHint ?? action.description);
1018
1093
  break;
@@ -113,6 +113,11 @@ class MemPlugins implements PluginsFacade {
113
113
  this.installed.set(pkg, { name: pkg, version: '1.0.0', enabled: true });
114
114
  return { needsRestart: true };
115
115
  }
116
+ /** issue #132:卸载(跟随远端删除);缺失即抛,模拟真实 CLI 的失败语义。 */
117
+ async uninstall(pkg: string) {
118
+ if (!this.installed.delete(pkg)) throw new Error(`plugin ${pkg} is not installed`);
119
+ return { needsRestart: true };
120
+ }
116
121
  }
117
122
 
118
123
  class MemWorkspace implements WorkspaceFacade {
@@ -52,7 +52,7 @@ function planWith(actions: RestorePlan['actions']): RestorePlan {
52
52
  createdAt: '2026-09-21T00:00:00.000Z',
53
53
  sourceZip: 'x.zip',
54
54
  pluginBaselineConfirmed: true,
55
- summary: { hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0, fileRestores: 0, fileRemoves: 0, credentialHints: 0, skips: 0 },
55
+ summary: { hostFileRestores: 0, hostFileRemoves: 0, pluginRemoves: 0, pluginInstalls: 0, fileRestores: 0, fileRemoves: 0, credentialHints: 0, skips: 0 },
56
56
  actions,
57
57
  };
58
58
  }
@@ -139,6 +139,7 @@ function statusOf(kind: RestoreActionKind, beforeExists: boolean): SnapshotChang
139
139
  case 'fileRemove':
140
140
  return 'deleted';
141
141
  case 'pluginRemove':
142
+ case 'pluginInstall':
142
143
  return 'plugin';
143
144
  case 'credentialHint':
144
145
  return 'hint';
@@ -293,7 +294,7 @@ export async function summarizeRestoreChanges(opts: {
293
294
  entries.push(entry);
294
295
  continue;
295
296
  }
296
- if (action.kind === 'pluginRemove') entry.status = 'plugin';
297
+ if (action.kind === 'pluginRemove' || action.kind === 'pluginInstall') entry.status = 'plugin';
297
298
  else if (action.kind === 'credentialHint') entry.status = 'hint';
298
299
  else entry.status = 'skip';
299
300
  entries.push(entry);
package/src/core/types.ts CHANGED
@@ -259,6 +259,14 @@ export interface PluginsFacade {
259
259
  * signal 可选:中止时宿主应 kill 子进程并清理半装状态(恢复 package.json + 删 node_modules/<pkg>)。
260
260
  */
261
261
  install(pkg: string, target?: string, signal?: AbortSignal): Promise<{ needsRestart: boolean; installedVersion?: string | null }>;
262
+ /**
263
+ * 卸载插件(issue #132 跟随远端删除;`dsh plugin remove <pkg>`)。
264
+ *
265
+ * 失败即抛(消息经 `classifyDshPluginFailure` 给出可操作诊断,例如 desktop 保留档案被 CLI 拒绝)。
266
+ * 调用方逐项记录 warning、**不阻断**其余项:一次卸载失败不该让整轮同步回滚。
267
+ * `signal` 中止语义与 install 一致(宿主 kill 子进程)。
268
+ */
269
+ uninstall(pkg: string, signal?: AbortSignal): Promise<{ needsRestart: boolean }>;
262
270
  }
263
271
 
264
272
  export interface WorkspaceFacade {
@@ -1021,6 +1029,21 @@ export interface HostFileBackup {
1021
1029
  unreadable?: boolean;
1022
1030
  }
1023
1031
 
1032
+ /**
1033
+ * 一轮同步里**跟随远端删除**掉的插件(issue #132)。
1034
+ *
1035
+ * 为什么写进快照:undo 必须能把用户装回去 —— 删插件是不可逆的外部副作用,只有快照记得
1036
+ * 「删的是谁、哪个版本」。有意**不进** computeMetadataHash(它只覆盖 entries/hostFileBackups/
1037
+ * beforePlugins 三样破坏性内容),因此记录它不需要重写 manifest 与 blob。
1038
+ */
1039
+ export interface SnapshotPluginRemoval {
1040
+ name: string;
1041
+ /** 删除时本机已装的版本(快照记的是事实;重装用 target = name@version) */
1042
+ version: string;
1043
+ /** 重装目标(name@version;版本未知时就是裸包名) */
1044
+ target: string;
1045
+ }
1046
+
1024
1047
  export interface Snapshot {
1025
1048
  id: string;
1026
1049
  createdAt: string;
@@ -1030,6 +1053,8 @@ export interface Snapshot {
1030
1053
  status?: SnapshotStatus;
1031
1054
  /** 导入前已安装插件清单(M2 restore 撤销插件时与当前已装对比)。旧快照缺省 */
1032
1055
  beforePlugins?: PluginInfo[];
1056
+ /** 本轮跟随远端删除的插件(issue #132;restore 计划里对称地重装)。旧快照缺省 */
1057
+ pluginRemovals?: SnapshotPluginRemoval[];
1033
1058
  /** 宿主整文件备份(settings.yaml / settings.json / cordis.patch.yml / profiles/<p>/cordis.patch.yml)。旧快照缺省 */
1034
1059
  hostFileBackups?: HostFileBackup[];
1035
1060
  /**
@@ -1079,6 +1104,12 @@ export interface SnapshotStore {
1079
1104
  readBlob(id: string, blobPath: string): Promise<Uint8Array>;
1080
1105
  /** 标记快照生命周期状态(导入成功→done;失败回滚→rolled-back;持久化由实现负责) */
1081
1106
  updateStatus(id: string, status: SnapshotStatus): Promise<void>;
1107
+ /**
1108
+ * 记录「本轮跟删掉的插件」(issue #132):只重写 snapshot.json 的这一个字段,
1109
+ * 不动 manifest 与 blob(它不在 metadataHash 覆盖面内)。不可用时调用方**跳过记录**并靠
1110
+ * 报告里的重装目标人工兜底,绝不因为记不上就中止同步。
1111
+ */
1112
+ recordPluginRemovals?(id: string, removals: SnapshotPluginRemoval[]): Promise<void>;
1082
1113
  }
1083
1114
 
1084
1115
  /**
package/src/index.ts CHANGED
@@ -92,7 +92,7 @@ import { ROLLBACK_ACTIVITY_FILE_NAME, RollbackSessionActivity } from './core/rol
92
92
  import { isRollbackEnabled, onRollbackEnabledChange, setRollbackEnabled } from './core/rollback-gate.ts'
93
93
  // t3:宿主斜杠命令 /rollback(与 HTTP 路由同一道写入门;命令服务惰取,未组合时安静跳过)。
94
94
  import { agentSessionFactsOf, registerRollbackCommand, type CommandServiceLike, type RollbackCommandHost } from './core/command-rollback.ts'
95
- import { cleanupAbortedInstall, hasDshBundlePatch, installAnchorFromProfileContext, installErrorFor, readInstalledVersion, reconcileBundlesAfterInstall, listInstalledPlugins, profileNameFromProfileContext, resolveProcessProfileName, resolveProfileDir, readProfileManifest, runDshPlugin, validateProfileName } from './core/plugin-cli.ts'
95
+ import { cleanupAbortedInstall, hasDshBundlePatch, installAnchorFromProfileContext, installErrorFor, uninstallViaCli, readInstalledVersion, reconcileBundlesAfterInstall, listInstalledPlugins, profileNameFromProfileContext, resolveProcessProfileName, resolveProfileDir, readProfileManifest, runDshPlugin, validateProfileName } from './core/plugin-cli.ts'
96
96
  import { ImportUserSkippedError, type ConfigAdapter, type CredentialsFacade, type ExportUnit, type FileSystemFacade, type HostContext, type ImportDecisions, type ImportPlan, type NamedNamespaceInfo, type NamespaceInfo, type PatchFileFacade, type PluginInfo, type PluginsFacade, type Portability, type SecretScanner, type SessionFormatDisposition, type SessionMoveResult, type SessionParentRelation, type SessionRewriteResult, type SessionStoreFacade, type SettingsFacade, type SkillDefinitionView, type SkillStoreFacade, type SkillSummaryView, type WorkspaceFacade } from './core/types.ts'
97
97
  import { PLUGIN_NPM_PACKAGE } from './core/update-check.ts'
98
98
  import { planSelfUpdate, runSelfUpdate, type SelfUpdateOutcome } from './core/self-update.ts'
@@ -183,7 +183,7 @@ export const name = 'config-manager'
183
183
  export const inject = ['settings', 'credentials']
184
184
 
185
185
  /** Plugin version, kept in sync with package.json ("version"). */
186
- export const PLUGIN_VERSION = '0.7.0'
186
+ export const PLUGIN_VERSION = '0.8.0'
187
187
 
188
188
  /** Plugin own package name — excluded from its own exported plugins list. */
189
189
  const PLUGIN_NAME = 'dsh-config-manager'
@@ -597,6 +597,11 @@ export class DshPluginsFacade implements PluginsFacade {
597
597
  // 回读实际落盘版本:调用方据此校验升级是否真的生效(issue #101),而不是只看子进程退出码。
598
598
  return { needsRestart: true, installedVersion: readInstalledVersion(profileDir, pkg) }
599
599
  }
600
+
601
+ /** 卸载插件(issue #132):走官方 CLI `dsh plugin remove`,不自己改 package.json、也不补对账。 */
602
+ uninstall(pkg: string, signal?: AbortSignal): Promise<{ needsRestart: boolean }> {
603
+ return uninstallViaCli(this.homeDir, this.profile, pkg, this.runner, signal)
604
+ }
600
605
  }
601
606
 
602
607
  /** Workspace facade over the real ctx.workspaceRegistry. */
@@ -2240,7 +2245,7 @@ export interface PluginDiagnostics {
2240
2245
  bundles: string[]
2241
2246
  }
2242
2247
 
2243
- type SelectionView = { mode: SyncSelectionMode; sections: SectionId[]; sessionsLimit: number; sessionsInclude: string[]; encrypt: boolean; includeSecrets: boolean }
2248
+ type SelectionView = { mode: SyncSelectionMode; sections: SectionId[]; sessionsLimit: number; sessionsInclude: string[]; encrypt: boolean; includeSecrets: boolean; deletePlugins: boolean }
2244
2249
 
2245
2250
 
2246
2251
  /**
@@ -2641,21 +2646,17 @@ function makeRoutes(deps: RoutesDeps): {
2641
2646
 
2642
2647
  /** 全部通道的分区选择视图(status 路由一次返回;UI 按当前 tab 取对应通道)。 */
2643
2648
  /** 指定通道的分区选择视图。 */
2644
- const selectionView = async (channel: SyncTransportType): Promise<SelectionView> => {
2645
- const sel = await ensureSelectionLoaded(channel)
2646
- return { mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets }
2647
- }
2649
+ /** SyncSelection → SelectionView(字段白名单;密码值永不进视图)。 */
2650
+ const toSelectionView = (sel: SyncSelection): SelectionView =>
2651
+ ({ mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets, deletePlugins: sel.deletePlugins })
2652
+
2653
+ const selectionView = async (channel: SyncTransportType): Promise<SelectionView> => toSelectionView(await ensureSelectionLoaded(channel))
2648
2654
 
2649
2655
  const selectionViewByChannel = async (): Promise<Record<SyncTransportType, SelectionView>> => {
2650
2656
  const all = await readAllSyncSelections(syncDir)
2651
- const view = (sel: SyncSelection): SelectionView =>
2652
- ({ mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets })
2653
2657
  // 通道集合来自唯一枚举(SYNC_CHANNELS);不得穷举字面量(漏一处即该通道状态静默缺失)
2654
2658
  const out = {} as Record<SyncTransportType, SelectionView>
2655
- for (const channel of SYNC_CHANNELS) {
2656
- selectionCache[channel] = all[channel]
2657
- out[channel] = view(all[channel])
2658
- }
2659
+ for (const channel of SYNC_CHANNELS) { selectionCache[channel] = all[channel]; out[channel] = toSelectionView(all[channel]) }
2659
2660
  return out
2660
2661
  }
2661
2662
 
@@ -2757,7 +2758,8 @@ function makeRoutes(deps: RoutesDeps): {
2757
2758
  transport = makeGitTransport(cfg.git.repoUrl, cfg.git.subdir)
2758
2759
  }
2759
2760
  const channel: SyncTransportType = channelOf(cfg)
2760
- const sections = effectiveSections(selectionCache[channel] ?? defaultSyncSelection())
2761
+ const selection = selectionCache[channel] ?? defaultSyncSelection()
2762
+ const sections = effectiveSections(selection)
2761
2763
  return new SyncEngine({
2762
2764
  ctx: host,
2763
2765
  transport,
@@ -2768,11 +2770,10 @@ function makeRoutes(deps: RoutesDeps): {
2768
2770
  zipDir: tmpDir,
2769
2771
  msg,
2770
2772
  ...(sections === undefined ? {} : { sections }),
2771
- ...(engineOpts.optInSections === undefined || engineOpts.optInSections.length === 0
2772
- ? {}
2773
- : { optInSections: engineOpts.optInSections }),
2774
- // m-retention:远端快照裁剪与本地备份产物共用同一份 GFS 保留策略(缺省 = 最近 10 个,
2775
- // 与改造前逐字等价);用户改完策略即时生效(每次 prune 都重读)。
2773
+ // issue #132:开关开 = 授权(手动/自动同判据);self 守卫防同步把自己删掉
2774
+ deletePlugins: selection.deletePlugins, selfPluginName: PLUGIN_NPM_PACKAGE,
2775
+ ...(engineOpts.optInSections?.length ? { optInSections: engineOpts.optInSections } : {}),
2776
+ // m-retention:远端裁剪与本地备份共用 GFS 策略(缺省最近 10 个,每次 prune 重读 ⇒ 改完即时生效)。
2776
2777
  retentionPolicy: () => retentionPolicyProvider(),
2777
2778
  })
2778
2779
  }
@@ -3795,8 +3796,7 @@ export function apply(ctx: Context, config?: Config): void {
3795
3796
  namespaces: async () => (await ctx.settings.describe({ redactSecrets: true })).map((d) => String(d.ns)),
3796
3797
  // Sessions 分区默认关(含敏感内容):挂载 adapter 供 Custom Export 显式勾选(§3.3/§15)。
3797
3798
  includeSessions: true,
3798
- // 导出 plugins 分区时不列本插件自身,避免备份中的自引用条目。
3799
- selfPluginName: PLUGIN_NAME,
3799
+ selfPluginName: PLUGIN_NAME, // 导出 plugins 分区时不列本插件自身,避免备份里的自引用条目
3800
3800
  // pluginFiles 扩展:额外白名单文件 + 约定配置目录(都相对 ~/.dsh 根),支持导出更多插件配置。
3801
3801
  pluginFiles: config?.pluginFiles,
3802
3802
  pluginFilesDir: config?.pluginFilesDir,
@@ -32,7 +32,7 @@ import type { CredentialProvider } from '@deepseek-ai/dsh-credentials'
32
32
  import { engineMsg } from '../core/engine-locale.ts'
33
33
  import { createPreRestoreAttemptDir } from '../core/restore.ts'
34
34
  import type { RestoreActionKind, RestorePlan, RestoreReport } from '../core/restore.ts'
35
- import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.ts'
35
+ import { collectRestoreWalEntries, createRestoreWal, isExternalPluginKind, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.ts'
36
36
  import type { RestoreResumeHint } from '../core/restore-resume.ts'
37
37
  import type { RestoreJournalPort, RestoreWalHandle, RestoreWalSettleStatus } from '../core/restore-wal.ts'
38
38
  import type { SyncConfig, SyncTransportType } from '../sync/sync-config.ts'
@@ -554,6 +554,8 @@ export interface RestoreExecutor {
554
554
  removeHome(relPath: string): Promise<void>
555
555
  /** 卸载插件(官方通道);失败返回 { ok:false, message } */
556
556
  uninstallPlugin(name: string): Promise<{ ok: boolean; message?: string }>
557
+ /** 装回跟远端删掉的插件(官方通道,issue 132 的反向);失败返回 { ok:false, message } */
558
+ installPlugin(name: string, target: string): Promise<{ ok: boolean; message?: string }>
557
559
  /**
558
560
  * home 相对路径 → 磁盘绝对路径(逐动作 WAL 用:journal 的 ref 必须是绝对路径,
559
561
  * reconcile 的 verifyStepFingerprint 直接拿它读盘算指纹)。缺省 = 不登记 WAL。
@@ -578,6 +580,7 @@ export async function executeRestorePlan(
578
580
  snapshotId: plan.snapshotId,
579
581
  restored: [],
580
582
  removedPlugins: [],
583
+ installedPlugins: [],
581
584
  manualHints: [],
582
585
  failed: [],
583
586
  skipped: [],
@@ -589,7 +592,7 @@ export async function executeRestorePlan(
589
592
  const walByAction = new Map<(typeof plan.actions)[number], RestoreWalHandle | undefined>()
590
593
  const resume = resumeHint
591
594
  const absOf = (action: (typeof plan.actions)[number]): string | null =>
592
- action.kind === 'pluginRemove' || action.target === undefined || exec.absPath === undefined
595
+ isExternalPluginKind(action.kind) || action.target === undefined || exec.absPath === undefined
593
596
  ? null
594
597
  : exec.absPath(action.target)
595
598
  if (wal !== null && exec.absPath !== undefined) {
@@ -656,6 +659,21 @@ export async function executeRestorePlan(
656
659
  }
657
660
  break
658
661
  }
662
+ case 'pluginInstall': {
663
+ const name = action.pluginName
664
+ const target = action.pluginTarget ?? name
665
+ if (name === undefined || target === undefined) throw new Error(engineMsg('restore.missingPluginName'))
666
+ const result = await exec.installPlugin(name, target)
667
+ if (result.ok) {
668
+ report.installedPlugins.push(target)
669
+ } else {
670
+ const reason = result.message ?? engineMsg('restore.pluginInstallFailed')
671
+ report.failed.push({ item: `plugin:${name}`, reason })
672
+ settleStatus = 'attention'
673
+ settleMessage = reason
674
+ }
675
+ break
676
+ }
659
677
  case 'credentialHint':
660
678
  report.manualHints.push(action.manualHint ?? action.description)
661
679
  break
@@ -720,6 +738,13 @@ export function makeRestoreExecutor(snapshotDir: string, host: HostContext, prof
720
738
  const tail = output.split('\n').slice(-8).join('\n') || msgOf(host)('host.restoreNoOutput')
721
739
  return { ok: false, message: msgOf(host)('host.restoreUninstallFailed', { name, code: String(result.exitCode), tail }) }
722
740
  },
741
+ installPlugin: async (name, target) => {
742
+ const result = await runDshPlugin(profileDir, profile, ['add', target])
743
+ if (result.exitCode === 0) return { ok: true }
744
+ const output = `${result.stderr}\n${result.stdout}`.trim()
745
+ const tail = output.split('\n').slice(-8).join('\n') || msgOf(host)('host.restoreNoOutput')
746
+ return { ok: false, message: engineMsg('restore.installFailedExit', { name, code: String(result.exitCode), tail }) }
747
+ },
723
748
  }
724
749
  }
725
750
 
@@ -1220,6 +1220,9 @@ export function syncRoutes(env: RoutesEnv): WebRoute[] {
1220
1220
  encrypt: body['encrypt'] === true,
1221
1221
  // 安全兜底:includeSecrets 必须同时 encrypt(密钥绝不明文进同步通道)
1222
1222
  includeSecrets: body['includeSecrets'] === true && body['encrypt'] === true,
1223
+ // issue #132:跟随远端删除插件。缺省关;请求体非 true 一律按关处理
1224
+ // (重新保存表单时收起开关 = 明确关掉,不留上一次的 true)
1225
+ deletePlugins: body['deletePlugins'] === true,
1223
1226
  }
1224
1227
  // 加密/解密密码持久化(用户要求:勾选即记住,取消勾选或主动删除才清)。
1225
1228
  // 值只写进 DSH credentials(绝不进 sync-selection.json / 日志 / 响应);
@@ -200,6 +200,7 @@ class MemCredentials implements CredentialsFacade {
200
200
  class MemPlugins implements PluginsFacade {
201
201
  async listInstalled() { return []; }
202
202
  async install(_pkg: string, _spec?: string) { return { needsRestart: true }; }
203
+ async uninstall(_pkg: string) { return { needsRestart: true }; }
203
204
  }
204
205
 
205
206
  class MemWorkspace implements WorkspaceFacade {
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 合并预览的**可渲染视图**(分区结果 → 界面结构),与「预览产物能否与基线比对」的判定。
3
+ *
4
+ * 为什么独立成文件:sync-engine 已顶到文件体量棘轮(tests/file-size-ratchet.test.ts),
5
+ * 而这两件事都只依赖 merge.ts 的结果类型与预览文本工具,不碰引擎实例状态;放这里可单测,
6
+ * 也让引擎只管编排。类型经 sync-engine 再导出,既有导入方(model-tools 等)无需改动。
7
+ */
8
+ import { isLocalPluginSpec } from '../core/local-plugin-pack.ts';
9
+ import type { SectionData, SectionId } from '../schema/types.ts';
10
+ import type { MergeConflictReason, MergeSectionResult } from './merge.ts';
11
+ import { previewTextOf } from './merge-preview-text.ts';
12
+
13
+ /** plan 的单个分区结果 → 预览视图(三侧都只回传可读文本,绝不回传原始值)。 */
14
+ export function mergePreviewSectionView(result: MergeSectionResult): MergePreviewSectionView {
15
+ const conflicts: MergePreviewConflictView[] = result.conflicts.map((c) => ({
16
+ path: c.path,
17
+ kind: c.kind,
18
+ ...(c.reason !== undefined ? { reason: c.reason } : {}),
19
+ localPreview: previewTextOf(c.local),
20
+ remotePreview: previewTextOf(c.remote),
21
+ ancestorPreview: previewTextOf(c.ancestor),
22
+ }));
23
+ return {
24
+ id: result.id,
25
+ decision: result.decision,
26
+ ...(result.autoMerged !== undefined ? { autoMerged: result.autoMerged } : {}),
27
+ conflictCount: result.conflicts.length,
28
+ conflicts,
29
+ };
30
+ }
31
+
32
+ /**
33
+ * issue #91:走只读 `preview()` 拿到的产物,能否直接与该分区**基线 hash**(push 时按 export() 产物记录)比对。
34
+ *
35
+ * 为什么需要这个判定:`plugins` 适配器的 `preview()` 走 `collect(…, pack=false)` —— 刻意**不做**
36
+ * 本地源(`link:` / `file:`)插件的 `npm pack`。于是当 profile 里存在本地源插件时,预览产物既没有
37
+ * `localTarballs`、插件 spec 也保持原样(export() 会改写成 `file:<tarball>`),与基线**不同口径**:
38
+ * 此时既不能断言「无变化」(本地插件源码改了体积/内容,预览看不见),也不该为了比对去打包
39
+ * (那正是本 issue 的缺陷本身)。
40
+ *
41
+ * 返回 true = 该分区本趟**不可比** ⇒ 调用方只能保守报「有变化」并如实说明原因。
42
+ * 其余分区的 preview() 产物与 export() 逐字节相同(文件类分区不走 preview(),见 previewPush)。
43
+ */
44
+ export function previewCaliberDiffersFromExport(sectionId: SectionId, data: SectionData): boolean {
45
+ if (sectionId !== 'plugins') return false;
46
+ const plugins = (data as { plugins?: { spec?: string }[] }).plugins;
47
+ return Array.isArray(plugins) && plugins.some((p) => isLocalPluginSpec(p?.spec));
48
+ }
49
+
50
+ /** previewMerge 的单条冲突视图(三侧文本都已截断 + redact;绝不回传原始值对象)。 */
51
+ export interface MergePreviewConflictView {
52
+ /** 冲突位置:JSON 分区是 top-level key;文件类分区是 relativePath;'$' = 整分区冲突。 */
53
+ path: string;
54
+ kind: 'key' | 'file';
55
+ /** 冲突成因(可选:旧数据/旧 merge 结果没有该字段,界面缺省按 'both-modified' 措辞)。 */
56
+ reason?: MergeConflictReason;
57
+ /** 本机侧的可读预览(≤ 2 KiB,超出截断加省略号;已过 redact())。 */
58
+ localPreview: string;
59
+ /** 远端侧的可读预览(同上)。 */
60
+ remotePreview: string;
61
+ /** 共同祖先侧的可读预览(同上;无祖先时为空串)。 */
62
+ ancestorPreview: string;
63
+ }
64
+
65
+ /** previewMerge 的单个分区视图。 */
66
+ export interface MergePreviewSectionView {
67
+ id: SectionId;
68
+ decision: MergeSectionResult['decision'];
69
+ /** 自动合并并入的变更点数量(仅 decision === 'merge' 时有意义;缺省 = 未统计)。 */
70
+ autoMerged?: number;
71
+ conflictCount: number;
72
+ conflicts: MergePreviewConflictView[];
73
+ }
74
+
75
+ /** previewMerge 结果(只读、零写入)。 */
76
+ export interface MergePreview {
77
+ /** 预览是否成功产出(远端无快照 → false + message,分区清单为空)。 */
78
+ ok: boolean;
79
+ /** 本次预览针对的**远端**快照 id;'' = 远端无快照。 */
80
+ snapshotId: string;
81
+ /** 是否拿到了本地祖先副本(false = 退化为两方合并 → 所有双侧差异都会呈现为 conflict)。 */
82
+ hasAncestor: boolean;
83
+ sections: MergePreviewSectionView[];
84
+ /** 与 risk.ts 的 classifyMergePlan 同口径计数:auto = 可自动应用,review = 需人工,conflicts = 冲突,skipped = 跳过。 */
85
+ summary: { auto: number; review: number; conflicts: number; skipped: number };
86
+ message?: string;
87
+ reason?: 'remote-empty'; // 远端没有任何快照:首次同步的正常起点,不是故障(客户端据此给「先推送」引导,issue 116)
88
+ /**
89
+ * 本轮合并**将卸载**的插件(issue #132):确认页必须单列出来,用户据此可以整轮取消。
90
+ * 仅在 plugins 分区可应用(useRemote/keepLocal/merge)时才有条目 —— 分区冲突时不删。
91
+ */
92
+ pluginRemovals?: { name: string; version: string }[];
93
+ /** 远端删了、本机却改过 → 不删,等人工裁决(与 conflict 清单同语义,这里为插件专列) */
94
+ pluginRemovalConflicts?: { name: string; ancestorVersion: string; localVersion: string }[];
95
+ /** 考察过但没删的条目及原因(含开关关闭 = 'switch-off',界面据此如实说明) */
96
+ pluginRemovalSkipped?: { name: string; reason: string }[];
97
+ }
@@ -132,34 +132,36 @@ test('merge: 深层嵌套 JSON 合并(不同叶子自动合,未知字段两
132
132
  assert.equal(merged.ui['remoteOnly'], true, '远端新增的未知字段不得被静默丢弃');
133
133
  });
134
134
 
135
+ // 注意:这里**故意**用 settings 的普通数组做样本。plugins 自 issue #132 起有了按包名的专属
136
+ // 合并钩子(见 plugin-removals.test.ts),不再走通用「数组两侧各改即冲突」的口径。
135
137
  test('merge: 数组双侧都改且不同 → conflict(reason=array),不按索引猜', () => {
136
- const anc: SectionData = { version: 1, plugins: [{ spec: 'a' }] } as unknown as SectionData;
137
- const loc: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
138
- const rem: SectionData = { version: 1, plugins: [{ spec: 'c' }] } as unknown as SectionData;
139
- const plan = merge({ plugins: loc }, { plugins: rem }, { plugins: anc });
138
+ const anc: SectionData = { version: 1, list: [{ spec: 'a' }] } as unknown as SectionData;
139
+ const loc: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
140
+ const rem: SectionData = { version: 1, list: [{ spec: 'c' }] } as unknown as SectionData;
141
+ const plan = merge({ settings: loc }, { settings: rem }, { settings: anc });
140
142
  const r = plan.sections[0]!;
141
143
  assert.equal(r.decision, 'conflict');
142
- assert.equal(r.conflicts[0]!.path, 'plugins');
144
+ assert.equal(r.conflicts[0]!.path, 'list');
143
145
  assert.equal(r.conflicts[0]!.reason, 'array');
144
146
  });
145
147
 
146
148
  test('merge: 数组仅一侧改 → 采纳该侧(另一侧键的改动同时保住)', () => {
147
- const anc: SectionData = { version: 1, plugins: [{ spec: 'a' }], note: 'x' } as unknown as SectionData;
148
- const loc: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }], note: 'x' } as unknown as SectionData;
149
- const rem: SectionData = { version: 1, plugins: [{ spec: 'a' }], note: 'y' } as unknown as SectionData;
150
- const plan = merge({ plugins: loc }, { plugins: rem }, { plugins: anc });
149
+ const anc: SectionData = { version: 1, list: [{ spec: 'a' }], note: 'x' } as unknown as SectionData;
150
+ const loc: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }], note: 'x' } as unknown as SectionData;
151
+ const rem: SectionData = { version: 1, list: [{ spec: 'a' }], note: 'y' } as unknown as SectionData;
152
+ const plan = merge({ settings: loc }, { settings: rem }, { settings: anc });
151
153
  const r = plan.sections[0]!;
152
154
  assert.equal(r.decision, 'merge');
153
- const merged = r.merged as unknown as { plugins: unknown[]; note: string };
154
- assert.equal(merged.plugins.length, 2);
155
+ const merged = r.merged as unknown as { list: unknown[]; note: string };
156
+ assert.equal(merged.list.length, 2);
155
157
  assert.equal(merged.note, 'y');
156
158
  });
157
159
 
158
160
  test('merge: 数组双侧改成相同结果 → 收敛为一份(不算冲突)', () => {
159
- const anc: SectionData = { version: 1, plugins: [{ spec: 'a' }] } as unknown as SectionData;
160
- const loc: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
161
- const rem: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
162
- const plan = merge({ plugins: loc }, { plugins: rem }, { plugins: anc });
161
+ const anc: SectionData = { version: 1, list: [{ spec: 'a' }] } as unknown as SectionData;
162
+ const loc: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
163
+ const rem: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
164
+ const plan = merge({ settings: loc }, { settings: rem }, { settings: anc });
163
165
  assert.equal(plan.sections[0]!.decision, 'skip');
164
166
  });
165
167