@narumitw/pi-sync 0.69.0 → 0.70.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 (91) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +2 -2
  3. package/dist/chunks/{chunk-EG6BUOUQ.ts → chunk-3XN4FR72.ts} +2 -2
  4. package/dist/chunks/{chunk-YX6DCQ7P.ts → chunk-5T4ZOHYF.ts} +2 -2
  5. package/dist/chunks/{chunk-RXZVLBPU.ts → chunk-7NQ7SFZK.ts} +3 -3
  6. package/dist/chunks/{chunk-2JNFEZ3V.ts → chunk-AMJRUXFT.ts} +6 -2
  7. package/dist/chunks/{chunk-2JNFEZ3V.ts.map → chunk-AMJRUXFT.ts.map} +1 -1
  8. package/dist/chunks/{chunk-XNUARYLR.ts → chunk-HFMGK6A6.ts} +2 -2
  9. package/dist/chunks/{chunk-OWSKD5XG.ts → chunk-JPTI4HFC.ts} +4 -4
  10. package/dist/chunks/{chunk-RZB2DPVU.ts → chunk-N24HEZSA.ts} +3 -3
  11. package/dist/chunks/{chunk-EI2J5Z4Q.ts → chunk-SPXEDJ2G.ts} +4 -4
  12. package/dist/chunks/{chunk-GXB74FYB.ts → chunk-V4IGBXBA.ts} +4 -4
  13. package/dist/chunks/{chunk-4KGDPLQ4.ts → chunk-ZWP6HAYV.ts} +16 -6
  14. package/dist/chunks/chunk-ZWP6HAYV.ts.map +7 -0
  15. package/dist/chunks/{command-handler-ZR26OSBX.ts → command-handler-4XHK5PVX.ts} +20 -15
  16. package/dist/chunks/command-handler-4XHK5PVX.ts.map +7 -0
  17. package/dist/chunks/{conflict-review-W5BCZIZG.ts → conflict-review-QI77P7KL.ts} +3 -3
  18. package/dist/chunks/diff-review-ILRZDQ4S.ts +143 -0
  19. package/dist/chunks/diff-review-ILRZDQ4S.ts.map +7 -0
  20. package/dist/chunks/diff-review-SOLP33TQ.ts +68 -0
  21. package/dist/chunks/diff-review-SOLP33TQ.ts.map +7 -0
  22. package/dist/chunks/{file-selection-STCIRKF6.ts → file-selection-2H3J2HTX.ts} +4 -4
  23. package/dist/chunks/{manager-result-dispatcher-MPLPDR2P.ts → manager-result-dispatcher-YXSDLTLV.ts} +5 -5
  24. package/dist/chunks/{manager-ui-OMZOBGYT.ts → manager-ui-RQSZLMJ5.ts} +19 -19
  25. package/dist/chunks/manager-ui-RQSZLMJ5.ts.map +7 -0
  26. package/dist/chunks/{merge-review-KTIQBRLL.ts → merge-review-DXSERTCK.ts} +3 -3
  27. package/dist/chunks/{ownership-recovery-UDDHSDSZ.ts → ownership-recovery-5KXAMFSL.ts} +2 -2
  28. package/dist/chunks/{remote-selection-ui-CCHMCAHQ.ts → remote-selection-ui-AE6FOEXH.ts} +4 -4
  29. package/dist/chunks/{setup-switch-J3YLBB6N.ts → setup-switch-LJPEZONY.ts} +3 -3
  30. package/dist/chunks/{setup-wizard-J3YOR7BR.ts → setup-wizard-FBX7RTZ6.ts} +4 -4
  31. package/dist/chunks/{sync-inspection-7OADBR57.ts → sync-inspection-TZ4EMSBN.ts} +3 -3
  32. package/dist/chunks/{sync-operations-3K6WLPXY.ts → sync-operations-QIQ3G66S.ts} +16 -5
  33. package/dist/chunks/{sync-operations-3K6WLPXY.ts.map → sync-operations-QIQ3G66S.ts.map} +2 -2
  34. package/dist/daemon/dist/build-id.json +1 -1
  35. package/dist/daemon/dist/client.js +131 -5
  36. package/dist/daemon/dist/daemon-debug.js +13 -6
  37. package/dist/daemon/dist/diff-review-binding.js +11 -0
  38. package/dist/daemon/dist/diff-review-protocol.js +85 -0
  39. package/dist/daemon/dist/diff-review-rpc.js +37 -0
  40. package/dist/daemon/dist/diff-review-store.js +89 -0
  41. package/dist/daemon/dist/engine/backends/git/git-backend.js +10 -6
  42. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +3 -3
  43. package/dist/daemon/dist/engine/backends/s3/s3-client.js +16 -6
  44. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +3 -3
  45. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +23 -10
  46. package/dist/daemon/dist/engine/snapshot/session-paths.js +12 -3
  47. package/dist/daemon/dist/engine/snapshot/snapshot-capture-limit.js +99 -0
  48. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +4 -1
  49. package/dist/daemon/dist/engine/snapshot/snapshot-difference.js +13 -0
  50. package/dist/daemon/dist/engine/snapshot/snapshot.js +44 -17
  51. package/dist/daemon/dist/engine/sync/diff-review-capture.js +210 -0
  52. package/dist/daemon/dist/engine/sync/diff-review-preview.js +114 -0
  53. package/dist/daemon/dist/engine/sync/remote-snapshot.js +6 -6
  54. package/dist/daemon/dist/engine/sync/sync-queries.js +32 -19
  55. package/dist/daemon/dist/engine/ui/sync-format.js +14 -24
  56. package/dist/daemon/dist/engine-service.js +5 -0
  57. package/dist/daemon/dist/index.js +1 -0
  58. package/dist/daemon/dist/server.js +112 -36
  59. package/dist/daemon/package.json +1 -1
  60. package/dist/index.ts +7 -7
  61. package/docs/tui-contract.md +1 -1
  62. package/package.json +3 -3
  63. package/skills/configure-pi-sync/references/configuration.md +1 -1
  64. package/src/commands/command-execution.ts +9 -4
  65. package/src/commands/command-handler.ts +3 -3
  66. package/src/commands/command-types.ts +1 -0
  67. package/src/daemon/diff-review.ts +68 -0
  68. package/src/sync/sync-operations.ts +12 -2
  69. package/src/ui/cancellable-operation.ts +32 -11
  70. package/src/ui/diff-review.ts +144 -0
  71. package/src/ui/manager-ui.ts +7 -6
  72. package/dist/chunks/chunk-4KGDPLQ4.ts.map +0 -7
  73. package/dist/chunks/command-handler-ZR26OSBX.ts.map +0 -7
  74. package/dist/chunks/manager-ui-OMZOBGYT.ts.map +0 -7
  75. /package/dist/chunks/{chunk-EG6BUOUQ.ts.map → chunk-3XN4FR72.ts.map} +0 -0
  76. /package/dist/chunks/{chunk-YX6DCQ7P.ts.map → chunk-5T4ZOHYF.ts.map} +0 -0
  77. /package/dist/chunks/{chunk-RXZVLBPU.ts.map → chunk-7NQ7SFZK.ts.map} +0 -0
  78. /package/dist/chunks/{chunk-XNUARYLR.ts.map → chunk-HFMGK6A6.ts.map} +0 -0
  79. /package/dist/chunks/{chunk-OWSKD5XG.ts.map → chunk-JPTI4HFC.ts.map} +0 -0
  80. /package/dist/chunks/{chunk-RZB2DPVU.ts.map → chunk-N24HEZSA.ts.map} +0 -0
  81. /package/dist/chunks/{chunk-EI2J5Z4Q.ts.map → chunk-SPXEDJ2G.ts.map} +0 -0
  82. /package/dist/chunks/{chunk-GXB74FYB.ts.map → chunk-V4IGBXBA.ts.map} +0 -0
  83. /package/dist/chunks/{conflict-review-W5BCZIZG.ts.map → conflict-review-QI77P7KL.ts.map} +0 -0
  84. /package/dist/chunks/{file-selection-STCIRKF6.ts.map → file-selection-2H3J2HTX.ts.map} +0 -0
  85. /package/dist/chunks/{manager-result-dispatcher-MPLPDR2P.ts.map → manager-result-dispatcher-YXSDLTLV.ts.map} +0 -0
  86. /package/dist/chunks/{merge-review-KTIQBRLL.ts.map → merge-review-DXSERTCK.ts.map} +0 -0
  87. /package/dist/chunks/{ownership-recovery-UDDHSDSZ.ts.map → ownership-recovery-5KXAMFSL.ts.map} +0 -0
  88. /package/dist/chunks/{remote-selection-ui-CCHMCAHQ.ts.map → remote-selection-ui-AE6FOEXH.ts.map} +0 -0
  89. /package/dist/chunks/{setup-switch-J3YLBB6N.ts.map → setup-switch-LJPEZONY.ts.map} +0 -0
  90. /package/dist/chunks/{setup-wizard-J3YOR7BR.ts.map → setup-wizard-FBX7RTZ6.ts.map} +0 -0
  91. /package/dist/chunks/{sync-inspection-7OADBR57.ts.map → sync-inspection-TZ4EMSBN.ts.map} +0 -0
