feat(shell): multi-shell per workspace + fix WS disconnect killing bash

BREAKING: every shell operation now requires a shellId. The Manager
previously keyed by workspaceID alone (one bash per workspace). It now
keys by (workspaceID, shellID) where shellID is a UUID returned by
Start.

Fixes the long-standing bug where the WS handler's closeAll called
stdin.Close() and killed bash when a WS client disconnected. The
Session owns the pty file; the WS handler no longer closes it. The
pty is only closed by Manager.Stop (explicit) or by captureOutput
when the process naturally exits (EOF).

- internal/shell/manager.go: Manager interface gains List and every
  method takes shellID; storage becomes
  map[workspaceID]map[shellID]*Session; Start returns (shellID, err)
  via uuid.NewString; Resize/Status/ExitStatus/Subscribe/Stdin/Stop
  route by shellID; new List(workspaceID) returns ShellInfo[] in
  creation order.
- internal/shell/session.go: Session gains ShellID + CreatedAt; Status
  type gains ShellID.
- internal/shell/manager_test.go: updated existing tests for new
  signatures; added TestShellMultiInstance (two shells in one
  workspace, no output cross-talk, independent stop, List behavior).
- internal/service/shell_service.go: wrappers carry shellID; new
  List method.
- internal/service/workspace_service.go: auto-start captures/logs
  shellID; Delete iterates and stops all workspace shells.
- internal/api/shell_handler.go: WS closeAll drops stdin.Close();
  start/restart return 201 with {shellId, pid, ...}; new list handler;
  stop/resize take shellId in body.
- internal/api/router.go: GET /api/workspaces/:id/shell (list).
- internal/model/shell.go: new ShellStartResponse, ShellInfo,
  ShellListResponse, ShellStopRequest, ShellRestartRequest; updated
  ShellStatusResponse + ShellResizeRequest to carry shellId.
- go.mod/go.sum: github.com/google/uuid.

E2E:
- workspace create -> 1 auto shell
- start 2 more -> 3 shells in list
- stop 1 -> 2 shells in list
- WS connect -> send cmd -> disconnect -> WS reconnect -> send cmd ->
  response OK, no [process exited] banner
