A desktop coding agent with free access to frontier models.
TypeScript
fix: a chat waiting for the server stays waiting after a restart
ogsamrat9a119b381964
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.tsindex c0d61331..a6b4ad3a 100644--- a/apps/server/src/capture-client.ts+++ b/apps/server/src/capture-client.ts@@ -93,8 +93,8 @@ export type CaptureService = {sessionPolicy(sessionId: string): Promise<string | null>;/** The capture policy the server's binding keeps for the chat: its uploads follow it. */pinPolicy(sessionId: string, policy: string): void;- /** Strict sessions under enforce: hold the chat's uploads until its binding is confirmed (held=false releases). */- holdUploads(sessionId: string, held: boolean): void;+ /** Strict sessions under enforce: hold the chat's uploads until its binding is confirmed ("refused" keeps the hold on disk). */+ holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed"): void;/** The app's permission mode, named in the setup record of the sessions started after it; before startSession. */permissionMode(mode: ApprovalMode | null): void;recordTrace(sessionId: string, type: string, data?: unknown): void;@@ -232,8 +232,8 @@ class CaptureClient implements CaptureService {this.send({ kind: "call", id: null, method: "pinPolicy", args: [sessionId, policy] });}- holdUploads(sessionId: string, held: boolean): void {- this.send({ kind: "call", id: null, method: "holdUploads", args: [sessionId, held] });+ holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed"): void {+ this.send({ kind: "call", id: null, method: "holdUploads", args: [sessionId, state] });}async captureClaude(context: ClaudeCaptureContext, action: NativeCaptureAction): Promise<NativeCaptureManifest> {diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.tsindex 8ad73969..a293a7a7 100644--- a/apps/server/src/capture-host.ts+++ b/apps/server/src/capture-host.ts@@ -276,8 +276,8 @@ export class CaptureHost {}/** The capture policy the server's binding keeps for the chat. */- holdUploads(sessionId: string, held: boolean): void {- this.sessionUploader.holdUploads(sessionId, held);+ holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed"): void {+ this.sessionUploader.holdUploads(sessionId, state);}pinPolicy(sessionId: string, policy: string): void {diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.tsindex a3e8971e..2d7a5907 100644--- a/apps/server/src/capture-protocol.ts+++ b/apps/server/src/capture-protocol.ts@@ -25,7 +25,7 @@ export type CaptureCalls = {boxSession: [sessionId: string, box: BoxCaptureInfo | null];sessionPolicy: [sessionId: string];pinPolicy: [sessionId: string, policy: string];- holdUploads: [sessionId: string, held: boolean];+ holdUploads: [sessionId: string, state: "pending" | "refused" | "confirmed"];permissionMode: [mode: ApprovalMode | null];recordTrace: [sessionId: string, type: string, data?: unknown];flushTrace: [sessionId: string, finalTrace?: unknown];diff --git a/apps/server/src/model-modes/model-modes.test.ts b/apps/server/src/model-modes/model-modes.test.tsindex 00dff0d3..f3b2ac6d 100644--- a/apps/server/src/model-modes/model-modes.test.ts+++ b/apps/server/src/model-modes/model-modes.test.ts@@ -388,7 +388,7 @@ describe("model modes", () => {strictStateFile: path.join(dir, "strict-sessions.json"),bindTimeoutMs: 100,chatPin: () => ({ box: false, revision: null, capturePolicy: "legacy" }),- onUploadHold: (id, held) => order.push(`${held ? "hold" : "release"} ${id}`),+ onUploadHold: (id, state) => order.push(`${state} ${id}`),fetch: async (input) => {const url = new URL(String(input));if (url.pathname === "/omnirush/collect/capabilities") return Response.json({ schema_versions: [1, 2, 3], strict_sessions: { mode: "enforce", bind: true, path: "/omnirush/device/session-binding", header: "X-OmniRush-Strict-Session" } });@@ -413,13 +413,13 @@ describe("model modes", () => {expect((await post()).status).toBe(503);expect((await post()).status).toBe(200);// The chat's uploads are held from its first bind until the retry's bind is confirmed.- expect(order).toEqual(["hold ses_rebind", "bind 503", "hold ses_rebind", "bind 200", "release ses_rebind", "upstream"]);+ expect(order).toEqual(["pending ses_rebind", "bind 503", "refused ses_rebind", "pending ses_rebind", "bind 200", "confirmed ses_rebind", "upstream"]);// The gateway cannot confirm a bound chat: it is bound again before the same request goes up.await b.sessionUploadCapabilities();order.length = 0;gatewayRefuses = 1;expect((await post("ses_second")).status).toBe(200);- expect(order).toEqual(["hold ses_second", "bind 200", "release ses_second", "upstream 503", "bind 200", "upstream"]);+ expect(order).toEqual(["pending ses_second", "bind 200", "confirmed ses_second", "upstream 503", "bind 200", "upstream"]);rmSync(dir, { recursive: true, force: true });});diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.tsindex 937f1f6d..3b098d67 100644--- a/apps/server/src/omnirush-gateway-broker.ts+++ b/apps/server/src/omnirush-gateway-broker.ts@@ -106,8 +106,8 @@ type BrokerOptions = {onCapturePolicy?: (sessionId: string, policy: string) => void;/** What a chat's binding says: verified, or bound late and why (a late binding is never verified). */onBinding?: (sessionId: string, binding: { verified: boolean; lateReason?: string }) => void;- /** Strict sessions under enforce: a chat's uploads are held until its binding is confirmed (held=false releases them). */- onUploadHold?: (sessionId: string, held: boolean) => void;+ /** Strict sessions under enforce: a chat's uploads are held from its bind until it is confirmed ("refused" is kept across restarts). */+ onUploadHold?: (sessionId: string, state: "pending" | "refused" | "confirmed") => void;/** The last strict_sessions answer per server, kept on disk: it stands while capabilities cannot be fetched. */strictStateFile?: string;/** How long a strict-session bind may take (BIND_TIMEOUT_MS unless a test shrinks it). */@@ -2226,7 +2226,7 @@ export class OmniRushGatewayBroker {const capturePolicy = ownPin?.capturePolicy ?? rootPin?.capturePolicy ?? null;// Under enforce nothing of an unconfirmed chat is uploaded until its binding is (the server's late check).const enforce = strict.mode === "enforce";- if (enforce && !this.bindsConfirmed.has(session)) this.uploadHold(session, true);+ if (enforce && !this.bindsConfirmed.has(session)) this.uploadHold(session, "pending");const outcome = await this.bindSession({path: strict.path,enforce,@@ -2252,18 +2252,19 @@ export class OmniRushGatewayBroker {if (!this.bindsConfirmed.has(session)) {this.bindsConfirmed.add(session);while (this.bindsConfirmed.size > 4000) this.bindsConfirmed.delete(this.bindsConfirmed.values().next().value!);- if (enforce) this.uploadHold(session, false);+ if (enforce) this.uploadHold(session, "confirmed");}return null;}+ if (enforce && !this.bindsConfirmed.has(session)) this.uploadHold(session, "refused");this.log?.("info", "omnirush.ai refused this chat's binding; not sent", { code: outcome.refused.code });const { code, message, retry } = outcome.refused;if (retry) return Response.json({ detail: code, error: { type: "server_error", code, message } }, { status: 503, headers: { "x-should-retry": "true" } });return Response.json({ detail: code, error: { type: "invalid_request_error", code, message } }, { status: code === VERIFICATION_REQUIRED ? 403 : 400, headers: { "x-should-retry": "false" } });}- private uploadHold(sessionId: string, held: boolean): void {- try { this.onUploadHold?.(sessionId, held); } catch { /* a listener never breaks the request */ }+ private uploadHold(sessionId: string, state: "pending" | "refused" | "confirmed"): void {+ try { this.onUploadHold?.(sessionId, state); } catch { /* a listener never breaks the request */ }}/**diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 1a089530..2180c355 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -1300,7 +1300,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {// Whether the chat's binding is verified, and why it was bound late (kept in its pin, never shown).onBinding: (sessionId, binding) => { void boxServiceFor(config).updatePin(sessionId, binding); },// Strict sessions under enforce: a chat's uploads wait for its confirmed binding.- onUploadHold: (sessionId, held) => { captureServicesByServer.get(config)?.holdUploads(sessionId, held); },+ onUploadHold: (sessionId, state) => { captureServicesByServer.get(config)?.holdUploads(sessionId, state); },// The last strict-session switch per server: it stands while capabilities cannot be fetched.strictStateFile: join(runtimeStorageDir(config), "strict-sessions.json"),// The desktop's update gate (banner, blocked view); session uploads anddiff --git a/apps/server/src/session-uploader-bind-hold.test.ts b/apps/server/src/session-uploader-bind-hold.test.tsindex bfc5f827..53a0ae93 100644--- a/apps/server/src/session-uploader-bind-hold.test.ts+++ b/apps/server/src/session-uploader-bind-hold.test.ts@@ -37,7 +37,8 @@ describe("strict sessions under enforce: an unbound chat's uploads wait for itsretryBaseMs: 20,});// The broker held the chat at its first bind, which got no answer (origin unreachable).- uploader.holdUploads("ses-held", true);+ uploader.holdUploads("ses-held", "pending");+ uploader.holdUploads("ses-held", "refused");uploader.startSession("ses-held", "ws", root);uploader.recordTrace("ses-held", "tool.call", { name: "x" });uploader.flushTrace("ses-held");@@ -50,7 +51,7 @@ describe("strict sessions under enforce: an unbound chat's uploads wait for itsexpect((await uploader.spoolStatus()).entries).toBeGreaterThan(0);// The retry's bind is confirmed: the hold is released and the upload goes out after it.events.push("bind ses-held");- uploader.holdUploads("ses-held", false);+ uploader.holdUploads("ses-held", "confirmed");await until(() => events.includes("upload ses-held"));expect(events[0]).toBe("bind ses-held");expect(events.filter((event) => event.startsWith("upload")).every((event) => event === "upload ses-held")).toBe(true);@@ -71,11 +72,89 @@ describe("strict sessions under enforce: an unbound chat's uploads wait for itschangeDebounceMs: 10,fallbackScanMs: 60_000,});- uploader.holdUploads("ses-other", true);+ uploader.holdUploads("ses-other", "pending");uploader.startSession("ses-free", "ws", root);uploader.recordTrace("ses-free", "tool.call", { name: "x" });uploader.flushTrace("ses-free");await until(() => events.includes("upload ses-free"));await uploader.stop();});++ test("bind refused, the app restarts: the new process keeps the chat held until a confirmed bind, then uploads", async () => {+ const root = await mkdtemp(join(tmpdir(), "omnirush-bind-hold-"));+ roots.push(root);+ await writeFile(join(root, "app.txt"), "hello\n");+ const stateDir = join(root, "state");+ const events: string[] = [];+ let reachable = false;+ const make = () => new SessionUploader({+ stateDir,+ upload: async (sessionId) => {+ if (!reachable) throw new Error("connect ECONNREFUSED");+ events.push(`upload ${sessionId}`);+ return Response.json({ ok: true }, { status: 201 });+ },+ changeDebounceMs: 10,+ fallbackScanMs: 60_000,+ retryBaseMs: 20,+ });+ const first = make();+ first.holdUploads("ses-restart", "pending");+ first.holdUploads("ses-restart", "refused");+ first.startSession("ses-restart", "ws", root);+ first.recordTrace("ses-restart", "tool.call", { name: "x" });+ first.flushTrace("ses-restart");+ await until(async () => (await first.spoolStatus()).entries > 0);+ await first.stop();+ // A new process (no bind yet in it), and the server is back: its startup drain sends nothing for the chat.+ reachable = true;+ const second = make();+ await second.drainSpool();+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(events).toEqual([]);+ expect((await second.spoolStatus()).entries).toBeGreaterThan(0);+ // The retry's bind in the new process is confirmed: the upload goes out after it.+ events.push("bind ses-restart");+ second.holdUploads("ses-restart", "pending");+ second.holdUploads("ses-restart", "confirmed");+ await until(() => events.includes("upload ses-restart"));+ expect(events[0]).toBe("bind ses-restart");+ await second.stop();+ });++ test("bind confirmed, then the app restarts: the chat's spooled upload is not held", async () => {+ const root = await mkdtemp(join(tmpdir(), "omnirush-bind-hold-"));+ roots.push(root);+ await writeFile(join(root, "app.txt"), "hello\n");+ const stateDir = join(root, "state");+ const events: string[] = [];+ let reachable = false;+ const make = () => new SessionUploader({+ stateDir,+ upload: async (sessionId) => {+ if (!reachable) throw new Error("connect ECONNREFUSED");+ events.push(`upload ${sessionId}`);+ return Response.json({ ok: true }, { status: 201 });+ },+ changeDebounceMs: 10,+ fallbackScanMs: 60_000,+ retryBaseMs: 20,+ });+ const first = make();+ // Refused (kept on disk), its upload spooled, then confirmed while the server is still down: nothing is kept.+ first.holdUploads("ses-confirmed", "pending");+ first.holdUploads("ses-confirmed", "refused");+ first.startSession("ses-confirmed", "ws", root);+ first.recordTrace("ses-confirmed", "tool.call", { name: "x" });+ first.flushTrace("ses-confirmed");+ await until(async () => (await first.spoolStatus()).entries > 0);+ first.holdUploads("ses-confirmed", "confirmed");+ await first.stop();+ expect(events).toEqual([]);+ // A new process and the server is back: the startup drain sends the chat's upload, no bind needed.+ reachable = true;+ const second = make();+ await until(() => events.includes("upload ses-confirmed"));+ await second.stop();+ });});diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.tsindex 96e01dfa..16c42af5 100644--- a/apps/server/src/session-uploader.ts+++ b/apps/server/src/session-uploader.ts@@ -2,7 +2,7 @@ import { permissionSetupSettings, type ApprovalMode } from "./approval-mode.js";import { gitChildEnv } from "./git-env.js";import { createHash, randomBytes } from "node:crypto";import { execFile, spawn } from "node:child_process";-import { createReadStream, createWriteStream, watch, type FSWatcher, type WriteStream } from "node:fs";+import { createReadStream, createWriteStream, mkdirSync, readFileSync, renameSync, watch, writeFileSync, type FSWatcher, type WriteStream } from "node:fs";import { appendFile, lstat, mkdir, open, readFile, readdir, readlink, rename, rm, stat } from "node:fs/promises";import { homedir, release as osRelease, tmpdir } from "node:os";import nodePath, { basename, dirname, extname, join, relative, resolve, sep, type PlatformPath } from "node:path";@@ -160,6 +160,8 @@ const MAX_SPOOL_TRACE_ENTRIES = 2_000;* A spooled upload that keeps failing with a retryable answer, or that waits* for its account to sign in again, is kept this long, then dropped.*/+/** Chats whose strict-session bind was refused (state dir): their uploads stay held across restarts. */+const UPLOAD_BIND_HOLDS_FILE = "omnirush-upload-bind-holds.json";export const MAX_SPOOL_AGE_MS = 14 * 24 * 60 * 60_000;/** Stamped at a sign-out on spooled uploads whose account was never learned: no account has it, so none sends them. */export const SIGNED_OUT_UNKNOWN_ACCOUNT = "signed-out:unknown";@@ -4706,6 +4708,9 @@ export class SessionUploader {private readonly settleCapturePolicy?: SessionUploaderOptions["settleCapturePolicy"];/** Chats whose binding the broker has not confirmed yet (strict sessions under enforce): nothing of theirs is sent. */private readonly heldUntilBound = new Set<string>();+ /** The held chats kept on disk (a refused bind), until a later bind is confirmed. */+ private readonly heldOnDisk = new Set<string>();+ private readonly holdsPath: string | null;private readonly repairTranscript?: SessionUploaderOptions["repairTranscript"];private readonly confirmEnabled: boolean;private readonly idleEndMs: number;@@ -4819,6 +4824,7 @@ export class SessionUploader {});this.ledgerPath = stateDir ? join(stateDir, UPLOAD_SESSION_LEDGER_FILE) : null;this.spoolDir = stateDir ? join(stateDir, UPLOAD_SPOOL_DIRECTORY) : null;+ this.holdsPath = stateDir ? join(stateDir, UPLOAD_BIND_HOLDS_FILE) : null;this.journalDir = stateDir ? join(stateDir, UPLOAD_JOURNAL_DIRECTORY) : null;// State left under the pre-2.2.2 names is moved before anything reads it.this.stateMigrated = stateDir@@ -4894,6 +4900,8 @@ export class SessionUploader {// Uploads spooled by a previous process are retried once this one is up.// Without an account they wait (up to the spool's age limit) for the// account to come back: only a user sign-out clears them (clearSpool()).+ // Chats a previous process could not bind stay held: read before the first drain is scheduled.+ this.loadHolds();if (this.spoolDir && this.enabled) this.scheduleRetry(this.retryBaseMs);// So do the journals a previous process left: their turns are settled now.this.journalsRead = this.enabled ? this.recoverJournals() : Promise.resolve();@@ -5951,15 +5959,49 @@ export class SessionUploader {}/**- * Strict sessions under enforce: a chat's uploads wait (spooled, never dropped) until the broker confirms- * its binding, so no history reaches the server before the bind. Releasing drains the spool.+ * Strict sessions under enforce: a chat's uploads wait (spooled) until the broker confirms its binding, so no+ * history reaches the server before the bind. "pending" holds for this bind; "refused" also keeps the hold on+ * disk, so a restart holds the chat until a later bind; "confirmed" releases it (on disk too) and drains the spool.*/- holdUploads(sessionId: string, held: boolean): void {- if (held) {+ holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed"): void {+ if (state !== "confirmed") {this.heldUntilBound.add(sessionId);while (this.heldUntilBound.size > 4000) this.heldUntilBound.delete(this.heldUntilBound.values().next().value!);- } else if (this.heldUntilBound.delete(sessionId)) {- void this.drainSpool().catch(() => undefined);+ if (state === "refused" && !this.heldOnDisk.has(sessionId)) {+ this.heldOnDisk.add(sessionId);+ this.saveHolds();+ }+ return;+ }+ const wasHeld = this.heldUntilBound.delete(sessionId);+ if (this.heldOnDisk.delete(sessionId)) this.saveHolds();+ if (wasHeld) void this.drainSpool().catch(() => undefined);+ }++ /** Chats refused a binding by an earlier process: read before any spool drain, so their uploads stay held. */+ private loadHolds(): void {+ if (!this.holdsPath) return;+ try {+ const saved: unknown = JSON.parse(readFileSync(this.holdsPath, "utf8"));+ if (!Array.isArray(saved)) return;+ for (const id of saved.slice(-4000)) {+ if (typeof id !== "string" || !id) continue;+ this.heldOnDisk.add(id);+ this.heldUntilBound.add(id);+ }+ } catch { /* none kept */ }+ }++ private saveHolds(): void {+ if (!this.holdsPath) return;+ try {+ while (this.heldOnDisk.size > 4000) this.heldOnDisk.delete(this.heldOnDisk.values().next().value!);+ mkdirSync(dirname(this.holdsPath), { recursive: true });+ const temp = `${this.holdsPath}.${process.pid}.tmp`;+ writeFileSync(temp, JSON.stringify([...this.heldOnDisk]));+ renameSync(temp, this.holdsPath);+ } catch (error) {+ this.log("warn", "OmniRush session upload: the held chats could not be saved", { error: String(error) });}}