@narumitw/pi-sync 0.60.2 → 0.60.5
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.
- package/CHANGELOG.md +36 -0
- package/README.md +10 -0
- package/dist/chunks/{chunk-FOMZEZER.ts → chunk-6KIWZ4AY.ts} +360 -60
- package/dist/chunks/chunk-6KIWZ4AY.ts.map +7 -0
- package/dist/chunks/{chunk-B53FS4RW.ts → chunk-F64YWRXG.ts} +2 -2
- package/dist/chunks/{chunk-ENFHHB5O.ts → chunk-H7VOTY5N.ts} +55 -6
- package/dist/chunks/chunk-H7VOTY5N.ts.map +7 -0
- package/dist/chunks/{chunk-E7UJHMNW.ts → chunk-V2QIMC3U.ts} +2 -2
- package/dist/chunks/{chunk-3YXBG7BQ.ts → chunk-YVH5VJR4.ts} +2 -2
- package/dist/chunks/{command-handler-RTBEFZUX.ts → command-handler-TNPWFIPG.ts} +10 -8
- package/dist/chunks/command-handler-TNPWFIPG.ts.map +7 -0
- package/dist/chunks/{conflict-review-YXROU42F.ts → conflict-review-ETCSYJTH.ts} +3 -3
- package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts → manager-result-dispatcher-2GFNWHDM.ts} +4 -4
- package/dist/chunks/{manager-ui-TNAMQNEU.ts → manager-ui-LFONXWQN.ts} +8 -8
- package/dist/chunks/{remote-selection-ui-47H7V62F.ts → remote-selection-ui-GFR6TDTX.ts} +3 -3
- package/dist/chunks/{sync-inspection-5GQEB62G.ts → sync-inspection-6VGR2UVZ.ts} +3 -3
- package/dist/chunks/{sync-operations-65HDA67O.ts → sync-operations-SAKAZL6Z.ts} +3 -3
- package/dist/index.ts +64 -41
- package/dist/index.ts.map +3 -3
- package/docs/agent-mode-verification.md +1 -1
- package/docs/agent-quality-verification.md +1 -1
- package/docs/continuous-sync-verification.md +1 -1
- package/docs/daemon-migration.md +88 -6
- package/docs/tui-contract.md +7 -1
- package/package.json +3 -3
- package/skills/configure-pi-sync/references/configuration.md +1 -0
- package/src/commands/command-execution.ts +1 -1
- package/src/commands/command-handler.ts +2 -0
- package/src/daemon/pi-client.ts +302 -57
- package/src/daemon/queue-release-ui.ts +88 -0
- package/src/sync-extension.ts +68 -43
- package/src/ui/sync-status.ts +67 -4
- package/dist/chunks/chunk-ENFHHB5O.ts.map +0 -7
- package/dist/chunks/chunk-FOMZEZER.ts.map +0 -7
- package/dist/chunks/command-handler-RTBEFZUX.ts.map +0 -7
- package/docs/settings.md +0 -90
- /package/dist/chunks/{chunk-B53FS4RW.ts.map → chunk-F64YWRXG.ts.map} +0 -0
- /package/dist/chunks/{chunk-E7UJHMNW.ts.map → chunk-V2QIMC3U.ts.map} +0 -0
- /package/dist/chunks/{chunk-3YXBG7BQ.ts.map → chunk-YVH5VJR4.ts.map} +0 -0
- /package/dist/chunks/{conflict-review-YXROU42F.ts.map → conflict-review-ETCSYJTH.ts.map} +0 -0
- /package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts.map → manager-result-dispatcher-2GFNWHDM.ts.map} +0 -0
- /package/dist/chunks/{manager-ui-TNAMQNEU.ts.map → manager-ui-LFONXWQN.ts.map} +0 -0
- /package/dist/chunks/{remote-selection-ui-47H7V62F.ts.map → remote-selection-ui-GFR6TDTX.ts.map} +0 -0
- /package/dist/chunks/{sync-inspection-5GQEB62G.ts.map → sync-inspection-6VGR2UVZ.ts.map} +0 -0
- /package/dist/chunks/{sync-operations-65HDA67O.ts.map → sync-operations-SAKAZL6Z.ts.map} +0 -0
package/src/daemon/pi-client.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
type Callback,
|
|
9
9
|
type ClientFacts,
|
|
10
10
|
type ClientHandoff,
|
|
11
|
+
type ContactState,
|
|
11
12
|
DaemonConnection,
|
|
12
13
|
DaemonError,
|
|
13
14
|
type DocumentView,
|
|
@@ -27,26 +28,34 @@ import { validateSettingsDocument } from "@narumitw/pi-sync-daemon/engine/settin
|
|
|
27
28
|
import { sessionDirFromContext } from "@narumitw/pi-sync-daemon/engine/snapshot/session-paths";
|
|
28
29
|
import type { CommandOptions } from "../commands/command-types.js";
|
|
29
30
|
import type { StartupTimingPublisher } from "../sync/startup-timings.js";
|
|
30
|
-
import { SyncDecisionRequiredError } from "../sync/sync-errors.js";
|
|
31
|
+
import { errorMessage, SyncDecisionRequiredError } from "../sync/sync-errors.js";
|
|
31
32
|
import { RemoteSelectionMismatchError } from "../sync/sync-policy.js";
|
|
32
|
-
import {
|
|
33
|
+
import {
|
|
34
|
+
type SyncStatusPresentation,
|
|
35
|
+
setSyncStatus,
|
|
36
|
+
showSyncConnectionStatus,
|
|
37
|
+
showSyncQueueReleaseRecovery,
|
|
38
|
+
} from "../ui/sync-status.js";
|
|
33
39
|
import { safeTerminalText } from "../ui/terminal-text.js";
|
|
34
40
|
import { PiApplyGate } from "./apply-gate.js";
|
|
41
|
+
import { createQueueReleaseUI, type QueueReleaseEvent } from "./queue-release-ui.js";
|
|
35
42
|
import { quarantineClient, recoverDetachedClients } from "./recovery.js";
|
|
36
43
|
|
|
37
|
-
const scope = new AsyncLocalStorage<PiDaemonClient>();
|
|
44
|
+
const scope = new AsyncLocalStorage<{ client: PiDaemonClient; reload?: AbortController }>();
|
|
38
45
|
const clients = new WeakMap<ExtensionContext["sessionManager"], PiDaemonClient>();
|
|
39
46
|
export function currentPiDaemonClient() {
|
|
40
47
|
return current();
|
|
41
48
|
}
|
|
42
49
|
function current() {
|
|
43
|
-
const client = scope.getStore();
|
|
50
|
+
const client = scope.getStore()?.client;
|
|
44
51
|
if (!client) throw new Error("Pi synchronization requires a current session-bound daemon client.");
|
|
45
52
|
client.validate();
|
|
46
53
|
return client;
|
|
47
54
|
}
|
|
48
55
|
function canonicalPath(value: string | undefined): string | undefined {
|
|
49
|
-
|
|
56
|
+
// An in-memory session (`pi --no-session`) reports an empty session dir instead of
|
|
57
|
+
// omitting it, so an empty path means "no path to publish", not a broken caller.
|
|
58
|
+
if (value === undefined || value === "") return undefined;
|
|
50
59
|
if (!path.isAbsolute(value)) throw new Error("Pi session paths must be absolute.");
|
|
51
60
|
const parts: string[] = [];
|
|
52
61
|
let cursor = path.resolve(value);
|
|
@@ -123,7 +132,7 @@ const authority: ConfigAuthority = {
|
|
|
123
132
|
/** Factory registration installs only adapters; it starts no process and performs no I/O. */
|
|
124
133
|
export function installPiDaemonHost() {
|
|
125
134
|
configureEngineHost({
|
|
126
|
-
root: () => scope.getStore()?.root ?? path.resolve(getAgentDir()),
|
|
135
|
+
root: () => scope.getStore()?.client.root ?? path.resolve(getAgentDir()),
|
|
127
136
|
config: authority,
|
|
128
137
|
mutate: async () => {
|
|
129
138
|
throw new Error("File mutation belongs to pi-sync-daemon; no in-process fallback is permitted.");
|
|
@@ -147,8 +156,9 @@ export function piDaemonClient(ctx: ExtensionContext) {
|
|
|
147
156
|
export function withPiDaemonClient<Context extends ExtensionContext, T>(
|
|
148
157
|
ctx: Context,
|
|
149
158
|
action: (owned: Context) => Promise<T>,
|
|
159
|
+
reload?: AbortController,
|
|
150
160
|
) {
|
|
151
|
-
const
|
|
161
|
+
const owner = { client: piDaemonClient(ctx), reload };
|
|
152
162
|
// TUI input arrives from Pi's event loop, outside the command's async call tree.
|
|
153
163
|
// Bind public component methods so later menu actions retain this exact owner,
|
|
154
164
|
// never a replacement session selected through a global fallback.
|
|
@@ -165,14 +175,14 @@ export function withPiDaemonClient<Context extends ExtensionContext, T>(
|
|
|
165
175
|
if (typeof value !== "function") return value;
|
|
166
176
|
const saved = methods.get(key);
|
|
167
177
|
if (saved?.source === value) return saved.bound;
|
|
168
|
-
const bound = (...values: unknown[]) => scope.run(
|
|
178
|
+
const bound = (...values: unknown[]) => scope.run(owner, () => Reflect.apply(value, original, values));
|
|
169
179
|
methods.set(key, { source: value, bound });
|
|
170
180
|
return bound;
|
|
171
181
|
},
|
|
172
182
|
});
|
|
173
183
|
};
|
|
174
184
|
const invoke = (...provided: Parameters<typeof factory>) => {
|
|
175
|
-
const component = scope.run(
|
|
185
|
+
const component = scope.run(owner, () => factory(...provided));
|
|
176
186
|
return component instanceof Promise ? component.then(wrap) : wrap(component);
|
|
177
187
|
};
|
|
178
188
|
// Do not turn synchronous editors/reviews into asynchronous factories.
|
|
@@ -188,11 +198,14 @@ export function withPiDaemonClient<Context extends ExtensionContext, T>(
|
|
|
188
198
|
return key === "ui" ? ui : Reflect.get(target, key, target);
|
|
189
199
|
},
|
|
190
200
|
});
|
|
191
|
-
return scope.run(
|
|
201
|
+
return scope.run(owner, () => action(owned));
|
|
192
202
|
}
|
|
193
203
|
export async function remoteOperation(ctx: ExtensionContext, operation: string, options: CommandOptions) {
|
|
194
204
|
const client = piDaemonClient(ctx);
|
|
195
205
|
const { signal, onCommit, args, setup } = options;
|
|
206
|
+
const owner = scope.getStore();
|
|
207
|
+
const reload = options.reload && owner?.client === client ? owner.reload : undefined;
|
|
208
|
+
reload?.signal.throwIfAborted();
|
|
196
209
|
const payload = {
|
|
197
210
|
args,
|
|
198
211
|
...(setup === undefined ? {} : { setup }),
|
|
@@ -200,23 +213,51 @@ export async function remoteOperation(ctx: ExtensionContext, operation: string,
|
|
|
200
213
|
force: options.force,
|
|
201
214
|
stale: options.stale,
|
|
202
215
|
silent: options.silent,
|
|
203
|
-
reload:
|
|
216
|
+
reload: reload !== undefined,
|
|
204
217
|
...(options.agentRetryRefusal ? { agentRetryRefusal: true } : {}),
|
|
205
218
|
};
|
|
206
|
-
return client.run(operation, payload, signal, ctx, onCommit);
|
|
219
|
+
return client.run(operation, payload, signal, ctx, onCommit, reload);
|
|
220
|
+
}
|
|
221
|
+
function remoteErrorNamed(error: unknown, name: string) {
|
|
222
|
+
return error instanceof DaemonError && error.remote.name === name;
|
|
207
223
|
}
|
|
224
|
+
|
|
208
225
|
export class PiDaemonClient {
|
|
209
226
|
private connection?: DaemonConnection;
|
|
227
|
+
private protectionOnly = false;
|
|
210
228
|
private partialConnection?: DaemonConnection;
|
|
211
229
|
private work = Promise.resolve();
|
|
212
230
|
private closing = false;
|
|
213
231
|
private paused = false;
|
|
214
232
|
private pausing?: Promise<void>;
|
|
215
233
|
private connecting?: Promise<DaemonConnection>;
|
|
234
|
+
private contactRepair?: { controller: AbortController; done: Promise<void> };
|
|
235
|
+
private contactAttempt?: { error?: unknown };
|
|
236
|
+
private contactFactsUnpublished = false;
|
|
237
|
+
private contactStatus?: { clear(redraw?: boolean): void; unavailable: boolean };
|
|
238
|
+
private releaseUIEnabled = true;
|
|
239
|
+
private runSignal?: AbortSignal;
|
|
240
|
+
private readonly releaseUI = createQueueReleaseUI(
|
|
241
|
+
() => {
|
|
242
|
+
const ctx = this.releaseContext();
|
|
243
|
+
if (ctx) return showSyncQueueReleaseRecovery(ctx);
|
|
244
|
+
},
|
|
245
|
+
() =>
|
|
246
|
+
this.releaseContext()?.ui.notify(
|
|
247
|
+
"Pi Sync could not confirm the file write queue release. Sync may be paused; check /sync daemon status before retrying.",
|
|
248
|
+
"warning",
|
|
249
|
+
),
|
|
250
|
+
);
|
|
251
|
+
private readonly stopReleaseUI = () => {
|
|
252
|
+
// Withdraw while the SDK owner is still active, but never redraw through a replaced context.
|
|
253
|
+
this.releaseUIEnabled = false;
|
|
254
|
+
this.releaseUI.clear(Boolean(this.releaseContext(true)));
|
|
255
|
+
};
|
|
216
256
|
private disposed = false;
|
|
217
257
|
private disposing?: Promise<void>;
|
|
218
258
|
private uiContext: ExtensionContext;
|
|
219
|
-
private
|
|
259
|
+
private reloadRequest?: { received: boolean };
|
|
260
|
+
private pendingReload?: AbortController;
|
|
220
261
|
private readonly busy = new Set<string>();
|
|
221
262
|
private initialized = false;
|
|
222
263
|
private startupDebug = false;
|
|
@@ -243,6 +284,7 @@ export class PiDaemonClient {
|
|
|
243
284
|
if (!root) throw new Error("Agent directory is unavailable.");
|
|
244
285
|
this.root = root;
|
|
245
286
|
this.gate = new PiApplyGate(() => this.validate());
|
|
287
|
+
this.signal.addEventListener("abort", this.stopReleaseUI, { once: true });
|
|
246
288
|
}
|
|
247
289
|
validate() {
|
|
248
290
|
this.signal.throwIfAborted();
|
|
@@ -268,7 +310,7 @@ export class PiDaemonClient {
|
|
|
268
310
|
return undefined;
|
|
269
311
|
return { provider: model.provider, id: model.id, signature: modelSignature(model), authSource: source };
|
|
270
312
|
}
|
|
271
|
-
private facts(): ClientFacts {
|
|
313
|
+
private facts(protectionOnly = this.protectionOnly): ClientFacts {
|
|
272
314
|
const manager = this.ctx.sessionManager;
|
|
273
315
|
return {
|
|
274
316
|
id: this.id,
|
|
@@ -276,14 +318,14 @@ export class PiDaemonClient {
|
|
|
276
318
|
pid: process.pid,
|
|
277
319
|
cwd: this.ctx.cwd,
|
|
278
320
|
mode: this.ctx.mode,
|
|
279
|
-
hasUI: this.ctx.hasUI,
|
|
280
|
-
idle: !this.paused && !this.busy.size && this.ctx.isIdle(),
|
|
281
|
-
ready: this.initialized,
|
|
321
|
+
hasUI: !protectionOnly && this.ctx.hasUI,
|
|
322
|
+
idle: !protectionOnly && !this.paused && !this.busy.size && this.ctx.isIdle(),
|
|
323
|
+
ready: !protectionOnly && this.initialized,
|
|
282
324
|
startupDebug: this.startupDebug,
|
|
283
325
|
sessionFile: canonicalPath(manager.getSessionFile?.()),
|
|
284
326
|
sessionId: manager.getSessionId?.(),
|
|
285
327
|
sessionDir: canonicalPath(sessionDirFromContext(this.ctx)),
|
|
286
|
-
model: this.modelBinding(),
|
|
328
|
+
model: protectionOnly ? undefined : this.modelBinding(),
|
|
287
329
|
};
|
|
288
330
|
}
|
|
289
331
|
async configured() {
|
|
@@ -297,6 +339,8 @@ export class PiDaemonClient {
|
|
|
297
339
|
async pauseForSessionChange() {
|
|
298
340
|
this.validate();
|
|
299
341
|
this.paused = true;
|
|
342
|
+
this.stopReleaseUI();
|
|
343
|
+
this.stopContactRepair(true);
|
|
300
344
|
this.gate.cancelPending();
|
|
301
345
|
this.pausing ??= (async () => {
|
|
302
346
|
const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));
|
|
@@ -307,21 +351,40 @@ export class PiDaemonClient {
|
|
|
307
351
|
})();
|
|
308
352
|
return this.pausing;
|
|
309
353
|
}
|
|
310
|
-
async attachExisting() {
|
|
354
|
+
async attachExisting({ allowUpgrade = false } = {}) {
|
|
311
355
|
this.validate();
|
|
312
356
|
const address = await findDaemon(this.root);
|
|
313
357
|
this.validate();
|
|
314
|
-
if (address)
|
|
358
|
+
if (!address) return false;
|
|
359
|
+
const upgrade = allowUpgrade && address.needsUpgrade && this.ctx.hasUI && ["tui", "rpc"].includes(this.ctx.mode);
|
|
360
|
+
let upgradeFailure: string | undefined;
|
|
361
|
+
if (upgrade) {
|
|
315
362
|
try {
|
|
316
|
-
await this.connect(
|
|
363
|
+
await this.connect();
|
|
364
|
+
this.validate();
|
|
365
|
+
return true;
|
|
317
366
|
} catch (error) {
|
|
318
367
|
this.validate();
|
|
319
|
-
if (
|
|
320
|
-
|
|
368
|
+
if (this.paused) throw error;
|
|
369
|
+
upgradeFailure = safeTerminalText(errorMessage(error));
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
// If upgrade failed, try only the original owner, with its protection-only facts.
|
|
374
|
+
await this.connect(address);
|
|
375
|
+
} catch (error) {
|
|
376
|
+
this.validate();
|
|
377
|
+
if (remoteErrorNamed(error, "DaemonStoppingError")) return false;
|
|
378
|
+
throw error;
|
|
379
|
+
} finally {
|
|
380
|
+
if (upgradeFailure !== undefined) {
|
|
381
|
+
this.validate();
|
|
382
|
+
this.ctx.ui.notify(`pi-sync daemon upgrade failed: ${upgradeFailure}`, "error");
|
|
321
383
|
}
|
|
322
384
|
}
|
|
323
385
|
this.validate();
|
|
324
|
-
|
|
386
|
+
// Headless, shutdown, and failed-upgrade paths must not schedule transfers on an older build.
|
|
387
|
+
return !this.protectionOnly;
|
|
325
388
|
}
|
|
326
389
|
async finishReattachment() {
|
|
327
390
|
this.validate();
|
|
@@ -339,7 +402,13 @@ export class PiDaemonClient {
|
|
|
339
402
|
startupSignal.throwIfAborted();
|
|
340
403
|
};
|
|
341
404
|
validateStartup();
|
|
342
|
-
if (this.connection)
|
|
405
|
+
if (this.connection) {
|
|
406
|
+
if (!existing && this.protectionOnly)
|
|
407
|
+
throw new Error(
|
|
408
|
+
"This session is only protecting its files on an older Pi Sync daemon. Use /reload to upgrade.",
|
|
409
|
+
);
|
|
410
|
+
return this.connection;
|
|
411
|
+
}
|
|
343
412
|
this.connecting ??= (async () => {
|
|
344
413
|
if (this.partialConnection) {
|
|
345
414
|
// A failed unpublished attempt may already be retired or own queue grants.
|
|
@@ -360,21 +429,23 @@ export class PiDaemonClient {
|
|
|
360
429
|
const daemon = existing ?? (await ensureDaemon(this.root, startupSignal));
|
|
361
430
|
validateStartup();
|
|
362
431
|
if (daemon.paths.root !== this.root) throw new Error("Daemon root changed before attach.");
|
|
363
|
-
const
|
|
364
|
-
|
|
432
|
+
const protectionOnly = daemon.needsUpgrade === true;
|
|
433
|
+
const connection = new DaemonConnection(daemon.paths, daemon.identity, this.facts(protectionOnly), {
|
|
434
|
+
callback: (callback, signal) => this.callback(callback, signal, protectionOnly),
|
|
365
435
|
event: (event) => {
|
|
366
436
|
if (event.kind === "commit") return;
|
|
367
437
|
if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;
|
|
368
438
|
const payload = event.payload as {
|
|
369
439
|
message?: string;
|
|
370
440
|
level?: "info" | "warning" | "error";
|
|
441
|
+
report?: string;
|
|
371
442
|
value?: string;
|
|
372
443
|
presentation?: SyncStatusPresentation;
|
|
373
444
|
};
|
|
374
445
|
if (event.kind === "notify" && typeof payload?.message === "string")
|
|
375
446
|
this.uiContext.ui.notify(safeTerminalText(payload.message), payload.level ?? "info");
|
|
376
|
-
if (event.kind === "timings" && typeof
|
|
377
|
-
this.publish?.(this.ctx,
|
|
447
|
+
if (event.kind === "timings" && typeof payload?.report === "string") {
|
|
448
|
+
this.publish?.(this.ctx, payload.report.split("\n").map(safeTerminalText).join("\n"));
|
|
378
449
|
}
|
|
379
450
|
if (event.kind === "status")
|
|
380
451
|
setSyncStatus(
|
|
@@ -383,9 +454,11 @@ export class PiDaemonClient {
|
|
|
383
454
|
payload.presentation,
|
|
384
455
|
);
|
|
385
456
|
},
|
|
457
|
+
contact: (state) => this.observeContact(connection, state),
|
|
458
|
+
queueRelease: (event) => this.observeQueueRelease(connection, event),
|
|
386
459
|
error: () => {
|
|
387
|
-
if (
|
|
388
|
-
|
|
460
|
+
if (this.ownsContactUI() && connection.facts.hasUI && !this.releaseUI.retrying)
|
|
461
|
+
this.showContactStatus("sync service unavailable", "blocked", true);
|
|
389
462
|
},
|
|
390
463
|
});
|
|
391
464
|
this.partialConnection = connection;
|
|
@@ -411,6 +484,7 @@ export class PiDaemonClient {
|
|
|
411
484
|
}
|
|
412
485
|
this.validate();
|
|
413
486
|
this.connection = connection;
|
|
487
|
+
this.protectionOnly = protectionOnly;
|
|
414
488
|
this.partialConnection = undefined;
|
|
415
489
|
return connection;
|
|
416
490
|
}
|
|
@@ -418,7 +492,146 @@ export class PiDaemonClient {
|
|
|
418
492
|
this.connecting = undefined;
|
|
419
493
|
throw error;
|
|
420
494
|
});
|
|
421
|
-
|
|
495
|
+
const connection = await this.connecting;
|
|
496
|
+
validateStartup();
|
|
497
|
+
if (!existing && this.protectionOnly)
|
|
498
|
+
throw new Error("This session is only protecting its files on an older Pi Sync daemon. Use /reload to upgrade.");
|
|
499
|
+
return connection;
|
|
500
|
+
}
|
|
501
|
+
private ownsContactUI() {
|
|
502
|
+
return (
|
|
503
|
+
!this.signal.aborted && !this.disposed && !this.closing && !this.paused && clients.get(this.manager) === this
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
private releaseContext(cleanup = false) {
|
|
507
|
+
if (clients.get(this.manager) !== this) return;
|
|
508
|
+
if (!cleanup && (!this.releaseUIEnabled || !this.ownsContactUI() || this.busy.has("shutdown"))) return;
|
|
509
|
+
try {
|
|
510
|
+
this.ctx.isIdle(); // Also verifies the SDK context has not been retired.
|
|
511
|
+
if (this.ctx.hasUI && (this.ctx.mode === "tui" || this.ctx.mode === "rpc")) return this.ctx;
|
|
512
|
+
} catch {
|
|
513
|
+
// Detached cleanup can outlive its UI.
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
disableQueueReleaseUI() {
|
|
517
|
+
this.stopReleaseUI();
|
|
518
|
+
}
|
|
519
|
+
private observeQueueRelease(connection: DaemonConnection, event: QueueReleaseEvent) {
|
|
520
|
+
if (connection !== this.connection || !connection.facts.hasUI || !this.releaseContext()) return;
|
|
521
|
+
if (event.state === "retrying" && this.contactStatus?.unavailable) this.clearConnectionStatus();
|
|
522
|
+
this.releaseUI.observe(event, this.busy.has("command"), !this.runSignal || this.runSignal.aborted);
|
|
523
|
+
}
|
|
524
|
+
private showContactStatus(text: string, activity: "retry" | "blocked", unavailable = false) {
|
|
525
|
+
const previous = this.contactStatus;
|
|
526
|
+
this.contactStatus = {
|
|
527
|
+
clear: showSyncConnectionStatus(this.ctx, text, { activity, reason: activity === "retry" ? "temp" : "repair" }),
|
|
528
|
+
unavailable,
|
|
529
|
+
};
|
|
530
|
+
previous?.clear();
|
|
531
|
+
}
|
|
532
|
+
private clearConnectionStatus(redraw = true) {
|
|
533
|
+
const status = this.contactStatus;
|
|
534
|
+
this.contactStatus = undefined;
|
|
535
|
+
status?.clear(redraw);
|
|
536
|
+
}
|
|
537
|
+
private stopContactRepair(redraw: boolean) {
|
|
538
|
+
this.contactRepair?.controller.abort(new DOMException("Pi session is changing", "AbortError"));
|
|
539
|
+
this.clearConnectionStatus(redraw);
|
|
540
|
+
}
|
|
541
|
+
private observeContact(connection: DaemonConnection, state: ContactState) {
|
|
542
|
+
if (connection !== this.connection || !this.ownsContactUI()) return;
|
|
543
|
+
if (state === "active") {
|
|
544
|
+
if (this.contactRepair || this.contactFactsUnpublished || connection.contactResumeState === "uncertain") return;
|
|
545
|
+
this.clearRestoredContact();
|
|
546
|
+
} else if (state === "expired" && connection.facts.hasUI && !this.contactAttempt && !this.contactRepair) {
|
|
547
|
+
if (this.gate.size || connection.hasPendingWork || this.releaseUI.retrying) return;
|
|
548
|
+
void this.resumeContact(connection).catch(() => {
|
|
549
|
+
// The owning repair updates the status; a later command reports the error.
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
private clearRestoredContact() {
|
|
554
|
+
this.contactAttempt = undefined;
|
|
555
|
+
this.contactFactsUnpublished = false;
|
|
556
|
+
this.clearConnectionStatus();
|
|
557
|
+
}
|
|
558
|
+
private async resumeContact(connection: DaemonConnection) {
|
|
559
|
+
this.validate();
|
|
560
|
+
if (this.paused || this.connection !== connection) throw new Error("Pi Sync is paused for a session change.");
|
|
561
|
+
if (this.contactRepair) return this.contactRepair.done;
|
|
562
|
+
if (connection.contactState === "active" && connection.contactResumeState !== "uncertain") return;
|
|
563
|
+
if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === "uncertain") {
|
|
564
|
+
throw new Error(
|
|
565
|
+
"Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying.",
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
const earlier = this.contactAttempt;
|
|
569
|
+
if (connection.contactState !== "expired" || earlier) {
|
|
570
|
+
throw new Error("Pi Sync could not restore contact. Review pending work before using /reload.", {
|
|
571
|
+
cause: earlier?.error,
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
const controller = new AbortController();
|
|
575
|
+
const signal = AbortSignal.any([this.signal, controller.signal]);
|
|
576
|
+
const attempt: { error?: unknown } = {};
|
|
577
|
+
this.contactAttempt = attempt;
|
|
578
|
+
const done = Promise.resolve().then(async () => {
|
|
579
|
+
try {
|
|
580
|
+
this.validate();
|
|
581
|
+
signal.throwIfAborted();
|
|
582
|
+
this.showContactStatus("sync reconnecting", "retry");
|
|
583
|
+
// Admission can wait behind an apply. Do not advertise readiness using
|
|
584
|
+
// facts sampled before that wait; publish current facts after the ack.
|
|
585
|
+
await connection.resumeContact({ ...this.facts(), idle: false, ready: false }, signal);
|
|
586
|
+
this.validate();
|
|
587
|
+
signal.throwIfAborted();
|
|
588
|
+
this.contactFactsUnpublished = true;
|
|
589
|
+
this.contactAttempt = undefined;
|
|
590
|
+
await connection.update(this.facts());
|
|
591
|
+
this.validate();
|
|
592
|
+
signal.throwIfAborted();
|
|
593
|
+
this.confirmContact(connection);
|
|
594
|
+
} catch (error) {
|
|
595
|
+
attempt.error = error;
|
|
596
|
+
if (this.ownsContactUI() && !signal.aborted)
|
|
597
|
+
this.showContactStatus("sync reconnect blocked; check /sync daemon status", "blocked");
|
|
598
|
+
throw error;
|
|
599
|
+
} finally {
|
|
600
|
+
if (this.contactRepair?.controller === controller) this.contactRepair = undefined;
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
this.contactRepair = { controller, done };
|
|
604
|
+
return done;
|
|
605
|
+
}
|
|
606
|
+
private async publishFacts(connection: DaemonConnection) {
|
|
607
|
+
if (this.contactRepair) await this.contactRepair.done;
|
|
608
|
+
this.validate();
|
|
609
|
+
if (this.paused) throw new Error("Pi Sync is paused for a session change.");
|
|
610
|
+
if (connection.contactResumeState === "uncertain")
|
|
611
|
+
throw new Error("Pi Sync cannot verify the previous reconnect. Review pending work before using /reload.");
|
|
612
|
+
try {
|
|
613
|
+
await connection.update(this.facts());
|
|
614
|
+
} catch (error) {
|
|
615
|
+
if (!connection.facts.hasUI || !remoteErrorNamed(error, "ClientContactExpiredError")) throw error;
|
|
616
|
+
await this.resumeContact(connection);
|
|
617
|
+
this.validate();
|
|
618
|
+
// A shared repair might have started before these facts changed.
|
|
619
|
+
await connection.update(this.facts());
|
|
620
|
+
}
|
|
621
|
+
this.validate();
|
|
622
|
+
this.confirmContact(connection);
|
|
623
|
+
}
|
|
624
|
+
private confirmContact(connection: DaemonConnection) {
|
|
625
|
+
if (connection.contactState === "expired" || connection.contactState === "inactive")
|
|
626
|
+
throw new Error("Pi Sync did not confirm active participation in the daemon.");
|
|
627
|
+
this.clearRestoredContact();
|
|
628
|
+
}
|
|
629
|
+
async verifyConnection(signal?: AbortSignal) {
|
|
630
|
+
const connection = await this.connect(undefined, signal);
|
|
631
|
+
signal?.throwIfAborted();
|
|
632
|
+
await this.publishFacts(connection);
|
|
633
|
+
signal?.throwIfAborted();
|
|
634
|
+
return connection;
|
|
422
635
|
}
|
|
423
636
|
async readSettings(repair = false) {
|
|
424
637
|
this.validate();
|
|
@@ -432,8 +645,15 @@ export class PiDaemonClient {
|
|
|
432
645
|
}
|
|
433
646
|
return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
|
|
434
647
|
}
|
|
435
|
-
run(
|
|
436
|
-
|
|
648
|
+
run(
|
|
649
|
+
operation: string,
|
|
650
|
+
payload: unknown,
|
|
651
|
+
signal?: AbortSignal,
|
|
652
|
+
ctx = this.ctx,
|
|
653
|
+
onCommit?: () => void,
|
|
654
|
+
reload?: AbortController,
|
|
655
|
+
) {
|
|
656
|
+
const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload));
|
|
437
657
|
this.work = result.then(
|
|
438
658
|
() => {},
|
|
439
659
|
() => {},
|
|
@@ -446,9 +666,12 @@ export class PiDaemonClient {
|
|
|
446
666
|
signal?: AbortSignal,
|
|
447
667
|
ctx = this.ctx,
|
|
448
668
|
onCommit?: () => void,
|
|
669
|
+
reload?: AbortController,
|
|
449
670
|
) {
|
|
450
671
|
this.validate();
|
|
451
672
|
signal?.throwIfAborted();
|
|
673
|
+
reload?.signal.throwIfAborted();
|
|
674
|
+
if (this.pendingReload) throw new Error("Pi resources are about to reload.");
|
|
452
675
|
if (this.paused && operation !== "shutdown")
|
|
453
676
|
throw new Error("Synchronization is paused for a session change; if it was cancelled, use /reload to reattach.");
|
|
454
677
|
const connection = await this.connect(undefined, signal);
|
|
@@ -459,17 +682,28 @@ export class PiDaemonClient {
|
|
|
459
682
|
}
|
|
460
683
|
this.validate();
|
|
461
684
|
signal?.throwIfAborted();
|
|
462
|
-
|
|
685
|
+
if (this.paused)
|
|
686
|
+
await connection.update(this.facts()); // Existing, explicitly attached shutdown path.
|
|
687
|
+
else await this.publishFacts(connection);
|
|
463
688
|
this.validate();
|
|
464
689
|
signal?.throwIfAborted();
|
|
465
690
|
this.uiContext = ctx;
|
|
691
|
+
// The daemon directs reload only to the submitting client, and run() serializes its jobs.
|
|
692
|
+
const request = reload ? { received: false } : undefined;
|
|
693
|
+
this.reloadRequest = request;
|
|
694
|
+
const runSignal = signal ? AbortSignal.any([signal, this.signal]) : this.signal;
|
|
695
|
+
this.runSignal = runSignal;
|
|
696
|
+
const clearForeground = () => this.releaseUI.finishForeground(Boolean(this.releaseContext()));
|
|
697
|
+
runSignal.addEventListener("abort", clearForeground, { once: true });
|
|
466
698
|
try {
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
699
|
+
const result = await connection.run(operation, payload, runSignal, onCommit);
|
|
700
|
+
if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
|
|
701
|
+
this.validate();
|
|
702
|
+
this.pendingReload = reload;
|
|
703
|
+
// Close the command's UI, not the session. Pi reload must run after this job and its UI drain.
|
|
704
|
+
reload.abort(new DOMException("Pi resource reload requested", "AbortError"));
|
|
705
|
+
}
|
|
706
|
+
return result;
|
|
473
707
|
} catch (error) {
|
|
474
708
|
if (error instanceof DaemonError) {
|
|
475
709
|
const prototype =
|
|
@@ -487,19 +721,21 @@ export class PiDaemonClient {
|
|
|
487
721
|
}
|
|
488
722
|
throw error;
|
|
489
723
|
} finally {
|
|
724
|
+
runSignal.removeEventListener("abort", clearForeground);
|
|
725
|
+
clearForeground();
|
|
726
|
+
this.runSignal = undefined;
|
|
490
727
|
this.uiContext = this.ctx;
|
|
491
|
-
|
|
492
|
-
this.reloadRequested &&
|
|
493
|
-
!this.signal.aborted &&
|
|
494
|
-
!this.disposed &&
|
|
495
|
-
!this.closing &&
|
|
496
|
-
clients.get(this.manager) === this
|
|
497
|
-
) {
|
|
498
|
-
this.reloadRequested = false;
|
|
499
|
-
if ("reload" in ctx && typeof ctx.reload === "function") await ctx.reload();
|
|
500
|
-
}
|
|
728
|
+
this.reloadRequest = undefined;
|
|
501
729
|
}
|
|
502
730
|
}
|
|
731
|
+
canReload(owner: AbortController) {
|
|
732
|
+
if (this.pendingReload !== owner || this.paused) return false;
|
|
733
|
+
this.validate();
|
|
734
|
+
return true;
|
|
735
|
+
}
|
|
736
|
+
releaseReload(owner: AbortController) {
|
|
737
|
+
if (this.pendingReload === owner) this.pendingReload = undefined;
|
|
738
|
+
}
|
|
503
739
|
async markReady(debug: boolean) {
|
|
504
740
|
this.validate();
|
|
505
741
|
this.startupDebug = debug;
|
|
@@ -507,18 +743,21 @@ export class PiDaemonClient {
|
|
|
507
743
|
await this.update();
|
|
508
744
|
this.validate();
|
|
509
745
|
}
|
|
510
|
-
async setBusy(reason: string, busy: boolean) {
|
|
746
|
+
async setBusy(reason: string, busy: boolean, publish = true) {
|
|
511
747
|
this.validate();
|
|
512
748
|
if (busy) this.busy.add(reason);
|
|
513
|
-
else this.busy.delete(reason)
|
|
514
|
-
|
|
749
|
+
else if (this.busy.delete(reason) && reason === "command") {
|
|
750
|
+
// Local command completion does not depend on publishing idle facts.
|
|
751
|
+
this.releaseUI.flushWarnings();
|
|
752
|
+
}
|
|
753
|
+
if (publish) await this.update();
|
|
515
754
|
this.validate();
|
|
516
755
|
}
|
|
517
756
|
async update() {
|
|
518
757
|
if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
|
|
519
|
-
await this.
|
|
758
|
+
await this.publishFacts(this.connection);
|
|
520
759
|
}
|
|
521
|
-
private async callback(callback: Callback, signal: AbortSignal) {
|
|
760
|
+
private async callback(callback: Callback, signal: AbortSignal, protectionOnly: boolean) {
|
|
522
761
|
const payload = callback.payload as {
|
|
523
762
|
reservation?: string;
|
|
524
763
|
targets?: string[];
|
|
@@ -541,6 +780,7 @@ export class PiDaemonClient {
|
|
|
541
780
|
signal.throwIfAborted();
|
|
542
781
|
if (this.paused) throw new Error("Pi session is changing; no new work is authorized.");
|
|
543
782
|
if (callback.kind === "queue-acquire") {
|
|
783
|
+
if (this.pendingReload) throw new Error("Pi resources are about to reload.");
|
|
544
784
|
if (payload.background && !this.facts().idle) throw new Error("Pi is busy; background apply was not granted.");
|
|
545
785
|
if (
|
|
546
786
|
payload.generation !== this.generation ||
|
|
@@ -553,6 +793,7 @@ export class PiDaemonClient {
|
|
|
553
793
|
const ctx = this.uiContext;
|
|
554
794
|
const combined = AbortSignal.any([signal, this.signal]);
|
|
555
795
|
if (callback.kind === "model-binding") {
|
|
796
|
+
if (protectionOnly) return null;
|
|
556
797
|
const facts = this.facts();
|
|
557
798
|
const connection = this.connection ?? this.partialConnection;
|
|
558
799
|
if (connection && JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
|
|
@@ -562,7 +803,8 @@ export class PiDaemonClient {
|
|
|
562
803
|
return payload.background && !facts.idle ? null : (facts.model ?? null);
|
|
563
804
|
}
|
|
564
805
|
if (callback.kind === "reload") {
|
|
565
|
-
this.
|
|
806
|
+
if (!this.reloadRequest) throw new Error("No active Pi command can reload resources.");
|
|
807
|
+
this.reloadRequest.received = true;
|
|
566
808
|
return true;
|
|
567
809
|
}
|
|
568
810
|
if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
|
|
@@ -619,6 +861,9 @@ export class PiDaemonClient {
|
|
|
619
861
|
async dispose(handoff?: ClientHandoff) {
|
|
620
862
|
if (this.disposing) return this.disposing;
|
|
621
863
|
this.closing = true;
|
|
864
|
+
this.signal.removeEventListener("abort", this.stopReleaseUI);
|
|
865
|
+
this.stopReleaseUI();
|
|
866
|
+
this.stopContactRepair(false);
|
|
622
867
|
this.disposing = (async () => {
|
|
623
868
|
const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));
|
|
624
869
|
let confirmed = false;
|