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

ServerUpdateAction.tsx

388 lines12.3 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​
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];
43​
44function updateFailureMessage(error: unknown): string {
45 return error instanceof Error ? error.message : "Server update failed.";
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 threadContinuation?: boolean;
55 readonly targetVersion: string;
56 readonly continueThreadsAfterServerUpdate?: boolean;
58​
59type UpdateButtonProps = Pick<ComponentProps<typeof Button>, "variant" | "size" | "className"> & {
60 readonly label?: string;
61 readonly appearance?: "button" | "icon";
62};
63​
64export type ServerUpdateOutcome =
65 | { readonly status: "updated" | "skipped" }
66 | { readonly status: "failed"; readonly message: string };
67​
68/** Toasts its success or failure unless `quiet`; never rejects. */
69export function useServerUpdate() {
70 const updateServer = useAtomCommand(serverEnvironment.updateServer, { reportFailure: false });
71 return async (
72 target: ServerUpdateTarget,
73 { quiet = false }: { readonly quiet?: boolean } = {},
74 ): Promise<ServerUpdateOutcome> => {
75 const { environmentId, serverLabel, selfUpdate, targetVersion } = target;
76 if (
77 !canUpdateServer(appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId))) ||
78 pendingUpdateEnvironmentIds.has(environmentId)
79 )
80 return { status: "skipped" };
81 pendingUpdateEnvironmentIds.add(environmentId);
82 try {
83 const result = await updateServer({
84 environmentId,
85 input: {
86 targetVersion,
87 ...(target.threadContinuation && target.continueThreadsAfterServerUpdate
88 ? { continueRunningThreads: true }
89 : {}),
90 },
91 });
92 if (result._tag === "Failure") {
93 if (isAtomCommandInterrupted(result)) return { status: "skipped" };
94 throw squashAtomCommandFailure(result);
95 }
96 if (!quiet) {
97 toastManager.add({
98 type: "success",
99 title: `${serverLabel} updated`,
100 description:
101 selfUpdate === "desktop-managed"
102 ? `Desktop app relaunched on ${result.value.targetVersion}.`
103 : `Reconnected on t3@${result.value.targetVersion}.`,
104 });
105 }
106 return { status: "updated" };
107 } catch (error) {
108 const message = updateFailureMessage(error);
109 if (!quiet) {
110 toastManager.add({
111 type: "error",
112 title: `${serverLabel} update failed`,
113 description: message,
114 });
115 }
116 return { status: "failed", message };
117 } finally {
118 pendingUpdateEnvironmentIds.delete(environmentId);
119 }
120 };
122​
123export function ServerUpdatesAction({
124 targets,
125 label = "Update all",
126 variant = "outline",
127 size = "xs",
128 className,
129}: UpdateButtonProps & {
130 readonly targets: ReadonlyArray<ServerUpdateTarget>;
131}) {
132 const update = useServerUpdate();
133 const pending = useRef(false);
134 const [isPending, setIsPending] = useState(false);
135 const eligible = targets.filter(
136 (target) =>
137 target.selfUpdate !== null &&
138 (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate),
139 );
140 const handleUpdate = async () => {
141 if (pending.current) return;
142 pending.current = true;
143 setIsPending(true);
144 try {
145 const available = eligible.filter(
146 (target) => !pendingUpdateEnvironmentIds.has(target.environmentId),
147 );
148 const desktopTargets = available.filter((target) => target.selfUpdate === "desktop-managed");
149 if (desktopTargets.length > 0) {
150 const confirmed =
151 (await requestConfirmDialog(
152 `Update the T3 Code desktop apps on ${desktopTargets.map((target) => target.serverLabel).join(", ")}? They will close and relaunch on those machines.`,
153 )) ?? true;
154 if (!confirmed) return;
155 }
156 await Promise.all(available.map((target) => update(target)));
157 } finally {
158 pending.current = false;
159 setIsPending(false);
160 }
161 };
162 return (
163 <Button
164 size={size}
165 variant={variant}
166 className={className}
167 disabled={isPending || eligible.length === 0}
168 onClick={() => void handleUpdate()}
169 >
170 {label}
171 </Button>
172 );
174​
175export function canUpdateServer(
176 result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
177): boolean {
178 if (result._tag !== "Success" || !result.value.authenticated) return false;
179 return sessionGrantsScope(result.value, AuthEnvironmentMaintainScope);
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 className="size-1.5 shrink-0 rounded-full bg-foreground" aria-hidden="true" />
201 <span>{serverUpdateStageLabel(state.stage)}</span>
202 </div>
203 );
205​
206/**
207 * Self-updates delegate their full lifecycle to client-runtime so this component can unmount
208 * 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 const confirmed =
263 (await requestConfirmDialog(
264 `Update the T3 Code desktop app that runs the ${serverLabel}? It will close and relaunch on that machine.`,
265 )) ?? true;
266 if (!confirmed) {
267 return;
268 }
269 }
270 if (!canUpdateServer(appAtomRegistry.get(sessionStateAtom))) return;
271 await update({
272 environmentId,
273 serverLabel,
274 selfUpdate,
275 desktopAppUpdate,
276 threadContinuation,
277 targetVersion,
278 continueThreadsAfterServerUpdate,
279 });
280 };
281​
282 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
283 return (
284 <span className="text-muted-foreground text-xs">
285 Update the desktop app on that machine to update this server.
286 </span>
287 );
288 }
289​
290 const manualCommand =
291 selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null;
292 const actionLabel =
293 manualCommand !== null
294 ? installation?.kind === "npm-global"
295 ? "Copy update command"
296 : "Copy relaunch command"
297 : label;
298 const onClick =
299 manualCommand !== null
300 ? () => copyToClipboard(manualCommand, { command: manualCommand })
301 : () => void handleUpdate();
302​
303 if (appearance === "icon") {
304 return (
305 <Tooltip>
306 <TooltipTrigger
307 render={
308 <Button
309 size="icon-xs"
310 variant="ghost-muted"
311 className={className}
312 aria-label={`${actionLabel} for ${serverLabel}`}
313 disabled={manualCommand === null && !canUpdate}
314 onClick={onClick}
315 />
316 }
317 >
318 <CircleArrowUpIcon className="size-3.5" />
319 </TooltipTrigger>
320 <TooltipPopup side="top">{actionLabel}</TooltipPopup>
321 </Tooltip>
322 );
323 }
324​
325 return (
326 <Button
327 size={size}
328 variant={variant}
329 className={className}
330 disabled={manualCommand === null && !canUpdate}
331 onClick={onClick}
332 >
333 {actionLabel}
334 </Button>
335 );
337​
338/**
339 * Its version comes from the host descriptor because the host never delivers a server config.
340 */
341export function OutdatedServerUpdateAction({
342 environmentId,
343 serverLabel,
344 fromVersion,
345 targetVersion,
346 label = "Update",
347}: {
348 readonly environmentId: EnvironmentId;
349 readonly serverLabel: string;
350 readonly fromVersion: string | undefined;
351 readonly targetVersion: string;
352 readonly label?: string;
353}) {
354 const update = useAtomCommand(updateOutdatedServer, { reportFailure: false });
355 const handleUpdate = async () => {
356 if (pendingUpdateEnvironmentIds.has(environmentId)) return;
357 pendingUpdateEnvironmentIds.add(environmentId);
358 try {
359 const result = await update({
360 environmentId,
361 input: { targetVersion },
362 ...(fromVersion === undefined ? {} : { fromVersion }),
363 });
364 if (result._tag === "Failure") {
365 if (isAtomCommandInterrupted(result)) return;
366 throw squashAtomCommandFailure(result);
367 }
368 toastManager.add({
369 type: "success",
370 title: `${serverLabel} updated`,
371 description: `Reconnected on t3@${result.value.targetVersion}.`,
372 });
373 } catch (error) {
374 toastManager.add({
375 type: "error",
376 title: `${serverLabel} update failed`,
377 description: updateFailureMessage(error),
378 });
379 } finally {
380 pendingUpdateEnvironmentIds.delete(environmentId);
381 }
382 };
383 return (
384 <Button size="xs" variant="outline" onClick={() => void handleUpdate()}>
385 {label}
386 </Button>
387 );