An open-source, faster Devin alternative
TypeScript
create docs
Brian Reardonb3180cd6fff4
diff --git a/docs/sdks/python/templates.mdx b/docs/sdks/python/templates.mdxindex e683bb3f..ba8c8b86 100644--- a/docs/sdks/python/templates.mdx+++ b/docs/sdks/python/templates.mdx@@ -1,108 +1,377 @@---title: "Templates"-description: "Build and manage reusable sandbox templates"+description: "Define sandbox environments programmatically with the Image builder and Snapshots"----Templates let you create reusable sandbox images from Dockerfiles. Pre-install languages, tools, and dependencies so your sandboxes start ready to go.+Templates provide a code-first approach to defining sandbox environments. Instead of configuring images manually, you define them programmatically using the SDK.-## Building a Template+The system supports two workflows:++1. **Declarative images** — build images with varying dependencies _on demand_ when creating sandboxes+2. **Pre-built snapshots** — create and register _ready-to-use_ snapshots that can be shared across multiple sandboxes++## Declarative image building++Build images on-the-fly when creating sandboxes. Ideal for iterating quickly without creating separate snapshots.++Declarative images are **cached by content hash** — identical manifests produce the same image. Subsequent runs reuse the cached image instantly.```python-from opencomputer import Template+from opencomputer import Sandbox, Image++# Define an image with packages, env vars, and files+image = (+ Image.base()+ .apt_install(["curl", "jq"])+ .pip_install(["requests", "pandas"])+ .env({"PROJECT_ROOT": "/workspace"})+ .workdir("/workspace")+)++# Create a sandbox — the image is built on first run, cached after+sandbox = await Sandbox.create(+ image=image,+ timeout=300,+ on_build_log=lambda log: print(f"build: {log}"),+)++result = await sandbox.commands.run("which curl")+print(result.exit_code) # 0+```++### `Sandbox.create(image=..., on_build_log=...)`++When you pass an `image` to `Sandbox.create()`, the server:++1. Hashes the image manifest to compute a **cache key**+2. If cached, creates the sandbox from the existing checkpoint instantly+3. If not cached, boots a build sandbox, executes each step, checkpoints the result, then creates your sandbox from it++<ParamField body="image" type="Image" optional>+ A declarative image definition built with the `Image` builder.+</ParamField>+<ParamField body="on_build_log" type="Callable[[str], None]" optional>+ Callback for streaming build log messages via SSE. Receives step-by-step progress updates during image building.+</ParamField>-templates = Template(api_url, api_key)+## Creating pre-built snapshots-template = await templates.build('python-ml', """-FROM ubuntu:22.04-RUN apt-get update && apt-get install -y python3 python3-pip-RUN pip3 install numpy pandas scikit-learn-""")+Create named snapshots that persist permanently and can be shared across sandboxes. Snapshots are visible in the dashboard and don't need to be rebuilt.-print(template.template_id) # tpl-abc123-print(template.status) # building → ready+```python+from opencomputer import Image, Snapshots++snapshots = Snapshots()++# Define the image+image = (+ Image.base()+ .apt_install(["python3-pip"])+ .pip_install(["pandas", "numpy", "scikit-learn"])+ .workdir("/workspace")+)++# Create a named snapshot with build log streaming+await snapshots.create(+ name="data-science",+ image=image,+ on_build_logs=lambda log: print(f"build: {log}"),+)++# Now create sandboxes from the snapshot — instant, no build step+sandbox = await Sandbox.create(snapshot="data-science")```-### `await templates.build(name, dockerfile)`+### `Snapshots(api_key=..., api_url=...)`-Builds a new template from a Dockerfile.+<ParamField body="api_key" type="str" optional>+ API key. Falls back to `OPENCOMPUTER_API_KEY` env var.+</ParamField>+<ParamField body="api_url" type="str" optional>+ API base URL. Falls back to `OPENCOMPUTER_API_URL` env var.+</ParamField>++### `await snapshots.create(name, image, on_build_logs=None)`++Creates a pre-built snapshot from a declarative image.<ParamField body="name" type="str" required>- A unique name for the template.+ Unique name for this snapshot.</ParamField>-<ParamField body="dockerfile" type="str" required>- The Dockerfile content to build from.+<ParamField body="image" type="Image" required>+ Declarative image definition.</ParamField>+<ParamField body="on_build_logs" type="Callable[[str], None]" optional>+ Callback for streaming build log messages.+</ParamField>++**Returns:** `dict` with snapshot info (id, name, status, etc.)-**Returns:** `TemplateInfo`+### `await snapshots.list()`-## Listing Templates+Returns all named snapshots for the current organization.```python-all_templates = await templates.list()+snapshot_list = await snapshots.list()+for s in snapshot_list:+ print(f"{s['name']} — {s['status']}")+```-for t in all_templates:- print(f"{t.name} ({t.tag}) — {t.status}")+**Returns:** `list[dict]`++### `await snapshots.get(name)`++Gets a snapshot by name.++```python+snapshot = await snapshots.get("data-science")+print(snapshot["status"]) # "ready"```-### `await templates.list()`+<ParamField body="name" type="str" required>+ Snapshot name.+</ParamField>-Returns all templates.+**Returns:** `dict`-**Returns:** `list[TemplateInfo]`+### `await snapshots.delete(name)`-## Getting a Template+Deletes a named snapshot. Existing sandboxes created from it are not affected.```python-template = await templates.get('python-ml')-print(template)+await snapshots.delete("data-science")```-### `await templates.get(name)`+<ParamField body="name" type="str" required>+ Snapshot name to delete.+</ParamField>-Gets a template by name.+**Returns:** `None`-<ParamField body="name" type="str" required>- Template name.+### `Sandbox.create(snapshot=...)`++Create a sandbox from a pre-built snapshot by name.++```python+sandbox = await Sandbox.create(snapshot="data-science")+```++<ParamField body="snapshot" type="str" optional>+ Name of a pre-built snapshot to create the sandbox from.</ParamField>-**Returns:** `TemplateInfo`+**Returns:** `Sandbox`-## Deleting a Template+---++## Image configuration++The `Image` class provides a fluent, immutable API for defining sandbox environments. Each method returns a **new** `Image` instance — the original is never modified.++### `Image.base()`++Creates a new image starting from the default OpenSandbox environment (Ubuntu 22.04 with Python, Node.js, build tools, and common utilities).```python-await templates.delete('python-ml')+image = Image.base()```-### `await templates.delete(name)`+### `image.apt_install(packages)`-Deletes a template by name.+Install system packages via `apt-get`.-<ParamField body="name" type="str" required>- Template name to delete.+```python+image = Image.base().apt_install(["curl", "git", "jq"])+```++<ParamField body="packages" type="list[str]" required>+ List of apt package names to install.</ParamField>-**Returns:** `None`+### `image.pip_install(packages)`++Install Python packages via `pip`.++```python+image = Image.base().pip_install(["requests", "pandas", "numpy"])+```-## TemplateInfo+<ParamField body="packages" type="list[str]" required>+ List of pip package names to install.+</ParamField>++### `image.run_commands(*commands)`++Run one or more shell commands during image build.++```python+image = Image.base().run_commands(+ "mkdir -p /workspace/project",+ "echo 'Hello' > /workspace/welcome.txt",+)+```++<ParamField body="commands" type="str (variadic)" required>+ Shell commands to execute sequentially.+</ParamField>++### `image.env(vars)`++Set environment variables. Written to `/etc/environment` so they're available in all sessions.++```python+image = Image.base().env({+ "PROJECT_ROOT": "/workspace",+ "NODE_ENV": "production",+})+```++<ParamField body="vars" type="dict[str, str]" required>+ Key-value pairs of environment variables.+</ParamField>++### `image.workdir(path)`++Set the default working directory.++```python+image = Image.base().workdir("/workspace/project")+```++<ParamField body="path" type="str" required>+ Absolute path for the working directory.+</ParamField>++### `image.add_file(remote_path, content)`++Embed a file with inline content into the image.++```python+image = (+ Image.base()+ .add_file("/workspace/config.json", '{"env": "production"}')+ .add_file("/workspace/setup.sh", "#!/bin/bash\necho 'Ready!'")+)+```-`TemplateInfo` is a dataclass:+<ParamField body="remote_path" type="str" required>+ Absolute path inside the sandbox.+</ParamField>+<ParamField body="content" type="str" required>+ String content of the file.+</ParamField>++### `image.add_local_file(local_path, remote_path)`++Read a file from the local machine and embed it into the image.++```python+image = Image.base().add_local_file("package.json", "/workspace/package.json")+```++<ParamField body="local_path" type="str" required>+ Path to the file on the local machine.+</ParamField>+<ParamField body="remote_path" type="str" required>+ Absolute path inside the sandbox.+</ParamField>++### `image.add_local_dir(local_path, remote_path)`++Recursively read a local directory and embed all files into the image.++```python+image = Image.base().add_local_dir("src", "/workspace/src")+```++<ParamField body="local_path" type="str" required>+ Path to the directory on the local machine.+</ParamField>+<ParamField body="remote_path" type="str" required>+ Absolute path inside the sandbox where the directory will be created.+</ParamField>++### `image.to_dict()`++Returns the image manifest as a plain dict.++**Returns:** `dict`++### `image.cache_key()`++Computes a deterministic SHA-256 hash of the manifest for cache lookups.++**Returns:** `str`++---++## Snapshot info fields| Field | Type | Description || --- | --- | --- |-| `template_id` | `str` | Unique template identifier |-| `name` | `str` | Template name |-| `tag` | `str` | Image tag |-| `status` | `str` | Build status: `"building"`, `"ready"`, `"error"` |+| `id` | `str` | Unique snapshot identifier |+| `name` | `str` | Snapshot name |+| `status` | `str` | `"building"`, `"ready"`, or `"failed"` |+| `contentHash` | `str` | SHA-256 hash of the image manifest |+| `checkpointId` | `str` | Linked checkpoint ID |+| `manifest` | `dict` | The declarative image manifest |+| `createdAt` | `str` | ISO 8601 creation timestamp |+| `lastUsedAt` | `str` | ISO 8601 last usage timestamp |-## Using a Template+----Once built, pass the template name when creating a sandbox:+## Complete example```python-sandbox = await Sandbox.create(template='python-ml')-result = await sandbox.commands.run(- 'python3 -c "import numpy; print(numpy.__version__)"'-)-print(result.stdout) # 1.24.0-await sandbox.kill()+import asyncio+from opencomputer import Sandbox, Image, Snapshots++async def main():+ # ── Pattern 1: On-demand image ──+ dev_image = (+ Image.base()+ .apt_install(["curl", "jq"])+ .pip_install(["requests"])+ .add_file("/workspace/config.json", '{"debug": true}')+ .env({"APP_ENV": "development"})+ .workdir("/workspace")+ )++ sandbox = await Sandbox.create(+ image=dev_image,+ on_build_log=lambda log: print(f"build: {log}"),+ )++ await sandbox.commands.run("curl --version")+ await sandbox.kill()++ # ── Pattern 2: Pre-built snapshot ──+ snapshots = Snapshots()++ prod_image = (+ Image.base()+ .apt_install(["python3-pip", "git"])+ .pip_install(["pandas", "numpy", "scikit-learn"])+ .run_commands("mkdir -p /workspace/data")+ .env({"APP_ENV": "production"})+ .workdir("/workspace")+ )++ await snapshots.create(+ name="ml-env",+ image=prod_image,+ on_build_logs=lambda log: print(f"build: {log}"),+ )++ # Instant — no build, just boot from snapshot+ ml_sandbox = await Sandbox.create(snapshot="ml-env")+ await ml_sandbox.commands.run(+ 'python3 -c "import pandas; print(pandas.__version__)"'+ )+ await ml_sandbox.kill()++ # Cleanup+ await snapshots.delete("ml-env")++asyncio.run(main())```diff --git a/docs/sdks/typescript/templates.mdx b/docs/sdks/typescript/templates.mdxindex c4b7421c..784b0990 100644--- a/docs/sdks/typescript/templates.mdx+++ b/docs/sdks/typescript/templates.mdx@@ -1,105 +1,372 @@---title: "Templates"-description: "Build and manage reusable sandbox templates"+description: "Define sandbox environments programmatically with the Image builder and Snapshots"----Templates let you create reusable sandbox images from Dockerfiles. Pre-install languages, tools, and dependencies so your sandboxes start ready to go.+Templates provide a code-first approach to defining sandbox environments. Instead of configuring images manually, you define them programmatically using the SDK.-## Building a Template+The system supports two workflows:++1. **Declarative images** — build images with varying dependencies _on demand_ when creating sandboxes+2. **Pre-built snapshots** — create and register _ready-to-use_ snapshots that can be shared across multiple sandboxes++## Declarative image building++Build images on-the-fly when creating sandboxes. Ideal for iterating quickly without creating separate snapshots.++Declarative images are **cached by content hash** — identical manifests produce the same image. Subsequent runs reuse the cached image instantly.++```typescript+import { Sandbox, Image } from '@opencomputer/sdk';++// Define an image with packages, env vars, and files+const image = Image.base()+ .aptInstall(['curl', 'jq'])+ .pipInstall(['requests', 'pandas'])+ .env({ PROJECT_ROOT: '/workspace' })+ .workdir('/workspace');++// Create a sandbox — the image is built on first run, cached after+const sandbox = await Sandbox.create({+ image,+ timeout: 300,+ onBuildLog: (log) => console.log(`build: ${log}`),+});++const result = await sandbox.commands.run('which curl');+console.log(result.exitCode); // 0+```++### `Sandbox.create({ image, onBuildLog? })`++When you pass an `image` to `Sandbox.create()`, the server:++1. Hashes the image manifest to compute a **cache key**+2. If cached, creates the sandbox from the existing checkpoint instantly+3. If not cached, boots a build sandbox, executes each step, checkpoints the result, then creates your sandbox from it++<ParamField body="image" type="Image" optional>+ A declarative image definition built with the `Image` builder.+</ParamField>+<ParamField body="onBuildLog" type="(log: string) => void" optional>+ Callback for streaming build log messages via SSE. Receives step-by-step progress updates during image building.+</ParamField>++## Creating pre-built snapshots++Create named snapshots that persist permanently and can be shared across sandboxes. Snapshots are visible in the dashboard and don't need to be rebuilt.```typescript-import { Templates } from '@opencomputer/sdk';+import { Image, Snapshots } from '@opencomputer/sdk';++const snapshots = new Snapshots();++// Define the image+const image = Image.base()+ .aptInstall(['python3-pip'])+ .pipInstall(['pandas', 'numpy', 'scikit-learn'])+ .workdir('/workspace');-const templates = new Templates(apiUrl, apiKey);+// Create a named snapshot with build log streaming+await snapshots.create({+ name: 'data-science',+ image,+ onBuildLogs: (log) => console.log(`build: ${log}`),+});-const template = await templates.build('python-ml', `-FROM ubuntu:22.04-RUN apt-get update && apt-get install -y python3 python3-pip-RUN pip3 install numpy pandas scikit-learn-`);+// Now create sandboxes from the snapshot — instant, no build step+const sandbox = await Sandbox.create({ snapshot: 'data-science' });+```++### `new Snapshots(opts?)`++<ParamField body="opts" type="SnapshotOpts" optional>+ <Expandable title="properties">+ <ParamField body="apiKey" type="string" optional>+ API key. Falls back to `OPENCOMPUTER_API_KEY` env var.+ </ParamField>+ <ParamField body="apiUrl" type="string" optional>+ API base URL. Falls back to `OPENCOMPUTER_API_URL` env var.+ </ParamField>+ </Expandable>+</ParamField>-console.log(template.templateID); // tpl-abc123-console.log(template.status); // building → ready+### `snapshots.create(opts)`++Creates a pre-built snapshot from a declarative image.++<ParamField body="opts" type="CreateSnapshotOpts" required>+ <Expandable title="properties">+ <ParamField body="name" type="string" required>+ Unique name for this snapshot.+ </ParamField>+ <ParamField body="image" type="Image" required>+ Declarative image definition.+ </ParamField>+ <ParamField body="onBuildLogs" type="(log: string) => void" optional>+ Callback for streaming build log messages.+ </ParamField>+ </Expandable>+</ParamField>++**Returns:** `Promise<SnapshotInfo>`++### `snapshots.list()`++Returns all named snapshots for the current organization.++```typescript+const list = await snapshots.list();+for (const s of list) {+ console.log(`${s.name} — ${s.status}`);+}```-### `templates.build(name, dockerfile)`+**Returns:** `Promise<SnapshotInfo[]>`++### `snapshots.get(name)`-Builds a new template from a Dockerfile.+Gets a snapshot by name.++```typescript+const snapshot = await snapshots.get('data-science');+console.log(snapshot.status); // "ready"+```<ParamField body="name" type="string" required>- A unique name for the template.+ Snapshot name.</ParamField>-<ParamField body="dockerfile" type="string" required>- The Dockerfile content to build from.++**Returns:** `Promise<SnapshotInfo>`++### `snapshots.delete(name)`++Deletes a named snapshot. Existing sandboxes created from it are not affected.++```typescript+await snapshots.delete('data-science');+```++<ParamField body="name" type="string" required>+ Snapshot name to delete.</ParamField>-**Returns:** `Promise<TemplateInfo>`+**Returns:** `Promise<void>`++### `Sandbox.create({ snapshot })`-## Listing Templates+Create a sandbox from a pre-built snapshot by name.```typescript-const allTemplates = await templates.list();+const sandbox = await Sandbox.create({ snapshot: 'data-science' });+```-for (const t of allTemplates) {- console.log(`${t.name} (${t.tag}) — ${t.status}`);-}+<ParamField body="snapshot" type="string" optional>+ Name of a pre-built snapshot to create the sandbox from.+</ParamField>++**Returns:** `Promise<Sandbox>`++---++## Image configuration++The `Image` class provides a fluent, immutable API for defining sandbox environments. Each method returns a **new** `Image` instance — the original is never modified.++### `Image.base()`++Creates a new image starting from the default OpenSandbox environment (Ubuntu 22.04 with Python, Node.js, build tools, and common utilities).++```typescript+const image = Image.base();```-### `templates.list()`+### `image.aptInstall(packages)`-Returns all templates.+Install system packages via `apt-get`.-**Returns:** `Promise<TemplateInfo[]>`+```typescript+const image = Image.base().aptInstall(['curl', 'git', 'jq']);+```-## Getting a Template+<ParamField body="packages" type="string[]" required>+ List of apt package names to install.+</ParamField>++### `image.pipInstall(packages)`++Install Python packages via `pip`.```typescript-const template = await templates.get('python-ml');-console.log(template);+const image = Image.base().pipInstall(['requests', 'pandas', 'numpy']);```-### `templates.get(name)`+<ParamField body="packages" type="string[]" required>+ List of pip package names to install.+</ParamField>-Gets a template by name.+### `image.runCommands(...commands)`-<ParamField body="name" type="string" required>- Template name.+Run one or more shell commands during image build.++```typescript+const image = Image.base().runCommands(+ 'mkdir -p /workspace/project',+ 'echo "Hello" > /workspace/welcome.txt',+);+```++<ParamField body="commands" type="string[]" required>+ Shell commands to execute sequentially.</ParamField>-**Returns:** `Promise<TemplateInfo>`+### `image.env(vars)`-## Deleting a Template+Set environment variables. Written to `/etc/environment` so they're available in all sessions.```typescript-await templates.delete('python-ml');+const image = Image.base().env({+ PROJECT_ROOT: '/workspace',+ NODE_ENV: 'production',+});```-### `templates.delete(name)`+<ParamField body="vars" type="Record<string, string>" required>+ Key-value pairs of environment variables.+</ParamField>++### `image.workdir(path)`-Deletes a template by name.+Set the default working directory.-<ParamField body="name" type="string" required>- Template name to delete.+```typescript+const image = Image.base().workdir('/workspace/project');+```++<ParamField body="path" type="string" required>+ Absolute path for the working directory.</ParamField>-**Returns:** `Promise<void>`+### `image.addFile(remotePath, content)`++Embed a file with inline content into the image.++```typescript+const image = Image.base()+ .addFile('/workspace/config.json', '{"env": "production"}')+ .addFile('/workspace/setup.sh', '#!/bin/bash\necho "Ready!"');+```++<ParamField body="remotePath" type="string" required>+ Absolute path inside the sandbox.+</ParamField>+<ParamField body="content" type="string" required>+ String content of the file.+</ParamField>-## TemplateInfo+### `image.addLocalFile(localPath, remotePath)`++Read a file from the local machine and embed it into the image.++```typescript+const image = Image.base()+ .addLocalFile('package.json', '/workspace/package.json');+```++<ParamField body="localPath" type="string" required>+ Path to the file on the local machine.+</ParamField>+<ParamField body="remotePath" type="string" required>+ Absolute path inside the sandbox.+</ParamField>++### `image.addLocalDir(localPath, remotePath)`++Recursively read a local directory and embed all files into the image.++```typescript+const image = Image.base()+ .addLocalDir('src', '/workspace/src');+```++<ParamField body="localPath" type="string" required>+ Path to the directory on the local machine.+</ParamField>+<ParamField body="remotePath" type="string" required>+ Absolute path inside the sandbox where the directory will be created.+</ParamField>++### `image.toJSON()`++Returns the image manifest as a plain object.++**Returns:** `ImageManifest`++### `image.cacheKey()`++Computes a deterministic SHA-256 hash of the manifest for cache lookups.++**Returns:** `string`++---++## SnapshotInfo| Field | Type | Description || --- | --- | --- |-| `templateID` | `string` | Unique template identifier |-| `name` | `string` | Template name |-| `tag` | `string` | Image tag |-| `status` | `string` | Build status: `"building"`, `"ready"`, `"error"` |+| `id` | `string` | Unique snapshot identifier |+| `name` | `string` | Snapshot name |+| `status` | `string` | `"building"`, `"ready"`, or `"failed"` |+| `contentHash` | `string` | SHA-256 hash of the image manifest |+| `checkpointId` | `string` | Linked checkpoint ID |+| `manifest` | `object` | The declarative image manifest |+| `createdAt` | `string` | ISO 8601 creation timestamp |+| `lastUsedAt` | `string` | ISO 8601 last usage timestamp |-## Using a Template+----Once built, pass the template name when creating a sandbox:+## Complete example```typescript-const sandbox = await Sandbox.create({ template: 'python-ml' });--const result = await sandbox.commands.run('python3 -c "import numpy; print(numpy.__version__)"');-console.log(result.stdout); // 1.24.0+import { Sandbox, Image, Snapshots } from '@opencomputer/sdk';++// ── Pattern 1: On-demand image ──+const devImage = Image.base()+ .aptInstall(['curl', 'jq'])+ .pipInstall(['requests'])+ .addFile('/workspace/config.json', '{"debug": true}')+ .env({ APP_ENV: 'development' })+ .workdir('/workspace');++const sandbox = await Sandbox.create({+ image: devImage,+ onBuildLog: console.log,+});++await sandbox.commands.run('curl --version');+await sandbox.kill();++// ── Pattern 2: Pre-built snapshot ──+const snapshots = new Snapshots();++const prodImage = Image.base()+ .aptInstall(['python3-pip', 'git'])+ .pipInstall(['pandas', 'numpy', 'scikit-learn'])+ .runCommands('mkdir -p /workspace/data')+ .env({ APP_ENV: 'production' })+ .workdir('/workspace');++await snapshots.create({+ name: 'ml-env',+ image: prodImage,+ onBuildLogs: console.log,+});++// Instant — no build, just boot from snapshot+const mlSandbox = await Sandbox.create({ snapshot: 'ml-env' });+await mlSandbox.commands.run('python3 -c "import pandas; print(pandas.__version__)"');+await mlSandbox.kill();++// Cleanup+await snapshots.delete('ml-env');```diff --git a/internal/api/dashboard.go b/internal/api/dashboard.goindex a394b2d7..134129af 100644--- a/internal/api/dashboard.go+++ b/internal/api/dashboard.go@@ -1353,3 +1353,51 @@ func (s *Server) dashboardDeleteCheckpoint(c echo.Context) error {return c.NoContent(http.StatusNoContent)}++// dashboardListImages lists all image cache entries (named snapshots) for the authenticated org.+func (s *Server) dashboardListImages(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ // namedOnly=false to show all cached images (both named snapshots and auto-cached)+ showAll := c.QueryParam("all") == "true"+ images, err := s.store.ListImageCacheByOrg(c.Request().Context(), orgID, !showAll)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ if images == nil {+ images = []db.ImageCache{}+ }++ return c.JSON(http.StatusOK, images)+}++// dashboardDeleteImage deletes an image cache entry for the authenticated org.+func (s *Server) dashboardDeleteImage(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "database not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ imageID, err := uuid.Parse(c.Param("id"))+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid image ID"})+ }++ if err := s.store.DeleteImageCache(c.Request().Context(), orgID, imageID); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ return c.NoContent(http.StatusNoContent)+}diff --git a/internal/api/router.go b/internal/api/router.goindex 88188ac1..bb31b629 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -218,6 +218,8 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, odash.DELETE("/templates/:id", s.dashboardDeleteTemplate)dash.GET("/checkpoints", s.dashboardListCheckpoints)dash.DELETE("/checkpoints/:id", s.dashboardDeleteCheckpoint)+ dash.GET("/images", s.dashboardListImages)+ dash.DELETE("/images/:id", s.dashboardDeleteImage)// Session detail + statsdash.GET("/sessions/:sandboxId", s.dashboardGetSession)diff --git a/web/src/App.tsx b/web/src/App.tsxindex 93d3e959..635bbb1a 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -7,6 +7,7 @@ import Dashboard from './pages/Dashboard'import Sessions from './pages/Sessions'import APIKeys from './pages/APIKeys'import Checkpoints from './pages/Checkpoints'+import Templates from './pages/Templates'import Settings from './pages/Settings'import SessionDetail from './pages/SessionDetail'@@ -21,6 +22,7 @@ export default function App() {<Route path="sessions" element={<Sessions />} /><Route path="sessions/:sandboxId" element={<SessionDetail />} /><Route path="checkpoints" element={<Checkpoints />} />+ <Route path="templates" element={<Templates />} /><Route path="api-keys" element={<APIKeys />} /><Route path="settings" element={<Settings />} /></Route>diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 2e629538..036d2083 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -63,6 +63,12 @@ export const getCheckpoints = (page = 1, perPage = 20) =>export const deleteCheckpointDashboard = (id: string) =>apiFetch<void>(`/checkpoints/${id}`, { method: 'DELETE' })+export const getImages = (all = false) =>+ apiFetch<ImageCacheItem[]>(`/images${all ? '?all=true' : ''}`)++export const deleteImage = (id: string) =>+ apiFetch<void>(`/images/${id}`, { method: 'DELETE' })+export const getSessionDetail = (sandboxId: string) =>apiFetch<SessionDetail>(`/sessions/${sandboxId}`)@@ -191,6 +197,18 @@ export interface CheckpointsResponse {perPage: number}+export interface ImageCacheItem {+ id: string+ orgId: string+ contentHash: string+ checkpointId?: string+ name?: string+ manifest: Record<string, unknown>+ status: string+ createdAt: string+ lastUsedAt: string+}+export interface Org {id: stringname: stringdiff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsxindex 0efda33a..e39c9522 100644--- a/web/src/components/Layout.tsx+++ b/web/src/components/Layout.tsx@@ -30,6 +30,13 @@ const icons = {<polyline points="2 12 12 17 22 12" /></svg>),+ box: (+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />+ <polyline points="3.27 6.96 12 12.01 20.73 6.96" />+ <line x1="12" y1="22.08" x2="12" y2="12" />+ </svg>+ ),gear: (<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3" />@@ -49,6 +56,7 @@ const navItems = [{ to: '/', label: 'Dashboard', end: true, icon: icons.grid },{ to: '/sessions', label: 'Sessions', icon: icons.clock },{ to: '/checkpoints', label: 'Checkpoints', icon: icons.layers },+ { to: '/templates', label: 'Templates', icon: icons.box },{ to: '/api-keys', label: 'API Keys', icon: icons.key },{ to: '/settings', label: 'Settings', icon: icons.gear },]diff --git a/web/src/pages/Templates.tsx b/web/src/pages/Templates.tsxindex ec6803e0..ab06525e 100644--- a/web/src/pages/Templates.tsx+++ b/web/src/pages/Templates.tsx@@ -1,114 +1,294 @@+import { useState } from 'react'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'-import { getTemplates, deleteTemplate, type Template } from '../api/client'+import {+ getTemplates, deleteTemplate, type Template,+ getImages, deleteImage, type ImageCacheItem,+} from '../api/client'++type Tab = 'templates' | 'images'++function StatusBadge({ status }: { status: string }) {+ const isReady = status === 'ready'+ const isFailed = status === 'failed'+ return (+ <span style={{+ fontSize: 11,+ fontWeight: 600,+ padding: '2px 8px',+ borderRadius: 10,+ background: isReady+ ? 'rgba(34, 197, 94, 0.08)'+ : isFailed+ ? 'rgba(251, 113, 133, 0.08)'+ : 'rgba(234, 179, 8, 0.08)',+ color: isReady+ ? 'var(--accent-green)'+ : isFailed+ ? 'var(--accent-rose)'+ : '#eab308',+ border: `1px solid ${+ isReady+ ? 'rgba(34, 197, 94, 0.15)'+ : isFailed+ ? 'rgba(251, 113, 133, 0.15)'+ : 'rgba(234, 179, 8, 0.15)'+ }`,+ }}>+ {isReady ? 'Ready' : isFailed ? 'Failed' : 'Building'}+ </span>+ )+}++function formatSteps(manifest: Record<string, unknown>): string {+ const steps = manifest.steps as Array<Record<string, unknown>> | undefined+ if (!steps || steps.length === 0) return 'base'+ return steps.map(s => {+ const t = s.type as string+ const args = s.args as Record<string, unknown> | undefined+ switch (t) {+ case 'apt_install': return `apt: ${(args?.packages as string[])?.join(', ') || '...'}`+ case 'pip_install': return `pip: ${(args?.packages as string[])?.join(', ') || '...'}`+ case 'run': return `run: ${((args?.commands as string[]) || []).length} cmd(s)`+ case 'env': return `env: ${Object.keys((args?.vars as Record<string, string>) || {}).length} var(s)`+ case 'workdir': return `workdir: ${args?.path || '...'}`+ case 'add_file': return `file: ${args?.path || '...'}`+ default: return t+ }+ }).join(' + ')+}export default function Templates() {const queryClient = useQueryClient()- const { data: templates, isLoading } = useQuery({+ const [tab, setTab] = useState<Tab>('templates')++ const { data: templates, isLoading: templatesLoading } = useQuery({queryKey: ['templates'],queryFn: getTemplates,})- const deleteMutation = useMutation({+ const { data: images, isLoading: imagesLoading } = useQuery({+ queryKey: ['images'],+ queryFn: () => getImages(),+ })++ const deleteTemplateMutation = useMutation({mutationFn: (id: string) => deleteTemplate(id),onSuccess: () => {queryClient.invalidateQueries({ queryKey: ['templates'] })},})+ const deleteImageMutation = useMutation({+ mutationFn: (id: string) => deleteImage(id),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['images'] })+ },+ })++ const templateCount = (templates ?? []).length+ const imageCount = (images ?? []).length+return (<div>{/* Header */}<div style={{ marginBottom: 28 }}>- <h1 className="page-title">Templates</h1>- <p className="page-subtitle">Manage sandbox templates for your organization</p>+ <h1 className="page-title">Templates & Images</h1>+ <p className="page-subtitle">Manage sandbox templates and declarative image snapshots</p>+ </div>++ {/* Tabs */}+ <div style={{ display: 'flex', gap: 4, marginBottom: 20 }}>+ {([+ { key: 'templates' as Tab, label: 'Templates', count: templateCount },+ { key: 'images' as Tab, label: 'Images', count: imageCount },+ ]).map(t => (+ <button+ key={t.key}+ onClick={() => setTab(t.key)}+ style={{+ padding: '8px 16px',+ fontSize: 13,+ fontWeight: tab === t.key ? 600 : 400,+ fontFamily: 'var(--font-body)',+ color: tab === t.key ? 'var(--text-primary)' : 'var(--text-secondary)',+ background: tab === t.key ? 'rgba(99, 102, 241, 0.08)' : 'transparent',+ border: `1px solid ${tab === t.key ? 'rgba(99, 102, 241, 0.2)' : 'var(--border-subtle)'}`,+ borderRadius: 8,+ cursor: 'pointer',+ transition: 'all 0.15s ease',+ display: 'flex',+ alignItems: 'center',+ gap: 8,+ }}+ >+ {t.label}+ <span style={{+ fontSize: 11,+ fontFamily: 'var(--font-mono)',+ padding: '1px 6px',+ borderRadius: 8,+ background: tab === t.key ? 'rgba(99, 102, 241, 0.15)' : 'rgba(255,255,255,0.04)',+ color: tab === t.key ? 'var(--accent-indigo)' : 'var(--text-tertiary)',+ }}>+ {t.count}+ </span>+ </button>+ ))}</div>- {/* Table */}- {isLoading ? (- <div style={{ display: 'flex', justifyContent: 'center', padding: 48 }}>- <div className="loading-spinner" />- </div>- ) : (- <div className="glass-card animate-in stagger-1" style={{ overflow: 'hidden' }}>- <table className="data-table">- <thead>- <tr>- <th>Name</th>- <th>Tag</th>- <th>Type</th>- <th>Status</th>- <th>Created</th>- <th style={{ width: 80 }}></th>- </tr>- </thead>- <tbody>- {(templates ?? []).map((t: Template) => (- <tr key={t.id}>- <td style={{ fontWeight: 500, color: 'var(--text-primary)' }}>{t.name}</td>- <td><code>{t.tag}</code></td>- <td>- <span style={{- fontSize: 11,- fontWeight: 600,- padding: '2px 8px',- borderRadius: 10,- background: t.isPublic- ? 'rgba(34, 197, 94, 0.08)'- : 'rgba(99, 102, 241, 0.08)',- color: t.isPublic- ? 'var(--accent-green)'- : 'var(--accent-indigo)',- border: `1px solid ${t.isPublic ? 'rgba(34, 197, 94, 0.15)' : 'rgba(99, 102, 241, 0.15)'}`,- }}>- {t.isPublic ? 'Built-in' : 'Custom'}- </span>- </td>- <td>- <span style={{- fontSize: 11,- fontWeight: 600,- padding: '2px 8px',- borderRadius: 10,- background: t.status === 'ready'- ? 'rgba(34, 197, 94, 0.08)'- : 'rgba(234, 179, 8, 0.08)',- color: t.status === 'ready'- ? 'var(--accent-green)'- : '#eab308',- border: `1px solid ${t.status === 'ready' ? 'rgba(34, 197, 94, 0.15)' : 'rgba(234, 179, 8, 0.15)'}`,- }}>- {t.status === 'ready' ? 'Ready' : 'Processing'}- </span>- </td>- <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>- {new Date(t.createdAt).toLocaleString()}- </td>- <td>- {!t.isPublic && (+ {/* Templates Tab */}+ {tab === 'templates' && (+ templatesLoading ? (+ <div style={{ display: 'flex', justifyContent: 'center', padding: 48 }}>+ <div className="loading-spinner" />+ </div>+ ) : (+ <div className="glass-card animate-in stagger-1" style={{ overflow: 'hidden' }}>+ <table className="data-table">+ <thead>+ <tr>+ <th>Name</th>+ <th>Tag</th>+ <th>Type</th>+ <th>Status</th>+ <th>Source Sandbox</th>+ <th>Created</th>+ <th style={{ width: 80 }}></th>+ </tr>+ </thead>+ <tbody>+ {(templates ?? []).map((t: Template) => (+ <tr key={t.id}>+ <td style={{ fontWeight: 500, color: 'var(--text-primary)' }}>{t.name}</td>+ <td><code>{t.tag}</code></td>+ <td>+ <span style={{+ fontSize: 11,+ fontWeight: 600,+ padding: '2px 8px',+ borderRadius: 10,+ background: t.isPublic+ ? 'rgba(34, 197, 94, 0.08)'+ : 'rgba(99, 102, 241, 0.08)',+ color: t.isPublic+ ? 'var(--accent-green)'+ : 'var(--accent-indigo)',+ border: `1px solid ${t.isPublic ? 'rgba(34, 197, 94, 0.15)' : 'rgba(99, 102, 241, 0.15)'}`,+ }}>+ {t.isPublic ? 'Built-in' : 'Custom'}+ </span>+ </td>+ <td><StatusBadge status={t.status || 'ready'} /></td>+ <td>+ {t.createdBySandboxId ? (+ <code style={{ fontSize: 12 }}>{t.createdBySandboxId}</code>+ ) : (+ <span style={{ color: 'var(--text-tertiary)' }}>-</span>+ )}+ </td>+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>+ {new Date(t.createdAt).toLocaleString()}+ </td>+ <td>+ {!t.isPublic && (+ <button+ className="btn-danger"+ onClick={() => {+ if (confirm('Delete this template? Existing sandboxes using it will not be affected.')) {+ deleteTemplateMutation.mutate(t.id)+ }+ }}+ >+ Delete+ </button>+ )}+ </td>+ </tr>+ ))}+ {templateCount === 0 && (+ <tr>+ <td colSpan={7} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>+ No templates yet. Save a running sandbox as a template from the session detail page.+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ )+ )}++ {/* Images Tab */}+ {tab === 'images' && (+ imagesLoading ? (+ <div style={{ display: 'flex', justifyContent: 'center', padding: 48 }}>+ <div className="loading-spinner" />+ </div>+ ) : (+ <div className="glass-card animate-in stagger-1" style={{ overflow: 'hidden' }}>+ <table className="data-table">+ <thead>+ <tr>+ <th>Name</th>+ <th>Steps</th>+ <th>Status</th>+ <th>Checkpoint</th>+ <th>Last Used</th>+ <th>Created</th>+ <th style={{ width: 80 }}></th>+ </tr>+ </thead>+ <tbody>+ {(images ?? []).map((img: ImageCacheItem) => (+ <tr key={img.id}>+ <td style={{ fontWeight: 500, color: 'var(--text-primary)' }}>+ {img.name || (+ <span style={{ color: 'var(--text-tertiary)', fontStyle: 'italic' }}>auto-cached</span>+ )}+ </td>+ <td style={{ fontSize: 12, color: 'var(--text-secondary)', maxWidth: 300, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {formatSteps(img.manifest)}+ </td>+ <td><StatusBadge status={img.status} /></td>+ <td>+ {img.checkpointId ? (+ <code style={{ fontSize: 11 }}>{img.checkpointId.slice(0, 8)}</code>+ ) : (+ <span style={{ color: 'var(--text-tertiary)' }}>-</span>+ )}+ </td>+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>+ {new Date(img.lastUsedAt).toLocaleString()}+ </td>+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>+ {new Date(img.createdAt).toLocaleString()}+ </td>+ <td><buttonclassName="btn-danger"onClick={() => {- if (confirm('Delete this template? Existing sandboxes using it will not be affected.')) {- deleteMutation.mutate(t.id)+ const label = img.name ? `"${img.name}"` : 'this cached image'+ if (confirm(`Delete ${label}? Existing sandboxes will not be affected.`)) {+ deleteImageMutation.mutate(img.id)}}}>Delete</button>- )}- </td>- </tr>- ))}- {(templates ?? []).length === 0 && (- <tr>- <td colSpan={6} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>- No templates yet- </td>- </tr>- )}- </tbody>- </table>- </div>+ </td>+ </tr>+ ))}+ {imageCount === 0 && (+ <tr>+ <td colSpan={7} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>+ No images yet. Create images using the SDK with Image.base().aptInstall([...]) or snapshots.create().+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ ))}</div>)