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

ServerUpdateAction.tsx

396 lines13.0 KB

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