@narumitw/pi-sync 0.63.1 → 0.64.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 (127) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +12 -5
  3. package/dist/chunks/{chunk-HLCML3OW.ts → chunk-4VKWHVUO.ts} +4 -3
  4. package/dist/chunks/chunk-4VKWHVUO.ts.map +7 -0
  5. package/dist/chunks/{chunk-27F5W7DX.ts → chunk-DAZZ5BEJ.ts} +3 -1
  6. package/dist/chunks/chunk-DAZZ5BEJ.ts.map +7 -0
  7. package/dist/chunks/{chunk-V76KCWHO.ts → chunk-F3VODLVQ.ts} +3 -3
  8. package/dist/chunks/{chunk-VQ47JBLF.ts → chunk-FI2F5JBS.ts} +2 -2
  9. package/dist/chunks/{chunk-LBNC5AOM.ts → chunk-NDEZ52SS.ts} +12 -12
  10. package/dist/chunks/{chunk-B5F3JLD3.ts → chunk-RW44KNFD.ts} +304 -70
  11. package/dist/chunks/chunk-RW44KNFD.ts.map +7 -0
  12. package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-TJ7YNITN.ts} +5 -5
  13. package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
  14. package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-VPSC7BXM.ts} +3 -3
  15. package/dist/chunks/{chunk-POWOMJ7S.ts → chunk-YT6PDRMM.ts} +58 -31
  16. package/dist/chunks/chunk-YT6PDRMM.ts.map +7 -0
  17. package/dist/chunks/{command-handler-GMRRFWOL.ts → command-handler-N45GY7AV.ts} +39 -27
  18. package/dist/chunks/command-handler-N45GY7AV.ts.map +7 -0
  19. package/dist/chunks/{conflict-review-JWEA7DPQ.ts → conflict-review-5E4M44BA.ts} +2 -2
  20. package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
  21. package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-FKW55L7I.ts} +5 -5
  22. package/dist/chunks/{manager-ui-T5J5WG7T.ts → manager-ui-EV23DPZQ.ts} +75 -57
  23. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +7 -0
  24. package/dist/chunks/{merge-review-OQDXNTJU.ts → merge-review-6YSLSMGS.ts} +3 -2
  25. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
  26. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
  27. package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-N4NMWFT2.ts} +4 -4
  28. package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-HY7K3442.ts} +4 -4
  29. package/dist/chunks/{setup-wizard-LL6YMGUR.ts → setup-wizard-LEKDQ3HK.ts} +9 -9
  30. package/dist/chunks/{sync-inspection-SRU6HGGK.ts → sync-inspection-OS2LVOLV.ts} +5 -5
  31. package/dist/chunks/{sync-operations-UGSCONZ7.ts → sync-operations-D3MDJUQQ.ts} +2 -2
  32. package/dist/daemon/dist/cli.js +2 -0
  33. package/dist/daemon/dist/client-transport.js +66 -0
  34. package/dist/daemon/dist/client.js +116 -86
  35. package/dist/daemon/dist/consent.js +33 -11
  36. package/dist/daemon/dist/daemon-debug.js +33 -0
  37. package/dist/daemon/dist/daemon-recovery.js +75 -0
  38. package/dist/daemon/dist/engine/backends/git/git-backend.js +39 -12
  39. package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
  40. package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
  41. package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
  42. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +10 -12
  43. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +15 -26
  44. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
  45. package/dist/daemon/dist/engine/debug-log.js +134 -0
  46. package/dist/daemon/dist/engine/paths.js +7 -1
  47. package/dist/daemon/dist/engine/settings/config-file.js +62 -17
  48. package/dist/daemon/dist/engine/settings/config.js +49 -14
  49. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
  50. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
  51. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
  52. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
  53. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
  54. package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
  55. package/dist/daemon/dist/engine/state/lock.js +157 -17
  56. package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
  57. package/dist/daemon/dist/engine/sync/initialization.js +2 -2
  58. package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
  59. package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
  60. package/dist/daemon/dist/engine/sync/remote-snapshot.js +18 -3
  61. package/dist/daemon/dist/engine/sync/session-push.js +13 -4
  62. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
  63. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
  64. package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
  65. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -1
  66. package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
  67. package/dist/daemon/dist/engine/sync/sync-local.js +3 -1
  68. package/dist/daemon/dist/engine/sync/sync-mutations.js +9 -3
  69. package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
  70. package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
  71. package/dist/daemon/dist/engine-service.js +54 -10
  72. package/dist/daemon/dist/identity.js +36 -6
  73. package/dist/daemon/dist/index.js +2 -1
  74. package/dist/daemon/dist/monitor.js +20 -1
  75. package/dist/daemon/dist/paged-review.js +177 -0
  76. package/dist/daemon/dist/participant-ledger.js +149 -0
  77. package/dist/daemon/dist/protocol.js +4 -0
  78. package/dist/daemon/dist/server.js +268 -120
  79. package/dist/daemon/dist/service-host.js +29 -9
  80. package/dist/daemon/dist/state-wait-jobs.js +23 -0
  81. package/dist/daemon/dist/state-wait.js +34 -0
  82. package/dist/daemon/package.json +1 -1
  83. package/dist/index.ts +128 -48
  84. package/dist/index.ts.map +2 -2
  85. package/docs/continuous-sync-verification.md +2 -0
  86. package/docs/daemon-migration.md +30 -2
  87. package/docs/tui-contract.md +7 -1
  88. package/package.json +2 -2
  89. package/skills/configure-pi-sync/references/configuration.md +23 -13
  90. package/src/commands/command-execution.ts +11 -3
  91. package/src/commands/command-handler.ts +10 -3
  92. package/src/commands/command.ts +3 -2
  93. package/src/daemon/client-debug.ts +45 -0
  94. package/src/daemon/ownership-recovery.ts +50 -0
  95. package/src/daemon/pi-client.ts +288 -63
  96. package/src/daemon/startup-bootstrap-client.ts +26 -0
  97. package/src/settings/config.ts +1 -0
  98. package/src/sync/automatic-sync.ts +61 -18
  99. package/src/sync/startup-check.ts +13 -5
  100. package/src/sync-extension.ts +46 -8
  101. package/src/ui/manager-state.ts +29 -21
  102. package/src/ui/manager-ui.ts +16 -1
  103. package/src/ui/merge-review.ts +52 -16
  104. package/src/ui/settings-ui.ts +2 -2
  105. package/src/ui/sync-confirmation.ts +16 -19
  106. package/src/ui/sync-setups-ui.ts +15 -12
  107. package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
  108. package/dist/chunks/chunk-B5F3JLD3.ts.map +0 -7
  109. package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
  110. package/dist/chunks/chunk-POWOMJ7S.ts.map +0 -7
  111. package/dist/chunks/command-handler-GMRRFWOL.ts.map +0 -7
  112. package/dist/chunks/manager-ui-T5J5WG7T.ts.map +0 -7
  113. /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-F3VODLVQ.ts.map} +0 -0
  114. /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
  115. /package/dist/chunks/{chunk-LBNC5AOM.ts.map → chunk-NDEZ52SS.ts.map} +0 -0
  116. /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-TJ7YNITN.ts.map} +0 -0
  117. /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
  118. /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-VPSC7BXM.ts.map} +0 -0
  119. /package/dist/chunks/{conflict-review-JWEA7DPQ.ts.map → conflict-review-5E4M44BA.ts.map} +0 -0
  120. /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
  121. /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-FKW55L7I.ts.map} +0 -0
  122. /package/dist/chunks/{merge-review-OQDXNTJU.ts.map → merge-review-6YSLSMGS.ts.map} +0 -0
  123. /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-N4NMWFT2.ts.map} +0 -0
  124. /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-HY7K3442.ts.map} +0 -0
  125. /package/dist/chunks/{setup-wizard-LL6YMGUR.ts.map → setup-wizard-LEKDQ3HK.ts.map} +0 -0
  126. /package/dist/chunks/{sync-inspection-SRU6HGGK.ts.map → sync-inspection-OS2LVOLV.ts.map} +0 -0
  127. /package/dist/chunks/{sync-operations-UGSCONZ7.ts.map → sync-operations-D3MDJUQQ.ts.map} +0 -0
