diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index dc26d3d25e..26857b79fb 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -25,7 +25,12 @@ import { connectionStatusTitle, type EnvironmentConnectionPresentation, } from "@t3tools/client-runtime/connection"; -import { clearExpectedServerRestart, useServerRestartExpected } from "~/serverRestartStore"; +import { + clearExpectedServerRestart, + isServerRestarting, + markServerRestartDisconnected, + useServerRestartExpectation, +} from "~/serverRestartStore"; import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { parseScopedThreadKey, @@ -1625,17 +1630,28 @@ 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 activeEnvironmentRestartExpected = useServerRestartExpected(activeEnvironmentId); - const activeEnvironmentRestarting = - activeEnvironmentRestartExpected && activeEnvironmentUnavailable; + const activeEnvironmentRestartExpectation = useServerRestartExpectation(activeEnvironmentId); + const activeEnvironmentRestartExpected = activeEnvironmentRestartExpectation.expected; + const activeEnvironmentRestartSawDisconnect = activeEnvironmentRestartExpectation.sawDisconnect; + const activeEnvironmentRestarting = isServerRestarting({ + expectation: activeEnvironmentRestartExpectation, + environmentUnavailable: activeEnvironmentUnavailable, + }); useEffect(() => { if (activeEnvironmentId === null || !activeEnvironmentRestartExpected) { return; } if (activeEnvironmentConnectionPhase === "connected") { - clearExpectedServerRestart(activeEnvironmentId); + // 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) { @@ -1650,6 +1666,7 @@ 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 7d5b4724e0..fbdf812512 100644 --- a/apps/web/src/components/ServerUpdateAction.test.tsx +++ b/apps/web/src/components/ServerUpdateAction.test.tsx @@ -16,6 +16,7 @@ const testState = vi.hoisted(() => ({ const restartStore = vi.hoisted(() => ({ expect: vi.fn(), clear: vi.fn(), + expectation: vi.fn(() => ({ expected: false, sawDisconnect: false })), })); const hooks = vi.hoisted(() => { @@ -87,10 +88,15 @@ vi.mock("~/state/use-atom-command", () => ({ vi.mock("./ui/toast", () => ({ toastManager: { add: testState.toast }, })); -vi.mock("~/serverRestartStore", () => ({ - expectServerRestart: restartStore.expect, - clearExpectedServerRestart: restartStore.clear, -})); +vi.mock("~/serverRestartStore", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + expectServerRestart: restartStore.expect, + clearExpectedServerRestart: restartStore.clear, + useServerRestartExpectation: restartStore.expectation, + }; +}); import { ServerUpdateAction } from "./ServerUpdateAction"; @@ -133,6 +139,8 @@ describe("ServerUpdateAction", () => { testState.toast.mockReset(); restartStore.expect.mockReset(); restartStore.clear.mockReset(); + restartStore.expectation.mockReset(); + restartStore.expectation.mockReturnValue({ expected: false, sawDisconnect: false }); }); afterEach(() => { diff --git a/apps/web/src/components/ServerUpdateAction.tsx b/apps/web/src/components/ServerUpdateAction.tsx index e186e3f851..1f5e721d2c 100644 --- a/apps/web/src/components/ServerUpdateAction.tsx +++ b/apps/web/src/components/ServerUpdateAction.tsx @@ -11,7 +11,12 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; -import { clearExpectedServerRestart, expectServerRestart } from "~/serverRestartStore"; +import { + clearExpectedServerRestart, + expectServerRestart, + isServerRestartSettled, + useServerRestartExpectation, +} from "~/serverRestartStore"; import { serverEnvironment } from "~/state/server"; import { useAtomCommand } from "~/state/use-atom-command"; import { manualServerUpdateCommand } from "~/versionSkew"; @@ -98,6 +103,27 @@ 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)); + useEffect(() => { + if (!restartSettled || !inFlightRef.current) { + return; + } + if (expiryRef.current !== null) { + clearTimeout(expiryRef.current); + expiryRef.current = null; + } + attemptRef.current += 1; + inFlightRef.current = false; + setPending(false); + }, [restartSettled]); + const handleUpdate = () => { // Synchronous re-entry guard: setPending is async, so a rapid // double-click would otherwise dispatch two updates. diff --git a/apps/web/src/serverRestartStore.test.ts b/apps/web/src/serverRestartStore.test.ts new file mode 100644 index 0000000000..939687ce9b --- /dev/null +++ b/apps/web/src/serverRestartStore.test.ts @@ -0,0 +1,123 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { + SERVER_RESTART_EXPECTED_WINDOW_MS, + clearExpectedServerRestart, + expectServerRestart, + isServerRestartSettled, + isServerRestarting, + markServerRestartDisconnected, + useServerRestartStore, +} from "./serverRestartStore"; + +const ENVIRONMENT_ID = "env-test" as EnvironmentId; + +function windowFor(environmentId: EnvironmentId) { + return useServerRestartStore.getState().windowByEnvironmentId[environmentId] ?? null; +} + +describe("serverRestartStore", () => { + beforeEach(() => { + vi.useFakeTimers(); + useServerRestartStore.setState({ windowByEnvironmentId: {} }); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("arms a window that has not yet seen the restart's disconnect", () => { + 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, + ); + }); + + it("remembers an observed disconnect across a re-arm", () => { + 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); + 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(); + }); + + it("clears only the requested environment", () => { + const other = "env-other" as EnvironmentId; + expectServerRestart(ENVIRONMENT_ID); + expectServerRestart(other); + + clearExpectedServerRestart(ENVIRONMENT_ID); + + expect(windowFor(ENVIRONMENT_ID)).toBeNull(); + expect(windowFor(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); + }); + + it("presents an armed window with an away environment as restarting", () => { + expect( + isServerRestarting({ + expectation: { expected: true, sawDisconnect: 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({ + expectation: { expected: false, sawDisconnect: true }, + environmentUnavailable: true, + }), + ).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 a439c81168..0c519e71b4 100644 --- a/apps/web/src/serverRestartStore.ts +++ b/apps/web/src/serverRestartStore.ts @@ -22,29 +22,60 @@ 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 expectedUntilByEnvironmentId: Readonly>; + readonly windowByEnvironmentId: Readonly>; readonly expect: (environmentId: EnvironmentId) => void; + readonly markDisconnected: (environmentId: EnvironmentId) => void; readonly clear: (environmentId: EnvironmentId) => void; } export const useServerRestartStore = create()((set) => ({ - expectedUntilByEnvironmentId: {}, + windowByEnvironmentId: {}, expect: (environmentId) => set((state) => ({ - expectedUntilByEnvironmentId: { - ...state.expectedUntilByEnvironmentId, - [environmentId]: Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS, + 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, + }, }, })), - clear: (environmentId) => + markDisconnected: (environmentId) => set((state) => { - if (!(environmentId in state.expectedUntilByEnvironmentId)) { + const current = state.windowByEnvironmentId[environmentId]; + if (current === undefined || current.sawDisconnect) { return state; } - const next = { ...state.expectedUntilByEnvironmentId }; + return { + windowByEnvironmentId: { + ...state.windowByEnvironmentId, + [environmentId]: { ...current, sawDisconnect: true }, + }, + }; + }), + clear: (environmentId) => + set((state) => { + if (!(environmentId in state.windowByEnvironmentId)) { + return state; + } + const next = { ...state.windowByEnvironmentId }; delete next[environmentId]; - return { expectedUntilByEnvironmentId: next }; + return { windowByEnvironmentId: next }; }), })); @@ -52,18 +83,58 @@ 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 a restart window is currently active for the environment. - * Re-renders when the window is set, cleared, or lapses. + * 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. */ -export function useServerRestartExpected(environmentId: EnvironmentId | null): boolean { - const expiresAt = useServerRestartStore((state) => - environmentId === null ? null : (state.expectedUntilByEnvironmentId[environmentId] ?? null), +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), ); + const expiresAt = window?.expiresAt ?? null; const [, tick] = useReducer((count: number) => count + 1, 0); useEffect(() => { if (expiresAt === null) { @@ -76,5 +147,8 @@ export function useServerRestartExpected(environmentId: EnvironmentId | null): b const timer = setTimeout(tick, remaining + 50); return () => clearTimeout(timer); }, [expiresAt]); - return expiresAt !== null && expiresAt > Date.now(); + return { + expected: expiresAt !== null && expiresAt > Date.now(), + sawDisconnect: window?.sawDisconnect === true, + }; }