This commit is contained in:
tao.chen
2026-07-06 14:57:03 +08:00
parent f5a6ff8b0d
commit 13b0c4e53f
10 changed files with 479 additions and 168 deletions
+1
View File
@@ -47,6 +47,7 @@ func NewRouter(workspaces *service.WorkspaceService, files *service.FileService,
api.POST("/workspaces/:id/shell/start", shellHandler.start)
api.POST("/workspaces/:id/shell/stop", shellHandler.stop)
api.POST("/workspaces/:id/shell/restart", shellHandler.restart)
api.GET("/workspaces/:id/shell", shellHandler.list)
api.GET("/workspaces/:id/shell/status", shellHandler.status)
api.GET("/workspaces/:id/shell/ws", shellHandler.ws)
api.POST("/workspaces/:id/shell/resize", shellHandler.resize)
+96 -22
View File
@@ -1,15 +1,14 @@
package api
import (
"fmt"
"net/http"
"strconv"
"sync"
"time"
"codespace/internal/model"
"codespace/internal/service"
"codespace/internal/shell"
"codespace/internal/util"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
@@ -21,23 +20,43 @@ type shellHandler struct {
func shellExitBanner(exit shell.ExitInfo) string {
if exit.Signal != "" {
return fmt.Sprintf("\r\n[process exited: signal %s]\r\n", exit.Signal)
return "\r\n[process exited: signal " + exit.Signal + "]\r\n"
}
return fmt.Sprintf("\r\n[process exited with code %d]\r\n", exit.Code)
return "\r\n[process exited with code " + strconv.Itoa(exit.Code) + "]\r\n"
}
func (h *shellHandler) start(c *gin.Context) {
id := c.Param("id")
if err := h.svc.Start(id); err != nil {
shellID, err := h.svc.Start(id)
if err != nil {
writeError(c, err)
return
}
c.Status(http.StatusNoContent)
status, err := h.svc.Status(id, shellID)
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusCreated, model.ShellStartResponse{
WorkspaceID: status.WorkspaceID,
ShellID: status.ShellID,
Running: status.Running,
PID: status.PID,
})
}
func (h *shellHandler) stop(c *gin.Context) {
id := c.Param("id")
if err := h.svc.Stop(id); err != nil {
var req model.ShellStopRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeBadRequest(c, "invalid json")
return
}
if req.ShellID == "" {
writeBadRequest(c, "shellId is required")
return
}
if err := h.svc.Stop(id, req.ShellID); err != nil {
writeError(c, err)
return
}
@@ -46,11 +65,31 @@ func (h *shellHandler) stop(c *gin.Context) {
func (h *shellHandler) restart(c *gin.Context) {
id := c.Param("id")
if err := h.svc.Restart(id); err != nil {
var req model.ShellRestartRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeBadRequest(c, "invalid json")
return
}
if req.ShellID == "" {
writeBadRequest(c, "shellId is required")
return
}
newShellID, err := h.svc.Restart(id, req.ShellID)
if err != nil {
writeError(c, err)
return
}
c.Status(http.StatusNoContent)
status, err := h.svc.Status(id, newShellID)
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusCreated, model.ShellStartResponse{
WorkspaceID: status.WorkspaceID,
ShellID: status.ShellID,
Running: status.Running,
PID: status.PID,
})
}
func (h *shellHandler) resize(c *gin.Context) {
@@ -60,11 +99,15 @@ func (h *shellHandler) resize(c *gin.Context) {
writeBadRequest(c, "invalid json")
return
}
if req.ShellID == "" {
writeBadRequest(c, "shellId is required")
return
}
if req.Cols <= 0 || req.Rows <= 0 {
writeBadRequest(c, "cols and rows must be positive")
return
}
if err := h.svc.Resize(id, req.Cols, req.Rows); err != nil {
if err := h.svc.Resize(id, req.ShellID, req.Cols, req.Rows); err != nil {
writeError(c, err)
return
}
@@ -73,38 +116,70 @@ func (h *shellHandler) resize(c *gin.Context) {
func (h *shellHandler) status(c *gin.Context) {
id := c.Param("id")
status, err := h.svc.Status(id)
shellID := c.Query("shellId")
if shellID == "" {
writeBadRequest(c, "shellId query parameter is required")
return
}
status, err := h.svc.Status(id, shellID)
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusOK, model.ShellStatusResponse{
WorkspaceID: status.WorkspaceID,
ShellID: status.ShellID,
Running: status.Running,
PID: status.PID,
})
}
func (h *shellHandler) list(c *gin.Context) {
id := c.Param("id")
shells, err := h.svc.List(id)
if err != nil {
writeError(c, err)
return
}
infos := make([]model.ShellInfo, 0, len(shells))
for _, sh := range shells {
infos = append(infos, model.ShellInfo{
WorkspaceID: sh.WorkspaceID,
ShellID: sh.ShellID,
Running: sh.Running,
PID: sh.PID,
CreatedAt: sh.CreatedAt.Format(time.RFC3339Nano),
})
}
c.JSON(http.StatusOK, model.ShellListResponse{
WorkspaceID: id,
Shells: infos,
})
}
func (h *shellHandler) ws(c *gin.Context) {
id := c.Param("id")
stdin, err := h.svc.Input(id)
if err != nil {
if util.CodeOf(err) == util.CodeNotFound {
c.JSON(409, gin.H{"error": "shell not running"})
return
}
writeError(c, err)
shellID := c.Query("shellId")
if shellID == "" {
writeBadRequest(c, "shellId query parameter is required")
return
}
sub, err := h.svc.Subscribe(id)
sub, err := h.svc.Subscribe(id, shellID)
if err != nil {
writeError(c, err)
return
}
exit, _ := h.svc.ExitStatus(id)
stdin, err := h.svc.Input(id, shellID)
if err != nil {
writeError(c, err)
return
}
exit, _ := h.svc.ExitStatus(id, shellID)
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
@@ -123,7 +198,6 @@ func (h *shellHandler) ws(c *gin.Context) {
closeOnce.Do(func() {
sub.Close()
conn.Close()
stdin.Close()
close(done)
})
}