@narumitw/pi-sync 0.50.2 → 0.51.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 (218) hide show
  1. package/README.md +4 -1
  2. package/dist/chunks/{chunk-6LP3MCR2.ts → chunk-2JZFHNLM.ts} +3 -5
  3. package/dist/chunks/chunk-2JZFHNLM.ts.map +7 -0
  4. package/dist/chunks/{chunk-LCRI3ABW.ts → chunk-2RZSQWBH.ts} +8 -19
  5. package/dist/chunks/chunk-2RZSQWBH.ts.map +7 -0
  6. package/dist/chunks/{chunk-IJ6FJFA5.ts → chunk-4AIHXRKE.ts} +11 -17
  7. package/dist/chunks/chunk-4AIHXRKE.ts.map +7 -0
  8. package/dist/chunks/{chunk-C7XY5NF5.ts → chunk-4MPIH46N.ts} +29 -51
  9. package/dist/chunks/chunk-4MPIH46N.ts.map +7 -0
  10. package/dist/chunks/{chunk-5B3FXBLE.ts → chunk-6546TS54.ts} +16 -20
  11. package/dist/chunks/chunk-6546TS54.ts.map +7 -0
  12. package/dist/chunks/{chunk-Q2TUM5X6.ts → chunk-6NT3YFGY.ts} +2 -2
  13. package/dist/chunks/chunk-6NT3YFGY.ts.map +7 -0
  14. package/dist/chunks/{chunk-2B2ELUF5.ts → chunk-7D5SF7P3.ts} +1 -1
  15. package/dist/chunks/chunk-7D5SF7P3.ts.map +7 -0
  16. package/dist/chunks/{chunk-4CHTZMEO.ts → chunk-7KHKWL3Q.ts} +37 -55
  17. package/dist/chunks/chunk-7KHKWL3Q.ts.map +7 -0
  18. package/dist/chunks/{chunk-ZI5MXMEX.ts → chunk-BVVP33U5.ts} +2 -4
  19. package/dist/chunks/chunk-BVVP33U5.ts.map +7 -0
  20. package/dist/chunks/{chunk-SZWBGPID.ts → chunk-DM4X4FIA.ts} +8 -13
  21. package/dist/chunks/chunk-DM4X4FIA.ts.map +7 -0
  22. package/dist/chunks/{chunk-SL64RLXR.ts → chunk-DZUSTGQV.ts} +8 -16
  23. package/dist/chunks/chunk-DZUSTGQV.ts.map +7 -0
  24. package/dist/chunks/{chunk-G4RNQQZS.ts → chunk-E42GXD6D.ts} +13 -19
  25. package/dist/chunks/chunk-E42GXD6D.ts.map +7 -0
  26. package/dist/chunks/{chunk-Z4DQF6L3.ts → chunk-ECYCNZOE.ts} +1 -1
  27. package/dist/chunks/chunk-ECYCNZOE.ts.map +7 -0
  28. package/dist/chunks/{chunk-OEX4ABY6.ts → chunk-EEJPYTWE.ts} +11 -21
  29. package/dist/chunks/chunk-EEJPYTWE.ts.map +7 -0
  30. package/dist/chunks/{chunk-CPEHGXJV.ts → chunk-G4RUXRWZ.ts} +3 -5
  31. package/dist/chunks/chunk-G4RUXRWZ.ts.map +7 -0
  32. package/dist/chunks/{chunk-T2B5IU74.ts → chunk-HGJH56KR.ts} +4 -4
  33. package/dist/chunks/chunk-HGJH56KR.ts.map +7 -0
  34. package/dist/chunks/{chunk-JAAKLL6M.ts → chunk-IVXEDPAD.ts} +10 -34
  35. package/dist/chunks/chunk-IVXEDPAD.ts.map +7 -0
  36. package/dist/chunks/chunk-K3RIEL6J.ts +20 -0
  37. package/dist/chunks/chunk-K3RIEL6J.ts.map +7 -0
  38. package/dist/chunks/{chunk-LTBWGSBV.ts → chunk-MSSW6F3R.ts} +1 -1
  39. package/dist/chunks/chunk-MSSW6F3R.ts.map +7 -0
  40. package/dist/chunks/{chunk-T3HH3UEJ.ts → chunk-OVDTF5CH.ts} +4 -10
  41. package/dist/chunks/chunk-OVDTF5CH.ts.map +7 -0
  42. package/dist/chunks/{chunk-NJFUIVYL.ts → chunk-PWMWOJP4.ts} +1 -1
  43. package/dist/chunks/chunk-PWMWOJP4.ts.map +7 -0
  44. package/dist/chunks/{chunk-HUDQATCL.ts → chunk-Q32CQWPM.ts} +6 -8
  45. package/dist/chunks/chunk-Q32CQWPM.ts.map +7 -0
  46. package/dist/chunks/{chunk-ETTRJDNP.ts → chunk-QLSN7AGX.ts} +6 -13
  47. package/dist/chunks/chunk-QLSN7AGX.ts.map +7 -0
  48. package/dist/chunks/{chunk-THMF4BVL.ts → chunk-SWUXA3MH.ts} +1 -1
  49. package/dist/chunks/chunk-SWUXA3MH.ts.map +7 -0
  50. package/dist/chunks/{chunk-TEN2ZBJV.ts → chunk-T2SJD3N7.ts} +2 -4
  51. package/dist/chunks/chunk-T2SJD3N7.ts.map +7 -0
  52. package/dist/chunks/{chunk-AUSDLD6F.ts → chunk-T56RNRZJ.ts} +10 -26
  53. package/dist/chunks/chunk-T56RNRZJ.ts.map +7 -0
  54. package/dist/chunks/{chunk-KW7YQEZN.ts → chunk-UA7RXOIT.ts} +48 -100
  55. package/dist/chunks/chunk-UA7RXOIT.ts.map +7 -0
  56. package/dist/chunks/{chunk-D5X27LCA.ts → chunk-UETBKTDI.ts} +1 -1
  57. package/dist/chunks/chunk-UETBKTDI.ts.map +7 -0
  58. package/dist/chunks/{chunk-CHH26D4F.ts → chunk-YFADF5ZQ.ts} +7 -6
  59. package/dist/chunks/chunk-YFADF5ZQ.ts.map +7 -0
  60. package/dist/chunks/{chunk-CCSN3F47.ts → chunk-YPXGU5OR.ts} +4 -4
  61. package/dist/chunks/chunk-YPXGU5OR.ts.map +7 -0
  62. package/dist/chunks/{file-selection-FTTKAOYX.ts → file-selection-RAVHRYFG.ts} +14 -26
  63. package/dist/chunks/file-selection-RAVHRYFG.ts.map +7 -0
  64. package/dist/chunks/{git-backend-GMVS4PD4.ts → git-backend-IAANDL3K.ts} +41 -104
  65. package/dist/chunks/git-backend-IAANDL3K.ts.map +7 -0
  66. package/dist/chunks/manager-result-dispatcher-OTUMQM26.ts +23 -0
  67. package/dist/chunks/{manager-ui-5KLKVMRC.ts → manager-ui-763NEKJY.ts} +124 -251
  68. package/dist/chunks/manager-ui-763NEKJY.ts.map +7 -0
  69. package/dist/chunks/remote-selection-ui-TZTJF32Y.ts +22 -0
  70. package/dist/chunks/{s3-backend-66O4FGBH.ts → s3-backend-XGXUOPUN.ts} +23 -54
  71. package/dist/chunks/s3-backend-XGXUOPUN.ts.map +7 -0
  72. package/dist/chunks/{setup-switch-IS2PEZ3J.ts → setup-switch-5G2VNJHL.ts} +9 -9
  73. package/dist/chunks/{setup-wizard-IUB6ESEU.ts → setup-wizard-YIEWGX32.ts} +12 -12
  74. package/dist/chunks/setup-wizard-YIEWGX32.ts.map +7 -0
  75. package/dist/chunks/{snapshot-HKEWCVK6.ts → snapshot-JL5DFSXI.ts} +5 -5
  76. package/dist/chunks/sync-inspection-P3ENJLNF.ts +20 -0
  77. package/dist/chunks/{sync-operations-LBX3GKCM.ts → sync-operations-AR76EB6C.ts} +85 -201
  78. package/dist/chunks/sync-operations-AR76EB6C.ts.map +7 -0
  79. package/dist/chunks/{sync-state-Q2FTXTW6.ts → sync-state-VHJUZ4YG.ts} +6 -6
  80. package/dist/chunks/{webdav-backend-ECIKD7SO.ts → webdav-backend-3EGUONAT.ts} +20 -51
  81. package/dist/chunks/webdav-backend-3EGUONAT.ts.map +7 -0
  82. package/dist/index.ts +49 -74
  83. package/dist/index.ts.map +3 -3
  84. package/docs/settings.md +9 -0
  85. package/package.json +61 -62
  86. package/src/backends/backend-factory.ts +15 -15
  87. package/src/backends/backend-identity.ts +31 -31
  88. package/src/backends/backend-types.ts +42 -42
  89. package/src/backends/git/git-backend.ts +714 -788
  90. package/src/backends/git/git-config.ts +104 -111
  91. package/src/backends/git/git-runner.ts +230 -247
  92. package/src/backends/git/git-storage.ts +228 -245
  93. package/src/backends/s3/s3-backend.ts +408 -441
  94. package/src/backends/s3/s3-client.ts +288 -333
  95. package/src/backends/sync-backend.ts +65 -65
  96. package/src/backends/webdav/webdav-backend.ts +542 -589
  97. package/src/backends/webdav/webdav-client.ts +292 -316
  98. package/src/backends/webdav/webdav-config.ts +57 -68
  99. package/src/commands/command-execution.ts +270 -289
  100. package/src/commands/command-handler.ts +160 -163
  101. package/src/commands/command-types.ts +13 -13
  102. package/src/commands/command.ts +190 -196
  103. package/src/commands/setup-completions.ts +1 -1
  104. package/src/paths.ts +47 -47
  105. package/src/settings/config-errors.ts +4 -5
  106. package/src/settings/config-file.ts +473 -506
  107. package/src/settings/config.ts +171 -174
  108. package/src/settings/settings-management.ts +191 -216
  109. package/src/settings/settings-store.ts +63 -77
  110. package/src/settings/settings-types.ts +78 -75
  111. package/src/settings/settings-validation.ts +328 -364
  112. package/src/snapshot/session-paths.ts +41 -55
  113. package/src/snapshot/snapshot-apply.ts +197 -229
  114. package/src/snapshot/snapshot-codec.ts +29 -31
  115. package/src/snapshot/snapshot-paths.ts +4 -6
  116. package/src/snapshot/snapshot-transaction.ts +161 -170
  117. package/src/snapshot/snapshot-types.ts +24 -24
  118. package/src/snapshot/snapshot.ts +310 -343
  119. package/src/state/json-file.ts +11 -11
  120. package/src/state/lock.ts +226 -242
  121. package/src/state/lockfile-fs.ts +20 -20
  122. package/src/state/operation-availability.ts +36 -41
  123. package/src/state/state-directory.ts +171 -173
  124. package/src/state/state-types.ts +15 -15
  125. package/src/state/sync-state-store.ts +23 -23
  126. package/src/sync/automatic-sync.ts +75 -80
  127. package/src/sync/remote-snapshot.ts +52 -60
  128. package/src/sync/setup-switch.ts +99 -114
  129. package/src/sync/signals.ts +3 -5
  130. package/src/sync/startup-check.ts +97 -111
  131. package/src/sync/sync-decision.ts +76 -80
  132. package/src/sync/sync-error-guidance.ts +41 -48
  133. package/src/sync/sync-errors.ts +10 -10
  134. package/src/sync/sync-inspection.ts +29 -33
  135. package/src/sync/sync-loaders.ts +28 -36
  136. package/src/sync/sync-mutations.ts +510 -622
  137. package/src/sync/sync-operations.ts +7 -7
  138. package/src/sync/sync-policy.ts +296 -326
  139. package/src/sync/sync-queries.ts +175 -194
  140. package/src/sync/sync-state.ts +74 -100
  141. package/src/sync-extension.ts +89 -101
  142. package/src/sync.ts +26 -26
  143. package/src/types.ts +37 -37
  144. package/src/ui/automatic-sync-summary.ts +1 -3
  145. package/src/ui/cancellable-operation.ts +92 -112
  146. package/src/ui/file-selection.ts +250 -274
  147. package/src/ui/manager-attention.ts +51 -63
  148. package/src/ui/manager-recovery.ts +48 -57
  149. package/src/ui/manager-result-dispatcher.ts +62 -76
  150. package/src/ui/manager-state.ts +200 -232
  151. package/src/ui/manager-ui.ts +264 -362
  152. package/src/ui/remote-selection-ui.ts +547 -588
  153. package/src/ui/secret-input.ts +198 -214
  154. package/src/ui/settings-ui.ts +175 -172
  155. package/src/ui/setup/git-ui.ts +232 -261
  156. package/src/ui/setup/s3-credentials-ui.ts +58 -65
  157. package/src/ui/setup/s3-ui.ts +171 -195
  158. package/src/ui/setup/setup-actions.ts +91 -101
  159. package/src/ui/setup/setup-location-ui.ts +121 -137
  160. package/src/ui/setup/setup-name-ui.ts +27 -27
  161. package/src/ui/setup/setup-prompts.ts +65 -65
  162. package/src/ui/setup/setup-review.ts +58 -59
  163. package/src/ui/setup/setup-switcher.ts +156 -160
  164. package/src/ui/setup/setup-wizard.ts +28 -28
  165. package/src/ui/setup/text-input.ts +54 -58
  166. package/src/ui/setup/webdav-ui.ts +246 -293
  167. package/src/ui/storage-connections-ui.ts +317 -369
  168. package/src/ui/sync-attention.ts +148 -164
  169. package/src/ui/sync-format.ts +110 -121
  170. package/src/ui/sync-resolution-ui.ts +147 -153
  171. package/src/ui/sync-setups-ui.ts +218 -238
  172. package/src/ui/sync-status.ts +17 -0
  173. package/src/ui/terminal-text.ts +2 -2
  174. package/dist/chunks/chunk-2B2ELUF5.ts.map +0 -7
  175. package/dist/chunks/chunk-4CHTZMEO.ts.map +0 -7
  176. package/dist/chunks/chunk-5B3FXBLE.ts.map +0 -7
  177. package/dist/chunks/chunk-6LP3MCR2.ts.map +0 -7
  178. package/dist/chunks/chunk-AUSDLD6F.ts.map +0 -7
  179. package/dist/chunks/chunk-C7XY5NF5.ts.map +0 -7
  180. package/dist/chunks/chunk-CCSN3F47.ts.map +0 -7
  181. package/dist/chunks/chunk-CHH26D4F.ts.map +0 -7
  182. package/dist/chunks/chunk-CPEHGXJV.ts.map +0 -7
  183. package/dist/chunks/chunk-D5X27LCA.ts.map +0 -7
  184. package/dist/chunks/chunk-ETTRJDNP.ts.map +0 -7
  185. package/dist/chunks/chunk-G4RNQQZS.ts.map +0 -7
  186. package/dist/chunks/chunk-HUDQATCL.ts.map +0 -7
  187. package/dist/chunks/chunk-IJ6FJFA5.ts.map +0 -7
  188. package/dist/chunks/chunk-JAAKLL6M.ts.map +0 -7
  189. package/dist/chunks/chunk-KW7YQEZN.ts.map +0 -7
  190. package/dist/chunks/chunk-LCRI3ABW.ts.map +0 -7
  191. package/dist/chunks/chunk-LTBWGSBV.ts.map +0 -7
  192. package/dist/chunks/chunk-NJFUIVYL.ts.map +0 -7
  193. package/dist/chunks/chunk-OEX4ABY6.ts.map +0 -7
  194. package/dist/chunks/chunk-Q2TUM5X6.ts.map +0 -7
  195. package/dist/chunks/chunk-SL64RLXR.ts.map +0 -7
  196. package/dist/chunks/chunk-SZWBGPID.ts.map +0 -7
  197. package/dist/chunks/chunk-T2B5IU74.ts.map +0 -7
  198. package/dist/chunks/chunk-T3HH3UEJ.ts.map +0 -7
  199. package/dist/chunks/chunk-TEN2ZBJV.ts.map +0 -7
  200. package/dist/chunks/chunk-THMF4BVL.ts.map +0 -7
  201. package/dist/chunks/chunk-Z4DQF6L3.ts.map +0 -7
  202. package/dist/chunks/chunk-ZI5MXMEX.ts.map +0 -7
  203. package/dist/chunks/file-selection-FTTKAOYX.ts.map +0 -7
  204. package/dist/chunks/git-backend-GMVS4PD4.ts.map +0 -7
  205. package/dist/chunks/manager-result-dispatcher-FKIBM3GO.ts +0 -22
  206. package/dist/chunks/manager-ui-5KLKVMRC.ts.map +0 -7
  207. package/dist/chunks/remote-selection-ui-D7RBRJNL.ts +0 -21
  208. package/dist/chunks/s3-backend-66O4FGBH.ts.map +0 -7
  209. package/dist/chunks/setup-wizard-IUB6ESEU.ts.map +0 -7
  210. package/dist/chunks/sync-inspection-CST2KL65.ts +0 -20
  211. package/dist/chunks/sync-operations-LBX3GKCM.ts.map +0 -7
  212. package/dist/chunks/webdav-backend-ECIKD7SO.ts.map +0 -7
  213. /package/dist/chunks/{manager-result-dispatcher-FKIBM3GO.ts.map → manager-result-dispatcher-OTUMQM26.ts.map} +0 -0
  214. /package/dist/chunks/{remote-selection-ui-D7RBRJNL.ts.map → remote-selection-ui-TZTJF32Y.ts.map} +0 -0
  215. /package/dist/chunks/{setup-switch-IS2PEZ3J.ts.map → setup-switch-5G2VNJHL.ts.map} +0 -0
  216. /package/dist/chunks/{snapshot-HKEWCVK6.ts.map → snapshot-JL5DFSXI.ts.map} +0 -0
  217. /package/dist/chunks/{sync-inspection-CST2KL65.ts.map → sync-inspection-P3ENJLNF.ts.map} +0 -0
  218. /package/dist/chunks/{sync-state-Q2FTXTW6.ts.map → sync-state-VHJUZ4YG.ts.map} +0 -0
