@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 542 lines 20.7 KB
Raw
1 import type {
2 DesktopTelemetryRequestDesktopUpdate,
3 DesktopUpdateRemoteOutcome,
4 DesktopUpdateState,
5 } from "@t3tools/contracts";
6 import * as Duration from "effect/Duration";
7 import * as Clock from "effect/Clock";
8 import * as Deferred from "effect/Deferred";
9 import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
11 import * as Queue from "effect/Queue";
12 import * as Ref from "effect/Ref";
13 import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
14 import { compareSemverVersions } from "@t3tools/shared/semver";
15 import type * as Scope from "effect/Scope";
16 import * as Stream from "effect/Stream";
17
18 import * as DesktopObservability from "../app/DesktopObservability.ts";
19 import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
20 import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
21 import * as DesktopUpdates from "./DesktopUpdates.ts";
22 import {
23 nextRemoteDesktopUpdateStep,
24 normalizeRemoteUpdateReason,
25 type RemoteDesktopUpdateAttempts,
26 } from "./remoteUpdateFlow.ts";
27
28 const { logInfo, logError } = DesktopObservability.makeComponentLogger("desktop-remote-updates");
29
30 const ACTION_RETRY_DELAY = Duration.millis(250);
31 const PREPARED_UPDATE_TTL = Duration.minutes(5);
32
33 interface PreparedUpdate {
34 readonly requestId: string;
35 readonly channel: DesktopTelemetryRequestDesktopUpdate["channel"];
36 readonly targetVersion: DesktopTelemetryRequestDesktopUpdate["targetVersion"];
37 readonly downloadedVersion: string;
38 readonly status: "prepared" | "committing" | "failed";
39 readonly failureReason?: string;
40 readonly expiresAt: number;
41 }
42
43 type CommitClaim =
44 | { readonly _tag: "invalid" }
45 | { readonly _tag: "failed"; readonly prepared: PreparedUpdate }
46 | { readonly _tag: "committing" }
47 | { readonly _tag: "claimed"; readonly prepared: PreparedUpdate };
48
49 export const listen: Effect.Effect<
50 void,
51 never,
52 | DesktopUpdates.DesktopUpdates
53 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
54 | DesktopBackendPool.DesktopBackendPool
55 | Scope.Scope
56 > = Effect.gen(function* () {
57 const updates = yield* DesktopUpdates.DesktopUpdates;
58 const backends = yield* DesktopBackendPool.DesktopBackendPool;
59 const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
60 const activeRequestIdRef = yield* Ref.make(Option.none<string>());
61 const requestControlRef = yield* Ref.make<{
62 readonly active: Option.Option<{
63 readonly requestId: string;
64 readonly signal: Deferred.Deferred<void>;
65 }>;
66 readonly cancelledBeforeStart: ReadonlyArray<string>;
67 }>({ active: Option.none(), cancelledBeforeStart: [] });
68 const preparedUpdateRef = yield* Ref.make(Option.none<PreparedUpdate>());
69
70 const publishReport = (
71 state: DesktopUpdateState,
72 terminal?: {
73 readonly outcome: DesktopUpdateRemoteOutcome;
74 readonly reason?: string;
75 readonly preparedRequestId?: string;
76 },
77 explicitRequestId?: string,
78 ): Effect.Effect<void> => {
79 const reason = normalizeRemoteUpdateReason(terminal?.reason);
80 return Ref.get(activeRequestIdRef).pipe(
81 Effect.flatMap((requestId) =>
82 publisher.publishUpdateReport({
83 version: 1,
84 type: "desktopUpdateStatus",
85 ...(explicitRequestId !== undefined
86 ? { requestId: explicitRequestId }
87 : Option.isSome(requestId)
88 ? { requestId: requestId.value }
89 : {}),
90 ...(terminal === undefined ? {} : { outcome: terminal.outcome }),
91 ...(terminal?.preparedRequestId === undefined
92 ? {}
93 : { preparedRequestId: terminal.preparedRequestId }),
94 ...(reason ? { reason } : {}),
95 state,
96 }),
97 ),
98 );
99 };
100
101 const recordPreparedFailure = (requestId: string, reason: string) =>
102 Ref.modify(preparedUpdateRef, (prepared) => {
103 if (
104 Option.isNone(prepared) ||
105 prepared.value.requestId !== requestId ||
106 prepared.value.status === "failed"
107 ) {
108 return [false, prepared] as const;
109 }
110 return [
111 true,
112 Option.some({ ...prepared.value, status: "failed" as const, failureReason: reason }),
113 ] as const;
114 });
115
116 const clearActiveRequest = (requestId: string) =>
117 Ref.update(activeRequestIdRef, (active) =>
118 Option.isSome(active) && active.value === requestId ? Option.none() : active,
119 );
120
121 yield* Effect.scoped(
122 Effect.gen(function* () {
123 const { latest, changes } = yield* updates.subscribe;
124 yield* publishReport(latest);
125 yield* Stream.runForEach(changes, (state) =>
126 Effect.gen(function* () {
127 yield* publishReport(state);
128 const prepared = yield* Ref.get(preparedUpdateRef);
129 if (
130 Option.isSome(prepared) &&
131 prepared.value.status === "committing" &&
132 state.errorContext === "install"
133 ) {
134 const reason = state.message ?? "The desktop app failed to install the update.";
135 if (yield* recordPreparedFailure(prepared.value.requestId, reason)) {
136 yield* publishReport(state, { outcome: "failed", reason }, prepared.value.requestId);
137 }
138 }
139 }),
140 );
141 }),
142 ).pipe(Effect.forkScoped);
143
144 const handleRequest = (request: DesktopTelemetryRequestDesktopUpdate): Effect.Effect<void> =>
145 Effect.scoped(
146 Effect.gen(function* () {
147 const cancellation = yield* Deferred.make<void>();
148 const shouldStart = yield* Ref.modify(requestControlRef, (control) => {
149 if (control.cancelledBeforeStart.includes(request.requestId)) {
150 return [
151 false,
152 {
153 ...control,
154 cancelledBeforeStart: control.cancelledBeforeStart.filter(
155 (requestId) => requestId !== request.requestId,
156 ),
157 },
158 ] as const;
159 }
160 return [
161 true,
162 {
163 ...control,
164 active: Option.some({ requestId: request.requestId, signal: cancellation }),
165 },
166 ] as const;
167 });
168 if (!shouldStart) return;
169
170 const now = yield* Clock.currentTimeMillis;
171 const prepared = yield* Ref.modify(preparedUpdateRef, (current) =>
172 Option.isSome(current) &&
173 current.value.status === "prepared" &&
174 current.value.expiresAt <= now
175 ? ([Option.none<typeof current.value>(), Option.none()] as const)
176 : ([current, current] as const),
177 );
178 if (Option.isSome(prepared) && prepared.value.status !== "failed") {
179 const state = yield* updates.getState;
180 if (
181 prepared.value.status === "prepared" &&
182 prepared.value.channel === request.channel &&
183 prepared.value.targetVersion === request.targetVersion &&
184 state.downloadedVersion === prepared.value.downloadedVersion
185 ) {
186 yield* publishReport(
187 state,
188 { outcome: "ready-to-install", preparedRequestId: prepared.value.requestId },
189 request.requestId,
190 );
191 return;
192 }
193 yield* publishReport(
194 state,
195 {
196 outcome: "failed",
197 reason: "A prepared desktop update is already in progress.",
198 },
199 request.requestId,
200 );
201 return;
202 }
203 yield* Ref.set(activeRequestIdRef, Option.some(request.requestId));
204 yield* logInfo("remote update requested", {
205 requestId: request.requestId,
206 channel: request.channel,
207 });
208 // A switch saves its track first, so the step machine never sees the old track's offer.
209 // The saved track is the user's intent and stays even if this request fails: a track saved
210 // toward Stable never offers an older build outside a guarded switch.
211 if (request.channel !== undefined) {
212 // A reinstall restarts every backend, but the requesting server checked only its own
213 // database. A WSL backend keeps its own, so cross tracks only where all can be checked.
214 const current = yield* updates.getState;
215 if (
216 desktopUpdateChannelOf(current.currentVersion) !== request.channel &&
217 (yield* backends.list).length > 1
218 ) {
219 yield* publishReport(
220 current,
221 {
222 outcome: "failed",
223 reason:
224 "This desktop app also runs WSL backends, whose databases a remote switch cannot check. Switch it on that machine.",
225 },
226 request.requestId,
227 );
228 return;
229 }
230 const switched = yield* Effect.raceFirst(
231 updates.setChannel(request.channel, { minimumVersion: request.targetVersion }).pipe(
232 Effect.as(true),
233 Effect.catch((error) =>
234 updates.getState.pipe(
235 Effect.flatMap((state) =>
236 publishReport(
237 state,
238 { outcome: "failed", reason: error.message },
239 request.requestId,
240 ),
241 ),
242 Effect.as(false),
243 ),
244 ),
245 ),
246 Deferred.await(cancellation).pipe(Effect.as(false)),
247 );
248 if (!switched) return;
249 // A host already running the target only needed its track saved; installing a newer
250 // build here would restart it without the dialog having said so.
251 const state = yield* updates.getState;
252 if (request.targetVersion === state.currentVersion) {
253 yield* publishReport(state, { outcome: "up-to-date" }, request.requestId);
254 return;
255 }
256 }
257 const { latest, changes } = yield* updates.subscribe;
258 const disabledReason = Option.getOrNull(yield* updates.disabledReason);
259 let attempts: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
260 // State events can precede reservation release; re-enqueue refused actions so they retry after release.
261 const retries = yield* Queue.unbounded<DesktopUpdateState>();
262 const retryLater = (state: DesktopUpdateState) =>
263 Effect.sleep(ACTION_RETRY_DELAY).pipe(
264 Effect.andThen(Queue.offer(retries, state)),
265 Effect.asVoid,
266 Effect.forkScoped,
267 );
268
269 // A host leaving its build's track may need an older build, down to the checked release;
270 // the updater offers nothing below it.
271 const crossing = (state: DesktopUpdateState) =>
272 request.channel !== undefined &&
273 request.targetVersion !== undefined &&
274 desktopUpdateChannelOf(state.currentVersion) !== request.channel;
275 const step = Effect.fn("DesktopRemoteUpdates.step")(function* (
276 state: DesktopUpdateState,
277 ): Effect.fn.Return<boolean, never, Scope.Scope> {
278 const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);
279 switch (next.action) {
280 case "wait":
281 return false;
282 case "check":
283 attempts = { ...attempts, checks: attempts.checks + 1 };
284 yield* updates.check("remote-update", { allowDowngrade: crossing(state) }).pipe(
285 Effect.flatMap((result) => {
286 if (result.checked) return Effect.void;
287 attempts = { ...attempts, checks: attempts.checks - 1 };
288 return retryLater(state);
289 }),
290 Effect.forkScoped,
291 );
292 return false;
293 case "download":
294 attempts = { ...attempts, downloads: attempts.downloads + 1 };
295 yield* updates.download.pipe(
296 Effect.flatMap((result) => {
297 if (result.accepted) return Effect.void;
298 attempts = { ...attempts, downloads: attempts.downloads - 1 };
299 return retryLater(state);
300 }),
301 Effect.forkScoped,
302 );
303 return false;
304 case "install": {
305 // The download event fires before its action releases the
306 // updater reservation. Wait until the prepared install can
307 // be committed by the client in a separate RPC.
308 if (yield* updates.isActionActive) {
309 yield* retryLater(state);
310 return false;
311 }
312 if (state.downloadedVersion === null) {
313 yield* publishReport(
314 state,
315 {
316 outcome: "failed",
317 reason: "The desktop app lost the downloaded update.",
318 },
319 request.requestId,
320 );
321 return true;
322 }
323 yield* Ref.set(
324 preparedUpdateRef,
325 Option.some({
326 requestId: request.requestId,
327 channel: request.channel,
328 targetVersion: request.targetVersion,
329 downloadedVersion: state.downloadedVersion,
330 status: "prepared",
331 expiresAt:
332 (yield* Clock.currentTimeMillis) + Duration.toMillis(PREPARED_UPDATE_TTL),
333 }),
334 );
335 yield* publishReport(state, { outcome: "ready-to-install" }, request.requestId);
336 yield* logInfo("remote update prepared", { requestId: request.requestId });
337 return true;
338 }
339 case "done": {
340 // A switch that leaves the host on its old track, or below its checked release, did
341 // not reach it; a track-only host already at the release is done.
342 const done =
343 request.targetVersion !== undefined &&
344 next.outcome === "up-to-date" &&
345 (crossing(state) ||
346 compareSemverVersions(state.currentVersion, request.targetVersion) < 0)
347 ? {
348 outcome: "failed" as const,
349 reason: `The desktop app found no build of ${request.targetVersion}.`,
350 }
351 : next;
352 yield* publishReport(
353 state,
354 {
355 outcome: done.outcome,
356 ...(done.reason === undefined ? {} : { reason: done.reason }),
357 },
358 request.requestId,
359 );
360 yield* logInfo("remote update finished", {
361 requestId: request.requestId,
362 outcome: done.outcome,
363 reason: done.reason ?? null,
364 });
365 return true;
366 }
367 }
368 });
369
370 yield* Effect.raceFirst(
371 Effect.gen(function* () {
372 if (yield* step(latest)) return;
373 yield* Stream.merge(changes, Stream.fromQueue(retries)).pipe(
374 Stream.mapEffect(step),
375 Stream.takeUntil((done) => done),
376 Stream.runDrain,
377 );
378 }),
379 Deferred.await(cancellation),
380 );
381 }),
382 ).pipe(
383 Effect.ensuring(
384 Effect.all(
385 [
386 clearActiveRequest(request.requestId),
387 Ref.update(requestControlRef, (control) => ({
388 ...control,
389 active:
390 Option.isSome(control.active) &&
391 control.active.value.requestId === request.requestId
392 ? Option.none()
393 : control.active,
394 })),
395 ],
396 { discard: true },
397 ),
398 ),
399 Effect.catchCause((cause) =>
400 logError("remote update request failed unexpectedly", {
401 requestId: request.requestId,
402 cause: String(cause),
403 }),
404 ),
405 );
406
407 yield* Stream.runForEach(publisher.updateRequests, handleRequest).pipe(Effect.forkScoped);
408
409 yield* Stream.runForEach(publisher.updateCancellations, (cancellation) =>
410 Effect.gen(function* () {
411 const activeSignal = yield* Ref.modify(requestControlRef, (control) => {
412 if (
413 Option.isSome(control.active) &&
414 control.active.value.requestId === cancellation.requestId
415 ) {
416 return [Option.some(control.active.value.signal), control] as const;
417 }
418 return [
419 Option.none<Deferred.Deferred<void>>(),
420 {
421 ...control,
422 cancelledBeforeStart: [
423 ...control.cancelledBeforeStart.filter(
424 (requestId) => requestId !== cancellation.requestId,
425 ),
426 cancellation.requestId,
427 ],
428 },
429 ] as const;
430 });
431 if (Option.isSome(activeSignal)) {
432 yield* Deferred.succeed(activeSignal.value, undefined);
433 }
434 const matchedPrepared = yield* Ref.modify(preparedUpdateRef, (prepared) => {
435 if (Option.isNone(prepared) || prepared.value.requestId !== cancellation.requestId) {
436 return [false, prepared] as const;
437 }
438 return [true, prepared.value.status === "prepared" ? Option.none() : prepared] as const;
439 });
440 if (matchedPrepared) {
441 yield* Ref.update(requestControlRef, (control) => {
442 return {
443 ...control,
444 cancelledBeforeStart: control.cancelledBeforeStart.filter(
445 (requestId) => requestId !== cancellation.requestId,
446 ),
447 };
448 });
449 }
450 }),
451 ).pipe(Effect.forkScoped);
452
453 yield* Stream.runForEach(publisher.updateCommits, (commit) =>
454 Effect.gen(function* () {
455 const current = yield* updates.getState;
456 const now = yield* Clock.currentTimeMillis;
457 const claim = yield* Ref.modify(
458 preparedUpdateRef,
459 (prepared): readonly [CommitClaim, Option.Option<PreparedUpdate>] => {
460 if (
461 Option.isNone(prepared) ||
462 prepared.value.requestId !== commit.requestId ||
463 (prepared.value.status === "prepared" && prepared.value.expiresAt <= now)
464 ) {
465 return [{ _tag: "invalid" as const }, prepared] as const;
466 }
467 if (prepared.value.status === "failed") {
468 return [{ _tag: "failed" as const, prepared: prepared.value }, prepared] as const;
469 }
470 if (prepared.value.status === "committing") {
471 return [{ _tag: "committing" as const }, prepared] as const;
472 }
473 return [
474 { _tag: "claimed" as const, prepared: prepared.value },
475 Option.some({ ...prepared.value, status: "committing" as const }),
476 ] as const;
477 },
478 );
479 if (claim._tag === "invalid") {
480 yield* publishReport(
481 yield* updates.getState,
482 {
483 outcome: "failed",
484 reason: "This desktop update is no longer prepared.",
485 },
486 commit.requestId,
487 );
488 return;
489 }
490 if (claim._tag === "failed") {
491 yield* publishReport(
492 current,
493 {
494 outcome: "failed",
495 reason: claim.prepared.failureReason ?? "The desktop app failed to install the update.",
496 },
497 commit.requestId,
498 );
499 return;
500 }
501 if (claim._tag === "committing") {
502 return;
503 }
504 yield* Ref.set(activeRequestIdRef, Option.some(commit.requestId));
505 if (current.downloadedVersion !== claim.prepared.downloadedVersion) {
506 const reason = "This desktop update is no longer prepared.";
507 if (yield* recordPreparedFailure(commit.requestId, reason)) {
508 yield* publishReport(current, { outcome: "failed", reason }, commit.requestId);
509 }
510 return;
511 }
512 const result = yield* updates.installPrepared(claim.prepared.downloadedVersion);
513 if (
514 !result.accepted &&
515 result.state.downloadedVersion === claim.prepared.downloadedVersion &&
516 (yield* updates.isInstallActive)
517 ) {
518 // Join the existing install; reconnect and target-version checks prove its handoff.
519 yield* logInfo("remote update commit joining an in-progress install", {
520 requestId: commit.requestId,
521 });
522 return;
523 }
524 if (!result.accepted || result.failed) {
525 const reason = result.state.message ?? "The desktop app could not start the install.";
526 if (yield* recordPreparedFailure(commit.requestId, reason)) {
527 yield* publishReport(result.state, { outcome: "failed", reason }, commit.requestId);
528 }
529 return;
530 }
531 // Installation kills this backend; only transport loss followed by the target version proves handoff.
532 }).pipe(
533 Effect.ensuring(clearActiveRequest(commit.requestId)),
534 Effect.catchCause((cause) =>
535 logError("remote update commit failed unexpectedly", {
536 requestId: commit.requestId,
537 cause: String(cause),
538 }),
539 ),
540 ),
541 ).pipe(Effect.forkScoped);
542 });