Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ServerUpdateAction.tsx

345 lines11.1 KB

1import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
2import type { ServerUpdateStage, ServerUpdateState } from "@t3tools/client-runtime/state/server";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import { CircleArrowUpIcon } from "lucide-react";
8import { type ComponentProps, useRef, useState } from "react";
9​
10import { requestConfirmDialog } from "~/confirmDialog";
11import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
12import { useEnvironmentSettings } from "~/hooks/useSettings";
13import { serverEnvironment, updateOutdatedServer } from "~/state/server";
14import { useAtomCommand } from "~/state/use-atom-command";
15import { manualServerUpdateCommand } from "~/versionSkew";
16import { Button } from "./ui/button";
17import { toastManager } from "./ui/toast";
18import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
19​
20// The wire "installing" stage is a sub-second launcher handoff, so the UI
21// folds it into the download phase; everything after the handoff is the
22// restart the user is actually waiting through.
23const UPDATE_STAGE_LABELS: Record<ServerUpdateStage, string> = {
24 downloading: "Downloading…",
25 installing: "Downloading…",
26 resuming: "Restarting…",
27};
28const pendingUpdateEnvironmentIds = new Set<EnvironmentId>();
29​
30export function serverUpdateStageLabel(stage: ServerUpdateStage): string {
31 return UPDATE_STAGE_LABELS[stage];
33​
34function updateFailureMessage(error: unknown): string {
35 return error instanceof Error ? error.message : "Server update failed.";
37​
38export interface ServerUpdateTarget {
39 readonly environmentId: EnvironmentId;
40 readonly serverLabel: string;
41 readonly selfUpdate: ServerSelfUpdateCapability | null;
42 readonly desktopAppUpdate?: boolean;
43 readonly threadContinuation?: boolean;
44 readonly targetVersion: string;
45 readonly continueThreadsAfterServerUpdate?: boolean;
47​
48type UpdateButtonProps = Pick<ComponentProps<typeof Button>, "variant" | "size" | "className"> & {
49 readonly label?: string;
50 /** "icon" renders a compact icon button with the label in a tooltip. */
51 readonly appearance?: "button" | "icon";
52};
53​
54function useServerUpdate() {
55 const updateServer = useAtomCommand(serverEnvironment.updateServer, { reportFailure: false });
56 return async (target: ServerUpdateTarget, failureTitle = "Server update failed") => {
57 const { environmentId, serverLabel, selfUpdate, targetVersion } = target;
58 if (pendingUpdateEnvironmentIds.has(environmentId)) return;
59 pendingUpdateEnvironmentIds.add(environmentId);
60 try {
61 const result = await updateServer({
62 environmentId,
63 input: {
64 targetVersion,
65 ...(target.threadContinuation && target.continueThreadsAfterServerUpdate
66 ? { continueRunningThreads: true }
67 : {}),
68 },
69 });
70 if (result._tag === "Failure") {
71 if (isAtomCommandInterrupted(result)) return;
72 throw squashAtomCommandFailure(result);
73 }
74 toastManager.add({
75 type: "success",
76 title: `${serverLabel} updated`,
77 description:
78 selfUpdate === "desktop-managed"
79 ? `Desktop app relaunched on ${result.value.targetVersion}.`
80 : `Reconnected on t3@${result.value.targetVersion}.`,
81 });
82 } catch (error) {
83 toastManager.add({
84 type: "error",
85 title: failureTitle,
86 description: updateFailureMessage(error),
87 });
88 } finally {
89 pendingUpdateEnvironmentIds.delete(environmentId);
90 }
91 };
93​
94/** Updates eligible machines independently; manual paths remain in the machine list. */
95export function ServerUpdatesAction({
96 targets,
97 label = "Update all",
98 variant = "outline",
99 size = "xs",
100 className,
101}: UpdateButtonProps & {
102 readonly targets: ReadonlyArray<ServerUpdateTarget>;
103}) {
104 const update = useServerUpdate();
105 const pending = useRef(false);
106 const [isPending, setIsPending] = useState(false);
107 const eligible = targets.filter(
108 (target) =>
109 target.selfUpdate !== null &&
110 (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate),
111 );
112 const handleUpdate = async () => {
113 if (pending.current) return;
114 pending.current = true;
115 setIsPending(true);
116 try {
117 const available = eligible.filter(
118 (target) => !pendingUpdateEnvironmentIds.has(target.environmentId),
119 );
120 const desktopTargets = available.filter((target) => target.selfUpdate === "desktop-managed");
121 if (desktopTargets.length > 0) {
122 const confirmed =
123 (await requestConfirmDialog(
124 `Update the T3 Code desktop apps on ${desktopTargets.map((target) => target.serverLabel).join(", ")}? They will close and relaunch on those machines.`,
125 )) ?? true;
126 if (!confirmed) return;
127 }
128 await Promise.all(
129 available.map((target) => update(target, `${target.serverLabel} update failed`)),
130 );
131 } finally {
132 pending.current = false;
133 setIsPending(false);
134 }
135 };
136 return (
137 <Button
138 size={size}
139 variant={variant}
140 className={className}
141 disabled={isPending || eligible.length === 0}
142 onClick={() => void handleUpdate()}
143 >
144 {label}
145 </Button>
146 );
148​
149/**
150 * One-row status for an in-flight server update: "Downloading…" then
151 * "Restarting…". The update is a wait, not a warning: a single pulsing dot
152 * and label, no step rail, no versions. Failure turns the row red with the
153 * rollback reason.
154 */
155export function ServerUpdateProgress({
156 state,
157}: {
158 readonly state: Exclude<ServerUpdateState, { status: "idle" }>;
159}) {
160 if (state.status === "failed") {
161 return (
162 <div className="mt-1 flex min-w-0 items-center gap-2 text-xs text-destructive" role="alert">
163 <span className="size-1.5 shrink-0 rounded-full bg-destructive" aria-hidden="true" />
164 <Tooltip>
165 <TooltipTrigger render={<span className="min-w-0 truncate">{state.message}</span>} />
166 <TooltipPopup side="top">{state.message}</TooltipPopup>
167 </Tooltip>
168 </div>
169 );
170 }
171 return (
172 <div className="mt-1 flex items-center gap-2 text-xs font-medium text-foreground">
173 <span
174 className="size-1.5 shrink-0 animate-status-pulse rounded-full bg-foreground"
175 aria-hidden="true"
176 />
177 <span>{serverUpdateStageLabel(state.stage)}</span>
178 </div>
179 );
181​
182/**
183 * Offers the update path advertised by a version-skewed server. Self-updates
184 * delegate their full lifecycle to client-runtime so this component can
185 * unmount during reconnect without losing operation state.
186 */
187export function ServerUpdateAction({
188 environmentId,
189 serverLabel,
190 selfUpdate,
191 desktopAppUpdate = false,
192 threadContinuation = false,
193 targetVersion,
194 label = "Update",
195 variant = "outline",
196 size = "xs",
197 className,
198 appearance = "button",
199}: Omit<ServerUpdateTarget, "continueThreadsAfterServerUpdate"> & UpdateButtonProps) {
200 const isDesktopAppUpdate = selfUpdate === "desktop-managed";
201 const continueThreadsAfterServerUpdate = useEnvironmentSettings(
202 environmentId,
203 (settings) => settings.continueThreadsAfterServerUpdate,
204 );
205 const update = useServerUpdate();
206 const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
207 target: "update command",
208 onCopy: ({ command }) => {
209 toastManager.add({
210 type: "success",
211 title: "Update command copied",
212 description: `Run \`${command}\` on ${serverLabel} to update it.`,
213 });
214 },
215 onError: (error) => {
216 toastManager.add({
217 type: "error",
218 title: "Could not copy update command",
219 description: error.message,
220 });
221 },
222 });
223​
224 const handleUpdate = async () => {
225 if (pendingUpdateEnvironmentIds.has(environmentId)) {
226 return;
227 }
228 if (isDesktopAppUpdate) {
229 // No themed host mounted (undefined) means proceed: the click itself
230 // was the request. This is the only confirmation in the flow; the
231 // remote machine installs without asking anyone there.
232 const confirmed =
233 (await requestConfirmDialog(
234 `Update the T3 Code desktop app that runs the ${serverLabel}? It will close and relaunch on that machine.`,
235 )) ?? true;
236 if (!confirmed) {
237 return;
238 }
239 }
240 await update({
241 environmentId,
242 serverLabel,
243 selfUpdate,
244 desktopAppUpdate,
245 threadContinuation,
246 targetVersion,
247 continueThreadsAfterServerUpdate,
248 });
249 };
250​
251 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
252 return (
253 <span className="text-muted-foreground text-xs">
254 Update the desktop app on that machine to update this server.
255 </span>
256 );
257 }
258​
259 const manualCommand = selfUpdate === null ? manualServerUpdateCommand(targetVersion) : null;
260 const actionLabel = manualCommand !== null ? "Copy update command" : label;
261 const onClick =
262 manualCommand !== null
263 ? () => copyToClipboard(manualCommand, { command: manualCommand })
264 : () => void handleUpdate();
265​
266 if (appearance === "icon") {
267 return (
268 <Tooltip>
269 <TooltipTrigger
270 render={
271 <Button
272 size="icon-xs"
273 variant="ghost-muted"
274 className={className}
275 aria-label={`${actionLabel} for ${serverLabel}`}
276 onClick={onClick}
277 />
278 }
279 >
280 <CircleArrowUpIcon className="size-3.5" />
281 </TooltipTrigger>
282 <TooltipPopup side="top">{actionLabel}</TooltipPopup>
283 </Tooltip>
284 );
285 }
286​
287 return (
288 <Button size={size} variant={variant} className={className} onClick={onClick}>
289 {actionLabel}
290 </Button>
291 );
293​
294/**
295 * Updates a host too old for this client to connect to. Its version comes
296 * from the host descriptor because the host never delivers a server config.
297 */
298export function OutdatedServerUpdateAction({
299 environmentId,
300 serverLabel,
301 fromVersion,
302 targetVersion,
303 label = "Update",
304}: {
305 readonly environmentId: EnvironmentId;
306 readonly serverLabel: string;
307 readonly fromVersion: string | undefined;
308 readonly targetVersion: string;
309 readonly label?: string;
310}) {
311 const update = useAtomCommand(updateOutdatedServer, { reportFailure: false });
312 const handleUpdate = async () => {
313 if (pendingUpdateEnvironmentIds.has(environmentId)) return;
314 pendingUpdateEnvironmentIds.add(environmentId);
315 try {
316 const result = await update({
317 environmentId,
318 input: { targetVersion },
319 ...(fromVersion === undefined ? {} : { fromVersion }),
320 });
321 if (result._tag === "Failure") {
322 if (isAtomCommandInterrupted(result)) return;
323 throw squashAtomCommandFailure(result);
324 }
325 toastManager.add({
326 type: "success",
327 title: `${serverLabel} updated`,
328 description: `Reconnected on t3@${result.value.targetVersion}.`,
329 });
330 } catch (error) {
331 toastManager.add({
332 type: "error",
333 title: "Server update failed",
334 description: updateFailureMessage(error),
335 });
336 } finally {
337 pendingUpdateEnvironmentIds.delete(environmentId);
338 }
339 };
340 return (
341 <Button size="xs" variant="outline" onClick={() => void handleUpdate()}>
342 {label}
343 </Button>
344 );