Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(app): session and workspace deletes reach the right engine, stick, and never fail silently

Samrat Talukdarc52d842d238a
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.ts
index 389bb222..6b7b32ff 100644
--- a/apps/app/src/app/lib/omnirush-server.ts
+++ b/apps/app/src/app/lib/omnirush-server.ts
@@ -1604,7 +1604,8 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s
capabilities: 6_000,
listWorkspaces: 8_000,
activateWorkspace: 10_000,
- deleteWorkspace: 10_000,
+ // The server first stops the workspace's running sessions and releases its engine instance.
+ deleteWorkspace: 30_000,
sessionRead: 12_000,
status: 6_000,
diagnostics: AGENT_CONTEXT_DIAGNOSTICS_REQUEST_TIMEOUT_MS,
diff --git a/apps/app/src/app/lib/opencode.ts b/apps/app/src/app/lib/opencode.ts
index 964173e4..13aab4d5 100644
--- a/apps/app/src/app/lib/opencode.ts
+++ b/apps/app/src/app/lib/opencode.ts
@@ -62,6 +62,11 @@ export const SESSION_READ_REQUEST_TIMEOUT_MS = 45_000;
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(?:[?#]|$)/;
+// DELETE <base>/session/<id>: the local server first stops the session's run
+// and its sub-agents, then the engine removes it. Past the generic budget the
+// person would see a failure for a delete that is still completing.
+const SESSION_DELETE_URL_RE = /\/session\/[^/?#]+\/?(?:[?#]|$)/;
+const SESSION_DELETE_REQUEST_TIMEOUT_MS = 30_000;
export class PromptAdmissionUnknownError extends Error {
readonly admission = "unknown";
@@ -122,6 +127,9 @@ export function resolveRequestTimeoutMs(input: RequestInfo | URL, fallbackMs: nu
if (SESSION_PROMPT_ASYNC_URL_RE.test(url)) {
return Math.max(fallbackMs, PROMPT_ASYNC_REQUEST_TIMEOUT_MS);
}
+ if (fallbackMs > 0 && getRequestMethod(input, init) === "DELETE" && SESSION_DELETE_URL_RE.test(url)) {
+ return Math.max(fallbackMs, SESSION_DELETE_REQUEST_TIMEOUT_MS);
+ }
if (/\/provider\/oauth\//.test(url) || /\/mcp\/auth\/callback\b/.test(url)) {
return Math.max(fallbackMs, OAUTH_OPENCODE_REQUEST_TIMEOUT_MS);
}
diff --git a/apps/app/src/i18n/locales/en.ts b/apps/app/src/i18n/locales/en.ts
index ab2174f4..b04ff950 100644
--- a/apps/app/src/i18n/locales/en.ts
+++ b/apps/app/src/i18n/locales/en.ts
@@ -77,6 +77,7 @@ export default {
"common.refresh": "Refresh",
"common.remove": "Remove",
"common.reset": "Reset",
+ "common.retry": "Retry",
"common.save": "Save",
"common.select": "select",
"common.show": "Show",
@@ -1251,9 +1252,11 @@ export default {
"session.title_generation_failed_body": "Your conversation is safe. Rename it from the task menu while we keep the generated placeholder.",
"session.title_generation_failed_title": "Automatic task title did not complete",
"session.delete": "Delete",
+ "session.delete_failed": "Couldn't delete session",
"session.delete_named_session_message": "This will permanently delete \"{title}\" and its messages.",
"session.delete_session_generic": "This will permanently delete the selected session and its messages.",
"session.delete_session_title": "Delete session?",
+ "session.delete_unavailable": "The workspace's local server is not connected yet. Try again in a moment.",
"session.deleting": "Deleting...",
"session.deny": "Deny",
"session.details": "Details",
@@ -2021,6 +2024,7 @@ export default {
"workspace_list.hide_child_sessions": "Hide child sessions",
"workspace_list.recover": "Recover",
"workspace_list.remove_confirm": "Remove this workspace from the sidebar? Sessions and files on disk are preserved.",
+ "workspace_list.remove_failed": "Couldn't remove workspace",
"workspace_list.remove_workspace": "Remove workspace",
"workspace_list.rename_session": "Rename session",
"workspace_list.remote_worker_unavailable": "Remote worker unavailable",
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 7347e3b7..111a5343 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
@@ -43,6 +43,7 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { ConfirmModal } from "../../../design-system/modals/confirm-modal";
+import { toast } from "@/components/ui/sonner";
import { usePlatform } from "../../../kernel/platform";
import { useDenAuth } from "../../cloud/den-auth-provider";
import ProviderAuthModal, { type ProviderAuthModalProps } from "../../connections/provider-auth/provider-auth-modal";
@@ -1331,18 +1332,31 @@ export function SessionPage(props: SessionPageProps) {
}
};
- const confirmDelete = async () => {
- const sessionId = sessionActionId;
- if (!sessionId || !props.onDeleteSession) return;
+ const deleteSession = async (sessionId: string) => {
+ if (!props.onDeleteSession) return;
setDeleteBusy(true);
try {
await props.onDeleteSession(sessionId);
setDeleteOpen(false);
+ } catch (error) {
+ // A delete never fails silently: say why and offer the same delete again.
+ toast.error(t("session.delete_failed"), {
+ id: `session-delete:${sessionId}`,
+ duration: 30_000,
+ description: error instanceof Error && error.message ? error.message : t("common.something_went_wrong"),
+ action: { label: t("common.retry"), onClick: () => void deleteSession(sessionId) },
+ });
} finally {
setDeleteBusy(false);
}
};
+ const confirmDelete = async () => {
+ const sessionId = sessionActionId;
+ if (!sessionId) return;
+ await deleteSession(sessionId);
+ };
+
const sidePanelContent = activeSidePanel === "extensions" && props.settingsSlot ? (
<div className="flex h-full min-h-0 flex-col overflow-y-auto bg-background">
{props.settingsSlot}
diff --git a/apps/app/src/react-app/domains/session/control/session-control-actions.ts b/apps/app/src/react-app/domains/session/control/session-control-actions.ts
index e4bdc914..2406ed05 100644
--- a/apps/app/src/react-app/domains/session/control/session-control-actions.ts
+++ b/apps/app/src/react-app/domains/session/control/session-control-actions.ts
@@ -40,6 +40,8 @@ type UseSessionControlActionsInput = {
createTaskInWorkspace: (workspaceId: string) => Promise<string | null> | string | null;
openModelPicker: () => void;
refreshRouteState: () => Promise<unknown> | unknown;
+ /** Drops a deleted session from every sidebar list at once. */
+ forgetDeletedSession?: (sessionId: string) => void;
};
function workspaceLabel(workspace: SessionControlWorkspace) {
@@ -74,6 +76,7 @@ export function useSessionControlActions(input: UseSessionControlActionsInput) {
canCreateTask,
createTaskInWorkspace,
endpointForWorkspace,
+ forgetDeletedSession,
navigateToSession,
navigateToSessionRoot,
openModelPicker,
@@ -220,13 +223,14 @@ export function useSessionControlActions(input: UseSessionControlActionsInput) {
const endpoint = endpointForWorkspace(targetWorkspace);
if (!endpoint) return { ok: false, error: "Workspace runtime is not connected" };
await deleteRouteSession(endpoint, sessionId);
+ forgetDeletedSession?.(sessionId);
if (selectedSessionId === sessionId) {
navigateToSessionRoot();
}
await refreshRouteState();
return { ok: true, sessionId, deleted: true };
},
- }), [endpointForWorkspace, navigateToSessionRoot, omnirushClient, refreshRouteState, selectedSessionId, sessionsByWorkspaceId, workspaces]);
+ }), [endpointForWorkspace, forgetDeletedSession, navigateToSessionRoot, omnirushClient, refreshRouteState, selectedSessionId, sessionsByWorkspaceId, workspaces]);
useControlAction(deleteSessionControlAction);
const modelPickerControlAction = useMemo<OmniRushControlAction>(() => ({
diff --git a/apps/app/src/react-app/shell/route-workspaces.ts b/apps/app/src/react-app/shell/route-workspaces.ts
index 199dccb5..ff3ebf71 100644
--- a/apps/app/src/react-app/shell/route-workspaces.ts
+++ b/apps/app/src/react-app/shell/route-workspaces.ts
@@ -111,8 +111,52 @@ export async function createRouteSession(endpoint: ResolvedWorkspaceEndpoint, di
return unwrap(await client.session.create({ directory }));
}
-export async function deleteRouteSession(endpoint: ResolvedWorkspaceEndpoint, sessionId: string): Promise<boolean> {
- return deleteNativeSession(await routeSessionEndpoint(endpoint), sessionId);
+const DELETE_SESSION_RETRY_DELAYS_MS = [500, 1_500, 3_000];
+
+/**
+ * Delete a session so that the result is the person's intent, not one
+ * request's fate: a session that is already gone (a delete whose answer was
+ * lost, a second click, another window) counts as deleted, and a transient
+ * engine gap (restart, rollover, a slow instance boot) is retried. Anything
+ * else is thrown for the caller to show.
+ */
+export async function deleteRouteSession(
+ endpoint: ResolvedWorkspaceEndpoint,
+ sessionId: string,
+ options: { retryDelaysMs?: readonly number[] } = {},
+): Promise<boolean> {
+ try {
+ return await withTransientEngineRetry({
+ load: async () => deleteNativeSession(await routeSessionEndpoint(endpoint), sessionId),
+ retryDelaysMs: options.retryDelaysMs ?? DELETE_SESSION_RETRY_DELAYS_MS,
+ wait: (delayMs) => new Promise<void>((resolve) => setTimeout(resolve, delayMs)),
+ });
+ } catch (error) {
+ if (classifyRouteSessionReadError(error) === "not-found") return true;
+ throw error;
+ }
+}
+
+/**
+ * Remove a workspace from the local server's registry and the desktop's list,
+ * or throw so the person sees why. Neither failure may be swallowed: the
+ * server's list is merged into the sidebar and is what the next start
+ * loads, so a half-removed workspace comes back. A workspace the server does
+ * not register (remote, or already removed) only leaves the desktop list.
+ */
+export async function removeRouteWorkspace(input: {
+ workspaceId: string;
+ deleteFromServer: ((workspaceId: string) => Promise<unknown>) | null;
+ forgetOnDesktop: ((workspaceId: string) => Promise<unknown>) | null;
+}): Promise<void> {
+ if (input.deleteFromServer) {
+ try {
+ await input.deleteFromServer(input.workspaceId);
+ } catch (error) {
+ if (!(error instanceof OmniRushServerError && error.status === 404)) throw error;
+ }
+ }
+ await input.forgetOnDesktop?.(input.workspaceId);
}
export async function listRouteSessions(
diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsx
index 4d4d2e7d..6de0d20b 100644
--- a/apps/app/src/react-app/shell/session-route.tsx
+++ b/apps/app/src/react-app/shell/session-route.tsx
@@ -82,6 +82,7 @@ import {
describeWorkspaceCreateError,
createRouteSession,
deleteRouteSession,
+ removeRouteWorkspace,
downloadWorkspaceJson,
folderNameFromPath,
getSessionStatus,
@@ -508,6 +509,7 @@ export function SessionRoute() {
handleRuntimeSessionCreated,
handleRuntimeSessionUpdated,
handleRuntimeSessionDeleted,
+ forgetDeletedSession,
handleRemoteWorkspaceConnectionSaved,
runRemoteWorkspaceConnectionCheck,
} = useWorkspaceRouteState({
@@ -2109,21 +2111,26 @@ export function SessionRoute() {
[endpointForWorkspace, workspaces],
);
- const handleForgetWorkspace = useCallback(
- async (workspaceId: string) => {
- if (typeof window !== "undefined") {
- const message =
- t("workspace_list.remove_confirm") ||
- "Remove this workspace from the sidebar?";
- if (!window.confirm(message)) return;
- }
+ const removeWorkspaceConfirmed = useCallback(
+ async (workspaceId: string): Promise<void> => {
// Remove from both stores so the next refresh can't resurrect the row
// from whichever list wins the merge.
- if (client) {
- await client.deleteWorkspace(workspaceId).catch(() => undefined);
- }
- if (isDesktopRuntime()) {
- await workspaceForget(workspaceId).catch(() => undefined);
+ try {
+ await removeRouteWorkspace({
+ workspaceId,
+ deleteFromServer: client ? (id) => client.deleteWorkspace(id) : null,
+ forgetOnDesktop: isDesktopRuntime() ? workspaceForget : null,
+ });
+ } catch (error) {
+ console.error("[session-route] remove workspace failed", error);
+ toast.error(t("workspace_list.remove_failed"), {
+ id: `workspace-remove:${workspaceId}`,
+ duration: 30_000,
+ description: describeRouteError(error),
+ action: { label: t("common.retry"), onClick: () => void removeWorkspaceConfirmed(workspaceId) },
+ });
+ await refreshRouteState();
+ return;
}
if (selectedWorkspaceId === workspaceId) {
setLegacySelectedWorkspaceId("");
@@ -2137,6 +2144,19 @@ export function SessionRoute() {
[client, navigate, refreshRouteState, selectedWorkspaceId],
);
+ const handleForgetWorkspace = useCallback(
+ async (workspaceId: string) => {
+ if (typeof window !== "undefined") {
+ const message =
+ t("workspace_list.remove_confirm") ||
+ "Remove this workspace from the sidebar?";
+ if (!window.confirm(message)) return;
+ }
+ await removeWorkspaceConfirmed(workspaceId);
+ },
+ [removeWorkspaceConfirmed],
+ );
+
const applyLastUsedModelToSession = useCallback((sessionId: string) => {
const previous = selectedSessionId ? getSessionModelSelection(selectedSessionId) : null;
@@ -2455,6 +2475,7 @@ export function SessionRoute() {
createTaskInWorkspace: handleCreateTaskInWorkspace,
openModelPicker: openModelPickerForControl,
refreshRouteState,
+ forgetDeletedSession,
});
const seedUnavailableModelControlAction = useMemo<OmniRushControlAction | null>(() => {
@@ -3663,13 +3684,21 @@ export function SessionRoute() {
onDeleteSession={
client && selectedWorkspaceId
? async (sessionId) => {
- const endpoint = endpointForWorkspace(selectedWorkspace);
- if (!endpoint) return;
+ // The sidebar lists sessions from every workspace: delete through
+ // the workspace that owns the session, whose engine runs it and
+ // whose list shows it.
+ const ownerId = workspaceSessionGroups.find((group) =>
+ group.sessions.some((session) => session?.id === sessionId),
+ )?.workspace.id;
+ const ownerWorkspace = workspaces.find((workspace) => workspace.id === ownerId) ?? selectedWorkspace;
+ const endpoint = endpointForWorkspace(ownerWorkspace);
+ if (!ownerWorkspace || !endpoint) throw new Error(t("session.delete_unavailable"));
await deleteRouteSession(endpoint, sessionId);
+ forgetDeletedSession(sessionId);
if (selectedSessionId === sessionId) {
navigateToWorkspaceSession(selectedWorkspaceId);
}
- await refreshRouteState();
+ void reloadWorkspaceSessions(ownerWorkspace.id);
}
: undefined
}
diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsx
index a6152e96..2989e5e3 100644
--- a/apps/app/src/react-app/shell/settings-route.tsx
+++ b/apps/app/src/react-app/shell/settings-route.tsx
@@ -48,6 +48,7 @@ import {
type RouteSession,
createRouteSession,
describeRouteError,
+ removeRouteWorkspace,
downloadWorkspaceJson,
getSessionStatus,
isActiveSessionStatus,
@@ -2186,16 +2187,23 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {
throw new Error("omnirush.ai server is unavailable. Reconnect the server before exporting workspace config.");
}, [workspaceServerClientResolver, workspaces]);
- const handleForgetWorkspace = useCallback(async (workspaceId: string) => {
- if (typeof window !== "undefined") {
- const message = t("workspace_list.remove_confirm") || "Remove this workspace from the sidebar?";
- if (!window.confirm(message)) return;
- }
- if (omnirushClient) {
- await omnirushClient.deleteWorkspace(workspaceId).catch(() => undefined);
- }
- if (isDesktopRuntime()) {
- await workspaceForget(workspaceId).catch(() => undefined);
+ const removeWorkspaceConfirmed = useCallback(async (workspaceId: string): Promise<void> => {
+ try {
+ await removeRouteWorkspace({
+ workspaceId,
+ deleteFromServer: omnirushClient ? (id) => omnirushClient.deleteWorkspace(id) : null,
+ forgetOnDesktop: isDesktopRuntime() ? workspaceForget : null,
+ });
+ } catch (error) {
+ console.error("[settings-route] remove workspace failed", error);
+ toast.error(t("workspace_list.remove_failed"), {
+ id: `workspace-remove:${workspaceId}`,
+ duration: 30_000,
+ description: describeRouteError(error),
+ action: { label: t("common.retry"), onClick: () => void removeWorkspaceConfirmed(workspaceId) },
+ });
+ await refreshRouteState();
+ return;
}
if (selectedWorkspaceId === workspaceId) {
const nextWorkspace = workspaces.find((workspace) => workspace.id !== workspaceId);
@@ -2208,6 +2216,14 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {
await refreshRouteState();
}, [omnirushClient, refreshRouteState, selectedWorkspaceId, workspaces]);
+ const handleForgetWorkspace = useCallback(async (workspaceId: string) => {
+ if (typeof window !== "undefined") {
+ const message = t("workspace_list.remove_confirm") || "Remove this workspace from the sidebar?";
+ if (!window.confirm(message)) return;
+ }
+ await removeWorkspaceConfirmed(workspaceId);
+ }, [removeWorkspaceConfirmed]);
+
if (route.redirectPath && !props.embedded) {
const target = props.standaloneExtensions
? selectedWorkspaceId
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 e483ce0c..37cae2b9 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
@@ -86,7 +86,9 @@ import {
legacySessionRoute,
mergeWorkspaceRouteSession,
preserveWorkspaceRouteSession,
+ removeSessionFromWorkspaceLists,
removeWorkspaceRouteSession,
+ withoutDeletedSessions,
sessionIdForLegacyWorkspaceInference,
automationsRoute,
dashboardRoute,
@@ -252,6 +254,10 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
const remoteWorkspaceCheckRunCounterRef = useRef(0);
const sessionsByWorkspaceIdRef = useRef<Record<string, RouteSession[]>>({});
const pendingCreatedSessionIdsRef = useRef<Record<string, Record<string, number>>>({});
+ // Sessions deleted in this window. A list load that started before the
+ // delete (a coalesced reload hands its caller that same load) still
+ // carries them; they never come back into the sidebar from it.
+ const deletedSessionIdsRef = useRef(new Set<string>());
const hydratedRouteSessionIdsRef = useRef<Record<string, string>>({});
const startupRetryTimerRef = useRef<number | null>(null);
const [retryingWorkspaceIds, setRetryingWorkspaceIds] = useState<string[]>([]);
@@ -293,7 +299,8 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
[id]: Date.now(),
};
}, []);
- const mergeFetchedSessionsWithPending = useCallback((workspaceId: string, fetched: RouteSession[], current: RouteSession[]) => {
+ const mergeFetchedSessionsWithPending = useCallback((workspaceId: string, listed: RouteSession[], current: RouteSession[]) => {
+ const fetched = withoutDeletedSessions(listed, deletedSessionIdsRef.current);
const pending = pendingCreatedSessionIdsRef.current[workspaceId];
let merged = fetched;
if (pending) {
@@ -938,18 +945,24 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
return next;
});
}, [rememberPendingCreatedSession, selectedWorkspaceId]);
- const handleRuntimeSessionDeleted = useCallback((sessionId: string) => {
- if (!selectedWorkspaceId) return;
- removeCachedWorkspaceSession(selectedWorkspaceId, sessionId);
- setSessionsByWorkspaceId((current) => {
- const list = current[selectedWorkspaceId] ?? [];
- const nextList = removeWorkspaceRouteSession(list, sessionId);
- if (nextList === list) return current;
- const next = { ...current, [selectedWorkspaceId]: nextList };
- sessionsByWorkspaceIdRef.current = next;
- return next;
- });
+ /**
+ * A deleted session leaves every sidebar list, the saved lists and any
+ * pending-created overlay at once, whichever workspace lists it: the delete
+ * may have gone through another workspace's engine, whose event the
+ * owning workspace never receives.
+ */
+ const forgetDeletedSession = useCallback((sessionId: string) => {
+ const id = sessionId.trim();
+ if (!id) return;
+ deletedSessionIdsRef.current.add(id);
+ for (const pending of Object.values(pendingCreatedSessionIdsRef.current)) delete pending[id];
+ const { lists, workspaceIds } = removeSessionFromWorkspaceLists(sessionsByWorkspaceIdRef.current, id);
+ for (const workspaceId of new Set([...workspaceIds, selectedWorkspaceId])) removeCachedWorkspaceSession(workspaceId, id);
+ if (workspaceIds.length === 0) return;
+ sessionsByWorkspaceIdRef.current = lists;
+ setSessionsByWorkspaceId(lists);
}, [selectedWorkspaceId]);
+ const handleRuntimeSessionDeleted = forgetDeletedSession;
useEffect(() => {
workspacesRef.current = workspaces;
@@ -1474,6 +1487,7 @@ export function useWorkspaceRouteState(input: UseWorkspaceRouteStateInput) {
handleRuntimeSessionCreated,
handleRuntimeSessionUpdated,
handleRuntimeSessionDeleted,
+ forgetDeletedSession,
handleRemoteWorkspaceConnectionSaved,
runRemoteWorkspaceConnectionCheck,
};
diff --git a/apps/app/src/react-app/shell/workspace-routes.ts b/apps/app/src/react-app/shell/workspace-routes.ts
index 6a85442c..ad6a717c 100644
--- a/apps/app/src/react-app/shell/workspace-routes.ts
+++ b/apps/app/src/react-app/shell/workspace-routes.ts
@@ -106,6 +106,33 @@ export function removeWorkspaceRouteSession<T extends { id: string }>(sessions:
return next.length === sessions.length ? sessions : next;
}
+/**
+ * Every workspace's list without a deleted session, whichever workspace
+ * listed it, and the workspaces that did. The same object when none did.
+ */
+export function removeSessionFromWorkspaceLists<T extends { id: string }>(
+ lists: Record<string, T[]>,
+ sessionId: string,
+): { lists: Record<string, T[]>; workspaceIds: string[] } {
+ let next = lists;
+ const workspaceIds: string[] = [];
+ for (const [workspaceId, list] of Object.entries(lists)) {
+ const nextList = removeWorkspaceRouteSession(list, sessionId);
+ if (nextList === list) continue;
+ if (next === lists) next = { ...lists };
+ next[workspaceId] = nextList;
+ workspaceIds.push(workspaceId);
+ }
+ return { lists: next, workspaceIds };
+}
+
+/** A fetched list without the sessions deleted since it was requested. */
+export function withoutDeletedSessions<T extends { id?: string | null }>(sessions: T[], deleted: ReadonlySet<string>): T[] {
+ if (deleted.size === 0) return sessions;
+ const next = sessions.filter((session) => !deleted.has(String(session?.id ?? "")));
+ return next.length === sessions.length ? sessions : next;
+}
+
export function legacySessionRoute(sessionId?: string | null) {
const session = sessionId?.trim();
return session ? `/session/${encodeURIComponent(session)}` : "/session";
diff --git a/apps/app/tests/session-read-transport-failure.test.ts b/apps/app/tests/session-read-transport-failure.test.ts
index aa367ea0..a8397ce1 100644
--- a/apps/app/tests/session-read-transport-failure.test.ts
+++ b/apps/app/tests/session-read-transport-failure.test.ts
@@ -281,9 +281,14 @@ describe("session read timeouts", () => {
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);
});
+
+ test("a session delete outlasts the server stopping the session's run first", () => {
+ expect(resolveRequestTimeoutMs(`${base}/session/ses_1`, 10_000, { method: "DELETE" })).toBe(30_000);
+ expect(resolveRequestTimeoutMs(new Request(`${base}/session/ses_1`, { method: "DELETE" }), 10_000)).toBe(30_000);
+ expect(resolveRequestTimeoutMs(new Request(`${base}/session/ses_1/message/msg_1`, { method: "DELETE" }), 10_000)).toBe(10_000);
+ });
});
describe("failed session lists in the sidebar", () => {
diff --git a/apps/app/tests/workspace-routes.test.ts b/apps/app/tests/workspace-routes.test.ts
index 406b5772..4cea20d4 100644
--- a/apps/app/tests/workspace-routes.test.ts
+++ b/apps/app/tests/workspace-routes.test.ts
@@ -7,8 +7,10 @@ import {
mergeRouteWorkspaces,
readRouteSessionsWithRetry,
refreshRouteWorkspaceListState,
+ removeRouteWorkspace,
stabilizeRouteWorkspaceOrder,
} from "../src/react-app/shell/route-workspaces";
+import { OmniRushServerError } from "../src/app/lib/omnirush-server";
import {
createRouteWorkspaceLoadCoalescer,
mapRouteWorkspaceLoads,
@@ -16,8 +18,10 @@ import {
import {
mergeWorkspaceRouteSession,
preserveWorkspaceRouteSession,
+ removeSessionFromWorkspaceLists,
removeWorkspaceRouteSession,
sessionIdForLegacyWorkspaceInference,
+ withoutDeletedSessions,
settingsNavigationFromPathname,
globalExtensionsRoute,
workspaceExtensionsRoute,
@@ -80,14 +84,106 @@ describe("workspace session mutations", () => {
});
if (!endpoint) throw new Error("Workspace endpoint missing");
await expect(createRouteSession(endpoint, "/existing")).rejects.toThrow();
- await expect(deleteRouteSession(endpoint, "ses_created")).rejects.toThrow();
- expect(methods).toEqual(["GET", "GET"]);
+ await expect(deleteRouteSession(endpoint, "ses_created", { retryDelaysMs: [1, 1] })).rejects.toThrow();
+ // The routing read is retried as a transient gap, but never turns into a blind delete.
+ expect(methods).toEqual(["GET", "GET", "GET", "GET"]);
} finally {
globalThis.fetch = originalFetch;
}
});
});
+describe("deleting a session", () => {
+ async function withEngine(answers: Array<() => Response>, run: (endpoint: NonNullable<ReturnType<typeof resolveWorkspaceEndpoint>>, deletes: () => number) => Promise<void>) {
+ const originalFetch = globalThis.fetch;
+ let deletes = 0;
+ globalThis.fetch = async (input, init) => {
+ const request = input instanceof Request ? input : new Request(input, init);
+ if (new URL(request.url).pathname === "/experimental/engine-v2-preview/status") return Response.json({}, { status: 404 });
+ const answer = answers[deletes] ?? answers[answers.length - 1];
+ deletes += 1;
+ return answer();
+ };
+ try {
+ const endpoint = resolveWorkspaceEndpoint({ id: "ws_existing", workspaceType: "local" }, { baseUrl: "http://owner.test", token: "fixture-token" });
+ if (!endpoint) throw new Error("Workspace endpoint missing");
+ await run(endpoint, () => deletes);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ }
+
+ test("a session that is already gone counts as deleted (second click, lost answer, another window)", async () => {
+ await withEngine([() => Response.json({ name: "NotFoundError", data: { message: "Session not found: ses_gone" } }, { status: 404 })], async (endpoint, deletes) => {
+ expect(await deleteRouteSession(endpoint, "ses_gone", { retryDelaysMs: [] })).toBe(true);
+ expect(deletes()).toBe(1);
+ });
+ });
+
+ test("a transient engine gap (restart, rollover) is retried until the delete lands", async () => {
+ await withEngine([
+ () => Response.json({ code: "opencode_unreachable", message: "OpenCode engine is unavailable" }, { status: 502 }),
+ () => Response.json({ code: "opencode_unreachable", message: "OpenCode engine is unavailable" }, { status: 502 }),
+ () => Response.json(true),
+ ], async (endpoint, deletes) => {
+ expect(await deleteRouteSession(endpoint, "ses_busy", { retryDelaysMs: [1, 1, 1] })).toBe(true);
+ expect(deletes()).toBe(3);
+ });
+ });
+
+ test("any other failure reaches the caller instead of passing silently", async () => {
+ await withEngine([() => Response.json({ code: "workspace_not_found", message: "Workspace not found" }, { status: 404 })], async (endpoint) => {
+ await expect(deleteRouteSession(endpoint, "ses_x", { retryDelaysMs: [1] })).rejects.toThrow("Workspace not found");
+ });
+ });
+
+ test("a deleted session leaves every workspace list, and stale lists cannot bring it back", () => {
+ const lists = {
+ alpha: [{ id: "ses_a" }],
+ beta: [{ id: "ses_b" }, { id: "ses_deleted" }],
+ };
+ const removed = removeSessionFromWorkspaceLists(lists, "ses_deleted");
+ expect(removed.workspaceIds).toEqual(["beta"]);
+ expect(removed.lists).toEqual({ alpha: [{ id: "ses_a" }], beta: [{ id: "ses_b" }] });
+ expect(removed.lists.alpha).toBe(lists.alpha);
+ expect(removeSessionFromWorkspaceLists(removed.lists, "ses_deleted").lists).toBe(removed.lists);
+ // A list load that started before the delete still carries it.
+ const staleLoad = [{ id: "ses_b" }, { id: "ses_deleted" }];
+ expect(withoutDeletedSessions(staleLoad, new Set(["ses_deleted"]))).toEqual([{ id: "ses_b" }]);
+ expect(withoutDeletedSessions(staleLoad, new Set())).toBe(staleLoad);
+ });
+});
+
+describe("removing a workspace", () => {
+ test("a server that cannot remove it stops the removal and the desktop keeps it", async () => {
+ const forgotten: string[] = [];
+ await expect(removeRouteWorkspace({
+ workspaceId: "ws_1",
+ deleteFromServer: async () => { throw new OmniRushServerError(500, "workspace_registry_write_failed", "saving the workspace list failed"); },
+ forgetOnDesktop: async (id) => { forgotten.push(id); },
+ })).rejects.toThrow("saving the workspace list failed");
+ expect(forgotten).toEqual([]);
+ });
+
+ test("a workspace the server does not register only leaves the desktop list", async () => {
+ const forgotten: string[] = [];
+ await removeRouteWorkspace({
+ workspaceId: "rem_remote",
+ deleteFromServer: async () => { throw new OmniRushServerError(404, "workspace_not_found", "Workspace not found"); },
+ forgetOnDesktop: async (id) => { forgotten.push(id); },
+ });
+ expect(forgotten).toEqual(["rem_remote"]);
+ });
+
+ test("a desktop list that cannot be saved is reported too", async () => {
+ await expect(removeRouteWorkspace({
+ workspaceId: "ws_1",
+ deleteFromServer: async () => ({ ok: true }),
+ forgetOnDesktop: async () => { throw new Error("EPERM: operation not permitted, rename"); },
+ })).rejects.toThrow("EPERM");
+ });
+});
+
describe("workspace surface routes", () => {
test("keeps Extensions outside Settings and preserves deep links", () => {
expect(workspaceSettingsRoute(" workspace/a ", "extensions")).toBe(