Skip to content

Commit 2d73746

Browse files
authored
fix(web): disconnect offline servers from threads (pingdotgg#11671)
1 parent c07575f commit 2d73746

3 files changed

Lines changed: 172 additions & 35 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 82 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,8 @@ import {
308308
} from "../lib/composerContextRecords";
309309
import { type ReviewCommentContext } from "../reviewCommentContext";
310310
import { environmentCatalog } from "../connection/catalog";
311+
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
312+
import { useEnvironmentDisconnectDelay } from "../hooks/useEnvironmentDisconnectDelay";
311313
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
312314
import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions";
313315
import { useEnvironmentQuery } from "../state/query";
@@ -1497,6 +1499,9 @@ export default function ChatView(props: ChatViewProps) {
14971499
const { environments } = useEnvironments();
14981500
const primaryEnvironment = usePrimaryEnvironment();
14991501
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
1502+
const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, {
1503+
reportFailure: false,
1504+
});
15001505
const environmentById = useMemo(
15011506
() => new Map(environments.map((environment) => [environment.environmentId, environment])),
15021507
[environments],
@@ -2208,6 +2213,37 @@ export default function ChatView(props: ChatViewProps) {
22082213
},
22092214
[retryEnvironment],
22102215
);
2216+
const disconnectDelayElapsed = useEnvironmentDisconnectDelay(
2217+
activeEnvironmentUnavailable ? activeEnvironment.environmentId : null,
2218+
);
2219+
const canDisconnectActiveEnvironment =
2220+
disconnectDelayElapsed &&
2221+
activeEnvironment !== null &&
2222+
activeEnvironment.entry.target._tag !== "PrimaryConnectionTarget" &&
2223+
!isDesktopLocalConnectionTarget(activeEnvironment.entry.target);
2224+
const [disconnectingEnvironment, setDisconnectingEnvironment] = useState(false);
2225+
const handleDisconnectActiveEnvironment = useCallback(
2226+
async (environmentId: EnvironmentId) => {
2227+
setDisconnectingEnvironment(true);
2228+
const result = await setEnvironmentEnabled({ environmentId, enabled: false });
2229+
setDisconnectingEnvironment(false);
2230+
if (result._tag === "Failure") {
2231+
if (!isAtomCommandInterrupted(result)) {
2232+
const error = squashAtomCommandFailure(result);
2233+
toastManager.add(
2234+
stackedThreadToast({
2235+
type: "error",
2236+
title: "Could not disconnect server",
2237+
description: error instanceof Error ? error.message : "Failed to disconnect.",
2238+
}),
2239+
);
2240+
}
2241+
return;
2242+
}
2243+
void navigate({ to: "/", replace: true });
2244+
},
2245+
[navigate, setEnvironmentEnabled],
2246+
);
22112247
const logicalProjectEnvironments = useMemo(() => {
22122248
if (!activeProject) return [];
22132249
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
@@ -2448,6 +2484,20 @@ export default function ChatView(props: ChatViewProps) {
24482484
const items: ComposerBannerStackItem[] = [];
24492485
const updateRunning = serverUpdateState.status === "running";
24502486
const unavailableConnection = activeEnvironmentUnavailableState?.connection ?? null;
2487+
const disconnectAction =
2488+
canDisconnectActiveEnvironment && activeEnvironmentUnavailableState ? (
2489+
<Button
2490+
size="xs"
2491+
variant="ghost"
2492+
disabled={disconnectingEnvironment}
2493+
title="Hide this server's threads. Switch it on again in Connections."
2494+
onClick={() =>
2495+
void handleDisconnectActiveEnvironment(activeEnvironmentUnavailableState.environmentId)
2496+
}
2497+
>
2498+
Disconnect server
2499+
</Button>
2500+
) : undefined;
24512501
const environmentReconnecting =
24522502
unavailableConnection !== null &&
24532503
(unavailableConnection.phase === "connecting" ||
@@ -2481,35 +2531,30 @@ export default function ChatView(props: ChatViewProps) {
24812531
),
24822532
title: `${unavailableConnection.phase === "connecting" ? "Connecting" : "Reconnecting"} to ${activeEnvironmentUnavailableState.label}`,
24832533
description: "Finishing an update",
2534+
actions: disconnectAction,
24842535
});
24852536
} else {
24862537
items.push({
24872538
id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,
24882539
variant: unavailableConnection.phase === "error" ? "error" : "warning",
24892540
icon: <WifiOffIcon />,
24902541
title: `${activeEnvironmentUnavailableState.label} is ${environmentReconnecting ? "reconnecting" : "offline"}`,
2491-
description: environmentReconnecting ? "Trying again" : "Reconnect to continue",
24922542
actions: (
24932543
<>
2494-
<Button
2495-
size="xs"
2496-
variant="ghost"
2497-
disabled={environmentReconnecting}
2498-
onClick={() =>
2499-
void handleReconnectActiveEnvironment(
2500-
activeEnvironmentUnavailableState.environmentId,
2501-
)
2502-
}
2503-
>
2504-
{environmentReconnecting ? "Reconnecting..." : "Reconnect"}
2505-
</Button>
2506-
<Button
2507-
size="xs"
2508-
variant="ghost"
2509-
onClick={() => void navigate({ to: "/settings/connections" })}
2510-
>
2511-
Connections
2512-
</Button>
2544+
{!environmentReconnecting ? (
2545+
<Button
2546+
size="xs"
2547+
variant="ghost"
2548+
onClick={() =>
2549+
void handleReconnectActiveEnvironment(
2550+
activeEnvironmentUnavailableState.environmentId,
2551+
)
2552+
}
2553+
>
2554+
Reconnect
2555+
</Button>
2556+
) : null}
2557+
{disconnectAction}
25132558
</>
25142559
),
25152560
});
@@ -2564,22 +2609,22 @@ export default function ChatView(props: ChatViewProps) {
25642609
(versionMismatchSelfUpdate !== "desktop-managed" || !versionMismatchDesktopAppUpdate)
25652610
? serverUpdateGuidance(versionMismatchSelfUpdate)
25662611
: undefined,
2567-
actions:
2568-
updateInProgress ||
2569-
!versionMismatch ||
2612+
actions: updateInProgress ? (
2613+
disconnectAction
2614+
) : !versionMismatch ||
25702615
(versionMismatchSelfUpdate === "desktop-managed" &&
25712616
!versionMismatchDesktopAppUpdate) ? undefined : (
2572-
<ServerUpdateAction
2573-
environmentId={serverUpdateEnvironmentId}
2574-
serverLabel={versionMismatchServerLabel}
2575-
selfUpdate={versionMismatchSelfUpdate}
2576-
desktopAppUpdate={versionMismatchDesktopAppUpdate}
2577-
threadContinuation={versionMismatchThreadContinuation}
2578-
targetVersion={versionMismatch.clientVersion}
2579-
label={updateFailed ? "Retry" : "Update"}
2580-
variant="ghost"
2581-
/>
2582-
),
2617+
<ServerUpdateAction
2618+
environmentId={serverUpdateEnvironmentId}
2619+
serverLabel={versionMismatchServerLabel}
2620+
selfUpdate={versionMismatchSelfUpdate}
2621+
desktopAppUpdate={versionMismatchDesktopAppUpdate}
2622+
threadContinuation={versionMismatchThreadContinuation}
2623+
targetVersion={versionMismatch.clientVersion}
2624+
label={updateFailed ? "Retry" : "Update"}
2625+
variant="ghost"
2626+
/>
2627+
),
25832628
...(updateInProgress || (!updateFailed && !versionMismatchDismissKey)
25842629
? {}
25852630
: {
@@ -2603,7 +2648,9 @@ export default function ChatView(props: ChatViewProps) {
26032648
activeEnvironmentUnavailableState,
26042649
reconnectWarningGraceElapsed,
26052650
handleReconnectActiveEnvironment,
2606-
navigate,
2651+
canDisconnectActiveEnvironment,
2652+
disconnectingEnvironment,
2653+
handleDisconnectActiveEnvironment,
26072654
setDismissedVersionMismatchKey,
26082655
showVersionMismatchBanner,
26092656
serverUpdateFailureDismissed,
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { EnvironmentId } from "@t3tools/contracts";
2+
import { act, useLayoutEffect } from "react";
3+
import { create, type ReactTestRenderer } from "react-test-renderer";
4+
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
5+
6+
import { useEnvironmentDisconnectDelay } from "./useEnvironmentDisconnectDelay";
7+
8+
const environmentId = EnvironmentId.make("remote");
9+
let renderer: ReactTestRenderer;
10+
let elapsed = false;
11+
12+
function Probe({ unavailableId }: { unavailableId: EnvironmentId | null }) {
13+
const value = useEnvironmentDisconnectDelay(unavailableId);
14+
useLayoutEffect(() => {
15+
elapsed = value;
16+
});
17+
return null;
18+
}
19+
20+
beforeEach(() => {
21+
vi.useFakeTimers();
22+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
23+
act(() => {
24+
renderer = create(<Probe unavailableId={environmentId} />);
25+
});
26+
});
27+
28+
afterEach(() => {
29+
act(() => renderer.unmount());
30+
vi.useRealTimers();
31+
vi.unstubAllGlobals();
32+
});
33+
34+
it("waits 20 seconds without restarting on renders for the same environment", () => {
35+
act(() => vi.advanceTimersByTime(10_000));
36+
expect(elapsed).toBe(false);
37+
act(() => renderer.update(<Probe unavailableId={environmentId} />));
38+
act(() => vi.advanceTimersByTime(9_999));
39+
expect(elapsed).toBe(false);
40+
act(() => vi.advanceTimersByTime(1));
41+
expect(elapsed).toBe(true);
42+
});
43+
44+
it("cancels a brief outage and starts a fresh delay on the next outage", () => {
45+
act(() => vi.advanceTimersByTime(10_000));
46+
act(() => renderer.update(<Probe unavailableId={null} />));
47+
act(() => vi.advanceTimersByTime(20_000));
48+
expect(elapsed).toBe(false);
49+
act(() => renderer.update(<Probe unavailableId={environmentId} />));
50+
act(() => vi.advanceTimersByTime(19_999));
51+
expect(elapsed).toBe(false);
52+
act(() => vi.advanceTimersByTime(1));
53+
expect(elapsed).toBe(true);
54+
act(() => renderer.update(<Probe unavailableId={null} />));
55+
expect(elapsed).toBe(false);
56+
});
57+
58+
it("does not carry elapsed time to another environment", () => {
59+
act(() => vi.advanceTimersByTime(20_000));
60+
expect(elapsed).toBe(true);
61+
act(() => renderer.update(<Probe unavailableId={EnvironmentId.make("another-remote")} />));
62+
expect(elapsed).toBe(false);
63+
act(() => vi.advanceTimersByTime(20_000));
64+
expect(elapsed).toBe(true);
65+
});
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import type { EnvironmentId } from "@t3tools/contracts";
2+
import { useEffect, useState } from "react";
3+
4+
/** Wait through brief outages before offering to switch off the active environment. */
5+
export function useEnvironmentDisconnectDelay(unavailableEnvironmentId: EnvironmentId | null) {
6+
const [delay, setDelay] = useState({ environmentId: unavailableEnvironmentId, elapsed: false });
7+
if (delay.environmentId !== unavailableEnvironmentId) {
8+
setDelay({ environmentId: unavailableEnvironmentId, elapsed: false });
9+
}
10+
11+
useEffect(() => {
12+
if (unavailableEnvironmentId === null) return;
13+
const timeout = setTimeout(
14+
() => setDelay({ environmentId: unavailableEnvironmentId, elapsed: true }),
15+
20_000,
16+
);
17+
return () => clearTimeout(timeout);
18+
}, [unavailableEnvironmentId]);
19+
20+
return (
21+
unavailableEnvironmentId !== null &&
22+
delay.environmentId === unavailableEnvironmentId &&
23+
delay.elapsed
24+
);
25+
}

0 commit comments

Comments
 (0)