A desktop coding agent with free access to frontier models.
TypeScript
fix: a stopped send does not count as a turn
ogsamratb9089ea4d809
diff --git a/apps/server/src/box/box-required-service.test.ts b/apps/server/src/box/box-required-service.test.tsindex 6f789e3a..6dcca453 100644--- a/apps/server/src/box/box-required-service.test.ts+++ b/apps/server/src/box/box-required-service.test.ts@@ -278,11 +278,43 @@ describe("required sandbox: a stopped send", () => {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;+ // Nothing more runs for the stopped prompt.const before = tries;await new Promise((resolve) => setTimeout(resolve, 1_200));expect(tries).toBe(before);expect(frozen).toEqual([]);++ // The retry is still the chat's first prompt: it waits for the box (no native "old chat"), and+ // goes on only once the box is ready.+ let retried = false;+ const retry = boxes.beforePrompt("ses_req_stop1", workspace).then((info) => { retried = true; return info; });+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(retried).toBe(false);+ expect((Reflect.get(boxes, "nativeChats") as Map<string, string>).has("ses_req_stop1")).toBe(false);+ ready = true;+ await retry;+ expect(frozen).toEqual(["ses_req_stop1 turn-1"]);+ expect((Reflect.get(boxes, "chatTurns") as Map<string, number>).get("ses_req_stop1")).toBe(1);+ });++ test("a prompt refused before the engine after its checkpoint counts as no turn; a chat that really ran here stays native", async () => {+ const stateDir = await temp("state");+ const root = await temp("project");+ const workspace: BoxWorkspace = { id: "ws_undo", 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[] = [];+ boxes.ensure = async () => fakeRun(root, frozen);+ await boxes.beforePrompt("ses_req_undo1", workspace);+ // The server stopped it before dispatch (send_stopped): undone.+ boxes.promptCancelled("ses_req_undo1");+ expect((Reflect.get(boxes, "chatTurns") as Map<string, number>).has("ses_req_undo1")).toBe(false);+ expect((Reflect.get(boxes, "boxedChats") as Set<string>).has("ses_req_undo1")).toBe(false);+ await boxes.beforePrompt("ses_req_undo1", workspace);+ expect((Reflect.get(boxes, "chatTurns") as Map<string, number>).get("ses_req_undo1")).toBe(1);+ expect((Reflect.get(boxes, "nativeChats") as Map<string, string>).has("ses_req_undo1")).toBe(false);+ // A chat with earlier turns on this machine (no checkpoint) still stays native.+ await boxes.beforePrompt("ses_req_undo_old", workspace, { turnsBefore: 2 });+ expect((Reflect.get(boxes, "nativeChats") as Map<string, string>).has("ses_req_undo_old")).toBe(true);});});diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.tsindex d90f07b8..5bee0175 100644--- a/apps/server/src/box/service.ts+++ b/apps/server/src/box/service.ts@@ -215,6 +215,8 @@ export class BoxService {private readonly turns = new Map<string, number>();/** Each chat's turn number as of its last prompt here (its turns before this run, then one per prompt). */private readonly chatTurns = new Map<string, number>();+ /** Per chat, its counts before the prompt beforePrompt last saw (promptCancelled puts them back). */+ private readonly uncommitted = new Map<string, { chatTurns: number | undefined; boxed: boolean; turns: number | undefined }>();/** Chats (and their project's key) that ran on this machine before the server's default turned the box on: they stay here. */private readonly nativeChats = new Map<string, string>();/** Chats sent to their project's box in this run (a failed checkpoint included). */@@ -779,6 +781,22 @@ export class BoxService {* label returned for its uploads. Null when the chat runs natively. Never* throws; waits at most FREEZE_WAIT_MS.*/+ /**+ * A prompt beforePrompt saw was not dispatched (stopped, refused before the+ * engine): the chat's turn count, its in-the-box mark and turn number go back+ * to what they were, so the next prompt is classified as this one was.+ */+ promptCancelled(sessionId: string): void {+ const before = this.uncommitted.get(sessionId);+ if (!before) return;+ this.uncommitted.delete(sessionId);+ if (before.chatTurns === undefined) this.chatTurns.delete(sessionId);+ else this.chatTurns.set(sessionId, before.chatTurns);+ if (!before.boxed) this.boxedChats.delete(sessionId);+ if (before.turns === undefined) this.turns.delete(sessionId);+ else this.turns.set(sessionId, before.turns);+ }+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@@ -786,6 +804,8 @@ export class BoxService {// turn; the checkpoint names it as session_turn (CLI: the same).const turnsSoFar = this.chatTurns.get(sessionId) ?? turnsBefore;const chatTurn = capture ? turnsSoFar + 1 : 0;+ // What this prompt counts as "the chat has run": undone if it never reaches the engine (promptCancelled).+ this.uncommitted.set(sessionId, { chatTurns: this.chatTurns.get(sessionId), boxed: this.boxedChats.has(sessionId), turns: this.turns.get(sessionId) });if (capture) this.chatTurns.set(sessionId, chatTurn);// Required: a new chat waits for its project's box (the download, the start) instead of starting here;// a chat that already ran on this machine stays here, without waiting.@@ -797,8 +817,12 @@ export class BoxService {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, 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;+ // The send was stopped while it waited: no checkpoint, the caller does not dispatch it, and the+ // chat counts as not having run this turn (a retry waits for the box again).+ if (signal?.aborted) {+ this.promptCancelled(sessionId);+ 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 defaultdiff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex cce3466b..8d483f15 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -1954,8 +1954,9 @@ 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 {+/** A send its user stopped before it reached the engine (held for the sandbox): never dispatched, and not counted as a turn of its chat. */+function stoppedSendResponse(config: ServerConfig, sessionId: string | null | undefined): Response {+ if (sessionId) boxServiceFor(config).promptCancelled(sessionId);return jsonResponse({ code: "send_stopped", message: "The send was stopped before it reached the engine." }, 409);}@@ -2127,7 +2128,7 @@ export async function proxyOpencodeV2Request(input: {const boxInfo = promptDispatch && sessionId? 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 (promptDispatch && input.request.signal.aborted) return stoppedSendResponse(input.config, sessionId);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@@ -2146,7 +2147,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();+ if (promptDispatch && input.request.signal.aborted) return stoppedSendResponse(input.config, sessionId);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();@@ -2569,7 +2570,9 @@ export async function proxyOpencodeRequest(input: {? 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();+ // The chat whose turn beforePrompt counted for this request (undone when it is stopped before the engine).+ const boxSession = workspace && uploadedSessionId && isUploadPromptDispatch(method, proxyPath) ? uploadedSessionId : null;+ if (dispatch && input.request.signal.aborted) return stoppedSendResponse(input.config, boxSession);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@@ -2677,7 +2680,7 @@ export async function proxyOpencodeRequest(input: {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();+ if (dispatch && input.request.signal.aborted) return stoppedSendResponse(input.config, boxSession);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 };