A desktop coding agent with free access to frontier models.
TypeScript
fix: stop cancels a send waiting for the sandbox
ogsamrat0a50b7b72dd1
diff --git a/apps/app/src/app/lib/opencode-interruption.ts b/apps/app/src/app/lib/opencode-interruption.tsindex 240e2cd5..9bc59c42 100644--- a/apps/app/src/app/lib/opencode-interruption.ts+++ b/apps/app/src/app/lib/opencode-interruption.ts@@ -1,5 +1,5 @@import type { Client } from "../types";-import { isPromptAdmissionUnknown, unwrap } from "./opencode";+import { isPromptAdmissionUnknown, promptHeldForSandbox, stopHeldSend, unwrap } from "./opencode";type Submission = {messageID?: string;@@ -81,6 +81,11 @@ export function interruptSessionTurn(turn.stopping = true;turn.needsStop = true;const pending = [...turn.submissions];+ // A send the local server still holds for the sandbox setup is given up now: its request+ // is aborted (the server never dispatches it) and it settles at once, so Stop does not wait on it.+ if (promptHeldForSandbox(`${baseUrl.replace(/\/+$/, "")}/session/`)) {+ for (const submission of pending) if (!submission.settled && submission.messageID) stopHeldSend(submission.messageID);+ }const controller = new AbortController();const timer = setTimeout(() => controller.abort(new Error("Stopping the previous turn timed out. Retry Stop before sending.")), options.timeoutMs ?? 15_000);const deadline = new Promise<never>((_, reject) => {diff --git a/apps/app/src/app/lib/opencode.ts b/apps/app/src/app/lib/opencode.tsindex 226eb88b..f87d801e 100644--- a/apps/app/src/app/lib/opencode.ts+++ b/apps/app/src/app/lib/opencode.ts@@ -84,6 +84,33 @@ export function isPromptAdmissionUnknown(error: unknown): error is PromptAdmissireturn error instanceof PromptAdmissionUnknownError;}+/** A send its user stopped while the local server held it (sandbox setup): given up on purpose, never replayed. */+export class SendStoppedError extends Error {+ constructor() {+ super("Send cancelled by Stop.");+ this.name = "SendStoppedError";+ }+}++export function isSendStopped(error: unknown): error is SendStoppedError {+ return error instanceof SendStoppedError;+}++/** In-flight prompt sends by message ID: Stop gives up a held one (stopHeldSend). */+const stoppableSends = new Map<string, () => void>();++/**+ * Gives up the send of `messageID` while its request is still open: the+ * request is aborted (the local server stops holding it and never dispatches+ * it) and the send rejects at once with SendStoppedError. False when it is+ * not in flight.+ */+export function stopHeldSend(messageID: string): boolean {+ const stop = stoppableSends.get(messageID);+ stop?.();+ return Boolean(stop);+}+let lastMessageStamp = 0;/** Native sortable msg_ format. This identifies a submission, NOT an idempotency key. */@@ -448,7 +475,7 @@ export function createClient(baseUrl: string, directory?: string, auth?: Opencoddirectory: requestDirectory ?? directory,throwOnError: options?.throwOnError,signal,- }), () => new PromptAdmissionUnknownError({ messageID: parameters.messageID }), () => promptHeldForSandbox(`${baseUrl}/session/`));+ }), () => new PromptAdmissionUnknownError({ messageID: parameters.messageID }), () => promptHeldForSandbox(`${baseUrl}/session/`), parameters.messageID);} catch (error) {if (isPromptAdmissionUnknown(error)) {throw new PromptAdmissionUnknownError({ cause: error, messageID: parameters.messageID });@@ -474,19 +501,26 @@ 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, holdOn: (() => boolean) | null = null): Promise<T> {+async function withAdmissionDeadline<T>(timeoutMs: number, operation: (signal: AbortSignal) => Promise<T>, timeoutError: () => Error, holdOn: (() => boolean) | null = null, stopKey?: string): Promise<T> {const controller = new AbortController();let clearDeadline: (() => void) | undefined;+ let stop: (() => void) | undefined;const deadline = new Promise<never>((_, reject) => {clearDeadline = holdingTimeout(timeoutMs, holdOn, () => {reject(timeoutError());controller.abort();});+ stop = () => {+ reject(new SendStoppedError());+ controller.abort();+ };});+ if (stopKey && stop) stoppableSends.set(stopKey, stop);try {return await Promise.race([operation(controller.signal), deadline]);} finally {clearDeadline?.();+ if (stopKey && stoppableSends.get(stopKey) === stop) stoppableSends.delete(stopKey);}}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 935560d5..dbcc38f5 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@@ -9,7 +9,7 @@ import { toast } from "@/components/ui/sonner";import { captureAnalyticsEvent } from "@/app/lib/analytics";import { useUpdateGateBlocked } from "@/app/lib/update-gate";import { interruptSessionTurn, sessionNeedsStop, submitAfterInterruption, subscribeSessionInterruption } from "@/app/lib/opencode-interruption";-import { createClient, createPromptMessageID, hasAcceptedPromptMessage, isPromptAdmissionUnknown, unwrap } from "@/app/lib/opencode";+import { createClient, createPromptMessageID, hasAcceptedPromptMessage, isPromptAdmissionUnknown, isSendStopped, unwrap } from "@/app/lib/opencode";import { compactSession } from "@/app/lib/opencode-session";import { createClientV2, isOpencodeV2BaseUrl } from "@/app/lib/opencode-v2-adapter";import * as opencodeSessionNative from "@/app/lib/opencode-session-native";@@ -2263,8 +2263,10 @@ export function SessionSurface(props: SessionSurfaceProps) {if (activeSessionOwnerRef.current === sessionOwner) setAwaitingAssistantBaseline(null);return { outcome: "unknown" };}- if (getQueuedSendGeneration(props.sessionId) !== generation) {+ // Stopped on purpose (or the context moved on): released at once, never sent again.+ if (isSendStopped(nextError) || getQueuedSendGeneration(props.sessionId) !== generation) {dispatchQueuedDrain(props.sessionId, { type: "send_result", itemId, outcome: "cancelled", at: Date.now() });+ if (activeSessionOwnerRef.current === sessionOwner) setAwaitingAssistantBaseline(null);return { outcome: "cancelled", reason: "context_changed" };}dispatchQueuedDrain(props.sessionId, { type: "send_error", itemId });diff --git a/apps/app/src/react-app/domains/session/sync/global-queue-drainer.ts b/apps/app/src/react-app/domains/session/sync/global-queue-drainer.tsindex 4503cea5..8b5cf680 100644--- a/apps/app/src/react-app/domains/session/sync/global-queue-drainer.ts+++ b/apps/app/src/react-app/domains/session/sync/global-queue-drainer.ts@@ -2,7 +2,7 @@ import type { SessionStatus } from "@opencode-ai/sdk/v2/client";import { isSessionReverted } from "./reverted-sessions";import { markTaskRunStart } from "@/app/lib/analytics";-import { createClient, createPromptMessageID, hasAcceptedPromptMessage, isPromptAdmissionUnknown } from "@/app/lib/opencode";+import { createClient, createPromptMessageID, hasAcceptedPromptMessage, isPromptAdmissionUnknown, isSendStopped } from "@/app/lib/opencode";import { shellInSession } from "@/app/lib/opencode-session";import { submitAfterInterruption } from "@/app/lib/opencode-interruption";import { createClientV2, isOpencodeV2BaseUrl } from "@/app/lib/opencode-v2-adapter";@@ -380,7 +380,8 @@ async function attemptDrain(sessionId: string) {type: "send_unknown", itemId: nextItem.id, messageID: draft.messageId, at: Date.now(),});draft.attachments.forEach(revokeAttachmentPreview);- } else if (getQueuedSendGeneration(sessionId) !== generation) {+ } else if (isSendStopped(error) || getQueuedSendGeneration(sessionId) !== generation) {+ // Stopped on purpose (or the context moved on): never sent again.dispatchQueuedDrain(sessionId, { type: "send_result", itemId: nextItem.id, outcome: "cancelled", at: Date.now() });draft.attachments.forEach(revokeAttachmentPreview);} else {diff --git a/apps/app/tests/sandbox-held-stop.test.ts b/apps/app/tests/sandbox-held-stop.test.tsnew file mode 100644index 00000000..176ed73b--- /dev/null+++ b/apps/app/tests/sandbox-held-stop.test.ts@@ -0,0 +1,66 @@+import { describe, expect, test } from "bun:test";+import type { Session } from "@opencode-ai/sdk/v2/client";++import { createClient, createPromptMessageID, isSendStopped, setSandboxSetupHold } from "../src/app/lib/opencode";+import { interruptSessionTurn, sessionNeedsStop, submitAfterInterruption } from "../src/app/lib/opencode-interruption";++const baseUrl = "https://worker.example/workspace/ws-held/opencode";+const root = { id: "ses_held_stop", projectID: "p", directory: "/workspace/held", title: "t", version: "1", time: { created: 1, updated: 2 } } as Session;++describe("a send held for the sandbox setup", () => {+ test("Stop releases it at once, and the prompt never reaches the engine, even once the box is ready", async () => {+ const boxReady = Promise.withResolvers<void>();+ const engineCalls: string[] = [];+ let held: Request | null = null;+ const originalFetch = globalThis.fetch;+ Object.defineProperty(globalThis, "fetch", {+ configurable: true,+ value: (input: RequestInfo | URL, init?: RequestInit) => {+ const request = new Request(input, init);+ const path = new URL(request.url).pathname;+ if (path.endsWith("/prompt_async")) {+ // The local server holds the prompt until the box is ready, unless the request is given up first.+ held = request;+ return new Promise<Response>((resolve, reject) => {+ request.signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true });+ void boxReady.promise.then(() => {+ if (request.signal.aborted) return;+ engineCalls.push(path);+ resolve(new Response(null, { status: 204 }));+ });+ });+ }+ if (path.endsWith(`/session/${root.id}`)) return Promise.resolve(Response.json(root));+ if (path.endsWith("/message")) return Promise.resolve(Response.json([]));+ if (path.endsWith("/abort")) return Promise.resolve(Response.json(true));+ if (path.endsWith("/status")) return Promise.resolve(Response.json({}));+ return Promise.reject(new Error(`Unexpected request: ${request.method} ${path}`));+ },+ });+ setSandboxSetupHold("ws-held", true);+ try {+ const client = createClient(baseUrl, root.directory);+ const messageID = createPromptMessageID();+ const send = submitAfterInterruption(baseUrl, root.id, () => client.session.promptAsync({+ sessionID: root.id, directory: root.directory, messageID, parts: [{ type: "text", text: "hi" }],+ } as never), messageID);+ const sent = send.then(() => null, (error: unknown) => error);+ for (let i = 0; i < 50 && !held; i += 1) await new Promise((resolve) => setTimeout(resolve, 5));+ expect(held).not.toBeNull();++ const started = Date.now();+ await interruptSessionTurn(baseUrl, client, root.id, root.directory, { timeoutMs: 15_000 });+ expect(Date.now() - started).toBeLessThan(2_000);+ expect(isSendStopped(await sent)).toBe(true);+ expect(held!.signal.aborted).toBe(true);+ expect(sessionNeedsStop(baseUrl, root.id)).toBe(false);++ boxReady.resolve();+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(engineCalls).toEqual([]);+ } finally {+ setSandboxSetupHold("ws-held", false);+ globalThis.fetch = originalFetch;+ }+ });+});diff --git a/apps/server/src/box/box-required-service.test.ts b/apps/server/src/box/box-required-service.test.tsindex 960a31a5..6f789e3a 100644--- a/apps/server/src/box/box-required-service.test.ts+++ b/apps/server/src/box/box-required-service.test.ts@@ -250,3 +250,39 @@ describe("required sandbox: the desktop's projects", () => {expect(await boxes.planOutcome("ses_old_srv1", workspace)).toEqual({ native: true, source: "project", reason: "off" });});});++describe("required sandbox: a stopped send", () => {+ test("a held prompt whose request is given up stops waiting at once and takes no checkpoint", async () => {+ const stateDir = await temp("state");+ const root = await temp("project");+ const workspace: BoxWorkspace = { id: "ws_stop", path: root, workspaceType: "local" };+ rememberServerDefault(stateDir, { local_box: { default: "on", required: true } });+ const boxes = service({ stateDir, workspaces: [workspace], env: { OMNIRUSH_BOX_HOME: await temp("boxhome") } });+ const frozen: string[] = [];+ const projects: unknown = Reflect.get(boxes, "projects");+ if (!(projects instanceof Map)) throw new Error("no projects map");+ let ready = false;+ let tries = 0;+ boxes.ensure = async () => {+ tries += 1;+ if (!ready) {+ projects.set(boxKey(root), { run: null, notice: "downloading", planning: null, nextPlanAt: 0, waitingImage: true, why: { reason: "downloading" } });+ return null;+ }+ return fakeRun(root, frozen);+ };+ const stop = new AbortController();+ const started = Date.now();+ const waiting = boxes.beforePrompt("ses_req_stop1", workspace, { signal: stop.signal });+ await new Promise((resolve) => setTimeout(resolve, 100));+ stop.abort();+ expect(await waiting).toBeNull();+ expect(Date.now() - started).toBeLessThan(1_000);+ // The box becomes ready afterwards: nothing runs for the stopped prompt.+ ready = true;+ const before = tries;+ await new Promise((resolve) => setTimeout(resolve, 1_200));+ expect(tries).toBe(before);+ expect(frozen).toEqual([]);+ });+});diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.tsindex 426cb1e6..d90f07b8 100644--- a/apps/server/src/box/service.ts+++ b/apps/server/src/box/service.ts@@ -779,7 +779,7 @@ export class BoxService {* label returned for its uploads. Null when the chat runs natively. Never* throws; waits at most FREEZE_WAIT_MS.*/- async beforePrompt(sessionId: string, workspace: BoxWorkspace, { capture = true, turnsBefore = 0 }: { capture?: boolean; turnsBefore?: number } = {}): Promise<BoxCaptureInfo | null> {+ async beforePrompt(sessionId: string, workspace: BoxWorkspace, { capture = true, turnsBefore = 0, signal }: { capture?: boolean; turnsBefore?: number; signal?: AbortSignal } = {}): Promise<BoxCaptureInfo | null> {if (!/^[A-Za-z0-9._:-]{8,128}$/.test(sessionId)) return null;// The chat's own turn number, counted with the box on or off: a chat that ran natively// (reopened, or its box turned on mid-chat) has its first checkpoint (turn-1) before a later@@ -796,7 +796,9 @@ export class BoxService {await this.writeProjects();this.log("info", "box: a chat that ran on this machine stays there", { sessionId, turnsBefore, required: true });}- const run = required && !this.nativeChats.has(sessionId) ? await this.waitForBox(workspace) : await this.ensure(workspace).catch(() => null);+ const run = required && !this.nativeChats.has(sessionId) ? await this.waitForBox(workspace, signal) : await this.ensure(workspace).catch(() => null);+ // The send was stopped while it waited: no checkpoint, and the caller does not dispatch it.+ if (signal?.aborted) return null;if (!run || run.native) return null;// A chat with turns but no checkpoint ran on this machine (reopened, or started in this run before the// server's default reached the app, or while the image downloaded): when only the server's default@@ -836,12 +838,14 @@ export class BoxService {* when it cannot run here (no backend: the setup screen says why; the* chat goes on per the server's required_fallback).*/- private async waitForBox(workspace: BoxWorkspace): Promise<BoxRun | null> {+ private async waitForBox(workspace: BoxWorkspace, signal?: AbortSignal): Promise<BoxRun | null> {const key = boxKey(boxRoot(workspace));const startedAt = Date.now();let lastProgressAt = startedAt;let said = false;for (;;) {+ // A stopped send stops waiting at once (its request was given up).+ if (signal?.aborted) return null;const run = await this.ensure(workspace).catch(() => null);if (run) return run;const project = this.projects.get(key);@@ -858,7 +862,16 @@ export class BoxService {said = true;this.log("info", "required sandbox: the prompt waits for the first setup", { maxMin: Math.round(REQUIRED_SETUP_MAX_MS / 60_000) });}- await new Promise((resolve) => setTimeout(resolve, REQUIRED_POLL_MS));+ await new Promise<void>((resolve) => {+ const timer = setTimeout(done, REQUIRED_POLL_MS);+ function done() {+ clearTimeout(timer);+ signal?.removeEventListener("abort", done);+ resolve();+ }+ signal?.addEventListener("abort", done, { once: true });+ });+ if (signal?.aborted) return null;if (pull && !pulling(this.home, pull.runtime, pull.image.pull)) project.nextPlanAt = 0;}}diff --git a/apps/server/src/opencode-proxy.e2e.test.ts b/apps/server/src/opencode-proxy.e2e.test.tsindex c7962c9a..c118e2e8 100644--- a/apps/server/src/opencode-proxy.e2e.test.ts+++ b/apps/server/src/opencode-proxy.e2e.test.ts@@ -483,6 +483,43 @@ describe("workspace OpenCode proxy", () => {expect(await readFile(commandPath, "utf8")).toBe(legacyCommand);});+ test.serial("a prompt whose request was given up while it was held never reaches the engine", async () => {+ const workspaceRoot = await createWorkspaceRoot();+ const engineUrl = "http://127.0.0.1:4333";+ const workspace: WorkspaceInfo = { id: "ws_stopped", name: "Workspace", path: workspaceRoot, preset: "starter", workspaceType: "local", baseUrl: engineUrl };+ const config: ServerConfig = {+ host: "127.0.0.1", port: 0, token: "owt_test_token", hostToken: "owt_host_token",+ approval: { mode: "auto", timeoutMs: 1_000 }, corsOrigins: ["*"], workspaces: [workspace], authorizedRoots: [workspaceRoot],+ readOnly: false, startedAt: Date.now(), tokenSource: "cli", hostTokenSource: "cli", logFormat: "pretty", logRequests: false,+ };+ const originalFetch = globalThis.fetch;+ const engineCalls: string[] = [];+ globalThis.fetch = Object.assign(+ (input: Parameters<typeof fetch>[0]) => {+ engineCalls.push(input instanceof Request ? input.url : String(input));+ return Promise.resolve(new Response(null, { status: 204 }));+ },+ { preconnect: originalFetch.preconnect },+ );+ try {+ for (const route of ["prompt_async", "command"]) {+ const proxyPath = `/session/ses_stopped/${route}`;+ const url = new URL(`http://omnirush.invalid/opencode${proxyPath}`);+ const stopped = new AbortController();+ stopped.abort();+ const response = await proxyOpencodeRequest({+ config, workspace, proxyPath, url,+ request: new Request(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messageID: `msg_${route}`, parts: [{ type: "text", text: "hi" }], command: "review", arguments: "" }), signal: stopped.signal }),+ });+ expect(response.status).toBe(409);+ expect(await response.json()).toMatchObject({ code: "send_stopped" });+ }+ expect(engineCalls.filter((call) => /prompt_async|\/command/.test(call))).toEqual([]);+ } finally {+ globalThis.fetch = originalFetch;+ }+ });+test.serial("acknowledges proxied session commands before upstream completion and admits each message once", async () => {const workspaceRoot = await createWorkspaceRoot();const engineUrl = "http://127.0.0.1:4111";diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 4bbca5cb..cce3466b 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -1954,6 +1954,11 @@ function lateWritesGate(workspace: WorkspaceInfo, enginePids: ReadonlyArray<numb* session, captures the prompt snapshot, traces the request and response and* observes the turn until it settles. Exported for the mount's tests.*/+/** A send its user stopped before it reached the engine (held for the sandbox): never dispatched. */+function stoppedSendResponse(): Response {+ return jsonResponse({ code: "send_stopped", message: "The send was stopped before it reached the engine." }, 409);+}+export async function proxyOpencodeV2Request(input: {config: ServerConfig;request: Request;@@ -2120,8 +2125,9 @@ export async function proxyOpencodeV2Request(input: {const turnsBefore = capture && uploadedSessionId && engine ? await turnsBeforeCapture(capture, uploadedSessionId, engine) : 0;// The Linux sandbox (box/): a prompt of a workspace whose box is on starts the box, and takes the turn's checkpoint when it is captured.const boxInfo = promptDispatch && sessionId- ? await boxServiceFor(input.config).beforePrompt(sessionId, input.workspace, { capture: Boolean(uploadedSessionId && engine), turnsBefore })+ ? await boxServiceFor(input.config).beforePrompt(sessionId, input.workspace, { capture: Boolean(uploadedSessionId && engine), turnsBefore, signal: input.request.signal }): null;+ if (promptDispatch && input.request.signal.aborted) return stoppedSendResponse();if (capture && uploadedSessionId && engine) {// The turn before's background processes finish writing (at most 10 s after it ended), its project// delta is taken (at most 5 s more, only when it ended a moment ago), then capture v2's session-start@@ -2140,6 +2146,7 @@ export async function proxyOpencodeV2Request(input: {if (input.workspace.task && promptDispatch && sessionId) {await noteTaskPrompt(input.workspace, sessionId, (id, type, data) => recordOpenSessionTrace(input.config, id, type, data));}+ if (promptDispatch && input.request.signal.aborted) return stoppedSendResponse();const response = await loopbackFetch(target.toString(), { method, headers, body, signal: input.recoverySignal });// The engine has the prompt: its session status says busy from now on.turnActivity?.promptDispatched();@@ -2559,8 +2566,10 @@ export async function proxyOpencodeRequest(input: {? await turnsBeforeCapture(capture, uploadedSessionId, engineTarget(baseUrl, headers, search)): 0;const boxInfo = workspace && uploadedSessionId && isUploadPromptDispatch(method, proxyPath)- ? await boxServiceFor(input.config).beforePrompt(uploadedSessionId, workspace, { capture: captured && !steer, turnsBefore })+ ? await boxServiceFor(input.config).beforePrompt(uploadedSessionId, workspace, { capture: captured && !steer, turnsBefore, signal: input.request.signal }): null;+ const dispatch = isUploadPromptDispatch(method, proxyPath) || isSessionCommandProxyRequest(method, proxyPath);+ if (dispatch && input.request.signal.aborted) return stoppedSendResponse();if (capture && captured && uploadedSessionId && workspace && !steer) {const promptDispatch = isUploadPromptDispatch(method, proxyPath);// The turn before's background processes finish writing (at most 10 s after it ended), its project@@ -2667,6 +2676,8 @@ export async function proxyOpencodeRequest(input: {await reloadOpencodeEngine(input.config, workspace, undefined, { reason: "client_instance_dispose", manual: true });return jsonResponse(true);}+ // Checked again right before the engine: a send stopped while it was held never reaches it.+ if (dispatch && input.request.signal.aborted) return stoppedSendResponse();const targetUrl = buildOpencodeProxyUrl(baseUrl, proxyPath, search);// The engine that answered: a request an engine rollover cut off is sent again to the engine that took over.let served = { baseUrl, headers };