An open-source, faster Devin alternative
TypeScript
web: remove sandbox UI (097 step 7.2)
Mohamed Habib via Computer9317e96119ff
diff --git a/web/package-lock.json b/web/package-lock.jsonindex 7e0e0599..c10b55e5 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -13,9 +13,6 @@"@fontsource-variable/inter": "^5.2.8","@posthog/react": "^1.10.3","@tanstack/react-query": "^5.101.1",- "@xterm/addon-fit": "^0.11.0",- "@xterm/addon-web-links": "^0.12.0",- "@xterm/xterm": "^6.0.0","ai": "^7.0.47","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -4103,27 +4100,6 @@"integrity": "sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ==","license": "Apache-2.0"},- "node_modules/@xterm/addon-fit": {- "version": "0.11.0",- "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz",- "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",- "license": "MIT"- },- "node_modules/@xterm/addon-web-links": {- "version": "0.12.0",- "resolved": "https://registry.npmjs.org/@xterm/addon-web-links/-/addon-web-links-0.12.0.tgz",- "integrity": "sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==",- "license": "MIT"- },- "node_modules/@xterm/xterm": {- "version": "6.0.0",- "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz",- "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==",- "license": "MIT",- "workspaces": [- "addons/*"- ]- },"node_modules/accepts": {"version": "2.0.0","resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",diff --git a/web/package.json b/web/package.jsonindex 339b88cb..1a90d675 100644--- a/web/package.json+++ b/web/package.json@@ -23,9 +23,6 @@"@fontsource-variable/inter": "^5.2.8","@posthog/react": "^1.10.3","@tanstack/react-query": "^5.101.1",- "@xterm/addon-fit": "^0.11.0",- "@xterm/addon-web-links": "^0.12.0",- "@xterm/xterm": "^6.0.0","ai": "^7.0.47","class-variance-authority": "^0.7.1","clsx": "^2.1.1",diff --git a/web/src/App.tsx b/web/src/App.tsxindex bf1031b1..2bc702fe 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -7,18 +7,12 @@ import PublicTemplateRoute from './components/PublicTemplateRoute'import { managedAgentsExperimentEnabled } from './managed-agents/feature'import { templateDeployPathFromSearch } from './managed-agents/templates'-// Route pages are code-split so the initial bundle stays small; the heaviest-// deps (xterm, in Terminal/LogsPanel) only load on SandboxDetail when opened.+// Route pages are code-split so the initial bundle stays small.const Dashboard = lazy(() => import('./pages/Dashboard'))const Browsers = lazy(() => import('./pages/Browsers'))-const Sandboxes = lazy(() => import('./pages/Sandboxes'))const APIKeys = lazy(() => import('./pages/APIKeys'))-const Checkpoints = lazy(() => import('./pages/Checkpoints'))-const Templates = lazy(() => import('./pages/Templates'))const Settings = lazy(() => import('./pages/Settings'))const Billing = lazy(() => import('./pages/Billing'))-const SandboxDetail = lazy(() => import('./pages/SandboxDetail'))-const SandboxWebhooks = lazy(() => import('./pages/SandboxWebhooks'))const DeferredAction = lazy(() => import('./pages/DeferredAction'))const ManagedAgentsHome = lazy(() => import('./managed-agents/Home'))const ManagedComputer = lazy(() => import('./managed-agents/Computer'))@@ -140,12 +134,6 @@ export default function App() {element={<ManagedAgentDetail />}/><Route path="browsers" element={<Browsers />} />- {/* Sandbox plane */}- <Route path="sandboxes" element={<Sandboxes />} />- <Route path="sandboxes/:sandboxId" element={<SandboxDetail />} />- <Route path="checkpoints" element={<Checkpoints />} />- <Route path="templates" element={<Templates />} />- <Route path="sandbox-webhooks" element={<SandboxWebhooks />} /><Route path="api-keys" element={<APIKeys />} /><Route path="billing" element={<Billing />} /><Route path="settings" element={<Settings />} />diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 70a98d42..8c9c7f21 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -6,17 +6,10 @@ import { ApiError } from './errors'export { ApiError } from './errors'// Re-export the inferred response types (schemas are the single source of-// truth) so existing `import { type Sandbox } from '@/api/client'` keeps working.+// truth) so existing `import { type APIKey } from '@/api/client'` keeps working.export type {OrgInfo,MeResponse,- Sandbox,- PreviewURL,- SandboxDetail,- SandboxStats,- CheckpointItem,- CheckpointsResponse,- ImageCacheItem,Org,APIKey,OrgMember,@@ -28,12 +21,8 @@ export type {AgentSessionUsage,AgentSessionUsageRow,StripeInvoice,- SandboxUsageRow,- SandboxUsage,BrowserSession,BrowserProfile,- SandboxWebhook,- SandboxWebhookDelivery,} from './schemas'const API_BASE = '/api/dashboard'@@ -197,42 +186,6 @@ export async function refreshSession(): Promise<void> {// API functionsexport const getMe = () => apiFetch('/me', {}, S.MeResponseSchema)-export const getSandboxes = (status?: string) =>- apiFetch(- `/sessions${status ? `?status=${status}` : ''}`,- {},- S.SandboxListSchema,- )--// Create a sandbox from the dashboard. Proxied by the edge to the org's home-// cell (POST /api/dashboard/sandboxes → cell /internal/sandboxes/create with a-// cap-token), so the box is owned by + billed to the logged-in org. Returns the-// new sandbox id so the caller can navigate straight into its live terminal.-export const createSandbox = (body: {- memoryMB?: number- cpuCount?: number- networkEnabled?: boolean- image?: string-}) =>- apiFetch<{ sandboxID: string; status?: string }>('/sandboxes', {- method: 'POST',- body: JSON.stringify(body),- })--// Expose a port on a running sandbox → a public preview URL (proxied edge→cell-// to the cap-token-authed /api/sandboxes/:id/preview). Returns the registered-// row incl. hostname; the sandbox detail page renders it in Preview URLs.-export const createPreviewUrl = (sandboxId: string, port: number) =>- apiFetch<{ id: string; sandboxId: string; hostname: string; port: number }>(- `/sandboxes/${sandboxId}/preview`,- { method: 'POST', body: JSON.stringify({ port }) },- )--export const deletePreviewUrl = (sandboxId: string, port: number) =>- apiFetch<void>(`/sandboxes/${sandboxId}/preview/${port}`, {- method: 'DELETE',- })-export const getAPIKeys = () =>apiFetch('/api-keys', {}, z.array(S.APIKeySchema))@@ -253,90 +206,6 @@ export const renameAPIKey = (keyId: string, name: string) =>export const deleteAPIKey = (keyId: string) =>apiFetch<void>(`/api-keys/${keyId}`, { method: 'DELETE' })-export const getCheckpoints = (page = 1, perPage = 20) =>- apiFetch(- `/checkpoints?page=${page}&per_page=${perPage}`,- {},- S.CheckpointsResponseSchema,- )--export const deleteCheckpointDashboard = (id: string) =>- apiFetch<void>(`/checkpoints/${id}`, { method: 'DELETE' })--export const getImages = (all = false) =>- apiFetch(- `/images${all ? '?all=true' : ''}`,- {},- z.array(S.ImageCacheItemSchema),- )--export const deleteImage = (id: string) =>- apiFetch<void>(`/images/${id}`, { method: 'DELETE' })--export const deleteSnapshot = (name: string) =>- apiFetch<void>(`/snapshots/${encodeURIComponent(name)}`, { method: 'DELETE' })--export const getSandboxDetail = (sandboxId: string) =>- apiFetch(`/sessions/${sandboxId}`, {}, S.SandboxDetailSchema)--export const getSandboxStats = (sandboxId: string) =>- apiFetch(`/sessions/${sandboxId}/stats`, {}, S.SandboxStatsSchema)--export const deleteSandbox = (sandboxId: string) =>- apiFetch<void>(`/sessions/${sandboxId}`, { method: 'DELETE' })--// Soft restart: guest kernel reboots, QEMU process + workspace stay.-export const rebootSandbox = (sandboxId: string) =>- apiFetch<void>(`/sessions/${sandboxId}/reboot`, { method: 'POST' })--// Hard restart: QEMU process recreated, workspace data preserved.-export const powerCycleSandbox = (sandboxId: string) =>- apiFetch<void>(`/sessions/${sandboxId}/power-cycle`, { method: 'POST' })--// Sandbox session logs: SSE stream of /var/log + exec stdout/stderr.-// The server proxies queries through to Axiom; the read token never-// reaches the browser. The returned EventSource emits one `message`-// event per log line (event.data = JSON-stringified LogEvent).-export interface LogEvent {- _time: string- source: 'var_log' | 'exec_stdout' | 'exec_stderr' | 'agent'- line: string- sandbox_id?: string- path?: string- exec_id?: string- command?: string- argv?: string[]- exit_code?: number- // Client-assigned monotonic ingest order. Not from the API — set on parse so- // the live list has a stable React key under filtering + cap trimming.- _seq?: number-}--export interface LogStreamOptions {- tail?: boolean // default true; if false, returns historical batch then closes- q?: string // free-text search (server applies "line contains")- source?: string // comma-separated subset of source values- since?: string // RFC3339; default = sandbox.startedAt- limit?: number // historical batch cap; default 1000, max 10000-}--export function streamSandboxLogs(- sandboxId: string,- opts: LogStreamOptions = {},-): EventSource {- const url = new URL(- `${API_BASE}/sessions/${encodeURIComponent(sandboxId)}/logs`,- window.location.origin,- )- if (opts.tail !== undefined) url.searchParams.set('tail', String(opts.tail))- if (opts.q) url.searchParams.set('q', opts.q)- if (opts.source) url.searchParams.set('source', opts.source)- if (opts.since) url.searchParams.set('since', opts.since)- if (opts.limit !== undefined)- url.searchParams.set('limit', String(opts.limit))- return new EventSource(url.toString(), { withCredentials: true })-}-export const getOrg = () => apiFetch('/org', {}, S.OrgSchema)export type OrgUpdate = {@@ -491,10 +360,6 @@ export const setAutumnAutoTopup = (cfg: {body: JSON.stringify(cfg),})-// Per-sandbox usage breakdown (compute cost over a recent window)-export const getSandboxUsage = (days = 30) =>- apiFetch(`/usage/sandboxes?days=${days}`, {}, S.SandboxUsageSchema)-export const getBrowsers = (params: { status?: string; limit?: number } = {},) => {@@ -522,45 +387,3 @@ export const getBrowserProfiles = () =>apiFetch('/browser-profiles', {}, S.BrowserProfileListSchema).then((r) => r.profiles,)--// ── Sandbox lifecycle webhooks (org-scoped, Svix-backed at the edge) ─────────-// Reached via /api/dashboard/webhooks* (cookie auth → org), mirroring the public-// /api/webhooks API.-export const getSandboxWebhooks = () =>- apiFetch('/webhooks', {}, S.SandboxWebhookListSchema).then((r) => r.data)--// No BYO secret: Svix generates the signing secret (a user-typed value isn't-// valid Svix whsec_ base64). Reveal it afterward via getSandboxWebhookSecret.-export const createSandboxWebhook = (body: {- url: string- eventTypes?: string[]- name?: string-}) =>- apiFetch(- '/webhooks',- { method: 'POST', body: JSON.stringify(body) },- S.SandboxWebhookSchema,- )--export const deleteSandboxWebhook = (id: string) =>- apiFetch<void>(`/webhooks/${id}`, { method: 'DELETE' })--export const testSandboxWebhook = (id: string) =>- apiFetch<void>(`/webhooks/${id}/test`, { method: 'POST' })--export const getSandboxWebhookDeliveries = (id: string) =>- apiFetch(- `/webhooks/${id}/deliveries`,- {},- S.SandboxWebhookDeliveryListSchema,- ).then((r) => r.data)--export const getSandboxWebhookSecret = (id: string) =>- apiFetch(`/webhooks/${id}/secret`, {}, z.object({ secret: z.string() })).then(- (r) => r.secret,- )--export const redeliverSandboxWebhook = (id: string, deliveryId: string) =>- apiFetch<void>(`/webhooks/${id}/deliveries/${deliveryId}/redeliver`, {- method: 'POST',- })diff --git a/web/src/api/mock.ts b/web/src/api/mock.tsindex 68079647..ba3a6846 100644--- a/web/src/api/mock.ts+++ b/web/src/api/mock.ts@@ -29,83 +29,6 @@ const me = {],}-const sandboxes = [- {- id: 's1',- sandboxId: 'sbx_a1b2c3d4e5',- orgId: 'org_digger',- template: 'python-3.12',- region: 'us-east-1',- workerId: 'w1',- status: 'running',- startedAt: at(0, 3),- },- {- id: 's2',- sandboxId: 'sbx_f6g7h8i9j0',- orgId: 'org_digger',- template: 'base',- region: 'us-east-1',- workerId: 'w1',- status: 'running',- startedAt: at(0, 6),- },- {- id: 's3',- sandboxId: 'sbx_k1l2m3n4o5',- orgId: 'org_digger',- template: 'node-20',- region: 'eu-west-1',- workerId: 'w2',- status: 'hibernated',- startedAt: at(1, 2),- },- {- id: 's4',- sandboxId: 'sbx_p6q7r8s9t0',- orgId: 'org_digger',- template: 'base',- region: 'us-east-1',- workerId: 'w1',- status: 'stopped',- startedAt: at(2, 5),- stoppedAt: at(2, 1),- },- {- id: 's5',- sandboxId: 'sbx_u1v2w3x4y5',- orgId: 'org_digger',- template: 'python-3.12',- region: 'us-east-1',- workerId: 'w2',- status: 'error',- startedAt: at(3, 4),- errorMsg: 'sandbox boot timed out after 120s',- },- {- id: 's6',- sandboxId: 'sbx_z6a7b8c9d0',- orgId: 'org_digger',- template: 'rust-1.80',- region: 'eu-west-1',- workerId: 'w2',- status: 'stopped',- startedAt: at(5, 8),- stoppedAt: at(5, 2),- },- {- id: 's7',- sandboxId: 'sbx_e1f2g3h4i5',- orgId: 'org_digger',- template: 'base',- region: 'us-east-1',- workerId: 'w1',- status: 'stopped',- startedAt: at(6, 3),- stoppedAt: at(6, 1),- },-]-const browserSessions = [{id: 'br_linkedin_live',@@ -191,121 +114,6 @@ const browserProfiles = [},]-const images = [- {- id: 'img1',- orgId: 'org_digger',- contentHash: 'sha256:aa11bb22',- checkpointId: 'ckpt_aa11bb22cc33',- name: 'ml-base',- manifest: {- steps: [- { type: 'apt_install', args: { packages: ['ffmpeg', 'git'] } },- {- type: 'pip_install',- args: { packages: ['torch', 'numpy', 'pandas'] },- },- ],- },- status: 'ready',- lastUsedAt: at(0, 5),- createdAt: at(12),- },- {- id: 'img2',- orgId: 'org_digger',- contentHash: 'sha256:cc33dd44',- checkpointId: 'ckpt_dd44ee55ff66',- name: 'node-web',- manifest: {- steps: [- { type: 'run', args: { commands: ['npm i -g pnpm'] } },- { type: 'env', args: { vars: { NODE_ENV: 'production' } } },- ],- },- status: 'building',- lastUsedAt: at(1),- createdAt: at(3),- },- {- id: 'img3',- orgId: 'org_digger',- contentHash: 'sha256:ee55ff66',- name: '',- manifest: { steps: [] },- status: 'ready',- lastUsedAt: at(4),- createdAt: at(20),- },- {- id: 'img4',- orgId: 'org_digger',- contentHash: 'sha256:gg77hh88',- name: 'broken-img',- manifest: {- steps: [{ type: 'apt_install', args: { packages: ['nonexistent-pkg'] } }],- },- status: 'failed',- lastUsedAt: at(8),- createdAt: at(8),- },-]--const checkpoints = [- {- id: 'cp1',- sandboxId: 'sbx_a1b2c3d4e5',- orgId: 'org_digger',- name: 'after-deps-install',- status: 'ready',- kind: 'disk_only',- promotionStatus: 'ready',- sizeBytes: 1_240_000_000,- activeForks: 3,- totalForks: 18,- createdAt: at(0, 4),- },- {- id: 'cp2',- sandboxId: 'sbx_f6g7h8i9j0',- orgId: 'org_digger',- name: 'clean-base',- status: 'ready',- kind: 'full',- sizeBytes: 2_900_000_000,- activeForks: 0,- totalForks: 2,- createdAt: at(1, 6),- },- {- id: 'cp3',- sandboxId: 'sbx_k1l2m3n4o5',- orgId: 'org_digger',- name: 'web-build',- status: 'processing',- kind: 'disk_only',- promotionStatus: 'processing',- sizeBytes: 800_000_000,- activeForks: 0,- totalForks: 0,- createdAt: at(0, 1),- },- {- id: 'cp4',- sandboxId: 'sbx_p6q7r8s9t0',- orgId: 'org_digger',- name: 'snapshot-failed',- status: 'failed',- kind: 'disk_only',- sizeBytes: 0,- activeForks: 0,- totalForks: 0,- createdAt: at(2, 2),- errorMsg: 'archive upload to object store failed: connection reset by peer',- failedAt: at(2, 1),- },-]-const apiKeys = [{id: 'k1',@@ -426,72 +234,6 @@ const billing = {hasPaymentMethod: false,}-const sandboxUsage = {- windowDays: 30,- totalCents: 156,- sandboxes: [- {- sandboxId: 'sbx_a1b2c3d4e5',- status: 'running',- seconds: 12_600,- costCents: 84,- },- {- sandboxId: 'sbx_f6g7h8i9j0',- status: 'stopped',- seconds: 3_600,- costCents: 24,- },- {- sandboxId: 'sbx_k1l2m3n4o5',- status: 'hibernated',- seconds: 7_200,- costCents: 48,- },- ],-}--const sessionDetail = {- id: 's1',- sandboxId: 'sbx_a1b2c3d4e5',- template: 'python-3.12',- status: 'running',- startedAt: at(0, 3),- config: { timeout: 3600, cpuCount: 2, memoryMB: 2048, networkEnabled: true },- previewUrls: [- {- id: 'pu1',- sandboxId: 'sbx_a1b2c3d4e5',- orgId: 'org_digger',- hostname: 'sbx-a1b2c3d4e5-3000.preview.opencomputer.dev',- customHostname: 'sbx-a1b2c3d4e5-3000.acme.dev',- port: 3000,- sslStatus: 'active',- authConfig: {},- createdAt: at(0, 2),- },- {- id: 'pu2',- sandboxId: 'sbx_a1b2c3d4e5',- orgId: 'org_digger',- hostname: 'sbx-a1b2c3d4e5-8080.preview.opencomputer.dev',- port: 8080,- sslStatus: 'active',- authConfig: {},- createdAt: at(0, 2),- },- ],-}--const sandboxStats = {- cpuPercent: 12.4,- memUsage: 734_003_200,- memLimit: 2_147_483_648,- pids: 37,- netOutput: 4_180_000,- netInput: 12_500_000,-}-const org = {id: 'org_digger',name: 'Digger',@@ -540,48 +282,6 @@ const orgInvitations = [},]-const sandboxWebhooks = [- {- id: 'whk_1',- url: 'https://acme.dev/hooks/sandbox',- eventTypes: ['sandbox.ready', 'sandbox.stopped'],- sandboxId: null,- name: 'Prod ingest',- enabled: true,- hasSecret: true,- createdAt: at(3),- updatedAt: at(0, 4),- },- {- id: 'whk_2',- url: 'https://hooks.internal.acme.dev/all',- eventTypes: [],- sandboxId: null,- name: '',- enabled: true,- hasSecret: true,- createdAt: at(8),- updatedAt: at(8),- },-]--const sandboxWebhookDeliveries = [- {- id: 'msg_1',- attemptId: 'att_1',- status: 'success',- responseStatusCode: 200,- timestamp: at(0, 1),- },- {- id: 'msg_2',- attemptId: 'att_2',- status: 'failed',- responseStatusCode: 500,- timestamp: at(0, 2),- },-]-type Handler = () => unknown// A handler may return NOT_FOUND to mimic a 404 (mockFetch throws, like a real@@ -1200,35 +900,17 @@ const ROUTES: Array<[RegExp, Handler]> = [turns: [],}),],- [/^\/sessions\/[^/]+\/stats$/, () => sandboxStats],- [/^\/sessions\/[^/]+$/, () => sessionDetail],- [/^\/sessions(\?.*)?$/, () => sandboxes],[/^\/browsers\/[^/]+$/, () => browserSessions[0]],[/^\/browsers(\?.*)?$/, () => ({ browsers: browserSessions })],[/^\/browser-profiles$/, () => ({ profiles: browserProfiles })],- [/^\/images(\?.*)?$/, () => images],- [- /^\/checkpoints(\?.*)?$/,- () => ({ checkpoints, total: checkpoints.length, page: 1, perPage: 20 }),- ],[/^\/api-keys$/, () => apiKeys],[/^\/billing\/autumn$/, () => autumnMock()],[/^\/billing\/invoices/, () => ({ invoices: [] })],[/^\/billing$/, () => billing],- [/^\/usage\/sandboxes/, () => sandboxUsage],[/^\/org\/members$/, () => orgMembers],[/^\/org\/invitations$/, () => orgInvitations],[/^\/org\/custom-domain$/, () => ({})],[/^\/org$/, () => org],- [- /^\/webhooks\/[^/]+\/deliveries$/,- () => ({ data: sandboxWebhookDeliveries }),- ],- [- /^\/webhooks\/[^/]+\/secret$/,- () => ({ secret: 'whsec_mockSigningSecret123' }),- ],- [/^\/webhooks$/, () => ({ data: sandboxWebhooks })],]// Mutations the preview needs to echo something parseable (e.g. the Slackdiff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex a8a461b9..7dffe0ae 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -5,8 +5,6 @@ import { z } from 'zod'// Status / kind / state fields are kept as z.string() (not z.enum) so a new// server-side value never fails validation — the UI compares them as strings.-const record = z.record(z.string(), z.unknown())-export const OrgInfoSchema = z.object({id: z.string(),name: z.string(),@@ -37,105 +35,6 @@ export const MeResponseSchema = z.object({.optional(),})-export const SandboxSchema = z.object({- id: z.string(),- sandboxId: z.string(),- orgId: z.string(),- template: z.string(),- region: z.string(),- workerId: z.string(),- status: z.string(),- startedAt: z.string(),- stoppedAt: z.string().optional(),- errorMsg: z.string().optional(),-})-export const SandboxListSchema = z.array(SandboxSchema)--export const PreviewURLSchema = z.object({- id: z.string(),- sandboxId: z.string(),- orgId: z.string(),- hostname: z.string(),- customHostname: z.string().optional(),- port: z.number(),- cfHostnameId: z.string().optional(),- sslStatus: z.string(),- authConfig: record,- createdAt: z.string(),-})--export const SandboxDetailSchema = z.object({- id: z.string(),- sandboxId: z.string(),- template: z.string(),- status: z.string(),- startedAt: z.string(),- stoppedAt: z.string().optional(),- errorMsg: z.string().optional(),- config: z- .object({- timeout: z.number().optional(),- cpuCount: z.number().optional(),- memoryMB: z.number().optional(),- networkEnabled: z.boolean().optional(),- envs: z.record(z.string(), z.string()).optional(),- })- .optional(),- checkpoint: z- .object({- checkpointKey: z.string(),- sizeBytes: z.number(),- hibernatedAt: z.string(),- })- .optional(),- previewUrls: z.array(PreviewURLSchema).optional(),-})--export const SandboxStatsSchema = z.object({- cpuPercent: z.number(),- memUsage: z.number(),- memLimit: z.number(),- netInput: z.number(),- netOutput: z.number(),- pids: z.number(),-})--export const CheckpointItemSchema = z.object({- id: z.string(),- sandboxId: z.string(),- orgId: z.string(),- name: z.string(),- status: z.string(),- kind: z.string().optional(),- promotionStatus: z.string().optional(),- promotedCheckpointId: z.string().optional(),- sizeBytes: z.number(),- activeForks: z.number(),- totalForks: z.number(),- createdAt: z.string(),- errorMsg: z.string().optional(),- failedAt: z.string().optional(),-})--export const CheckpointsResponseSchema = z.object({- checkpoints: z.array(CheckpointItemSchema),- total: z.number(),- page: z.number(),- perPage: z.number(),-})--export const ImageCacheItemSchema = z.object({- id: z.string(),- orgId: z.string(),- contentHash: z.string(),- checkpointId: z.string().optional(),- name: z.string().optional(),- manifest: record,- status: z.string(),- createdAt: z.string(),- lastUsedAt: z.string(),-})-export const OrgSchema = z.object({id: z.string(),name: z.string(),@@ -310,20 +209,6 @@ export const InvoicesResponseSchema = z.object({invoices: z.array(StripeInvoiceSchema),})-export const SandboxUsageRowSchema = z.object({- sandboxId: z.string(),- status: z.string(),- createdAt: z.number().optional(),- seconds: z.number(),- costCents: z.number(),-})--export const SandboxUsageSchema = z.object({- windowDays: z.number(),- totalCents: z.number(),- sandboxes: z.array(SandboxUsageRowSchema),-})-export const BrowserSessionSchema = z.object({id: z.string(),provider: z.string(),@@ -378,44 +263,8 @@ export const BrowserProfileListSchema = z.object({profiles: z.array(BrowserProfileSchema),})-// Sandbox lifecycle webhooks (Svix-backed, served by the edge /api/webhooks*).-// Org-scoped; shapes mirror the edge's toWire()/listDeliveries() camelCase.-export const SandboxWebhookSchema = z.object({- id: z.string(),- url: z.string(),- eventTypes: z.array(z.string()).nullish(), // empty/absent = all events- sandboxId: z.string().nullish(),- name: z.string().nullish(),- enabled: z.boolean(),- hasSecret: z.boolean().optional(),- createdAt: z.string().optional(),- updatedAt: z.string().optional(),- secret: z.string().optional(), // returned once on create / rotate-})-export const SandboxWebhookListSchema = z.object({- data: z.array(SandboxWebhookSchema),-})--export const SandboxWebhookDeliverySchema = z.object({- id: z.string(), // message id — the redeliver/get key- attemptId: z.string().optional(),- status: z.string().optional(), // success | pending | failed- responseStatusCode: z.number().nullish(),- timestamp: z.string().optional(),-})-export const SandboxWebhookDeliveryListSchema = z.object({- data: z.array(SandboxWebhookDeliverySchema),-})-export type OrgInfo = z.infer<typeof OrgInfoSchema>export type MeResponse = z.infer<typeof MeResponseSchema>-export type Sandbox = z.infer<typeof SandboxSchema>-export type PreviewURL = z.infer<typeof PreviewURLSchema>-export type SandboxDetail = z.infer<typeof SandboxDetailSchema>-export type SandboxStats = z.infer<typeof SandboxStatsSchema>-export type CheckpointItem = z.infer<typeof CheckpointItemSchema>-export type CheckpointsResponse = z.infer<typeof CheckpointsResponseSchema>-export type ImageCacheItem = z.infer<typeof ImageCacheItemSchema>export type Org = z.infer<typeof OrgSchema>export type APIKey = z.infer<typeof APIKeySchema>export type OrgMember = z.infer<typeof OrgMemberSchema>@@ -427,11 +276,5 @@ export type AutumnBilling = z.infer<typeof AutumnBillingSchema>export type AgentSessionUsageRow = z.infer<typeof AgentSessionUsageRowSchema>export type AgentSessionUsage = z.infer<typeof AgentSessionUsageSchema>export type StripeInvoice = z.infer<typeof StripeInvoiceSchema>-export type SandboxUsageRow = z.infer<typeof SandboxUsageRowSchema>-export type SandboxUsage = z.infer<typeof SandboxUsageSchema>export type BrowserSession = z.infer<typeof BrowserSessionSchema>export type BrowserProfile = z.infer<typeof BrowserProfileSchema>-export type SandboxWebhook = z.infer<typeof SandboxWebhookSchema>-export type SandboxWebhookDelivery = z.infer<- typeof SandboxWebhookDeliverySchema->diff --git a/web/src/components/LogsPanel.tsx b/web/src/components/LogsPanel.tsxdeleted file mode 100644index 87fb0b0f..00000000--- a/web/src/components/LogsPanel.tsx+++ /dev/null@@ -1,394 +0,0 @@-// LogsPanel — sandbox session logs view.-//-// Streams from /api/dashboard/sessions/:sandboxId/logs (SSE) and renders-// a live, source-color-coded timeline of events: lines from /var/log-// inside the sandbox, stdout/stderr of every platform-exec'd command,-// and synthetic "exit_code" markers showing how each command finished.-//-// Design contract:-//-// - Auto-scroll to bottom unless the user has scrolled up. Scrolling-// up "pins" the view; scrolling back to within ~40px of the bottom-// unpins it.-// - Hard cap on retained events (visibleCap below). Once exceeded,-// drop the oldest. Memory grows linearly with cap and is bounded.-// - The EventSource opens ONCE per sandbox; search + source filters are-// applied client-side against the in-memory buffer (no SSE re-open on-// filter change). Search is debounced only to avoid re-running the filter-// pipeline on every keystroke.-// - Pause toggle freezes display only — the EventSource keeps-// receiving so unpausing catches up; if buffer overflows, oldest-// pending events drop.-//-// PTY content is intentionally not part of this view (consent surface-// is different — see design doc).--import { useEffect, useMemo, useRef, useState } from 'react'-import { X } from 'lucide-react'-import { streamSandboxLogs, type LogEvent } from '@/api/client'--const visibleCap = 3000 // hard cap on retained events-const debounceMs = 200 // search-box debounce-const nearBottomPx = 40 // "auto-scroll if within this many px of bottom"--// One muted hue per source — distinct but toned down (not neon) so they sit-// quietly on the warm-dark surface; no overlap with the green/rose used for-// EOF rows.-const sources: { value: LogEvent['source']; label: string; color: string }[] = [- { value: 'exec_stdout', label: 'stdout', color: '#a8a299' }, // warm grey- { value: 'exec_stderr', label: 'stderr', color: '#dc8f88' }, // soft rose- { value: 'var_log', label: 'var/log', color: '#cfa45e' }, // soft amber- { value: 'agent', label: 'agent', color: '#7ba4cd' }, // soft blue-]--function useDebouncedValue<T>(value: T, delayMs: number): T {- const [debounced, setDebounced] = useState(value)- useEffect(() => {- const t = setTimeout(() => setDebounced(value), delayMs)- return () => clearTimeout(t)- }, [value, delayMs])- return debounced-}--interface LogsPanelProps {- sandboxId: string- onClose?: () => void-}--export default function LogsPanel({ sandboxId, onClose }: LogsPanelProps) {- const [query, setQuery] = useState('')- const [paused, setPaused] = useState(false)- // Subtractive filter: every source is shown by default. Clicking a- // chip *hides* that source; clicking again brings it back.- const [hiddenSources, setHiddenSources] = useState<Set<LogEvent['source']>>(- new Set(),- )- const [events, setEvents] = useState<LogEvent[]>([])- const [connState, setConnState] = useState<- 'connecting' | 'open' | 'error' | 'closed'- >('connecting')-- const debouncedQuery = useDebouncedValue(query, debounceMs)-- // Buffered events that arrived while paused; flushed on resume.- const pausedBufRef = useRef<LogEvent[]>([])- const seqRef = useRef(0)- const containerRef = useRef<HTMLDivElement | null>(null)- const stickToBottomRef = useRef(true)-- // Mirror `paused` into a ref so the SSE onmessage handler — created once per- // sandbox — reads the live value instead of its stale first-render closure.- const pausedRef = useRef(paused)- useEffect(() => {- pausedRef.current = paused- }, [paused])-- // Open the EventSource ONCE per sandbox. Search and source filters- // are applied client-side against the in-memory buffer — no SSE- // re-open on filter change, no flicker. The historical batch is- // bounded by visibleCap so memory stays cheap; if a user really- // wants to search beyond the current buffer they can adjust the- // since= URL param later.- useEffect(() => {- // Reset + (re)subscribe when the sandbox changes. The synchronous resets- // are intentional here (clear the stream before opening a new EventSource).- // eslint-disable-next-line react-hooks/set-state-in-effect- setEvents([])- pausedBufRef.current = []- stickToBottomRef.current = true- setConnState('connecting')-- const es = streamSandboxLogs(sandboxId, { tail: true })-- es.onopen = () => setConnState('open')- es.onerror = () => setConnState('error')- es.onmessage = (e) => {- let ev: LogEvent- try {- ev = JSON.parse(e.data as string) as LogEvent- } catch {- return- }- ev._seq = seqRef.current++- if (pausedRef.current) {- pausedBufRef.current.push(ev)- // Defensive cap on the paused buffer.- if (pausedBufRef.current.length > visibleCap) {- pausedBufRef.current = pausedBufRef.current.slice(-visibleCap)- }- return- }- setEvents((prev) => {- const next =- prev.length >= visibleCap- ? prev.slice(prev.length - visibleCap + 1)- : prev.slice()- next.push(ev)- return next- })- }-- return () => {- es.close()- setConnState('closed')- }- }, [sandboxId])-- // When unpausing, drain the paused buffer into events.- useEffect(() => {- if (!paused && pausedBufRef.current.length > 0) {- const buf = pausedBufRef.current- pausedBufRef.current = []- setEvents((prev) => {- const merged = prev.concat(buf)- return merged.length > visibleCap- ? merged.slice(merged.length - visibleCap)- : merged- })- }- }, [paused])-- // Auto-scroll to bottom when new events arrive — but only if the- // user is already near the bottom (i.e. they haven't scrolled up to- // read older lines).- useEffect(() => {- if (!stickToBottomRef.current) return- const el = containerRef.current- if (!el) return- el.scrollTop = el.scrollHeight- }, [events])-- const handleScroll = () => {- const el = containerRef.current- if (!el) return- const distFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight- stickToBottomRef.current = distFromBottom <= nearBottomPx- }-- const toggleSource = (src: LogEvent['source']) => {- setHiddenSources((prev) => {- const next = new Set(prev)- if (next.has(src)) next.delete(src)- else next.add(src)- return next- })- }-- // Client-side filter pipeline: source filter → text search → EOF- // dedup. Each command emits one EOF event per stream (stdout AND- // stderr) so without dedup the timeline shows "exited 0" twice for- // the same exec. We collapse them to one per exec_id.- const visible = useMemo(() => {- const lowerQuery = debouncedQuery.trim().toLowerCase()-- // Two-pass:- // 1. Dedupe EOFs by exec_id — agent emits one EOF on stdout AND- // one on stderr per exec; we keep the first (stdout, by emit- // order), drop the rest. Must happen BEFORE the source filter- // — otherwise hiding stdout lets the suppressed stderr-EOF- // through and the row "moves" from stdout-coloured to stderr.- // 2. Apply source + text filters to the deduped list.- const seenEofExecIDs = new Set<string>()- const deduped: LogEvent[] = []- for (const ev of events) {- const isEof = ev.line === '' && ev.exit_code !== undefined- if (isEof && ev.exec_id) {- if (seenEofExecIDs.has(ev.exec_id)) continue- seenEofExecIDs.add(ev.exec_id)- }- deduped.push(ev)- }-- return deduped.filter((ev) => {- if (hiddenSources.has(ev.source)) return false- if (lowerQuery && !searchCorpus(ev).includes(lowerQuery)) return false- return true- })- }, [events, hiddenSources, debouncedQuery])-- return (- <div className="bg-terminal border-code-border flex h-[480px] flex-col overflow-hidden rounded-lg border">- {/* Header */}- <div className="border-code-border flex flex-wrap items-center gap-3 border-b px-3 py-2.5">- <span className="text-code-muted text-xs font-medium tracking-wide uppercase">- Logs- </span>- <ConnectionDot state={connState} />-- <div className="relative min-w-40 flex-1">- <input- type="text"- value={query}- onChange={(e) => setQuery(e.target.value)}- placeholder="Search…"- className="border-code-border text-code-foreground placeholder:text-code-muted focus-visible:border-code-muted/70 w-full rounded-md border bg-black/20 px-2.5 py-1.5 pr-7 text-[13px] outline-none"- />- {query ? (- <button- type="button"- onClick={() => setQuery('')}- aria-label="Clear search"- className="text-code-muted hover:text-code-foreground absolute top-1/2 right-1.5 -translate-y-1/2"- >- <X className="size-3.5" />- </button>- ) : null}- </div>-- <div className="flex gap-1">- {sources.map((src) => {- // Subtractive filter: chip ON = source visible (default); OFF =- // hidden. ON uses a subtle tint of the (data-driven) source color.- const isVisible = !hiddenSources.has(src.value)- return (- <button- key={src.value}- onClick={() => toggleSource(src.value)}- title={isVisible ? `Hide ${src.label}` : `Show ${src.label}`}- className="rounded-md border px-2 py-0.5 font-mono text-[11px] transition-opacity"- style={{- color: src.color,- // Fine, low-contrast border — a faint tint of the source- // color rather than a screamy full-saturation outline.- borderColor: `color-mix(in srgb, ${src.color} 32%, transparent)`,- background: isVisible- ? `color-mix(in srgb, ${src.color} 12%, transparent)`- : 'transparent',- opacity: isVisible ? 1 : 0.45,- fontWeight: isVisible ? 500 : 400,- }}- >- {src.label}- </button>- )- })}- </div>-- <button- onClick={() => setPaused((p) => !p)}- className="text-code-muted hover:text-code-foreground text-xs transition-colors"- title={- paused ? 'Resume live tail' : 'Pause display (stream keeps running)'- }- >- {paused ? 'Resume' : 'Pause'}- </button>-- {onClose ? (- <button- onClick={onClose}- className="text-code-muted hover:text-code-foreground text-xs transition-colors"- >- Close- </button>- ) : null}- </div>-- {/* Stream */}- <div- ref={containerRef}- onScroll={handleScroll}- className="flex-1 overflow-y-auto py-2 font-mono text-xs leading-relaxed"- >- {visible.length === 0 && connState === 'open' ? (- <div className="text-code-muted px-4 py-5 text-center">- No logs yet. Run a command, write to <code>/var/log/...</code>, or- wait for system activity.- </div>- ) : null}- {visible.length === 0 && connState === 'error' ? (- <div className="px-4 py-5 text-center text-rose-400">- Couldn't connect to log stream. Logs may not be configured for- this deployment.- </div>- ) : null}- {visible.map((ev) => (- <Row key={ev._seq} ev={ev} />- ))}- </div>-- {visible.length >= visibleCap ? (- <div className="border-code-border text-code-muted border-t px-4 py-1.5 text-[11px]">- Showing latest {visibleCap} events; older events scrolled off.- </div>- ) : null}- </div>- )-}--function ConnectionDot({- state,-}: {- state: 'connecting' | 'open' | 'error' | 'closed'-}) {- const color =- state === 'open' ? '#6bbd95' : state === 'error' ? '#dc8f88' : '#8a847b'- return (- <span- title={`Connection: ${state}`}- className="inline-block size-2 shrink-0 rounded-full"- style={{ background: color }}- />- )-}--function Row({ ev }: { ev: LogEvent }) {- const sourceMeta = sources.find((s) => s.value === ev.source)- const sourceColor = sourceMeta?.color || '#8a847b'- const time = formatTime(ev._time)-- // Exec EOF marker: empty line + exit_code present → a synthetic "command X- // exited N" row.- if (ev.line === '' && ev.exit_code !== undefined) {- const ok = ev.exit_code === 0- return (- <div- className="flex gap-2.5 px-4 py-0.5 italic"- style={{ color: ok ? '#6bbd95' : '#dc8f88' }}- >- <span className="text-code-muted not-italic">{time}</span>- <span>- {ok ? '✓' : '✗'} {ev.command || 'command'} exited {ev.exit_code}- </span>- </div>- )- }-- return (- <div className="flex gap-2.5 px-4 py-px break-words whitespace-pre-wrap">- <span className="text-code-muted shrink-0">{time}</span>- <span- className="w-14 shrink-0 text-[11px]"- style={{ color: sourceColor }}- >- {sourceMeta?.label || ev.source}- </span>- <span className="text-code-foreground flex-1">{ev.line}</span>- </div>- )-}--// searchCorpus returns the text the search box matches against for a-// given event, lower-cased. For real lines it's just `line`; for EOF-// markers (which have line=='' and a synthesized "X exited N"-// rendering) we include the synthesized text plus the command name +-// argv so users can search for "exit", a command, or its args.-function searchCorpus(ev: LogEvent): string {- if (ev.line === '' && ev.exit_code !== undefined) {- const cmd = ev.command || 'command'- const argv = ev.argv ? ev.argv.join(' ') : ''- return `${cmd} ${argv} exited ${ev.exit_code}`.toLowerCase()- }- return ev.line.toLowerCase()-}--function formatTime(rfc3339: string): string {- // Display HH:MM:SS.mmm — matches the granularity shippers use.- const d = new Date(rfc3339)- if (isNaN(d.getTime())) return ''- const hh = String(d.getHours()).padStart(2, '0')- const mm = String(d.getMinutes()).padStart(2, '0')- const ss = String(d.getSeconds()).padStart(2, '0')- const ms = String(d.getMilliseconds()).padStart(3, '0')- return `${hh}:${mm}:${ss}.${ms}`-}diff --git a/web/src/components/Terminal.tsx b/web/src/components/Terminal.tsxdeleted file mode 100644index a21a7208..00000000--- a/web/src/components/Terminal.tsx+++ /dev/null@@ -1,271 +0,0 @@-import { useEffect, useRef, useState } from 'react'-import { Terminal as XTerm } from '@xterm/xterm'-import { FitAddon } from '@xterm/addon-fit'-import { WebLinksAddon } from '@xterm/addon-web-links'-import { SquareTerminal } from 'lucide-react'-import '@xterm/xterm/css/xterm.css'-import { cn } from '@/lib/utils'--interface TerminalProps {- sandboxId: string- onClose?: () => void- /** Typed into the shell once connected — used by dashboard example chips. */- startupCommand?: string- /** Fired once after the startup command is sent (parent clears it so a- * later manual reopen of the terminal doesn't re-run it). */- onStarted?: () => void-}--export default function Terminal({- sandboxId,- onClose,- startupCommand,- onStarted,-}: TerminalProps) {- const termRef = useRef<HTMLDivElement>(null)- const xtermRef = useRef<XTerm | null>(null)- const wsRef = useRef<WebSocket | null>(null)- const fitRef = useRef<FitAddon | null>(null)- const ptySessionIdRef = useRef<string | null>(null)- // Latest-value refs so the PTY effect can stay keyed on [sandboxId] alone- // (a changing startupCommand/onStarted must not tear down the connection).- const startupRef = useRef(startupCommand)- startupRef.current = startupCommand- const onStartedRef = useRef(onStarted)- onStartedRef.current = onStarted- const [status, setStatus] = useState<- 'connecting' | 'connected' | 'disconnected' | 'error'- >('connecting')- const [errorMsg, setErrorMsg] = useState('')-- useEffect(() => {- if (!termRef.current) return-- const term = new XTerm({- cursorBlink: true,- fontSize: 13,- fontFamily: '"Geist Mono Variable", Menlo, Monaco, Consolas, monospace',- theme: {- background: '#14120f', // warm near-black — matches --terminal- foreground: '#e6e1d8', // warm light- cursor: '#c2bcae', // warm neutral (de-purpled)- selectionBackground: 'rgba(230, 225, 216, 0.16)',- black: '#18181b',- red: '#fb7185',- green: '#34d399',- yellow: '#fbbf24',- blue: '#818cf8',- magenta: '#c084fc',- cyan: '#22d3ee',- white: '#e4e4e7',- brightBlack: '#52525b',- brightRed: '#fda4af',- brightGreen: '#6ee7b7',- brightYellow: '#fde68a',- brightBlue: '#a5b4fc',- brightMagenta: '#d8b4fe',- brightCyan: '#67e8f9',- brightWhite: '#fafafa',- },- allowProposedApi: true,- })-- const fit = new FitAddon()- const webLinks = new WebLinksAddon()-- term.loadAddon(fit)- term.loadAddon(webLinks)- term.open(termRef.current)-- // Fit after a frame to let the container render.- const raf = requestAnimationFrame(() => fit.fit())-- xtermRef.current = term- fitRef.current = fit-- term.writeln('\x1b[2m Connecting to sandbox...\x1b[0m')-- // Guard the async PTY/WS setup against racing the effect cleanup (close or- // navigate before the POST returns): abort the in-flight fetch and never- // open a socket / write to a disposed terminal.- let disposed = false- const controller = new AbortController()-- // Create PTY session, then connect WebSocket- const initTerminal = async () => {- try {- const cols = term.cols- const rows = term.rows-- // Create PTY session- const res = await fetch(`/api/dashboard/sessions/${sandboxId}/pty`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- credentials: 'include',- body: JSON.stringify({ cols, rows }),- signal: controller.signal,- })-- if (!res.ok) {- const data: unknown = await res.json().catch(() => null)- const err =- data && typeof data === 'object'- ? (data as Record<string, unknown>).error- : undefined- throw new Error(typeof err === 'string' ? err : `HTTP ${res.status}`)- }-- const payload: unknown = await res.json()- if (disposed) return- const sessionId =- payload && typeof payload === 'object'- ? (payload as Record<string, unknown>).sessionId- : undefined- if (typeof sessionId !== 'string') {- throw new Error('Invalid PTY session response')- }- ptySessionIdRef.current = sessionId-- // Connect WebSocket- const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'- const wsUrl = `${proto}//${window.location.host}/api/dashboard/sessions/${sandboxId}/pty/${sessionId}`- const ws = new WebSocket(wsUrl)- ws.binaryType = 'arraybuffer'- wsRef.current = ws-- ws.onopen = () => {- if (disposed) return- setStatus('connected')- term.clear()- term.focus()- // Auto-run a starter command (from a dashboard example chip). Small- // delay so the shell's first prompt has painted before we type in.- const cmd = startupRef.current- if (cmd) {- setTimeout(() => {- if (disposed || ws.readyState !== WebSocket.OPEN) return- ws.send(new TextEncoder().encode(cmd + '\n'))- onStartedRef.current?.()- }, 500)- }- }-- ws.onmessage = (event) => {- if (disposed) return- const data = new Uint8Array(event.data)- term.write(data)- }-- ws.onclose = () => {- if (disposed) return- setStatus('disconnected')- term.writeln('')- term.writeln('\x1b[2m Session ended.\x1b[0m')- }-- ws.onerror = () => {- if (disposed) return- setStatus('error')- setErrorMsg('WebSocket connection failed')- }-- // Terminal input -> WebSocket- term.onData((data) => {- if (ws.readyState === WebSocket.OPEN) {- ws.send(new TextEncoder().encode(data))- }- })-- // Handle resize — send to backend resize endpoint (not via PTY stream)- term.onResize(({ cols, rows }) => {- if (ptySessionIdRef.current) {- fetch(- `/api/dashboard/sessions/${sandboxId}/pty/${ptySessionIdRef.current}/resize`,- {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- credentials: 'include',- body: JSON.stringify({ cols, rows }),- },- ).catch(() => {- // Resize failed — not critical, ignore- })- }- })- } catch (err: unknown) {- if (disposed) return // unmounted mid-setup (incl. fetch AbortError)- setStatus('error')- const msg = err instanceof Error ? err.message : 'Failed to connect'- setErrorMsg(msg)- term.writeln(`\x1b[31m Error: ${msg}\x1b[0m`)- }- }-- void initTerminal()-- // Handle window resize- const handleResize = () => {- if (fitRef.current) {- fitRef.current.fit()- }- }- window.addEventListener('resize', handleResize)-- return () => {- disposed = true- controller.abort()- cancelAnimationFrame(raf)- window.removeEventListener('resize', handleResize)- if (wsRef.current) {- wsRef.current.close()- }- term.dispose()- }- }, [sandboxId])-- const statusColor = {- connected: 'text-emerald-400',- connecting: 'text-blue-400',- error: 'text-rose-400',- disconnected: 'text-zinc-500',- }[status]-- return (- <div className="bg-terminal border-code-border overflow-hidden rounded-lg border">- {/* Header */}- <div className="border-code-border flex items-center justify-between border-b px-4 py-2.5">- <div className="flex items-center gap-2">- <SquareTerminal className="text-code-muted size-3.5" />- <span className="text-code-muted text-xs font-medium tracking-wide uppercase">- Terminal- </span>- <span- className={cn(- 'rounded bg-white/5 px-1.5 py-0.5 font-mono text-[10px]',- statusColor,- )}- >- {status}- </span>- </div>- {onClose ? (- <button- onClick={onClose}- className="text-code-muted hover:text-code-foreground text-xs transition-colors"- >- Close- </button>- ) : null}- </div>-- {/* Terminal surface (xterm) */}- <div ref={termRef} className="bg-terminal h-[350px] px-1 py-2" />-- {status === 'error' && errorMsg ? (- <div className="border-code-border border-t px-4 py-2 text-[11px] text-rose-400">- {errorMsg}- </div>- ) : null}- </div>- )-}diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.tsindex 77d9ad9e..0196035c 100644--- a/web/src/components/app-shell-nav.ts+++ b/web/src/components/app-shell-nav.ts@@ -2,7 +2,6 @@ import {ArrowLeft,BookOpen,Bot,- Boxes,BrainCircuit,CalendarClock,Computer,@@ -10,10 +9,8 @@ import {FolderKanban,KeyRound,KeySquare,- Layers,MessagesSquare,Monitor,- Package,Plug,Radar,Rocket,@@ -159,14 +156,8 @@ export function managedAgentsNav(options: {groups.push({label: 'Infrastructure',collapsible: true,- landingTo: '/sandboxes',- items: [- { to: '/sandboxes', label: 'Sandboxes', icon: Boxes },- { to: '/checkpoints', label: 'Checkpoints', icon: Layers },- { to: '/templates', label: 'Sandbox templates', icon: Package },- { to: '/sandbox-webhooks', label: 'Webhooks', icon: Webhook },- { to: '/browsers', label: 'Browsers', icon: Monitor },- ],+ landingTo: '/browsers',+ items: [{ to: '/browsers', label: 'Browsers', icon: Monitor }],})}diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsxindex 2f42380c..8fa4e63a 100644--- a/web/src/components/app-shell.tsx+++ b/web/src/components/app-shell.tsx@@ -8,13 +8,8 @@ import {} from 'react-router-dom'import { useQuery } from '@tanstack/react-query'import {- LayoutGrid,Rocket,Monitor,- Boxes,- Layers,- Package,- Webhook,KeyRound,CreditCard,Settings,@@ -75,14 +70,11 @@ type NavItem = {}type LegacyNavGroup = Omit<NavGroup, 'items'> & { items: NavItem[] }-// The raw-compute (sandbox) plane plus account/org. Groups render with spacing + a small muted+// The legacy (VITE_MANAGED_AGENTS_EXPERIMENT=0) navigation: browsers plus account/org. Groups render with spacing + a small muted// label rather than hard dividers.const LEGACY_NAV: LegacyNavGroup[] = [{- items: [- { to: '/', label: 'Dashboard', icon: LayoutGrid, end: true },- { to: '/getting-started', label: 'Getting started', icon: Rocket },- ],+ items: [{ to: '/', label: 'Getting started', icon: Rocket, end: true }],},{label: 'Browser Sessions',@@ -95,15 +87,6 @@ const LEGACY_NAV: LegacyNavGroup[] = [},],},- {- label: 'Sandboxes',- items: [- { to: '/sandboxes', label: 'Sandboxes', icon: Boxes },- { to: '/checkpoints', label: 'Checkpoints', icon: Layers },- { to: '/templates', label: 'Templates', icon: Package },- { to: '/sandbox-webhooks', label: 'Webhooks', icon: Webhook },- ],- },{label: 'Account',items: [diff --git a/web/src/components/code-off-ramp.tsx b/web/src/components/code-off-ramp.tsxdeleted file mode 100644index a9b0e4c4..00000000--- a/web/src/components/code-off-ramp.tsx+++ /dev/null@@ -1,105 +0,0 @@-import { useState } from 'react'-import { Check, ChevronDown, Code2, Copy, ExternalLink } from 'lucide-react'-import { Button } from '@/components/ui/button'-import { useTransientFlag } from '@/lib/use-transient-flag'-import { notifyError } from '@/lib/errors'-import { cn } from '@/lib/utils'--export type CodeTab = { label: string; code: string }--/**- * A collapsible "dev off-ramp": a muted "</> Show code" toggle that expands to- * tabbed, copyable code (SDK / CLI / cURL) for whatever the adjacent one-click- * button does under the hood. Collapsed by default so it never touches the- * guided happy path — technical users pop it to see that the dashboard is just a- * thin client over the public API/SDK, and copy the exact call.- */-export function CodeOffRamp({- tabs,- docs,- label = 'Show code',- className,-}: {- tabs: CodeTab[]- docs?: string- label?: string- className?: string-}) {- const [open, setOpen] = useState(false)- const [active, setActive] = useState(0)- const [copied, markCopied] = useTransientFlag(1500)-- const current = tabs[active] ?? tabs[0]-- const copy = () => {- void navigator.clipboard.writeText(current.code).then(- () => markCopied(),- (e: unknown) => notifyError("Couldn't copy to clipboard.", e),- )- }-- return (- <div className={className}>- <button- type="button"- onClick={() => setOpen((o) => !o)}- className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5 text-xs font-medium transition-colors"- aria-expanded={open}- >- <Code2 className="size-3.5" />- {label}- <ChevronDown- className={cn(- 'size-3.5 transition-transform',- open ? '' : '-rotate-90',- )}- />- </button>-- {open ? (- <div className="mt-2 overflow-hidden rounded-md border">- <div className="bg-panel-2 flex items-center gap-1 border-b px-2 py-1.5">- {tabs.map((t, i) => (- <button- key={t.label}- type="button"- onClick={() => setActive(i)}- className={cn(- 'rounded px-2 py-1 text-xs font-medium transition-colors',- i === active- ? 'bg-background text-foreground'- : 'text-muted-foreground hover:text-foreground',- )}- >- {t.label}- </button>- ))}- <div className="flex-1" />- {docs ? (- <a- href={docs}- target="_blank"- rel="noreferrer"- className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 px-2 py-1 text-xs underline-offset-4 hover:underline"- >- Docs- <ExternalLink className="size-3" />- </a>- ) : null}- <Button variant="ghost" size="xs" onClick={copy}>- {copied ? (- <Check className="size-3.5" />- ) : (- <Copy className="size-3.5" />- )}- {copied ? 'Copied' : 'Copy'}- </Button>- </div>- <pre className="bg-panel-2 overflow-x-auto px-3 py-3 text-[12.5px] leading-relaxed">- <code className="text-foreground font-mono">{current.code}</code>- </pre>- </div>- ) : null}- </div>- )-}diff --git a/web/src/components/connect-panel.tsx b/web/src/components/connect-panel.tsxdeleted file mode 100644index df09e3fc..00000000--- a/web/src/components/connect-panel.tsx+++ /dev/null@@ -1,130 +0,0 @@-import { useState } from 'react'-import { Check, Copy } from 'lucide-react'-import { Link } from 'react-router-dom'-import { Panel } from '@/components/panel'-import { Button } from '@/components/ui/button'-import { useTransientFlag } from '@/lib/use-transient-flag'-import { notifyError } from '@/lib/errors'-import { cn } from '@/lib/utils'--type Lang = 'shell' | 'ts' | 'python'--const TABS: { key: Lang; label: string }[] = [- { key: 'shell', label: 'Shell' },- { key: 'ts', label: 'TypeScript' },- { key: 'python', label: 'Python' },-]--// Real, copy-and-go snippets for reaching THIS sandbox by id. The SDK/CLI both-// read the key from OPENCOMPUTER_API_KEY (or `oc config`), so we never inline a-// secret — the placeholder + API-keys link is the auth story.-function snippetFor(lang: Lang, id: string): string {- switch (lang) {- case 'shell':- return [- '# one-time: point the CLI at your account',- 'oc config set api-key <your-key>',- '',- '# drop into an interactive shell on this sandbox',- `oc shell ${id}`,- ].join('\n')- case 'ts':- return [- '// npm i @opencomputer/sdk · export OPENCOMPUTER_API_KEY=<your-key>',- 'import { Sandbox } from "@opencomputer/sdk"',- '',- `const sandbox = await Sandbox.connect("${id}")`,- 'const { stdout } = await sandbox.exec.run("echo hello from code")',- 'console.log(stdout)',- ].join('\n')- case 'python':- return [- '# pip install opencomputer-sdk · export OPENCOMPUTER_API_KEY=<your-key>',- 'import asyncio',- 'from opencomputer import Sandbox',- '',- 'async def main():',- ` sandbox = await Sandbox.connect("${id}")`,- ' result = await sandbox.exec.run("echo hello from code")',- ' print(result.stdout)',- '',- 'asyncio.run(main())',- ].join('\n')- }-}--function CodeBlock({ code }: { code: string }) {- const [copied, markCopied] = useTransientFlag(1500)- const copy = () => {- void navigator.clipboard.writeText(code).then(- () => markCopied(),- (e: unknown) => notifyError("Couldn't copy to clipboard.", e),- )- }- return (- <div className="bg-panel-2 relative overflow-hidden rounded-md border">- <Button- variant="ghost"- size="xs"- onClick={copy}- className="text-muted-foreground hover:text-foreground absolute top-2 right-2 z-10"- >- {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}- {copied ? 'Copied' : 'Copy'}- </Button>- <pre className="text-foreground overflow-x-auto px-3 py-3 pr-20 font-mono text-[12.5px] leading-relaxed">- {code}- </pre>- </div>- )-}--/**- * "Connect" reference for a sandbox — shell in via the CLI or drive it from the- * TypeScript / Python SDKs, prefilled with this sandbox's id.- */-export function ConnectPanel({ sandboxId }: { sandboxId: string }) {- const [lang, setLang] = useState<Lang>('shell')- return (- <Panel className="p-6">- <div className="mb-3 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">- <div>- <h2 className="text-sm font-semibold">Connect</h2>- <p className="text-muted-foreground mt-0.5 text-xs">- Shell in or drive this sandbox from your code.- </p>- </div>- <div className="bg-secondary inline-flex w-fit rounded-md p-0.5">- {TABS.map((t) => (- <button- key={t.key}- type="button"- onClick={() => setLang(t.key)}- className={cn(- 'rounded px-3 py-1 text-xs font-medium transition-colors',- lang === t.key- ? 'bg-background text-foreground shadow-sm'- : 'text-muted-foreground hover:text-foreground',- )}- >- {t.label}- </button>- ))}- </div>- </div>-- <CodeBlock code={snippetFor(lang, sandboxId)} />-- <p className="text-muted-foreground mt-3 text-xs">- Need a key?{' '}- <Link- to="/api-keys"- className="text-foreground font-medium underline underline-offset-4"- >- Create one on the API Keys page- </Link>- .- </p>- </Panel>- )-}diff --git a/web/src/components/guided-tour.tsx b/web/src/components/guided-tour.tsxdeleted file mode 100644index b4176ed4..00000000--- a/web/src/components/guided-tour.tsx+++ /dev/null@@ -1,294 +0,0 @@-import { useEffect, useLayoutEffect, useRef, useState } from 'react'-import { createPortal } from 'react-dom'-import {- ArrowLeft,- ArrowRight,- Check,- Copy,- ExternalLink,- X,-} from 'lucide-react'-import { Button } from '@/components/ui/button'-import { type CodeTab } from '@/components/code-off-ramp'-import { useTransientFlag } from '@/lib/use-transient-flag'-import { cn } from '@/lib/utils'--export type GuideStep = {- /** The real UI element this step points at (spotlighted). */- target: React.RefObject<HTMLElement | null>- title: string- body: string- /** The API call that produced this region, e.g. "POST /v3/sessions". */- api?: string- /** Tabbed, copyable snippets of the real call (SDK / CLI / API). */- code?: CodeTab[]- docs?: string-}--const CALLOUT_W = 520-const PAD = 8-const M = 16 // viewport margin-const GAP = 12 // gap between spotlight and callout--const clamp = (v: number, lo: number, hi: number) =>- Math.max(lo, Math.min(v, hi))--/**- * A first-run guided overlay: spotlights real UI regions on the destination view- * and, beside each, explains what it is + the exact public API call that- * produced it, with SDK / CLI / API tabs so people can jump to the path they- * care about. Non-blocking (the page behind stays usable); resize/scroll-safe.- */-export function GuidedTour({- steps,- open,- onClose,-}: {- steps: GuideStep[]- open: boolean- onClose: () => void-}) {- const [i, setI] = useState(0)- const [tab, setTab] = useState(0)- const [rect, setRect] = useState<DOMRect | null>(null)- const [copied, markCopied] = useTransientFlag(1500)- const calloutRef = useRef<HTMLDivElement>(null)- const [calloutH, setCalloutH] = useState(360)-- useEffect(() => {- if (open) {- setI(0)- setTab(0)- }- }, [open])-- // Reset the code tab whenever the step changes.- useEffect(() => {- setTab(0)- }, [i])-- // Measure the callout's real height so placement can avoid overlapping the- // spotlight (a fixed estimate misplaces short/tall callouts).- useLayoutEffect(() => {- if (calloutRef.current) setCalloutH(calloutRef.current.offsetHeight)- }, [open, i, tab, rect])-- const step = steps[i]-- // Measure the current target, scroll it into view, and keep the spotlight- // pinned to it through the smooth-scroll settle + any resize/scroll.- useLayoutEffect(() => {- if (!open || !step) return- const measure = () => {- const el = step.target.current- if (el) setRect(el.getBoundingClientRect())- }- step.target.current?.scrollIntoView({ behavior: 'smooth', block: 'center' })- measure()- const timers = [setTimeout(measure, 150), setTimeout(measure, 450)]- window.addEventListener('resize', measure)- window.addEventListener('scroll', measure, true)- return () => {- timers.forEach(clearTimeout)- window.removeEventListener('resize', measure)- window.removeEventListener('scroll', measure, true)- }- }, [open, i, step])-- // Esc closes; arrows navigate.- useEffect(() => {- if (!open) return- const onKey = (e: KeyboardEvent) => {- if (e.key === 'Escape') onClose()- else if (e.key === 'ArrowRight' && i < steps.length - 1) setI((n) => n + 1)- else if (e.key === 'ArrowLeft' && i > 0) setI((n) => n - 1)- }- window.addEventListener('keydown', onKey)- return () => window.removeEventListener('keydown', onKey)- }, [open, i, steps.length, onClose])-- if (!open || !step) return null-- const spot = rect- ? {- top: rect.top - PAD,- left: rect.left - PAD,- width: rect.width + PAD * 2,- height: rect.height + PAD * 2,- }- : null-- // Place the callout in whichever region around the spotlight has real room —- // below → above → right → left — so it never sits on top of the target. If the- // target is too big to clear (full-width, tall panels), dock it to the right- // edge (guaranteed on-screen).- const vw = window.innerWidth- const vh = window.innerHeight- let calloutTop = M- let calloutLeft = M- if (spot) {- const roomBelow = vh - (spot.top + spot.height)- const roomAbove = spot.top- const roomRight = vw - (spot.left + spot.width)- const roomLeft = spot.left- if (roomBelow >= calloutH + GAP + M) {- calloutTop = spot.top + spot.height + GAP- calloutLeft = clamp(spot.left, M, vw - CALLOUT_W - M)- } else if (roomAbove >= calloutH + GAP + M) {- calloutTop = spot.top - calloutH - GAP- calloutLeft = clamp(spot.left, M, vw - CALLOUT_W - M)- } else if (roomRight >= CALLOUT_W + GAP + M) {- calloutLeft = spot.left + spot.width + GAP- calloutTop = clamp(spot.top, M, vh - calloutH - M)- } else if (roomLeft >= CALLOUT_W + GAP + M) {- calloutLeft = spot.left - CALLOUT_W - GAP- calloutTop = clamp(spot.top, M, vh - calloutH - M)- } else {- calloutLeft = vw - CALLOUT_W - M- calloutTop = clamp(vh / 2 - calloutH / 2, M, vh - calloutH - M)- }- }-- const tabs = step.code ?? []- const current = tabs[tab] ?? tabs[0]- const copy = () => {- if (current) void navigator.clipboard.writeText(current.code).then(markCopied)- }-- return createPortal(- <div className="fixed inset-0 z-[100]" role="dialog" aria-modal="false">- {/* Spotlight: a ring around the target with a huge box-shadow scrim so- everything else dims. pointer-events-none → the page stays usable. */}- {spot ? (- <div- className="ring-primary pointer-events-none absolute rounded-lg ring-2 transition-all duration-200"- style={{- top: spot.top,- left: spot.left,- width: spot.width,- height: spot.height,- boxShadow: '0 0 0 9999px rgba(0,0,0,0.55)',- }}- />- ) : (- <div className="pointer-events-none absolute inset-0 bg-black/55" />- )}-- {/* Callout */}- <div- ref={calloutRef}- className="bg-background absolute rounded-lg border p-4 shadow-xl"- style={{- top: calloutTop,- left: calloutLeft,- width: CALLOUT_W,- maxWidth: 'calc(100vw - 32px)',- }}- >- <div className="flex items-start justify-between gap-3">- <span className="text-muted-foreground text-xs">- Step {i + 1} of {steps.length}- </span>- <button- onClick={onClose}- aria-label="Close"- className="text-muted-foreground hover:text-foreground -mt-1 -mr-1"- >- <X className="size-4" />- </button>- </div>-- <h3 className="text-foreground mt-1 text-sm font-semibold">- {step.title}- </h3>- <p className="text-muted-foreground mt-1 text-sm">{step.body}</p>-- {step.api ? (- <div className="text-muted-foreground mt-2 font-mono text-xs">- {step.api}- </div>- ) : null}-- {tabs.length > 0 ? (- <div className="bg-panel-2 mt-2 overflow-hidden rounded-md border">- <div className="flex items-center gap-1 border-b px-2 py-1.5">- {tabs.map((t, n) => (- <button- key={t.label}- type="button"- onClick={() => setTab(n)}- className={cn(- 'rounded px-2 py-1 text-xs font-medium transition-colors',- n === tab- ? 'bg-background text-foreground'- : 'text-muted-foreground hover:text-foreground',- )}- >- {t.label}- </button>- ))}- <div className="flex-1" />- <Button variant="ghost" size="xs" onClick={copy}>- {copied ? (- <Check className="size-3.5" />- ) : (- <Copy className="size-3.5" />- )}- {copied ? 'Copied' : 'Copy'}- </Button>- </div>- <pre className="max-h-[220px] overflow-auto px-3 py-3 text-[12.5px] leading-relaxed">- <code className="text-foreground font-mono whitespace-pre">- {current?.code}- </code>- </pre>- </div>- ) : null}-- <div className="mt-3 flex items-center justify-between">- <div className="flex items-center gap-1.5">- {steps.map((_, n) => (- <span- key={n}- className={cn(- 'size-1.5 rounded-full',- n === i ? 'bg-primary' : 'bg-border',- )}- />- ))}- </div>- <div className="flex items-center gap-2">- {step.docs ? (- <a- href={step.docs}- target="_blank"- rel="noreferrer"- className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs underline-offset-4 hover:underline"- >- Docs- <ExternalLink className="size-3" />- </a>- ) : null}- {i > 0 ? (- <Button variant="ghost" size="sm" onClick={() => setI((n) => n - 1)}>- <ArrowLeft className="size-3.5" />- Back- </Button>- ) : null}- {i < steps.length - 1 ? (- <Button size="sm" onClick={() => setI((n) => n + 1)}>- Next- <ArrowRight className="size-3.5" />- </Button>- ) : (- <Button size="sm" onClick={onClose}>- Done- </Button>- )}- </div>- </div>- </div>- </div>,- document.body,- )-}diff --git a/web/src/components/metric-card.tsx b/web/src/components/metric-card.tsxdeleted file mode 100644index f3c9433b..00000000--- a/web/src/components/metric-card.tsx+++ /dev/null@@ -1,27 +0,0 @@-import type { ReactNode } from 'react'-import { Panel } from '@/components/panel'-import { cn } from '@/lib/utils'--export function MetricCard({- label,- value,- hint,- className,-}: {- label: ReactNode- value: ReactNode- hint?: ReactNode- className?: string-}) {- return (- <Panel className={cn('px-5 py-4', className)}>- <div className="text-muted-foreground text-xs">{label}</div>- <div className="text-foreground mt-1.5 font-mono text-3xl leading-none font-semibold tabular-nums">- {value}- </div>- {hint ? (- <div className="text-muted-foreground mt-1.5 text-xs">{hint}</div>- ) : null}- </Panel>- )-}diff --git a/web/src/hooks/use-prefetch.ts b/web/src/hooks/use-prefetch.tsdeleted file mode 100644index 34a0d6f8..00000000--- a/web/src/hooks/use-prefetch.ts+++ /dev/null@@ -1,20 +0,0 @@-import { useQueryClient } from '@tanstack/react-query'-import { getSandboxDetail } from '@/api/client'--/**- * Returns a prefetcher for a sandbox detail page. Call it on row hover/focus to- * warm the lazy route chunk and the detail query, so the click feels instant.- * Cheap + idempotent — the chunk import dedupes and the query has a staleTime.- */-export function usePrefetchSandbox() {- const queryClient = useQueryClient()- return (sandboxId: string) => {- // Warm the code-split SandboxDetail chunk (same module the route lazy-loads).- void import('@/pages/SandboxDetail')- void queryClient.prefetchQuery({- queryKey: ['sandbox-detail', sandboxId],- queryFn: () => getSandboxDetail(sandboxId),- staleTime: 10_000,- })- }-}diff --git a/web/src/index.css b/web/src/index.cssindex ef2e3792..8701ed72 100644--- a/web/src/index.css+++ b/web/src/index.css@@ -196,9 +196,7 @@--code-foreground: hsl(40 12% 88%);--code-muted: hsl(40 6% 54%); /* line numbers, gutters */--code-border: hsl(36 8% 19%);- --terminal: hsl(- 36 13% 7%- ); /* warm near-black (xterm bg matches in Terminal.tsx) */+ --terminal: hsl(36 13% 7%); /* warm near-black *//* Charts — neutral ink ramp (light → dark) */--chart-1: hsl(45 8% 25%);diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsxindex c6baaa13..d65ba6b4 100644--- a/web/src/pages/Billing.tsx+++ b/web/src/pages/Billing.tsx@@ -145,10 +145,6 @@ function PlanTab() {<div className="text-foreground text-2xl font-semibold tracking-tight">{isPro ? 'Pro' : 'Free'}</div>- <p className="text-muted-foreground mt-1 text-sm">- {billing?.maxConcurrentSandboxes ?? 50} concurrent sandboxes ·{' '}- {isPro ? 'all tiers' : 'up to 4 GB / 1 vCPU'}- </p>{isPro &&billing?.stripeCreditCents != null &&@@ -171,8 +167,7 @@ function PlanTab() {) : (<p className="text-status-error flex items-center gap-1.5 text-sm"><CircleAlert className="size-4 shrink-0" />- Free trial credits exhausted — upgrade to continue using- sandboxes+ Free trial credits exhausted — upgrade to continue</p>)}<p className="text-muted-foreground text-sm">@@ -829,7 +824,7 @@ function ModelUsageCard({</div><p className="text-muted-foreground mt-2 text-sm">Serverless-agent models draw from the same prepaid credits balance as- agent runtime and sandboxes.+ agent runtime.</p><div className="mt-4 grid grid-cols-2 gap-3 text-sm"><div>diff --git a/web/src/pages/Checkpoints.tsx b/web/src/pages/Checkpoints.tsxdeleted file mode 100644index 549b4734..00000000--- a/web/src/pages/Checkpoints.tsx+++ /dev/null@@ -1,268 +0,0 @@-import { useMemo, useState } from 'react'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import { Layers, CircleAlert } from 'lucide-react'-import { notifyError } from '@/lib/errors'-import {- deleteCheckpointDashboard,- getCheckpoints,- type CheckpointItem,-} from '@/api/client'-import { PageHeader } from '@/components/page-header'-import { Panel } from '@/components/panel'-import { Button } from '@/components/ui/button'-import { Badge } from '@/components/ui/badge'-import { Checkbox } from '@/components/ui/checkbox'-import { StatusBadge } from '@/components/status-badge'-import { EmptyState } from '@/components/empty-state'-import { ConfirmDialog } from '@/components/confirm-dialog'-import { ResourceTable, type Column } from '@/components/resource-table'--function checkpointTypeLabel(cp: CheckpointItem) {- return cp.kind === 'disk_only' ? 'Disk-only' : 'Full'-}--function checkpointTypeDetail(cp: CheckpointItem) {- if (cp.kind !== 'disk_only') return 'Disk, memory, CPU'- if (cp.promotionStatus === 'ready') return 'Promoted for fast fork'- if (cp.promotionStatus === 'processing' || cp.promotionStatus === 'pending')- return 'Promoting'- if (cp.promotionStatus === 'failed') return 'Promotion failed'- return 'Disk only'-}--const PER_PAGE = 20--export default function Checkpoints() {- const queryClient = useQueryClient()- const [page, setPage] = useState(1)- const [showFailed, setShowFailed] = useState(false)- const [toDelete, setToDelete] = useState<CheckpointItem | null>(null)-- const { data, isLoading } = useQuery({- queryKey: ['checkpoints', page],- queryFn: () => getCheckpoints(page, PER_PAGE),- })-- const deleteMutation = useMutation({- mutationFn: (id: string) => deleteCheckpointDashboard(id),- onError: (error) => notifyError("Couldn't delete the checkpoint.", error),- onSettled: () =>- void queryClient.invalidateQueries({ queryKey: ['checkpoints'] }),- })-- const confirmDelete = () => {- if (!toDelete) return- deleteMutation.mutate(toDelete.id, { onSuccess: () => setToDelete(null) })- }-- const checkpoints = useMemo(() => data?.checkpoints ?? [], [data])- const visibleCheckpoints = useMemo(() => {- if (!showFailed) return checkpoints.filter((cp) => cp.status !== 'failed')- // Keep failed at the bottom, otherwise preserve order.- return checkpoints- .map((cp, index) => ({ cp, index }))- .sort((a, b) => {- const aFailed = a.cp.status === 'failed'- const bFailed = b.cp.status === 'failed'- if (aFailed !== bFailed) return aFailed ? 1 : -1- return a.index - b.index- })- .map(({ cp }) => cp)- }, [checkpoints, showFailed])-- const total = data?.total ?? 0- const totalPages = Math.ceil(total / PER_PAGE)-- const columns: Column<CheckpointItem>[] = [- {- key: 'name',- header: 'Name',- cell: (cp) => (- <span className="text-foreground font-medium">{cp.name}</span>- ),- },- {- key: 'sandbox',- header: 'Sandbox',- cell: (cp) => <code className="font-mono text-xs">{cp.sandboxId}</code>,- },- {- key: 'type',- header: 'Type',- cell: (cp) => (- <div className="flex flex-col gap-1">- <Badge- variant={cp.kind === 'disk_only' ? 'secondary' : 'outline'}- className="w-fit"- >- {checkpointTypeLabel(cp)}- </Badge>- <span className="text-muted-foreground text-xs">- {checkpointTypeDetail(cp)}- </span>- </div>- ),- },- {- key: 'status',- header: 'Status',- cell: (cp) => <StatusBadge status={cp.status} />,- },- {- key: 'activeForks',- header: 'Active forks',- align: 'right',- cell: (cp) => (- <span className="font-mono text-xs">- {cp.activeForks > 0 ? (- <span className="text-status-running">{cp.activeForks}</span>- ) : (- <span className="text-muted-foreground">0</span>- )}- </span>- ),- },- {- key: 'totalForks',- header: 'Total forks',- align: 'right',- cell: (cp) => (- <span className="text-muted-foreground font-mono text-xs">- {cp.totalForks}- </span>- ),- },- {- key: 'created',- header: 'Created',- cell: (cp) => (- <span className="text-muted-foreground font-mono text-xs">- {new Date(cp.createdAt).toLocaleString()}- </span>- ),- },- {- key: 'actions',- header: '',- align: 'right',- cell: (cp) => (- <Button- variant="ghost"- size="sm"- className="text-status-error hover:text-destructive underline-offset-2 hover:bg-transparent hover:underline"- onClick={() => setToDelete(cp)}- >- Delete- </Button>- ),- },- ]-- return (- <div>- <PageHeader- title="Checkpoints"- description="Sandbox snapshots across your organization"- api={{- sdk: 'sandbox.checkpoints.list()',- docs: 'https://docs.opencomputer.dev/sandboxes/checkpoints',- }}- actions={- <label- htmlFor="show-failed"- className="text-muted-foreground hover:text-foreground flex cursor-pointer items-center gap-2 text-sm transition-colors"- >- <Checkbox- id="show-failed"- checked={showFailed}- onCheckedChange={(v) => setShowFailed(v === true)}- />- Show failed- </label>- }- />-- <Panel className="overflow-hidden">- <ResourceTable- columns={columns}- rows={visibleCheckpoints}- rowKey={(cp) => cp.id}- loading={isLoading}- renderSubRow={(cp) =>- cp.status === 'failed' && cp.errorMsg ? (- <div className="bg-status-error-bg/50 flex items-start gap-2 px-4 py-2.5">- <CircleAlert className="text-status-error mt-px size-3.5 shrink-0" />- <div className="min-w-0 text-xs">- <span className="text-status-error break-words">- {cp.errorMsg}- </span>- {cp.failedAt ? (- <span className="text-muted-foreground">- {' · failed '}- {new Date(cp.failedAt).toLocaleString()}- </span>- ) : null}- </div>- </div>- ) : null- }- empty={- <EmptyState- icon={Layers}- title={- checkpoints.length === 0- ? 'No checkpoints yet'- : 'No checkpoints to show'- }- description={- checkpoints.length === 0- ? 'Snapshots of your sandboxes will appear here.'- : 'Toggle “Show failed checkpoints” to include failures.'- }- />- }- />-- {totalPages > 1 && (- <div className="text-muted-foreground flex items-center justify-between border-t px-4 py-3 text-sm">- <span>- {total} checkpoint{total !== 1 ? 's' : ''}- </span>- <div className="flex items-center gap-2">- <Button- variant="outline"- size="sm"- disabled={page <= 1}- onClick={() => setPage((p) => p - 1)}- >- Previous- </Button>- <span className="px-1 font-mono text-xs">- {page} / {totalPages}- </span>- <Button- variant="outline"- size="sm"- disabled={page >= totalPages}- onClick={() => setPage((p) => p + 1)}- >- Next- </Button>- </div>- </div>- )}- </Panel>-- <ConfirmDialog- open={toDelete !== null}- onOpenChange={(open) => !open && setToDelete(null)}- title={`Delete checkpoint ${toDelete?.name ? `"${toDelete.name}"` : ''}?`}- description="Active forks will not be affected."- confirmLabel="Delete checkpoint"- destructive- pending={deleteMutation.isPending}- onConfirm={confirmDelete}- />- </div>- )-}diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsxindex 58b9dc1a..3d56a4d0 100644--- a/web/src/pages/Dashboard.tsx+++ b/web/src/pages/Dashboard.tsx@@ -1,183 +1,20 @@import { useEffect, useRef } from 'react'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import { Link, useLocation } from 'react-router-dom'-import { Boxes, Check, Copy, ExternalLink, KeyRound } from 'lucide-react'-import {- createAPIKey,- getAPIKeys,- getSandboxes,- type Sandbox,-} from '@/api/client'-import { usePrefetchSandbox } from '@/hooks/use-prefetch'-import { PageHeader } from '@/components/page-header'-import { Panel, PanelHeader, PanelTitle } from '@/components/panel'-import { MetricCard } from '@/components/metric-card'+import { Link } from 'react-router-dom'+import { KeyRound } from 'lucide-react'+import { createAPIKey, getAPIKeys } from '@/api/client'+import { Panel } from '@/components/panel'import { CopyRow } from '@/components/copy-row'-import { StatusBadge } from '@/components/status-badge'-import { EmptyState } from '@/components/empty-state'-import { ResourceTable, type Column } from '@/components/resource-table'import { Button } from '@/components/ui/button'-import { notifyError } from '@/lib/errors'-import { useTransientFlag } from '@/lib/use-transient-flag'-import { cn } from '@/lib/utils'--const SANDBOX_API_CODE = `const sandbox = await Sandbox.create();-const result =- await sandbox.commands.run("uname -a");--console.log(result.stdout);-await sandbox.kill();`--function formatDuration(sandbox: Sandbox): string {- const start = new Date(sandbox.startedAt).getTime()- const end = sandbox.stoppedAt- ? new Date(sandbox.stoppedAt).getTime()- : Date.now()- const secs = Math.round((end - start) / 1000)- if (secs < 60) return `${secs}s`- if (secs < 3600) return `${Math.round(secs / 60)}m`- return `${Math.round((secs / 3600) * 10) / 10}h`-}+// The legacy home (VITE_MANAGED_AGENTS_EXPERIMENT=0). The sandbox overview and+// quickstart it used to show are gone with the sandbox product (work 097); what+// remains is the organization's API key.export default function Dashboard() {- const prefetch = usePrefetchSandbox()- const location = useLocation()- // Getting started is its own left-nav item (/getting-started). Brand-new orgs- // also see it inline on first run (at /).- const onGettingStartedRoute = location.pathname === '/getting-started'-- const { data: runningSandboxesData, isLoading: loadingRunningSandboxes } =- useQuery({- queryKey: ['sandboxes', 'running'],- queryFn: () => getSandboxes('running'),- })- const { data: allSandboxesData, isLoading: loadingSandboxes } = useQuery({- queryKey: ['sandboxes', ''],- queryFn: () => getSandboxes(),- })-- const activeSandboxes = runningSandboxesData ?? []- const allSandboxes = allSandboxesData ?? []-- const today = new Date().toISOString().slice(0, 10)- const isToday = (iso: string) =>- new Date(iso).toISOString().slice(0, 10) === today-- const sandboxesToday = allSandboxes.filter((s) => isToday(s.startedAt)).length-- // First-run only when the org has no sandboxes yet.- const isFirstRun = !loadingSandboxes && allSandboxes.length === 0-- // Genuine first-run auto-shows onboarding; returning users reach it via the- // left-nav "Getting started" item (/getting-started).- const showOnboarding = isFirstRun || onGettingStartedRoute-- const sandboxColumns: Column<Sandbox>[] = [- {- key: 'id',- header: 'Sandbox ID',- cell: (s) => (- <Link- to={`/sandboxes/${s.sandboxId}`}- onMouseEnter={() => prefetch(s.sandboxId)}- onFocus={() => prefetch(s.sandboxId)}- className="text-foreground font-mono text-[13px] underline-offset-4 hover:underline"- >- {s.sandboxId}- </Link>- ),- },- {- key: 'template',- header: 'Template',- cell: (s) => (- <span className="text-muted-foreground">{s.template || 'base'}</span>- ),- },- {- key: 'status',- header: 'Status',- cell: (s) => <StatusBadge status={s.status} />,- },- {- key: 'started',- header: 'Started',- cell: (s) => (- <span className="text-muted-foreground font-mono text-xs">- {new Date(s.startedAt).toLocaleString()}- </span>- ),- },- {- key: 'duration',- header: 'Duration',- cell: (s) => (- <span className="text-muted-foreground font-mono text-xs">- {formatDuration(s)}- </span>- ),- },- ]-- return (- <div>- {!showOnboarding && (- <PageHeader- title="Dashboard"- description="Overview of your sandboxes"- />- )}-- {showOnboarding ? (- <GettingStarted />- ) : (- <div className="space-y-6">- <div className="grid grid-cols-2 gap-4">- <MetricCard- label="Active sandboxes"- value={- loadingRunningSandboxes- ? '—'- : activeSandboxes.length.toLocaleString()- }- />- <MetricCard- label="Sandboxes today"- value={loadingSandboxes ? '—' : sandboxesToday.toLocaleString()}- />- </div>-- <Panel className="overflow-hidden">- <PanelHeader>- <PanelTitle>Recent sandboxes</PanelTitle>- <Link- to="/sandboxes"- className="text-muted-foreground hover:text-foreground text-xs underline-offset-4 hover:underline"- >- View all- </Link>- </PanelHeader>- <ResourceTable- columns={sandboxColumns}- rows={allSandboxes.slice(0, 10)}- rowKey={(s) => s.id}- loading={loadingSandboxes}- empty={- <EmptyState- icon={Boxes}- title="No sandboxes yet"- description="Sandboxes you start will show up here."- />- }- />- </Panel>- </div>- )}- </div>- )+ return <GettingStarted />}-/* ── First-run onboarding ─────────────────────────────────────────────────── */+/* ── API key ─────────────────────────────────────────────────── */export function GettingStarted() {const queryClient = useQueryClient()const keysQuery = useQuery({@@ -278,87 +115,6 @@ export function GettingStarted() {</div></div></Panel>-- <div className="mt-8">- <ApiExample- icon={Boxes}- title="Sandboxes"- description="Run commands in an isolated computer."- code={SANDBOX_API_CODE}- docs="https://docs.opencomputer.dev/quickstart"- docsLabel="Open sandbox quickstart"- />- </div></div>)}--function ApiExample({- icon: Icon,- title,- description,- code,- docs,- docsLabel,- className,-}: {- icon: typeof Boxes- title: string- description: string- code: string- docs: string- docsLabel: string- className?: string-}) {- const [copied, markCopied] = useTransientFlag(1500)-- const copy = () => {- void navigator.clipboard.writeText(code).then(- () => markCopied(),- (error: unknown) => notifyError("Couldn't copy to clipboard.", error),- )- }-- return (- <article className={cn('min-w-0', className)}>- <div className="flex items-start gap-3">- <span className="bg-secondary mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md">- <Icon className="text-muted-foreground size-4" aria-hidden />- </span>- <div>- <h3 className="text-sm font-semibold">{title}</h3>- <p className="text-muted-foreground mt-1 text-sm leading-6">- {description}- </p>- </div>- </div>-- <div className="bg-panel-2 relative mt-4 overflow-hidden rounded-lg border">- <pre className="overflow-x-auto p-4 pr-12 font-mono text-xs leading-5">- <code>{code}</code>- </pre>- <Button- type="button"- size="icon-sm"- variant="ghost"- className="bg-panel-2 absolute top-2 right-2"- onClick={copy}- aria-label={copied ? 'Copied' : `Copy ${title} example`}- >- {copied ? (- <Check className="size-3.5" />- ) : (- <Copy className="size-3.5" />- )}- </Button>- </div>-- <Button variant="outline" size="sm" className="mt-4" asChild>- <a href={docs} target="_blank" rel="noreferrer">- {docsLabel}- <ExternalLink className="size-3.5" aria-hidden />- </a>- </Button>- </article>- )-}diff --git a/web/src/pages/SandboxDetail.tsx b/web/src/pages/SandboxDetail.tsxdeleted file mode 100644index be50401c..00000000--- a/web/src/pages/SandboxDetail.tsx+++ /dev/null@@ -1,831 +0,0 @@-import { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react'-import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import { notifyError } from '@/lib/errors'-import {- ArrowLeft,- List,- SquareTerminal,- RotateCcw,- Power,- Trash2,- ChevronRight,- Loader2,- Sparkles,-} from 'lucide-react'-import { GuidedTour, type GuideStep } from '@/components/guided-tour'-import {- ApiError,- createPreviewUrl,- deletePreviewUrl,- deleteSandbox,- getSandboxDetail,- getSandboxStats,- powerCycleSandbox,- rebootSandbox,- type Sandbox,- type SandboxDetail as SessionDetailData,-} from '@/api/client'-// Lazy — these pull in xterm / the SSE stream; keep them out of the main chunk.-const Terminal = lazy(() => import('@/components/Terminal'))-const LogsPanel = lazy(() => import('@/components/LogsPanel'))-import { Panel } from '@/components/panel'-import { Button } from '@/components/ui/button'-import { Input } from '@/components/ui/input'-import { MetricCard } from '@/components/metric-card'-import { ConnectPanel } from '@/components/connect-panel'-import { StatusBadge } from '@/components/status-badge'-import { EmptyState } from '@/components/empty-state'-import { ConfirmDialog } from '@/components/confirm-dialog'--// "Host a web app" demo, built once the preview hostname is known: a styled-// index.html (with a charset so the emoji renders instead of mojibake), a-// background server, then the live URL echoed into the terminal — which is the-// front-and-center element on the sandbox page.-const WEB_APP_HTML =- '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Live from my sandbox</title><style>body{font-family:system-ui,-apple-system,sans-serif;margin:0;min-height:100vh;display:grid;place-items:center;background:radial-gradient(circle at 50% 30%,#1a1a24,#0b0b0f);color:#e6e1d8}main{text-align:center;padding:2rem}h1{font-size:2.25rem;margin:0 0 .5rem}p{color:#9a948a;margin:0}.tag{display:inline-block;margin-top:1.25rem;font-family:ui-monospace,monospace;font-size:.8rem;color:#818cf8;border:1px solid #2a2a35;border-radius:999px;padding:.4rem .8rem}</style></head><body><main><h1>Hello from your sandbox 👋</h1><p>This page is served live from a real cloud VM.</p><span class="tag">OpenComputer</span></main></body></html>'--function buildWebAppCommand(hostname: string): string {- return (- `printf '%s' '${WEB_APP_HTML}' > index.html` +- ` && (python3 -m http.server 8000 >/dev/null 2>&1 &)` +- ` && sleep 1` +- ` && echo "" && echo "🌐 Your site is LIVE — open it in a new tab:"` +- ` && echo " https://${hostname}" && echo ""`- )-}--function formatBytes(bytes: number): string {- if (bytes === 0) return '0 B'- const units = ['B', 'KB', 'MB', 'GB']- const i = Math.floor(Math.log(bytes) / Math.log(1024))- return `${(bytes / Math.pow(1024, i)).toFixed(i > 0 ? 1 : 0)} ${units[i]}`-}--function timeAgo(dateStr: string): string {- const diff = Date.now() - new Date(dateStr).getTime()- const mins = Math.floor(diff / 60000)- if (mins < 1) return 'just now'- if (mins < 60) return `${mins}m ago`- const hrs = Math.floor(mins / 60)- if (hrs < 24) return `${hrs}h ${mins % 60}m ago`- return `${Math.floor(hrs / 24)}d ago`-}--type ConfirmKind = 'delete' | 'reboot' | 'power-cycle' | null--export default function SandboxDetail() {- const { sandboxId } = useParams<{ sandboxId: string }>()- const navigate = useNavigate()- const location = useLocation()- const queryClient = useQueryClient()-- const [copiedUrl, setCopiedUrl] = useState<string | null>(null)- const [showTerminal, setShowTerminal] = useState(false)- const [showLogs, setShowLogs] = useState(false)- const [showInternal, setShowInternal] = useState(false)- const [confirm, setConfirm] = useState<ConfirmKind>(null)-- // Consumed once from navigation state (dashboard example chips): a command to- // auto-run in the terminal, and whether to jump to the Connect panel.- const [startupCommand, setStartupCommand] = useState<string | undefined>(- () => (location.state as { startupCommand?: string } | null)?.startupCommand,- )- const [focusConnect] = useState(- () => (location.state as { focus?: string } | null)?.focus === 'connect',- )- // "Host a web app" carries a port to auto-expose once the box is running; the- // webApp flag then runs the styled-page demo (with the real preview hostname).- const [exposePort] = useState(- () => (location.state as { exposePort?: number } | null)?.exposePort,- )- const [webApp] = useState(- () => (location.state as { webApp?: boolean } | null)?.webApp === true,- )- const exposedRef = useRef(false)- const [portInput, setPortInput] = useState('')- const connectRef = useRef<HTMLDivElement>(null)- const scrolledRef = useRef(false)-- // Guided first-run overlay: maps this sandbox's UI to the API/SDK/CLI that- // achieves each thing. Ordered so the chip you launched from leads (after the- // create step). Anchors: header, Terminal button, Preview panel, Connect panel.- const headerRef = useRef<HTMLDivElement>(null)- const terminalBtnRef = useRef<HTMLButtonElement>(null)- const previewRef = useRef<HTMLDivElement>(null)- const [guideOpen, setGuideOpen] = useState(- () => (location.state as { guide?: boolean } | null)?.guide === true,- )- const guideSteps: GuideStep[] = useMemo(() => {- const id = sandboxId || '<id>'- const stepCreate: GuideStep = {- target: headerRef,- title: 'You created a real cloud sandbox',- body: 'One call spun up a persistent Linux VM. It stays alive until you kill it or it idles out.',- api: 'POST /api/sandboxes',- code: [- {- label: 'SDK',- code: `import { Sandbox } from "@opencomputer/sdk";--const sandbox = await Sandbox.create();`,- },- { label: 'CLI', code: `oc create` },- {- label: 'API',- code: `curl -X POST https://app.opencomputer.dev/api/sandboxes \\- -H "X-API-Key: $OPENCOMPUTER_API_KEY" \\- -H "Content-Type: application/json" \\- -d '{"memoryMB":1024,"cpuCount":1,"networkEnabled":true}'`,- },- ],- docs: 'https://docs.opencomputer.dev/quickstart',- }- const stepExec: GuideStep = {- target: terminalBtnRef,- title: 'Run commands in it',- body: 'This terminal runs against the live VM. In code it is exec — install packages, run scripts, anything.',- api: 'sandbox.exec.run(…)',- code: [- {- label: 'SDK',- code: `const { stdout } = await sandbox.exec.run("python3 --version");-console.log(stdout);`,- },- { label: 'CLI', code: `oc exec ${id} -- python3 --version` },- {- label: 'API',- code: `curl -X POST https://app.opencomputer.dev/api/sandboxes/${id}/exec/run \\- -H "X-API-Key: $OPENCOMPUTER_API_KEY" \\- -H "Content-Type: application/json" \\- -d '{"cmd":"python3 --version"}'`,- },- ],- docs: 'https://docs.opencomputer.dev/sandboxes/overview',- }- const stepExpose: GuideStep = {- target: previewRef,- title: 'Expose a port → public URL',- body: 'Start a server in the box, then expose its port to get a public https URL — great for web apps and webhooks.',- api: 'sandbox.createPreviewURL({ port })',- code: [- {- label: 'SDK',- code: `// exec.start() runs the server in the background (exec.run() would block)-await sandbox.exec.start("python3 -m http.server 8000");-const preview = await sandbox.createPreviewURL({ port: 8000 });-console.log(preview.hostname);`,- },- { label: 'CLI', code: `oc preview create ${id} --port 8000` },- {- label: 'API',- code: `curl -X POST https://app.opencomputer.dev/api/sandboxes/${id}/preview \\- -H "X-API-Key: $OPENCOMPUTER_API_KEY" \\- -H "Content-Type: application/json" \\- -d '{"port":8000}'`,- },- ],- docs: 'https://docs.opencomputer.dev/sandboxes/preview-urls',- }- const stepConnect: GuideStep = {- target: connectRef,- title: 'Drive it from your code',- body: 'Reconnect to this exact box by id from your own app and keep working — same VM, same state.',- api: `Sandbox.connect("${id}")`,- code: [- {- label: 'SDK',- code: `import { Sandbox } from "@opencomputer/sdk";--const sandbox = await Sandbox.connect("${id}");-const { stdout } = await sandbox.exec.run("echo hello from code");`,- },- { label: 'CLI', code: `oc shell ${id}` },- ],- docs: 'https://docs.opencomputer.dev/sandboxes/overview',- }- // Lead with the step matching the chip that launched this box.- if (webApp || exposePort) return [stepCreate, stepExpose, stepExec, stepConnect]- if (focusConnect) return [stepCreate, stepConnect, stepExec, stepExpose]- if (startupCommand) return [stepCreate, stepExec, stepExpose, stepConnect]- return [stepCreate, stepExec, stepExpose, stepConnect]- }, [sandboxId, webApp, exposePort, focusConnect, startupCommand])-- // On arrival from an example chip: open the terminal (so the startup command- // has somewhere to run) and wipe history state so a refresh doesn't re-fire.- useEffect(() => {- if (startupCommand) setShowTerminal(true)- if (location.state) window.history.replaceState({}, '')- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [])-- const { data: session, isLoading } = useQuery({- queryKey: ['sandbox-detail', sandboxId],- queryFn: () => getSandboxDetail(sandboxId!),- enabled: !!sandboxId,- // A just-created sandbox is briefly not-yet-queryable on the cell (create- // returns before the read path is consistent, so the detail GET 404s for a- // few seconds). Retry a 404 through the boot window — the skeleton stays up- // instead of flashing "Sandbox not found" — then give up for a real 404.- retry: (failureCount, error) =>- failureCount < 10 && error instanceof ApiError && error.status === 404,- retryDelay: 1000,- })-- const { data: stats } = useQuery({- queryKey: ['sandbox-stats', sandboxId],- queryFn: () => getSandboxStats(sandboxId!),- enabled: !!sandboxId && session?.status === 'running',- refetchInterval: 5000,- retry: false,- })-- const invalidate = () => {- void queryClient.invalidateQueries({- queryKey: ['sandbox-detail', sandboxId],- })- void queryClient.invalidateQueries({- queryKey: ['sandbox-stats', sandboxId],- })- void queryClient.invalidateQueries({ queryKey: ['sandboxes'] })- }-- const deleteMutation = useMutation({- mutationFn: () => deleteSandbox(sandboxId!),- onMutate: async () => {- await queryClient.cancelQueries({- queryKey: ['sandbox-detail', sandboxId],- })- const stoppedAt = new Date().toISOString()- queryClient.setQueryData<SessionDetailData>(- ['sandbox-detail', sandboxId],- (old) => (old ? { ...old, status: 'stopped', stoppedAt } : old),- )- queryClient.setQueriesData<Sandbox[]>(- { queryKey: ['sandboxes'] },- (old) =>- old?.map((item) =>- item.sandboxId === sandboxId- ? { ...item, status: 'stopped', stoppedAt }- : item,- ),- )- setShowTerminal(false)- },- onError: (e) => notifyError("Couldn't delete the sandbox.", e),- onSettled: invalidate,- })-- const rebootMutation = useMutation({- mutationFn: () => rebootSandbox(sandboxId!),- onError: (e) => notifyError("Couldn't reboot the sandbox.", e),- onSettled: invalidate,- })-- const powerCycleMutation = useMutation({- mutationFn: () => powerCycleSandbox(sandboxId!),- onError: (e) => notifyError("Couldn't power-cycle the sandbox.", e),- onSettled: invalidate,- })-- const createPreviewMutation = useMutation({- mutationFn: (port: number) => createPreviewUrl(sandboxId!, port),- onSuccess: () =>- queryClient.invalidateQueries({- queryKey: ['sandbox-detail', sandboxId],- }),- onError: (e) => notifyError("Couldn't expose the port.", e),- })-- const deletePreviewMutation = useMutation({- mutationFn: (port: number) => deletePreviewUrl(sandboxId!, port),- onSuccess: () =>- queryClient.invalidateQueries({- queryKey: ['sandbox-detail', sandboxId],- }),- onError: (e) => notifyError("Couldn't remove the preview URL.", e),- })-- const copyTimer = useRef<ReturnType<typeof setTimeout> | null>(null)- useEffect(- () => () => {- if (copyTimer.current) clearTimeout(copyTimer.current)- },- [],- )-- // "Drive it from code" chip: once the sandbox has loaded, bring the Connect- // panel into view so the SDK snippets are the first thing you see.- useEffect(() => {- if (focusConnect && !scrolledRef.current && session && connectRef.current) {- scrolledRef.current = true- connectRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })- }- }, [focusConnect, session])-- // "Host a web app" chip: once the box is running, auto-expose the port so the- // Preview URLs section fills in with a real clickable link (skip if one for- // that port already exists).- useEffect(() => {- if (exposedRef.current || !exposePort || session?.status !== 'running')- return- exposedRef.current = true- const existing = session.previewUrls?.find((u) => u.port === exposePort)- if (existing) {- if (webApp) {- setStartupCommand(buildWebAppCommand(existing.hostname))- setShowTerminal(true)- }- return- }- createPreviewMutation.mutate(exposePort, {- onSuccess: (pv) => {- if (webApp && pv?.hostname) {- setStartupCommand(buildWebAppCommand(pv.hostname))- setShowTerminal(true)- }- },- })- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [exposePort, session])-- const copyUrl = (hostname: string, key: string) => {- void navigator.clipboard.writeText(`https://${hostname}`).then(- () => {- setCopiedUrl(key)- if (copyTimer.current) clearTimeout(copyTimer.current)- copyTimer.current = setTimeout(() => setCopiedUrl(null), 2000)- },- (e: unknown) => notifyError("Couldn't copy to clipboard.", e),- )- }-- if (isLoading) {- return (- <div>- <Link- to="/sandboxes"- className="text-muted-foreground hover:text-foreground mb-5 inline-flex items-center gap-1.5 text-sm transition-colors"- >- <ArrowLeft className="size-4" />- Back to Sandboxes- </Link>- <Panel className="p-8">- <div className="flex flex-col items-center justify-center gap-3 py-6 text-center">- <Loader2 className="text-muted-foreground size-6 animate-spin" />- <div className="space-y-1">- <p className="text-foreground text-sm font-medium">- Provisioning your sandbox…- </p>- <p className="text-muted-foreground text-xs">- Booting a fresh cloud VM- {sandboxId ? ` · ${sandboxId}` : ''}…- </p>- </div>- </div>- </Panel>- </div>- )- }-- if (!session) {- return (- <Panel>- <EmptyState- title="Sandbox not found"- description="This sandbox may have been deleted."- action={- <Button- variant="outline"- onClick={() => void navigate('/sandboxes')}- >- Back to Sandboxes- </Button>- }- />- </Panel>- )- }-- const isRunning = session.status === 'running'- const canDelete = isRunning || session.status === 'hibernated'- const busy =- rebootMutation.isPending ||- powerCycleMutation.isPending ||- deleteMutation.isPending-- return (- <div>- <Link- to="/sandboxes"- className="text-muted-foreground hover:text-foreground mb-5 inline-flex items-center gap-1.5 text-sm transition-colors"- >- <ArrowLeft className="size-4" />- Back to Sandboxes- </Link>-- <GuidedTour- steps={guideSteps}- open={guideOpen}- onClose={() => setGuideOpen(false)}- />-- {/* Header */}- <Panel ref={headerRef} className="mb-4 p-6">- <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">- <div className="min-w-0">- <div className="flex flex-wrap items-center gap-3">- <code className="text-foreground font-mono text-lg font-semibold">- {session.sandboxId}- </code>- <StatusBadge status={session.status} />- </div>- <div className="text-muted-foreground mt-1 text-sm">- {session.template || 'base'} · Started{' '}- {timeAgo(session.startedAt)}- </div>- </div>-- <div className="flex flex-wrap gap-2">- <Button- variant="ghost"- size="sm"- className="text-muted-foreground"- onClick={() => setGuideOpen(true)}- >- <Sparkles className="size-4" />- How it works- </Button>- <Button- variant={showLogs ? 'default' : 'outline'}- size="sm"- onClick={() => setShowLogs((v) => !v)}- >- <List className="size-4" />- Logs- </Button>- {isRunning ? (- <>- <Button- ref={terminalBtnRef}- variant={showTerminal ? 'default' : 'outline'}- size="sm"- onClick={() => setShowTerminal((v) => !v)}- >- <SquareTerminal className="size-4" />- Terminal- </Button>- <Button- variant="outline"- size="sm"- disabled={busy}- onClick={() => setConfirm('reboot')}- >- <RotateCcw className="size-4" />- {rebootMutation.isPending ? 'Rebooting…' : 'Reboot'}- </Button>- <Button- variant="outline"- size="sm"- disabled={busy}- onClick={() => setConfirm('power-cycle')}- >- <Power className="size-4" />- {powerCycleMutation.isPending- ? 'Power-cycling…'- : 'Power cycle'}- </Button>- </>- ) : null}- {canDelete ? (- <Button- size="sm"- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"- disabled={busy}- onClick={() => setConfirm('delete')}- >- <Trash2 className="size-4" />- Delete- </Button>- ) : null}- </div>- </div>- </Panel>-- {showTerminal && isRunning ? (- <div className="mb-4">- <Suspense fallback={<PanelLoading />}>- <Terminal- sandboxId={sandboxId!}- startupCommand={startupCommand}- onStarted={() => setStartupCommand(undefined)}- onClose={() => setShowTerminal(false)}- />- </Suspense>- </div>- ) : null}-- {showLogs ? (- <div className="mb-4">- <Suspense fallback={<PanelLoading />}>- <LogsPanel- sandboxId={sandboxId!}- onClose={() => setShowLogs(false)}- />- </Suspense>- </div>- ) : null}-- {/* Resource usage */}- {isRunning ? (- <div className="mb-4 grid grid-cols-2 gap-4 lg:grid-cols-4">- <MetricCard- label="CPU"- value={stats ? `${stats.cpuPercent.toFixed(1)}%` : '—'}- />- <MetricCard- label="Memory"- value={stats ? formatBytes(stats.memUsage) : '—'}- hint={stats ? `of ${formatBytes(stats.memLimit)}` : undefined}- />- <MetricCard- label="Processes"- value={stats ? String(stats.pids) : '—'}- />- <MetricCard- label="Network"- value={stats ? `↑${formatBytes(stats.netOutput)}` : '—'}- hint={stats ? `↓${formatBytes(stats.netInput)}` : undefined}- />- </div>- ) : null}-- {/* Preview URLs — expose a port to get a public https URL */}- {isRunning || (session.previewUrls?.length ?? 0) > 0 ? (- <Panel ref={previewRef} className="mb-4 p-6">- <h2 className="mb-3 text-sm font-semibold">Preview URLs</h2>- {session.previewUrls && session.previewUrls.length > 0 ? (- <div className="space-y-2">- {session.previewUrls.map((url) => {- const host = url.customHostname || url.hostname- return (- <PreviewUrlRow- key={url.id}- port={url.port}- host={host}- copied={copiedUrl === `${url.port}`}- onCopy={() => copyUrl(host, `${url.port}`)}- onRemove={- isRunning- ? () => deletePreviewMutation.mutate(url.port)- : undefined- }- removing={- deletePreviewMutation.isPending &&- deletePreviewMutation.variables === url.port- }- />- )- })}- </div>- ) : (- <p className="text-muted-foreground text-sm">- No ports exposed yet — start a server in the sandbox, then expose- its port to get a public URL.- </p>- )}-- {isRunning ? (- <form- className="mt-3 flex items-center gap-2"- onSubmit={(e) => {- e.preventDefault()- const port = Number(portInput)- if (Number.isInteger(port) && port >= 1 && port <= 65535) {- createPreviewMutation.mutate(port, {- onSuccess: () => setPortInput(''),- })- }- }}- >- <Input- type="number"- min={1}- max={65535}- placeholder="Port (e.g. 8000)"- value={portInput}- onChange={(e) => setPortInput(e.target.value)}- className="w-44"- />- <Button- type="submit"- variant="outline"- size="sm"- disabled={createPreviewMutation.isPending || !portInput}- >- {createPreviewMutation.isPending ? 'Exposing…' : 'Expose port'}- </Button>- </form>- ) : null}-- {session.previewUrls &&- session.previewUrls.some((u) => u.customHostname) ? (- <div className="mt-3">- <button- onClick={() => setShowInternal((v) => !v)}- className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-xs transition-colors"- >- <ChevronRight- className={`size-3.5 transition-transform ${showInternal ? 'rotate-90' : ''}`}- />- Internal URLs- </button>- {showInternal ? (- <div className="mt-2 space-y-2">- {session.previewUrls.map((url) => (- <PreviewUrlRow- key={`int-${url.id}`}- port={url.port}- host={url.hostname}- copied={copiedUrl === `int-${url.port}`}- onCopy={() => copyUrl(url.hostname, `int-${url.port}`)}- />- ))}- </div>- ) : null}- </div>- ) : null}- </Panel>- ) : null}-- {/* Connect — shell in / drive from code */}- <div ref={connectRef} className="mb-4 scroll-mt-6">- <ConnectPanel sandboxId={session.sandboxId} />- </div>-- {/* Details */}- <Panel className="mb-4 p-6">- <h2 className="mb-4 text-sm font-semibold">Details</h2>- <dl className="grid grid-cols-1 gap-x-8 gap-y-4 sm:grid-cols-2">- <Detail label="Template" value={session.template || 'base'} />- <Detail- label="Timeout"- value={`${session.config?.timeout ?? 300}s`}- />- <Detail label="CPUs" value={String(session.config?.cpuCount ?? 1)} />- <Detail- label="Memory"- value={`${session.config?.memoryMB ?? 512} MB`}- />- <Detail- label="Started"- value={new Date(session.startedAt).toLocaleString()}- />- {session.stoppedAt ? (- <Detail- label="Stopped"- value={new Date(session.stoppedAt).toLocaleString()}- />- ) : null}- {session.errorMsg ? (- <Detail label="Error" value={session.errorMsg} error />- ) : null}- </dl>- </Panel>-- {/* Checkpoint */}- {session.checkpoint ? (- <Panel className="p-6">- <h2 className="mb-4 text-sm font-semibold">Checkpoint</h2>- <dl className="grid grid-cols-1 gap-x-8 gap-y-4 sm:grid-cols-2">- <Detail- label="Size"- value={formatBytes(session.checkpoint.sizeBytes)}- />- <Detail- label="Hibernated"- value={new Date(session.checkpoint.hibernatedAt).toLocaleString()}- />- </dl>- </Panel>- ) : null}-- <ConfirmDialog- open={confirm === 'reboot'}- onOpenChange={(o) => !o && setConfirm(null)}- title="Reboot this sandbox?"- description="The guest kernel restarts. Running processes are killed; workspace data is preserved. Takes a few seconds."- confirmLabel="Reboot"- pending={rebootMutation.isPending}- onConfirm={() =>- rebootMutation.mutate(undefined, {- onSuccess: () => setConfirm(null),- })- }- />- <ConfirmDialog- open={confirm === 'power-cycle'}- onOpenChange={(o) => !o && setConfirm(null)}- title="Power-cycle this sandbox?"- description="The VM is destroyed and recreated with the same disks — use this if a reboot didn't recover. Workspace data is preserved; takes ~30 seconds."- confirmLabel="Power cycle"- pending={powerCycleMutation.isPending}- onConfirm={() =>- powerCycleMutation.mutate(undefined, {- onSuccess: () => setConfirm(null),- })- }- />- <ConfirmDialog- open={confirm === 'delete'}- onOpenChange={(o) => !o && setConfirm(null)}- title={`Delete sandbox ${session.sandboxId}?`}- description="The sandbox will be stopped and its preview URLs removed."- confirmLabel="Delete sandbox"- destructive- pending={deleteMutation.isPending}- onConfirm={() =>- deleteMutation.mutate(undefined, {- onSuccess: () => setConfirm(null),- })- }- />- </div>- )-}--// Dark fallback while a lazy panel (Terminal / Logs) chunk loads.-function PanelLoading() {- return (- <div className="bg-terminal border-code-border flex h-40 items-center justify-center rounded-lg border">- <Loader2 className="text-code-muted size-5 animate-spin" />- </div>- )-}--function PreviewUrlRow({- port,- host,- copied,- onCopy,- onRemove,- removing,-}: {- port: number- host: string- copied: boolean- onCopy: () => void- onRemove?: () => void- removing?: boolean-}) {- return (- <div className="flex items-center gap-3">- <span className="text-muted-foreground w-12 shrink-0 font-mono text-xs">- :{port}- </span>- <a- href={`https://${host}`}- target="_blank"- rel="noopener noreferrer"- className="bg-panel-2 text-foreground flex-1 truncate rounded-md border px-3 py-2 font-mono text-[13px] hover:underline"- >- https://{host}- </a>- <Button variant="ghost" size="sm" onClick={onCopy}>- {copied ? 'Copied' : 'Copy'}- </Button>- {onRemove ? (- <Button- variant="ghost"- size="sm"- onClick={onRemove}- disabled={removing}- className="text-muted-foreground"- >- {removing ? '…' : 'Remove'}- </Button>- ) : null}- </div>- )-}--function Detail({- label,- value,- error,-}: {- label: string- value: string- error?: boolean-}) {- return (- <div>- <dt className="text-muted-foreground text-xs">{label}</dt>- <dd- className={`font-mono text-[13px] break-all ${error ? 'text-status-error' : 'text-foreground'}`}- >- {value}- </dd>- </div>- )-}diff --git a/web/src/pages/SandboxWebhooks.tsx b/web/src/pages/SandboxWebhooks.tsxdeleted file mode 100644index 47fea32d..00000000--- a/web/src/pages/SandboxWebhooks.tsx+++ /dev/null@@ -1,429 +0,0 @@-import { useState } from 'react'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import {- Check,- ChevronRight,- Copy,- KeyRound,- Plus,- RotateCw,- Send,- Webhook,- X,-} from 'lucide-react'-import { notifyError } from '@/lib/errors'-import {- getSandboxWebhooks,- createSandboxWebhook,- deleteSandboxWebhook,- testSandboxWebhook,- getSandboxWebhookDeliveries,- getSandboxWebhookSecret,- redeliverSandboxWebhook,- type SandboxWebhook,-} from '@/api/client'-import { PageHeader } from '@/components/page-header'-import { Panel } from '@/components/panel'-import { Button } from '@/components/ui/button'-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from '@/components/ui/dialog'-import { Field, Input, Label } from '@/components/form'-import { Checkbox } from '@/components/ui/checkbox'-import { StatusBadge } from '@/components/status-badge'-import { EmptyState } from '@/components/empty-state'-import { ConfirmDialog } from '@/components/confirm-dialog'-import { cn } from '@/lib/utils'--// The event taxonomy's sandbox-plane counterpart (pkg/types/webhook.go).-// Empty selection = every event.-const SANDBOX_EVENT_TYPES = [- { value: 'sandbox.created', label: 'Created' },- { value: 'sandbox.ready', label: 'Ready' },- { value: 'sandbox.hibernated', label: 'Hibernated' },- { value: 'sandbox.resumed', label: 'Resumed' },- { value: 'sandbox.stopped', label: 'Stopped' },- { value: 'sandbox.migrated', label: 'Migrated' },- { value: 'sandbox.checkpoint.created', label: 'Checkpoint created' },- { value: 'sandbox.forked', label: 'Forked' },- { value: 'sandbox.scaled', label: 'Scaled' },- { value: 'sandbox.preview_url.changed', label: 'Preview URL changed' },-]--export default function SandboxWebhooks() {- const queryClient = useQueryClient()- const { data: webhooks, isLoading } = useQuery({- queryKey: ['sandbox-webhooks'],- queryFn: getSandboxWebhooks,- })-- const [showAdd, setShowAdd] = useState(false)- const [url, setUrl] = useState('')- const [name, setName] = useState('')- const [selectedTypes, setSelectedTypes] = useState<Set<string>>(new Set())- const [expanded, setExpanded] = useState<Set<string>>(new Set())- const [toDelete, setToDelete] = useState<SandboxWebhook | null>(null)-- const toggleType = (v: string) =>- setSelectedTypes((prev) => {- const next = new Set(prev)- if (next.has(v)) next.delete(v)- else next.add(v)- return next- })- const toggleExpand = (id: string) =>- setExpanded((prev) => {- const next = new Set(prev)- if (next.has(id)) next.delete(id)- else next.add(id)- return next- })-- const invalidate = () =>- void queryClient.invalidateQueries({ queryKey: ['sandbox-webhooks'] })-- const addMutation = useMutation({- mutationFn: () =>- createSandboxWebhook({- url: url.trim(),- name: name.trim() || undefined,- eventTypes: selectedTypes.size ? Array.from(selectedTypes) : undefined,- }),- onSuccess: () => {- setShowAdd(false)- setUrl('')- setName('')- setSelectedTypes(new Set())- invalidate()- },- onError: (e) => notifyError("Couldn't add the destination.", e),- })- const deleteMutation = useMutation({- mutationFn: (id: string) => deleteSandboxWebhook(id),- onSettled: invalidate,- onError: (e) => notifyError("Couldn't delete the destination.", e),- })- const testMutation = useMutation({- mutationFn: (id: string) => testSandboxWebhook(id),- onError: (e) => notifyError("Couldn't send the test event.", e),- })-- return (- <div>- <PageHeader- title="Webhooks"- description="Deliver sandbox lifecycle events (created, ready, stopped, …) to your endpoints, signed and retried."- api={{- method: 'POST',- path: '/api/webhooks',- sdk: 'Webhooks.create()',- docs: 'https://docs.opencomputer.dev/sandboxes/webhooks',- }}- actions={- <Button onClick={() => setShowAdd(true)}>- <Plus className="size-4" />- Add destination- </Button>- }- />-- <Panel className="overflow-hidden">- {isLoading ? (- <div className="text-muted-foreground px-4 py-6 text-sm">- Loading…- </div>- ) : (webhooks?.length ?? 0) === 0 ? (- <EmptyState- icon={Webhook}- title="No webhook destinations"- description="Add an endpoint to receive sandbox lifecycle events for your org."- action={- <Button size="sm" onClick={() => setShowAdd(true)}>- <Plus className="size-4" />- Add destination- </Button>- }- />- ) : (- <ul className="divide-y">- {webhooks?.map((w) => {- const isOpen = expanded.has(w.id)- return (- <li key={w.id}>- <div className="flex items-center gap-3 px-4 py-2.5">- <button- type="button"- onClick={() => toggleExpand(w.id)}- aria-expanded={isOpen}- className="flex min-w-0 flex-1 items-center gap-2 text-left"- >- <ChevronRight- className={cn(- 'size-3.5 shrink-0 opacity-60 transition-transform',- isOpen && 'rotate-90',- )}- />- <span className="min-w-0 flex-1 truncate">- {w.name ? (- <span className="text-foreground text-sm font-medium">- {w.name}{' '}- </span>- ) : null}- <code className="text-muted-foreground font-mono text-xs">- {w.url}- </code>- </span>- </button>- <span className="text-muted-foreground hidden text-xs sm:inline">- {w.eventTypes?.length- ? `${w.eventTypes.length} event${w.eventTypes.length > 1 ? 's' : ''}`- : 'All events'}- </span>- <StatusBadge- status={w.enabled ? 'active' : 'paused'}- label={w.enabled ? 'Enabled' : 'Paused'}- />- <Button- variant="ghost"- size="sm"- onClick={() => testMutation.mutate(w.id)}- disabled={testMutation.isPending}- >- <Send className="size-3.5" />- Test- </Button>- <Button- variant="ghost"- size="icon-sm"- aria-label="Delete destination"- className="text-muted-foreground hover:text-status-error"- onClick={() => setToDelete(w)}- >- <X className="size-4" />- </Button>- </div>-- {isOpen ? (- <div className="bg-panel-2/40 border-t px-4 py-2 pl-9">- {w.eventTypes?.length ? (- <p className="text-muted-foreground mb-1.5 font-mono text-[11px]">- {w.eventTypes.join(', ')}- </p>- ) : null}- <SecretReveal webhookId={w.id} />- <Deliveries webhookId={w.id} />- </div>- ) : null}- </li>- )- })}- </ul>- )}- </Panel>-- {/* Add dialog */}- <Dialog open={showAdd} onOpenChange={setShowAdd}>- <DialogContent>- <DialogHeader>- <DialogTitle>Add destination</DialogTitle>- <DialogDescription>- Sandbox lifecycle events for your org are delivered to this HTTPS- endpoint. A signing secret is generated automatically — reveal it- from the destination after you add it.- </DialogDescription>- </DialogHeader>- <form- className="space-y-4"- onSubmit={(e) => {- e.preventDefault()- if (url.trim()) addMutation.mutate()- }}- >- <Field label="Endpoint URL" htmlFor="swh-url">- <Input- id="swh-url"- value={url}- onChange={(e) => setUrl(e.target.value)}- placeholder="https://example.com/hooks/sandbox"- />- </Field>- <Field- label="Name"- htmlFor="swh-name"- description="Optional — a label to recognize this destination."- >- <Input- id="swh-name"- value={name}- onChange={(e) => setName(e.target.value)}- placeholder="Prod ingest"- />- </Field>- <div className="space-y-2">- <Label>Event types</Label>- <p className="text-muted-foreground text-xs">- Leave all unchecked to receive every event.- </p>- <div className="grid grid-cols-2 gap-2 pt-0.5">- {SANDBOX_EVENT_TYPES.map((t) => (- <label- key={t.value}- htmlFor={`swh-et-${t.value}`}- className="flex cursor-pointer items-center gap-2 text-sm"- >- <Checkbox- id={`swh-et-${t.value}`}- checked={selectedTypes.has(t.value)}- onCheckedChange={() => toggleType(t.value)}- />- {t.label}- </label>- ))}- </div>- </div>- <DialogFooter className="mt-2">- <Button- type="button"- variant="ghost"- onClick={() => setShowAdd(false)}- >- Cancel- </Button>- <Button- type="submit"- disabled={addMutation.isPending || !url.trim()}- >- {addMutation.isPending ? 'Adding…' : 'Add destination'}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>-- <ConfirmDialog- open={toDelete !== null}- onOpenChange={(open) => !open && setToDelete(null)}- title="Delete this destination?"- description="It stops receiving sandbox events. Delivery history is lost. This can't be undone."- confirmLabel="Delete destination"- destructive- pending={deleteMutation.isPending}- onConfirm={() => {- if (toDelete)- deleteMutation.mutate(toDelete.id, {- onSuccess: () => setToDelete(null),- })- }}- />- </div>- )-}--// Deliveries for one destination — lazy-loaded when its row is expanded.-function Deliveries({ webhookId }: { webhookId: string }) {- const queryClient = useQueryClient()- const { data: deliveries, isLoading } = useQuery({- queryKey: ['sandbox-webhook-deliveries', webhookId],- queryFn: () => getSandboxWebhookDeliveries(webhookId),- })- const redeliverMutation = useMutation({- mutationFn: (deliveryId: string) =>- redeliverSandboxWebhook(webhookId, deliveryId),- onSettled: () =>- void queryClient.invalidateQueries({- queryKey: ['sandbox-webhook-deliveries', webhookId],- }),- onError: (e) => notifyError("Couldn't redeliver.", e),- })-- if (isLoading)- return <p className="text-muted-foreground py-1 text-xs">Loading…</p>- if ((deliveries?.length ?? 0) === 0)- return (- <p className="text-muted-foreground py-1 text-xs">No deliveries yet.</p>- )-- return (- <ul className="divide-border/50 divide-y">- {deliveries?.map((d) => (- <li key={d.id} className="flex items-center gap-3 py-1.5 text-xs">- <StatusBadge status={d.status ?? 'pending'} />- <span className="text-muted-foreground font-mono">- {d.responseStatusCode ?? '—'}- </span>- <span className="text-muted-foreground truncate">- {d.timestamp ? new Date(d.timestamp).toLocaleString() : ''}- </span>- <span className="flex-1" />- {d.status === 'failed' ? (- <Button- variant="ghost"- size="sm"- onClick={() => redeliverMutation.mutate(d.id)}- disabled={redeliverMutation.isPending}- >- <RotateCw className="size-3.5" />- Redeliver- </Button>- ) : null}- </li>- ))}- </ul>- )-}--// Reveal + copy a destination's signing secret (Svix generates it; re-fetchable-// any time, like the Svix App Portal). Verify request signatures against it.-function SecretReveal({ webhookId }: { webhookId: string }) {- const [secret, setSecret] = useState<string | null>(null)- const [copied, setCopied] = useState(false)- const reveal = useMutation({- mutationFn: () => getSandboxWebhookSecret(webhookId),- onSuccess: setSecret,- onError: (e) => notifyError("Couldn't reveal the signing secret.", e),- })-- if (!secret) {- return (- <Button- variant="ghost"- size="sm"- className="mb-1.5 -ml-2"- onClick={() => reveal.mutate()}- disabled={reveal.isPending}- >- <KeyRound className="size-3.5" />- {reveal.isPending ? 'Revealing…' : 'Reveal signing secret'}- </Button>- )- }-- return (- <div className="mb-1.5 flex items-center gap-2">- <code className="bg-panel min-w-0 flex-1 truncate rounded border px-2 py-1 font-mono text-[11px]">- {secret}- </code>- <Button- variant="ghost"- size="icon-sm"- aria-label="Copy signing secret"- onClick={() => {- void navigator.clipboard.writeText(secret)- setCopied(true)- window.setTimeout(() => setCopied(false), 1500)- }}- >- {copied ? (- <Check className="size-3.5" />- ) : (- <Copy className="size-3.5" />- )}- </Button>- </div>- )-}diff --git a/web/src/pages/Sandboxes.tsx b/web/src/pages/Sandboxes.tsxdeleted file mode 100644index 65b3145d..00000000--- a/web/src/pages/Sandboxes.tsx+++ /dev/null@@ -1,328 +0,0 @@-import { useMemo, useState } from 'react'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import { Link } from 'react-router-dom'-import { Boxes } from 'lucide-react'-import { notifyError } from '@/lib/errors'-import { usePrefetchSandbox } from '@/hooks/use-prefetch'-import { deleteSandbox, getSandboxes, type Sandbox } from '@/api/client'-import { PageHeader } from '@/components/page-header'-import { Panel } from '@/components/panel'-import { Button } from '@/components/ui/button'-import { Skeleton } from '@/components/ui/skeleton'-import { StatusBadge } from '@/components/status-badge'-import { EmptyState } from '@/components/empty-state'-import { ConfirmDialog } from '@/components/confirm-dialog'-import { ResourceTable, type Column } from '@/components/resource-table'-import { cn } from '@/lib/utils'--const STATUS_FILTERS = [- { value: '', label: 'All' },- { value: 'running', label: 'Running' },- { value: 'stopped', label: 'Stopped' },- { value: 'hibernated', label: 'Hibernated' },- { value: 'error', label: 'Error' },-] as const--function canDeleteSession(session: Sandbox) {- return session.status === 'running' || session.status === 'hibernated'-}--export default function Sandboxes() {- const queryClient = useQueryClient()- const prefetch = usePrefetchSandbox()- const [status, setStatus] = useState<string>('')- const [toDelete, setToDelete] = useState<Sandbox | null>(null)-- const { data: sessions, isLoading } = useQuery({- queryKey: ['sandboxes', status],- queryFn: () => getSandboxes(status || undefined),- })-- // Always fetch all sessions for the activity chart.- const { data: allSessions, isLoading: loadingAll } = useQuery({- queryKey: ['sandboxes', ''],- queryFn: () => getSandboxes(),- })-- const deleteMutation = useMutation({- mutationFn: (sandboxId: string) => deleteSandbox(sandboxId),- onMutate: async (sandboxId) => {- await queryClient.cancelQueries({ queryKey: ['sandboxes'] })- const stoppedAt = new Date().toISOString()- queryClient.setQueriesData<Sandbox[]>(- { queryKey: ['sandboxes'] },- (old) =>- old?.map((session) =>- session.sandboxId === sandboxId- ? { ...session, status: 'stopped', stoppedAt }- : session,- ),- )- },- onError: (error) => notifyError("Couldn't delete the sandbox.", error),- onSettled: () => {- void queryClient.invalidateQueries({ queryKey: ['sandboxes'] })- },- })-- const confirmDelete = () => {- if (!toDelete) return- deleteMutation.mutate(toDelete.sandboxId, {- onSuccess: () => setToDelete(null),- })- }-- const columns: Column<Sandbox>[] = [- {- key: 'id',- header: 'Sandbox ID',- cell: (s) => (- <Link- to={`/sandboxes/${s.sandboxId}`}- onMouseEnter={() => prefetch(s.sandboxId)}- onFocus={() => prefetch(s.sandboxId)}- className="text-foreground font-mono text-[13px] underline-offset-4 hover:underline"- >- {s.sandboxId}- </Link>- ),- },- {- key: 'template',- header: 'Template',- cell: (s) => (- <span className="text-muted-foreground">{s.template || 'base'}</span>- ),- },- {- key: 'status',- header: 'Status',- cell: (s) => <StatusBadge status={s.status} />,- },- {- key: 'started',- header: 'Started',- cell: (s) => (- <span className="text-muted-foreground font-mono text-xs">- {new Date(s.startedAt).toLocaleString()}- </span>- ),- },- {- key: 'stopped',- header: 'Stopped',- cell: (s) => (- <span className="text-muted-foreground font-mono text-xs">- {s.stoppedAt ? new Date(s.stoppedAt).toLocaleString() : '—'}- </span>- ),- },- {- key: 'actions',- header: '',- align: 'right',- // Reserve the button height on every row so rows without a Delete action- // (stopped / error) aren't shorter than running / hibernated rows.- cell: (s) => (- <div className="flex h-7 items-center justify-end">- {canDeleteSession(s) ? (- <Button- variant="ghost"- size="sm"- className="text-status-error hover:text-destructive underline-offset-2 hover:bg-transparent hover:underline"- onClick={() => setToDelete(s)}- >- Delete- </Button>- ) : null}- </div>- ),- },- ]-- return (- <div>- <PageHeader- title="Sandboxes"- description="Active and recent sandboxes"- api={{- method: 'POST',- path: '/api/sandboxes',- sdk: 'Sandbox.create()',- docs: 'https://docs.opencomputer.dev/sandboxes/overview',- }}- />-- <ActivityChart sessions={allSessions ?? []} loading={loadingAll} />-- <div className="mb-4 flex flex-wrap gap-1.5">- {STATUS_FILTERS.map((f) => (- <Button- key={f.value}- size="sm"- variant={status === f.value ? 'default' : 'ghost'}- onClick={() => setStatus(f.value)}- >- {f.label}- </Button>- ))}- </div>-- <Panel className="overflow-hidden">- <ResourceTable- columns={columns}- rows={sessions ?? []}- rowKey={(s) => s.id}- loading={isLoading}- empty={- <EmptyState- icon={Boxes}- title="No sandboxes found"- description={- status- ? 'No sandboxes match this filter.'- : 'Sandboxes you start will show up here.'- }- />- }- />- </Panel>-- <ConfirmDialog- open={toDelete !== null}- onOpenChange={(open) => !open && setToDelete(null)}- title={`Delete sandbox ${toDelete?.sandboxId ?? ''}?`}- description="The sandbox will be stopped and its preview URLs removed."- confirmLabel="Delete sandbox"- destructive- pending={deleteMutation.isPending}- onConfirm={confirmDelete}- />- </div>- )-}--/* ── Activity chart (last 14 days) ──────────────────────────────────────────- Hand-built positioned divs (not recharts) — kept as a data-driven inline- geometry per the migration contract; only the chrome + colors are reskinned.- A recharts rebuild is a follow-up. */-function ActivityChart({- sessions,- loading,-}: {- sessions: Sandbox[]- loading: boolean-}) {- const { days, maxCount } = useMemo(() => {- const now = new Date()- const dayBuckets: {- label: string- date: string- count: number- hibernated: number- errored: number- }[] = []-- for (let i = 13; i >= 0; i--) {- const d = new Date(now)- d.setDate(d.getDate() - i)- const dateStr = d.toISOString().slice(0, 10)- dayBuckets.push({- label: d.toLocaleDateString('en-US', {- month: 'short',- day: 'numeric',- }),- date: dateStr,- count: 0,- hibernated: 0,- errored: 0,- })- }-- for (const s of sessions) {- const dateStr = new Date(s.startedAt).toISOString().slice(0, 10)- const bucket = dayBuckets.find((b) => b.date === dateStr)- if (bucket) {- bucket.count++- if (s.status === 'hibernated') bucket.hibernated++- else if (s.status === 'error') bucket.errored++- }- }-- const maxCount = Math.max(1, ...dayBuckets.map((b) => b.count))- return { days: dayBuckets, maxCount }- }, [sessions])-- const total = days.reduce((n, d) => n + d.count, 0)-- return (- <Panel className="mb-6 px-6 py-5">- <div className="mb-4 flex items-center justify-between">- <h2 className="text-sm font-semibold">Activity</h2>- <span className="text-muted-foreground font-mono text-xs">- Last 14 days- </span>- </div>-- {loading ? (- <Skeleton className="h-[150px] w-full" />- ) : (- <div className="relative">- {/* Accessible summary (chart is decorative; this conveys the data). */}- <p className="sr-only">- {total} sandboxes started in the last 14 days.- </p>-- {/* Y-axis */}- <div className="absolute top-0 bottom-6 left-0 flex w-8 flex-col justify-between">- <span className="text-muted-foreground font-mono text-[10px]">- {maxCount}- </span>- <span className="text-muted-foreground font-mono text-[10px]">- 0- </span>- </div>-- {/* Bars */}- <div className="ml-9 flex h-[120px] items-end gap-1" aria-hidden>- {days.map((day) => {- const barHeight =- maxCount > 0 ? Math.round((day.count / maxCount) * 110) : 0- return (- <div- key={day.date}- title={`${day.label}: ${day.count} sandboxes${- day.hibernated ? ` (${day.hibernated} hibernated)` : ''- }${day.errored ? ` (${day.errored} errors)` : ''}`}- className={cn(- 'bg-foreground/70 relative flex-1 rounded-t-sm transition-[height] duration-300',- day.count > 0 ? '' : 'bg-transparent',- )}- style={{ height: day.count > 0 ? Math.max(barHeight, 4) : 0 }}- >- {day.count > 0 && (- <span className="text-muted-foreground absolute -top-4 left-1/2 -translate-x-1/2 font-mono text-[9px] whitespace-nowrap">- {day.count}- </span>- )}- </div>- )- })}- </div>-- {/* X-axis */}- <div className="mt-1.5 ml-9 flex gap-1" aria-hidden>- {days.map((day, i) => (- <div- key={day.date}- className="text-muted-foreground flex-1 text-center font-mono text-[9px]"- >- {i % 2 === 0 ? day.label : ''}- </div>- ))}- </div>- </div>- )}- </Panel>- )-}diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsxindex a7e5a4ed..174ccf41 100644--- a/web/src/pages/Settings.tsx+++ b/web/src/pages/Settings.tsx@@ -184,7 +184,7 @@ export default function Settings() {<NavigationToggleid="infrastructure-enabled"label="Enable infrastructure"- description="Show sandboxes, checkpoints, templates, webhooks, and browsers."+ description="Show browsers."checked={user?.infrastructureEnabled ?? false}disabled={navigationMutation.isPending}onCheckedChange={(checked) =>diff --git a/web/src/pages/Templates.tsx b/web/src/pages/Templates.tsxdeleted file mode 100644index e8a4257a..00000000--- a/web/src/pages/Templates.tsx+++ /dev/null@@ -1,194 +0,0 @@-import { useState } from 'react'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import { Package } from 'lucide-react'-import { notifyError } from '@/lib/errors'-import { deleteSnapshot, getImages, type ImageCacheItem } from '@/api/client'-import { PageHeader } from '@/components/page-header'-import { Panel } from '@/components/panel'-import { Button } from '@/components/ui/button'-import { StatusBadge } from '@/components/status-badge'-import { EmptyState } from '@/components/empty-state'-import { ConfirmDialog } from '@/components/confirm-dialog'-import { ResourceTable, type Column } from '@/components/resource-table'--// Total over unknown backend data — a malformed/older manifest must not crash-// the page, so every field is guarded (no bare casts into .join()/.length).-function formatSteps(manifest: Record<string, unknown>): string {- const steps = Array.isArray(manifest?.steps)- ? (manifest.steps as Array<Record<string, unknown>>)- : []- if (steps.length === 0) return 'base'- const list = (v: unknown): string[] =>- Array.isArray(v) ? (v as string[]) : []- return steps- .map((s) => {- const t = typeof s?.type === 'string' ? s.type : ''- const args = (s?.args ?? {}) as Record<string, unknown>- switch (t) {- case 'apt_install':- return `apt: ${list(args.packages).join(', ') || '...'}`- case 'pip_install':- return `pip: ${list(args.packages).join(', ') || '...'}`- case 'run':- return `run: ${list(args.commands).length} cmd(s)`- case 'env': {- const vars = args.vars- const n =- vars && typeof vars === 'object' ? Object.keys(vars).length : 0- return `env: ${n} var(s)`- }- case 'workdir':- return `workdir: ${typeof args.path === 'string' ? args.path : '...'}`- case 'add_file':- return `file: ${typeof args.path === 'string' ? args.path : '...'}`- default:- return t || 'step'- }- })- .join(' + ')-}--export default function Templates() {- const queryClient = useQueryClient()- const [toDelete, setToDelete] = useState<ImageCacheItem | null>(null)-- const { data: images, isLoading } = useQuery({- queryKey: ['images'],- queryFn: () => getImages(),- })-- const deleteMutation = useMutation({- mutationFn: (name: string) => deleteSnapshot(name),- onError: (error) => notifyError("Couldn't delete the template.", error),- onSettled: () => queryClient.invalidateQueries({ queryKey: ['images'] }),- })-- const confirmDelete = () => {- if (!toDelete?.name) return- deleteMutation.mutate(toDelete.name, { onSuccess: () => setToDelete(null) })- }-- const columns: Column<ImageCacheItem>[] = [- {- key: 'name',- header: 'Name',- cell: (img) =>- img.name ? (- <span className="text-foreground font-medium">{img.name}</span>- ) : (- <span className="text-muted-foreground italic">auto-cached</span>- ),- },- {- key: 'steps',- header: 'Steps',- cell: (img) => (- <span className="text-muted-foreground block max-w-[300px] truncate text-xs">- {formatSteps(img.manifest)}- </span>- ),- },- {- key: 'status',- header: 'Status',- cell: (img) => <StatusBadge status={img.status} />,- },- {- key: 'checkpoint',- header: 'Checkpoint',- cell: (img) =>- img.checkpointId ? (- <code className="font-mono text-xs">- {img.checkpointId.slice(0, 8)}- </code>- ) : (- <span className="text-muted-foreground">—</span>- ),- },- {- key: 'lastUsed',- header: 'Last used',- cell: (img) => (- <span className="text-muted-foreground font-mono text-xs">- {new Date(img.lastUsedAt).toLocaleString()}- </span>- ),- },- {- key: 'created',- header: 'Created',- cell: (img) => (- <span className="text-muted-foreground font-mono text-xs">- {new Date(img.createdAt).toLocaleString()}- </span>- ),- },- {- key: 'actions',- header: '',- align: 'right',- cell: (img) => (- <Button- variant="ghost"- size="sm"- className="text-status-error hover:text-destructive underline-offset-2 hover:bg-transparent hover:underline"- onClick={() => setToDelete(img)}- >- Delete- </Button>- ),- },- ]-- return (- <div>- <PageHeader- title="Templates"- description="Declarative image snapshots for your organization"- api={{- sdk: 'Templates.list()',- docs: 'https://docs.opencomputer.dev/sandboxes/templates',- }}- />-- <Panel className="overflow-hidden">- <ResourceTable- columns={columns}- rows={images ?? []}- rowKey={(img) => img.id}- loading={isLoading}- empty={- <EmptyState- icon={Package}- title="No templates yet"- description={- <>- Create one with the SDK using{' '}- <code className="bg-muted text-foreground rounded px-1.5 py-0.5 font-mono text-xs">- Image.base().aptInstall([…])- </code>{' '}- or{' '}- <code className="bg-muted text-foreground rounded px-1.5 py-0.5 font-mono text-xs">- snapshots.create()- </code>- .- </>- }- />- }- />- </Panel>-- <ConfirmDialog- open={toDelete !== null}- onOpenChange={(open) => !open && setToDelete(null)}- title={`Delete ${toDelete?.name ? `"${toDelete.name}"` : 'this cached image'}?`}- description="Existing sandboxes will not be affected."- confirmLabel="Delete template"- destructive- pending={deleteMutation.isPending}- onConfirm={confirmDelete}- />- </div>- )-}diff --git a/web/src/pages/getting-started.test.tsx b/web/src/pages/getting-started.test.tsxindex 0f982b3d..e9666d06 100644--- a/web/src/pages/getting-started.test.tsx+++ b/web/src/pages/getting-started.test.tsx@@ -31,15 +31,11 @@ function renderGettingStarted(path = '/') {}describe('getting started', () => {- it('shows the API key and the sandbox quickstart', () => {+ it('shows the API key without the retired sandbox quickstart', () => {const markup = renderGettingStarted()expect(markup).toContain('API key ready')- expect(markup).toContain('Sandboxes')- expect(markup).toContain('Sandbox.create()')- expect(markup).toContain('Open sandbox quickstart')- expect(markup).toContain('Run commands in an isolated computer.')- expect(markup).not.toContain('oc.sessions.create')- expect(markup).not.toContain('Durable agent sessions')+ expect(markup).not.toContain('Sandbox.create()')+ expect(markup).not.toContain('sandbox quickstart')})})diff --git a/web/vite.config.ts b/web/vite.config.tsindex 7b2fd6c8..709118a4 100644--- a/web/vite.config.ts+++ b/web/vite.config.ts@@ -64,14 +64,6 @@ const v3Proxy: Record<string, ProxyOptions> = v3Keyrewrite: (p) => p.replace(/^\/api\/dashboard/, ''),configure: injectKey,},- // Sandbox webhooks live at the prod public API (/api/webhooks/*).- '/api/dashboard/webhooks': {- target: v3Target,- changeOrigin: true,- rewrite: (p) =>- p.replace(/^\/api\/dashboard\/webhooks/, '/api/webhooks'),- configure: injectKey,- },}: {}