@@ -6,6 +6,9 @@ import { createServer } from "node:http";
6
6
  import lockfile from "proper-lockfile";
7
7
  import { DAEMON_BUILD_ID, DAEMON_BUILD_VERSION } from "./build-version.js";
8
8
  import { ConsentPublicationError, readConsent } from "./consent.js";
9
+ import { sameDiffReviewBinding } from "./diff-review-binding.js";
10
+ import { handleDiffReviewRequest } from "./diff-review-rpc.js";
11
+ import { createDiffReviewStore } from "./diff-review-store.js";
9
12
  import { endpointOwner } from "./endpoint.js";
10
13
  import { debugJobResult, debugOperation } from "./engine/debug-log.js";
11
14
  import { SyncDecisionRequiredError } from "./engine/sync/sync-errors.js";
@@ -59,7 +62,7 @@ export async function startServer(root, execute, hooks = {}) {
59
62
  const debug = diagnostic
60
63
  ? (event, current) => {
61
64
  try {
62
- diagnostic(event, () => ownsLog() && (current?.() ?? true));
65
+ return diagnostic(event, () => ownsLog() && (current?.() ?? true))?.catch(() => { });
63
66
  }
64
67
  catch { }
65
68
  }
@@ -69,6 +72,15 @@ export async function startServer(root, execute, hooks = {}) {
69
72
  hooks.failure?.();
70
73
  };
71
74
  const participants = new Map();
75
+ const diffReviews = createDiffReviewStore();
76
+ const invalidateDiffReview = (peer) => {
77
+ const owner = peer.diffReviewOwner;
78
+ if (!owner)
79
+ return;
80
+ peer.diffReviewOwner = undefined;
81
+ diffReviews.release(owner);
82
+ owner.abort(new DOMException("File review owner changed", "AbortError"));
83
+ };
72
84
  const waiters = new WeakMap();
73
85
  const admission = new ParticipantAdmission();
74
86
  const jobs = new Map();
@@ -190,7 +202,10 @@ export async function startServer(root, execute, hooks = {}) {
190
202
  events: peer.events.filter((event) => event.id > (typeof cursor === "number" && Number.isSafeInteger(cursor) ? cursor : 0)),
191
203
  job: job?.view,
192
204
  });
