An open-source, faster Devin alternative
TypeScript
prepare for cutover, add missing surfaces
Brian Reardon350ac55b3aed
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 3d14b1a6..bd491774 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -933,13 +933,24 @@ export async function handleDashboard(if (m && method === "DELETE") return handleDeleteCheckpoint(req, env, caller, m[1]);}- // ── images: proxy to home cell ────────────────────────────────────────- // image_cache is per-cell; for now dashboard shows the home cell's view.- // Cross-cell image visibility is Phase 2 (D1 image_cache mirror).- if (sub === "/images" || sub.startsWith("/images/")) {- const cell = await homeCell(env, caller.orgID);- if (!cell) return json({ error: "home cell unavailable" }, 503);- return proxyToCell(req, env, caller, cell, `/internal/dashboard${sub}`);+ // ── images: cross-cell list from D1 images_index ───────────────────────+ // CP emits image_cache_ready / image_cache_deleted events; events-ingest+ // upserts/deletes this table. The dashboard's Images page used to proxy+ // to the user's home_cell, which broke cross-cell visibility — building+ // a snapshot on cell A wouldn't show in the dashboard if the user later+ // moved to cell B. D1 is now authoritative.+ //+ // Mutations (DELETE) still need to land on the owning cell — only that+ // cell has the underlying bytes/checkpoint to clean up — so DELETE is+ // routed to the cell that owns the row.+ if (sub === "/images" && method === "GET") {+ return handleListImages(env, caller);+ }+ {+ const m = sub.match(/^\/images\/([^/]+)$/);+ if (m && method === "DELETE") {+ return handleDeleteImage(req, env, caller, m[1]);+ }}// ── agents: proxy to home cell (cell-side hits external agents service) ─@@ -1023,6 +1034,70 @@ export async function handleDashboard(return json({ error: `not found: ${method} ${sub}` }, 404);}+// ── Images (cross-cell via D1 images_index) ────────────────────────────++interface ImagesRow {+ id: string;+ org_id: string;+ owner_cell_id: string;+ content_hash: string;+ checkpoint_id: string | null;+ name: string | null;+ manifest: string;+ status: string;+ created_at: number;+ last_used_at: number;+}++async function handleListImages(env: DashboardEnv, caller: Caller): Promise<Response> {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, org_id, owner_cell_id, content_hash, checkpoint_id, name, manifest, status, created_at, last_used_at+ FROM images_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT 200`,+ )+ .bind(caller.orgID)+ .all<ImagesRow>();+ const out = (results ?? []).map((r) => {+ let manifest: unknown = {};+ try { manifest = JSON.parse(r.manifest); } catch { /* keep empty */ }+ return {+ id: r.id,+ orgId: r.org_id,+ cellId: r.owner_cell_id,+ contentHash: r.content_hash,+ checkpointId: r.checkpoint_id,+ name: r.name,+ manifest,+ status: r.status,+ createdAt: new Date(r.created_at * 1000).toISOString(),+ lastUsedAt: new Date(r.last_used_at * 1000).toISOString(),+ };+ });+ return json(out);+}++async function handleDeleteImage(req: Request, env: DashboardEnv, caller: Caller, imageID: string): Promise<Response> {+ // Look up owning cell to forward the DELETE to (bytes + checkpoint live there).+ const row = await env.OPENCOMPUTER_DB.prepare(+ `SELECT owner_cell_id, name FROM images_index WHERE id = ?1 AND org_id = ?2`,+ )+ .bind(imageID, caller.orgID)+ .first<{ owner_cell_id: string; name: string | null }>();+ if (!row) return json({ error: "image not found" }, 404);+ if (!row.name) return json({ error: "auto-cached images are managed by the cell — only named snapshots can be deleted via dashboard" }, 400);++ // Find the cell's base_url and forward via tunnel.+ const cell = await env.OPENCOMPUTER_DB.prepare(+ `SELECT base_url FROM cells WHERE cell_id = ?1`,+ )+ .bind(row.owner_cell_id)+ .first<{ base_url: string }>();+ if (!cell) return json({ error: "owning cell not registered" }, 503);++ // Reuse proxyToCell so the cap-token / cookie auth chain handles auth.+ // Path mirrors what the legacy dashboard called: /internal/dashboard/images/{name}+ return proxyToCell(req, env, caller, { cell_id: row.owner_cell_id, base_url: cell.base_url }, `/internal/dashboard/images/${row.name}`);+}+// ── Stripe helpers ─────────────────────────────────────────────────────// stripeApi POSTs form-urlencoded to Stripe's REST API. GET is supported viadiff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlnew file mode 100644index 00000000..32bfc6dc--- /dev/null+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -0,0 +1,68 @@+# api-edge Worker — PROD on opencomputer.dev zone.+# Mirrors wrangler.toml (dev) but targets Mo's CF account.+# Deploy: `wrangler deploy -c wrangler.prod.toml`+#+# Final cutover hostname will be app.opencomputer.dev; during parallel run+# we serve at app2.opencomputer.dev so the legacy app at opencomputer.dev+# (opencomputer-site-v1 worker) keeps serving.++name = "opencomputer-edge-prod"+main = "src/index.ts"+compatibility_date = "2026-04-28"+compatibility_flags = ["nodejs_compat"]+account_id = "b8f23cb87a7a6c64040d3134643da448"++# Preview URL routing — same scheme as dev (`*.sb.<zone>/*`).+# Requires an Advanced Certificate Manager cert for *.sb.opencomputer.dev+# + sb.opencomputer.dev (two-level wildcard isn't covered by Universal SSL).+# Order the ACM cert BEFORE the first deploy or the route will 525-error.+routes = [+ { pattern = "*.sb.opencomputer.dev/*", zone_name = "opencomputer.dev" },+]++# Static assets — the dashboard SPA. Built from `web/` by the deploy script.+[assets]+directory = "./assets"+binding = "ASSETS"+not_found_handling = "single-page-application"+run_worker_first = true++[[d1_databases]]+binding = "OPENCOMPUTER_DB"+database_name = "opencomputer-prod"+database_id = "8329e0f0-100d-445a-bf89-95c065f15dbb"++[[kv_namespaces]]+binding = "SESSIONS_KV"+id = "b496f905ce634f94b6ac1d4f619825e0"++[[durable_objects.bindings]]+name = "CREDIT_ACCOUNT"+class_name = "CreditAccount"+script_name = "opencomputer-edge-prod"++[[migrations]]+tag = "v1"+new_sqlite_classes = ["CreditAccount"]++# Secrets (set via `wrangler secret put --config wrangler.prod.toml`):+# SESSION_JWT_SECRET — fresh prod HMAC (DO NOT reuse dev secret)+# CF_ADMIN_SECRET — fresh prod HMAC, shared with prod CPs+# STRIPE_WEBHOOK_SECRET — Stripe LIVE mode webhook signing secret+# STRIPE_API_KEY — Stripe LIVE mode API key (sk_live_...)+# WORKOS_API_KEY — prod WorkOS app API key+# WORKOS_CLIENT_ID — prod WorkOS client identifier+# EVENT_SECRET — fresh prod HMAC, shared with prod CPs + events-ingest+# SECRET_ENCRYPTION_KEY — envelope-encryption key for D1 secret_store_entries+# (must match Infisical /shared/ key the CPs use, so+# plaintext stays in sync across edge ↔ cells)++[vars]+WORKER_ENV = "prod"+# No prod cells registered yet. Populate when prod CPs come online and+# their rows are written to the D1 `cells` table.+CELLS = ""++# Ship Worker logs to opencomputer-log-tail-prod → Axiom dataset cf-prod.+[[tail_consumers]]+service = "opencomputer-log-tail-prod"diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.tsindex 1bdbeb2f..21dcecfc 100644--- a/cloudflare-workers/events-ingest/src/index.ts+++ b/cloudflare-workers/events-ingest/src/index.ts@@ -155,6 +155,15 @@ export default {SET status = 'running', stopped_at = NULL, last_event_at = ?1WHERE id = ?2 AND (last_event_at IS NULL OR last_event_at < ?1)`,);+ // Migration: sandbox moved to a new worker. Update worker_id alongside+ // status so proxyToCellSDK + dashboard reflect the new home immediately+ // (the "created" event on the destination worker would set status but+ // not worker_id otherwise).+ const lifecycleMigrated = env.OPENCOMPUTER_DB.prepare(+ `UPDATE sandboxes_index+ SET status = 'running', worker_id = ?1, stopped_at = NULL, last_event_at = ?2+ WHERE id = ?3 AND (last_event_at IS NULL OR last_event_at < ?2)`,+ );const capacityBatches = fresh.filter((e) => e.type === "cell_capacity").map((e) => {@@ -175,11 +184,17 @@ export default {});const lifecycleBatches = fresh- .filter((e) => e.sandbox_id && (e.type === "stopped" || e.type === "hibernated" || e.type === "running" || e.type === "woke" || e.type === "created"))+ .filter((e) => e.sandbox_id && (e.type === "stopped" || e.type === "hibernated" || e.type === "running" || e.type === "woke" || e.type === "created" || e.type === "migrated")).map((e) => {const tsSec = Math.floor((Date.parse(e.timestamp) || Date.now()) / 1000);if (e.type === "stopped") return lifecycleStopped.bind(tsSec, e.sandbox_id);if (e.type === "hibernated") return lifecycleHibernated.bind(tsSec, e.sandbox_id);+ if (e.type === "migrated") {+ // worker_id moves with the sandbox; payload carries the new one+ // (the CP-side publishSandboxLifecycleEvent uses the envelope's+ // worker_id field rather than payload for migrated events).+ return lifecycleMigrated.bind(e.worker_id ?? "", tsSec, e.sandbox_id);+ }// "running", "woke", "created" all set the row to running (created// is handled by the edge on POST, but accept here for redundancy// in case of replay against a future cell-only create path).@@ -234,8 +249,61 @@ export default {];});+ // Image cache lifecycle (analogous to checkpoint lifecycle): CP emits+ // image_cache_ready after a build/snapshot lands in cell PG image_cache,+ // image_cache_deleted on removal. Keeps the dashboard's /api/dashboard/+ // images view in sync without per-cell fan-out.+ const imageUpsert = env.OPENCOMPUTER_DB.prepare(+ `INSERT INTO images_index+ (id, org_id, owner_cell_id, content_hash, checkpoint_id, name, manifest, status, created_at, last_used_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)+ ON CONFLICT(id) DO UPDATE SET+ content_hash = excluded.content_hash,+ checkpoint_id = excluded.checkpoint_id,+ name = excluded.name,+ manifest = excluded.manifest,+ status = excluded.status,+ last_used_at = excluded.last_used_at`,+ );+ const imageDelete = env.OPENCOMPUTER_DB.prepare(+ `DELETE FROM images_index WHERE id = ?1`,+ );+ const imageBatches = fresh+ .filter((e) => e.type === "image_cache_ready" || e.type === "image_cache_deleted")+ .flatMap((e) => {+ const p = (e.payload ?? {}) as {+ image_id?: string;+ content_hash?: string;+ checkpoint_id?: string | null;+ name?: string | null;+ manifest?: string;+ status?: string;+ created_at?: number;+ last_used_at?: number;+ };+ if (!p.image_id) return [];+ if (e.type === "image_cache_deleted") {+ return [imageDelete.bind(p.image_id)];+ }+ const ts = Math.floor((Date.parse(e.timestamp) || Date.now()) / 1000);+ return [+ imageUpsert.bind(+ p.image_id,+ e.org_id ?? "",+ e.cell_id,+ p.content_hash ?? "",+ p.checkpoint_id ?? null,+ p.name ?? null,+ p.manifest ?? "{}",+ p.status ?? "ready",+ p.created_at ?? ts,+ p.last_used_at ?? ts,+ ),+ ];+ });+try {- await env.OPENCOMPUTER_DB.batch([...batches, ...capacityBatches, ...lifecycleBatches, ...checkpointBatches]);+ await env.OPENCOMPUTER_DB.batch([...batches, ...capacityBatches, ...lifecycleBatches, ...checkpointBatches, ...imageBatches]);} catch (err) {// Database errors are retryable — return 5xx so the CP forwarder// leaves the batch in the PEL.diff --git a/cloudflare-workers/events-ingest/wrangler.prod.toml b/cloudflare-workers/events-ingest/wrangler.prod.tomlnew file mode 100644index 00000000..a3abadb4--- /dev/null+++ b/cloudflare-workers/events-ingest/wrangler.prod.toml@@ -0,0 +1,39 @@+# events-ingest Worker — PROD on opencomputer.dev zone.+# Mirrors wrangler.toml (dev) but targets Mo's CF account.+# Deploy: `wrangler deploy -c wrangler.prod.toml`+#+# Route at events.opencomputer.dev (set up as a Workers Custom Domain after+# first deploy) or use the workers.dev URL until DNS is live. Prod CPs hit+# this directly via OPENSANDBOX_CF_EVENT_ENDPOINT.++name = "opencomputer-events-ingest-prod"+main = "src/index.ts"+compatibility_date = "2026-04-28"+compatibility_flags = ["nodejs_compat"]+account_id = "b8f23cb87a7a6c64040d3134643da448"++[[d1_databases]]+binding = "OPENCOMPUTER_DB"+database_name = "opencomputer-prod"+database_id = "8329e0f0-100d-445a-bf89-95c065f15dbb"++[[r2_buckets]]+binding = "EVENTS_ARCHIVE"+bucket_name = "events-archive-prod"++# CreditAccount DO is owned by api-edge prod; reference it here for /debit.+[[durable_objects.bindings]]+name = "CREDIT_ACCOUNT"+class_name = "CreditAccount"+script_name = "opencomputer-edge-prod"++# Secrets (set via `wrangler secret put --config wrangler.prod.toml`):+# EVENT_SECRET — fresh prod HMAC, shared with prod CPs + api-edge prod+# CF_ADMIN_SECRET — fresh prod HMAC, shared with api-edge prod + CPs++[vars]+WORKER_ENV = "prod"++# Ship Worker logs to opencomputer-log-tail-prod → Axiom dataset cf-prod.+[[tail_consumers]]+service = "opencomputer-log-tail-prod"diff --git a/cloudflare-workers/log-tail/wrangler.prod.toml b/cloudflare-workers/log-tail/wrangler.prod.tomlnew file mode 100644index 00000000..f89c09a0--- /dev/null+++ b/cloudflare-workers/log-tail/wrangler.prod.toml@@ -0,0 +1,16 @@+# log-tail Worker — PROD on Mo's CF account.+# Tail consumer for opencomputer-edge-prod + opencomputer-events-ingest-prod.+# Forwards console output + exceptions to Axiom dataset cf-prod.+# Deploy: `wrangler deploy -c wrangler.prod.toml`++name = "opencomputer-log-tail-prod"+main = "src/index.ts"+compatibility_date = "2024-12-01"+account_id = "b8f23cb87a7a6c64040d3134643da448"+workers_dev = false++# Secrets (set via `wrangler secret put --config wrangler.prod.toml`):+# AXIOM_TOKEN — xaat-... ingest token for the cf-prod dataset+[vars]+AXIOM_HOST = "https://api.axiom.co"+AXIOM_DATASET = "oc-platform-edge"diff --git a/cloudflare-workers/shared/credit_account.ts b/cloudflare-workers/shared/credit_account.tsindex cb04096b..bb9924ce 100644--- a/cloudflare-workers/shared/credit_account.ts+++ b/cloudflare-workers/shared/credit_account.ts@@ -125,10 +125,14 @@ export class CreditAccount {dispatchedHalt = true;} else {await this.persist(s);- // Best-effort: mirror to D1 every N debits to keep dashboard reads- // close to real-time without paying the write on every tick. waitUntil- // keeps it async so it doesn't block the /debit ack to events-ingest.- this.state.waitUntil(this.mirrorBalanceToD1(orgID, s.balance_cents));+ // Mirror balance to D1 synchronously on every debit. Was async via+ // waitUntil — that left a window where two close debits could land+ // their mirror writes out of order, briefly showing a higher D1+ // balance than the DO truth. The synchronous write costs ~5-20ms per+ // debit but eliminates the desync. Dashboard /billing still cross-+ // reads the DO snapshot as the authoritative source; the D1 column+ // is the fast-path cache the create-flow halt check reads.+ await this.mirrorBalanceToD1(orgID, s.balance_cents);}return json({diff --git a/cmd/server/main.go b/cmd/server/main.goindex 2abb4761..6ae1fcbd 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -479,6 +479,13 @@ func main() {MaxWorkers: cfg.MaxWorkersPerRegion,IdleReserve: cfg.IdleReserveWorkers,MachineSizes: machineSizes,+ // For "migrated" event emit after scaler-driven migrations+ // (rolling replace, evacuation) — keeps D1 sandboxes_index+ // worker_id in sync with cell-PG truth. Without this, the+ // dashboard's "which worker is my sandbox on" view goes stale+ // every time the autoscaler shuffles things around.+ RedisClient: redisRegistry.RedisClient(),+ CellID: cfg.CellID,})defer scaler.Stop()diff --git a/internal/api/checkpoint_events.go b/internal/api/checkpoint_events.goindex 5d7aed96..eb0789f3 100644--- a/internal/api/checkpoint_events.go+++ b/internal/api/checkpoint_events.go@@ -8,6 +8,8 @@ import ("github.com/google/uuid""github.com/redis/go-redis/v9"++ "github.com/opensandbox/opensandbox/internal/db")// publishCheckpointEvent XADDs a checkpoint lifecycle event to the cell's@@ -72,3 +74,121 @@ func (s *Server) publishCheckpointEvent(log.Printf("publishCheckpointEvent: XADD %s: %v", eventType, err)}}++// publishSandboxLifecycleEvent emits a sandbox lifecycle event ("stopped",+// "hibernated", etc) from the CP when the canonical emit path (worker's+// per-sandbox SQLite via sdb.LogEvent) didn't run — typically because the+// gRPC call to the worker failed and the worker never reached the LogEvent+// line. Without this fallback, cell PG can flip to status='stopped' while+// D1 sandboxes_index stays at 'running' indefinitely.+func (s *Server) publishSandboxLifecycleEvent(+ ctx context.Context,+ eventType string,+ sandboxID string,+ orgID uuid.UUID,+ workerID string,+ reason string,+) {+ if s.redisClient == nil || s.cellID == "" || sandboxID == "" {+ return+ }+ envelope := map[string]any{+ "id": uuid.NewString(),+ "type": eventType,+ "sandbox_id": sandboxID,+ "org_id": orgID.String(),+ "worker_id": workerID,+ "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("publishSandboxLifecycleEvent: marshal: %v", err)+ return+ }+ streamKey := "events:" + s.cellID+ xaddCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ if err := s.redisClient.XAdd(xaddCtx, &redis.XAddArgs{+ Stream: streamKey,+ MaxLen: 100000,+ Approx: true,+ Values: map[string]any{"event": string(body)},+ }).Err(); err != nil {+ log.Printf("publishSandboxLifecycleEvent: XADD %s: %v", eventType, err)+ }+}++// publishImageCacheReadyFrom packs the relevant fields from a db.ImageCache+// row and emits an image_cache_ready event. Sugar over publishImageCacheEvent+// so callers can just pass the row they already have in hand.+func (s *Server) publishImageCacheReadyFrom(ctx context.Context, ic *db.ImageCache) {+ if ic == nil {+ return+ }+ payload := map[string]any{+ "content_hash": ic.ContentHash,+ "manifest": string(ic.Manifest),+ "status": ic.Status,+ "created_at": ic.CreatedAt.Unix(),+ "last_used_at": ic.LastUsedAt.Unix(),+ }+ if ic.CheckpointID != nil {+ payload["checkpoint_id"] = ic.CheckpointID.String()+ }+ if ic.Name != nil {+ payload["name"] = *ic.Name+ }+ s.publishImageCacheEvent(ctx, "image_cache_ready", ic.ID, ic.OrgID, payload)+}++// publishImageCacheEvent mirrors publishCheckpointEvent for the image_cache+// table. The same event-→D1 sync pattern keeps the dashboard's cross-cell+// Images view in sync without proxying per-cell at request time.+//+// Event types:+// image_cache_ready — image is in ready state; UPSERT into D1 images_index+// image_cache_deleted — image dropped from cell PG; DELETE from D1+func (s *Server) publishImageCacheEvent(+ ctx context.Context,+ eventType string,+ imageID uuid.UUID,+ orgID uuid.UUID,+ payload map[string]any,+) {+ if s.redisClient == nil || s.cellID == "" {+ return+ }+ envelope := map[string]any{+ "id": uuid.NewString(),+ "type": eventType,+ "sandbox_id": "", // not a sandbox event+ "org_id": orgID.String(),+ "worker_id": "",+ "cell_id": s.cellID,+ "payload": map[string]any{},+ "timestamp": time.Now().UTC().Format(time.RFC3339Nano),+ }+ out := envelope["payload"].(map[string]any)+ out["image_id"] = imageID.String()+ for k, v := range payload {+ out[k] = v+ }+ body, err := json.Marshal(envelope)+ if err != nil {+ log.Printf("publishImageCacheEvent: marshal: %v", err)+ return+ }+ streamKey := "events:" + s.cellID+ xaddCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ if err := s.redisClient.XAdd(xaddCtx, &redis.XAddArgs{+ Stream: streamKey,+ MaxLen: 100000,+ Approx: true,+ Values: map[string]any{"event": string(body)},+ }).Err(); err != nil {+ log.Printf("publishImageCacheEvent: XADD %s: %v", eventType, err)+ }+}diff --git a/internal/api/image_builder.go b/internal/api/image_builder.goindex a07344db..04f7c81c 100644--- a/internal/api/image_builder.go+++ b/internal/api/image_builder.go@@ -226,6 +226,7 @@ func (s *Server) resolveImageManifest(ctx context.Context, orgID uuid.UUID, manilog.Printf("image-builder: cache hit for hash %s but checkpoint %s is invalid, rebuilding",contentHash[:12], cached.CheckpointID)_ = s.store.DeleteImageCache(ctx, orgID, cached.ID)+ s.publishImageCacheEvent(ctx, "image_cache_deleted", cached.ID, orgID, nil)} else {validHit := s.checkpointStore == nilif !validHit {@@ -334,6 +335,11 @@ func (s *Server) resolveImageManifest(ctx context.Context, orgID uuid.UUID, manibuild.checkpointID = checkpointIDif s.store != nil {_ = s.store.SetImageCacheReady(ctx, cacheID, checkpointID)+ // Sync to D1 images_index. Read back the now-ready row so the event+ // carries the same data the dashboard expects (manifest, timestamps).+ if ic, err := s.store.GetImageCacheByHash(ctx, orgID, contentHash); err == nil {+ s.publishImageCacheReadyFrom(ctx, ic)+ }}log.Printf("image-builder: built image hash=%s checkpoint=%s (%d steps)", contentHash[:12], checkpointID, len(manifest.Steps))diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex c953ee65..e167b9b5 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -820,6 +820,11 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)if err != nil {log.Printf("sandbox: worker %s unreachable for destroy: %v", session.WorkerID, err)+ // Worker never received the destroy call — its LogEvent("stopped") path+ // won't run, so D1 sandboxes_index would otherwise stay at "running"+ // while cell PG says "stopped". Emit a CP-side fallback to close the+ // drift. status is already marked stopped on cell PG above.+ s.publishSandboxLifecycleEvent(c.Request().Context(), "stopped", sandboxID, session.OrgID, session.WorkerID, "worker_unreachable")return c.NoContent(http.StatusNoContent)}@@ -828,6 +833,10 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {if _, err := client.DestroySandbox(grpcCtx, &pb.DestroySandboxRequest{SandboxId: sandboxID}); err != nil {log.Printf("sandbox: gRPC destroy failed for %s: %v", sandboxID, err)+ // Same drift-prevention as above: worker's emit path may not have run+ // (timeout, transient gRPC error, worker dying mid-destroy). Fallback+ // emit so D1 reflects the cell-PG truth.+ s.publishSandboxLifecycleEvent(c.Request().Context(), "stopped", sandboxID, session.OrgID, session.WorkerID, "grpc_destroy_failed")}_ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", nil)@@ -1111,6 +1120,14 @@ func (s *Server) migrateSandbox(c echo.Context) error {log.Printf("migrate %s: WARNING: CompleteMigration DB update failed: %v", id, err)}completeDBCancel()+ // Mirror to D1 sandboxes_index so the dashboard's cross-cell view and+ // the proxyToCellSDK routing reflect the new worker immediately. The+ // new worker's `created` event would eventually sync it, but emitting+ // here closes the window where stale routing would re-target the+ // vanished source worker. Reads org from the existing session.+ if session, err := s.store.GetSandboxSession(context.Background(), id); err == nil {+ s.publishSandboxLifecycleEvent(context.Background(), "migrated", id, session.OrgID, req.TargetWorker, "user_migrate")+ }}migrationDone = truediff --git a/internal/api/snapshots.go b/internal/api/snapshots.goindex f464b0df..0ccaacff 100644--- a/internal/api/snapshots.go+++ b/internal/api/snapshots.go@@ -92,6 +92,7 @@ func (s *Server) createSnapshotCore(ctx context.Context, orgID uuid.UUID, name sif createErr := s.store.CreateImageCache(ctx, ic); createErr != nil {return nil, fmt.Errorf("failed to save snapshot: %w", createErr)}+ s.publishImageCacheReadyFrom(ctx, ic)return ic, nil}@@ -114,6 +115,7 @@ func (s *Server) createSnapshotCore(ctx context.Context, orgID uuid.UUID, name s}return nil, fmt.Errorf("failed to save snapshot: %w", createErr)}+ s.publishImageCacheReadyFrom(ctx, ic)log.Printf("snapshot: created %q (checkpoint=%s)", name, checkpointID)return ic, nil@@ -231,9 +233,15 @@ func (s *Server) deleteSnapshot(c echo.Context) error {}name := c.Param("name")+ // Read the row first so we can publish a deletion event with the same id+ // the dashboard's images_index entry is keyed on.+ ic, _ := s.store.GetImageCacheByName(c.Request().Context(), orgID, name)if err := s.store.DeleteImageCacheByName(c.Request().Context(), orgID, name); err != nil {return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})}+ if ic != nil {+ s.publishImageCacheEvent(c.Request().Context(), "image_cache_deleted", ic.ID, orgID, nil)+ }return c.NoContent(http.StatusNoContent)}diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex ded3cf65..b25395c3 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -2,6 +2,7 @@ package controlplaneimport ("context"+ "encoding/json""errors""fmt""log"@@ -11,6 +12,9 @@ import ("sync/atomic""time"+ "github.com/google/uuid"+ "github.com/redis/go-redis/v9"+"github.com/opensandbox/opensandbox/internal/compute""github.com/opensandbox/opensandbox/internal/db"pb "github.com/opensandbox/opensandbox/proto/worker"@@ -82,6 +86,13 @@ type ScalerConfig struct {MaxWorkers int // maximum workers per region (0 = default 10). Hard cap to prevent runaway launches.IdleReserve int // target idle (0 sandbox) workers for burst absorption (0 = default 1). Separate from MinWorkers.+ // Event emit for D1 sandboxes_index sync. After a scaler-triggered+ // migration succeeds (rolling replace, evacuation), XADD a "migrated"+ // event so events-ingest updates D1's worker_id. Without these, D1+ // silently drifts from cell PG on every rolling replace.+ RedisClient *redis.Client+ CellID string+// MachineSizes is a ranked list of provider-specific machine sizes the// scaler tries in order on each scale-up. On a quota or capacity error// (compute.ErrQuotaExceeded), the scaler falls through to the next size.@@ -117,6 +128,9 @@ type Scaler struct {maxWorkers intidleReserve int+ rdb *redis.Client+ cellID string+mu sync.Mutex // protects stop/cancelcancel context.CancelFuncwg sync.WaitGroup@@ -168,6 +182,44 @@ func NewScaler(cfg ScalerConfig) *Scaler {maxWorkers: maxWorkers,idleReserve: idleReserve,machineSizes: cfg.MachineSizes,+ rdb: cfg.RedisClient,+ cellID: cfg.CellID,+ }+}++// 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.+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)}}@@ -1547,6 +1599,7 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker// Step 5: Complete migration — update DB status and worker_id atomically.// Use background context in case the drain context is close to expiry.+ var migratedOrgID uuid.UUIDif s.store != nil {dbCtx, dbCancel := context.WithTimeout(context.Background(), 10*time.Second)if err := s.store.CompleteMigration(dbCtx, sandboxID, targetWorkerID); err != nil {@@ -1558,9 +1611,16 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorkerif targetWorker != nil && targetWorker.GoldenVersion != "" {_ = s.store.SetSandboxGoldenVersion(dbCtx, sandboxID, targetWorker.GoldenVersion)}+ // Read org for the D1 sync event below.+ if sess, err := s.store.GetSandboxSession(dbCtx, sandboxID); err == nil && sess != nil {+ migratedOrgID = sess.OrgID+ }dbCancel()}migrationCompleted = true+ // Mirror the worker_id change to D1 sandboxes_index so the dashboard's+ // cross-cell view + proxyToCellSDK routing reflect the new home worker.+ s.publishMigrated(context.Background(), sandboxID, targetWorkerID, migratedOrgID, "scaler_migrate")elapsed := time.Since(t0).Milliseconds()log.Printf("scaler: migrate %s: complete in %dms (source=%s target=%s)", sandboxID, elapsed, sourceWorkerID, targetWorkerID)