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

ServerUpdateAction.tsx

445 lines14.8 KB

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