An open-source, faster Devin alternative
TypeScript
fix: index streamed sandbox creates inline (#374)
Mohamed Habib7c0a88dc6175
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.tsindex 8ca25b7c..bd339c21 100644--- a/cloudflare-workers/api-edge/src/index.test.ts+++ b/cloudflare-workers/api-edge/src/index.test.ts@@ -5,10 +5,15 @@ const orgID = "org-1";const userID = "user-1";const cellID = "azure-us-east-2-a";+const sandboxIndexInserts: unknown[][] = [];+class FakeStatement {constructor(private sql: string) {}- bind(..._args: unknown[]) {+ private args: unknown[] = [];++ bind(...args: unknown[]) {+ this.args = args;return this;}@@ -33,10 +38,44 @@ class FakeStatement {if (this.sql.includes("SELECT plan FROM orgs")) {return { plan: "pro" } as T;}+ if (this.sql.includes("SELECT home_cell, plan, is_halted")) {+ return {+ home_cell: cellID,+ plan: "pro",+ is_halted: 0,+ max_concurrent_sandboxes: 10,+ max_disk_mb: 262144,+ } as T;+ }+ if (this.sql.includes("COUNT(*) AS n FROM sandboxes_index")) {+ return { n: 0 } as T;+ }return null;}+ async all<T>() {+ if (this.sql.includes("FROM cells WHERE status = 'active'")) {+ return {+ results: [+ {+ cell_id: cellID,+ cloud: "azure",+ region: "us-east-2",+ base_url: "https://cp-us-east-2.opencomputer.dev",+ status: "active",+ available_workers: 1,+ capacity_updated_at: Math.floor(Date.now() / 1000),+ },+ ],+ } as { results: T[] };+ }+ return { results: [] as T[] };+ }+async run() {+ if (this.sql.includes("INSERT OR REPLACE INTO sandboxes_index")) {+ sandboxIndexInserts.push(this.args);+ }return {};}}@@ -68,6 +107,7 @@ const ctx = {describe("api-edge WebSocket auth", () => {afterEach(() => {vi.unstubAllGlobals();+ sandboxIndexInserts.length = 0;});it("accepts api_key query auth for sandbox WebSocket proxy requests", async () => {@@ -168,3 +208,57 @@ describe("api-edge WebSocket auth", () => {expect(fetchSpy).not.toHaveBeenCalled();});});++describe("api-edge sandbox create", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ sandboxIndexInserts.length = 0;+ });++ it("indexes SSE snapshot creates before the streamed response completes", async () => {+ const fetchSpy = vi.fn(async (_url: string, _init?: RequestInit) => {+ const body = [+ "event: build_log",+ 'data: {"message":"creating"}',+ "",+ "event: result",+ 'data: {"sandboxID":"sb-sse1234","workerID":"worker-1","status":"running","memoryMB":2048}',+ "",+ ].join("\n");+ return new Response(body, {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });+ });+ vi.stubGlobal("fetch", fetchSpy);++ const resp = await worker.fetch(+ new Request("https://app.opencomputer.dev/api/sandboxes", {+ method: "POST",+ headers: {+ "X-API-Key": "osb_test",+ "Content-Type": "application/json",+ Accept: "text/event-stream",+ },+ body: JSON.stringify({ snapshot: "snapshot-1", memoryMB: 1024 }),+ }),+ env,+ ctx,+ );++ expect(resp.status).toBe(200);+ expect(await resp.text()).toContain("event: result");+ expect(sandboxIndexInserts).toHaveLength(1);+ expect(sandboxIndexInserts[0]).toEqual([+ "sb-sse1234",+ orgID,+ userID,+ cellID,+ "worker-1",+ "running",+ 0,+ 2048,+ expect.any(Number),+ ]);+ });+});diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex a7db3dfd..63d800ad 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -102,6 +102,13 @@ interface Caller {userID: string | null;}+interface SandboxCreateResult {+ sandboxID?: string;+ workerID?: string;+ status?: string;+ memoryMB?: number;+}+function isWebSocketUpgrade(req: Request): boolean {return req.headers.get("upgrade")?.toLowerCase() === "websocket";}@@ -433,6 +440,107 @@ async function enforceCreatePolicy(return null;}+async function insertSandboxIndex(+ env: Env,+ caller: Caller,+ cellID: string,+ parsed: SandboxCreateResult,+ fallbackCpuCount: number,+ fallbackMemoryMB: number,+): Promise<void> {+ if (!parsed.sandboxID) return;+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT OR REPLACE INTO sandboxes_index+ (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)`,+ )+ .bind(+ parsed.sandboxID,+ caller.orgID,+ caller.userID,+ cellID,+ parsed.workerID ?? null,+ parsed.status ?? "running",+ fallbackCpuCount,+ parsed.memoryMB ?? fallbackMemoryMB,+ Math.floor(Date.now() / 1000),+ )+ .run();+}++function indexSandboxFromSSE(+ resp: Response,+ env: Env,+ caller: Caller,+ cellID: string,+ fallbackCpuCount: number,+ fallbackMemoryMB: number,+): Response {+ if (!resp.ok || !resp.body) return resp;++ const decoder = new TextDecoder();+ let buffer = "";+ let eventName = "message";+ let dataLines: string[] = [];+ let indexed = false;++ const handleEvent = async () => {+ if (eventName !== "result" || dataLines.length === 0 || indexed) {+ eventName = "message";+ dataLines = [];+ return;+ }++ indexed = true;+ const data = dataLines.join("\n");+ eventName = "message";+ dataLines = [];++ try {+ const parsed = JSON.parse(data) as SandboxCreateResult;+ await insertSandboxIndex(env, caller, cellID, parsed, fallbackCpuCount, fallbackMemoryMB);+ } catch (e) {+ console.error("sandboxes_index SSE create insert failed:", e);+ }+ };++ const processLine = async (line: string) => {+ if (line === "") {+ await handleEvent();+ return;+ }+ if (line.startsWith(":")) return;+ const colon = line.indexOf(":");+ const field = colon === -1 ? line : line.slice(0, colon);+ const value = colon === -1 ? "" : line.slice(colon + (line[colon + 1] === " " ? 2 : 1));+ if (field === "event") {+ eventName = value;+ } else if (field === "data") {+ dataLines.push(value);+ }+ };++ const stream = new TransformStream<Uint8Array, Uint8Array>({+ async transform(chunk, controller) {+ buffer += decoder.decode(chunk, { stream: true });+ const lines = buffer.split(/\r\n|\r|\n/);+ buffer = lines.pop() ?? "";+ for (const line of lines) {+ await processLine(line);+ }+ controller.enqueue(chunk);+ },+ async flush() {+ const tail = decoder.decode();+ if (tail) buffer += tail;+ if (buffer) await processLine(buffer);+ await handleEvent();+ },+ });++ return new Response(resp.body.pipeThrough(stream), resp);+}+async function createSandbox(req: Request, env: Env): Promise<Response> {const caller = await authenticate(req, env);if (!caller) return json({ error: "missing or invalid API key" }, 401);@@ -509,21 +617,18 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {const capToken = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, caller.userID);// SSE build streaming: image/snapshot creates can take minutes (apt installs,- // etc.). When the client asks for an event stream, forward the Accept header- // and stream the cell's SSE response straight through — build logs reach the- // client live and the final `result` event is delivered intact. Buffering- // with .text() (the non-SSE path below) collapsed the stream to one blob,- // which broke the Python SDK ("No result received from build stream"). The- // sandboxes_index row is populated by the cell's `created` event via the- // events pipeline, so we don't need the inline INSERT on this path.+ // etc.). Preserve live streaming, but index the final `result` event inline+ // before the stream closes. Relying only on async lifecycle events leaves a+ // race where immediate GET/DELETE after create sees no sandboxes_index row.const wantsSSE = req.headers.get("accept") === "text/event-stream";if (wantsSSE) {try {- return await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/create", {+ const cpResp = await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/create", {method: "POST",headers: { authorization: "Bearer " + capToken, "content-type": "application/json", accept: "text/event-stream" },body: bodyText || "{}",});+ return indexSandboxFromSSE(cpResp, env, caller, cell.cell_id, bodyCpuCount, bodyMemoryMB);} catch (e) {return json({ error: `cell ${cell.cell_id} unreachable: ${(e as Error).message}` }, 502);}@@ -542,31 +647,13 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {const cpText = await cpResp.text();if (cpResp.status >= 200 && cpResp.status < 300) {- let parsed: { sandboxID?: string; workerID?: string; status?: string; memoryMB?: number } = {};+ let parsed: SandboxCreateResult = {};try {parsed = JSON.parse(cpText);} catch {/* leave parsed empty — still record what we can */}- if (parsed.sandboxID) {- await env.OPENCOMPUTER_DB.prepare(- `INSERT OR REPLACE INTO sandboxes_index- (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)`,- )- .bind(- parsed.sandboxID,- caller.orgID,- caller.userID,- cell.cell_id,- parsed.workerID ?? null,- parsed.status ?? "running",- bodyCpuCount,- parsed.memoryMB ?? bodyMemoryMB,- Math.floor(Date.now() / 1000),- )- .run();- }+ await insertSandboxIndex(env, caller, cell.cell_id, parsed, bodyCpuCount, bodyMemoryMB);}// Pass the CP's response through verbatim (status + body).return new Response(cpText, {