Skip to content

An open-source, faster Devin alternative

TypeScript

add more chips, adjust styling, add connect panel

Brian Reardond30f88c7de8b
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 2c6df874..cf8a3909 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -1039,6 +1039,31 @@ export async function handleDashboard(
if (!cell) return json({ error: "home cell unavailable" }, 503);
return proxyToCell(req, env, caller, cell, `/internal/dashboard${sub}`);
}
+
+ // ── sandboxes: one-click create from the dashboard → the org's home cell.
+ // Reuses the cap-token /internal/sandboxes/create path (same token shape the
+ // /api/sandboxes create mints); the cell stamps ownership from the token's org.
+ if (sub === "/sandboxes" && method === "POST") {
+ const cell = await homeCell(env, caller.orgID);
+ if (!cell) return json({ error: "home cell unavailable" }, 503);
+ return proxyToCell(req, env, caller, cell, "/internal/sandboxes/create");
+ }
+
+ // ── sandbox preview URLs: expose/list/unexpose a port on a running sandbox.
+ // Proxies to the public /api/sandboxes/:id/preview, which accepts this same
+ // edge cap-token (PGAPIKeyMiddleware validates it and sets the org), so no
+ // cell-side handler is needed. POST create, GET list, DELETE /:port unexpose.
+ {
+ const pv = sub.match(/^\/sandboxes\/([^/]+)\/preview(?:\/(\d+))?$/);
+ if (pv) {
+ const cell = await homeCell(env, caller.orgID);
+ if (!cell) return json({ error: "home cell unavailable" }, 503);
+ const cellPath = pv[2]
+ ? `/api/sandboxes/${pv[1]}/preview/${pv[2]}`
+ : `/api/sandboxes/${pv[1]}/preview`;
+ return proxyToCell(req, env, caller, cell, cellPath);
+ }
+ }
if (sub === "/billing/agent-subscriptions" && method === "GET") return handleListAgentSubscriptions(req, env, caller);
// /billing — basic billing read used by the dashboard billing page.
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index c298e172..f5785119 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -180,6 +180,35 @@ export const getSandboxes = (status?: string) =>
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))
diff --git a/web/src/components/Terminal.tsx b/web/src/components/Terminal.tsx
index d12660ed..a21a7208 100644
--- a/web/src/components/Terminal.tsx
+++ b/web/src/components/Terminal.tsx
@@ -9,14 +9,30 @@ 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 }: TerminalProps) {
+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')
@@ -122,6 +138,16 @@ export default function Terminal({ sandboxId, onClose }: TerminalProps) {
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) => {
diff --git a/web/src/components/connect-panel.tsx b/web/src/components/connect-panel.tsx
new file mode 100644
index 00000000..df09e3fc
--- /dev/null
+++ b/web/src/components/connect-panel.tsx
@@ -0,0 +1,130 @@
+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/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx
index c7f0ea40..a98b82d6 100644
--- a/web/src/pages/Dashboard.tsx
+++ b/web/src/pages/Dashboard.tsx
@@ -1,7 +1,17 @@
-import { useEffect, useRef, type ReactNode } from 'react'
+import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Link, useNavigate } from 'react-router-dom'
-import { Boxes, MessagesSquare, Sparkles } from 'lucide-react'
+import {
+ ArrowLeft,
+ BarChart3,
+ Boxes,
+ ChevronDown,
+ Code2,
+ Globe,
+ MessagesSquare,
+ Sparkles,
+ Terminal,
+} from 'lucide-react'
import {
createAPIKey,
getAPIKeys,
@@ -10,6 +20,9 @@ import {
getAgents,
createAgent,
createSession,
+ createSandbox,
+ getMe,
+ getBilling,
type Sandbox,
} from '@/api/client'
import type { Session } from '@/api/schemas'
@@ -42,6 +55,69 @@ function quicklaunchName(): string {
return `${pick(QL_ADJ)}-${pick(QL_NOUN)}`
}
+// Example tasks shown as chips on the launch card — concrete starting points so a
+// new user sees what the product actually does, instead of a blank button.
+const QUICKLAUNCH_TASKS: { icon: typeof BarChart3; label: string; task: string }[] = [
+ {
+ icon: BarChart3,
+ label: 'Analyze a CSV',
+ task: 'Create a small sample sales CSV, analyze it with Python, and produce a chart summarizing the key trends.',
+ },
+ {
+ icon: Globe,
+ label: 'Build a web app',
+ task: 'Build a small working single-page web app, start a dev server, and give me the preview URL so I can see it.',
+ },
+ {
+ icon: Terminal,
+ label: 'Write & run a script',
+ task: 'Write a short Python script that prints the current date/time and basic system info, then run it and show me the output.',
+ },
+]
+
+// Sandbox example chips. Unlike the agent chips (which are tasks for Claude), a
+// sandbox has no "task" — so each chip creates the box and lands you somewhere
+// useful: two auto-run a starter command in the terminal; "Drive it from code"
+// jumps to the Connect panel (SDK snippets). Commands lean on python3 (always
+// present on the base image) so the demo is self-contained — no external routing.
+// "Host a web app" is a webApp intent (not a static command): the sandbox page
+// exposes :8000, then builds the terminal command with the real preview hostname
+// so it can echo the live URL. See buildWebAppCommand in SandboxDetail.
+const SANDBOX_TRY_TOOL_CMD =
+ `echo "Python $(python3 --version 2>&1 | cut -d' ' -f2) · Node $(node --version) · $(uname -sr)" && echo "It's a real machine — try: pip install <pkg> or npm i <pkg>"`
+
+type SandboxIntent = {
+ startupCommand?: string
+ focus?: 'connect'
+ exposePort?: number
+ webApp?: boolean
+}
+const SANDBOX_EXAMPLES: {
+ icon: typeof Globe
+ label: string
+ intent: SandboxIntent
+}[] = [
+ {
+ icon: Globe,
+ label: 'Host a web app',
+ intent: { exposePort: 8000, webApp: true },
+ },
+ {
+ icon: Terminal,
+ label: 'Try a tool instantly',
+ intent: { startupCommand: SANDBOX_TRY_TOOL_CMD },
+ },
+ { icon: Code2, label: 'Drive it from code', intent: { focus: 'connect' } },
+]
+
+// Derive a friendly first name from an email local part (brian+test81@… → "Brian").
+function firstNameFromEmail(email: string | undefined): string {
+ if (!email) return ''
+ const local = email.split('@')[0]?.split('+')[0] ?? ''
+ const first = local.replace(/[._-]+/g, ' ').trim().split(' ')[0] ?? ''
+ return first ? first.charAt(0).toUpperCase() + first.slice(1) : ''
+}
+
function formatDuration(sandbox: Sandbox): string {
const start = new Date(sandbox.startedAt).getTime()
const end = sandbox.stoppedAt
@@ -73,6 +149,8 @@ const isLiveSession = (s: Session) =>
export default function Dashboard() {
const prefetch = usePrefetchSandbox()
+ // Returning users can re-open the getting-started screen from the header.
+ const [showGettingStarted, setShowGettingStarted] = useState(false)
const { data: runningSandboxesData, isLoading: loadingRunningSandboxes } =
useQuery({
@@ -116,6 +194,9 @@ export default function Dashboard() {
allSandboxes.length === 0 &&
sessions.length === 0
+ // Genuine first-run auto-shows onboarding; returning users opt in via the link.
+ const showOnboarding = isFirstRun || showGettingStarted
+
const sessionColumns: Column<Session>[] = [
{
key: 'id',
@@ -201,17 +282,27 @@ export default function Dashboard() {
return (
<div>
- <PageHeader
- title={isFirstRun ? 'Welcome to OpenComputer' : 'Dashboard'}
- description={
- isFirstRun
- ? 'Get started in two steps'
- : 'Overview of your agent sessions and sandboxes'
- }
- />
-
- {isFirstRun ? (
- <GettingStarted />
+ {!showOnboarding && (
+ <PageHeader
+ title="Dashboard"
+ description="Overview of your agent sessions and sandboxes"
+ actions={
+ <button
+ type="button"
+ onClick={() => setShowGettingStarted(true)}
+ className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5 text-sm underline-offset-4 hover:underline"
+ >
+ <Sparkles className="size-3.5" />
+ Getting started
+ </button>
+ }
+ />
+ )}
+
+ {showOnboarding ? (
+ <GettingStarted
+ onBack={!isFirstRun ? () => setShowGettingStarted(false) : undefined}
+ />
) : (
<div className="space-y-6">
<div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
@@ -295,7 +386,7 @@ export default function Dashboard() {
}
/* ── First-run onboarding ─────────────────────────────────────────────────── */
-function GettingStarted() {
+function GettingStarted({ onBack }: { onBack?: () => void }) {
const queryClient = useQueryClient()
const {
data: keys,
@@ -305,7 +396,10 @@ function GettingStarted() {
queryKey: ['api-keys'],
queryFn: getAPIKeys,
})
+ const { data: me } = useQuery({ queryKey: ['me'], queryFn: getMe })
+ const { data: billing } = useQuery({ queryKey: ['billing'], queryFn: getBilling })
const autoCreateRef = useRef(false)
+ const [showTerminal, setShowTerminal] = useState(false)
const navigate = useNavigate()
@@ -314,10 +408,11 @@ function GettingStarted() {
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['api-keys'] }),
})
- // One click: create a managed agent + start a session on it, then drop the
- // user straight onto the live session screen. No skill, no key, no terminal.
+ // One click: create a managed agent + start a session on it (with the given
+ // task), then drop the user straight onto the live session screen. No skill,
+ // no key, no terminal. The task varies by which chip/button the user picked.
const launchMutation = useMutation({
- mutationFn: async () => {
+ mutationFn: async (task: string) => {
const agent = await createAgent({
name: quicklaunchName(),
prompt: QUICKLAUNCH_PROMPT,
@@ -325,16 +420,40 @@ function GettingStarted() {
runtime: DEFAULT_RUNTIME,
credential: 'managed', // run via OpenComputer, billed to credits, no BYO key
})
- return createSession({ agent: agent.id, input: QUICKLAUNCH_TASK })
+ return createSession({ agent: agent.id, input: task })
},
onSuccess: (session) => {
void queryClient.invalidateQueries({ queryKey: ['agents'] })
void navigate(`/sessions/${session.id}`)
},
})
+ const launching = launchMutation.isPending
+
+ // Second door: create a real sandbox and drop into its live terminal. Goes
+ // through the CP (edge → home cell → /internal/sandboxes/create), so unlike
+ // the managed-agent path this works end to end today.
+ const createSandboxMutation = useMutation({
+ mutationFn: (_intent: SandboxIntent) =>
+ createSandbox({ memoryMB: 1024, cpuCount: 1, networkEnabled: true }),
+ onSuccess: (sb, intent) => {
+ void queryClient.invalidateQueries({ queryKey: ['sandboxes'] })
+ void navigate(`/sandboxes/${sb.sandboxID}`, {
+ state:
+ intent.startupCommand ||
+ intent.focus ||
+ intent.exposePort ||
+ intent.webApp
+ ? intent
+ : undefined,
+ })
+ },
+ })
+ const creatingSandbox = createSandboxMutation.isPending
const hasKeys = (keys?.length ?? 0) > 0
const createdKey = createMutation.data?.key ?? null
+ const firstName = firstNameFromEmail(me?.email)
+ const freeCents = billing?.freeCreditsRemainingCents ?? null
// On first signup (no keys), auto-create a Default key so the user sees it
// immediately without clicking anything.
@@ -349,7 +468,38 @@ function GettingStarted() {
}, [keysLoaded, hasKeys, createdKey, createMutation])
return (
- <div className="space-y-4">
+ <div className="space-y-5">
+ {onBack ? (
+ <button
+ type="button"
+ onClick={onBack}
+ className="text-muted-foreground hover:text-foreground -mb-1 inline-flex items-center gap-1.5 text-sm underline-offset-4 hover:underline"
+ >
+ <ArrowLeft className="size-3.5" />
+ Back to dashboard
+ </button>
+ ) : null}
+
+ {/* Personalized welcome + reassurance in the first paint */}
+ <div className="space-y-2">
+ <h2 className="text-foreground text-2xl font-semibold tracking-tight">
+ Welcome{firstName ? `, ${firstName}` : ''}.
+ </h2>
+ <p className="text-muted-foreground text-sm">
+ {freeCents != null && freeCents > 0
+ ? `You've got $${(freeCents / 100).toFixed(2)} in free credits — enough to run a real agent right now. No card, no setup.`
+ : 'Run a real Claude agent in a fresh sandbox — no setup, no API key required.'}
+ </p>
+ <div className="text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 pt-0.5 text-xs">
+ <span>Real Claude Opus</span>
+ <span aria-hidden>·</span>
+ <span>Isolated cloud VM</span>
+ <span aria-hidden>·</span>
+ <span>Watch it work live</span>
+ </div>
+ </div>
+
+ {/* Agent card — primary door, with concrete example tasks */}
<Panel className="p-5">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="space-y-1">
@@ -357,20 +507,41 @@ function GettingStarted() {
Launch an agent
</h3>
<p className="text-muted-foreground text-sm">
- Spin up a Claude agent in a fresh sandbox and watch it work — no
- setup, no API key. Runs on OpenComputer, billed to your credits.
+ Spin up a Claude agent in a fresh sandbox and watch it work —
+ billed to your credits, no API key.
</p>
</div>
<Button
size="lg"
className="shrink-0"
- onClick={() => launchMutation.mutate()}
- disabled={launchMutation.isPending}
+ onClick={() => launchMutation.mutate(QUICKLAUNCH_TASK)}
+ disabled={launching}
>
<Sparkles className="size-4" />
- {launchMutation.isPending ? 'Launching…' : 'Launch agent'}
+ {launching ? 'Launching…' : 'Launch agent'}
</Button>
</div>
+
+ <div className="border-border/60 mt-4 border-t pt-4">
+ <p className="text-muted-foreground mb-2 text-xs">
+ Or start with an example:
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {QUICKLAUNCH_TASKS.map((t) => (
+ <button
+ key={t.label}
+ type="button"
+ onClick={() => launchMutation.mutate(t.task)}
+ disabled={launching}
+ className="border-border bg-background hover:bg-secondary text-foreground inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50"
+ >
+ <t.icon className="size-3.5" />
+ {t.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
{launchMutation.isError ? (
<div className="mt-3 flex items-center gap-3">
<span className="text-status-error text-sm">
@@ -378,7 +549,9 @@ function GettingStarted() {
</span>
<button
className="text-foreground text-sm font-medium underline underline-offset-4"
- onClick={() => launchMutation.mutate()}
+ onClick={() =>
+ launchMutation.mutate(launchMutation.variables ?? QUICKLAUNCH_TASK)
+ }
>
Retry
</button>
@@ -386,72 +559,148 @@ function GettingStarted() {
) : null}
</Panel>
- <p className="text-muted-foreground px-1 text-xs">
- Or drive OpenComputer from your terminal:
- </p>
-
- <StepCard
- index={1}
- title="Install the OpenComputer skill"
- description="Adds OpenComputer controls to Claude Code so you can create and manage agents, sessions, and sandboxes from your terminal."
- >
- <CopyRow value={SKILL_INSTALL_CMD} />
- </StepCard>
-
- <StepCard
- index={2}
- title="Your API key"
- description="The skill uses this key to authenticate with OpenComputer. We've created a Default key for you — copy it now, you won't be able to see it again."
- >
- {loadingKeys || createMutation.isPending ? (
- <p className="text-muted-foreground text-sm">
- Preparing your API key…
- </p>
- ) : null}
-
- {createdKey ? (
- <div className="space-y-2.5">
- <CopyRow value={createdKey} maskable />
- <p className="text-muted-foreground text-xs">
- Then run this in your terminal to configure the CLI:
+ {/* Second door: a real sandbox — a full VM you drive yourself */}
+ <Panel className="p-5">
+ <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
+ <div className="space-y-1">
+ <h3 className="text-foreground text-base font-semibold">
+ Build with a sandbox
+ </h3>
+ <p className="text-muted-foreground text-sm">
+ Spin up a real cloud computer — a full Linux shell, files, and
+ ports — and drive it from the browser or your code.
</p>
- <CopyRow
- value={createdKey}
- maskable
- transform={(s) => `oc config set api-key ${s}`}
- />
</div>
- ) : null}
+ <Button
+ size="lg"
+ variant="outline"
+ className="shrink-0"
+ onClick={() => createSandboxMutation.mutate({})}
+ disabled={creatingSandbox}
+ >
+ <Boxes className="size-4" />
+ {creatingSandbox ? 'Creating…' : 'Create a sandbox'}
+ </Button>
+ </div>
- {!createdKey && !createMutation.isPending && hasKeys ? (
- <p className="text-muted-foreground text-sm">
- You already have {keys!.length} API key
- {keys!.length === 1 ? '' : 's'} from a previous session. For
- security, existing key values can&apos;t be re-displayed.{' '}
- <Link
- to="/api-keys"
- className="text-foreground font-medium underline underline-offset-4"
- >
- Manage keys
- </Link>{' '}
- to rotate.
- </p>
- ) : null}
+ <div className="border-border/60 mt-4 border-t pt-4">
+ <p className="text-muted-foreground mb-2 text-xs">Or jump straight in:</p>
+ <div className="flex flex-wrap gap-2">
+ {SANDBOX_EXAMPLES.map((ex) => (
+ <button
+ key={ex.label}
+ type="button"
+ onClick={() => createSandboxMutation.mutate(ex.intent)}
+ disabled={creatingSandbox}
+ className="border-border bg-background hover:bg-secondary text-foreground inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50"
+ >
+ <ex.icon className="size-3.5" />
+ {ex.label}
+ </button>
+ ))}
+ </div>
+ </div>
- {createMutation.isError ? (
- <div className="flex items-center gap-3">
+ <p className="text-muted-foreground mt-3 text-xs">
+ {creatingSandbox
+ ? 'Booting a fresh cloud VM — this can take 10–20s…'
+ : 'Ubuntu · Python & Node preinstalled · opens a live terminal'}
+ </p>
+ {createSandboxMutation.isError ? (
+ <div className="mt-3 flex items-center gap-3">
<span className="text-status-error text-sm">
- Failed to create your API key.
+ Couldn&apos;t create the sandbox.
</span>
<button
className="text-foreground text-sm font-medium underline underline-offset-4"
- onClick={() => createMutation.mutate()}
+ onClick={() => createSandboxMutation.mutate({})}
>
Retry
</button>
</div>
) : null}
- </StepCard>
+ </Panel>
+
+ {/* Terminal / power-user path — available, not the required first step */}
+ <div>
+ <button
+ type="button"
+ onClick={() => setShowTerminal((v) => !v)}
+ className="text-muted-foreground hover:text-foreground flex items-center gap-1.5 px-1 text-xs font-medium"
+ >
+ <ChevronDown
+ className={`size-3.5 transition-transform ${showTerminal ? '' : '-rotate-90'}`}
+ />
+ Prefer your terminal? Drive OpenComputer from Claude Code or the CLI
+ </button>
+
+ {showTerminal ? (
+ <div className="mt-3 space-y-4">
+ <StepCard
+ index={1}
+ title="Install the OpenComputer skill"
+ description="Adds OpenComputer controls to Claude Code so you can create and manage agents, sessions, and sandboxes from your terminal."
+ >
+ <CopyRow value={SKILL_INSTALL_CMD} />
+ </StepCard>
+
+ <StepCard
+ index={2}
+ title="Your API key"
+ description="The skill uses this key to authenticate with OpenComputer. We've created a Default key for you — copy it now, you won't be able to see it again."
+ >
+ {loadingKeys || createMutation.isPending ? (
+ <p className="text-muted-foreground text-sm">
+ Preparing your API key…
+ </p>
+ ) : null}
+
+ {createdKey ? (
+ <div className="space-y-2.5">
+ <CopyRow value={createdKey} maskable />
+ <p className="text-muted-foreground text-xs">
+ Then run this in your terminal to configure the CLI:
+ </p>
+ <CopyRow
+ value={createdKey}
+ maskable
+ transform={(s) => `oc config set api-key ${s}`}
+ />
+ </div>
+ ) : null}
+
+ {!createdKey && !createMutation.isPending && hasKeys ? (
+ <p className="text-muted-foreground text-sm">
+ You already have {keys!.length} API key
+ {keys!.length === 1 ? '' : 's'} from a previous session. For
+ security, existing key values can&apos;t be re-displayed.{' '}
+ <Link
+ to="/api-keys"
+ className="text-foreground font-medium underline underline-offset-4"
+ >
+ Manage keys
+ </Link>{' '}
+ to rotate.
+ </p>
+ ) : null}
+
+ {createMutation.isError ? (
+ <div className="flex items-center gap-3">
+ <span className="text-status-error text-sm">
+ Failed to create your API key.
+ </span>
+ <button
+ className="text-foreground text-sm font-medium underline underline-offset-4"
+ onClick={() => createMutation.mutate()}
+ >
+ Retry
+ </button>
+ </div>
+ ) : null}
+ </StepCard>
+ </div>
+ ) : null}
+ </div>
</div>
)
}
diff --git a/web/src/pages/SandboxDetail.tsx b/web/src/pages/SandboxDetail.tsx
index ebac8e31..c467713c 100644
--- a/web/src/pages/SandboxDetail.tsx
+++ b/web/src/pages/SandboxDetail.tsx
@@ -1,5 +1,5 @@
import { lazy, Suspense, useEffect, useRef, useState } from 'react'
-import { Link, useNavigate, useParams } from 'react-router-dom'
+import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { notifyError } from '@/lib/errors'
import {
@@ -13,6 +13,9 @@ import {
Loader2,
} from 'lucide-react'
import {
+ ApiError,
+ createPreviewUrl,
+ deletePreviewUrl,
deleteSandbox,
getSandboxDetail,
getSandboxStats,
@@ -26,13 +29,30 @@ const Terminal = lazy(() => import('@/components/Terminal'))
const LogsPanel = lazy(() => import('@/components/LogsPanel'))
import { Panel } from '@/components/panel'
import { Button } from '@/components/ui/button'
-import { Skeleton } from '@/components/ui/skeleton'
+import { Input } from '@/components/ui/input'
import { MetricCard } from '@/components/metric-card'
-import { CopyRow } from '@/components/copy-row'
+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']
@@ -55,6 +75,7 @@ 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)
@@ -63,10 +84,46 @@ export default function SandboxDetail() {
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)
+
+ // 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({
@@ -125,6 +182,24 @@ export default function SandboxDetail() {
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(
() => () => {
@@ -133,6 +208,41 @@ export default function SandboxDetail() {
[],
)
+ // "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(
() => {
@@ -146,9 +256,28 @@ export default function SandboxDetail() {
if (isLoading) {
return (
- <div className="space-y-4">
- <Skeleton className="h-28 w-full" />
- <Skeleton className="h-40 w-full" />
+ <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}` : ''}. This takes a few seconds.
+ </p>
+ </div>
+ </div>
+ </Panel>
</div>
)
}
@@ -266,6 +395,8 @@ export default function SandboxDetail() {
<Suspense fallback={<PanelLoading />}>
<Terminal
sandboxId={sandboxId!}
+ startupCommand={startupCommand}
+ onStarted={() => setStartupCommand(undefined)}
onClose={() => setShowTerminal(false)}
/>
</Suspense>
@@ -307,26 +438,76 @@ export default function SandboxDetail() {
</div>
) : null}
- {/* Preview URLs */}
- {session.previewUrls && session.previewUrls.length > 0 ? (
+ {/* Preview URLs — expose a port to get a public https URL */}
+ {isRunning || (session.previewUrls?.length ?? 0) > 0 ? (
<Panel className="mb-4 p-6">
<h2 className="mb-3 text-sm font-semibold">Preview URLs</h2>
- <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}`)}
- />
- )
- })}
- </div>
+ {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>
+ )}
- {session.previewUrls.some((u) => u.customHostname) ? (
+ {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)}
@@ -355,6 +536,11 @@ export default function SandboxDetail() {
</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>
@@ -383,12 +569,6 @@ export default function SandboxDetail() {
<Detail label="Error" value={session.errorMsg} error />
) : null}
</dl>
- {isRunning ? (
- <div className="mt-4 space-y-1.5">
- <div className="text-muted-foreground text-xs">CLI shell</div>
- <CopyRow value={`oc shell ${session.sandboxId}`} />
- </div>
- ) : null}
</Panel>
{/* Checkpoint */}
@@ -466,11 +646,15 @@ function PreviewUrlRow({
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">
@@ -488,6 +672,17 @@ function PreviewUrlRow({
<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>
)
}