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