Open History to see the last commit
1import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
2import type { EnvironmentId, ServerConfig } from "@t3tools/contracts";
3import { cliReleaseChannelOf } from "@t3tools/shared/cliRelease";
4
5import {
6 resolveServerSelfUpdateCapability,
7 resolveVersionMismatch,
8 supportsDesktopAppUpdate,
9 supportsServerUpdateThreadContinuation,
10} from "~/versionSkew";
11import type { ServerUpdateTarget } from "../ServerUpdateAction";
12
13export interface UpdateEverythingMachine {
14 readonly environmentId: EnvironmentId;
15 readonly label: string;
16 readonly serverConfig: {
17 readonly environment: ServerConfig["environment"];
18 readonly settings: Pick<ServerConfig["settings"], "continueThreadsAfterServerUpdate">;
19 } | null;
20 readonly connected: boolean;
21 /** Served by the desktop app this client runs in (the primary backend or a
22 local WSL backend). Its server updates when the app installs. */
23 readonly hostedByThisApp: boolean;
24 /** The session holds the scope a server update needs. */
25 readonly canMaintain: boolean;
26 readonly updateState: ServerUpdateState;
27}
28
29/** A server that restarts during a run. */
30export interface RestartingMachine {
31 readonly environmentId: EnvironmentId;
32 /** The server resumes interrupted threads after it restarts. */
33 readonly continuesThreads: boolean;
34}
35
36/**
37 * The servers a run restarts: each server it updates, and the servers this app
38 * hosts when this app installs. Provider updates restart nothing.
39 */
40export function collectRestartingMachines(
41 machines: ReadonlyArray<UpdateEverythingMachine>,
42 servers: ReadonlyArray<Pick<ServerUpdateTarget, "environmentId">>,
43 installsLocal: boolean,
44): RestartingMachine[] {
45 const updated = new Set(servers.map((server) => server.environmentId));
46 return machines.flatMap((machine) => {
47 const config = machine.serverConfig;
48 if (
49 config === null ||
50 !machine.connected ||
51 !(updated.has(machine.environmentId) || (installsLocal && machine.hostedByThisApp))
52 ) {
53 return [];
54 }
55 return [
56 {
57 environmentId: machine.environmentId,
58 continuesThreads:
59 config.environment.capabilities.threadRestartContinuation === true &&
60 config.settings.continueThreadsAfterServerUpdate === true,
61 },
62 ];
63 });
64}
65
66/**
67 * The servers that "update everything" moves to `targetVersion`: connected,
68 * permitted, able to update over RPC, and behind the target. Two kinds stay
69 * out. Servers this app hosts would relaunch the app mid-run, and the app's
70 * own install updates them anyway. A service on another release channel
71 * stays there; a desktop-managed server follows its own app's update feed, so
72 * the channel rule does not apply to it.
73 */
74export function collectServerUpdateTargets(
75 machines: ReadonlyArray<UpdateEverythingMachine>,
76 targetVersion: string,
77): ServerUpdateTarget[] {
78 return machines.flatMap((machine) => {
79 const config = machine.serverConfig;
80 if (
81 config === null ||
82 !machine.connected ||
83 machine.hostedByThisApp ||
84 !machine.canMaintain ||
85 machine.updateState.status === "running"
86 ) {
87 return [];
88 }
89 const selfUpdate = resolveServerSelfUpdateCapability(config);
90 const desktopAppUpdate = supportsDesktopAppUpdate(config);
91 if (selfUpdate === null || (selfUpdate === "desktop-managed" && !desktopAppUpdate)) {
92 return [];
93 }
94 const serverVersion = config.environment.serverVersion;
95 if (resolveVersionMismatch(serverVersion, targetVersion) === null) return [];
96 if (
97 selfUpdate !== "desktop-managed" &&
98 cliReleaseChannelOf(serverVersion) !== cliReleaseChannelOf(targetVersion)
99 ) {
100 return [];
101 }
102 return [
103 {
104 environmentId: machine.environmentId,
105 serverLabel: machine.label,
106 selfUpdate,
107 installation: config.environment.capabilities.serverInstallation,
108 desktopAppUpdate,
109 threadContinuation: supportsServerUpdateThreadContinuation(config),
110 continueThreadsAfterServerUpdate: config.settings.continueThreadsAfterServerUpdate ?? false,
111 targetVersion,
112 },
113 ];
114 });
115}
116
117export interface UpdateEverythingSteps {
118 /** Downloads this app's update. Resolves true when it is ready to install. */
119 readonly downloadLocal?: () => Promise<boolean>;
120 readonly updateProviders: () => Promise<void>;
121 readonly updateServers: () => Promise<void>;
122 /** Installs this app's update. The relaunch ends the run. */
123 readonly installLocal?: () => Promise<void>;
124}
125
126/**
127 * Runs one "update everything" pass. Providers
128 * finish before any server restarts, so no install is cut off. The local download runs alongside the
129 * remote work. This app installs last because its relaunch ends the run; a
130 * failed download skips only that install. Steps report their own results.
131 */
132export async function runUpdateEverything(steps: UpdateEverythingSteps): Promise<void> {
133 const [localReady] = await Promise.all([
134 steps.downloadLocal?.() ?? Promise.resolve(true),
135 steps.updateProviders().then(steps.updateServers),
136 ]);
137 if (localReady) await steps.installLocal?.();
138}
139
140export interface UpdateEverythingPlan {
141 /** The version this desktop app installs, or null when it is not updating. */
142 readonly localVersion: string | null;
143 readonly servers: ReadonlyArray<
144 Pick<ServerUpdateTarget, "environmentId" | "serverLabel" | "selfUpdate" | "targetVersion">
145 >;
146 readonly providerMachines: ReadonlyArray<{
147 readonly environmentId: EnvironmentId;
148 readonly label: string;
149 /** Display names of the outdated providers on that machine. */
150 readonly providers: ReadonlyArray<string>;
151 }>;
152}
153
154function countLabel(count: number, noun: string): string | null {
155 return count === 0 ? null : `${count} ${noun}${count === 1 ? "" : "s"}`;
156}
157
158function joinList(parts: ReadonlyArray<string>): string {
159 if (parts.length <= 2) return parts.join(" and ");
160 return `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}`;
161}
162
163/**
164 * Text for the sidebar tooltip and the confirmation. `summary` reads like
165 * "Update this app, 2 servers, and 3 providers". `lines` has one entry per
166 * machine, this app first, such as "alvin: server to 0.0.50, Codex, Claude".
167 */
168export function describeUpdateEverything(plan: UpdateEverythingPlan): {
169 readonly summary: string;
170 readonly lines: ReadonlyArray<string>;
171} {
172 const providerCount = plan.providerMachines.reduce(
173 (count, machine) => count + machine.providers.length,
174 0,
175 );
176 const summary = `Update ${joinList(
177 [
178 plan.localVersion ? "this app" : null,
179 countLabel(plan.servers.length, "server"),
180 countLabel(providerCount, "provider"),
181 ].filter((part) => part !== null),
182 )}`;
183
184 const machines = new Map<EnvironmentId, { label: string; items: string[] }>();
185 const itemsFor = (environmentId: EnvironmentId, label: string) => {
186 const existing = machines.get(environmentId);
187 if (existing) return existing.items;
188 const items: string[] = [];
189 machines.set(environmentId, { label, items });
190 return items;
191 };
192 for (const server of plan.servers) {
193 // A desktop-managed server installs whatever its own app's update feed
194 // offers, so it has no target version to show.
195 itemsFor(server.environmentId, server.serverLabel).push(
196 server.selfUpdate === "desktop-managed"
197 ? "desktop app update"
198 : `server to ${server.targetVersion}`,
199 );
200 }
201 for (const machine of plan.providerMachines) {
202 itemsFor(machine.environmentId, machine.label).push(...machine.providers);
203 }
204
205 return {
206 summary,
207 lines: [
208 ...(plan.localVersion ? [`This app: ${plan.localVersion}, restarts last`] : []),
209 ...Array.from(machines.values(), ({ label, items }) => `${label}: ${items.join(", ")}`),
210 ],
211 };
212}