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