Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useSystemComposerBanners.tsx

264 lines11.1 KB

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