Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(app): keep session lists and routed sessions alive through engine gaps

ogsamrat6dbe6afde6c6
diff --git a/apps/app/src/app/lib/opencode-session-native.ts b/apps/app/src/app/lib/opencode-session-native.ts
index 747b45fb..0f9d6bb9 100644
--- a/apps/app/src/app/lib/opencode-session-native.ts
+++ b/apps/app/src/app/lib/opencode-session-native.ts
@@ -73,15 +73,26 @@ function sessionOperations(endpoint: NativeSessionEndpoint, dependencies?: Nativ
return (dependencies?.createOperations ?? createNativeOperations)(endpoint);
}
-function unwrapSessionResult<T>(result: FieldsResult<T>, notFoundCode?: string): NonNullable<T> {
+/**
+ * Unwraps a native SDK result and tags the thrown error with the HTTP status
+ * and error code the route retry logic classifies. When fetch itself rejected
+ * (built-in server not listening, transport timeout) the SDK returns no
+ * `response`; the original transport error ("Failed to fetch", "Request timed
+ * out.") is rethrown untouched so callers keep treating it as transient.
+ */
+export function unwrapNativeSessionResult<T>(result: FieldsResult<T>, notFoundCode?: string): NonNullable<T> {
+ const status = result.response?.status;
+ if (result.data === undefined && status === undefined && result.error instanceof Error) {
+ throw result.error;
+ }
try {
return unwrap(result);
} catch (error) {
if (error instanceof Error) {
- Object.assign(error, { status: result.response.status });
+ if (typeof status === "number") Object.assign(error, { status });
const code = result.error && typeof result.error === "object" && "code" in result.error && typeof result.error.code === "string"
? result.error.code
- : result.response.status === 404
+ : status === 404
? notFoundCode
: undefined;
if (code) Object.assign(error, { code });
@@ -90,6 +101,8 @@ function unwrapSessionResult<T>(result: FieldsResult<T>, notFoundCode?: string):
}
}
+const unwrapSessionResult = unwrapNativeSessionResult;
+
export async function getNativeSession(
endpoint: NativeSessionEndpoint,
sessionId: string,
diff --git a/apps/app/src/app/lib/opencode-v2-adapter.ts b/apps/app/src/app/lib/opencode-v2-adapter.ts
index 66de161d..3778fb51 100644
--- a/apps/app/src/app/lib/opencode-v2-adapter.ts
+++ b/apps/app/src/app/lib/opencode-v2-adapter.ts
@@ -1418,7 +1418,7 @@ export function createClientV2(
reply: parameters.reply,
message: parameters.message,
}, options);
- if (result.error !== undefined) {
+ if (result.error !== undefined || !result.response) {
return { error: result.error, request: result.request, response: result.response };
}
return { data: true, request: result.request, response: result.response };
@@ -1433,7 +1433,7 @@ export function createClientV2(
requestID: parameters.permissionID,
reply: parameters.response,
}, options);
- if (result.error !== undefined) {
+ if (result.error !== undefined || !result.response) {
return { error: result.error, request: result.request, response: result.response };
}
return { data: true, request: result.request, response: result.response };
diff --git a/apps/app/src/app/lib/opencode.ts b/apps/app/src/app/lib/opencode.ts
index 83fc1a08..964173e4 100644
--- a/apps/app/src/app/lib/opencode.ts
+++ b/apps/app/src/app/lib/opencode.ts
@@ -3,9 +3,14 @@ import { createOpencodeClient } from "@opencode-ai/sdk/v2/client";
import { desktopFetch } from "./desktop";
import { isDesktopRuntime } from "./runtime-env";
+/**
+ * Mirrors the SDK's fields-style result. On an error the SDK omits `response`
+ * when fetch itself rejected (server not listening, transport timeout), so
+ * error readers must not assume an HTTP status exists.
+ */
export type FieldsResult<T> =
| ({ data: T; error?: undefined } & { request: Request; response: Response })
- | ({ data?: undefined; error: unknown } & { request: Request; response: Response });
+ | ({ data?: undefined; error: unknown } & { request: Request; response?: Response });
type PromptAsyncParameters = {
sessionID: string;
@@ -47,6 +52,14 @@ const MCP_AUTH_OPENCODE_REQUEST_TIMEOUT_MS = 90_000;
// Bound the acceptance handshake, not the task. A timeout leaves admission
// unknown, so the transport must never automatically resend the prompt.
const PROMPT_ASYNC_REQUEST_TIMEOUT_MS = 30_000;
+// Listing or reading sessions waits on the engine to start the workspace's
+// instance (cold boot, restart after the built-in server came back). The
+// generic 10 s budget aborted those reads, and the sidebar then showed an
+// empty workspace. Keep them bounded, but long enough to outlast a start.
+export const SESSION_READ_REQUEST_TIMEOUT_MS = 45_000;
+// GET <base>/session (list) and GET <base>/session/<id> (get), v1 or v2
+// (/api/session). The 300 ms status poll keeps the short budget.
+const SESSION_READ_PATH_RE = /\/session(?:\/(?!status$)[^/]+)?\/?$/;
const SESSION_LONG_RUNNING_URL_RE = /\/session\/[^/?#]+\/(?:command|summarize)(?:[?#]|$)/;
const SESSION_PROMPT_ASYNC_URL_RE = /\/session\/[^/?#]+\/prompt_async(?:[?#]|$)/;
@@ -82,8 +95,27 @@ function getRequestUrl(input: RequestInfo | URL): string {
return String(input);
}
-function resolveRequestTimeoutMs(input: RequestInfo | URL, fallbackMs: number): number {
+function getRequestMethod(input: RequestInfo | URL, init?: RequestInit): string {
+ if (init?.method) return init.method.toUpperCase();
+ if (typeof Request !== "undefined" && input instanceof Request) return input.method.toUpperCase();
+ return "GET";
+}
+
+function isSessionReadPath(url: string): boolean {
+ let pathname: string;
+ try {
+ pathname = new URL(url, "http://localhost").pathname;
+ } catch {
+ pathname = url.split(/[?#]/)[0] ?? "";
+ }
+ return SESSION_READ_PATH_RE.test(pathname);
+}
+
+export function resolveRequestTimeoutMs(input: RequestInfo | URL, fallbackMs: number, init?: RequestInit): number {
const url = getRequestUrl(input);
+ if (fallbackMs > 0 && getRequestMethod(input, init) === "GET" && isSessionReadPath(url)) {
+ return Math.max(fallbackMs, SESSION_READ_REQUEST_TIMEOUT_MS);
+ }
if (SESSION_LONG_RUNNING_URL_RE.test(url)) {
return 0;
}
@@ -179,7 +211,7 @@ async function fetchWithTimeout(
init: RequestInit | undefined,
timeoutMs: number,
) {
- const effectiveTimeoutMs = resolveRequestTimeoutMs(input, timeoutMs);
+ const effectiveTimeoutMs = resolveRequestTimeoutMs(input, timeoutMs, init);
if (!Number.isFinite(effectiveTimeoutMs) || effectiveTimeoutMs <= 0) {
return fetchImpl(input, init);
}
diff --git a/apps/app/src/app/types.ts b/apps/app/src/app/types.ts
index 698e4f76..709dbb9b 100644
--- a/apps/app/src/app/types.ts
+++ b/apps/app/src/app/types.ts
@@ -35,6 +35,8 @@ export type WorkspaceSessionGroup = {
sessions: SidebarSessionItem[];
status: "idle" | "loading" | "ready" | "error";
error?: string | null;
+ /** The session list could not be loaded; `sessions` holds the last known list, if any. */
+ listError?: string | null;
};
export type PlaceholderMessageInfo = {
diff --git a/apps/app/src/i18n/locales/en.ts b/apps/app/src/i18n/locales/en.ts
index b4081d94..5e17425f 100644
--- a/apps/app/src/i18n/locales/en.ts
+++ b/apps/app/src/i18n/locales/en.ts
@@ -1989,6 +1989,8 @@ export default {
"workspace.local_badge": "Local",
"workspace.new_task_inline": "+ New task",
"workspace.no_tasks": "No tasks yet.",
+ "workspace.tasks_load_failed": "Couldn't load tasks",
+ "workspace.tasks_load_retry": "Retry",
"workspace.remote_badge": "Remote",
"workspace.rename_description": "Update the name shown in the sidebar.",
"workspace.rename_label": "Workspace name",
diff --git a/apps/app/src/react-app/domains/session/chat/session-page.tsx b/apps/app/src/react-app/domains/session/chat/session-page.tsx
index 64e3648c..7347e3b7 100644
--- a/apps/app/src/react-app/domains/session/chat/session-page.tsx
+++ b/apps/app/src/react-app/domains/session/chat/session-page.tsx
@@ -171,6 +171,8 @@ export type SessionPageSidebarProps = {
onRevealWorkspace: (workspaceId: string) => void;
onRecoverWorkspace: (workspaceId: string) => Promise<boolean> | boolean | void;
onTestWorkspaceConnection: (workspaceId: string) => Promise<boolean> | boolean | void;
+ /** Reloads a workspace's task list after it failed to load. */
+ onRetryWorkspaceTasks?: (workspaceId: string) => void;
onEditWorkspaceConnection: (workspaceId: string) => void;
onForgetWorkspace: (workspaceId: string) => void;
onOpenCreateWorkspace: () => void;
@@ -1405,6 +1407,7 @@ export function SessionPage(props: SessionPageProps) {
onRevealWorkspace={props.sidebar.onRevealWorkspace}
onRecoverWorkspace={props.sidebar.onRecoverWorkspace}
onTestWorkspaceConnection={props.sidebar.onTestWorkspaceConnection}
+ onRetryWorkspaceTasks={props.sidebar.onRetryWorkspaceTasks}
onEditWorkspaceConnection={props.sidebar.onEditWorkspaceConnection}
onForgetWorkspace={props.sidebar.onForgetWorkspace}
onOpenCreateWorkspace={props.sidebar.onOpenCreateWorkspace}
diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar-provider.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar-provider.tsx
index 4303b1b4..9a02f534 100644
--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar-provider.tsx
+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar-provider.tsx
@@ -27,6 +27,7 @@ export type SidebarContextValue = {
onRevealWorkspace: (workspaceId: string) => void;
onRecoverWorkspace: (workspaceId: string) => Promise<boolean> | boolean | void;
onTestWorkspaceConnection: (workspaceId: string) => Promise<boolean> | boolean | void;
+ onRetryWorkspaceTasks?: (workspaceId: string) => void;
onEditWorkspaceConnection: (workspaceId: string) => void;
onForgetWorkspace: (workspaceId: string) => void;
expandWorkspace: (workspaceId: string) => void;
diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
index 9bcedbaf..8c53ef83 100644
--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
@@ -135,6 +135,7 @@ import {
isActiveWorkSessionStatus,
isNeedsAttentionSessionStatus,
isSessionArchived,
+ isWorkspaceTaskListUnavailable,
partitionArchivedSessions,
workspaceKindLabel,
workspaceLabel,
@@ -937,6 +938,7 @@ export type AppSidebarProps = {
onRevealWorkspace: (workspaceId: string) => void;
onRecoverWorkspace: (workspaceId: string) => Promise<boolean> | boolean | void;
onTestWorkspaceConnection: (workspaceId: string) => Promise<boolean> | boolean | void;
+ onRetryWorkspaceTasks?: (workspaceId: string) => void;
onEditWorkspaceConnection: (workspaceId: string) => void;
onForgetWorkspace: (workspaceId: string) => void;
onOpenCreateWorkspace: () => void;
@@ -1201,6 +1203,7 @@ export function AppSidebar(props: AppSidebarProps) {
onRevealWorkspace: props.onRevealWorkspace,
onRecoverWorkspace: props.onRecoverWorkspace,
onTestWorkspaceConnection: props.onTestWorkspaceConnection,
+ onRetryWorkspaceTasks: props.onRetryWorkspaceTasks,
onEditWorkspaceConnection: props.onEditWorkspaceConnection,
onForgetWorkspace: props.onForgetWorkspace,
expandWorkspace,
@@ -1921,6 +1924,22 @@ function WorkspaceSidebarGroup({
<span className="truncate">{taskLoadError.message}</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
+ ) : isWorkspaceTaskListUnavailable(group) ? (
+ <SidebarMenuSubItem>
+ <SidebarMenuSubButton
+ data-workspace-tasks-load-failed
+ className="text-muted-foreground text-xs"
+ title={group.listError ?? undefined}
+ onClick={() => ctx.onRetryWorkspaceTasks?.(workspace.id)}
+ >
+ <span className="truncate">
+ {t("workspace.tasks_load_failed")}
+ {ctx.onRetryWorkspaceTasks ? (
+ <span className="text-foreground underline-offset-2 hover:underline"> · {t("workspace.tasks_load_retry")}</span>
+ ) : null}
+ </span>
+ </SidebarMenuSubButton>
+ </SidebarMenuSubItem>
) : (
<SidebarMenuSubItem>
<SidebarMenuSubButton
diff --git a/apps/app/src/react-app/domains/session/sidebar/utils.ts b/apps/app/src/react-app/domains/session/sidebar/utils.ts
index d50cd886..09c57ff8 100644
--- a/apps/app/src/react-app/domains/session/sidebar/utils.ts
+++ b/apps/app/src/react-app/domains/session/sidebar/utils.ts
@@ -5,6 +5,13 @@ import { t } from "../../../../i18n";
export const MAX_SESSIONS_PREVIEW = 6;
+/**
+ * A group with no sessions to show whose list failed to load. It renders a
+ * "Couldn't load tasks · Retry" row, never the "No tasks yet" empty state.
+ */
+export const isWorkspaceTaskListUnavailable = (group: Pick<WorkspaceSessionGroup, "status" | "listError">): boolean =>
+ group.status !== "loading" && Boolean(group.listError?.trim());
+
export type SessionListItem = WorkspaceSessionGroup["sessions"][number];
export type FlattenedSessionRow = { session: SessionListItem };
diff --git a/apps/app/src/react-app/shell/route-workspaces.ts b/apps/app/src/react-app/shell/route-workspaces.ts
index 6c840fa0..c25de051 100644
--- a/apps/app/src/react-app/shell/route-workspaces.ts
+++ b/apps/app/src/react-app/shell/route-workspaces.ts
@@ -7,7 +7,7 @@ import type { Session } from "@opencode-ai/sdk/v2/client";
import { createClient, unwrap } from "@/app/lib/opencode";
import { createClientV2, isOpencodeV2BaseUrl } from "@/app/lib/opencode-v2-adapter";
-import { deleteNativeSession } from "@/app/lib/opencode-session-native";
+import { deleteNativeSession, unwrapNativeSessionResult } from "@/app/lib/opencode-session-native";
import { OmniRushServerError, type OmniRushWorkspaceInfo } from "@/app/lib/omnirush-server";
import type { ResolvedWorkspaceEndpoint } from "@/app/lib/workspace-endpoint";
import type { WorkspaceInfo } from "@/app/lib/desktop-types";
@@ -36,7 +36,8 @@ export type RouteSession = Session & {
type RouteSessionListResult =
| { data: RouteSession[]; error?: undefined; request: Request; response: Response }
- | { data?: undefined; error: unknown; request: Request; response: Response };
+ // No response when fetch itself rejected (server down, transport timeout).
+ | { data?: undefined; error: unknown; request: Request; response?: Response };
export type RouteSessionListTransport = (input: {
endpoint: ResolvedWorkspaceEndpoint;
limit: number;
@@ -83,18 +84,7 @@ export async function listRouteSessions(
endpoint: ResolvedWorkspaceEndpoint,
transport: RouteSessionListTransport = nativeRouteSessionList,
): Promise<RouteSession[]> {
- const result = await transport({ endpoint, limit: 200 });
- try {
- return unwrap(result);
- } catch (error) {
- if (error instanceof Error) {
- Object.assign(error, { status: result.response.status });
- if (result.error && typeof result.error === "object" && "code" in result.error && typeof result.error.code === "string") {
- Object.assign(error, { code: result.error.code });
- }
- }
- throw error;
- }
+ return unwrapNativeSessionResult(await transport({ endpoint, limit: 200 }));
}
export function mapDesktopWorkspace(workspace: WorkspaceInfo): RouteWorkspace {
@@ -217,6 +207,51 @@ export async function withTransientEngineRetry<T>(input: {
export const readRouteSessionsWithRetry = withTransientEngineRetry;
+/** Waits between reads of a routed session the engine could not answer yet; the last one repeats. */
+export const ROUTE_SESSION_RETRY_DELAYS_MS: readonly number[] = [500, 1_000, 2_000, 4_000, 8_000, 15_000];
+
+export type RouteSessionLoadOutcome<T> =
+ | { status: "loaded"; value: T }
+ | { status: "not-found" | "error"; message: string; error: unknown }
+ | { status: "cancelled" };
+
+/**
+ * Loads the session named by the route. Transient failures (built-in server
+ * restarting, engine still starting, request timeout) keep retrying with
+ * backoff while the caller still wants the session, so a restart window never
+ * ends in a terminal "Session could not be loaded". A missing session and
+ * terminal errors (auth, bad request) resolve at once.
+ */
+export async function loadRouteSessionWithRetry<T>(input: {
+ load: () => Promise<T>;
+ isCancelled: () => boolean;
+ retryDelaysMs?: readonly number[];
+ /** Total attempts including the first; unbounded by default. */
+ maxAttempts?: number;
+ wait?: (delayMs: number) => Promise<void>;
+}): Promise<RouteSessionLoadOutcome<T>> {
+ const retryDelaysMs = input.retryDelaysMs ?? ROUTE_SESSION_RETRY_DELAYS_MS;
+ const maxAttempts = input.maxAttempts ?? Number.POSITIVE_INFINITY;
+ const wait = input.wait ?? ((delayMs: number) => new Promise<void>((resolve) => {
+ window.setTimeout(resolve, delayMs);
+ }));
+ for (let attempt = 0; ; attempt += 1) {
+ if (input.isCancelled()) return { status: "cancelled" };
+ try {
+ const value = await input.load();
+ return input.isCancelled() ? { status: "cancelled" } : { status: "loaded", value };
+ } catch (error) {
+ if (input.isCancelled()) return { status: "cancelled" };
+ const kind = classifyRouteSessionReadError(error);
+ if (kind !== "retryable" || attempt + 1 >= maxAttempts) {
+ return { status: kind === "not-found" ? "not-found" : "error", message: describeRouteError(error), error };
+ }
+ const delayMs = retryDelaysMs[Math.min(attempt, retryDelaysMs.length - 1)] ?? 0;
+ await wait(delayMs);
+ }
+ }
+}
+
/** Waits between task-creation attempts; each attempt itself may take the 10 s request timeout. */
export const TASK_CREATE_RETRY_DELAYS_MS: readonly number[] = [1_000, 2_000, 4_000];
@@ -482,6 +517,7 @@ export function toSessionGroups(
sessionsByWorkspaceId: Record<string, RouteSession[]>,
errorsByWorkspaceId: Record<string, string | null>,
loadingWorkspaceIds: Set<string>,
+ listErrorsByWorkspaceId: Record<string, string | null> = {},
): WorkspaceSessionGroup[] {
return workspaces.map((workspace) => ({
workspace,
@@ -492,9 +528,39 @@ export function toSessionGroups(
? "error"
: "ready",
error: errorsByWorkspaceId[workspace.id],
+ listError: listErrorsByWorkspaceId[workspace.id] ?? null,
}));
}
+/**
+ * Pause before each further round of automatic session-list reloads once a
+ * round's own quick retries failed. The last value repeats: a workspace whose
+ * list cannot load keeps being retried until it loads or disappears.
+ */
+export const SESSION_LIST_RECOVERY_DELAYS_MS: readonly number[] = [5_000, 10_000, 20_000, 30_000, 60_000];
+
+export function sessionListRecoveryDelayMs(round: number): number {
+ const delays = SESSION_LIST_RECOVERY_DELAYS_MS;
+ return delays[Math.min(Math.max(0, round), delays.length - 1)] ?? 60_000;
+}
+
+/**
+ * Sessions to show after a list load failed: never swap known sessions for an
+ * empty list. A list that was loaded in this window stays as it is. Otherwise
+ * the few sessions already present (just created, or opened from the route)
+ * are completed with the last saved list for the workspace.
+ */
+export function sessionsAfterListFailure<T extends { id: string }>(input: {
+ current: readonly T[] | undefined;
+ cached: readonly T[] | null | undefined;
+ currentIsListed: boolean;
+}): T[] {
+ const current = input.current ?? [];
+ if (input.currentIsListed && current.length > 0) return [...current];
+ const currentIds = new Set(current.map((session) => session.id));
+ return [...current, ...(input.cached ?? []).filter((session) => !currentIds.has(session.id))];
+}
+
export function isActiveSessionStatus(status: unknown) {
return status === "running" || status === "retry" || status === "busy" || status === "streaming";
}
diff --git a/apps/app/src/react-app/shell/session-memory.ts b/apps/app/src/react-app/shell/session-memory.ts
index 79941e06..7fe526f3 100644
--- a/apps/app/src/react-app/shell/session-memory.ts
+++ b/apps/app/src/react-app/shell/session-memory.ts
@@ -8,6 +8,9 @@ const ACTIVE_WORKSPACE_KEY = "omnirush.react.activeWorkspace";
const SESSION_BY_WORKSPACE_KEY = "omnirush.react.sessionByWorkspace";
const WORKSPACE_ORDER_KEY = "omnirush.react.workspaceOrder";
const WORKSPACE_PROJECT_DIMENSION_KEY = "omnirush.react.workspaceProjectDimension";
+const WORKSPACE_SESSION_LIST_KEY = "omnirush.react.workspaceSessionList";
+const WORKSPACE_SESSION_LIST_MAX_WORKSPACES = 20;
+const WORKSPACE_SESSION_LIST_MAX_SESSIONS = 100;
function safeGet(key: string): string | null {
if (typeof window === "undefined") return null;
@@ -155,9 +158,118 @@ export function writeWorkspaceProjectDimension(
safeSet(WORKSPACE_PROJECT_DIMENSION_KEY, Object.keys(map).length ? JSON.stringify(map) : null);
}
+/**
+ * The sidebar fields of a session, kept so a workspace whose session list
+ * cannot be loaded (engine starting, built-in server restarting) still shows
+ * its last known tasks instead of "No tasks yet". Heavy fields (diffs,
+ * permissions, metadata) are dropped.
+ */
+export type CachedWorkspaceSession = {
+ id: string;
+ slug: string;
+ projectID: string;
+ directory: string;
+ parentID?: string;
+ title: string;
+ version: string;
+ time: { created: number; updated: number; archived?: number };
+};
+
+type WorkspaceSessionListCache = Record<string, { savedAt: number; sessions: CachedWorkspaceSession[] }>;
+
+function finiteNumber(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
+}
+
+function toCachedWorkspaceSession(value: unknown): CachedWorkspaceSession | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const record = value as Record<string, unknown>;
+ const id = typeof record.id === "string" ? record.id.trim() : "";
+ if (!id) return null;
+ const time = record.time && typeof record.time === "object" ? record.time as Record<string, unknown> : {};
+ const archived = finiteNumber(time.archived);
+ const parentID = typeof record.parentID === "string" && record.parentID ? record.parentID : undefined;
+ return {
+ id,
+ slug: typeof record.slug === "string" ? record.slug : "",
+ projectID: typeof record.projectID === "string" ? record.projectID : "",
+ directory: typeof record.directory === "string" ? record.directory : "",
+ ...(parentID ? { parentID } : {}),
+ title: typeof record.title === "string" ? record.title : "",
+ version: typeof record.version === "string" ? record.version : "",
+ time: {
+ created: finiteNumber(time.created) ?? 0,
+ updated: finiteNumber(time.updated) ?? finiteNumber(time.created) ?? 0,
+ ...(archived !== undefined ? { archived } : {}),
+ },
+ };
+}
+
+function readWorkspaceSessionListCache(): WorkspaceSessionListCache {
+ const raw = safeGet(WORKSPACE_SESSION_LIST_KEY);
+ if (!raw) return {};
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
+ const result: WorkspaceSessionListCache = {};
+ for (const [workspaceId, entry] of Object.entries(parsed as Record<string, unknown>)) {
+ if (!workspaceId.trim() || !entry || typeof entry !== "object") continue;
+ const record = entry as Record<string, unknown>;
+ if (!Array.isArray(record.sessions)) continue;
+ result[workspaceId] = {
+ savedAt: finiteNumber(record.savedAt) ?? 0,
+ sessions: record.sessions.flatMap((session) => {
+ const cached = toCachedWorkspaceSession(session);
+ return cached ? [cached] : [];
+ }),
+ };
+ }
+ return result;
+ } catch {
+ return {};
+ }
+}
+
+function writeWorkspaceSessionListCache(cache: WorkspaceSessionListCache): void {
+ const entries = Object.entries(cache)
+ .sort(([, a], [, b]) => b.savedAt - a.savedAt)
+ .slice(0, WORKSPACE_SESSION_LIST_MAX_WORKSPACES);
+ safeSet(WORKSPACE_SESSION_LIST_KEY, entries.length ? JSON.stringify(Object.fromEntries(entries)) : null);
+}
+
+/** Last successfully loaded session list for a workspace, or null when none was saved. */
+export function readCachedWorkspaceSessions(workspaceId: string | null | undefined): CachedWorkspaceSession[] | null {
+ const wsId = workspaceId?.trim();
+ if (!wsId) return null;
+ return readWorkspaceSessionListCache()[wsId]?.sessions ?? null;
+}
+
+export function writeCachedWorkspaceSessions(
+ workspaceId: string | null | undefined,
+ sessions: readonly unknown[],
+ now: number = Date.now(),
+): void {
+ const wsId = workspaceId?.trim();
+ if (!wsId) return;
+ const cache = readWorkspaceSessionListCache();
+ cache[wsId] = {
+ savedAt: now,
+ sessions: sessions.slice(0, WORKSPACE_SESSION_LIST_MAX_SESSIONS).flatMap((session) => {
+ const cached = toCachedWorkspaceSession(session);
+ return cached ? [cached] : [];
+ }),
+ };
+ writeWorkspaceSessionListCache(cache);
+}
+
export function forgetWorkspaceMemory(workspaceId: string): void {
const wsId = workspaceId?.trim();
if (!wsId) return;
+ const sessionListCache = readWorkspaceSessionListCache();
+ if (wsId in sessionListCache) {
+ delete sessionListCache[wsId];
+ writeWorkspaceSessionListCache(sessionListCache);
+ }
const map = readSessionByWorkspaceMap();
if (wsId in map) {
delete map[wsId];
diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsx
index 4d9d1d73..4d4d2e7d 100644
--- a/apps/app/src/react-app/shell/session-route.tsx
+++ b/apps/app/src/react-app/shell/session-route.tsx
@@ -481,6 +481,7 @@ export function SessionRoute() {
sessionsByWorkspaceIdRef,
errorsByWorkspaceId,
setErrorsByWorkspaceId,
+ sessionListErrorsByWorkspaceId,
workspaceConnectionOverrides,
routeError,
setRouteError,
@@ -502,6 +503,7 @@ export function SessionRoute() {
endpointForWorkspace,
refreshRouteState,
reloadWorkspaceSessions,
+ retryWorkspaceSessions,
rememberPendingCreatedSession,
handleRuntimeSessionCreated,
handleRuntimeSessionUpdated,
@@ -744,8 +746,14 @@ export function SessionRoute() {
const workspaceSessionGroups = useMemo(
- () => toSessionGroups(workspaces, sessionsByWorkspaceId, errorsByWorkspaceId, new Set(retryingWorkspaceIds)),
- [errorsByWorkspaceId, retryingWorkspaceIds, sessionsByWorkspaceId, workspaces],
+ () => toSessionGroups(
+ workspaces,
+ sessionsByWorkspaceId,
+ errorsByWorkspaceId,
+ new Set(retryingWorkspaceIds),
+ sessionListErrorsByWorkspaceId,
+ ),
+ [errorsByWorkspaceId, retryingWorkspaceIds, sessionListErrorsByWorkspaceId, sessionsByWorkspaceId, workspaces],
);
useSessionGroupSync({ workspaces, endpointForWorkspace });
const selectedWorkspaceGroupState = sessionManagementStore((state) => (
@@ -3581,6 +3589,7 @@ export function SessionRoute() {
onRevealWorkspace: (id) => void handleRevealWorkspace(id),
onRecoverWorkspace: (workspaceId) => runRemoteWorkspaceConnectionCheck(workspaceId, "recover"),
onTestWorkspaceConnection: (workspaceId) => runRemoteWorkspaceConnectionCheck(workspaceId, "test"),
+ onRetryWorkspaceTasks: retryWorkspaceSessions,
onEditWorkspaceConnection: remoteWorkspaceConnectionEditor.open,
onForgetWorkspace: (id) => void handleForgetWorkspace(id),
onOpenCreateWorkspace: handleOpenCreateWorkspace,
diff --git a/apps/app/src/react-app/shell/use-workspace-route-state.ts b/apps/app/src/react-app/shell/use-workspace-route-state.ts
index 4da2c6f9..008c2983 100644
--- a/apps/app/src/react-app/shell/use-workspace-route-state.ts
+++ b/apps/app/src/react-app/shell/use-workspace-route-state.ts
@@ -61,8 +61,11 @@ import {
classifyRouteSessionReadError,
describeRouteError,
listRouteSessions,
+ loadRouteSessionWithRetry,
mapDesktopWorkspace,
refreshRouteWorkspaceListState,
+ sessionListRecoveryDelayMs,
+ sessionsAfterListFailure,
stabilizeRouteWorkspaceOrder,
type RouteSession,
type RouteWorkspace,
@@ -70,8 +73,10 @@ import {
} from "./route-workspaces";
import {
readActiveWorkspaceId,
+ readCachedWorkspaceSessions,
readWorkspaceOrderIds,
writeActiveWorkspaceId,
+ writeCachedWorkspaceSessions,
writeWorkspaceOrderIds,
} from "./session-memory";
import {
@@ -195,6 +200,9 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
const [workspaceOrderIds, setWorkspaceOrderIds] = useState<string[]>(() => readWorkspaceOrderIds());
const [sessionsByWorkspaceId, setSessionsByWorkspaceId] = useState<Record<string, RouteSession[]>>({});
const [errorsByWorkspaceId, setErrorsByWorkspaceId] = useState<Record<string, string | null>>({});
+ // Session-list load failures, kept apart from errorsByWorkspaceId: a list
+ // that failed to load must not disable the workspace's composer or client.
+ const [sessionListErrorsByWorkspaceId, setSessionListErrorsByWorkspaceId] = useState<Record<string, string | null>>({});
const [workspaceConnectionOverrides, setWorkspaceConnectionOverrides] = useState<Record<string, WorkspaceConnectionState>>({});
const [routeError, setRouteError] = useState<string | null>(null);
// True while the desktop local server has not (re)published a usable base
@@ -247,6 +255,10 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
const reconnectAttemptedWorkspaceIdRef = useRef("");
const backgroundSessionLoadCoalescerRef = useRef(createRouteWorkspaceLoadCoalescer());
const loadedWorkspaceIdsRef = useRef(new Set<string>());
+ // Per-workspace automatic reload after a session list failed to load.
+ const sessionListRecoveryRef = useRef<Record<string, { timer: number | null; round: number }>>({});
+ // Workspaces whose sidebar list came from a successful load in this window.
+ const listedWorkspaceIdsRef = useRef(new Set<string>());
const serverActiveWorkspaceIdRef = useRef("");
const workspaceSelectionCommitTimerRef = useRef<number | null>(null);
const commitStableWorkspaceOrder = useCallback((nextWorkspaces: RouteWorkspace[]) => {
@@ -315,11 +327,51 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
hydratedSessionId,
);
}, []);
+ const clearSessionListRecovery = useCallback((workspaceId: string) => {
+ const entry = sessionListRecoveryRef.current[workspaceId];
+ if (!entry) return;
+ if (entry.timer !== null) window.clearTimeout(entry.timer);
+ delete sessionListRecoveryRef.current[workspaceId];
+ }, []);
+ // A list that failed to load keeps the sessions the sidebar already shows;
+ // with none, it falls back to the last list saved for this workspace.
+ const keepKnownSessionsAfterListFailure = useCallback((workspaceId: string) => {
+ const current = sessionsByWorkspaceIdRef.current;
+ const currentItems = current[workspaceId] ?? [];
+ const currentIsListed = listedWorkspaceIdsRef.current.has(workspaceId);
+ if (currentIsListed && currentItems.length > 0) return;
+ const sessions = sessionsAfterListFailure({
+ current: currentItems,
+ cached: readCachedWorkspaceSessions(workspaceId) as RouteSession[] | null,
+ currentIsListed,
+ });
+ if (sessions.length === currentItems.length) return;
+ const next = { ...current, [workspaceId]: sessions };
+ sessionsByWorkspaceIdRef.current = next;
+ setSessionsByWorkspaceId(next);
+ }, []);
const loadWorkspaceSessionsInBackground = useCallback(
async (workspaces: RouteWorkspace[]) => {
const MAX_ATTEMPTS = 6;
const backoffMs = (attempt: number) => Math.min(500 * Math.pow(2, attempt), 4_000);
+ const scheduleRecovery = (workspaceId: string) => {
+ const entry = sessionListRecoveryRef.current[workspaceId] ?? { timer: null, round: 0 };
+ sessionListRecoveryRef.current[workspaceId] = entry;
+ if (entry.timer !== null) return;
+ const delayMs = sessionListRecoveryDelayMs(entry.round);
+ entry.round += 1;
+ entry.timer = window.setTimeout(() => {
+ entry.timer = null;
+ const workspace = workspacesRef.current.find((item) => item.id === workspaceId);
+ if (!workspace) {
+ delete sessionListRecoveryRef.current[workspaceId];
+ return;
+ }
+ void backgroundSessionLoadCoalescerRef.current.run(workspaceId, () => fetchWithRetries(workspace, 0));
+ }, delayMs);
+ };
+
const fetchWithRetries = async (workspace: RouteWorkspace, attempt: number): Promise<void> => {
const isRemoteOmniRushWorkspace = workspace.workspaceType === "remote" && workspace.remoteType !== "opencode";
const endpoint = endpointForWorkspace(workspace);
@@ -338,6 +390,9 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
setRetryingWorkspaceIds((current) =>
current.includes(workspace.id) ? current.filter((id) => id !== workspace.id) : current,
);
+ } else if (sessionListRecoveryRef.current[workspace.id]) {
+ // The built-in server is between restarts; keep the reload alive.
+ scheduleRecovery(workspace.id);
}
return;
}
@@ -368,6 +423,15 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
sessionsByWorkspaceIdRef.current = next;
setSessionsByWorkspaceId(next);
loadedWorkspaceIdsRef.current.add(workspace.id);
+ listedWorkspaceIdsRef.current.add(workspace.id);
+ if (workspace.workspaceType !== "remote") writeCachedWorkspaceSessions(workspace.id, nextItems);
+ clearSessionListRecovery(workspace.id);
+ setSessionListErrorsByWorkspaceId((current) => {
+ if (!current[workspace.id]) return current;
+ const next = { ...current };
+ delete next[workspace.id];
+ return next;
+ });
setErrorsByWorkspaceId((current) => ({ ...current, [workspace.id]: null }));
setWorkspaceConnectionOverrides((current) => {
if (isRemoteOmniRushWorkspace) {
@@ -412,6 +476,7 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
// in the meantime instead of flashing "error" next to the
// workspace name.
if (attempt + 1 < MAX_ATTEMPTS && classifyRouteSessionReadError(error) === "retryable") {
+ if (workspace.workspaceType !== "remote") keepKnownSessionsAfterListFailure(workspace.id);
await new Promise((r) => window.setTimeout(r, backoffMs(attempt)));
await fetchWithRetries(workspace, attempt + 1);
return;
@@ -430,6 +495,19 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
[workspace.id]: connectionState,
};
});
+ } else {
+ // Never let a failed list read as "No tasks yet": keep the known
+ // sessions, flag the group, and reload it again later. A later
+ // route refresh (reconnect, restart) also reloads it because it
+ // no longer counts as loaded.
+ console.warn("[session-route] session list failed to load", { workspaceId: workspace.id, message });
+ recordInspectorEvent("route.session_list.error", { workspaceId: workspace.id, message });
+ keepKnownSessionsAfterListFailure(workspace.id);
+ loadedWorkspaceIdsRef.current.delete(workspace.id);
+ setSessionListErrorsByWorkspaceId((current) =>
+ current[workspace.id] === message ? current : { ...current, [workspace.id]: message },
+ );
+ scheduleRecovery(workspace.id);
}
setRetryingWorkspaceIds((current) =>
current.includes(workspace.id) ? current.filter((id) => id !== workspace.id) : current,
@@ -444,7 +522,7 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
),
);
},
- [endpointForWorkspace, mergeFetchedSessionsWithPending],
+ [clearSessionListRecovery, endpointForWorkspace, keepKnownSessionsAfterListFailure, mergeFetchedSessionsWithPending],
);
const reloadWorkspaceSessions = useCallback(async (workspaceId: string): Promise<void> => {
const workspace = workspacesRef.current.find((item) => item.id === workspaceId);
@@ -452,6 +530,18 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
loadedWorkspaceIdsRef.current.delete(workspaceId);
await loadWorkspaceSessionsInBackground([workspace]);
}, [loadWorkspaceSessionsInBackground]);
+ /** The sidebar's "Retry" on a workspace whose task list could not be loaded. */
+ const retryWorkspaceSessions = useCallback((workspaceId: string) => {
+ clearSessionListRecovery(workspaceId);
+ setRetryingWorkspaceIds((current) => current.includes(workspaceId) ? current : [...current, workspaceId]);
+ void reloadWorkspaceSessions(workspaceId);
+ }, [clearSessionListRecovery, reloadWorkspaceSessions]);
+ useEffect(() => () => {
+ for (const entry of Object.values(sessionListRecoveryRef.current)) {
+ if (entry.timer !== null) window.clearTimeout(entry.timer);
+ }
+ sessionListRecoveryRef.current = {};
+ }, []);
const workspaceSelectionCommitRef = useRef<(workspaceId: string) => Promise<void>>(async () => undefined);
workspaceSelectionCommitRef.current = async (workspaceId) => {
await commitRouteWorkspaceSelection({
@@ -1111,55 +1201,46 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
setModernRouteSessionResolution({ key: modernRouteSessionLoadKey, status: "loading" });
const hydrateSelectedSession = async () => {
- const maxAttempts = 6;
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
- if (cancelled) return;
- try {
- const session = engineV2ChatRouting
- ? unwrap(await createClientV2(opencode2BaseUrl, selectedWorkspaceRoot || undefined, {
- token: selectedWorkspaceServerToken,
- }).session.get({ sessionID: selectedSessionId }))
- : await getNativeSession(selectedWorkspaceEndpoint, selectedSessionId);
- if (cancelled) return;
- if (session.id !== selectedSessionId) {
- setModernRouteSessionResolution({
- key: modernRouteSessionLoadKey,
- status: "error",
- message: "The server returned a different session.",
- });
- return;
- }
- setSessionsByWorkspaceId((current) => {
- const currentItems = current[selectedWorkspaceId] ?? [];
- if (currentItems.some((session) => session.id === selectedSessionId)) {
- delete hydratedRouteSessionIdsRef.current[selectedWorkspaceId];
- return current;
- }
- hydratedRouteSessionIdsRef.current[selectedWorkspaceId] = selectedSessionId;
- const nextItems = mergeWorkspaceRouteSession(currentItems, session);
- const next = { ...current, [selectedWorkspaceId]: nextItems };
- sessionsByWorkspaceIdRef.current = next;
- return next;
- });
- setErrorsByWorkspaceId((current) => ({ ...current, [selectedWorkspaceId]: null }));
- setModernRouteSessionResolution(null);
- return;
- } catch (error) {
- if (cancelled) return;
- const message = error instanceof Error ? error.message : describeRouteError(error);
- const kind = classifyRouteSessionReadError(error);
- if (kind !== "retryable" || attempt + 1 >= maxAttempts) {
- setModernRouteSessionResolution({
- key: modernRouteSessionLoadKey,
- status: kind === "not-found" ? "not-found" : "error",
- message,
- });
- return;
- }
- await new Promise((resolve) => window.setTimeout(resolve, Math.min(500 * Math.pow(2, attempt), 4_000)));
- if (cancelled) return;
- }
+ const outcome = await loadRouteSessionWithRetry({
+ isCancelled: () => cancelled,
+ load: async () => engineV2ChatRouting
+ ? unwrap(await createClientV2(opencode2BaseUrl, selectedWorkspaceRoot || undefined, {
+ token: selectedWorkspaceServerToken,
+ }).session.get({ sessionID: selectedSessionId }))
+ : await getNativeSession(selectedWorkspaceEndpoint, selectedSessionId),
+ });
+ if (cancelled || outcome.status === "cancelled") return;
+ if (outcome.status !== "loaded") {
+ setModernRouteSessionResolution({
+ key: modernRouteSessionLoadKey,
+ status: outcome.status,
+ message: outcome.message,
+ });
+ return;
+ }
+ const session = outcome.value;
+ if (session.id !== selectedSessionId) {
+ setModernRouteSessionResolution({
+ key: modernRouteSessionLoadKey,
+ status: "error",
+ message: "The server returned a different session.",
+ });
+ return;
}
+ setSessionsByWorkspaceId((current) => {
+ const currentItems = current[selectedWorkspaceId] ?? [];
+ if (currentItems.some((session) => session.id === selectedSessionId)) {
+ delete hydratedRouteSessionIdsRef.current[selectedWorkspaceId];
+ return current;
+ }
+ hydratedRouteSessionIdsRef.current[selectedWorkspaceId] = selectedSessionId;
+ const nextItems = mergeWorkspaceRouteSession(currentItems, session);
+ const next = { ...current, [selectedWorkspaceId]: nextItems };
+ sessionsByWorkspaceIdRef.current = next;
+ return next;
+ });
+ setErrorsByWorkspaceId((current) => ({ ...current, [selectedWorkspaceId]: null }));
+ setModernRouteSessionResolution(null);
};
void hydrateSelectedSession();
@@ -1282,6 +1363,7 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
sessionsByWorkspaceIdRef,
errorsByWorkspaceId,
setErrorsByWorkspaceId,
+ sessionListErrorsByWorkspaceId,
workspaceConnectionOverrides,
routeError,
setRouteError,
@@ -1303,6 +1385,7 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
endpointForWorkspace,
refreshRouteState,
reloadWorkspaceSessions,
+ retryWorkspaceSessions,
loadWorkspaceSessionsInBackground,
rememberPendingCreatedSession,
handleRuntimeSessionCreated,
diff --git a/apps/app/tests/session-read-transport-failure.test.ts b/apps/app/tests/session-read-transport-failure.test.ts
new file mode 100644
index 00000000..117ff4fe
--- /dev/null
+++ b/apps/app/tests/session-read-transport-failure.test.ts
@@ -0,0 +1,378 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import type { Session, SessionStatus } from "@opencode-ai/sdk/v2/client";
+
+import { resolveRequestTimeoutMs, SESSION_READ_REQUEST_TIMEOUT_MS, type FieldsResult } from "../src/app/lib/opencode";
+import {
+ composeNativeSessionSnapshot,
+ deleteNativeSession,
+ getNativeSession,
+ unwrapNativeSessionResult,
+ type NativeSessionOperations,
+} from "../src/app/lib/opencode-session-native";
+import { resolveWorkspaceEndpoint } from "../src/app/lib/workspace-endpoint";
+import {
+ classifyRouteSessionReadError,
+ listRouteSessions,
+ loadRouteSessionWithRetry,
+ readRouteSessionsWithRetry,
+ ROUTE_SESSION_RETRY_DELAYS_MS,
+ sessionListRecoveryDelayMs,
+ sessionsAfterListFailure,
+ toSessionGroups,
+ type RouteSession,
+ type RouteSessionListTransport,
+ type RouteWorkspace,
+} from "../src/react-app/shell/route-workspaces";
+import {
+ forgetWorkspaceMemory,
+ readCachedWorkspaceSessions,
+ writeCachedWorkspaceSessions,
+} from "../src/react-app/shell/session-memory";
+import { isWorkspaceTaskListUnavailable } from "../src/react-app/domains/session/sidebar/utils";
+
+const nativeEndpoint = {
+ opencodeBaseUrl: "http://127.0.0.1:4096/workspace/ws_local/opencode",
+ token: "local-token",
+};
+
+const session = {
+ id: "ses_1",
+ slug: "one",
+ projectID: "project",
+ directory: "/work/taskforge",
+ title: "Build the parser",
+ version: "1",
+ time: { created: 1, updated: 2 },
+} as Session;
+
+/** The SDK's result when fetch itself rejected: no HTTP response at all. */
+function transportFailure(error: unknown): FieldsResult<never> {
+ return { error, request: new Request(nativeEndpoint.opencodeBaseUrl), response: undefined };
+}
+
+function httpFailure(error: unknown, status: number): FieldsResult<never> {
+ return { error, request: new Request(nativeEndpoint.opencodeBaseUrl), response: new Response(null, { status }) };
+}
+
+function ok<T>(data: T): FieldsResult<T> {
+ return { data, request: new Request(nativeEndpoint.opencodeBaseUrl), response: new Response(null, { status: 200 }) };
+}
+
+function operations(overrides: Partial<NativeSessionOperations> = {}): NativeSessionOperations {
+ return {
+ get: async () => ok(session),
+ messages: async () => ok([]),
+ todo: async () => ok([]),
+ status: async () => ok<Record<string, SessionStatus>>({}),
+ delete: async () => ok(true),
+ ...overrides,
+ };
+}
+
+describe("native session reads without an HTTP response", () => {
+ test("a refused connection keeps the original error and stays retryable", async () => {
+ const refused = new TypeError("Failed to fetch");
+ const read = getNativeSession(nativeEndpoint, session.id, undefined, {
+ createOperations: () => operations({ get: async () => transportFailure(refused) }),
+ });
+ const error = await read.catch((caught: unknown) => caught);
+ expect(error).toBe(refused);
+ expect(classifyRouteSessionReadError(error)).toBe("retryable");
+ });
+
+ test("a transport timeout keeps the original error and stays retryable", async () => {
+ const timedOut = new Error("Request timed out.");
+ const error = await getNativeSession(nativeEndpoint, session.id, undefined, {
+ createOperations: () => operations({ get: async () => transportFailure(timedOut) }),
+ }).catch((caught: unknown) => caught);
+ expect(error).toBe(timedOut);
+ expect(classifyRouteSessionReadError(error)).toBe("retryable");
+ });
+
+ test("a 404 is still tagged as a missing session", async () => {
+ const error = await getNativeSession(nativeEndpoint, session.id, undefined, {
+ createOperations: () => operations({ get: async () => httpFailure({ name: "NotFoundError" }, 404) }),
+ }).catch((caught: unknown) => caught);
+ expect(error).toMatchObject({ status: 404, code: "session_not_found" });
+ expect(classifyRouteSessionReadError(error)).toBe("not-found");
+ });
+
+ test("a non-Error failure without a response never throws a TypeError", () => {
+ let caught: unknown;
+ try {
+ unwrapNativeSessionResult(transportFailure({ message: "engine gone" }));
+ } catch (error) {
+ caught = error;
+ }
+ expect(caught).toBeInstanceOf(Error);
+ expect(caught).not.toBeInstanceOf(TypeError);
+ expect((caught as Error).message).toBe(JSON.stringify({ message: "engine gone" }));
+ expect(caught).not.toHaveProperty("status");
+ });
+
+ test("snapshot and delete surface the transport error, not a TypeError", async () => {
+ const refused = new TypeError("Failed to fetch");
+ await expect(composeNativeSessionSnapshot(nativeEndpoint, session.id, undefined, {
+ createOperations: () => operations({ status: async () => transportFailure(refused) }),
+ })).rejects.toBe(refused);
+ await expect(deleteNativeSession(nativeEndpoint, session.id, undefined, {
+ createOperations: () => operations({ delete: async () => transportFailure(refused) }),
+ })).rejects.toBe(refused);
+ });
+});
+
+describe("sidebar session list without an HTTP response", () => {
+ const endpoint = resolveWorkspaceEndpoint({ id: "ws_7a33db60cd66", workspaceType: "local" }, {
+ baseUrl: "http://127.0.0.1:4096",
+ token: "local-token",
+ });
+ if (!endpoint) throw new Error("Expected a local endpoint");
+
+ const failingTransport = (error: unknown): RouteSessionListTransport => async () => ({
+ error,
+ request: new Request(`${endpoint.opencodeBaseUrl}/session?limit=200`),
+ response: undefined,
+ });
+
+ test("refused and timed-out list calls reject with the original, retryable error", async () => {
+ for (const original of [new TypeError("Failed to fetch"), new Error("Request timed out.")]) {
+ const error = await listRouteSessions(endpoint, failingTransport(original)).catch((caught: unknown) => caught);
+ expect(error).toBe(original);
+ expect(classifyRouteSessionReadError(error)).toBe("retryable");
+ }
+ });
+
+ test("an HTTP failure keeps its status and code", async () => {
+ const error = await listRouteSessions(endpoint, async () => ({
+ error: { code: "opencode_engine_unreachable", message: "engine starting" },
+ request: new Request(`${endpoint.opencodeBaseUrl}/session?limit=200`),
+ response: new Response(null, { status: 503 }),
+ })).catch((caught: unknown) => caught);
+ expect(error).toMatchObject({ status: 503, code: "opencode_engine_unreachable" });
+ expect(classifyRouteSessionReadError(error)).toBe("retryable");
+
+ const notFound = await listRouteSessions(endpoint, async () => ({
+ error: { name: "NotFoundError" },
+ request: new Request(`${endpoint.opencodeBaseUrl}/session?limit=200`),
+ response: new Response(null, { status: 404 }),
+ })).catch((caught: unknown) => caught);
+ expect(notFound).toMatchObject({ status: 404 });
+ });
+
+ test("the retry loop recovers after the built-in server comes back", async () => {
+ let calls = 0;
+ const waits: number[] = [];
+ const sessions = await readRouteSessionsWithRetry({
+ load: () => listRouteSessions(endpoint, async (input) => {
+ calls += 1;
+ if (calls < 3) {
+ return {
+ error: new TypeError("Failed to fetch"),
+ request: new Request(`${input.endpoint.opencodeBaseUrl}/session?limit=200`),
+ response: undefined,
+ };
+ }
+ return {
+ data: [session as RouteSession],
+ request: new Request(`${input.endpoint.opencodeBaseUrl}/session?limit=200`),
+ response: Response.json([session]),
+ };
+ }),
+ retryDelaysMs: [250, 750, 1_500],
+ wait: async (delayMs) => { waits.push(delayMs); },
+ });
+ expect(sessions.map((item) => item.id)).toEqual([session.id]);
+ expect(waits).toEqual([250, 750]);
+ });
+});
+
+describe("routed session hydration", () => {
+ test("transient failures keep retrying past the old six-attempt limit", async () => {
+ let calls = 0;
+ const waits: number[] = [];
+ const outcome = await loadRouteSessionWithRetry({
+ isCancelled: () => false,
+ wait: async (delayMs) => { waits.push(delayMs); },
+ load: () => {
+ calls += 1;
+ return getNativeSession(nativeEndpoint, session.id, undefined, {
+ createOperations: () => operations({
+ get: async () => calls <= 8
+ ? transportFailure(calls % 2 ? new TypeError("Failed to fetch") : new Error("Request timed out."))
+ : ok(session),
+ }),
+ });
+ },
+ });
+ expect(outcome).toEqual({ status: "loaded", value: session });
+ expect(calls).toBe(9);
+ const last = ROUTE_SESSION_RETRY_DELAYS_MS[ROUTE_SESSION_RETRY_DELAYS_MS.length - 1];
+ expect(waits).toEqual([...ROUTE_SESSION_RETRY_DELAYS_MS, last, last]);
+ });
+
+ test("a missing session resolves at once as not found", async () => {
+ const waits: number[] = [];
+ const outcome = await loadRouteSessionWithRetry({
+ isCancelled: () => false,
+ wait: async (delayMs) => { waits.push(delayMs); },
+ load: () => getNativeSession(nativeEndpoint, session.id, undefined, {
+ createOperations: () => operations({ get: async () => httpFailure({ name: "NotFoundError" }, 404) }),
+ }),
+ });
+ expect(outcome.status).toBe("not-found");
+ expect(waits).toEqual([]);
+ });
+
+ test("a terminal error resolves at once with its message", async () => {
+ const outcome = await loadRouteSessionWithRetry({
+ isCancelled: () => false,
+ wait: async () => { throw new Error("must not wait"); },
+ load: () => getNativeSession(nativeEndpoint, session.id, undefined, {
+ createOperations: () => operations({ get: async () => httpFailure("Unauthorized", 401) }),
+ }),
+ });
+ expect(outcome).toMatchObject({ status: "error", message: "Unauthorized" });
+ });
+
+ test("stops when the route no longer wants the session", async () => {
+ let cancelled = false;
+ let calls = 0;
+ const outcome = await loadRouteSessionWithRetry({
+ isCancelled: () => cancelled,
+ wait: async () => { cancelled = true; },
+ load: async () => {
+ calls += 1;
+ throw new TypeError("Failed to fetch");
+ },
+ });
+ expect(outcome).toEqual({ status: "cancelled" });
+ expect(calls).toBe(1);
+ });
+
+ test("an explicit attempt bound still ends in an error", async () => {
+ const outcome = await loadRouteSessionWithRetry({
+ isCancelled: () => false,
+ maxAttempts: 2,
+ wait: async () => undefined,
+ load: async () => { throw new Error("Request timed out."); },
+ });
+ expect(outcome).toMatchObject({ status: "error", message: "Request timed out." });
+ });
+});
+
+describe("session read timeouts", () => {
+ const base = "http://127.0.0.1:4096/workspace/ws_1/opencode";
+
+ test("session list and get reads get the longer bounded budget", () => {
+ expect(SESSION_READ_REQUEST_TIMEOUT_MS).toBeGreaterThan(10_000);
+ expect(SESSION_READ_REQUEST_TIMEOUT_MS).toBeLessThanOrEqual(60_000);
+ expect(resolveRequestTimeoutMs(new Request(`${base}/session?limit=200`), 10_000)).toBe(SESSION_READ_REQUEST_TIMEOUT_MS);
+ expect(resolveRequestTimeoutMs(new Request(`${base}/session/ses_1`), 10_000)).toBe(SESSION_READ_REQUEST_TIMEOUT_MS);
+ expect(resolveRequestTimeoutMs(`${base}/session`, 10_000)).toBe(SESSION_READ_REQUEST_TIMEOUT_MS);
+ expect(resolveRequestTimeoutMs(new Request("http://127.0.0.1:4096/workspace/ws_1/opencode2/api/session"), 10_000))
+ .toBe(SESSION_READ_REQUEST_TIMEOUT_MS);
+ });
+
+ test("status polls, writes, message reads and streams keep their own budgets", () => {
+ expect(resolveRequestTimeoutMs(new Request(`${base}/session/status`), 10_000)).toBe(10_000);
+ expect(resolveRequestTimeoutMs(new Request(`${base}/session/ses_1/message?limit=140`), 10_000)).toBe(10_000);
+ expect(resolveRequestTimeoutMs(new Request(`${base}/session`, { method: "POST" }), 10_000)).toBe(10_000);
+ expect(resolveRequestTimeoutMs(`${base}/session/ses_1`, 10_000, { method: "DELETE" })).toBe(10_000);
+ expect(resolveRequestTimeoutMs(new Request(`${base}/session`), 0)).toBe(0);
+ });
+});
+
+describe("failed session lists in the sidebar", () => {
+ const workspace = { id: "ws_taskforge", displayNameResolved: "taskforge" } as RouteWorkspace;
+ const cached = [{ id: "ses_a" }, { id: "ses_b" }];
+
+ test("a failed load keeps a listed workspace's sessions", () => {
+ expect(sessionsAfterListFailure({ current: [{ id: "ses_a" }], cached, currentIsListed: true }))
+ .toEqual([{ id: "ses_a" }]);
+ });
+
+ test("an unlisted workspace falls back to the saved list, keeping sessions already present", () => {
+ expect(sessionsAfterListFailure({ current: undefined, cached, currentIsListed: false })).toEqual(cached);
+ expect(sessionsAfterListFailure({ current: [{ id: "ses_new" }, { id: "ses_b" }], cached, currentIsListed: false }))
+ .toEqual([{ id: "ses_new" }, { id: "ses_b" }, { id: "ses_a" }]);
+ expect(sessionsAfterListFailure({ current: [], cached: null, currentIsListed: true })).toEqual([]);
+ });
+
+ test("a failed empty group shows the retry row, never 'No tasks yet'", () => {
+ const [failed] = toSessionGroups([workspace], {}, {}, new Set(), { [workspace.id]: "Request timed out." });
+ expect(failed).toMatchObject({ status: "ready", sessions: [], listError: "Request timed out." });
+ expect(isWorkspaceTaskListUnavailable(failed!)).toBe(true);
+
+ const [loading] = toSessionGroups([workspace], {}, {}, new Set([workspace.id]), { [workspace.id]: "Failed to fetch" });
+ expect(isWorkspaceTaskListUnavailable(loading!)).toBe(false);
+
+ const [empty] = toSessionGroups([workspace], {}, {}, new Set());
+ expect(empty?.listError).toBeNull();
+ expect(isWorkspaceTaskListUnavailable(empty!)).toBe(false);
+ });
+
+ test("automatic reloads back off and keep going at the last delay", () => {
+ const delays = [0, 1, 2, 3, 4, 5, 50].map(sessionListRecoveryDelayMs);
+ expect(delays).toEqual([5_000, 10_000, 20_000, 30_000, 60_000, 60_000, 60_000]);
+ });
+});
+
+describe("saved session lists", () => {
+ const originalWindow = globalThis.window;
+
+ function installStorage() {
+ const values = new Map<string, string>();
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {
+ localStorage: {
+ getItem: (key: string) => values.get(key) ?? null,
+ setItem: (key: string, value: string) => { values.set(key, value); },
+ removeItem: (key: string) => { values.delete(key); },
+ },
+ },
+ });
+ return values;
+ }
+
+ afterEach(() => {
+ Object.defineProperty(globalThis, "window", { configurable: true, value: originalWindow });
+ });
+
+ test("survive a restart with only the sidebar fields", () => {
+ const values = installStorage();
+ writeCachedWorkspaceSessions("ws_taskforge", [
+ {
+ ...session,
+ parentID: "ses_parent",
+ time: { created: 1, updated: 2, archived: 3 },
+ summary: { additions: 1, deletions: 0, files: 1, diffs: [{ file: "a.ts", before: "x", after: "y" }] },
+ permission: [{ permission: "edit", pattern: "*", action: "allow" }],
+ },
+ { title: "no id" },
+ ], 100);
+ const stored = [...values.values()].join("");
+ expect(stored).not.toContain("diffs");
+ expect(stored).not.toContain("permission");
+ expect(readCachedWorkspaceSessions("ws_taskforge")).toEqual([{
+ id: "ses_1",
+ slug: "one",
+ projectID: "project",
+ directory: "/work/taskforge",
+ parentID: "ses_parent",
+ title: "Build the parser",
+ version: "1",
+ time: { created: 1, updated: 2, archived: 3 },
+ }]);
+ expect(readCachedWorkspaceSessions("ws_other")).toBeNull();
+ });
+
+ test("are dropped when the workspace is forgotten and tolerate bad storage", () => {
+ const values = installStorage();
+ writeCachedWorkspaceSessions("ws_taskforge", [session]);
+ forgetWorkspaceMemory("ws_taskforge");
+ expect(readCachedWorkspaceSessions("ws_taskforge")).toBeNull();
+ values.set("omnirush.react.workspaceSessionList", "{not json");
+ expect(readCachedWorkspaceSessions("ws_taskforge")).toBeNull();
+ });
+});