dsh-config-manager 0.5.0 → 0.7.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 (79) hide show
  1. package/lib/client.d.ts +8 -0
  2. package/lib/client.js +748 -602
  3. package/lib/core/local-plugin-host.d.ts +9 -0
  4. package/lib/core/local-plugin-host.js +174 -1
  5. package/lib/core/messages.d.ts +7 -0
  6. package/lib/core/messages.js +16 -0
  7. package/lib/core/migration-history.d.ts +40 -0
  8. package/lib/core/migration-history.js +55 -0
  9. package/lib/core/plugin-cli.d.ts +5 -0
  10. package/lib/core/plugin-cli.js +11 -3
  11. package/lib/core/run-registry.d.ts +10 -0
  12. package/lib/core/run-registry.js +17 -0
  13. package/lib/index.d.ts +7 -2
  14. package/lib/index.js +20 -19
  15. package/lib/profiles/dsh-profile-manager.d.ts +1 -1
  16. package/lib/profiles/dsh-profile-manager.js +26 -7
  17. package/lib/profiles/dsh-profile-shared.d.ts +3 -1
  18. package/lib/routes/import.js +6 -1
  19. package/lib/routes/route-support.d.ts +2 -1
  20. package/lib/routes/route-support.js +8 -3
  21. package/lib/routes/sync.js +5 -2
  22. package/lib/sync/autosync-config.d.ts +9 -1
  23. package/lib/sync/autosync-config.js +10 -2
  24. package/lib/sync/autosync-scheduler.js +18 -6
  25. package/lib/sync/git/git-transport.d.ts +31 -1
  26. package/lib/sync/git/git-transport.js +119 -23
  27. package/lib/sync/sync-config.d.ts +34 -3
  28. package/lib/sync/sync-config.js +38 -5
  29. package/lib/ui/sync-repository-picker.d.ts +21 -0
  30. package/lib/ui/sync-repository-picker.js +18 -0
  31. package/lib/ui/sync-settings-view.d.ts +4 -0
  32. package/lib/ui/sync-settings-view.js +3 -0
  33. package/lib/utils/remove-tree.d.ts +7 -0
  34. package/lib/utils/remove-tree.js +265 -0
  35. package/package.json +1 -1
  36. package/src/client/config-manager.module.css +21 -1
  37. package/src/client/environment/EnvironmentPanel.tsx +2 -2
  38. package/src/client/locales/profiles.ts +2 -0
  39. package/src/client/run-store.test.ts +1 -1
  40. package/src/client/run-store.ts +5 -0
  41. package/src/client/sync/ChannelConfigDialog.tsx +47 -2
  42. package/src/client/sync/SyncPanel.tsx +17 -30
  43. package/src/client/sync/SyncRepositoryPicker.tsx +34 -13
  44. package/src/client/sync/SyncSettingsView.test.ts +32 -0
  45. package/src/client/sync/config-save-state.test.ts +99 -0
  46. package/src/client/sync/config-save-state.ts +69 -0
  47. package/src/client/sync/sync-api.ts +2 -0
  48. package/src/client/sync/sync-locales.ts +10 -0
  49. package/src/core/engine-locale.test.ts +4 -0
  50. package/src/core/local-plugin-host.test.ts +31 -2
  51. package/src/core/local-plugin-host.ts +175 -2
  52. package/src/core/messages.ts +16 -0
  53. package/src/core/migration-history.test.ts +65 -0
  54. package/src/core/migration-history.ts +70 -0
  55. package/src/core/plugin-cli.fs.test.ts +30 -3
  56. package/src/core/plugin-cli.ts +11 -3
  57. package/src/core/run-registry-runs.test.ts +26 -1
  58. package/src/core/run-registry.ts +18 -0
  59. package/src/index.sync.test.ts +27 -0
  60. package/src/index.ts +21 -21
  61. package/src/profiles/dsh-profile-manager.test.ts +20 -0
  62. package/src/profiles/dsh-profile-manager.ts +25 -7
  63. package/src/profiles/dsh-profile-shared.ts +2 -0
  64. package/src/routes/import.ts +6 -1
  65. package/src/routes/route-support.ts +7 -3
  66. package/src/routes/sync.ts +5 -2
  67. package/src/sync/autosync-config.ts +10 -2
  68. package/src/sync/autosync-scheduler.test.ts +61 -1
  69. package/src/sync/autosync-scheduler.ts +17 -5
  70. package/src/sync/git/git-transport.test.ts +117 -0
  71. package/src/sync/git/git-transport.ts +131 -23
  72. package/src/sync/sync-config.test.ts +59 -1
  73. package/src/sync/sync-config.ts +51 -5
  74. package/src/ui/sync-repository-picker.test.ts +34 -1
  75. package/src/ui/sync-repository-picker.ts +24 -0
  76. package/src/ui/sync-settings-view.test.ts +1 -0
  77. package/src/ui/sync-settings-view.ts +7 -0
  78. package/src/utils/remove-tree.test.ts +120 -0
  79. package/src/utils/remove-tree.ts +239 -0
@@ -26,7 +26,7 @@ import { createSnapshotFs, joinFs } from '../fs.js';
26
26
  import { readSnapshotFromDir, SNAPSHOT_BLOB_REFS_SUFFIX, SNAPSHOT_KEEP_CONTENT, SNAPSHOT_KEEP_FILE, SNAPSHOT_MANIFEST_FILE, writeSnapshotToDir } from '../layout.js';
