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, useServerUpdate } from "../ServerUpdateAction";
16import {
17 collectRestartingMachines,
18 collectServerUpdateTargets,
19 collectUpdateEverythingResult,
20 describeUpdateEverything,
21 runUpdateEverything,
22 type SkippedMachine,
23 type UpdateRunMachine,
24} from "./updateEverything.logic";
25import {
26 clearSavedUpdateEverythingResult,
27 saveUpdateEverythingResult,
28 setUpdateEverythingRun,
29 settleUpdateRunMachine,
30 showUpdateEverythingResult,
31} from "./updateEverythingRun";
32
33/** Where this app's own download or install reports a failure. */
34export type ReportLocalUpdateError = (title: string, description: string) => void;
35
36/**
37 * The remote half of the sidebar update button: outdated providers on every
38 * connected machine, and servers behind the version this client runs or is
39 * about to install (`localUpdateVersion`). Servers that install from npm appear
40 * only once npm confirms that version. `run` performs the whole pass, including
41 * this app's own download and install when given. It updates quietly, tracks
42 * each machine in the run state, and reports one summary toast at the end.
43 * When this app installs, the summary waits for the relaunch.
44 */
45export function useUpdateEverything(localUpdateVersion: string | null) {
46 const targetVersion = localUpdateVersion ?? APP_VERSION;
47 const { environments } = useEnvironments();
48 const machinesAtom = useMemo(
49 () =>
50 Atom.make((get) =>
51 environments.map((environment) => ({
52 environmentId: environment.environmentId,
53 label: environment.label,
54 serverConfig: environment.serverConfig,
55 connected: environment.connection.phase === "connected",
56 hostedByThisApp:
57 isElectron &&
58 (environment.entry.target._tag === "PrimaryConnectionTarget" ||
59 isDesktopLocalConnectionTarget(environment.entry.target)),
60 canMaintain: canUpdateServer(
61 get(environmentSession.sessionStateAtom(environment.environmentId)),
62 ),
63 updateState: get(serverEnvironment.updateStateAtom(environment.environmentId)),
64 })),
65 ),
66 [environments],
67 );
68 const machines = useAtomValue(machinesAtom);
69 const { targets: behindServers, skipped: unreachable } = collectServerUpdateTargets(
70 machines,
71 targetVersion,
72 );
73 // A desktop-managed server installs from its own app's update feed, so only
74 // servers that download t3 from npm wait for npm to publish the version.
75 const needsNpm = behindServers.some((server) => server.selfUpdate !== "desktop-managed");
76 const published = useNpmReleasePublished(needsNpm ? targetVersion : null);
77 const servers = published
78 ? behindServers
79 : behindServers.filter((server) => server.selfUpdate === "desktop-managed");
80 const skipped: ReadonlyArray<SkippedMachine> = [
81 ...unreachable,
82 ...behindServers
83 .filter((server) => !servers.includes(server))
84 .map((server) => ({
85 environmentId: server.environmentId,
86 label: server.serverLabel,
87 reason: `t3@${targetVersion} is not on npm yet`,
88 })),
89 ];
90 const restarts = collectRestartingMachines(machines, servers, localUpdateVersion !== null);
91 const providers = useProviderUpdates();
92 const updateServer = useServerUpdate();
93
94 const { summary, lines } = describeUpdateEverything({
95 localVersion: localUpdateVersion,
96 servers,
97 providerMachines: providers.machines.map((machine) => ({
98 environmentId: machine.environmentId,
99 label: machine.label,
100 providers: machine.candidates.map(
101 (candidate) => PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver,
102 ),
103 })),
104 });
105
106 return {
107 hasUpdates: servers.length > 0 || providers.machines.length > 0,
108 /** Short label for the tooltip and the confirmation title. */
109 summary,
110 /** One line per machine, for the confirmation. */
111 lines,
112 /** The servers this run restarts, which stops their running threads. */
113 restarts,
114 /** Behind machines the run leaves alone, with the reason. */
115 skipped,
116 /** Runs the pass. `installLocal` resolves true when this app is relaunching.
117 Both report failures to the pass, which lists them in its summary. */
118 run: async ({
119 downloadLocal,
120 installLocal,
121 }: {
122 downloadLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
123 installLocal?: (reportError: ReportLocalUpdateError) => Promise<boolean>;
124 }) => {
125 const localFailures: Array<string> = [];
126 const reportLocalError: ReportLocalUpdateError = (title, description) => {
127 localFailures.push(`${title}: ${description}`);
128 };
129 const machinesById = new Map<UpdateRunMachine["environmentId"], UpdateRunMachine>();
130 for (const machine of providers.machines) {
131 machinesById.set(machine.environmentId, {
132 environmentId: machine.environmentId,
133 label: machine.label,
134 updatesProviders: true,
135 updatesServer: false,
136 result: null,
137 });
138 }
139 for (const server of servers) {
140 const existing = machinesById.get(server.environmentId);
141 machinesById.set(server.environmentId, {
142 environmentId: server.environmentId,
143 label: server.serverLabel,
144 updatesProviders: existing?.updatesProviders ?? false,
145 updatesServer: true,
146 result: null,
147 });
148 }
149 const localVersion = installLocal ? localUpdateVersion : null;
150 setUpdateEverythingRun(() => ({
151 localVersion,
152 phase: "providers",
153 machines: Array.from(machinesById.values()),
154 }));
155 const failedProviderMachines = new Set<UpdateRunMachine["environmentId"]>();
156 try {
157 const outcome = await runUpdateEverything({
158 ...(downloadLocal ? { downloadLocal: () => downloadLocal(reportLocalError) } : {}),
159 updateProviders: async () => {
160 const runs = await providers.updateAll({ quiet: true });
161 const outcomes = runs.map((run) => {
162 const runOutcome = getProviderUpdateRunOutcome(run);
163 // An interrupted update did not finish either, so its row is not "done".
164 if (runOutcome.status !== "updated") failedProviderMachines.add(run.environmentId);
165 return runOutcome;
166 });
167 for (const machine of machinesById.values()) {
168 if (!machine.updatesServer) {
169 settleUpdateRunMachine(
170 machine.environmentId,
171 failedProviderMachines.has(machine.environmentId),
172 );
173 }
174 }
175 setUpdateEverythingRun((run) => run && { ...run, phase: "servers" });
176 return outcomes;
177 },
178 updateServers: () =>
179 Promise.all(
180 servers.map(async (server) => {
181 const serverOutcome = await updateServer(server, { quiet: true });
182 settleUpdateRunMachine(
183 server.environmentId,
184 serverOutcome.status === "failed" ||
185 failedProviderMachines.has(server.environmentId),
186 );
187 return { label: server.serverLabel, outcome: serverOutcome };
188 }),
189 ),
190 });
191 const result = () =>
192 collectUpdateEverythingResult({
193 localVersion: null,
194 localFailures,
195 servers: outcome.servers,
196 providers: outcome.providers,
197 });
198 if (outcome.localReady && installLocal) {
199 setUpdateEverythingRun((run) => run && { ...run, phase: "installing" });
200 saveUpdateEverythingResult({ ...result(), localVersion });
201 if (await installLocal(reportLocalError)) return;
202 clearSavedUpdateEverythingResult();
203 }
204 showUpdateEverythingResult(result());
205 } finally {
206 setUpdateEverythingRun(() => null);
207 }
208 },
209 };
210}