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

ServerUpdateAction.tsx

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