Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions apps/web/src/connection/platform.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,29 @@ describe("desktop SSH pairing", () => {
}),
);

it.effect("blocks SSH failures that need the user instead of retrying them", () =>
Effect.gen(function* () {
const failEnsure = (message: string) => {
const bridge = makeBridge([]);
vi.spyOn(bridge, "ensureSshEnvironment").mockRejectedValue(new Error(message));
return provisionDesktopSshEnvironment(bridge, TARGET).pipe(Effect.flip);
};

for (const message of [
"SSH authentication cancelled for devbox.",
"SSH authentication timed out for devbox.",
"user@devbox: Permission denied (publickey,password).",
"sign_and_send_pubkey: signing failed for ED25519-SK from agent: agent refused operation",
"Host key verification failed.",
]) {
expect(yield* failEnsure(message)).toBeInstanceOf(ConnectionBlockedError);
}
expect(
yield* failEnsure("ssh: connect to host devbox port 22: Operation timed out"),
).toBeInstanceOf(ConnectionTransientError);
}),
);

it.effect("reconnects with the saved token while it holds every standard scope", () =>
Effect.gen(function* () {
const calls: string[] = [];
Expand Down
17 changes: 16 additions & 1 deletion apps/web/src/connection/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,24 @@ export function currentClientMetadata() {
});
}

// Failures only the user can resolve: a cancelled or unanswered password
// prompt, a refused key or password, a security key nobody touched, or a
// changed host key. Retrying them would only prompt again.
const SSH_NEEDS_USER_PATTERNS = [
/cancel/u,
/ssh authentication timed out/u,
/permission denied \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic)/u,
/authentication failed/u,
/too many authentication failures/u,
/sign_and_send_pubkey: signing failed/u,
/host key verification failed/u,
/remote host identification has changed/u,
];

function sshPreparationError(cause: unknown) {
const message = cause instanceof Error ? cause.message : String(cause);
if (message.toLowerCase().includes("cancel")) {
const normalized = message.toLowerCase();
if (SSH_NEEDS_USER_PATTERNS.some((pattern) => pattern.test(normalized))) {
return new ConnectionBlockedError({
reason: "authentication",
detail: message,
Expand Down
11 changes: 11 additions & 0 deletions docs/internals/connection-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ client of a restarted server reconnects in the same second; with a short cap, a
client that can never connect retries all day. Offline states and authentication
failures wait for a wakeup instead of spending attempts on unchanged conditions.

Desktop-managed SSH environments use their own ladder: one client per host has
no herd to spread, and the desktop bounds every SSH step and drops a dead link
itself. An attempt that failed after 3 seconds or more usually waited out a
stalled link that may already be back, so the next starts at once, up to three
times in a row; after that, and after a faster failure (offline, refused), it
waits 1 second, doubling to 20, until a connection, an explicit retry,
foregrounding, or a network change resets it. The renderer
classifies SSH failures that only the user can fix, such as a refused key, an
unanswered password prompt, or a changed host key, as authentication failures,
so neither ladder prompts again on its own.

Foregrounding, a network change, an explicit retry, and an offline report probe
the established session, and only a failed probe reconnects. Offline reports are
often wrong, for example for a loopback server. The OS can kill a suspended
Expand Down
6 changes: 6 additions & 0 deletions docs/user/remote-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,12 @@ neither answers, it keeps the first connection and tries again. When the old
connection has clearly closed, for example after your computer sleeps, it is
replaced right away.

When an SSH environment drops, T3 Code tries again as soon as an attempt times
out, up to three times in a row, and otherwise waits at most 20 seconds between
attempts, for example while your computer is offline. It stops trying when the host needs you:
a password or security key prompt you did not answer, a refused key, or a
changed host key. Choose **Reconnect** once you have dealt with it.

T3 Code sets up the host and its port forward over a single SSH connection, so
a slow link pays for the SSH handshake once. It keeps its own shared connection
and does not use `ControlMaster` settings from your SSH config. On Windows each
Expand Down
75 changes: 72 additions & 3 deletions packages/client-runtime/src/connection/supervisor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type ServerConfigStreamEvent,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
Expand Down Expand Up @@ -596,9 +597,77 @@ describe("EnvironmentSupervisor", () => {

// Once prepared, the session still has only its usual budget.
yield* TestClock.adjust("90 seconds");
const timedOut = yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
expect(timedOut).toMatchObject({ attempt: 1, lastFailure: { reason: "timeout" } });
expect(yield* Ref.get(harness.prepareCount)).toBe(1);
const timedOut = yield* awaitState(supervisor.state, (state) => state.attempt === 2);
expect(timedOut).toMatchObject({ phase: "connecting", lastFailure: { reason: "timeout" } });
expect(yield* Ref.get(harness.prepareCount)).toBe(2);
}).pipe(Effect.provide(TestClock.layer())),
);

it.effect("retries an SSH environment at once after a slow failure", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
prepare: (attempt, target) =>
attempt === 1
? Effect.sleep("5 seconds").pipe(Effect.andThen(Effect.fail(transient())))
: Effect.succeed(preparedFor(target)),
});
const supervisor = yield* EnvironmentSupervisor.make(SSH_ENTRY, {
initiallyDesired: true,
}).pipe(Effect.provide(harness.dependencies));

yield* TestClock.adjust("5 seconds");
const next = yield* awaitState(
supervisor.state,
(state) => state.phase === "backoff" || state.phase === "connected",
);
expect(next.phase).toBe("connected");
expect(yield* Ref.get(harness.prepareCount)).toBe(2);
}).pipe(Effect.provide(TestClock.layer())),
);

