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