An open-source, faster Devin alternative
TypeScript
Add dashboard sandbox delete action (#383)
Mohamed Habib6aefc77b21ad
diff --git a/internal/api/dashboard.go b/internal/api/dashboard.goindex 811480d0..d6200805 100644--- a/internal/api/dashboard.go+++ b/internal/api/dashboard.go@@ -1095,6 +1095,44 @@ func (s *Server) dashboardPowerCycleSession(c echo.Context) error {return c.NoContent(http.StatusNoContent)}+// dashboardDeleteSession stops a running or hibernated sandbox owned by the+// authenticated org. The underlying kill path marks the session stopped,+// removes preview URLs, and best-effort destroys any live VM.+func (s *Server) dashboardDeleteSession(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "database not configured",+ })+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{+ "error": "org context required",+ })+ }++ sandboxID := c.Param("sandboxId")+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{+ "error": "session not found",+ })+ }+ if session.OrgID != orgID {+ return c.JSON(http.StatusForbidden, map[string]string{+ "error": "session does not belong to this organization",+ })+ }+ if session.Status != "running" && session.Status != "hibernated" {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "only running or hibernated sandboxes can be deleted",+ })+ }++ return s.killSandboxByID(c, sandboxID)+}+// dashboardResolveSandbox validates the sandbox belongs to the authenticated org and is running.func (s *Server) dashboardResolveSandbox(c echo.Context) (string, *db.SandboxSession, error) {if s.store == nil {diff --git a/internal/api/router.go b/internal/api/router.goindex ea58f805..87df9046 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -340,6 +340,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oidash := internal.Group("/dashboard")idash.GET("/sessions/:sandboxId", s.dashboardGetSession)idash.GET("/sessions/:sandboxId/stats", s.dashboardGetSessionStats)+ idash.DELETE("/sessions/:sandboxId", s.dashboardDeleteSession)idash.POST("/sessions/:sandboxId/reboot", s.dashboardRebootSession)idash.POST("/sessions/:sandboxId/power-cycle", s.dashboardPowerCycleSession)idash.POST("/sessions/:sandboxId/pty", s.dashboardCreatePTY)@@ -669,6 +670,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// Session detail + statsdash.GET("/sessions/:sandboxId", s.dashboardGetSession)dash.GET("/sessions/:sandboxId/stats", s.dashboardGetSessionStats)+ dash.DELETE("/sessions/:sandboxId", s.dashboardDeleteSession)// Reset operationsdash.POST("/sessions/:sandboxId/reboot", s.dashboardRebootSession)dash.POST("/sessions/:sandboxId/power-cycle", s.dashboardPowerCycleSession)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 3633e94e..fcc05883 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -842,11 +842,13 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {}func (s *Server) killSandbox(c echo.Context) error {- id := c.Param("id")+ return s.killSandboxByID(c, c.Param("id"))+}+func (s *Server) killSandboxByID(c echo.Context, sandboxID string) error {// Server mode with worker registry: dispatch destroy via gRPCif s.workerRegistry != nil {- return s.killSandboxRemote(c, id)+ return s.killSandboxRemote(c, sandboxID)}// Combined/worker mode: kill locally@@ -856,11 +858,11 @@ func (s *Server) killSandbox(c echo.Context) error {// Mark stopped immediately so it no longer counts toward concurrency limits.if s.store != nil {- _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), id, "stopped", nil)- s.cleanupPreviewURLs(c.Request().Context(), id)+ _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", nil)+ s.cleanupPreviewURLs(c.Request().Context(), sandboxID)}- if err := s.manager.Kill(c.Request().Context(), id); err != nil {+ if err := s.manager.Kill(c.Request().Context(), sandboxID); err != nil {return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error(),})@@ -868,11 +870,11 @@ func (s *Server) killSandbox(c echo.Context) error {// Unregister from sandbox routerif s.router != nil {- s.router.Unregister(id)+ s.router.Unregister(sandboxID)}if s.sandboxDBs != nil {- _ = s.sandboxDBs.Remove(id)+ _ = s.sandboxDBs.Remove(sandboxID)}return c.NoContent(http.StatusNoContent)@@ -1120,7 +1122,6 @@ func (s *Server) migrateSandbox(c echo.Context) error {})}-// effectivePlan returns the org's billing plan for billing gates, resolving it// from the most authoritative source available. Plan is a GLOBAL signal: it// changes via the edge (Stripe → DO mark-pro → D1), and no single cell has thediff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 441abf14..038abb3b 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -81,6 +81,9 @@ export const getSessionDetail = (sandboxId: string) =>export const getSessionStats = (sandboxId: string) =>apiFetch<SandboxStats>(`/sessions/${sandboxId}/stats`)+export const deleteSession = (sandboxId: string) =>+ apiFetch<void>(`/sessions/${sandboxId}`, { method: 'DELETE' })+// Soft restart: guest kernel reboots, QEMU process + workspace stay.export const rebootSession = (sandboxId: string) =>apiFetch<void>(`/sessions/${sandboxId}/reboot`, { method: 'POST' })diff --git a/web/src/pages/SessionDetail.tsx b/web/src/pages/SessionDetail.tsxindex d3396a00..05b71348 100644--- a/web/src/pages/SessionDetail.tsx+++ b/web/src/pages/SessionDetail.tsx@@ -1,7 +1,7 @@import { useState } from 'react'import { useParams, useNavigate } from 'react-router-dom'-import { useQuery, useQueryClient } from '@tanstack/react-query'-import { getSessionDetail, getSessionStats, rebootSession, powerCycleSession } from '../api/client'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { deleteSession, getSessionDetail, getSessionStats, rebootSession, powerCycleSession, type Session, type SessionDetail as SessionDetailData } from '../api/client'import Terminal from '../components/Terminal'import LogsPanel from '../components/LogsPanel'@@ -68,6 +68,40 @@ export default function SessionDetail() {const [showInternal, setShowInternal] = useState(false)const [resetState, setResetState] = useState<'idle' | 'rebooting' | 'power-cycling'>('idle')const [resetError, setResetError] = useState<string | null>(null)+ const deleteMutation = useMutation({+ mutationFn: (id: string) => deleteSession(id),+ onMutate: async () => {+ await queryClient.cancelQueries({ queryKey: ['session-detail', sandboxId] })+ await queryClient.cancelQueries({ queryKey: ['sessions'] })+ const stoppedAt = new Date().toISOString()+ queryClient.setQueryData<SessionDetailData>(['session-detail', sandboxId], (old) =>+ old ? { ...old, status: 'stopped', stoppedAt } : old+ )+ queryClient.setQueriesData<Session[]>({ queryKey: ['sessions'] }, (old) =>+ old?.map((item) =>+ item.sandboxId === sandboxId+ ? { ...item, status: 'stopped', stoppedAt }+ : item+ )+ )+ setShowTerminal(false)+ setResetError(null)+ },+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: ['sessions'] })+ queryClient.invalidateQueries({ queryKey: ['session-detail', sandboxId] })+ queryClient.invalidateQueries({ queryKey: ['session-stats', sandboxId] })+ },+ })++ const handleDelete = () => {+ if (!sandboxId) return+ if (!confirm(+ `Delete sandbox ${sandboxId}?\n\n` ++ 'The sandbox will be stopped and its preview URLs removed.'+ )) return+ deleteMutation.mutate(sandboxId)+ }const handleReboot = async () => {if (resetState !== 'idle') return@@ -244,9 +278,27 @@ export default function SessionDetail() {</button></>)}+ {(session.status === 'running' || session.status === 'hibernated') && (+ <button+ className="btn-danger"+ onClick={handleDelete}+ disabled={deleteMutation.isPending}+ title="Stop and delete this sandbox"+ style={{ padding: '9px 18px', fontSize: 13 }}+ >+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">+ <polyline points="3 6 5 6 21 6" />+ <path d="M19 6l-1 14H6L5 6" />+ <path d="M10 11v6" />+ <path d="M14 11v6" />+ <path d="M9 6V4h6v2" />+ </svg>+ {deleteMutation.isPending ? 'Deleting...' : 'Delete'}+ </button>+ )}</div></div>- {resetError && (+ {(resetError || deleteMutation.isError) && (<div style={{marginTop: 12,padding: '10px 14px',@@ -256,7 +308,9 @@ export default function SessionDetail() {color: 'var(--text-error, #f87171)',fontSize: 13,}}>- Reset failed: {resetError}+ {resetError+ ? `Reset failed: ${resetError}`+ : `Delete failed: ${deleteMutation.error instanceof Error ? deleteMutation.error.message : String(deleteMutation.error)}`}</div>)}</div>diff --git a/web/src/pages/Sessions.tsx b/web/src/pages/Sessions.tsxindex 72ac931d..50c7d1ac 100644--- a/web/src/pages/Sessions.tsx+++ b/web/src/pages/Sessions.tsx@@ -1,11 +1,12 @@import { useState, useMemo } from 'react'-import { useQuery } from '@tanstack/react-query'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { useNavigate } from 'react-router-dom'-import { getSessions, type Session } from '../api/client'+import { deleteSession, getSessions, type Session } from '../api/client'const statusFilters = ['', 'running', 'stopped', 'hibernated', 'error'] as constexport default function Sessions() {+ const queryClient = useQueryClient()const [status, setStatus] = useState<string>('')const { data: sessions, isLoading } = useQuery({queryKey: ['sessions', status],@@ -18,6 +19,29 @@ export default function Sessions() {queryFn: () => getSessions(),})+ const deleteMutation = useMutation({+ mutationFn: (sandboxId: string) => deleteSession(sandboxId),+ onMutate: async (sandboxId) => {+ await queryClient.cancelQueries({ queryKey: ['sessions'] })+ const stoppedAt = new Date().toISOString()+ queryClient.setQueriesData<Session[]>({ queryKey: ['sessions'] }, (old) =>+ old?.map((session) =>+ session.sandboxId === sandboxId+ ? { ...session, status: 'stopped', stoppedAt }+ : session+ )+ )+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['sessions'] })+ },+ })++ const handleDelete = (sandboxId: string) => {+ if (!confirm(`Delete sandbox ${sandboxId}?\n\nThe sandbox will be stopped and its preview URLs removed.`)) return+ deleteMutation.mutate(sandboxId)+ }+return (<div><div style={{ marginBottom: 28 }}>@@ -53,6 +77,7 @@ export default function Sessions() {<th>Status</th><th>Started</th><th>Stopped</th>+ <th style={{ width: 96 }}></th></tr></thead><tbody>@@ -63,17 +88,41 @@ export default function Sessions() {<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>+ <td>+ {canDeleteSession(s) && (+ <button+ className="btn-danger"+ disabled={deleteMutation.isPending && deleteMutation.variables === s.sandboxId}+ onClick={(e) => {+ e.stopPropagation()+ handleDelete(s.sandboxId)+ }}+ >+ {deleteMutation.isPending && deleteMutation.variables === s.sandboxId ? 'Deleting...' : 'Delete'}+ </button>+ )}+ </td></ClickableRow>))}{(sessions ?? []).length === 0 && (<tr>- <td colSpan={5} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>+ <td colSpan={6} style={{ textAlign: 'center', padding: 32, color: 'var(--text-tertiary)' }}>No sessions found</td></tr>)}</tbody></table>+ {deleteMutation.isError && (+ <div style={{+ padding: '10px 16px',+ borderTop: '1px solid var(--border-subtle)',+ color: 'var(--accent-rose)',+ fontSize: 13,+ }}>+ Delete failed: {deleteMutation.error instanceof Error ? deleteMutation.error.message : String(deleteMutation.error)}+ </div>+ )}</div>)}</div>@@ -224,6 +273,10 @@ function LegendItem({ color, label }: { color: string; label: string }) {)}+function canDeleteSession(session: Session) {+ return session.status === 'running' || session.status === 'hibernated'+}+function ClickableRow({ sandboxId, children }: { sandboxId: string; children: React.ReactNode }) {const navigate = useNavigate()return (