it.effect("backs off after three immediate retries of a persistent slow SSH failure", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
prepare: () => Effect.sleep("5 seconds").pipe(Effect.andThen(Effect.fail(transient()))),
});
const supervisor = yield* EnvironmentSupervisor.make(SSH_ENTRY, {
initiallyDesired: true,
}).pipe(Effect.provide(harness.dependencies));

yield* TestClock.adjust("20 seconds");
const backoff = yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
expect(backoff.attempt).toBe(4);
expect(backoff.retryAt! - (yield* Clock.currentTimeMillis)).toBe(1_000);
expect(yield* Ref.get(harness.prepareCount)).toBe(4);

yield* TestClock.adjust("6 seconds");
const next = yield* awaitState(
supervisor.state,
(state) => state.phase === "backoff" && state.attempt === 5,
);
expect(next.retryAt! - (yield* Clock.currentTimeMillis)).toBe(2_000);
}).pipe(Effect.provide(TestClock.layer())),
);

it.effect("backs off an SSH environment that fails fast from 1 to at most 20 seconds", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({ prepare: () => Effect.fail(transient()) });
const supervisor = yield* EnvironmentSupervisor.make(SSH_ENTRY, {
initiallyDesired: true,
}).pipe(Effect.provide(harness.dependencies));

const delays: Array<number> = [];
for (let attempt = 1; attempt <= 7; attempt += 1) {
const backoff = yield* awaitState(
supervisor.state,
(state) => state.phase === "backoff" && state.attempt === attempt,
);
const delayMs = backoff.retryAt! - (yield* Clock.currentTimeMillis);
delays.push(delayMs);
yield* TestClock.adjust(delayMs);
}

expect(delays).toEqual([1_000, 2_000, 4_000, 8_000, 16_000, 20_000, 20_000]);
}).pipe(Effect.provide(TestClock.layer())),
);