27
27
  import { BLOB_SECTIONS, gcBlobs, referencedBlobHashes } from '../blob-store.js';
28
28
  import { deserializeSnapshot, serializeSnapshot } from '../snapshot-json.js';
29
- import { classifyRepoUrl, isPrivateRepoHost } from '../sync-config.js';
29
+ import { classifyRepoUrl, isPrivateRepoHost, normalizeGitSubdir } from '../sync-config.js';
30
30
  import { classifyNetworkErrorText, computeSnapshotMeta, DEFAULT_SYNC_TIMEOUT_MS, isEncryptedSections, SyncTransportError, withSyncRetry, } from '../transport.js';
31
31
  import { markLocalOnlyExternalFailure } from '../../core/external-failure.js';
32
32
  import { parseJsonSafe } from '../../utils/json.js';
@@ -64,12 +64,22 @@ const inspectFactsCache = new Map();
64
64
  * 缺省的 300 s:一次自动同步持锁就能让同步页每次打开都白等 10 s(真机 2026-10-27)。
65
65
  */
66
66
  const INSPECT_WORKDIR_LOCK_TIMEOUT_MS = 1_500;
67
- function inspectFactsCacheKey(workDir, repoUrl) {
68
- return workDir + '\u0000' + repoUrl;
67
+ /**
68
+ * 工作副本布局身份的进程内缓存(key = workDir,值同 `readStoredSubdir()`,issue #131)。
69
+ *
70
+ * 为什么缓存:每次操作都要校验布局,而读一次 git 本地配置就是一次 git 子进程启动
71
+ * (Windows 真机约 80 ms,正是 L-04 在削的那笔开销)。布局身份是**工作副本的属性**,
72
+ * 只有本类写入(clone / adopt)与重建(reclone)会改它 —— 那三处显式更新缓存。
73
+ */
74
+ const storedSubdirCache = new Map();
75
+ function inspectFactsCacheKey(workDir, repoUrl, subdir) {
76
+ // 子目录前缀必须进 key:同一工作副本路径在不同前缀下的「远端快照数」是不同的答案(issue #131)。
77
+ return workDir + '\u0000' + repoUrl + '\u0000' + subdir;
69
78
  }
70
79
  /** 清空自检缓存(测试隔离用;生产路径由 `withWorkdir` 逐 key 失效)。 */
71
80
  export function clearInspectFactsCache() {
72
81
  inspectFactsCache.clear();
82
+ storedSubdirCache.clear();
73
83
  }
74
84
  /**
75
85
  * git 通道错误:继承统一错误基类(kind / retryable / status 分类对上层可见)。
@@ -103,7 +113,22 @@ const ADOPT_ROOT_ALLOW = new Set([SNAPSHOTS_REL, SNAPSHOTS_ENCRYPTED_REL, BLOBS_
103
113
  * 远端仓库比同步内容大几个数量级时(报告者现场:1.8 GB 仓库 / 6 MB 内容),全量 clone 与全量 fetch
104
114
  * 都要拉完整对象图,而工作副本真正需要的只有这三个目录。
105
115
  */
106
- const SYNC_ROOT_DIRS = [...ADOPT_ROOT_ALLOW];
116
+ /* 具体的 sparse 面在 `syncDirs()` 里按子目录前缀派生(issue #131),基名与 ADOPT_ROOT_ALLOW 同源。 */
117
+ /**
118
+ * 工作副本的**布局身份**键(git 本地配置,issue #131):记录这份工作副本是按哪个子目录前缀建的。
119
+ *
120
+ * 为什么必须落盘:sparse-checkout 只在首次 clone 时生效 —— 前缀从「仓库根」改成 `DSH备份` 后,
121
+ * 旧工作副本里根本没有 `DSH备份/` 这棵树,pull 会成功、list 会读空,用户看到的是
122
+ * 「远端没有快照」(issue #104 那类最难自查的假象)。存成 git 本地配置而不是工作树里的文件:
123
+ * 工作树文件会让 `status --porcelain` 恒 dirty,adopt 直接拒绝。
124
+ */
125
+ const SUBDIR_CONFIG_KEY = 'dsh.syncSubdir';
126
+ /**
127
+ * 标记值的版本前缀(issue #131)。为什么带前缀:读侧必须能区分「本插件写的」与「任何别的值」——
128
+ * 值不匹配前缀一律按「读不出」处理(回落历史布局 = 仓库根),这样伪造/污染的配置不会凭空
129
+ * 造出一条假的「布局已变」错误。空子目录写作 `1:`,仍是可判读的有效标记。
130
+ */
131
+ const SUBDIR_MARKER_PREFIX = '1:';
107
132
  /**
108
133
  * 走网络的 git 子命令:一律附加低速上限(issue #122)。
109
134
  *
@@ -287,6 +312,8 @@ export class GitTransport {
287
312
  msg;
288
313
  /** repoUrl 是否为网络地址(本地目录仓库 == false):决定要不要额外禁 file 传输(SEC-12)。 */
289
314
  networkRepo;
315
+ /** 仓库内子目录前缀('' = 仓库根):快照布局、sparse 面与 adopt 判据都从它派生(issue #131)。 */
316
+ subdir;
290
317
  constructor(options) {
291
318
  if (typeof options.repoUrl !== 'string' || options.repoUrl.length === 0) {
292
319
  throw new GitTransportError(zhMsg('sync.git.repoUrlRequired'));
@@ -309,6 +336,12 @@ export class GitTransport {
309
336
  throw new GitTransportError(this.msg('sync.git.repoUrlInvalid', { url: REPO_URL_PLACEHOLDER }));
310
337
  }
311
338
  this.networkRepo = repoShape.kind !== 'local';
339
+ // issue #131:子目录前缀在构造期就收窄(与 repoUrl 同一条纪律:非法值绝不进 git 子进程)。
340
+ const subdirCheck = normalizeGitSubdir(options.subdir ?? '');
341
+ if (!subdirCheck.ok) {
342
+ throw new GitTransportError(this.msg('sync.git.subdirInvalid', { subdir: String(options.subdir ?? '') }));
343
+ }
344
+ this.subdir = subdirCheck.value;
312
345
  this.o = {
313
346
  repoUrl: options.repoUrl,
314
347
  workDir: options.workDir,
@@ -406,7 +439,7 @@ export class GitTransport {
406
439
  await fsx.writeFile(file, new TextEncoder().encode(serializeSnapshot(snapshot)));
407
440
  // 同 id 旧散文件目录残留 → 一并清理(形态切换不残留)
408
441
  await fsx.remove(this.snapshotDir(snapshot.id));
409
- rel = `${SNAPSHOTS_ENCRYPTED_REL}/${snapshot.id}.json`;
442
+ rel = `${this.relDir(SNAPSHOTS_ENCRYPTED_REL)}/${snapshot.id}.json`;
410
443
  }
411
444
  else {
412
445
  const dir = this.snapshotDir(snapshot.id);
@@ -431,11 +464,11 @@ export class GitTransport {
431
464
  }
432
465
  // 同 id 旧密文单文件残留 → 一并清理(形态切换不残留)
433
466
  await fsx.remove(this.encryptedSnapshotFile(snapshot.id));
434
- rel = `${SNAPSHOTS_REL}/${snapshot.id}`;
467
+ rel = `${this.relDir(SNAPSHOTS_REL)}/${snapshot.id}`;
435
468
  }
436
469
  // blob 仓与快照同一次提交:引用文件与它引用的字节绝不跨 commit 分离
437
470
  const hasBlobs = await fsx.exists(this.blobsDir());
438
- await this.runGit(hasBlobs ? ['add', '--', rel, BLOBS_REL] : ['add', '--', rel]);
471
+ await this.runGit(hasBlobs ? ['add', '--', rel, this.relDir(BLOBS_REL)] : ['add', '--', rel]);
439
472
  const diff = await this.runGit(['diff', '--cached', '--quiet'], { allowNonZero: true });
440
473
  if (diff.code !== 0) {
441
474
  const verb = existed ? 'update' : 'add';
@@ -498,11 +531,11 @@ export class GitTransport {
498
531
  let rel;
499
532
  if (plainExists) {
500
533
  await fsx.remove(plainDir);
501
- rel = `${SNAPSHOTS_REL}/${id}`;
534
+ rel = `${this.relDir(SNAPSHOTS_REL)}/${id}`;
502
535
  }
503
536
  else {
504
537
  await fsx.remove(encFile);
505
- rel = `${SNAPSHOTS_ENCRYPTED_REL}/${id}.json`;
538
+ rel = `${this.relDir(SNAPSHOTS_ENCRYPTED_REL)}/${id}.json`;
506
539
  }
507
540
  await this.runGit(['add', '-A', '--', rel]);
508
541
  const diff = await this.runGit(['diff', '--cached', '--quiet'], { allowNonZero: true });
@@ -597,7 +630,7 @@ export class GitTransport {
597
630
  // 除纯只读自检外,任何操作都可能改变工作副本状态(push 改 ahead、fetch 改远端引用、
598
631
  // 重建删目录、失败也可能已留下 commit)→ 收尾即丢弃自检缓存,绝不让「写后读」看到旧事实。
599
632
  if (opts.readonly !== true)
600
- inspectFactsCache.delete(inspectFactsCacheKey(this.o.workDir, this.o.repoUrl));
633
+ inspectFactsCache.delete(inspectFactsCacheKey(this.o.workDir, this.o.repoUrl, this.subdir));
601
634
  }
602
635
  }
603
636
  async ensureRepo() {
@@ -612,6 +645,8 @@ export class GitTransport {
612
645
  // 而失败面表现为旧地址的网络超时(真机:局域网地址 → Tailscale 地址后同步长期失败),
613
646
  // 用户会误判成网络/凭据问题。
614
647
  await this.reconcileOrigin();
648
+ // issue #131:布局身份(子目录前缀)与当前配置不一致 ⇒ 明确报「需重建」,绝不照常同步
649
+ await this.assertLayoutMatches();
615
650
  // 真机 issue:仓库级提交身份此前**只在首次 clone 时**写过(见本方法末尾),已有 .git 的分支
616
651
  // 直接 return —— 换机器/换工作副本/用户清过本地配置之后,每次 commit 都以 exit 128 失败
617
652
  // ("unable to auto-detect email address"),交易停在 NEEDS_ATTENTION,用户只看到
@@ -635,6 +670,8 @@ export class GitTransport {
635
670
  // 仓库级提交身份(写入远端历史,可经 author 选项覆盖;不改全局配置)
636
671
  await this.runGit(['config', 'user.name', this.o.author.name]);
637
672
  await this.runGit(['config', 'user.email', this.o.author.email]);
673
+ // 记录布局身份(issue #131):此后前缀再变,assertLayoutMatches 能把它判出来
674
+ await this.writeLayoutMarker();
638
675
  this.repoReady = true;
639
676
  }
640
677
  /**
@@ -668,6 +705,45 @@ export class GitTransport {
668
705
  /* best-effort:写入失败留给后续 commit 以 config 分类暴露,不在这里阻断同步 */
669
706
  }
670
707
  }
708
+ /**
709
+ * 工作副本是按哪个子目录前缀建的(issue #131):读 git 本地配置 `dsh.syncSubdir`。
710
+ * null = 键不存在 ⇒ 本功能上线前建的工作副本,布局 = 仓库根(历史行为)。
711
+ */
712
+ async readStoredSubdir() {
713
+ const cached = storedSubdirCache.get(this.o.workDir);
714
+ if (cached !== undefined)
715
+ return cached;
716
+ try {
717
+ const r = await this.runGit(['config', '--get', SUBDIR_CONFIG_KEY], { allowNonZero: true });
718
+ const raw = r.code === 0 ? r.stdout.trim() : '';
719
+ // 键不存在 / 前缀不符(不是本插件写的标记,或被人改坏)⇒ 不知道,按历史布局处理
720
+ const value = raw.startsWith(SUBDIR_MARKER_PREFIX) ? raw.slice(SUBDIR_MARKER_PREFIX.length) : null;
721
+ storedSubdirCache.set(this.o.workDir, value);
722
+ return value;
723
+ }
724
+ catch {
725
+ return null; // 读不出 = 不知道,按历史布局处理(不拿猜测阻断同步;失败不进缓存,下次再读)
726
+ }
727
+ }
728
+ /** 写入布局身份标记(issue #131):git 本地配置 + 同步更新进程内缓存。 */
729
+ async writeLayoutMarker() {
730
+ await this.runGit(['config', SUBDIR_CONFIG_KEY, SUBDIR_MARKER_PREFIX + this.subdir]);
731
+ storedSubdirCache.set(this.o.workDir, this.subdir);
732
+ }
733
+ /**
734
+ * 布局身份校验(issue #131):工作副本建好时的前缀必须与当前配置一致。
735
+ *
736
+ * 为什么必须显式报错而不是「照常同步」:sparse-checkout 只在首次 clone 生效 —— 前缀换了以后,
737
+ * 旧工作副本里根本没有 `<新前缀>/` 这棵树,pull 成功、list 读空,用户看到的是
738
+ * 「远端没有快照」。这条错误把出口指回既有的「重建工作副本(重新克隆)」。
739
+ */
740
+ async assertLayoutMatches() {
741
+ const stored = (await this.readStoredSubdir()) ?? '';
742
+ if (stored === this.subdir)
743
+ return;
744
+ const label = (prefix) => (prefix === '' ? this.msg('sync.git.subdirRoot') : prefix);
745
+ throw new GitTransportError(this.msg('sync.git.subdirChanged', { stored: label(stored), expected: label(this.subdir) }), { kind: 'protocol', retryable: false });
746
+ }
671
747
  /**
672
748
  * 首次 clone(issue #122):partial clone + sparse-checkout,只落地同步内容。
673
749
  *
@@ -698,7 +774,8 @@ export class GitTransport {
698
774
  if (head.code !== 0)
699
775
  return; // 空仓库:没有可 checkout 的树,后续 push 会建分支
700
776
  const target = branch === '' ? 'HEAD' : branch;
701
- const sparse = await this.runGit(['sparse-checkout', 'set', '--cone', ...SYNC_ROOT_DIRS], { allowNonZero: true });
777
+ // issue #131:sparse 面跟着子目录前缀走 —— 共用仓库里其它工具的目录绝不被 materialize
778
+ const sparse = await this.runGit(['sparse-checkout', 'set', '--cone', ...this.syncDirs()], { allowNonZero: true });
702
779
  if (sparse.code !== 0) {
703
780
  // 老 git 没有 cone 模式:宁可全量落地(修复前行为),也不留下一个空工作树
704
781
  await this.runGit(['checkout', target], { allowNonZero: true });
@@ -803,7 +880,7 @@ export class GitTransport {
803
880
  * 因此放进 `detail: true`(供「重建工作副本」前评估数据量等场景显式索取)。
804
881
  */
805
882
  async inspectWorkDir(opts = {}) {
806
- const key = inspectFactsCacheKey(this.o.workDir, this.o.repoUrl);
883
+ const key = inspectFactsCacheKey(this.o.workDir, this.o.repoUrl, this.subdir);
807
884
  const detail = opts.detail === true;
808
885
  const hit = inspectFactsCache.get(key);
809
886
  // 命中即返回:不必排队等锁,也不必再 spawn 一条 git(这是首页/切页/轮询的常态路径)。
@@ -859,8 +936,8 @@ export class GitTransport {
859
936
  // 每个快照是一级子项;`.gitkeep` 只是占位,不是快照
860
937
  .filter((line) => line !== '' && !line.endsWith(SNAPSHOT_KEEP_FILE)).length;
861
938
  };
862
- const plain = await countTree(`origin/${branch}:${SNAPSHOTS_REL}`);
863
- const encrypted = await countTree(`origin/${branch}:${SNAPSHOTS_ENCRYPTED_REL}`);
939
+ const plain = await countTree(`origin/${branch}:${this.relDir(SNAPSHOTS_REL)}`);
940
+ const encrypted = await countTree(`origin/${branch}:${this.relDir(SNAPSHOTS_ENCRYPTED_REL)}`);
864
941
  // 两个目录都不存在 = 远端分支根本没有快照布局(0);分支/引用读不出 = null(不猜)
865
942
  remoteSnapshots = plain === null && encrypted === null ? 0 : (plain ?? 0) + (encrypted ?? 0);
866
943
  }
@@ -913,6 +990,7 @@ export class GitTransport {
913
990
  return;
914
991
  }
915
992
  await fs.rm(this.o.workDir, { recursive: true, force: true });
993
+ storedSubdirCache.delete(this.o.workDir); // 旧副本连同它的布局身份一起没了
916
994
  await this.ensureRepo();
917
995
  }
918
996
  /**
@@ -947,6 +1025,8 @@ export class GitTransport {
947
1025
  throw new GitTransportError(this.msg('sync.git.adoptDirty', { dir: this.o.workDir }), { kind: 'protocol', retryable: false });
948
1026
  }
949
1027
  await this.reconcileOrigin();
1028
+ // issue #131:采纳远端历史也不许跨布局 —— 前缀变了要先重建工作副本
1029
+ await this.assertLayoutMatches();
950
1030
  const branchRes = await this.runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { allowNonZero: true });
951
1031
  const branch = branchRes.code === 0 ? branchRes.stdout.trim() : '';
952
1032
  if (branch === '' || branch === 'HEAD') {
@@ -973,16 +1053,20 @@ export class GitTransport {
973
1053
  }
974
1054
  throw new GitTransportError(this.msg('sync.git.adoptNoRemoteBranch', { branch, heads: heads.slice(0, 3).join(', ') }), { kind: 'protocol', retryable: false });
975
1055
  }
976
- // ② 远端顶层只能是快照布局
977
- const treeRes = await this.runGit(['ls-tree', '--name-only', `origin/${branch}`], { allowNonZero: true });
978
- if (treeRes.code !== 0) {
1056
+ // ② 同步布局只能是那三个目录。配了子目录前缀时校验的是 <subdir>/ **子树**(issue #131):
1057
+ // 共用仓库里其它工具的目录在仓库根,那不是本插件的同步内容,也不该被判成「污染」。
1058
+ const treeish = this.subdir === '' ? `origin/${branch}` : `origin/${branch}:${this.subdir}`;
1059
+ const treeRes = await this.runGit(['ls-tree', '--name-only', treeish], { allowNonZero: true });
1060
+ // 子树不存在 = 远端还没有该前缀的同步内容(首次 push 会建它),不是错误;
1061
+ // 仓库根读不出来才是真异常(引用在上面已验过存在)。
1062
+ if (treeRes.code !== 0 && this.subdir === '') {
979
1063
  throw new GitTransportError(this.msg('sync.git.cmdFailed', {
980
1064
  args: `ls-tree --name-only origin/${branch}`,
981
1065
  code: String(treeRes.code),
982
1066
  err: this.mask(treeRes.stderr, await this.readTokenOnce()),
983
1067
  }), { kind: 'unknown', retryable: true });
984
1068
  }
985
- const unknownEntries = treeRes.stdout
1069
+ const unknownEntries = (treeRes.code === 0 ? treeRes.stdout : '')
986
1070
  .split('\n')
987
1071
  .map((name) => name.trim().replace(/\/$/, ''))
988
1072
  .filter((name) => name !== '' && !ADOPT_ROOT_ALLOW.has(name));
@@ -997,6 +1081,7 @@ export class GitTransport {
997
1081
  }
998
1082
  // 让后续 pull --ff-only 有 upstream 可用(忽略失败:分支可能已被删/重命名)
999
1083
  await this.runGit(['branch', '--set-upstream-to', `origin/${branch}`, branch], { allowNonZero: true });
1084
+ await this.writeLayoutMarker();
1000
1085
  this.repoReady = true;
1001
1086
  }
1002
1087
  /**
@@ -1278,8 +1363,19 @@ export class GitTransport {
1278
1363
  ? this.msg('sync.git.hostKeyUnverifiedNoHost')
1279
1364
  : this.msg('sync.git.hostKeyUnverified', { host });
1280
1365
  }
1366
+ /** 子目录前缀下的同步布局相对路径('' 前缀 = 历史布局,逐字不变)。 */
1367
+ relDir(base) {
1368
+ return this.subdir === '' ? base : `${this.subdir}/${base}`;
1369
+ }
1370
+ /**
1371
+ * 三个同步根目录(带前缀):sparse 面、add 路径、adopt 判据都从这里取 ——
1372
+ * 任何一处漏加前缀都会让「写入 A、读取 B」(issue #131 的失败面)。
1373
+ */
1374
+ syncDirs() {
1375
+ return [this.relDir(SNAPSHOTS_REL), this.relDir(SNAPSHOTS_ENCRYPTED_REL), this.relDir(BLOBS_REL)];
1376
+ }
1281
1377
  blobsDir() {
1282
- return path.join(this.o.workDir, BLOBS_REL);
1378
+ return path.join(this.o.workDir, this.relDir(BLOBS_REL));
1283
1379
  }
1284
1380
  /**
1285
1381
  * git 通道的 blob 仓实现:工作树内 `blobs/<sha256>`(跨快照共享、按内容寻址)。
@@ -1357,7 +1453,7 @@ export class GitTransport {
1357
1453
  const deleted = await gcBlobs({ sink: this.blobSink(fsx), referenced, nowMs: Date.now() });
1358
1454
  if (deleted.length === 0)
1359
1455
  return;
1360
- await this.runGit(['add', '-A', '--', BLOBS_REL]);
1456
+ await this.runGit(['add', '-A', '--', this.relDir(BLOBS_REL)]);
1361
1457
  const diff = await this.runGit(['diff', '--cached', '--quiet'], { allowNonZero: true });
1362
1458
  if (diff.code === 0)
1363
1459
  return;
@@ -1373,11 +1469,11 @@ export class GitTransport {
1373
1469
  return joinFs(this.snapshotsDir(), id);
1374
1470
  }
1375
1471
  snapshotsDir() {
1376
- return joinFs(this.o.workDir, SNAPSHOTS_REL);
1472
+ return joinFs(this.o.workDir, this.relDir(SNAPSHOTS_REL));
1377
1473
  }
1378
- /** 加密快照密文单文件目录(<workDir>/snapshots-encrypted/) */
1474
+ /** 加密快照密文单文件目录(<workDir>/snapshots-encrypted/;配了前缀则在 <subdir>/ 下) */
1379
1475
  encryptedSnapshotsDir() {
1380
- return joinFs(this.o.workDir, SNAPSHOTS_ENCRYPTED_REL);
1476
+ return joinFs(this.o.workDir, this.relDir(SNAPSHOTS_ENCRYPTED_REL));
1381
1477
  }
1382
1478
  /** 加密快照密文单文件路径(<id>.json) */
1383
1479
  encryptedSnapshotFile(id) {
@@ -32,13 +32,25 @@ export declare function channelOf(cfg: SyncConfig): SyncTransportType;
32
32
  * 在每处穷举字面量(漏写的表现曾是「该通道的配置永远读不到 / 写不回」,静默且难查)。
33
33
  */
34
34
  export declare function channelMap<T>(make: (channel: SyncTransportType) => T): Record<SyncTransportType, T>;
35
- /** 当前 sync-config.json schema 版本号(v3:双命名空间共存,切换通道不丢失另一通道配置)。 */
36
- export declare const SYNC_CONFIG_SCHEMA_VERSION = 3;
37
- /** 历史可读取版本:v1、v2、v3。 */
35
+ /**
36
+ * 当前 sync-config.json schema 版本号(v4:git 通道新增可选 `subdir` 子目录前缀,issue #131)。
37
+ *
38
+ * 为什么必须升版而不是只加一个可选字段:老版本插件读到带 `subdir` 的配置会**丢掉这个字段**
39
+ * 然后照旧往仓库根写快照 —— 在「多工具共用一个备份仓库」的现场,那等于把快照撒进别人的目录布局。
40
+ * 升版后老版本读到 v4 直接判为不支持(显示未配置),宁可让用户看见「要升级」,也不静默写错位置。
41
+ */
42
+ export declare const SYNC_CONFIG_SCHEMA_VERSION = 4;
43
+ /** 历史可读取版本:v1、v2、v3、v4。 */
38
44
  export declare const SYNC_CONFIG_SUPPORTED_VERSIONS: readonly number[];
39
45
  /** git 通道配置(不含任何凭据;git 可执行文件固定使用系统 PATH 中的 git) */
40
46
  export interface GitConfig {
41
47
  repoUrl: string;
48
+ /**
49
+ * 仓库内子目录前缀(issue #131,可缺省):快照布局落在 `<subdir>/snapshots`、
50
+ * `<subdir>/snapshots-encrypted`、`<subdir>/blobs`。缺省 = 仓库根(历史行为逐字不变)。
51
+ * 多工具共用同一个私有备份仓库时,每个工具各占一个子目录。
52
+ */
53
+ subdir?: string;
42
54
  }
43
55
  /** webdav 通道配置(不含 password;password 走 DSH credentials) */
44
56
  export interface WebDavConfig {
@@ -372,6 +384,25 @@ export declare function validateCloudEndpoint(endpoint: string): CloudConfigIssu
372
384
  export declare function validateCloudRegion(region: string): CloudConfigIssueCode | null;
373
385
  /** 桶名校验。 */
374
386
  export declare function validateCloudBucket(bucket: string): CloudConfigIssueCode | null;
387
+ /**
388
+ * git 通道子目录前缀的归一化与校验(issue #131)。
389
+ *
390
+ * 为什么单独一个函数而不是复用 validateCloudPrefix:对象键前缀与仓库内目录名不是同一套约束 ——
391
+ * 目录名要允许 UTF-8(报告者现场就是 `DSH备份/` 这种中文目录)与多级嵌套,而对象键前缀按
392
+ * 存储桶语义只关心「不是绝对路径、没有 ..」。
393
+ *
394
+ * 接受:空串(= 仓库根,历史行为)、UTF-8 段、多级嵌套(`a/b`)。
395
+ * 拒绝:绝对路径(首部 /)、尾部 /、反斜杠、空段(含 `a//b`)、`.` / `..` 段、控制字符、
396
+ * `.git` 段(写进去会撞 git 自己的元数据目录名,任何大小写都算)。
397
+ */
398
+ export type GitSubdirCheck = {
399
+ ok: true;
400
+ value: string;
401
+ } | {
402
+ ok: false;
403
+ reason: 'gitSubdirInvalid';
404
+ };
405
+ export declare function normalizeGitSubdir(raw: unknown): GitSubdirCheck;
375
406
  /** 对象键前缀校验(可缺省 = 根前缀;不得以 / 开头、不得含 .. / 反斜杠 / 空段)。 */
376
407
  export declare function validateCloudPrefix(prefix: string): CloudConfigIssueCode | null;
377
408
  /** gist id 校验。 */
@@ -69,10 +69,16 @@ export function channelMap(make) {
69
69
  out[channel] = make(channel);
70
70
  return out;
71
71
  }
72
- /** 当前 sync-config.json schema 版本号(v3:双命名空间共存,切换通道不丢失另一通道配置)。 */
73
- export const SYNC_CONFIG_SCHEMA_VERSION = 3;
74
- /** 历史可读取版本:v1、v2、v3。 */
75
- export const SYNC_CONFIG_SUPPORTED_VERSIONS = [1, 2, 3];
72
+ /**
73
+ * 当前 sync-config.json schema 版本号(v4:git 通道新增可选 `subdir` 子目录前缀,issue #131)。
74
+ *
75
+ * 为什么必须升版而不是只加一个可选字段:老版本插件读到带 `subdir` 的配置会**丢掉这个字段**
76
+ * 然后照旧往仓库根写快照 —— 在「多工具共用一个备份仓库」的现场,那等于把快照撒进别人的目录布局。
77
+ * 升版后老版本读到 v4 直接判为不支持(显示未配置),宁可让用户看见「要升级」,也不静默写错位置。
78
+ */
79
+ export const SYNC_CONFIG_SCHEMA_VERSION = 4;
80
+ /** 历史可读取版本:v1、v2、v3、v4。 */
81
+ export const SYNC_CONFIG_SUPPORTED_VERSIONS = [1, 2, 3, 4];
76
82
  /** git 通道守卫 */
77
83
  export function isGitConfig(cfg) {
78
84
  return cfg.transport === 'git';
@@ -93,7 +99,12 @@ export function isGistConfig(cfg) {
93
99
  function parseV1Git(obj) {
94
100
  if (typeof obj['repoUrl'] !== 'string' || obj['repoUrl'] === '')
95
101
  return null;
96
- return { repoUrl: obj['repoUrl'] };
102
+ // issue #131:子目录前缀必须在这里**显式搬运** —— 本函数只构造已知字段,漏搬就是静默丢掉用户配置。
103
+ // 读侧同口径校验:非法值当作「未设置」(落在仓库根),绝不把可疑路径继续交给 git 子进程。
104
+ const subdir = normalizeGitSubdir(obj['subdir']);
105
+ return subdir.ok && subdir.value !== ''
106
+ ? { repoUrl: obj['repoUrl'], subdir: subdir.value }
107
+ : { repoUrl: obj['repoUrl'] };
97
108
  }
98
109
  /** 从 v2 git 命名空间解析;缺有效 repoUrl → null */
99
110
  function parseV2GitNamespace(ns) {
@@ -705,6 +716,28 @@ export function validateCloudBucket(bucket) {
705
716
  return 'cloud.bucketInvalid';
706
717
  return null;
707
718
  }
719
+ export function normalizeGitSubdir(raw) {
720
+ // 缺省(字段不存在)与空串同义:仓库根。只有「显式写了但不是字符串」才算非法。
721
+ if (raw === undefined || raw === null)
722
+ return { ok: true, value: '' };
723
+ if (typeof raw !== 'string')
724
+ return { ok: false, reason: 'gitSubdirInvalid' };
725
+ const p = raw.trim();
726
+ if (p === '')
727
+ return { ok: true, value: '' };
728
+ if (p.startsWith('/') || p.endsWith('/'))
729
+ return { ok: false, reason: 'gitSubdirInvalid' };
730
+ if (p.includes('\\') || /[\u0000-\u001f\u007f]/.test(p))
731
+ return { ok: false, reason: 'gitSubdirInvalid' };
732
+ const segments = p.split('/');
733
+ for (const seg of segments) {
734
+ if (seg === '' || seg === '.' || seg === '..')
735
+ return { ok: false, reason: 'gitSubdirInvalid' };
736
+ if (seg.toLowerCase() === '.git')
737
+ return { ok: false, reason: 'gitSubdirInvalid' };
738
+ }
739
+ return { ok: true, value: segments.join('/') };
740
+ }
708
741
  /** 对象键前缀校验(可缺省 = 根前缀;不得以 / 开头、不得含 .. / 反斜杠 / 空段)。 */
709
742
  export function validateCloudPrefix(prefix) {
710
743
  if (typeof prefix !== 'string')
@@ -96,3 +96,24 @@ export declare function repoCreateBody(name: string, description: string): {
96
96
  * `Invalid Date`);与 src/ui/snapshots-view.ts:170 同一口径(`toLocaleString()`)。
97
97
  */
98
98
  export declare function formatRepoUpdatedAt(iso: string, locale?: string): string;
99
+ /**
100
+ * 仓库列表是否该**自动加载**(不要求用户先点开下拉)。
101
+ *
102
+ * 用户反馈(2026-11-08):GitHub 登录成功后界面没有任何提示,列表也不会自己出现 ——
103
+ * 必须手动点一下「从我的仓库中选择」才知道成功了。这里把「该拉列表」的判定收成一条纯函数,
104
+ * 三个触发点共用:弹窗打开、登录状态由「未登录」变「已登录」、表单里已经有地址。
105
+ *
106
+ * 规则:
107
+ * - 弹窗没打开 / 已加载过 / 正在加载 → 不重复发请求;
108
+ * - `failed` 为真 → 不自动重试(否则每次重渲染都会打一次必然失败的请求;重试由「刷新列表」或
109
+ * 登录状态变化后的复位负责)。
110
+ * - 未登录且地址为空 → 保持惰性(此时拉列表必然 401,白跑一次网络)。
111
+ */
112
+ export declare function shouldAutoLoadRepos(input: {
113
+ open: boolean;
114
+ signedIn: boolean | null;
115
+ loaded: boolean;
116
+ loading: boolean;
117
+ failed: boolean;
118
+ repoUrl: string;
119
+ }): boolean;
@@ -142,4 +142,22 @@ export function formatRepoUpdatedAt(iso, locale) {
142
142
  const date = new Date(ms);
143
143
  return locale === undefined ? date.toLocaleString() : date.toLocaleString(locale);
144
144
  }
145
+ /**
146
+ * 仓库列表是否该**自动加载**(不要求用户先点开下拉)。
147
+ *
148
+ * 用户反馈(2026-11-08):GitHub 登录成功后界面没有任何提示,列表也不会自己出现 ——
149
+ * 必须手动点一下「从我的仓库中选择」才知道成功了。这里把「该拉列表」的判定收成一条纯函数,
150
+ * 三个触发点共用:弹窗打开、登录状态由「未登录」变「已登录」、表单里已经有地址。
151
+ *
152
+ * 规则:
153
+ * - 弹窗没打开 / 已加载过 / 正在加载 → 不重复发请求;
154
+ * - `failed` 为真 → 不自动重试(否则每次重渲染都会打一次必然失败的请求;重试由「刷新列表」或
155
+ * 登录状态变化后的复位负责)。
156
+ * - 未登录且地址为空 → 保持惰性(此时拉列表必然 401,白跑一次网络)。
157
+ */
158
+ export function shouldAutoLoadRepos(input) {
159
+ if (!input.open || input.loaded || input.loading || input.failed)
160
+ return false;
161
+ return input.signedIn === true || input.repoUrl.trim() !== '';
162
+ }
145
163
  //# sourceMappingURL=sync-repository-picker.js.map
@@ -32,6 +32,8 @@ export type SyncAutosyncInterval = '5m' | '15m' | '30m' | '60m' | '6h' | '12h' |
32
32
  export interface SyncFormSnapshot {
33
33
  channel: SyncChannelName;
34
34
  repoUrl: string;
35
+ /** 仓库内子目录前缀(空 = 仓库根;issue #131:多工具共用一个私有仓库时各自独立) */
36
+ gitSubdir: string;
35
37
  /** 仅内存;成功后由组件清空(已写入 DSH credentials) */
36
38
  token: string;
37
39
  webdavUrl: string;
@@ -89,6 +91,8 @@ export interface SyncPushBody {
89
91
  */
90
92
  transport?: SyncTransportType;
91
93
  repoUrl?: string;
94
+ /** git:仓库内子目录前缀(issue #131;空 / 缺省 = 仓库根,旧配置读出来即空) */
95
+ subdir?: string;
92
96
  token?: string;
93
97
  url?: string;
94
98
  username?: string;
@@ -61,9 +61,12 @@ function channelAuthBody(form, opts) {
61
61
  ...(token === '' ? {} : { secret: token }),
62
62
  };
63
63
  }
64
+ const subdir = form.gitSubdir.trim();
64
65
  return {
65
66
  transport: 'git',
66
67
  repoUrl: form.repoUrl.trim(),
68
+ // 空串不携带:宿主按「缺省 = 仓库根」解析,旧配置与旧宿主都能吃这份载荷
69
+ ...(subdir === '' ? {} : { subdir }),
67
70
  token: form.token.trim() !== '' ? (opts.trimToken ? form.token.trim() : form.token) : undefined,
68
71
  };
69
72
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * 同步严格删除:目标不存在算成功;链接只删链接本身;删不掉抛底层错误;
3
+ * 结束时目标**仍然存在**也抛错(rm 静默失效的兜底判据)。
4
+ */
5
+ export declare function removeTreeSync(target: string): void;
6
+ /** 异步版本(大批量目录不阻塞事件循环);语义与 removeTreeSync 完全一致。 */
7
+ export declare function removeTree(target: string): Promise<void>;