@narumitw/pi-sync 0.63.0 → 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 (135) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +28 -18
  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-S6FUUWV5.ts → chunk-NDEZ52SS.ts} +13 -13
  10. package/dist/chunks/{chunk-S6FUUWV5.ts.map → chunk-NDEZ52SS.ts.map} +1 -1
  11. package/dist/chunks/{chunk-UGS6RYDZ.ts → chunk-RW44KNFD.ts} +304 -70
  12. package/dist/chunks/chunk-RW44KNFD.ts.map +7 -0
  13. package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-TJ7YNITN.ts} +5 -5
  14. package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
  15. package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-VPSC7BXM.ts} +3 -3
  16. package/dist/chunks/chunk-YT6PDRMM.ts +282 -0
  17. package/dist/chunks/chunk-YT6PDRMM.ts.map +7 -0
  18. package/dist/chunks/{command-handler-VINMQ7ZM.ts → command-handler-N45GY7AV.ts} +39 -27
  19. package/dist/chunks/command-handler-N45GY7AV.ts.map +7 -0
  20. package/dist/chunks/{conflict-review-PCDFRIVB.ts → conflict-review-5E4M44BA.ts} +2 -2
  21. package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
  22. package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-FKW55L7I.ts} +5 -5
  23. package/dist/chunks/{manager-ui-YHDECYKI.ts → manager-ui-EV23DPZQ.ts} +104 -77
  24. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +7 -0
  25. package/dist/chunks/{merge-review-SGDLMVS4.ts → merge-review-6YSLSMGS.ts} +3 -2
  26. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
  27. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
  28. package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-N4NMWFT2.ts} +4 -4
  29. package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-HY7K3442.ts} +4 -4
  30. package/dist/chunks/{setup-wizard-YO4MCPUF.ts → setup-wizard-LEKDQ3HK.ts} +9 -9
  31. package/dist/chunks/{sync-inspection-H2WX5SUT.ts → sync-inspection-OS2LVOLV.ts} +5 -5
  32. package/dist/chunks/{sync-operations-2MZAYHL2.ts → sync-operations-D3MDJUQQ.ts} +2 -2
  33. package/dist/daemon/dist/cli.js +2 -0
  34. package/dist/daemon/dist/client-transport.js +66 -0
  35. package/dist/daemon/dist/client.js +116 -86
  36. package/dist/daemon/dist/consent.js +33 -11
  37. package/dist/daemon/dist/daemon-debug.js +33 -0
  38. package/dist/daemon/dist/daemon-recovery.js +75 -0
  39. package/dist/daemon/dist/engine/backends/git/git-backend.js +39 -12
  40. package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
  41. package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
  42. package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
  43. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +10 -12
  44. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +15 -26
  45. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
  46. package/dist/daemon/dist/engine/debug-log.js +134 -0
  47. package/dist/daemon/dist/engine/ignore/ignore-initialization.js +50 -14
  48. package/dist/daemon/dist/engine/ignore/ignore-settings.js +11 -14
  49. package/dist/daemon/dist/engine/ignore/ignore-source.js +1 -1
  50. package/dist/daemon/dist/engine/paths.js +7 -1
  51. package/dist/daemon/dist/engine/settings/config-file.js +62 -17
  52. package/dist/daemon/dist/engine/settings/config.js +49 -14
  53. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
  54. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
  55. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
  56. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
  57. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
  58. package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
  59. package/dist/daemon/dist/engine/state/lock.js +157 -17
  60. package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
  61. package/dist/daemon/dist/engine/sync/initialization.js +2 -2
  62. package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
  63. package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
  64. package/dist/daemon/dist/engine/sync/remote-snapshot.js +18 -3
  65. package/dist/daemon/dist/engine/sync/session-push.js +13 -4
  66. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
  67. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
  68. package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
  69. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +22 -4
  70. package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
  71. package/dist/daemon/dist/engine/sync/sync-local.js +3 -1
  72. package/dist/daemon/dist/engine/sync/sync-mutations.js +13 -7
  73. package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
  74. package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
  75. package/dist/daemon/dist/engine/ui/sync-format.js +23 -55
  76. package/dist/daemon/dist/engine/ui/transfer-review.js +3 -3
  77. package/dist/daemon/dist/engine-service.js +54 -10
  78. package/dist/daemon/dist/identity.js +36 -6
  79. package/dist/daemon/dist/index.js +2 -1
  80. package/dist/daemon/dist/monitor.js +20 -1
  81. package/dist/daemon/dist/paged-review.js +177 -0
  82. package/dist/daemon/dist/participant-ledger.js +149 -0
  83. package/dist/daemon/dist/protocol.js +4 -0
  84. package/dist/daemon/dist/server.js +268 -120
  85. package/dist/daemon/dist/service-host.js +29 -9
  86. package/dist/daemon/dist/state-wait-jobs.js +23 -0
  87. package/dist/daemon/dist/state-wait.js +34 -0
  88. package/dist/daemon/package.json +1 -1
  89. package/dist/index.ts +128 -48
  90. package/dist/index.ts.map +2 -2
  91. package/docs/continuous-sync-verification.md +2 -0
  92. package/docs/daemon-migration.md +30 -2
  93. package/docs/tui-contract.md +8 -2
  94. package/package.json +2 -2
  95. package/skills/configure-pi-sync/SKILL.md +119 -18
  96. package/skills/configure-pi-sync/references/configuration.md +88 -48
  97. package/src/commands/command-execution.ts +11 -3
  98. package/src/commands/command-handler.ts +10 -3
  99. package/src/commands/command.ts +3 -2
  100. package/src/daemon/client-debug.ts +45 -0
  101. package/src/daemon/ownership-recovery.ts +50 -0
  102. package/src/daemon/pi-client.ts +288 -63
  103. package/src/daemon/startup-bootstrap-client.ts +26 -0
  104. package/src/settings/config.ts +1 -0
  105. package/src/sync/automatic-sync.ts +61 -18
  106. package/src/sync/startup-check.ts +13 -5
  107. package/src/sync-extension.ts +46 -8
  108. package/src/ui/manager-state.ts +35 -24
  109. package/src/ui/manager-ui.ts +39 -18
  110. package/src/ui/merge-review.ts +75 -12
  111. package/src/ui/settings-ui.ts +2 -2
  112. package/src/ui/setup/webdav-ui.ts +1 -1
  113. package/src/ui/sync-confirmation.ts +81 -65
  114. package/src/ui/sync-setups-ui.ts +15 -12
  115. package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
  116. package/dist/chunks/chunk-GSQGBVKG.ts +0 -218
  117. package/dist/chunks/chunk-GSQGBVKG.ts.map +0 -7
  118. package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
  119. package/dist/chunks/chunk-UGS6RYDZ.ts.map +0 -7
  120. package/dist/chunks/command-handler-VINMQ7ZM.ts.map +0 -7
  121. package/dist/chunks/manager-ui-YHDECYKI.ts.map +0 -7
  122. /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-F3VODLVQ.ts.map} +0 -0
  123. /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
  124. /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-TJ7YNITN.ts.map} +0 -0
  125. /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
  126. /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-VPSC7BXM.ts.map} +0 -0
  127. /package/dist/chunks/{conflict-review-PCDFRIVB.ts.map → conflict-review-5E4M44BA.ts.map} +0 -0
  128. /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
  129. /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-FKW55L7I.ts.map} +0 -0
  130. /package/dist/chunks/{merge-review-SGDLMVS4.ts.map → merge-review-6YSLSMGS.ts.map} +0 -0
  131. /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-N4NMWFT2.ts.map} +0 -0
  132. /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-HY7K3442.ts.map} +0 -0
  133. /package/dist/chunks/{setup-wizard-YO4MCPUF.ts.map → setup-wizard-LEKDQ3HK.ts.map} +0 -0
  134. /package/dist/chunks/{sync-inspection-H2WX5SUT.ts.map → sync-inspection-OS2LVOLV.ts.map} +0 -0
  135. /package/dist/chunks/{sync-operations-2MZAYHL2.ts.map → sync-operations-D3MDJUQQ.ts.map} +0 -0
