Skip to content

An open-source, faster Devin alternative

TypeScript

feat(webhooks): emit the P3 producer events (ready/scaled/checkpoint/fork/preview)

Igor Zalutski05ba8f3044c2
diff --git a/docs/sandboxes/webhooks.mdx b/docs/sandboxes/webhooks.mdx
index a6746cd2..e9b4fbb4 100644
--- a/docs/sandboxes/webhooks.mdx
+++ b/docs/sandboxes/webhooks.mdx
@@ -30,20 +30,20 @@ The envelope is camelCase, with top-level routing fields, your sandbox [`metadat
## Events
-Subscribe to all events, or filter with `eventTypes` (exact like `sandbox.stopped`, or a prefix like `sandbox.*`). You can subscribe to a **Coming soon** type now; it simply won't deliver until that event ships.
-
-| Event | When | `event.data` | Status |
-| --- | --- | --- | --- |
-| `sandbox.created` | the sandbox resource is accepted | `template`, `cpuCount`, `memoryMB` | Live |
-| `sandbox.stopped` | the sandbox stopped | `reason`: `user_requested` \| `expired` \| `crash` | Live |
-| `sandbox.hibernated` | the sandbox was paused (disk persisted) | — | Live |
-| `sandbox.resumed` | a hibernated sandbox woke | — | Live |
-| `sandbox.migrated` | the sandbox moved to new infrastructure | — | Live |
-| `sandbox.ready` | the VM has booted and can run commands | — | Coming soon |
-| `sandbox.checkpoint.created` | a checkpoint was taken | `checkpointId` | Coming soon |
-| `sandbox.forked` | a sandbox was forked from a checkpoint | `parentId` | Coming soon |
-| `sandbox.scaled` | the sandbox's resources changed | `cpuCount`, `memoryMB` | Coming soon |
-| `sandbox.preview_url.changed` | a preview-URL port mapping changed | `port`, `url` | Coming soon |
+Subscribe to all events, or filter with `eventTypes` (exact like `sandbox.stopped`, or a prefix like `sandbox.*`).
+
+| Event | When | `event.data` |
+| --- | --- | --- |
+| `sandbox.created` | the sandbox resource is accepted | `template`, `cpuCount`, `memoryMB` |
+| `sandbox.ready` | the VM has booted and can run commands | — |
+| `sandbox.hibernated` | the sandbox was paused (disk persisted) | — |
+| `sandbox.resumed` | a hibernated sandbox woke | — |
+| `sandbox.stopped` | the sandbox stopped | `reason`: `user_requested` \| `expired` \| `crash` |
+| `sandbox.migrated` | the sandbox moved to new infrastructure | — |
+| `sandbox.checkpoint.created` | a checkpoint was taken | `checkpointId` |
+| `sandbox.forked` | a sandbox was forked from a checkpoint | `parentId` |
+| `sandbox.scaled` | the sandbox's resources changed | `cpuCount`, `memoryMB` |
+| `sandbox.preview_url.changed` | a preview-URL port mapping changed | `port`, `url` |
## Destinations
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 037db525..24e713bb 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -258,6 +258,10 @@ func (s *Server) createSandbox(c echo.Context) error {
if len(cfg.Webhooks) > 0 {
sb.Webhooks = s.registerInlineWebhooks(ctx, orgID, sb.ID, cfg.Webhooks)
}
+ // Combined-mode create writes the session directly as 'running' (no
+ // pending→running promotion), so emit sandbox.ready here; the remote
+ // path emits it in-tx on the promotion.
+ s.recordLifecycle(ctx, orgID, sb.ID, types.WebhookEventReady, nil)
}
// Preview-URL auth: same flow as createSandboxRemote — validate the
@@ -1488,6 +1492,9 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32
// Only emit scale events for non-default sizes (4096MB is the creation default)
if requestedMemMB != 4096 || migrated {
s.emitEvent("scale", sandboxID, workerID, fmt.Sprintf("scaled to %dMB (migrated=%v)", requestedMemMB, migrated))
+ s.recordLifecycle(ctx, session.OrgID, sandboxID, types.WebhookEventScaled, map[string]any{
+ "cpuCount": requestedCPUs, "memoryMB": requestedMemMB,
+ })
}
resp := map[string]any{
@@ -2209,6 +2216,9 @@ func (s *Server) createCheckpoint(c echo.Context) error {
// Pre-fix this was hardcoded to 0, leaving size_bytes meaningless.
_ = s.store.SetCheckpointReady(context.Background(), checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, grpcResp.SizeBytes)
log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, grpcResp.SizeBytes)
+ s.recordLifecycle(context.Background(), orgID, sandboxID, types.WebhookEventCheckpointCreated, map[string]any{
+ "checkpointId": checkpointID.String(),
+ })
golden := ""
if session.GoldenVersion != nil {
golden = *session.GoldenVersion
@@ -2768,6 +2778,12 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st
}
// Track checkpoint lineage for patch system
_ = s.store.SetSandboxCheckpointID(ctx, sandboxID, checkpointID)
+ // Emit sandbox.forked on the child, carrying the parent sandbox id (the
+ // sandbox the checkpoint was taken from). The child also gets created
+ // (worker) + ready (the running promotion above).
+ s.recordLifecycle(ctx, orgID, sandboxID, types.WebhookEventForked, map[string]any{
+ "parentId": cp.SandboxID,
+ })
}
s.applyPendingPatches(sandboxID, workerID)
@@ -3281,6 +3297,9 @@ func (s *Server) createPreviewURL(c echo.Context) error {
})
}
+ s.recordLifecycle(ctx, orgID, sandboxID, types.WebhookEventPreviewURLChanged, map[string]any{
+ "port": req.Port, "url": "https://" + hostname,
+ })
return c.JSON(http.StatusCreated, previewURLToMap(*previewURL, customDomain))
}
diff --git a/internal/api/webhooks.go b/internal/api/webhooks.go
index b3e62bbe..4337f6cc 100644
--- a/internal/api/webhooks.go
+++ b/internal/api/webhooks.go
@@ -116,6 +116,29 @@ func webhookRequestHash(req types.CreateWebhookRequest) string {
return hex.EncodeToString(h.Sum(nil))
}
+// recordLifecycle records a CP-origin lifecycle event for a sandbox in its own
+// transaction. Best-effort: a failure is logged, never fails the request. Used
+// for the events the control plane emits directly (ready on the local create
+// path, checkpoint.created, forked, scaled, preview_url.changed).
+func (s *Server) recordLifecycle(ctx context.Context, orgID uuid.UUID, sandboxID, evType string, data map[string]any) {
+ if s.store == nil || orgID == uuid.Nil || sandboxID == "" {
+ return
+ }
+ var raw json.RawMessage
+ if len(data) > 0 {
+ raw, _ = json.Marshal(data)
+ }
+ if err := s.store.RecordLifecycleEvent(ctx, db.LifecycleEvent{
+ ID: fmt.Sprintf("%s:%s:%d", sandboxID, evType, time.Now().UnixNano()),
+ OrgID: orgID,
+ SandboxID: sandboxID,
+ Type: evType,
+ Data: raw,
+ }); err != nil {
+ log.Printf("recordLifecycle %s for %s: %v", evType, sandboxID, err)
+ }
+}
+
// registerInlineWebhooks registers webhooks supplied inline on sandbox create,
// each pinned to the sandbox with no watermark floor (created_after_event_seq=0
// → full lifecycle from `created`). Best-effort: a bad URL or register error is
diff --git a/internal/db/store.go b/internal/db/store.go
index 6083532e..cf888ff2 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -849,20 +849,23 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statu
// usage reporter can never observe a stopped/hibernated/failed session with
// an ended_at IS NULL scale_event (which would keep billing the window).
var orgID uuid.UUID
- if tag.RowsAffected() > 0 && (terminal || status == "hibernated") {
+ affected := tag.RowsAffected() > 0
+ if affected && (terminal || status == "hibernated") {
if _, err := tx.Exec(ctx,
`UPDATE sandbox_scale_events SET ended_at = now()
WHERE sandbox_id = $1 AND ended_at IS NULL`, sandboxID); err != nil {
return fmt.Errorf("failed to close scale events: %w", err)
}
- // Capture org for the lifecycle publish below (same tx; cheap).
+ }
+
+ // Record the canonical lifecycle event in THIS tx (CP-origin → durable from
+ // the state change) so sandbox webhooks fire. `running` here is the
+ // pending→running boot promotion = sandbox.ready (wake takes a different code
+ // path, so this never doubles with the worker-origin `resumed`). Other
+ // worker-origin events (created/resumed/migrated) arrive via the ingress.
+ if affected && (terminal || status == "hibernated" || status == "running") {
_ = tx.QueryRow(ctx,
`SELECT org_id FROM sandbox_sessions WHERE sandbox_id = $1`, sandboxID).Scan(&orgID)
-
- // Record the canonical lifecycle event in THIS tx (CP-origin → durable
- // from the state change) so sandbox webhooks fire. Only the public
- // moments owned by the control plane; worker-origin events
- // (created/ready/migrated) arrive via the Redis stream ingress.
if orgID != uuid.Nil {
var evType string
var data json.RawMessage
@@ -875,6 +878,8 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statu
data = json.RawMessage(`{"reason":"crash"}`)
case "hibernated":
evType = "sandbox.hibernated"
+ case "running":
+ evType = "sandbox.ready"
}
if evType != "" {
if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{