@@ -3,684 +3,643 @@ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
3
3
  import { createSyncBackend, type SyncBackendFactory } from "../backends/backend-factory.js";
4
4
  import type { RemoteHead, SyncBackend } from "../backends/sync-backend.js";
5
5
  import {
6
- loadConfig,
7
- loadPartialConfig,
8
- type SyncSetupStorageReview,
9
- syncConfigReviewFingerprint,
6
+ loadConfig,
7
+ loadPartialConfig,
8
+ type SyncSetupStorageReview,
9
+ syncConfigReviewFingerprint,
10
10
  } from "../settings/config.js";
11
11
  import { SyncSetupReviewChangedError, updateSyncSetup } from "../settings/settings-management.js";
12
12
  import type { AnySyncConfig, PartialConfig } from "../settings/settings-types.js";
13
13
  import { readSnapshotForHead } from "../sync/remote-snapshot.js";
14
14
  import { errorMessage } from "../sync/sync-errors.js";
15
15
  import {
16
- compareSyncInclude,
17
- inspectRemoteSelection,
18
- type RemoteSelectionDecision,
19
- type RemoteSelectionState,
20
- sameSyncInclude,
16
+ compareSyncInclude,
17
+ inspectRemoteSelection,
18
+ type RemoteSelectionDecision,
19
+ type RemoteSelectionState,
20
+ sameSyncInclude,
21
21
  } from "../sync/sync-policy.js";
