Skip to content

An open-source, faster Devin alternative

TypeScript

adjust ui, remove placeholders, add template support

Brian Reardon391aa00a9962
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 69e33021..57d544df 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -14,11 +14,11 @@ import (
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/ecr"
"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"
)
func main() {
@@ -32,9 +32,6 @@ func main() {
// Initialize Podman (optional in server mode — no container runtime needed)
var mgr *sandbox.Manager
var ptyMgr *sandbox.PTYManager
- var registry *template.Registry
- var builder *template.Builder
-
podmanClient, err := podman.NewClient()
if err != nil {
if cfg.Mode == "server" {
@@ -59,9 +56,6 @@ func main() {
podmanPath, _ := exec.LookPath("podman")
ptyMgr = sandbox.NewPTYManager(podmanPath, podmanClient.AuthFile())
defer ptyMgr.CloseAll()
-
- registry = template.NewRegistry()
- builder = template.NewBuilder(podmanClient, registry)
}
}
@@ -134,6 +128,19 @@ func main() {
}
}
+ // Initialize ECR config for template images (if configured)
+ if cfg.ECRRegistry != "" {
+ ecrCfg := &ecr.Config{
+ Registry: cfg.ECRRegistry,
+ Repository: cfg.ECRRepository,
+ Region: cfg.S3Region, // reuse S3 region (same AWS account)
+ AccessKey: cfg.S3AccessKeyID,
+ SecretKey: cfg.S3SecretAccessKey,
+ }
+ opts.ECRConfig = ecrCfg
+ log.Printf("opensandbox: ECR configured (registry=%s, repo=%s)", cfg.ECRRegistry, cfg.ECRRepository)
+ }
+
// Initialize SandboxRouter for rolling timeouts, auto-wake, and command routing
if mgr != nil {
workerID := cfg.WorkerID
@@ -192,9 +199,6 @@ func main() {
// Create API server
server := api.NewServer(mgr, ptyMgr, cfg.APIKey, opts)
- if registry != nil && builder != nil {
- server.SetTemplateDeps(registry, builder)
- }
// Start NATS sync consumer if both PG and NATS are configured
if opts.Store != nil && cfg.NATSURL != "" {
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index c9dba021..58bcb7e0 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -12,11 +12,13 @@ import (
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/config"
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/ecr"
"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"
)
@@ -122,8 +124,22 @@ func main() {
defer metricsSrv.Close()
log.Println("opensandbox-worker: metrics server started on :9091")
+ // Initialize ECR config + template builder for building custom templates
+ var ecrCfg *ecr.Config
+ if cfg.ECRRegistry != "" {
+ ecrCfg = &ecr.Config{
+ Registry: cfg.ECRRegistry,
+ Repository: cfg.ECRRepository,
+ Region: cfg.S3Region,
+ AccessKey: cfg.S3AccessKeyID,
+ SecretKey: cfg.S3SecretAccessKey,
+ }
+ log.Printf("opensandbox-worker: ECR configured (registry=%s, repo=%s)", cfg.ECRRegistry, cfg.ECRRepository)
+ }
+ builder := template.NewBuilder(client, ecrCfg)
+
// Start gRPC server for control plane communication
- grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore, sbRouter)
+ grpcServer := worker.NewGRPCServer(mgr, ptyMgr, sandboxDBMgr, checkpointStore, sbRouter, builder)
grpcAddr := ":9090"
log.Printf("opensandbox-worker: starting gRPC server on %s", grpcAddr)
go func() {
diff --git a/go.mod b/go.mod
index ea1e94ca..2877b4e9 100644
--- a/go.mod
+++ b/go.mod
@@ -5,6 +5,7 @@ go 1.23.0
require (
github.com/aws/aws-sdk-go-v2 v1.41.1
github.com/aws/aws-sdk-go-v2/credentials v1.19.8
+ github.com/aws/aws-sdk-go-v2/service/ecr v1.55.2
github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0
github.com/creack/pty v1.1.24
github.com/golang-jwt/jwt/v5 v5.2.1
diff --git a/go.sum b/go.sum
index fde07db8..4fe6ef13 100644
--- a/go.sum
+++ b/go.sum
@@ -10,6 +10,8 @@ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 h1:JqcdRG//czea7Ppjb+g/n4o8i/R50aTBHkA7vu0lK+k=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17/go.mod h1:CO+WeGmIdj/MlPel2KwID9Gt7CNq4M65HUfBW97liM0=
+github.com/aws/aws-sdk-go-v2/service/ecr v1.55.2 h1:eEiC82g/AJpNtBB73Par9iO/EbWXcl8vh6tbM8wb+EM=
+github.com/aws/aws-sdk-go-v2/service/ecr v1.55.2/go.mod h1:cpYRXx5BkmS3mwWRKPbWSPKmyAUNL7aLWAPiiinwk/U=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 h1:Z5EiPIzXKewUQK0QTMkutjiaPVeVYXX7KIqhXu/0fXs=
diff --git a/internal/api/dashboard.go b/internal/api/dashboard.go
index fdac608c..d54f7796 100644
--- a/internal/api/dashboard.go
+++ b/internal/api/dashboard.go
@@ -133,7 +133,7 @@ func (s *Server) dashboardCreateAPIKey(c echo.Context) error {
})
}
-// dashboardDeleteAPIKey revokes an API key.
+// dashboardDeleteAPIKey revokes an API key (scoped to the authenticated org).
func (s *Server) dashboardDeleteAPIKey(c echo.Context) error {
if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
@@ -141,6 +141,13 @@ func (s *Server) dashboardDeleteAPIKey(c echo.Context) error {
})
}
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{
+ "error": "org context required",
+ })
+ }
+
keyID, err := uuid.Parse(c.Param("keyId"))
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{
@@ -148,7 +155,7 @@ func (s *Server) dashboardDeleteAPIKey(c echo.Context) error {
})
}
- if err := s.store.DeleteAPIKey(c.Request().Context(), keyID); err != nil {
+ if err := s.store.DeleteAPIKeyForOrg(c.Request().Context(), keyID, orgID); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": err.Error(),
})
@@ -215,3 +222,65 @@ func (s *Server) dashboardUpdateOrg(c echo.Context) error {
return c.JSON(http.StatusOK, org)
}
+
+// 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(),
+ })
+ }
+
+ return c.JSON(http.StatusOK, templates)
+}
+
+// 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)
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 401c28fa..16807a35 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -13,6 +13,7 @@ import (
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/ecr"
"github.com/opensandbox/opensandbox/internal/proxy"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
@@ -28,7 +29,6 @@ type Server struct {
manager *sandbox.Manager
router *sandbox.SandboxRouter // routes all sandbox interactions (state machine, auto-wake, rolling timeout)
ptyManager *sandbox.PTYManager
- templates *templateDeps
store *db.Store // nil in combined/dev mode without PG
jwtIssuer *auth.JWTIssuer // nil if JWT not configured
mode string // "server", "worker", "combined"
@@ -40,6 +40,7 @@ type Server struct {
workerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
checkpointStore *storage.CheckpointStore // nil if hibernation not configured
sandboxDomain string // base domain for sandbox subdomains
+ ecrConfig *ecr.Config // nil if ECR not configured
}
// ServerOpts holds optional dependencies for the API server.
@@ -57,6 +58,7 @@ type ServerOpts struct {
WorkOSConfig *auth.WorkOSConfig // nil if WorkOS not configured
WorkerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
CheckpointStore *storage.CheckpointStore // nil if hibernation not configured
+ ECRConfig *ecr.Config // nil if ECR not configured
}
// NewServer creates a new API server with all routes configured.
@@ -83,6 +85,7 @@ func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string,
s.workerRegistry = opts.WorkerRegistry
s.checkpointStore = opts.CheckpointStore
s.sandboxDomain = opts.SandboxDomain
+ s.ecrConfig = opts.ECRConfig
}
// Global middleware
@@ -164,6 +167,9 @@ func NewServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string,
dash.DELETE("/api-keys/:keyId", s.dashboardDeleteAPIKey)
dash.GET("/org", s.dashboardGetOrg)
dash.PUT("/org", s.dashboardUpdateOrg)
+ dash.GET("/templates", s.dashboardListTemplates)
+ dash.POST("/templates", s.dashboardBuildTemplate)
+ dash.DELETE("/templates/:id", s.dashboardDeleteTemplate)
}
// Auto-detect FrontendURL for dev: if web/dist doesn't exist, assume Vite dev on :3000
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index fc1280f5..1fa03480 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -128,6 +128,15 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
})
}
+ // Resolve template image from DB (org-scoped lookup with public fallback)
+ var imageRef string
+ if s.store != nil && hasOrg {
+ tmpl, err := s.store.GetTemplateByName(ctx, orgID, cfg.Template)
+ if err == nil {
+ imageRef = tmpl.ImageRef
+ }
+ }
+
// Dispatch via persistent gRPC connection
grpcCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
@@ -139,6 +148,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
MemoryMb: int32(cfg.MemoryMB),
CpuCount: int32(cfg.CpuCount),
NetworkEnabled: cfg.NetworkEnabled,
+ ImageRef: imageRef,
})
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
diff --git a/internal/api/templates.go b/internal/api/templates.go
index 29bc1a94..b3353177 100644
--- a/internal/api/templates.go
+++ b/internal/api/templates.go
@@ -1,51 +1,96 @@
package api
import (
+ "context"
"net/http"
+ "time"
"github.com/labstack/echo/v4"
- "github.com/opensandbox/opensandbox/internal/template"
- "github.com/opensandbox/opensandbox/pkg/types"
+ "github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/ecr"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
)
-// templateDeps holds template-related dependencies injected into the server.
-type templateDeps struct {
- registry *template.Registry
- builder *template.Builder
-}
-
-// SetTemplateDeps sets the template dependencies on the server.
-func (s *Server) SetTemplateDeps(registry *template.Registry, builder *template.Builder) {
- s.templates = &templateDeps{
- registry: registry,
- builder: builder,
- }
-}
-
func (s *Server) buildTemplate(c echo.Context) error {
- if s.templates == nil {
+ if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
- "error": "template service not configured",
+ "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 types.TemplateBuildRequest
+ 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"
+ }
- tmpl, err := s.templates.builder.Build(c.Request().Context(), req.Dockerfile, req.Name)
+ _, 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": err.Error(),
+ "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(),
})
}
@@ -53,22 +98,45 @@ func (s *Server) buildTemplate(c echo.Context) error {
}
func (s *Server) listTemplates(c echo.Context) error {
- if s.templates == nil {
- return c.JSON(http.StatusOK, []types.Template{})
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "database not configured",
+ })
}
- return c.JSON(http.StatusOK, s.templates.registry.List())
+ 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.templates == nil {
+ if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
- "error": "template service not configured",
+ "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.templates.registry.Get(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(),
@@ -79,18 +147,40 @@ func (s *Server) getTemplate(c echo.Context) error {
}
func (s *Server) deleteTemplate(c echo.Context) error {
- if s.templates == nil {
+ if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
- "error": "template service not configured",
+ "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")
- if err := s.templates.registry.Delete(name); err != nil {
+
+ // 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/auth/oauth_handlers.go b/internal/auth/oauth_handlers.go
index d64b7da6..9a790097 100644
--- a/internal/auth/oauth_handlers.go
+++ b/internal/auth/oauth_handlers.go
@@ -108,8 +108,8 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {
name = authResult.User.Email
}
- // Determine org name — use organization ID or default
- orgName := "Default"
+ // Determine org name — use organization ID, or create a personal org per user
+ orgName := authResult.User.Email // personal org keyed by email
if authResult.OrganizationID != "" {
orgName = authResult.OrganizationID
}
diff --git a/internal/auth/workos.go b/internal/auth/workos.go
index aa65466f..6e206e48 100644
--- a/internal/auth/workos.go
+++ b/internal/auth/workos.go
@@ -162,8 +162,11 @@ func (w *WorkOSMiddleware) ProvisionOrgAndUser(ctx context.Context, email, name,
}, nil
}
- // Create org (slug from org name)
- slug := strings.ToLower(strings.ReplaceAll(orgName, " ", "-"))
+ // Create org (slug from org name — sanitize for emails and special chars)
+ slug := strings.ToLower(orgName)
+ slug = strings.ReplaceAll(slug, "@", "-at-")
+ slug = strings.ReplaceAll(slug, ".", "-")
+ slug = strings.ReplaceAll(slug, " ", "-")
org, err := w.store.GetOrgBySlug(ctx, slug)
if err != nil {
org, err = w.store.CreateOrg(ctx, orgName, slug)
diff --git a/internal/config/config.go b/internal/config/config.go
index 9e791904..6a9d4923 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -52,6 +52,10 @@ type Config struct {
S3AccessKeyID string
S3SecretAccessKey string
S3ForcePathStyle bool // true for R2/MinIO
+
+ // ECR for template images
+ ECRRegistry string // e.g. "086971355112.dkr.ecr.us-east-2.amazonaws.com"
+ ECRRepository string // e.g. "opensandbox-templates"
}
// Load reads configuration from environment variables with sensible defaults.
@@ -89,6 +93,9 @@ func Load() (*Config, error) {
S3AccessKeyID: os.Getenv("OPENSANDBOX_S3_ACCESS_KEY_ID"),
S3SecretAccessKey: os.Getenv("OPENSANDBOX_S3_SECRET_ACCESS_KEY"),
S3ForcePathStyle: os.Getenv("OPENSANDBOX_S3_FORCE_PATH_STYLE") == "true",
+
+ ECRRegistry: os.Getenv("OPENSANDBOX_ECR_REGISTRY"),
+ ECRRepository: envOrDefault("OPENSANDBOX_ECR_REPOSITORY", "opensandbox-templates"),
}
// Default S3 region to worker region for same-region storage
diff --git a/internal/db/migrations/004_seed_templates.up.sql b/internal/db/migrations/004_seed_templates.up.sql
new file mode 100644
index 00000000..f25766e2
--- /dev/null
+++ b/internal/db/migrations/004_seed_templates.up.sql
@@ -0,0 +1,12 @@
+-- Partial unique index for public templates (NULL org_id).
+-- The existing UNIQUE(org_id, name, tag) doesn't enforce uniqueness when org_id IS NULL
+-- because NULL != NULL in SQL.
+CREATE UNIQUE INDEX IF NOT EXISTS idx_templates_public_name_tag
+ ON templates (name, tag) WHERE org_id IS NULL;
+
+-- Seed built-in public templates
+INSERT INTO templates (org_id, name, tag, image_ref, is_public) VALUES
+ (NULL, 'base', 'latest', 'docker.io/library/ubuntu:22.04', true),
+ (NULL, 'python', 'latest', 'docker.io/library/python:3.12-slim', true),
+ (NULL, 'node', 'latest', 'docker.io/library/node:20-slim', true)
+ON CONFLICT DO NOTHING;
diff --git a/internal/db/store.go b/internal/db/store.go
index dac49bad..8dd0a67e 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -67,6 +67,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{1, "migrations/001_initial.up.sql"},
{2, "migrations/002_user_sessions.up.sql"},
{3, "migrations/003_checkpoint_hibernation.up.sql"},
+ {4, "migrations/004_seed_templates.up.sql"},
}
for _, m := range migrations {
@@ -279,6 +280,18 @@ func (s *Store) DeleteAPIKey(ctx context.Context, id uuid.UUID) error {
return err
}
+// DeleteAPIKeyForOrg deletes an API key only if it belongs to the given org.
+func (s *Store) DeleteAPIKeyForOrg(ctx context.Context, id uuid.UUID, orgID uuid.UUID) error {
+ result, err := s.pool.Exec(ctx, `DELETE FROM api_keys WHERE id = $1 AND org_id = $2`, id, orgID)
+ if err != nil {
+ return err
+ }
+ if result.RowsAffected() == 0 {
+ return fmt.Errorf("api key not found or not owned by this org")
+ }
+ return nil
+}
+
// --- Sandbox Session operations ---
type SandboxSession struct {
@@ -583,3 +596,85 @@ func (s *Store) UpdateSandboxSessionForWake(ctx context.Context, sandboxID, newW
newWorkerID, sandboxID)
return err
}
+
+// --- Template operations ---
+
+// DBTemplate represents a template record in the database.
+type DBTemplate struct {
+ ID uuid.UUID `json:"id"`
+ OrgID *uuid.UUID `json:"orgId,omitempty"`
+ Name string `json:"name"`
+ Tag string `json:"tag"`
+ ImageRef string `json:"imageRef"`
+ Dockerfile *string `json:"dockerfile,omitempty"`
+ IsPublic bool `json:"isPublic"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+// CreateTemplate inserts a new template record.
+func (s *Store) CreateTemplate(ctx context.Context, orgID *uuid.UUID, name, tag, imageRef string, dockerfile *string, isPublic bool) (*DBTemplate, error) {
+ t := &DBTemplate{}
+ err := s.pool.QueryRow(ctx,
+ `INSERT INTO templates (org_id, name, tag, image_ref, dockerfile, is_public)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ RETURNING id, org_id, name, tag, image_ref, dockerfile, is_public, created_at`,
+ orgID, name, tag, imageRef, dockerfile, isPublic,
+ ).Scan(&t.ID, &t.OrgID, &t.Name, &t.Tag, &t.ImageRef, &t.Dockerfile, &t.IsPublic, &t.CreatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create template: %w", err)
+ }
+ return t, nil
+}
+
+// GetTemplateByName finds a template by name, preferring org-specific over public.
+func (s *Store) GetTemplateByName(ctx context.Context, orgID uuid.UUID, name string) (*DBTemplate, error) {
+ t := &DBTemplate{}
+ err := s.pool.QueryRow(ctx,
+ `SELECT id, org_id, name, tag, image_ref, dockerfile, is_public, created_at
+ FROM templates
+ WHERE name = $1 AND (org_id = $2 OR (is_public = true AND org_id IS NULL))
+ ORDER BY org_id IS NULL ASC
+ LIMIT 1`,
+ name, orgID,
+ ).Scan(&t.ID, &t.OrgID, &t.Name, &t.Tag, &t.ImageRef, &t.Dockerfile, &t.IsPublic, &t.CreatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("template %q not found: %w", name, err)
+ }
+ return t, nil
+}
+
+// ListTemplates returns all templates visible to an org (org-specific + public).
+func (s *Store) ListTemplates(ctx context.Context, orgID uuid.UUID) ([]DBTemplate, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT id, org_id, name, tag, image_ref, dockerfile, is_public, created_at
+ FROM templates
+ WHERE org_id = $1 OR (is_public = true AND org_id IS NULL)
+ ORDER BY is_public DESC, name ASC`,
+ orgID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to list templates: %w", err)
+ }
+ defer rows.Close()
+
+ var templates []DBTemplate
+ for rows.Next() {
+ var t DBTemplate
+ if err := rows.Scan(&t.ID, &t.OrgID, &t.Name, &t.Tag, &t.ImageRef, &t.Dockerfile, &t.IsPublic, &t.CreatedAt); err != nil {
+ return nil, err
+ }
+ templates = append(templates, t)
+ }
+ return templates, nil
+}
+
+// DeleteTemplateForOrg deletes a template only if it belongs to the given org (not public).
+func (s *Store) DeleteTemplateForOrg(ctx context.Context, id uuid.UUID, orgID uuid.UUID) error {
+ result, err := s.pool.Exec(ctx, `DELETE FROM templates WHERE id = $1 AND org_id = $2`, id, orgID)
+ if err != nil {
+ return err
+ }
+ if result.RowsAffected() == 0 {
+ return fmt.Errorf("template not found or not owned by this org")
+ }
+ return nil
+}
diff --git a/internal/ecr/auth.go b/internal/ecr/auth.go
new file mode 100644
index 00000000..85c0a819
--- /dev/null
+++ b/internal/ecr/auth.go
@@ -0,0 +1,76 @@
+package ecr
+
+import (
+ "context"
+ "encoding/base64"
+ "fmt"
+ "strings"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/service/ecr"
+)
+
+// Config holds ECR connection settings.
+type Config struct {
+ Registry string // e.g. "086971355112.dkr.ecr.us-east-2.amazonaws.com"
+ Repository string // e.g. "opensandbox-templates"
+ Region string // e.g. "us-east-2"
+ AccessKey string
+ SecretKey string
+}
+
+// IsConfigured returns true if ECR settings are provided.
+func (c *Config) IsConfigured() bool {
+ return c.Registry != "" && c.Repository != "" && c.AccessKey != "" && c.SecretKey != ""
+}
+
+// GetAuthToken retrieves a Docker-compatible auth token from ECR.
+// Returns (username, password) suitable for `podman login`.
+func GetAuthToken(ctx context.Context, cfg *Config) (string, string, error) {
+ awsCfg := aws.Config{
+ Region: cfg.Region,
+ Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, ""),
+ }
+
+ client := ecr.NewFromConfig(awsCfg)
+ output, err := client.GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{})
+ if err != nil {
+ return "", "", fmt.Errorf("failed to get ECR auth token: %w", err)
+ }
+
+ if len(output.AuthorizationData) == 0 {
+ return "", "", fmt.Errorf("no authorization data returned from ECR")
+ }
+
+ // Token is base64-encoded "username:password"
+ encoded := *output.AuthorizationData[0].AuthorizationToken
+ decoded, err := base64.StdEncoding.DecodeString(encoded)
+ if err != nil {
+ return "", "", fmt.Errorf("failed to decode ECR auth token: %w", err)
+ }
+
+ parts := strings.SplitN(string(decoded), ":", 2)
+ if len(parts) != 2 {
+ return "", "", fmt.Errorf("unexpected ECR auth token format")
+ }
+
+ return parts[0], parts[1], nil
+}
+
+// ImageRef returns the full ECR image reference for an org-scoped template.
+// Format: {registry}/{repo}:{orgPrefix}-{name}-{tag}
+func ImageRef(cfg *Config, orgID, name, tag string) string {
+ // Use first 8 chars of orgID as prefix to keep tags manageable
+ prefix := orgID
+ if len(prefix) > 8 {
+ prefix = prefix[:8]
+ }
+ return fmt.Sprintf("%s/%s:%s-%s-%s", cfg.Registry, cfg.Repository, prefix, name, tag)
+}
+
+// PublicImageRef returns the full ECR image reference for a public template.
+// Format: {registry}/{repo}:public-{name}-{tag}
+func PublicImageRef(cfg *Config, name, tag string) string {
+ return fmt.Sprintf("%s/%s:public-%s-%s", cfg.Registry, cfg.Repository, name, tag)
+}
diff --git a/internal/podman/client.go b/internal/podman/client.go
index 58255a5f..5375addb 100644
--- a/internal/podman/client.go
+++ b/internal/podman/client.go
@@ -307,6 +307,42 @@ func FindFreePort() (int, error) {
return port, nil
}
+// TagImage tags a local image with a new name/reference.
+func (c *Client) TagImage(ctx context.Context, source, target string) error {
+ result, err := c.Run(ctx, "tag", source, target)
+ if err != nil {
+ return fmt.Errorf("failed to tag image: %w", err)
+ }
+ if result.ExitCode != 0 {
+ return fmt.Errorf("podman tag failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))
+ }
+ return nil
+}
+
+// PushImage pushes an image to a remote registry.
+func (c *Client) PushImage(ctx context.Context, imageRef string) error {
+ result, err := c.Run(ctx, "push", imageRef)
+ if err != nil {
+ return fmt.Errorf("failed to push image %s: %w", imageRef, err)
+ }
+ if result.ExitCode != 0 {
+ return fmt.Errorf("podman push failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))
+ }
+ return nil
+}
+
+// LoginRegistry authenticates podman to a container registry.
+func (c *Client) LoginRegistry(ctx context.Context, registry, username, password string) error {
+ result, err := c.Run(ctx, "login", "--username", username, "--password", password, registry)
+ if err != nil {
+ return fmt.Errorf("failed to login to registry %s: %w", registry, err)
+ }
+ if result.ExitCode != 0 {
+ return fmt.Errorf("podman login failed (exit %d): %s", result.ExitCode, strings.TrimSpace(result.Stderr))
+ }
+ return nil
+}
+
// Version returns the podman version string.
func (c *Client) Version(ctx context.Context) (string, error) {
result, err := c.Run(ctx, "version", "--format", "{{.Client.Version}}")
diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.go
index d18e354c..f63eebe8 100644
--- a/internal/sandbox/manager.go
+++ b/internal/sandbox/manager.go
@@ -50,7 +50,10 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
}
image := defaultImage
- if cfg.Template != "" {
+ if cfg.ImageRef != "" {
+ // DB-resolved ECR URI takes precedence
+ image = cfg.ImageRef
+ } else if cfg.Template != "" {
image = resolveTemplateImage(cfg.Template)
}
diff --git a/internal/template/builder.go b/internal/template/builder.go
index ee23d77c..27cd83c8 100644
--- a/internal/template/builder.go
+++ b/internal/template/builder.go
@@ -3,66 +3,100 @@ package template
import (
"context"
"fmt"
+ "log"
"os"
"path/filepath"
- "time"
- "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/ecr"
"github.com/opensandbox/opensandbox/internal/podman"
- "github.com/opensandbox/opensandbox/pkg/types"
)
-// Builder builds container images from Dockerfiles.
+// Builder builds container images from Dockerfiles and pushes to ECR.
type Builder struct {
- podman *podman.Client
- registry *Registry
+ podman *podman.Client
+ ecrConfig *ecr.Config // nil if ECR not configured
}
// NewBuilder creates a new template builder.
-func NewBuilder(client *podman.Client, registry *Registry) *Builder {
+func NewBuilder(client *podman.Client, ecrConfig *ecr.Config) *Builder {
return &Builder{
- podman: client,
- registry: registry,
+ podman: client,
+ ecrConfig: ecrConfig,
}
}
-// Build builds a template from Dockerfile content.
-func (b *Builder) Build(ctx context.Context, dockerfileContent, name string) (*types.Template, error) {
- buildID := uuid.New().String()[:8]
- tag := "latest"
- imageName := fmt.Sprintf("localhost/opensandbox-template/%s:%s", name, tag)
+// Build builds a template from Dockerfile content, tags it, and pushes to ECR.
+// Returns the final ECR image reference and the build log.
+func (b *Builder) Build(ctx context.Context, dockerfile, name, tag, ecrImageRef string) (string, string, error) {
+ if tag == "" {
+ tag = "latest"
+ }
+
+ localImage := fmt.Sprintf("localhost/opensandbox-template/%s:%s", name, tag)
// Write Dockerfile to temp directory
tmpDir, err := os.MkdirTemp("", "opensandbox-build-*")
if err != nil {
- return nil, fmt.Errorf("failed to create temp dir for build: %w", err)
+ return "", "", fmt.Errorf("failed to create temp dir for build: %w", err)
}
defer os.RemoveAll(tmpDir)
dockerfilePath := filepath.Join(tmpDir, "Dockerfile")
- if err := os.WriteFile(dockerfilePath, []byte(dockerfileContent), 0644); err != nil {
- return nil, fmt.Errorf("failed to write Dockerfile: %w", err)
+ if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0644); err != nil {
+ return "", "", fmt.Errorf("failed to write Dockerfile: %w", err)
}
// Build image with podman
- result, err := b.podman.Run(ctx, "build", "-t", imageName, "-f", dockerfilePath, tmpDir)
+ result, err := b.podman.Run(ctx, "build", "-t", localImage, "-f", dockerfilePath, tmpDir)
if err != nil {
- return nil, fmt.Errorf("failed to build template %s: %w", name, err)
+ return "", "", fmt.Errorf("failed to build template %s: %w", name, err)
}
if result.ExitCode != 0 {
- return nil, fmt.Errorf("podman build failed (exit %d): %s", result.ExitCode, result.Stderr)
+ return "", "", fmt.Errorf("podman build failed (exit %d): %s", result.ExitCode, result.Stderr)
}
+ buildLog := result.Stdout + result.Stderr
+
+ // If ECR is configured and an image ref was provided, tag and push
+ if b.ecrConfig != nil && b.ecrConfig.IsConfigured() && ecrImageRef != "" {
+ // Authenticate to ECR
+ username, password, err := ecr.GetAuthToken(ctx, b.ecrConfig)
+ if err != nil {
+ return "", buildLog, fmt.Errorf("failed to get ECR auth: %w", err)
+ }
+
+ if err := b.podman.LoginRegistry(ctx, b.ecrConfig.Registry, username, password); err != nil {
+ return "", buildLog, fmt.Errorf("failed to login to ECR: %w", err)
+ }
- tmpl := &types.Template{
- ID: name,
- Name: name,
- Tag: tag,
- ImageID: imageName,
- BuildID: buildID,
- Status: "ready",
- CreatedAt: time.Now(),
+ // Tag with ECR reference
+ if err := b.podman.TagImage(ctx, localImage, ecrImageRef); err != nil {
+ return "", buildLog, fmt.Errorf("failed to tag image for ECR: %w", err)
+ }
+
+ // Push to ECR
+ log.Printf("template: pushing %s to ECR...", ecrImageRef)
+ if err := b.podman.PushImage(ctx, ecrImageRef); err != nil {
+ return "", buildLog, fmt.Errorf("failed to push image to ECR: %w", err)
+ }
+ log.Printf("template: push complete for %s", ecrImageRef)
+
+ return ecrImageRef, buildLog, nil
+ }
+
+ // No ECR — return local image reference
+ return localImage, buildLog, nil
+}
+
+// RefreshECRAuth authenticates podman to ECR. Call periodically (tokens expire after 12h).
+func (b *Builder) RefreshECRAuth(ctx context.Context) error {
+ if b.ecrConfig == nil || !b.ecrConfig.IsConfigured() {
+ return nil
+ }
+
+ username, password, err := ecr.GetAuthToken(ctx, b.ecrConfig)
+ if err != nil {
+ return fmt.Errorf("failed to get ECR auth: %w", err)
}
- b.registry.Register(tmpl)
- return tmpl, nil
+ return b.podman.LoginRegistry(ctx, b.ecrConfig.Registry, username, password)
}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index dce61fd2..e1c44f74 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -10,6 +10,7 @@ import (
"github.com/opensandbox/opensandbox/internal/sandbox"
"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"
)
@@ -22,17 +23,19 @@ type GRPCServer struct {
ptyManager *sandbox.PTYManager
sandboxDBs *sandbox.SandboxDBManager
checkpointStore *storage.CheckpointStore
+ builder *template.Builder
server *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) *GRPCServer {
+func NewGRPCServer(mgr *sandbox.Manager, ptyMgr *sandbox.PTYManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder *template.Builder) *GRPCServer {
s := &GRPCServer{
manager: mgr,
router: router,
ptyManager: ptyMgr,
sandboxDBs: sandboxDBs,
checkpointStore: checkpointStore,
+ builder: builder,
server: grpc.NewServer(),
}
pb.RegisterSandboxWorkerServer(s.server, s)
@@ -61,6 +64,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
MemoryMB: int(req.MemoryMb),
CpuCount: int(req.CpuCount),
NetworkEnabled: req.NetworkEnabled,
+ ImageRef: req.ImageRef,
}
sb, err := s.manager.Create(ctx, cfg)
@@ -342,3 +346,19 @@ func (s *GRPCServer) WakeSandbox(ctx context.Context, req *pb.WakeSandboxRequest
Status: string(sb.Status),
}, nil
}
+
+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
+}
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index 774d63a1..8f171ee4 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -41,6 +41,7 @@ type SandboxConfig struct {
MemoryMB int `json:"memoryMB,omitempty"` // default 512
Envs map[string]string `json:"envs,omitempty"`
NetworkEnabled bool `json:"networkEnabled,omitempty"`
+ ImageRef string `json:"imageRef,omitempty"` // resolved ECR URI for custom templates
}
// SandboxListResponse is the response for listing sandboxes.
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index a2549f72..7e4c7a07 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -75,6 +75,7 @@ type CreateSandboxRequest struct {
MemoryMb int32 `protobuf:"varint,4,opt,name=memory_mb,json=memoryMb,proto3" json:"memory_mb,omitempty"`
CpuCount int32 `protobuf:"varint,5,opt,name=cpu_count,json=cpuCount,proto3" json:"cpu_count,omitempty"`
NetworkEnabled bool `protobuf:"varint,6,opt,name=network_enabled,json=networkEnabled,proto3" json:"network_enabled,omitempty"`
+ ImageRef string `protobuf:"bytes,7,opt,name=image_ref,json=imageRef,proto3" json:"image_ref,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -151,6 +152,13 @@ func (x *CreateSandboxRequest) GetNetworkEnabled() bool {
return false
}
+func (x *CreateSandboxRequest) GetImageRef() string {
+ if x != nil {
+ return x.ImageRef
+ }
+ return ""
+}
+
type CreateSandboxResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
@@ -1557,18 +1565,139 @@ func (x *WakeSandboxResponse) GetStatus() string {
return ""
}
+type BuildTemplateRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+ Dockerfile string `protobuf:"bytes,2,opt,name=dockerfile,proto3" json:"dockerfile,omitempty"`
+ Tag string `protobuf:"bytes,3,opt,name=tag,proto3" json:"tag,omitempty"`
+ EcrImageRef string `protobuf:"bytes,4,opt,name=ecr_image_ref,json=ecrImageRef,proto3" json:"ecr_image_ref,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *BuildTemplateRequest) Reset() {
+ *x = BuildTemplateRequest{}
+ mi := &file_proto_worker_worker_proto_msgTypes[27]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *BuildTemplateRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BuildTemplateRequest) ProtoMessage() {}
+
+func (x *BuildTemplateRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[27]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use BuildTemplateRequest.ProtoReflect.Descriptor instead.
+func (*BuildTemplateRequest) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{27}
+}
+
+func (x *BuildTemplateRequest) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *BuildTemplateRequest) GetDockerfile() string {
+ if x != nil {
+ return x.Dockerfile
+ }
+ return ""
+}
+
+func (x *BuildTemplateRequest) GetTag() string {
+ if x != nil {
+ return x.Tag
+ }
+ return ""
+}
+
+func (x *BuildTemplateRequest) GetEcrImageRef() string {
+ if x != nil {
+ return x.EcrImageRef
+ }
+ return ""
+}
+
+type BuildTemplateResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ ImageRef string `protobuf:"bytes,1,opt,name=image_ref,json=imageRef,proto3" json:"image_ref,omitempty"`
+ BuildLog string `protobuf:"bytes,2,opt,name=build_log,json=buildLog,proto3" json:"build_log,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *BuildTemplateResponse) Reset() {
+ *x = BuildTemplateResponse{}
+ mi := &file_proto_worker_worker_proto_msgTypes[28]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *BuildTemplateResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*BuildTemplateResponse) ProtoMessage() {}
+
+func (x *BuildTemplateResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_worker_worker_proto_msgTypes[28]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use BuildTemplateResponse.ProtoReflect.Descriptor instead.
+func (*BuildTemplateResponse) Descriptor() ([]byte, []int) {
+ return file_proto_worker_worker_proto_rawDescGZIP(), []int{28}
+}
+
+func (x *BuildTemplateResponse) GetImageRef() string {
+ if x != nil {
+ return x.ImageRef
+ }
+ return ""
+}
+
+func (x *BuildTemplateResponse) GetBuildLog() string {
+ if x != nil {
+ return x.BuildLog
+ }
+ return ""
+}
+
var File_proto_worker_worker_proto protoreflect.FileDescriptor
const file_proto_worker_worker_proto_rawDesc = "" +
"\n" +
- "\x19proto/worker/worker.proto\x12\x06worker\"\xa4\x02\n" +
+ "\x19proto/worker/worker.proto\x12\x06worker\"\xc1\x02\n" +
"\x14CreateSandboxRequest\x12\x1a\n" +
"\btemplate\x18\x01 \x01(\tR\btemplate\x12\x18\n" +
"\atimeout\x18\x02 \x01(\x05R\atimeout\x12:\n" +
"\x04envs\x18\x03 \x03(\v2&.worker.CreateSandboxRequest.EnvsEntryR\x04envs\x12\x1b\n" +
"\tmemory_mb\x18\x04 \x01(\x05R\bmemoryMb\x12\x1b\n" +
"\tcpu_count\x18\x05 \x01(\x05R\bcpuCount\x12'\n" +
- "\x0fnetwork_enabled\x18\x06 \x01(\bR\x0enetworkEnabled\x1a7\n" +
+ "\x0fnetwork_enabled\x18\x06 \x01(\bR\x0enetworkEnabled\x12\x1b\n" +
+ "\timage_ref\x18\a \x01(\tR\bimageRef\x1a7\n" +
"\tEnvsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"N\n" +
@@ -1679,7 +1808,17 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\x13WakeSandboxResponse\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x16\n" +
- "\x06status\x18\x02 \x01(\tR\x06status2\xa9\a\n" +
+ "\x06status\x18\x02 \x01(\tR\x06status\"\x80\x01\n" +
+ "\x14BuildTemplateRequest\x12\x12\n" +
+ "\x04name\x18\x01 \x01(\tR\x04name\x12\x1e\n" +
+ "\n" +
+ "dockerfile\x18\x02 \x01(\tR\n" +
+ "dockerfile\x12\x10\n" +
+ "\x03tag\x18\x03 \x01(\tR\x03tag\x12\"\n" +
+ "\recr_image_ref\x18\x04 \x01(\tR\vecrImageRef\"Q\n" +
+ "\x15BuildTemplateResponse\x12\x1b\n" +
+ "\timage_ref\x18\x01 \x01(\tR\bimageRef\x12\x1b\n" +
+ "\tbuild_log\x18\x02 \x01(\tR\bbuildLog2\xf7\a\n" +
"\rSandboxWorker\x12L\n" +
"\rCreateSandbox\x12\x1c.worker.CreateSandboxRequest\x1a\x1d.worker.CreateSandboxResponse\x12O\n" +
"\x0eDestroySandbox\x12\x1d.worker.DestroySandboxRequest\x1a\x1e.worker.DestroySandboxResponse\x12C\n" +
@@ -1694,7 +1833,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\tCreatePTY\x12\x18.worker.CreatePTYRequest\x1a\x19.worker.CreatePTYResponse\x124\n" +
"\tPTYStream\x12\x10.worker.PTYInput\x1a\x11.worker.PTYOutput(\x010\x01\x12U\n" +
"\x10HibernateSandbox\x12\x1f.worker.HibernateSandboxRequest\x1a .worker.HibernateSandboxResponse\x12F\n" +
- "\vWakeSandbox\x12\x1a.worker.WakeSandboxRequest\x1a\x1b.worker.WakeSandboxResponseB1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"
+ "\vWakeSandbox\x12\x1a.worker.WakeSandboxRequest\x1a\x1b.worker.WakeSandboxResponse\x12L\n" +
+ "\rBuildTemplate\x12\x1c.worker.BuildTemplateRequest\x1a\x1d.worker.BuildTemplateResponseB1Z/github.com/opensandbox/opensandbox/proto/workerb\x06proto3"
var (
file_proto_worker_worker_proto_rawDescOnce sync.Once
@@ -1709,7 +1849,7 @@ func file_proto_worker_worker_proto_rawDescGZIP() []byte {
}
var file_proto_worker_worker_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
-var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 29)
+var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 31)
var file_proto_worker_worker_proto_goTypes = []any{
(ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream
(*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest
@@ -1739,13 +1879,15 @@ var file_proto_worker_worker_proto_goTypes = []any{
(*HibernateSandboxResponse)(nil), // 25: worker.HibernateSandboxResponse
(*WakeSandboxRequest)(nil), // 26: worker.WakeSandboxRequest
(*WakeSandboxResponse)(nil), // 27: worker.WakeSandboxResponse
- nil, // 28: worker.CreateSandboxRequest.EnvsEntry
- nil, // 29: worker.ExecCommandRequest.EnvsEntry
+ (*BuildTemplateRequest)(nil), // 28: worker.BuildTemplateRequest
+ (*BuildTemplateResponse)(nil), // 29: worker.BuildTemplateResponse
+ nil, // 30: worker.CreateSandboxRequest.EnvsEntry
+ nil, // 31: worker.ExecCommandRequest.EnvsEntry
}
var file_proto_worker_worker_proto_depIdxs = []int32{
- 28, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
+ 30, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry
6, // 1: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse
- 29, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry
+ 31, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry
0, // 3: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream
17, // 4: worker.ListDirResponse.entries:type_name -> worker.DirEntry
22, // 5: worker.PTYInput.resize:type_name -> worker.PTYResize
@@ -1762,21 +1904,23 @@ var file_proto_worker_worker_proto_depIdxs = []int32{
21, // 16: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput
24, // 17: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest
26, // 18: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest
- 2, // 19: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse
- 4, // 20: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse
- 6, // 21: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse
- 8, // 22: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse
- 10, // 23: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse
- 11, // 24: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk
- 13, // 25: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse
- 15, // 26: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse
- 18, // 27: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse
- 20, // 28: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse
- 23, // 29: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput
- 25, // 30: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse
- 27, // 31: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse
- 19, // [19:32] is the sub-list for method output_type
- 6, // [6:19] is the sub-list for method input_type
+ 28, // 19: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest
+ 2, // 20: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse
+ 4, // 21: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse
+ 6, // 22: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse
+ 8, // 23: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse
+ 10, // 24: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse
+ 11, // 25: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk
+ 13, // 26: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse
+ 15, // 27: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse
+ 18, // 28: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse
+ 20, // 29: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse
+ 23, // 30: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput
+ 25, // 31: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse
+ 27, // 32: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse
+ 29, // 33: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse
+ 20, // [20:34] is the sub-list for method output_type
+ 6, // [6:20] is the sub-list for method input_type
6, // [6:6] is the sub-list for extension type_name
6, // [6:6] is the sub-list for extension extendee
0, // [0:6] is the sub-list for field type_name
@@ -1797,7 +1941,7 @@ func file_proto_worker_worker_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)),
NumEnums: 1,
- NumMessages: 29,
+ NumMessages: 31,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index 0ed2ec31..f6272c1c 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -22,6 +22,8 @@ service SandboxWorker {
rpc HibernateSandbox(HibernateSandboxRequest) returns (HibernateSandboxResponse);
rpc WakeSandbox(WakeSandboxRequest) returns (WakeSandboxResponse);
+
+ rpc BuildTemplate(BuildTemplateRequest) returns (BuildTemplateResponse);
}
message CreateSandboxRequest {
@@ -31,6 +33,7 @@ message CreateSandboxRequest {
int32 memory_mb = 4;
int32 cpu_count = 5;
bool network_enabled = 6;
+ string image_ref = 7;
}
message CreateSandboxResponse {
@@ -168,3 +171,15 @@ message WakeSandboxResponse {
string sandbox_id = 1;
string status = 2;
}
+
+message BuildTemplateRequest {
+ string name = 1;
+ string dockerfile = 2;
+ string tag = 3;
+ string ecr_image_ref = 4;
+}
+
+message BuildTemplateResponse {
+ string image_ref = 1;
+ string build_log = 2;
+}
diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.go
index 5fc8353d..fba53a87 100644
--- a/proto/worker/worker_grpc.pb.go
+++ b/proto/worker/worker_grpc.pb.go
@@ -32,6 +32,7 @@ const (
SandboxWorker_PTYStream_FullMethodName = "/worker.SandboxWorker/PTYStream"
SandboxWorker_HibernateSandbox_FullMethodName = "/worker.SandboxWorker/HibernateSandbox"
SandboxWorker_WakeSandbox_FullMethodName = "/worker.SandboxWorker/WakeSandbox"
+ SandboxWorker_BuildTemplate_FullMethodName = "/worker.SandboxWorker/BuildTemplate"
)
// SandboxWorkerClient is the client API for SandboxWorker service.
@@ -51,6 +52,7 @@ type SandboxWorkerClient interface {
PTYStream(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[PTYInput, PTYOutput], error)
HibernateSandbox(ctx context.Context, in *HibernateSandboxRequest, opts ...grpc.CallOption) (*HibernateSandboxResponse, error)
WakeSandbox(ctx context.Context, in *WakeSandboxRequest, opts ...grpc.CallOption) (*WakeSandboxResponse, error)
+ BuildTemplate(ctx context.Context, in *BuildTemplateRequest, opts ...grpc.CallOption) (*BuildTemplateResponse, error)
}
type sandboxWorkerClient struct {
@@ -203,6 +205,16 @@ func (c *sandboxWorkerClient) WakeSandbox(ctx context.Context, in *WakeSandboxRe
return out, nil
}
+func (c *sandboxWorkerClient) BuildTemplate(ctx context.Context, in *BuildTemplateRequest, opts ...grpc.CallOption) (*BuildTemplateResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(BuildTemplateResponse)
+ err := c.cc.Invoke(ctx, SandboxWorker_BuildTemplate_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
// SandboxWorkerServer is the server API for SandboxWorker service.
// All implementations must embed UnimplementedSandboxWorkerServer
// for forward compatibility.
@@ -220,6 +232,7 @@ type SandboxWorkerServer interface {
PTYStream(grpc.BidiStreamingServer[PTYInput, PTYOutput]) error
HibernateSandbox(context.Context, *HibernateSandboxRequest) (*HibernateSandboxResponse, error)
WakeSandbox(context.Context, *WakeSandboxRequest) (*WakeSandboxResponse, error)
+ BuildTemplate(context.Context, *BuildTemplateRequest) (*BuildTemplateResponse, error)
mustEmbedUnimplementedSandboxWorkerServer()
}
@@ -269,6 +282,9 @@ func (UnimplementedSandboxWorkerServer) HibernateSandbox(context.Context, *Hiber
func (UnimplementedSandboxWorkerServer) WakeSandbox(context.Context, *WakeSandboxRequest) (*WakeSandboxResponse, error) {
return nil, status.Error(codes.Unimplemented, "method WakeSandbox not implemented")
}
+func (UnimplementedSandboxWorkerServer) BuildTemplate(context.Context, *BuildTemplateRequest) (*BuildTemplateResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method BuildTemplate not implemented")
+}
func (UnimplementedSandboxWorkerServer) mustEmbedUnimplementedSandboxWorkerServer() {}
func (UnimplementedSandboxWorkerServer) testEmbeddedByValue() {}
@@ -506,6 +522,24 @@ func _SandboxWorker_WakeSandbox_Handler(srv interface{}, ctx context.Context, de
return interceptor(ctx, in, info, handler)
}
+func _SandboxWorker_BuildTemplate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(BuildTemplateRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(SandboxWorkerServer).BuildTemplate(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: SandboxWorker_BuildTemplate_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(SandboxWorkerServer).BuildTemplate(ctx, req.(*BuildTemplateRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
// SandboxWorker_ServiceDesc is the grpc.ServiceDesc for SandboxWorker service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -557,6 +591,10 @@ var SandboxWorker_ServiceDesc = grpc.ServiceDesc{
MethodName: "WakeSandbox",
Handler: _SandboxWorker_WakeSandbox_Handler,
},
+ {
+ MethodName: "BuildTemplate",
+ Handler: _SandboxWorker_BuildTemplate_Handler,
+ },
},
Streams: []grpc.StreamDesc{
{
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index 01dac3fb..7c6ac1c3 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "opensandbox",
- "version": "0.2.0",
+ "version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opensandbox",
- "version": "0.2.0",
+ "version": "0.3.0",
"license": "MIT",
"devDependencies": {
"typescript": "^5.4.0",
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 6b98cc0f..17c9f015 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -6,6 +6,7 @@ import Login from './pages/Login'
import Dashboard from './pages/Dashboard'
import Sessions from './pages/Sessions'
import APIKeys from './pages/APIKeys'
+import Templates from './pages/Templates'
import Settings from './pages/Settings'
export default function App() {
@@ -17,6 +18,7 @@ export default function App() {
<Route element={<Layout />}>
<Route index element={<Dashboard />} />
<Route path="sessions" element={<Sessions />} />
+ <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.ts
index f22bee41..f2fc446e 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -52,6 +52,17 @@ 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 buildTemplate = (name: string, dockerfile: string) =>
+ apiFetch<Template>('/templates', {
+ method: 'POST',
+ body: JSON.stringify({ name, dockerfile }),
+ })
+
+export const deleteTemplate = (id: string) =>
+ apiFetch<void>(`/templates/${id}`, { method: 'DELETE' })
+
export const getOrg = () => apiFetch<Org>('/org')
export const updateOrg = (name: string) =>
@@ -82,6 +93,17 @@ export interface APIKey {
createdAt: string
}
+export interface Template {
+ id: string
+ orgId?: string
+ name: string
+ tag: string
+ imageRef: string
+ dockerfile?: string
+ isPublic: boolean
+ createdAt: string
+}
+
export interface Org {
id: string
name: string
diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsx
index 76e00c86..c7a64fe5 100644
--- a/web/src/components/Layout.tsx
+++ b/web/src/components/Layout.tsx
@@ -23,6 +23,13 @@ const icons = {
<path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4" />
</svg>
),
+ layers: (
+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
+ <polygon points="12 2 2 7 12 12 22 7 12 2" />
+ <polyline points="2 17 12 22 22 17" />
+ <polyline points="2 12 12 17 22 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" />
@@ -41,6 +48,7 @@ const icons = {
const navItems = [
{ to: '/', label: 'Dashboard', end: true, icon: icons.grid },
{ to: '/sessions', label: 'Sessions', icon: icons.clock },
+ { to: '/templates', label: 'Templates', icon: icons.layers },
{ to: '/api-keys', label: 'API Keys', icon: icons.key },
{ to: '/settings', label: 'Settings', icon: icons.gear },
]
diff --git a/web/src/data/mockData.ts b/web/src/data/mockData.ts
deleted file mode 100644
index 7c78e317..00000000
--- a/web/src/data/mockData.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-/**
- * Deterministic mock data for dashboard charts.
- * Uses a seeded PRNG so charts look consistent across renders.
- * Replace with real API calls when endpoints exist.
- */
-
-function createRng(seed: number) {
- let s = seed
- return () => {
- s = (s * 16807 + 13) % 2147483647
- return (s - 1) / 2147483646
- }
-}
-
-// ── Chart color palette ─────────────────────────────────────
-export const CHART_COLORS = [
- '#818cf8', // indigo
- '#34d399', // emerald
- '#22d3ee', // cyan
- '#f472b6', // pink
- '#fbbf24', // amber
- '#a78bfa', // violet
-]
-
-// ── Types ────────────────────────────────────────────────────
-export interface UsagePoint {
- time: string
- sandboxes: number
- sessions: number
-}
-
-export interface TemplateSlice {
- name: string
- value: number
- color: string
-}
-
-export interface RegionBar {
- region: string
- label: string
- count: number
- color: string
-}
-
-export interface SparkPoint {
- value: number
-}
-
-export interface TimelinePoint {
- hour: string
- started: number
- stopped: number
- errors: number
-}
-
-// ── Generators ───────────────────────────────────────────────
-
-export function generateUsageData(days: number): UsagePoint[] {
- const rng = createRng(days === 7 ? 101 : 202)
- const data: UsagePoint[] = []
- const points = days === 7 ? 42 : 30
-
- const now = new Date()
-
- for (let i = points; i >= 0; i--) {
- const date = new Date(now)
- if (days === 7) {
- date.setHours(date.getHours() - i * 4)
- } else {
- date.setDate(date.getDate() - i)
- }
-
- const hour = date.getHours()
- const dayPeak = Math.sin((hour - 5) * Math.PI / 13) * 0.35
- const base = 16 + dayPeak * 12
- const trend = ((points - i) / points) * 9
- const noise = (rng() - 0.5) * 10
-
- data.push({
- time:
- days === 7
- ? `${(date.getMonth() + 1)}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:00`
- : date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
- sandboxes: Math.round(Math.max(3, base + trend + noise)),
- sessions: Math.round(Math.max(6, (base + trend) * 2.8 + (rng() - 0.5) * 18)),
- })
- }
- return data
-}
-
-export function generateTemplateData(): TemplateSlice[] {
- return [
- { name: 'Python', value: 342, color: CHART_COLORS[0] },
- { name: 'Node.js', value: 256, color: CHART_COLORS[1] },
- { name: 'Go', value: 128, color: CHART_COLORS[2] },
- { name: 'Rust', value: 89, color: CHART_COLORS[3] },
- { name: 'Custom', value: 45, color: CHART_COLORS[4] },
- ]
-}
-
-export function generateRegionData(): RegionBar[] {
- return [
- { region: 'us-east-1', label: 'US East', count: 412, color: CHART_COLORS[0] },
- { region: 'eu-west-1', label: 'EU West', count: 289, color: CHART_COLORS[1] },
- { region: 'ap-south-1', label: 'AP South', count: 198, color: CHART_COLORS[2] },
- { region: 'us-west-2', label: 'US West', count: 156, color: CHART_COLORS[3] },
- { region: 'eu-central-1', label: 'EU Central', count: 134, color: CHART_COLORS[4] },
- ]
-}
-
-export function generateSparkData(
- seed: number,
- points = 24,
- trend: 'up' | 'down' | 'stable' = 'up',
-): SparkPoint[] {
- const rng = createRng(seed)
- const data: SparkPoint[] = []
- let value = 35 + rng() * 25
-
- for (let i = 0; i < points; i++) {
- const t = trend === 'up' ? 0.7 : trend === 'down' ? -0.5 : 0
- value = Math.max(4, Math.min(96, value + t + (rng() - 0.5) * 11))
- data.push({ value: Math.round(value) })
- }
- return data
-}
-
-export function generateSessionTimeline(): TimelinePoint[] {
- const rng = createRng(303)
- const data: TimelinePoint[] = []
-
- for (let i = 23; i >= 0; i--) {
- const date = new Date()
- date.setHours(date.getHours() - i, 0, 0, 0)
- const peak = Math.sin((date.getHours() - 4) * Math.PI / 12)
-
- data.push({
- hour: date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }),
- started: Math.round(Math.max(1, 14 + peak * 9 + (rng() - 0.5) * 7)),
- stopped: Math.round(Math.max(0, 9 + peak * 6 + (rng() - 0.5) * 5)),
- errors: Math.round(Math.max(0, rng() * 2.5 - 0.3)),
- })
- }
- return data
-}
-
-/** Demo sandboxes for the live-list when no real data exists. */
-export function generateDemoSandboxes() {
- const rng = createRng(404)
- const templates = ['python', 'node', 'go', 'rust', 'python', 'node']
- const regions = ['us-east-1', 'eu-west-1', 'ap-south-1', 'us-west-2', 'eu-central-1', 'us-east-1']
- const ids = ['a8f2c1', 'b3d7e9', 'c1a4b6', 'd9e2f0', 'e5b8a3', 'f7c6d4']
-
- return ids.map((id, i) => ({
- id: `demo-${i}`,
- sandboxId: `sbx-${id}`,
- orgId: 'demo',
- template: templates[i],
- region: regions[i],
- workerId: `wkr-${Math.round(rng() * 99)}`,
- status: 'running' as const,
- startedAt: new Date(Date.now() - (8 + i * 18) * 60000).toISOString(),
- }))
-}
diff --git a/web/src/pages/APIKeys.tsx b/web/src/pages/APIKeys.tsx
index e45f103b..ac56bd8d 100644
--- a/web/src/pages/APIKeys.tsx
+++ b/web/src/pages/APIKeys.tsx
@@ -135,7 +135,7 @@ export default function APIKeys() {
{(keys ?? []).map((k: APIKey) => (
<tr key={k.id}>
<td style={{ fontWeight: 500, color: 'var(--text-primary)' }}>{k.name}</td>
- <td><code>{k.keyPrefix}\u2026</code></td>
+ <td><code>{k.keyPrefix}…</code></td>
<td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>
{k.lastUsed ? new Date(k.lastUsed).toLocaleString() : 'Never'}
</td>
diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx
index bab2a5f0..1cc27543 100644
--- a/web/src/pages/Dashboard.tsx
+++ b/web/src/pages/Dashboard.tsx
@@ -1,201 +1,50 @@
-import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getSessions, type Session } from '../api/client'
-import {
- AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
- ResponsiveContainer, PieChart, Pie, Cell, LineChart, Line,
-} from 'recharts'
-import {
- generateUsageData, generateTemplateData, generateRegionData,
- generateSparkData, generateDemoSandboxes, CHART_COLORS,
-} from '../data/mockData'
-/* ── Custom Tooltip ───────────────────────────────────────── */
-function ChartTooltip({ active, payload, label }: {
- active?: boolean
- payload?: Array<{ name: string; value: number; color: string }>
- label?: string
-}) {
- if (!active || !payload?.length) return null
- return (
- <div style={{
- background: 'rgba(8, 8, 12, 0.92)',
- backdropFilter: 'blur(14px)',
- border: '1px solid var(--border-accent)',
- borderRadius: 10,
- padding: '10px 14px',
- boxShadow: '0 12px 40px rgba(0,0,0,0.5)',
- }}>
- <div style={{
- fontSize: 10, color: 'var(--text-tertiary)',
- fontFamily: 'var(--font-mono)', marginBottom: 6,
- }}>{label}</div>
- {payload.map((p, i) => (
- <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, marginBottom: 2 }}>
- <span style={{ width: 7, height: 7, borderRadius: '50%', background: p.color, flexShrink: 0 }} />
- <span style={{ color: 'var(--text-secondary)' }}>{p.name}</span>
- <span style={{ color: 'var(--text-primary)', fontFamily: 'var(--font-mono)', fontWeight: 600, marginLeft: 'auto' }}>
- {p.value.toLocaleString()}
- </span>
- </div>
- ))}
- </div>
- )
-}
-
-/* ── Main Dashboard ───────────────────────────────────────── */
export default function Dashboard() {
- const [timeRange, setTimeRange] = useState<7 | 30>(7)
-
- const { data: sessions, isLoading } = useQuery({
+ const { data: runningSessions, isLoading: loadingRunning } = useQuery({
queryKey: ['sessions', 'running'],
queryFn: () => getSessions('running'),
})
- const activeSandboxes = sessions ?? []
-
- const usageData = useMemo(() => generateUsageData(timeRange), [timeRange])
- const templateData = useMemo(() => generateTemplateData(), [])
- const regionData = useMemo(() => generateRegionData(), [])
- const sparkActive = useMemo(() => generateSparkData(10, 24, 'up'), [])
- const sparkSessions = useMemo(() => generateSparkData(20, 24, 'up'), [])
- const sparkUptime = useMemo(() => generateSparkData(30, 24, 'stable'), [])
- const sparkAPI = useMemo(() => generateSparkData(40, 24, 'up'), [])
+ const { data: allSessions, isLoading: loadingAll } = useQuery({
+ queryKey: ['sessions', ''],
+ queryFn: () => getSessions(),
+ })
- const templateTotal = templateData.reduce((s, t) => s + t.value, 0)
- const liveList = activeSandboxes.length > 0 ? activeSandboxes : generateDemoSandboxes()
+ const active = runningSessions ?? []
+ const all = allSessions ?? []
+ const today = new Date().toISOString().slice(0, 10)
+ const sessionsToday = all.filter(s => new Date(s.startedAt).toISOString().slice(0, 10) === today).length
return (
<div>
- {/* Header */}
<div style={{ marginBottom: 32 }}>
<h1 className="page-title">Dashboard</h1>
- <p className="page-subtitle">Real-time overview of your sandbox infrastructure</p>
+ <p className="page-subtitle">Overview of your sandbox infrastructure</p>
</div>
{/* ── Stat Cards ── */}
- <div className="grid-stats" style={{
- display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 24,
- }}>
- <StatCard label="Active Sandboxes" value={activeSandboxes.length || 24} change="+12%" up sparkData={sparkActive} color={CHART_COLORS[0]} idx={0} />
- <StatCard label="Sessions Today" value={847} change="+23%" up sparkData={sparkSessions} color={CHART_COLORS[1]} idx={1} />
- <StatCard label="Avg Uptime" value="99.7%" change="+0.2%" up sparkData={sparkUptime} color={CHART_COLORS[2]} idx={2} />
- <StatCard label="API Calls (24h)" value="12.4k" change="+18%" up sparkData={sparkAPI} color={CHART_COLORS[4]} idx={3} />
- </div>
-
- {/* ── Main Charts Row ── */}
- <div className="grid-charts-main" style={{
- display: 'grid', gridTemplateColumns: '5fr 2fr', gap: 14, marginBottom: 24,
+ <div style={{
+ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14, marginBottom: 24,
}}>
- {/* Area — Usage Over Time */}
- <div className="glass-card animate-in stagger-5" style={{ padding: '22px 24px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
- <span className="section-title" style={{ marginBottom: 0 }}>Usage Over Time</span>
- <div style={{ display: 'flex', gap: 4 }}>
- {([7, 30] as const).map(d => (
- <button key={d} onClick={() => setTimeRange(d)}
- className={`filter-btn${timeRange === d ? ' active' : ''}`}
- style={{ padding: '3px 12px', fontSize: 11 }}>
- {d}d
- </button>
- ))}
- </div>
- </div>
- <ResponsiveContainer width="100%" height={270}>
- <AreaChart data={usageData}>
- <defs>
- <linearGradient id="gSandboxes" x1="0" y1="0" x2="0" y2="1">
- <stop offset="0%" stopColor="#818cf8" stopOpacity={0.22} />
- <stop offset="100%" stopColor="#818cf8" stopOpacity={0} />
- </linearGradient>
- <linearGradient id="gSessions" x1="0" y1="0" x2="0" y2="1">
- <stop offset="0%" stopColor="#34d399" stopOpacity={0.18} />
- <stop offset="100%" stopColor="#34d399" stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid strokeDasharray="3 3" />
- <XAxis dataKey="time" tick={{ fontSize: 10 }} axisLine={{ stroke: 'rgba(255,255,255,0.05)' }} tickLine={false} interval="preserveStartEnd" />
- <YAxis tick={{ fontSize: 10 }} axisLine={false} tickLine={false} width={36} />
- <Tooltip content={<ChartTooltip />} />
- <Area type="monotone" dataKey="sessions" name="Sessions" stroke="#34d399" strokeWidth={1.5} fill="url(#gSessions)" />
- <Area type="monotone" dataKey="sandboxes" name="Sandboxes" stroke="#818cf8" strokeWidth={2} fill="url(#gSandboxes)" />
- </AreaChart>
- </ResponsiveContainer>
- </div>
-
- {/* Donut — Template Distribution */}
- <div className="glass-card animate-in stagger-5" style={{ padding: '22px 24px', display: 'flex', flexDirection: 'column' }}>
- <span className="section-title">By Template</span>
- <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
- <ResponsiveContainer width="100%" height={175}>
- <PieChart>
- <Pie data={templateData} cx="50%" cy="50%" innerRadius={52} outerRadius={78}
- paddingAngle={3} dataKey="value" stroke="none">
- {templateData.map((e, i) => <Cell key={i} fill={e.color} />)}
- </Pie>
- <Tooltip content={<ChartTooltip />} />
- </PieChart>
- </ResponsiveContainer>
- </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginTop: 4 }}>
- {templateData.map(t => (
- <div key={t.name} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
- <span style={{ width: 8, height: 8, borderRadius: 2, background: t.color, flexShrink: 0 }} />
- <span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{t.name}</span>
- </div>
- <span className="metric-value" style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
- {Math.round((t.value / templateTotal) * 100)}%
- </span>
- </div>
- ))}
- </div>
- </div>
+ <StatCard
+ label="Active Sandboxes"
+ value={loadingRunning ? '\u2014' : active.length}
+ accent="var(--accent-emerald)"
+ />
+ <StatCard
+ label="Sessions Today"
+ value={loadingAll ? '\u2014' : sessionsToday}
+ accent="#818cf8"
+ />
</div>
- {/* ── Bottom Row ── */}
- <div className="grid-charts-secondary" style={{
- display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14,
- }}>
- {/* Region Distribution */}
- <div className="glass-card" style={{ padding: '22px 24px' }}>
- <span className="section-title">By Region</span>
- <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
- {regionData.map((r, i) => {
- const pct = (r.count / regionData[0].count) * 100
- return (
- <div key={r.region}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 7 }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
- <span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{r.label}</span>
- <code style={{
- fontSize: 10, color: 'var(--text-tertiary)',
- fontFamily: 'var(--font-mono)',
- background: 'rgba(255,255,255,0.03)', padding: '1px 5px', borderRadius: 3,
- }}>{r.region}</code>
- </div>
- <span className="metric-value" style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
- {r.count}
- </span>
- </div>
- <div style={{ height: 5, borderRadius: 3, background: 'rgba(255,255,255,0.04)', overflow: 'hidden' }}>
- <div style={{
- height: '100%', width: `${pct}%`, borderRadius: 3,
- background: CHART_COLORS[i],
- boxShadow: `0 0 8px ${CHART_COLORS[i]}33`,
- transition: 'width 0.6s cubic-bezier(0.16,1,0.3,1)',
- }} />
- </div>
- </div>
- )
- })}
- </div>
- </div>
-
- {/* Live Sandboxes */}
- <div className="glass-card" style={{ padding: '22px 24px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
- <span className="section-title" style={{ marginBottom: 0 }}>Live Sandboxes</span>
+ {/* ── Live Sandboxes ── */}
+ <div className="glass-card animate-in stagger-1" style={{ padding: '22px 24px', marginBottom: 24 }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 0 }}>Live Sandboxes</span>
+ {active.length > 0 && (
<span style={{
fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--accent-emerald)',
display: 'flex', alignItems: 'center', gap: 6,
@@ -204,69 +53,100 @@ export default function Dashboard() {
width: 6, height: 6, borderRadius: '50%',
background: 'var(--accent-emerald)', display: 'inline-block',
}} />
- {liveList.length} active
+ {active.length} active
</span>
- </div>
-
- {isLoading ? (
- <div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
- <div className="loading-spinner" />
- </div>
- ) : (
- <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 270, overflowY: 'auto' }}>
- {liveList.map((s, i) => <SandboxRow key={s.id ?? i} session={s} />)}
- </div>
)}
</div>
+
+ {loadingRunning ? (
+ <div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
+ <div className="loading-spinner" />
+ </div>
+ ) : active.length === 0 ? (
+ <div style={{
+ textAlign: 'center', padding: '40px 20px',
+ color: 'var(--text-tertiary)', fontSize: 13,
+ }}>
+ No sandboxes running
+ </div>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 300, overflowY: 'auto' }}>
+ {active.map(s => <SandboxRow key={s.id} session={s} />)}
+ </div>
+ )}
+ </div>
+
+ {/* ── Recent Sessions ── */}
+ <div className="glass-card animate-in stagger-2" style={{ padding: '22px 24px' }}>
+ <span className="section-title">Recent Sessions</span>
+ {loadingAll ? (
+ <div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
+ <div className="loading-spinner" />
+ </div>
+ ) : all.length === 0 ? (
+ <div style={{
+ textAlign: 'center', padding: '40px 20px',
+ color: 'var(--text-tertiary)', fontSize: 13,
+ }}>
+ No sessions yet
+ </div>
+ ) : (
+ <div style={{ overflow: 'hidden' }}>
+ <table className="data-table">
+ <thead>
+ <tr>
+ <th>Sandbox ID</th>
+ <th>Template</th>
+ <th>Status</th>
+ <th>Started</th>
+ <th>Duration</th>
+ </tr>
+ </thead>
+ <tbody>
+ {all.slice(0, 20).map(s => (
+ <tr key={s.id}>
+ <td><code>{s.sandboxId}</code></td>
+ <td>{s.template || 'base'}</td>
+ <td><StatusBadge status={s.status} /></td>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>
+ {new Date(s.startedAt).toLocaleString()}
+ </td>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>
+ {formatDuration(s)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
</div>
</div>
)
}
-/* ── Stat Card w/ Sparkline ───────────────────────────────── */
-function StatCard({ label, value, change, up, sparkData, color, idx }: {
+/* ── Stat Card ───────────────────────────────────────────── */
+function StatCard({ label, value, accent }: {
label: string
value: number | string
- change: string
- up: boolean
- sparkData: { value: number }[]
- color: string
- idx: number
+ accent: string
}) {
- const gradId = `spark-g-${idx}`
return (
- <div className={`stat-card animate-in stagger-${idx + 1}`}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
- <div>
- <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginBottom: 8, letterSpacing: '0.03em' }}>{label}</div>
- <div className="metric-value" style={{ fontSize: 30, fontWeight: 700, lineHeight: 1 }}>{typeof value === 'number' ? value.toLocaleString() : value}</div>
- </div>
- <span style={{
- fontSize: 11, fontFamily: 'var(--font-mono)', fontWeight: 500,
- color: up ? 'var(--accent-emerald)' : 'var(--accent-rose)',
- background: up ? 'rgba(52,211,153,0.08)' : 'rgba(251,113,133,0.08)',
- padding: '2px 8px', borderRadius: 10,
- }}>{change}</span>
+ <div className="stat-card animate-in">
+ <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginBottom: 8, letterSpacing: '0.03em' }}>
+ {label}
</div>
- <div style={{ height: 36, marginLeft: -6, marginRight: -6 }}>
- <ResponsiveContainer width="100%" height="100%">
- <LineChart data={sparkData}>
- <defs>
- <linearGradient id={gradId} x1="0" y1="0" x2="1" y2="0">
- <stop offset="0%" stopColor={color} stopOpacity={0.15} />
- <stop offset="100%" stopColor={color} stopOpacity={0.9} />
- </linearGradient>
- </defs>
- <Line type="monotone" dataKey="value" stroke={`url(#${gradId})`} strokeWidth={1.8} dot={false} />
- </LineChart>
- </ResponsiveContainer>
+ <div className="metric-value" style={{
+ fontSize: 30, fontWeight: 700, lineHeight: 1, color: accent,
+ }}>
+ {typeof value === 'number' ? value.toLocaleString() : value}
</div>
</div>
)
}
/* ── Sandbox Row ──────────────────────────────────────────── */
-function SandboxRow({ session }: { session: Session | ReturnType<typeof generateDemoSandboxes>[number] }) {
+function SandboxRow({ session }: { session: Session }) {
const elapsed = Math.round((Date.now() - new Date(session.startedAt).getTime()) / 1000 / 60)
return (
<div style={{
@@ -294,7 +174,7 @@ function SandboxRow({ session }: { session: Session | ReturnType<typeof generate
{session.sandboxId}
</code>
<div style={{ fontSize: 10, color: 'var(--text-tertiary)', marginTop: 1 }}>
- {session.template || 'base'} &middot; {session.region}
+ {session.template || 'base'}
</div>
</div>
</div>
@@ -304,3 +184,33 @@ function SandboxRow({ session }: { session: Session | ReturnType<typeof generate
</div>
)
}
+
+/* ── Status Badge ─────────────────────────────────────────── */
+function StatusBadge({ status }: { status: string }) {
+ const cls =
+ status === 'running' ? 'badge-running'
+ : status === 'hibernated' ? 'badge-hibernated'
+ : status === 'error' ? 'badge-error'
+ : 'badge-stopped'
+ return (
+ <span className={`badge ${cls}`}>
+ {status === 'running' && (
+ <span className="pulse-dot" style={{
+ width: 5, height: 5, borderRadius: '50%',
+ background: 'currentColor', display: 'inline-block',
+ }} />
+ )}
+ {status}
+ </span>
+ )
+}
+
+/* ── Helpers ──────────────────────────────────────────────── */
+function formatDuration(session: Session): string {
+ const start = new Date(session.startedAt).getTime()
+ const end = session.stoppedAt ? new Date(session.stoppedAt).getTime() : Date.now()
+ const secs = Math.round((end - start) / 1000)
+ if (secs < 60) return `${secs}s`
+ if (secs < 3600) return `${Math.round(secs / 60)}m`
+ return `${Math.round(secs / 3600 * 10) / 10}h`
+}
diff --git a/web/src/pages/Sessions.tsx b/web/src/pages/Sessions.tsx
index afb13c5d..64b53008 100644
--- a/web/src/pages/Sessions.tsx
+++ b/web/src/pages/Sessions.tsx
@@ -1,39 +1,9 @@
import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getSessions, type Session } from '../api/client'
-import {
- BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend,
-} from 'recharts'
-import { generateSessionTimeline } from '../data/mockData'
-
-const statusFilters = ['', 'running', 'stopped', 'error'] as const
-
-/* ── Tooltip ──────────────────────────────────────────────── */
-function TimelineTooltip({ active, payload, label }: {
- active?: boolean
- payload?: Array<{ name: string; value: number; color: string }>
- label?: string
-}) {
- if (!active || !payload?.length) return null
- return (
- <div style={{
- background: 'rgba(8,8,12,0.92)', backdropFilter: 'blur(14px)',
- border: '1px solid var(--border-accent)', borderRadius: 10,
- padding: '10px 14px', boxShadow: '0 12px 40px rgba(0,0,0,0.5)',
- }}>
- <div style={{ fontSize: 10, color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)', marginBottom: 6 }}>{label}</div>
- {payload.map((p, i) => (
- <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, marginBottom: 2 }}>
- <span style={{ width: 7, height: 7, borderRadius: '50%', background: p.color, flexShrink: 0 }} />
- <span style={{ color: 'var(--text-secondary)' }}>{p.name}</span>
- <span style={{ color: 'var(--text-primary)', fontFamily: 'var(--font-mono)', fontWeight: 600, marginLeft: 'auto' }}>{p.value}</span>
- </div>
- ))}
- </div>
- )
-}
-/* ── Main ─────────────────────────────────────────────────── */
+const statusFilters = ['', 'running', 'stopped', 'hibernated', 'error'] as const
+
export default function Sessions() {
const [status, setStatus] = useState<string>('')
const { data: sessions, isLoading } = useQuery({
@@ -41,45 +11,21 @@ export default function Sessions() {
queryFn: () => getSessions(status || undefined),
})
- const timeline = useMemo(() => generateSessionTimeline(), [])
+ // Always fetch all sessions for the activity chart
+ const { data: allSessions, isLoading: loadingAll } = useQuery({
+ queryKey: ['sessions', ''],
+ queryFn: () => getSessions(),
+ })
return (
<div>
<div style={{ marginBottom: 28 }}>
<h1 className="page-title">Sessions</h1>
- <p className="page-subtitle">Session history and activity timeline</p>
+ <p className="page-subtitle">Session history</p>
</div>
- {/* ── Timeline Chart ── */}
- <div className="glass-card animate-in stagger-1" style={{ padding: '22px 24px', marginBottom: 22 }}>
- <span className="section-title">Activity — Last 24 Hours</span>
- <ResponsiveContainer width="100%" height={190}>
- <BarChart data={timeline} barGap={1}>
- <defs>
- <linearGradient id="gStarted" x1="0" y1="0" x2="0" y2="1">
- <stop offset="0%" stopColor="#818cf8" stopOpacity={0.85} />
- <stop offset="100%" stopColor="#818cf8" stopOpacity={0.45} />
- </linearGradient>
- <linearGradient id="gStopped" x1="0" y1="0" x2="0" y2="1">
- <stop offset="0%" stopColor="#8585a0" stopOpacity={0.6} />
- <stop offset="100%" stopColor="#8585a0" stopOpacity={0.25} />
- </linearGradient>
- </defs>
- <CartesianGrid strokeDasharray="3 3" />
- <XAxis dataKey="hour" tick={{ fontSize: 9 }} axisLine={{ stroke: 'rgba(255,255,255,0.05)' }} tickLine={false} interval={2} />
- <YAxis tick={{ fontSize: 10 }} axisLine={false} tickLine={false} width={30} />
- <Tooltip content={<TimelineTooltip />} />
- <Legend
- iconType="circle"
- iconSize={7}
- wrapperStyle={{ fontSize: 11, color: 'var(--text-tertiary)', fontFamily: 'var(--font-body)' }}
- />
- <Bar dataKey="started" name="Started" fill="url(#gStarted)" radius={[3, 3, 0, 0]} />
- <Bar dataKey="stopped" name="Stopped" fill="url(#gStopped)" radius={[3, 3, 0, 0]} />
- <Bar dataKey="errors" name="Errors" fill="#fb718544" radius={[3, 3, 0, 0]} />
- </BarChart>
- </ResponsiveContainer>
- </div>
+ {/* ── Activity Chart ── */}
+ <ActivityChart sessions={allSessions ?? []} loading={loadingAll} />
{/* ── Filters ── */}
<div style={{ marginBottom: 16, display: 'flex', gap: 6 }}>
@@ -97,13 +43,12 @@ export default function Sessions() {
<div className="loading-spinner" />
</div>
) : (
- <div className="glass-card animate-in stagger-2" style={{ overflow: 'hidden' }}>
+ <div className="glass-card animate-in stagger-1" style={{ overflow: 'hidden' }}>
<table className="data-table">
<thead>
<tr>
<th>Sandbox ID</th>
<th>Template</th>
- <th>Region</th>
<th>Status</th>
<th>Started</th>
<th>Stopped</th>
@@ -114,7 +59,6 @@ export default function Sessions() {
<tr key={s.id}>
<td><code>{s.sandboxId}</code></td>
<td>{s.template || 'base'}</td>
- <td>{s.region}</td>
<td><StatusBadge status={s.status} /></td>
<td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>{new Date(s.startedAt).toLocaleString()}</td>
<td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>{s.stoppedAt ? new Date(s.stoppedAt).toLocaleString() : '\u2014'}</td>
@@ -122,7 +66,7 @@ export default function Sessions() {
))}
{(sessions ?? []).length === 0 && (
<tr>
- <td colSpan={6} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>
+ <td colSpan={5} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>
No sessions found
</td>
</tr>
@@ -135,9 +79,154 @@ export default function Sessions() {
)
}
+/* ── Activity Chart (last 14 days) ────────────────────────── */
+function ActivityChart({ sessions, loading }: { sessions: Session[]; loading: boolean }) {
+ const { days, maxCount } = useMemo(() => {
+ const now = new Date()
+ const dayBuckets: { label: string; date: string; count: number; hibernated: number; errored: number }[] = []
+
+ for (let i = 13; i >= 0; i--) {
+ const d = new Date(now)
+ d.setDate(d.getDate() - i)
+ const dateStr = d.toISOString().slice(0, 10)
+ dayBuckets.push({
+ label: d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
+ date: dateStr,
+ count: 0,
+ hibernated: 0,
+ errored: 0,
+ })
+ }
+
+ for (const s of sessions) {
+ const dateStr = new Date(s.startedAt).toISOString().slice(0, 10)
+ const bucket = dayBuckets.find(b => b.date === dateStr)
+ if (bucket) {
+ bucket.count++
+ if (s.status === 'hibernated') bucket.hibernated++
+ else if (s.status === 'error') bucket.errored++
+ }
+ }
+
+ const maxCount = Math.max(1, ...dayBuckets.map(b => b.count))
+ return { days: dayBuckets, maxCount }
+ }, [sessions])
+
+ return (
+ <div className="glass-card animate-in" style={{ padding: '22px 24px', marginBottom: 24 }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
+ <span className="section-title" style={{ marginBottom: 0 }}>Activity</span>
+ <span style={{ fontSize: 11, color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)' }}>
+ Last 14 days
+ </span>
+ </div>
+
+ {loading ? (
+ <div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
+ <div className="loading-spinner" />
+ </div>
+ ) : (
+ <div style={{ position: 'relative' }}>
+ {/* Y-axis labels */}
+ <div style={{
+ position: 'absolute', left: 0, top: 0, bottom: 24,
+ display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
+ width: 32,
+ }}>
+ <span style={{ fontSize: 10, color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)' }}>
+ {maxCount}
+ </span>
+ <span style={{ fontSize: 10, color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)' }}>
+ 0
+ </span>
+ </div>
+
+ {/* Chart bars */}
+ <div style={{
+ display: 'flex', alignItems: 'flex-end', gap: 4, height: 120,
+ marginLeft: 36,
+ }}>
+ {days.map((day) => {
+ const barHeight = maxCount > 0 ? Math.round((day.count / maxCount) * 110) : 0
+ const hasHibernated = day.hibernated > 0
+ const hasError = day.errored > 0
+
+ return (
+ <div
+ key={day.date}
+ title={`${day.label}: ${day.count} sessions${day.hibernated ? ` (${day.hibernated} hibernated)` : ''}${day.errored ? ` (${day.errored} errors)` : ''}`}
+ style={{
+ flex: 1,
+ height: day.count > 0 ? Math.max(barHeight, 4) : 0,
+ borderRadius: '4px 4px 2px 2px',
+ background: hasError
+ ? 'linear-gradient(to top, rgba(251,113,133,0.5), rgba(129,140,248,0.5))'
+ : hasHibernated
+ ? 'linear-gradient(to top, rgba(34,211,238,0.4), rgba(129,140,248,0.5))'
+ : day.count > 0
+ ? 'linear-gradient(to top, rgba(99,102,241,0.25), rgba(129,140,248,0.5))'
+ : 'transparent',
+ transition: 'height 0.3s ease',
+ cursor: 'default',
+ position: 'relative',
+ }}
+ >
+ {day.count > 0 && (
+ <span style={{
+ position: 'absolute', top: -16, left: '50%', transform: 'translateX(-50%)',
+ fontSize: 9, fontFamily: 'var(--font-mono)', color: 'var(--text-tertiary)',
+ whiteSpace: 'nowrap',
+ }}>
+ {day.count}
+ </span>
+ )}
+ </div>
+ )
+ })}
+ </div>
+
+ {/* X-axis labels */}
+ <div style={{
+ display: 'flex', gap: 4, marginLeft: 36, marginTop: 6,
+ }}>
+ {days.map((day, i) => (
+ <div key={day.date} style={{
+ flex: 1, textAlign: 'center',
+ fontSize: 9, color: 'var(--text-tertiary)',
+ fontFamily: 'var(--font-mono)',
+ }}>
+ {i % 2 === 0 ? day.label : ''}
+ </div>
+ ))}
+ </div>
+
+ {/* Legend */}
+ <div style={{
+ display: 'flex', gap: 16, justifyContent: 'center', marginTop: 12,
+ }}>
+ <LegendItem color="rgba(129,140,248,0.5)" label="Sessions" />
+ <LegendItem color="rgba(34,211,238,0.4)" label="Hibernated" />
+ <LegendItem color="rgba(251,113,133,0.5)" label="Errors" />
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
+
+function LegendItem({ color, label }: { color: string; label: string }) {
+ return (
+ <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
+ <div style={{ width: 8, height: 8, borderRadius: 2, background: color }} />
+ <span style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>{label}</span>
+ </div>
+ )
+}
+
function StatusBadge({ status }: { status: string }) {
const cls =
status === 'running' ? 'badge-running'
+ : status === 'hibernated' ? 'badge-hibernated'
: status === 'error' ? 'badge-error'
: 'badge-stopped'
return (
diff --git a/web/src/pages/Templates.tsx b/web/src/pages/Templates.tsx
new file mode 100644
index 00000000..ad2d7a3a
--- /dev/null
+++ b/web/src/pages/Templates.tsx
@@ -0,0 +1,192 @@
+import { useState } from 'react'
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { getTemplates, buildTemplate, deleteTemplate, type Template } from '../api/client'
+
+export default function Templates() {
+ const queryClient = useQueryClient()
+ const { data: templates, isLoading } = useQuery({
+ queryKey: ['templates'],
+ queryFn: getTemplates,
+ })
+
+ const [showCreate, setShowCreate] = useState(false)
+ const [newName, setNewName] = useState('')
+ const [newDockerfile, setNewDockerfile] = useState('')
+
+ const buildMutation = useMutation({
+ mutationFn: ({ name, dockerfile }: { name: string; dockerfile: string }) =>
+ buildTemplate(name, dockerfile),
+ onSuccess: () => {
+ setShowCreate(false)
+ setNewName('')
+ setNewDockerfile('')
+ queryClient.invalidateQueries({ queryKey: ['templates'] })
+ },
+ })
+
+ const deleteMutation = useMutation({
+ mutationFn: (id: string) => deleteTemplate(id),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['templates'] })
+ },
+ })
+
+ return (
+ <div>
+ {/* Header */}
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
+ <div>
+ <h1 className="page-title">Templates</h1>
+ <p className="page-subtitle">Manage sandbox base images for your organization</p>
+ </div>
+ <button className="btn-primary" onClick={() => setShowCreate(true)}>
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
+ <line x1="12" y1="5" x2="12" y2="19" /><line x1="5" y1="12" x2="19" y2="12" />
+ </svg>
+ Create Template
+ </button>
+ </div>
+
+ {/* Create Dialog */}
+ {showCreate && (
+ <div className="glass-card animate-in" style={{ padding: 22, marginBottom: 20 }}>
+ <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={newName}
+ onChange={e => setNewName(e.target.value)}
+ placeholder="e.g. my-app"
+ className="input"
+ autoFocus
+ />
+ </div>
+ <div style={{ marginBottom: 14 }}>
+ <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 6 }}>
+ Dockerfile
+ </label>
+ <textarea
+ value={newDockerfile}
+ onChange={e => setNewDockerfile(e.target.value)}
+ placeholder={'FROM ubuntu:22.04\nRUN apt-get update && apt-get install -y curl'}
+ className="input"
+ rows={8}
+ style={{
+ fontFamily: 'var(--font-mono)',
+ fontSize: 13,
+ resize: 'vertical',
+ minHeight: 120,
+ }}
+ />
+ </div>
+ {buildMutation.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)',
+ }}>
+ {buildMutation.error?.message || 'Build failed'}
+ </div>
+ )}
+ <div style={{ display: 'flex', gap: 8 }}>
+ <button
+ className="btn-primary"
+ onClick={() => buildMutation.mutate({ name: newName, dockerfile: newDockerfile })}
+ disabled={buildMutation.isPending || !newName.trim() || !newDockerfile.trim()}
+ >
+ {buildMutation.isPending ? 'Building\u2026' : 'Build Template'}
+ </button>
+ <button className="btn-ghost" onClick={() => { setShowCreate(false); setNewName(''); setNewDockerfile('') }}>
+ Cancel
+ </button>
+ </div>
+ {buildMutation.isPending && (
+ <div style={{ marginTop: 12, fontSize: 12, color: 'var(--text-tertiary)' }}>
+ Building image and pushing to registry. This may take a few minutes...
+ </div>
+ )}
+ </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>Image</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 style={{ fontFamily: 'var(--font-mono)', fontSize: 12, maxWidth: 300, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
+ {t.imageRef}
+ </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.')) {
+ deleteMutation.mutate(t.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>
+ )}
+ </div>
+ )
+}
diff --git a/web/src/styles/theme.css b/web/src/styles/theme.css
index 17d99137..8900f45e 100644
--- a/web/src/styles/theme.css
+++ b/web/src/styles/theme.css
@@ -213,6 +213,12 @@ body::before {
border: 1px solid rgba(251, 113, 133, 0.18);
}
+.badge-hibernated {
+ background: rgba(34, 211, 238, 0.10);
+ color: #22d3ee;
+ border: 1px solid rgba(34, 211, 238, 0.18);
+}
+
/* --- Table --- */
.data-table {
width: 100%;
diff --git a/web/tsconfig.tsbuildinfo b/web/tsconfig.tsbuildinfo
index 967e053a..b328fe66 100644
--- a/web/tsconfig.tsbuildinfo
+++ b/web/tsconfig.tsbuildinfo
@@ -1 +1 @@
-{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/client.ts","./src/components/layout.tsx","./src/components/protectedroute.tsx","./src/data/mockdata.ts","./src/hooks/useauth.tsx","./src/pages/apikeys.tsx","./src/pages/dashboard.tsx","./src/pages/login.tsx","./src/pages/sessions.tsx","./src/pages/settings.tsx"],"version":"5.6.3"}
\ No newline at end of file
+{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/client.ts","./src/components/layout.tsx","./src/components/protectedroute.tsx","./src/hooks/useauth.tsx","./src/pages/apikeys.tsx","./src/pages/dashboard.tsx","./src/pages/login.tsx","./src/pages/sessions.tsx","./src/pages/settings.tsx","./src/pages/templates.tsx"],"version":"5.6.3"}
\ No newline at end of file