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 const result = await retryEnvironment(environmentId);
88 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
89 const error = squashAtomCommandFailure(result);
90 toastManager.add(
91 stackedThreadToast({
92 type: "error",
93 title: "Could not reconnect environment",
94 description: error instanceof Error ? error.message : "Failed to reconnect.",
95 }),
96 );
97 }
98 };
99 const handleReconnectActiveEnvironmentStable = useStableCallback(
100 handleReconnectActiveEnvironment,
101 );
102 const disconnectDelayElapsed = useEnvironmentDisconnectDelay(
103 activeEnvironmentUnavailable && activeEnvironment ? activeEnvironment.environmentId : null,
104 );
105 const canDisconnectActiveEnvironment =
106 disconnectDelayElapsed &&
107 activeEnvironment !== null &&
108 activeEnvironment.entry.target._tag !== "PrimaryConnectionTarget" &&
109 !isDesktopLocalConnectionTarget(activeEnvironment.entry.target);
110 const [disconnectingEnvironment, setDisconnectingEnvironment] = useState(false);
111 const handleDisconnectActiveEnvironment = async (environmentId: EnvironmentId) => {
112 setDisconnectingEnvironment(true);
113 const result = await setEnvironmentEnabled({ environmentId, enabled: false });
114 setDisconnectingEnvironment(false);
115 if (result._tag === "Failure") {
116 if (!isAtomCommandInterrupted(result)) {
117 const error = squashAtomCommandFailure(result);
118 toastManager.add(
119 stackedThreadToast({
120 type: "error",
121 title: "Could not disconnect server",
122 description: error instanceof Error ? error.message : "Failed to disconnect.",
123 }),
124 );
125 }
126 return;
127 }
128 void navigate({ to: "/", replace: true });
129 };
130 const handleDisconnectActiveEnvironmentStable = useStableCallback(
131 handleDisconnectActiveEnvironment,
132 );
133 const autoBalanceUpdateBanner = useAutoBalanceUpdateBanner(autoUpdateEnvironments);
134 const versionMismatch = resolveServerConfigVersionMismatch(serverConfig);
135 const versionMismatchServerLabel =
136 hasMultipleRegisteredEnvironments && activeThreadEnvironmentId !== null
137 ? `${activeEnvironment?.label ?? serverConfig?.environment.label ?? activeThreadEnvironmentId} server`
138 : "server";
139 const serverUpdateEnvironmentId = activeThreadEnvironmentId;
140 const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
141 const versionMismatchInstallation = serverConfig?.environment.capabilities.serverInstallation;
142 const versionMismatchDesktopAppUpdate = supportsDesktopAppUpdate(serverConfig);
143 const serverUpdateState = useAtomValue(
144 serverEnvironment.updateStateAtom(serverUpdateEnvironmentId),
145 );
146 const [dismissedServerUpdateState, setDismissedServerUpdateState] = useState<
147 typeof serverUpdateState | null
148 >(null);
149 const serverUpdateFailureDismissed =
150 serverUpdateState === dismissedServerUpdateState ||
151 isServerUpdateFailureDismissed(serverUpdateState);
152 return (() => {
153 const items: ComposerBannerStackItem[] = [];
154 const updateRunning = serverUpdateState.status === "running";
155 const unavailableConnection = activeEnvironmentUnavailableState?.connection ?? null;
156 const disconnectAction =
157 canDisconnectActiveEnvironment && activeEnvironmentUnavailableState ? (
158 <Button
159 size="xs"
160 variant="ghost"
161 disabled={disconnectingEnvironment}
162 title="Hide this server's threads. Switch it on again in Environments."
163 onClick={() =>
164 void handleDisconnectActiveEnvironmentStable(
165 activeEnvironmentUnavailableState.environmentId,
166 )
167 }
168 >
169 Disconnect server
170 </Button>
171 ) : undefined;
172 const environmentReconnecting =
173 unavailableConnection !== null &&
174 (unavailableConnection.phase === "connecting" ||
175 unavailableConnection.phase === "reconnecting");
176 const suppressUnavailableBanner =
177 environmentReconnecting && (updateRunning || !reconnectWarningGraceElapsed);
178 const showUnavailableBanner =
179 activeEnvironmentUnavailableState !== null &&
180 unavailableConnection !== null &&
181 !suppressUnavailableBanner;
182 if (showUnavailableBanner) {
183 items.push({
184 id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
185 variant: unavailableConnection.phase === "error" ? "error" : "warning",
186 group: "environment",
187 icon: <WifiOffIcon />,
188 title: `${activeEnvironmentUnavailableState.label} is ${environmentReconnecting ? "reconnecting" : "offline"}`,
189 description: activeEnvironment ? (
190 <ConnectionDiagnosisHeadline environment={activeEnvironment} />
191 ) : undefined,
192 actions: (
193 <>
194 {!environmentReconnecting ? (
195 <Button
196 size="xs"
197 variant="ghost"
198 onClick={() =>
199 void handleReconnectActiveEnvironmentStable(
200 activeEnvironmentUnavailableState.environmentId,
201 )
202 }
203 >
204 Reconnect
205 </Button>
206 ) : null}
207 {disconnectAction}
208 </>
209 ),
210 });
211 }
212 // An available update is offered by the sidebar's update pill; the composer only shows one
213 // that is running or failed, since either explains what this thread's server is doing.
214 if (
215 !automaticEnvironment &&
216 serverUpdateEnvironmentId &&
217 serverUpdateState.status !== "idle" &&
218 !serverUpdateFailureDismissed
219 ) {
220 const updateFailed = serverUpdateState.status === "failed";
221 items.push({
222 id: `server-version:${serverUpdateEnvironmentId}`,
223 variant: updateFailed ? "error" : "default",
224 group: "environment",
225 icon: <ComposerServerUpdateIcon status={serverUpdateState.status} />,
226 title: `${updateFailed ? "Could not update" : "Updating"} ${versionMismatchServerLabel}`,
227 description:
228 serverUpdateState.status === "failed"
229 ? serverUpdateState.message
230 : serverUpdateStageLabel(serverUpdateState.stage),
231 actions: !updateFailed ? (
232 disconnectAction
233 ) : !versionMismatch ||
234 (versionMismatchSelfUpdate === "desktop-managed" &&
235 !versionMismatchDesktopAppUpdate) ? undefined : (
236 <ServerUpdateAction
237 environmentId={serverUpdateEnvironmentId}
238 serverLabel={versionMismatchServerLabel}
239 selfUpdate={versionMismatchSelfUpdate}
240 installation={versionMismatchInstallation}
241 desktopAppUpdate={versionMismatchDesktopAppUpdate}
242 targetVersion={versionMismatch.clientVersion}
243 label="Retry"
244 variant="ghost"
245 />
246 ),
247 ...(updateFailed
248 ? {
249 dismissLabel: "Dismiss update notice",
250 onDismiss: () => {
251 dismissServerUpdateFailure(serverUpdateState);
252 setDismissedServerUpdateState(serverUpdateState);
253 },
254 }
255 : {}),
256 });
257 }
258 if (autoBalanceUpdateBanner) items.push(autoBalanceUpdateBanner);
259 return items;
260 })() as ComposerBannerStackItem[];
261}