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