193
- function makeExecution(job) {
205
+ function makeExecution(job, diffReviewOwner) {
206
+ const signal = diffReviewOwner
207
+ ? AbortSignal.any([job.controller.signal, diffReviewOwner.signal])
208
+ : job.controller.signal;
194
209
  const validate = () => {
195
210
  if (compromised)
196
211
  throw new Error("Daemon ownership is no longer valid.");
@@ -200,16 +215,16 @@ export async function startServer(root, execute, hooks = {}) {
200
215
  return;
201
216
  }
202
217
  assertOwner();
203
- job.controller.signal.throwIfAborted();
218
+ signal.throwIfAborted();
204
219
  if (job.participantGeneration !== undefined && job.participantGeneration !== participantGeneration)
205
220
  throw new Error("Daemon participants changed before automatic work completed.");
206
221
  if (job.client) {
207
222
  const peer = requireParticipant(job.client);
208
- if (peer.facts.generation !== job.generation)
223
+ if (peer.facts.generation !== job.generation || (diffReviewOwner && peer.diffReviewOwner !== diffReviewOwner))
209
224
  throw new Error("Client session generation changed.");
210
225
  }
211
226
  };
212
- const request = (kind, data, target = job.client, signal = job.controller.signal) => {
227
+ const request = (kind, data, target = job.client, requestSignal = signal) => {
213
228
  const cleanup = kind === "queue-release";
214
229
  if (!cleanup)
215
230
  validate();
@@ -259,7 +274,7 @@ export async function startServer(root, execute, hooks = {}) {
259
274
  }
260
275
  return new Promise((resolve, reject) => {
261
276
  let timer;
262
- const effectiveSignal = cleanup ? undefined : signal;
277
+ const effectiveSignal = cleanup ? undefined : requestSignal;
263
278
  const abort = () => finish(undefined, effectiveSignal?.reason);
264
279
  const finish = (value, error) => {
265
280
  if (timer)
@@ -310,15 +325,27 @@ export async function startServer(root, execute, hooks = {}) {
310
325
  return {
311
326
  root: paths.root,
312
327
  clientId: job.client,
313
- signal: job.controller.signal,
328
+ signal,
314
329
  facts: () => (job.client ? participants.get(job.client)?.facts : undefined),
315
330
  participants: participantFacts,
316
331
  liveClients: liveClientFacts,
317
332
  withParticipants: (action) => admission.run(async () => {
318
333
  validate();
319
334
  return action(participantFacts());
320
- }, job.committed ? undefined : job.controller.signal),
335
+ }, job.committed ? undefined : signal),
321
336
  validate,
337
+ ...(diffReviewOwner && {
338
+ diffReview: {
339
+ clear() {
340
+ validate();
341
+ diffReviews.release(diffReviewOwner);
342
+ },
343
+ retain(prepared) {
344
+ validate();
345
+ return diffReviews.retain(diffReviewOwner, prepared, signal);
346
+ },
347
+ },
348
+ }),
322
349
  request,
323
350
  emit: (kind, data, target = job.client) => emit(kind, data, target),
324
351
  debug: debug &&
@@ -382,11 +409,17 @@ export async function startServer(root, execute, hooks = {}) {
382
409
  };
383
410
  if (cancelled.has(`${client}:${id}`))
384
411
  job.controller.abort(new DOMException("Operation cancelled before dispatch", "AbortError"));
385
- const execution = makeExecution(job);
412
+ let diffReviewOwner;
413
+ if (operation === "diff.review" && peer.facts.mode === "tui" && peer.facts.hasUI) {
414
+ peer.diffReviewOwner ??= new AbortController();
415
+ diffReviewOwner = peer.diffReviewOwner;
416
+ }
417
+ const execution = makeExecution(job, diffReviewOwner);
386
418
  const kind = debug && debugOperation(operation);
387
- const note = (outcome) => {
419
+ const waitForInspectionLog = kind === "inspect";
420
+ const note = (outcome, current) => {
388
421
  if (kind)
389
- debug?.({ event: "job", operation: kind, outcome, operationId: id });
422
+ return debug?.({ event: "job", operation: kind, outcome, operationId: id }, current);
390
423
  };
391
424
  job.promise = queue
392
425
  .then(async () => {
@@ -404,21 +437,29 @@ export async function startServer(root, execute, hooks = {}) {
404
437
  });
405
438
  foregroundRecoveryJob ??= job;
406
439
  }
440
+ const logged = note(debugJobResult(operation, result) ?? job.debugOutcome ?? "completed", waitForInspectionLog ? () => !execution.signal.aborted : undefined);
441
+ if (waitForInspectionLog && logged) {
442
+ await logged;
443
+ execution.validate();
444
+ }
407
445
  job.view.result = result;
408
446
  job.view.phase = "done";
409
- note(debugJobResult(operation, result) ?? job.debugOutcome ?? "completed");
410
447
  })
411
- .catch((error) => {
448
+ .catch(async (error) => {
412
449
  if (error instanceof ConsentPublicationError)
413
450
  consentPublicationFailed = true;
414
- job.view.phase = "failed";
415
- job.view.error = remoteError(error);
416
- note(!job.committed && (job.controller.signal.aborted || (error instanceof Error && error.name === "AbortError"))
451
+ const logged = note(!job.committed && (job.controller.signal.aborted || (error instanceof Error && error.name === "AbortError"))
417
452
  ? "cancelled"
418
453
  : (job.debugOutcome ??
419
454
  (error instanceof SyncDecisionRequiredError || error instanceof DaemonStoppingError
420
455
  ? "blocked"
421
456
  : "failed")));
457
+ if (waitForInspectionLog && logged)
458
+ await logged;
459
+ job.view.phase = "failed";
460
+ job.view.error = remoteError(error);
461
+ if (diffReviewOwner)
462
+ job.controller.abort();
422
463
  if (job.committed)
423
464
  for (const id of new Set([client, ...job.peers])) {
424
465
  const affected = participants.get(id);
@@ -507,14 +548,7 @@ export async function startServer(root, execute, hooks = {}) {
507
548
  async function resumeContact(facts, disconnect) {
508
549
  const peer = requireParticipant(facts.id, true);
509
550
  const expiry = peer.expiry;
510
- const matchesSession = (old) => old.pid === facts.pid &&
511
- old.generation === facts.generation &&
512
- old.cwd === facts.cwd &&
513
- old.sessionId === facts.sessionId &&
514
- old.sessionFile === facts.sessionFile &&
515
- old.sessionDir === facts.sessionDir &&
516
- old.mode === facts.mode &&
517
- old.hasUI === facts.hasUI;
551
+ const matchesSession = (old) => sameDiffReviewBinding(old, facts);
518
552
  if (!expiry || contactState(peer) !== "expired" || peer.resumeFacts || !matchesSession(peer.facts))
519
553
  throw new Error("Client is not eligible to resume contact for this session.");
520
554
  const signal = disconnect ? AbortSignal.any([disconnect, expiry.signal]) : expiry.signal;
@@ -587,6 +621,7 @@ export async function startServer(root, execute, hooks = {}) {
587
621
  if (closedClients.has(id))
588
622
  return poll(peer, 0);
589
623
  peer.closing = true;
624
+ invalidateDiffReview(peer);
590
625
  participantsChanged();
591
626
  invalidateExpiry(peer);
592
627
  for (const waiting of [...pending.values()])
@@ -760,9 +795,12 @@ export async function startServer(root, execute, hooks = {}) {
760
795
  throw new Error("Client retirement ledger is full; stop and restart the service.");
761
796
  if (!processExists(params.pid))
762
797
  throw new Error("Client process is not alive.");
763
- for (const [id, peer] of participants)
764
- if (!processExists(peer.facts.pid) && !peer.callbacks.size)
798
+ for (const [id, peer] of participants) {
799
+ if (!processExists(peer.facts.pid) && !peer.callbacks.size) {
800
+ invalidateDiffReview(peer);
765
801
  participants.delete(id);
802
+ }
803
+ }
766
804
  if (!participants.has(params.id) && participants.size >= 64)
767
805
  throw new Error("Daemon client capacity reached.");
768
806
  const old = participants.get(params.id);
@@ -770,10 +808,12 @@ export async function startServer(root, execute, hooks = {}) {
770
808
  (old.facts.pid !== params.pid ||
771
809
  ((old.connected || old.suspected) && old.facts.generation !== params.generation)))
772
810
  throw new Error("Client identity collision.");
773
- if (old)
811
+ if (old) {
774
812
  invalidateExpiry(old);
813
+ invalidateDiffReview(old);
814
+ }
775
815
  participantsChanged();
776
- participants.set(params.id, {
816
+ const replacement = {
777
817
  facts: structuredClone(params),
778
818
  reviewDetails,
779
819
  reservations: old?.reservations,
@@ -785,16 +825,20 @@ export async function startServer(root, execute, hooks = {}) {
785
825
  suspected: false,
786
826
  seen: Date.now(),
787
827
  publishing: !old,
788
- });
828
+ };
829
+ participants.set(params.id, replacement);
789
830
  try {
790
831
  await savePeers();
791
832
  assertOwner();
792
833
  }
793
834
  catch (error) {
794
- if (old)
795
- participants.set(params.id, old);
796
- else
797
- participants.delete(params.id);
835
+ if (participants.get(params.id) === replacement) {
836
+ invalidateDiffReview(replacement);
837
+ if (old)
838
+ participants.set(params.id, old);
839
+ else
840
+ participants.delete(params.id);
841
+ }
798
842
  throw error;
799
843
  }
800
844
  const attached = requireParticipant(params.id, true);
@@ -812,6 +856,7 @@ export async function startServer(root, execute, hooks = {}) {
812
856
  ? next.sessionId === params.sessionId
813
857
  : params.sessionFile === undefined && next.cwd === params.cwd;
814
858
  if (matches) {
859
+ invalidateDiffReview(peer);
815
860
  participants.delete(id);
816
861
  closedClients.add(id);
817
862
  }
@@ -864,8 +909,11 @@ export async function startServer(root, execute, hooks = {}) {
864
909
  if (contactState(peer) === "expired")
865
910
  throw new ClientContactExpiredError();
866
911
  requireParticipant(params.facts.id);
867
- peer.facts = structuredClone(params.facts);
868
- const published = peer.facts;
912
+ const published = structuredClone(params.facts);
913
+ const bindingChanged = !sameDiffReviewBinding(old, published);
914
+ if (bindingChanged)
915
+ invalidateDiffReview(peer);
916
+ peer.facts = published;
869
917
  const unchanged = JSON.stringify(old) === JSON.stringify(published);
870
918
  if (!unchanged)
871
919
  participantsChanged();
@@ -873,8 +921,11 @@ export async function startServer(root, execute, hooks = {}) {
873
921
  await savePeers(undefined, unchanged);
874
922
  }
875
923
  catch (error) {
876
- if (peer.facts === published)
924
+ if (participants.get(published.id) === peer && peer.facts === published) {
877
925
  peer.facts = old;
926
+ if (bindingChanged)
927
+ invalidateDiffReview(peer);
928
+ }
878
929
  throw error;
879
930
  }
880
931
  await hooks.factsChanged?.();
@@ -1006,6 +1057,16 @@ export async function startServer(root, execute, hooks = {}) {
1006
1057
  return stop();
1007
1058
  throw new Error("Unknown daemon method.");
1008
1059
  }
1060
+ const diffReviewOwner = (client, generation) => {
1061
+ const peer = participants.get(client);
1062
+ if (peer &&
1063
+ peer.facts.generation === generation &&
1064
+ peer.facts.mode === "tui" &&
1065
+ peer.facts.hasUI &&
1066
+ contactState(peer) === "active" &&
1067
+ Date.now() - peer.seen <= 5_000)
1068
+ return peer.diffReviewOwner;
1069
+ };
1009
1070
  const respond = (response, status, value) => {
1010
1071
  let encoded = JSON.stringify(value);
1011
1072
  if (Buffer.byteLength(encoded) > MAX_MESSAGE_BYTES) {
@@ -1041,6 +1102,7 @@ export async function startServer(root, execute, hooks = {}) {
1041
1102
  "resume-contact",
1042
1103
  "startup.bootstrap",
1043
1104
  "state-wait",
1105
+ "diff-review-read",
1044
1106
  "foreground-stop",
1045
1107
  "upgrade-stop",
1046
1108
  ].includes(body.method)) {
@@ -1049,6 +1111,18 @@ export async function startServer(root, execute, hooks = {}) {
1049
1111
  if (response.destroyed)
1050
1112
  disconnect();
1051
1113
  }
1114
+ if (body.method === "diff-review-read" || body.method === "diff-review-close") {
1115
+ if (!published)
1116
+ throw new Error("Daemon readiness is not published.");
1117
+ assertOwner();
1118
+ if (!record(body.params))
1119
+ throw new Error("Invalid diff review request.");
1120
+ await handleDiffReviewRequest(body.method, body.params, admissionController?.signal, diffReviews, diffReviewOwner, assertOwner, (result) => {
1121
+ if (!response.destroyed)
1122
+ respond(response, 200, { result });
1123
+ });
1124
+ return;
1125
+ }
1052
1126
  const operation = handle(body.method, body.params, admissionController?.signal, body.reviewDetails === 1);
1053
1127
  if ([
1054
1128
  "attach",
@@ -1110,6 +1184,7 @@ export async function startServer(root, execute, hooks = {}) {
1110
1184
  if (!exited && (!peer.connected || Date.now() - peer.seen <= 5_000))
1111
1185
  continue;
1112
1186
  participationChanged ||= participates(peer);
1187
+ invalidateDiffReview(peer);
1113
1188
  peer.connected = false;
1114
1189
  peer.suspected = !exited;
1115
1190
  if (exited)
@@ -1197,6 +1272,7 @@ export async function startServer(root, execute, hooks = {}) {
1197
1272
  return closing;
1198
1273
  closing = (async () => {
1199
1274
  closed = true;
1275
+ diffReviews.close();
1200
1276
  for (const peer of participants.values()) {
1201
1277
  invalidateExpiry(peer);
1202
1278
  waiters.get(peer)?.changed();
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.15.0"
2
+ "version": "0.16.0"
3
3
  }
package/dist/index.ts CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  createSyncAttentionController,
5
5
  readStateForConfig,
6
6
  syncStateFingerprint
7
- } from "./chunks/chunk-YX6DCQ7P.ts";
7
+ } from "./chunks/chunk-5T4ZOHYF.ts";
8
8
  import {
9
9
  combineSignals,
10
10
  throwIfAborted
@@ -33,7 +33,7 @@ import {
33
33
  installPiDaemonHost,
34
34
  piDaemonClient,
35
35
  withPiDaemonClient
36
- } from "./chunks/chunk-EI2J5Z4Q.ts";
36
+ } from "./chunks/chunk-SPXEDJ2G.ts";
37
37
  import {
38
38
  configureSyncStatus,
39
39
  createSyncStatusPublisher,
@@ -47,7 +47,7 @@ import {
47
47
  } from "./chunks/chunk-R3SAMXB6.ts";
48
48
  import {
49
49
  safeTerminalText
50
- } from "./chunks/chunk-2JNFEZ3V.ts";
50
+ } from "./chunks/chunk-AMJRUXFT.ts";
51
51
 
52
52
  // src/sync/agent-policy.ts
53
53
  import {
@@ -433,12 +433,12 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
433
433
  // src/sync/sync-loaders.ts
434
434
  function createSyncLoaders(dependencies) {
435
435
  const loaders = {
436
- commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-ZR26OSBX.ts"))),
437
- inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-7OADBR57.ts"))),
438
- setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-J3YLBB6N.ts"))),
436
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-4XHK5PVX.ts"))),
437
+ inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-TZ4EMSBN.ts"))),
438
+ setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-LJPEZONY.ts"))),
439
439
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-ZUJJZCFW.ts"))),
440
440
  syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import("./chunks/sync-state-QIT64TKV.ts"))),
441
- operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-3K6WLPXY.ts")))
441
+ operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-QIQ3G66S.ts")))
442
442
  };
443
443
  return loaders;
444
444
  }
@@ -8,7 +8,7 @@ The `/sync` TUI manager uses Kit's public `ChoiceScreen` without search. It show
8
8
 
9
9
  The homepage shows setup/storage, cached remote observations, last applied state and relevant automatic-transfer permissions. It does not render scheduler owners, leases, request accounting or candidate limits. Recorded background phases and successful background-transfer timestamps are explicitly historical; neither replaces a fresh remote check. Missing records show **not yet observed**, and unreadable or invalid records show **Unknown**. Last applied does not invent a timestamp or direction.
10
10
 
11
- **View differences** remains an explicit read action. **History** offers repair only when the active WebDAV snapshot is missing from History. It discloses the temporary conditional-write probe and history update before asking for consent and revalidates the reviewed setup and remote head before changing history.
11
+ **View differences** and `/sync diff` share the same read-only comparison. TUI lists changed paths as **Local only**, **Remote only**, or **Different**. Select a file to load its unified diff (`− Local`, `+ Remote`). The review floats on terminals with at least 24 columns and five rows when opened; smaller terminals use the inline view. Escape returns to the selected file and filter; Ctrl+C closes the review. Binary, over-limit, and session files show a notice instead of text. If the retained comparison expires or the setup changes, reopen **View differences** to refresh. The comparison uses neither the last sync as a baseline nor transfer permission. RPC retains the summary and does not request file bodies. **History** offers repair only when the active WebDAV snapshot is missing from History. It discloses the temporary conditional-write probe and history update before asking for consent and revalidates the reviewed setup and remote head before changing history.
12
12
 
13
13
  The attention widget retains its labeled muted separator and one body row: **Open /sync to review** with the setup name. It remains passive, preserves collapse state and observation classification, and exposes detailed reasons through the manager and existing notifications. Session replacement, shutdown and stale asynchronous publication retain their existing cleanup guards.
14
14
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-sync",
3
- "version": "0.69.0",
3
+ "version": "0.70.0",
4
4
  "description": "Pi extension that syncs Pi configuration through Git, WebDAV, Cloudflare R2, or S3-compatible storage.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -47,7 +47,7 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@narumitw/sync-node-sdk": "npm:@earendil-works/pi-coding-agent@1.6.0",
50
- "@narumitw/pi-tui-kit": "^0.72.0",
50
+ "@narumitw/pi-tui-kit": "^0.74.0",
51
51
  "fast-xml-parser": "^5.12.1",
52
52
  "minimatch": "^11.0.9",
53
53
  "proper-lockfile": "^4.1.2",
@@ -57,7 +57,7 @@
57
57
  "@earendil-works/pi-ai": "1.6.0",
58
58
  "@earendil-works/pi-coding-agent": "1.6.0",
59
59
  "@earendil-works/pi-tui": "1.6.0",
60
- "@narumitw/pi-sync-daemon": "^0.15.0",
60
+ "@narumitw/pi-sync-daemon": "^0.16.0",
61
61
  "@types/proper-lockfile": "^4.1.4",
62
62
  "@types/semver": "^7.8.0",
63
63
  "esbuild": "0.28.2",
@@ -79,7 +79,7 @@ Escape closes the screen without undoing successful saves.
79
79
  Complex values retain their input/review flows.
80
80
  This navigation change does not alter schema, defaults, automatic-sync behavior, or explicit opt-ins.
81
81
 
82
- The main menu shows cached status separately from transfer, inspection, and management actions. **View differences** (`/sync diff`) reads current file differences only when selected. It works with Debug mode off and is not a comparison against the last sync.
82
+ The main menu shows cached status separately from transfer, inspection, and management actions. **View differences** (`/sync diff`) reads current file differences only when selected. In TUI, select an entry to inspect one text diff; RPC shows the file summary. It works with Debug mode off and is not a comparison against the last sync.
83
83
  **Last applied snapshot** shows an ID, not an application time. The menu shortens long IDs; **History** shows the full IDs.
84
84
  See the [TUI behavior contract](https://github.com/narumiruna/pi-extensions/blob/main/packages/pi-sync/docs/tui-contract.md) for scopes and transfer branches.
85
85
 
@@ -10,7 +10,7 @@ import { syncErrorGuidance } from "../sync/sync-error-guidance.js";
10
10
  import { errorMessage, isSyncDecisionRequiredError, SetupPullRequiresUiError } from "../sync/sync-errors.js";
11
11
  import type { SyncLoaders } from "../sync/sync-loaders.js";
12
12
  import { RemoteSelectionMismatchError } from "../sync/sync-policy.js";
13
- import type { DirectionalIntent, RunRouteResult } from "../ui/cancellable-operation.js";
13
+ import type { DirectionalIntent, RunRouteIntent, RunRouteResult } from "../ui/cancellable-operation.js";
14
14
  import { trackOperationDialogs } from "../ui/operation-dialogs.js";
15
15
  import { setSyncStatus } from "../ui/sync-status.js";
16
16
  import { safeTerminalText } from "../ui/terminal-text.js";
@@ -79,9 +79,10 @@ export async function executeCommand(
79
79
  setup?: string,
80
80
  onDialog?: (active: boolean) => void,
81
81
  retryRefusal = false,
82
- directional?: DirectionalIntent,
82
+ intent?: RunRouteIntent,
83
83
  ): Promise<RunRouteResult> {
84
84
  ctx = trackOperationDialogs(ctx, onDialog);
85
+ const directional = intent?.intent === "read-diff" ? undefined : intent;
85
86
  try {
86
87
  const directionalClient = directional === undefined ? undefined : piDaemonClient(ctx);
87
88
  const command = await resolveSyncCommand(rawArgs, ctx);
@@ -102,6 +103,10 @@ export async function executeCommand(
102
103
  if (signal) options.signal = signal;
103
104
  if (onCommit) options.onCommit = onCommit;
104
105
  validateCommandOptions(subcommand, options);
106
+ if (intent?.intent === "read-diff") {
107
+ if (subcommand !== "diff" || !setup || rest.length) throw new Error("Invalid diff review action.");
108
+ options.diffReviewFingerprint = intent.fingerprint;
109
+ }
105
110
  if (retryRefusal) throw new Error("Model retries are no longer supported. Use reviewed manual sync.");
106
111
 
107
112
  switch (subcommand) {
@@ -156,8 +161,8 @@ export async function executeCommand(
156
161
  case "diff": {
157
162
  const operations = await loaders.operations();
158
163
  throwIfAborted(options.signal);
159
- await operations.diff(ctx, options);
160
- return { kind: "completed" };
164
+ const result = await operations.diff(ctx, options);
165
+ return { kind: result === "close" ? "closed" : "completed" };
161
166
  }
162
167
  case "conflicts": {
163
168
  const { showConflicts } = await import("../sync/conflict-review.js");
@@ -5,7 +5,7 @@ import { combineSignals } from "../sync/signals.js";
5
5
  import { errorMessage } from "../sync/sync-errors.js";
6
6
  import type { SyncLoaders } from "../sync/sync-loaders.js";
7
7
  import { formatRemoteSelectionMismatch } from "../sync/sync-policy.js";
8
- import type { DirectionalIntent, RunRouteResult } from "../ui/cancellable-operation.js";
8
+ import type { RunRouteIntent, RunRouteResult } from "../ui/cancellable-operation.js";
9
9
  import {
10
10
  observationMatchesConfig,
11
11
  type SyncAttentionController,
@@ -39,7 +39,7 @@ export async function handleCommand(
39
39
  target?: string,
40
40
  onDialog?: (active: boolean) => void,
41
41
  retryRefusal = false,
42
- directional?: DirectionalIntent,
42
+ intent?: RunRouteIntent,
43
43
  ) => {
44
44
  const [command, ...args] = splitArgs(route);
45
45
  if (command === "sync" && !retryRefusal) {
@@ -60,7 +60,7 @@ export async function handleCommand(
60
60
  target,
61
61
  onDialog,
62
62
  retryRefusal,
63
- directional,
63
+ intent,
64
64
  );
65
65
  };
66
66
  if (!rawArgs.trim()) {
@@ -11,6 +11,7 @@ export interface CommandOptions {
11
11
  auto: boolean;
12
12
  setup?: string;
13
13
  automaticFingerprint?: string;
14
+ diffReviewFingerprint?: string;
14
15
  signal?: AbortSignal;
15
16
  onCommit?: () => void;
16
17
  /** In-memory startup diagnostics only; never persisted or sent to a backend. */
@@ -0,0 +1,68 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ DaemonError,
4
+ type DiffReviewInventory,
5
+ type DiffReviewPreview,
6
+ parseDiffReviewInventory,
7
+ } from "@narumitw/pi-sync-daemon";
8
+ import { piDaemonClient } from "./pi-client.js";
9
+
10
+ export type ActiveDiffReview = Extract<DiffReviewInventory, { kind: "review" }> & {
11
+ read(fileId: string, signal?: AbortSignal): Promise<DiffReviewPreview>;
12
+ close(): Promise<void>;
13
+ };
14
+ export type OpenDiffReviewResult = ActiveDiffReview | Extract<DiffReviewInventory, { kind: "unavailable" }>;
15
+
16
+ export async function openDiffReview(
17
+ ctx: ExtensionContext,
18
+ setup: string | undefined,
19
+ fingerprint: string | undefined,
20
+ signal?: AbortSignal,
21
+ ): Promise<OpenDiffReviewResult> {
22
+ const client = piDaemonClient(ctx);
23
+ const connection = await client.connect(undefined, signal);
24
+ const generation = client.generation;
25
+ const validate = () => {
26
+ client.validate();
27
+ if (client.generation !== generation) throw new Error("The Sync review owner changed.");
28
+ };
29
+ validate();
30
+ signal?.throwIfAborted();
31
+ let inventory: DiffReviewInventory;
32
+ try {
33
+ inventory = parseDiffReviewInventory(
34
+ await client.run(
35
+ "diff.review",
36
+ { ...(setup === undefined ? {} : { setup }), ...(fingerprint === undefined ? {} : { fingerprint }) },
37
+ signal,
38
+ ctx,
39
+ ),
40
+ );
41
+ } catch (error) {
42
+ if (error instanceof DaemonError && error.message === "Unsupported engine operation.") {
43
+ return {
44
+ kind: "unavailable",
45
+ message: "File previews need a compatible Pi Sync daemon. Reload Pi to update it.",
46
+ };
47
+ }
48
+ throw error;
49
+ }
50
+ if (inventory.kind !== "review") return inventory;
51
+ const reviewId = inventory.id;
52
+ return {
53
+ ...inventory,
54
+ async read(fileId, signal) {
55
+ validate();
56
+ if ((await client.verifyConnection(signal)) !== connection) return { kind: "stale" };
57
+ validate();
58
+ signal?.throwIfAborted();
59
+ const preview = await connection.readDiffReview(reviewId, fileId, signal);
60
+ validate();
61
+ signal?.throwIfAborted();
62
+ return preview;
63
+ },
64
+ async close() {
65
+ await connection.closeDiffReview(reviewId, AbortSignal.timeout(2_000)).catch(() => {});
66
+ },
67
+ };
68
+ }
@@ -27,8 +27,18 @@ export async function syncBoth(ctx: ExtensionContext, options: CommandOptions) {
27
27
  export async function rollback(ctx: ExtensionContext, options: CommandOptions) {
28
28
  await remoteOperation(ctx, "rollback", options);
29
29
  }
30
- export async function diff(ctx: ExtensionContext, options: CommandOptions) {
31
- await remoteOperation(ctx, "diff", options);
30
+ export function diff(ctx: ExtensionContext, options: CommandOptions) {
31
+ if (ctx.mode !== "tui" || !ctx.hasUI) return remoteOperation(ctx, "diff", options).then(() => {});
32
+ return Promise.all([import("../daemon/diff-review.js"), import("../ui/diff-review.js")]).then(
33
+ ([{ openDiffReview }, { showSyncDiffReview }]) => {
34
+ options.signal?.throwIfAborted();
35
+ return showSyncDiffReview(
36
+ ctx,
37
+ (signal) => openDiffReview(ctx, options.setup, options.diffReviewFingerprint, signal),
38
+ options.signal,
39
+ );
40
+ },
41
+ );
32
42
  }
33
43
  export async function history(ctx: ExtensionContext, options: CommandOptions) {
34
44
  await remoteOperation(ctx, "history", options);