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

ServerUpdateAction.tsx

202 lines6.7 KB

1import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
2import type { ServerUpdateStage, ServerUpdateState } from "@t3tools/client-runtime/state/server";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import type { ComponentProps } from "react";
8​
9import { requestConfirmDialog } from "~/confirmDialog";
10import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
11import { useEnvironmentSettings } from "~/hooks/useSettings";
12import { serverEnvironment } from "~/state/server";
13import { useAtomCommand } from "~/state/use-atom-command";
14import { manualServerUpdateCommand } from "~/versionSkew";
15import { Button } from "./ui/button";
16import { toastManager } from "./ui/toast";
17import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
18​
19// The wire "installing" stage is a sub-second launcher handoff, so the UI
20// folds it into the download phase; everything after the handoff is the
21// restart the user is actually waiting through.
22const UPDATE_STAGE_LABELS: Record<ServerUpdateStage, string> = {
23 downloading: "Downloading…",
24 installing: "Downloading…",
25 resuming: "Restarting…",
26};
27const pendingUpdateEnvironmentIds = new Set<EnvironmentId>();
28​
29export function serverUpdateStageLabel(stage: ServerUpdateStage): string {
30 return UPDATE_STAGE_LABELS[stage];
32​
33function updateFailureMessage(error: unknown): string {
34 return error instanceof Error ? error.message : "Server update failed.";
36​
37/**
38 * One-row status for an in-flight server update: "Downloading…" then
39 * "Restarting…". The update is a wait, not a warning: a single pulsing dot
40 * and label, no step rail, no versions. Failure turns the row red with the
41 * rollback reason.
42 */
43export function ServerUpdateProgress({
44 state,
45}: {
46 readonly state: Exclude<ServerUpdateState, { status: "idle" }>;
47}) {
48 if (state.status === "failed") {
49 return (
50 <div className="mt-1 flex min-w-0 items-center gap-2 text-xs text-destructive" role="alert">
51 <span className="size-1.5 shrink-0 rounded-full bg-destructive" aria-hidden="true" />
52 <Tooltip>
53 <TooltipTrigger render={<span className="min-w-0 truncate">{state.message}</span>} />
54 <TooltipPopup side="top" className="max-w-80">
55 {state.message}
56 </TooltipPopup>
57 </Tooltip>
58 </div>
59 );
60 }
61 return (
62 <div className="mt-1 flex items-center gap-2 text-xs font-medium text-foreground">
63 <span
64 className="size-1.5 shrink-0 animate-status-pulse rounded-full bg-foreground"
65 aria-hidden="true"
66 />
67 <span>{serverUpdateStageLabel(state.stage)}</span>
68 </div>
69 );
71​
72/**
73 * Offers the update path advertised by a version-skewed server. Self-updates
74 * delegate their full lifecycle to client-runtime so this component can
75 * unmount during reconnect without losing operation state.
76 */
77export function ServerUpdateAction({
78 environmentId,
79 serverLabel,
80 selfUpdate,
81 desktopAppUpdate = false,
82 threadContinuation = false,
83 targetVersion,
84 label = "Update",
85 variant = "outline",
86 size = "xs",
87}: {
88 readonly environmentId: EnvironmentId;
89 readonly serverLabel: string;
90 readonly selfUpdate: ServerSelfUpdateCapability | null;
91 /** The desktop app supervising this server accepts remote update
92 requests (capabilities.desktopAppUpdate). */
93 readonly desktopAppUpdate?: boolean;
94 /** The server can durably continue running provider turns after updating. */
95 readonly threadContinuation?: boolean;
96 readonly targetVersion: string;
97 readonly label?: string;
98 readonly variant?: ComponentProps<typeof Button>["variant"];
99 readonly size?: ComponentProps<typeof Button>["size"];
100}) {
101 const isDesktopAppUpdate = selfUpdate === "desktop-managed";
102 const continueThreadsAfterServerUpdate = useEnvironmentSettings(
103 environmentId,
104 (settings) => settings.continueThreadsAfterServerUpdate,
105 );
106 const updateServer = useAtomCommand(serverEnvironment.updateServer, {
107 reportFailure: false,
108 });
109 const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
110 target: "update command",
111 onCopy: ({ command }) => {
112 toastManager.add({
113 type: "success",
114 title: "Update command copied",
115 description: `Run \`${command}\` on ${serverLabel} to update it.`,
116 });
117 },
118 onError: (error) => {
119 toastManager.add({
120 type: "error",
121 title: "Could not copy update command",
122 description: error.message,
123 });
124 },
125 });
126​
127 const handleUpdate = async () => {
128 if (pendingUpdateEnvironmentIds.has(environmentId)) {
129 return;
130 }
131 if (isDesktopAppUpdate) {
132 // No themed host mounted (undefined) means proceed: the click itself
133 // was the request. This is the only confirmation in the flow; the
134 // remote machine installs without asking anyone there.
135 const confirmed =
136 (await requestConfirmDialog(
137 `Update the T3 Code desktop app that runs the ${serverLabel}? It will close and relaunch on that machine.`,
138 )) ?? true;
139 if (!confirmed) {
140 return;
141 }
142 }
143 if (pendingUpdateEnvironmentIds.has(environmentId)) {
144 return;
145 }
146 pendingUpdateEnvironmentIds.add(environmentId);
147 try {
148 const result = await updateServer({
149 environmentId,
150 input: {
151 targetVersion,
152 ...(threadContinuation && continueThreadsAfterServerUpdate
153 ? { continueRunningThreads: true }
154 : {}),
155 },
156 });
157 if (result._tag === "Failure") {
158 if (isAtomCommandInterrupted(result)) {
159 return;
160 }
161 toastManager.add({
162 type: "error",
163 title: "Server update failed",
164 description: updateFailureMessage(squashAtomCommandFailure(result)),
165 });
166 return;
167 }
168 toastManager.add({
169 type: "success",
170 title: `${serverLabel} updated`,
171 description: isDesktopAppUpdate
172 ? `Desktop app relaunched on ${result.value.targetVersion}.`
173 : `Reconnected on t3@${result.value.targetVersion}.`,
174 });
175 } finally {
176 pendingUpdateEnvironmentIds.delete(environmentId);
177 }
178 };
179​
180 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
181 return (
182 <span className="text-muted-foreground text-xs">
183 Update the desktop app on that machine to update this server.
184 </span>
185 );
186 }
187​
188 if (selfUpdate === null) {
189 const command = manualServerUpdateCommand(targetVersion);
190 return (
191 <Button size={size} variant={variant} onClick={() => copyToClipboard(command, { command })}>
192 Copy update command
193 </Button>
194 );
195 }
196​
197 return (
198 <Button size={size} variant={variant} onClick={() => void handleUpdate()}>
199 {label}
200 </Button>
201 );