22
- import {
23
- type RunRoute,
24
- type RunRouteResult,
25
- runCancellableOperation,
26
- } from "./cancellable-operation.js";
22
+ import { type RunRoute, type RunRouteResult, runCancellableOperation } from "./cancellable-operation.js";
23
+ import { setSyncStatus } from "./sync-status.js";
27
24
  import { safeTerminalText } from "./terminal-text.js";
28
25
 
29
- const STATUS_KEY = "sync";
30
-
31
26
  export type RemoteSelectionOrigin = "settings" | "sync" | "pull" | "push";
32
27
 
33
28
  export interface RemoteSelectionReviewOptions {
34
- decision?: RemoteSelectionDecision;
35
- origin?: RemoteSelectionOrigin;
36
- runRoute?: RunRoute;
37
- cancelLabel?: string;
38
- /** The explicit mismatch is resolved or superseded; this does not imply file equality. */
39
- onSelectionResolved?: () => void;
40
- withStateAccess?: <T>(task: () => Promise<T>) => Promise<T>;
29
+ decision?: RemoteSelectionDecision;
30
+ origin?: RemoteSelectionOrigin;
31
+ runRoute?: RunRoute;
32
+ cancelLabel?: string;
33
+ /** The explicit mismatch is resolved or superseded; this does not imply file equality. */
34
+ onSelectionResolved?: () => void;
35
+ withStateAccess?: <T>(task: () => Promise<T>) => Promise<T>;
41
36
  }
42
37
 
43
38
  export type RemoteSelectionReviewResult =
44
- | { kind: "back" }
45
- | { kind: "closed" }
46
- | { kind: "done" }
47
- | { kind: "stale" }
48
- | { kind: "route-result"; result: RunRouteResult; route: "sync" | "pull" | "push" };
39
+ | { kind: "back" }
40
+ | { kind: "closed" }
41
+ | { kind: "done" }
42
+ | { kind: "stale" }
43
+ | { kind: "route-result"; result: RunRouteResult; route: "sync" | "pull" | "push" };
49
44
 
50
45
  export async function showRemoteSelectionReview(
51
- ctx: ExtensionContext,
52
- setupName?: string,
53
- signal?: AbortSignal,
54
- factory: SyncBackendFactory = createSyncBackend,
55
- options: RemoteSelectionReviewOptions = {},
46
+ ctx: ExtensionContext,
47
+ setupName?: string,
48
+ signal?: AbortSignal,
49
+ factory: SyncBackendFactory = createSyncBackend,
50
+ options: RemoteSelectionReviewOptions = {},
56
51
  ): Promise<RemoteSelectionReviewResult> {
57
- try {
58
- let decision = options.decision;
59
- if (!decision) {
60
- const inspected = await inspectConfiguredRemoteSelection(ctx, setupName, signal, factory);
61
- if (!inspected || signal?.aborted) return { kind: "stale" };
62
- // A successful fresh read can supersede an old explicit mismatch without
63
- // changing local settings. This is not user cancellation or proof of file equality.
64
- if (inspected.kind === "empty" || inspected.state.kind !== "different") {
65
- options.onSelectionResolved?.();
66
- }
67
- if (inspected.kind === "empty") {
68
- ctx.ui.notify("Remote storage has no snapshot or synced-content list yet.", "info");
69
- return { kind: "back" };
70
- }
71
- if (inspected.state.kind === "same") {
72
- ctx.ui.notify("Remote synced content already matches this sync setup.", "info");
73
- return { kind: "back" };
74
- }
75
- if (inspected.state.kind === "legacy") {
76
- if (ctx.mode !== "tui") {
77
- ctx.ui.notify(formatLegacySummary(inspected.config, inspected.state.discovered), "info");
78
- return { kind: "back" };
79
- }
80
- await showLegacyDiscovery(ctx, inspected.config, inspected.state.discovered, signal);
81
- return signal?.aborted ? { kind: "stale" } : { kind: "back" };
82
- }
83
- decision = decisionFromState(inspected.config, inspected.state);
84
- }
85
-
86
- if (ctx.mode !== "tui") {
87
- ctx.ui.notify(formatRemoteSelectionSummary(decision), "warning");
88
- return { kind: "back" };
89
- }
90
-
91
- let currentDecision = decision;
92
- for (;;) {
93
- if (signal?.aborted) return { kind: "stale" };
94
- const result = await showSelectionDifference(
95
- ctx,
96
- currentDecision,
97
- options.origin ?? "settings",
98
- options.runRoute,
99
- signal,
100
- factory,
101
- options,
102
- );
103
- if (result.kind !== "refresh") return result;
104
- const refreshed = await runWithOptionalStateAccess(options, () =>
105
- inspectConfiguredRemoteSelection(ctx, currentDecision.setupName, signal, factory),
106
- );
107
- if (!refreshed || signal?.aborted) return { kind: "stale" };
108
- if (refreshed.kind === "empty") {
109
- options.onSelectionResolved?.();
110
- ctx.ui.notify("Remote storage no longer has a snapshot or synced-content list.", "warning");
111
- return { kind: "back" };
112
- }
113
- if (refreshed.state.kind !== "different") {
114
- ctx.ui.notify(
115
- refreshed.state.kind === "same"
116
- ? "Remote synced content now matches this sync setup."
117
- : "The refreshed legacy snapshot has no authoritative synced-content list.",
118
- "info",
119
- );
120
- options.onSelectionResolved?.();
121
- return { kind: "done" };
122
- }
123
- currentDecision = decisionFromState(refreshed.config, refreshed.state);
124
- }
125
- } catch (error) {
126
- if (signal?.aborted) return { kind: "stale" };
127
- ctx.ui.notify(`Could not review synced content: ${errorMessage(error)}`, "error");
128
- return { kind: "back" };
129
- } finally {
130
- ctx.ui.setStatus(STATUS_KEY, undefined);
131
- }
52
+ try {
53
+ let decision = options.decision;
54
+ if (!decision) {
55
+ const inspected = await inspectConfiguredRemoteSelection(ctx, setupName, signal, factory);
56
+ if (!inspected || signal?.aborted) return { kind: "stale" };
57
+ // A successful fresh read can supersede an old explicit mismatch without
58
+ // changing local settings. This is not user cancellation or proof of file equality.
59
+ if (inspected.kind === "empty" || inspected.state.kind !== "different") {
60
+ options.onSelectionResolved?.();
61
+ }
62
+ if (inspected.kind === "empty") {
63
+ ctx.ui.notify("Remote storage has no snapshot or synced-content list yet.", "info");
64
+ return { kind: "back" };
65
+ }
66
+ if (inspected.state.kind === "same") {
67
+ ctx.ui.notify("Remote synced content already matches this sync setup.", "info");
68
+ return { kind: "back" };
69
+ }
70
+ if (inspected.state.kind === "legacy") {
71
+ if (ctx.mode !== "tui") {
72
+ ctx.ui.notify(formatLegacySummary(inspected.config, inspected.state.discovered), "info");
73
+ return { kind: "back" };
74
+ }
75
+ await showLegacyDiscovery(ctx, inspected.config, inspected.state.discovered, signal);
76
+ return signal?.aborted ? { kind: "stale" } : { kind: "back" };
77
+ }
78
+ decision = decisionFromState(inspected.config, inspected.state);
79
+ }
80
+
81
+ if (ctx.mode !== "tui") {
82
+ ctx.ui.notify(formatRemoteSelectionSummary(decision), "warning");
83
+ return { kind: "back" };
84
+ }
85
+
86
+ let currentDecision = decision;
87
+ for (;;) {
88
+ if (signal?.aborted) return { kind: "stale" };
89
+ const result = await showSelectionDifference(
90
+ ctx,
91
+ currentDecision,
92
+ options.origin ?? "settings",
93
+ options.runRoute,
94
+ signal,
95
+ factory,
96
+ options,
97
+ );
98
+ if (result.kind !== "refresh") return result;
99
+ const refreshed = await runWithOptionalStateAccess(options, () =>
100
+ inspectConfiguredRemoteSelection(ctx, currentDecision.setupName, signal, factory),
101
+ );
102
+ if (!refreshed || signal?.aborted) return { kind: "stale" };
103
+ if (refreshed.kind === "empty") {
104
+ options.onSelectionResolved?.();
105
+ ctx.ui.notify("Remote storage no longer has a snapshot or synced-content list.", "warning");
106
+ return { kind: "back" };
107
+ }
108
+ if (refreshed.state.kind !== "different") {
109
+ ctx.ui.notify(
110
+ refreshed.state.kind === "same"
111
+ ? "Remote synced content now matches this sync setup."
112
+ : "The refreshed legacy snapshot has no authoritative synced-content list.",
113
+ "info",
114
+ );
115
+ options.onSelectionResolved?.();
116
+ return { kind: "done" };
117
+ }
118
+ currentDecision = decisionFromState(refreshed.config, refreshed.state);
119
+ }
120
+ } catch (error) {
121
+ if (signal?.aborted) return { kind: "stale" };
122
+ ctx.ui.notify(`Could not review synced content: ${errorMessage(error)}`, "error");
123
+ return { kind: "back" };
124
+ } finally {
125
+ setSyncStatus(ctx, undefined);
126
+ }
132
127
  }
