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