GeezerVison is showing github.com — fix(desktop): retry transient bearer bootstrap and degrade on session fetch failure by jamesvillarrubia · Pull Request #12919 · pingdotgg/t3code
fix(desktop): retry transient bearer bootstrap and degrade on session fetch failure
#12919
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter
Filter by extension
.ts
(4)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
fix(desktop): retry only the local bearer exchange's transient failures
Classify retryable failures by the request error union instead of probing
untyped fields, and let the outer 15 s timeout alone bound the retries.
Tests cover both sides: a backend still starting (503) is retried until the
token arrives, and a rejected credential (401) fails after one request.
The renderer fallback is dropped. When the session fetch fails on desktop it
showed the pairing form, which asks for a token a desktop user does not have;
with the bearer exchange retrying, the root error view's Try again and Reload
app cover what is left.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected] >
Loading branch information
Uh oh!
There was an error while loading. Please reload this page.
commit ecb809a1ff1a93a3598964579f1cd364f112959d
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -91,7 +91,7 @@ describe("DesktopLocalEnvironmentAuth", () => {
() =>
Effect.gen(function* () {
const presented = yield* Ref.make<string | null>(null);
const layerHttpClient = Layer.succeed(
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) => {
const body =
Expand Down
Expand Up
@@ -136,7 +136,7 @@ describe("DesktopLocalEnvironmentAuth", () => {
}).pipe(
Effect.provide(
DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(poolLayer, layerHttpClient )),
Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer )),
),
),
);
Expand All
@@ -148,70 +148,90 @@ describe("DesktopLocalEnvironmentAuth", () => {
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("retries transient /oauth/token failures before surfacing the bootstrap error", () =>
const tokenResponse = (request: HttpClientRequest.HttpClientRequest) =>
HttpClientResponse.fromWeb(
request,
new Response(
JSON.stringify({
access_token: "desktop-bearer-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "Bearer",
expires_in: 3600,
scope: "orchestration:read",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
);
const layerPool = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
list: Effect.succeed([
{
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
label: Effect.succeed("Windows"),
currentConfig: Effect.succeedSome(config),
},
]),
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
// Answers the first `failures` exchanges with `failure`, then with a token.
const makeExchange = (failures: number, failure: () => Response) =>
Effect.gen(function* () {
// The first two attempts return a 503 (the shape a settling backend
// produces); the third succeeds. Before the retry, a single transient
// failure hard-failed into DesktopLocalEnvironmentAuthSessionBootstrapError.
// A 503 flows through the real HttpApiClient pipeline and maps to
// RemoteEnvironmentAuthUndeclaredStatusError(url, 503), which the
// classifier treats as transient. TestClock advances the spaced schedule
// deterministically instead of waiting out real 500ms delays.
const requestCount = yield* Ref.make(0);
const successResponse = (request: HttpClientRequest.HttpClientRequest) =>
HttpClientResponse.fromWeb(
request,
new Response(
JSON.stringify({
access_token: "desktop-bearer-token",
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
token_type: "Bearer",
expires_in: 3600,
scope: "orchestration:read",
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
);
const transientResponse = (request: HttpClientRequest.HttpClientRequest) =>
HttpClientResponse.fromWeb(request, new Response("", { status: 503 }));
const layerHttpClient = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Ref.modify (requestCount, (n ) => [n + 1, n + 1] ).pipe(
Effect.flatMap ((count) =>
count <= 2
? Effect.succeed(transientResponse( request))
: Effect.succeed(successResponse( request) ),
Ref.updateAndGet (requestCount, (count ) => count + 1).pipe(
Effect.map ((count) =>
count <= failures
? HttpClientResponse.fromWeb( request, failure( ))
: tokenResponse( request),
),
),
),
);
const poolLayer = Layer.succeed(DesktopBackendPool.DesktopBackendPool, {
list: Effect.succeed([
{
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
label: Effect.succeed("Windows"),
currentConfig: Effect.succeedSome(config),
},
]),
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
const testLayer = DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(poolLayer, layerHttpClient)),
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe(
Effect.provide(
DesktopLocalEnvironmentAuth.layer.pipe(
Layer.provide(Layer.mergeAll(layerPool, layerHttpClient)),
),
),
);
return { auth, requestCount };
});
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe(
Effect.provide(testLayer),
it.effect("retries a backend that is still starting", () =>
Effect.gen(function* () {
const { auth, requestCount } = yield* makeExchange(
2,
() => new Response("", { status: 503 }),
);
// Fork getBearerToken so the TestClock can advance the spaced schedule
// delays without blocking the test fiber.
const fiber = yield* auth.getBearerToken.pipe(Effect.forkChild);
// Two transient attempts each park for 500ms on the spaced schedule;
// advance past both delays so the third attempt (success) can run.
yield* TestClock.adjust(Duration.millis(500));
yield* TestClock.adjust(Duration.millis(500));
const token = yield* Fiber.join(fiber);
assert.strictEqual(token, "desktop-bearer-token");
assert.isAtLeast(yield* Ref.get(requestCount), 3);
yield* TestClock.adjust(Duration.seconds(1));
assert.strictEqual(yield* Fiber.join(fiber), "desktop-bearer-token");
assert.strictEqual(yield* Ref.get(requestCount), 3);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("does not retry a rejected bootstrap credential", () =>
Effect.gen(function* () {
const { auth, requestCount } = yield* makeExchange(1, () =>
Response.json(
{
_tag: "EnvironmentAuthInvalidError",
code: "auth_invalid",
reason: "invalid_credential",
traceId: "trace-1",
},
{ status: 401 },
),
);
const fiber = yield* auth.getBearerToken.pipe(Effect.flip, Effect.forkChild);
yield* TestClock.adjust(Duration.seconds(1));
const error = yield* Fiber.join(fiber);
assert.strictEqual(error._tag, "DesktopLocalEnvironmentAuthSessionBootstrapError");
assert.strictEqual(yield* Ref.get(requestCount), 1);
}).pipe(Effect.provide(TestClock.layer())),
);
});
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,5 @@
import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
import type { RemoteEnvironmentRequestError } from "@t3tools/client-runtime/rpc";
import { PRIMARY_LOCAL_ENVIRONMENT_ID } from "@t3tools/contracts";
import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken";
import * as Clock from "effect/Clock";
Expand All
@@ -15,62 +16,24 @@ import * as HttpClient from "effect/http/HttpClient";
import * as DesktopBackendPool from "./DesktopBackendPool.ts";
// The renderer's cookie-session bootstrap retries transient failures for
// ~15s (see retryTransientBootstrap in apps/web/src/environments/primary/auth.ts).
// The main-process bearer exchange had no such retry, so a single transient
// /oauth/token failure (a first-request connection reset on a new OS, a
// loopback quirk, a brief 503 while the backend settles) hard-crashed the app
// via DesktopLocalEnvironmentAuthSessionBootstrapError. Mirror the renderer's
// transient classification here so the bearer path degrades the same way.
// A loopback /oauth/token exchange can fail transiently while the backend
// settles (a 502-504, a refused or reset connection, a timeout). Retry those
// for as long as the renderer's own bootstrap does; a rejected credential or a
// server error is final.
const BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT = Duration.seconds(15);
const BOOTSTRAP_TRANSIENT_RETRY_INTERVAL = Duration.millis(500);
const TRANSIENT_BOOTSTRAP_STATUS_CODES = new Set([502, 503, 504]);
// `executeEnvironmentHttpRequest` normalizes every failure into a
// `RemoteEnvironmentRequestError` (a union of Data.TaggedError shapes from
// packages/client-runtime/src/rpc/http.ts). Declared server errors keep their
// own `_tag`; transport failures become `RemoteEnvironmentAuthFetchError`;
// undeclared HTTP statuses become `RemoteEnvironmentAuthUndeclaredStatusError`.
// Classify by `_tag` so we don't need value imports of the error constructors.
const isTransientBearerBootstrapError = (error: unknown): boolean => {
if (error === null || typeof error !== "object") return false;
const tag = (error as { readonly _tag?: unknown })._tag;
if (typeof tag !== "string") return false;
// Declared EnvironmentHttp errors with a known non-transient status. The
// token endpoint wraps internal failures in EnvironmentInternalError (500),
// credential problems in EnvironmentAuthInvalidError (401), and bad requests
// in EnvironmentRequestInvalidError (400). None of these are transient.
if (
tag === "EnvironmentInternalError" ||
tag === "EnvironmentAuthInvalidError" ||
tag === "EnvironmentRequestInvalidError"
) {
return false;
const isTransientBearerBootstrapError = (error: RemoteEnvironmentRequestError): boolean => {
switch (error._tag) {
case "RemoteEnvironmentAuthFetchError":
case "RemoteEnvironmentAuthTimeoutError":
return true;
case "RemoteEnvironmentAuthUndeclaredStatusError":
return TRANSIENT_BOOTSTRAP_STATUS_CODES.has(error.status);
default:
return false;
}
// Undeclared HTTP statuses: transient only for 502/503/504.
if (tag === "RemoteEnvironmentAuthUndeclaredStatusError") {
const status = (error as { readonly status?: number }).status;
return typeof status === "number" && TRANSIENT_BOOTSTRAP_STATUS_CODES.has(status);
}
// A transport-level fetch failure (connection reset, ECONNREFUSED while the
// loopback listener is still coming up, an undici quirk on a new OS) surfaces
// as RemoteEnvironmentAuthFetchError. Treat these as transient so the bearer
// exchange rides out a brief loopback hiccup instead of crashing the app.
if (tag === "RemoteEnvironmentAuthFetchError") {
return true;
}
if (tag === "RemoteEnvironmentAuthTimeoutError") {
return true;
}
// Effect's HttpClientError carries a response status for status-code errors.
const maybeResponse = (error as { readonly response?: { readonly status: number } }).response;
if (maybeResponse !== undefined && TRANSIENT_BOOTSTRAP_STATUS_CODES.has(maybeResponse.status)) {
return true;
}
// Node fetch throws a TypeError on a network-level failure (DNS, refused,
// reset). The renderer's isTransientBootstrapError treats TypeError as
// transient; mirror that for the main-process undici client.
return error instanceof TypeError;
};
export class DesktopLocalEnvironmentAuthBackendNotConfiguredError extends Schema.TaggedError<DesktopLocalEnvironmentAuthBackendNotConfiguredError>()(
Expand Down
Expand Up
@@ -146,22 +109,11 @@ export const make = Effect.gen(function* () {
},
}).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
// Retry transient failures (502/503/504, transport-level fetch errors,
// timeouts, TypeErrors) before surfacing the bootstrap error. A single
// transient /oauth/token failure no longer hard-crashes the app; the
// renderer's cookie path already had this resilience. spaced(500ms) +
// upTo(15s) gives ~30 attempts in a 15s window.
Effect.retry({
while: isTransientBearerBootstrapError,
schedule: Schedule.spaced(BOOTSTRAP_TRANSIENT_RETRY_INTERVAL).pipe(
Schedule.upTo({ duration: BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT }),
),
schedule: Schedule.spaced(BOOTSTRAP_TRANSIENT_RETRY_INTERVAL),
}),
// Schedule.upTo only bounds when retries are *scheduled*, not an
// in-flight request: an attempt starting near the 15s mark could run
// for its own per-request timeout, leaving getBearerToken blocked for
// ~20s+. Bound the entire retrying effect so a hung request is
// interrupted at the deadline and mapped to the bootstrap error below.
// Bounds the attempts and any request still in flight at the deadline.
Effect.timeout(BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT),
Effect.mapError(
(cause) =>
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -35,13 +35,6 @@ const DESKTOP_AUTH = {
sessionCookieName: "t3_session",
} as const;
const REMOTE_AUTH = {
policy: "remote-reachable",
bootstrapMethods: ["one-time-token"],
sessionMethods: ["browser-session-cookie"],
sessionCookieName: "t3_session",
} as const;
const SESSION_EXPIRES_AT = DateTime.makeUnsafe("2026-04-05T00:00:00.000Z");
const unauthenticatedSession = (auth: AuthSessionState["auth"]): AuthSessionState => ({
authenticated: false,
Expand Down
Expand Up
@@ -276,64 +269,6 @@ describe("resolveInitialServerAuthGateState", () => {
expect(attempts).toBe(4);
});
it("degrades to requires-auth instead of crashing beforeLoad when the initial session fetch fails", async () => {
// Reproduces the launch crash: the initial fetchSessionState() goes
// through the desktop bearer-token path, and a failed bearer bootstrap
// surfaced as an uncaught error in beforeLoad. The fix wraps the initial
// fetch so a failure degrades to requires-auth with an error message.
const runner: PrimaryHttpEffectRunner = async () => {
throw new Error("Failed to create the local desktop bearer session.");
};
__setPrimaryHttpRunnerForTests(runner);
installDesktopBootstrap();
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
// fetchSessionState wraps the thrown error as a PrimaryEnvironmentRequestError
// (status 500 for a non-HTTP cause). The important behavior is that the gate
// resolves to requires-auth instead of rejecting — before the fix this
// rejection crashed TanStack Router's beforeLoad.
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "requires-auth",
auth: DESKTOP_AUTH,
errorMessage: "Primary environment request failed during fetch-session-state (HTTP 500).",
});
});
it("uses loopback-browser fallback metadata when the session fetch fails without a desktop bridge", async () => {
const runner: PrimaryHttpEffectRunner = async () => {
throw new Error("session fetch failed");
};
__setPrimaryHttpRunnerForTests(runner);
installTestBrowser("http://localhost/");
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "requires-auth",
auth: LOOPBACK_AUTH,
errorMessage: "Primary environment request failed during fetch-session-state (HTTP 500).",
});
});
it("uses remote-reachable fallback metadata when the session fetch fails on a remote origin", async () => {
const runner: PrimaryHttpEffectRunner = async () => {
throw new Error("session fetch failed");
};
__setPrimaryHttpRunnerForTests(runner);
vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
installTestBrowser("https://remote.example.com/");
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
await expect(resolveInitialServerAuthGateState()).resolves.toEqual({
status: "requires-auth",
auth: REMOTE_AUTH,
errorMessage: "Primary environment request failed during fetch-session-state (HTTP 500).",
});
});
it("takes a pairing token from the location hash and strips it immediately", async () => {
const testWindow = installTestBrowser("http://localhost/#token=pairing-token");
const { takePairingTokenFromUrl } = await import("./environments/primary");
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.