@@ -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"),
@@ -313,11 +321,14 @@ export function backendStorageDescription(config: AnySyncConfig) {
313
321
  config.backend.profile.kind === "r2" || isCloudflareR2Endpoint(config.backend.profile.endpoint)
314
322
  ? "Cloudflare R2"
315
323
  : "S3-compatible";
316
- return `${type} · ${connection} · ${safeTerminalText(config.backend.destination.bucket)}`;
324
+ const { bucket, prefix } = config.backend.destination;
325
+ return `${type} · ${connection} · ${safeTerminalText(bucket)} · ${safeTerminalText(prefix)}`;
317
326
  }
318
327
  case "webdav":
319
328
  return `WebDAV · ${connection} · ${safeTerminalText(config.backend.destination.path)}`;
320
- case "git":
321
- return `Git · ${connection} · ${safeTerminalText(config.backend.destination.branch)}`;
329
+ case "git": {
330
+ const { branch, directory } = config.backend.destination;
331
+ return `Git · ${connection} · ${safeTerminalText(branch)} · ${safeTerminalText(directory)}`;
332
+ }
322
333
  }
323
334
  }
@@ -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";
@@ -80,23 +81,29 @@ export async function showSyncManager(
80
81
  >({
81
82
  start: "main",
82
83
  screens: {
83
- main: ({ state }) => ({
84
- kind: "choice",
85
- title: "Manage sync",
86
- lines: state.manager.title.split("\n").slice(1),
87
- items: menuItems(state.manager).map((item) => ({
88
- id: item.id,
89
- label: ctx.mode === "tui" && item.id === "sync" ? "Sync…" : item.label,
90
- details: [item.description ?? "Review synced content."],
91
- searchText: `${item.label} ${item.description ?? ""}`,
92
- disabled: item.disabled,
93
- disabledReason: item.disabledReason,
94
- })),
95
- action: "activate",
96
- enableSearch: true,
97
- viewportSize: 5,
98
- hint: "close",
99
- }),
84
+ main: ({ state: { manager } }) => {
85
+ const [title = "Manage sync", ...lines] = manager.title.split("\n");
86
+ const setupName = ctx.mode === "tui" ? manager.configReview?.setupName : undefined;
87
+ const setup = setupName === undefined ? undefined : safeTerminalText(setupName);
88
+ const setupInHeading = setup !== undefined && lines[0] === `Current sync setup: ${setup}`;
89
+ return {
90
+ kind: "choice",
91
+ title: setupInHeading ? `${title} · ${setup}` : title,
92
+ lines: setupInHeading ? lines.slice(1) : lines,
93
+ items: menuItems(manager).map((item) => ({
94
+ id: item.id,
95
+ label: ctx.mode === "tui" && item.id === "sync" ? "Sync…" : item.label,
96
+ details: [item.description ?? "Review synced content."],
97
+ searchText: `${item.label} ${item.description ?? ""}`,
98
+ disabled: item.disabled,
99
+ disabledReason: item.disabledReason,
100
+ })),
101
+ action: "activate",
102
+ enableSearch: true,
103
+ viewportSize: 5,
104
+ hint: "close",
105
+ };
106
+ },
100
107
  },
101
108
  actions: {
102
109
  activate: async (invocation) => {
@@ -289,6 +296,10 @@ export async function showSyncManager(
289
296
  });
290
297
  return { kind: result.kind === "closed" ? "close" : "stay" };
291
298
  },
299
+ "daemon-recovery": async ({ signal }) => {
300
+ await runRoute("daemon recover", signal);
301
+ return { kind: "stay" };
302
+ },
292
303
  recover: async ({ state, signal: actionSignal }) => {
293
304
  const result = await recoverSyncAccess(ctx, state.manager, runRoute, sessionSignal, actionSignal);
294
305
  return { kind: result === "close" ? "close" : "stay" };
@@ -371,13 +382,20 @@ export async function showSyncManager(
371
382
  },
372
383
  };
373
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
+ };
374
390
  const describe = async (signal: AbortSignal) => {
391
+ if (options.needsDaemonRecovery?.()) return recovery;
375
392
  const pendingAttention = options.getAttention?.();
376
393
  const observation = options.getObservation?.();
377
394
  const manager = await describeManagerState(signal, pendingAttention, undefined, observation, () =>
378
395
  ignoreFileSettingsAvailable(ctx, signal),
379
396
  );
380
397
  if (signal.aborted || !isCurrent()) return manager;
398
+ if (options.needsDaemonRecovery?.()) return recovery;
381
399
  // A busy operation suppresses baseline reads, not the stored check-time hint.
382
400
  if (
383
401
  observation &&
@@ -430,6 +448,7 @@ function syncMainMenuItem(
430
448
  | "conflicts"
431
449
  | "doctor"
432
450
  | "recover"
451
+ | "daemon-recovery"
433
452
  | "refresh"
434
453
  | "help"
435
454
  | "init"
@@ -447,6 +466,7 @@ function syncMainMenuItem(
447
466
  Diagnostics: "doctor",
448
467
  "Review unresolved conflicts": "conflicts",
449
468
  "Restore sync access… (recommended)": "recover",
469
+ "Stop daemon for recovery…": "daemon-recovery",
450
470
  "Refresh operation status": "refresh",
451
471
  "Sync setups…": "setups",
452
472
  "Storage connections…": "connections",
@@ -473,6 +493,7 @@ function syncMainMenuItem(
473
493
  switch: "Choose another sync setup.",
474
494
  conflicts: "Review unresolved file groups.",
475
495
  recover: "Review local lock recovery.",
496
+ "daemon-recovery": "Review and stop the current daemon without starting another.",
476
497
  refresh: "Recheck the operation lock.",
477
498
  setups: "Manage sync setups.",
478
499
  connections: "Manage storage connections.",
@@ -1,29 +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
- ];
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;
26
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;
27
43
  const choice: { value: "cancel" | "approve" | "details" } = { value: "cancel" };
28
44
  const menu = defineMenu<undefined, "confirm", "choose", ReviewContext>({
29
45
  start: "confirm",
@@ -35,7 +51,7 @@ export async function confirmMergeReview(
35
51
  initialItemId: "cancel",
36
52
  items: [
37
53
  { id: "cancel", label: "No, cancel" },
38
- { id: "approve", label: `Yes, ${confirmationLabel}` },
54
+ ...(allowApproval ? [{ id: "approve", label: `Yes, ${confirmationLabel}` }] : []),
39
55
  { id: "details", label: "View details" },
40
56
  ],
41
57
  action: "choose",
@@ -53,7 +69,16 @@ export async function confirmMergeReview(
53
69
  ctx.mode === "tui" && ctx.hasUI
54
70
  ? await runCustomInteraction<SyncConfirmationChoice, ReviewContext>(ctx, {
55
71
  create: ({ tui, theme, keybindings, complete }) =>
56
- createSyncConfirmation({ title, lines, 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
+ }),
57
82
  signal,
58
83
  isCurrent,
59
84
  onError: () => {},
@@ -66,8 +91,23 @@ export async function confirmMergeReview(
66
91
  if (result.kind === "completed") choice.value = result.value;
67
92
  else if (result.kind !== "closed") return false;
68
93
  // Keep authorization separate from UI termination in both adapters.
69
- if (choice.value === "approve") return true;
94
+ if (choice.value === "approve") return allowApproval;
70
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;
71
111
  const detail = await runDocumentReview(ctx, {
72
112
  title: "Sync change details",
73
113
  content,
@@ -86,3 +126,26 @@ export async function confirmMergeReview(
86
126
  }
87
127
  return false;
88
128
  }
129
+
130
+ function compactLegacyTransferSummary(lines: readonly string[]): string[] {
131
+ const result: string[] = [];
132
+ for (let index = 0; index < lines.length; index++) {
133
+ const line = lines[index] ?? "";
134
+ result.push(line);
135
+ const counts = /^Changes: (\d+) add · (\d+) update · (\d+) remove$/u.exec(line);
136
+ if (!counts) continue;
137
+ const expected = counts.slice(1).map(Number);
138
+ const actual = [0, 0, 0];
139
+ let side: string | undefined;
140
+ let end = index + 1;
141
+ for (; end < lines.length; end++) {
142
+ const row = /^(Add|Update|Remove) (locally|remotely): .+$/u.exec(lines[end] ?? "");
143
+ if (!row || (side && row[2] !== side)) break;
144
+ side = row[2];
145
+ const action = row[1] === "Add" ? 0 : row[1] === "Update" ? 1 : 2;
146
+ actual[action] = (actual[action] ?? 0) + 1;
147
+ }
148
+ if (actual.every((count, action) => count === expected[action])) index = end - 1;
149
+ }
150
+ return result;
151
+ }
@@ -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",
@@ -43,7 +43,7 @@ export async function showWebDavSetup(ctx: ExtensionCommandContext, targetName:
43
43
  "Username and password: stored privately (values hidden)",
44
44
  ...policy.lines,
45
45
  `Automatic sync: ${automaticSyncSummary(policy.sync.automatic)}`,
46
- "Check setup tests whether this server can safely save sync updates using a temporary probe.",
46
+ "After saving, Diagnostics in /sync checks WebDAV write support with a temporary probe.",
47
47
  "Saving does not contact remote storage or start syncing.",
48
48
  ],
49
49
  "Save setup",