@@ -27,29 +27,66 @@ export async function startSession(
27
27
  return { debug: false };
28
28
  }
29
29
  const timings = createStartupTimings(publish);
30
- const document = await timings.measure("settings read", () => client.readSettings());
31
- throwIfAborted(signal);
32
- configureSyncStatus(ctx, (document?.parsed.showStatus as boolean | undefined) ?? true);
33
- const { stateDirectoryMigrationNotice } = await import("../state/state-directory.js");
34
- const notice = stateDirectoryMigrationNotice();
35
- const { pendingTransactionEntries } = await import("../snapshot/snapshot-transaction-directory.js");
36
- const recoveryNeeded = (await pendingTransactionEntries()).some((entry) => entry.isDirectory());
37
- throwIfAborted(signal);
38
- if (!(await client.configured()) && !recoveryNeeded) {
39
- if (notice) ctx.ui.notify(notice, "warning");
40
- setSyncSetupCompletions([]);
41
- const debug = document?.parsed.debug === true;
42
- await client.markReady(debug);
43
- timings.publish(ctx, debug, signal, "local initialization", "completed");
44
- return { debug };
30
+ let showLocalTimings = false;
31
+ let localStartupComplete = false;
32
+ try {
33
+ const { document, settings } = await timings.measure("settings read", () => client.readStartupSettings(signal));
34
+ client.validate();
35
+ throwIfAborted(signal);
36
+ const debug = settings?.debug ?? false;
37
+ client.setDebugPreference(debug);
38
+ configureSyncStatus(ctx, settings?.showStatus ?? true);
39
+ const { stateDirectoryMigrationNotice } = await import("../state/state-directory.js");
40
+ client.validate();
41
+ throwIfAborted(signal);
42
+ const notice = stateDirectoryMigrationNotice();
43
+ if (settings?.activeSyncSetup && document) {
44
+ const ready = !notice && (await client.tryStartupBootstrap(document, debug, signal));
45
+ client.validate();
46
+ throwIfAborted(signal);
47
+ if (ready) {
48
+ setSyncSetupCompletions(Object.keys(settings.syncSetups).sort((a, b) => a.localeCompare(b)));
49
+ showLocalTimings = debug;
50
+ localStartupComplete = true;
51
+ return { debug, config: configFromSettings(settings) };
52
+ }
53
+ } else {
54
+ const { pendingTransactionEntries } = await import("../snapshot/snapshot-transaction-directory.js");
55
+ const recoveryNeeded = (await pendingTransactionEntries()).length > 0;
56
+ client.validate();
57
+ throwIfAborted(signal);
58
+ if (!recoveryNeeded) {
59
+ if (notice) ctx.ui.notify(notice, "warning");
60
+ setSyncSetupCompletions([]);
61
+ await client.markReady(debug);
62
+ client.validate();
63
+ throwIfAborted(signal);
64
+ client.recordDebug({ event: "job", operation: "initialize", outcome: "skipped" });
65
+ showLocalTimings = debug;
66
+ localStartupComplete = true;
67
+ return { debug };
68
+ }
69
+ }
70
+ localStartupComplete = true;
71
+ } finally {
72
+ timings.publish(
73
+ ctx,
74
+ showLocalTimings,
75
+ signal,
76
+ "local initialization",
77
+ localStartupComplete ? "completed" : "stopped",
78
+ client.debugEnabled && !signal.aborted
79
+ ? (report) => client.recordDebug({ event: "startup-timings", report })
80
+ : undefined,
81
+ );
45
82
  }
46
- throwIfAborted(signal);
47
83
  const result = (await client.run("initialize", {}, signal)) as {
48
84
  debug: boolean;
49
85
  config?: AnySyncConfig;
50
86
  settings?: PiSyncSettingsV3;
51
87
  handoverRequired: boolean;
52
88
  };
89
+ client.validate();
53
90
  throwIfAborted(signal);
54
91
  configureSyncStatus(ctx, result.settings?.showStatus ?? true);
55
92
  setSyncSetupCompletions(Object.keys(result.settings?.syncSetups ?? {}).sort((a, b) => a.localeCompare(b)));
@@ -68,11 +105,17 @@ export async function autoPushSessions(ctx: ExtensionContext, signal: AbortSigna
68
105
  try {
69
106
  const client = piDaemonClient(ctx);
70
107
  const eligible = (config: AnySyncConfig) => config.automatic && syncSessionsSelected(config);
71
- if (!(await client.configured((settings) => eligible(configFromSettings(settings))))) return;
108
+ if (!(await client.configured((settings) => eligible(configFromSettings(settings))))) {
109
+ client.recordDebug({ event: "job", operation: "shutdown", outcome: "skipped" });
110
+ return;
111
+ }
72
112
  throwIfAborted(signal);
73
113
  const config = await loadConfigForCheck(undefined, signal);
74
114
  throwIfAborted(signal);
75
- if (!eligible(config)) return;
115
+ if (!eligible(config)) {
116
+ client.recordDebug({ event: "job", operation: "shutdown", outcome: "skipped" });
117
+ return;
118
+ }
76
119
  const automaticFingerprint = syncCheckConfigFingerprint(config);
77
120
  await client.run(
78
121
  "shutdown",
@@ -30,7 +30,9 @@ export function createStartupCheck(
30
30
  }
31
31
  | undefined;
32
32
 
33
- let pending: { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig } | undefined;
33
+ let pending:
34
+ | { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig; logTimings?: (report: string) => void }
35
+ | undefined;
34
36
 
35
37
  const controllerApi = {
36
38
  async interrupt(ctx: ExtensionContext) {
@@ -43,12 +45,17 @@ export function createStartupCheck(
43
45
  const queued = pending;
44
46
  if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;
45
47
  pending = undefined;
46
- controllerApi.start(ctx, queued.signal, queued.config);
48
+ controllerApi.start(ctx, queued.signal, queued.config, queued.logTimings);
47
49
  },
48
- start(ctx: ExtensionContext, sessionSignal: AbortSignal, initialConfig?: AnySyncConfig) {
50
+ start(
51
+ ctx: ExtensionContext,
52
+ sessionSignal: AbortSignal,
53
+ initialConfig?: AnySyncConfig,
54
+ logTimings?: (report: string) => void,
55
+ ) {
49
56
  if (!ctx.hasUI || sessionSignal.aborted) return;
50
57
  if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {
51
- pending = { ctx, signal: sessionSignal, config: initialConfig };
58
+ pending = { ctx, signal: sessionSignal, config: initialConfig, logTimings };
52
59
  return;
53
60
  }
54
61
  if (active) throw new Error("Previous startup check has not been drained.");
@@ -119,7 +126,7 @@ export function createStartupCheck(
119
126
  throwIfAborted(signal);
120
127
  if (!isCurrent() || syncCheckConfigFingerprint(transferConfig) !== identity) return;
121
128
  if (!ctx.isIdle()) {
122
- pending = { ctx, signal: sessionSignal, config: captured };
129
+ pending = { ctx, signal: sessionSignal, config: captured, logTimings };
123
130
  return;
124
131
  }
125
132
  await timings.measure("automatic transfer", () =>
@@ -191,6 +198,7 @@ export function createStartupCheck(
191
198
  sessionSignal,
192
199
  "background startup",
193
200
  signal.aborted || stopped ? "stopped" : "completed",
201
+ logTimings,
194
202
  );
195
203
  }
196
204
  if (active === task) active = undefined;
@@ -53,9 +53,29 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
53
53
  await withPiDaemonClient(
54
54
  ctx,
55
55
  async (ctx) => {
56
- const command = splitArgs(args)[0];
57
- const ready = await initialization;
56
+ const [command, action, ...extra] = splitArgs(args);
57
+ const recover = command === "daemon" && action === "recover";
58
+ const ready = recover ? undefined : await initialization;
58
59
  if (signal.aborted || owner !== client) return;
60
+ const needsDaemonRecovery = () => client.ownershipCleanupRequired;
61
+ if (recover || (!command && needsDaemonRecovery())) {
62
+ if (recover && extra.length) {
63
+ ctx.ui.notify("Usage: /sync daemon recover", "error");
64
+ return;
65
+ }
66
+ const commands = await loaders.commands();
67
+ if (signal.aborted || owner !== client) return;
68
+ await commands.handleCommand(
69
+ args,
70
+ ctx,
71
+ commandSignal,
72
+ loaders,
73
+ attention,
74
+ undefined,
75
+ needsDaemonRecovery,
76
+ );
77
+ return;
78
+ }
59
79
  const requiresContact = !["help", "unlock", "migrate-state"].includes(command ?? "");
60
80
  let busyPublished = false;
61
81
  try {
@@ -85,8 +105,17 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
85
105
  }
86
106
  const commands = await loaders.commands();
87
107
  if (signal.aborted || owner !== client) return;
88
- await commands.handleCommand(args, ctx, commandSignal, loaders, attention);
108
+ await commands.handleCommand(
109
+ args,
110
+ ctx,
111
+ commandSignal,
112
+ loaders,
113
+ attention,
114
+ undefined,
115
+ needsDaemonRecovery,
116
+ );
89
117
  } catch (error) {
118
+ client.recordOwnershipFailure(error);
90
119
  if (!commandSignal.aborted && owner === client) {
91
120
  ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, "error");
92
121
  if (command === "unlock" || command === "migrate-state") throw error;
@@ -96,7 +125,7 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
96
125
  // Recovery can publish busy facts after bypassing the initial contact check.
97
126
  const publish = busyPublished || command === "unlock" || command === "migrate-state";
98
127
  // Release local busy state even if contact failed; do not mask the command result.
99
- await client.setBusy("command", false, publish).catch(() => {});
128
+ await client.setBusy("command", false, publish && !needsDaemonRecovery()).catch(() => {});
100
129
  }
101
130
  }
102
131
  },
@@ -148,9 +177,12 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
148
177
  } catch (error) {
149
178
  if (!signal.aborted && owner === client) {
150
179
  try {
151
- client.validate();
152
- if (ctx.hasUI)
153
- ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, "error");
180
+ ctx.isIdle();
181
+ client.recordOwnershipFailure(error);
182
+ if (ctx.hasUI) {
183
+ const advice = client.ownershipCleanupRequired ? " Open /sync to recover the daemon." : "";
184
+ ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}${advice}`, "error");
185
+ }
154
186
  } catch {
155
187
  /* SDK context was replaced. */
156
188
  }
@@ -172,7 +204,12 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
172
204
  (ready.automatic || startupTransferEnabled(ready))
173
205
  )
174
206
  await withPiDaemonClient(ctx, async () => {
175
- check.start(ctx, signal, ready);
207
+ check.start(
208
+ ctx,
209
+ signal,
210
+ ready,
211
+ client.debugEnabled ? (report) => client.recordDebug({ event: "startup-timings", report }) : undefined,
212
+ );
176
213
  });
177
214
  } catch (error) {
178
215
  client.disableQueueReleaseUI();
@@ -239,6 +276,7 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
239
276
  if (signal.aborted || owner !== client) return;
240
277
  if (reason !== "reload") {
241
278
  shutdownClient = bindPiDaemonClient(ctx, signal, publishTimings);
279
+ shutdownClient.setDebugPreference(client.debugEnabled);
242
280
  await shutdownClient.setBusy("shutdown", true);
243
281
  const attached = await shutdownClient.attachExisting();
244
282
  if (!signal.aborted && owner === client && attached)
@@ -1,8 +1,8 @@
1
1
  import { truncateToWidth } from "@earendil-works/pi-tui";
2
- import { configFromSettings, loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
3
- import { activeLocalConfigPath, readActiveLocalConfigDocumentForRepair } from "../settings/config-file.js";
4
- import type { AnySyncConfig, PiSyncSettingsV3 } from "../settings/settings-types.js";
5
- import { isCloudflareR2Endpoint, validateSettingsDocument } from "../settings/settings-validation.js";
2
+ import { createSettingsConfigView, syncCheckConfigFingerprint } from "../settings/config.js";
3
+ import { type LocalConfigDocument, readActiveLocalConfigDocumentForRepair } from "../settings/config-file.js";
4
+ import type { AnySyncConfig } from "../settings/settings-types.js";
5
+ import { isCloudflareR2Endpoint } from "../settings/settings-validation.js";
6
6
  import {
7
7
  inspectOperationAvailability,
8
8
  type OperationAvailability,
@@ -20,7 +20,7 @@ import {
20
20
  type SyncAttentionState,
21
21
  syncAttentionMatchesConfig,
22
22
  } from "./sync-attention.js";
23
- import { countValidSyncSetups } from "./sync-setups-ui.js";
23
+ import { hasAnotherSwitchableSetup } from "./sync-setups-ui.js";
24
24
  import { safeTerminalText } from "./terminal-text.js";
25
25
 
26
26
  export const MAIN_MENU_ACTIONS = [
@@ -53,34 +53,35 @@ export async function describeManagerState(
53
53
  observation?: StartupObservation,
54
54
  canUseIgnoreSettings?: () => Promise<boolean>,
55
55
  ): Promise<ManagerDescription> {
56
- let raw: PiSyncSettingsV3 | undefined;
56
+ signal?.throwIfAborted();
57
+ let document: LocalConfigDocument | undefined;
58
+ let view: ReturnType<typeof createSettingsConfigView> | undefined;
57
59
  try {
58
- const document = await readActiveLocalConfigDocumentForRepair();
60
+ document = await readActiveLocalConfigDocumentForRepair();
59
61
  signal?.throwIfAborted();
60
- if (document) raw = validateSettingsDocument(document.parsed);
62
+ if (document) view = createSettingsConfigView(document);
61
63
  } catch (error) {
62
- if (signal?.aborted) throw error;
64
+ signal?.throwIfAborted();
63
65
  return {
64
66
  title: [
65
67
  "Manage sync",
66
68
  "",
67
69
  "Settings file needs repair. Automatic sync and settings writes are paused.",
68
70
  `Error: ${safeTerminalText(errorMessage(error))}`,
69
- `File: ${safeTerminalText(await activeLocalConfigPath())}`,
71
+ ...(document ? [`File: ${safeTerminalText(document.path)}`] : []),
70
72
  "",
71
73
  "Repair the JSON file, then reopen /sync.",
72
74
  ].join("\n"),
73
75
  actions: ["Help"],
74
76
  };
75
77
  }
76
- if (!raw) {
78
+ if (!view || !document) {
77
79
  return {
78
80
  title: ["Manage sync", "", "Not set up.", "", "What do you want to do?"].join("\n"),
79
81
  actions: ["Set up sync", "Help"],
80
82
  };
81
83
  }
82
- const configuredTargets = raw.syncSetups;
83
- if (Object.keys(configuredTargets).length === 0) {
84
+ if (view.setupNames.length === 0) {
84
85
  return {
85
86
  title: [
86
87
  "Manage sync",
@@ -95,25 +96,30 @@ export async function describeManagerState(
95
96
  }
96
97
  let settingsConfig: AnySyncConfig | undefined;
97
98
  try {
98
- settingsConfig = configFromSettings(raw);
99
+ settingsConfig = view.metadata();
99
100
  if (settingsConfig.reservedIgnoreNames && canUseIgnoreSettings && !(await canUseIgnoreSettings())) {
100
101
  throw new Error("the connected daemon does not support ignore-file setups");
101
102
  }
102
103
  signal?.throwIfAborted();
103
- const config = await loadConfig();
104
+ const config = await view.observe(undefined, signal);
104
105
  signal?.throwIfAborted();
105
106
  const operation = await inspectOperation();
107
+ signal?.throwIfAborted();
106
108
  const changesBlocked = operationBlocksChanges(operation);
107
109
  let currentAttention: SyncAttentionState | undefined;
110
+ let alternateUsable = false;
108
111
  if (attention) {
109
112
  try {
110
113
  const attentionConfig =
111
- attention.decision.setupName === config.setupName ? config : await loadConfig(attention.decision.setupName);
114
+ attention.decision.setupName === config.setupName
115
+ ? config
116
+ : await view.observe(attention.decision.setupName, signal);
117
+ alternateUsable = attentionConfig.setupName !== config.setupName;
112
118
  if (syncAttentionMatchesConfig(attention, attentionConfig)) currentAttention = attention;
113
119
  } catch {
114
120
  currentAttention = undefined;
115
121
  }
116
- if (signal?.aborted) throw signal.reason;
122
+ signal?.throwIfAborted();
117
123
  }
118
124
  const attentionComparison = currentAttention
119
125
  ? compareSyncInclude(currentAttention.decision.localInclude, currentAttention.decision.remoteInclude)
@@ -125,6 +131,7 @@ export async function describeManagerState(
125
131
  currentAttention?.decision.localDirectory || currentAttention?.decision.remoteDirectory;
126
132
  const noSyncedContent = !syncSelectionHasContent(config);
127
133
  const syncState = changesBlocked ? undefined : await readStateForConfig(config).catch(() => undefined);
134
+ signal?.throwIfAborted();
128
135
  const currentObservation =
129
136
  observation &&
130
137
  observationMatchesConfig(observation, config) &&
@@ -139,7 +146,8 @@ export async function describeManagerState(
139
146
  : syncState
140
147
  ? "Never synced"
141
148
  : "Unavailable";
142
- const canSwitch = (await countValidSyncSetups(configuredTargets, signal)) > 1;
149
+ const canSwitch = !changesBlocked && (alternateUsable || (await hasAnotherSwitchableSetup(view, signal)));
150
+ signal?.throwIfAborted();
143
151
  const mainActions: string[] = [...MAIN_MENU_ACTIONS];
144
152
  if (config.agentMode && !noSyncedContent) mainActions.splice(1, 0, "Retry refused model result…");
145
153
  if (canSwitch) mainActions.push("Switch sync setup");
@@ -201,7 +209,7 @@ export async function describeManagerState(
201
209
  : {}),
202
210
  };
203
211
  } catch (error) {
204
- if (signal?.aborted) throw error;
212
+ signal?.throwIfAborted();
205
213
  if (settingsConfig?.reservedIgnoreNames !== undefined) {
206
214
  return {
207
215
  title: [
@@ -221,9 +229,9 @@ export async function describeManagerState(
221
229
  "Manage sync",
222
230
  "",
223
231
  "Settings need attention. Automatic sync is paused.",
224
- `Current sync setup: ${safeTerminalText(typeof raw.activeSyncSetup === "string" ? raw.activeSyncSetup : "none")}`,
232
+ `Current sync setup: ${safeTerminalText(view.activeSetupName ?? "none")}`,
225
233
  `Error: ${safeTerminalText(errorMessage(error))}`,
226
- `File: ${safeTerminalText(await activeLocalConfigPath())}`,
234
+ `File: ${safeTerminalText(document.path)}`,
227
235
  "",
228
236
  "What do you want to do?",
229
237
  ].join("\n"),
@@ -27,7 +27,7 @@ export async function showSyncManager(
27
27
  ctx: ExtensionCommandContext,
28
28
  runRoute: RunRoute,
29
29
  sessionSignal?: AbortSignal,
30
- options: SyncManagerAttentionOptions = {},
30
+ options: SyncManagerAttentionOptions & { needsDaemonRecovery?: () => boolean } = {},
31
31
  ): Promise<void> {
32
32
  if (!ctx.hasUI) {
33
33
  await runRoute("help");
@@ -60,6 +60,7 @@ export async function showSyncManager(
60
60
  | "conflicts"
61
61
  | "doctor"
62
62
  | "recover"
63
+ | "daemon-recovery"
63
64
  | "refresh"
64
65
  | "help"
65
66
  | "init";
@@ -295,6 +296,10 @@ export async function showSyncManager(
295
296
  });
296
297
  return { kind: result.kind === "closed" ? "close" : "stay" };
297
298
  },
299
+ "daemon-recovery": async ({ signal }) => {
300
+ await runRoute("daemon recover", signal);
301
+ return { kind: "stay" };
302
+ },
298
303
  recover: async ({ state, signal: actionSignal }) => {
299
304
  const result = await recoverSyncAccess(ctx, state.manager, runRoute, sessionSignal, actionSignal);
300
305
  return { kind: result === "close" ? "close" : "stay" };
@@ -377,13 +382,20 @@ export async function showSyncManager(
377
382
  },
378
383
  };
379
384
  let firstOpen = true;
385
+ const recovery: State["manager"] = {
386
+ title:
387
+ "Pi Sync recovery required\nDaemon cleanup could not be confirmed. Stop the daemon before retrying a transfer.",
388
+ actions: ["Stop daemon for recovery…", "Help"],
389
+ };
380
390
  const describe = async (signal: AbortSignal) => {
391
+ if (options.needsDaemonRecovery?.()) return recovery;
381
392
  const pendingAttention = options.getAttention?.();
382
393
  const observation = options.getObservation?.();
383
394
  const manager = await describeManagerState(signal, pendingAttention, undefined, observation, () =>
384
395
  ignoreFileSettingsAvailable(ctx, signal),
385
396
  );
386
397
  if (signal.aborted || !isCurrent()) return manager;
398
+ if (options.needsDaemonRecovery?.()) return recovery;
387
399
  // A busy operation suppresses baseline reads, not the stored check-time hint.
388
400
  if (
389
401
  observation &&
@@ -436,6 +448,7 @@ function syncMainMenuItem(
436
448
  | "conflicts"
437
449
  | "doctor"
438
450
  | "recover"
451
+ | "daemon-recovery"
439
452
  | "refresh"
440
453
  | "help"
441
454
  | "init"
@@ -453,6 +466,7 @@ function syncMainMenuItem(
453
466
  Diagnostics: "doctor",
454
467
  "Review unresolved conflicts": "conflicts",
455
468
  "Restore sync access… (recommended)": "recover",
469
+ "Stop daemon for recovery…": "daemon-recovery",
456
470
  "Refresh operation status": "refresh",
457
471
  "Sync setups…": "setups",
458
472
  "Storage connections…": "connections",
@@ -479,6 +493,7 @@ function syncMainMenuItem(
479
493
  switch: "Choose another sync setup.",
480
494
  conflicts: "Review unresolved file groups.",
481
495
  recover: "Review local lock recovery.",
496
+ "daemon-recovery": "Review and stop the current daemon without starting another.",
482
497
  refresh: "Recheck the operation lock.",
483
498
  setups: "Manage sync setups.",
484
499
  connections: "Manage storage connections.",
@@ -1,33 +1,45 @@
1
1
  import type { ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { truncateToWidth } from "@earendil-works/pi-tui";
3
3
  import { defineMenu, runCustomInteraction, runDocumentReview, runMenu } from "@narumitw/pi-tui-kit";
4
+ import { runCancellableTask } from "./cancellable-operation.js";
4
5
  import { createSyncConfirmation, type SyncConfirmationChoice } from "./sync-confirmation.js";
5
6
  import { safeTerminalText } from "./terminal-text.js";
6
7
 
7
8
  type ReviewContext = ExtensionCommandContext | ExtensionContext;
9
+ type ReviewDetails = string | ((signal?: AbortSignal) => Promise<string>);
8
10
 
9
- /** One approval screen; full details are optional and never authorize a transfer. */
10
11
  export async function confirmMergeReview(
11
12
  ctx: ReviewContext,
12
13
  title: string,
13
- content: string,
14
+ details: ReviewDetails,
14
15
  signal: AbortSignal | undefined,
15
16
  isCurrent: () => boolean,
16
17
  confirmationLabel = "apply changes",
17
18
  summaryLines?: readonly string[],
18
19
  ) {
19
- const lines = summaryLines ?? [
20
- ...content
21
- .split("\n")
22
- .slice(0, 6)
23
- .map((line) => truncateToWidth(safeTerminalText(line), 100)),
24
- "View details for the complete review.",
25
- ];
26
- const tuiLines =
27
- ctx.mode === "tui" && confirmationLabel === "apply reviewed transfer" && summaryLines?.join("\n") === content
28
- ? compactLegacyTransferSummary(lines)
29
- : lines;
20
+ let content = typeof details === "string" ? details : undefined;
21
+ const summary =
22
+ summaryLines ??
23
+ (typeof details === "string"
24
+ ? [
25
+ ...details
26
+ .split("\n")
27
+ .slice(0, 6)
28
+ .map((line) => truncateToWidth(safeTerminalText(line), 100)),
29
+ "View details for the complete review.",
30
+ ]
31
+ : []);
32
+ const tuiSummary =
33
+ ctx.mode === "tui" &&
34
+ typeof details === "string" &&
35
+ confirmationLabel === "apply reviewed transfer" &&
36
+ summaryLines?.join("\n") === details
37
+ ? compactLegacyTransferSummary(summary)
38
+ : summary;
30
39
  while (isCurrent() && !signal?.aborted) {
40
+ const allowApproval = content !== undefined;
41
+ const lines = allowApproval ? summary : [...summary, "Open View details before approving."];
42
+ const tuiLines = allowApproval ? tuiSummary : lines;
31
43
  const choice: { value: "cancel" | "approve" | "details" } = { value: "cancel" };
32
44
  const menu = defineMenu<undefined, "confirm", "choose", ReviewContext>({
33
45
  start: "confirm",
@@ -39,7 +51,7 @@ export async function confirmMergeReview(
39
51
  initialItemId: "cancel",
40
52
  items: [
41
53
  { id: "cancel", label: "No, cancel" },
42
- { id: "approve", label: `Yes, ${confirmationLabel}` },
54
+ ...(allowApproval ? [{ id: "approve", label: `Yes, ${confirmationLabel}` }] : []),
43
55
  { id: "details", label: "View details" },
44
56
  ],
45
57
  action: "choose",
@@ -57,7 +69,16 @@ export async function confirmMergeReview(
57
69
  ctx.mode === "tui" && ctx.hasUI
58
70
  ? await runCustomInteraction<SyncConfirmationChoice, ReviewContext>(ctx, {
59
71
  create: ({ tui, theme, keybindings, complete }) =>
60
- createSyncConfirmation({ title, lines: tuiLines, confirmationLabel, tui, theme, keybindings, complete }),
72
+ createSyncConfirmation({
73
+ title,
74
+ lines: tuiLines,
75
+ confirmationLabel,
76
+ allowApproval,
77
+ tui,
78
+ theme,
79
+ keybindings,
80
+ complete,
81
+ }),
61
82
  signal,
62
83
  isCurrent,
63
84
  onError: () => {},
@@ -70,8 +91,23 @@ export async function confirmMergeReview(
70
91
  if (result.kind === "completed") choice.value = result.value;
71
92
  else if (result.kind !== "closed") return false;
72
93
  // Keep authorization separate from UI termination in both adapters.
73
- if (choice.value === "approve") return true;
94
+ if (choice.value === "approve") return allowApproval;
74
95
  if (choice.value !== "details") return false;
96
+ if (content === undefined && typeof details === "function") {
97
+ try {
98
+ const loaded = await runCancellableTask(ctx, "Loading exact sync details…", details, {
99
+ signal,
100
+ isCurrent,
101
+ cancelledMessage: null,
102
+ });
103
+ if (!isCurrent() || signal?.aborted || loaded.kind !== "completed") return false;
104
+ content = loaded.value;
105
+ } catch {
106
+ if (!isCurrent() || signal?.aborted) return false;
107
+ throw new Error("Sync review failed; no transfer was performed.");
108
+ }
109
+ }
110
+ if (content === undefined) return false;
75
111
  const detail = await runDocumentReview(ctx, {
76
112
  title: "Sync change details",
77
113
  content,
@@ -371,9 +371,9 @@ export async function showSyncSettings(
371
371
  },
372
372
  {
373
373
  id: "debug",
374
- label: "Debug startup timings",
374
+ label: "Debug mode",
375
375
  description:
376
- "All setups on this device: show startup durations in the TUI transcript or RPC notifications, including initial Continuous sync. Applies next session start; no credentials or file contents.",
376
+ "Write startup timings and sync events to the local pi-sync.log. Pi applies this at the next session start; the daemon applies it at its next settings check.",
377
377
  currentValue: state.debug ? "On" : "Off",
378
378
  values: ["On", "Off"],
379
379
  action: "debug",
@@ -14,28 +14,25 @@ export function createSyncConfirmation(options: {
14
14
  title: string;
15
15
  lines: readonly string[];
16
16
  confirmationLabel: string;
17
+ allowApproval?: boolean;
17
18
  tui: TUI;
18
19
  theme: Theme;
19
20
  keybindings: KeybindingsManager;
20
21
  complete(choice: SyncConfirmationChoice): void;
21
22
  }) {
22
- const { tui, theme, keybindings } = options;
23
- const choices: SyncConfirmationChoice[] = ["cancel", "approve", "details"];
24
- const list = new SelectList(
25
- [
26
- { value: "cancel", label: "No, cancel" },
27
- { value: "approve", label: `Yes, ${sanitizeTerminalText(options.confirmationLabel)}` },
28
- { value: "details", label: "View details" },
29
- ],
30
- 3,
31
- {
32
- selectedPrefix: (text) => theme.fg("accent", text),
33
- selectedText: (text) => theme.fg("accent", text),
34
- description: (text) => theme.fg("muted", text),
35
- scrollInfo: (text) => theme.fg("dim", text),
36
- noMatch: (text) => theme.fg("muted", text),
37
- },
38
- );
23
+ const { tui, theme, keybindings, allowApproval = true } = options;
24
+ const actions: { value: SyncConfirmationChoice; label: string }[] = [{ value: "cancel", label: "No, cancel" }];
25
+ if (allowApproval)
26
+ actions.push({ value: "approve", label: `Yes, ${sanitizeTerminalText(options.confirmationLabel)}` });
27
+ actions.push({ value: "details", label: "View details" });
28
+ const choices = actions.map((item) => item.value);
29
+ const list = new SelectList(actions, actions.length, {
30
+ selectedPrefix: (text) => theme.fg("accent", text),
31
+ selectedText: (text) => theme.fg("accent", text),
32
+ description: (text) => theme.fg("muted", text),
33
+ scrollInfo: (text) => theme.fg("dim", text),
34
+ noMatch: (text) => theme.fg("muted", text),
35
+ });
39
36
  const rule = new HorizontalRule({ ruleStyle: (text) => theme.fg("border", text) });
40
37
  let selected = 0;
41
38
  let offset = 0;
@@ -108,7 +105,7 @@ export function createSyncConfirmation(options: {
108
105
  // aliased, or shadowed by an earlier cancellation/navigation binding.
109
106
  const status = theme.fg(
110
107
  "muted",
111
- `Summary ${visible.length ? offset + 1 : 0}-${offset + visible.length}/${summary.length}${reviewed ? "" : " — page before Yes"}`,
108
+ `Summary ${visible.length ? offset + 1 : 0}-${offset + visible.length}/${summary.length}${reviewed || !allowApproval ? "" : " — page before Yes"}`,
112
109
  );
113
110
  const layout = renderBoundedFrameLayout({
114
111
  width: cells,
@@ -117,7 +114,7 @@ export function createSyncConfirmation(options: {
117
114
  title: [theme.fg("accent", theme.bold(sanitizeTerminalText(options.title)))],
118
115
  context: [...visible.map((line) => theme.fg("text", line)), status],
119
116
  content: actions,
120
- priorityRows: [selected, 0, 1, 2],
117
+ priorityRows: [selected, ...choices.map((_, index) => index)],
121
118
  focusedRow: selected,
122
119
  });
123
120
  actionRows = layout.contentRows;