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 } from "react";
8
9import { requestConfirmDialog } from "~/confirmDialog";
10import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
11import { serverEnvironment } from "~/state/server";
12import { useAtomCommand } from "~/state/use-atom-command";
13import { manualServerUpdateCommand } from "~/versionSkew";
14import { Button } from "./ui/button";
15import { toastManager } from "./ui/toast";
16import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
17
18// The wire "installing" stage is a sub-second launcher handoff, so the UI
19// folds it into the download phase; everything after the handoff is the
20// restart the user is actually waiting through.
21const UPDATE_STAGE_LABELS: Record<ServerUpdateStage, string> = {
22 downloading: "Downloading…",
23 installing: "Downloading…",
24 resuming: "Restarting…",
25};
26const pendingUpdateEnvironmentIds = new Set<EnvironmentId>();
27
28export function serverUpdateStageLabel(stage: ServerUpdateStage): string {
29 return UPDATE_STAGE_LABELS[stage];
30}
31
32function updateFailureMessage(error: unknown): string {
33 return error instanceof Error ? error.message : "Server update failed.";
34}
35
36/**
37 * One-row status for an in-flight server update: "Downloading…" then
38 * "Restarting…". The update is a wait, not a warning: a single pulsing dot
39 * and label, no step rail, no versions. Failure turns the row red with the
40 * rollback reason.
41 */
42export function ServerUpdateProgress({
43 state,
44}: {
45 readonly state: Exclude<ServerUpdateState, { status: "idle" }>;
46}) {
47 if (state.status === "failed") {
48 return (
49 <div className="mt-1 flex min-w-0 items-center gap-2 text-xs text-destructive" role="alert">
50 <span className="size-1.5 shrink-0 rounded-full bg-destructive" aria-hidden="true" />
51 <Tooltip>
52 <TooltipTrigger render={<span className="min-w-0 truncate">{state.message}</span>} />
53 <TooltipPopup side="top" className="max-w-80">
54 {state.message}
55 </TooltipPopup>
56 </Tooltip>
57 </div>
58 );
59 }
60 return (
61 <div className="mt-1 flex items-center gap-2 text-xs font-medium text-foreground">
62 <span
63 className="size-1.5 shrink-0 animate-status-pulse rounded-full bg-foreground"
64 aria-hidden="true"
65 />
66 <span>{serverUpdateStageLabel(state.stage)}</span>
67 </div>
68 );
69}
70
71/**
72 * Offers the update path advertised by a version-skewed server. Self-updates
73 * delegate their full lifecycle to client-runtime so this component can
74 * unmount during reconnect without losing operation state.
75 */
76export function ServerUpdateAction({
77 environmentId,
78 serverLabel,
79 selfUpdate,
80 desktopAppUpdate = false,
81 targetVersion,
82 label = "Update",
83 variant = "outline",
84}: {
85 readonly environmentId: EnvironmentId;
86 readonly serverLabel: string;
87 readonly selfUpdate: ServerSelfUpdateCapability | null;
88 /** The desktop app supervising this server accepts remote update
89 requests (capabilities.desktopAppUpdate). */
90 readonly desktopAppUpdate?: boolean;
91 readonly targetVersion: string;
92 readonly label?: string;
93 readonly variant?: ComponentProps<typeof Button>["variant"];
94}) {
95 const isDesktopAppUpdate = selfUpdate === "desktop-managed";
96 const updateServer = useAtomCommand(serverEnvironment.updateServer, {
97 reportFailure: false,
98 });
99 const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
100 target: "update command",
101 onCopy: ({ command }) => {
102 toastManager.add({
103 type: "success",
104 title: "Update command copied",
105 description: `Run \`${command}\` on ${serverLabel} to update it.`,
106 });
107 },
108 onError: (error) => {
109 toastManager.add({
110 type: "error",
111 title: "Could not copy update command",
112 description: error.message,
113 });
114 },
115 });
116
117 const handleUpdate = async () => {
118 if (pendingUpdateEnvironmentIds.has(environmentId)) {
119 return;
120 }
121 if (isDesktopAppUpdate) {
122 // No themed host mounted (undefined) means proceed: the click itself
123 // was the request. This is the only confirmation in the flow; the
124 // remote machine installs without asking anyone there.
125 const confirmed =
126 (await requestConfirmDialog(
127 `Update the T3 Code desktop app that runs the ${serverLabel}? It will close and relaunch on that machine.`,
128 )) ?? true;
129 if (!confirmed) {
130 return;
131 }
132 }
133 if (pendingUpdateEnvironmentIds.has(environmentId)) {
134 return;
135 }
136 pendingUpdateEnvironmentIds.add(environmentId);
137 try {
138 const result = await updateServer({
139 environmentId,
140 input: { targetVersion },
141 });
142 if (result._tag === "Failure") {
143 if (isAtomCommandInterrupted(result)) {
144 return;
145 }
146 toastManager.add({
147 type: "error",
148 title: "Server update failed",
149 description: updateFailureMessage(squashAtomCommandFailure(result)),
150 });
151 return;
152 }
153 toastManager.add({
154 type: "success",
155 title: `${serverLabel} updated`,
156 description: isDesktopAppUpdate
157 ? `Desktop app relaunched on ${result.value.targetVersion}.`
158 : `Reconnected on t3@${result.value.targetVersion}.`,
159 });
160 } finally {
161 pendingUpdateEnvironmentIds.delete(environmentId);
162 }
163 };
164
165 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
166 return (
167 <span className="text-muted-foreground text-xs">
168 Update the desktop app on that machine to update this server.
169 </span>
170 );
171 }
172
173 if (selfUpdate === null) {
174 const command = manualServerUpdateCommand(targetVersion);
175 return (
176 <Button size="xs" variant={variant} onClick={() => copyToClipboard(command, { command })}>
177 Copy update command
178 </Button>
179 );
180 }
181
182 return (
183 <Button size="xs" variant={variant} onClick={() => void handleUpdate()}>
184 {label}
185 </Button>
186 );
187}