A desktop coding agent with free access to frontier models.
TypeScript
fix: box checkpoints name the chat turn they come before
ogsamratfe60a3de88b9
diff --git a/apps/server/src/box/box.test.ts b/apps/server/src/box/box.test.tsindex 4be1368b..8f9e598d 100644--- a/apps/server/src/box/box.test.ts+++ b/apps/server/src/box/box.test.ts@@ -6,7 +6,7 @@ import { join } from "node:path";import { boxKey, containerName, containerRoot, createArgs, credentialPath, filterChanges, helperPath, installShell, parseDiff, parseSize, rt, setToolsRoot, singleFileTar, wslPath } from "./box.js";import { readBoxSettings } from "./desktop.js";import { detectStack, imageFor } from "./images.js";-import { engineConfig, gcInBackground, mapToBox, rememberServerDefault, resolveMode, serverDefault } from "./launch.js";+import { engineConfig, gcInBackground, mapToBox, rememberServerDefault, resolveMode, serverDefault, type BoxRun } from "./launch.js";import { DESKTOP_PROJECTS_FILE } from "./plugin-lib.js";import { candidates, detectRuntime, explainFailure, probe, probeWsl, wslLauncher, type RunCommand } from "./runtime.js";import { BoxService, type BoxWorkspace } from "./service.js";@@ -262,6 +262,49 @@ describe("box service", () => {expect(await none.engineBits()).toBeNull();});+ test("a chat that ran natively names its turn in each checkpoint (session_turn)", async () => {+ const stateDir = await temp("state");+ const root = await temp("project");+ const workspace: BoxWorkspace = { id: "ws_t", path: root, workspaceType: "local" };+ const env = { OMNIRUSH_BOX_HOME: await temp("boxhome") };+ const frozen: Array<string> = [];+ const run: BoxRun = {+ key: "k", container: "c", runtimeBin: "docker", runtimeArgs: [], backend: "docker", exec: null, root, native: false, box: null,+ ready: async () => null,+ label: () => null,+ setTurn: () => {},+ freeze: async (label, { sessionId, turn = null, sessionTurn = null }) => {+ frozen.push(`${sessionId} ${label} ${sessionTurn}`);+ return { label, turn, copied: 0, carried: 0, save: async () => ({ label, changed: 0, bytes: 0 }), discard: async () => null };+ },+ };+ let on = false;+ const start = () => {+ const boxes = service({ stateDir, workspaces: [workspace], settings: new Map(), env });+ boxes.ensure = async () => (on ? run : null);+ return boxes;+ };+ // Two turns with the box off, a steer (not captured), then the box turned on mid-chat: turn-1 comes before turn 3.+ let boxes = start();+ await boxes.beforePrompt("ses_turns_a1", workspace);+ await boxes.beforePrompt("ses_turns_a1", workspace);+ await boxes.beforePrompt("ses_turns_a1", workspace, { capture: false });+ on = true;+ await boxes.beforePrompt("ses_turns_a1", workspace);+ await boxes.beforePrompt("ses_turns_a1", workspace);+ expect(frozen.splice(0)).toEqual(["ses_turns_a1 turn-1 3", "ses_turns_a1 turn-2 4"]);+ // Reopened after a restart with 4 native turns: before turns 5 and 6.+ boxes = start();+ await boxes.beforePrompt("ses_turns_b1", workspace, { turnsBefore: 4 });+ await boxes.beforePrompt("ses_turns_b1", workspace);+ expect(frozen.splice(0)).toEqual(["ses_turns_b1 turn-1 5", "ses_turns_b1 turn-2 6"]);+ // Saved checkpoints go on numbering the files; the chat's turn comes from the engine's count.+ await mkdir(join(stateDir, "sandbox", "snapshots", "ses_turns_c1"), { recursive: true });+ await writeFile(join(boxes.snapshotsDir, "ses_turns_c1", "turn-7.json"), "{}");+ await boxes.beforePrompt("ses_turns_c1", workspace, { turnsBefore: 2 });+ expect(frozen.splice(0)).toEqual(["ses_turns_c1 turn-8 3"]);+ });+test("a remote workspace never gets a box", async () => {const stateDir = await temp("state");const workspace: BoxWorkspace = { id: "ws_r", path: "/remote", workspaceType: "remote" };diff --git a/apps/server/src/box/box.ts b/apps/server/src/box/box.tsindex 1bc080e9..96acdca0 100644--- a/apps/server/src/box/box.ts+++ b/apps/server/src/box/box.ts@@ -270,6 +270,8 @@ export type CheckpointSummary = {schema: number;label: string;turn: number | null;+ /** The chat's own turn number of the prompt this checkpoint comes before (when known). */+ session_turn?: number;tar: string | null;bytes: number;sha256: string | null;@@ -467,13 +469,13 @@ export class Box {* `discard()` drops it (a turn that never came). Checkpoints are taken one* at a time. Resolves { summary, commit, discard }.*/- checkpoint(dir: string, turn: number | null, opts: { label?: string | null; leaf?: boolean; deps?: boolean; tarMax?: number; depsMax?: number } = {}): Promise<Checkpoint> {+ checkpoint(dir: string, turn: number | null, opts: { label?: string | null; leaf?: boolean; sessionTurn?: number | null; deps?: boolean; tarMax?: number; depsMax?: number } = {}): Promise<Checkpoint> {const work = this.queue.then(() => this.takeCheckpoint(dir, turn, opts));this.queue = work.catch(() => undefined);return work;}- private async takeCheckpoint(dir: string, turn: number | null, { label: asked = null, leaf = false, deps = this.env.OMNIRUSH_BOX_DEPS !== "off", tarMax = Number(this.env.OMNIRUSH_BOX_TAR_MAX) || TAR_MAX_BYTES, depsMax = Number(this.env.OMNIRUSH_BOX_DEPS_MAX) || DEPS_MAX_BYTES }: { label?: string | null; leaf?: boolean; deps?: boolean; tarMax?: number; depsMax?: number } = {}): Promise<Checkpoint> {+ private async takeCheckpoint(dir: string, turn: number | null, { label: asked = null, leaf = false, sessionTurn = null, deps = this.env.OMNIRUSH_BOX_DEPS !== "off", tarMax = Number(this.env.OMNIRUSH_BOX_TAR_MAX) || TAR_MAX_BYTES, depsMax = Number(this.env.OMNIRUSH_BOX_DEPS_MAX) || DEPS_MAX_BYTES }: { label?: string | null; leaf?: boolean; sessionTurn?: number | null; deps?: boolean; tarMax?: number; depsMax?: number } = {}): Promise<Checkpoint> {if (!this.ready || !this.endpoint) throw new Error(`the sandbox is ${this.state}`);const endpoint = this.endpoint;const t0 = Date.now();@@ -576,6 +578,9 @@ export class Box {schema: RECORD_SCHEMA,label,turn: turn ?? null,+ // The chat's own turn number of this checkpoint's prompt: a chat that ran on this+ // machine before its box was on has its first checkpoint (turn-1) before a later prompt.+ ...(sessionTurn && Number.isInteger(sessionTurn) && sessionTurn > 0 ? { session_turn: sessionTurn } : {}),tar: tarInfo ? `${label}.tar` : null,bytes: tarInfo?.bytes ?? 0,sha256: tarInfo?.sha256 ?? null,diff --git a/apps/server/src/box/launch.ts b/apps/server/src/box/launch.tsindex 1c5ae2c8..8ef64618 100644--- a/apps/server/src/box/launch.ts+++ b/apps/server/src/box/launch.ts@@ -313,7 +313,8 @@ export type BoxRun = {/** environment.sandbox for a chat's uploads; null while it is not (or no longer) the chat's. */label: (sessionId: string) => BoxLabel | null;setTurn: (turn: number) => void;- freeze: (label: string, options: { sessionId: string; turn?: number | null; chain?: string | null }) => Promise<Frozen | null>;+ /** `sessionTurn`: the chat's own number of the prompt the checkpoint comes before (written as session_turn). */+ freeze: (label: string, options: { sessionId: string; turn?: number | null; sessionTurn?: number | null; chain?: string | null }) => Promise<Frozen | null>;};/**@@ -363,13 +364,13 @@ export function boxRun(plan: ReadyPlan, { log = () => {}, readyWaitMs = 30_000,* the checkpoint is taken now and placed by save(); `final` (the state a* chat ends with) is a leaf, so a resumed chat chains on from its last turn.*/- freeze: async (label, { sessionId, turn = null, chain = null }) => {+ freeze: async (label, { sessionId, turn = null, sessionTurn = null, chain = null }) => {const opened = await ready();if (!opened) return null;const n = Number(turn ?? /^turn-(\d+)$/.exec(label)?.[1] ?? 0) || null;const name = n ? `turn-${n}` : label;const dir = chain ?? path.join(pending, `${process.pid}-${Date.now()}`);- const taken = await opened.checkpoint(dir, n, { label: name, leaf: !n });+ const taken = await opened.checkpoint(dir, n, { label: name, leaf: !n, sessionTurn: n ? sessionTurn : null });checkpoints.set(sessionId, (checkpoints.get(sessionId) ?? 0) + 1);const summary: CheckpointSummary = taken.summary;return {diff --git a/apps/server/src/box/service.ts b/apps/server/src/box/service.tsindex 8e26de8f..b4bdb1db 100644--- a/apps/server/src/box/service.ts+++ b/apps/server/src/box/service.ts@@ -122,6 +122,8 @@ export function boxRoot(workspace: BoxWorkspace): string {export class BoxService {private readonly projects = new Map<string, Project>();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>();private readonly home: string;private readonly env: NodeJS.ProcessEnv;private log: BoxLog;@@ -407,8 +409,13 @@ 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 }: { capture?: boolean } = {}): Promise<BoxCaptureInfo | null> {+ async beforePrompt(sessionId: string, workspace: BoxWorkspace, { capture = true, turnsBefore = 0 }: { capture?: boolean; turnsBefore?: number } = {}): 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+ // turn; the checkpoint names it as session_turn (CLI: the same).+ const chatTurn = capture ? (this.chatTurns.get(sessionId) ?? turnsBefore) + 1 : 0;+ if (capture) this.chatTurns.set(sessionId, chatTurn);const run = await this.ensure(workspace).catch(() => null);if (!run || run.native) return null;if (!capture) return null;@@ -416,14 +423,14 @@ export class BoxService {const started = Date.now();try {const frozen = await Promise.race([- run.freeze(`turn-${turn}`, { sessionId, turn, chain: this.snapshotDir(sessionId) }),+ run.freeze(`turn-${turn}`, { sessionId, turn, sessionTurn: chatTurn, chain: this.snapshotDir(sessionId) }),new Promise<null>((resolve) => setTimeout(() => resolve(null), FREEZE_WAIT_MS)),]);if (frozen) {const saved = await frozen.save(this.snapshotDir(sessionId));this.turns.set(sessionId, turn);run.setTurn(turn);- this.log("info", "box checkpoint saved", { sessionId, turn, changed: saved.changed, bytes: saved.bytes, ms: Date.now() - started });+ this.log("info", "box checkpoint saved", { sessionId, turn, sessionTurn: chatTurn, changed: saved.changed, bytes: saved.bytes, ms: Date.now() - started });}} catch (error) {this.log("warn", "box checkpoint failed", { sessionId, turn, error: error instanceof Error ? error.message : String(error) });diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 3adc7091..c58296c4 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -1806,16 +1806,18 @@ export async function proxyOpencodeV2Request(input: {? sessionId: null;const engine = capture && uploadedSessionId ? engineTarget(input.connection.url, headers, target.search, "v2") : null;+ // A reopened chat's turns before this prompt: its turn numbers (uploads and box checkpoints) carry on from them.+ 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) })+ ? await boxServiceFor(input.config).beforePrompt(sessionId, input.workspace, { capture: Boolean(uploadedSessionId && engine), turnsBefore }): null;if (capture && uploadedSessionId && engine) {// The turn before's background processes finish writing (at most 10 s after it ended), then// capture v2's session-start manifest is taken before the prompt reaches the engine (at most about 3 s).await capture.archiveStartGate(uploadedSessionId, input.workspace.path, lateWritesGate(input.workspace));capture.boxSession(uploadedSessionId, boxInfo);- capture.startSession(uploadedSessionId, input.workspace.id, input.workspace.path, await turnsBeforeCapture(capture, uploadedSessionId, engine));+ capture.startSession(uploadedSessionId, input.workspace.id, input.workspace.path, turnsBefore);capture.recordPrompt(uploadedSessionId, { method, path: routePath, body: requestBody, engine: "v2", root: input.workspace.path, attachments: true, dispatchedAt: Date.now() });capture.captureSnapshot(uploadedSessionId, "prompt");capture.archiveSessionStarted(uploadedSessionId, input.workspace.path, engine);@@ -2192,8 +2194,12 @@ export async function proxyOpencodeRequest(input: {const steer = Boolean(turnKind?.steer && uploadedSessionId && capture?.hasSession(uploadedSessionId));if (steer) createServerLogger(input.config).log("info", "Prompt steers the running turn.", { "turn.steer.reason": turnKind?.reason ?? "" });// 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.+ // A reopened chat's turns before this prompt: its turn numbers (uploads and box checkpoints) carry on from them.+ const turnsBefore = capture && captured && uploadedSessionId && workspace && !steer && isUploadPromptDispatch(method, proxyPath)+ ? 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 })+ ? await boxServiceFor(input.config).beforePrompt(uploadedSessionId, workspace, { capture: captured && !steer, turnsBefore }): null;if (capture && captured && uploadedSessionId && workspace && !steer) {const promptDispatch = isUploadPromptDispatch(method, proxyPath);@@ -2201,7 +2207,7 @@ export async function proxyOpencodeRequest(input: {// capture v2's session-start manifest is taken before the prompt reaches the engine (at most about 3 s).if (promptDispatch) await capture.archiveStartGate(uploadedSessionId, workspace.path, lateWritesGate(workspace, pool?.snapshot().generations.map((generation) => generation.pid) ?? []));if (promptDispatch) capture.boxSession(uploadedSessionId, boxInfo);- capture.startSession(uploadedSessionId, workspace.id, workspace.path, promptDispatch ? await turnsBeforeCapture(capture, uploadedSessionId, engineTarget(baseUrl, headers, search)) : 0);+ capture.startSession(uploadedSessionId, workspace.id, workspace.path, turnsBefore);capture.recordPrompt(uploadedSessionId, {method,path: normalizeOpencodeProxyPath(proxyPath),