Expand Down
46 changes: 41 additions & 5 deletions packages/client-runtime/src/connection/supervisor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ import {

const RETRY_BASE_DELAY_MS = 1_000;
const RETRY_MAX_DELAY_MS = 300_000;
// An SSH attempt that fails this slowly usually waited out a stalled link that
// may already be back, and the desktop bounds each SSH step, so the next
// attempt starts at once, up to a few times in a row so a persistent slow
// failure cannot loop. Faster failures (offline, refused) back off briefly.
const SSH_SLOW_FAILURE_MS = 3_000;
const SSH_MAX_IMMEDIATE_RETRIES = 3;
const SSH_RETRY_MAX_DELAY_MS = 20_000;
const SESSION_LOSS_RETRY_DELAY_MS = 250;
// A cold server with a large database can take longer than 15 seconds to
// answer, and that is not a reason to drop a working connection. Preparing an
Expand Down Expand Up @@ -163,6 +170,10 @@ function retryDelayMs(failureCount: number, random: number): number {
return Math.round(ceiling / 2 + (ceiling / 2) * random);
}

function sshRetryDelayMs(fastFailures: number): number {
return Math.min(SSH_RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (fastFailures - 1));
}

interface SilentRoute {
readonly failures: number;
readonly until: bigint;
Expand Down Expand Up @@ -295,6 +306,9 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
const usesRelay = connectionRoutes(entry).some(
(route) => route.target._tag === "RelayConnectionTarget",
);
const usesSsh = connectionRoutes(entry).some(
(route) => route.target._tag === "SshConnectionTarget",
);
const setupTimeoutDetail = `${target.label} did not respond during connection setup.${
usesRelay ? ` ${NETWORK_BLOCKING_HINT}` : ""
}`;
Expand Down Expand Up @@ -1130,17 +1144,20 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
let generation = 0;
let latestFailure: ConnectionAttemptError | null = null;
let pendingRetry = Option.none<PendingRetryTrace>();
let sshFastFailures = 0;
let sshSlowFailures = 0;
const resetRetryLadder = () => {
failureCount = 0;
sshFastFailures = 0;
sshSlowFailures = 0;
pendingRetry = Option.none();
};
let replacing = false;

for (;;) {
if (yield* Ref.getAndSet(resetRetryState, false)) {
failureCount = 0;
resetRetryLadder();
latestFailure = null;
pendingRetry = Option.none();
}
const currentIntent = yield* Ref.get(intent);
if (!currentIntent.desired) {
Expand All @@ -1163,9 +1180,11 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (

const attempt = failureCount + 1;
const nextGeneration = generation + 1;
const attemptStartedAt = yield* Clock.monotonicTimeNanos;
const outcome: AttemptOutcome = yield* Effect.scoped(
runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, replacing),
);
const attemptMs = Number(((yield* Clock.monotonicTimeNanos) - attemptStartedAt) / 1_000_000n);
replacing = false;
const failedProbe = yield* Ref.getAndSet(probeUnanswered, false);
if (outcome.established) {
Expand All @@ -1175,6 +1194,8 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
// a socket the OS killed while the app was suspended: its replacement
// reports no failure until it fails itself.
latestFailure = null;
sshFastFailures = 0;
sshSlowFailures = 0;
if (outcome.stable) {
resetRetryLadder();
}
Expand Down Expand Up @@ -1221,15 +1242,30 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
// still counts it, so a host that keeps dropping sessions backs off.
const firstLoss = outcome.established && failureCount === 0;
failureCount += 1;
const delayMs = firstLoss
? Math.round(SESSION_LOSS_RETRY_DELAY_MS * (0.5 + (yield* Random.next) / 2))
: retryDelayMs(failureCount - 1, yield* Random.next);
if (usesSsh) {
sshSlowFailures = attemptMs >= SSH_SLOW_FAILURE_MS ? sshSlowFailures + 1 : 0;
const immediate = sshSlowFailures > 0 && sshSlowFailures <= SSH_MAX_IMMEDIATE_RETRIES;
sshFastFailures = immediate ? 0 : sshFastFailures + 1;
}
const delayMs = usesSsh
? sshFastFailures === 0
? 0
: sshRetryDelayMs(sshFastFailures)
: firstLoss
? Math.round(SESSION_LOSS_RETRY_DELAY_MS * (0.5 + (yield* Random.next) / 2))
: retryDelayMs(failureCount - 1, yield* Random.next);
pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
previousAttempt,
failureCount,
delayMs,
reason: error.reason,
}));
if (delayMs === 0) {
yield* setState(
connectingState(yield* Ref.get(intent), generation, failureCount + 1, latestFailure),
);
continue;
}
const failedIntent = yield* Ref.get(intent);
yield* setState({
desired: failedIntent.desired,
Expand Down
Loading