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