fix: make the restart window survive until the restart is observed

An independent gpt-5.6-sol review found that the restart overlay never
actually engaged in the normal flow — the feature was inert.

ChatView cleared the expectation on any render where the connection was
"connected". But the window is armed while the old server is still
connected (that is the point: the acknowledgement races its own
disconnect), so the store update triggered a render that destroyed the
window within milliseconds, long before the server went away. Both
re-arm points had the same problem. The user therefore still got the
outage banner and escalating backoff.

The window now tracks whether the restart's disconnect was actually
observed. A connected environment only ends the window once that has
happened; before it, "connected" just means the restart has not started
yet. Re-arming preserves an already-observed disconnect.

Also fixes the follow-on the same review found: because a rejected
restart can no longer be reported through the acknowledged RPC, the
update action could stay disabled for the full 12-minute safety window
with the mismatch unresolved. A settled restart window (disconnect seen,
window closed) now releases it so the user can retry immediately.

The restarting/settled decisions are pure exported predicates, since the
component test harness stubs useEffect and cannot exercise
effect-driven behavior. Both are tested, and both tests were confirmed
to fail against the old logic.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5 committed 2026-07-24 16:59:17 -07:00
1 parent 7aecc5d47a
commit 02abc2cb3d
5 files changed
+273 -25

No files matched your search

+22 -5
View File
@@ -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(
@@ -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<typeof import("~/serverRestartStore")>();
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(() => {
+27 -1
View File
@@ -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.
+123
View File
@@ -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);
});
});
});
+89 -15
View File
@@ -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<Record<string, number>>;
readonly windowByEnvironmentId: Readonly<Record<string, ServerRestartWindow>>;
readonly expect: (environmentId: EnvironmentId) => void;
readonly markDisconnected: (environmentId: EnvironmentId) => void;
readonly clear: (environmentId: EnvironmentId) => void;
}
export const useServerRestartStore = create<ServerRestartState>()((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,
};
}