Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: a chat stays waiting until the server confirms it, even before its settings are known

ogsamrat03732b5d1351
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.ts
index a6b4ad3a..13f0d72f 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 ("refused" keeps the hold on disk). */
- holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed"): void;
+ /** Strict sessions: hold the chat's uploads until its binding is confirmed (kept on disk); `seq` orders the calls. */
+ holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed", seq: number): 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,9 @@ class CaptureClient implements CaptureService {
this.send({ kind: "call", id: null, method: "pinPolicy", args: [sessionId, policy] });
}
- holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed"): void {
- this.send({ kind: "call", id: null, method: "holdUploads", args: [sessionId, state] });
+ holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed", seq: number): void {
+ // Awaited: a full start-up queue never drops it (it drops calls nobody waits on first).
+ void this.query({ kind: "call", id: null, method: "holdUploads", args: [sessionId, state, seq] }).catch(() => null);
}
async captureClaude(context: ClaudeCaptureContext, action: NativeCaptureAction): Promise<NativeCaptureManifest> {
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index a293a7a7..4e5a7c6d 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, state: "pending" | "refused" | "confirmed"): void {
- this.sessionUploader.holdUploads(sessionId, state);
+ holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed", seq: number): void {
+ this.sessionUploader.holdUploads(sessionId, state, seq);
}
pinPolicy(sessionId: string, policy: string): void {
diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.ts
index 2d7a5907..9f23e8ee 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, state: "pending" | "refused" | "confirmed"];
+ holdUploads: [sessionId: string, state: "pending" | "refused" | "confirmed", seq: number];
permissionMode: [mode: ApprovalMode | null];
recordTrace: [sessionId: string, type: string, data?: unknown];
flushTrace: [sessionId: string, finalTrace?: unknown];
diff --git a/apps/server/src/gateway-broker-upload-hold.test.ts b/apps/server/src/gateway-broker-upload-hold.test.ts
new file mode 100644
index 00000000..d399f60b
--- /dev/null
+++ b/apps/server/src/gateway-broker-upload-hold.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+import { ALL_HELD_CHATS, answerCompleted, OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";
+
+const request = (sessionId: string) => new Request("http://127.0.0.1/omnirush-gateway/v1/responses", {
+ method: "POST",
+ headers: { authorization: "Bearer local-engine-token", "content-type": "application/json", "x-omnirush-session-id": sessionId },
+ body: JSON.stringify({ model: "gpt-6-astra", tools: [{ type: "function", name: "bash" }] }),
+});
+
+const sse = (...events: string[]) => new Response(events.map((type) => `event: ${type}\ndata: {"type":"${type}"}\n\n`).join(""), { status: 200, headers: { "content-type": "text/event-stream" } });
+
+/** A broker whose capabilities check always fails (the strict switch stays unknown); `answers` play the gateway. */
+function unknownSwitch(answers: Array<() => Response>) {
+ const dir = mkdtempSync(path.join(tmpdir(), "strict-unknown-hold-"));
+ const order: string[] = [];
+ const seqs: number[] = [];
+ let next = 0;
+ const broker = new OmniRushGatewayBroker({
+ credentials: { gatewayUrl: "https://gateway.example/omnirush/v1", accessToken: "access-token", refreshToken: "refresh-token" },
+ engineToken: "local-engine-token",
+ strictStateFile: path.join(dir, "strict-sessions.json"),
+ chatPin: () => ({ box: false, revision: null, capturePolicy: "client-v3" }),
+ onUploadHold: (id, state, seq) => { order.push(`${state} ${id}`); seqs.push(seq); },
+ fetch: async (input) => {
+ const url = new URL(String(input));
+ if (url.pathname === "/omnirush/collect/capabilities") return Response.json({ detail: "unavailable" }, { status: 503 });
+ if (url.pathname === "/omnirush/device/session-binding") { order.push("bind"); return Response.json({}, { status: 500 }); }
+ const answer = answers[Math.min(next, answers.length - 1)]!;
+ next += 1;
+ order.push(`upstream ${next}`);
+ return answer();
+ },
+ });
+ return { broker, order, seqs, ready: () => broker.sessionUploadCapabilities().catch(() => null), done: () => rmSync(dir, { recursive: true, force: true }) };
+}
+
+describe("strict switch unknown: a chat's uploads wait for an answer that ran to its end", () => {
+ test("the first request fails, the retry's answer completes: only then is the chat released", async () => {
+ const { broker, order, seqs, ready, done } = unknownSwitch([
+ () => Response.json({ error: { type: "server_error", message: "upstream unavailable" } }, { status: 502, headers: { "x-should-retry": "false" } }),
+ () => sse("response.created", "response.completed"),
+ ]);
+ // The capabilities check fails: the switch is unknown.
+ await ready();
+ const first = await broker.handle(request("ses_unknown_hold"), "responses");
+ expect(first.ok).toBe(false);
+ await first.text();
+ expect(order.filter((entry) => !entry.startsWith("upstream"))).toEqual(["pending ses_unknown_hold"]);
+ const retry = await broker.handle(request("ses_unknown_hold"), "responses");
+ expect(retry.status).toBe(200);
+ // Not released before the answer has run to its end.
+ expect(order.includes("confirmed ses_unknown_hold")).toBe(false);
+ await retry.text();
+ expect(order).toEqual(["pending ses_unknown_hold", "upstream 1", "pending ses_unknown_hold", "upstream 2", "confirmed ses_unknown_hold"]);
+ expect(seqs).toEqual([...seqs].sort((a, b) => a - b));
+ done();
+ }, 20_000);
+
+ test("a 426, an answer ending in an error, or a stream cut short never release the chat", async () => {
+ const cut = () => new Response(new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode('event: response.created\ndata: {"type":"response.created"}\n\n'));
+ controller.error(new Error("socket hang up"));
+ },
+ }), { status: 200, headers: { "content-type": "text/event-stream" } });
+ const { broker, order, ready, done } = unknownSwitch([
+ () => Response.json({ detail: "update_required" }, { status: 426 }),
+ () => sse("response.created", "error"),
+ cut,
+ ]);
+ await ready();
+ for (let turn = 0; turn < 3; turn += 1) {
+ const response = await broker.handle(request("ses_never_released"), "responses");
+ await response.text().catch(() => undefined);
+ }
+ expect(order.some((entry) => entry.startsWith("confirmed"))).toBe(false);
+ expect(order.filter((entry) => entry === "pending ses_never_released").length).toBe(3);
+ done();
+ }, 20_000);
+
+ test("answerCompleted: a completed stream or a JSON body counts; an error or a missing end does not", () => {
+ expect(answerCompleted('data: {"type":"response.completed"}\n', "text/event-stream")).toBe(true);
+ expect(answerCompleted('data: {"type":"response.created"}\n', "text/event-stream")).toBe(false);
+ expect(answerCompleted('data: {"type":"response.failed"}\n', "text/event-stream")).toBe(false);
+ expect(answerCompleted('{"output":[]}', "application/json")).toBe(true);
+ expect(answerCompleted("", "application/json")).toBe(false);
+ expect(ALL_HELD_CHATS).toBe("*");
+ });
+});
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.ts
index 3b098d67..13e411b3 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -106,8 +106,11 @@ 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 from its bind until it is confirmed ("refused" is kept across restarts). */
- onUploadHold?: (sessionId: string, state: "pending" | "refused" | "confirmed") => void;
+ /**
+ * Strict sessions (enforce, or the switch not known yet): a chat's uploads are held from its first model request
+ * until its binding is confirmed; `seq` is this broker's order of the calls for the chat.
+ */
+ onUploadHold?: (sessionId: string, state: "pending" | "refused" | "confirmed", seq: number) => 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). */
@@ -162,6 +165,19 @@ export const UPDATE_REQUIRED_CODE = "update_required";
* frame. Comment lines such as `: keepalive` carry no data and are never
* terminal.
*/
+/** The uploader's "every held chat" (a strict switch known not to enforce releases them all). */
+export const ALL_HELD_CHATS = "*";
+
+/** How much of an answer's end is kept to tell whether it ran to its normal end (strict switch unknown). */
+const STRICT_TAIL_CHARS = 64 * 1024;
+
+/** Whether an answer ran to its normal end: no error or refusal event, and a completed event (or a JSON body). */
+export function answerCompleted(tail: string, contentType: string): boolean {
+ if (/"type"\s*:\s*"(?:error|response\.failed|response\.incomplete)"/.test(tail) || /^event:\s*error\b/m.test(tail)) return false;
+ if (!contentType.includes("event-stream")) return tail.trim().length > 0;
+ return /"type"\s*:\s*"(?:response\.completed|response\.done|message_stop)"|^data:\s*\[DONE\]/m.test(tail);
+}
+
const TERMINAL_RESPONSE_EVENTS = new Set(["response.completed", "response.incomplete", "response.failed"]);
const TERMINAL_OR_ERROR_MARKER = /"(?:response\.(?:completed|incomplete|failed)|error)"/;
/** An event larger than this passes through unread; the marker scan below then decides terminality. */
@@ -1311,6 +1327,7 @@ export class OmniRushGatewayBroker {
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>();
+ private holdSeq = 0;
/** 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;
@@ -2082,6 +2099,12 @@ export class OmniRushGatewayBroker {
const strictHeader = strict?.header ?? (this.strictUnknown() ? STRICT_SESSION_HEADER : null);
const unbound = strict ? await this.strictBindRefusal(strict, request, path, body) : null;
if (unbound) return unbound;
+ // Switch not known: the chat is held from this request until an answer that ran to its end confirms it.
+ const unknownSession = !strict && strictHeader && body !== undefined && (path === "responses" || path === "responses/compact")
+ ? request.headers.get("x-omnirush-session-id")
+ : null;
+ if (unknownSession && !this.bindsConfirmed.has(unknownSession)) this.uploadHold(unknownSession, "pending");
+ const confirmed = (response: Response) => (unknownSession ? this.confirmOnCompletion(response, unknownSession) : response);
const forwardedBody = path === "responses" && body !== undefined
? await withReasoningSummary(body, this.reasoningSummaryFor)
: body;
@@ -2094,7 +2117,7 @@ export class OmniRushGatewayBroker {
if (!this.state) break;
try {
const response = await this.forward(request, path, forwardedBody, attempt === 0 ? accessToken : this.state.accessToken, requestId, strictHeader);
- return await this.strictRetry(response, async () => {
+ return confirmed(await this.strictRetry(response, async () => {
// The gateway could not confirm the chat: it is bound again before the same request goes up.
const session = request.headers.get("x-omnirush-session-id");
if (strict && session) {
@@ -2103,7 +2126,7 @@ export class OmniRushGatewayBroker {
if (refused) return refused;
}
return this.forward(request, path, forwardedBody, this.state?.accessToken, requestId, strictHeader);
- }, request.signal);
+ }, request.signal));
} catch (error) {
if (request.signal.aborted) throw error;
failure = fetchFailure(error);
@@ -2249,11 +2272,7 @@ export class OmniRushGatewayBroker {
try { this.onBinding?.(session, { verified: binding.verified === true && !late, ...(late ? { lateReason: late } : {}) }); } catch { /* a listener never breaks the request */ }
}
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, "confirmed");
- }
+ this.bindConfirmed(session, enforce);
return null;
}
if (enforce && !this.bindsConfirmed.has(session)) this.uploadHold(session, "refused");
@@ -2264,7 +2283,39 @@ export class OmniRushGatewayBroker {
}
private uploadHold(sessionId: string, state: "pending" | "refused" | "confirmed"): void {
- try { this.onUploadHold?.(sessionId, state); } catch { /* a listener never breaks the request */ }
+ this.holdSeq += 1;
+ try { this.onUploadHold?.(sessionId, state, this.holdSeq); } catch { /* a listener never breaks the request */ }
+ }
+
+ /** The chat's binding is confirmed in this process: its held uploads may go out. */
+ private bindConfirmed(sessionId: string, release: boolean): void {
+ if (this.bindsConfirmed.has(sessionId)) return;
+ this.bindsConfirmed.add(sessionId);
+ while (this.bindsConfirmed.size > 4000) this.bindsConfirmed.delete(this.bindsConfirmed.values().next().value!);
+ if (release) this.uploadHold(sessionId, "confirmed");
+ }
+
+ /**
+ * Switch not known yet: the gateway binds the chat itself on its first request (the strict header). Only an
+ * answer that ran to its normal end confirms it; an error, a refusal, a non-2xx (426 included) or a stream cut
+ * short does not, and the chat's uploads stay held.
+ */
+ private confirmOnCompletion(response: Response, sessionId: string): Response {
+ if (!response.ok || !response.body || this.bindsConfirmed.has(sessionId)) return response;
+ const contentType = response.headers.get("content-type") ?? "";
+ const decoder = new TextDecoder();
+ let tail = "";
+ const watch = new TransformStream<Uint8Array, Uint8Array>({
+ transform: (chunk, controller) => {
+ tail = (tail + decoder.decode(chunk, { stream: true })).slice(-STRICT_TAIL_CHARS);
+ controller.enqueue(chunk);
+ },
+ flush: () => {
+ tail = (tail + decoder.decode()).slice(-STRICT_TAIL_CHARS);
+ if (answerCompleted(tail, contentType)) this.bindConfirmed(sessionId, true);
+ },
+ });
+ return new Response(response.body.pipeThrough(watch), { status: response.status, statusText: response.statusText, headers: response.headers });
}
/**
@@ -2331,6 +2382,8 @@ export class OmniRushGatewayBroker {
private rememberStrict(gatewayUrl: string, capabilities: TraceCapabilities): void {
this.strictBind = strictSessions(capabilities);
this.strictOrigin = originOf(gatewayUrl);
+ // The server holds nothing back (strict off or observe): no chat's uploads wait for a binding any more.
+ if (this.strictBind?.mode !== "enforce") this.uploadHold(ALL_HELD_CHATS, "confirmed");
if (!this.strictStateFile) return;
try {
mkdirSync(dirname(this.strictStateFile), { recursive: true, mode: 0o700 });
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 2180c355..054b6375 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, state) => { captureServicesByServer.get(config)?.holdUploads(sessionId, state); },
+ onUploadHold: (sessionId, state, seq) => { captureServicesByServer.get(config)?.holdUploads(sessionId, state, seq); },
// 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
index 53a0ae93..377fa5a2 100644
--- a/apps/server/src/session-uploader-bind-hold.test.ts
+++ b/apps/server/src/session-uploader-bind-hold.test.ts
@@ -157,4 +157,86 @@ describe("strict sessions under enforce: an unbound chat's uploads wait for its
await until(() => events.includes("upload ses-confirmed"));
await second.stop();
});
+
+ async function spooledWhileHeld(stateDir: string, root: string, sessionId: string, holds: Array<[string, "pending" | "refused" | "confirmed", number]>) {
+ const first = new SessionUploader({
+ stateDir,
+ upload: async () => { throw new Error("connect ECONNREFUSED"); },
+ changeDebounceMs: 10,
+ fallbackScanMs: 60_000,
+ retryBaseMs: 20,
+ });
+ for (const [id, state, seq] of holds) first.holdUploads(id, state, seq);
+ first.startSession(sessionId, "ws", root);
+ first.recordTrace(sessionId, "tool.call", { name: "x" });
+ first.flushTrace(sessionId);
+ await until(async () => (await first.spoolStatus()).entries > 0);
+ return first;
+ }
+
+ test("the app quits while the bind is pending: the restarted process keeps the chat held until it is confirmed", 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 first = await spooledWhileHeld(stateDir, root, "ses-pending-quit", [["ses-pending-quit", "pending", 1]]);
+ await first.stop();
+ const events: string[] = [];
+ const second = new SessionUploader({
+ stateDir,
+ upload: async (sessionId) => { events.push(`upload ${sessionId}`); return Response.json({ ok: true }, { status: 201 }); },
+ changeDebounceMs: 10,
+ fallbackScanMs: 60_000,
+ retryBaseMs: 20,
+ });
+ await second.drainSpool();
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(events).toEqual([]);
+ events.push("bind ses-pending-quit");
+ second.holdUploads("ses-pending-quit", "pending", 1);
+ second.holdUploads("ses-pending-quit", "confirmed", 2);
+ await until(() => events.includes("upload ses-pending-quit"));
+ expect(events[0]).toBe("bind ses-pending-quit");
+ await second.stop();
+ });
+
+ test("a late, older hold call never undoes a confirmed binding", 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");
+ // Confirmed (seq 2) arrives before the pending of its bind (seq 1): the chat stays released.
+ const first = await spooledWhileHeld(stateDir, root, "ses-reordered", [["ses-reordered", "pending", 3], ["ses-reordered", "confirmed", 5], ["ses-reordered", "pending", 4]]);
+ await first.stop();
+ const events: string[] = [];
+ const second = new SessionUploader({
+ stateDir,
+ upload: async (sessionId) => { events.push(`upload ${sessionId}`); return Response.json({ ok: true }, { status: 201 }); },
+ changeDebounceMs: 10,
+ fallbackScanMs: 60_000,
+ retryBaseMs: 20,
+ });
+ await until(() => events.includes("upload ses-reordered"));
+ await second.stop();
+ });
+
+ test("a switch known not to enforce releases every held chat, on disk too", 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 first = await spooledWhileHeld(stateDir, root, "ses-switch-off", [["ses-switch-off", "refused", 1]]);
+ first.holdUploads("*", "confirmed", 2);
+ await first.stop();
+ const events: string[] = [];
+ const second = new SessionUploader({
+ stateDir,
+ upload: async (sessionId) => { events.push(`upload ${sessionId}`); return Response.json({ ok: true }, { status: 201 }); },
+ changeDebounceMs: 10,
+ fallbackScanMs: 60_000,
+ retryBaseMs: 20,
+ });
+ await until(() => events.includes("upload ses-switch-off"));
+ await second.stop();
+ });
});
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index 16c42af5..e0707dc2 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -160,7 +160,7 @@ 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. */
+/** Chats whose strict-session bind is not confirmed (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. */
@@ -4708,8 +4708,10 @@ 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. */
+ /** The held chats kept on disk (a bind pending or refused), until a later bind is confirmed. */
private readonly heldOnDisk = new Set<string>();
+ /** The broker's last hold call per chat (its order): a late older call is ignored. */
+ private readonly holdSeq = new Map<string, number>();
private readonly holdsPath: string | null;
private readonly repairTranscript?: SessionUploaderOptions["repairTranscript"];
private readonly confirmEnabled: boolean;
@@ -5959,26 +5961,41 @@ export class SessionUploader {
}
/**
- * 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.
+ * Strict sessions (enforce, or the switch not known yet): a chat's uploads wait (spooled) until the broker
+ * confirms its binding, so no history reaches the server before it. "pending" and "refused" hold the chat, on
+ * disk too, so a restart keeps it held; "confirmed" releases it (on disk too) and drains the spool. `seq` is the
+ * broker's order of these calls for the chat: an older one arriving late is ignored.
*/
- holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed"): void {
+ holdUploads(sessionId: string, state: "pending" | "refused" | "confirmed", seq = 0): void {
+ const last = this.holdSeq.get(sessionId) ?? -1;
+ if (seq > 0 && seq <= last) return;
+ if (seq > 0) {
+ this.holdSeq.set(sessionId, seq);
+ while (this.holdSeq.size > 4000) this.holdSeq.delete(this.holdSeq.keys().next().value!);
+ }
if (state !== "confirmed") {
this.heldUntilBound.add(sessionId);
while (this.heldUntilBound.size > 4000) this.heldUntilBound.delete(this.heldUntilBound.values().next().value!);
- if (state === "refused" && !this.heldOnDisk.has(sessionId)) {
+ if (!this.heldOnDisk.has(sessionId)) {
this.heldOnDisk.add(sessionId);
this.saveHolds();
}
return;
}
+ // "*": the server's switch is known not to enforce, so nothing waits for a binding.
+ if (sessionId === "*") {
+ const any = this.heldUntilBound.size > 0;
+ this.heldUntilBound.clear();
+ if (this.heldOnDisk.size > 0) { this.heldOnDisk.clear(); this.saveHolds(); }
+ if (any) void this.drainSpool().catch(() => undefined);
+ 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. */
+ /** Chats an earlier process held (bind pending or refused): read before any spool drain, so their uploads stay held. */
private loadHolds(): void {
if (!this.holdsPath) return;
try {