Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: keep queued uploads and steady their keys

ogsamrat89ff52649746
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index 35bbf542..c0fcf863 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -2196,6 +2196,8 @@ const desktopCommandHandlers = {
return result;
},
"omnirushAccountSignOut": async (event, ...args) => {
+ // Only a user's sign-out deletes what is queued for upload; a sign-in the server retired keeps it.
+ await runtimeManager.markUploadQueueClear();
const result = await omnirushAccountStore.clear();
await runtimeManager.omnirushServerRestart({ reason: "account_signed_out", source: "account", userInitiated: true });
return { connected: false, remoteRevoked: result.remoteRevoked, reason: result.reason };
diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjs
index 5733e715..3b7e441e 100644
--- a/apps/desktop/electron/runtime.mjs
+++ b/apps/desktop/electron/runtime.mjs
@@ -391,6 +391,15 @@ export function snapshotEngineState(state) {
* apps have no visible stdout, so without this file every engine rollover
* reason and reload trigger is lost. An explicit OMNIRUSH_SERVER_LOG_FILE wins.
*/
+/**
+ * Set by a user's sign-out, cleared once a server started with it: that
+ * server deletes the queued uploads and archives first. On disk, so a quit
+ * before the next start still clears them at the one after.
+ */
+export function uploadQueueClearMarkerPath(userDataDir) {
+ return path.join(userDataDir, "omnirush-upload-queue-clear");
+}
+
export function resolveOmniRushServerLogFile(userDataDir, env = process.env) {
const explicit = String(env.OMNIRUSH_SERVER_LOG_FILE ?? "").trim();
if (explicit) return explicit;
@@ -2193,6 +2202,7 @@ export function createRuntimeManager({
process.env.OMNIRUSH_DESKTOP_USER_DATA_DIR = userDataDir;
omnirushServerState.logFilePath = logFilePath;
const { startEmbeddedServer } = await import(embeddedServerImportUrl(embeddedPath));
+ const clearUploadQueue = existsSync(uploadQueueClearMarkerPath(userDataDir));
// startEmbeddedServer falls back to an OS-assigned port if `port` races
// into EADDRINUSE (see apps/server/src/serve-node.ts), so the bound port
// below is authoritative.
@@ -2214,6 +2224,7 @@ export function createRuntimeManager({
localManagedMcpVaultKey,
appVersion: typeof appVersion === "string" && appVersion.trim() ? appVersion.trim() : undefined,
captureFileUpload: typeof captureFileUpload === "function" ? captureFileUpload : undefined,
+ clearUploadQueue,
// Bundled UI-control MCP launch for the startup migration of persisted
// `npx -y omnirush-ui-mcp` entries; null removes those entries instead.
omnirushUiMcp: omnirushUiMcpLaunch() ?? null,
@@ -2239,6 +2250,7 @@ export function createRuntimeManager({
: undefined,
});
inProcessServer = handle;
+ if (clearUploadQueue) await rm(uploadQueueClearMarkerPath(userDataDir), { force: true }).catch(() => undefined);
omnirushServerState.managedOpencodeExecution = handle.managedOpencodeExecution ?? null;
engineState.managedByServer = Boolean(handle.managedOpencode);
engineState.managedPid = handle.managedOpencode?.pid ?? null;
@@ -2659,6 +2671,11 @@ export function createRuntimeManager({
engineInstall,
omnirushServerInfo,
omnirushServerRestart: (options) => withRuntimeLifecycle(() => omnirushServerRestart(options)),
+ /** A user's sign-out: the next server start deletes the queued uploads and archives. */
+ markUploadQueueClear: async () => {
+ await mkdir(userDataDir, { recursive: true });
+ await writeFile(uploadQueueClearMarkerPath(userDataDir), `${new Date().toISOString()}\n`, { mode: 0o600 });
+ },
opencodeMcpAuth,
sandboxCleanupOmniRushContainers,
};
diff --git a/apps/desktop/electron/runtime.test.mjs b/apps/desktop/electron/runtime.test.mjs
index 97387b2f..20eb3c08 100644
--- a/apps/desktop/electron/runtime.test.mjs
+++ b/apps/desktop/electron/runtime.test.mjs
@@ -21,6 +21,7 @@ import {
selectStickyOmniRushPortWorkspace,
snapshotEngineState,
snapshotOmniRushServerState,
+ uploadQueueClearMarkerPath,
} from "./runtime.mjs";
import {
appendRuntimeRestartRecord,
@@ -627,3 +628,22 @@ describe("built-in server restart record", () => {
}
});
});
+
+describe("upload queue clear marker", () => {
+ it("a user's sign-out leaves a marker in the user data folder for the next server start", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "omnirush-runtime-queue-clear-"));
+ try {
+ const manager = createRuntimeManager({
+ app: { getPath: (name) => name === "exe" ? path.join(root, "OmniRush.ai.exe") : root, isPackaged: false },
+ desktopRoot: path.dirname(fileURLToPath(import.meta.url)),
+ listLocalWorkspacePaths: async () => [],
+ localManagedMcpVaultKey: "test-key",
+ });
+ assert.equal(uploadQueueClearMarkerPath(root), path.join(root, "omnirush-upload-queue-clear"));
+ await manager.markUploadQueueClear();
+ assert.match(await readFile(uploadQueueClearMarkerPath(root), "utf8"), /^\d{4}-\d{2}-\d{2}T/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/apps/server/src/capture-client.test.ts b/apps/server/src/capture-client.test.ts
index c2197b30..13802ce0 100644
--- a/apps/server/src/capture-client.test.ts
+++ b/apps/server/src/capture-client.test.ts
@@ -454,6 +454,38 @@ describe("capture worker", () => {
expect(members[1]!.content.equals(brief)).toBe(true);
}, 60_000);
+ test("through the worker, uploads carry their Idempotency-Key, the integrity read reaches the main thread and the spool is stamped with the account", async () => {
+ const stateDir = await tempDir("keys-state");
+ const root = await tempDir("keys-root");
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const keys: Array<string | undefined> = [];
+ const integrity: string[] = [];
+ const capture = service({
+ stateDir,
+ accountId: async () => "user-worker-1",
+ sessionIntegrity: async (sessionId, options) => {
+ integrity.push(`${sessionId}:${options?.summary === true}`);
+ return Response.json({ detail: "session_not_found" }, { status: 404 });
+ },
+ sessionUploader: {
+ upload: async (_sessionId, _bytes, _signal, request) => {
+ keys.push(request?.idempotencyKey);
+ return Response.json({ detail: "unavailable" }, { status: 503 });
+ },
+ },
+ });
+ capture.startSession("session-worker-keys", "workspace-keys", root);
+ await capture.idle();
+ await capture.stop();
+ expect(integrity).toEqual(["session-worker-keys:true"]);
+ expect(keys.length).toBeGreaterThan(0);
+ expect(keys.every((key) => typeof key === "string" && /^[0-9a-f]{64}$/.test(key))).toBe(true);
+ const spool = join(stateDir, "omnirush-upload-spool");
+ const metas = await Promise.all((await readdir(spool)).filter((name) => name.endsWith(".json")).map(async (name) => JSON.parse(await readFile(join(spool, name), "utf8")) as Record<string, unknown>));
+ expect(metas.length).toBeGreaterThan(0);
+ expect(metas.every((meta) => meta.account_id === "user-worker-1" && typeof meta.idempotency_key === "string")).toBe(true);
+ });
+
test("OMNIRUSH_CAPTURE_WORKER=0 captures in-process with the same envelopes", async () => {
const root = await syntheticWorkspace(20);
const results: Array<Array<[string, string, number]>> = [];
diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.ts
index fa33fb8e..f8aca0c2 100644
--- a/apps/server/src/capture-client.ts
+++ b/apps/server/src/capture-client.ts
@@ -313,6 +313,8 @@ class CaptureClient implements CaptureService {
stateDir: this.options.stateDir,
appVersion: this.options.appVersion,
engineVersion: this.options.engineVersion,
+ accountId: Boolean(this.options.accountId),
+ sessionIntegrity: Boolean(this.options.sessionIntegrity),
sessionUploader: {
upload: Boolean(sessionUploader.upload),
uploadFile: Boolean(sessionUploader.uploadFile),
@@ -479,7 +481,7 @@ class CaptureClient implements CaptureService {
switch (request.type) {
case "upload": {
if (!sessionUploader.upload) throw new Error("no session upload hook");
- return { kind: "result", id, ok: true, response: await serializeResponse(await sessionUploader.upload(request.sessionId, request.body, signal)) };
+ return { kind: "result", id, ok: true, response: await serializeResponse(await sessionUploader.upload(request.sessionId, request.body, signal, request.options)) };
}
case "uploadFile": {
if (!sessionUploader.uploadFile) throw new Error("no session file upload hook");
@@ -494,13 +496,22 @@ class CaptureClient implements CaptureService {
kind: "result",
id,
ok: true,
- response: await serializeResponse(await sessionUploader.uploadFile(request.sessionId, path, request.size, signal)),
+ response: await serializeResponse(await sessionUploader.uploadFile(request.sessionId, path, request.size, signal, request.options)),
};
}
case "capabilities": {
if (!sessionUploader.capabilities) throw new Error("no session capability hook");
return { kind: "result", id, ok: true, response: null, value: await sessionUploader.capabilities() };
}
+ case "sessionIntegrity": {
+ if (!this.options.sessionIntegrity) throw new Error("no integrity hook");
+ return { kind: "result", id, ok: true, response: await serializeResponse(await this.options.sessionIntegrity(request.sessionId, {
+ ...(request.summary ? { summary: true } : {}),
+ ...(request.turns !== undefined ? { turns: request.turns } : {}),
+ })) };
+ }
+ case "accountId":
+ return { kind: "result", id, ok: true, response: null, account: this.options.accountId ? await this.options.accountId() : null };
case "refreshAccessToken": {
const refresh = channel === "archive" ? archive.refreshAccessToken : sessionUploader.refreshAccessToken;
return { kind: "result", id, ok: true, response: null, token: refresh ? await refresh() : null };
diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.ts
index 9005db2a..e563adbb 100644
--- a/apps/server/src/capture-host.ts
+++ b/apps/server/src/capture-host.ts
@@ -25,7 +25,7 @@ import {
import type { CaptureStopOptions } from "./capture-protocol.js";
import { SessionArchiver, type FilesUsedStatus, type SessionArchiverOptions } from "./session-archive/index.js";
import { ProjectArchiveLifecycle, type ArchiveLifecycleLog } from "./session-archive/lifecycle.js";
-import { SessionUploader, type TraceCapabilities, type UploadMetrics, type UploadWebVisit } from "./session-uploader.js";
+import { SessionUploader, type TraceCapabilities, type UploadMetrics, type UploadRequestOptions, type UploadWebVisit } from "./session-uploader.js";
export type { EngineReplacement, EngineTarget } from "./session-upload-observer.js";
@@ -58,9 +58,13 @@ export type CaptureHostOptions = {
appVersion: string;
engineVersion: string;
log: CaptureLog;
+ /** The signed-in account's id (null: not known now); spooled uploads are stamped with it. */
+ accountId?: () => Promise<string | null>;
+ /** GET /omnirush/me/sessions/{id}/integrity with the device bearer. */
+ sessionIntegrity?: (sessionId: string, options?: { summary?: boolean; turns?: number }) => Promise<Response>;
sessionUploader: {
- upload?: (sessionId: string, compressed: Uint8Array, signal?: AbortSignal) => Promise<Response>;
- uploadFile?: (sessionId: string, path: string, size: number, signal?: AbortSignal) => Promise<Response>;
+ upload?: (sessionId: string, compressed: Uint8Array, signal?: AbortSignal, request?: UploadRequestOptions) => Promise<Response>;
+ uploadFile?: (sessionId: string, path: string, size: number, signal?: AbortSignal, request?: UploadRequestOptions) => Promise<Response>;
capabilities?: () => Promise<TraceCapabilities>;
refreshAccessToken?: () => Promise<string | null>;
fetch?: (input: string, init?: RequestInit) => Promise<Response>;
@@ -111,6 +115,8 @@ export class CaptureHost {
appVersion: options.appVersion,
engineVersion: options.engineVersion,
log: options.log,
+ ...(options.accountId ? { accountId: options.accountId } : {}),
+ ...(options.sessionIntegrity ? { sessionIntegrity: options.sessionIntegrity } : {}),
// Capture context (context/); OMNIRUSH_CAPTURE_CONTEXT=0 turns it off.
context: options.sessionUploader?.context ?? {},
...(options.onSessionClosed ? { onSessionClosed: options.onSessionClosed } : {}),
@@ -122,8 +128,17 @@ export class CaptureHost {
const { enabled, excludedDirs, folderGate, baseIdleMs, baseMaxDeferMs, ...auth } = options.archive;
this.appDirs = [options.stateDir, ...excludedDirs];
this.archive = new ProjectArchiveLifecycle({
- archiver: new SessionArchiver({ stateDir: options.stateDir, excludedDirs, folderGate, log: options.log, ...auth }),
+ archiver: new SessionArchiver({
+ stateDir: options.stateDir,
+ excludedDirs,
+ folderGate,
+ log: options.log,
+ ...auth,
+ // Through the gateway broker, the account behind the device bearer (claimAccount()).
+ ...(auth.request && options.accountId ? { accountId: options.accountId } : {}),
+ }),
enabled: enabled && this.sessionUploader.enabled,
+ accountMissing: !this.sessionUploader.enabled,
log: options.log,
...(baseIdleMs !== undefined ? { baseIdleMs } : {}),
...(baseMaxDeferMs !== undefined ? { baseMaxDeferMs } : {}),
diff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.ts
index 4aca47d2..2663ada1 100644
--- a/apps/server/src/capture-protocol.ts
+++ b/apps/server/src/capture-protocol.ts
@@ -9,7 +9,7 @@
*/
import type { CaptureHost, EngineReplacement, EngineTarget, PromptRecord } from "./capture-host.js";
import type { FolderGateOptions } from "./session-archive/detect.js";
-import type { TraceCapabilities, UploadWebVisit } from "./session-uploader.js";
+import type { TraceCapabilities, UploadRequestOptions, UploadWebVisit } from "./session-uploader.js";
/** How the capture stops: `archiveFinals` false (the account is gone) packs no final project archives. */
export type CaptureStopOptions = { archiveFinals: boolean };
@@ -42,9 +42,11 @@ export type CaptureCall = { [M in CaptureCallName]: { kind: "call"; id: number |
/** What a worker asks of the main thread. `channel` says whose request it is: archive requests are aborted first at shutdown. */
export type HostRequest =
- | { type: "upload"; sessionId: string; body: Uint8Array<ArrayBuffer> }
- | { type: "uploadFile"; sessionId: string; path: string; size: number }
+ | { type: "upload"; sessionId: string; body: Uint8Array<ArrayBuffer>; options?: UploadRequestOptions }
+ | { type: "uploadFile"; sessionId: string; path: string; size: number; options?: UploadRequestOptions }
| { type: "capabilities" }
+ | { type: "accountId" }
+ | { type: "sessionIntegrity"; sessionId: string; summary?: boolean; turns?: number }
| { type: "refreshAccessToken" }
| { type: "archiveRequest"; path: string; method: "GET" | "POST"; body?: string; refresh?: false }
| { type: "fetch"; url: string; method: string; headers: Array<[string, string]>; body?: Uint8Array<ArrayBuffer> | string };
@@ -54,7 +56,7 @@ export type RequestChannel = "uploader" | "archive";
export type SerializedResponse = { status: number; statusText: string; headers: Array<[string, string]>; body: ArrayBuffer | null };
export type RequestResult =
- | { kind: "result"; id: number; ok: true; response: SerializedResponse | null; token?: string | null; value?: TraceCapabilities }
+ | { kind: "result"; id: number; ok: true; response: SerializedResponse | null; token?: string | null; value?: TraceCapabilities; account?: string | null }
| { kind: "result"; id: number; ok: false; error: string; name: string };
export type ToWorker = CaptureCall | RequestResult;
@@ -73,6 +75,10 @@ export type CaptureWorkerInit = {
stateDir: string;
appVersion: string;
engineVersion: string;
+ /** The main thread can name the signed-in account (spooled uploads are stamped with it). */
+ accountId: boolean;
+ /** The main thread can read the server's integrity record of a chat. */
+ sessionIntegrity: boolean;
sessionUploader: { upload: boolean; uploadFile: boolean; capabilities: boolean; refreshAccessToken: boolean; gatewayUrl?: string; accessToken?: string };
archive: {
enabled: boolean;
diff --git a/apps/server/src/capture-worker.ts b/apps/server/src/capture-worker.ts
index f7bafd5a..452b1bdb 100644
--- a/apps/server/src/capture-worker.ts
+++ b/apps/server/src/capture-worker.ts
@@ -22,7 +22,7 @@ import {
type ToWorker,
} from "./capture-protocol.js";
import type { ArchiveApiRequestInit } from "./session-archive/upload.js";
-import type { TraceCapabilities } from "./session-uploader.js";
+import type { TraceCapabilities, UploadRequestOptions } from "./session-uploader.js";
function mainThreadPort(): MessagePort {
if (!parentPort) throw new Error("capture-worker runs as a worker thread only");
@@ -115,12 +115,27 @@ const host = new CaptureHost({
appVersion: init.appVersion,
engineVersion: init.engineVersion,
log,
+ ...(init.accountId ? { accountId: async () => (await ask("uploader", { type: "accountId" })).account ?? null } : {}),
+ ...(init.sessionIntegrity
+ ? {
+ sessionIntegrity: async (sessionId: string, options: { summary?: boolean; turns?: number } = {}) => {
+ const result = await ask("uploader", {
+ type: "sessionIntegrity",
+ sessionId,
+ ...(options.summary ? { summary: true } : {}),
+ ...(options.turns !== undefined ? { turns: options.turns } : {}),
+ });
+ if (!result.response) throw new Error("the main thread returned no response");
+ return deserializeResponse(result.response);
+ },
+ }
+ : {}),
sessionUploader: {
...(init.sessionUploader.upload
? {
- upload: async (sessionId: string, compressed: Uint8Array, signal?: AbortSignal) => {
+ upload: async (sessionId: string, compressed: Uint8Array, signal?: AbortSignal, options?: UploadRequestOptions) => {
const body = new Uint8Array(compressed);
- const result = await ask("uploader", { type: "upload", sessionId, body }, signal);
+ const result = await ask("uploader", { type: "upload", sessionId, body, ...(options ? { options } : {}) }, signal);
if (!result.response) throw new Error("the main thread returned no response");
return deserializeResponse(result.response);
},
@@ -128,8 +143,8 @@ const host = new CaptureHost({
: {}),
...(init.sessionUploader.uploadFile
? {
- uploadFile: async (sessionId: string, path: string, size: number, signal?: AbortSignal) => {
- const result = await ask("uploader", { type: "uploadFile", sessionId, path, size }, signal);
+ uploadFile: async (sessionId: string, path: string, size: number, signal?: AbortSignal, options?: UploadRequestOptions) => {
+ const result = await ask("uploader", { type: "uploadFile", sessionId, path, size, ...(options ? { options } : {}) }, signal);
if (!result.response) throw new Error("the main thread returned no response");
return deserializeResponse(result.response);
},
diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.ts
index 3b0a08ad..f3c88155 100644
--- a/apps/server/src/embedded.ts
+++ b/apps/server/src/embedded.ts
@@ -61,6 +61,8 @@ export type EmbeddedServerOptions = CliArgs & {
appVersion?: string;
/** File-aware transport for immutable compressed session uploads. */
captureFileUpload?: CaptureFileUpload;
+ /** The user signed out since the last start: queued uploads and archives are deleted first. */
+ clearUploadQueue?: boolean;
/**
* How the embedding desktop launches its bundled UI-control MCP. Persisted
* entries still using `npx -y omnirush-ui-mcp` are rewritten to it before
@@ -99,6 +101,7 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promi
config.resumeInterruptedTasks = options.resumeInterruptedTasks === true && options.manageOpencode === true && !config.opencodeBaseUrl;
config.appVersion = typeof options.appVersion === "string" && options.appVersion.trim() ? options.appVersion.trim() : undefined;
config.captureFileUpload = options.captureFileUpload;
+ config.clearUploadQueue = options.clearUploadQueue === true;
const logger = createServerLogger(config);
// Spawn managed OpenCode if requested and no explicit base URL was provided.
diff --git a/apps/server/src/omnirush-gateway-broker.test.ts b/apps/server/src/omnirush-gateway-broker.test.ts
index 0326798a..ea1e649b 100644
--- a/apps/server/src/omnirush-gateway-broker.test.ts
+++ b/apps/server/src/omnirush-gateway-broker.test.ts
@@ -1426,3 +1426,99 @@ describe("OmniRush gateway broker: connection failures never become a bare 500",
expect(text).toContain("upstream_stream_interrupted");
});
});
+
+describe("OmniRush gateway broker upload keys, account and integrity", () => {
+ const credentials = { gatewayUrl: "https://gateway.example/omnirush/v1", accessToken: "access-1", refreshToken: "refresh-1" };
+
+ test("uploadSession and uploadSessionFile send the Idempotency-Key they are given", async () => {
+ const keys: Array<string | null> = [];
+ const fileKeys: Array<string | undefined> = [];
+ const broker = new OmniRushGatewayBroker({
+ credentials,
+ engineToken: "local-engine-token",
+ fetch: async (_input, init) => {
+ keys.push(new Headers(init?.headers).get("idempotency-key"));
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ uploadFile: async (_url, init) => {
+ fileKeys.push((init.headers as Record<string, string>)["Idempotency-Key"]);
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ });
+ const key = "a".repeat(64);
+ await broker.uploadSession("session-key-1234", new Uint8Array([1, 2, 3]), undefined, { idempotencyKey: key });
+ await broker.uploadSession("session-key-1234", new Uint8Array([1, 2, 3]));
+ await broker.uploadSessionFile("session-key-1234", "/tmp/never-read.zst", 3, undefined, { idempotencyKey: key });
+ expect(keys).toEqual([key, null]);
+ expect(fileKeys).toEqual([key]);
+ });
+
+ test("accountId reads /device/me once and keeps the id; a failure is not remembered", async () => {
+ const urls: string[] = [];
+ let healthy = false;
+ const broker = new OmniRushGatewayBroker({
+ credentials,
+ engineToken: "local-engine-token",
+ fetch: async (input) => {
+ urls.push(String(input));
+ return healthy ? Response.json({ id: "user-1", email: "[email protected]" }) : Response.json({ detail: "down" }, { status: 503 });
+ },
+ });
+ expect(await broker.accountId()).toBeNull();
+ healthy = true;
+ expect(await broker.accountId()).toBe("user-1");
+ expect(await broker.accountId()).toBe("user-1");
+ expect(urls).toEqual(["https://gateway.example/omnirush/device/me", "https://gateway.example/omnirush/device/me"]);
+ });
+
+ test("sessionIntegrity reads the chat's integrity record with the device bearer", async () => {
+ const calls: Array<{ url: string; authorization: string | null }> = [];
+ const broker = new OmniRushGatewayBroker({
+ credentials,
+ engineToken: "local-engine-token",
+ fetch: async (input, init) => {
+ calls.push({ url: String(input), authorization: new Headers(init?.headers).get("authorization") });
+ return Response.json({ integrity: "ok" });
+ },
+ });
+ expect((await broker.sessionIntegrity("ses_abc/1", { turns: 3 })).status).toBe(200);
+ expect((await broker.sessionIntegrity("ses_abc/1", { summary: true })).status).toBe(200);
+ expect(calls).toEqual([
+ { url: "https://gateway.example/omnirush/me/sessions/ses_abc%2F1/integrity?turns=3", authorization: "Bearer access-1" },
+ { url: "https://gateway.example/omnirush/me/sessions/ses_abc%2F1/integrity?summary=1", authorization: "Bearer access-1" },
+ ]);
+ });
+
+ test("sessionIntegrity stays under the route's limit and honours its Retry-After", async () => {
+ let calls = 0;
+ let limited = false;
+ const broker = new OmniRushGatewayBroker({
+ credentials,
+ engineToken: "local-engine-token",
+ fetch: async () => {
+ calls += 1;
+ return limited ? Response.json({ detail: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }) : Response.json({ integrity: "ok" });
+ },
+ });
+ const statuses: number[] = [];
+ for (let index = 0; index < 26; index += 1) statuses.push((await broker.sessionIntegrity("ses_limit_1234", { summary: true })).status);
+ expect(statuses.filter((status) => status === 200)).toHaveLength(24);
+ expect(statuses.slice(-2)).toEqual([429, 429]);
+ expect(calls).toBe(24);
+ const fresh = new OmniRushGatewayBroker({
+ credentials,
+ engineToken: "local-engine-token",
+ fetch: async () => {
+ calls += 1;
+ return Response.json({ detail: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } });
+ },
+ });
+ limited = true;
+ calls = 0;
+ expect((await fresh.sessionIntegrity("ses_limit_1234")).status).toBe(429);
+ const local = await fresh.sessionIntegrity("ses_limit_1234");
+ expect(local.status).toBe(429);
+ expect(Number(local.headers.get("retry-after"))).toBeGreaterThan(25);
+ expect(calls).toBe(1);
+ });
+});
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.ts
index e7ddedc9..bca18754 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -4,7 +4,7 @@ import { createReadStream } from "node:fs";
import { SESSION_UPLOAD_BUDGET, SESSION_UPLOAD_ENDPOINT_PATH, sessionUploadTimeoutMs, type SessionUploadBudget } from "./session-upload-budget.js";
import { externalFetch } from "./server-fetch.js";
import type { OmniRushGatewayCredentials } from "./types.js";
-import type { TraceCapabilities } from "./session-uploader.js";
+import type { TraceCapabilities, UploadRequestOptions } from "./session-uploader.js";
import {
SUBAGENT_FALLBACK_EFFORT_HEADER,
SUBAGENT_FALLBACK_MODEL_HEADER,
@@ -695,6 +695,11 @@ function secureEqual(left: string, right: string): boolean {
return a.length === b.length && a.length > 0 && timingSafeEqual(a, b);
}
+/** Integrity reads per minute this device makes, under the route's 30 per account. */
+const INTEGRITY_CALLS_PER_MINUTE = 24;
+
+export type SessionIntegrityOptions = { summary?: boolean; turns?: number };
+
function refreshUrl(gatewayUrl: string): string {
const url = new URL(gatewayUrl);
url.pathname = url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "") + "/device/refresh";
@@ -997,6 +1002,11 @@ function responseHeaders(headers: Headers): Headers {
export class OmniRushGatewayBroker {
private state: CredentialState | null;
+ private knownAccountId: string | null = null;
+ /** When the last integrity reads went out (one minute's worth), and a Retry-After the route gave. */
+ private integrityCalls: number[] = [];
+ private integrityBlockedUntil = 0;
+ private accountIdLookup: Promise<string | null> | null = null;
private readonly engineToken: string;
private readonly invalidate?: OmniRushGatewayCredentials["invalidate"];
private readonly refreshOwner?: OmniRushGatewayCredentials["refresh"];
@@ -1243,7 +1253,7 @@ export class OmniRushGatewayBroker {
* deadline of its own; `signal`, the session uploader's own deadline or cancel,
* ends either sooner.
*/
- uploadSession(sessionId: string, body: Uint8Array, signal?: AbortSignal): Promise<Response> {
+ uploadSession(sessionId: string, body: Uint8Array, signal?: AbortSignal, options: UploadRequestOptions = {}): Promise<Response> {
const timeoutMs = sessionUploadTimeoutMs(body.byteLength, this.sessionUploadBudget);
return this.withDeviceBearer((state) => this.fetcher(apiUrl(state.gatewayUrl, SESSION_UPLOAD_ENDPOINT_PATH), {
method: "POST",
@@ -1251,13 +1261,14 @@ export class OmniRushGatewayBroker {
Authorization: `Bearer ${state.accessToken}`,
"Content-Type": "application/zstd",
"X-OmniRush-Session-ID": sessionId,
+ ...(options.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}),
},
body: body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer,
signal: signal ? AbortSignal.any([AbortSignal.timeout(timeoutMs), signal]) : AbortSignal.timeout(timeoutMs),
}));
}
- uploadSessionFile(sessionId: string, path: string, size: number, signal?: AbortSignal): Promise<Response> {
+ uploadSessionFile(sessionId: string, path: string, size: number, signal?: AbortSignal, options: UploadRequestOptions = {}): Promise<Response> {
const timeoutMs = sessionUploadTimeoutMs(size, this.sessionUploadBudget);
return this.withDeviceBearer(async (state) => {
const requestSignal = signal ? AbortSignal.any([AbortSignal.timeout(timeoutMs), signal]) : AbortSignal.timeout(timeoutMs);
@@ -1266,6 +1277,7 @@ export class OmniRushGatewayBroker {
Authorization: `Bearer ${state.accessToken}`,
"Content-Type": "application/zstd",
"X-OmniRush-Session-ID": sessionId,
+ ...(options.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : {}),
};
// The Electron file transport bypasses this.fetcher.
if (this.clientHeader) headers[CLIENT_HEADER] = this.clientHeader;
@@ -1321,6 +1333,71 @@ export class OmniRushGatewayBroker {
this.capabilityProbe = null;
}
+ /**
+ * The server's integrity record of one chat (GET
+ * `<gateway root>/me/sessions/{id}/integrity`), with the device bearer and
+ * the same bounded 401 refresh as uploadSession(). `turns` is the client's
+ * count of completed turns; `summary` leaves out the per-upload rows. The
+ * route allows 30 calls a minute per account: past INTEGRITY_CALLS_PER_MINUTE
+ * here, or before a Retry-After it gave, the answer is a local 429.
+ */
+ async sessionIntegrity(sessionId: string, options: SessionIntegrityOptions = {}): Promise<Response> {
+ const now = Date.now();
+ this.integrityCalls = this.integrityCalls.filter((at) => now - at < 60_000);
+ const waitMs = Math.max(this.integrityBlockedUntil - now, this.integrityCalls.length >= INTEGRITY_CALLS_PER_MINUTE ? this.integrityCalls[0]! + 60_000 - now : 0);
+ if (waitMs > 0) {
+ return Response.json({ detail: "rate_limited" }, { status: 429, headers: { "Retry-After": String(Math.ceil(waitMs / 1_000)) } });
+ }
+ this.integrityCalls.push(now);
+ const response = await this.withDeviceBearer((state) => {
+ const url = new URL(apiUrl(state.gatewayUrl, `me/sessions/${encodeURIComponent(sessionId)}/integrity`));
+ if (options.summary) url.searchParams.set("summary", "1");
+ if (options.turns !== undefined && Number.isSafeInteger(options.turns) && options.turns >= 0) url.searchParams.set("turns", String(options.turns));
+ return this.fetcher(url.toString(), {
+ method: "GET",
+ headers: { Authorization: `Bearer ${state.accessToken}`, Accept: "application/json" },
+ signal: AbortSignal.timeout(10_000),
+ });
+ });
+ if (response.status === 429) {
+ const retryAfter = Number(response.headers.get("retry-after"));
+ this.integrityBlockedUntil = Date.now() + (Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 3_600) * 1_000 : 60_000);
+ }
+ return response;
+ }
+
+ /**
+ * The id of the account behind the device bearer (`<gateway root>/device/me`),
+ * learned once: an account change restarts the server. Null while it
+ * cannot be learned (signed out, offline, an unexpected answer).
+ */
+ accountId(): Promise<string | null> {
+ if (this.knownAccountId) return Promise.resolve(this.knownAccountId);
+ this.accountIdLookup ??= (async () => {
+ try {
+ const response = await this.withDeviceBearer((state) => this.fetcher(apiUrl(state.gatewayUrl, "device/me"), {
+ method: "GET",
+ headers: { Authorization: `Bearer ${state.accessToken}`, Accept: "application/json" },
+ signal: AbortSignal.timeout(8_000),
+ }));
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ return null;
+ }
+ const text = await boundedText(response, 256 * 1024);
+ const payload: unknown = text === null ? null : JSON.parse(text);
+ const id = isRecord(payload) && typeof payload.id === "string" ? payload.id.trim() : "";
+ if (id) this.knownAccountId = id;
+ return id || null;
+ } catch {
+ return null;
+ } finally {
+ this.accountIdLookup = null;
+ }
+ })();
+ return this.accountIdLookup;
+ }
+
private capabilityKey(state: CredentialState): string {
return `${state.gatewayUrl}\0${state.refreshToken}`;
}
diff --git a/apps/server/src/opencode-proxy-gate.test.ts b/apps/server/src/opencode-proxy-gate.test.ts
index 5b541977..174ee815 100644
--- a/apps/server/src/opencode-proxy-gate.test.ts
+++ b/apps/server/src/opencode-proxy-gate.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
import {
assertOpencodeProxyAllowed,
+ engineHasSession,
normalizeOpencodeDirectory,
proxyOpencodeRequest,
scopeWorkspaceOpencodeRequest,
@@ -161,3 +162,30 @@ describe("proxyOpencodeRequest read-only guard", () => {
expect(error instanceof ApiError ? error.code : null).toBe("opencode_unconfigured");
});
});
+
+describe("engineHasSession", () => {
+ test("false only when the engine answers 404; a slow or unreachable engine counts as having it", async () => {
+ const seen: Array<{ path: string; directory: string | null; authorization: string | null }> = [];
+ const engine = Bun.serve({
+ port: 0,
+ hostname: "127.0.0.1",
+ fetch: async (request) => {
+ const url = new URL(request.url);
+ seen.push({ path: url.pathname, directory: url.searchParams.get("directory"), authorization: request.headers.get("authorization") });
+ if (url.pathname === "/session/ses_known_00001") return Response.json({ id: "ses_known_00001" });
+ if (url.pathname === "/session/ses_slow_000001") return new Promise<Response>(() => undefined);
+ return Response.json({ name: "NotFoundError" }, { status: 404 });
+ },
+ });
+ try {
+ const baseUrl = `http://127.0.0.1:${engine.port}`;
+ expect(await engineHasSession(baseUrl, "Basic abc", "/work", "ses_known_00001")).toBe(true);
+ expect(await engineHasSession(baseUrl, "Basic abc", "/work", "ses_gone_000001")).toBe(false);
+ expect(await engineHasSession(baseUrl, null, null, "ses_slow_000001")).toBe(true);
+ expect(await engineHasSession("http://127.0.0.1:1", null, null, "ses_down_000001")).toBe(true);
+ expect(seen[0]).toEqual({ path: "/session/ses_known_00001", directory: "/work", authorization: "Basic abc" });
+ } finally {
+ engine.stop(true);
+ }
+ }, 15_000);
+});
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 57e27047..7f93512b 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -901,6 +901,31 @@ function uploadDeletedSessionId(method: string, proxyPath: string): string | nul
type EngineRequestTarget = { baseUrl: string; headers: Headers };
+/** How long the existence check before a chat's first captured prompt waits for the engine. */
+const ENGINE_SESSION_CHECK_TIMEOUT_MS = 3_000;
+
+/**
+ * Whether the engine has this session: false only when it answers 404. An
+ * engine that is slow or unreachable counts as having it, so no prompt it
+ * does run goes uncaptured.
+ */
+export async function engineHasSession(baseUrl: string, auth: string | null, directory: string | null, sessionId: string): Promise<boolean> {
+ const headers = new Headers();
+ if (auth) headers.set("Authorization", auth);
+ const scoped = scopeWorkspaceOpencodeRequest(headers, "", directory);
+ try {
+ const response = await loopbackFetch(buildOpencodeProxyUrl(baseUrl, `/session/${encodeURIComponent(sessionId)}`, scoped.search), {
+ method: "GET",
+ headers: scoped.headers,
+ signal: AbortSignal.timeout(ENGINE_SESSION_CHECK_TIMEOUT_MS),
+ });
+ await response.body?.cancel().catch(() => undefined);
+ return response.status !== 404;
+ } catch {
+ return true;
+ }
+}
+
const SESSION_STOP_TIMEOUT_MS = 5_000;
const SESSION_STOP_MAX_SESSIONS = 100;
@@ -973,12 +998,12 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
credentials: gatewayCredentials
? {
...gatewayCredentials,
- // Revoked or expired omnirush.ai credentials also discard spooled
- // session uploads and queued project archives: a signed-out
- // account leaves nothing queued.
+ // A device session the server retired (a refused refresh) keeps
+ // the queued uploads and archives, each stamped with its account,
+ // for when the account signs in again; only a user's sign-out
+ // deletes them (config.clearUploadQueue at the next start).
invalidate: async () => {
gatewayBroker.resetCapabilities();
- await capture.signOut();
await gatewayCredentials.invalidate?.();
},
}
@@ -1035,10 +1060,13 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
// "opencode/1.18.32-r2": the bundled engine, as every upload names it (engine-identity.ts).
engineVersion: BUNDLED_ENGINE_VERSION,
log: (level, message, attributes) => logger.log(level, message, attributes),
+ ...(gatewayBroker.enabled
+ ? { accountId: () => gatewayBroker.accountId(), sessionIntegrity: (sessionId: string, options?: { summary?: boolean; turns?: number }) => gatewayBroker.sessionIntegrity(sessionId, options) }
+ : {}),
sessionUploader: gatewayBroker.enabled
? {
- upload: (sessionId, compressed, signal) => gatewayBroker.uploadSession(sessionId, compressed, signal),
- uploadFile: (sessionId, path, size, signal) => gatewayBroker.uploadSessionFile(sessionId, path, size, signal),
+ upload: (sessionId, compressed, signal, request) => gatewayBroker.uploadSession(sessionId, compressed, signal, request),
+ uploadFile: (sessionId, path, size, signal, request) => gatewayBroker.uploadSessionFile(sessionId, path, size, signal, request),
capabilities: () => gatewayBroker.sessionUploadCapabilities(),
refreshAccessToken: () => gatewayBroker.refreshAccessToken(),
}
@@ -1060,6 +1088,10 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
},
});
captureServicesByServer.set(config, capture);
+ if (config.clearUploadQueue) {
+ // The user signed out: what the last account queued is deleted before anything else runs.
+ await Promise.race([capture.signOut(), new Promise((resolvePromise) => setTimeout(resolvePromise, 10_000).unref?.())]);
+ }
try {
await reconcileLocalManagedMcpRuntimeEntries(config);
} catch (error) {
@@ -2037,7 +2069,11 @@ export async function proxyOpencodeRequest(input: {
const capture = workspace ? captureServicesByServer.get(input.config) : undefined;
const uploadedSessionId = uploadSessionId(proxyPath);
const deletedUploadedSessionId = uploadDeletedSessionId(method, proxyPath);
- if (capture?.uploadEnabled && uploadedSessionId && workspace && workspace.workspaceType !== "remote") {
+ // A chat the engine does not have (a stale tab, a deleted chat) is not
+ // started: its prompt is refused, and it would only leave an empty start
+ // and end snapshot behind.
+ if (capture?.uploadEnabled && uploadedSessionId && workspace && workspace.workspaceType !== "remote"
+ && (capture.hasSession(uploadedSessionId) || await engineHasSession(baseUrl, auth, directory, uploadedSessionId))) {
const promptDispatch = isUploadPromptDispatch(method, proxyPath);
// Capture v2: the session-start manifest is taken before the prompt reaches the engine (at most about 3 s).
if (promptDispatch) await capture.archiveStartGate(uploadedSessionId, workspace.path);
diff --git a/apps/server/src/session-archive/index.test.ts b/apps/server/src/session-archive/index.test.ts
index 32198311..b38401c8 100644
--- a/apps/server/src/session-archive/index.test.ts
+++ b/apps/server/src/session-archive/index.test.ts
@@ -578,6 +578,34 @@ describe("SessionArchiver", () => {
expect(server.objects().at(-1)!.request).toMatchObject({ session_id: "ses_rotated_key", kind: "base", turn: 1 });
});
+ test("claimAccount keeps the queue for the same account and removes another account's", async () => {
+ const server = new FakeArchiveServer();
+ const { root } = await project();
+ const state = await tempDir("state");
+ let account: string | null = "user-a";
+ const first = archiver(server, state, { accountId: async () => account });
+ await first.claimAccount();
+ expect((await first.captureBase("ses_account_a", root)).status).toBe("queued");
+ await first.stop();
+ // The same account after a restart (a retired sign-in, then signed in again): its queue is still there.
+ const again = archiver(server, state, { accountId: async () => account });
+ await again.claimAccount();
+ expect((await again.drain()).uploaded).toBe(1);
+ await again.stop();
+ // Another account: what user-a queued is removed, never uploaded for user-b.
+ account = "user-b";
+ const other = archiver(server, state, { accountId: async () => account });
+ const uploadsBefore = server.objects().length;
+ await other.claimAccount();
+ expect((await other.drain()).uploaded).toBe(0);
+ expect(server.objects().length).toBe(uploadsBefore);
+ expect(await readFile(join(state, ARCHIVE_STATE_DIRECTORY, "account.json"), "utf8")).toContain("user-b");
+ // While the account cannot be learned nothing changes.
+ account = null;
+ await other.claimAccount();
+ expect(await readFile(join(state, ARCHIVE_STATE_DIRECTORY, "account.json"), "utf8")).toContain("user-b");
+ });
+
test("signOut aborts uploads in flight and removes every queued archive and record", async () => {
const server = new FakeArchiveServer();
const { root } = await project();
diff --git a/apps/server/src/session-archive/index.ts b/apps/server/src/session-archive/index.ts
index 06ee2c0c..528136f8 100644
--- a/apps/server/src/session-archive/index.ts
+++ b/apps/server/src/session-archive/index.ts
@@ -210,8 +210,13 @@ export type SessionArchiverOptions = {
minimumFreeDiskBytes?: number;
/** Tests and diagnostics: override the filesystem free-space probe. */
freeDiskBytes?: (path: string) => Promise<number>;
+ /** The signed-in account's id (null: not known now): queued archives of another account are never uploaded for this one. */
+ accountId?: () => Promise<string | null>;
};
+/** How long claimAccount() waits to learn the account. */
+const ACCOUNT_LOOKUP_TIMEOUT_MS = 5_000;
+
export type CaptureSkipReason =
| "not_archivable"
| "disabled"
@@ -435,6 +440,7 @@ export class SessionArchiver {
private readonly pendingByteBudget: number;
private readonly minimumFreeDiskBytes: number;
private readonly freeDiskBytes: (path: string) => Promise<number>;
+ private readonly accountId?: () => Promise<string | null>;
private packingReservedBytes = 0;
private budgetTail: Promise<void> = Promise.resolve();
private started: Promise<void> | null = null;
@@ -498,6 +504,7 @@ export class SessionArchiver {
};
this.pendingByteBudget = archiveDiskBytes(options.pendingByteBudget, "OMNIRUSH_ARCHIVE_PENDING_BYTE_BUDGET", DEFAULT_PENDING_BYTE_BUDGET);
this.minimumFreeDiskBytes = archiveDiskBytes(options.minimumFreeDiskBytes, "OMNIRUSH_ARCHIVE_MIN_FREE_DISK_BYTES", DEFAULT_MIN_FREE_DISK_BYTES);
+ this.accountId = options.accountId;
this.freeDiskBytes = options.freeDiskBytes ?? (async (path) => {
const filesystem = await statfs(path);
return Number(filesystem.bavail) * Number(filesystem.bsize);
@@ -542,6 +549,36 @@ export class SessionArchiver {
return this.started;
}
+ /**
+ * App start with an account: the archive state on disk is this account's.
+ * The state a device session the server retired left behind waits for the
+ * account to come back (only a user's sign-out removes it, signOut()); if
+ * another account signed in meanwhile, it is removed rather than uploaded
+ * for that one. Nothing happens while the account cannot be learned.
+ */
+ async claimAccount(): Promise<void> {
+ if (!this.accountId) return;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const id = await Promise.race([
+ this.accountId().catch(() => null),
+ new Promise<null>((resolvePromise) => {
+ timer = setTimeout(() => resolvePromise(null), ACCOUNT_LOOKUP_TIMEOUT_MS);
+ timer.unref?.();
+ }),
+ ]).finally(() => clearTimeout(timer));
+ if (!id) return;
+ const path = join(this.dir, "account.json");
+ const saved = await readJsonFile(path);
+ const owner = saved && typeof saved === "object" && typeof Reflect.get(saved, "account_id") === "string" ? String(Reflect.get(saved, "account_id")) : null;
+ if (owner === id) return;
+ if (owner) {
+ this.log("warn", "OmniRush project archives queued for another account were removed", {});
+ await this.signOut();
+ }
+ await mkdir(this.dir, { recursive: true, mode: 0o700 });
+ await writeJsonAtomic(path, { v: 1, account_id: id });
+ }
+
/** The device bearer changed (session uploader token rotation). */
setAccessToken(token: string | null): void {
this.uploader.setAccessToken(token);
diff --git a/apps/server/src/session-archive/lifecycle.test.ts b/apps/server/src/session-archive/lifecycle.test.ts
index 7c5b5afa..424322ba 100644
--- a/apps/server/src/session-archive/lifecycle.test.ts
+++ b/apps/server/src/session-archive/lifecycle.test.ts
@@ -115,11 +115,12 @@ function engine(input: { parentID?: string; messages?: () => unknown; session?:
return { reader, reads };
}
-function lifecycle(archiver: ProjectArchiver, options: { enabled?: boolean; now?: () => number; concurrency?: number; finalIdleMs?: number; quitBudgetMs?: number } = {}) {
+function lifecycle(archiver: ProjectArchiver, options: { enabled?: boolean; accountMissing?: boolean; now?: () => number; concurrency?: number; finalIdleMs?: number; quitBudgetMs?: number } = {}) {
const logs: Array<{ level: string; message: string; attributes?: Record<string, unknown> }> = [];
const subject = new ProjectArchiveLifecycle({
archiver,
enabled: options.enabled ?? true,
+ ...(options.accountMissing ? { accountMissing: true } : {}),
log: (level, message, attributes) => logs.push({ level, message, ...(attributes ? { attributes } : {}) }),
consentRecheckMs: 60_000,
...(options.now ? { now: options.now } : {}),
@@ -333,7 +334,28 @@ describe("ProjectArchiveLifecycle", () => {
expect(archiver.calls).toEqual(["drain", `base ses_resumed_0001 ${root} 3`, `delta ses_resumed_0001 ${root} 4`, "drain"]);
});
- test("without an account (or with archiving turned off) start clears what a previous run left and nothing is captured", async () => {
+ test("without an account the queue a previous run left waits for it (a refused refresh never clears it) and nothing is captured", async () => {
+ const archiver = new FakeArchiver();
+ const { subject } = lifecycle(archiver, { enabled: false, accountMissing: true });
+ subject.start();
+ const root = await tempDir("root");
+ subject.sessionStarted({ sessionId: "ses_retired_0001", root, engine: engine().reader });
+ subject.turnCompleted("ses_retired_0001", messages(1));
+ await subject.settled();
+ expect(archiver.calls).toEqual([]);
+ });
+
+ test("with an account, start first claims the queue for it, then drains", async () => {
+ const archiver = new FakeArchiver();
+ const calls = archiver.calls;
+ const claiming = Object.assign(archiver, { claimAccount: async () => { calls.push("claim"); } });
+ const { subject } = lifecycle(claiming);
+ subject.start();
+ await subject.settled();
+ expect(calls.slice(0, 2)).toEqual(["claim", "drain"]);
+ });
+
+ test("with archiving turned off on this device start clears what a previous run left and nothing is captured", async () => {
const archiver = new FakeArchiver();
const { subject } = lifecycle(archiver, { enabled: false });
subject.start();
diff --git a/apps/server/src/session-archive/lifecycle.ts b/apps/server/src/session-archive/lifecycle.ts
index 4000331b..2fd2a324 100644
--- a/apps/server/src/session-archive/lifecycle.ts
+++ b/apps/server/src/session-archive/lifecycle.ts
@@ -21,7 +21,7 @@ import type { UsedToolCall } from "./files-used.js";
export type ProjectArchiver = Pick<
SessionArchiver,
"captureBase" | "captureDelta" | "captureFinal" | "startFinalCandidates" | "recordTouched" | "forgetTouched" | "drain" | "signOut" | "stop"
-> & Partial<Pick<SessionArchiver, "startManifest" | "hasStartManifest" | "captureState" | "recordAttachments" | "recordBinary" | "filesUsedToolCallEnded" | "filesUsedTurnStarted" | "filesUsedTurnEnded" | "filesUsedMaybe" | "filesUsedStatus">>;
+> & Partial<Pick<SessionArchiver, "claimAccount" | "startManifest" | "hasStartManifest" | "captureState" | "recordAttachments" | "recordBinary" | "filesUsedToolCallEnded" | "filesUsedTurnStarted" | "filesUsedTurnEnded" | "filesUsedMaybe" | "filesUsedStatus">>;
/** Engine reads for one session, resolving to the parsed JSON, or null when it cannot be read. */
export type ArchiveEngineReads = {
@@ -37,6 +37,11 @@ export type ProjectArchiveLifecycleOptions = {
archiver: ProjectArchiver;
/** An account is connected and OMNIRUSH_ARCHIVE_ENABLED is not off. */
enabled: boolean;
+ /**
+ * No account is connected (a sign-in the server retired, or none yet):
+ * the queue on disk waits for it rather than being removed.
+ */
+ accountMissing?: boolean;
log: ArchiveLifecycleLog;
/** Session steps (engine reads plus a capture) running at once. */
concurrency?: number;
@@ -190,6 +195,7 @@ export class ProjectArchiveLifecycle {
private readonly quitBudgetMs: number;
private readonly now: () => number;
private readonly enabled: boolean;
+ private readonly accountMissing: boolean;
private signedOut = false;
private stopped = false;
/** Archiving is off for the account until then (428 / 503 archive_disabled). */
@@ -211,6 +217,7 @@ export class ProjectArchiveLifecycle {
constructor(options: ProjectArchiveLifecycleOptions) {
this.archiver = options.archiver;
this.enabled = options.enabled;
+ this.accountMissing = options.accountMissing === true;
this.log = options.log;
this.concurrency = Math.max(1, options.concurrency ?? 1);
this.consentRecheckMs = options.consentRecheckMs ?? DEFAULT_CONSENT_RECHECK_MS;
@@ -233,19 +240,22 @@ export class ProjectArchiveLifecycle {
* App start. With an account, resumes the uploads the last run left
* unfinished, and checks the folders of recent sessions once for changes
* made after their last archive (a final archive the last shutdown did not
- * get to, or edits while the app was closed). Without one (signed out, or
- * archiving turned off on this device), removes whatever a previous run
- * left: nothing queued under an account may be uploaded later.
+ * get to, or edits while the app was closed); a queue another account left
+ * is removed first (claimAccount). Without an account the queue waits for
+ * it (a user's sign-out removes it, signOut()); with archiving turned off
+ * on this device it is removed.
*/
start(): void {
if (!this.enabled) {
- this.track(this.archiver.signOut().catch((error: unknown) => this.warn("clear", error)));
+ if (!this.accountMissing) this.track(this.archiver.signOut().catch((error: unknown) => this.warn("clear", error)));
return;
}
- this.kick();
- this.track(this.archiver.startFinalCandidates().then((sessionIds) => {
+ this.track((async () => {
+ await this.archiver.claimAccount?.().catch((error: unknown) => this.warn("account", error));
+ this.kick();
+ const sessionIds = await this.archiver.startFinalCandidates();
for (const sessionId of sessionIds) this.final(sessionId, "app_start");
- }, (error: unknown) => this.warn("start", error)));
+ })().catch((error: unknown) => this.warn("start", error)));
}
/**
diff --git a/apps/server/src/session-uploader.server.e2e.test.ts b/apps/server/src/session-uploader.server.e2e.test.ts
index bad2d13e..6a32c83a 100644
--- a/apps/server/src/session-uploader.server.e2e.test.ts
+++ b/apps/server/src/session-uploader.server.e2e.test.ts
@@ -534,6 +534,40 @@ describe("session uploader server integration", () => {
expect(events(turnThree).map((event) => event.type)).toContain("session.resumed");
}, 90_000);
+ test("a prompt to a chat the engine does not have starts nothing: no start or end snapshot", async () => {
+ const { root, stateDir } = await createWorkspace();
+ const engine = startMockEngine({ provider: "anthropic", model: "claude-sonnet-4-5" });
+ const gateway = startMockGateway();
+ const omnirush = await startOmniRush(serverConfig({ root, stateDir, engineBaseUrl: engine.baseUrl, gatewayUrl: gateway.gatewayUrl }));
+ const response = await fetch(`${omnirush.base}/workspace/ws_1/opencode/session/ses_missing_chat/prompt_async`, {
+ method: "POST",
+ headers: { Authorization: "Bearer owt_test_token", "content-type": "application/json" },
+ body: JSON.stringify({ parts: [{ type: "text", text: "Do the task" }] }),
+ });
+ expect(response.status).toBe(404);
+ await omnirush.stop();
+ expect(gateway.uploads.filter((upload) => upload.sessionId === "ses_missing_chat")).toEqual([]);
+ }, 30_000);
+
+ test("a user's sign-out (clearUploadQueue) deletes the queued uploads; a start without an account keeps them", async () => {
+ const { root, stateDir } = await createWorkspace();
+ const engine = startMockEngine({ provider: "anthropic", model: "claude-sonnet-4-5" });
+ const spool = join(stateDir, "omnirush-upload-spool");
+ await mkdir(spool, { recursive: true });
+ const id = "000000000001-000001-00000001";
+ await writeFile(join(spool, `${id}.zst`), Buffer.alloc(64, 1));
+ await writeFile(join(spool, `${id}.json`), JSON.stringify({ id, session_id: "ses_queued_0001", snapshot_type: "trace", trigger: "trace_flush", sequence: 1, bytes: 64, created_at: new Date().toISOString(), attempts: 1, account_id: "user-1" }));
+ // Signed out by a refused refresh: the next start has no account, and the queue stays.
+ const retired = await startOmniRush(serverConfig({ root, stateDir, engineBaseUrl: engine.baseUrl }));
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ await retired.stop();
+ expect((await readdir(spool)).sort()).toEqual([`${id}.json`, `${id}.zst`]);
+ // The user signed out: the start after it deletes it.
+ const signedOut = await startOmniRush({ ...serverConfig({ root, stateDir, engineBaseUrl: engine.baseUrl }), clearUploadQueue: true });
+ await signedOut.stop();
+ expect(await readdir(spool).catch(() => [])).toEqual([]);
+ }, 30_000);
+
test("refuses prompt dispatch on a local workspace without an account, unless both development flags are set", async () => {
const { root, stateDir } = await createWorkspace();
const engine = startMockEngine({ provider: "anthropic", model: "claude-sonnet-4-5" });
diff --git a/apps/server/src/session-uploader.test.ts b/apps/server/src/session-uploader.test.ts
index cf7383b0..00a9d68c 100644
--- a/apps/server/src/session-uploader.test.ts
+++ b/apps/server/src/session-uploader.test.ts
@@ -16,6 +16,9 @@ import {
MAX_UPLOAD_TRACE_BYTES,
MAX_UPLOAD_TRACE_EVENTS,
MAX_UPLOAD_WEB_VISIT_TEXT_BYTES,
+ MAX_SPOOL_AGE_MS,
+ uploadIdempotencyKey,
+ serverSessionPosition,
SessionUploader,
isRetryableUploadStatus,
mapBounded,
@@ -182,6 +185,169 @@ describe("session uploader privacy", () => {
expect(parsed!.dropped_event_count).toBeGreaterThanOrEqual(1);
});
+ test("every upload carries the Idempotency-Key of its session, segment, sequence and type, and its sequence is taken first", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-keys-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-keys-state-"));
+ roots.push(root, stateDir);
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const sent: Array<{ key: string | undefined; envelope: Record<string, unknown> }> = [];
+ const sessionUploader = new SessionUploader({
+ stateDir,
+ upload: async (_sessionId, compressed, _signal, request) => {
+ sent.push({ key: request?.idempotencyKey, envelope: JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown> });
+ // An envelope the server refuses keeps its sequence: the next one never reuses its key.
+ return sent.length === 2 ? Response.json({ detail: "bad" }, { status: 422 }) : Response.json({ ok: true }, { status: 201 });
+ },
+ fallbackScanMs: 60_000,
+ });
+ const sessionId = "session-keys-1234";
+ sessionUploader.startSession(sessionId, "workspace-keys", root);
+ sessionUploader.recordTrace(sessionId, "tool.call", {});
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.idle(sessionId);
+ sessionUploader.recordTrace(sessionId, "tool.call", {});
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
+ expect(sent.map((item) => [item.envelope.snapshot_type, item.envelope.sequence])).toEqual([["start", 1], ["trace", 2], ["trace", 3], ["end", 4]]);
+ for (const item of sent) {
+ const envelope = item.envelope as { session_id: string; session_segment: number; sequence: number; snapshot_type: "start" | "trace" | "end" };
+ expect(item.key).toBe(uploadIdempotencyKey(envelope.session_id, envelope.session_segment, envelope.sequence, envelope.snapshot_type));
+ }
+ });
+
+ test("a chat the local ledger does not know continues after the server's segment and sequence", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-position-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-position-state-"));
+ roots.push(root, stateDir);
+ const envelopes: Array<Record<string, unknown>> = [];
+ const asked: string[] = [];
+ const sessionUploader = new SessionUploader({
+ stateDir,
+ upload: async (_sessionId, compressed) => {
+ envelopes.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>);
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ sessionIntegrity: async (sessionId, options) => {
+ asked.push(`${sessionId}:${options?.summary === true}`);
+ return Response.json({ session_id: sessionId, segments: [
+ { segment: 1, sequences: [1, 2, 3], gaps: [], max_sequence: 3 },
+ { segment: 3, sequences: [9, 10], gaps: [], max_sequence: 10 },
+ ] });
+ },
+ fallbackScanMs: 60_000,
+ });
+ const sessionId = "session-position-1234";
+ sessionUploader.startSession(sessionId, "workspace-position", root);
+ await sessionUploader.stop();
+ expect(asked).toEqual([`${sessionId}:true`]);
+ expect(envelopes[0]).toMatchObject({ snapshot_type: "start", trigger: "resume", session_segment: 4, sequence: 11, session_resumed: true });
+ });
+
+ test("a new chat the server has never seen starts at segment 1; the lookup is skipped once the ledger knows it", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-newchat-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-newchat-state-"));
+ roots.push(root, stateDir);
+ const envelopes: Array<Record<string, unknown>> = [];
+ let asked = 0;
+ const make = () => new SessionUploader({
+ stateDir,
+ upload: async (_sessionId, compressed) => {
+ envelopes.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>);
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ sessionIntegrity: async () => {
+ asked += 1;
+ return Response.json({ detail: "session_not_found" }, { status: 404 });
+ },
+ fallbackScanMs: 60_000,
+ });
+ const first = make();
+ first.startSession("session-newchat-1234", "workspace-newchat", root);
+ await first.stop();
+ const second = make();
+ second.startSession("session-newchat-1234", "workspace-newchat", root);
+ await second.stop();
+ expect(asked).toBe(1);
+ expect(envelopes.filter((item) => item.snapshot_type === "start").map((item) => [item.session_segment, item.sequence])).toEqual([[1, 1], [2, 3]]);
+ });
+
+ test("an Idempotency-Key the server holds with other bytes moves the chat past the server's numbering and sends the trace again once", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-reused-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-reused-state-"));
+ roots.push(root, stateDir);
+ const accepted: Array<Record<string, unknown>> = [];
+ let lookups = 0;
+ const sessionUploader = new SessionUploader({
+ stateDir,
+ upload: async (_sessionId, compressed) => {
+ const envelope = JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>;
+ // The server already holds segment 1 up to sequence 5 (this device's ledger was lost).
+ if (envelope.session_segment === 1 && Number(envelope.sequence) <= 5 && envelope.snapshot_type === "trace") {
+ return Response.json({ detail: "idempotency_key_reused" }, { status: 409 });
+ }
+ accepted.push(envelope);
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ sessionIntegrity: async () => {
+ lookups += 1;
+ // Offline for the first lookup at start; known by the time of the 409.
+ return lookups === 1
+ ? Response.json({ detail: "unavailable" }, { status: 503 })
+ : Response.json({ segments: [{ segment: 1, sequences: [1, 2, 3, 4, 5], gaps: [], max_sequence: 5 }] });
+ },
+ fallbackScanMs: 60_000,
+ });
+ const sessionId = "session-reused-1234";
+ sessionUploader.startSession(sessionId, "workspace-reused", root);
+ sessionUploader.recordTrace(sessionId, "tool.call", { n: 1 });
+ sessionUploader.flushTrace(sessionId);
+ await sessionUploader.stop();
+ const trace = accepted.find((item) => item.snapshot_type === "trace");
+ expect(trace).toMatchObject({ session_segment: 2, sequence: 6 });
+ expect(JSON.stringify(accepted)).toContain("collector.resegmented");
+ expect(accepted.map((item) => [item.snapshot_type, item.session_segment, item.sequence])).toEqual([["start", 1, 1], ["trace", 2, 6], ["trace", 2, 7], ["end", 2, 8]]);
+ });
+
+ test("reads the server's position from an integrity answer", () => {
+ expect(serverSessionPosition({ segments: [{ segment: null, sequences: [1, 4], max_sequence: 4 }, { segment: 2, sequences: [7], max_sequence: 7 }] })).toEqual({ segment: 2, sequence: 7 });
+ expect(serverSessionPosition({ segments: [] })).toBeNull();
+ expect(serverSessionPosition({ detail: "session_not_found" })).toBeNull();
+ expect(serverSessionPosition({ summary: true, max_segment: 3, max_sequence: 12, segments: [] })).toEqual({ segment: 3, sequence: 12 });
+ expect(serverSessionPosition({ summary: true, max_segment: null, max_sequence: null, segments: [] })).toBeNull();
+ });
+
+ test("the ledger keeps far more than 512 chats, so an older one resumed continues its numbering; only the newest keep sub-agent detail", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-ledger-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-ledger-state-"));
+ roots.push(root, stateDir);
+ const sessions: Record<string, unknown> = {};
+ for (let index = 0; index < 1_200; index += 1) {
+ sessions[`session-ledger-${String(index).padStart(5, "0")}`] = {
+ segment: 2,
+ nextSequence: 40,
+ lastSeenAt: new Date(Date.UTC(2026, 0, 1) + index * 60_000).toISOString(),
+ childSessionIds: ["child-a"],
+ };
+ }
+ await writeFile(join(stateDir, "omnirush-upload-sessions.json"), JSON.stringify({ version: 1, sessions }));
+ const envelopes: Array<Record<string, unknown>> = [];
+ const sessionUploader = new SessionUploader({
+ stateDir,
+ upload: async (_sessionId, compressed) => {
+ envelopes.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>);
+ return Response.json({ ok: true }, { status: 201 });
+ },
+ fallbackScanMs: 60_000,
+ });
+ // The oldest chat of the 1,200 (it fell out of the old 512 cap).
+ sessionUploader.startSession("session-ledger-00000", "workspace-ledger", root);
+ await sessionUploader.stop();
+ expect(envelopes[0]).toMatchObject({ snapshot_type: "start", session_segment: 3, sequence: 41, session_resumed: true });
+ const ledger = JSON.parse(await readFile(join(stateDir, "omnirush-upload-sessions.json"), "utf8")) as { sessions: Record<string, { childSessionIds?: string[] }> };
+ expect(Object.keys(ledger.sessions)).toHaveLength(1_200);
+ expect(Object.values(ledger.sessions).filter((record) => record.childSessionIds)).toHaveLength(512);
+ });
+
test("persists session segments and message checkpoints across a resume", async () => {
const root = await mkdtemp(join(tmpdir(), "omnirush-upload-resume-"));
const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-state-"));
@@ -916,7 +1082,7 @@ describe("session uploader durable retry", () => {
await uploader.clearSpool();
await uploader.stop();
}
- });
+ }, 20_000);
test("bounds the spool, drops permanently rejected uploads and clears on request", async () => {
const root = await mkdtemp(join(tmpdir(), "omnirush-upload-spoolcap-"));
@@ -1126,23 +1292,136 @@ describe("session upload deadline and spool drain", () => {
await sessionUploader.stop();
});
- test("drops an entry once it reaches the attempt limit", async () => {
+ test("a long outage keeps every entry however many attempts fail; only age drops one", async () => {
const stateDir = await drainState();
- await spoolEntry(stateDir, 1, 512, { attempts: 23 });
- await spoolEntry(stateDir, 2, 512);
+ // 85 min of 503s used to drop an entry at its 24th attempt; it is kept now.
+ await spoolEntry(stateDir, 1, 512, { attempts: 400 });
+ await spoolEntry(stateDir, 2, 512, { created_at: new Date(Date.now() - 2 * 60 * 60_000).toISOString() });
const warnings: string[] = [];
const sessionUploader = new SessionUploader({
stateDir,
upload: async () => Response.json({ error: "unavailable" }, { status: 503 }),
- log: (level, message) => { if (level === "warn") warnings.push(message); },
+ log: (level, message, attributes) => { if (level === "warn") warnings.push(`${message}:${String(attributes?.reason ?? "")}`); },
retryBaseMs: 60_000,
+ // A short age limit stands in for the 7 days.
+ spoolMaxAgeMs: 60 * 60_000,
});
expect(await sessionUploader.drainSpool()).toEqual({ delivered: 0, pending: 1 });
- expect(warnings).toEqual(["OmniRush session upload artifact dropped from spool"]);
+ expect(warnings).toEqual(["OmniRush session upload artifact dropped from spool:expired"]);
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 1, bytes: 512 });
+ await sessionUploader.stop();
+ });
+
+ test("the default age limit is seven days", () => {
+ expect(MAX_SPOOL_AGE_MS).toBe(7 * 24 * 60 * 60_000);
+ });
+
+ test("a non-retryable answer still drops the entry", async () => {
+ const stateDir = await drainState();
+ await spoolEntry(stateDir, 1, 512);
+ const sessionUploader = new SessionUploader({
+ stateDir,
+ upload: async () => Response.json({ detail: "idempotency_key_reused" }, { status: 409 }),
+ retryBaseMs: 60_000,
+ });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 0, pending: 0 });
+ expect(await sessionUploader.spoolStatus()).toEqual({ entries: 0, bytes: 0 });
+ await sessionUploader.stop();
+ });
+
+ test("traces have their own spool budget: a large snapshot never pushes one out", async () => {
+ const stateDir = await drainState();
+ await spoolEntry(stateDir, 1, 600, { snapshot_type: "trace", trigger: "trace_flush" });
+ await spoolEntry(stateDir, 2, 600, { snapshot_type: "trace", trigger: "trace_flush" });
+ await spoolEntry(stateDir, 3, 600);
+ const sessionUploader = new SessionUploader({
+ stateDir,
+ upload: async () => Response.json({ error: "unavailable" }, { status: 503 }),
+ retryBaseMs: 60_000,
+ spoolMaxBytes: 1_000,
+ spoolMaxTraceBytes: 1_000,
+ });
+ const uploads = sessionUploader as unknown as { enforceSpoolBounds(): Promise<void> };
+ await uploads.enforceSpoolBounds();
+ // The oldest trace went for the trace budget; the snapshot did not touch either trace.
+ const left = (await readdir(join(stateDir, "omnirush-upload-spool"))).filter((name) => name.endsWith(".json")).sort();
+ expect(left.map((name) => name.slice(-6, -5))).toEqual(["2", "3"]);
+ await sessionUploader.stop();
+ });
+
+ test("the spool is kept at start without an account and drained for that account once it is back", async () => {
+ const stateDir = await drainState();
+ await spoolEntry(stateDir, 1, 512, { account_id: "acct-a" });
+ await spoolEntry(stateDir, 2, 512, { account_id: "acct-b" });
+ await spoolEntry(stateDir, 3, 512);
+ // Signed out by a refused refresh: nothing uploads, and nothing is deleted.
+ const signedOut = new SessionUploader({ stateDir, retryBaseMs: 60_000 });
+ expect(signedOut.enabled).toBe(false);
+ await signedOut.stop();
+ expect(await signedOut.spoolStatus()).toEqual({ entries: 3, bytes: 1_536 });
+ const sent: string[] = [];
+ const sessionUploader = new SessionUploader({
+ stateDir,
+ upload: async (sessionId) => {
+ sent.push(sessionId);
+ return Response.json({}, { status: 201 });
+ },
+ accountId: async () => "acct-a",
+ retryBaseMs: 60_000,
+ });
+ // Account A's own entry and the unstamped one go out; account B's stays for B.
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 2, pending: 0 });
+ expect(sent.sort()).toEqual(["session-drain-1", "session-drain-3"]);
expect(await sessionUploader.spoolStatus()).toEqual({ entries: 1, bytes: 512 });
await sessionUploader.stop();
});
+ test("while the account cannot be learned only this process's own entries go out", async () => {
+ const stateDir = await drainState();
+ await spoolEntry(stateDir, 1, 512);
+ const sent: string[] = [];
+ const sessionUploader = new SessionUploader({
+ stateDir,
+ upload: async (sessionId) => {
+ sent.push(sessionId);
+ return Response.json({}, { status: 201 });
+ },
+ accountId: async () => null,
+ retryBaseMs: 60_000,
+ });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 0, pending: 1 });
+ expect(sent).toEqual([]);
+ await sessionUploader.stop();
+ });
+
+ test("a spooled entry is re-sent with its Idempotency-Key and checked against the stored body hash", async () => {
+ const stateDir = await drainState();
+ const body = Buffer.alloc(512, 1);
+ const digest = createHash("sha256").update(body).digest("hex");
+ const key = uploadIdempotencyKey("session-drain-1", 2, 1, "start");
+ await spoolEntry(stateDir, 1, 512, { idempotency_key: key, body_sha256: digest });
+ const keys: Array<string | undefined> = [];
+ let answers = 0;
+ const sessionUploader = new SessionUploader({
+ stateDir,
+ upload: async (_sessionId, _compressed, _signal, request) => {
+ keys.push(request?.idempotencyKey);
+ answers += 1;
+ // The first answer names other bytes: the envelope is sent again.
+ return Response.json({ body_sha256: answers === 1 ? "0".repeat(64) : digest }, { status: 201 });
+ },
+ retryBaseMs: 60_000,
+ });
+ expect(await sessionUploader.drainSpool()).toEqual({ delivered: 1, pending: 0 });
+ expect(keys).toEqual([key, key]);
+ await sessionUploader.stop();
+ });
+
+ test("the Idempotency-Key is the sha256 of session, segment, sequence and type joined by newlines", () => {
+ expect(uploadIdempotencyKey("ses_abc12345", 2, 7, "trace")).toBe(createHash("sha256").update("ses_abc12345\n2\n7\ntrace").digest("hex"));
+ expect(uploadIdempotencyKey("ses_abc12345", 2, 7, "trace")).toMatch(/^[0-9a-f]{64}$/);
+ });
+
test("a sign-out aborts the spooled upload in flight and empties the spool", async () => {
const stateDir = await drainState();
await spoolEntry(stateDir, 1, 1_024);
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index a341b628..977a6a4f 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -108,7 +108,10 @@ const MAX_IGNORED_CACHE_ENTRIES = 8_192;
const ENVELOPE_WRITE_CHUNK_BYTES = 64 * 1024;
const MAX_CHANGE_JOURNAL_ENTRIES = 512;
const MAX_CHANGE_JOURNAL_BYTES = 768 * 1024;
-const MAX_SESSION_LEDGER_ENTRIES = 512;
+/** Sessions the ledger keeps: an older chat resumed later restarts at sequence 0 and uploads its history again. */
+const MAX_SESSION_LEDGER_ENTRIES = 5_000;
+/** Of those, the most recent keep their sub-agent ids and checkpoints too (the bulk of a record). */
+const MAX_LEDGER_CHILD_ENTRIES = 512;
const MAX_TOUCHED_PATHS = 128;
const MAX_GIT_STATUS_ENTRIES = 500;
const MAX_GIT_RECENT_COMMITS = 50;
@@ -133,9 +136,16 @@ const REDACTED_TEXT_CACHE_BYTES = 32 * 1024 * 1024;
* another machine) is no write of the current turn's.
*/
const TURN_CLOCK_SLACK_MS = 1_000;
+/** Workspace snapshots (start, change, end) in the spool. */
const MAX_SPOOL_BYTES = 128 * 1024 * 1024;
const MAX_SPOOL_ENTRIES = 200;
-const MAX_SPOOL_ATTEMPTS = 24;
+/** Trace uploads have a budget of their own: a large snapshot never pushes one out. */
+const MAX_SPOOL_TRACE_BYTES = 128 * 1024 * 1024;
+const MAX_SPOOL_TRACE_ENTRIES = 2_000;
+/** A spooled upload that keeps failing with a retryable answer is kept this long, then dropped. */
+export const MAX_SPOOL_AGE_MS = 7 * 24 * 60 * 60_000;
+/** How long spooling or a drain waits to learn which account is signed in. */
+const ACCOUNT_LOOKUP_TIMEOUT_MS = 5_000;
const UPLOAD_ATTEMPTS = 3;
const UPLOAD_RETRY_DELAY_MS = 250;
const RETRY_BASE_MS = 5_000;
@@ -179,6 +189,10 @@ export function isRetryableUploadStatus(status: number, retryAfter: number | nul
// A rejected bearer. The body tells a stale device token (refreshed once and
// retried, spooled if still rejected) from the sign-in gate, which is final.
const UNAUTHORIZED_STATUSES = new Set([401, 403]);
+/** The 409 detail for an Idempotency-Key the server already holds with other bytes. */
+const IDEMPOTENCY_KEY_REUSED = "idempotency_key_reused";
+/** How long a chat's first prompt waits to learn where the server's copy of it stands. */
+const SERVER_POSITION_TIMEOUT_MS = 5_000;
const ACCOUNT_REQUIRED_MARKER = "omnirush_account_required";
type SnapshotType = "start" | "change" | "end" | "trace";
@@ -447,6 +461,12 @@ type SpoolMeta = {
last_attempt_at?: string;
/** Not sent again before this (a Retry-After the server gave). */
not_before?: string;
+ /** The account it was captured for; only that account's drain sends it. */
+ account_id?: string;
+ /** Sent as Idempotency-Key, so a re-send is recognised as the same envelope. */
+ idempotency_key?: string;
+ /** SHA-256 of the compressed bytes, checked against the server's `body_sha256`. */
+ body_sha256?: string;
};
type SessionState = {
@@ -537,6 +557,8 @@ type SessionState = {
tail: Promise<void>;
/** Capture v2: the binary files and symlinks of the workspace as last scanned (manifest entries without text). */
extras: Map<string, ExtraManifestEntry>;
+ /** The numbering already moved past the server's once (an Idempotency-Key it held with other bytes). */
+ repositioned?: boolean;
};
type SessionUploaderOptions = {
@@ -544,9 +566,17 @@ type SessionUploaderOptions = {
accessToken?: string;
fetch?: typeof externalFetch;
/** Sends one envelope; `signal` aborts at the upload deadline (session-upload-budget.ts) or when the spool is cleared. */
- upload?: (sessionId: string, compressed: Uint8Array, signal?: AbortSignal) => Promise<Response>;
+ upload?: (sessionId: string, compressed: Uint8Array, signal?: AbortSignal, request?: UploadRequestOptions) => Promise<Response>;
/** Sends an immutable compressed envelope directly from its spool/temp path. */
- uploadFile?: (sessionId: string, path: string, size: number, signal?: AbortSignal) => Promise<Response>;
+ uploadFile?: (sessionId: string, path: string, size: number, signal?: AbortSignal, request?: UploadRequestOptions) => Promise<Response>;
+ /**
+ * The signed-in account's id (null: not known right now). Spooled uploads
+ * are stamped with it and only that account's drain sends them. Without
+ * this hook the spool is the one account's.
+ */
+ accountId?: () => Promise<string | null>;
+ /** GET /omnirush/me/sessions/{id}/integrity for this account (where the server's copy of a chat stands). */
+ sessionIntegrity?: (sessionId: string, options?: { summary?: boolean; turns?: number }) => Promise<Response>;
/** Negotiates the canonical structured trace envelope. Failures fall back to schema v2. */
capabilities?: () => Promise<TraceCapabilities>;
/**
@@ -569,6 +599,10 @@ type SessionUploaderOptions = {
uploadBudget?: SessionUploadBudget;
spoolMaxEntries?: number;
spoolMaxBytes?: number;
+ spoolMaxTraceEntries?: number;
+ spoolMaxTraceBytes?: number;
+ /** How long a spooled upload is kept; MAX_SPOOL_AGE_MS unless a test lowers it. */
+ spoolMaxAgeMs?: number;
/** Uncompressed envelope cap; the backend's MAX_SNAPSHOT_BYTES unless a test lowers it. */
snapshotMaxBytes?: number;
/** Minimum spacing between change snapshots; MIN_UPLOAD_CHANGE_INTERVAL_MS unless a test lowers it. */
@@ -608,7 +642,7 @@ export type TraceCapabilities = {
type TransmitOutcome =
| { ok: true }
- | { ok: false; retryable: boolean; reason: string; unsupportedSchema?: boolean; retryAfterMs?: number };
+ | { ok: false; retryable: boolean; reason: string; unsupportedSchema?: boolean; retryAfterMs?: number; keyReused?: boolean };
type CompressedArtifact = { path: string; size: number };
@@ -3889,6 +3923,17 @@ async function boundedResponseText(response: Response, maxBytes = MAX_RESPONSE_B
}
}
+/** The `body_sha256` of a /collect answer (null: none, as from an older backend). */
+async function responseBodySha256(response: Response): Promise<string | null> {
+ try {
+ const payload: unknown = JSON.parse(await boundedResponseText(response));
+ const value = isRecord(payload) ? payload.body_sha256 : null;
+ return typeof value === "string" && SHA256_HEX.test(value.toLowerCase()) ? value.toLowerCase() : null;
+ } catch {
+ return null;
+ }
+}
+
async function responseSignalsAccountRequired(response: Response): Promise<boolean> {
return (await boundedResponseText(response)).includes(ACCOUNT_REQUIRED_MARKER);
}
@@ -4126,9 +4171,53 @@ function parseSpoolMeta(value: unknown): SpoolMeta | null {
attempts: optionalCount(record.attempts) ?? 0,
...(optionalString(record.last_attempt_at) ? { last_attempt_at: record.last_attempt_at } : {}),
...(optionalString(record.not_before) ? { not_before: record.not_before } : {}),
+ ...(optionalString(record.account_id) ? { account_id: record.account_id } : {}),
+ ...(typeof record.idempotency_key === "string" && SHA256_HEX.test(record.idempotency_key) ? { idempotency_key: record.idempotency_key } : {}),
+ ...(typeof record.body_sha256 === "string" && SHA256_HEX.test(record.body_sha256) ? { body_sha256: record.body_sha256 } : {}),
};
}
+const SHA256_HEX = /^[0-9a-f]{64}$/;
+
+/**
+ * The Idempotency-Key of a /collect upload: the lowercase hex SHA-256 of
+ * `${session_id}\n${segment}\n${sequence}\n${snapshot_type}` (UTF-8, no
+ * trailing newline), the same in the CLI. The backend answers a re-send
+ * under the same key with the first upload's answer.
+ */
+export function uploadIdempotencyKey(sessionId: string, segment: number, sequence: number, snapshotType: SnapshotType): string {
+ return createHash("sha256").update(`${sessionId}\n${segment}\n${sequence}\n${snapshotType}`, "utf8").digest("hex");
+}
+
+/**
+ * The highest segment and sequence of an integrity answer (its top-level
+ * max_segment and max_sequence, else read off its segments); null when it
+ * holds nothing.
+ */
+export function serverSessionPosition(payload: unknown): { segment: number; sequence: number } | null {
+ if (!isRecord(payload)) return null;
+ const topSegment = Number.isSafeInteger(payload.max_segment) ? Number(payload.max_segment) : null;
+ const topSequence = Number.isSafeInteger(payload.max_sequence) ? Number(payload.max_sequence) : null;
+ if (topSequence !== null) return { segment: topSegment ?? 0, sequence: topSequence };
+ if (!Array.isArray(payload.segments)) return null;
+ let segment = 0;
+ let sequence = 0;
+ let found = false;
+ for (const item of payload.segments) {
+ if (!isRecord(item)) continue;
+ const max = typeof item.max_sequence === "number" && Number.isSafeInteger(item.max_sequence) ? item.max_sequence : 0;
+ const sequences = Array.isArray(item.sequences) ? item.sequences.filter((value): value is number => Number.isSafeInteger(value)) : [];
+ const highest = Math.max(max, ...sequences, 0);
+ if (typeof item.segment === "number" && Number.isSafeInteger(item.segment)) segment = Math.max(segment, item.segment);
+ sequence = Math.max(sequence, highest);
+ found = found || highest > 0;
+ }
+ return found ? { segment, sequence } : null;
+}
+
+/** What a /collect upload carries besides its body. */
+export type UploadRequestOptions = { idempotencyKey?: string };
+
export class SessionUploader {
private readonly uploadUrl: string | null;
private token: string;
@@ -4155,6 +4244,16 @@ export class SessionUploader {
private readonly uploadBudget: SessionUploadBudget;
private readonly spoolMaxEntries: number;
private readonly spoolMaxBytes: number;
+ private readonly spoolMaxTraceEntries: number;
+ private readonly spoolMaxTraceBytes: number;
+ private readonly spoolMaxAgeMs: number;
+ private readonly accountIdHook?: SessionUploaderOptions["accountId"];
+ private readonly sessionIntegrity?: SessionUploaderOptions["sessionIntegrity"];
+ /** The signed-in account, once known (it never changes within a process: an account change restarts the server). */
+ private accountKnown: string | null = null;
+ private accountLookup: Promise<string | null> | null = null;
+ /** Spool entries this process wrote: the current account's even while its id is not known. */
+ private readonly ownSpoolEntries = new Set<string>();
private readonly snapshotMaxBytes: number;
private environmentCache: Promise<UploadEnvironment> | null = null;
private readonly toolchains: ToolchainCache | null;
@@ -4233,6 +4332,11 @@ export class SessionUploader {
this.uploadBudget = options.uploadBudget ?? SESSION_UPLOAD_BUDGET;
this.spoolMaxEntries = options.spoolMaxEntries ?? MAX_SPOOL_ENTRIES;
this.spoolMaxBytes = options.spoolMaxBytes ?? MAX_SPOOL_BYTES;
+ this.spoolMaxTraceEntries = options.spoolMaxTraceEntries ?? MAX_SPOOL_TRACE_ENTRIES;
+ this.spoolMaxTraceBytes = options.spoolMaxTraceBytes ?? MAX_SPOOL_TRACE_BYTES;
+ this.spoolMaxAgeMs = options.spoolMaxAgeMs ?? MAX_SPOOL_AGE_MS;
+ this.accountIdHook = options.accountId;
+ this.sessionIntegrity = options.sessionIntegrity;
this.snapshotMaxBytes = options.snapshotMaxBytes ?? MAX_SNAPSHOT_BYTES;
this.minChangeIntervalMs = options.minChangeIntervalMs ?? MIN_UPLOAD_CHANGE_INTERVAL_MS;
this.maxWatchedFiles = options.maxWatchedFiles ?? MAX_UPLOAD_WATCHED_FILES;
@@ -4255,16 +4359,10 @@ export class SessionUploader {
);
void this.stateMigrated.then(() => this.cleanTempDir(60 * 60_000)).catch(() => undefined);
this.context = !options.context || !this.enabled ? null : this.createContext(stateDir, options.context);
- if (this.spoolDir) {
- if (this.enabled) {
- // Uploads spooled by a previous process are retried once this one is up.
- this.scheduleRetry(this.retryBaseMs);
- } else {
- // Without an account there is nobody to deliver queued snapshots to;
- // a sign-out must not leave workspace content waiting on disk.
- void this.clearSpool().catch(() => undefined);
- }
- }
+ // 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()).
+ if (this.spoolDir && this.enabled) this.scheduleRetry(this.retryBaseMs);
}
/** Capture context wired to this uploader: its trace, its scrub, the project archive and the archive's exclusions. */
@@ -4331,7 +4429,12 @@ export class SessionUploader {
await this.ledgerReady;
const entries = Object.entries(this.ledger.sessions)
.sort(([, left], [, right]) => right.lastSeenAt.localeCompare(left.lastSeenAt))
- .slice(0, MAX_SESSION_LEDGER_ENTRIES);
+ .slice(0, MAX_SESSION_LEDGER_ENTRIES)
+ .map(([sessionId, record], index): [string, SessionLedgerRecord] => {
+ if (index < MAX_LEDGER_CHILD_ENTRIES || (!record.childSessionIds && !record.childCheckpoints)) return [sessionId, record];
+ const { childSessionIds: _ids, childCheckpoints: _checkpoints, ...rest } = record;
+ return [sessionId, rest];
+ });
this.ledger.sessions = Object.fromEntries(entries);
const snapshot = JSON.stringify(this.ledger);
this.ledgerWriteTail = this.ledgerWriteTail
@@ -4361,7 +4464,13 @@ export class SessionUploader {
private async prepareSession(state: SessionState): Promise<void> {
await this.ledgerReady;
- const previous = this.ledger.sessions[state.id];
+ const recorded = this.ledger.sessions[state.id];
+ // No local record: a new chat, or one this device's ledger lost. The
+ // server says where its copy stands, so the numbering goes on after it
+ // instead of reusing keys it already holds.
+ const server = recorded ? null : await this.serverPosition(state.id);
+ const previous: SessionLedgerRecord | undefined = recorded
+ ?? (server ? { segment: server.segment, nextSequence: server.sequence, lastSeenAt: new Date().toISOString() } : undefined);
state.segment = (previous?.segment ?? 0) + 1;
state.sequence = previous?.nextSequence ?? 0;
state.sentBytes = previous?.sentBytes ?? 0;
@@ -4376,12 +4485,56 @@ export class SessionUploader {
state.childCheckpoints = new Map([...Object.entries(previous?.childCheckpoints ?? {}), ...state.childCheckpoints]);
state.resumed = Boolean(previous);
if (state.resumed) {
- this.appendTrace(state, "session.resumed", { session_segment: state.segment, previous_segment: previous?.segment ?? null });
+ this.appendTrace(state, "session.resumed", {
+ session_segment: state.segment,
+ previous_segment: previous?.segment ?? null,
+ ...(server ? { ledger: "server" } : {}),
+ });
}
this.ledger.sessions[state.id] = this.ledgerRecord(state);
await this.saveLedger();
}
+ /**
+ * Where the server's copy of a chat stands (its highest segment and
+ * sequence), from the integrity route; null when it has none or cannot
+ * say (offline, an older backend).
+ */
+ private async serverPosition(sessionId: string): Promise<{ segment: number; sequence: number } | null> {
+ if (!this.sessionIntegrity) return null;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const response = await Promise.race([
+ this.sessionIntegrity(sessionId, { summary: true }),
+ new Promise<null>((resolvePromise) => {
+ timer = setTimeout(() => resolvePromise(null), SERVER_POSITION_TIMEOUT_MS);
+ timer.unref?.();
+ }),
+ ]);
+ if (!response) return null;
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ return null;
+ }
+ return serverSessionPosition(JSON.parse(await boundedResponseText(response, 4 * 1024 * 1024)));
+ } catch {
+ return null;
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
+ /** Moves a chat's numbering past the server's (or one segment on, when the server cannot say). */
+ private async repositionSession(state: SessionState): Promise<void> {
+ const server = await this.serverPosition(state.id);
+ const from = { segment: state.segment, sequence: state.sequence };
+ state.segment = Math.max(state.segment + 1, (server?.segment ?? 0) + 1);
+ state.sequence = Math.max(state.sequence, server?.sequence ?? 0);
+ this.appendTrace(state, "collector.resegmented", { from_segment: from.segment, from_sequence: from.sequence, session_segment: state.segment, sequence: state.sequence });
+ this.log("warn", "OmniRush session numbering moved past the server's copy", { sessionId: state.id, segment: state.segment, sequence: state.sequence });
+ await this.persistSession(state).catch(() => undefined);
+ }
+
private async persistSession(state: SessionState): Promise<void> {
await this.ledgerReady;
this.ledger.sessions[state.id] = this.ledgerRecord(state);
@@ -5941,7 +6094,7 @@ export class SessionUploader {
budgetBytes: budget,
});
}
- if (!uploaded) return false;
+ if (uploaded !== true) return false;
// The baseline is the last *accepted* manifest (uploaded or spooled): the
// next change snapshot reports exactly what moved since this one.
accepted = true;
@@ -5990,6 +6143,7 @@ export class SessionUploader {
trace: batch.events,
});
let uploaded = await this.uploadEnvelope(state, "trace", "trace_flush", await makeBody(schemaVersion));
+ if (uploaded === "key_reused") uploaded = await this.uploadEnvelope(state, "trace", "trace_flush", await makeBody(schemaVersion));
if (uploaded === "unsupported_schema" && schemaVersion === TRACE_SCHEMA_VERSION && !downgraded) {
downgraded = true;
schemaVersion = 2;
@@ -6023,37 +6177,29 @@ export class SessionUploader {
}
}
- private async send(sessionId: string, compressed: Uint8Array | CompressedArtifact, deadline: AbortSignal, cancel?: AbortSignal): Promise<Response> {
+ private async send(sessionId: string, compressed: Uint8Array | CompressedArtifact, deadline: AbortSignal, cancel?: AbortSignal, request: UploadRequestOptions = {}): Promise<Response> {
const signal = cancel ? AbortSignal.any([deadline, cancel]) : deadline;
if (signal.aborted) return Promise.reject(signal.reason);
+ const headers: Record<string, string> = {
+ Authorization: `Bearer ${this.token}`,
+ "Content-Type": "application/zstd",
+ "X-OmniRush-Session-ID": sessionId,
+ ...(request.idempotencyKey ? { "Idempotency-Key": request.idempotencyKey } : {}),
+ };
if ("path" in compressed) {
await this.validateCompressedArtifact(compressed);
- if (this.fileUploader) return untilAborted(this.fileUploader(sessionId, compressed.path, compressed.size, signal), signal);
+ if (this.fileUploader) return untilAborted(this.fileUploader(sessionId, compressed.path, compressed.size, signal, request), signal);
if (!this.uploader) {
const body = fileReadableBody(compressed.path, signal);
- const init: RequestInit & { duplex: "half" } = {
- method: "POST",
- headers: {
- Authorization: `Bearer ${this.token}`,
- "Content-Type": "application/zstd",
- "X-OmniRush-Session-ID": sessionId,
- },
- body,
- duplex: "half",
- signal,
- };
+ const init: RequestInit & { duplex: "half" } = { method: "POST", headers, body, duplex: "half", signal };
return this.fetcher(this.uploadUrl!, init);
}
- return untilAborted(readFile(compressed.path).then((bytes) => this.uploader!(sessionId, bytes, signal)), signal);
+ return untilAborted(readFile(compressed.path).then((bytes) => this.uploader!(sessionId, bytes, signal, request)), signal);
}
- if (this.uploader) return untilAborted(this.uploader(sessionId, compressed, signal), signal);
+ if (this.uploader) return untilAborted(this.uploader(sessionId, compressed, signal, request), signal);
return this.fetcher(this.uploadUrl!, {
method: "POST",
- headers: {
- Authorization: `Bearer ${this.token}`,
- "Content-Type": "application/zstd",
- "X-OmniRush-Session-ID": sessionId,
- },
+ headers,
body: compressed.buffer.slice(compressed.byteOffset, compressed.byteOffset + compressed.byteLength) as ArrayBuffer,
signal,
});
@@ -6085,17 +6231,31 @@ export class SessionUploader {
attempts = UPLOAD_ATTEMPTS,
cancel?: AbortSignal,
schemaVersion: 2 | 3 = 2,
+ check: { idempotencyKey?: string; bodySha256?: string } = {},
): Promise<TransmitOutcome> {
const timeoutMs = sessionUploadTimeoutMs("path" in compressed ? compressed.size : compressed.byteLength, this.uploadBudget);
let lastReason = "session upload unavailable";
let refreshAttempted = false;
+ let resentForHash = false;
let attempt = 0;
+ const request: UploadRequestOptions = check.idempotencyKey ? { idempotencyKey: check.idempotencyKey } : {};
while (attempt < attempts) {
// Each attempt, the retry with a refreshed bearer too, gets a deadline of its own.
const deadline = AbortSignal.timeout(timeoutMs);
try {
- const response = await this.send(sessionId, compressed, deadline, cancel);
- if (response.ok) return { ok: true };
+ const response = await this.send(sessionId, compressed, deadline, cancel, request);
+ if (response.ok) {
+ // The server names the SHA-256 of the bytes it stored: a different
+ // one means the body was damaged on the way, so it is sent again.
+ const stored = check.bodySha256 ? await responseBodySha256(response) : null;
+ if (!stored || stored === check.bodySha256) return { ok: true };
+ lastReason = "the server stored different bytes than were sent";
+ this.log("warn", "OmniRush session upload stored with a different body hash; sending it again", { sessionId });
+ // The first such answer is sent again at once, outside the transport attempts.
+ if (!resentForHash) resentForHash = true;
+ else attempt += 1;
+ continue;
+ }
lastReason = `sessionUploader upload failed with status ${response.status}`;
if (UNAUTHORIZED_STATUSES.has(response.status)) {
// The sign-in gate is final: nothing is queued for an account that
@@ -6121,6 +6281,11 @@ export class SessionUploader {
if (response.status === 422 && schemaVersion === TRACE_SCHEMA_VERSION && await responseSignalsUnsupportedSchema(response)) {
return { ok: false, retryable: false, reason: lastReason, unsupportedSchema: true };
}
+ // The server holds other bytes under this key: final for this envelope.
+ if (response.status === 409) {
+ const keyReused = (await boundedResponseText(response)).includes(IDEMPOTENCY_KEY_REUSED);
+ return { ok: false, retryable: false, reason: keyReused ? `${lastReason} (${IDEMPOTENCY_KEY_REUSED})` : lastReason, ...(keyReused ? { keyReused } : {}) };
+ }
await response.body?.cancel().catch(() => undefined);
const retryAfter = retryAfterMs(response.headers?.get?.("retry-after"));
if (!isRetryableUploadStatus(response.status, retryAfter)) return { ok: false, retryable: false, reason: lastReason };
@@ -6184,7 +6349,7 @@ export class SessionUploader {
snapshotType: SnapshotType,
trigger: UploadTrigger,
body: EnvelopeBody,
- ): Promise<boolean | "unsupported_schema"> {
+ ): Promise<boolean | "unsupported_schema" | "key_reused"> {
if (!this.uploadUrl && !this.uploader && !this.fileUploader) return false;
const sequence = state.sequence + 1;
const path = await this.envelopeTempPath();
@@ -6254,11 +6419,22 @@ export class SessionUploader {
return false;
}
const compressed: CompressedArtifact = { path, size: compressedBytes };
+ const idempotencyKey = uploadIdempotencyKey(state.id, state.segment, sequence, snapshotType);
+ const bodySha256 = await sha256File(path);
+ // The sequence is taken before the envelope leaves: one the server
+ // stored is never used again for other bytes (it would answer
+ // idempotency_key_reused), even if this process ends before it answers.
+ state.sequence = sequence;
+ await this.persistSession(state).catch(() => undefined);
const account = this.account.signal;
const uploadSignal = AbortSignal.any([account, this.halted.signal]);
const spoolArtifact = async (reason: string, retryAfter?: number): Promise<boolean> => {
+ const accountId = await this.currentAccount();
const spooled = await this.spoolEnvelopeFile({
id: "", session_id: state.id, snapshot_type: snapshotType, trigger, sequence, bytes: compressedBytes, created_at: new Date().toISOString(), attempts: 1,
+ idempotency_key: idempotencyKey,
+ body_sha256: bodySha256,
+ ...(accountId ? { account_id: accountId } : {}),
...(retryAfter !== undefined ? { not_before: new Date(Date.now() + retryAfter).toISOString() } : {}),
}, path, account);
if (!spooled) {
@@ -6267,7 +6443,6 @@ export class SessionUploader {
return false;
}
state.sentBytes += bytes;
- state.sequence = sequence;
state.failureCount += 1;
state.lastFailureAt = new Date().toISOString();
await this.persistSession(state).catch(() => undefined);
@@ -6292,11 +6467,18 @@ export class SessionUploader {
}
let outcome: TransmitOutcome;
try {
- outcome = await this.transmit(state.id, compressed, UPLOAD_ATTEMPTS, uploadSignal, body.schemaVersion ?? UPLOAD_SCHEMA_VERSION);
+ outcome = await this.transmit(state.id, compressed, UPLOAD_ATTEMPTS, uploadSignal, body.schemaVersion ?? UPLOAD_SCHEMA_VERSION, { idempotencyKey, bodySha256 });
} finally {
releaseUpload();
}
if (!outcome.ok && outcome.unsupportedSchema) return "unsupported_schema";
+ if (!outcome.ok && outcome.keyReused && !state.repositioned) {
+ // This chat's numbering on the server is ahead of the local ledger (a
+ // lost or capped ledger): continue after the server's, once.
+ state.repositioned = true;
+ await this.repositionSession(state);
+ return "key_reused";
+ }
if (!outcome.ok) {
if ((!outcome.retryable || !this.spoolDir) && !account.aborted) {
await this.recordLedgerOutcome(state.id, "failure").catch(() => undefined);
@@ -6305,9 +6487,9 @@ export class SessionUploader {
return await spoolArtifact(outcome.reason, outcome.retryAfterMs);
}
state.sentBytes += bytes;
- state.sequence = sequence;
state.lastSuccessAt = new Date().toISOString();
- await this.persistSession(state).catch((error: unknown) => {
+ // The sequence is already on disk; this only records the outcome (stop() waits for it).
+ void this.persistSession(state).catch((error: unknown) => {
this.log("warn", "OmniRush session ledger update failed", {
sessionId: state.id,
error: error instanceof Error ? error.message : "unknown",
@@ -6393,28 +6575,92 @@ export class SessionUploader {
await writePrivateFileAtomic(target, await readFile(sourcePath));
}
await this.writeSpoolMeta({ ...meta, id });
+ this.ownSpoolEntries.add(id);
await this.enforceSpoolBounds();
return true;
});
}
+ /**
+ * Keeps the spool within its bounds, oldest first: trace uploads and
+ * workspace snapshots each within a budget of their own, so a large start
+ * snapshot never pushes out a trace (nor traces a snapshot).
+ */
private async enforceSpoolBounds(): Promise<void> {
const entries = await this.listSpool();
- let total = entries.reduce((sum, entry) => sum + entry.bytes, 0);
- let count = entries.length;
- for (const entry of entries) {
- if (count <= this.spoolMaxEntries && total <= this.spoolMaxBytes) break;
- await this.removeSpoolEntry(entry.id);
- total -= entry.bytes;
- count -= 1;
- this.log("warn", "OmniRush session upload spool dropped its oldest entry", {
- sessionId: entry.session_id,
- snapshotType: entry.snapshot_type,
- sequence: entry.sequence,
- });
+ const classes: Array<{ entries: SpoolMeta[]; maxEntries: number; maxBytes: number }> = [
+ { entries: entries.filter((entry) => entry.snapshot_type === "trace"), maxEntries: this.spoolMaxTraceEntries, maxBytes: this.spoolMaxTraceBytes },
+ { entries: entries.filter((entry) => entry.snapshot_type !== "trace"), maxEntries: this.spoolMaxEntries, maxBytes: this.spoolMaxBytes },
+ ];
+ for (const kind of classes) {
+ let total = kind.entries.reduce((sum, entry) => sum + entry.bytes, 0);
+ let count = kind.entries.length;
+ for (const entry of kind.entries) {
+ if (count <= kind.maxEntries && total <= kind.maxBytes) break;
+ await this.removeSpoolEntry(entry.id);
+ total -= entry.bytes;
+ count -= 1;
+ this.log("warn", "OmniRush session upload spool dropped its oldest entry", {
+ sessionId: entry.session_id,
+ snapshotType: entry.snapshot_type,
+ sequence: entry.sequence,
+ });
+ }
}
}
+ /** Whether a spooled upload is past the spool's age limit (an unreadable date counts as fresh). */
+ private spoolEntryExpired(entry: SpoolMeta, now = Date.now()): boolean {
+ const created = Date.parse(entry.created_at);
+ return Number.isFinite(created) && now - created > this.spoolMaxAgeMs;
+ }
+
+ /**
+ * The signed-in account's id; null while it cannot be learned (offline, or
+ * no account). Asked once per process: an account change restarts the server.
+ */
+ private async currentAccount(): Promise<string | null> {
+ if (this.accountKnown || !this.accountIdHook) return this.accountKnown;
+ this.accountLookup ??= (async () => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const id = await Promise.race([
+ this.accountIdHook!().catch(() => null),
+ new Promise<null>((resolvePromise) => {
+ timer = setTimeout(() => resolvePromise(null), ACCOUNT_LOOKUP_TIMEOUT_MS);
+ timer.unref?.();
+ }),
+ ]);
+ const trimmed = typeof id === "string" ? id.trim() : "";
+ if (trimmed) this.accountKnown = trimmed;
+ return this.accountKnown;
+ } finally {
+ clearTimeout(timer);
+ this.accountLookup = null;
+ }
+ })();
+ return this.accountLookup;
+ }
+
+ /**
+ * Whether the current account's drain may send `entry`. Without an account
+ * hook the spool is one account's. An entry stamped for another account
+ * waits (for that account, or its age limit). An unstamped one (spooled
+ * before stamping, or while the id was unknown) is this account's once
+ * the id is known, and stamped so; until then only this process's own are.
+ */
+ private async spoolEntryOwned(entry: SpoolMeta, account: string | null, spoolDir: string): Promise<boolean> {
+ if (!this.accountIdHook) return true;
+ if (entry.account_id) return entry.account_id === account;
+ if (!account) return this.ownSpoolEntries.has(entry.id);
+ entry.account_id = account;
+ await this.spoolLocked(async () => {
+ await lstat(join(spoolDir, `${entry.id}.zst`));
+ await this.writeSpoolMeta(entry);
+ }).catch(() => undefined);
+ return true;
+ }
+
private scheduleRetry(delayMs?: number): void {
if (!this.spoolDir || this.stopped || this.retryTimer) return;
// Never past the retry cap: a delay computed from a spool entry dated in
@@ -6486,11 +6732,31 @@ export class SessionUploader {
const spoolDir = this.spoolDir;
if (!spoolDir || !this.enabled) return { delivered, pending: 0 };
const entries = await this.spoolLocked(() => this.listSpool());
+ const account = this.accountIdHook ? await this.currentAccount() : null;
let pending = entries.length;
let failures = 0;
let nextDueAt = Number.POSITIVE_INFINITY;
+ let waitingForAccount = false;
for (const entry of entries) {
if (this.stopped || signal.aborted) break;
+ if (this.spoolEntryExpired(entry)) {
+ await this.spoolLocked(() => this.removeSpoolEntry(entry.id));
+ pending -= 1;
+ this.log("warn", "OmniRush session upload artifact dropped from spool", {
+ sessionId: entry.session_id,
+ snapshotType: entry.snapshot_type,
+ sequence: entry.sequence,
+ reason: "expired",
+ });
+ continue;
+ }
+ // Another account's upload is never sent; it is not this drain's to retry either.
+ if (!(await this.spoolEntryOwned(entry, account, spoolDir))) {
+ // Waiting to learn the account: tried again on the backoff.
+ if (account) pending -= 1;
+ else waitingForAccount = true;
+ continue;
+ }
const dueAt = this.spoolEntryDueAt(entry);
if (failures >= MAX_DRAIN_FAILURES || dueAt > Date.now()) {
nextDueAt = Math.min(nextDueAt, dueAt);
@@ -6510,11 +6776,15 @@ export class SessionUploader {
const releaseUpload = await GLOBAL_CAPTURE_ADMISSION.acquire(signal);
let outcome: TransmitOutcome;
try {
- outcome = await this.transmit(entry.session_id, compressed, 1, signal);
+ outcome = await this.transmit(entry.session_id, compressed, 1, signal, 2, {
+ ...(entry.idempotency_key ? { idempotencyKey: entry.idempotency_key } : {}),
+ ...(entry.body_sha256 ? { bodySha256: entry.body_sha256 } : {}),
+ });
} finally {
releaseUpload();
}
if (outcome.ok) {
+ this.ownSpoolEntries.delete(entry.id);
await this.spoolLocked(() => this.removeSpoolEntry(entry.id));
await this.recordLedgerOutcome(entry.session_id, "success").catch(() => undefined);
this.retryFailures = 0;
@@ -6531,7 +6801,8 @@ export class SessionUploader {
}
// Stopped or signed out mid-upload: the entry stays as it was, or goes with the spool.
if (signal.aborted) break;
- if (!outcome.retryable || entry.attempts + 1 >= MAX_SPOOL_ATTEMPTS) {
+ // A retryable failure keeps the entry, however long the outage (up to the spool's age limit).
+ if (!outcome.retryable) {
await this.spoolLocked(() => this.removeSpoolEntry(entry.id));
pending -= 1;
this.log("warn", "OmniRush session upload artifact dropped from spool", {
@@ -6558,7 +6829,7 @@ export class SessionUploader {
await this.recordLedgerOutcome(entry.session_id, "failure").catch(() => undefined);
nextDueAt = Math.min(nextDueAt, this.spoolEntryDueAt(attempted));
}
- if (failures > 0) this.retryFailures += 1;
+ if (failures > 0 || waitingForAccount) this.retryFailures += 1;
if (pending > 0 && !signal.aborted) {
this.scheduleRetry(Math.max(this.jitteredBackoffMs(), Number.isFinite(nextDueAt) ? nextDueAt - Date.now() : 0));
}
@@ -6575,11 +6846,13 @@ export class SessionUploader {
/**
* Discards every spooled upload and the stored turn-diff bases, and aborts
- * every upload in flight without spooling it. Wire this to sign-out and
- * consent withdrawal: once the account is gone nothing may stay queued on
- * disk.
+ * every upload in flight without spooling it. Wire this to a user's
+ * sign-out and consent withdrawal only: a device session the server
+ * retired (a refused refresh) keeps its queue for when the account is
+ * back, each upload stamped with its account.
*/
clearSpool(): Promise<void> {
+ this.ownSpoolEntries.clear();
if (this.retryTimer) {
clearTimeout(this.retryTimer);
this.retryTimer = null;
diff --git a/apps/server/src/types.ts b/apps/server/src/types.ts
index 647f7445..5e90dfd6 100644
--- a/apps/server/src/types.ts
+++ b/apps/server/src/types.ts
@@ -161,6 +161,8 @@ export interface ServerConfig {
appVersion?: string;
/** Embedding-owned transport for immutable session upload files. */
captureFileUpload?: CaptureFileUpload;
+ /** The user signed out: queued uploads and archives are deleted as this server starts. */
+ clearUploadQueue?: boolean;
}
export interface Capabilities {