Open History to see the last commit
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 } 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];
32}
33
34function updateFailureMessage(error: unknown): string {
35 return error instanceof Error ? error.message : "Server update failed.";
36}
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;
46}
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 };
92}
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 );
147}
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" className="max-w-80">
167 {state.message}
168 </TooltipPopup>
169 </Tooltip>
170 </div>
171 );
172 }
173 return (
174 <div className="mt-1 flex items-center gap-2 text-xs font-medium text-foreground">
175 <span
176 className="size-1.5 shrink-0 animate-status-pulse rounded-full bg-foreground"
177 aria-hidden="true"
178 />
179 <span>{serverUpdateStageLabel(state.stage)}</span>
180 </div>
181 );
182}
183
184/**
185 * Offers the update path advertised by a version-skewed server. Self-updates
186 * delegate their full lifecycle to client-runtime so this component can
187 * unmount during reconnect without losing operation state.
188 */
189export function ServerUpdateAction({
190 environmentId,
191 serverLabel,
192 selfUpdate,
193 desktopAppUpdate = false,
194 threadContinuation = false,
195 targetVersion,
196 label = "Update",
197 variant = "outline",
198 size = "xs",
199 className,
200 appearance = "button",
201}: Omit<ServerUpdateTarget, "continueThreadsAfterServerUpdate"> & UpdateButtonProps) {
202 const isDesktopAppUpdate = selfUpdate === "desktop-managed";
203 const continueThreadsAfterServerUpdate = useEnvironmentSettings(
204 environmentId,
205 (settings) => settings.continueThreadsAfterServerUpdate,
206 );
207 const update = useServerUpdate();
208 const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
209 target: "update command",
210 onCopy: ({ command }) => {
211 toastManager.add({
212 type: "success",
213 title: "Update command copied",
214 description: `Run \`${command}\` on ${serverLabel} to update it.`,
215 });
216 },
217 onError: (error) => {
218 toastManager.add({
219 type: "error",
220 title: "Could not copy update command",
221 description: error.message,
222 });
223 },
224 });
225
226 const handleUpdate = async () => {
227 if (pendingUpdateEnvironmentIds.has(environmentId)) {
228 return;
229 }
230 if (isDesktopAppUpdate) {
231 // No themed host mounted (undefined) means proceed: the click itself
232 // was the request. This is the only confirmation in the flow; the
233 // remote machine installs without asking anyone there.
234 const confirmed =
235 (await requestConfirmDialog(
236 `Update the T3 Code desktop app that runs the ${serverLabel}? It will close and relaunch on that machine.`,
237 )) ?? true;
238 if (!confirmed) {
239 return;
240 }
241 }
242 await update({
243 environmentId,
244 serverLabel,
245 selfUpdate,
246 desktopAppUpdate,
247 threadContinuation,
248 targetVersion,
249 continueThreadsAfterServerUpdate,
250 });
251 };
252
253 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
254 return (
255 <span className="text-muted-foreground text-xs">
256 Update the desktop app on that machine to update this server.
257 </span>
258 );
259 }
260
261 const manualCommand = selfUpdate === null ? manualServerUpdateCommand(targetVersion) : null;
262 const actionLabel = manualCommand !== null ? "Copy update command" : label;
263 const onClick =
264 manualCommand !== null
265 ? () => copyToClipboard(manualCommand, { command: manualCommand })
266 : () => void handleUpdate();
267
268 if (appearance === "icon") {
269 return (
270 <Tooltip>
271 <TooltipTrigger
272 render={
273 <Button
274 size="icon-xs"
275 variant="ghost"
276 className={className ?? "text-muted-foreground hover:text-foreground"}
277 aria-label={`${actionLabel} for ${serverLabel}`}
278 onClick={onClick}
279 />
280 }
281 >
282 <CircleArrowUpIcon className="size-3.5" />
283 </TooltipTrigger>
284 <TooltipPopup side="top">{actionLabel}</TooltipPopup>
285 </Tooltip>
286 );
287 }
288
289 return (
290 <Button size={size} variant={variant} className={className} onClick={onClick}>
291 {actionLabel}
292 </Button>
293 );
294}