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 settlePromise,
18 squashAtomCommandFailure,
19} from "@t3tools/client-runtime/state/runtime";
20import { CircleArrowUpIcon } from "lucide-react";
21import { type ComponentProps, useRef, useState } from "react";
22
23import { requestConfirmDialog } from "~/confirmDialog";
24import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
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
33const UPDATE_STAGE_LABELS: Record<ServerUpdateStage, string> = {
34 downloading: "Downloading…",
35 installing: "Downloading…",
36 resuming: "Restarting…",
37};
38const pendingUpdateEnvironmentIds = new Set<EnvironmentId>();
39
40export function serverUpdateStageLabel(stage: ServerUpdateStage): string {
41 return UPDATE_STAGE_LABELS[stage];
42}
43
44function updateFailureMessage(error: unknown): string {
45 return error instanceof Error ? error.message : "Server update failed.";
46}
47
48export interface ServerUpdateTarget {
49 readonly environmentId: EnvironmentId;
50 readonly serverLabel: string;
51 readonly selfUpdate: ServerSelfUpdateCapability | null;
52 readonly installation?: ServerInstallation | undefined;
53 readonly desktopAppUpdate?: boolean;
54 readonly targetVersion: string;
55}
56
57type UpdateButtonProps = Pick<ComponentProps<typeof Button>, "variant" | "size" | "className"> & {
58 readonly label?: string;
59 readonly appearance?: "button" | "icon";
60};
61
62export type ServerUpdateOutcome =
63 | { readonly status: "updated" | "skipped" }
64 | { readonly status: "failed"; readonly message: string };
65
66/** Toasts its success or failure unless `quiet`; never rejects. */
67export function useServerUpdate() {
68 const updateServer = useAtomCommand(serverEnvironment.updateServer, { reportFailure: false });
69 return async (
70 target: ServerUpdateTarget,
71 { quiet = false }: { readonly quiet?: boolean } = {},
72 ): Promise<ServerUpdateOutcome> => {
73 const { environmentId, serverLabel, selfUpdate, targetVersion } = target;
74 if (
75 !canUpdateServer(appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId))) ||
76 pendingUpdateEnvironmentIds.has(environmentId)
77 )
78 return { status: "skipped" };
79 pendingUpdateEnvironmentIds.add(environmentId);
80 const result = await updateServer({
81 environmentId,
82 input: { targetVersion },
83 });
84 pendingUpdateEnvironmentIds.delete(environmentId);
85 if (result._tag === "Failure") {
86 if (isAtomCommandInterrupted(result)) return { status: "skipped" };
87 const message = updateFailureMessage(squashAtomCommandFailure(result));
88 if (!quiet) {
89 toastManager.add({
90 type: "error",
91 title: `${serverLabel} update failed`,
92 description: message,
93 });
94 }
95 return { status: "failed", message };
96 }
97 if (!quiet) {
98 toastManager.add({
99 type: "success",
100 title: `${serverLabel} updated`,
101 description:
102 selfUpdate === "desktop-managed"
103 ? `Desktop app relaunched on ${result.value.targetVersion}.`
104 : `Reconnected on t3@${result.value.targetVersion}.`,
105 });
106 }
107 return { status: "updated" };
108 };
109}
110
111export function ServerUpdatesAction({
112 targets,
113 label = "Update all",
114 variant = "outline",
115 size = "xs",
116 className,
117}: UpdateButtonProps & {
118 readonly targets: ReadonlyArray<ServerUpdateTarget>;
119}) {
120 const update = useServerUpdate();
121 const pending = useRef(false);
122 const [isPending, setIsPending] = useState(false);
123 const eligible = targets.filter(
124 (target) =>
125 target.selfUpdate !== null &&
126 (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate),
127 );
128 const handleUpdate = async () => {
129 if (pending.current) return;
130 pending.current = true;
131 setIsPending(true);
132 await settlePromise(async () => {
133 const available = eligible.filter(
134 (target) => !pendingUpdateEnvironmentIds.has(target.environmentId),
135 );
136 const desktopTargets = available.filter((target) => target.selfUpdate === "desktop-managed");
137 if (desktopTargets.length > 0) {
138 const confirmed =
139 (await requestConfirmDialog(
140 `Update the T3 Code desktop apps on ${desktopTargets.map((target) => target.serverLabel).join(", ")}? They will close and relaunch on those machines.`,
141 )) ?? true;
142 if (!confirmed) return;
143 }
144 await Promise.all(available.map((target) => update(target)));
145 });
146 pending.current = false;
147 setIsPending(false);
148 };
149 return (
150 <Button
151 size={size}
152 variant={variant}
153 className={className}
154 disabled={isPending || eligible.length === 0}
155 onClick={() => void handleUpdate()}
156 >
157 {label}
158 </Button>
159 );
160}
161
162export function canUpdateServer(
163 result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
164): boolean {
165 if (result._tag !== "Success" || !result.value.authenticated) return false;
166 return sessionGrantsScope(result.value, AuthEnvironmentMaintainScope);
167}
168
169export function ServerUpdateProgress({
170 state,
171}: {
172 readonly state: Exclude<ServerUpdateState, { status: "idle" }>;
173}) {
174 if (state.status === "failed") {
175 return (
176 <div className="mt-1 flex min-w-0 items-center gap-2 text-xs text-destructive" role="alert">
177 <span className="size-1.5 shrink-0 rounded-full bg-destructive" aria-hidden="true" />
178 <Tooltip>
179 <TooltipTrigger render={<span className="min-w-0 truncate">{state.message}</span>} />
180 <TooltipPopup side="top">{state.message}</TooltipPopup>
181 </Tooltip>
182 </div>
183 );
184 }
185 return (
186 <div className="mt-1 flex items-center gap-2 text-xs font-medium text-foreground">
187 <span className="size-1.5 shrink-0 rounded-full bg-foreground" aria-hidden="true" />
188 <span>{serverUpdateStageLabel(state.stage)}</span>
189 </div>
190 );
191}
192
193/** client-runtime owns self-updates so unmounting during reconnect preserves operation state. */
194export function ServerUpdateAction({
195 environmentId,
196 serverLabel,
197 selfUpdate,
198 installation,
199 desktopAppUpdate = false,
200 targetVersion,
201 label = "Update",
202 variant = "outline",
203 size = "xs",
204 className,
205 appearance = "button",
206}: ServerUpdateTarget & UpdateButtonProps) {
207 const isDesktopAppUpdate = selfUpdate === "desktop-managed";
208 const sessionStateAtom = environmentSession.sessionStateAtom(environmentId);
209 const canUpdate = canUpdateServer(useAtomValue(sessionStateAtom));
210 const update = useServerUpdate();
211 const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
212 target: installation?.kind === "npm-global" ? "update command" : "relaunch command",
213 onCopy: ({ command }) => {
214 toastManager.add({
215 type: "success",
216 title:
217 installation?.kind === "npm-global" ? "Update command copied" : "Relaunch command copied",
218 description:
219 installation?.kind === "npm-global"
220 ? `Run \`${command}\` on ${serverLabel}, then restart t3 with your usual options.`
221 : `Stop t3 on ${serverLabel}, then relaunch with \`${command}\` using the same subcommand and options. This does not update an installed t3 command.`,
222 });
223 },
224 onError: (error) => {
225 toastManager.add({
226 type: "error",
227 title: "Could not copy update command",
228 description: error.message,
229 });
230 },
231 });
232
233 const handleUpdate = async () => {
234 if (
235 !canUpdateServer(appAtomRegistry.get(sessionStateAtom)) ||
236 pendingUpdateEnvironmentIds.has(environmentId)
237 ) {
238 return;
239 }
240 if (isDesktopAppUpdate) {
241 const confirmed =
242 (await requestConfirmDialog(
243 `Update the T3 Code desktop app that runs the ${serverLabel}? It will close and relaunch on that machine.`,
244 )) ?? true;
245 if (!confirmed) {
246 return;
247 }
248 }
249 if (!canUpdateServer(appAtomRegistry.get(sessionStateAtom))) return;
250 await update({
251 environmentId,
252 serverLabel,
253 selfUpdate,
254 desktopAppUpdate,
255 targetVersion,
256 });
257 };
258
259 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
260 return (
261 <span className="text-muted-foreground text-xs">
262 Update the desktop app on that machine to update this server.
263 </span>
264 );
265 }
266
267 const manualCommand =
268 selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null;
269 const actionLabel =
270 manualCommand !== null
271 ? installation?.kind === "npm-global"
272 ? "Copy update command"
273 : "Copy relaunch command"
274 : label;
275 const onClick =
276 manualCommand !== null
277 ? () => copyToClipboard(manualCommand, { command: manualCommand })
278 : () => void handleUpdate();
279
280 if (appearance === "icon") {
281 return (
282 <Tooltip>
283 <TooltipTrigger
284 render={
285 <Button
286 size="icon-xs"
287 variant="ghost-muted"
288 className={className}
289 aria-label={`${actionLabel} for ${serverLabel}`}
290 disabled={manualCommand === null && !canUpdate}
291 onClick={onClick}
292 />
293 }
294 >
295 <CircleArrowUpIcon className="size-3.5" />
296 </TooltipTrigger>
297 <TooltipPopup side="top">{actionLabel}</TooltipPopup>
298 </Tooltip>
299 );
300 }
301
302 return (
303 <Button
304 size={size}
305 variant={variant}
306 className={className}
307 disabled={manualCommand === null && !canUpdate}
308 onClick={onClick}
309 >
310 {actionLabel}
311 </Button>
312 );
313}
314
315/** Read the host descriptor's version because the host never delivers server config. */
316export function OutdatedServerUpdateAction({
317 environmentId,
318 serverLabel,
319 fromVersion,
320 targetVersion,
321 label = "Update",
322}: {
323 readonly environmentId: EnvironmentId;
324 readonly serverLabel: string;
325 readonly fromVersion: string | undefined;
326 readonly targetVersion: string;
327 readonly label?: string;
328}) {
329 const update = useAtomCommand(updateOutdatedServer, { reportFailure: false });
330 const handleUpdate = async () => {
331 if (pendingUpdateEnvironmentIds.has(environmentId)) return;
332 pendingUpdateEnvironmentIds.add(environmentId);
333 const result = await update({
334 environmentId,
335 input: { targetVersion },
336 ...(fromVersion === undefined ? {} : { fromVersion }),
337 });
338 pendingUpdateEnvironmentIds.delete(environmentId);
339 if (result._tag === "Failure") {
340 if (isAtomCommandInterrupted(result)) return;
341 toastManager.add({
342 type: "error",
343 title: `${serverLabel} update failed`,
344 description: updateFailureMessage(squashAtomCommandFailure(result)),
345 });
346 return;
347 }
348 toastManager.add({
349 type: "success",
350 title: `${serverLabel} updated`,
351 description: `Reconnected on t3@${result.value.targetVersion}.`,
352 });
353 };
354 return (
355 <Button size="xs" variant="outline" onClick={() => void handleUpdate()}>
356 {label}
357 </Button>
358 );
359}