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/** client-runtime owns self-updates so unmounting during reconnect preserves operation state. */
202export function ServerUpdateAction({
203 environmentId,
204 serverLabel,
205 selfUpdate,
206 installation,
207 desktopAppUpdate = false,
208 threadContinuation = false,
209 targetVersion,
210 label = "Update",
211 variant = "outline",
212 size = "xs",
213 className,
214 appearance = "button",
215}: Omit<ServerUpdateTarget, "continueThreadsAfterServerUpdate"> & UpdateButtonProps) {
216 const isDesktopAppUpdate = selfUpdate === "desktop-managed";
217 const sessionStateAtom = environmentSession.sessionStateAtom(environmentId);
218 const canUpdate = canUpdateServer(useAtomValue(sessionStateAtom));
219 const continueThreadsAfterServerUpdate = useEnvironmentSettings(
220 environmentId,
221 (settings) => settings.continueThreadsAfterServerUpdate,
222 );
223 const update = useServerUpdate();
224 const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
225 target: installation?.kind === "npm-global" ? "update command" : "relaunch command",
226 onCopy: ({ command }) => {
227 toastManager.add({
228 type: "success",
229 title:
230 installation?.kind === "npm-global" ? "Update command copied" : "Relaunch command copied",
231 description:
232 installation?.kind === "npm-global"
233 ? `Run \`${command}\` on ${serverLabel}, then restart t3 with your usual options.`
234 : `Stop t3 on ${serverLabel}, then relaunch with \`${command}\` using the same subcommand and options. This does not update an installed t3 command.`,
235 });
236 },
237 onError: (error) => {
238 toastManager.add({
239 type: "error",
240 title: "Could not copy update command",
241 description: error.message,
242 });
243 },
244 });
245
246 const handleUpdate = async () => {
247 if (
248 !canUpdateServer(appAtomRegistry.get(sessionStateAtom)) ||
249 pendingUpdateEnvironmentIds.has(environmentId)
250 ) {
251 return;
252 }
253 if (isDesktopAppUpdate) {
254 const confirmed =
255 (await requestConfirmDialog(
256 `Update the T3 Code desktop app that runs the ${serverLabel}? It will close and relaunch on that machine.`,
257 )) ?? true;
258 if (!confirmed) {
259 return;
260 }
261 }
262 if (!canUpdateServer(appAtomRegistry.get(sessionStateAtom))) return;
263 await update({
264 environmentId,
265 serverLabel,
266 selfUpdate,
267 desktopAppUpdate,
268 threadContinuation,
269 targetVersion,
270 continueThreadsAfterServerUpdate,
271 });
272 };
273
274 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
275 return (
276 <span className="text-muted-foreground text-xs">
277 Update the desktop app on that machine to update this server.
278 </span>
279 );
280 }
281
282 const manualCommand =
283 selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null;
284 const actionLabel =
285 manualCommand !== null
286 ? installation?.kind === "npm-global"
287 ? "Copy update command"
288 : "Copy relaunch command"
289 : label;
290 const onClick =
291 manualCommand !== null
292 ? () => copyToClipboard(manualCommand, { command: manualCommand })
293 : () => void handleUpdate();
294
295 if (appearance === "icon") {
296 return (
297 <Tooltip>
298 <TooltipTrigger
299 render={
300 <Button
301 size="icon-xs"
302 variant="ghost-muted"
303 className={className}
304 aria-label={`${actionLabel} for ${serverLabel}`}
305 disabled={manualCommand === null && !canUpdate}
306 onClick={onClick}
307 />
308 }
309 >
310 <CircleArrowUpIcon className="size-3.5" />
311 </TooltipTrigger>
312 <TooltipPopup side="top">{actionLabel}</TooltipPopup>
313 </Tooltip>
314 );
315 }
316
317 return (
318 <Button
319 size={size}
320 variant={variant}
321 className={className}
322 disabled={manualCommand === null && !canUpdate}
323 onClick={onClick}
324 >
325 {actionLabel}
326 </Button>
327 );
328}
329
330/** Read the host descriptor's version because the host never delivers server config. */
331export function OutdatedServerUpdateAction({
332 environmentId,
333 serverLabel,
334 fromVersion,
335 targetVersion,
336 label = "Update",
337}: {
338 readonly environmentId: EnvironmentId;
339 readonly serverLabel: string;
340 readonly fromVersion: string | undefined;
341 readonly targetVersion: string;
342 readonly label?: string;
343}) {
344 const update = useAtomCommand(updateOutdatedServer, { reportFailure: false });
345 const handleUpdate = async () => {
346 if (pendingUpdateEnvironmentIds.has(environmentId)) return;
347 pendingUpdateEnvironmentIds.add(environmentId);
348 const result = await update({
349 environmentId,
350 input: { targetVersion },
351 ...(fromVersion === undefined ? {} : { fromVersion }),
352 });
353 pendingUpdateEnvironmentIds.delete(environmentId);
354 if (result._tag === "Failure") {
355 if (isAtomCommandInterrupted(result)) return;
356 toastManager.add({
357 type: "error",
358 title: `${serverLabel} update failed`,
359 description: updateFailureMessage(squashAtomCommandFailure(result)),
360 });
361 return;
362 }
363 toastManager.add({
364 type: "success",
365 title: `${serverLabel} updated`,
366 description: `Reconnected on t3@${result.value.targetVersion}.`,
367 });
368 };
369 return (
370 <Button size="xs" variant="outline" onClick={() => void handleUpdate()}>
371 {label}
372 </Button>
373 );
374}