feat(web): show a sidebar status alert while WSL backend is connecting

A cold-start launch where the WSL backend is still booting (or where
the renderer's first registration attempt fails before retries cover
the gap) used to leave the sidebar silent: no projects, no
indication anything was happening. The user has no way to tell
whether the backend is starting up, broken, or simply not
configured.

Promote the reconciler's in-memory trace to a real zustand store
(useLocalSecondaryReconcileStore) tracking pendingInstanceIds,
per-instance registrationErrors, and budgetExhausted. The reconciler
writes:
  - addPending/removePending around each register attempt
  - setRegistrationError on Promise.race failure or timeout
  - clearRegistrationError when an attempt actually returns a record
  - budgetExhausted = true once auto-retry runs out of attempts
  - budgetExhausted = false on user-driven reconcile (so Retry resets it)

The window.__t3LocalSecondaryDebug global keeps working - it now
just reads from the store.

Add a LocalSecondaryStatus component to the sidebar. It renders:
  - A "Connecting <label>" alert with a spinner while pendingInstanceIds
    is non-empty.
  - A "Couldn't connect <label>" warning alert with the error message
    and a Retry button when the retry budget runs out with errors
    still recorded.

Retry calls reconcileLocalSecondaryEnvironments() (resetBudget: true)
so the loop gets a fresh shot.
This commit is contained in:
Josh Gratton committed 2026-05-18 10:01:25 -04:00
1 parent 6bf864d277
commit c47ec5db04
2 files changed
+165 -32

No files matched your search

