Open History to see the last commit
1import { T, msg, useGT, useMessages } from "gt-react";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { m } from "~/i18n/messages";
4import { useStableCallback } from "../../hooks/useStableCallback";
5import { type EnvironmentId } from "@t3tools/contracts";
6import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
7import { useAtomValue } from "@effect/atom-react";
8import { useState } from "react";
9import { useNavigate } from "@tanstack/react-router";
10import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13} from "@t3tools/client-runtime/state/runtime";
14import { WifiOffIcon } from "lucide-react";
15import { stackedThreadToast, toastManager } from "../ui/toast";
16import { environmentCatalog } from "../../connection/catalog";
17import { ConnectionDiagnosisHeadline } from "../settings/ConnectionDiagnosisDetails";
18import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
19import {
20 useEnvironmentDisconnectDelay,
21 useEnvironmentStateHeldFor,
22} from "../../hooks/useEnvironmentDisconnectDelay";
23import { serverEnvironment } from "../../state/server";
24import { type EnvironmentPresentation } from "../../state/environments";
25import type { ComposerBannerStackItem } from "./ComposerBannerStack";
26import { ENVIRONMENT_RECONNECT_WARNING_GRACE_MS } from "../ChatView.logic";
27import { useAtomCommand } from "../../state/use-atom-command";
28import { Button } from "../ui/button";
29import { ServerUpdateAction, serverUpdateStageLabel } from "../ServerUpdateAction";
30import { useAutoBalanceUpdateBanner } from "./useAutoBalanceUpdateBanner";
31import { ComposerServerUpdateIcon } from "./ComposerServerUpdateStatus";
32import {
33 dismissServerUpdateFailure,
34 isServerUpdateFailureDismissed,
35 resolveServerConfigVersionMismatch,
36 resolveServerSelfUpdateCapability,
37 supportsDesktopAppUpdate,
38} from "../../versionSkew";
39
40export type EnvironmentUnavailableState = {
41 readonly environmentId: EnvironmentId;
42 readonly label: string;
43 readonly connection: EnvironmentConnectionPresentation;
44};
45
46interface SystemComposerBannersInput {
47 readonly activeEnvironment: EnvironmentPresentation | null;
48 readonly activeEnvironmentUnavailable: boolean;
49 readonly activeEnvironmentUnavailableState: EnvironmentUnavailableState | null;
50 readonly activeThreadEnvironmentId: EnvironmentId | null;
51 readonly serverConfig: EnvironmentPresentation["serverConfig"] | null;
52 readonly hasMultipleRegisteredEnvironments: boolean;
53 readonly automaticEnvironment: boolean;
54 readonly autoUpdateEnvironments: ReadonlyArray<EnvironmentPresentation>;
55}
56
57/**
58 * The composer banners about the machine itself: offline or reconnecting,
59 * a server update, and auto-balanced machines that need one.
60 */
61export function useSystemComposerBanners(input: SystemComposerBannersInput) {
62 const {
63 activeEnvironment,
64 activeEnvironmentUnavailable,
65 activeEnvironmentUnavailableState,
66 activeThreadEnvironmentId,
67 serverConfig,
68 hasMultipleRegisteredEnvironments,
69 automaticEnvironment,
70 autoUpdateEnvironments,
71 } = input;
72 const gt = useGT();
73 const messages = useMessages();
74 const navigate = useNavigate();
75 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
76 const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, {
77 reportFailure: false,
78 });
79 const activeEnvironmentConnectionPhase = activeEnvironment?.connection.phase ?? "available";
80 const activeReconnectingEnvironmentId =
81 activeEnvironmentConnectionPhase === "connecting" ||
82 activeEnvironmentConnectionPhase === "reconnecting"
83 ? (activeEnvironment?.environmentId ?? null)
84 : null;
85 // Each reconnect attempt gets its own grace period, including a later one to
86 // the same environment.
87 const reconnectWarningGraceElapsed = useEnvironmentStateHeldFor(
88 activeReconnectingEnvironmentId,
89 ENVIRONMENT_RECONNECT_WARNING_GRACE_MS,
90 );
91 const handleReconnectActiveEnvironment = async (environmentId: EnvironmentId) => {
92 // A retry does nothing while the environment is switched off.
93 const result =
94 activeEnvironment?.entry.enabled === false
95 ? await setEnvironmentEnabled({ environmentId, enabled: true })
96 : await retryEnvironment(environmentId);
97 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
98 const error = squashAtomCommandFailure(result);
99 toastManager.add(
100 stackedThreadToast({
101 type: "error",
102 title: m(msg("Could not reconnect environment")),
103 description: thrownErrorMessage(error, m) ?? m(msg("Failed to reconnect.")),
104 }),
105 );
106 }
107 };
108 const handleReconnectActiveEnvironmentStable = useStableCallback(
109 handleReconnectActiveEnvironment,
110 );
111 const disconnectDelayElapsed = useEnvironmentDisconnectDelay(
112 activeEnvironmentUnavailable && activeEnvironment ? activeEnvironment.environmentId : null,
113 );
114 const canDisconnectActiveEnvironment =
115 disconnectDelayElapsed &&
116 activeEnvironment !== null &&
117 activeEnvironment.entry.target._tag !== "PrimaryConnectionTarget" &&
118 !isDesktopLocalConnectionTarget(activeEnvironment.entry.target);
119 const [disconnectingEnvironment, setDisconnectingEnvironment] = useState(false);
120 const handleDisconnectActiveEnvironment = async (environmentId: EnvironmentId) => {
121 setDisconnectingEnvironment(true);
122 const result = await setEnvironmentEnabled({ environmentId, enabled: false });
123 setDisconnectingEnvironment(false);
124 if (result._tag === "Failure") {
125 if (!isAtomCommandInterrupted(result)) {
126 const error = squashAtomCommandFailure(result);
127 toastManager.add(
128 stackedThreadToast({
129 type: "error",
130 title: m(msg("Could not disconnect server")),
131 description: thrownErrorMessage(error, m) ?? m(msg("Failed to disconnect.")),
132 }),
133 );
134 }
135 return;
136 }
137 void navigate({ to: "/", replace: true });
138 };
139 const handleDisconnectActiveEnvironmentStable = useStableCallback(
140 handleDisconnectActiveEnvironment,
141 );
142 const autoBalanceUpdateBanner = useAutoBalanceUpdateBanner(autoUpdateEnvironments);
143 const versionMismatch = resolveServerConfigVersionMismatch(serverConfig, messages);
144 const versionMismatchServerName =
145 hasMultipleRegisteredEnvironments && activeThreadEnvironmentId !== null
146 ? (activeEnvironment?.label ?? serverConfig?.environment.label ?? activeThreadEnvironmentId)
147 : null;
148 const versionMismatchServerLabel =
149 versionMismatchServerName !== null
150 ? gt`${{ environment: versionMismatchServerName }} server`
151 : gt({ context: "noun, the T3 Code server" })`server`;
152 const serverUpdateEnvironmentId = activeThreadEnvironmentId;
153 const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
154 const versionMismatchInstallation = serverConfig?.environment.capabilities.serverInstallation;
155 const versionMismatchDesktopAppUpdate = supportsDesktopAppUpdate(serverConfig);
156 const serverUpdateState = useAtomValue(
157 serverEnvironment.updateStateAtom(serverUpdateEnvironmentId),
158 );
159 const [dismissedServerUpdateState, setDismissedServerUpdateState] = useState<
160 typeof serverUpdateState | null
161 >(null);
162 const serverUpdateFailureDismissed =
163 serverUpdateState === dismissedServerUpdateState ||
164 isServerUpdateFailureDismissed(serverUpdateState);
165 return (() => {
166 const items: ComposerBannerStackItem[] = [];
167 const updateRunning = serverUpdateState.status === "running";
168 const unavailableConnection = activeEnvironmentUnavailableState?.connection ?? null;
169 const disconnectAction =
170 canDisconnectActiveEnvironment && activeEnvironmentUnavailableState ? (
171 <Button
172 size="xs"
173 variant="ghost"
174 disabled={disconnectingEnvironment}
175 title={gt`Hide this server's threads. Switch it on again in Environments.`}
176 onClick={() =>
177 void handleDisconnectActiveEnvironmentStable(
178 activeEnvironmentUnavailableState.environmentId,
179 )
180 }
181 >
182 <T>Disconnect server</T>
183 </Button>
184 ) : undefined;
185 const environmentReconnecting =
186 unavailableConnection !== null &&
187 (unavailableConnection.phase === "connecting" ||
188 unavailableConnection.phase === "reconnecting");
189 const awaitingApproval = unavailableConnection?.awaitingApproval === true;
190 const suppressUnavailableBanner =
191 environmentReconnecting &&
192 !awaitingApproval &&
193 (updateRunning || !reconnectWarningGraceElapsed);
194 const showUnavailableBanner =
195 activeEnvironmentUnavailableState !== null &&
196 unavailableConnection !== null &&
197 !suppressUnavailableBanner;
198 if (showUnavailableBanner) {
199 items.push({
200 id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
201 variant: unavailableConnection.phase === "error" ? "error" : "warning",
202 group: "environment",
203 icon: <WifiOffIcon />,
204 title: awaitingApproval
205 ? gt`${{ environment: activeEnvironmentUnavailableState.label }} is waiting to approve this device`
206 : environmentReconnecting
207 ? gt`${{ environment: activeEnvironmentUnavailableState.label }} is reconnecting`
208 : gt`${{ environment: activeEnvironmentUnavailableState.label }} is offline`,
209 description: awaitingApproval ? (
210 (unavailableConnection.error ?? undefined)
211 ) : activeEnvironment ? (
212 <ConnectionDiagnosisHeadline environment={activeEnvironment} />
213 ) : undefined,
214 actions: (
215 <>
216 {unavailableConnection.phase !== "connecting" ? (
217 <Button
218 size="xs"
219 variant="ghost"
220 onClick={() =>
221 void handleReconnectActiveEnvironmentStable(
222 activeEnvironmentUnavailableState.environmentId,
223 )
224 }
225 >
226 {environmentReconnecting ? gt`Retry now` : gt`Reconnect`}
227 </Button>
228 ) : null}
229 {disconnectAction}
230 </>
231 ),
232 });
233 }
234 // An available update is offered by the sidebar's update pill; the composer only shows one
235 // that is running or failed, since either explains what this thread's server is doing.
236 if (
237 !automaticEnvironment &&
238 serverUpdateEnvironmentId &&
239 serverUpdateState.status !== "idle" &&
240 !serverUpdateFailureDismissed
241 ) {
242 const updateFailed = serverUpdateState.status === "failed";
243 items.push({
244 id: `server-version:${serverUpdateEnvironmentId}`,
245 variant: updateFailed ? "error" : "default",
246 group: "environment",
247 icon: <ComposerServerUpdateIcon status={serverUpdateState.status} />,
248 title:
249 versionMismatchServerName !== null
250 ? updateFailed
251 ? gt`Could not update ${{ environment: versionMismatchServerName }} server`
252 : gt`Updating ${{ environment: versionMismatchServerName }} server`
253 : updateFailed
254 ? gt`Could not update server`
255 : gt`Updating server`,
256 description:
257 serverUpdateState.status === "failed"
258 ? serverUpdateState.message
259 : serverUpdateStageLabel(serverUpdateState.stage, messages),
260 actions: !updateFailed ? (
261 disconnectAction
262 ) : !versionMismatch ||
263 (versionMismatchSelfUpdate === "desktop-managed" &&
264 !versionMismatchDesktopAppUpdate) ? undefined : (
265 <ServerUpdateAction
266 environmentId={serverUpdateEnvironmentId}
267 serverLabel={versionMismatchServerLabel}
268 selfUpdate={versionMismatchSelfUpdate}
269 installation={versionMismatchInstallation}
270 desktopAppUpdate={versionMismatchDesktopAppUpdate}
271 targetVersion={versionMismatch.clientVersion}
272 label={gt({ context: "verb, retries the server update" })`Retry`}
273 variant="ghost"
274 />
275 ),
276 ...(updateFailed
277 ? {
278 dismissLabel: gt`Dismiss update notice`,
279 onDismiss: () => {
280 dismissServerUpdateFailure(serverUpdateState);
281 setDismissedServerUpdateState(serverUpdateState);
282 },
283 }
284 : {}),
285 });
286 }
287 if (autoBalanceUpdateBanner) items.push(autoBalanceUpdateBanner);
288 return items;
289 })() as ComposerBannerStackItem[];
290}