An open-source, faster Devin alternative
TypeScript
remove old template systems
Brian Reardon1b5faa8e7bb5
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 0a532b99..577b9f39 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -15,11 +15,9 @@ import ("github.com/opensandbox/opensandbox/internal/db"fc "github.com/opensandbox/opensandbox/internal/firecracker""github.com/opensandbox/opensandbox/internal/metrics"- "github.com/opensandbox/opensandbox/internal/podman""github.com/opensandbox/opensandbox/internal/proxy""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/storage"- "github.com/opensandbox/opensandbox/internal/template""github.com/opensandbox/opensandbox/internal/worker""github.com/opensandbox/opensandbox/pkg/types")@@ -233,23 +231,8 @@ func main() {defer metricsSrv.Close()log.Println("opensandbox-worker: metrics server started on :9091")- // Initialize template builder (Podman as build tool → ext4 images)- var builder *template.Builder- podmanClient, podmanErr := podman.NewClient()- if podmanErr != nil {- log.Printf("opensandbox-worker: podman not available: %v (template building disabled)", podmanErr)- } else {- imagesDir := fcCfg.ImagesDir- agentPath := filepath.Join(filepath.Dir(os.Args[0]), "osb-agent")- if _, err := os.Stat(agentPath); err != nil {- agentPath = "/usr/local/bin/osb-agent"- }- builder = template.NewBuilder(podmanClient, imagesDir, agentPath)- log.Printf("opensandbox-worker: template builder configured (images=%s, agent=%s)", imagesDir, agentPath)- }-// Start gRPC server for control plane communication- grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore, sbRouter, builder, store)+ grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore, sbRouter, store)grpcAddr := ":9090"log.Printf("opensandbox-worker: starting gRPC server on %s", grpcAddr)go func() {diff --git a/examples/test_templates.ts b/examples/test_templates.tsdeleted file mode 100644index 5571b107..00000000--- a/examples/test_templates.ts+++ /dev/null@@ -1,125 +0,0 @@-/**- * Test script for the OpenSandbox Templates API.- *- * Templates are standalone — they're not accessed through a Sandbox instance.- * They let you build custom container images from Dockerfiles, which can then- * be used as the `template` parameter when creating sandboxes.- *- * Usage:- * npx tsx test_templates.ts [API_URL] [API_KEY]- *- * Defaults to http://localhost:8080 with no API key.- */--import { Sandbox } from "../sdks/typescript/src/index";-import { Templates, type TemplateInfo } from "../sdks/typescript/src/template";--function resolveApiUrl(url: string): string {- const base = url.replace(/\/+$/, "");- return base.endsWith("/api") ? base : `${base}/api`;-}--async function main() {- const apiUrl = resolveApiUrl(- process.argv[2] ?? process.env.OPENSANDBOX_API_URL ?? "http://localhost:8080"- );- const apiKey = process.argv[3] ?? process.env.OPENSANDBOX_API_KEY ?? "";- const rawUrl = process.argv[2] ?? process.env.OPENSANDBOX_API_URL ?? "http://localhost:8080";-- const templates = new Templates(apiUrl, apiKey);-- // ── 1. List default templates ────────────────────────────────- console.log("=== 1. List default templates ===");- let allTemplates = await templates.list();- console.log(`Found ${allTemplates.length} templates:`);- for (const t of allTemplates) {- console.log(` - ${t.name} (id=${t.templateID}, tag=${t.tag}, status=${t.status})`);- }-- // ── 2. Get a specific template ───────────────────────────────- console.log("\n=== 2. Get 'base' template ===");- const base = await templates.get("base");- console.log(` name=${base.name}, id=${base.templateID}, tag=${base.tag}, status=${base.status}`);-- // ── 3. Build a custom template ───────────────────────────────- console.log("\n=== 3. Build custom template 'test-custom' ===");- console.log(" (This runs `podman build` synchronously — may take a minute...)");- const custom = await templates.build(- "test-custom",- `FROM ubuntu:22.04-RUN apt-get update -qq && apt-get install -y -qq curl > /dev/null 2>&1-RUN echo "custom template ready" > /etc/motd-`- );- console.log(` Built! id=${custom.templateID}, name=${custom.name}, status=${custom.status}`);-- // ── 4. Verify it shows up in the list ────────────────────────- console.log("\n=== 4. Verify template appears in list ===");- allTemplates = await templates.list();- const names = allTemplates.map((t) => t.name);- if (!names.includes("test-custom")) {- throw new Error(`Expected 'test-custom' in ${JSON.stringify(names)}`);- }- console.log(` OK — found ${allTemplates.length} templates: ${JSON.stringify(names)}`);-- // ── 5. Get the custom template by name ───────────────────────- console.log("\n=== 5. Get custom template ===");- const fetched = await templates.get("test-custom");- console.log(` name=${fetched.name}, status=${fetched.status}`);-- // ── 6. Create a sandbox using the custom template ────────────- console.log("\n=== 6. Create sandbox with custom template ===");- const sandbox = await Sandbox.create({- template: "test-custom",- timeout: 60,- apiUrl: rawUrl,- apiKey,- });- console.log(` Sandbox created: ${sandbox.sandboxId}`);-- // Verify the custom image works- const motd = await sandbox.commands.run("cat /etc/motd");- console.log(` /etc/motd says: ${motd.stdout.trim()}`);- if (!motd.stdout.includes("custom template ready")) {- throw new Error(`Unexpected motd: ${motd.stdout}`);- }-- const curl = await sandbox.commands.run("curl --version | head -1");- console.log(` curl: ${curl.stdout.trim()}`);-- await sandbox.kill();- console.log(" Sandbox killed.");-- // ── 7. Delete the custom template ────────────────────────────- console.log("\n=== 7. Delete custom template ===");- await templates.delete("test-custom");- console.log(" Deleted 'test-custom'.");-- // ── 8. Verify deletion ───────────────────────────────────────- console.log("\n=== 8. Verify deletion ===");- try {- await templates.get("test-custom");- console.log(" ERROR: template still exists after deletion!");- } catch (e: any) {- if (e.message.includes("404")) {- console.log(" OK — template not found (404), as expected.");- } else {- console.log(` Unexpected error: ${e.message}`);- }- }-- // Final list- allTemplates = await templates.list();- const remaining = allTemplates.map((t) => t.name);- if (remaining.includes("test-custom")) {- throw new Error(`'test-custom' still in ${JSON.stringify(remaining)}`);- }- console.log(` Remaining templates: ${JSON.stringify(remaining)}`);-- console.log("\n✅ All template tests passed!");-}--main().catch((err) => {- console.error(`\n❌ Test failed: ${err.message}`);- process.exit(1);-});diff --git a/internal/api/dashboard.go b/internal/api/dashboard.goindex 134129af..5fd3947e 100644--- a/internal/api/dashboard.go+++ b/internal/api/dashboard.go@@ -435,227 +435,6 @@ func strPtr(s string) *string {return &s}-// dashboardListTemplates returns all templates visible to the authenticated org.-func (s *Server) dashboardListTemplates(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",- })- }-- templates, err := s.store.ListTemplates(c.Request().Context(), orgID)- if err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })- }-- // Strip internal fields and filter: only show "default" as built-in template.- type safeTemplate struct {- ID uuid.UUID `json:"id"`- OrgID *uuid.UUID `json:"orgId,omitempty"`- Name string `json:"name"`- Tag string `json:"tag"`- IsPublic bool `json:"isPublic"`- TemplateType string `json:"templateType"`- CreatedBySandboxID *string `json:"createdBySandboxId,omitempty"`- Status string `json:"status"`- CreatedAt time.Time `json:"createdAt"`- }- safe := make([]safeTemplate, 0, len(templates))- for _, t := range templates {- // Only show "default" as the built-in template; hide base, node, python, etc.- if t.IsPublic && t.Name != "default" {- continue- }- safe = append(safe, safeTemplate{- ID: t.ID, OrgID: t.OrgID, Name: t.Name,- Tag: t.Tag, IsPublic: t.IsPublic,- TemplateType: t.TemplateType, CreatedBySandboxID: t.CreatedBySandboxID,- Status: t.Status, CreatedAt: t.CreatedAt,- })- }-- return c.JSON(http.StatusOK, safe)-}--// dashboardBuildTemplate builds a new template for the authenticated org.-func (s *Server) dashboardBuildTemplate(c echo.Context) error {- // Delegate to the shared buildTemplate handler (uses same auth context)- return s.buildTemplate(c)-}--// dashboardDeleteTemplate deletes a custom template for the authenticated org.-func (s *Server) dashboardDeleteTemplate(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",- })- }-- templateID, err := uuid.Parse(c.Param("id"))- if err != nil {- return c.JSON(http.StatusBadRequest, map[string]string{- "error": "invalid template ID",- })- }-- if err := s.store.DeleteTemplateForOrg(c.Request().Context(), templateID, orgID); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })- }-- return c.NoContent(http.StatusNoContent)-}--// dashboardSaveAsTemplate snapshots a running sandbox's drives and creates a new template record.-// The VM is briefly paused on the worker while drives are copied, then resumed.-// The S3 upload and template DB record creation happen in the same call (upload is async on the worker).-func (s *Server) dashboardSaveAsTemplate(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",- })- }-- sandboxID := c.Param("sandboxId")- session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)- if err != nil {- return c.JSON(http.StatusNotFound, map[string]string{- "error": "session not found",- })- }- if session.OrgID != orgID {- return c.JSON(http.StatusForbidden, map[string]string{- "error": "session does not belong to this organization",- })- }- if session.Status != "running" {- return c.JSON(http.StatusBadRequest, map[string]string{- "error": "sandbox must be running to save as template",- })- }-- var req struct {- Name string `json:"name"`- Tag string `json:"tag"`- }- if err := c.Bind(&req); err != nil {- return c.JSON(http.StatusBadRequest, map[string]string{- "error": "invalid request body",- })- }- if req.Name == "" {- return c.JSON(http.StatusBadRequest, map[string]string{- "error": "name is required",- })- }- if req.Tag == "" {- req.Tag = "latest"- }-- ctx := c.Request().Context()-- // Reserve a template UUID upfront so the worker can use it for S3 key naming.- templateID := uuid.New()-- // Dispatch SaveAsTemplate gRPC call to the worker that owns the sandbox.- var rootfsKey, workspaceKey string- if s.workerRegistry != nil {- grpcClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)- if err != nil {- return c.JSON(http.StatusServiceUnavailable, map[string]string{- "error": "worker not available: " + err.Error(),- })- }-- // Give 2 minutes: SyncFS + pause + file copy + resume (upload is async on the worker)- grpcCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)- defer cancel()-- resp, err := grpcClient.SaveAsTemplate(grpcCtx, &pb.SaveAsTemplateRequest{- SandboxId: sandboxID,- TemplateId: templateID.String(),- })- if err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": "save-as-template failed: " + err.Error(),- })- }- rootfsKey = resp.RootfsS3Key- workspaceKey = resp.WorkspaceS3Key- } else if s.manager != nil {- // Combined/worker mode: call directly- if s.checkpointStore == nil {- return c.JSON(http.StatusServiceUnavailable, map[string]string{- "error": "checkpoint store not configured",- })- }- onReady := func() {- if err := s.store.SetTemplateReady(context.Background(), templateID); err != nil {- log.Printf("dashboard: failed to mark template %s ready: %v", templateID, err)- } else {- log.Printf("dashboard: template %s is now ready", templateID)- }- }- rootfsKey, workspaceKey, err = s.manager.SaveAsTemplate(ctx, sandboxID, templateID.String(), s.checkpointStore, onReady)- if err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": "save-as-template failed: " + err.Error(),- })- }- } else {- return c.JSON(http.StatusServiceUnavailable, map[string]string{- "error": "no sandbox manager available",- })- }-- // Create template record in DB (status=processing for sandbox templates)- tmpl, err := s.store.CreateSandboxTemplate(ctx, templateID, &orgID, req.Name, req.Tag, rootfsKey, workspaceKey, sandboxID)- if err != nil {- log.Printf("dashboard: template snapshot succeeded but DB insert failed for sandbox %s: %v", sandboxID, err)- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": "failed to save template record: " + err.Error(),- })- }-- // Label the sandbox session with the new template- _ = s.store.UpdateSandboxSessionTemplate(ctx, sandboxID, tmpl.ID)-- log.Printf("dashboard: saved sandbox %s as template %s (%s)", sandboxID, tmpl.Name, tmpl.ID)-- return c.JSON(http.StatusCreated, map[string]interface{}{- "id": tmpl.ID,- "name": tmpl.Name,- "tag": tmpl.Tag,- "templateType": tmpl.TemplateType,- "status": tmpl.Status,- "createdAt": tmpl.CreatedAt,- })-}-// dashboardGetSession returns detailed info for a single session.func (s *Server) dashboardGetSession(c echo.Context) error {if s.store == nil {diff --git a/internal/api/router.go b/internal/api/router.goindex bb31b629..319d5cd8 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -168,13 +168,6 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.POST("/sandboxes/:id/pty/:sessionID/resize", s.resizePTY)api.DELETE("/sandboxes/:id/pty/:sessionID", s.killPTY)- // Templates- api.POST("/templates", s.buildTemplate)- api.GET("/templates", s.listTemplates)- api.GET("/templates/:name", s.getTemplate)- api.DELETE("/templates/:name", s.deleteTemplate)- api.POST("/sandboxes/:sandboxId/save-as-template", s.dashboardSaveAsTemplate)-// Snapshots (pre-built declarative images)api.POST("/snapshots", s.createSnapshot)api.GET("/snapshots", s.listSnapshots)@@ -214,8 +207,6 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, odash.PUT("/org/custom-domain", s.dashboardSetCustomDomain)dash.DELETE("/org/custom-domain", s.dashboardDeleteCustomDomain)dash.POST("/org/custom-domain/refresh", s.dashboardRefreshCustomDomain)- dash.GET("/templates", s.dashboardListTemplates)- dash.DELETE("/templates/:id", s.dashboardDeleteTemplate)dash.GET("/checkpoints", s.dashboardListCheckpoints)dash.DELETE("/checkpoints/:id", s.dashboardDeleteCheckpoint)dash.GET("/images", s.dashboardListImages)@@ -224,8 +215,6 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// Session detail + statsdash.GET("/sessions/:sandboxId", s.dashboardGetSession)dash.GET("/sessions/:sandboxId/stats", s.dashboardGetSessionStats)- dash.POST("/sessions/:sandboxId/save-as-template", s.dashboardSaveAsTemplate)-// PTY (terminal)dash.POST("/sessions/:sandboxId/pty", s.dashboardCreatePTY)dash.GET("/sessions/:sandboxId/pty/:sessionId", s.dashboardPTYWebSocket)diff --git a/internal/api/templates.go b/internal/api/templates.godeleted file mode 100644index b3353177..00000000--- a/internal/api/templates.go+++ /dev/null@@ -1,186 +0,0 @@-package api--import (- "context"- "net/http"- "time"-- "github.com/labstack/echo/v4"- "github.com/opensandbox/opensandbox/internal/auth"- "github.com/opensandbox/opensandbox/internal/ecr"- pb "github.com/opensandbox/opensandbox/proto/worker"-)--func (s *Server) buildTemplate(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",- })- }-- var req struct {- Name string `json:"name"`- Dockerfile string `json:"dockerfile"`- Tag string `json:"tag"`- }- if err := c.Bind(&req); err != nil {- return c.JSON(http.StatusBadRequest, map[string]string{- "error": "invalid request body: " + err.Error(),- })- }- if req.Name == "" || req.Dockerfile == "" {- return c.JSON(http.StatusBadRequest, map[string]string{- "error": "name and dockerfile are required",- })- }- if req.Tag == "" {- req.Tag = "latest"- }-- ctx := c.Request().Context()-- // Compute ECR image reference- var ecrImageRef string- if s.ecrConfig != nil && s.ecrConfig.IsConfigured() {- ecrImageRef = ecr.ImageRef(s.ecrConfig, orgID.String(), req.Name, req.Tag)- }-- // Pick a worker and dispatch build via gRPC- if s.workerRegistry == nil {- return c.JSON(http.StatusServiceUnavailable, map[string]string{- "error": "no workers available for template builds",- })- }-- region := s.region- if region == "" {- region = "use2"- }-- _, grpcClient, err := s.workerRegistry.GetLeastLoadedWorker(region)- if err != nil {- return c.JSON(http.StatusServiceUnavailable, map[string]string{- "error": "no workers available: " + err.Error(),- })- }-- grpcCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)- defer cancel()-- grpcResp, err := grpcClient.BuildTemplate(grpcCtx, &pb.BuildTemplateRequest{- Name: req.Name,- Dockerfile: req.Dockerfile,- Tag: req.Tag,- EcrImageRef: ecrImageRef,- })- if err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": "template build failed: " + err.Error(),- })- }-- // Insert template record in DB- tmpl, err := s.store.CreateTemplate(ctx, &orgID, req.Name, req.Tag, grpcResp.ImageRef, &req.Dockerfile, false)- if err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": "failed to save template: " + err.Error(),- })- }-- return c.JSON(http.StatusCreated, tmpl)-}--func (s *Server) listTemplates(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",- })- }-- templates, err := s.store.ListTemplates(c.Request().Context(), orgID)- if err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })- }-- return c.JSON(http.StatusOK, templates)-}--func (s *Server) getTemplate(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",- })- }-- name := c.Param("name")- tmpl, err := s.store.GetTemplateByName(c.Request().Context(), orgID, name)- if err != nil {- return c.JSON(http.StatusNotFound, map[string]string{- "error": err.Error(),- })- }-- return c.JSON(http.StatusOK, tmpl)-}--func (s *Server) deleteTemplate(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",- })- }-- name := c.Param("name")-- // Look up template first- tmpl, err := s.store.GetTemplateByName(c.Request().Context(), orgID, name)- if err != nil {- return c.JSON(http.StatusNotFound, map[string]string{- "error": err.Error(),- })- }-- if tmpl.IsPublic {- return c.JSON(http.StatusForbidden, map[string]string{- "error": "cannot delete public templates",- })- }-- if err := s.store.DeleteTemplateForOrg(c.Request().Context(), tmpl.ID, orgID); err != nil {- return c.JSON(http.StatusInternalServerError, map[string]string{- "error": err.Error(),- })- }-- return c.NoContent(http.StatusNoContent)-}diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.goindex 44401acf..7397c149 100644--- a/internal/firecracker/manager.go+++ b/internal/firecracker/manager.go@@ -869,13 +869,9 @@ func (m *Manager) Wake(ctx context.Context, sandboxID string, checkpointKey strireturn m.doWake(ctx, sandboxID, checkpointKey, checkpointStore, timeout)}-// SaveAsTemplate snapshots a running sandbox's drives for use as a template.+// SaveAsTemplate is deprecated. Use the declarative image builder instead.func (m *Manager) SaveAsTemplate(ctx context.Context, sandboxID, templateID string, checkpointStore *storage.CheckpointStore, onReady func()) (rootfsKey, workspaceKey string, err error) {- vm, err := m.getVM(sandboxID)- if err != nil {- return "", "", err- }- return m.doSaveAsTemplate(ctx, vm, templateID, checkpointStore, onReady)+ return "", "", fmt.Errorf("deprecated: use declarative image builder")}// getVM retrieves a VM by ID (read-locked).diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex 73355055..80cb2215 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -15,11 +15,13 @@ import ("google.golang.org/grpc""google.golang.org/grpc/keepalive"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/status"+"github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/sparse""github.com/opensandbox/opensandbox/internal/storage"- "github.com/opensandbox/opensandbox/internal/template""github.com/opensandbox/opensandbox/pkg/types"pb "github.com/opensandbox/opensandbox/proto/worker")@@ -32,20 +34,18 @@ type GRPCServer struct {ptyManager *sandbox.PTYManagersandboxDBs *sandbox.SandboxDBManagercheckpointStore *storage.CheckpointStore- builder *template.Builderstore *db.Store // nil if no DB configuredserver *grpc.Server}// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.-func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder *template.Builder, store *db.Store) *GRPCServer {+func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, store *db.Store) *GRPCServer {s := &GRPCServer{manager: mgr,router: router,ptyManager: ptyMgr,sandboxDBs: sandboxDBs,checkpointStore: checkpointStore,- builder: builder,store: store,server: grpc.NewServer(grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{@@ -408,53 +408,11 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequest}func (s *GRPCServer) BuildTemplate(ctx context.Context, req *pb.BuildTemplateRequest) (*pb.BuildTemplateResponse, error) {- if s.builder == nil {- return nil, fmt.Errorf("template builder not configured on this worker")- }-- imageRef, buildLog, err := s.builder.Build(ctx, req.Dockerfile, req.Name, req.Tag, req.EcrImageRef)- if err != nil {- return nil, fmt.Errorf("template build failed: %w", err)- }-- return &pb.BuildTemplateResponse{- ImageRef: imageRef,- BuildLog: buildLog,- }, nil+ return nil, status.Errorf(codes.Unimplemented, "deprecated")}func (s *GRPCServer) SaveAsTemplate(ctx context.Context, req *pb.SaveAsTemplateRequest) (*pb.SaveAsTemplateResponse, error) {- if s.checkpointStore == nil {- return nil, fmt.Errorf("checkpoint store not configured on this worker")- }-- templateID := req.TemplateId- if _, err := uuid.Parse(templateID); err != nil {- return nil, fmt.Errorf("invalid template ID: %w", err)- }-- // The onReady callback marks the template as ready in the DB when the async S3 upload completes.- var onReady func()- if s.store != nil {- tid, _ := uuid.Parse(templateID)- onReady = func() {- if err := s.store.SetTemplateReady(context.Background(), tid); err != nil {- log.Printf("grpc: SaveAsTemplate: failed to mark template %s ready: %v", templateID, err)- } else {- log.Printf("grpc: SaveAsTemplate: template %s is now ready", templateID)- }- }- }-- rootfsKey, workspaceKey, err := s.manager.SaveAsTemplate(ctx, req.SandboxId, templateID, s.checkpointStore, onReady)- if err != nil {- return nil, fmt.Errorf("save-as-template failed: %w", err)- }-- return &pb.SaveAsTemplateResponse{- RootfsS3Key: rootfsKey,- WorkspaceS3Key: workspaceKey,- }, nil+ return nil, status.Errorf(codes.Unimplemented, "deprecated")}func (s *GRPCServer) CreateCheckpoint(ctx context.Context, req *pb.CreateCheckpointRequest) (*pb.CreateCheckpointResponse, error) {diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.pyindex f9d472f9..5acd20f6 100644--- a/sdks/python/opencomputer/__init__.py+++ b/sdks/python/opencomputer/__init__.py@@ -6,7 +6,6 @@ from opencomputer.commands import Commands, ProcessResultfrom opencomputer.image import Imagefrom opencomputer.pty import Pty, PtySessionfrom opencomputer.snapshot import Snapshots-from opencomputer.template import Template__all__ = ["Sandbox",@@ -17,7 +16,6 @@ __all__ = ["Pty","PtySession","Snapshots",- "Template",]__version__ = "0.5.0"diff --git a/sdks/python/opencomputer/template.py b/sdks/python/opencomputer/template.pydeleted file mode 100644index 7c026e14..00000000--- a/sdks/python/opencomputer/template.py+++ /dev/null@@ -1,75 +0,0 @@-"""Template management for custom sandbox environments."""--from __future__ import annotations--from dataclasses import dataclass--import httpx---@dataclass-class TemplateInfo:- """Template metadata."""-- template_id: str- name: str- tag: str- status: str---@dataclass-class Template:- """Template management operations."""-- _client: httpx.AsyncClient-- @classmethod- def _from_client(cls, client: httpx.AsyncClient) -> Template:- return cls(_client=client)-- async def build(self, name: str, dockerfile: str) -> TemplateInfo:- """Build a new template from a Dockerfile."""- resp = await self._client.post(- "/templates",- json={"name": name, "dockerfile": dockerfile},- timeout=300.0,- )- resp.raise_for_status()- data = resp.json()- return TemplateInfo(- template_id=data["templateID"],- name=data["name"],- tag=data.get("tag", "latest"),- status=data.get("status", "ready"),- )-- async def list(self) -> list[TemplateInfo]:- """List all available templates."""- resp = await self._client.get("/templates")- resp.raise_for_status()- return [- TemplateInfo(- template_id=t["templateID"],- name=t["name"],- tag=t.get("tag", "latest"),- status=t.get("status", "ready"),- )- for t in resp.json()- ]-- async def get(self, name: str) -> TemplateInfo:- """Get template details by name."""- resp = await self._client.get(f"/templates/{name}")- resp.raise_for_status()- data = resp.json()- return TemplateInfo(- template_id=data["templateID"],- name=data["name"],- tag=data.get("tag", "latest"),- status=data.get("status", "ready"),- )-- async def delete(self, name: str) -> None:- """Delete a template."""- resp = await self._client.delete(f"/templates/{name}")- resp.raise_for_status()diff --git a/sdks/typescript/examples/test-default-template.ts b/sdks/typescript/examples/test-default-template.tsdeleted file mode 100644index 181fbcfd..00000000--- a/sdks/typescript/examples/test-default-template.ts+++ /dev/null@@ -1,184 +0,0 @@-/**- * Default Template Verification Test- *- * Verifies that the "default" template image contains all expected packages:- * 1. Python 3 + pip + venv- * 2. Node.js 20 + npm- * 3. Build tools (gcc, g++, make, cmake)- * 4. Git + git-lfs- * 5. Common utilities (curl, wget, jq, tar, zip, unzip, etc.)- * 6. System libraries (libssl, libffi, zlib, sqlite3)- * 7. Locale is set to en_US.UTF-8- *- * Usage:- * npx tsx examples/test-default-template.ts- */--import { Sandbox } from "../src/index";--function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }--let passed = 0;-let failed = 0;--function check(desc: string, condition: boolean, detail?: string) {- if (condition) {- green(desc);- passed++;- } else {- red(`${desc}${detail ? ` (${detail})` : ""}`);- failed++;- }-}--/** Run a command and check it exits 0 and stdout contains expected substring */-async function expectCommand(- sandbox: Sandbox,- desc: string,- cmd: string,- opts?: { contains?: string; versionMin?: string },-) {- const result = await sandbox.commands.run(cmd);- const out = result.stdout.trim() || result.stderr.trim();- dim(`$ ${cmd}`);- dim(` → ${out}`);-- if (result.exitCode !== 0) {- check(desc, false, `exit code ${result.exitCode}`);- return out;- }-- if (opts?.contains) {- check(desc, out.toLowerCase().includes(opts.contains.toLowerCase()),- `expected "${opts.contains}" in output`);- } else {- check(desc, true);- }- return out;-}--async function main() {- bold("\n╔══════════════════════════════════════════════════╗");- bold("║ Default Template Verification Test ║");- bold("╚══════════════════════════════════════════════════╝\n");-- let sandbox: Sandbox | null = null;-- try {- sandbox = await Sandbox.create({ template: "default", timeout: 120 });- green(`Created sandbox: ${sandbox.sandboxId}`);- console.log();-- // ── 1. Python ───────────────────────────────────────────────────- bold("━━━ 1. Python 3 ━━━\n");-- await expectCommand(sandbox, "python3 is installed", "python3 --version", { contains: "Python 3" });- await expectCommand(sandbox, "python symlink works", "python --version", { contains: "Python 3" });- await expectCommand(sandbox, "pip3 is installed", "pip3 --version", { contains: "pip" });- await expectCommand(sandbox, "python3-venv is available", "python3 -m venv --help 2>&1 | head -1", { contains: "usage" });-- // Verify pip can install a package- const pipInstall = await sandbox.commands.run("pip3 install --no-cache-dir cowsay 2>&1", { timeout: 30 });- check("pip install works", pipInstall.exitCode === 0, `exit ${pipInstall.exitCode}`);- const cowsay = await sandbox.commands.run("python3 -c 'import cowsay; print(\"pip-ok\")'");- check("installed Python package importable", cowsay.stdout.trim().includes("pip-ok"));- console.log();-- // ── 2. Node.js ──────────────────────────────────────────────────- bold("━━━ 2. Node.js 20 + npm ━━━\n");-- const nodeVersion = await expectCommand(sandbox, "node is installed", "node --version");- check("Node.js is v20.x", nodeVersion.startsWith("v20"), `got ${nodeVersion}`);- await expectCommand(sandbox, "npm is installed", "npm --version");-- // Verify npm can install a package- await sandbox.commands.run("mkdir -p /tmp/npm-test && cd /tmp/npm-test && npm init -y 2>&1", { timeout: 10 });- const npmInstall = await sandbox.commands.run("cd /tmp/npm-test && npm install is-odd 2>&1", { timeout: 30 });- check("npm install works", npmInstall.exitCode === 0, `exit ${npmInstall.exitCode}`);- const nodeRun = await sandbox.commands.run('node -e "console.log(require(\'is-odd\')(3))"', { cwd: "/tmp/npm-test" });- check("installed npm package works", nodeRun.stdout.trim() === "true", `got "${nodeRun.stdout.trim()}"`);- console.log();-- // ── 3. Build tools ──────────────────────────────────────────────- bold("━━━ 3. Build tools ━━━\n");-- await expectCommand(sandbox, "gcc is installed", "gcc --version 2>&1 | head -1", { contains: "gcc" });- await expectCommand(sandbox, "g++ is installed", "g++ --version 2>&1 | head -1", { contains: "g++" });- await expectCommand(sandbox, "make is installed", "make --version 2>&1 | head -1", { contains: "make" });- await expectCommand(sandbox, "cmake is installed", "cmake --version 2>&1 | head -1", { contains: "cmake" });- await expectCommand(sandbox, "pkg-config is installed", "pkg-config --version");-- // Verify compilation works end-to-end- await sandbox.files.write("/tmp/hello.c", '#include <stdio.h>\nint main() { printf("compiled-ok\\n"); return 0; }');- const compile = await sandbox.commands.run("gcc -o /tmp/hello /tmp/hello.c && /tmp/hello");- check("C compilation + execution works", compile.stdout.trim() === "compiled-ok", `got "${compile.stdout.trim()}"`);- console.log();-- // ── 4. Git ──────────────────────────────────────────────────────- bold("━━━ 4. Git ━━━\n");-- await expectCommand(sandbox, "git is installed", "git --version", { contains: "git version" });- await expectCommand(sandbox, "git-lfs is installed", "git lfs version 2>&1 | head -1", { contains: "git-lfs" });- console.log();-- // ── 5. Networking & utilities ────────────────────────────────────- bold("━━━ 5. Networking & common utilities ━━━\n");-- await expectCommand(sandbox, "curl is installed", "curl --version 2>&1 | head -1", { contains: "curl" });- await expectCommand(sandbox, "wget is installed", "wget --version 2>&1 | head -1", { contains: "wget" });- await expectCommand(sandbox, "ssh client is installed", "ssh -V 2>&1", { contains: "OpenSSH" });- await expectCommand(sandbox, "jq is installed", "jq --version", { contains: "jq" });- await expectCommand(sandbox, "tar is installed", "tar --version 2>&1 | head -1", { contains: "tar" });- await expectCommand(sandbox, "zip is installed", "zip --version 2>&1 | head -2 | tail -1", { contains: "zip" });- await expectCommand(sandbox, "unzip is installed", "unzip -v 2>&1 | head -1", { contains: "unzip" });- await expectCommand(sandbox, "rsync is installed", "rsync --version 2>&1 | head -1", { contains: "rsync" });- await expectCommand(sandbox, "htop is installed", "htop --version 2>&1 | head -1", { contains: "htop" });- await expectCommand(sandbox, "tree is installed", "tree --version 2>&1", { contains: "tree" });- console.log();-- // ── 6. System libraries ─────────────────────────────────────────- bold("━━━ 6. System libraries ━━━\n");-- await expectCommand(sandbox, "sqlite3 is installed", "sqlite3 --version 2>&1 | head -1");- await expectCommand(sandbox, "libssl headers present", "test -f /usr/include/openssl/ssl.h && echo ok", { contains: "ok" });- await expectCommand(sandbox, "libffi headers present", "test -f /usr/include/ffi.h && echo ok || (test -d /usr/include/*/ffi.h 2>/dev/null && echo ok || dpkg -L libffi-dev 2>/dev/null | grep ffi.h | head -1)", { contains: "ffi" });- await expectCommand(sandbox, "zlib headers present", "test -f /usr/include/zlib.h && echo ok", { contains: "ok" });- console.log();-- // ── 7. Locale ───────────────────────────────────────────────────- bold("━━━ 7. Locale ━━━\n");-- await expectCommand(sandbox, "en_US.UTF-8 locale is available", "locale -a 2>&1 | grep -i en_US.utf8", { contains: "en_US" });- console.log();-- // ── 8. Workspace ────────────────────────────────────────────────- bold("━━━ 8. Workspace directory ━━━\n");-- await expectCommand(sandbox, "/workspace exists", "test -d /workspace && echo ok", { contains: "ok" });- console.log();-- } catch (err: any) {- red(`Fatal error: ${err.message}`);- if (err.stack) dim(err.stack);- failed++;- } finally {- if (sandbox) {- await sandbox.kill();- green("Sandbox killed");- }- }-- // --- Summary ---- bold("========================================");- bold(` Results: ${passed} passed, ${failed} failed`);- bold("========================================\n");- if (failed > 0) process.exit(1);-}--main().catch((err) => {- console.error("Fatal error:", err);- process.exit(1);-});diff --git a/sdks/typescript/examples/test-multi-template.ts b/sdks/typescript/examples/test-multi-template.tsdeleted file mode 100644index 01a4b36c..00000000--- a/sdks/typescript/examples/test-multi-template.ts+++ /dev/null@@ -1,154 +0,0 @@-/**- * Multi-Template Production Test- *- * Verifies all 3 templates (base, python, node) create, run commands,- * and have the expected runtimes available.- *- * Usage:- * npx tsx examples/test-multi-template.ts- */--import { Sandbox } from "../src/index";--function green(msg: string) { console.log(`\x1b[32m✓ ${msg}\x1b[0m`); }-function red(msg: string) { console.log(`\x1b[31m✗ ${msg}\x1b[0m`); }-function bold(msg: string) { console.log(`\x1b[1m${msg}\x1b[0m`); }-function dim(msg: string) { console.log(`\x1b[2m ${msg}\x1b[0m`); }--let passed = 0;-let failed = 0;--function check(desc: string, condition: boolean, detail?: string) {- if (condition) {- green(desc);- passed++;- } else {- red(`${desc}${detail ? ` (${detail})` : ""}`);- failed++;- }-}--interface TemplateTest {- template: string;- expectedBinary: string;- versionCmd: string;- versionPrefix: string;- testCmd: string;- testExpected: string;-}--const TEMPLATES: TemplateTest[] = [- {- template: "base",- expectedBinary: "bash",- versionCmd: "bash --version | head -1",- versionPrefix: "GNU bash",- testCmd: "echo 'hello from base'",- testExpected: "hello from base",- },- {- template: "python",- expectedBinary: "python3",- versionCmd: "python3 --version",- versionPrefix: "Python 3",- testCmd: "python3 -c \"print(2 + 2)\"",- testExpected: "4",- },- {- template: "node",- expectedBinary: "node",- versionCmd: "node --version",- versionPrefix: "v",- testCmd: "node -e \"console.log(JSON.stringify({ok:true}))\"",- testExpected: '{"ok":true}',- },-];--async function testTemplate(t: TemplateTest, index: number): Promise<{ passed: number; failed: number }> {- let p = 0;- let f = 0;-- const localCheck = (desc: string, condition: boolean, detail?: string) => {- if (condition) { green(desc); p++; } else { red(`${desc}${detail ? ` (${detail})` : ""}`); f++; }- };-- bold(`\n━━━ Template ${index + 1}/3: "${t.template}" ━━━\n`);- let sandbox: Sandbox | null = null;-- try {- // Create- const start = Date.now();- sandbox = await Sandbox.create({ template: t.template, timeout: 120 });- const createMs = Date.now() - start;- localCheck(`Created ${t.template} sandbox (${createMs}ms)`, true);- dim(`ID: ${sandbox.sandboxId}`);- dim(`Domain: ${sandbox.domain}`);-- // Verify domain assigned- localCheck(`Domain assigned`, !!sandbox.domain);-- // Check expected binary exists- const which = await sandbox.commands.run(`which ${t.expectedBinary}`);- localCheck(`${t.expectedBinary} binary exists`, which.exitCode === 0, which.stderr.trim());-- // Get version- const version = await sandbox.commands.run(t.versionCmd);- localCheck(- `Version starts with "${t.versionPrefix}"`,- version.stdout.trim().startsWith(t.versionPrefix),- version.stdout.trim(),- );- dim(`Version: ${version.stdout.trim()}`);-- // Run template-specific test command- const test = await sandbox.commands.run(t.testCmd);- localCheck(- `Test command output correct`,- test.stdout.trim() === t.testExpected,- `expected "${t.testExpected}", got "${test.stdout.trim()}"`,- );-- // Verify basic file ops work- await sandbox.files.write("/tmp/template-test.txt", `from-${t.template}`);- const content = await sandbox.files.read("/tmp/template-test.txt");- localCheck(`File ops work`, content === `from-${t.template}`);-- // Verify uname (should always be Linux)- const uname = await sandbox.commands.run("uname -s");- localCheck(`Running on Linux`, uname.stdout.trim() === "Linux");-- } catch (err: any) {- red(` Error testing ${t.template}: ${err.message}`);- f++;- } finally {- if (sandbox) {- await sandbox.kill();- dim(`Sandbox killed`);- }- }-- return { passed: p, failed: f };-}--async function main() {- bold("\n╔══════════════════════════════════════════════════╗");- bold("║ Multi-Template Production Test ║");- bold("╚══════════════════════════════════════════════════╝");-- for (let i = 0; i < TEMPLATES.length; i++) {- const result = await testTemplate(TEMPLATES[i], i);- passed += result.passed;- failed += result.failed;- }-- console.log();- bold("========================================");- bold(` Results: ${passed} passed, ${failed} failed`);- bold("========================================\n");- if (failed > 0) process.exit(1);-}--main().catch((err) => {- console.error("Fatal error:", err);- process.exit(1);-});diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.tsindex adf5c76b..37369159 100644--- a/sdks/typescript/src/index.ts+++ b/sdks/typescript/src/index.ts@@ -2,6 +2,5 @@ export { Sandbox, type SandboxOpts, type CheckpointInfo, type PatchInfo, type Paexport { Filesystem, type EntryInfo } from "./filesystem.js";export { Commands, type ProcessResult, type RunOpts } from "./commands.js";export { Pty, type PtySession, type PtyOpts } from "./pty.js";-export { Templates, type TemplateInfo } from "./template.js";export { Image, type ImageManifest, type ImageStep } from "./image.js";export { Snapshots, type SnapshotInfo, type CreateSnapshotOpts } from "./snapshot.js";diff --git a/sdks/typescript/src/template.ts b/sdks/typescript/src/template.tsdeleted file mode 100644index a38b1f25..00000000--- a/sdks/typescript/src/template.ts+++ /dev/null@@ -1,68 +0,0 @@-export interface TemplateInfo {- templateID: string;- name: string;- tag: string;- status: string;-}--export class Templates {- constructor(- private apiUrl: string,- private apiKey: string,- ) {}-- private get headers(): Record<string, string> {- const h: Record<string, string> = { "Content-Type": "application/json" };- if (this.apiKey) h["X-API-Key"] = this.apiKey;- return h;- }-- async build(name: string, dockerfile: string): Promise<TemplateInfo> {- const resp = await fetch(`${this.apiUrl}/templates`, {- method: "POST",- headers: this.headers,- body: JSON.stringify({ name, dockerfile }),- });-- if (!resp.ok) {- throw new Error(`Failed to build template: ${resp.status}`);- }-- return resp.json();- }-- async list(): Promise<TemplateInfo[]> {- const resp = await fetch(`${this.apiUrl}/templates`, {- headers: this.headers,- });-- if (!resp.ok) {- throw new Error(`Failed to list templates: ${resp.status}`);- }-- return resp.json();- }-- async get(name: string): Promise<TemplateInfo> {- const resp = await fetch(`${this.apiUrl}/templates/${name}`, {- headers: this.headers,- });-- if (!resp.ok) {- throw new Error(`Failed to get template: ${resp.status}`);- }-- return resp.json();- }-- async delete(name: string): Promise<void> {- const resp = await fetch(`${this.apiUrl}/templates/${name}`, {- method: "DELETE",- headers: this.headers,- });-- if (!resp.ok) {- throw new Error(`Failed to delete template: ${resp.status}`);- }- }-}diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 036d2083..8eb7772a 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -52,11 +52,6 @@ export const createAPIKey = (name: string) =>export const deleteAPIKey = (keyId: string) =>apiFetch<void>(`/api-keys/${keyId}`, { method: 'DELETE' })-export const getTemplates = () => apiFetch<Template[]>('/templates')--export const deleteTemplate = (id: string) =>- apiFetch<void>(`/templates/${id}`, { method: 'DELETE' })-export const getCheckpoints = (page = 1, perPage = 20) =>apiFetch<CheckpointsResponse>(`/checkpoints?page=${page}&per_page=${perPage}`)@@ -72,12 +67,6 @@ export const deleteImage = (id: string) =>export const getSessionDetail = (sandboxId: string) =>apiFetch<SessionDetail>(`/sessions/${sandboxId}`)-export const saveAsTemplate = (sandboxId: string, name: string, tag?: string) =>- apiFetch<Template>(`/sessions/${sandboxId}/save-as-template`, {- method: 'POST',- body: JSON.stringify({ name, tag: tag || 'latest' }),- })-export const getSessionStats = (sandboxId: string) =>apiFetch<SandboxStats>(`/sessions/${sandboxId}/stats`)@@ -120,19 +109,6 @@ export interface APIKey {createdAt: string}-export interface Template {- id: string- orgId?: string- name: string- tag: string- dockerfile?: string- isPublic: boolean- templateType?: string- createdBySandboxId?: string- status?: string- createdAt: string-}-export interface PreviewURL {id: stringsandboxId: stringdiff --git a/web/src/pages/SessionDetail.tsx b/web/src/pages/SessionDetail.tsxindex a3b2ac39..ae0c0918 100644--- a/web/src/pages/SessionDetail.tsx+++ b/web/src/pages/SessionDetail.tsx@@ -1,7 +1,7 @@import { useState } from 'react'import { useParams, useNavigate } from 'react-router-dom'-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'-import { getSessionDetail, getSessionStats, saveAsTemplate } from '../api/client'+import { useQuery } from '@tanstack/react-query'+import { getSessionDetail, getSessionStats } from '../api/client'import Terminal from '../components/Terminal'function StatusBadge({ status }: { status: string }) {@@ -63,25 +63,12 @@ export default function SessionDetail() {const [showTerminal, setShowTerminal] = useState(false)const [showInternal, setShowInternal] = useState(false)- const queryClient = useQueryClient()- const [showSaveTemplate, setShowSaveTemplate] = useState(false)- const [templateName, setTemplateName] = useState('')-const { data: session, isLoading } = useQuery({queryKey: ['session-detail', sandboxId],queryFn: () => getSessionDetail(sandboxId!),enabled: !!sandboxId,})- const saveTemplateMutation = useMutation({- mutationFn: () => saveAsTemplate(sandboxId!, templateName),- onSuccess: () => {- setShowSaveTemplate(false)- setTemplateName('')- queryClient.invalidateQueries({ queryKey: ['templates'] })- },- })-const { data: stats } = useQuery({queryKey: ['session-stats', sandboxId],queryFn: () => getSessionStats(sandboxId!),@@ -158,17 +145,6 @@ export default function SessionDetail() {</svg>Terminal</button>- <button- className="btn-ghost"- onClick={() => setShowSaveTemplate(true)}- >- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">- <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />- <polyline points="17 21 17 13 7 13 7 21" />- <polyline points="7 3 7 8 15 8" />- </svg>- Save as Template- </button></>)}</div>@@ -182,58 +158,6 @@ export default function SessionDetail() {</div>)}- {/* Save as Template modal */}- {showSaveTemplate && (- <div className="glass-card animate-in" style={{ padding: 22, marginBottom: 16 }}>- <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-tertiary)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 14 }}>- Save as Template- </div>- <div style={{ marginBottom: 14 }}>- <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 6 }}>- Template Name- </label>- <input- type="text"- value={templateName}- onChange={e => setTemplateName(e.target.value)}- placeholder="e.g. my-dev-environment"- className="input"- autoFocus- />- </div>- {saveTemplateMutation.isError && (- <div style={{- color: 'var(--accent-rose)',- fontSize: 12,- marginBottom: 12,- padding: '8px 12px',- background: 'rgba(244, 63, 94, 0.06)',- borderRadius: 'var(--radius-sm)',- border: '1px solid rgba(244, 63, 94, 0.15)',- }}>- {saveTemplateMutation.error?.message || 'Failed to save template'}- </div>- )}- <div style={{ display: 'flex', gap: 8 }}>- <button- className="btn-primary"- onClick={() => saveTemplateMutation.mutate()}- disabled={saveTemplateMutation.isPending || !templateName.trim()}- >- {saveTemplateMutation.isPending ? 'Saving...' : 'Save Template'}- </button>- <button className="btn-ghost" onClick={() => { setShowSaveTemplate(false); setTemplateName('') }}>- Cancel- </button>- </div>- {saveTemplateMutation.isPending && (- <div style={{ marginTop: 12, fontSize: 12, color: 'var(--text-tertiary)' }}>- Snapshotting sandbox filesystem. This may take a moment...- </div>- )}- </div>- )}-{/* Stats cards — only for running sandboxes */}{session.status === 'running' && (<div className="glass-card animate-in stagger-1" style={{ padding: 20, marginBottom: 16 }}>