An open-source, faster Devin alternative
TypeScript
cutover fixes
Brian Reardone274977d78a4
diff --git a/cloudflare-workers/api-edge/assets b/cloudflare-workers/api-edge/assetsnew file mode 120000index 00000000..31e65a1d--- /dev/null+++ b/cloudflare-workers/api-edge/assets@@ -0,0 +1 @@+/Users/brian/development/opencomputer/web/dist\ No newline at end of filediff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex bd491774..bfdcfa9a 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -969,11 +969,12 @@ export async function handleDashboard(// dashboard renders instead of 404-erroring on a missing route.if (sub === "/billing" && method === "GET") {const org = await env.OPENCOMPUTER_DB.prepare(- `SELECT plan, stripe_customer_id, stripe_subscription_id, free_credits_remaining_cents, credit_balance_cents, is_halted+ `SELECT plan, stripe_customer_id, stripe_subscription_id, free_credits_remaining_cents, credit_balance_cents, is_halted, max_concurrent_sandboxesFROM orgs WHERE id = ?1`,).bind(caller.orgID).first<{plan: string; stripe_customer_id: string | null; stripe_subscription_id: string | null;free_credits_remaining_cents: number; credit_balance_cents: number; is_halted: number;+ max_concurrent_sandboxes: number;}>();if (!org) return json({ error: "org not found" }, 404);// Cross-check against the live DO state — the D1 mirror gets written by@@ -1005,6 +1006,7 @@ export async function handleDashboard(freeCreditsRemainingCents: liveBalance,creditBalanceCents: org.credit_balance_cents,isHalted: !!org.is_halted,+ maxConcurrentSandboxes: org.max_concurrent_sandboxes,// Upcoming-invoice + meters would come from Stripe API on demand;// surface stubs for now so the UI has stable keys to render against.upcomingInvoice: null,diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex ff9c027c..123a1224 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -1267,6 +1267,30 @@ export default {return proxyToCellSDK(req, env, ctx, caller, id);}+ // Generic /api/* fallback proxy — routes unmatched dashboard endpoints+ // (/api/images, /api/sessions, /api/me, /api/workers, /api/checkpoints,+ // /api/api-keys, /api/org*, /api/agents, /api/billing*, etc.) to the+ // home cell's CP. These were served by the CP pre-cutover; the edge+ // doesn't have native handlers for them yet. The CP does its own auth+ // (X-API-Key or session JWT) — we just pass through.+ if (path.startsWith("/api/")) {+ const cellRow = await env.OPENCOMPUTER_DB.prepare(+ `SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at+ FROM cells WHERE status = 'active' LIMIT 1`,+ ).first<CellRow>();+ if (!cellRow) return json({ error: "no active cell" }, 503);+ const target = cellRow.base_url.replace(/\/$/, "") + url.pathname + url.search;+ const proxyHeaders = new Headers(req.headers);+ proxyHeaders.set("X-Forwarded-Host", url.host);+ const proxyReq = new Request(target, {+ method: req.method,+ headers: proxyHeaders,+ body: ["GET", "HEAD"].includes(req.method) ? null : req.body,+ redirect: "manual",+ });+ return fetch(proxyReq);+ }+// Anything not matched above is the dashboard SPA — delegate to the// assets binding. run_worker_first=true in wrangler.toml means CF runs// this Worker before checking assets, so we have to explicitly handdiff --git a/cmd/server/main.go b/cmd/server/main.goindex 6ae1fcbd..e7fcd9ee 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -13,6 +13,8 @@ import ("syscall""time"+ "github.com/redis/go-redis/v9"+"github.com/opensandbox/opensandbox/internal/api""github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/billing"@@ -530,12 +532,21 @@ func main() {for _, w := range redisRegistry.GetAllWorkers() {liveWorkers[w.ID] = true}- orphaned, err := opts.Store.MarkOrphanedSandboxes(ctx, liveWorkers)+ orphans, err := opts.Store.MarkOrphanedSandboxes(ctx, liveWorkers)if err != nil {log.Printf("maintenance: orphan reconciliation error: %v", err)observability.CaptureError(err, "area", "maintenance", "op", "mark_orphaned_sandboxes")- } else if orphaned > 0 {- log.Printf("maintenance: marked %d sandboxes as error (worker lost)", orphaned)+ } else if len(orphans) > 0 {+ log.Printf("maintenance: marked %d sandboxes as error (worker lost)", len(orphans))+ // Mirror to D1 via the events stream. Without these XADDs,+ // sandboxes_index keeps showing the rows as running on the+ // dead worker indefinitely — the post-cutover ghost-row+ // bug. Best-effort; the next tick will re-emit for any+ // row still marked `error` on a dead worker if Redis+ // rejected the first attempt.+ if redisRegistry.RedisClient() != nil && cfg.CellID != "" {+ publishStoppedFromMaintenance(ctx, redisRegistry.RedisClient(), cfg.CellID, orphans)+ }}}})@@ -784,3 +795,13 @@ func getIntEnv(key string, def int) int {}return def}++// publishStoppedFromMaintenance emits a `stopped` lifecycle event per+// orphaned sandbox so D1 sandboxes_index mirrors the PG sweep done by+// MarkOrphanedSandboxes. Without these XADDs, the maintenance loop's+// dead-worker cleanup is invisible to the dashboard.+func publishStoppedFromMaintenance(ctx context.Context, rdb *redis.Client, cellID string, orphans []db.OrphanedSandbox) {+ for _, o := range orphans {+ controlplane.PublishLifecycle(ctx, rdb, cellID, "stopped", o.SandboxID, o.WorkerID, o.OrgID, "worker_lost")+ }+}diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex fada3f6d..32b57663 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -488,6 +488,20 @@ func main() {}_ = store.UpdateSandboxSessionStatus(context.Background(), sandboxID, "hibernated", nil)}+ // Emit "hibernated" lifecycle event so events-ingest mirrors the+ // status flip to D1 sandboxes_index. Without this, idle-timeout+ // hibernations only land in cell PG and D1 keeps showing the+ // sandbox as running on a worker that no longer hosts it.+ if sandboxDBMgr != nil {+ if sdb, dbErr := sandboxDBMgr.Get(sandboxID); dbErr == nil {+ _ = sdb.LogEvent("hibernated", map[string]string{+ "sandbox_id": sandboxID,+ "checkpoint_key": result.HibernationKey,+ "reason": "idle_timeout",+ })+ }+ _ = sandboxDBMgr.Remove(sandboxID)+ }},OnKill: func(sandboxID string) {log.Printf("opensandbox-worker: sandbox %s killed on timeout", sandboxID)@@ -495,6 +509,17 @@ func main() {if store != nil {_ = store.UpdateSandboxSessionStatus(context.Background(), sandboxID, "stopped", nil)}+ // Same fix as OnHibernate above — D1 needs a "stopped" event so+ // the dashboard doesn't keep the row at "running" forever.+ if sandboxDBMgr != nil {+ if sdb, dbErr := sandboxDBMgr.Get(sandboxID); dbErr == nil {+ _ = sdb.LogEvent("stopped", map[string]string{+ "sandbox_id": sandboxID,+ "reason": "kill_timeout",+ })+ }+ _ = sandboxDBMgr.Remove(sandboxID)+ }},})defer sbRouter.Close()diff --git a/internal/controlplane/event_publish.go b/internal/controlplane/event_publish.gonew file mode 100644index 00000000..e9a38553--- /dev/null+++ b/internal/controlplane/event_publish.go@@ -0,0 +1,69 @@+package controlplane++import (+ "context"+ "encoding/json"+ "log"+ "time"++ "github.com/google/uuid"+ "github.com/redis/go-redis/v9"+)++// PublishLifecycle XADDs a sandbox lifecycle event (`stopped`, `hibernated`,+// `migrated`, etc.) to the cell's events stream. Used for CP-side state+// changes — the scaler's orphan sweep, the maintenance loop's dead-worker+// reconciler — where the worker's per-sandbox SQLite never emitted because+// the worker is gone or never got involved.+//+// Retries up to 3 times with a short backoff so a Redis hiccup doesn't+// permanently drop the event. Drops on this path produce ghost rows in D1+// sandboxes_index that only the periodic reconciler can clean up.+//+// Returns true if the XADD succeeded on some attempt, false if all three+// failed (caller logs/decides next steps).+func PublishLifecycle(ctx context.Context, rdb *redis.Client, cellID, eventType, sandboxID, workerID string, orgID uuid.UUID, reason string) bool {+ if rdb == nil || cellID == "" || sandboxID == "" {+ return false+ }+ envelope := map[string]any{+ "id": uuid.NewString(),+ "type": eventType,+ "sandbox_id": sandboxID,+ "org_id": orgID.String(),+ "worker_id": workerID,+ "cell_id": cellID,+ "payload": map[string]any{"reason": reason},+ "timestamp": time.Now().UTC().Format(time.RFC3339Nano),+ }+ body, err := json.Marshal(envelope)+ if err != nil {+ log.Printf("PublishLifecycle marshal %s: %v", eventType, err)+ return false+ }+ stream := "events:" + cellID+ backoff := 200 * time.Millisecond+ for attempt := 1; attempt <= 3; attempt++ {+ xaddCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ err := rdb.XAdd(xaddCtx, &redis.XAddArgs{+ Stream: stream,+ MaxLen: 100000,+ Approx: true,+ Values: map[string]any{"event": string(body)},+ }).Err()+ cancel()+ if err == nil {+ return true+ }+ log.Printf("PublishLifecycle %s sandbox=%s attempt %d/3 failed: %v", eventType, sandboxID, attempt, err)+ if attempt < 3 {+ select {+ case <-ctx.Done():+ return false+ case <-time.After(backoff):+ }+ backoff *= 2+ }+ }+ return false+}diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex b25395c3..b53b9f50 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -2,7 +2,6 @@ package controlplaneimport ("context"- "encoding/json""errors""fmt""log"@@ -187,40 +186,18 @@ func NewScaler(cfg ScalerConfig) *Scaler {}}-// publishMigrated XADDs a "migrated" event to events:{cell_id} so events--// ingest updates D1 sandboxes_index.worker_id. Required for rolling-replace-// + evacuation paths — without it, the dashboard's cross-cell view drifts-// from cell-PG truth on every scaler-driven migration. Best-effort; failures-// are logged but don't block the migration itself.+// publishMigrated XADDs a "migrated" event when a sandbox's worker_id moves+// (rolling replace, evacuation). Without it, D1 drifts from cell PG.func (s *Scaler) publishMigrated(ctx context.Context, sandboxID, newWorkerID string, orgID uuid.UUID, reason string) {- if s.rdb == nil || s.cellID == "" || sandboxID == "" {- return- }- envelope := map[string]any{- "id": uuid.NewString(),- "type": "migrated",- "sandbox_id": sandboxID,- "org_id": orgID.String(),- "worker_id": newWorkerID,- "cell_id": s.cellID,- "payload": map[string]any{"reason": reason},- "timestamp": time.Now().UTC().Format(time.RFC3339Nano),- }- body, err := json.Marshal(envelope)- if err != nil {- log.Printf("scaler: publishMigrated marshal: %v", err)- return- }- xaddCtx, cancel := context.WithTimeout(ctx, 3*time.Second)- defer cancel()- if err := s.rdb.XAdd(xaddCtx, &redis.XAddArgs{- Stream: "events:" + s.cellID,- MaxLen: 100000,- Approx: true,- Values: map[string]any{"event": string(body)},- }).Err(); err != nil {- log.Printf("scaler: publishMigrated XADD: %v", err)- }+ PublishLifecycle(ctx, s.rdb, s.cellID, "migrated", sandboxID, newWorkerID, orgID, reason)+}++// publishStopped XADDs a "stopped" event when the CP determines a sandbox+// can no longer be reached on its prior worker (orphan sweep). The+// worker_id in the envelope is the dead one for trace continuity;+// events-ingest sets status='stopped' on D1.+func (s *Scaler) publishStopped(ctx context.Context, sandboxID, workerID string, orgID uuid.UUID, reason string) {+ PublishLifecycle(ctx, s.rdb, s.cellID, "stopped", sandboxID, workerID, orgID, reason)}// Start begins the autoscaling loop. Can be called multiple times (idempotent).@@ -1130,10 +1107,17 @@ func (s *Scaler) drainWorker(workerID, machineID, region string) {// reflects reality before the worker gets destroyed.if s.store != nil {sweepCtx, sweepCancel := context.WithTimeout(context.Background(), 10*time.Second)- if n, err := s.store.MarkOrphanedOnWorker(sweepCtx, workerID, "drain completed; worker reported no sandboxes"); err != nil {+ orphans, err := s.store.MarkOrphanedOnWorker(sweepCtx, workerID, "drain completed; worker reported no sandboxes")+ if err != nil {log.Printf("scaler: drain: orphan sweep on %s failed: %v", workerID, err)- } else if n > 0 {- log.Printf("scaler: drain: orphan sweep on %s reconciled %d phantom row(s)", workerID, n)+ } else if len(orphans) > 0 {+ log.Printf("scaler: drain: orphan sweep on %s reconciled %d phantom row(s)", workerID, len(orphans))+ // Mirror the PG change to D1 via the events stream — without+ // these XADDs, sandboxes_index stays at status='running'+ // pointing at the about-to-be-destroyed worker forever.+ for _, o := range orphans {+ s.publishStopped(context.Background(), o.SandboxID, workerID, o.OrgID, "drain_orphan_sweep")+ }}sweepCancel()}diff --git a/internal/db/store.go b/internal/db/store.goindex 4b9f3016..aec40c97 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -777,19 +777,40 @@ func (s *Store) FailMigrationPostQMP(ctx context.Context, sandboxID, errorMsg streturn err}+// OrphanedSandbox is one row affected by MarkOrphanedOnWorker /+// MarkOrphanedSandboxes — callers use these to emit downstream `stopped`+// events so D1 sandboxes_index mirrors the PG state change (without an+// event, D1 drifts).+type OrphanedSandbox struct {+ SandboxID string+ OrgID uuid.UUID+ WorkerID string+}+// MarkOrphanedOnWorker marks any still-running/migrating sandboxes pointing at the given worker// as error. Called when drain finishes to sweep up rows the per-sandbox migration failure paths// missed — e.g. a sandbox that vanished from the worker (failed migration cleanup) but whose DB-// row still references the worker.-func (s *Store) MarkOrphanedOnWorker(ctx context.Context, workerID, errorMsg string) (int, error) {- tag, err := s.pool.Exec(ctx,+// row still references the worker. Returns the affected (sandbox_id, org_id) pairs so the+// caller can publish `stopped` events; without them, D1 keeps the row at `running`.+func (s *Store) MarkOrphanedOnWorker(ctx context.Context, workerID, errorMsg string) ([]OrphanedSandbox, error) {+ rows, err := s.pool.Query(ctx,`UPDATE sandbox_sessions SET status = 'error', migrating_to_worker = '', stopped_at = now(), error_msg = $2- WHERE worker_id = $1 AND status IN ('running', 'migrating')`,+ WHERE worker_id = $1 AND status IN ('running', 'migrating')+ RETURNING sandbox_id, org_id, worker_id`,workerID, errorMsg)if err != nil {- return 0, err+ return nil, err}- return int(tag.RowsAffected()), nil+ defer rows.Close()+ var orphans []OrphanedSandbox+ for rows.Next() {+ var o OrphanedSandbox+ if err := rows.Scan(&o.SandboxID, &o.OrgID, &o.WorkerID); err != nil {+ return nil, err+ }+ orphans = append(orphans, o)+ }+ return orphans, rows.Err()}// RecoverStaleMigrations resets any sandbox stuck in 'migrating' status for more than the given duration.@@ -804,18 +825,19 @@ func (s *Store) RecoverStaleMigrations(ctx context.Context, maxAge time.Durationreturn int(tag.RowsAffected()), nil}-// MarkOrphanedSandboxes marks running sandboxes on dead workers as error.-// liveWorkers is the set of worker IDs currently registered.-func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[string]bool) (int, error) {- // Get all distinct worker_ids with running sandboxes+// MarkOrphanedSandboxes marks running sandboxes on dead workers as error+// and returns the affected (sandbox_id, org_id, worker_id) tuples so the+// caller can publish `stopped` lifecycle events. liveWorkers is the set+// of worker IDs currently registered. Without the returned IDs the maintenance+// loop's PG sweep would never reach D1 sandboxes_index, which is exactly+// the post-cutover ghost-row bug.+func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[string]bool) ([]OrphanedSandbox, error) {rows, err := s.pool.Query(ctx,`SELECT DISTINCT worker_id FROM sandbox_sessions WHERE status = 'running'`)if err != nil {- return 0, err+ return nil, err}- defer rows.Close()-- total := 0+ deadWorkers := make([]string, 0)for rows.Next() {var workerID stringif err := rows.Scan(&workerID); err != nil {@@ -824,15 +846,28 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strinif liveWorkers[workerID] {continue}- // Worker not in registry — mark its sandboxes as error- tag, err := s.pool.Exec(ctx,+ deadWorkers = append(deadWorkers, workerID)+ }+ rows.Close()++ var orphans []OrphanedSandbox+ for _, workerID := range deadWorkers {+ upd, err := s.pool.Query(ctx,`UPDATE sandbox_sessions SET status = 'error', error_msg = 'worker lost', stopped_at = now()- WHERE worker_id = $1 AND status = 'running'`, workerID)- if err == nil {- total += int(tag.RowsAffected())+ WHERE worker_id = $1 AND status = 'running'+ RETURNING sandbox_id, org_id, worker_id`, workerID)+ if err != nil {+ continue+ }+ for upd.Next() {+ var o OrphanedSandbox+ if err := upd.Scan(&o.SandboxID, &o.OrgID, &o.WorkerID); err == nil {+ orphans = append(orphans, o)+ }}+ upd.Close()}- return total, nil+ return orphans, nil}func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*SandboxSession, error) {diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.jsonindex b637c778..1b37e8fb 100644--- a/sdks/typescript/package-lock.json+++ b/sdks/typescript/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/sdk",- "version": "0.5.0",+ "version": "0.5.17","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/sdk",- "version": "0.5.0",+ "version": "0.5.17","license": "MIT","devDependencies": {"@types/node": "^25.3.0",@@ -850,7 +850,6 @@"integrity": "sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"undici-types": "~7.18.0"}