Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: sends wait during sandbox setup

ogsamratd9cf21226ad6
diff --git a/apps/app/src/app/lib/opencode.ts b/apps/app/src/app/lib/opencode.ts
index a2c537f2..226eb88b 100644
--- a/apps/app/src/app/lib/opencode.ts
+++ b/apps/app/src/app/lib/opencode.ts
@@ -213,6 +213,42 @@ function resolveOmniRushWorkspaceMount(baseUrl: string): { baseUrl: string; work
}
}
+/**
+ * Workspaces whose required sandbox is still being set up (its image
+ * downloading, the box starting). The local server holds their prompts until
+ * the box is ready (apps/server/src/box/service.ts waitForBox: at most 60 min,
+ * 15 min without download progress), so a prompt that has not answered yet is
+ * waiting, not lost: its deadline waits on instead of calling it unknown.
+ */
+const sandboxSetupWorkspaces = new Set<string>();
+const SANDBOX_SETUP_HOLD_MAX_MS = 80 * 60_000;
+
+/** The sandbox setup card's state for a workspace (linux-sandbox.ts). */
+export function setSandboxSetupHold(workspaceId: string, held: boolean): void {
+ if (held) sandboxSetupWorkspaces.add(workspaceId);
+ else sandboxSetupWorkspaces.delete(workspaceId);
+}
+
+/** Whether a request URL belongs to a workspace whose sandbox setup holds its prompts. */
+export function promptHeldForSandbox(url: string): boolean {
+ if (sandboxSetupWorkspaces.size === 0) return false;
+ const match = url.match(/\/(?:w|workspace)\/([^/?#]+)\/opencode(?:\/|$)/);
+ if (!match?.[1]) return false;
+ try { return sandboxSetupWorkspaces.has(decodeURIComponent(match[1])); } catch { return false; }
+}
+
+/** setTimeout that, when it is due while `holdOn()`, waits another `ms` (up to the sandbox setup limit). */
+function holdingTimeout(ms: number, holdOn: (() => boolean) | null, fire: () => void): () => void {
+ const startedAt = Date.now();
+ let timer: ReturnType<typeof setTimeout>;
+ const due = () => {
+ if (holdOn?.() && Date.now() - startedAt < SANDBOX_SETUP_HOLD_MAX_MS) timer = setTimeout(due, ms);
+ else fire();
+ };
+ timer = setTimeout(due, ms);
+ return () => clearTimeout(timer);
+}
+
async function fetchWithTimeout(
fetchImpl: typeof globalThis.fetch,
input: RequestInfo | URL,
@@ -228,16 +264,18 @@ async function fetchWithTimeout(
const signal = controller?.signal;
const initWithSignal = signal && !init?.signal ? { ...(init ?? {}), signal } : init;
- let timeoutId: ReturnType<typeof setTimeout> | null = null;
+ let clearDeadline = (): void => {};
+ const url = getRequestUrl(input);
+ const holdOn = SESSION_PROMPT_ASYNC_URL_RE.test(url) ? () => promptHeldForSandbox(url) : null;
const timeoutPromise = new Promise<never>((_, reject) => {
- timeoutId = setTimeout(() => {
+ clearDeadline = holdingTimeout(effectiveTimeoutMs, holdOn, () => {
try {
controller?.abort();
} catch {
// ignore
}
reject(new Error("Request timed out."));
- }, effectiveTimeoutMs);
+ });
});
try {
@@ -258,7 +296,7 @@ async function fetchWithTimeout(
}
throw error;
} finally {
- if (timeoutId) clearTimeout(timeoutId);
+ clearDeadline();
}
}
@@ -410,7 +448,7 @@ export function createClient(baseUrl: string, directory?: string, auth?: Opencod
directory: requestDirectory ?? directory,
throwOnError: options?.throwOnError,
signal,
- }), () => new PromptAdmissionUnknownError({ messageID: parameters.messageID }));
+ }), () => new PromptAdmissionUnknownError({ messageID: parameters.messageID }), () => promptHeldForSandbox(`${baseUrl}/session/`));
} catch (error) {
if (isPromptAdmissionUnknown(error)) {
throw new PromptAdmissionUnknownError({ cause: error, messageID: parameters.messageID });
@@ -436,19 +474,19 @@ export function createClient(baseUrl: string, directory?: string, auth?: Opencod
}
/** Includes body consumption: receiving headers alone cannot release a send lock. */
-async function withAdmissionDeadline<T>(timeoutMs: number, operation: (signal: AbortSignal) => Promise<T>, timeoutError: () => Error): Promise<T> {
+async function withAdmissionDeadline<T>(timeoutMs: number, operation: (signal: AbortSignal) => Promise<T>, timeoutError: () => Error, holdOn: (() => boolean) | null = null): Promise<T> {
const controller = new AbortController();
- let timer: ReturnType<typeof setTimeout> | undefined;
+ let clearDeadline: (() => void) | undefined;
const deadline = new Promise<never>((_, reject) => {
- timer = setTimeout(() => {
+ clearDeadline = holdingTimeout(timeoutMs, holdOn, () => {
reject(timeoutError());
controller.abort();
- }, timeoutMs);
+ });
});
try {
return await Promise.race([operation(controller.signal), deadline]);
} finally {
- clearTimeout(timer);
+ clearDeadline?.();
}
}
diff --git a/apps/app/src/react-app/domains/settings/linux-sandbox.ts b/apps/app/src/react-app/domains/settings/linux-sandbox.ts
index 7f2406b2..99e34da9 100644
--- a/apps/app/src/react-app/domains/settings/linux-sandbox.ts
+++ b/apps/app/src/react-app/domains/settings/linux-sandbox.ts
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { captureAnalyticsEvent, type AnalyticsProperties } from "@/app/lib/analytics";
+import { setSandboxSetupHold } from "@/app/lib/opencode";
import type { OmniRushServerClient, OmniRushWorkspaceBox, OmniRushWorkspaceBoxProgress, OmniRushWorkspaceBoxSetupAction } from "@/app/lib/omnirush-server";
export type LinuxSandboxClient = Pick<OmniRushServerClient, "getWorkspaceBox" | "setWorkspaceBox" | "setWorkspaceBoxBackend" | "resetWorkspaceBox" | "retryWorkspaceBox"> & Partial<Pick<OmniRushServerClient, "setupWorkspaceBox">>;
@@ -212,6 +213,11 @@ export type LinuxSandboxProblem = { message: string; retry: (() => void) | null
* while it moves, and when the window comes back), the switch (shown at
* once, before the server answers), the backend, Retry and Reset.
*/
+/** Whether the local server holds a new chat's prompt for this box (box/service.ts waitForBox): required, on, downloading or starting. */
+export function sandboxSetupHolds(box: Pick<OmniRushWorkspaceBox, "required" | "on" | "state"> | null): boolean {
+ return Boolean(box?.required && box.on && (box.state === "downloading" || box.state === "starting"));
+}
+
export function useLinuxSandbox(client: LinuxSandboxClient | null, workspaceId: string | null, { fresh: freshOnOpen = true, sessionId = null }: { fresh?: boolean; sessionId?: string | null } = {}) {
const [box, setBox] = useState<OmniRushWorkspaceBox | null>(null);
const [pending, setPending] = useState<LinuxSandboxPending>(null);
@@ -255,6 +261,11 @@ export function useLinuxSandbox(client: LinuxSandboxClient | null, workspaceId:
if (boxFor.current === workspaceId) reportSandboxFallback(workspaceId, box);
}, [box, workspaceId]);
+ // The local server holds this project's prompts while its required box is set up: a send then waits, not "unknown".
+ useEffect(() => {
+ if (workspaceId && boxFor.current === workspaceId) setSandboxSetupHold(workspaceId, sandboxSetupHolds(box));
+ }, [box, workspaceId]);
+
// While it moves: every second for a minute, then every 3 s.
const moving = linuxSandboxMoving(box);
useEffect(() => {
diff --git a/apps/app/tests/opencode-stream-timeout.test.ts b/apps/app/tests/opencode-stream-timeout.test.ts
index 0076fdae..1bf6747a 100644
--- a/apps/app/tests/opencode-stream-timeout.test.ts
+++ b/apps/app/tests/opencode-stream-timeout.test.ts
@@ -11,7 +11,7 @@ mock.module("@opencode-ai/sdk/v2/client", () => ({
},
}));
-const { createClient, createPromptMessageID, PromptAdmissionUnknownError, hasAcceptedPromptMessage } = await import("../src/app/lib/opencode");
+const { createClient, createPromptMessageID, PromptAdmissionUnknownError, hasAcceptedPromptMessage, setSandboxSetupHold, promptHeldForSandbox } = await import("../src/app/lib/opencode");
const originalWindow = globalThis.window;
const originalFetch = globalThis.fetch;
@@ -170,6 +170,35 @@ describe("OpenCode transport timeouts", () => {
}
});
+ test("a prompt held by the sandbox setup waits past 30 seconds; it is unknown only once the setup is over", async () => {
+ jest.useFakeTimers();
+ installWindow({ __OMNIRUSH_ELECTRON__: {} });
+ const { cancel, observedSignal, attempts } = installControllableFetch();
+ const fetchImpl = createCapturedFetch();
+ const url = "http://127.0.0.1:8788/workspace/ws_box/opencode/session/ses_send/prompt_async";
+ expect(promptHeldForSandbox(url)).toBe(false);
+ setSandboxSetupHold("ws_box", true);
+ expect(promptHeldForSandbox(url)).toBe(true);
+ expect(promptHeldForSandbox("http://127.0.0.1:8788/workspace/ws_other/opencode/session/s/prompt_async")).toBe(false);
+ const response = fetchImpl(new Request(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }));
+ const state = trackPromise(response);
+ const errorPromise = response.catch((error: unknown) => error);
+ try {
+ jest.advanceTimersByTime(10 * 60_000);
+ await Promise.resolve();
+ expect(state()).toBe("pending");
+ expect(observedSignal()?.aborted).toBe(false);
+ // The box is ready (or the setup failed): the next deadline decides as before.
+ setSandboxSetupHold("ws_box", false);
+ jest.advanceTimersByTime(30_000);
+ expect(await errorPromise).toBeInstanceOf(PromptAdmissionUnknownError);
+ expect(attempts()).toBe(1);
+ } finally {
+ setSandboxSetupHold("ws_box", false);
+ cancel();
+ }
+ });
+
test("keeps synchronous command and summarize requests untimed", async () => {
jest.useFakeTimers();
installWindow(undefined);