133
128
 
134
129
  type DifferenceFlowResult = RemoteSelectionReviewResult | { kind: "refresh" };
135
130
 
136
131
  async function showSelectionDifference(
137
- ctx: ExtensionContext,
138
- initialDecision: RemoteSelectionDecision,
139
- origin: RemoteSelectionOrigin,
140
- runRoute: RunRoute | undefined,
141
- sessionSignal: AbortSignal | undefined,
142
- factory: SyncBackendFactory,
143
- options: Pick<
144
- RemoteSelectionReviewOptions,
145
- "cancelLabel" | "onSelectionResolved" | "withStateAccess"
146
- >,
132
+ ctx: ExtensionContext,
133
+ initialDecision: RemoteSelectionDecision,
134
+ origin: RemoteSelectionOrigin,
135
+ runRoute: RunRoute | undefined,
136
+ sessionSignal: AbortSignal | undefined,
137
+ factory: SyncBackendFactory,
138
+ options: Pick<RemoteSelectionReviewOptions, "cancelLabel" | "onSelectionResolved" | "withStateAccess">,
147
139
  ): Promise<DifferenceFlowResult> {
148
- type Screen = "choice" | "review" | "saved";
149
- type Action = "adopt" | "keep" | "cancel" | "continue" | "done";
150
- interface FlowState {
151
- decision: RemoteSelectionDecision;
152
- saved: boolean;
153
- }
154
- let flowState: FlowState = { decision: initialDecision, saved: false };
155
- let continuationReview: PartialConfig | undefined;
156
- let nextResult: RemoteSelectionReviewResult | undefined;
157
- let refreshRequested = false;
158
- const route = origin === "settings" ? "sync" : origin;
159
- const menu = defineMenu<FlowState, Screen, Action, ExtensionContext>({
160
- start: "choice",
161
- screens: {
162
- choice: ({ state }) => ({
163
- kind: "actions",
164
- title: "Synced content differs",
165
- lines: selectionSummaryLines(state.decision),
166
- items: [
167
- {
168
- id: "review",
169
- label: "Review all paths (recommended)",
170
- description: "Compare exact remote-only, device-only, and ordered lists.",
171
- to: "review",
172
- },
173
- {
174
- id: "adopt",
175
- label: "Use remote content list",
176
- description: "Save the reviewed list on this device without pulling files.",
177
- action: "adopt",
178
- },
179
- {
180
- id: "keep",
181
- label: "Keep this device's content list and update remote…",
182
- description:
183
- "Open the existing exact force-push preview without skipping confirmation.",
184
- action: "keep",
185
- },
186
- { id: "cancel", label: options.cancelLabel ?? "Cancel", action: "cancel" },
187
- ],
188
- hint: "back",
189
- }),
190
- review: ({ state }) => ({
191
- kind: "review",
192
- title: `Review synced content · ${safeTerminalText(state.decision.setupName)}`,
193
- content: formatSelectionDifference(state.decision),
194
- format: { kind: "text" },
195
- viewportSize: "adaptive",
196
- hint: "back",
197
- }),
198
- saved: ({ state }) => ({
199
- kind: "actions",
200
- title: "Remote content list saved",
201
- lines: [
202
- `Sync setup: ${safeTerminalText(state.decision.setupName)}`,
203
- "Only the included-content setting was saved.",
204
- "No files were pulled and sync state was not changed.",
205
- ],
206
- items: [
207
- ...(runRoute
208
- ? [
209
- {
210
- id: "continue",
211
- label: continueLabel(origin),
212
- description: "Start a fresh check and exact preview for this sync setup.",
213
- action: "continue" as const,
214
- },
215
- ]
216
- : []),
217
- { id: "done", label: "Done", action: "done" },
218
- ],
219
- hint: "close",
220
- }),
221
- },
222
- actions: {
223
- adopt: async ({ state, signal: actionSignal }) => {
224
- const signal = combineSignals(sessionSignal, actionSignal);
225
- try {
226
- const currentConfig = await loadConfig(state.decision.setupName);
227
- if (signal.aborted) return { kind: "close" as const };
228
- assertLocalSelectionCurrent(currentConfig, state.decision);
229
- if (
230
- !currentConfig.include.includes("sessions") &&
231
- state.decision.remoteInclude.includes("sessions")
232
- ) {
233
- const acknowledged = await ctx.ui.confirm(
234
- "Use a content list that includes session conversations?",
235
- "Session JSONL may contain prompts, tool output, file paths, images, and secrets. This saves the list only; it does not pull files.",
236
- { signal },
237
- );
238
- if (signal.aborted) return { kind: "close" as const };
239
- if (!acknowledged) return { kind: "stay" as const };
240
- }
241
- const review = await runWithOptionalStateAccess(options, async () => {
242
- const loaded = await loadAdoptionReview(state.decision, signal, factory);
243
- if (signal.aborted) throw signal.reason;
244
- await revalidateAndAdopt(loaded, state.decision, signal);
245
- return loaded;
246
- });
247
- if (signal.aborted) return { kind: "close" as const };
248
- options.onSelectionResolved?.();
249
- continuationReview = {
250
- ...review.storageReview,
251
- setupName: state.decision.setupName,
252
- include: [...state.decision.remoteInclude],
253
- automatic: review.config.automatic,
254
- onSwitch: review.config.onSwitch,
255
- };
256
- flowState = { decision: state.decision, saved: true };
257
- return { kind: "to" as const, screen: "saved" as const };
258
- } catch (error) {
259
- if (signal.aborted) return { kind: "close" as const };
260
- if (isStaleReviewError(error)) {
261
- ctx.ui.notify(`${errorMessage(error)} Refreshing the comparison.`, "warning");
262
- refreshRequested = true;
263
- return { kind: "close" as const };
264
- }
265
- ctx.ui.notify(`Could not save the remote content list: ${errorMessage(error)}`, "error");
266
- return { kind: "stay" as const };
267
- }
268
- },
269
- keep: async ({ state, signal: actionSignal }) => {
270
- if (!runRoute) {
271
- ctx.ui.notify("The reviewed update-remote route is unavailable.", "error");
272
- return { kind: "stay" as const };
273
- }
274
- const signal = combineSignals(sessionSignal, actionSignal);
275
- try {
276
- const latest = await loadConfig(state.decision.setupName);
277
- if (signal.aborted) return { kind: "close" as const };
278
- assertLocalSelectionCurrent(latest, state.decision);
279
- const result = await runCancellableOperation(
280
- ctx,
281
- "Preparing this device's push preview…",
282
- "push --force",
283
- runRoute,
284
- {
285
- commitAware: true,
286
- cancelledMessage: "Push preparation cancelled; no remote files were changed.",
287
- target: state.decision.setupName,
288
- signal,
289
- },
290
- );
291
- return handleNestedRouteResult(result, "push");
292
- } catch (error) {
293
- if (signal.aborted) return { kind: "close" as const };
294
- if (isStaleReviewError(error)) {
295
- ctx.ui.notify(`${errorMessage(error)} Refreshing the comparison.`, "warning");
296
- refreshRequested = true;
297
- return { kind: "close" as const };
298
- }
299
- ctx.ui.notify(`Could not prepare the remote update: ${errorMessage(error)}`, "error");
300
- return { kind: "stay" as const };
301
- }
302
- },
303
- continue: async ({ state, signal: actionSignal }) => {
304
- if (!runRoute || !continuationReview) return { kind: "stay" as const };
305
- const signal = combineSignals(sessionSignal, actionSignal);
306
- try {
307
- const latest = await loadPartialConfig(state.decision.setupName);
308
- if (signal.aborted) return { kind: "close" as const };
309
- if (!sameContinuationReview(latest, continuationReview)) {
310
- throw new StaleRemoteSelectionReviewError(
311
- `Sync setup “${safeTerminalText(state.decision.setupName)}” changed after the remote content list was saved.`,
312
- );
313
- }
314
- const result = await runCancellableOperation(
315
- ctx,
316
- continueBusyLabel(origin),
317
- route,
318
- runRoute,
319
- {
320
- commitAware: true,
321
- cancelledMessage: continuationCancelledMessage(route),
322
- target: state.decision.setupName,
323
- signal,
324
- },
325
- );
326
- return handleNestedRouteResult(result, route);
327
- } catch (error) {
328
- if (signal.aborted) return { kind: "close" as const };
329
- ctx.ui.notify(`Could not continue: ${errorMessage(error)}`, "error");
330
- return { kind: "stay" as const };
331
- }
332
- },
333
- cancel: async () => ({ kind: "back" }),
334
- done: async () => {
335
- nextResult = { kind: "done" };
336
- return { kind: "close" };
337
- },
338
- },
339
- });
340
-
341
- function handleNestedRouteResult(
342
- result: Awaited<ReturnType<typeof runCancellableOperation>>,
343
- nestedRoute: "sync" | "pull" | "push",
344
- ) {
345
- if (result.kind === "completed" && result.outcome === "applied") {
346
- options.onSelectionResolved?.();
347
- }
348
- if (result.kind === "closed") {
349
- nextResult = { kind: "closed" };
350
- return { kind: "close" as const };
351
- }
352
- if (
353
- result.kind === "cancelled" ||
354
- (result.kind === "completed" && result.outcome === "cancelled") ||
355
- result.kind === "failed"
356
- ) {
357
- return { kind: "stay" as const };
358
- }
359
- nextResult = { kind: "route-result", result, route: nestedRoute };
360
- return { kind: "close" as const };
361
- }
362
-
363
- const menuResult = await runMenu(ctx, menu, {
364
- getState: () => flowState,
365
- signal: sessionSignal,
366
- isCurrent: () => !sessionSignal?.aborted,
367
- onError: (_menuCtx, error) => ctx.ui.notify(errorMessage(error), "error"),
368
- });
369
- if (sessionSignal?.aborted || menuResult.kind === "stale") return { kind: "stale" };
370
- if (refreshRequested) return { kind: "refresh" };
371
- if (nextResult) return nextResult;
372
- if (menuResult.kind === "closed") {
373
- return menuResult.reason === "back" ? { kind: "back" } : { kind: "closed" };
374
- }
375
- return { kind: "closed" };
140
+ type Screen = "choice" | "review" | "saved";
141
+ type Action = "adopt" | "keep" | "cancel" | "continue" | "done";
142
+ interface FlowState {
143
+ decision: RemoteSelectionDecision;
144
+ saved: boolean;
145
+ }
146
+ let flowState: FlowState = { decision: initialDecision, saved: false };
147
+ let continuationReview: PartialConfig | undefined;
148
+ let nextResult: RemoteSelectionReviewResult | undefined;
149
+ let refreshRequested = false;
150
+ const route = origin === "settings" ? "sync" : origin;
151
+ const menu = defineMenu<FlowState, Screen, Action, ExtensionContext>({
152
+ start: "choice",
153
+ screens: {
154
+ choice: ({ state }) => ({
155
+ kind: "actions",
156
+ title: "Synced content differs",
157
+ lines: selectionSummaryLines(state.decision),
158
+ items: [
159
+ {
160
+ id: "review",
161
+ label: "Review all paths (recommended)",
162
+ description: "Compare exact remote-only, device-only, and ordered lists.",
163
+ to: "review",
164
+ },
165
+ {
166
+ id: "adopt",
167
+ label: "Use remote content list",
168
+ description: "Save the reviewed list on this device without pulling files.",
169
+ action: "adopt",
170
+ },
171
+ {
172
+ id: "keep",
173
+ label: "Keep this device's content list and update remote…",
174
+ description: "Open the existing exact force-push preview without skipping confirmation.",
175
+ action: "keep",
176
+ },
177
+ { id: "cancel", label: options.cancelLabel ?? "Cancel", action: "cancel" },
178
+ ],
179
+ hint: "back",
180
+ }),
181
+ review: ({ state }) => ({
182
+ kind: "review",
183
+ title: `Review synced content · ${safeTerminalText(state.decision.setupName)}`,
184
+ content: formatSelectionDifference(state.decision),
185
+ format: { kind: "text" },
186
+ viewportSize: "adaptive",
187
+ hint: "back",
188
+ }),
189
+ saved: ({ state }) => ({
190
+ kind: "actions",
191
+ title: "Remote content list saved",
192
+ lines: [
193
+ `Sync setup: ${safeTerminalText(state.decision.setupName)}`,
194
+ "Only the included-content setting was saved.",
195
+ "No files were pulled and sync state was not changed.",
196
+ ],
197
+ items: [
198
+ ...(runRoute
199
+ ? [
200
+ {
201
+ id: "continue",
202
+ label: continueLabel(origin),
203
+ description: "Start a fresh check and exact preview for this sync setup.",
204
+ action: "continue" as const,
205
+ },
206
+ ]
207
+ : []),
208
+ { id: "done", label: "Done", action: "done" },
209
+ ],
210
+ hint: "close",
211
+ }),
212
+ },
213
+ actions: {
214
+ adopt: async ({ state, signal: actionSignal }) => {
215
+ const signal = combineSignals(sessionSignal, actionSignal);
216
+ try {
217
+ const currentConfig = await loadConfig(state.decision.setupName);
218
+ if (signal.aborted) return { kind: "close" as const };
219
+ assertLocalSelectionCurrent(currentConfig, state.decision);
220
+ if (!currentConfig.include.includes("sessions") && state.decision.remoteInclude.includes("sessions")) {
221
+ const acknowledged = await ctx.ui.confirm(
222
+ "Use a content list that includes session conversations?",
223
+ "Session JSONL may contain prompts, tool output, file paths, images, and secrets. This saves the list only; it does not pull files.",
224
+ { signal },
225
+ );
226
+ if (signal.aborted) return { kind: "close" as const };
227
+ if (!acknowledged) return { kind: "stay" as const };
228
+ }
229
+ const review = await runWithOptionalStateAccess(options, async () => {
230
+ const loaded = await loadAdoptionReview(state.decision, signal, factory);
231
+ if (signal.aborted) throw signal.reason;
232
+ await revalidateAndAdopt(loaded, state.decision, signal);
233
+ return loaded;
234
+ });
235
+ if (signal.aborted) return { kind: "close" as const };
236
+ options.onSelectionResolved?.();
237
+ continuationReview = {
238
+ ...review.storageReview,
239
+ setupName: state.decision.setupName,
240
+ include: [...state.decision.remoteInclude],
241
+ automatic: review.config.automatic,
242
+ onSwitch: review.config.onSwitch,
243
+ showStatus: review.config.showStatus,
244
+ };
245
+ flowState = { decision: state.decision, saved: true };
246
+ return { kind: "to" as const, screen: "saved" as const };
247
+ } catch (error) {
248
+ if (signal.aborted) return { kind: "close" as const };
249
+ if (isStaleReviewError(error)) {
250
+ ctx.ui.notify(`${errorMessage(error)} Refreshing the comparison.`, "warning");
251
+ refreshRequested = true;
252
+ return { kind: "close" as const };
253
+ }
254
+ ctx.ui.notify(`Could not save the remote content list: ${errorMessage(error)}`, "error");
255
+ return { kind: "stay" as const };
256
+ }
257
+ },
258
+ keep: async ({ state, signal: actionSignal }) => {
259
+ if (!runRoute) {
260
+ ctx.ui.notify("The reviewed update-remote route is unavailable.", "error");
261
+ return { kind: "stay" as const };
262
+ }
263
+ const signal = combineSignals(sessionSignal, actionSignal);
264
+ try {
265
+ const latest = await loadConfig(state.decision.setupName);
266
+ if (signal.aborted) return { kind: "close" as const };
267
+ assertLocalSelectionCurrent(latest, state.decision);
268
+ const result = await runCancellableOperation(
269
+ ctx,
270
+ "Preparing this device's push preview…",
271
+ "push --force",
272
+ runRoute,
273
+ {
274
+ commitAware: true,
275
+ cancelledMessage: "Push preparation cancelled; no remote files were changed.",
276
+ target: state.decision.setupName,
277
+ signal,
278
+ },
279
+ );
280
+ return handleNestedRouteResult(result, "push");
281
+ } catch (error) {
282
+ if (signal.aborted) return { kind: "close" as const };
283
+ if (isStaleReviewError(error)) {
284
+ ctx.ui.notify(`${errorMessage(error)} Refreshing the comparison.`, "warning");
285
+ refreshRequested = true;
286
+ return { kind: "close" as const };
287
+ }
288
+ ctx.ui.notify(`Could not prepare the remote update: ${errorMessage(error)}`, "error");
289
+ return { kind: "stay" as const };
290
+ }
291
+ },
292
+ continue: async ({ state, signal: actionSignal }) => {
293
+ if (!runRoute || !continuationReview) return { kind: "stay" as const };
294
+ const signal = combineSignals(sessionSignal, actionSignal);
295
+ try {
296
+ const latest = await loadPartialConfig(state.decision.setupName);
297
+ if (signal.aborted) return { kind: "close" as const };
298
+ if (!sameContinuationReview(latest, continuationReview)) {
299
+ throw new StaleRemoteSelectionReviewError(
300
+ `Sync setup “${safeTerminalText(state.decision.setupName)}” changed after the remote content list was saved.`,
301
+ );
302
+ }
303
+ const result = await runCancellableOperation(ctx, continueBusyLabel(origin), route, runRoute, {
304
+ commitAware: true,
305
+ cancelledMessage: continuationCancelledMessage(route),
306
+ target: state.decision.setupName,
307
+ signal,
308
+ });
309
+ return handleNestedRouteResult(result, route);
310
+ } catch (error) {
311
+ if (signal.aborted) return { kind: "close" as const };
312
+ ctx.ui.notify(`Could not continue: ${errorMessage(error)}`, "error");
313
+ return { kind: "stay" as const };
314
+ }
315
+ },
316
+ cancel: async () => ({ kind: "back" }),
317
+ done: async () => {
318
+ nextResult = { kind: "done" };
319
+ return { kind: "close" };
320
+ },
321
+ },
322
+ });
323
+
324
+ function handleNestedRouteResult(
325
+ result: Awaited<ReturnType<typeof runCancellableOperation>>,
326
+ nestedRoute: "sync" | "pull" | "push",
327
+ ) {
328
+ if (result.kind === "completed" && result.outcome === "applied") {
329
+ options.onSelectionResolved?.();
330
+ }
331
+ if (result.kind === "closed") {
332
+ nextResult = { kind: "closed" };
333
+ return { kind: "close" as const };
334
+ }
335
+ if (
336
+ result.kind === "cancelled" ||
337
+ (result.kind === "completed" && result.outcome === "cancelled") ||
338
+ result.kind === "failed"
339
+ ) {
340
+ return { kind: "stay" as const };
341
+ }
342
+ nextResult = { kind: "route-result", result, route: nestedRoute };
343
+ return { kind: "close" as const };
344
+ }
345
+
346
+ const menuResult = await runMenu(ctx, menu, {
347
+ getState: () => flowState,
348
+ signal: sessionSignal,
349
+ isCurrent: () => !sessionSignal?.aborted,
350
+ onError: (_menuCtx, error) => ctx.ui.notify(errorMessage(error), "error"),
351
+ });
352
+ if (sessionSignal?.aborted || menuResult.kind === "stale") return { kind: "stale" };
353
+ if (refreshRequested) return { kind: "refresh" };
354
+ if (nextResult) return nextResult;
355
+ if (menuResult.kind === "closed") {
356
+ return menuResult.reason === "back" ? { kind: "back" } : { kind: "closed" };
357
+ }
358
+ return { kind: "closed" };
376
359
  }
