@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 298 lines 12.6 KB
Raw
1 import { T, msg, useGT, useMessages } from "gt-react";
2 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3 import { m } from "~/i18n/messages";
4 import { useStableCallback } from "../../hooks/useStableCallback";
5 import { type EnvironmentId } from "@t3tools/contracts";
6 import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
7 import { useAtomValue } from "@effect/atom-react";
8 import { useState } from "react";
9 import { useNavigate } from "@tanstack/react-router";
10 import {
11 isAtomCommandInterrupted,
12 squashAtomCommandFailure,
13 } from "@t3tools/client-runtime/state/runtime";
14 import { WifiOffIcon } from "lucide-react";
15 import { stackedThreadToast, toastManager } from "../ui/toast";
16 import { environmentCatalog } from "../../connection/catalog";
17 import { ConnectionDiagnosisHeadline } from "../settings/ConnectionDiagnosisDetails";
18 import { isDesktopLocalConnectionTarget } from "../../connection/desktopLocal";
19 import {
20 useEnvironmentDisconnectDelay,
21 useEnvironmentStateHeldFor,
22 } from "../../hooks/useEnvironmentDisconnectDelay";
23 import { serverEnvironment } from "../../state/server";
24 import { type EnvironmentPresentation } from "../../state/environments";
25 import type { ComposerBannerStackItem } from "./ComposerBannerStack";
26 import { ENVIRONMENT_RECONNECT_WARNING_GRACE_MS } from "../ChatView.logic";
27 import { useAtomCommand } from "../../state/use-atom-command";
28 import { Button } from "../ui/button";
29 import { ServerUpdateAction, serverUpdateStageLabel } from "../ServerUpdateAction";
30 import { useAutoBalanceUpdateBanner } from "./useAutoBalanceUpdateBanner";
31 import { ComposerServerUpdateIcon } from "./ComposerServerUpdateStatus";
32 import {
33 dismissServerUpdateFailure,
34 isServerUpdateFailureDismissed,
35 resolveServerConfigVersionMismatch,
36 resolveServerSelfUpdateCapability,
37 supportsDesktopAppUpdate,
38 } from "../../versionSkew";
39
40 export type EnvironmentUnavailableState = {
41 readonly environmentId: EnvironmentId;
42 readonly label: string;
43 readonly connection: EnvironmentConnectionPresentation;
44 };
45
46 interface 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 */
61 export 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} server", { environment: versionMismatchServerName })
151 : gt("server", { $context: "noun, the T3 Code 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} is waiting to approve this device", {
206 environment: activeEnvironmentUnavailableState.label,
207 })
208 : environmentReconnecting
209 ? gt("{environment} is reconnecting", {
210 environment: activeEnvironmentUnavailableState.label,
211 })
212 : gt("{environment} is offline", {
213 environment: activeEnvironmentUnavailableState.label,
214 }),
215 description: awaitingApproval ? (
216 (unavailableConnection.error ?? undefined)
217 ) : activeEnvironment ? (
218 <ConnectionDiagnosisHeadline environment={activeEnvironment} />
219 ) : undefined,
220 actions: (
221 <>
222 {unavailableConnection.phase !== "connecting" ? (
223 <Button
224 size="xs"
225 variant="ghost"
226 onClick={() =>
227 void handleReconnectActiveEnvironmentStable(
228 activeEnvironmentUnavailableState.environmentId,
229 )
230 }
231 >
232 {environmentReconnecting ? gt("Retry now") : gt("Reconnect")}
233 </Button>
234 ) : null}
235 {disconnectAction}
236 </>
237 ),
238 });
239 }
240 // An available update is offered by the sidebar's update pill; the composer only shows one
241 // that is running or failed, since either explains what this thread's server is doing.
242 if (
243 !automaticEnvironment &&
244 serverUpdateEnvironmentId &&
245 serverUpdateState.status !== "idle" &&
246 !serverUpdateFailureDismissed
247 ) {
248 const updateFailed = serverUpdateState.status === "failed";
249 items.push({
250 id: `server-version:${serverUpdateEnvironmentId}`,
251 variant: updateFailed ? "error" : "default",
252 group: "environment",
253 icon: <ComposerServerUpdateIcon status={serverUpdateState.status} />,
254 title:
255 versionMismatchServerName !== null
256 ? updateFailed
257 ? gt("Could not update {environment} server", {
258 environment: versionMismatchServerName,
259 })
260 : gt("Updating {environment} server", { environment: versionMismatchServerName })
261 : updateFailed
262 ? gt("Could not update server")
263 : gt("Updating server"),
264 description:
265 serverUpdateState.status === "failed"
266 ? serverUpdateState.message
267 : serverUpdateStageLabel(serverUpdateState.stage, messages),
268 actions: !updateFailed ? (
269 disconnectAction
270 ) : !versionMismatch ||
271 (versionMismatchSelfUpdate === "desktop-managed" &&
272 !versionMismatchDesktopAppUpdate) ? undefined : (
273 <ServerUpdateAction
274 environmentId={serverUpdateEnvironmentId}
275 serverLabel={versionMismatchServerLabel}
276 selfUpdate={versionMismatchSelfUpdate}
277 installation={versionMismatchInstallation}
278 desktopAppUpdate={versionMismatchDesktopAppUpdate}
279 targetVersion={versionMismatch.clientVersion}
280 label={gt("Retry", { $context: "verb, retries the server update" })}
281 variant="ghost"
282 />
283 ),
284 ...(updateFailed
285 ? {
286 dismissLabel: gt("Dismiss update notice"),
287 onDismiss: () => {
288 dismissServerUpdateFailure(serverUpdateState);
289 setDismissedServerUpdateState(serverUpdateState);
290 },
291 }
292 : {}),
293 });
294 }
295 if (autoBalanceUpdateBanner) items.push(autoBalanceUpdateBanner);
296 return items;
297 })() as ComposerBannerStackItem[];
298 }