A desktop coding agent with free access to frontier models.
TypeScript
fix: follow the backend's upload features
ogsamrat7a82cb659d9a
diff --git a/apps/server/src/capture-client.test.ts b/apps/server/src/capture-client.test.tsindex 5d52a94e..f39a2ab0 100644--- a/apps/server/src/capture-client.test.ts+++ b/apps/server/src/capture-client.test.ts@@ -468,6 +468,7 @@ describe("capture worker", () => {return Response.json({ detail: "session_not_found" }, { status: 404 });},sessionUploader: {+ capabilities: async () => ({ schema_versions: [1, 2], canonical_trace: false, idempotency_key: true, integrity: true, integrity_summary: true }),upload: async (_sessionId, _bytes, _signal, request) => {keys.push(request?.idempotencyKey);return Response.json({ detail: "unavailable" }, { status: 503 });diff --git a/apps/server/src/omnirush-gateway-broker.test.ts b/apps/server/src/omnirush-gateway-broker.test.tsindex ea1e649b..f90ab1ac 100644--- a/apps/server/src/omnirush-gateway-broker.test.ts+++ b/apps/server/src/omnirush-gateway-broker.test.ts@@ -121,10 +121,8 @@ describe("OmniRush gateway broker", () => {});const first = await Promise.all([broker.sessionUploadCapabilities(), broker.sessionUploadCapabilities()]);- expect(first).toEqual([- { schema_versions: [1, 2, 3], canonical_trace: true },- { schema_versions: [1, 2, 3], canonical_trace: true },- ]);+ const v3 = { schema_versions: [1, 2, 3], canonical_trace: true, ...{ idempotency_key: false, body_sha256: false, integrity: false, integrity_summary: false, recovered_segments: false } };+ expect(first).toEqual([v3, v3]);expect(probes).toBe(1);now += 5 * 60_000 + 1;@@ -134,7 +132,7 @@ describe("OmniRush gateway broker", () => {broker.resetCapabilities();supported = true;- expect(await broker.sessionUploadCapabilities()).toEqual({ schema_versions: [1, 2, 3], canonical_trace: true });+ expect(await broker.sessionUploadCapabilities()).toEqual(v3);expect(probes).toBe(3);} finally {Date.now = originalNow;@@ -1427,7 +1425,33 @@ describe("OmniRush gateway broker: connection failures never become a bare 500",});});+const INTEGRITY_FEATURES = { schema_versions: [1, 2, 3], canonical_trace: true, idempotency_key: true, body_sha256: true, integrity: true, integrity_summary: true };+describe("OmniRush gateway broker upload keys, account and integrity", () => {+ test("reads the backend's features (a missing key is false) and never calls the integrity route a backend lacks", async () => {+ let features: Record<string, unknown> = { schema_versions: [1, 2, 3], canonical_trace: true };+ const integrityCalls: string[] = [];+ const make = () => new OmniRushGatewayBroker({+ credentials,+ engineToken: "local-engine-token",+ fetch: async (input) => {+ if (String(input).endsWith("/collect/capabilities")) return Response.json(features);+ integrityCalls.push(String(input));+ return Response.json({ integrity: "ok" });+ },+ });+ const old = make();+ expect(await old.sessionUploadCapabilities()).toMatchObject({ idempotency_key: false, integrity: false });+ expect((await old.sessionIntegrity("ses_feature_1234", { summary: true })).status).toBe(404);+ expect(integrityCalls).toEqual([]);+ features = { ...INTEGRITY_FEATURES, integrity_summary: false, triggers: ["trace_flush", "start"] };+ const partial = make();+ expect(await partial.sessionUploadCapabilities()).toMatchObject({ idempotency_key: true, integrity: true, integrity_summary: false, triggers: ["trace_flush", "start"] });+ expect((await partial.sessionIntegrity("ses_feature_1234", { summary: true })).status).toBe(200);+ // No summary mode on this backend: the full record is read.+ expect(integrityCalls).toEqual(["https://gateway.example/omnirush/me/sessions/ses_feature_1234/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 () => {@@ -1477,6 +1501,7 @@ describe("OmniRush gateway broker upload keys, account and integrity", () => {credentials,engineToken: "local-engine-token",fetch: async (input, init) => {+ if (String(input).endsWith("/collect/capabilities")) return Response.json(INTEGRITY_FEATURES);calls.push({ url: String(input), authorization: new Headers(init?.headers).get("authorization") });return Response.json({ integrity: "ok" });},@@ -1495,7 +1520,8 @@ describe("OmniRush gateway broker upload keys, account and integrity", () => {const broker = new OmniRushGatewayBroker({credentials,engineToken: "local-engine-token",- fetch: async () => {+ fetch: async (input) => {+ if (String(input).endsWith("/collect/capabilities")) return Response.json(INTEGRITY_FEATURES);calls += 1;return limited ? Response.json({ detail: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } }) : Response.json({ integrity: "ok" });},@@ -1508,7 +1534,8 @@ describe("OmniRush gateway broker upload keys, account and integrity", () => {const fresh = new OmniRushGatewayBroker({credentials,engineToken: "local-engine-token",- fetch: async () => {+ fetch: async (input) => {+ if (String(input).endsWith("/collect/capabilities")) return Response.json(INTEGRITY_FEATURES);calls += 1;return Response.json({ detail: "rate_limited" }, { status: 429, headers: { "Retry-After": "30" } });},diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.tsindex bca18754..f1879aa6 100644--- a/apps/server/src/omnirush-gateway-broker.ts+++ b/apps/server/src/omnirush-gateway-broker.ts@@ -695,6 +695,17 @@ function secureEqual(left: string, right: string): boolean {return a.length === b.length && a.length > 0 && timingSafeEqual(a, b);}+/** The feature flags of a /collect/capabilities answer, each true only when the backend says so. */+function uploadFeatureFlags(payload: Record<string, unknown>): Pick<TraceCapabilities, "idempotency_key" | "body_sha256" | "integrity" | "integrity_summary" | "recovered_segments"> {+ return {+ idempotency_key: payload.idempotency_key === true,+ body_sha256: payload.body_sha256 === true,+ integrity: payload.integrity === true,+ integrity_summary: payload.integrity_summary === true,+ recovered_segments: payload.recovered_segments === true,+ };+}+/** Integrity reads per minute this device makes, under the route's 30 per account. */const INTEGRITY_CALLS_PER_MINUTE = 24;@@ -1029,8 +1040,8 @@ export class OmniRushGatewayBroker {* every later request, so one bad file cannot fail the rest of a session.*/private readonly rejectedAttachments = new RejectedAttachments();- private capabilityCache: { gatewayUrl: string; accountKey: string; version: 2 | 3; expiresAt: number } | null = null;- private capabilityProbe: { key: string; promise: Promise<2 | 3> } | null = null;+ private capabilityCache: { gatewayUrl: string; accountKey: string; capabilities: TraceCapabilities; expiresAt: number } | null = null;+ private capabilityProbe: { key: string; promise: Promise<TraceCapabilities> } | null = null;constructor(options: BrokerOptions) {const gatewayUrl = options.credentials ? normalizedGatewayUrl(options.credentials.gatewayUrl) : null;@@ -1310,7 +1321,7 @@ export class OmniRushGatewayBroker {if (this.capabilityCache?.gatewayUrl === gatewayUrl&& this.capabilityCache.accountKey === key&& this.capabilityCache.expiresAt > Date.now()) {- return { schema_versions: this.capabilityCache.version === 3 ? [1, 2, 3] : [1, 2], canonical_trace: this.capabilityCache.version === 3 };+ return this.capabilityCache.capabilities;}const pending = this.capabilityProbe?.key === key? this.capabilityProbe.promise@@ -1321,11 +1332,11 @@ export class OmniRushGatewayBroker {if (this.capabilityProbe?.promise === pending) this.capabilityProbe = null;}).catch(() => undefined);}- const version = await pending;+ const capabilities = await pending;if (this.state && this.capabilityKey(this.state) === key) {- this.capabilityCache = { gatewayUrl, accountKey: key, version, expiresAt: Date.now() + TRACE_CAPABILITY_TTL_MS };+ this.capabilityCache = { gatewayUrl, accountKey: key, capabilities, expiresAt: Date.now() + TRACE_CAPABILITY_TTL_MS };}- return { schema_versions: version === 3 ? [1, 2, 3] : [1, 2], canonical_trace: version === 3 };+ return capabilities;}resetCapabilities(): void {@@ -1342,6 +1353,10 @@ export class OmniRushGatewayBroker {* here, or before a Retry-After it gave, the answer is a local 429.*/async sessionIntegrity(sessionId: string, options: SessionIntegrityOptions = {}): Promise<Response> {+ // A backend without the route answers like one that holds nothing (the callers' "pending").+ const features = await this.sessionUploadCapabilities();+ if (features.integrity !== true) return Response.json({ detail: "integrity_unavailable" }, { status: 404 });+ const summary = options.summary === true && features.integrity_summary === true;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);@@ -1351,7 +1366,7 @@ export class OmniRushGatewayBroker {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 (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",@@ -1402,9 +1417,15 @@ export class OmniRushGatewayBroker {return `${state.gatewayUrl}\0${state.refreshToken}`;}- private async probeSessionUploadCapabilities(gatewayUrl: string): Promise<2 | 3> {+ /**+ * The backend's /collect/capabilities: the trace schema and the features+ * it has (a key it does not name is false). A failed read is the oldest+ * backend: schema 2 and no features, asked again once the cache expires.+ */+ private async probeSessionUploadCapabilities(gatewayUrl: string): Promise<TraceCapabilities> {+ const none: TraceCapabilities = { schema_versions: [1, 2], canonical_trace: false };try {- if (this.state?.gatewayUrl !== gatewayUrl) return 2;+ if (this.state?.gatewayUrl !== gatewayUrl) return none;const response = await this.withDeviceBearer((state) => this.fetcher(apiUrl(state.gatewayUrl, "collect/capabilities"), {method: "GET",headers: { Authorization: `Bearer ${state.accessToken}`, Accept: "application/json" },@@ -1412,15 +1433,22 @@ export class OmniRushGatewayBroker {}));if (!response.ok) {await response.body?.cancel().catch(() => undefined);- return 2;+ return none;}const text = await boundedText(response, 64 * 1024);- if (text === null) return 2;+ if (text === null) return none;const payload: unknown = JSON.parse(text);- if (!isRecord(payload) || payload.canonical_trace !== true || !Array.isArray(payload.schema_versions)) return 2;- return payload.schema_versions.some((version) => version === 3) ? 3 : 2;+ if (!isRecord(payload)) return none;+ const v3 = payload.canonical_trace === true && Array.isArray(payload.schema_versions) && payload.schema_versions.some((version) => version === 3);+ const triggers = Array.isArray(payload.triggers) ? payload.triggers.filter((item): item is string => typeof item === "string") : null;+ return {+ schema_versions: v3 ? [1, 2, 3] : [1, 2],+ canonical_trace: v3,+ ...uploadFeatureFlags(payload),+ ...(triggers ? { triggers } : {}),+ };} catch {- return 2;+ return none;}}diff --git a/apps/server/src/session-uploader.test.ts b/apps/server/src/session-uploader.test.tsindex 1735df9f..938f9600 100644--- a/apps/server/src/session-uploader.test.ts+++ b/apps/server/src/session-uploader.test.ts@@ -193,6 +193,7 @@ describe("session uploader privacy", () => {await writeFile(join(root, "app.txt"), "hello\n");const sent: Array<{ key: string | undefined; envelope: Record<string, unknown> }> = [];const sessionUploader = new SessionUploader({+ capabilities: async () => ({ schema_versions: [1, 2], canonical_trace: false, idempotency_key: true, integrity: true, integrity_summary: true }),stateDir,upload: async (_sessionId, compressed, _signal, request) => {sent.push({ key: request?.idempotencyKey, envelope: JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown> });@@ -223,6 +224,7 @@ describe("session uploader privacy", () => {const envelopes: Array<Record<string, unknown>> = [];const asked: string[] = [];const sessionUploader = new SessionUploader({+ capabilities: async () => ({ schema_versions: [1, 2], canonical_trace: false, idempotency_key: true, integrity: true, integrity_summary: true }),stateDir,upload: async (_sessionId, compressed) => {envelopes.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>);@@ -251,6 +253,7 @@ describe("session uploader privacy", () => {const envelopes: Array<Record<string, unknown>> = [];let asked = 0;const make = () => new SessionUploader({+ capabilities: async () => ({ schema_versions: [1, 2], canonical_trace: false, idempotency_key: true, integrity: true, integrity_summary: true }),stateDir,upload: async (_sessionId, compressed) => {envelopes.push(JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>);@@ -279,6 +282,7 @@ describe("session uploader privacy", () => {const accepted: Array<Record<string, unknown>> = [];let lookups = 0;const sessionUploader = new SessionUploader({+ capabilities: async () => ({ schema_versions: [1, 2], canonical_trace: false, idempotency_key: true, integrity: true, integrity_summary: true }),stateDir,upload: async (_sessionId, compressed) => {const envelope = JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>;@@ -1477,6 +1481,7 @@ describe("session upload deadline and spool drain", () => {const keys: Array<string | undefined> = [];let answers = 0;const sessionUploader = new SessionUploader({+ capabilities: async () => ({ schema_versions: [1, 2], canonical_trace: false, idempotency_key: true, integrity: true, integrity_summary: true }),stateDir,upload: async (_sessionId, _compressed, _signal, request) => {keys.push(request?.idempotencyKey);@@ -3988,3 +3993,31 @@ describe("session uploader incremental snapshots", () => {expect(start.privacy).toMatchObject({ files_truncated: false });}, 60_000);});++describe("upload features", () => {+ test("without the backend's idempotency_key feature (or any capability answer) no Idempotency-Key is sent and no integrity read is made", async () => {+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-nofeat-"));+ roots.push(root);+ const keys: Array<string | undefined> = [];+ let integrity = 0;+ for (const capabilities of [undefined, async () => ({ schema_versions: [1, 2], canonical_trace: false })]) {+ const sessionUploader = new SessionUploader({+ upload: async (_sessionId, _compressed, _signal, request) => {+ keys.push(request?.idempotencyKey);+ return Response.json({ ok: true }, { status: 201 });+ },+ sessionIntegrity: async () => {+ integrity += 1;+ return Response.json({ max_segment: 4, max_sequence: 9 });+ },+ ...(capabilities ? { capabilities } : {}),+ fallbackScanMs: 60_000,+ });+ sessionUploader.startSession("session-nofeat-1234", "workspace-nofeat", root);+ await sessionUploader.stop();+ }+ expect(keys.length).toBeGreaterThan(0);+ expect(keys.every((key) => key === undefined)).toBe(true);+ expect(integrity).toBe(0);+ });+});diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.tsindex e7ab98bb..18fa9518 100644--- a/apps/server/src/session-uploader.ts+++ b/apps/server/src/session-uploader.ts@@ -719,8 +719,17 @@ type SessionUploaderOptions = {export type TraceCapabilities = {schema_versions: number[];canonical_trace: boolean;+ /** Features of /collect/capabilities: a key the backend does not send is false. */+ idempotency_key?: boolean;+ body_sha256?: boolean;+ integrity?: boolean;+ integrity_summary?: boolean;+ recovered_segments?: boolean;+ /** The upload triggers the backend takes, when it lists them. */+ triggers?: string[];};+type TransmitOutcome =| { ok: true }| { ok: false; retryable: boolean; reason: string; unsupportedSchema?: boolean; retryAfterMs?: number; keyReused?: boolean };@@ -4322,6 +4331,10 @@ export function serverSessionPosition(payload: unknown): { segment: number; sequreturn found ? { segment, sequence } : null;}+/** The /collect features this client uses; without a capability answer, none. */+type UploadFeatures = { idempotencyKey: boolean; integrity: boolean };+const NO_UPLOAD_FEATURES: UploadFeatures = { idempotencyKey: false, integrity: false };+/** What a /collect upload carries besides its body. */export type UploadRequestOptions = { idempotencyKey?: string };@@ -4411,7 +4424,7 @@ export class SessionUploader {private readonly onBinaryFile?: (sessionId: string, path: string) => void;private readonly fileUploader?: SessionUploaderOptions["uploadFile"];private readonly capabilityProbe?: SessionUploaderOptions["capabilities"];- private traceSchemaCache: { version: 2 | 3; expiresAt: number } | null = null;+ private traceSchemaCache: { version: 2 | 3; features: UploadFeatures; expiresAt: number } | null = null;private traceSchemaProbe: Promise<2 | 3> | null = null;/** Work counters for tests and profiling. */readonly metrics: UploadMetrics = freshMetrics();@@ -4624,7 +4637,7 @@ export class SessionUploader {* say (offline, an older backend).*/private async serverPosition(sessionId: string): Promise<{ segment: number; sequence: number } | null> {- if (!this.sessionIntegrity) return null;+ if (!this.sessionIntegrity || !(await this.uploadFeatures()).integrity) return null;let timer: ReturnType<typeof setTimeout> | undefined;try {const response = await Promise.race([@@ -4770,6 +4783,7 @@ export class SessionUploader {if (this.traceSchemaProbe) return this.traceSchemaProbe;this.traceSchemaProbe = (async () => {let version: 2 | 3 = 2;+ let features: UploadFeatures = NO_UPLOAD_FEATURES;if (this.capabilityProbe) {try {const capabilities = await this.capabilityProbe();@@ -4778,11 +4792,12 @@ export class SessionUploader {&& capabilities.schema_versions.includes(TRACE_SCHEMA_VERSION)? 3: 2;+ features = { idempotencyKey: capabilities.idempotency_key === true, integrity: capabilities.integrity === true };} catch {version = 2;}}- this.traceSchemaCache = { version, expiresAt: Date.now() + TRACE_CAPABILITY_TTL_MS };+ this.traceSchemaCache = { version, features, expiresAt: Date.now() + TRACE_CAPABILITY_TTL_MS };return version;})().finally(() => {this.traceSchemaProbe = null;@@ -4791,7 +4806,13 @@ export class SessionUploader {}private downgradeTraceSchema(): void {- this.traceSchemaCache = { version: 2, expiresAt: Date.now() + TRACE_CAPABILITY_TTL_MS };+ this.traceSchemaCache = { version: 2, features: this.traceSchemaCache?.features ?? NO_UPLOAD_FEATURES, expiresAt: Date.now() + TRACE_CAPABILITY_TTL_MS };+ }++ /** What the backend's /collect takes beyond the envelope (Idempotency-Key, the integrity route), asked with the trace schema. */+ private async uploadFeatures(): Promise<UploadFeatures> {+ await this.negotiatedTraceSchema();+ return this.traceSchemaCache?.features ?? NO_UPLOAD_FEATURES;}startSession(sessionId: string, workspaceId: string, root: string): void {@@ -6377,7 +6398,8 @@ export class SessionUploader {let refreshAttempted = false;let resentForHash = false;let attempt = 0;- const request: UploadRequestOptions = check.idempotencyKey ? { idempotencyKey: check.idempotencyKey } : {};+ // The key goes out (and its 400/409 answers mean something) only where the backend takes it.+ const request: UploadRequestOptions = check.idempotencyKey && (await this.uploadFeatures()).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);@@ -6421,7 +6443,7 @@ export class SessionUploader {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) {+ if (response.status === 409 && request.idempotencyKey) {const keyReused = (await boundedResponseText(response)).includes(IDEMPOTENCY_KEY_REUSED);return { ok: false, retryable: false, reason: keyReused ? `${lastReason} (${IDEMPOTENCY_KEY_REUSED})` : lastReason, ...(keyReused ? { keyReused } : {}) };}