377
360
 
378
361
  interface AdoptionReview {
379
- config: AnySyncConfig;
380
- storageReview: SyncSetupStorageReview;
381
- backend: SyncBackend;
382
- reviewedHead: RemoteHead;
362
+ config: AnySyncConfig;
363
+ storageReview: SyncSetupStorageReview;
364
+ backend: SyncBackend;
365
+ reviewedHead: RemoteHead;
383
366
  }
384
367
 
385
368
  async function loadAdoptionReview(
386
- decision: RemoteSelectionDecision,
387
- signal: AbortSignal,
388
- factory: SyncBackendFactory,
369
+ decision: RemoteSelectionDecision,
370
+ signal: AbortSignal,
371
+ factory: SyncBackendFactory,
389
372
  ): Promise<AdoptionReview> {
390
- const config = await loadConfig(decision.setupName);
391
- throwIfAborted(signal);
392
- assertLocalSelectionCurrent(config, decision);
393
- const partial = await loadPartialConfig(decision.setupName);
394
- throwIfAborted(signal);
395
- if (!sameSyncInclude(partial.include, decision.localInclude)) {
396
- throw new StaleRemoteSelectionReviewError(
397
- `Sync setup “${safeTerminalText(decision.setupName)}” changed while the comparison was open.`,
398
- );
399
- }
400
- const backend = await factory(config);
401
- throwIfAborted(signal);
402
- const reviewedHead = await backend.readHead(signal);
403
- throwIfAborted(signal);
404
- if (!reviewedHead) {
405
- throw new StaleRemoteSelectionReviewError(
406
- "Remote storage changed while the comparison was open.",
407
- );
408
- }
409
- const snapshot = await readSnapshotForHead(backend, reviewedHead, signal);
410
- throwIfAborted(signal);
411
- const state = inspectRemoteSelection(config.include, snapshot);
412
- if (state.kind !== "different" || !sameSyncInclude(state.include, decision.remoteInclude)) {
413
- throw new StaleRemoteSelectionReviewError(
414
- "Remote synced content changed while the comparison was open.",
415
- );
416
- }
417
- return { config, storageReview: partial, backend, reviewedHead };
373
+ const config = await loadConfig(decision.setupName);
374
+ throwIfAborted(signal);
375
+ assertLocalSelectionCurrent(config, decision);
376
+ const partial = await loadPartialConfig(decision.setupName);
377
+ throwIfAborted(signal);
378
+ if (!sameSyncInclude(partial.include, decision.localInclude)) {
379
+ throw new StaleRemoteSelectionReviewError(
380
+ `Sync setup “${safeTerminalText(decision.setupName)}” changed while the comparison was open.`,
381
+ );
382
+ }
383
+ const backend = await factory(config);
384
+ throwIfAborted(signal);
385
+ const reviewedHead = await backend.readHead(signal);
386
+ throwIfAborted(signal);
387
+ if (!reviewedHead) {
388
+ throw new StaleRemoteSelectionReviewError("Remote storage changed while the comparison was open.");
389
+ }
390
+ const snapshot = await readSnapshotForHead(backend, reviewedHead, signal);
391
+ throwIfAborted(signal);
392
+ const state = inspectRemoteSelection(config.include, snapshot);
393
+ if (state.kind !== "different" || !sameSyncInclude(state.include, decision.remoteInclude)) {
394
+ throw new StaleRemoteSelectionReviewError("Remote synced content changed while the comparison was open.");
395
+ }
396
+ return { config, storageReview: partial, backend, reviewedHead };
418
397
  }
