Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts";
3import { Atom } from "effect/reactivity";
4import { useMemo } from "react";
5
6import { APP_VERSION } from "~/branding";
7import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
8import { isElectron } from "~/env";
9import { useEnvironments } from "~/state/environments";
10import { useNpmReleasePublished } from "~/state/npmRelease";
11import { serverEnvironment } from "~/state/server";
12import { environmentSession } from "~/state/session";
13import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification.logic";
14import { useProviderUpdates } from "../ProviderUpdatesAction";
15import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction";
16import {
17 closeFinishedUpdateRun,
18 collectRestartingMachines,
19 collectServerUpdateTargets,
20 collectUpdateEverythingResult,
21 describeUpdateEverything,
22 runUpdateEverything,
23 type SkippedMachine,
24 type UpdateRunMachine,
25} from "./updateEverything.logic";
26import {
27 clearSavedUpdateEverythingResult,
28 saveUpdateEverythingResult,
29 setUpdateEverythingRun,
30 settleUpdateRunMachine,
31 showUpdateEverythingResult,
32 waitForServerUpdateHandoff,
33 waitForUpdateRestart,
34} from "./updateEverythingRun";
35
36/** How long this app counts down before it relaunches, so the user can postpone it. */
37const UPDATE_RESTART_DELAY_MS = 5_000;
38
39/** Where this app's own download or install reports a failure. */
40export type ReportLocalUpdateError = (title: string, description: string) => void;
41
42/**
43 * The remote half of the sidebar update button: outdated providers on every
44 * connected machine, and servers behind the version this client runs or is
45 * about to install (`localUpdateVersion`). Servers that install from npm appear
46 * only once npm confirms that version. `run` performs the whole pass, including
47 * this app's own download and install when given. It updates quietly, tracks
48 * each machine in the run state, and reports one summary toast at the end.
49 * This app relaunches once every server restarts into its update, after a
50 * short countdown the user can postpone. The summary then waits for the
51 * relaunch, and servers still restarting are followed after it.
52 */
53export function useUpdateEverything(localUpdateVersion: string | null) {
54 const targetVersion = localUpdateVersion ?? APP_VERSION;
55 const { environments } = useEnvironments();
56 const machinesAtom = useMemo(
57 () =>
58 Atom.make((get) =>
59 environments.map((environment) => ({
60 environmentId: environment.environmentId,
61 label: environment.label,
62 serverConfig: environment.serverConfig,
63 connected: environment.connection.phase === "connected",
64 hostedByThisApp:
65 isElectron &&
66 (environment.entry.target._tag === "PrimaryConnectionTarget" ||
67 isDesktopLocalConnectionTarget(environment.entry.target)),
68 canMaintain: canUpdateServer(
69 get(environmentSession.sessionStateAtom(environment.environmentId)),
70 ),
71 updateState: get(serverEnvironment.updateStateAtom(environment.environmentId)),
72 })),
73 ),
74 [environments],
75 );
76 const machines = useAtomValue(machinesAtom);
77 const { targets: behindServers, skipped: unreachable } = collectServerUpdateTargets(
78 machines,
79 targetVersion,
80 );
81 // A desktop-managed server installs from its own app's update feed, so only
82 // servers that download t3 from npm wait for npm to publish the version.
83 const needsNpm = behindServers.some((server) => server.selfUpdate !== "desktop-managed");
84 const published = useNpmReleasePublished(needsNpm ? targetVersion : null);
85 const servers = published
86 ? behindServers
87 : behindServers.filter((server) => server.selfUpdate === "desktop-managed");
88 const skipped: ReadonlyArray<SkippedMachine> = [
89 ...unreachable,
90 ...behindServers
91 .filter((server) => !servers.includes(server))
92 .map((server) => ({
93 environmentId: server.environmentId,
94 label: server.serverLabel,
95 reason: `t3@${targetVersion} is not on npm yet`,
96 })),
97 ];
98 const restarts = collectRestartingMachines(machines, servers, localUpdateVersion !== null);
99 const providers = useProviderUpdates();
100 const updateServer = useServerUpdate();
101
102 const { summary, lines } = describeUpdateEverything({
103 localVersion: localUpdateVersion,
104 servers,
105 providerMachines: providers.machines.map((machine) => ({
106 environmentId: machine.environmentId,
107 label: machine.label,
108 providers: machine.candidates.map(
109 (candidate) => PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver,
110 ),
111 })),
112 });
113
114 return {
115 hasUpdates: servers.length > 0 || providers.machines.length > 0,
116 /** Short label for the tooltip and the confirmation title. */
117 summary,
118 /** One line per machine, for the confirmation. */
119 lines,
120 /** The servers this run restarts, which stops their running threads. */
121 restarts,
122 /** Behind machines the run leaves alone, with the reason. */
123 skipped,
124 /** Runs the pass. `installLocal` resolves true when this app is relaunching.
125 Both report failures to the pass, which lists them in its summary. */
126 run: async ({
127 downloadLocal,
128 installLocal,
129 }: {
130 downloadLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
131 installLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
132 }) => {
133 const localFailures: Array<string> = [];
134 const reportLocalError: ReportLocalUpdateError = (title, description) => {
135 localFailures.push(`${title}: ${description}`);
136 };
137 const startedAt = Date.now();
138 const machinesById = new Map<UpdateRunMachine["environmentId"], UpdateRunMachine>();
139 for (const machine of providers.machines) {
140 machinesById.set(machine.environmentId, {
141 environmentId: machine.environmentId,
142 label: machine.label,
143 updatesProviders: true,
144 server: null,
145 handedOffVersion: null,
146 startedAt,
147 result: null,
148 failure: null,
149 providerFailure: null,
150 });
151 }
152 for (const server of servers) {
153 const existing = machinesById.get(server.environmentId);
154 machinesById.set(server.environmentId, {
155 environmentId: server.environmentId,
156 label: server.serverLabel,
157 updatesProviders: existing?.updatesProviders ?? false,
158 server,
159 handedOffVersion: null,
160 startedAt,
161 result: null,
162 failure: null,
163 providerFailure: null,
164 });
165 }
166 const localVersion = installLocal ? localUpdateVersion : null;
167 setUpdateEverythingRun(() => ({
168 localVersion,
169 phase: "providers",
170 restartAt: null,
171 machines: Array.from(machinesById.values()),
172 }));
173 const providerFailures = new Map<UpdateRunMachine["environmentId"], string>();
174 const finishedServers: Array<{ label: string; outcome: ServerUpdateOutcome }> = [];
175 try {
176 const outcome = await runUpdateEverything({
177 ...(downloadLocal ? { downloadLocal: () => downloadLocal(reportLocalError) } : {}),
178 updateProviders: async () => {
179 const runs = await providers.updateAll({ quiet: true });
180 const outcomes = runs.map((run) => {
181 const runOutcome = getProviderUpdateRunOutcome(run);
182 // An interrupted update did not finish either, so its row is not "done".
183 if (runOutcome.status !== "updated") {
184 providerFailures.set(
185 run.environmentId,
186 runOutcome.status === "failed" ? runOutcome.line : "Provider update interrupted",
187 );
188 }
189 return runOutcome;
190 });
191 for (const machine of machinesById.values()) {
192 if (machine.server === null) {
193 settleUpdateRunMachine(
194 machine.environmentId,
195 providerFailures.get(machine.environmentId) ?? null,
196 );
197 }
198 }
199 const serversStartedAt = Date.now();
200 setUpdateEverythingRun(
201 (run) =>
202 run && {
203 ...run,
204 phase: "servers",
205 machines: run.machines.map((machine) =>
206 machine.server === null ? machine : { ...machine, startedAt: serversStartedAt },
207 ),
208 },
209 );
210 return outcomes;
211 },
212 updateServers: async () => {
213 const runs = servers.map(async (server) => {
214 const serverOutcome = await updateServer(server, { quiet: true });
215 settleUpdateRunMachine(
216 server.environmentId,
217 serverOutcome.status === "failed"
218 ? serverOutcome.message
219 : (providerFailures.get(server.environmentId) ?? null),
220 {
221 serverUpdated: serverOutcome.status !== "failed",
222 providerFailure: providerFailures.get(server.environmentId) ?? null,
223 },
224 );
225 const finished = { label: server.serverLabel, outcome: serverOutcome };
226 finishedServers.push(finished);
227 return finished;
228 });
229 // Once a server restarts into its update it finishes on its own,
230 // so this app does not wait for it to come back.
231 await Promise.all(
232 servers.map((server, index) =>
233 waitForServerUpdateHandoff(server.environmentId, runs[index]!),
234 ),
235 );
236 return runs;
237 },
238 });
239 const result = (finished: ReadonlyArray<{ label: string; outcome: ServerUpdateOutcome }>) =>
240 collectUpdateEverythingResult({
241 localVersion: null,
242 localFailures,
243 servers: finished,
244 providers: outcome.providers,
245 });
246 if (outcome.localReady && installLocal) {
247 if (await waitForUpdateRestart(UPDATE_RESTART_DELAY_MS)) {
248 setUpdateEverythingRun(
249 (run) => run && { ...run, phase: "installing", restartAt: null },
250 );
251 saveUpdateEverythingResult({ ...result(finishedServers), localVersion });
252 if (await installLocal(reportLocalError)) return;
253 clearSavedUpdateEverythingResult();
254 }
255 }
256 // This app is not relaunching, so the pass waits for every server.
257 setUpdateEverythingRun(
258 (run) =>
259 run &&
260 closeFinishedUpdateRun({
261 ...run,
262 phase: "servers",
263 restartAt: null,
264 localVersion: null,
265 }),
266 );
267 showUpdateEverythingResult(result(await Promise.all(outcome.servers)));
268 } catch (error) {
269 setUpdateEverythingRun(() => null);
270 throw error;
271 }
272 },
273 };
274}