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

main
tsx 400 lines 12.9 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import { AVAILABLE_CONNECTION_STATE } from "@t3tools/client-runtime/connection";
3 import {
4 nudgeReconnectDuringUpdateRestart,
5 serverUpdateStateAtom,
6 } from "@t3tools/client-runtime/state/server";
7 import { EnvironmentId, type ServerConfig } from "@t3tools/contracts";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Schema from "effect/Schema";
11 import * as Stream from "effect/Stream";
12 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
13 import { msg } from "gt-react";
14
15 import { APP_VERSION } from "~/branding";
16 import { environmentCatalog } from "~/connection/catalog";
17 import { m } from "~/i18n/messages";
18 import { appAtomRegistry } from "~/rpc/atomRegistry";
19 import { desktopUpdateStateAtom } from "~/state/desktopUpdate";
20 import { serverEnvironment } from "~/state/server";
21 import { resolveVersionMismatch } from "~/versionSkew";
22 import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
23 import { stackedThreadToast, toastManager } from "../ui/toast";
24 import {
25 closeFinishedUpdateRun,
26 getUpdateEverythingToastView,
27 isServerUpdateHandedOff,
28 type UpdateEverythingResult,
29 type UpdateEverythingRun,
30 type UpdateRunMachine,
31 } from "./updateEverything.logic";
32
33 const updateEverythingRunAtom = Atom.make<UpdateEverythingRun | null>(null).pipe(
34 Atom.keepAlive,
35 Atom.withLabel("update-everything-run"),
36 );
37
38 export function useUpdateEverythingRun(): UpdateEverythingRun | null {
39 return useAtomValue(updateEverythingRunAtom);
40 }
41
42 export function setUpdateEverythingRun(
43 update: (run: UpdateEverythingRun | null) => UpdateEverythingRun | null,
44 ): void {
45 appAtomRegistry.update(updateEverythingRunAtom, update);
46 }
47
48 function updateRunMachines(update: (machine: UpdateRunMachine) => UpdateRunMachine): void {
49 setUpdateEverythingRun(
50 (run) => run && closeFinishedUpdateRun({ ...run, machines: run.machines.map(update) }),
51 );
52 }
53
54 export function settleUpdateRunMachine(
55 environmentId: EnvironmentId,
56 failure: string | null,
57 {
58 serverUpdated = false,
59 providerFailure,
60 }: { readonly serverUpdated?: boolean; readonly providerFailure?: string | null } = {},
61 ): void {
62 updateRunMachines((machine) =>
63 machine.environmentId === environmentId
64 ? {
65 ...machine,
66 result: failure === null ? "done" : "failed",
67 failure,
68 ...(serverUpdated ? { server: null } : {}),
69 ...(providerFailure === undefined ? {} : { providerFailure }),
70 }
71 : machine,
72 );
73 }
74
75 function runsVersion(config: ServerConfig | null, targetVersion: string): boolean {
76 return (
77 config !== null &&
78 resolveVersionMismatch(config.environment.serverVersion, targetVersion) === null
79 );
80 }
81
82 export function retryFailedUpdateRunServers(
83 update: (
84 target: ServerUpdateTarget,
85 options: { readonly quiet: boolean },
86 ) => Promise<ServerUpdateOutcome>,
87 ): void {
88 const failed = (appAtomRegistry.get(updateEverythingRunAtom)?.machines ?? []).flatMap(
89 (machine) =>
90 machine.result === "failed" && machine.server !== null
91 ? [{ target: machine.server, providerFailure: machine.providerFailure }]
92 : [],
93 );
94 const pending: typeof failed = [];
95 for (const entry of failed) {
96 // The host rejects a same-version update; a server that came back on the target is done.
97 if (
98 runsVersion(
99 appAtomRegistry.get(serverEnvironment.configValueAtom(entry.target.environmentId)),
100 entry.target.targetVersion,
101 )
102 ) {
103 settleUpdateRunMachine(entry.target.environmentId, entry.providerFailure, {
104 serverUpdated: true,
105 });
106 } else {
107 pending.push(entry);
108 }
109 }
110 const targets = pending.map(({ target }) => target);
111 const retried = new Set(targets.map((target) => target.environmentId));
112 const startedAt = Date.now();
113 updateRunMachines((machine) =>
114 retried.has(machine.environmentId)
115 ? { ...machine, result: null, failure: null, startedAt }
116 : machine,
117 );
118 for (const { target, providerFailure } of pending) {
119 void update(target, { quiet: true }).then((outcome) =>
120 settleUpdateRunMachine(
121 target.environmentId,
122 outcome.status === "updated"
123 ? providerFailure
124 : outcome.status === "failed"
125 ? outcome.message
126 : m(msg("Could not start the update")),
127 { serverUpdated: outcome.status === "updated" },
128 ),
129 );
130 }
131 }
132
133 export function dismissSettledUpdateRunMachines(): void {
134 setUpdateEverythingRun(
135 (run) =>
136 run &&
137 closeFinishedUpdateRun({
138 ...run,
139 machines: run.machines.filter((machine) => machine.result === null),
140 }),
141 );
142 }
143
144 export function waitForServerUpdateHandoff(
145 environmentId: EnvironmentId,
146 finished: Promise<unknown>,
147 ): Promise<void> {
148 return new Promise((resolve) => {
149 let done = false;
150 const finish = () => {
151 if (done) return;
152 done = true;
153 queueMicrotask(() => unsubscribe());
154 resolve();
155 };
156 const unsubscribe = appAtomRegistry.subscribe(
157 serverEnvironment.updateStateAtom(environmentId),
158 (state) => {
159 if (isServerUpdateHandedOff(state)) finish();
160 },
161 { immediate: true },
162 );
163 void finished.then(finish, finish);
164 });
165 }
166
167 let decideRestart: ((restart: boolean) => void) | null = null;
168
169 export function waitForUpdateRestart(delayMs: number): Promise<boolean> {
170 return new Promise((resolve) => {
171 const decide = (restart: boolean) => {
172 clearTimeout(timer);
173 decideRestart = null;
174 resolve(restart);
175 };
176 const timer = setTimeout(() => decide(true), delayMs);
177 decideRestart = decide;
178 setUpdateEverythingRun(
179 (run) => run && { ...run, phase: "countdown", restartAt: Date.now() + delayMs },
180 );
181 });
182 }
183
184 export function postponeUpdateRestart(): void {
185 decideRestart?.(false);
186 }
187
188 const SAVED_RESULT_KEY = "t3code:update-everything-result:v1";
189 const SAVED_RESULT_MAX_AGE_MS = 10 * 60 * 1000;
190 // Covers a background service's 30-minute trial start, like the server update itself.
191 const HANDOFF_TIMEOUT_MS = 32 * 60 * 1000;
192
193 const HandedOffServer = Schema.Struct({
194 environmentId: EnvironmentId,
195 label: Schema.String,
196 targetVersion: Schema.String,
197 startedAt: Schema.Number,
198 });
199 type HandedOffServer = typeof HandedOffServer.Type;
200
201 const SavedResult = Schema.Struct({
202 savedAt: Schema.Number,
203 localVersion: Schema.NullOr(Schema.String),
204 updatedServers: Schema.Number,
205 updatedProviders: Schema.Number,
206 failures: Schema.Array(Schema.String),
207 handedOff: Schema.optional(Schema.Array(HandedOffServer)),
208 });
209 const decodeSavedResult = Schema.decodeUnknownOption(Schema.fromJsonString(SavedResult));
210
211 export function saveUpdateEverythingResult(result: UpdateEverythingResult): void {
212 const run = appAtomRegistry.get(updateEverythingRunAtom);
213 const handedOff = (run?.machines ?? []).flatMap((machine): HandedOffServer[] => {
214 if (machine.result !== null) return [];
215 const state = appAtomRegistry.get(serverEnvironment.updateStateAtom(machine.environmentId));
216 // Only the desktop-managed server's update state knows its own feed version.
217 const targetVersion =
218 machine.handedOffVersion ??
219 (state.status === "running" ? state.targetVersion : machine.server?.targetVersion);
220 if (targetVersion === undefined) return [];
221 return [
222 {
223 environmentId: machine.environmentId,
224 label: machine.label,
225 targetVersion,
226 startedAt: machine.startedAt,
227 },
228 ];
229 });
230 try {
231 window.localStorage.setItem(
232 SAVED_RESULT_KEY,
233 JSON.stringify({
234 savedAt: Date.now(),
235 localVersion: result.localVersion,
236 updatedServers: result.updatedServers,
237 updatedProviders: result.updatedProviders,
238 failures: result.failures,
239 handedOff,
240 } satisfies typeof SavedResult.Type),
241 );
242 } catch {}
243 }
244
245 export function clearSavedUpdateEverythingResult(): void {
246 try {
247 window.localStorage.removeItem(SAVED_RESULT_KEY);
248 } catch {}
249 }
250
251 function takeSavedUpdateEverythingResult(): typeof SavedResult.Type | null {
252 try {
253 const raw = window.localStorage.getItem(SAVED_RESULT_KEY);
254 if (raw === null) return null;
255 window.localStorage.removeItem(SAVED_RESULT_KEY);
256 return Option.getOrNull(
257 Option.filter(
258 decodeSavedResult(raw),
259 (saved) => Date.now() - saved.savedAt < SAVED_RESULT_MAX_AGE_MS,
260 ),
261 );
262 } catch {
263 return null;
264 }
265 }
266
267 export function showUpdateEverythingResult(result: UpdateEverythingResult): void {
268 const view = getUpdateEverythingToastView(result, APP_VERSION);
269 if (!view) return;
270 toastManager.add(
271 stackedThreadToast({
272 type: view.type,
273 title: view.title,
274 ...(view.description
275 ? { description: <span className="whitespace-pre-line">{view.description}</span> }
276 : {}),
277 }),
278 );
279 }
280
281 function followHandedOffServers(servers: ReadonlyArray<HandedOffServer>): void {
282 if (servers.length === 0) return;
283 setUpdateEverythingRun(() => ({
284 localVersion: null,
285 phase: "servers",
286 restartAt: null,
287 machines: servers.map((server) => ({
288 environmentId: server.environmentId,
289 label: server.label,
290 updatesProviders: false,
291 server: null,
292 handedOffVersion: server.targetVersion,
293 startedAt: server.startedAt,
294 result: null,
295 failure: null,
296 providerFailure: null,
297 })),
298 }));
299 let remaining = servers.length;
300 let updatedServers = 0;
301 const failures: string[] = [];
302 for (const server of servers) {
303 // Update state is in memory, so restore it or the relaunched app offers this server's update again.
304 const stateAtom = serverUpdateStateAtom(server.environmentId);
305 appAtomRegistry.set(stateAtom, {
306 status: "running",
307 stage: "resuming",
308 fromVersion:
309 appAtomRegistry.get(serverEnvironment.configValueAtom(server.environmentId))?.environment
310 .serverVersion ?? server.targetVersion,
311 targetVersion: server.targetVersion,
312 });
313 // Nothing observes the atom until the UI mounts, and the registry drops unobserved atoms.
314 const releaseState = appAtomRegistry.mount(stateAtom);
315 let settled = false;
316 const settle = (failure: string | null) => {
317 if (settled) return;
318 settled = true;
319 clearTimeout(timer);
320 stopReconnectNudge();
321 queueMicrotask(() => unsubscribe());
322 appAtomRegistry.set(stateAtom, { status: "idle" });
323 releaseState();
324 settleUpdateRunMachine(server.environmentId, failure);
325 if (failure === null) updatedServers += 1;
326 else failures.push(m(msg("{machine}: {failure}", { machine: server.label, failure })));
327 remaining -= 1;
328 if (remaining === 0) {
329 showUpdateEverythingResult({
330 localVersion: null,
331 updatedServers,
332 updatedProviders: 0,
333 failures,
334 restarting: [],
335 });
336 }
337 };
338 const timer = setTimeout(
339 () =>
340 settle(
341 m(msg("Not back after {minutes} minutes", { minutes: HANDOFF_TIMEOUT_MS / 60_000 })),
342 ),
343 server.startedAt + HANDOFF_TIMEOUT_MS - Date.now(),
344 );
345 const stopReconnectNudge = Effect.runCallback(
346 nudgeReconnectDuringUpdateRestart({
347 stateChanges: AtomRegistry.toStream(
348 appAtomRegistry,
349 environmentCatalog.stateAtom(server.environmentId),
350 ).pipe(
351 Stream.map((state) => AsyncResult.getOrElse(state, () => AVAILABLE_CONNECTION_STATE)),
352 ),
353 retryNow: environmentCatalog.retryNow
354 .run(appAtomRegistry, server.environmentId)
355 .pipe(Effect.ignoreCause),
356 }),
357 );
358 const unsubscribe = appAtomRegistry.subscribe(
359 serverEnvironment.configValueAtom(server.environmentId),
360 (config) => {
361 if (runsVersion(config, server.targetVersion)) settle(null);
362 },
363 { immediate: true },
364 );
365 }
366 }
367
368 /** Reports, once per launch, how the update run that restarted the app ended. */
369 export function startDesktopUpdateLaunchNotice(): () => void {
370 const saved = takeSavedUpdateEverythingResult();
371 if (saved) {
372 const handedOff = saved.handedOff ?? [];
373 showUpdateEverythingResult({ ...saved, restarting: handedOff.map((server) => server.label) });
374 followHandedOffServers(handedOff);
375 }
376
377 let notifiedNotAppliedVersion: string | null = null;
378 return appAtomRegistry.subscribe(
379 desktopUpdateStateAtom,
380 (result) => {
381 const notAppliedVersion =
382 AsyncResult.getOrElse(result, () => null)?.notAppliedVersion ?? null;
383 if (notAppliedVersion === null || notifiedNotAppliedVersion === notAppliedVersion) return;
384 notifiedNotAppliedVersion = notAppliedVersion;
385 toastManager.add(
386 stackedThreadToast({
387 type: "error",
388 title: m(msg("Update did not apply")),
389 description: m(
390 msg("T3 Code is still on {current}. Install {version} again from the update button.", {
391 current: APP_VERSION,
392 version: notAppliedVersion,
393 }),
394 ),
395 }),
396 );
397 },
398 { immediate: true },
399 );
400 }