419
398
 
420
- async function revalidateAndAdopt(
421
- review: AdoptionReview,
422
- decision: RemoteSelectionDecision,
423
- signal: AbortSignal,
424
- ) {
425
- const currentHead = await review.backend.readHead(signal);
426
- throwIfAborted(signal);
427
- if (
428
- !currentHead ||
429
- !review.backend.sameRevision(review.reviewedHead.revision, currentHead.revision)
430
- ) {
431
- throw new StaleRemoteSelectionReviewError(
432
- "Remote storage changed while the comparison was open.",
433
- );
434
- }
435
- const currentSnapshot = await readSnapshotForHead(review.backend, currentHead, signal);
436
- throwIfAborted(signal);
437
- const currentState = inspectRemoteSelection(review.config.include, currentSnapshot);
438
- if (
439
- currentState.kind !== "different" ||
440
- !sameSyncInclude(currentState.include, decision.remoteInclude)
441
- ) {
442
- throw new StaleRemoteSelectionReviewError(
443
- "Remote synced content changed while the comparison was open.",
444
- );
445
- }
446
- await updateSyncSetup(
447
- decision.setupName,
448
- (setup) => ({
449
- ...setup,
450
- sync: { ...setup.sync, include: [...decision.remoteInclude] },
451
- }),
452
- {
453
- expectedStorage: review.storageReview,
454
- expectedInclude: decision.localInclude,
455
- signal,
456
- },
457
- );
399
+ async function revalidateAndAdopt(review: AdoptionReview, decision: RemoteSelectionDecision, signal: AbortSignal) {
400
+ const currentHead = await review.backend.readHead(signal);
401
+ throwIfAborted(signal);
402
+ if (!currentHead || !review.backend.sameRevision(review.reviewedHead.revision, currentHead.revision)) {
403
+ throw new StaleRemoteSelectionReviewError("Remote storage changed while the comparison was open.");
404
+ }
405
+ const currentSnapshot = await readSnapshotForHead(review.backend, currentHead, signal);
406
+ throwIfAborted(signal);
407
+ const currentState = inspectRemoteSelection(review.config.include, currentSnapshot);
408
+ if (currentState.kind !== "different" || !sameSyncInclude(currentState.include, decision.remoteInclude)) {
409
+ throw new StaleRemoteSelectionReviewError("Remote synced content changed while the comparison was open.");
410
+ }
411
+ await updateSyncSetup(
412
+ decision.setupName,
413
+ (setup) => ({
414
+ ...setup,
415
+ sync: { ...setup.sync, include: [...decision.remoteInclude] },
416
+ }),
417
+ {
418
+ expectedStorage: review.storageReview,
419
+ expectedInclude: decision.localInclude,
420
+ signal,
421
+ },
422
+ );
458
423
  }
459
424
 
460
425
  async function inspectConfiguredRemoteSelection(
461
- ctx: ExtensionContext,
462
- setupName: string | undefined,
463
- signal: AbortSignal | undefined,
464
- factory: SyncBackendFactory,
426
+ ctx: ExtensionContext,
427
+ setupName: string | undefined,
428
+ signal: AbortSignal | undefined,
429
+ factory: SyncBackendFactory,
465
430
  ): Promise<
466
- | { kind: "empty"; config: AnySyncConfig }
467
- | { kind: "selection"; config: AnySyncConfig; state: RemoteSelectionState }
468
- | undefined
431
+ | { kind: "empty"; config: AnySyncConfig }
432
+ | { kind: "selection"; config: AnySyncConfig; state: RemoteSelectionState }
433
+ | undefined
469
434
  > {
470
- const config = await loadConfig(setupName);
471
- if (signal?.aborted) return undefined;
472
- ctx.ui.setStatus(STATUS_KEY, `checking synced content for ${safeTerminalText(config.setupName)}`);
473
- const backend = await factory(config);
474
- if (signal?.aborted) return undefined;
475
- const head = await backend.readHead(signal);
476
- if (signal?.aborted) return undefined;
477
- if (!head) return { kind: "empty", config };
478
- const snapshot = await readSnapshotForHead(backend, head, signal);
479
- if (signal?.aborted) return undefined;
480
- return {
481
- kind: "selection",
482
- config,
483
- state: inspectRemoteSelection(config.include, snapshot),
484
- };
435
+ const config = await loadConfig(setupName);
436
+ if (signal?.aborted) return undefined;
437
+ setSyncStatus(ctx, `checking synced content for ${safeTerminalText(config.setupName)}`);
438
+ const backend = await factory(config);
439
+ if (signal?.aborted) return undefined;
440
+ const head = await backend.readHead(signal);
441
+ if (signal?.aborted) return undefined;
442
+ if (!head) return { kind: "empty", config };
443
+ const snapshot = await readSnapshotForHead(backend, head, signal);
444
+ if (signal?.aborted) return undefined;
445
+ return {
446
+ kind: "selection",
447
+ config,
448
+ state: inspectRemoteSelection(config.include, snapshot),
449
+ };
485
450
  }
486
451
 
487
452
  async function showLegacyDiscovery(
488
- ctx: ExtensionContext,
489
- config: AnySyncConfig,
490
- discovered: string[],
491
- signal?: AbortSignal,
453
+ ctx: ExtensionContext,
454
+ config: AnySyncConfig,
455
+ discovered: string[],
456
+ signal?: AbortSignal,
492
457
  ) {
493
- const menu = defineMenu<undefined, "choice" | "review", "back", ExtensionContext>({
494
- start: "choice",
495
- screens: {
496
- choice: () => ({
497
- kind: "actions",
498
- title: `Compare synced content · ${safeTerminalText(config.setupName)}`,
499
- lines: [
500
- "This legacy snapshot has no portable synced-content list.",
501
- "Discovered paths are partial and read-only; preserved files may not have been selected.",
502
- ],
503
- items: [
504
- { id: "review", label: "Review discovered paths", to: "review" },
505
- { id: "back", label: "Back", action: "back" },
506
- ],
507
- hint: "close",
508
- }),
509
- review: () => ({
510
- kind: "review",
511
- title: "Partial discovery from legacy snapshot",
512
- content: [
513
- "Partial discovery only — not an authoritative selection.",
514
- "",
515
- ...(discovered.length > 0
516
- ? discovered.map((item) => `Discovered: ${safeTerminalText(item)}`)
517
- : ["No safe paths were discovered."]),
518
- "",
519
- "Use Add custom path… in the local Included Content editor if needed.",
520
- ].join("\n"),
521
- format: { kind: "text" },
522
- viewportSize: "adaptive",
523
- hint: "back",
524
- }),
525
- },
526
- actions: { back: async () => ({ kind: "close" }) },
527
- });
528
- await runMenu(ctx, menu, {
529
- getState: () => undefined,
530
- signal,
531
- isCurrent: () => !signal?.aborted,
532
- });
458
+ const menu = defineMenu<undefined, "choice" | "review", "back", ExtensionContext>({
459
+ start: "choice",
460
+ screens: {
461
+ choice: () => ({
462
+ kind: "actions",
463
+ title: `Compare synced content · ${safeTerminalText(config.setupName)}`,
464
+ lines: [
465
+ "This legacy snapshot has no portable synced-content list.",
466
+ "Discovered paths are partial and read-only; preserved files may not have been selected.",
467
+ ],
468
+ items: [
469
+ { id: "review", label: "Review discovered paths", to: "review" },
470
+ { id: "back", label: "Back", action: "back" },
471
+ ],
472
+ hint: "close",
473
+ }),
474
+ review: () => ({
475
+ kind: "review",
476
+ title: "Partial discovery from legacy snapshot",
477
+ content: [
478
+ "Partial discovery only — not an authoritative selection.",
479
+ "",
480
+ ...(discovered.length > 0
481
+ ? discovered.map((item) => `Discovered: ${safeTerminalText(item)}`)
482
+ : ["No safe paths were discovered."]),
483
+ "",
484
+ "Use Add custom path… in the local Included Content editor if needed.",
485
+ ].join("\n"),
486
+ format: { kind: "text" },
487
+ viewportSize: "adaptive",
488
+ hint: "back",
489
+ }),
490
+ },
491
+ actions: { back: async () => ({ kind: "close" }) },
492
+ });
493
+ await runMenu(ctx, menu, {
494
+ getState: () => undefined,
495
+ signal,
496
+ isCurrent: () => !signal?.aborted,
497
+ });
533
498
  }
534
499
 
535
500
  function selectionSummaryLines(decision: RemoteSelectionDecision) {
536
- const comparison = compareSyncInclude(decision.localInclude, decision.remoteInclude);
537
- return [
538
- `Sync setup: ${safeTerminalText(decision.setupName)}`,
539
- "Nothing changed. Review both lists before choosing what happens next.",
540
- ...(comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0
541
- ? ["Only the ordering differs; membership is the same."]
542
- : [
543
- `Remote-only paths: ${comparison.remoteOnly.length} · Device-only paths: ${comparison.localOnly.length}`,
544
- ]),
545
- ];
501
+ const comparison = compareSyncInclude(decision.localInclude, decision.remoteInclude);
502
+ return [
503
+ `Sync setup: ${safeTerminalText(decision.setupName)}`,
504
+ "Nothing changed. Review both lists before choosing what happens next.",
505
+ ...(comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0
506
+ ? ["Only the ordering differs; membership is the same."]
507
+ : [`Remote-only paths: ${comparison.remoteOnly.length} · Device-only paths: ${comparison.localOnly.length}`]),
508
+ ];
546
509
  }
547
510
 
548
511
  function formatSelectionDifference(decision: RemoteSelectionDecision) {
549
- const comparison = compareSyncInclude(decision.localInclude, decision.remoteInclude);
550
- return [
551
- ...(comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0
552
- ? ["Only ordering differs; both lists contain the same paths.", ""]
553
- : []),
554
- "Remote-only paths:",
555
- ...(comparison.remoteOnly.length > 0
556
- ? comparison.remoteOnly.map((item) => `+ ${safeTerminalText(item)}`)
557
- : ["(none)"]),
558
- "",
559
- "Device-only paths:",
560
- ...(comparison.localOnly.length > 0
561
- ? comparison.localOnly.map((item) => `- ${safeTerminalText(item)}`)
562
- : ["(none)"]),
563
- "",
564
- "Remote ordered list:",
565
- ...(decision.remoteInclude.length > 0
566
- ? decision.remoteInclude.map((item, index) => `${index + 1}. ${safeTerminalText(item)}`)
567
- : ["(none)"]),
568
- "",
569
- "This device's ordered list:",
570
- ...(decision.localInclude.length > 0
571
- ? decision.localInclude.map((item, index) => `${index + 1}. ${safeTerminalText(item)}`)
572
- : ["(none)"]),
573
- "",
574
- "Using the remote list saves settings only and does not pull files.",
575
- ].join("\n");
512
+ const comparison = compareSyncInclude(decision.localInclude, decision.remoteInclude);
513
+ return [
514
+ ...(comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0
515
+ ? ["Only ordering differs; both lists contain the same paths.", ""]
516
+ : []),
517
+ "Remote-only paths:",
518
+ ...(comparison.remoteOnly.length > 0
519
+ ? comparison.remoteOnly.map((item) => `+ ${safeTerminalText(item)}`)
520
+ : ["(none)"]),
521
+ "",
522
+ "Device-only paths:",
523
+ ...(comparison.localOnly.length > 0
524
+ ? comparison.localOnly.map((item) => `- ${safeTerminalText(item)}`)
525
+ : ["(none)"]),
526
+ "",
527
+ "Remote ordered list:",
528
+ ...(decision.remoteInclude.length > 0
529
+ ? decision.remoteInclude.map((item, index) => `${index + 1}. ${safeTerminalText(item)}`)
530
+ : ["(none)"]),
531
+ "",
532
+ "This device's ordered list:",
533
+ ...(decision.localInclude.length > 0
534
+ ? decision.localInclude.map((item, index) => `${index + 1}. ${safeTerminalText(item)}`)
535
+ : ["(none)"]),
536
+ "",
537
+ "Using the remote list saves settings only and does not pull files.",
538
+ ].join("\n");
576
539
  }
577
540
 
578
541
  function formatRemoteSelectionSummary(decision: RemoteSelectionDecision) {
579
- const comparison = compareSyncInclude(decision.localInclude, decision.remoteInclude);
580
- return [
581
- `Synced content for “${safeTerminalText(decision.setupName)}” differs from this device.`,
582
- `Remote-only: ${safeList(comparison.remoteOnly)}`,
583
- `Device-only: ${safeList(comparison.localOnly)}`,
584
- ...(comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0
585
- ? [
586
- "Only ordering differs.",
587
- `Remote order: ${safeList(decision.remoteInclude)}`,
588
- `Device order: ${safeList(decision.localInclude)}`,
589
- ]
590
- : []),
591
- "Run /sync in TUI to choose a content list; RPC review is read-only.",
592
- ].join("\n");
542
+ const comparison = compareSyncInclude(decision.localInclude, decision.remoteInclude);
543
+ return [
544
+ `Synced content for “${safeTerminalText(decision.setupName)}” differs from this device.`,
545
+ `Remote-only: ${safeList(comparison.remoteOnly)}`,
546
+ `Device-only: ${safeList(comparison.localOnly)}`,
547
+ ...(comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0
548
+ ? [
549
+ "Only ordering differs.",
550
+ `Remote order: ${safeList(decision.remoteInclude)}`,
551
+ `Device order: ${safeList(decision.localInclude)}`,
552
+ ]
553
+ : []),
554
+ "Run /sync in TUI to choose a content list; RPC review is read-only.",
555
+ ].join("\n");
593
556
  }
594
557
 
595
558
  function formatLegacySummary(config: AnySyncConfig, discovered: readonly string[]) {
596
- return `Remote snapshot for “${safeTerminalText(config.setupName)}” has no portable synced-content list; ${discovered.length} safe path${discovered.length === 1 ? " was" : "s were"} discovered, but the result is partial and read-only.`;
559
+ return `Remote snapshot for “${safeTerminalText(config.setupName)}” has no portable synced-content list; ${discovered.length} safe path${discovered.length === 1 ? " was" : "s were"} discovered, but the result is partial and read-only.`;
597
560
  }
598
561
 
599
562
  function decisionFromState(
600
- config: AnySyncConfig,
601
- state: Extract<RemoteSelectionState, { kind: "different" }>,
563
+ config: AnySyncConfig,
564
+ state: Extract<RemoteSelectionState, { kind: "different" }>,
602
565
  ): RemoteSelectionDecision {
603
- return {
604
- setupName: config.setupName,
605
- configIdentity: syncConfigReviewFingerprint(config),
606
- localInclude: [...config.include],
607
- remoteInclude: [...state.include],
608
- };
566
+ return {
567
+ setupName: config.setupName,
568
+ configIdentity: syncConfigReviewFingerprint(config),
569
+ localInclude: [...config.include],
570
+ remoteInclude: [...state.include],
571
+ };
609
572
  }
610
573
 
611
574
  function assertLocalSelectionCurrent(config: AnySyncConfig, decision: RemoteSelectionDecision) {
612
- if (
613
- syncConfigReviewFingerprint(config) === decision.configIdentity &&
614
- sameSyncInclude(config.include, decision.localInclude)
615
- ) {
616
- return;
617
- }
618
- throw new StaleRemoteSelectionReviewError(
619
- `Sync setup “${safeTerminalText(config.setupName)}” changed while the comparison was open.`,
620
- );
575
+ if (
576
+ syncConfigReviewFingerprint(config) === decision.configIdentity &&
577
+ sameSyncInclude(config.include, decision.localInclude)
578
+ ) {
579
+ return;
580
+ }
581
+ throw new StaleRemoteSelectionReviewError(
582
+ `Sync setup “${safeTerminalText(config.setupName)}” changed while the comparison was open.`,
583
+ );
621
584
  }
622
585
 
623
586
  function sameContinuationReview(left: PartialConfig, right: PartialConfig) {
624
- return (
625
- left.setupName === right.setupName &&
626
- left.connectionName === right.connectionName &&
627
- left.storageKind === right.storageKind &&
628
- left.storagePath === right.storagePath &&
629
- left.bucket === right.bucket &&
630
- left.branch === right.branch &&
631
- sameSyncInclude(left.include, right.include)
632
- );
587
+ return (
588
+ left.setupName === right.setupName &&
589
+ left.connectionName === right.connectionName &&
590
+ left.storageKind === right.storageKind &&
591
+ left.storagePath === right.storagePath &&
592
+ left.bucket === right.bucket &&
593
+ left.branch === right.branch &&
594
+ sameSyncInclude(left.include, right.include)
595
+ );
633
596
  }
634
597
 
635
598
  function continueLabel(origin: RemoteSelectionOrigin) {
636
- if (origin === "pull") return "Continue Pull now…";
637
- if (origin === "push") return "Continue Push now…";
638
- return "Continue Sync now…";
599
+ if (origin === "pull") return "Continue Pull now…";
600
+ if (origin === "push") return "Continue Push now…";
601
+ return "Continue Sync now…";
639
602
  }
640
603
 
641
604
  function continueBusyLabel(origin: RemoteSelectionOrigin) {
642
- if (origin === "pull") return "Checking remote changes…";
643
- if (origin === "push") return "Preparing push preview…";
644
- return "Checking current sync setup…";
605
+ if (origin === "pull") return "Checking remote changes…";
606
+ if (origin === "push") return "Preparing push preview…";
607
+ return "Checking current sync setup…";
645
608
  }
646
609
 
647
610
  function continuationCancelledMessage(route: "sync" | "pull" | "push") {
648
- if (route === "pull") return "Pull check cancelled; no local files were changed.";
649
- if (route === "push") return "Push preparation cancelled; no remote files were changed.";
650
- return "Sync check cancelled; no settings or files were changed.";
611
+ if (route === "pull") return "Pull check cancelled; no local files were changed.";
612
+ if (route === "push") return "Push preparation cancelled; no remote files were changed.";
613
+ return "Sync check cancelled; no settings or files were changed.";
651
614
  }
652
615
 
653
616
  function safeList(values: readonly string[]) {
654
- return values.length > 0 ? values.map(safeTerminalText).join(", ") : "none";
617
+ return values.length > 0 ? values.map(safeTerminalText).join(", ") : "none";
655
618
  }
656
619
 
657
620
  class StaleRemoteSelectionReviewError extends Error {
658
- constructor(message: string) {
659
- super(message);
660
- this.name = "StaleRemoteSelectionReviewError";
661
- }
621
+ constructor(message: string) {
622
+ super(message);
623
+ this.name = "StaleRemoteSelectionReviewError";
624
+ }
662
625
  }
663
626
 
664
627
  function isStaleReviewError(error: unknown) {
665
- return (
666
- error instanceof StaleRemoteSelectionReviewError || error instanceof SyncSetupReviewChangedError
667
- );
628
+ return error instanceof StaleRemoteSelectionReviewError || error instanceof SyncSetupReviewChangedError;
668
629
  }
669
630
 
670
631
  function runWithOptionalStateAccess<T>(
671
- options: Pick<RemoteSelectionReviewOptions, "withStateAccess">,
672
- task: () => Promise<T>,
632
+ options: Pick<RemoteSelectionReviewOptions, "withStateAccess">,
633
+ task: () => Promise<T>,
673
634
  ) {
674
- return options.withStateAccess ? options.withStateAccess(task) : task();
635
+ return options.withStateAccess ? options.withStateAccess(task) : task();
675
636
  }
676
637
 
677
638
  function combineSignals(sessionSignal: AbortSignal | undefined, actionSignal: AbortSignal) {
678
- return sessionSignal ? AbortSignal.any([sessionSignal, actionSignal]) : actionSignal;
639
+ return sessionSignal ? AbortSignal.any([sessionSignal, actionSignal]) : actionSignal;
679
640
  }
680
641
 
681
642
  function throwIfAborted(signal: AbortSignal) {
682
- if (!signal.aborted) return;
683
- throw signal.reason instanceof Error
684
- ? signal.reason
685
- : new DOMException("The operation was aborted", "AbortError");
643
+ if (!signal.aborted) return;
644
+ throw signal.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
686
645
  }