This repository has been archived on 2026-07-17. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
codespace/internal/api/shell_handler.go
T
tao.chen f5a6ff8b0d feat(shell): PTY resize via HTTP + frontend xterm.onResize hook
The PTY was hardcoded to 80x24 at start, so full-screen programs
(htop, vim, less, tmux, top) drew themselves for 80x24 regardless
of the actual xterm window. Add a path for the frontend to push the
real cols/rows to the backend, which calls pty.Setsize on the pty
file.

Backend:
- internal/shell/manager.go: Resize(workspaceID, cols, rows) added to
  the Manager interface and implemented on LocalManager. Looks up the
  session, type-asserts sess.Stdin.(*os.File), calls pty.Setsize.
  Validates cols/rows in [1, 10000] and returns CodeBadRequest on
  bad input, CodeNotFound when no session.
- internal/service/shell_service.go: ShellService.Resize wrapper that
  checks workspace existence first.
- internal/api/shell_handler.go: resize handler, 204 on success.
- internal/api/router.go: register POST /workspaces/:id/shell/resize.
- internal/model/shell.go: ShellResizeRequest{Cols, Rows}.
- internal/shell/manager_test.go: 3 new tests (valid resize via
  pty.Getsize round-trip, invalid size, missing session).

Frontend:
- web/src/lib/api/process.ts: useShellResize mutation hook.
- web/src/components/terminal/TerminalPanel.tsx: terminal.onResize
  subscription with 100ms debounce; filters 0x0; only fires when
  workspaceId is set; cleanup clears timeout + disposes listener.

E2E: 'stty size' after POST /shell/resize {cols:200, rows:50} returns
'50 200'. 0x40 → 400, missing workspace → 404, valid → 204.

Conversation: 019f360a-5eba-7c81-94d3-e5d58ad3c026
2026-07-06 14:16:09 +08:00

176 lines
3.5 KiB
Go

package api
import (
"fmt"
"net/http"
"sync"
"time"
"codespace/internal/model"
"codespace/internal/service"
"codespace/internal/shell"
"codespace/internal/util"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
type shellHandler struct {
svc *service.ShellService
}
func shellExitBanner(exit shell.ExitInfo) string {
if exit.Signal != "" {
return fmt.Sprintf("\r\n[process exited: signal %s]\r\n", exit.Signal)
}
return fmt.Sprintf("\r\n[process exited with code %d]\r\n", exit.Code)
}
func (h *shellHandler) start(c *gin.Context) {
id := c.Param("id")
if err := h.svc.Start(id); err != nil {
writeError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (h *shellHandler) stop(c *gin.Context) {
id := c.Param("id")
if err := h.svc.Stop(id); err != nil {
writeError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (h *shellHandler) restart(c *gin.Context) {
id := c.Param("id")
if err := h.svc.Restart(id); err != nil {
writeError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (h *shellHandler) resize(c *gin.Context) {
id := c.Param("id")
var req model.ShellResizeRequest
if err := c.ShouldBindJSON(&req); err != nil {
writeBadRequest(c, "invalid json")
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 {
writeError(c, err)
return
}
c.Status(http.StatusNoContent)
}
func (h *shellHandler) status(c *gin.Context) {
id := c.Param("id")
status, err := h.svc.Status(id)
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusOK, model.ShellStatusResponse{
WorkspaceID: status.WorkspaceID,
Running: status.Running,
PID: status.PID,
})
}
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)
return
}
sub, err := h.svc.Subscribe(id)
if err != nil {
writeError(c, err)
return
}
exit, _ := h.svc.ExitStatus(id)
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
ReadBufferSize: 4096,
WriteBufferSize: 4096,
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
done := make(chan struct{})
var closeOnce sync.Once
closeAll := func() {
closeOnce.Do(func() {
sub.Close()
conn.Close()
stdin.Close()
close(done)
})
}
go func() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-ticker.C:
if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(5*time.Second)); err != nil {
closeAll()
return
}
case chunk, ok := <-sub.Output():
if !ok {
banner := shellExitBanner(exit)
conn.WriteMessage(websocket.TextMessage, []byte(banner))
conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
closeAll()
return
}
if err := conn.WriteMessage(websocket.TextMessage, chunk); err != nil {
closeAll()
return
}
}
}
}()
conn.SetReadLimit(1 << 20)
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})
for {
mt, data, err := conn.ReadMessage()
if err != nil {
break
}
if mt == websocket.TextMessage {
stdin.Write(data)
}
}
closeAll()
}