fix: address review findings on the reconnect flow

Three defects found by Macroscope and Cursor Bugbot:

- The restart window was armed only at click time, but an npm install can
  consume most of the 10-minute request window, so a slow-but-successful
  update restarted after the window had lapsed and was presented as an
  outage. Re-arm from the acknowledgement and from the interrupt path,
  matching what keepPendingForRestart already does for the button expiry.

- Effect.catch on the detached restart fiber only sees typed failures, so
  an unexpected defect skipped the inFlight reset and left a live process
  refusing every further update until restarted by other means. Release
  the guard from Effect.onExit, outside the typed handler. Success still
  deliberately keeps it set: systemd is about to stop the process and a
  second update would race the handoff.

- "A server update is already in progress" is a typed failure, so it
  cleared a restart overlay that the earlier still-pending update needed,
  restoring the harsh reconnect UI mid-restart. That reason now lives in
  contracts as SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON with an
  isAlreadyRunning helper, so the client can distinguish it structurally
  instead of matching prose.

Each fix has a regression test; the defect-path test was confirmed to
fail without the onExit change.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5 committed 2026-07-24 16:47:51 -07:00
1 parent b462ae5f2f
commit 7aecc5d47a
5 files changed
+181 -9

No files matched your search

+33
View File
@@ -62,6 +62,8 @@ const makeRecordingRunnerLayer = (
readonly stdoutFor?:
| ((command: string, args: ReadonlyArray<string>) => string | undefined)
| undefined;
/** Raises a defect (not a typed failure) to exercise unexpected-error paths. */
readonly dieWhen?: ((command: string, args: ReadonlyArray<string>) => boolean) | undefined;
},
) =>
Layer.succeed(
@@ -70,6 +72,9 @@ const makeRecordingRunnerLayer = (
run: (input) =>
Effect.sync(() => {
commands.push({ command: input.command, args: input.args });
if (options?.dieWhen?.(input.command, input.args) === true) {
throw new Error(`${input.command} died unexpectedly`);
}
const failed = options?.failWhen?.(input.command, input.args) === true;
const versionFromPath =
input.command === NODE_PATH && input.args[1] === "--version"
@@ -281,6 +286,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
readonly failWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
readonly stdoutFor?: (command: string, args: ReadonlyArray<string>) => string | undefined;
readonly failSpawn?: boolean;
readonly dieWhen?: (command: string, args: ReadonlyArray<string>) => boolean;
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -353,6 +359,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
makeRecordingRunnerLayer(commands, {
failWhen: options?.failWhen,
stdoutFor: options?.stdoutFor,
dieWhen: options?.dieWhen,
}),
configLayer,
),
@@ -588,6 +595,32 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("permits a retry when the deferred restart dies unexpectedly", () =>
Effect.gen(function* () {
let dieOnRestart = true;
const context = yield* makeContext({
bootService: true,
dieWhen: (command, args) => {
if (command !== "systemctl" || args[1] !== "restart" || !dieOnRestart) {
return false;
}
dieOnRestart = false;
return true;
},
});
const first = yield* context.service.update({ targetVersion: "0.0.29" });
assert.deepEqual(first, { targetVersion: "0.0.29", method: "boot-service" });
yield* TestClock.adjust(Duration.seconds(10));
// A defect bypasses the typed rollback handler, so the in-flight guard
// has to be released outside it — otherwise this live process would
// reject every further update until restarted by other means.
const retry = yield* context.service.update({ targetVersion: "0.0.30" });
assert.deepEqual(retry, { targetVersion: "0.0.30", method: "boot-service" });
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("restores the previous systemd unit when daemon-reload fails", () =>
Effect.gen(function* () {
const context = yield* makeContext({
+18 -1
View File
@@ -3,6 +3,7 @@
// detached fire-and-forget child that outlives this process, while Effect's
// ChildProcessSpawner ties every child to a scope that kills it.
import {
SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON,
ServerSelfUpdateError,
type ServerSelfUpdateCapability,
type ServerSelfUpdateInput,
@@ -18,6 +19,7 @@ import * as NodeChildProcess from "node:child_process";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
@@ -246,7 +248,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
const alreadyRunning = yield* Ref.getAndSet(inFlight, true);
if (alreadyRunning) {
return yield* failWith("A server update is already in progress.");
return yield* failWith(SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON);
}
return yield* Effect.gen(function* () {
@@ -387,9 +389,24 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
"Server self-update could not restore the previous systemd unit after a rejected restart.",
).pipe(Effect.annotateLogs({ targetVersion, error: String(rollbackError) })),
),
// The process survived a rejected restart, so it must stay
// updatable — leaving the guard set would reject every retry
// until the server was restarted by other means.
Effect.ensuring(Ref.set(inFlight, false)),
),
),
// The typed catch above cannot see defects or interrupts, which
// would otherwise strand the guard on a live process. A success
// deliberately leaves it set: systemd is about to stop this
// process and a second update would race the handoff.
Effect.onExit((exit) =>
Exit.isSuccess(exit)
? Effect.void
: Effect.logError("Server self-update restart fiber ended unexpectedly.").pipe(
Effect.annotateLogs({ targetVersion, exit: String(exit) }),
Effect.ensuring(Ref.set(inFlight, false)),
),
),
),
);
} else {
@@ -2,13 +2,22 @@ import type { Dispatch, ReactElement, SetStateAction } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/unstable/reactivity";
import type { EnvironmentId } from "@t3tools/contracts";
import {
SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON,
ServerSelfUpdateError,
type EnvironmentId,
} from "@t3tools/contracts";
const testState = vi.hoisted(() => ({
updateServer: vi.fn(),
toast: vi.fn(),
}));
const restartStore = vi.hoisted(() => ({
expect: vi.fn(),
clear: vi.fn(),
}));
const hooks = vi.hoisted(() => {
let cursor = 0;
let slots: unknown[] = [];
@@ -78,6 +87,10 @@ vi.mock("~/state/use-atom-command", () => ({
vi.mock("./ui/toast", () => ({
toastManager: { add: testState.toast },
}));
vi.mock("~/serverRestartStore", () => ({
expectServerRestart: restartStore.expect,
clearExpectedServerRestart: restartStore.clear,
}));
import { ServerUpdateAction } from "./ServerUpdateAction";
@@ -118,6 +131,8 @@ describe("ServerUpdateAction", () => {
hooks.reset();
testState.updateServer.mockReset();
testState.toast.mockReset();
restartStore.expect.mockReset();
restartStore.clear.mockReset();
});
afterEach(() => {
@@ -195,4 +210,71 @@ describe("ServerUpdateAction", () => {
expect.objectContaining({ title: "Server update failed" }),
);
});
it("re-arms the restart window when a slow install finally succeeds", async () => {
const update =
deferred<
ReturnType<typeof AsyncResult.success<{ targetVersion: string; method: "boot-service" }>>
>();
testState.updateServer.mockReturnValue(update.promise);
renderAction().props.onClick?.();
expect(restartStore.expect).toHaveBeenCalledTimes(1);
// An install can outlast the 90s restart window armed at click time, so
// the acknowledgement must restart the clock or the ensuing disconnect
// would be presented as an outage.
await vi.advanceTimersByTimeAsync(5 * 60_000);
update.resolve(AsyncResult.success({ targetVersion: "0.0.29", method: "boot-service" }));
await flushPromises();
expect(restartStore.expect).toHaveBeenCalledTimes(2);
expect(restartStore.clear).not.toHaveBeenCalled();
});
it("re-arms the restart window on an interrupted restart RPC", async () => {
testState.updateServer.mockResolvedValue(AsyncResult.failure(Cause.interrupt()));
renderAction().props.onClick?.();
await flushPromises();
expect(restartStore.expect).toHaveBeenCalledTimes(2);
expect(restartStore.clear).not.toHaveBeenCalled();
});
it("withdraws the restart expectation when the server reports a real failure", async () => {
testState.updateServer.mockResolvedValue(
AsyncResult.failure(
Cause.fail(
new ServerSelfUpdateError({ reason: "Could not install the requested t3 version." }),
),
),
);
renderAction().props.onClick?.();
await flushPromises();
// The server answered, so it is still alive and no restart is coming.
expect(restartStore.clear).toHaveBeenCalledTimes(1);
expect(testState.toast).toHaveBeenCalledWith(
expect.objectContaining({ title: "Server update failed" }),
);
});
it("keeps the restart expectation when an update is already in progress", async () => {
testState.updateServer.mockResolvedValue(
AsyncResult.failure(
Cause.fail(
new ServerSelfUpdateError({ reason: SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON }),
),
),
);
renderAction().props.onClick?.();
await flushPromises();
// An earlier request is still installing, so a restart really is pending
// — clearing here would restore the harsh reconnect UI mid-restart.
expect(restartStore.clear).not.toHaveBeenCalled();
});
});
+36 -7
View File
@@ -1,5 +1,10 @@
import { useEffect, useRef, useState } from "react";
import type { EnvironmentId, ServerSelfUpdateCapability } from "@t3tools/contracts";
import {
ServerSelfUpdateError,
type EnvironmentId,
type ServerSelfUpdateCapability,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
@@ -25,6 +30,18 @@ function updateFailureMessage(error: unknown): string {
return error instanceof Error ? error.message : "Server update failed.";
}
/**
* The server rejects a second update while one is already installing. That
* failure means a restart is still pending from the earlier request, so the
* restart expectation must survive it — unlike every other failure, which
* proves nothing is coming.
*/
const isServerSelfUpdateError = Schema.is(ServerSelfUpdateError);
function isUpdateAlreadyRunning(error: unknown): boolean {
return isServerSelfUpdateError(error) && error.isAlreadyRunning;
}
/**
* The call-to-action for a version-skewed server, matched to the update path
* it advertises: a one-click install-and-restart for servers that can update
@@ -116,13 +133,17 @@ export function ServerUpdateAction({
clearTimeout(expiry);
expiry = armExpiry();
}
// The install can consume most of the request window, so the window
// armed at click time may already have lapsed by the time the restart
// actually begins. Re-arm from the handoff, not from the click.
expectServerRestart(environmentId);
};
// Armed before dispatch: the boot-service path acknowledges and then
// drops every connection, and even the respawn acknowledgement can lose
// the race against the disconnect. An explicit RPC failure proves the
// server stayed alive, so the expectation is withdrawn there; on
// success or interrupt it stays armed and expires on its own if the
// server never returns.
// success or interrupt it is re-armed from that point and expires on its
// own if the server never returns.
expectServerRestart(environmentId);
void Promise.resolve()
.then(() =>
@@ -137,15 +158,21 @@ export function ServerUpdateAction({
// An interrupt may be the expected boot-service disconnect, but it
// can also be client-side cancellation before restart was accepted.
// Release the action quietly; version sync will remove it when a
// successful replacement reconnects.
// successful replacement reconnects. Re-arm from here for the same
// reason as the success path: a long install may have outlasted the
// window armed at click time.
if (isAtomCommandInterrupted(result)) {
expectServerRestart(environmentId);
return;
}
clearExpectedServerRestart(environmentId);
const failure = squashAtomCommandFailure(result);
if (!isUpdateAlreadyRunning(failure)) {
clearExpectedServerRestart(environmentId);
}
toastManager.add({
type: "error",
title: "Server update failed",
description: updateFailureMessage(squashAtomCommandFailure(result)),
description: updateFailureMessage(failure),
});
return;
}
@@ -161,7 +188,9 @@ export function ServerUpdateAction({
})
.catch((error: unknown) => {
if (!ownsAttempt()) return;
clearExpectedServerRestart(environmentId);
if (!isUpdateAlreadyRunning(error)) {
clearExpectedServerRestart(environmentId);
}
toastManager.add({
type: "error",
title: "Server update failed",
+11
View File
@@ -590,6 +590,12 @@ export const ServerSelfUpdateResult = Schema.Struct({
});
export type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;
/** Rejection reason when an update is dispatched while one is already
installing. Shared so clients can tell "nothing is happening" apart from
"a restart is already pending from an earlier request", which the update
UI must not treat as the end of the flow. */
export const SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON = "A server update is already in progress.";
export class ServerSelfUpdateError extends Schema.TaggedErrorClass<ServerSelfUpdateError>()(
"ServerSelfUpdateError",
{
@@ -600,4 +606,9 @@ export class ServerSelfUpdateError extends Schema.TaggedErrorClass<ServerSelfUpd
override get message(): string {
return `Server update failed: ${this.reason}`;
}
/** True when this rejection means an earlier update is still in flight. */
get isAlreadyRunning(): boolean {
return this.reason === SERVER_SELF_UPDATE_ALREADY_RUNNING_REASON;
}
}