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