diff --git a/apps/web/src/AppRoot.test.tsx b/apps/web/src/AppRoot.test.tsx index d6d7434769..a08f3be532 100644 --- a/apps/web/src/AppRoot.test.tsx +++ b/apps/web/src/AppRoot.test.tsx @@ -6,7 +6,7 @@ import { ElectronBrowserHost } from "./browser/ElectronBrowserHost"; import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts"; import { AppAtomRegistryProvider } from "./rpc/atomRegistry"; import type { AppRouter } from "./router"; -import { AppRoot } from "./AppRoot"; +import { AppRoot, ServerRestartReconnectHost } from "./AppRoot"; describe("AppRoot", () => { it("shares the application atom registry with routed UI and renderer-wide desktop hosts", () => { @@ -16,9 +16,13 @@ describe("AppRoot", () => { const children = Children.toArray( (root as ReactElement<{ readonly children: ReactNode }>).props.children, ); - expect(children).toHaveLength(3); - expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider); - expect(isValidElement(children[1]) && children[1].type).toBe(PreviewAutomationHosts); - expect(isValidElement(children[2]) && children[2].type).toBe(ElectronBrowserHost); + expect(children).toHaveLength(4); + // The restart-reconnect host is inside the registry provider (it reads + // environment atoms) and outside the router, because a server restart + // outlives the route the update was triggered from. + expect(isValidElement(children[0]) && children[0].type).toBe(ServerRestartReconnectHost); + expect(isValidElement(children[1]) && children[1].type).toBe(RouterProvider); + expect(isValidElement(children[2]) && children[2].type).toBe(PreviewAutomationHosts); + expect(isValidElement(children[3]) && children[3].type).toBe(ElectronBrowserHost); }); }); diff --git a/apps/web/src/AppRoot.tsx b/apps/web/src/AppRoot.tsx index b1fd21f84f..85708eae23 100644 --- a/apps/web/src/AppRoot.tsx +++ b/apps/web/src/AppRoot.tsx @@ -4,6 +4,18 @@ import { ElectronBrowserHost } from "./browser/ElectronBrowserHost"; import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts"; import { AppAtomRegistryProvider } from "./rpc/atomRegistry"; import type { AppRouter } from "./router"; +import { useServerRestartReconnect } from "./useServerRestartReconnect"; + +/** + * Reconnects environments through an expected server restart. Mounted here + * because a restart outlives the view it was triggered from — the update + * action appears both in the chat composer's skew banner and in + * Settings → Connections. + */ +export function ServerRestartReconnectHost() { + useServerRestartReconnect(); + return null; +} /** * Owns renderer-wide providers. The Electron browser host intentionally sits @@ -13,6 +25,7 @@ import type { AppRouter } from "./router"; export function AppRoot({ router }: { readonly router: AppRouter }) { return ( + diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index c75a35dbcc..26f9dbdbfc 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -25,11 +25,7 @@ import { connectionStatusTitle, type EnvironmentConnectionPresentation, } from "@t3tools/client-runtime/connection"; -import { - clearExpectedServerRestart, - isServerRestarting, - useServerRestartExpected, -} from "~/serverRestartStore"; +import { isServerRestarting, useServerRestartExpected } from "~/serverRestartStore"; import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { parseScopedThreadKey, @@ -1634,45 +1630,10 @@ function ChatViewContent(props: ChatViewProps) { restartExpected: activeEnvironmentRestartExpected, environmentUnavailable: activeEnvironmentUnavailable, }); - // While the restart is expected, poke the supervisor on a flat cadence so a - // 16-second backoff sleep cannot outlast the server's return. - // - // The window also has to end at the right moment. Ending it on any healthy - // connection is wrong — it is armed while the old server is still connected, - // so that clears it before the restart it exists to cover. Never ending it - // is also wrong — an unrelated outage later in the window would be dressed - // up as an intentional restart. So it ends once this environment has gone - // away and come back: the restart it was armed for has been seen through. - const restartSawDisconnectRef = useRef(false); - useEffect(() => { - if (activeEnvironmentId === null || !activeEnvironmentRestartExpected) { - restartSawDisconnectRef.current = false; - return; - } - if (activeEnvironmentConnectionPhase === "connected") { - if (restartSawDisconnectRef.current) { - restartSawDisconnectRef.current = false; - clearExpectedServerRestart(activeEnvironmentId); - } - return; - } - restartSawDisconnectRef.current = true; - // Only wake the supervisor out of a backoff sleep; while an attempt is - // live, retryNow would interrupt and restart it. - if (activeEnvironment?.connection.retryAt == null) { - return; - } - const timer = setTimeout(() => { - void retryEnvironment(activeEnvironmentId); - }, 2_000); - return () => clearTimeout(timer); - }, [ - activeEnvironment?.connection.retryAt, - activeEnvironmentConnectionPhase, - activeEnvironmentId, - activeEnvironmentRestartExpected, - retryEnvironment, - ]); + // Reconnecting through the restart (and ending the window once its restart + // has been seen through) is owned by useServerRestartReconnect at the app + // level, since an update can be triggered from Settings → Connections too. + // This view only presents the result. const handleReconnectActiveEnvironment = useCallback( async (environmentId: EnvironmentId) => { const result = await retryEnvironment(environmentId); diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 52b8953012..7e39263b20 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -130,6 +130,7 @@ import { useEnvironments, usePrimaryEnvironment, } from "~/state/environments"; +import { isServerRestarting, useServerRestartExpected } from "~/serverRestartStore"; import { useAtomCommand } from "../../state/use-atom-command"; import { ConnectionStatusDot } from "../ConnectionStatusDot"; import { ServerUpdateAction } from "../ServerUpdateAction"; @@ -1353,15 +1354,24 @@ function SavedBackendListRow({ const connectionState = environment.connection.phase; const isConnected = connectionState === "connected"; const isConnecting = connectionState === "connecting" || connectionState === "reconnecting"; + // An update started from this row restarts the server, so present that + // disconnect as the expected restart rather than as a connection failure — + // the same treatment the chat composer's skew banner gives it. + const isRestarting = isServerRestarting({ + restartExpected: useServerRestartExpected(environmentId), + environmentUnavailable: !isConnected, + }); const stateDotClassName = connectionState === "connected" ? "bg-success" - : connectionState === "connecting" || connectionState === "reconnecting" + : isRestarting || connectionState === "connecting" || connectionState === "reconnecting" ? "bg-warning" : connectionState === "error" ? "bg-destructive" : "bg-muted-foreground/40"; - const statusTooltip = connectionStatusText(environment.connection); + const statusTooltip = isRestarting + ? "Restarting to finish the server update..." + : connectionStatusText(environment.connection); const errorTraceId = environment.connection.traceId; const { copyToClipboard: copyTraceIdToClipboard } = useCopyToClipboard<{ traceId: string }>({ target: "trace ID", @@ -1440,7 +1450,13 @@ function SavedBackendListRow({ /> ) : null} - {environment.connection.error ? ( + {isRestarting ? ( +

+ + Restarting to finish the server update — reconnecting automatically. + +

+ ) : environment.connection.error ? (

{connectionStatusText(environment.connection)} {errorTraceId ? ( diff --git a/apps/web/src/useServerRestartReconnect.test.ts b/apps/web/src/useServerRestartReconnect.test.ts new file mode 100644 index 0000000000..735c66bd7a --- /dev/null +++ b/apps/web/src/useServerRestartReconnect.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + MAX_RETRIES_PER_WINDOW, + restartRetryDelayMs, + shouldPokeRestartRetry, +} from "./useServerRestartReconnect"; + +describe("restart reconnect pacing", () => { + it("starts fast so a backoff sleep cannot outlast the server's return", () => { + expect(restartRetryDelayMs(0)).toBe(2_000); + expect(restartRetryDelayMs(1)).toBe(2_000); + }); + + it("eases off rather than polling at a fixed rate for the whole window", () => { + const delays = [0, 1, 2, 3, 4, 5, 20].map(restartRetryDelayMs); + // Monotonic, and flat once it reaches the ceiling. + for (let index = 1; index < delays.length; index++) { + expect(delays[index]).toBeGreaterThanOrEqual(delays[index - 1] ?? 0); + } + expect(restartRetryDelayMs(20)).toBe(8_000); + }); + + describe("shouldPokeRestartRetry", () => { + const base = { connected: false, retryAt: 1, attempts: 0 }; + + it("pokes a supervisor asleep in backoff", () => { + expect(shouldPokeRestartRetry(base)).toBe(true); + }); + + it("does not poke a connected environment", () => { + expect(shouldPokeRestartRetry({ ...base, connected: true })).toBe(false); + }); + + it("does not interrupt a live connection attempt", () => { + // retryAt is null while an attempt is in flight; waking it would tear + // the attempt down and restart it, making reconnection slower. + expect(shouldPokeRestartRetry({ ...base, retryAt: null })).toBe(false); + }); + + it("stops once the retry budget is spent", () => { + // The window is a duration, not a budget. Without the cap a server that + // never returns would be retried for the window's full length, and each + // poke rebuilds a connection attempt. + expect(shouldPokeRestartRetry({ ...base, attempts: MAX_RETRIES_PER_WINDOW - 1 })).toBe(true); + expect(shouldPokeRestartRetry({ ...base, attempts: MAX_RETRIES_PER_WINDOW })).toBe(false); + expect(shouldPokeRestartRetry({ ...base, attempts: MAX_RETRIES_PER_WINDOW + 5 })).toBe(false); + }); + }); +}); diff --git a/apps/web/src/useServerRestartReconnect.ts b/apps/web/src/useServerRestartReconnect.ts new file mode 100644 index 0000000000..6c1866bb82 --- /dev/null +++ b/apps/web/src/useServerRestartReconnect.ts @@ -0,0 +1,151 @@ +/** + * Drives expected-restart reconnection for every environment with an armed + * restart window, wherever the update was triggered from. + * + * This is mounted once at the app level rather than in a route: the update + * action appears in the chat composer's version-mismatch banner *and* in + * Settings → Connections, and the restart it schedules outlives whatever view + * the user happens to be on. Scoping this to one view meant an update started + * from Settings got no fast reconnect and left its window uncleared. + */ +import type { EnvironmentId } from "@t3tools/contracts"; +import { useEffect, useRef } from "react"; + +import { environmentCatalog } from "./connection/catalog"; +import { clearExpectedServerRestart, useServerRestartStore } from "./serverRestartStore"; +import { useEnvironments } from "./state/environments"; +import { useAtomCommand } from "./state/use-atom-command"; + +/** + * Retry cadence while a restart is expected. Starts fast — a restart is back + * in seconds, and the supervisor's own 1s→16s escalation is what strands the + * client — then eases off so a server that never returns is not polled at a + * fixed 2s for the whole window. + */ +const RETRY_DELAYS_MS = [2_000, 2_000, 3_000, 5_000, 8_000] as const; + +/** + * Upper bound on pokes per restart window. The window is a duration, not a + * budget, so without a cap a slow-starting server would be retried for its + * full length; each poke tears down and rebuilds a connection attempt, so a + * runaway loop is real work. Reaching the cap leaves normal supervisor + * backoff in charge, which is the correct end state for a server that is not + * coming back. + */ +export const MAX_RETRIES_PER_WINDOW = 12; + +export function restartRetryDelayMs(attempt: number): number { + return RETRY_DELAYS_MS[Math.min(attempt, RETRY_DELAYS_MS.length - 1)] ?? 8_000; +} + +/** + * Whether to poke the supervisor for an environment inside a restart window. + * Requires a supervisor asleep in backoff (waking a live attempt restarts it, + * making reconnection slower) and an unspent retry budget. + */ +export function shouldPokeRestartRetry(input: { + readonly connected: boolean; + readonly retryAt: number | null; + readonly attempts: number; +}): boolean { + if (input.connected || input.retryAt == null) { + return false; + } + return input.attempts < MAX_RETRIES_PER_WINDOW; +} + +interface RestartProgress { + /** Pokes issued for the current window. */ + attempts: number; + /** The restart's disconnect has been observed for this window. */ + sawDisconnect: boolean; + /** Window identity, so a re-armed window restarts the budget. */ + expiresAt: number; +} + +export function useServerRestartReconnect(): void { + const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false }); + const expiresAtByEnvironmentId = useServerRestartStore((state) => state.expiresAtByEnvironmentId); + const { environments } = useEnvironments(); + const progressRef = useRef(new Map()); + + // Effects key off primitives so an unstable environment array identity + // cannot restart the timer on every unrelated render. + const armed = environments + .filter((environment) => expiresAtByEnvironmentId[environment.environmentId] !== undefined) + .map((environment) => ({ + environmentId: environment.environmentId, + expiresAt: expiresAtByEnvironmentId[environment.environmentId] ?? 0, + connected: environment.connection.phase === "connected", + // Only wake a supervisor that is asleep in backoff; interrupting a live + // attempt would restart it and make things slower, not faster. + retryAt: environment.connection.retryAt, + })); + const armedKey = armed + .map( + (entry) => + `${entry.environmentId}:${entry.expiresAt}:${String(entry.connected)}:${String(entry.retryAt ?? 0)}`, + ) + .join("|"); + + useEffect(() => { + const progress = progressRef.current; + for (const key of Array.from(progress.keys())) { + if (!armed.some((entry) => entry.environmentId === key)) { + progress.delete(key); + } + } + + const timers: Array> = []; + for (const entry of armed) { + const current = progress.get(entry.environmentId); + const state: RestartProgress = + current === undefined || current.expiresAt !== entry.expiresAt + ? { + attempts: 0, + sawDisconnect: current?.sawDisconnect ?? false, + expiresAt: entry.expiresAt, + } + : current; + progress.set(entry.environmentId, state); + + if (entry.connected) { + // Ending the window needs the disconnect to have been seen first: it + // is armed while the old server is still connected, so "connected" + // alone would clear it before the restart it exists to cover. Never + // clearing is equally wrong — a later unrelated outage would then be + // dressed up as an intentional restart. + if (state.sawDisconnect) { + progress.delete(entry.environmentId); + clearExpectedServerRestart(entry.environmentId as EnvironmentId); + } + continue; + } + + state.sawDisconnect = true; + if ( + !shouldPokeRestartRetry({ + connected: entry.connected, + retryAt: entry.retryAt, + attempts: state.attempts, + }) + ) { + continue; + } + const delay = restartRetryDelayMs(state.attempts); + timers.push( + setTimeout(() => { + state.attempts += 1; + void retryEnvironment(entry.environmentId as EnvironmentId); + }, delay), + ); + } + return () => { + for (const timer of timers) { + clearTimeout(timer); + } + }; + // armedKey is the stable serialization of `armed`; depending on the array + // itself would re-run this on every render. + }, [armedKey, retryEnvironment]); +}