Open History to see the last commit
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 { useClientSettings } 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];
31}
32
33function updateFailureMessage(error: unknown): string {
34 return error instanceof Error ? error.message : "Server update failed.";
35}
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 );
70}
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}: {
87 readonly environmentId: EnvironmentId;
88 readonly serverLabel: string;
89 readonly selfUpdate: ServerSelfUpdateCapability | null;
90 /** The desktop app supervising this server accepts remote update
91 requests (capabilities.desktopAppUpdate). */
92 readonly desktopAppUpdate?: boolean;
93 /** The server can durably continue running provider turns after updating. */
94 readonly threadContinuation?: boolean;
95 readonly targetVersion: string;
96 readonly label?: string;
97 readonly variant?: ComponentProps<typeof Button>["variant"];
98}) {
99 const isDesktopAppUpdate = selfUpdate === "desktop-managed";
100 const continueThreadsAfterServerUpdate = useClientSettings(
101 (settings) => settings.continueThreadsAfterServerUpdate,
102 );
103 const updateServer = useAtomCommand(serverEnvironment.updateServer, {
104 reportFailure: false,
105 });
106 const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
107 target: "update command",
108 onCopy: ({ command }) => {
109 toastManager.add({
110 type: "success",
111 title: "Update command copied",
112 description: `Run \`${command}\` on ${serverLabel} to update it.`,
113 });
114 },
115 onError: (error) => {
116 toastManager.add({
117 type: "error",
118 title: "Could not copy update command",
119 description: error.message,
120 });
121 },
122 });
123
124 const handleUpdate = async () => {
125 if (pendingUpdateEnvironmentIds.has(environmentId)) {
126 return;
127 }
128 if (isDesktopAppUpdate) {
129 // No themed host mounted (undefined) means proceed: the click itself
130 // was the request. This is the only confirmation in the flow; the
131 // remote machine installs without asking anyone there.
132 const confirmed =
133 (await requestConfirmDialog(
134 `Update the T3 Code desktop app that runs the ${serverLabel}? It will close and relaunch on that machine.`,
135 )) ?? true;
136 if (!confirmed) {
137 return;
138 }
139 }
140 if (pendingUpdateEnvironmentIds.has(environmentId)) {
141 return;
142 }
143 pendingUpdateEnvironmentIds.add(environmentId);
144 try {
145 const result = await updateServer({
146 environmentId,
147 input: {
148 targetVersion,
149 ...(threadContinuation && continueThreadsAfterServerUpdate
150 ? { continueRunningThreads: true }
151 : {}),
152 },
153 });
154 if (result._tag === "Failure") {
155 if (isAtomCommandInterrupted(result)) {
156 return;
157 }
158 toastManager.add({
159 type: "error",
160 title: "Server update failed",
161 description: updateFailureMessage(squashAtomCommandFailure(result)),
162 });
163 return;
164 }
165 toastManager.add({
166 type: "success",
167 title: `${serverLabel} updated`,
168 description: isDesktopAppUpdate
169 ? `Desktop app relaunched on ${result.value.targetVersion}.`
170 : `Reconnected on t3@${result.value.targetVersion}.`,
171 });
172 } finally {
173 pendingUpdateEnvironmentIds.delete(environmentId);
174 }
175 };
176
177 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
178 return (
179 <span className="text-muted-foreground text-xs">
180 Update the desktop app on that machine to update this server.
181 </span>
182 );
183 }
184
185 if (selfUpdate === null) {
186 const command = manualServerUpdateCommand(targetVersion);
187 return (
188 <Button size="xs" variant={variant} onClick={() => copyToClipboard(command, { command })}>
189 Copy update command
190 </Button>
191 );
192 }
193
194 return (
195 <Button size="xs" variant={variant} onClick={() => void handleUpdate()}>
196 {label}
197 </Button>
198 );
199}