+67
View File
@@ -5,6 +5,7 @@ import {
CloudIcon,
ContainerIcon,
FolderPlusIcon,
LoaderIcon,
SearchIcon,
SettingsIcon,
SquarePenIcon,
@@ -62,6 +63,10 @@ import {
type SidebarThreadSortOrder,
} from "@t3tools/contracts/settings";
import { usePrimaryEnvironmentId } from "../environments/primary";
import {
reconcileLocalSecondaryEnvironments,
useLocalSecondaryReconcileStore,
} from "../environments/local";
import { isElectron } from "../env";
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
import { isTerminalFocused } from "../lib/terminalFocus";
@@ -2257,6 +2262,67 @@ const SidebarProjectListRow = memo(function SidebarProjectListRow(props: Sidebar
);
});
function LocalSecondaryStatus() {
const pendingIds = useLocalSecondaryReconcileStore((state) => state.pendingInstanceIds);
const errors = useLocalSecondaryReconcileStore((state) => state.registrationErrors);
const bootstraps = useLocalSecondaryReconcileStore((state) => state.bootstrapsSeen);
const budgetExhausted = useLocalSecondaryReconcileStore((state) => state.budgetExhausted);
const labelForId = useCallback(
(id: string) => {
const match = bootstraps.find((b) => b.id === id);
return match?.label ?? id;
},
[bootstraps],
);
// Pending takes precedence: while a registration is in flight, show
// "Connecting" even if a previous attempt left an error in the store.
// Once nothing is pending and the auto-retry budget has run out, the
// remaining errors are the user-actionable failures.
const pendingSet = new Set(pendingIds);
const failedIds = budgetExhausted ? Object.keys(errors).filter((id) => !pendingSet.has(id)) : [];
if (pendingIds.length === 0 && failedIds.length === 0) return null;
const handleRetry = () => {
void reconcileLocalSecondaryEnvironments();
};
return (
<SidebarGroup className="px-2 pt-2 pb-0">
{pendingIds.length > 0 ? (
<Alert
variant="default"
className="rounded-2xl border-border/40 bg-accent/40 text-muted-foreground"
>
<LoaderIcon className="animate-spin" />
<AlertTitle className="text-xs font-medium text-foreground">
Connecting {pendingIds.map(labelForId).join(", ")}
</AlertTitle>
</Alert>
) : null}
{failedIds.length > 0 ? (
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
<TriangleAlertIcon />
<AlertTitle>Couldn't connect {failedIds.map(labelForId).join(", ")}</AlertTitle>
<AlertDescription>
{failedIds
.map((id) => errors[id]?.message)
.filter(Boolean)
.join("; ") || "The backend didn't respond."}
</AlertDescription>
<AlertAction>
<Button size="xs" variant="outline" onClick={handleRetry}>
Retry
</Button>
</AlertAction>
</Alert>
) : null}
</SidebarGroup>
);
}
function T3Wordmark() {
return (
<svg
@@ -2688,6 +2754,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
</Alert>
</SidebarGroup>
) : null}
<LocalSecondaryStatus />
<SidebarGroup className="px-2 py-2">
<div className="mb-1 flex items-center justify-between pl-2 pr-1.5">
<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
+98 -32
View File
@@ -27,6 +27,8 @@
// It's safe to call multiple times — pending work is deduped by
// `pendingByInstanceId` and entries already wired up are skipped.
import { create } from "zustand";
import {
PRIMARY_LOCAL_ENVIRONMENT_ID,
type AuthSessionRole,
@@ -67,45 +69,98 @@ const AUTO_RETRY_DELAYS_MS = [2_000, 4_000, 8_000, 16_000, 30_000, 45_000, 60_00
let autoRetryHandle: ReturnType<typeof setTimeout> | null = null;
let autoRetryAttempt = 0;
interface LocalSecondaryReconcileTrace {
readonly bootstrapsSeen: ReadonlyArray<{ id: string; hasToken: boolean; httpBaseUrl: string }>;
readonly registrationErrors: ReadonlyMap<string, { message: string; at: string }>;
export interface LocalSecondaryReconcileBootstrapSnapshot {
readonly id: string;
readonly label: string;
readonly hasToken: boolean;
readonly httpBaseUrl: string;
}
export interface LocalSecondaryReconcileError {
readonly message: string;
readonly at: string;
}
export interface LocalSecondaryReconcileState {
// Bootstraps the renderer most recently learned about from the
// desktop pool. Reflects whatever the next register attempt will
// try to bring up.
readonly bootstrapsSeen: ReadonlyArray<LocalSecondaryReconcileBootstrapSnapshot>;
// Instance ids that have a register call in flight right now.
readonly pendingInstanceIds: ReadonlyArray<string>;
// Per-instance error trace from the most recent register attempt
// that failed. Cleared when that instance registers successfully.
readonly registrationErrors: Readonly<Record<string, LocalSecondaryReconcileError>>;
// True once the auto-retry budget has run out without all
// secondaries landing. The sidebar uses this to switch from
// "Connecting" to "Couldn't connect, retry?".
readonly budgetExhausted: boolean;
readonly lastReconcileAt: string | null;
readonly attempts: number;
}
const reconcileTrace: {
bootstrapsSeen: ReadonlyArray<{ id: string; hasToken: boolean; httpBaseUrl: string }>;
registrationErrors: Map<string, { message: string; at: string }>;
lastReconcileAt: string | null;
attempts: number;
} = {
export const useLocalSecondaryReconcileStore = create<LocalSecondaryReconcileState>()(() => ({
bootstrapsSeen: [],
registrationErrors: new Map(),
pendingInstanceIds: [],
registrationErrors: {},
budgetExhausted: false,
lastReconcileAt: null,
attempts: 0,
};
}));
// Surface the reconciler's internal state on `window` for ad-hoc
// debugging. Production renderers don't expose CDP, so this is the
// only way for a user to inspect "what does the local-secondary
// reconciler think happened?" from the dev tools console.
function patchReconcileState(patch: Partial<LocalSecondaryReconcileState>): void {
useLocalSecondaryReconcileStore.setState((state) => ({ ...state, ...patch }));
}
function addPending(instanceId: string): void {
useLocalSecondaryReconcileStore.setState((state) => {
if (state.pendingInstanceIds.includes(instanceId)) return state;
return { ...state, pendingInstanceIds: [...state.pendingInstanceIds, instanceId] };
});
}
function removePending(instanceId: string): void {
useLocalSecondaryReconcileStore.setState((state) => {
if (!state.pendingInstanceIds.includes(instanceId)) return state;
return {
...state,
pendingInstanceIds: state.pendingInstanceIds.filter((id) => id !== instanceId),
};
});
}
function setRegistrationError(instanceId: string, error: LocalSecondaryReconcileError): void {
useLocalSecondaryReconcileStore.setState((state) => ({
...state,
registrationErrors: { ...state.registrationErrors, [instanceId]: error },
}));
}
function clearRegistrationError(instanceId: string): void {
useLocalSecondaryReconcileStore.setState((state) => {
if (!(instanceId in state.registrationErrors)) return state;
const next = { ...state.registrationErrors };
delete next[instanceId];
return { ...state, registrationErrors: next };
});
}
// Surface the reconciler's state on `window` for ad-hoc debugging.
// Production renderers don't expose CDP, so this is the only way for
// a user to inspect what the local-secondary reconciler thinks
// happened. Reads straight from the zustand store so it always
// reflects the current state.
function exposeDebugGlobal(): void {
if (typeof window === "undefined") return;
const w = window as unknown as {
__t3LocalSecondaryDebug?: {
getState: () => LocalSecondaryReconcileTrace;
getState: () => LocalSecondaryReconcileState;
retryNow: () => Promise<void>;
};
};
if (w.__t3LocalSecondaryDebug) return;
w.__t3LocalSecondaryDebug = {
getState: () => ({
bootstrapsSeen: reconcileTrace.bootstrapsSeen,
registrationErrors: new Map(reconcileTrace.registrationErrors),
lastReconcileAt: reconcileTrace.lastReconcileAt,
attempts: reconcileTrace.attempts,
}),
getState: () => useLocalSecondaryReconcileStore.getState(),
retryNow: () => reconcileLocalSecondaryEnvironments(),
};
}
@@ -123,13 +178,16 @@ function readBootstraps(): readonly DesktopEnvironmentBootstrap[] {
console.error("[LOCAL_SECONDARY] readBootstraps threw", error);
return [];
}
reconcileTrace.bootstrapsSeen = list.map((entry) => ({
id: entry.id,
hasToken: Boolean(entry.bootstrapToken),
httpBaseUrl: entry.httpBaseUrl ?? "",
}));
reconcileTrace.lastReconcileAt = new Date().toISOString();
reconcileTrace.attempts += 1;
patchReconcileState({
bootstrapsSeen: list.map((entry) => ({
id: entry.id,
label: entry.label,
hasToken: Boolean(entry.bootstrapToken),
httpBaseUrl: entry.httpBaseUrl ?? "",
})),
lastReconcileAt: new Date().toISOString(),
attempts: useLocalSecondaryReconcileStore.getState().attempts + 1,
});
return list;
}
@@ -307,16 +365,17 @@ async function reconcileOnce(): Promise<void> {
attemptTimeoutMs,
);
});
addPending(bootstrap.id);
const promise = Promise.race([registerSecondaryLocalEnvironment(bootstrap), timeoutPromise])
.then((record) => {
if (record) {
reconcileTrace.registrationErrors.delete(bootstrap.id);
clearRegistrationError(bootstrap.id);
}
return record;
})
.catch((error) => {
const message = error instanceof Error ? error.message : String(error);
reconcileTrace.registrationErrors.set(bootstrap.id, {
setRegistrationError(bootstrap.id, {
message,
at: new Date().toISOString(),
});
@@ -325,6 +384,7 @@ async function reconcileOnce(): Promise<void> {
})
.finally(() => {
pendingByInstanceId.delete(bootstrap.id);
removePending(bootstrap.id);
});
pendingByInstanceId.set(bootstrap.id, { promise });
await promise;
@@ -334,7 +394,12 @@ async function reconcileOnce(): Promise<void> {
function scheduleAutoRetry(): void {
if (autoRetryHandle !== null) return;
if (autoRetryAttempt >= AUTO_RETRY_DELAYS_MS.length) return;
if (autoRetryAttempt >= AUTO_RETRY_DELAYS_MS.length) {
// Budget exhausted. Surface this through the store so the sidebar
// can switch from "Connecting..." to "Couldn't connect, retry?".
patchReconcileState({ budgetExhausted: true });
return;
}
// Note: we deliberately don't short-circuit when the current bootstraps
// list lacks any secondary entry. The desktop pool only publishes a
// backend's bootstrap once its first start cycle has produced a config
@@ -365,6 +430,7 @@ function runReconcile(options: { readonly resetBudget: boolean }): Promise<void>
clearTimeout(autoRetryHandle);
autoRetryHandle = null;
}
patchReconcileState({ budgetExhausted: false });
}
const next = reconcileOnce()
.finally(() => {