Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: a retried chat sends its history only after the server confirms it

ogsamrat4f4d7f30c43f
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.ts
index 35a440fd..c0d61331 100644
--- a/apps/server/src/capture-client.ts
+++ b/apps/server/src/capture-client.ts
@@ -93,6 +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;
/** 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;
@@ -230,6 +232,10 @@ 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] });
+ }
+
async captureClaude(context: ClaudeCaptureContext, action: NativeCaptureAction): Promise<NativeCaptureManifest> {
const call: CaptureCall = { kind: "call", id: null, method: "captureClaude", args: [context, action] };
let timeout: ReturnType<typeof setTimeout> | undefined;
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index be134fe2..8ad73969 100644
--- a/apps/server/src/capture-host.ts
+++ b/apps/server/src/capture-host.ts
@@ -276,6 +276,10 @@ 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);
+ }
+
pinPolicy(sessionId: string, policy: string): void {
this.sessionUploader.pinPolicy(sessionId, policy);
}
diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.ts
index d5b3c8db..a3e8971e 100644
--- a/apps/server/src/capture-protocol.ts
+++ b/apps/server/src/capture-protocol.ts
@@ -25,6 +25,7 @@ export type CaptureCalls = {
boxSession: [sessionId: string, box: BoxCaptureInfo | null];
sessionPolicy: [sessionId: string];
pinPolicy: [sessionId: string, policy: string];
+ holdUploads: [sessionId: string, held: boolean];
permissionMode: [mode: ApprovalMode | null];
recordTrace: [sessionId: string, type: string, data?: unknown];
flushTrace: [sessionId: string, finalTrace?: unknown];
@@ -185,6 +186,8 @@ export function invokeCapture(host: CaptureHost, call: CaptureCall): unknown {
return host.sessionPolicy(...call.args);
case "pinPolicy":
return host.pinPolicy(...call.args);
+ case "holdUploads":
+ return host.holdUploads(...call.args);
case "permissionMode":
return host.permissionMode(...call.args);
case "recordTrace":
diff --git a/apps/server/src/model-modes/model-modes.test.ts b/apps/server/src/model-modes/model-modes.test.ts
index 9e82208c..00dff0d3 100644
--- a/apps/server/src/model-modes/model-modes.test.ts
+++ b/apps/server/src/model-modes/model-modes.test.ts
@@ -388,6 +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}`),
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" } });
@@ -411,13 +412,14 @@ describe("model modes", () => {
const post = (id = "ses_rebind") => b.handle(request({ model: "gpt-6-astra", tools: [{ type: "function", name: "bash" }] }, { "x-omnirush-session-id": id }), "responses");
expect((await post()).status).toBe(503);
expect((await post()).status).toBe(200);
- expect(order).toEqual(["bind 503", "bind 200", "upstream"]);
+ // 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"]);
// 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(["bind 200", "upstream 503", "bind 200", "upstream"]);
+ expect(order).toEqual(["hold ses_second", "bind 200", "release 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.ts
index 95615eec..937f1f6d 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -106,6 +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;
/** 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). */
@@ -1306,6 +1308,9 @@ export class OmniRushGatewayBroker {
private readonly strictStateFile?: string;
private readonly onCapturePolicy?: BrokerOptions["onCapturePolicy"];
private readonly onBinding?: BrokerOptions["onBinding"];
+ private readonly onUploadHold?: BrokerOptions["onUploadHold"];
+ /** Chats whose binding is confirmed in this process (bound, or not bindable): their uploads may go out. */
+ private readonly bindsConfirmed = new Set<string>();
/** Strict sessions: each chat binds its model and mode once per process (model-modes/strict-sessions.mjs). */
private readonly reasoningSummaryFor: (model: string) => boolean | Promise<boolean>;
private readonly clientHeader: string | null;
@@ -1374,6 +1379,7 @@ export class OmniRushGatewayBroker {
this.bindSession = this.makeBinder(options.bindTimeoutMs);
this.onCapturePolicy = options.onCapturePolicy;
this.onBinding = options.onBinding;
+ this.onUploadHold = options.onUploadHold;
this.strictStateFile = options.strictStateFile;
this.reasoningSummaryFor = options.reasoningSummaryFor ?? defaultReasoningSummaryFor;
@@ -2218,9 +2224,12 @@ export class OmniRushGatewayBroker {
const ownPin = this.chatPin?.(session) ?? null;
// A sub-agent has no prompt of its own: it takes its main chat's capture policy, as the server does.
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);
const outcome = await this.bindSession({
path: strict.path,
- enforce: strict.mode === "enforce",
+ enforce,
sessionId: session,
rootId,
model: this.sessionModels.get(session) ?? model,
@@ -2239,13 +2248,24 @@ export class OmniRushGatewayBroker {
const late = typeof binding.late_reason === "string" && binding.late_reason ? binding.late_reason : binding.bound_late === true ? "bound_late" : null;
try { this.onBinding?.(session, { verified: binding.verified === true && !late, ...(late ? { lateReason: late } : {}) }); } catch { /* a listener never breaks the request */ }
}
- if (!("refused" in outcome)) return null;
+ if (!("refused" in outcome)) {
+ 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);
+ }
+ return null;
+ }
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 */ }
+ }
+
/**
* strict_session_unavailable (503 under enforce: the server could not look up or bind the chat): the same
* request again after its Retry-After, at most STRICT_RETRIES times, never on another model or unbound;
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index ae4272b3..1a089530 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1299,6 +1299,8 @@ 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); },
// 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 and
diff --git a/apps/server/src/session-uploader-bind-hold.test.ts b/apps/server/src/session-uploader-bind-hold.test.ts
new file mode 100644
index 00000000..bfc5f827
--- /dev/null
+++ b/apps/server/src/session-uploader-bind-hold.test.ts
@@ -0,0 +1,81 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { SessionUploader } from "./session-uploader.js";
+
+const roots: string[] = [];
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
+});
+
+const until = async (check: () => boolean | Promise<boolean>, ms = 5_000) => {
+ const end = Date.now() + ms;
+ while (!(await check())) {
+ if (Date.now() > end) throw new Error("timed out");
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+};
+
+describe("strict sessions under enforce: an unbound chat's uploads wait for its binding", () => {
+ test("bind fails, the server comes back: the spool flush is held, the retry binds, then the upload goes out", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-bind-hold-"));
+ roots.push(root);
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const events: string[] = [];
+ let reachable = false;
+ const uploader = new SessionUploader({
+ stateDir: join(root, "state"),
+ 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,
+ });
+ // The broker held the chat at its first bind, which got no answer (origin unreachable).
+ uploader.holdUploads("ses-held", true);
+ uploader.startSession("ses-held", "ws", root);
+ uploader.recordTrace("ses-held", "tool.call", { name: "x" });
+ uploader.flushTrace("ses-held");
+ await until(async () => (await uploader.spoolStatus()).entries > 0);
+ // The server is reachable again: the spool drains, but the held chat's upload stays spooled.
+ reachable = true;
+ await uploader.drainSpool();
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(events).toEqual([]);
+ expect((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);
+ 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);
+ await uploader.stop();
+ });
+
+ test("a chat that is not held uploads at once", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-bind-hold-"));
+ roots.push(root);
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const events: string[] = [];
+ const uploader = new SessionUploader({
+ stateDir: join(root, "state"),
+ upload: async (sessionId) => {
+ events.push(`upload ${sessionId}`);
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ changeDebounceMs: 10,
+ fallbackScanMs: 60_000,
+ });
+ uploader.holdUploads("ses-other", true);
+ 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();
+ });
+});
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index 1ae2212a..96e01dfa 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -4704,6 +4704,8 @@ export class SessionUploader {
private readonly sessionIntegrity?: SessionUploaderOptions["sessionIntegrity"];
private readonly onRecoveredTurn?: SessionUploaderOptions["onRecoveredTurn"];
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>();
private readonly repairTranscript?: SessionUploaderOptions["repairTranscript"];
private readonly confirmEnabled: boolean;
private readonly idleEndMs: number;
@@ -5948,6 +5950,19 @@ export class SessionUploader {
return answer === CLIENT_RAW || answer === CLIENT_V3 || answer === "legacy" ? answer : null;
}
+ /**
+ * 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.
+ */
+ holdUploads(sessionId: string, held: boolean): void {
+ if (held) {
+ 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);
+ }
+ }
+
/** The capture policy the server stored for the chat (its binding): the session's uploads keep it. */
pinPolicy(sessionId: string, policy: string): void {
if (policy !== CLIENT_RAW && policy !== CLIENT_V3 && policy !== "legacy") return;
@@ -7180,6 +7195,8 @@ export class SessionUploader {
schemaVersion: 2 | 3 = 2,
check: { idempotencyKey?: string; bodySha256?: string } = {},
): Promise<TransmitOutcome> {
+ // Held (strict sessions: the chat's binding is not confirmed): spooled, nothing sent.
+ if (this.heldUntilBound.has(sessionId)) return { ok: false, retryable: true, reason: "held until the chat's binding with the server is confirmed" };
const timeoutMs = sessionUploadTimeoutMs("path" in compressed ? compressed.size : compressed.byteLength, this.uploadBudget);
let lastReason = "session upload unavailable";
let refreshAttempted = false;
@@ -8190,6 +8207,8 @@ export class SessionUploader {
else waitingForAccount = true;
continue;
}
+ // A chat whose uploads are held (its binding not confirmed yet) waits, no attempt counted.
+ if (this.heldUntilBound.has(entry.session_id)) continue;
const dueAt = this.spoolEntryDueAt(entry);
if (failures >= MAX_DRAIN_FAILURES || dueAt > Date.now()) {
nextDueAt = Math.min(nextDueAt, dueAt);