diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 26857b79fb..c1745d7d36 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -25,12 +25,7 @@ import { connectionStatusTitle, type EnvironmentConnectionPresentation, } from "@t3tools/client-runtime/connection"; -import { - clearExpectedServerRestart, - isServerRestarting, - markServerRestartDisconnected, - useServerRestartExpectation, -} from "~/serverRestartStore"; +import { isServerRestarting, useServerRestartExpected } from "~/serverRestartStore"; import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { parseScopedThreadKey, @@ -1630,28 +1625,25 @@ function ChatViewContent(props: ChatViewProps) { // present them calmly and retry fast instead of letting exponential // backoff strand the client asleep when the server comes back. const activeEnvironmentId = activeEnvironment?.environmentId ?? null; - const activeEnvironmentRestartExpectation = useServerRestartExpectation(activeEnvironmentId); - const activeEnvironmentRestartExpected = activeEnvironmentRestartExpectation.expected; - const activeEnvironmentRestartSawDisconnect = activeEnvironmentRestartExpectation.sawDisconnect; + const activeEnvironmentRestartExpected = useServerRestartExpected(activeEnvironmentId); const activeEnvironmentRestarting = isServerRestarting({ - expectation: activeEnvironmentRestartExpectation, + 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 is + // never cleared here: it is armed while the old server is still connected, + // so nothing observed on the connection distinguishes "before the restart" + // from "after it". Presentation already gates on the environment being + // away, which makes a lingering window inert once the replacement is back. useEffect(() => { - if (activeEnvironmentId === null || !activeEnvironmentRestartExpected) { + if ( + activeEnvironmentId === null || + !activeEnvironmentRestartExpected || + activeEnvironmentConnectionPhase === "connected" + ) { return; } - if (activeEnvironmentConnectionPhase === "connected") { - // The window is armed while the old server is still connected, so a - // healthy connection only ends it once the restart's disconnect has - // actually been seen. Clearing on any connected render would destroy - // the window before the restart it exists to cover. - if (activeEnvironmentRestartSawDisconnect) { - clearExpectedServerRestart(activeEnvironmentId); - } - return; - } - markServerRestartDisconnected(activeEnvironmentId); // 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) { @@ -1666,7 +1658,6 @@ function ChatViewContent(props: ChatViewProps) { activeEnvironmentConnectionPhase, activeEnvironmentId, activeEnvironmentRestartExpected, - activeEnvironmentRestartSawDisconnect, retryEnvironment, ]); const handleReconnectActiveEnvironment = useCallback( diff --git a/apps/web/src/components/ServerUpdateAction.test.tsx b/apps/web/src/components/ServerUpdateAction.test.tsx index fbdf812512..093b22a513 100644 --- a/apps/web/src/components/ServerUpdateAction.test.tsx +++ b/apps/web/src/components/ServerUpdateAction.test.tsx @@ -16,7 +16,11 @@ const testState = vi.hoisted(() => ({ const restartStore = vi.hoisted(() => ({ expect: vi.fn(), clear: vi.fn(), - expectation: vi.fn(() => ({ expected: false, sawDisconnect: false })), + expected: vi.fn(() => false), +})); + +const environmentState = vi.hoisted(() => ({ + useEnvironment: vi.fn(() => ({ connection: { phase: "connected" } })), })); const hooks = vi.hoisted(() => { @@ -94,9 +98,12 @@ vi.mock("~/serverRestartStore", async (importOriginal) => { ...actual, expectServerRestart: restartStore.expect, clearExpectedServerRestart: restartStore.clear, - useServerRestartExpectation: restartStore.expectation, + useServerRestartExpected: restartStore.expected, }; }); +vi.mock("~/state/environments", () => ({ + useEnvironment: environmentState.useEnvironment, +})); import { ServerUpdateAction } from "./ServerUpdateAction"; @@ -139,8 +146,10 @@ describe("ServerUpdateAction", () => { testState.toast.mockReset(); restartStore.expect.mockReset(); restartStore.clear.mockReset(); - restartStore.expectation.mockReset(); - restartStore.expectation.mockReturnValue({ expected: false, sawDisconnect: false }); + restartStore.expected.mockReset(); + restartStore.expected.mockReturnValue(false); + environmentState.useEnvironment.mockReset(); + environmentState.useEnvironment.mockReturnValue({ connection: { phase: "connected" } }); }); afterEach(() => { diff --git a/apps/web/src/components/ServerUpdateAction.tsx b/apps/web/src/components/ServerUpdateAction.tsx index 1f5e721d2c..e8a8bbfb4a 100644 --- a/apps/web/src/components/ServerUpdateAction.tsx +++ b/apps/web/src/components/ServerUpdateAction.tsx @@ -14,9 +14,10 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; import { clearExpectedServerRestart, expectServerRestart, - isServerRestartSettled, - useServerRestartExpectation, + isExpectedRestartResolved, + useServerRestartExpected, } from "~/serverRestartStore"; +import { useEnvironment } from "~/state/environments"; import { serverEnvironment } from "~/state/server"; import { useAtomCommand } from "~/state/use-atom-command"; import { manualServerUpdateCommand } from "~/versionSkew"; @@ -104,17 +105,46 @@ export function ServerUpdateAction({ ); // The restart is scheduled after the RPC is acknowledged, so a rejected - // restart (or a replacement that comes back on the old version) can no - // longer be reported through the call. Without this, the mismatch banner - // would keep its only action disabled for the full safety window. Once the - // restart window has closed and this component is still mounted — meaning - // the skew is unresolved and the server is answering again — release the - // action so the user can retry immediately. - const restartSettled = isServerRestartSettled(useServerRestartExpectation(environmentId)); + // restart — or a replacement that comes back on the old version — can no + // longer be reported through the call. Without a release path the mismatch + // banner would keep its only action disabled for the full safety window. + // + // The signal is the environment going away and then answering again while + // this component is still mounted: still mounted means the skew is + // unresolved, so whatever restarted did not deliver the new version. + // Deliberately independent of the restart window, which is UI presentation + // state and can lapse or be re-armed for unrelated reasons. + // Two ways that resolves, because a rejected restart may or may not have + // taken the connection down with it: + // - the environment went away and came back, so something restarted but + // did not deliver the new version; or + // - the restart window lapsed with the connection never dropping, so no + // restart ever happened (systemd refused it and rolled back). + const connectionPhase = useEnvironment(environmentId)?.connection.phase ?? null; + const connectionUnavailable = connectionPhase !== null && connectionPhase !== "connected"; + const restartExpected = useServerRestartExpected(environmentId); + const wentAwayRef = useRef(false); + const sawWindowRef = useRef(false); + if (connectionUnavailable) { + wentAwayRef.current = true; + } + if (restartExpected) { + // Guards against reading a not-yet-rendered window as "already lapsed" + // in the render between the click and the store update landing. + sawWindowRef.current = true; + } + const restartResolved = isExpectedRestartResolved({ + sawRestartWindow: sawWindowRef.current, + restartExpected, + wentAway: wentAwayRef.current, + environmentUnavailable: connectionUnavailable, + }); useEffect(() => { - if (!restartSettled || !inFlightRef.current) { + if (!restartResolved || !inFlightRef.current) { return; } + wentAwayRef.current = false; + sawWindowRef.current = false; if (expiryRef.current !== null) { clearTimeout(expiryRef.current); expiryRef.current = null; @@ -122,7 +152,7 @@ export function ServerUpdateAction({ attemptRef.current += 1; inFlightRef.current = false; setPending(false); - }, [restartSettled]); + }, [restartResolved]); const handleUpdate = () => { // Synchronous re-entry guard: setPending is async, so a rapid diff --git a/apps/web/src/serverRestartStore.test.ts b/apps/web/src/serverRestartStore.test.ts index 939687ce9b..36ab446c06 100644 --- a/apps/web/src/serverRestartStore.test.ts +++ b/apps/web/src/serverRestartStore.test.ts @@ -5,58 +5,40 @@ import { SERVER_RESTART_EXPECTED_WINDOW_MS, clearExpectedServerRestart, expectServerRestart, - isServerRestartSettled, + isExpectedRestartResolved, isServerRestarting, - markServerRestartDisconnected, useServerRestartStore, } from "./serverRestartStore"; const ENVIRONMENT_ID = "env-test" as EnvironmentId; -function windowFor(environmentId: EnvironmentId) { - return useServerRestartStore.getState().windowByEnvironmentId[environmentId] ?? null; +function expiresAtFor(environmentId: EnvironmentId) { + return useServerRestartStore.getState().expiresAtByEnvironmentId[environmentId] ?? null; } describe("serverRestartStore", () => { beforeEach(() => { vi.useFakeTimers(); - useServerRestartStore.setState({ windowByEnvironmentId: {} }); + useServerRestartStore.setState({ expiresAtByEnvironmentId: {} }); }); afterEach(() => { vi.useRealTimers(); }); - it("arms a window that has not yet seen the restart's disconnect", () => { + it("arms a window that expires on its own", () => { expectServerRestart(ENVIRONMENT_ID); - - // The window is armed while the old server is still connected, so the - // consumer must be able to tell "waiting for the restart" apart from - // "the restart already happened". - expect(windowFor(ENVIRONMENT_ID)?.sawDisconnect).toBe(false); - expect(windowFor(ENVIRONMENT_ID)?.expiresAt).toBe( - Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS, - ); + expect(expiresAtFor(ENVIRONMENT_ID)).toBe(Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS); }); - it("remembers an observed disconnect across a re-arm", () => { + it("extends the window when a slow install acknowledges late", () => { expectServerRestart(ENVIRONMENT_ID); - markServerRestartDisconnected(ENVIRONMENT_ID); - - // A slow install acknowledging late re-arms the window; forgetting the - // disconnect here would strand the restarting UI until the window lapsed. - vi.advanceTimersByTime(30_000); + vi.advanceTimersByTime(60_000); expectServerRestart(ENVIRONMENT_ID); - expect(windowFor(ENVIRONMENT_ID)?.sawDisconnect).toBe(true); - expect(windowFor(ENVIRONMENT_ID)?.expiresAt).toBe( - Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS, - ); - }); - - it("ignores a disconnect for an environment with no armed window", () => { - markServerRestartDisconnected(ENVIRONMENT_ID); - expect(windowFor(ENVIRONMENT_ID)).toBeNull(); + // Re-arming from the acknowledgement is what keeps a restart that begins + // minutes after the click from being presented as an outage. + expect(expiresAtFor(ENVIRONMENT_ID)).toBe(Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS); }); it("clears only the requested environment", () => { @@ -66,58 +48,71 @@ describe("serverRestartStore", () => { clearExpectedServerRestart(ENVIRONMENT_ID); - expect(windowFor(ENVIRONMENT_ID)).toBeNull(); - expect(windowFor(other)).not.toBeNull(); + expect(expiresAtFor(ENVIRONMENT_ID)).toBeNull(); + expect(expiresAtFor(other)).not.toBeNull(); }); describe("isServerRestarting", () => { it("does not claim a still-connected environment is restarting", () => { // The window is armed before dispatch, while the old server is still - // connected. Presenting that as "restarting" would fire the moment the - // user clicks, before anything has actually gone away. - expect( - isServerRestarting({ - expectation: { expected: true, sawDisconnect: false }, - environmentUnavailable: false, - }), - ).toBe(false); + // connected. Gating on availability is what keeps that from showing the + // restarting banner the instant the user clicks — and what makes a + // window outliving its restart harmless. + expect(isServerRestarting({ restartExpected: true, environmentUnavailable: false })).toBe( + false, + ); }); it("presents an armed window with an away environment as restarting", () => { - expect( - isServerRestarting({ - expectation: { expected: true, sawDisconnect: true }, - environmentUnavailable: true, - }), - ).toBe(true); + expect(isServerRestarting({ restartExpected: true, environmentUnavailable: true })).toBe( + true, + ); }); it("falls back to the outage UI once the window lapses", () => { // The server never came back; the calm banner must give way. + expect(isServerRestarting({ restartExpected: false, environmentUnavailable: true })).toBe( + false, + ); + }); + }); + + describe("isExpectedRestartResolved", () => { + const base = { + sawRestartWindow: true, + restartExpected: true, + wentAway: false, + environmentUnavailable: false, + }; + + it("does not resolve while the environment is still away", () => { expect( - isServerRestarting({ - expectation: { expected: false, sawDisconnect: true }, - environmentUnavailable: true, - }), + isExpectedRestartResolved({ ...base, wentAway: true, environmentUnavailable: true }), + ).toBe(false); + }); + + it("resolves once the environment comes back after going away", () => { + // Something restarted but the skew is still here, so whatever came back + // did not carry the new version. + expect(isExpectedRestartResolved({ ...base, wentAway: true })).toBe(true); + }); + + it("resolves when the window lapses without the connection ever dropping", () => { + // systemd refused the restart and rolled back: the RPC already returned + // success, so nothing else can release the action. + expect(isExpectedRestartResolved({ ...base, restartExpected: false })).toBe(true); + }); + + it("does not resolve while the restart is still expected", () => { + expect(isExpectedRestartResolved(base)).toBe(false); + }); + + it("does not resolve before a window has been observed", () => { + // Guards the render between the click and the store update landing, + // which would otherwise look like an already-lapsed window. + expect( + isExpectedRestartResolved({ ...base, sawRestartWindow: false, restartExpected: false }), ).toBe(false); }); }); - - describe("isServerRestartSettled", () => { - it("does not treat a live window as settled", () => { - expect(isServerRestartSettled({ expected: true, sawDisconnect: true })).toBe(false); - }); - - it("treats an observed restart whose window has closed as settled", () => { - // Covers a rejected systemd restart: the RPC already acknowledged, so - // nothing else can tell the update action to release itself. - expect(isServerRestartSettled({ expected: false, sawDisconnect: true })).toBe(true); - }); - - it("does not settle a window that never saw a disconnect", () => { - // The restart simply never happened; the explicit-failure path owns - // that case, and settling here would release the action early. - expect(isServerRestartSettled({ expected: false, sawDisconnect: false })).toBe(false); - }); - }); }); diff --git a/apps/web/src/serverRestartStore.ts b/apps/web/src/serverRestartStore.ts index 0c519e71b4..2db7cf62ab 100644 --- a/apps/web/src/serverRestartStore.ts +++ b/apps/web/src/serverRestartStore.ts @@ -8,6 +8,12 @@ * deliberately not a connection-supervisor phase — the supervisor state * machine stays transport-only, and this store is UI-side intent that * expires on its own if the server never comes back. + * + * The window is intentionally write-once-and-expire: it is armed while the + * old server is still connected (the acknowledgement races its own + * disconnect), and nothing observed on the connection can reliably end it + * early. Presentation gates on the environment actually being unavailable, + * so a lingering window is inert once the replacement is back. */ import type { EnvironmentId } from "@t3tools/contracts"; import { useEffect, useReducer } from "react"; @@ -22,60 +28,29 @@ import { create } from "zustand"; */ export const SERVER_RESTART_EXPECTED_WINDOW_MS = 90_000; -interface ServerRestartWindow { - readonly expiresAt: number; - /** - * Whether the environment has actually gone away since the window was - * armed. The window is armed while the old server is still connected — that - * is the point, since the acknowledgement races its own disconnect — so a - * connected environment must not end the window until the restart it is - * waiting for has been observed. - */ - readonly sawDisconnect: boolean; -} - interface ServerRestartState { - readonly windowByEnvironmentId: Readonly>; + readonly expiresAtByEnvironmentId: Readonly>; readonly expect: (environmentId: EnvironmentId) => void; - readonly markDisconnected: (environmentId: EnvironmentId) => void; readonly clear: (environmentId: EnvironmentId) => void; } export const useServerRestartStore = create()((set) => ({ - windowByEnvironmentId: {}, + expiresAtByEnvironmentId: {}, expect: (environmentId) => set((state) => ({ - windowByEnvironmentId: { - ...state.windowByEnvironmentId, - [environmentId]: { - expiresAt: Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS, - // Re-arming (a slow install acknowledging late) must not forget a - // disconnect that was already observed. - sawDisconnect: state.windowByEnvironmentId[environmentId]?.sawDisconnect ?? false, - }, + expiresAtByEnvironmentId: { + ...state.expiresAtByEnvironmentId, + [environmentId]: Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS, }, })), - markDisconnected: (environmentId) => - set((state) => { - const current = state.windowByEnvironmentId[environmentId]; - if (current === undefined || current.sawDisconnect) { - return state; - } - return { - windowByEnvironmentId: { - ...state.windowByEnvironmentId, - [environmentId]: { ...current, sawDisconnect: true }, - }, - }; - }), clear: (environmentId) => set((state) => { - if (!(environmentId in state.windowByEnvironmentId)) { + if (!(environmentId in state.expiresAtByEnvironmentId)) { return state; } - const next = { ...state.windowByEnvironmentId }; + const next = { ...state.expiresAtByEnvironmentId }; delete next[environmentId]; - return { windowByEnvironmentId: next }; + return { expiresAtByEnvironmentId: next }; }), })); @@ -83,58 +58,18 @@ export function expectServerRestart(environmentId: EnvironmentId): void { useServerRestartStore.getState().expect(environmentId); } -/** Records that the expected restart's disconnect has now been observed. */ -export function markServerRestartDisconnected(environmentId: EnvironmentId): void { - useServerRestartStore.getState().markDisconnected(environmentId); -} - export function clearExpectedServerRestart(environmentId: EnvironmentId): void { useServerRestartStore.getState().clear(environmentId); } -export interface ServerRestartExpectation { - /** An unexpired restart window is armed for this environment. */ - readonly expected: boolean; - /** The restart's disconnect has been observed, so a reconnect ends it. */ - readonly sawDisconnect: boolean; -} - /** - * Whether an armed restart window has run its course: the disconnect was - * observed and the window has since closed. Callers use this to recover UI - * that was held for the restart — the update RPC is acknowledged before the - * restart runs, so a rejected restart cannot report itself through the call. - * - * Note that a window which never saw a disconnect is not "settled": the - * restart simply never happened, and other paths (an explicit RPC failure) - * own that case. + * Whether an unexpired restart window is armed for the environment. + * Re-renders when the window is armed, cleared, or lapses. */ -export function isServerRestartSettled(expectation: ServerRestartExpectation): boolean { - return expectation.sawDisconnect && !expectation.expected; -} - -/** - * Whether the environment should currently be presented as restarting rather - * than as an outage: a live window plus an environment that is actually away. - */ -export function isServerRestarting(input: { - readonly expectation: ServerRestartExpectation; - readonly environmentUnavailable: boolean; -}): boolean { - return input.expectation.expected && input.environmentUnavailable; -} - -/** - * The restart window state for an environment. Re-renders when the window is - * armed, observes its disconnect, is cleared, or lapses. - */ -export function useServerRestartExpectation( - environmentId: EnvironmentId | null, -): ServerRestartExpectation { - const window = useServerRestartStore((state) => - environmentId === null ? null : (state.windowByEnvironmentId[environmentId] ?? null), +export function useServerRestartExpected(environmentId: EnvironmentId | null): boolean { + const expiresAt = useServerRestartStore((state) => + environmentId === null ? null : (state.expiresAtByEnvironmentId[environmentId] ?? null), ); - const expiresAt = window?.expiresAt ?? null; const [, tick] = useReducer((count: number) => count + 1, 0); useEffect(() => { if (expiresAt === null) { @@ -147,8 +82,47 @@ export function useServerRestartExpectation( const timer = setTimeout(tick, remaining + 50); return () => clearTimeout(timer); }, [expiresAt]); - return { - expected: expiresAt !== null && expiresAt > Date.now(), - sawDisconnect: window?.sawDisconnect === true, - }; + return expiresAt !== null && expiresAt > Date.now(); +} + +/** + * Whether the environment should be presented as restarting rather than as an + * outage. Requires the environment to actually be away, which is why a window + * that outlives its restart is harmless: a reconnected environment reports + * false regardless of the window. + */ +export function isServerRestarting(input: { + readonly restartExpected: boolean; + readonly environmentUnavailable: boolean; +}): boolean { + return input.restartExpected && input.environmentUnavailable; +} + +/** + * Whether an expected restart has resolved without delivering a new version, + * so UI held for it should be released. + * + * The update RPC is acknowledged before the restart runs, so a rejected + * restart cannot report itself through the call. Two shapes resolve it, + * because a rejected restart may or may not have dropped the connection: + * the environment went away and came back (something restarted, but the skew + * is still here), or the window lapsed while the connection never dropped + * (no restart ever happened). + */ +export function isExpectedRestartResolved(input: { + /** A restart window was observed as armed at some point. */ + readonly sawRestartWindow: boolean; + /** A restart window is armed right now. */ + readonly restartExpected: boolean; + /** The environment has been unavailable at some point since arming. */ + readonly wentAway: boolean; + readonly environmentUnavailable: boolean; +}): boolean { + if (input.environmentUnavailable) { + return false; + } + if (input.wentAway) { + return true; + } + return input.sawRestartWindow && !input.restartExpected; }