A desktop coding agent with free access to frontier models.
TypeScript
fix: recover from chats the engine no longer has
ogsamrat4f2b71c55197
diff --git a/apps/app/src/app/lib/opencode-session-native.ts b/apps/app/src/app/lib/opencode-session-native.tsindex 0f9d6bb9..d7668b9f 100644--- a/apps/app/src/app/lib/opencode-session-native.ts+++ b/apps/app/src/app/lib/opencode-session-native.ts@@ -96,11 +96,38 @@ export function unwrapNativeSessionResult<T>(result: FieldsResult<T>, notFoundCo? notFoundCode: undefined;if (code) Object.assign(error, { code });+ if (status === 404 && isMissingSessionBody(result.error)) Object.assign(error, { sessionMissing: true });}throw error;}}+/**+ * A 404 body that names the session itself as missing: the local server's+ * `session_not_found` (its ownership check reads the session from the engine+ * first) or the engine's own NotFoundError ("Session not found: ses_…").+ * A bare 404 (an unknown route, a proxy page) is not proof the chat is gone.+ */+function isMissingSessionBody(body: unknown): boolean {+ if (!body || typeof body !== "object") return false;+ const record = body as Record<string, unknown>;+ if (record.code === "session_not_found") return true;+ if (record.name !== "NotFoundError") return false;+ const data = record.data && typeof record.data === "object" ? record.data as Record<string, unknown> : null;+ return typeof data?.message === "string" && /^Session not found\b/i.test(data.message);+}++/**+ * True only when the engine confirmed the session does not exist. Callers use+ * it to drop a stale chat from the sidebar, tabs and saved lists, so transport+ * failures, restarts and other 404s must never match.+ */+export function isMissingSessionError(error: unknown): boolean {+ return error instanceof Error+ && "sessionMissing" in error+ && error.sessionMissing === true;+}+const unwrapSessionResult = unwrapNativeSessionResult;export async function getNativeSession(diff --git a/apps/app/src/i18n/locales/en.ts b/apps/app/src/i18n/locales/en.tsindex ce5df783..15dee666 100644--- a/apps/app/src/i18n/locales/en.ts+++ b/apps/app/src/i18n/locales/en.ts@@ -1246,6 +1246,9 @@ export default {"session.resume_interrupted": "Resume","session.admission_outcome_unknown": "The task was accepted, but no result arrived","session.stop_failed": "Could not stop the run — the engine reported no active run was aborted. Try again.",+ "session.missing_chat_title": "That chat is no longer available",+ "session.missing_chat_description": "It was deleted, or it was not carried over to the current engine. It has been removed from the sidebar.",+ "session.missing_chat_inline": "This chat is no longer available.","session.revert_failed": "Could not revert the conversation. Try again once the current run finishes.","session.branch_failed": "Could not branch this conversation. Try again.","session.default_title": "New session",diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsxindex a90ac356..ae68150f 100644--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx@@ -643,6 +643,8 @@ export type SessionSurfaceProps = {onForkAtMessage?: (messageId: string | null, sessionId: string) => void;/** Open a sub-agent (child) session in the main chat surface. */onOpenSubagentSession?: (sessionId: string) => void;+ /** The engine confirmed this chat does not exist; the shell forgets it and moves on. */+ onSessionMissing?: (workspaceId: string, sessionId: string) => void;onOpenTarget?: (target: OpenTarget, options?: OpenTargetOptions, sessionId?: string) => void;environmentRuntimeKey?: string | null;onApplyEnvironmentChanges?: () => Promise<ApplyEnvironmentChangesResult>;@@ -1292,6 +1294,33 @@ export function SessionSurface(props: SessionSurfaceProps) {});const currentSnapshot = snapshotQuery.data?.session.id === props.sessionId ? snapshotQuery.data : null;+ const snapshotSessionMissing = opencodeSessionNative.isMissingSessionError(snapshotQuery.error);+ const onSessionMissingRef = useRef(props.onSessionMissing);+ onSessionMissingRef.current = props.onSessionMissing;+ // A chat the sidebar or a saved tab still lists but the engine does not+ // have. Confirm with one more read (a stale answer must not drop a real+ // chat), then let the shell forget it instead of showing a dead end.+ useEffect(() => {+ if (!snapshotSessionMissing) return;+ const { workspaceId, sessionId } = props;+ let cancelled = false;+ void opencodeSessionNative.getNativeSession(+ { opencodeBaseUrl: props.opencodeBaseUrl, token: props.omnirushToken },+ sessionId,+ ).then(+ () => {+ if (!cancelled) void snapshotQuery.refetch();+ },+ (error: unknown) => {+ if (cancelled || !opencodeSessionNative.isMissingSessionError(error)) return;+ onSessionMissingRef.current?.(workspaceId, sessionId);+ },+ );+ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [snapshotSessionMissing, props.workspaceId, props.sessionId, props.opencodeBaseUrl, props.omnirushToken]);const inspectorOpencodeBaseUrl = useMemo(() => {try {const url = new URL(props.opencodeBaseUrl);@@ -3156,7 +3185,9 @@ export function SessionSurface(props: SessionSurfaceProps) {<div className="mx-auto max-w-xl rounded-3xl border border-red-6/40 bg-red-3/20 px-6 py-5 text-sm text-red-11">{props.developerMode && snapshotQuery.error instanceof Error? snapshotQuery.error.message- : describeOpencodeSessionError(snapshotQuery.error, "Failed to load session.")}+ : snapshotSessionMissing+ ? t("session.missing_chat_inline")+ : describeOpencodeSessionError(snapshotQuery.error, "Failed to load session.")}</div>)}</div>diff --git a/apps/app/src/react-app/shell/missing-chat.ts b/apps/app/src/react-app/shell/missing-chat.tsnew file mode 100644index 00000000..cbac606f--- /dev/null+++ b/apps/app/src/react-app/shell/missing-chat.ts@@ -0,0 +1,26 @@+/**+ * A chat the engine confirmed it does not have (deleted elsewhere, never+ * carried over from an earlier engine, or saved by an older app) must leave+ * every place the app remembers it, or it keeps coming back as a dead end:+ * the saved sidebar list, the remembered chat for its workspace, and the+ * workbench tabs and side-chat pairs that outlive restarts.+ */+import { useWorkbenchStore } from "@/react-app/domains/session/chat/workbench-store";+import { forgetLastSessionFor, removeCachedWorkspaceSession } from "./session-memory";++export type MissingChatRef = { workspaceId: string; sessionId: string };++/**+ * Drops one workspace's saved references to a missing chat. Scoped to the+ * pair: the same id listed under another workspace is left alone, so a route+ * that briefly pairs a chat with the wrong workspace cannot erase it.+ */+export function forgetMissingChatMemory(ref: MissingChatRef): boolean {+ const workspaceId = ref.workspaceId.trim();+ const sessionId = ref.sessionId.trim();+ if (!workspaceId || !sessionId) return false;+ removeCachedWorkspaceSession(workspaceId, sessionId);+ forgetLastSessionFor(workspaceId, sessionId);+ useWorkbenchStore.getState().closeTab({ workspaceId, sessionId });+ return true;+}diff --git a/apps/app/src/react-app/shell/session-memory.ts b/apps/app/src/react-app/shell/session-memory.tsindex a41652b3..32764135 100644--- a/apps/app/src/react-app/shell/session-memory.ts+++ b/apps/app/src/react-app/shell/session-memory.ts@@ -112,6 +112,14 @@ export function writeLastSessionFor(workspaceId: string, sessionId: string | nulsafeSet(SESSION_BY_WORKSPACE_KEY, Object.keys(map).length ? JSON.stringify(map) : null);}+/** Forget the remembered chat for a workspace, but only while it is still `sessionId`. */+export function forgetLastSessionFor(workspaceId: string, sessionId: string): void {+ const wsId = workspaceId?.trim();+ const id = sessionId?.trim();+ if (!wsId || !id || readLastSessionFor(wsId) !== id) return;+ writeLastSessionFor(wsId, null);+}+function readWorkspaceProjectDimensionMap(): Record<string, WorkspaceProjectDimension> {const raw = safeGet(WORKSPACE_PROJECT_DIMENSION_KEY);if (!raw) return {};diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsxindex 5210d488..d1f5a3e3 100644--- a/apps/app/src/react-app/shell/session-route.tsx+++ b/apps/app/src/react-app/shell/session-route.tsx@@ -511,6 +511,7 @@ export function SessionRoute() {handleRuntimeSessionUpdated,handleRuntimeSessionDeleted,forgetDeletedSession,+ forgetMissingSession,handleRemoteWorkspaceConnectionSaved,runRemoteWorkspaceConnectionCheck,} = useWorkspaceRouteState({@@ -1585,9 +1586,11 @@ export function SessionRoute() {onApplyEnvironmentChanges: isDesktopRuntime() && selectedWorkspace?.workspaceType !== "remote"? handleApplyEnvironmentChanges: undefined,+ onSessionMissing: forgetMissingSession,};}, [client,+ forgetMissingSession,modelPicker.compactOpen,handleOpenExtensions,handleOpenSettings,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.tsindex 064ab93a..56d218c2 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@@ -24,11 +24,12 @@ import {} from "@/app/lib/desktop";import { createClient, unwrap } from "@/app/lib/opencode";import { createClientV2 } from "@/app/lib/opencode-v2-adapter";-import { getNativeSession } from "@/app/lib/opencode-session-native";+import { getNativeSession, isMissingSessionError } from "@/app/lib/opencode-session-native";import { createOmniRushServerClient, OmniRushServerError, type OmniRushServerClient } from "@/app/lib/omnirush-server";import { isDesktopRuntime } from "@/app/lib/runtime-env";import { toast } from "@/components/ui/sonner";import { showFilesUsedNoticeOnce } from "./files-used-notice";+import { forgetMissingChatMemory } from "./missing-chat";import type { ResolvedWorkspaceEndpoint } from "@/app/lib/workspace-endpoint";import type { WorkspaceConnectionState } from "@/app/types";import { normalizeDirectoryPath } from "@/app/utils";@@ -220,6 +221,10 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {const [routeRefreshVersion, setRouteRefreshVersion] = useState(0);const [legacySelectedWorkspaceId, setLegacySelectedWorkspaceId] = useState<string>(() => readActiveWorkspaceId() ?? "");const selectedWorkspaceId = routeWorkspaceId || legacySelectedWorkspaceId;+ const selectedWorkspaceIdRef = useRef(selectedWorkspaceId);+ selectedWorkspaceIdRef.current = selectedWorkspaceId;+ const selectedSessionIdRef = useRef(selectedSessionId);+ selectedSessionIdRef.current = selectedSessionId;const selectedWorkspace = useMemo(() => workspaces.find((workspace) => workspace.id === selectedWorkspaceId) ?? (selectedWorkspaceId ? null : workspaces[0] ?? null),[selectedWorkspaceId, workspaces],@@ -965,6 +970,40 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {setSessionsByWorkspaceId(lists);}, [selectedWorkspaceId]);const handleRuntimeSessionDeleted = forgetDeletedSession;+ /**+ * The engine confirmed this workspace has no such chat. Drop it from the+ * sidebar, the saved list, the remembered chat and the tabs, and move off it+ * when it is the open chat, instead of a dead-end "not found" page. Unlike a+ * delete it is not blocked from coming back: a chat still being carried+ * over from the earlier engine shows up again on a later list.+ */+ const forgetMissingSession = useCallback((workspaceId: string, sessionId: string) => {+ const wsId = workspaceId.trim();+ const id = sessionId.trim();+ if (!wsId || !id) return;+ const pending = pendingCreatedSessionIdsRef.current[wsId];+ if (pending) delete pending[id];+ if (hydratedRouteSessionIdsRef.current[wsId] === id) delete hydratedRouteSessionIdsRef.current[wsId];+ const current = sessionsByWorkspaceIdRef.current;+ const list = current[wsId] ?? [];+ const nextList = removeWorkspaceRouteSession(list, id);+ if (nextList !== list) {+ const next = { ...current, [wsId]: nextList };+ sessionsByWorkspaceIdRef.current = next;+ setSessionsByWorkspaceId(next);+ }+ forgetMissingChatMemory({ workspaceId: wsId, sessionId: id });+ recordInspectorEvent("route.session.missing", { workspaceId: wsId, sessionId: id });+ if (wsId === selectedWorkspaceIdRef.current && id === selectedSessionIdRef.current) {+ navigateToWorkspaceSession(wsId, null, { replace: true });+ }+ toast.info(t("session.missing_chat_title"), {+ id: `missing-chat:${id}`,+ description: t("session.missing_chat_description"),+ });+ }, [navigateToWorkspaceSession]);+ const forgetMissingSessionRef = useRef(forgetMissingSession);+ forgetMissingSessionRef.current = forgetMissingSession;useEffect(() => {workspacesRef.current = workspaces;@@ -1323,6 +1362,11 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {: await getNativeSession(selectedWorkspaceEndpoint, selectedSessionId),});if (cancelled || outcome.status === "cancelled") return;+ if (outcome.status === "not-found" && isMissingSessionError(outcome.error)) {+ setModernRouteSessionResolution(null);+ forgetMissingSessionRef.current(selectedWorkspaceId, selectedSessionId);+ return;+ }if (outcome.status !== "loaded") {setModernRouteSessionResolution({key: modernRouteSessionLoadKey,@@ -1505,6 +1549,7 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {handleRuntimeSessionUpdated,handleRuntimeSessionDeleted,forgetDeletedSession,+ forgetMissingSession,handleRemoteWorkspaceConnectionSaved,runRemoteWorkspaceConnectionCheck,};diff --git a/apps/app/tests/composer-clears-after-send.test.tsx b/apps/app/tests/composer-clears-after-send.test.tsxindex f2406094..4eb8c773 100644--- a/apps/app/tests/composer-clears-after-send.test.tsx+++ b/apps/app/tests/composer-clears-after-send.test.tsx@@ -96,6 +96,7 @@ test("a new-session send clears the handed-off text and attachment chips, later}));mock.module("@/app/lib/opencode-session-native", () => ({composeNativeSessionSnapshot: async () => createSnapshot(sessionId),+ isMissingSessionError: () => false,}));const { SessionSurface } = await import("../src/react-app/domains/session/surface/session-surface");const { snapshotKey } = await import("../src/react-app/domains/session/sync/session-sync");diff --git a/apps/app/tests/composer-editable-on-snapshot-error.test.tsx b/apps/app/tests/composer-editable-on-snapshot-error.test.tsxindex 2bcc8b07..b45f76f1 100644--- a/apps/app/tests/composer-editable-on-snapshot-error.test.tsx+++ b/apps/app/tests/composer-editable-on-snapshot-error.test.tsx@@ -118,6 +118,7 @@ test("the composer stays editable when snapshot refresh fails or the model is unif (rejectSnapshot) throw new Error("snapshot refresh failed");return fetchedSnapshot;},+ isMissingSessionError: () => false,}));const { SessionSurface } = await import("../src/react-app/domains/session/surface/session-surface");const { snapshotKey } = await import("../src/react-app/domains/session/sync/session-sync");diff --git a/apps/app/tests/composer-focus-continuity.test.tsx b/apps/app/tests/composer-focus-continuity.test.tsxindex 0539d518..f7b68bc2 100644--- a/apps/app/tests/composer-focus-continuity.test.tsx+++ b/apps/app/tests/composer-focus-continuity.test.tsx@@ -138,6 +138,7 @@ test("composer focus and optimistic sends preserve drafts through snapshots andmock.module("@/react-app/domains/session/surface/composer/subagent-model-menu", () => ({ SubagentModelMenu: () => null }));mock.module("@/app/lib/opencode-session-native", () => ({composeNativeSessionSnapshot: async () => fetchedSnapshot,+ isMissingSessionError: () => false,}));const { SessionSurface } = await import("../src/react-app/domains/session/surface/session-surface");const { snapshotKey, transcriptKey } = await import("../src/react-app/domains/session/sync/session-sync");diff --git a/apps/app/tests/missing-chat-memory.test.ts b/apps/app/tests/missing-chat-memory.test.tsnew file mode 100644index 00000000..0e268c29--- /dev/null+++ b/apps/app/tests/missing-chat-memory.test.ts@@ -0,0 +1,61 @@+import { beforeEach, describe, expect, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";++if (typeof globalThis.window === "undefined") GlobalRegistrator.register({ url: "http://localhost/" });++const { useWorkbenchStore } = await import("../src/react-app/domains/session/chat/workbench-store");+const { forgetMissingChatMemory } = await import("../src/react-app/shell/missing-chat");+const {+ readCachedWorkspaceSessions,+ readLastSessionFor,+ writeCachedWorkspaceSessions,+ writeLastSessionFor,+} = await import("../src/react-app/shell/session-memory");++function savedSession(id: string, directory: string) {+ return { id, slug: id, projectID: "p", directory, title: id, version: "1.18.32", time: { created: 1, updated: 2 } };+}++describe("a chat the engine no longer has", () => {+ beforeEach(() => {+ window.localStorage.clear();+ useWorkbenchStore.setState({ revision: 0, primary: null, tabs: [], secondary: null, focusedPane: "primary", sideChats: {} });+ });++ test("leaves its workspace's saved list, remembered chat, tab and side-chat pair", () => {+ // What an app that ran the earlier engine saved: the chat is in the+ // sidebar cache, remembered as the last chat, open as a tab and paired.+ writeCachedWorkspaceSessions("ws-a", [savedSession("ses_gone", "/p/a"), savedSession("ses_kept", "/p/a")]);+ writeCachedWorkspaceSessions("ws-b", [savedSession("ses_gone", "/p/b")]);+ writeLastSessionFor("ws-a", "ses_gone");+ writeLastSessionFor("ws-b", "ses_gone");+ const store = useWorkbenchStore.getState();+ store.sync({ workspaceId: "ws-a", primarySessionId: "ses_kept", sessions: [], sessionsKnown: false });+ store.openTab({ workspaceId: "ws-a", sessionId: "ses_gone" });+ store.openTab({ workspaceId: "ws-b", sessionId: "ses_gone" });+ store.setSideChat({ workspaceId: "ws-a", sessionId: "ses_kept" }, { workspaceId: "ws-a", sessionId: "ses_gone" });+ expect(Object.keys(useWorkbenchStore.getState().sideChats)).toHaveLength(1);++ expect(forgetMissingChatMemory({ workspaceId: "ws-a", sessionId: "ses_gone" })).toBe(true);++ expect(readCachedWorkspaceSessions("ws-a")?.map((session) => session.id)).toEqual(["ses_kept"]);+ expect(readLastSessionFor("ws-a")).toBeNull();+ const state = useWorkbenchStore.getState();+ expect(state.tabs.map((tab) => [tab.workspaceId, tab.sessionId])).toEqual([+ ["ws-a", "ses_kept"],+ ["ws-b", "ses_gone"],+ ]);+ expect(state.sideChats).toEqual({});++ // Scoped to the pair: the same id under another workspace is untouched.+ expect(readCachedWorkspaceSessions("ws-b")?.map((session) => session.id)).toEqual(["ses_gone"]);+ expect(readLastSessionFor("ws-b")).toBe("ses_gone");+ });++ test("keeps a remembered chat that has since moved on", () => {+ writeLastSessionFor("ws-a", "ses_newer");+ forgetMissingChatMemory({ workspaceId: "ws-a", sessionId: "ses_gone" });+ expect(readLastSessionFor("ws-a")).toBe("ses_newer");+ expect(forgetMissingChatMemory({ workspaceId: " ", sessionId: "ses_gone" })).toBe(false);+ });+});diff --git a/apps/app/tests/missing-chat-surface.test.tsx b/apps/app/tests/missing-chat-surface.test.tsxnew file mode 100644index 00000000..23cf9936--- /dev/null+++ b/apps/app/tests/missing-chat-surface.test.tsx@@ -0,0 +1,198 @@+/** @jsxImportSource react */+import { expect, mock, test } from "bun:test";+import { GlobalRegistrator } from "@happy-dom/global-registrator";+import { QueryClientProvider } from "@tanstack/react-query";+import { createRequire } from "node:module";+import { act } from "react";+import { createRoot } from "react-dom/client";++const workspaceId = "workspace-missing-chat";++async function waitFor(predicate: () => boolean, label: string) {+ const deadline = Date.now() + 3_000;+ while (Date.now() < deadline) {+ if (predicate()) return;+ await act(async () => {+ await new Promise<void>((resolve) => setTimeout(resolve, 10));+ });+ }+ throw new Error(`Timed out waiting for ${label}`);+}++/** The error a native read throws for the engine's 404 on a session it does not have. */+function missingSessionError(sessionId: string) {+ return Object.assign(+ new Error(JSON.stringify({ name: "NotFoundError", data: { message: `Session not found: ${sessionId}` } })),+ { status: 404, code: "session_not_found", sessionMissing: true },+ );+}++test("a listed chat the engine does not have is handed back to the shell instead of a dead end", async () => {+ const require = createRequire(import.meta.url);+ // Bun's isolated test loader cycles Lexical's ESM entries; use their real CJS entries before the app imports the editor.+ for (const moduleId of [+ "lexical",+ "@lexical/react/LexicalComposer.js",+ "@lexical/react/LexicalPlainTextPlugin.js",+ "@lexical/react/LexicalContentEditable.js",+ "@lexical/react/LexicalErrorBoundary.js",+ "@lexical/react/LexicalOnChangePlugin.js",+ "@lexical/react/LexicalHistoryPlugin.js",+ "@lexical/react/LexicalComposerContext.js",+ ]) {+ const moduleExports = require(moduleId);+ mock.module(moduleId, () => moduleExports);+ }+ const [+ { createOmniRushServerClient },+ { IDLE_CLOUD_MCP_SUBMISSION_GATE_STATE },+ { useComposerStateStore },+ { getReactQueryClient },+ { LocalProvider },+ { ShellConfigProvider },+ ] = await Promise.all([+ import("../src/app/lib/omnirush-server"),+ import("../src/react-app/domains/connections/cloud-mcp-submit-readiness"),+ import("../src/react-app/domains/session/surface/composer-state-store"),+ import("../src/react-app/infra/query-client"),+ import("../src/react-app/kernel/local-provider"),+ import("../src/react-app/shell/shell-config"),+ ]);+ const registeredDom = typeof globalThis.window === "undefined" || typeof globalThis.document === "undefined";+ if (registeredDom) GlobalRegistrator.register({ url: "http://localhost/" });+ Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });+ document.open();+ document.write("<!doctype html><html><body></body></html>");+ document.close();+ Object.defineProperty(document, "compatMode", { configurable: true, value: "CSS1Compat" });+ const fetchStub = async () => new Response("{}", { headers: { "content-type": "application/json" } });+ Object.defineProperty(globalThis, "fetch", { configurable: true, value: fetchStub });+ Object.defineProperty(window, "fetch", { configurable: true, value: fetchStub });+ window.localStorage.setItem("omnirush.shell-config", JSON.stringify({ starterCards: false }));++ // Per session: what the snapshot read and the confirming read answer.+ const snapshotError: Record<string, Error> = {};+ const confirmError: Record<string, Error | null> = {};+ mock.module("@/components/model-select", () => ({ ModelSelect: () => null }));+ mock.module("@/components/chat/task-suggestions", () => ({ TaskSuggestions: () => null }));+ mock.module("@/react-app/domains/session/surface/composer/workspace-run-mode-menu", () => ({ WorkspaceRunModeMenu: () => null }));+ mock.module("@/react-app/domains/session/surface/composer/full-permissions-toggle", () => ({ FullPermissionsToggle: () => null }));+ mock.module("@/react-app/domains/session/surface/composer/subagent-model-menu", () => ({ SubagentModelMenu: () => null }));+ mock.module("@/app/lib/opencode-session-native", () => ({+ composeNativeSessionSnapshot: async (_endpoint: unknown, sessionId: string) => {+ throw snapshotError[sessionId] ?? new Error("unexpected snapshot read");+ },+ getNativeSession: async (_endpoint: unknown, sessionId: string) => {+ const error = confirmError[sessionId];+ if (error) throw error;+ return { id: sessionId };+ },+ isMissingSessionError: (error: unknown) =>+ error instanceof Error && "sessionMissing" in error && error.sessionMissing === true,+ }));+ const { SessionSurface } = await import("../src/react-app/domains/session/surface/session-surface");+ const { snapshotKey } = await import("../src/react-app/domains/session/sync/session-sync");+ const queryClient = getReactQueryClient();+ queryClient.clear();+ const client = createOmniRushServerClient({ baseUrl: "http://127.0.0.1:1", token: "test-token" });+ const missing: Array<[string, string]> = [];++ const surface = (sessionId: string) => (+ <QueryClientProvider client={queryClient}>+ <LocalProvider>+ <ShellConfigProvider>+ <SessionSurface+ client={client}+ workspaceId={workspaceId}+ workspaceRoot="/tmp/project-missing-chat"+ sessionId={sessionId}+ draftScope="local"+ isControlTarget={false}+ opencodeBaseUrl="http://127.0.0.1:1/opencode"+ omnirushToken="test-token"+ developerMode={false}+ modelLabel="Test model"+ onModelClick={() => {}}+ modelPickerOpen={false}+ selectedModel={{ providerID: "test", modelID: "test-model" }}+ onModelPickerOpenChange={() => {}}+ onModelChange={() => {}}+ onSendDraft={async () => ({ outcome: "accepted" })}+ cloudMcpSubmissionState={IDLE_CLOUD_MCP_SUBMISSION_GATE_STATE}+ onOpenConnect={() => {}}+ onDraftChange={() => {}}+ attachmentsEnabled={false}+ attachmentsDisabledReason="Not needed in this test"+ modelVariantLabel="Default"+ modelVariant={null}+ onModelVariantChange={() => {}}+ agentLabel="OmniRush.ai"+ selectedAgent={null}+ listAgents={async () => []}+ onSelectAgent={() => {}}+ listCommands={async () => []}+ recentFiles={[]}+ searchFiles={async () => []}+ isRemoteWorkspace+ isSandboxWorkspace={false}+ providerConnectedCount={1}+ onSessionMissing={(workspace, session) => missing.push([workspace, session])}+ />+ </ShellConfigProvider>+ </LocalProvider>+ </QueryClientProvider>+ );++ const containers: HTMLDivElement[] = [];+ const roots: ReturnType<typeof createRoot>[] = [];+ const mount = async (sessionId: string) => {+ queryClient.setQueryDefaults(snapshotKey(workspaceId, sessionId), { retry: false, retryDelay: 0 });+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ containers.push(container);+ roots.push(root);+ await act(async () => root.render(surface(sessionId)));+ return container;+ };+ const settle = () => act(async () => {+ await new Promise<void>((resolve) => setTimeout(resolve, 150));+ });++ try {+ // Gone: the snapshot read and the confirming read both say so.+ snapshotError.ses_gone = missingSessionError("ses_gone");+ confirmError.ses_gone = missingSessionError("ses_gone");+ const gone = await mount("ses_gone");+ await waitFor(() => missing.length > 0, "the shell to be told the chat is missing");+ expect(missing).toEqual([[workspaceId, "ses_gone"]]);+ await waitFor(() => gone.textContent?.includes("no longer available") === true, "the readable notice");+ expect(gone.textContent).not.toContain("NotFoundError");++ // Back by the confirming read (e.g. carried over meanwhile): not dropped.+ snapshotError.ses_back = missingSessionError("ses_back");+ confirmError.ses_back = null;+ await mount("ses_back");+ await waitFor(() => queryClient.getQueryState(snapshotKey(workspaceId, "ses_back"))?.status === "error", "the failed read");+ await settle();++ // Any other failure (engine restarting, bare 404) never drops a chat.+ snapshotError.ses_restarting = Object.assign(new Error("OmniRush request failed"), { status: 503, code: "opencode_engine_unreachable" });+ snapshotError.ses_bare = Object.assign(new Error("404 Not Found"), { status: 404, code: "session_not_found" });+ const restarting = await mount("ses_restarting");+ await mount("ses_bare");+ await waitFor(() => queryClient.getQueryState(snapshotKey(workspaceId, "ses_bare"))?.status === "error", "the bare 404");+ await settle();+ expect(missing).toEqual([[workspaceId, "ses_gone"]]);+ expect(restarting.textContent).not.toContain("no longer available");+ } finally {+ await act(async () => {+ for (const root of roots) root.unmount();+ });+ useComposerStateStore.setState({ sessions: {}, queuedDrafts: {}, history: {} });+ queryClient.clear();+ for (const container of containers) container.remove();+ mock.restore();+ if (registeredDom) await GlobalRegistrator.unregister();+ }+});diff --git a/apps/app/tests/opencode-session-native.test.ts b/apps/app/tests/opencode-session-native.test.tsindex 3d22039f..c349aacb 100644--- a/apps/app/tests/opencode-session-native.test.ts+++ b/apps/app/tests/opencode-session-native.test.ts@@ -11,6 +11,7 @@ import {deleteNativeSession,getNativeSession,getNativeSessionMessages,+ isMissingSessionError,type NativeSessionOperations,} from "../src/app/lib/opencode-session-native";import { classifyRouteSessionReadError } from "../src/react-app/shell/route-workspaces";@@ -200,6 +201,36 @@ describe("native OpenCode session operations", () => {}});+ test("only a 404 that names the session marks it as missing", async () => {+ const read = async (error: unknown, status: number) => {+ try {+ await composeNativeSessionSnapshot(endpoint, "ses_gone", undefined, {+ createOperations: () => operations({ get: async () => failedResult(error, status) }),+ });+ } catch (thrown) {+ return thrown;+ }+ throw new Error("Expected the snapshot read to fail");+ };++ // The local server's ownership check, and the engine's own answer.+ const server = await read({ code: "session_not_found", message: "Session not found" }, 404);+ const engine = await read({ name: "NotFoundError", data: { message: "Session not found: ses_gone" } }, 404);+ expect(server).toMatchObject({ status: 404, code: "session_not_found" });+ expect(isMissingSessionError(server)).toBe(true);+ expect(isMissingSessionError(engine)).toBe(true);++ // A bare 404 keeps its route classification but is no proof the chat is gone.+ const bare = await read({ message: "missing" }, 404);+ expect(bare).toMatchObject({ status: 404, code: "session_not_found" });+ expect(isMissingSessionError(bare)).toBe(false);+ expect(isMissingSessionError(await read("404 Not Found", 404))).toBe(false);+ expect(isMissingSessionError(await read({ name: "NotFoundError", data: { message: "Project not found" } }, 404))).toBe(false);+ expect(isMissingSessionError(await read({ code: "session_not_found" }, 502))).toBe(false);+ expect(isMissingSessionError(await read({ code: "opencode_engine_unreachable" }, 503))).toBe(false);+ expect(isMissingSessionError(new TypeError("Failed to fetch"))).toBe(false);+ });+test("a request with no response keeps its own error and stays retryable", async () => {for (const cause of [new TypeError("Failed to fetch"), new Error("Request timed out.")]) {const promise = getNativeSession(endpoint, "ses_native", undefined, {