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