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