From 32ccb028959688ed8381446bb8a80643f5768656 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Thu, 6 Aug 2026 11:16:29 +0100 Subject: [PATCH] feat(quick-terminal): unify terminal and chat tabs (#2235) --- .../internal/agent/loginpty/handlers.go | 79 +++- .../internal/agent/loginpty/handlers_test.go | 191 +++++++++ .../internal/agent/loginpty/manager.go | 68 ++- .../internal/agent/loginpty/manager_test.go | 43 ++ .../backend/internal/backendapp/boot_state.go | 12 + apps/backend/internal/backendapp/helpers.go | 18 +- .../internal/backendapp/helpers_test.go | 35 +- apps/backend/internal/backendapp/main.go | 14 + apps/backend/internal/backendapp/storage.go | 6 + apps/backend/internal/backendapp/types.go | 22 +- .../internal/quickterminal/handler_test.go | 118 ++++++ .../internal/quickterminal/models/tab.go | 27 ++ .../quickterminal/repository/sqlite.go | 218 ++++++++++ .../quickterminal/repository/sqlite_test.go | 94 +++++ .../backend/internal/quickterminal/service.go | 311 ++++++++++++++ .../internal/quickterminal/service_test.go | 74 ++++ apps/web/AGENTS.md | 16 +- apps/web/app/page.tsx | 29 +- .../app-sidebar-new-task-item.test.tsx | 51 ++- .../app-sidebar/app-sidebar-new-task-item.tsx | 52 ++- .../settings/settings-tree-render.test.tsx | 7 +- .../kanban/kanban-header-mobile.test.tsx | 30 +- .../kanban/kanban-header-mobile.tsx | 25 +- apps/web/components/kanban/kanban-header.tsx | 50 ++- .../quick-chat/quick-chat-focus.test.ts | 41 ++ .../components/quick-chat/quick-chat-focus.ts | 17 + .../quick-chat/quick-chat-modal.test.tsx | 172 ++++++++ .../quick-chat/quick-chat-modal.tsx | 219 ++++++---- .../quick-chat-provider-focus.test.tsx | 55 +++ .../quick-chat/quick-chat-provider.test.ts | 51 ++- .../quick-chat/quick-chat-provider.tsx | 52 ++- .../quick-chat/quick-chat-tab-item.test.tsx | 37 ++ .../quick-chat/quick-chat-tab-item.tsx | 32 +- .../quick-chat/quick-tab-add-menu.test.tsx | 59 +++ .../quick-chat/quick-tab-add-menu.tsx | 65 +++ .../quick-chat/quick-terminal-tab-item.tsx | 59 +++ .../quick-terminal-tab-view.test.tsx | 112 +++++ .../quick-chat/quick-terminal-tab-view.tsx | 141 +++++++ .../quick-chat/use-quick-chat-modal.test.ts | 151 ++++++- .../quick-chat/use-quick-chat-modal.ts | 294 ++++++++++--- .../components/settings/host-shell-dialog.tsx | 12 +- .../settings/pty-terminal-dialog.tsx | 318 +++----------- .../settings/pty-terminal-lifecycle.ts | 9 + .../settings/pty-terminal-view.test.tsx | 340 +++++++++++++++ .../components/settings/pty-terminal-view.tsx | 392 ++++++++++++++++++ .../chat/entity-reference-composer.spec.ts | 3 +- apps/web/e2e/tests/chat/message-queue.spec.ts | 4 +- .../chat/mobile-quick-chat-entry.spec.ts | 8 +- .../chat/mobile-quick-chat-repository.spec.ts | 3 +- .../chat/quick-chat-cross-device.spec.ts | 13 +- apps/web/e2e/tests/chat/quick-chat-helpers.ts | 22 +- apps/web/e2e/tests/chat/quick-chat.spec.ts | 9 +- .../tests/chat/slash-command-composer.spec.ts | 4 +- .../e2e/tests/settings/host-shell-pty.spec.ts | 238 ++++++----- .../e2e/tests/task/file-tree-rename.spec.ts | 4 +- .../task/repository-selector-scroll.spec.ts | 7 +- .../terminal/mobile-quick-terminal.spec.ts | 180 ++++++++ .../e2e/tests/terminal/quick-terminal.spec.ts | 190 +++++++++ apps/web/hooks/use-quick-chat-launcher.ts | 2 + apps/web/hooks/use-quick-chat-resync.test.ts | 17 +- apps/web/hooks/use-quick-chat-resync.ts | 9 +- .../hooks/use-quick-terminal-launcher.test.ts | 34 ++ apps/web/hooks/use-quick-terminal-launcher.ts | 16 + apps/web/lib/api/domains/host-shell-api.ts | 84 ++++ .../api/domains/quick-terminal-api.test.ts | 103 +++++ .../web/lib/api/domains/quick-terminal-api.ts | 91 ++++ apps/web/lib/api/domains/settings-api.test.ts | 32 ++ apps/web/lib/api/domains/settings-api.ts | 81 +--- apps/web/lib/api/index.ts | 1 + .../lib/desktop/external-links-usage.test.ts | 2 +- apps/web/lib/state/hydration/hydrator.test.ts | 110 +++++ apps/web/lib/state/hydration/hydrator.ts | 99 ++++- .../slices/ui/quick-chat-actions.test.ts | 142 +++++++ .../state/slices/ui/quick-chat-sync.test.ts | 175 +++++++- .../lib/state/slices/ui/quick-chat-sync.ts | 129 +++++- .../state/slices/ui/quick-terminal-actions.ts | 175 ++++++++ apps/web/lib/state/slices/ui/types.ts | 33 ++ apps/web/lib/state/slices/ui/ui-slice.ts | 48 ++- apps/web/lib/state/store.ts | 9 +- apps/web/src/locales/en/agents.json | 1 + apps/web/src/locales/en/common.json | 1 + apps/web/src/locales/en/sidebar.json | 15 + apps/web/src/locales/pseudo/agents.json | 1 + apps/web/src/locales/pseudo/common.json | 1 + apps/web/src/locales/pseudo/sidebar.json | 15 + apps/web/src/locales/zh-cn/agents.json | 1 + apps/web/src/locales/zh-cn/chat.json | 13 + apps/web/src/locales/zh-cn/common.json | 1 + apps/web/src/locales/zh-cn/sidebar.json | 15 + ...server-owned-quick-terminal-descriptors.md | 47 +++ docs/decisions/INDEX.md | 1 + .../plan.md | 185 +++++++++ .../task-01-persist-descriptors.md | 65 +++ .../task-02-descriptor-api-boot.md | 63 +++ .../task-03-web-descriptor-reconciliation.md | 83 ++++ .../task-04-refresh-reattachment-e2e.md | 59 +++ docs/plans/quick-terminal/plan.md | 297 +++++++++++++ .../task-01-quick-terminal-ui.md | 99 +++++ .../task-02-quick-terminal-e2e.md | 87 ++++ ...task-03-fix-quick-terminal-startup-race.md | 57 +++ .../task-04-per-tab-host-shell-sessions.md | 89 ++++ .../task-05-detachable-pty-lifecycle.md | 97 +++++ .../task-06-unified-quick-tabs.md | 141 +++++++ .../quick-terminal/task-07-shared-tabs-e2e.md | 113 +++++ docs/specs/INDEX.md | 1 + docs/specs/quick-terminal/spec.md | 259 ++++++++++++ 106 files changed, 7341 insertions(+), 761 deletions(-) create mode 100644 apps/backend/internal/agent/loginpty/handlers_test.go create mode 100644 apps/backend/internal/quickterminal/handler_test.go create mode 100644 apps/backend/internal/quickterminal/models/tab.go create mode 100644 apps/backend/internal/quickterminal/repository/sqlite.go create mode 100644 apps/backend/internal/quickterminal/repository/sqlite_test.go create mode 100644 apps/backend/internal/quickterminal/service.go create mode 100644 apps/backend/internal/quickterminal/service_test.go create mode 100644 apps/web/components/quick-chat/quick-chat-focus.test.ts create mode 100644 apps/web/components/quick-chat/quick-chat-focus.ts create mode 100644 apps/web/components/quick-chat/quick-chat-modal.test.tsx create mode 100644 apps/web/components/quick-chat/quick-chat-provider-focus.test.tsx create mode 100644 apps/web/components/quick-chat/quick-tab-add-menu.test.tsx create mode 100644 apps/web/components/quick-chat/quick-tab-add-menu.tsx create mode 100644 apps/web/components/quick-chat/quick-terminal-tab-item.tsx create mode 100644 apps/web/components/quick-chat/quick-terminal-tab-view.test.tsx create mode 100644 apps/web/components/quick-chat/quick-terminal-tab-view.tsx create mode 100644 apps/web/components/settings/pty-terminal-lifecycle.ts create mode 100644 apps/web/components/settings/pty-terminal-view.test.tsx create mode 100644 apps/web/components/settings/pty-terminal-view.tsx create mode 100644 apps/web/e2e/tests/terminal/mobile-quick-terminal.spec.ts create mode 100644 apps/web/e2e/tests/terminal/quick-terminal.spec.ts create mode 100644 apps/web/hooks/use-quick-terminal-launcher.test.ts create mode 100644 apps/web/hooks/use-quick-terminal-launcher.ts create mode 100644 apps/web/lib/api/domains/host-shell-api.ts create mode 100644 apps/web/lib/api/domains/quick-terminal-api.test.ts create mode 100644 apps/web/lib/api/domains/quick-terminal-api.ts create mode 100644 apps/web/lib/state/slices/ui/quick-terminal-actions.ts create mode 100644 docs/decisions/2026-08-05-server-owned-quick-terminal-descriptors.md create mode 100644 docs/plans/quick-terminal-refresh-persistence/plan.md create mode 100644 docs/plans/quick-terminal-refresh-persistence/task-01-persist-descriptors.md create mode 100644 docs/plans/quick-terminal-refresh-persistence/task-02-descriptor-api-boot.md create mode 100644 docs/plans/quick-terminal-refresh-persistence/task-03-web-descriptor-reconciliation.md create mode 100644 docs/plans/quick-terminal-refresh-persistence/task-04-refresh-reattachment-e2e.md create mode 100644 docs/plans/quick-terminal/plan.md create mode 100644 docs/plans/quick-terminal/task-01-quick-terminal-ui.md create mode 100644 docs/plans/quick-terminal/task-02-quick-terminal-e2e.md create mode 100644 docs/plans/quick-terminal/task-03-fix-quick-terminal-startup-race.md create mode 100644 docs/plans/quick-terminal/task-04-per-tab-host-shell-sessions.md create mode 100644 docs/plans/quick-terminal/task-05-detachable-pty-lifecycle.md create mode 100644 docs/plans/quick-terminal/task-06-unified-quick-tabs.md create mode 100644 docs/plans/quick-terminal/task-07-shared-tabs-e2e.md create mode 100644 docs/specs/quick-terminal/spec.md diff --git a/apps/backend/internal/agent/loginpty/handlers.go b/apps/backend/internal/agent/loginpty/handlers.go index d1bffdccc4..3d414d19aa 100644 --- a/apps/backend/internal/agent/loginpty/handlers.go +++ b/apps/backend/internal/agent/loginpty/handlers.go @@ -2,13 +2,17 @@ package loginpty import ( "encoding/json" + "errors" + "io" "net/http" "net/url" "os" "os/exec" + "runtime" "strings" "github.com/gin-gonic/gin" + "github.com/google/uuid" gorillaws "github.com/gorilla/websocket" "go.uber.org/zap" @@ -104,17 +108,38 @@ func (h *Handlers) RegisterRoutes(r *gin.Engine) { // hostShellAgentID is the synthetic key the session manager uses for host // shell sessions so they don't collide with agent login sessions. -const hostShellAgentID = "_host_shell" +const HostShellAgentID = "_host_shell" -// httpStartHostShell spawns the user's $SHELL (or /bin/bash, then /bin/sh) -// under a PTY. Returns the standard session snapshot — the client uses the -// same stop/resize/stream endpoints. +const hostShellAgentID = HostShellAgentID + +// httpStartHostShell spawns the user's interactive shell under a PTY. Returns +// the standard session snapshot — the client uses the same +// stop/resize/stream endpoints. func (h *Handlers) httpStartHostShell(c *gin.Context) { var req startRequest - _ = c.ShouldBindJSON(&req) + if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"}) + return + } - shell := detectShell() - sess, err := h.mgr.Start(hostShellAgentID, []string{shell}, req.Cols, req.Rows) + managerKey := hostShellAgentID + if len(req.ClientID) > 0 { + var clientID string + if err := json.Unmarshal(req.ClientID, &clientID); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "client_id must be a UUID"}) + return + } + parsedClientID, err := uuid.Parse(clientID) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "client_id must be a UUID"}) + return + } + managerKey += ":" + parsedClientID.String() + } + + shell, shellArgs := detectShell() + command := append([]string{shell}, shellArgs...) + sess, err := h.mgr.StartWithKey(managerKey, hostShellAgentID, command, req.Cols, req.Rows) if err != nil && err != ErrSessionAlreadyRunning { h.logger.Warn("host shell start failed", zap.Error(err)) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) @@ -123,24 +148,44 @@ func (h *Handlers) httpStartHostShell(c *gin.Context) { c.JSON(http.StatusOK, sess.Status()) } -// detectShell picks a sensible interactive shell, preferring $SHELL. -func detectShell() string { - if s := os.Getenv("SHELL"); s != "" { - if _, err := exec.LookPath(s); err == nil { - return s +// detectShell picks a sensible interactive shell, preferring $SHELL on Unix +// and PowerShell on Windows. The returned arguments are part of the shell +// command because PowerShell needs flags to remain an interactive PTY shell. +func detectShell() (string, []string) { + return detectShellForOS(runtime.GOOS, os.Getenv, func(candidate string) bool { + _, err := exec.LookPath(candidate) + return err == nil + }) +} + +func detectShellForOS(goos string, getenv func(string) string, exists func(string) bool) (string, []string) { + if goos == "windows" { + for _, candidate := range []string{"pwsh.exe", "powershell.exe"} { + if exists(candidate) { + return candidate, []string{"-NoLogo", "-NoExit"} + } } + if comspec := strings.TrimSpace(getenv("COMSPEC")); comspec != "" { + return comspec, nil + } + return "cmd.exe", nil + } + + if shell := strings.TrimSpace(getenv("SHELL")); shell != "" && exists(shell) { + return shell, nil } for _, candidate := range []string{"/bin/bash", "/bin/zsh", "/bin/sh"} { - if _, err := os.Stat(candidate); err == nil { - return candidate + if exists(candidate) { + return candidate, nil } } - return "/bin/sh" + return "/bin/sh", nil } type startRequest struct { - Cols uint16 `json:"cols"` - Rows uint16 `json:"rows"` + Cols uint16 `json:"cols"` + Rows uint16 `json:"rows"` + ClientID json.RawMessage `json:"client_id"` } func (h *Handlers) httpStart(c *gin.Context) { diff --git a/apps/backend/internal/agent/loginpty/handlers_test.go b/apps/backend/internal/agent/loginpty/handlers_test.go new file mode 100644 index 0000000000..0d8785692d --- /dev/null +++ b/apps/backend/internal/agent/loginpty/handlers_test.go @@ -0,0 +1,191 @@ +package loginpty + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +func TestDetectShellWindows(t *testing.T) { + tests := []struct { + name string + env map[string]string + available map[string]bool + wantShell string + wantArgs []string + }{ + { + name: "prefers PowerShell 7", + available: map[string]bool{"pwsh.exe": true, "powershell.exe": true}, + wantShell: "pwsh.exe", + wantArgs: []string{"-NoLogo", "-NoExit"}, + }, + { + name: "falls back to Windows PowerShell", + available: map[string]bool{"powershell.exe": true}, + wantShell: "powershell.exe", + wantArgs: []string{"-NoLogo", "-NoExit"}, + }, + { + name: "uses COMSPEC when PowerShell is unavailable", + env: map[string]string{"COMSPEC": `C:\\Windows\\System32\\cmd.exe`}, + wantShell: `C:\\Windows\\System32\\cmd.exe`, + }, + { + name: "falls back to cmd when COMSPEC is unset", + wantShell: "cmd.exe", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + shell, args := detectShellForOS( + "windows", + func(key string) string { return tt.env[key] }, + func(candidate string) bool { return tt.available[candidate] }, + ) + if shell != tt.wantShell { + t.Fatalf("shell = %q, want %q", shell, tt.wantShell) + } + if !reflect.DeepEqual(args, tt.wantArgs) { + t.Fatalf("args = %#v, want %#v", args, tt.wantArgs) + } + }) + } +} + +func newHostShellRouter(t *testing.T, mgr *Manager) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + router := gin.New() + NewHandlers(mgr, nil, mgr.log.Zap(), nil).RegisterRoutes(router) + return router +} + +func startHostShellRequest(t *testing.T, router http.Handler, body map[string]any) (Status, int) { + t.Helper() + payload, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal request: %v", err) + } + req := httptest.NewRequest(http.MethodPost, "/api/v1/host-shell/start", bytes.NewReader(payload)) + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + router.ServeHTTP(response, req) + if response.Code != http.StatusOK { + return Status{}, response.Code + } + var status Status + if err := json.Unmarshal(response.Body.Bytes(), &status); err != nil { + t.Fatalf("decode start response: %v", err) + } + return status, response.Code +} + +func stopSession(t *testing.T, mgr *Manager, sessionID string) { + t.Helper() + if sess := mgr.GetByID(sessionID); sess != nil { + sess.stop() + } +} + +func TestHostShellClientIDIsIdempotentAndIndependent(t *testing.T) { + mgr := newTestManager(t, nil) + router := newHostShellRouter(t, mgr) + + firstClient := uuid.NewString() + secondClient := uuid.NewString() + first, code := startHostShellRequest(t, router, map[string]any{ + "client_id": firstClient, + "cols": 80, + "rows": 24, + }) + if code != http.StatusOK { + t.Fatalf("first start status = %d", code) + } + t.Cleanup(func() { stopSession(t, mgr, first.ID) }) + if first.AgentID != hostShellAgentID { + t.Fatalf("agent id = %q, want %q", first.AgentID, hostShellAgentID) + } + + repeated, code := startHostShellRequest(t, router, map[string]any{"client_id": firstClient}) + if code != http.StatusOK { + t.Fatalf("repeated start status = %d", code) + } + if repeated.ID != first.ID { + t.Fatalf("repeated start id = %q, want %q", repeated.ID, first.ID) + } + + second, code := startHostShellRequest(t, router, map[string]any{"client_id": secondClient}) + if code != http.StatusOK { + t.Fatalf("second start status = %d", code) + } + t.Cleanup(func() { stopSession(t, mgr, second.ID) }) + if second.ID == first.ID { + t.Fatalf("different client id reused session %q", second.ID) + } + if second.AgentID != hostShellAgentID { + t.Fatalf("second agent id = %q, want %q", second.AgentID, hostShellAgentID) + } + + stopSession(t, mgr, first.ID) + if got := mgr.GetByID(second.ID); got == nil || !got.Status().Running { + t.Fatal("stopping the first client session affected its sibling") + } +} + +func TestHostShellClientIDValidationAndLegacySingleton(t *testing.T) { + mgr := newTestManager(t, nil) + router := newHostShellRouter(t, mgr) + + invalid, code := startHostShellRequest(t, router, map[string]any{"client_id": "not-a-uuid"}) + if code != http.StatusBadRequest { + if invalid.ID != "" { + stopSession(t, mgr, invalid.ID) + } + t.Fatalf("invalid client id status = %d, want %d", code, http.StatusBadRequest) + } + + first, code := startHostShellRequest(t, router, map[string]any{}) + if code != http.StatusOK { + t.Fatalf("legacy first start status = %d", code) + } + t.Cleanup(func() { stopSession(t, mgr, first.ID) }) + second, code := startHostShellRequest(t, router, map[string]any{}) + if code != http.StatusOK { + t.Fatalf("legacy repeated start status = %d", code) + } + if second.ID != first.ID { + t.Fatalf("legacy repeated start id = %q, want %q", second.ID, first.ID) + } +} + +func TestHostShellRejectsMalformedJSON(t *testing.T) { + mgr := newTestManager(t, nil) + router := newHostShellRouter(t, mgr) + + req := httptest.NewRequest( + http.MethodPost, + "/api/v1/host-shell/start", + bytes.NewBufferString(`{"client_id":`), + ) + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + router.ServeHTTP(response, req) + + if response.Code != http.StatusBadRequest { + t.Fatalf("malformed body status = %d, want %d", response.Code, http.StatusBadRequest) + } + mgr.mu.Lock() + activeSessions := len(mgr.sessions) + mgr.mu.Unlock() + if activeSessions != 0 { + t.Fatal("malformed body started a host shell session") + } +} diff --git a/apps/backend/internal/agent/loginpty/manager.go b/apps/backend/internal/agent/loginpty/manager.go index c95206633b..c1afce4a49 100644 --- a/apps/backend/internal/agent/loginpty/manager.go +++ b/apps/backend/internal/agent/loginpty/manager.go @@ -3,10 +3,10 @@ // browser-based or token-prompt auth flows without shelling into the // container. // -// Sessions are keyed by agent ID — at most one login PTY per agent runs at a -// time, since concurrent logins for the same agent would race on the same -// HOME dotfile. The session terminates when the command exits, on idle -// timeout, or on explicit Stop. +// Sessions are keyed by an internal uniqueness key — at most one login PTY per +// key runs at a time. Normal agent logins use the agent ID as that key, while +// callers that own separate logical sessions (such as host-shell tabs) can +// provide a bounded key without changing the public AgentID. package loginpty import ( @@ -47,7 +47,7 @@ var ( // Manager owns active login sessions and dispatches lifecycle callbacks. type Manager struct { mu sync.Mutex - sessions map[string]*Session // key: agentID + sessions map[string]*Session // key: internal uniqueness key byID map[string]*Session // key: sessionID log *logger.Logger @@ -55,6 +55,11 @@ type Manager struct { // agent ID and exit code). Used by callers to invalidate discovery cache // and broadcast updated availability. Optional. onExit func(agentID string, exitCode int, exitErr error) + + // onSessionExit is the owner-aware lifecycle hook. It carries the internal + // uniqueness key so keyed callers can reconcile their durable descriptor + // without changing the stable public AgentID passed to onExit. + onSessionExit func(managerKey, sessionID, agentID string, exitCode int, exitErr error) } // NewManager constructs a Manager. onExit may be nil. @@ -67,15 +72,29 @@ func NewManager(log *logger.Logger, onExit func(agentID string, exitCode int, ex } } -// Start spawns a PTY-backed process for the agent. Returns the session -// snapshot. Fails with ErrSessionAlreadyRunning if a session for this agent -// is already active. +// SetSessionExitCallback registers the owner-aware lifecycle hook. Call this +// during backend construction, before any sessions are started. +func (m *Manager) SetSessionExitCallback(callback func(managerKey, sessionID, agentID string, exitCode int, exitErr error)) { + m.mu.Lock() + defer m.mu.Unlock() + m.onSessionExit = callback +} + +// Start spawns a PTY-backed process for the agent. It preserves the legacy +// one-session-per-agent behavior by using agentID as the internal key. func (m *Manager) Start(agentID string, cmd []string, cols, rows uint16) (*Session, error) { + return m.StartWithKey(agentID, agentID, cmd, cols, rows) +} + +// StartWithKey spawns a PTY-backed process using managerKey for uniqueness +// while retaining agentID as the stable public identity and exit-callback +// value. Fails with ErrSessionAlreadyRunning if managerKey is already active. +func (m *Manager) StartWithKey(managerKey, agentID string, cmd []string, cols, rows uint16) (*Session, error) { if len(cmd) == 0 { return nil, errors.New("empty command") } m.mu.Lock() - if existing, ok := m.sessions[agentID]; ok { + if existing, ok := m.sessions[managerKey]; ok { m.mu.Unlock() _ = existing.Status() // touch return existing, ErrSessionAlreadyRunning @@ -91,6 +110,7 @@ func (m *Manager) Start(agentID string, cmd []string, cols, rows uint16) (*Sessi sess := &Session{ ID: uuid.NewString(), AgentID: agentID, + managerKey: managerKey, Cmd: append([]string(nil), cmd...), subscribers: map[chan<- []byte]struct{}{}, log: m.log.WithFields(zap.String("agent", agentID)), @@ -102,7 +122,7 @@ func (m *Manager) Start(agentID string, cmd []string, cols, rows uint16) (*Sessi return nil, err } - m.sessions[agentID] = sess + m.sessions[managerKey] = sess m.byID[sess.ID] = sess m.mu.Unlock() @@ -129,6 +149,17 @@ func (m *Manager) Stop(agentID string) error { return nil } +// StopSession terminates a session by its public session ID. It is used by +// owners whose uniqueness key is intentionally different from AgentID. +func (m *Manager) StopSession(sessionID string) error { + sess := m.GetByID(sessionID) + if sess == nil { + return ErrSessionNotFound + } + sess.stop() + return nil +} + // supervise watches the session's lifetime: waits on the process, enforces // timeouts, then deletes the session from the manager and notifies onExit. func (m *Manager) supervise(sess *Session) { @@ -204,7 +235,9 @@ loop: } m.mu.Lock() - delete(m.sessions, sess.AgentID) + if current, ok := m.sessions[sess.managerKey]; ok && current == sess { + delete(m.sessions, sess.managerKey) + } delete(m.byID, sess.ID) m.mu.Unlock() @@ -235,6 +268,9 @@ loop: if m.onExit != nil { m.onExit(sess.AgentID, info.code, info.err) } + if m.onSessionExit != nil { + m.onSessionExit(sess.managerKey, sess.ID, sess.AgentID, info.code, info.err) + } } type exitInfo struct { @@ -260,6 +296,7 @@ type Session struct { AgentID string Cmd []string + managerKey string mu sync.Mutex cmd *exec.Cmd pty ptyHandle @@ -281,6 +318,15 @@ type Session struct { log *logger.Logger } +// ManagerKey returns the internal uniqueness key used by Manager. It is +// intentionally separate from AgentID so keyed host shells can prove their +// descriptor owns the session without exposing the key as an agent identity. +func (s *Session) ManagerKey() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.managerKey +} + func (s *Session) start(cmd []string, cols, rows uint16) error { s.activityCh = make(chan struct{}, 1) s.readDone = make(chan struct{}) diff --git a/apps/backend/internal/agent/loginpty/manager_test.go b/apps/backend/internal/agent/loginpty/manager_test.go index 2805a59ec0..84a589e11b 100644 --- a/apps/backend/internal/agent/loginpty/manager_test.go +++ b/apps/backend/internal/agent/loginpty/manager_test.go @@ -102,6 +102,49 @@ func TestStart_IdempotentPerAgent(t *testing.T) { } } +func TestStartWithKey_SeparatesUniquenessFromPublicAgentID(t *testing.T) { + mgr := newTestManager(t, nil) + + first, err := mgr.StartWithKey("_host_shell:tab-a", "_host_shell", []string{"sh", "-c", "sleep 30"}, 80, 24) + if err != nil { + t.Fatalf("first start: %v", err) + } + t.Cleanup(func() { first.stop() }) + second, err := mgr.StartWithKey("_host_shell:tab-b", "_host_shell", []string{"sh", "-c", "sleep 30"}, 80, 24) + if err != nil { + t.Fatalf("second start: %v", err) + } + t.Cleanup(func() { second.stop() }) + + if first.ID == second.ID { + t.Fatalf("distinct manager keys reused session %q", first.ID) + } + if first.AgentID != "_host_shell" || second.AgentID != "_host_shell" { + t.Fatalf("public agent ids = %q and %q, want _host_shell", first.AgentID, second.AgentID) + } + + repeated, err := mgr.StartWithKey("_host_shell:tab-a", "_host_shell", []string{"sh", "-c", "sleep 30"}, 80, 24) + if !errors.Is(err, ErrSessionAlreadyRunning) { + t.Fatalf("repeated start err = %v, want ErrSessionAlreadyRunning", err) + } + if repeated.ID != first.ID { + t.Fatalf("repeated start id = %q, want %q", repeated.ID, first.ID) + } + + first.stop() + deadline := time.After(3 * time.Second) + for mgr.GetByID(first.ID) != nil { + select { + case <-deadline: + t.Fatal("first session was not removed from manager") + case <-time.After(20 * time.Millisecond): + } + } + if sibling := mgr.GetByID(second.ID); sibling == nil || !sibling.Status().Running { + t.Fatal("cleaning up one internal key removed or stopped its sibling") + } +} + func TestStart_EmptyCommand(t *testing.T) { mgr := newTestManager(t, nil) _, err := mgr.Start("test-agent", nil, 80, 24) diff --git a/apps/backend/internal/backendapp/boot_state.go b/apps/backend/internal/backendapp/boot_state.go index 1e75a2418b..28fc953323 100644 --- a/apps/backend/internal/backendapp/boot_state.go +++ b/apps/backend/internal/backendapp/boot_state.go @@ -331,9 +331,21 @@ func (b bootStateBuilder) addQuickChatState( b.logBootError("list quick-chat sessions", err) return } + terminalTabs := []any{} + if b.p.quickTerminalSvc != nil { + if tabs, terminalErr := b.p.quickTerminalSvc.List(ctx, workspaceID); terminalErr != nil { + b.logBootError("list quick-terminal tabs", terminalErr) + } else { + terminalTabs = make([]any, 0, len(tabs)) + for _, tab := range tabs { + terminalTabs = append(terminalTabs, tab) + } + } + } state["quickChat"] = map[string]any{ "isOpen": false, "sessions": quickChat.sessions, + "terminalTabs": terminalTabs, "activeSessionId": nil, } mergeBootTaskSessionItems(state, quickChat.taskSessions) diff --git a/apps/backend/internal/backendapp/helpers.go b/apps/backend/internal/backendapp/helpers.go index 94a7a64031..e89dc29f68 100644 --- a/apps/backend/internal/backendapp/helpers.go +++ b/apps/backend/internal/backendapp/helpers.go @@ -69,6 +69,7 @@ import ( "github.com/kandev/kandev/internal/profiles" promptcontroller "github.com/kandev/kandev/internal/prompts/controller" prompthandlers "github.com/kandev/kandev/internal/prompts/handlers" + "github.com/kandev/kandev/internal/quickterminal" "github.com/kandev/kandev/internal/repoclone" "github.com/kandev/kandev/internal/runtimeflags" "github.com/kandev/kandev/internal/secrets" @@ -517,6 +518,8 @@ type routeParams struct { analyticsRepo analyticsrepository.Repository orchestratorSvc *orchestrator.Service lifecycleMgr *lifecycle.Manager + loginMgr *loginpty.Manager + quickTerminalSvc *quickterminal.Service hostUtilityMgr *hostutility.Manager eventBus bus.EventBus services *Services @@ -1046,15 +1049,12 @@ func registerSecondaryRoutes( p.log.Debug("Registered Agent Settings handlers (HTTP)") // Login PTY: spawns agent login commands under a PTY on the kandev host - // (claude auth login, auggie login, ...). The user explicitly closes the - // dialog when done, so invalidate the discovery cache on every session - // end regardless of exit code — rescanning is cheap and correctly picks - // up new auth state for agents whose login flow lives inside the TUI - // (e.g. gemini) where the process keeps running after auth completes. - loginMgr := loginpty.NewManager(p.log, func(_ string, _ int, _ error) { - p.agentSettingsController.InvalidateDiscoveryCache() - }) - loginpty.NewHandlers(loginMgr, p.agentRegistry, p.log.Zap(), nil).RegisterRoutes(p.router) + // (claude auth login, auggie login, ...). The manager is shared with Quick + // Terminal so descriptor lifecycle callbacks observe the same sessions. + loginpty.NewHandlers(p.loginMgr, p.agentRegistry, p.log.Zap(), nil).RegisterRoutes(p.router) + if p.quickTerminalSvc != nil { + p.quickTerminalSvc.RegisterRoutes(p.router) + } p.log.Debug("Registered Login PTY handlers (HTTP + WebSocket)") userhandlers.RegisterRoutes(p.router, p.gateway.Dispatcher, p.userCtrl, p.log) diff --git a/apps/backend/internal/backendapp/helpers_test.go b/apps/backend/internal/backendapp/helpers_test.go index 1bcf67ee83..9060fc8700 100644 --- a/apps/backend/internal/backendapp/helpers_test.go +++ b/apps/backend/internal/backendapp/helpers_test.go @@ -21,6 +21,8 @@ import ( "github.com/kandev/kandev/internal/db" "github.com/kandev/kandev/internal/events/bus" gateways "github.com/kandev/kandev/internal/gateway/websocket" + "github.com/kandev/kandev/internal/quickterminal" + quickterminalrepo "github.com/kandev/kandev/internal/quickterminal/repository" storagepkg "github.com/kandev/kandev/internal/system/storage" storageworkspaces "github.com/kandev/kandev/internal/system/storage/workspaces" taskdto "github.com/kandev/kandev/internal/task/dto" @@ -1344,6 +1346,11 @@ func TestBootPayloadRestoresQuickChatSessions(t *testing.T) { harness := newBootStateTestHarness(t) ctx := context.Background() repo := harness.taskRepo + quickTerminalRepo, err := quickterminalrepo.NewWithDB(harness.db, harness.db) + if err != nil { + t.Fatalf("quick terminal repository: %v", err) + } + quickTerminalSvc := quickterminal.NewService(quickTerminalRepo, nil, harness.taskSvc) if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-qc", Name: "Quick Chats"}); err != nil { t.Fatalf("CreateWorkspace: %v", err) @@ -1387,12 +1394,16 @@ func TestBootPayloadRestoresQuickChatSessions(t *testing.T) { id: "task-workflow", title: "Workflow Ephemeral", updatedAt: base, sessionUpdatedAt: base, agentProfileID: "agent-workflow", workflowID: "wf-qc", }) + if _, err := quickTerminalSvc.Create(ctx, "ws-qc", "11111111-1111-4111-8111-111111111111"); err != nil { + t.Fatalf("create quick terminal descriptor: %v", err) + } req := httptest.NewRequest(http.MethodGet, "/?workspaceId=ws-qc", nil) payload := bootPayload(ctx, req, routeParams{ - taskSvc: harness.taskSvc, - services: &Services{Workflow: harness.workflowSvc}, - userCtrl: harness.userCtrl, + taskSvc: harness.taskSvc, + services: &Services{Workflow: harness.workflowSvc}, + userCtrl: harness.userCtrl, + quickTerminalSvc: quickTerminalSvc, }, webapp.ClassifyRoute("/")) raw, err := json.Marshal(payload) @@ -1411,6 +1422,12 @@ func TestBootPayloadRestoresQuickChatSessions(t *testing.T) { } `json:"sessions"` IsOpen bool `json:"isOpen"` ActiveSessionID *string `json:"activeSessionId"` + TerminalTabs []struct { + TabID string `json:"tabId"` + Status string `json:"status"` + Error string `json:"error"` + Workspace string `json:"workspaceId"` + } `json:"terminalTabs"` } `json:"quickChat"` TaskSessions struct { Items map[string]struct { @@ -1451,6 +1468,16 @@ func TestBootPayloadRestoresQuickChatSessions(t *testing.T) { if decoded.InitialState.QuickChat.ActiveSessionID != nil { t.Fatalf("quick chat active session = %q, want nil", *decoded.InitialState.QuickChat.ActiveSessionID) } + if len(decoded.InitialState.QuickChat.TerminalTabs) != 1 { + t.Fatalf("quickChat terminal tabs = %#v, want one restored descriptor", decoded.InitialState.QuickChat.TerminalTabs) + } + tab := decoded.InitialState.QuickChat.TerminalTabs[0] + if tab.TabID != "11111111-1111-4111-8111-111111111111" || tab.Workspace != "ws-qc" { + t.Fatalf("restored terminal identity = %#v", tab) + } + if tab.Status != "exited" || tab.Error == "" { + t.Fatalf("stale terminal lifecycle = %#v, want exited/unavailable", tab) + } } func TestBootPayloadRestoresQuickChatsFromTaskRouteWorkspace(t *testing.T) { @@ -1804,6 +1831,7 @@ func TestQueryValueReadsRouteQueryFromAppStatePath(t *testing.T) { } type bootStateTestHarness struct { + db *sqlx.DB taskSvc *taskservice.Service taskRepo *sqlitetaskrepo.Repository workflowSvc *workflowservice.Service @@ -1881,6 +1909,7 @@ func newBootStateTestHarness(t *testing.T) bootStateTestHarness { taskSvc.SetStartStepResolver(&startStepResolverAdapter{svc: workflowSvc}) workflowSvc.SetWorkflowProvider(&workflowProviderAdapter{svc: taskSvc}) return bootStateTestHarness{ + db: sqlxDB, taskSvc: taskSvc, taskRepo: taskRepo, workflowSvc: workflowSvc, diff --git a/apps/backend/internal/backendapp/main.go b/apps/backend/internal/backendapp/main.go index cf7f15f1c1..4a88386a33 100644 --- a/apps/backend/internal/backendapp/main.go +++ b/apps/backend/internal/backendapp/main.go @@ -45,6 +45,7 @@ import ( // Agent infrastructure "github.com/kandev/kandev/internal/agent/hostutility" + "github.com/kandev/kandev/internal/agent/loginpty" "github.com/kandev/kandev/internal/agent/mcpconfig" "github.com/kandev/kandev/internal/agent/registry" agentctlclient "github.com/kandev/kandev/internal/agent/runtime/agentctl" @@ -109,6 +110,7 @@ import ( workflowservice "github.com/kandev/kandev/internal/workflow/service" // Repository cloning + "github.com/kandev/kandev/internal/quickterminal" "github.com/kandev/kandev/internal/repoclone" "github.com/kandev/kandev/internal/runtimeflags" @@ -1797,6 +1799,16 @@ func buildHTTPServer( return nil, fmt.Errorf("generate interim settings interlock token: %w", err) } userSecretStore := secrets.NewUserVisibleStore(repos.Secrets) + // The login PTY manager is shared by agent-login dialogs and Quick + // Terminal tabs. The latter uses an owner-aware exit callback to keep its + // durable descriptor accurate even while no browser is attached. + loginMgr := loginpty.NewManager(log, func(_ string, _ int, _ error) { + if agentSettingsController != nil { + agentSettingsController.InvalidateDiscoveryCache() + } + }) + quickTerminalSvc := quickterminal.NewService(repos.QuickTerminal, loginMgr, services.Task) + loginMgr.SetSessionExitCallback(quickTerminalSvc.HandleSessionExit) // Opt-in authentication. Runs after CORS; in disabled mode it only // injects the synthetic single-user identity (behavior unchanged). @@ -1817,6 +1829,8 @@ func buildHTTPServer( analyticsRepo: repos.Analytics, orchestratorSvc: orchestratorSvc, lifecycleMgr: lifecycleMgr, + loginMgr: loginMgr, + quickTerminalSvc: quickTerminalSvc, hostUtilityMgr: hostUtilityMgr, eventBus: eventBus, services: services, diff --git a/apps/backend/internal/backendapp/storage.go b/apps/backend/internal/backendapp/storage.go index 09b93753a8..c2aaa5fc13 100644 --- a/apps/backend/internal/backendapp/storage.go +++ b/apps/backend/internal/backendapp/storage.go @@ -12,6 +12,7 @@ import ( "github.com/kandev/kandev/internal/common/logger" "github.com/kandev/kandev/internal/db" "github.com/kandev/kandev/internal/persistence" + quickterminalrepository "github.com/kandev/kandev/internal/quickterminal/repository" "github.com/kandev/kandev/internal/secrets" "github.com/kandev/kandev/internal/task/repository" terminalrepo "github.com/kandev/kandev/internal/terminal/repository" @@ -72,6 +73,10 @@ func provideRepositories(ctx context.Context, cfg *config.Config, log *logger.Lo if err != nil { return nil, nil, nil, fmt.Errorf("terminal repo: %w", err) } + quickTerminalRepoImpl, err := quickterminalrepository.NewWithDB(writer, reader) + if err != nil { + return nil, nil, nil, fmt.Errorf("quick terminal repo: %w", err) + } runtimeFlagsStore, err := runtimeflags.NewSQLiteStore(writer, reader) if err != nil { return nil, nil, nil, fmt.Errorf("runtime flags store: %w", err) @@ -109,6 +114,7 @@ func provideRepositories(ctx context.Context, cfg *config.Config, log *logger.Lo Secrets: secretStore, Office: officeRepo, Terminal: terminalRepoImpl, + QuickTerminal: quickTerminalRepoImpl, RuntimeFlags: runtimeFlagsStore, Auth: authRepo, } diff --git a/apps/backend/internal/backendapp/types.go b/apps/backend/internal/backendapp/types.go index 313bcb073b..d7337d857d 100644 --- a/apps/backend/internal/backendapp/types.go +++ b/apps/backend/internal/backendapp/types.go @@ -23,6 +23,7 @@ import ( "github.com/kandev/kandev/internal/plugins" promptservice "github.com/kandev/kandev/internal/prompts/service" promptstore "github.com/kandev/kandev/internal/prompts/store" + quickterminalrepository "github.com/kandev/kandev/internal/quickterminal/repository" "github.com/kandev/kandev/internal/runtimeflags" "github.com/kandev/kandev/internal/secrets" "github.com/kandev/kandev/internal/sentry" @@ -49,16 +50,17 @@ type Repositories struct { User userstore.Repository // UserAccounts is the account-management view of the same user store // (list/create/role/status), consumed by the auth service. - UserAccounts userstore.AccountRepository - Notification notificationstore.Repository - Editor editorstore.Repository - Prompts promptstore.Repository - Utility utilitystore.Repository - Workflow *workflowrepository.Repository - Secrets secrets.SecretStore - Office *officesqlite.Repository - Terminal *terminalrepo.Repository - RuntimeFlags *runtimeflags.SQLiteStore + UserAccounts userstore.AccountRepository + Notification notificationstore.Repository + Editor editorstore.Repository + Prompts promptstore.Repository + Utility utilitystore.Repository + Workflow *workflowrepository.Repository + Secrets secrets.SecretStore + Office *officesqlite.Repository + Terminal *terminalrepo.Repository + QuickTerminal *quickterminalrepository.Repository + RuntimeFlags *runtimeflags.SQLiteStore // Auth persists login identities, sessions, PATs, and invites. Auth *authstore.Store } diff --git a/apps/backend/internal/quickterminal/handler_test.go b/apps/backend/internal/quickterminal/handler_test.go new file mode 100644 index 0000000000..149af21673 --- /dev/null +++ b/apps/backend/internal/quickterminal/handler_test.go @@ -0,0 +1,118 @@ +package quickterminal + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "github.com/kandev/kandev/internal/quickterminal/repository" +) + +func testRouter(t *testing.T, svc *Service) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + router := gin.New() + svc.RegisterRoutes(router) + return router +} + +func TestHTTPQuickTerminalTabLifecycleIsWorkspaceScopedAndIdempotent(t *testing.T) { + repo := serviceRepository(t) + svc := NewService(repo, nil, nil) + router := testRouter(t, svc) + tabID := uuid.NewString() + + body, _ := json.Marshal(map[string]string{ + "tab_id": tabID, + "workspace_id": "workspace-1", + }) + request := httptest.NewRequest(http.MethodPost, "/api/v1/quick-terminal-tabs", bytes.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + if response.Code != http.StatusOK { + t.Fatalf("create status = %d, body %s", response.Code, response.Body.String()) + } + var first struct { + TabID string `json:"tabId"` + Sequence int `json:"sequence"` + } + if err := json.Unmarshal(response.Body.Bytes(), &first); err != nil { + t.Fatalf("decode create: %v", err) + } + if first.TabID != tabID || first.Sequence != 1 { + t.Fatalf("first descriptor = %#v", first) + } + + repeated := httptest.NewRecorder() + router.ServeHTTP(repeated, httptest.NewRequest( + http.MethodPost, + "/api/v1/quick-terminal-tabs", + bytes.NewReader(body), + )) + if repeated.Code != http.StatusOK { + t.Fatalf("repeated status = %d", repeated.Code) + } + var repeatedTab struct { + Sequence int `json:"sequence"` + } + _ = json.Unmarshal(repeated.Body.Bytes(), &repeatedTab) + if repeatedTab.Sequence != 1 { + t.Fatalf("repeated sequence = %d, want 1", repeatedTab.Sequence) + } + + list := httptest.NewRecorder() + router.ServeHTTP(list, httptest.NewRequest( + http.MethodGet, + "/api/v1/quick-terminal-tabs?workspace_id=workspace-1", + nil, + )) + if list.Code != http.StatusOK { + t.Fatalf("list status = %d", list.Code) + } + var listed struct { + Tabs []struct { + TabID string `json:"tabId"` + } `json:"tabs"` + } + if err := json.Unmarshal(list.Body.Bytes(), &listed); err != nil { + t.Fatalf("decode list: %v", err) + } + if len(listed.Tabs) != 1 || listed.Tabs[0].TabID != tabID { + t.Fatalf("listed tabs = %#v", listed.Tabs) + } + + deleteResponse := httptest.NewRecorder() + router.ServeHTTP(deleteResponse, httptest.NewRequest( + http.MethodDelete, + "/api/v1/quick-terminal-tabs/"+tabID, + nil, + )) + if deleteResponse.Code != http.StatusOK { + t.Fatalf("delete status = %d", deleteResponse.Code) + } + if _, err := repo.Get(context.Background(), "default-user", tabID); err == nil { + t.Fatal("deleted descriptor still exists") + } else if err != repository.ErrNotFound { + t.Fatalf("get deleted descriptor: %v", err) + } +} + +func TestHTTPQuickTerminalRejectsInvalidTabID(t *testing.T) { + svc := NewService(serviceRepository(t), nil, nil) + router := testRouter(t, svc) + body := bytes.NewBufferString(`{"tab_id":"bad","workspace_id":"workspace-1"}`) + request := httptest.NewRequest(http.MethodPost, "/api/v1/quick-terminal-tabs", body) + request.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + if response.Code != http.StatusBadRequest { + t.Fatalf("invalid tab status = %d, want 400", response.Code) + } +} diff --git a/apps/backend/internal/quickterminal/models/tab.go b/apps/backend/internal/quickterminal/models/tab.go new file mode 100644 index 0000000000..8d4761b3c6 --- /dev/null +++ b/apps/backend/internal/quickterminal/models/tab.go @@ -0,0 +1,27 @@ +// Package models defines the durable descriptors for Quick Terminal tabs. +package models + +import "time" + +const ( + StatusConnecting = "connecting" + StatusRunning = "running" + StatusExited = "exited" + StatusError = "error" +) + +// Tab is the server-owned identity and lifecycle snapshot for one Quick +// Terminal tab. The PTY itself remains owned by loginpty and is intentionally +// not persisted here. +type Tab struct { + TabID string `db:"tab_id" json:"tabId"` + UserID string `db:"user_id" json:"-"` + WorkspaceID string `db:"workspace_id" json:"workspaceId"` + SessionID *string `db:"session_id" json:"sessionId"` + Sequence int `db:"sequence" json:"sequence"` + Status string `db:"status" json:"status"` + ExitCode *int `db:"exit_code" json:"exitCode,omitempty"` + Error string `db:"error" json:"error,omitempty"` + CreatedAt time.Time `db:"created_at" json:"-"` + UpdatedAt time.Time `db:"updated_at" json:"-"` +} diff --git a/apps/backend/internal/quickterminal/repository/sqlite.go b/apps/backend/internal/quickterminal/repository/sqlite.go new file mode 100644 index 0000000000..a843032f98 --- /dev/null +++ b/apps/backend/internal/quickterminal/repository/sqlite.go @@ -0,0 +1,218 @@ +// Package repository persists server-owned Quick Terminal descriptors. +package repository + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + + "github.com/jmoiron/sqlx" + + "github.com/kandev/kandev/internal/quickterminal/models" +) + +var ( + ErrNotFound = errors.New("quick terminal tab not found") + ErrTabIDConflict = errors.New("quick terminal tab id belongs to another user") +) + +type Repository struct { + db *sqlx.DB + ro *sqlx.DB +} + +func NewWithDB(writer, reader *sqlx.DB) (*Repository, error) { + r := &Repository{db: writer, ro: reader} + if err := r.initSchema(); err != nil { + return nil, fmt.Errorf("init quick terminal schema: %w", err) + } + return r, nil +} + +func (r *Repository) initSchema() error { + statements := []string{ + `CREATE TABLE IF NOT EXISTS quick_terminal_tabs ( + tab_id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + workspace_id TEXT NOT NULL, + session_id TEXT, + sequence INTEGER NOT NULL, + status TEXT NOT NULL DEFAULT 'connecting', + exit_code INTEGER, + error TEXT NOT NULL DEFAULT '', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE(user_id, workspace_id, sequence) + )`, + `CREATE TABLE IF NOT EXISTS quick_terminal_workspace_sequences ( + user_id TEXT NOT NULL, + workspace_id TEXT NOT NULL, + next_sequence INTEGER NOT NULL, + PRIMARY KEY(user_id, workspace_id) + )`, + `CREATE INDEX IF NOT EXISTS idx_quick_terminal_tabs_workspace + ON quick_terminal_tabs(user_id, workspace_id, sequence)`, + `CREATE INDEX IF NOT EXISTS idx_quick_terminal_tabs_session + ON quick_terminal_tabs(session_id)`, + } + for _, statement := range statements { + if _, err := r.db.Exec(r.db.Rebind(statement)); err != nil { + return err + } + } + return nil +} + +const tabColumns = `tab_id, user_id, workspace_id, session_id, sequence, status, + exit_code, error, created_at, updated_at` + +func (r *Repository) Create(ctx context.Context, userID, workspaceID, tabID string) (*models.Tab, error) { + tx, err := r.db.BeginTxx(ctx, nil) + if err != nil { + return nil, fmt.Errorf("begin quick terminal create: %w", err) + } + defer func() { _ = tx.Rollback() }() + + var existing models.Tab + err = tx.GetContext(ctx, &existing, r.db.Rebind( + `SELECT `+tabColumns+` FROM quick_terminal_tabs WHERE tab_id = ? AND user_id = ?`, + ), tabID, userID) + if err == nil { + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit existing quick terminal: %w", err) + } + return &existing, nil + } + if !errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("find quick terminal: %w", err) + } + + var sequence int + err = tx.GetContext(ctx, &sequence, r.db.Rebind(` + INSERT INTO quick_terminal_workspace_sequences (user_id, workspace_id, next_sequence) + VALUES (?, ?, 2) + ON CONFLICT(user_id, workspace_id) DO UPDATE + SET next_sequence = quick_terminal_workspace_sequences.next_sequence + 1 + RETURNING next_sequence - 1 + `), userID, workspaceID) + if err != nil { + return nil, fmt.Errorf("allocate quick terminal sequence: %w", err) + } + + _, err = tx.ExecContext(ctx, r.db.Rebind(` + INSERT INTO quick_terminal_tabs + (tab_id, user_id, workspace_id, sequence, status, error) + VALUES (?, ?, ?, ?, ?, ?) + `), tabID, userID, workspaceID, sequence, models.StatusConnecting, "") + if err != nil { + if strings.Contains(strings.ToLower(err.Error()), "unique") { + return nil, ErrTabIDConflict + } + return nil, fmt.Errorf("insert quick terminal: %w", err) + } + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("commit quick terminal: %w", err) + } + return r.Get(ctx, userID, tabID) +} + +func (r *Repository) Get(ctx context.Context, userID, tabID string) (*models.Tab, error) { + var tab models.Tab + err := r.ro.GetContext(ctx, &tab, r.ro.Rebind( + `SELECT `+tabColumns+` FROM quick_terminal_tabs WHERE user_id = ? AND tab_id = ?`, + ), userID, tabID) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("get quick terminal: %w", err) + } + return &tab, nil +} + +func (r *Repository) GetByTabID(ctx context.Context, tabID string) (*models.Tab, error) { + var tab models.Tab + err := r.ro.GetContext(ctx, &tab, r.ro.Rebind( + `SELECT `+tabColumns+` FROM quick_terminal_tabs WHERE tab_id = ?`, + ), tabID) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, fmt.Errorf("get quick terminal by id: %w", err) + } + return &tab, nil +} + +func (r *Repository) List(ctx context.Context, userID, workspaceID string) ([]*models.Tab, error) { + var tabs []*models.Tab + if err := r.ro.SelectContext(ctx, &tabs, r.ro.Rebind( + `SELECT `+tabColumns+` FROM quick_terminal_tabs + WHERE user_id = ? AND workspace_id = ? ORDER BY sequence ASC`, + ), userID, workspaceID); err != nil { + return nil, fmt.Errorf("list quick terminals: %w", err) + } + return tabs, nil +} + +func (r *Repository) UpdateLifecycle( + ctx context.Context, + userID, tabID, sessionID, status string, + exitCode *int, + errorText string, +) error { + result, err := r.db.ExecContext(ctx, r.db.Rebind(` + UPDATE quick_terminal_tabs + SET session_id = ?, status = ?, exit_code = ?, error = ?, updated_at = CURRENT_TIMESTAMP + WHERE user_id = ? AND tab_id = ? + `), nullableString(sessionID), status, exitCode, errorText, userID, tabID) + if err != nil { + return fmt.Errorf("update quick terminal lifecycle: %w", err) + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return nil +} + +func (r *Repository) UpdateLifecycleByTabID( + ctx context.Context, + tabID, sessionID, status string, + exitCode *int, + errorText string, +) error { + result, err := r.db.ExecContext(ctx, r.db.Rebind(` + UPDATE quick_terminal_tabs + SET session_id = ?, status = ?, exit_code = ?, error = ?, updated_at = CURRENT_TIMESTAMP + WHERE tab_id = ? AND session_id = ? + `), nullableString(sessionID), status, exitCode, errorText, tabID, sessionID) + if err != nil { + return fmt.Errorf("update quick terminal exit: %w", err) + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return nil +} + +func (r *Repository) Delete(ctx context.Context, userID, tabID string) error { + result, err := r.db.ExecContext(ctx, r.db.Rebind( + `DELETE FROM quick_terminal_tabs WHERE user_id = ? AND tab_id = ?`, + ), userID, tabID) + if err != nil { + return fmt.Errorf("delete quick terminal: %w", err) + } + if affected, _ := result.RowsAffected(); affected == 0 { + return ErrNotFound + } + return nil +} + +func nullableString(value string) any { + if value == "" { + return nil + } + return value +} diff --git a/apps/backend/internal/quickterminal/repository/sqlite_test.go b/apps/backend/internal/quickterminal/repository/sqlite_test.go new file mode 100644 index 0000000000..3bf5794d13 --- /dev/null +++ b/apps/backend/internal/quickterminal/repository/sqlite_test.go @@ -0,0 +1,94 @@ +package repository + +import ( + "context" + "database/sql" + "testing" + + "github.com/jmoiron/sqlx" + _ "github.com/mattn/go-sqlite3" +) + +func testRepository(t *testing.T) *Repository { + t.Helper() + raw, err := sql.Open("sqlite3", "file::memory:?cache=shared&_foreign_keys=on") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + raw.SetMaxOpenConns(1) + db := sqlx.NewDb(raw, "sqlite3") + t.Cleanup(func() { _ = db.Close() }) + repo, err := NewWithDB(db, db) + if err != nil { + t.Fatalf("new repository: %v", err) + } + return repo +} + +func TestCreateIsIdempotentAndSequencesNeverReuse(t *testing.T) { + repo := testRepository(t) + ctx := context.Background() + + first, err := repo.Create(ctx, "user-1", "workspace-1", "tab-1") + if err != nil { + t.Fatalf("create first: %v", err) + } + repeated, err := repo.Create(ctx, "user-1", "workspace-1", "tab-1") + if err != nil { + t.Fatalf("create repeated: %v", err) + } + if repeated.TabID != first.TabID || repeated.Sequence != first.Sequence { + t.Fatalf("repeated create = %#v, want %#v", repeated, first) + } + + second, err := repo.Create(ctx, "user-1", "workspace-1", "tab-2") + if err != nil { + t.Fatalf("create second: %v", err) + } + if second.Sequence != 2 { + t.Fatalf("second sequence = %d, want 2", second.Sequence) + } + if err := repo.Delete(ctx, "user-1", "tab-2"); err != nil { + t.Fatalf("delete second: %v", err) + } + + third, err := repo.Create(ctx, "user-1", "workspace-1", "tab-3") + if err != nil { + t.Fatalf("create third: %v", err) + } + if third.Sequence != 3 { + t.Fatalf("third sequence = %d, want 3 after deleting sequence 2", third.Sequence) + } + + otherWorkspace, err := repo.Create(ctx, "user-1", "workspace-2", "tab-4") + if err != nil { + t.Fatalf("create other workspace: %v", err) + } + if otherWorkspace.Sequence != 1 { + t.Fatalf("other workspace sequence = %d, want 1", otherWorkspace.Sequence) + } +} + +func TestUpdateLifecyclePersistsSessionAndExit(t *testing.T) { + repo := testRepository(t) + ctx := context.Background() + if _, err := repo.Create(ctx, "user-1", "workspace-1", "tab-1"); err != nil { + t.Fatalf("create: %v", err) + } + + exitCode := 7 + if err := repo.UpdateLifecycle(ctx, "user-1", "tab-1", "session-1", "running", nil, ""); err != nil { + t.Fatalf("set running: %v", err) + } + if err := repo.UpdateLifecycle(ctx, "user-1", "tab-1", "", "exited", &exitCode, ""); err != nil { + t.Fatalf("set exited: %v", err) + } + + tab, err := repo.Get(ctx, "user-1", "tab-1") + if err != nil { + t.Fatalf("get: %v", err) + } + if tab.SessionID != nil || tab.Status != "exited" || tab.ExitCode == nil || *tab.ExitCode != exitCode { + t.Fatalf("lifecycle = %#v, want cleared exited session", tab) + } +} diff --git a/apps/backend/internal/quickterminal/service.go b/apps/backend/internal/quickterminal/service.go new file mode 100644 index 0000000000..7887d0cc7c --- /dev/null +++ b/apps/backend/internal/quickterminal/service.go @@ -0,0 +1,311 @@ +package quickterminal + +import ( + "context" + "errors" + "strings" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "github.com/kandev/kandev/internal/agent/loginpty" + "github.com/kandev/kandev/internal/auth/authn" + "github.com/kandev/kandev/internal/quickterminal/models" + "github.com/kandev/kandev/internal/quickterminal/repository" + "github.com/kandev/kandev/internal/user/store" +) + +var ( + ErrInvalidTabID = errors.New("quick terminal tab id must be a UUID") + ErrInvalidStatus = errors.New("invalid quick terminal status") + ErrSessionBinding = errors.New("quick terminal session is not owned by this tab") +) + +// WorkspaceAuthorizer is the narrow task-service capability needed to keep +// descriptors scoped to a workspace the caller can see. +type WorkspaceAuthorizer interface { + AuthorizeWorkspaceAccess(context.Context, string) error +} + +type Service struct { + repo *repository.Repository + manager *loginpty.Manager + authorizer WorkspaceAuthorizer +} + +func NewService( + repo *repository.Repository, + manager *loginpty.Manager, + authorizer WorkspaceAuthorizer, +) *Service { + return &Service{repo: repo, manager: manager, authorizer: authorizer} +} + +func (s *Service) RegisterRoutes(router *gin.Engine) { + api := router.Group("/api/v1") + api.GET("/quick-terminal-tabs", s.httpList) + api.POST("/quick-terminal-tabs", s.httpCreate) + api.PATCH("/quick-terminal-tabs/:tabID", s.httpUpdate) + api.DELETE("/quick-terminal-tabs/:tabID", s.httpDelete) +} + +func (s *Service) List(ctx context.Context, workspaceID string) ([]*models.Tab, error) { + if err := s.authorize(ctx, workspaceID); err != nil { + return nil, err + } + userID := callerID(ctx) + tabs, err := s.repo.List(ctx, userID, workspaceID) + if err != nil { + return nil, err + } + for _, tab := range tabs { + if err := s.reconcileTab(ctx, tab); err != nil { + return nil, err + } + } + return tabs, nil +} + +func (s *Service) Create(ctx context.Context, workspaceID, tabID string) (*models.Tab, error) { + if err := validateTabID(tabID); err != nil { + return nil, err + } + if err := s.authorize(ctx, workspaceID); err != nil { + return nil, err + } + tab, err := s.repo.Create(ctx, callerID(ctx), workspaceID, tabID) + if err != nil { + return nil, err + } + if tab.WorkspaceID != workspaceID { + return nil, repository.ErrTabIDConflict + } + return tab, nil +} + +func (s *Service) UpdateLifecycle( + ctx context.Context, + tabID, sessionID, status, errorText string, + exitCode *int, +) (*models.Tab, error) { + if err := validateTabID(tabID); err != nil { + return nil, err + } + if !validStatus(status) { + return nil, ErrInvalidStatus + } + userID := callerID(ctx) + tab, err := s.repo.Get(ctx, userID, tabID) + if err != nil { + return nil, err + } + if err := s.authorize(ctx, tab.WorkspaceID); err != nil { + return nil, err + } + + sessionID = strings.TrimSpace(sessionID) + if status == models.StatusExited { + sessionID = "" + } + if status == models.StatusRunning && sessionID == "" { + return nil, ErrSessionBinding + } + if sessionID != "" && !s.ownsSession(tabID, sessionID) { + return nil, ErrSessionBinding + } + if err := s.repo.UpdateLifecycle(ctx, userID, tabID, sessionID, status, exitCode, errorText); err != nil { + return nil, err + } + return s.repo.Get(ctx, userID, tabID) +} + +func (s *Service) Delete(ctx context.Context, tabID string) error { + if err := validateTabID(tabID); err != nil { + return err + } + userID := callerID(ctx) + tab, err := s.repo.Get(ctx, userID, tabID) + if err != nil { + return err + } + if err := s.authorize(ctx, tab.WorkspaceID); err != nil { + return err + } + if tab.SessionID != nil && s.ownsSession(tabID, *tab.SessionID) { + if err := s.manager.StopSession(*tab.SessionID); err != nil && !errors.Is(err, loginpty.ErrSessionNotFound) { + return err + } + } + return s.repo.Delete(ctx, userID, tabID) +} + +// HandleSessionExit is registered as loginpty's owner-aware callback. It is +// intentionally context-free because the manager outlives any one request. +func (s *Service) HandleSessionExit(managerKey, sessionID, _ string, exitCode int, exitErr error) { + const prefix = loginpty.HostShellAgentID + ":" + if !strings.HasPrefix(managerKey, prefix) { + return + } + tabID := strings.TrimPrefix(managerKey, prefix) + if validateTabID(tabID) != nil { + return + } + errorText := "" + if exitErr != nil { + errorText = exitErr.Error() + } + if err := s.repo.UpdateLifecycleByTabID( + context.Background(), tabID, sessionID, models.StatusExited, &exitCode, errorText, + ); err != nil && !errors.Is(err, repository.ErrNotFound) { + // The descriptor may have been explicitly deleted while the PTY was + // unwinding. There is no request to report that failure to. + return + } +} + +func (s *Service) reconcileTab(ctx context.Context, tab *models.Tab) error { + if tab == nil || tab.SessionID == nil { + if tab != nil && tab.Status == models.StatusConnecting { + tab.Status = models.StatusExited + tab.Error = "terminal session unavailable" + if err := s.repo.UpdateLifecycle(ctx, tab.UserID, tab.TabID, "", tab.Status, nil, tab.Error); err != nil { + return err + } + } + return nil + } + if !s.ownsSession(tab.TabID, *tab.SessionID) { + return s.markUnavailable(ctx, tab) + } + status := s.manager.GetByID(*tab.SessionID).Status() + if !status.Running { + return s.markUnavailable(ctx, tab) + } + tab.Status = models.StatusRunning + tab.ExitCode = nil + tab.Error = "" + return s.repo.UpdateLifecycle(ctx, tab.UserID, tab.TabID, *tab.SessionID, tab.Status, nil, "") +} + +func (s *Service) markUnavailable(ctx context.Context, tab *models.Tab) error { + tab.SessionID = nil + tab.Status = models.StatusExited + tab.ExitCode = nil + tab.Error = "terminal session unavailable" + return s.repo.UpdateLifecycle(ctx, tab.UserID, tab.TabID, "", tab.Status, nil, tab.Error) +} + +func (s *Service) ownsSession(tabID, sessionID string) bool { + if s.manager == nil { + return false + } + session := s.manager.GetByID(sessionID) + return session != nil && + session.AgentID == loginpty.HostShellAgentID && + session.ManagerKey() == loginpty.HostShellAgentID+":"+tabID +} + +func (s *Service) authorize(ctx context.Context, workspaceID string) error { + if strings.TrimSpace(workspaceID) == "" { + return errors.New("workspace id is required") + } + if s.authorizer == nil { + return nil + } + return s.authorizer.AuthorizeWorkspaceAccess(ctx, workspaceID) +} + +func (s *Service) httpList(c *gin.Context) { + tabs, err := s.List(c.Request.Context(), c.Query("workspace_id")) + if err != nil { + s.writeError(c, err) + return + } + c.JSON(200, gin.H{"tabs": tabs}) +} + +type createRequest struct { + TabID string `json:"tab_id"` + WorkspaceID string `json:"workspace_id"` +} + +func (s *Service) httpCreate(c *gin.Context) { + var req createRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(400, gin.H{"error": "invalid request body"}) + return + } + tab, err := s.Create(c.Request.Context(), req.WorkspaceID, req.TabID) + if err != nil { + s.writeError(c, err) + return + } + c.JSON(200, tab) +} + +type updateRequest struct { + SessionID string `json:"session_id"` + Status string `json:"status"` + ExitCode *int `json:"exit_code"` + Error string `json:"error"` +} + +func (s *Service) httpUpdate(c *gin.Context) { + var req updateRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(400, gin.H{"error": "invalid request body"}) + return + } + tab, err := s.UpdateLifecycle(c.Request.Context(), c.Param("tabID"), req.SessionID, req.Status, req.Error, req.ExitCode) + if err != nil { + s.writeError(c, err) + return + } + c.JSON(200, tab) +} + +func (s *Service) httpDelete(c *gin.Context) { + if err := s.Delete(c.Request.Context(), c.Param("tabID")); err != nil { + s.writeError(c, err) + return + } + c.JSON(200, gin.H{"ok": true}) +} + +func (s *Service) writeError(c *gin.Context, err error) { + status := 500 + switch { + case errors.Is(err, repository.ErrNotFound): + status = 404 + case errors.Is(err, repository.ErrTabIDConflict), errors.Is(err, ErrSessionBinding): + status = 409 + case errors.Is(err, ErrInvalidTabID), errors.Is(err, ErrInvalidStatus): + status = 400 + case strings.Contains(err.Error(), "workspace id is required"): + status = 400 + } + c.JSON(status, gin.H{"error": err.Error()}) +} + +func callerID(ctx context.Context) string { + if identity, ok := authn.IdentityFromContext(ctx); ok && identity.UserID != "" { + return identity.UserID + } + return store.DefaultUserID +} + +func validateTabID(tabID string) error { + if _, err := uuid.Parse(strings.TrimSpace(tabID)); err != nil { + return ErrInvalidTabID + } + return nil +} + +func validStatus(status string) bool { + switch status { + case models.StatusConnecting, models.StatusRunning, models.StatusExited, models.StatusError: + return true + default: + return false + } +} diff --git a/apps/backend/internal/quickterminal/service_test.go b/apps/backend/internal/quickterminal/service_test.go new file mode 100644 index 0000000000..80118f0365 --- /dev/null +++ b/apps/backend/internal/quickterminal/service_test.go @@ -0,0 +1,74 @@ +package quickterminal + +import ( + "context" + "database/sql" + "testing" + + "github.com/jmoiron/sqlx" + _ "github.com/mattn/go-sqlite3" + + "github.com/kandev/kandev/internal/quickterminal/repository" + "github.com/kandev/kandev/internal/user/store" +) + +func serviceRepository(t *testing.T) *repository.Repository { + t.Helper() + raw, err := sql.Open("sqlite3", "file::memory:?cache=shared&_foreign_keys=on") + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + raw.SetMaxOpenConns(1) + db := sqlx.NewDb(raw, "sqlite3") + t.Cleanup(func() { _ = db.Close() }) + repo, err := repository.NewWithDB(db, db) + if err != nil { + t.Fatalf("new repository: %v", err) + } + return repo +} + +func TestListMarksAConnectingDescriptorWithoutPTYAsUnavailable(t *testing.T) { + repo := serviceRepository(t) + ctx := context.Background() + tabID := "11111111-1111-4111-8111-111111111111" + if _, err := repo.Create(ctx, store.DefaultUserID, "workspace-1", tabID); err != nil { + t.Fatalf("create: %v", err) + } + + svc := NewService(repo, nil, nil) + tabs, err := svc.List(ctx, "workspace-1") + if err != nil { + t.Fatalf("list: %v", err) + } + if len(tabs) != 1 || tabs[0].Status != "exited" || tabs[0].Error == "" { + t.Fatalf("tabs = %#v, want unavailable exited descriptor", tabs) + } + if tabs[0].SessionID != nil { + t.Fatalf("session id = %v, want nil", tabs[0].SessionID) + } +} + +func TestCreateRejectsNonUUIDAndRequiresWorkspace(t *testing.T) { + svc := NewService(serviceRepository(t), nil, nil) + if _, err := svc.Create(context.Background(), "workspace-1", "not-a-uuid"); err != ErrInvalidTabID { + t.Fatalf("invalid tab id error = %v, want %v", err, ErrInvalidTabID) + } + if _, err := svc.Create(context.Background(), "", "11111111-1111-4111-8111-111111111111"); err == nil { + t.Fatal("expected empty workspace to be rejected") + } +} + +func TestCreateRejectsReusingATabIDInAnotherWorkspace(t *testing.T) { + repo := serviceRepository(t) + svc := NewService(repo, nil, nil) + ctx := context.Background() + tabID := "11111111-1111-4111-8111-111111111111" + + if _, err := svc.Create(ctx, "workspace-1", tabID); err != nil { + t.Fatalf("create first: %v", err) + } + if _, err := svc.Create(ctx, "workspace-2", tabID); err != repository.ErrTabIDConflict { + t.Fatalf("cross-workspace reuse error = %v, want %v", err, repository.ErrTabIDConflict) + } +} diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index a7204c95f9..9a58b7d829 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -72,6 +72,10 @@ lib/api/domains/ # API clients - `tasks.activeTaskId`, `tasks.activeSessionId`, `workspaces.activeId` - `repositories.byWorkspace`, `repositoryBranches.byRepository` +Quick Chat stores server conversations in `quickChat.sessions` and browser-local terminals in +`quickChat.terminalTabs`; `activeKind` and terminal IDs track selection. `quick-terminal-actions.ts` +owns lifecycle/fallback; terminal descriptors never enter conversation APIs or get lost in reconciliation. + **Hydration:** Go injects `window.__KANDEV_BOOT_PAYLOAD__` into the SPA shell before React mounts. `lib/state/hydration/merge-strategies.ts` has `deepMerge()`, `mergeSessionMap()`, `mergeLoadingState()` to avoid overwriting live client state. Pass `activeSessionId` to protect active sessions. For rebasing or finishing PRs written against the old Next.js runtime, follow [`docs/nextjs-spa-migration.md`](../../docs/nextjs-spa-migration.md). @@ -285,16 +289,12 @@ plugin leaks a stale registration. `/api/plugins/{id}/user-state/...` (`docs/decisions/2026-08-01-per-user-plugin-storage.md`). `subscribe` (`lib/plugins/user-state-sync.ts`) wraps `registerWsHandler` with own-plugin filtering and own-tab echo suppression via a per-tab `writerId`. -- **`host.ui.RichTextEditor`/`RichTextReadOnly`** (`components/editors/tiptap/rich-text-editor.tsx`): - narrow Plan-panel-tiptap wrappers — don't widen their props beyond - `{ taskId, value, onChange, placeholder, className, testId }` / `{ value, className, testId }` - without updating `PLUGIN-API.md`. +- **`host.ui.RichTextEditor`/`RichTextReadOnly`** (`components/editors/tiptap/rich-text-editor.tsx`): narrow Plan-panel-tiptap wrappers; update `PLUGIN-API.md` before widening props beyond `{ taskId, value, onChange, placeholder, className, testId }` / `{ value, className, testId }`. ## Testing notes - jsdom drops `secure` cookies over `http`, so `document.cookie` reads back empty. To assert a cookie write in a Vitest unit test, intercept the setter with `Object.defineProperty(document, "cookie", { set: ... })` and restore it after. -- jsdom synthetic mouse events do not reliably open Radix Tooltip. In component tests, render under - `TooltipProvider` and assert the keyboard-focus path with `fireEvent.focus`. Cover pointer hover in - Playwright with `locator.hover()` and assert the portaled `role="tooltip"`; don't drop a hover - regression just because `mouseenter`/`pointerMove` failed in jsdom. +- jsdom synthetic mouse events do not reliably open Radix Tooltip. In component tests, use + `TooltipProvider` and assert keyboard focus; cover pointer hover in Playwright with `locator.hover()` + and a visible `role="tooltip"`, keeping regressions that jsdom cannot exercise. - In Playwright tests, avoid strict locators that assume only one `terminal-panel` or `.xterm` exists. Mobile and dockview layouts can mount multiple terminal instances; scope to the active panel or use `.first()` / `.last()` deliberately with a comment or helper. Shared E2E helpers that inspect mounted React/DOM internals must also be scoped to the active panel/container, not global selectors, because hidden or stale mounted panels can coexist in dock/mobile layouts. diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx index 07cbe55b10..a1d9119398 100644 --- a/apps/web/app/page.tsx +++ b/apps/web/app/page.tsx @@ -8,9 +8,11 @@ import { listWorkspaces, listTaskSessionMessages, listQuickChatSessions, + listQuickTerminalTabs, } from "@/lib/api"; import { listWorkspaceTaskPRs } from "@/lib/api/domains/github-api"; import { toQuickChatSessions } from "@/lib/quick-chat/map-sessions"; +import { toQuickTerminalTab } from "@/lib/api/domains/quick-terminal-api"; import { snapshotToState } from "@/lib/ssr/mapper"; import { mapUserSettingsResponse } from "@/lib/ssr/user-settings"; import { resolveDesiredWorkflowId } from "@/lib/kanban/resolve-workflow"; @@ -125,16 +127,18 @@ async function loadWorkspaceState({ // The client will fetch the data after mount via useWorkspacePRs. listWorkspaceTaskPRs(activeWorkspaceId, { cache: "no-store" }).catch(() => {}); - const [workflowList, repositoriesResponse, quickChatResponse] = await Promise.all([ - listWorkflows(activeWorkspaceId, { cache: "no-store", includeHidden: true }), - listRepositories(activeWorkspaceId, undefined, { cache: "no-store" }).catch(() => ({ - repositories: [], - })), - listQuickChatSessions(activeWorkspaceId, { cache: "no-store" }).catch(() => ({ - sessions: [], - task_sessions: [], - })), - ]); + const [workflowList, repositoriesResponse, quickChatResponse, quickTerminalResponse] = + await Promise.all([ + listWorkflows(activeWorkspaceId, { cache: "no-store", includeHidden: true }), + listRepositories(activeWorkspaceId, undefined, { cache: "no-store" }).catch(() => ({ + repositories: [], + })), + listQuickChatSessions(activeWorkspaceId, { cache: "no-store" }).catch(() => ({ + sessions: [], + task_sessions: [], + })), + listQuickTerminalTabs(activeWorkspaceId, { cache: "no-store" }).catch(() => ({ tabs: [] })), + ]); // null preserves the user's explicit "All Workflows" choice. const workflowId = resolveDesiredWorkflowId({ activeWorkflowId: workflowIdParam ?? null, @@ -142,6 +146,7 @@ async function loadWorkspaceState({ workspaceWorkflows: workflowList.workflows, }); const quickChatSessions = toQuickChatSessions(quickChatResponse.sessions); + const quickTerminalTabs = quickTerminalResponse.tabs.map(toQuickTerminalTab); return { workflowId, @@ -169,6 +174,10 @@ async function loadWorkspaceState({ isOpen: false, sessions: quickChatSessions, activeSessionId: null, + terminalTabs: quickTerminalTabs, + activeKind: "conversation" as const, + activeTerminalTabId: null, + lastTerminalTabIdByWorkspace: {}, }, }, }; diff --git a/apps/web/components/app-sidebar/app-sidebar-new-task-item.test.tsx b/apps/web/components/app-sidebar/app-sidebar-new-task-item.test.tsx index c952caf6e2..b38c43a6a4 100644 --- a/apps/web/components/app-sidebar/app-sidebar-new-task-item.test.tsx +++ b/apps/web/components/app-sidebar/app-sidebar-new-task-item.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; -import { act, cleanup, render, screen } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; import { TooltipProvider } from "@kandev/ui/tooltip"; const mocks = vi.hoisted(() => ({ @@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({ setActiveTask: vi.fn(), setActiveSession: vi.fn(), openQuickChat: vi.fn(), + openQuickTerminal: vi.fn(), dialogTaskSessionId: null as string | null, dialogWillNavigate: false, })); @@ -28,6 +29,8 @@ const state = { setActiveTask: mocks.setActiveTask, setActiveSession: mocks.setActiveSession, }; +const QUICK_TERMINAL_TEST_ID = "sidebar-quick-terminal-shortcut"; +const QUICK_CHAT_TEST_ID = "sidebar-quick-chat-shortcut"; let officeEnabled = false; let pathname = "/"; @@ -37,6 +40,9 @@ vi.mock("@/components/state-provider", () => ({ vi.mock("@/hooks/use-quick-chat-launcher", () => ({ useQuickChatLauncher: () => mocks.openQuickChat, })); +vi.mock("@/hooks/use-quick-terminal-launcher", () => ({ + useQuickTerminalLauncher: () => mocks.openQuickTerminal, +})); vi.mock("@/hooks/domains/features/use-feature", () => ({ useFeature: () => officeEnabled, })); @@ -88,6 +94,7 @@ function resetTestState() { mocks.setActiveTask.mockClear(); mocks.setActiveSession.mockClear(); mocks.openQuickChat.mockClear(); + mocks.openQuickTerminal.mockClear(); mocks.dialogTaskSessionId = null; mocks.dialogWillNavigate = false; officeEnabled = false; @@ -149,21 +156,57 @@ describe("AppSidebarNewTaskItem dialog routing", () => { }); describe("AppSidebarNewTaskItem row actions", () => { + it("opens quick terminal from the action immediately left of Quick Chat", () => { + renderItem(false); + + const terminal = screen.getByTestId(QUICK_TERMINAL_TEST_ID); + const quickChat = screen.getByTestId(QUICK_CHAT_TEST_ID); + expect(terminal.nextElementSibling).toBe(quickChat); + + terminal.click(); + expect(mocks.openQuickTerminal).toHaveBeenCalledOnce(); + }); + + it("does not show the terminal tooltip when focus returns after closing", async () => { + renderItem(false); + + const terminal = screen.getByTestId(QUICK_TERMINAL_TEST_ID); + fireEvent.pointerEnter(terminal); + expect(await screen.findByRole("tooltip")).toBeTruthy(); + fireEvent.focus(terminal); + + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + + it("shows the terminal tooltip on pointer hover", async () => { + renderItem(false); + + const terminal = screen.getByTestId(QUICK_TERMINAL_TEST_ID); + fireEvent.pointerEnter(terminal); + + expect((await screen.findByRole("tooltip")).textContent).toBe("Quick terminal"); + + fireEvent.pointerLeave(terminal); + expect(screen.queryByRole("tooltip")).toBeNull(); + }); + it("opens quick chat from the trailing action beside New Task", () => { renderItem(false); - screen.getByTestId("sidebar-quick-chat-shortcut").click(); + screen.getByTestId(QUICK_CHAT_TEST_ID).click(); expect(mocks.openQuickChat).toHaveBeenCalledOnce(); }); it("hides the quick chat shortcut when the rail is collapsed", () => { renderItem(true); - expect(screen.queryByTestId("sidebar-quick-chat-shortcut")).toBeNull(); + expect(screen.queryByTestId(QUICK_CHAT_TEST_ID)).toBeNull(); + expect(screen.queryByTestId(QUICK_TERMINAL_TEST_ID)).toBeNull(); }); it("hides the quick chat shortcut when there is no active workspace", () => { state.workspaces.activeId = null; renderItem(false); - expect(screen.queryByTestId("sidebar-quick-chat-shortcut")).toBeNull(); + expect(screen.queryByTestId(QUICK_CHAT_TEST_ID)).toBeNull(); + expect(screen.queryByTestId(QUICK_TERMINAL_TEST_ID)).toBeNull(); }); }); diff --git a/apps/web/components/app-sidebar/app-sidebar-new-task-item.tsx b/apps/web/components/app-sidebar/app-sidebar-new-task-item.tsx index f676a5975e..2a5e1197a3 100644 --- a/apps/web/components/app-sidebar/app-sidebar-new-task-item.tsx +++ b/apps/web/components/app-sidebar/app-sidebar-new-task-item.tsx @@ -1,15 +1,23 @@ "use client"; -import { useCallback, useEffect, useState, type Dispatch, type SetStateAction } from "react"; +import { + useCallback, + useEffect, + useRef, + useState, + type Dispatch, + type SetStateAction, +} from "react"; import { useTranslation } from "react-i18next"; import dynamic from "@/lib/routing/client-dynamic"; import { useRouter } from "@/lib/routing/client-router"; -import { IconMessageCircle, IconSquarePlus } from "@tabler/icons-react"; +import { IconMessageCircle, IconSquarePlus, IconTerminal2 } from "@tabler/icons-react"; import type { Icon as TablerIcon } from "@tabler/icons-react"; import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; import { useAppStore } from "@/components/state-provider"; import { useInOffice } from "@/hooks/use-in-office"; import { useQuickChatLauncher } from "@/hooks/use-quick-chat-launcher"; +import { useQuickTerminalLauncher } from "@/hooks/use-quick-terminal-launcher"; import { TaskCreateDialog } from "@/components/task-create-dialog"; import { linkToTask } from "@/lib/links"; import type { Task } from "@/lib/types/http"; @@ -38,7 +46,7 @@ function useNewTaskCreationRequest( }, [setOpen, workspaceId]); } -const ONE_ROW_ACTION_INSET_CLASS = "pr-10"; +const ROW_ACTION_INSET_CLASS = "pr-16"; type RowActionButtonProps = { icon: TablerIcon; label: string; @@ -47,12 +55,35 @@ type RowActionButtonProps = { }; function RowActionButton({ icon: Icon, label, testId, onClick }: RowActionButtonProps) { + const [tooltipOpen, setTooltipOpen] = useState(false); + const hoveredRef = useRef(false); + + const handleTooltipOpenChange = (nextOpen: boolean) => { + // Focus is restored to this action after Quick Terminal closes. Keep the + // tooltip pointer-driven so that accessibility focus does not leave a + // stale popover behind the dialog. + if (nextOpen && !hoveredRef.current) return; + setTooltipOpen(nextOpen); + }; + return ( - + + )} {workspaceId && ( + + + ); +} + function TabletHeader({ title, workspaceLabel, @@ -172,7 +206,6 @@ function TabletHeader({ }) { const { t } = useTranslation(); const isHome = title === "Home"; - const handleOpenQuickChat = useQuickChatLauncher(workspaceId); return ( - {workspaceId && ( - - )} + diff --git a/apps/web/components/quick-chat/quick-chat-focus.test.ts b/apps/web/components/quick-chat/quick-chat-focus.test.ts new file mode 100644 index 0000000000..c0db671f77 --- /dev/null +++ b/apps/web/components/quick-chat/quick-chat-focus.test.ts @@ -0,0 +1,41 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { captureQuickChatLauncherFocus, restoreQuickChatLauncherFocus } from "./quick-chat-focus"; + +afterEach(() => { + vi.unstubAllGlobals(); + document.body.replaceChildren(); +}); + +describe("quick chat launcher focus", () => { + it("restores focus through the animation frame after closing", () => { + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { + callback(0); + return 0; + }); + const launcher = document.createElement("button"); + document.body.append(launcher); + launcher.focus(); + + captureQuickChatLauncherFocus(); + launcher.blur(); + restoreQuickChatLauncherFocus(); + + expect(document.activeElement).toBe(launcher); + }); + + it("does not focus a launcher that was removed while the dialog was open", () => { + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { + callback(0); + return 0; + }); + const launcher = document.createElement("button"); + document.body.append(launcher); + launcher.focus(); + + captureQuickChatLauncherFocus(); + launcher.remove(); + restoreQuickChatLauncherFocus(); + + expect(document.activeElement).not.toBe(launcher); + }); +}); diff --git a/apps/web/components/quick-chat/quick-chat-focus.ts b/apps/web/components/quick-chat/quick-chat-focus.ts new file mode 100644 index 0000000000..61b8599bea --- /dev/null +++ b/apps/web/components/quick-chat/quick-chat-focus.ts @@ -0,0 +1,17 @@ +let launcherFocus: HTMLElement | null = null; + +/** Records the control that opened the shared Quick Chat surface. */ +export function captureQuickChatLauncherFocus(): void { + if (typeof document === "undefined") return; + launcherFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null; +} + +/** Restores launcher focus after the shared dialog has finished closing. */ +export function restoreQuickChatLauncherFocus(): void { + const element = launcherFocus; + launcherFocus = null; + if (!element) return; + requestAnimationFrame(() => { + if (element.isConnected) element.focus(); + }); +} diff --git a/apps/web/components/quick-chat/quick-chat-modal.test.tsx b/apps/web/components/quick-chat/quick-chat-modal.test.tsx new file mode 100644 index 0000000000..9baa8f4f70 --- /dev/null +++ b/apps/web/components/quick-chat/quick-chat-modal.test.tsx @@ -0,0 +1,172 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +const setQuickChatInitialPrompt = vi.fn(); +const handleActivateTerminal = vi.fn(); +const handleNewTerminal = vi.fn(); +const handleCloseTerminal = vi.fn(); +const handleOpenChange = vi.fn(); +const handleNewChat = vi.fn(); +const CHAT_NAME = "Chat one"; +const WORKSPACE_ID = "ws-1"; +const TERMINAL_TAB_ID = "terminal-1"; + +vi.mock("@/components/state-provider", () => ({ + useAppStore: ( + selector: (state: { setQuickChatInitialPrompt: typeof setQuickChatInitialPrompt }) => unknown, + ) => selector({ setQuickChatInitialPrompt }), +})); + +vi.mock("@/lib/routing/client-dynamic", () => ({ + default: () => + function MockTerminalView({ tab }: { tab: { tabId: string } }) { + return
; + }, +})); + +vi.mock("@kandev/ui/dialog", () => ({ + Dialog: ({ open, children }: { open: boolean; children: React.ReactNode }) => + open ?
{children}
: null, + DialogContent: ({ children }: { children: React.ReactNode }) =>
{children}
, + DialogTitle: ({ children }: { children: React.ReactNode }) =>
{children}
, +})); + +vi.mock("@kandev/ui/dropdown-menu", () => ({ + DropdownMenu: ({ children }: { children: React.ReactNode }) =>
{children}
, + DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) =>
{children}
, + DropdownMenuContent: ({ children }: { children: React.ReactNode }) =>
{children}
, + DropdownMenuLabel: ({ children }: { children: React.ReactNode }) =>
{children}
, + DropdownMenuSeparator: () =>
, + DropdownMenuItem: ({ + children, + onSelect, + ...props + }: { + children: React.ReactNode; + onSelect?: () => void; + [key: string]: unknown; + }) => ( + + ), +})); + +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ + t: (key: string, values?: { count?: number }) => { + if (key === "sidebar:quickChatTerminalTab") return `Terminal ${values?.count}`; + if (key === "common:agents") return "Agents"; + if (key === "sidebar:quickChatTerminals") return "Terminals"; + if (key === "sidebar:quickChatNewAgent") return "New Agent"; + if (key === "sidebar:quickChatNewTerminal") return "New Terminal"; + if (key === "sidebar:quickChatAdd") return "Add or switch tab"; + return key; + }, + }), +})); + +vi.mock("@/hooks/use-quick-chat-width", () => ({ + useQuickChatWidth: () => ({ + width: 720, + leftResizeHandleProps: {}, + rightResizeHandleProps: {}, + }), +})); + +vi.mock("@/components/config-chat/use-config-chat", () => ({ + useConfigChat: () => ({ + defaultProfileId: null, + isStarting: false, + error: null, + reset: vi.fn(), + startSession: vi.fn(), + }), +})); + +vi.mock("./quick-chat-delete-dialog", () => ({ + QuickChatDeleteDialog: () => null, +})); +vi.mock("./quick-chat-session-view", () => ({ + QuickChatSessionView: () =>
, +})); +vi.mock("./quick-chat-setup", () => ({ + QuickChatSetup: () =>
, +})); +vi.mock("@/components/config-chat/config-chat-setup", () => ({ + ConfigChatSetup: () =>
, +})); +vi.mock("./use-quick-chat-modal", () => ({ + useQuickChatModal: () => ({ + isOpen: true, + sessions: [{ sessionId: "chat-1", workspaceId: WORKSPACE_ID, kind: "chat", name: CHAT_NAME }], + terminalTabs: [ + { + tabId: TERMINAL_TAB_ID, + workspaceId: WORKSPACE_ID, + sessionId: "pty-1", + sequence: 1, + status: "running", + }, + ], + activeKind: "terminal", + activeSessionId: "chat-1", + activeTerminalTabId: TERMINAL_TAB_ID, + activeTerminalTab: { + tabId: TERMINAL_TAB_ID, + workspaceId: WORKSPACE_ID, + sessionId: "pty-1", + sequence: 1, + status: "running", + }, + activeSession: { + sessionId: "chat-1", + workspaceId: WORKSPACE_ID, + kind: "chat", + name: CHAT_NAME, + }, + sessionToClose: null, + setupKey: 0, + activeSessionNeedsAgent: true, + pendingAgentId: null, + setActiveQuickChatSession: vi.fn(), + setSessionToClose: vi.fn(), + handleOpenChange, + handleNewChat, + handleNewTerminal, + handleActivateTerminal, + handleTerminalStateChange: vi.fn(), + handleSetupKindChange: vi.fn(), + handleSelectAgent: vi.fn(), + handleCloseTab: vi.fn(), + handleCloseTerminal, + handleConfirmClose: vi.fn(), + handleRename: vi.fn(), + }), +})); + +import { QuickChatModal } from "./quick-chat-modal"; + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); +}); + +describe("QuickChatModal mixed tabs", () => { + it("renders terminal content beside conversation tabs in one dialog", () => { + render(); + + expect(screen.getByTestId("quick-chat-dialog")).toBeTruthy(); + expect(screen.queryByTestId("quick-chat-session-view")).toBeNull(); + expect(screen.queryByTestId("quick-chat-setup")).toBeNull(); + expect(screen.getByTestId("quick-chat-tab").className).toContain("text-muted-foreground"); + expect(screen.getByTestId("mock-quick-terminal-view").getAttribute("data-tab-id")).toBe( + "terminal-1", + ); + expect(screen.getByTestId("quick-chat-add-menu-trigger")).toBeTruthy(); + expect(screen.getByText("Agents")).toBeTruthy(); + expect(screen.getByText("Terminals")).toBeTruthy(); + expect(screen.queryByTestId("quick-chat-menu-session-chat-1")).toBeNull(); + expect(screen.queryByTestId("quick-chat-menu-terminal-terminal-1")).toBeNull(); + }); +}); diff --git a/apps/web/components/quick-chat/quick-chat-modal.tsx b/apps/web/components/quick-chat/quick-chat-modal.tsx index 91f4c37d16..edd9e7897c 100644 --- a/apps/web/components/quick-chat/quick-chat-modal.tsx +++ b/apps/web/components/quick-chat/quick-chat-modal.tsx @@ -1,23 +1,31 @@ "use client"; import { memo, type CSSProperties } from "react"; +import { useTranslation } from "react-i18next"; import { Dialog, DialogContent, DialogTitle } from "@kandev/ui/dialog"; import { Button } from "@kandev/ui/button"; -import { IconPlus, IconX } from "@tabler/icons-react"; +import { IconX } from "@tabler/icons-react"; import { useAppStore } from "@/components/state-provider"; +import dynamic from "@/lib/routing/client-dynamic"; import { QuickChatDeleteDialog } from "./quick-chat-delete-dialog"; import { QuickChatSessionView } from "./quick-chat-session-view"; import { QuickChatTabItem } from "./quick-chat-tab-item"; +import { QuickTerminalTabItem } from "./quick-terminal-tab-item"; +import { QuickTabAddMenu } from "./quick-tab-add-menu"; import { QuickChatSetup } from "./quick-chat-setup"; import { useQuickChatModal } from "./use-quick-chat-modal"; import { useQuickChatWidth } from "@/hooks/use-quick-chat-width"; import { ConfigChatSetup } from "@/components/config-chat/config-chat-setup"; import { useConfigChat } from "@/components/config-chat/use-config-chat"; -import type { QuickChatSession } from "@/lib/state/slices/ui/types"; +import type { QuickChatSession, QuickTerminalTab } from "@/lib/state/slices/ui/types"; import { isQuickChatSetupSessionId } from "@/lib/state/slices/ui/quick-chat-session"; -import { useTranslation } from "react-i18next"; import type { TFunction } from "i18next"; +const QuickTerminalTabView = dynamic( + () => import("./quick-terminal-tab-view").then((module) => module.QuickTerminalTabView), + { ssr: false }, +); + type QuickChatModalProps = { workspaceId: string; }; @@ -31,24 +39,34 @@ function quickChatTabName(t: TFunction, session: QuickChatSession, index: number function QuickChatTabs({ sessions, + terminalTabs, + activeKind, activeSessionId, + activeTerminalTabId, onTabChange, onTabClose, onNewChat, + onNewTerminal, + onTerminalClose, + onTerminalActivate, onRename, onCloseModal, }: { sessions: QuickChatSession[]; - activeSessionId: string; + terminalTabs: QuickTerminalTab[]; + activeKind: "conversation" | "terminal"; + activeSessionId: string | null; + activeTerminalTabId: string | null; onTabChange: (sessionId: string) => void; onTabClose: (sessionId: string) => void; onNewChat: () => void; + onNewTerminal: () => void; + onTerminalClose: (tabId: string) => void; + onTerminalActivate: (tabId: string) => void; onRename: (sessionId: string, name: string) => void; onCloseModal: () => void; }) { const { t } = useTranslation(); - if (sessions.length === 0) return null; - return (
@@ -58,7 +76,7 @@ function QuickChatTabs({ onTabChange(s.sessionId)} @@ -67,15 +85,17 @@ function QuickChatTabs({ /> ); })} - + {terminalTabs.map((tab) => ( + onTerminalActivate(tab.tabId)} + onClose={() => onTerminalClose(tab.tabId)} + /> + ))} +
{/* Touch devices have no Escape key or visible overlay to dismiss the full-screen dialog, so give them an explicit close control. */} @@ -84,7 +104,7 @@ function QuickChatTabs({ variant="ghost" className="h-11 w-11 shrink-0 cursor-pointer p-0 sm:hidden" onClick={onCloseModal} - aria-label={t("chat:closeQuickChat")} + aria-label={t("sidebar:quickChatClose")} data-testid="quick-chat-close" > @@ -93,6 +113,97 @@ function QuickChatTabs({ ); } +type QuickChatContentProps = { + workspaceId: string; + configChat: ReturnType; + quickChat: ReturnType; + setQuickChatInitialPrompt: (sessionId: string, prompt?: string) => void; +}; + +function QuickChatContent({ + workspaceId, + configChat, + quickChat, + setQuickChatInitialPrompt, +}: QuickChatContentProps) { + const canCreateConfigurationChat = !quickChat.sessions.some( + (session) => session.kind === "config", + ); + const setupKind = + quickChat.activeSession && isQuickChatSetupSessionId(quickChat.activeSession.sessionId) + ? quickChat.activeSession.kind + : null; + + return ( + <> + quickChat.handleOpenChange(false)} + /> + {quickChat.activeKind === "terminal" && quickChat.activeTerminalTab && ( + + quickChat.handleTerminalStateChange(quickChat.activeTerminalTab!.tabId, state) + } + onDescriptorReady={(descriptor) => + quickChat.handleTerminalDescriptorReady(quickChat.activeTerminalTab!.tabId, descriptor) + } + /> + )} + {quickChat.activeKind === "conversation" && + quickChat.activeSessionId && + quickChat.activeSession && + !quickChat.activeSessionNeedsAgent && ( + + setQuickChatInitialPrompt(quickChat.activeSessionId!, undefined) + } + /> + )} + {quickChat.activeKind === "conversation" && + quickChat.activeSessionNeedsAgent && + setupKind === "chat" && ( + quickChat.handleOpenChange(false)} + onKindChange={quickChat.handleSetupKindChange} + /> + )} + {quickChat.activeKind === "conversation" && + quickChat.activeSessionNeedsAgent && + setupKind === "config" && ( + configChat.startSession(profileId, prompt)} + onCancel={() => quickChat.handleOpenChange(false)} + onKindChange={quickChat.handleSetupKindChange} + /> + )} + + ); +} + function QuickChatResizeHandle({ edge, onMouseDown, @@ -126,35 +237,14 @@ function QuickChatResizeHandle({ export const QuickChatModal = memo(function QuickChatModal({ workspaceId }: QuickChatModalProps) { const { t } = useTranslation(); const configChat = useConfigChat(workspaceId); - const { - isOpen, - sessions, - activeSessionId, - activeSession, - sessionToClose, - setupKey, - activeSessionNeedsAgent, - pendingAgentId, - setActiveQuickChatSession, - setSessionToClose, - handleOpenChange, - handleNewChat, - handleSetupKindChange, - handleSelectAgent, - handleCloseTab, - handleConfirmClose, - handleRename, - } = useQuickChatModal(workspaceId, configChat.reset); + const quickChat = useQuickChatModal(workspaceId, configChat.reset); const setQuickChatInitialPrompt = useAppStore((state) => state.setQuickChatInitialPrompt); const { width, leftResizeHandleProps, rightResizeHandleProps } = useQuickChatWidth(); - const canCreateConfigurationChat = !sessions.some((session) => session.kind === "config"); - const setupKind = - activeSession && isQuickChatSetupSessionId(activeSession.sessionId) ? activeSession.kind : null; return ( <> - + {t("common:commandQuickChat")} - handleOpenChange(false)} + - {activeSessionId && activeSession && !activeSessionNeedsAgent && ( - setQuickChatInitialPrompt(activeSessionId, undefined)} - /> - )} - {activeSessionNeedsAgent && setupKind === "chat" && ( - handleOpenChange(false)} - onKindChange={handleSetupKindChange} - /> - )} - {activeSessionNeedsAgent && setupKind === "config" && ( - configChat.startSession(profileId, prompt)} - onCancel={() => handleOpenChange(false)} - onKindChange={handleSetupKindChange} - /> - )} !open && setSessionToClose(null)} - onConfirm={handleConfirmClose} + sessionToDelete={quickChat.sessionToClose} + onOpenChange={(open) => !open && quickChat.setSessionToClose(null)} + onConfirm={quickChat.handleConfirmClose} /> ); diff --git a/apps/web/components/quick-chat/quick-chat-provider-focus.test.tsx b/apps/web/components/quick-chat/quick-chat-provider-focus.test.tsx new file mode 100644 index 0000000000..b7be33758d --- /dev/null +++ b/apps/web/components/quick-chat/quick-chat-provider-focus.test.tsx @@ -0,0 +1,55 @@ +import { cleanup, render } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +const providerState = vi.hoisted(() => ({ + quickChat: { + isOpen: true, + sessions: [{ sessionId: "chat-1", workspaceId: "ws-1" }], + terminalTabs: [], + activeKind: "conversation" as const, + activeSessionId: "chat-1", + activeTerminalTabId: null, + }, + workspaces: { activeId: "ws-1" }, +})); + +vi.mock("@/components/state-provider", () => ({ + useAppStore: (selector: (state: typeof providerState) => unknown) => selector(providerState), +})); +vi.mock("@/hooks/domains/settings/use-settings-data", () => ({ useSettingsData: vi.fn() })); +vi.mock("@/hooks/use-quick-chat-resync", () => ({ useQuickChatResync: vi.fn() })); +vi.mock("./quick-chat-modal", () => ({ QuickChatModal: () => null })); + +import { captureQuickChatLauncherFocus } from "./quick-chat-focus"; +import { QuickChatProvider } from "./quick-chat-provider"; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +describe("QuickChatProvider focus contract", () => { + it("restores focus to the launcher after the shared surface closes", () => { + vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { + callback(0); + return 0; + }); + const { rerender } = render( + + + , + ); + const launcher = document.querySelector("button") as HTMLButtonElement; + launcher.focus(); + captureQuickChatLauncherFocus(); + + providerState.quickChat.isOpen = false; + rerender( + + + , + ); + + expect(document.activeElement).toBe(launcher); + }); +}); diff --git a/apps/web/components/quick-chat/quick-chat-provider.test.ts b/apps/web/components/quick-chat/quick-chat-provider.test.ts index 12f383a91f..07b366f876 100644 --- a/apps/web/components/quick-chat/quick-chat-provider.test.ts +++ b/apps/web/components/quick-chat/quick-chat-provider.test.ts @@ -5,17 +5,62 @@ const sessions = [ { sessionId: "session-a", workspaceId: "ws-a" }, { sessionId: "session-b", workspaceId: "ws-b" }, ]; +const terminalTabs = [{ tabId: "terminal-a", workspaceId: "ws-a" }]; describe("getWorkspaceId", () => { it("uses the active tab workspace instead of the first persisted tab", () => { - expect(getWorkspaceId(sessions, true, "session-b", "ws-a")).toBe("ws-b"); + expect( + getWorkspaceId({ + sessions, + terminalTabs, + isOpen: true, + activeKind: "conversation", + activeSessionId: "session-b", + activeTerminalTabId: null, + activeWorkspace: "ws-a", + }), + ).toBe("ws-b"); }); it("uses the active workspace for a new-chat placeholder", () => { - expect(getWorkspaceId(sessions, true, "", "ws-b")).toBe("ws-b"); + expect( + getWorkspaceId({ + sessions, + terminalTabs, + isOpen: true, + activeKind: "conversation", + activeSessionId: "", + activeTerminalTabId: null, + activeWorkspace: "ws-b", + }), + ).toBe("ws-b"); + }); + + it("uses the active terminal workspace when a terminal is selected", () => { + expect( + getWorkspaceId({ + sessions, + terminalTabs, + isOpen: true, + activeKind: "terminal", + activeSessionId: "session-b", + activeTerminalTabId: "terminal-a", + activeWorkspace: "ws-b", + }), + ).toBe("ws-a"); }); it("does not mount a closed dialog from stale sessions", () => { - expect(getWorkspaceId(sessions, false, "session-a", "ws-a")).toBeNull(); + expect( + getWorkspaceId({ + sessions, + terminalTabs, + isOpen: false, + activeKind: "conversation", + activeSessionId: "session-a", + activeTerminalTabId: null, + activeWorkspace: "ws-a", + }), + ).toBeNull(); }); }); diff --git a/apps/web/components/quick-chat/quick-chat-provider.tsx b/apps/web/components/quick-chat/quick-chat-provider.tsx index 59cb2f6c9d..8ebde73559 100644 --- a/apps/web/components/quick-chat/quick-chat-provider.tsx +++ b/apps/web/components/quick-chat/quick-chat-provider.tsx @@ -1,9 +1,10 @@ "use client"; -import { useSyncExternalStore } from "react"; +import { useEffect, useRef, useSyncExternalStore } from "react"; import { useAppStore } from "@/components/state-provider"; import { useSettingsData } from "@/hooks/domains/settings/use-settings-data"; import { useQuickChatResync } from "@/hooks/use-quick-chat-resync"; +import { restoreQuickChatLauncherFocus } from "./quick-chat-focus"; import { QuickChatModal } from "./quick-chat-modal"; // SSR-safe client mount detection without useEffect setState @@ -15,15 +16,33 @@ function useIsMounted() { return useSyncExternalStore(emptySubscribe, getClientSnapshot, getServerSnapshot); } -export function getWorkspaceId( - sessions: { sessionId: string; workspaceId: string }[], - isOpen: boolean, - activeSessionId: string | null, - activeWorkspace: string | null, -): string | null { +type WorkspaceSelection = { + sessions: { sessionId: string; workspaceId: string }[]; + terminalTabs: { tabId: string; workspaceId: string }[]; + isOpen: boolean; + activeKind: "conversation" | "terminal"; + activeSessionId: string | null; + activeTerminalTabId: string | null; + activeWorkspace: string | null; +}; + +export function getWorkspaceId({ + sessions, + terminalTabs, + isOpen, + activeKind, + activeSessionId, + activeTerminalTabId, + activeWorkspace, +}: WorkspaceSelection): string | null { if (!isOpen) return null; + if (activeKind === "terminal") { + const activeTerminal = terminalTabs.find((tab) => tab.tabId === activeTerminalTabId); + if (activeTerminal) return activeTerminal.workspaceId; + } return ( sessions.find((session) => session.sessionId === activeSessionId)?.workspaceId ?? + terminalTabs.find((tab) => tab.tabId === activeTerminalTabId)?.workspaceId ?? activeWorkspace ); } @@ -36,9 +55,13 @@ export function getWorkspaceId( export function QuickChatProvider({ children }: { children: React.ReactNode }) { const quickChatSessions = useAppStore((s) => s.quickChat.sessions); const isOpen = useAppStore((s) => s.quickChat.isOpen); + const quickTerminalTabs = useAppStore((s) => s.quickChat.terminalTabs); + const activeKind = useAppStore((s) => s.quickChat.activeKind); const activeSessionId = useAppStore((s) => s.quickChat.activeSessionId); + const activeTerminalTabId = useAppStore((s) => s.quickChat.activeTerminalTabId); const activeWorkspace = useAppStore((s) => s.workspaces.activeId); const mounted = useIsMounted(); + const wasOpen = useRef(false); // Preload agent profiles so they're available when quick chat is opened useSettingsData(true); @@ -46,7 +69,20 @@ export function QuickChatProvider({ children }: { children: React.ReactNode }) { // the socket connects so tabs opened or closed elsewhere show up here too. useQuickChatResync(activeWorkspace); - const workspaceId = getWorkspaceId(quickChatSessions, isOpen, activeSessionId, activeWorkspace); + const workspaceId = getWorkspaceId({ + sessions: quickChatSessions, + terminalTabs: quickTerminalTabs, + isOpen, + activeKind, + activeSessionId, + activeTerminalTabId, + activeWorkspace, + }); + + useEffect(() => { + if (wasOpen.current && !isOpen) restoreQuickChatLauncherFocus(); + wasOpen.current = isOpen; + }, [isOpen]); return ( <> diff --git a/apps/web/components/quick-chat/quick-chat-tab-item.test.tsx b/apps/web/components/quick-chat/quick-chat-tab-item.test.tsx index 664a693ed1..12c7958a95 100644 --- a/apps/web/components/quick-chat/quick-chat-tab-item.test.tsx +++ b/apps/web/components/quick-chat/quick-chat-tab-item.test.tsx @@ -2,6 +2,34 @@ import { afterEach, describe, it, expect, vi } from "vitest"; import { cleanup, render, fireEvent } from "@testing-library/react"; import { QuickChatTabItem } from "./quick-chat-tab-item"; +vi.mock("@kandev/ui/context-menu", () => ({ + ContextMenu: ({ children }: { children: React.ReactNode }) => <>{children}, + ContextMenuTrigger: ({ children }: { children: React.ReactNode }) => <>{children}, + ContextMenuContent: ({ children }: { children: React.ReactNode }) => <>{children}, + ContextMenuItem: ({ + children, + onSelect, + }: { + children: React.ReactNode; + onSelect?: () => void; + }) => ( + + ), +})); + +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ + t: (key: string) => + ({ + "common:rename": "Rename", + "chat:renameChat": "Rename chat", + "chat:configurationChat": "Configuration chat", + })[key] ?? key, + }), +})); + afterEach(cleanup); function makeProps(overrides: Partial[0]> = {}) { @@ -23,6 +51,15 @@ function startEditing(label: HTMLElement) { } describe("QuickChatTabItem rename", () => { + it("starts renaming from the tab context menu", () => { + const { getByRole, getByLabelText } = render(); + + fireEvent.contextMenu(getByRole("button", { name: "Original" })); + fireEvent.click(getByRole("button", { name: "Rename" })); + + expect(getByLabelText(RENAME_LABEL)).toBeTruthy(); + }); + it("renders an accessible configuration indicator", () => { const { getByLabelText } = render( void; }; -/** Tab in the quick-chat modal. Double-click the label to rename (local-only). */ +function RenameContextMenu({ children, onRename }: { children: ReactNode; onRename: () => void }) { + const { t } = useTranslation(); + + return ( + + {children} + + + {t("common:rename")} + + + + ); +} + +/** Tab in the quick-chat modal. Renameable tabs support double-click and context-menu editing. */ export const QuickChatTabItem = memo(function QuickChatTabItem({ name, isActive, @@ -65,7 +87,7 @@ export const QuickChatTabItem = memo(function QuickChatTabItem({ setIsEditing(true); }, [isRenameable, name]); - return ( + const tabContent = (
); + + if (!isRenameable) return tabContent; + + return {tabContent}; }); diff --git a/apps/web/components/quick-chat/quick-tab-add-menu.test.tsx b/apps/web/components/quick-chat/quick-tab-add-menu.test.tsx new file mode 100644 index 0000000000..8ff4752f04 --- /dev/null +++ b/apps/web/components/quick-chat/quick-tab-add-menu.test.tsx @@ -0,0 +1,59 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { QuickTabAddMenu } from "./quick-tab-add-menu"; + +vi.mock("@kandev/ui/dropdown-menu", () => ({ + DropdownMenu: ({ children }: { children: React.ReactNode }) =>
{children}
, + DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) =>
{children}
, + DropdownMenuContent: ({ children }: { children: React.ReactNode }) =>
{children}
, + DropdownMenuLabel: ({ children }: { children: React.ReactNode }) =>
{children}
, + DropdownMenuSeparator: () =>
, + DropdownMenuItem: ({ + children, + onSelect, + ...props + }: { + children: React.ReactNode; + onSelect?: () => void; + [key: string]: unknown; + }) => ( + + ), +})); + +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ + t: (key: string, values?: { count?: number; error?: string }) => { + const messages: Record = { + "sidebar:quickChatAdd": "Add or switch tab", + "common:agents": "Agents", + "sidebar:quickChatNewAgent": "New Agent", + "sidebar:quickChatTerminals": "Terminals", + "sidebar:quickChatNewTerminal": "New Terminal", + "sidebar:quickChatTerminalTab": `Terminal ${values?.count ?? ""}`, + "sidebar:quickChatTerminalError": `Terminal error: ${values?.error ?? ""}`, + }; + return messages[key] ?? key; + }, + }), +})); + +afterEach(() => cleanup()); + +describe("QuickTabAddMenu", () => { + it("offers creation actions without duplicating the tab strip", async () => { + const onNewTerminal = vi.fn(); + render(); + + fireEvent.click(screen.getByTestId("quick-chat-add-menu-trigger")); + + expect(await screen.findByText("Agents")).toBeTruthy(); + expect(screen.getByText("New Agent")).toBeTruthy(); + expect(screen.getByText("Terminals")).toBeTruthy(); + expect(screen.getByText("New Terminal")).toBeTruthy(); + fireEvent.click(screen.getByTestId("quick-chat-new-terminal")); + expect(onNewTerminal).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/web/components/quick-chat/quick-tab-add-menu.tsx b/apps/web/components/quick-chat/quick-tab-add-menu.tsx new file mode 100644 index 0000000000..5a26d73d1f --- /dev/null +++ b/apps/web/components/quick-chat/quick-tab-add-menu.tsx @@ -0,0 +1,65 @@ +"use client"; + +import { IconMessagePlus, IconPlus, IconTerminal2 } from "@tabler/icons-react"; +import { useTranslation } from "react-i18next"; +import { Button } from "@kandev/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@kandev/ui/dropdown-menu"; + +type QuickTabAddMenuProps = { + onNewAgent: () => void; + onNewTerminal: () => void; +}; + +/** Grouped creation menu for the shared Quick Chat surface. */ +export function QuickTabAddMenu({ onNewAgent, onNewTerminal }: QuickTabAddMenuProps) { + const { t } = useTranslation(); + + return ( + + + + + + + {t("common:agents")} + + + + {t("sidebar:quickChatNewAgent")} + + + + {t("sidebar:quickChatTerminals")} + + + + {t("sidebar:quickChatNewTerminal")} + + + + ); +} diff --git a/apps/web/components/quick-chat/quick-terminal-tab-item.tsx b/apps/web/components/quick-chat/quick-terminal-tab-item.tsx new file mode 100644 index 0000000000..39da927d0e --- /dev/null +++ b/apps/web/components/quick-chat/quick-terminal-tab-item.tsx @@ -0,0 +1,59 @@ +"use client"; + +import { memo } from "react"; +import { IconAlertCircle, IconTerminal2, IconX } from "@tabler/icons-react"; +import { useTranslation } from "react-i18next"; + +type QuickTerminalTabItemProps = { + sequence: number; + isActive: boolean; + error?: string; + onActivate: () => void; + onClose: () => void; +}; + +/** Fixed-label tab for a browser-local quick terminal. */ +export const QuickTerminalTabItem = memo(function QuickTerminalTabItem({ + sequence, + isActive, + error, + onActivate, + onClose, +}: QuickTerminalTabItemProps) { + const { t } = useTranslation(); + const label = t("sidebar:quickChatTerminalTab", { count: sequence }); + const closeLabel = t("sidebar:quickChatCloseTerminal", { count: sequence }); + + return ( +
+ + +
+ ); +}); diff --git a/apps/web/components/quick-chat/quick-terminal-tab-view.test.tsx b/apps/web/components/quick-chat/quick-terminal-tab-view.test.tsx new file mode 100644 index 0000000000..812f1b3cc0 --- /dev/null +++ b/apps/web/components/quick-chat/quick-terminal-tab-view.test.tsx @@ -0,0 +1,112 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +const startHostShell = vi.hoisted(() => + vi.fn().mockResolvedValue({ + session_id: "session-1", + agent_id: "_host_shell", + cmd: ["/bin/bash"], + running: true, + started_at: "2026-08-04T00:00:00Z", + }), +); +const createQuickTerminalTab = vi.hoisted(() => + vi.fn().mockResolvedValue({ + tabId: "6f2d7f2d-0d0c-4c9b-8b73-1c53a5ed5b6b", + workspaceId: "workspace-1", + sessionId: null, + sequence: 1, + status: "connecting", + }), +); +const deleteQuickTerminalTab = vi.hoisted(() => vi.fn().mockResolvedValue(undefined)); + +vi.mock("@/lib/api", () => ({ + startHostShell, + createQuickTerminalTab, + deleteQuickTerminalTab, + toQuickTerminalTab: (tab: unknown) => tab, +})); +vi.mock("@/components/settings/pty-terminal-view", () => ({ + PtyTerminalView: (props: { + startSession: ( + size: { cols: number; rows: number }, + options?: { clientId?: string }, + ) => Promise; + clientId?: string; + lifecycle: string; + }) => ( + + ), +})); +vi.mock("react-i18next", () => ({ + useTranslation: () => ({ + t: (key: string, values?: { code?: number; error?: string }) => { + if (key === "sidebar:quickChatTerminalConnecting") return "Connecting to terminal…"; + if (key === "sidebar:quickChatTerminalExited") return "Terminal exited."; + if (key === "sidebar:quickChatTerminalExitedWithCode") { + return `Terminal exited with code ${values?.code}.`; + } + if (key === "sidebar:quickChatTerminalError") { + return `Terminal error: ${values?.error ?? "The terminal could not be started."}`; + } + return key; + }, + }), +})); + +import { QuickTerminalTabView } from "./quick-terminal-tab-view"; + +const tab = { + tabId: "6f2d7f2d-0d0c-4c9b-8b73-1c53a5ed5b6b", + workspaceId: "workspace-1", + sessionId: null, + sequence: 1, + status: "connecting" as const, +}; + +describe("QuickTerminalTabView", () => { + it("starts a host shell with the terminal tab's stable client id and detaches on unmount", () => { + const onStateChange = vi.fn(); + const view = render(); + + return waitFor(() => + expect(screen.getByTestId("pty-view-probe").getAttribute("data-lifecycle")).toBe( + "detach-on-unmount", + ), + ).then(() => { + fireEvent.click(screen.getByTestId("pty-view-probe")); + expect(startHostShell).toHaveBeenCalledWith({ cols: 80, rows: 24 }, { clientId: tab.tabId }); + view.unmount(); + }); + }); + + it("renders accessible lifecycle status for the selected terminal", () => { + const { rerender } = render(); + + expect(screen.getByRole("status").textContent).toContain("Connecting to terminal…"); + + rerender( + , + ); + expect(screen.getByRole("alert").textContent).toContain("Terminal error: Unable to reattach."); + + rerender( + , + ); + expect(screen.getByRole("status").textContent).toContain("Terminal exited with code 7."); + }); +}); diff --git a/apps/web/components/quick-chat/quick-terminal-tab-view.tsx b/apps/web/components/quick-chat/quick-terminal-tab-view.tsx new file mode 100644 index 0000000000..5564a06840 --- /dev/null +++ b/apps/web/components/quick-chat/quick-terminal-tab-view.tsx @@ -0,0 +1,141 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { + createQuickTerminalTab, + deleteQuickTerminalTab, + startHostShell, + toQuickTerminalTab, +} from "@/lib/api"; +import { + PtyTerminalView, + type PtyTerminalState, + type StartPtySession, +} from "@/components/settings/pty-terminal-view"; +import type { QuickTerminalTab } from "@/lib/state/slices/ui/types"; + +export type QuickTerminalTabDescriptor = QuickTerminalTab; + +type Props = { + tab: QuickTerminalTab; + onStateChange: (state: PtyTerminalState) => void; + onDescriptorReady?: (tab: QuickTerminalTab) => void; +}; + +function QuickTerminalLifecycleStatus({ tab }: { tab: QuickTerminalTab }) { + const { t } = useTranslation(); + if (tab.status === "connecting") { + return ( +

+ {t("sidebar:quickChatTerminalConnecting")} +

+ ); + } + + if (tab.status === "error" || tab.error) { + return ( +

+ {t("sidebar:quickChatTerminalError", { + error: tab.error || t("sidebar:quickChatTerminalUnknownError"), + })} +

+ ); + } + + if (tab.status === "exited") { + return ( +

+ {tab.exitCode == null + ? t("sidebar:quickChatTerminalExited") + : t("sidebar:quickChatTerminalExitedWithCode", { code: tab.exitCode })} +

+ ); + } + + return null; +} + +/** Selected terminal content for the shared Quick Chat surface. */ +export function QuickTerminalTabView({ tab, onStateChange, onDescriptorReady }: Props) { + const needsDescriptor = !tab.sessionId && tab.status === "connecting"; + const [descriptorReady, setDescriptorReady] = useState(!needsDescriptor); + const onStateChangeRef = useRef(onStateChange); + const onDescriptorReadyRef = useRef(onDescriptorReady); + onStateChangeRef.current = onStateChange; + onDescriptorReadyRef.current = onDescriptorReady; + + useEffect(() => { + if (!needsDescriptor) { + setDescriptorReady(true); + return undefined; + } + + let cancelled = false; + setDescriptorReady(false); + createQuickTerminalTab(tab.tabId, tab.workspaceId) + .then((descriptor) => { + if (cancelled) { + return deleteQuickTerminalTab(tab.tabId).catch(() => undefined); + } + const nextTab = toQuickTerminalTab(descriptor); + onDescriptorReadyRef.current?.(nextTab); + setDescriptorReady(true); + }) + .catch((error: unknown) => { + if (cancelled) return; + onStateChangeRef.current({ + status: "error", + sessionId: null, + exitCode: null, + error: error instanceof Error ? error.message : String(error), + }); + }); + + return () => { + cancelled = true; + }; + }, [needsDescriptor, tab.tabId, tab.workspaceId]); + + const shouldRenderTerminal = Boolean(tab.sessionId) || (needsDescriptor && descriptorReady); + const startSession = useCallback( + (size, options) => startHostShell(size, options), + [], + ); + + return ( +
+ {shouldRenderTerminal && ( + + )} + +
+ ); +} diff --git a/apps/web/components/quick-chat/use-quick-chat-modal.test.ts b/apps/web/components/quick-chat/use-quick-chat-modal.test.ts index 9ee1a9c9a9..fc0fa52a6a 100644 --- a/apps/web/components/quick-chat/use-quick-chat-modal.test.ts +++ b/apps/web/components/quick-chat/use-quick-chat-modal.test.ts @@ -1,11 +1,14 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { renderHook, act } from "@testing-library/react"; +import type { QuickTerminalTab } from "@/lib/state/slices/ui/types"; // Mocks must be declared before importing the hook so vi.mock hoists correctly. const mockToast = vi.fn(); const mockStartQuickChat = vi.fn(); const mockDeleteTask = vi.fn(); const mockUpdateTask = vi.fn(); +const mockDeleteQuickTerminalTab = vi.fn(); +const mockUpdateQuickTerminalTab = vi.fn(); let mockAppState: ReturnType; vi.mock("@/components/state-provider", () => ({ @@ -26,11 +29,20 @@ vi.mock("@/lib/api/domains/kanban-api", () => ({ updateTask: (...args: unknown[]) => mockUpdateTask(...args), })); +vi.mock("@/lib/api/domains/quick-terminal-api", () => ({ + deleteQuickTerminalTab: (...args: unknown[]) => mockDeleteQuickTerminalTab(...args), + updateQuickTerminalTab: (...args: unknown[]) => mockUpdateQuickTerminalTab(...args), +})); + import { useAgentSelection, useQuickChatModal } from "./use-quick-chat-modal"; import { getQuickChatSetupSessionId } from "@/lib/state/slices/ui/quick-chat-session"; const WORKSPACE_ID = "ws-1"; +const TERMINAL_ONE_ID = "terminal-1"; +const SESSION_ONE_ID = "session-1"; const CHAT_SETUP_ID = getQuickChatSetupSessionId(WORKSPACE_ID, "chat"); +const LATE_TERMINAL_ID = "terminal-late"; +const LATE_SESSION_ID = "late-session"; type MockStore = Parameters[1]; @@ -45,10 +57,17 @@ function makeAppState() { taskId?: string; }>, activeSessionId: "", + activeKind: "conversation" as const, + activeTerminalTabId: null, + terminalTabs: [] as QuickTerminalTab[], }, closeQuickChat: vi.fn(), closeQuickChatSession: vi.fn(), setActiveQuickChatSession: vi.fn(), + createQuickTerminal: vi.fn(), + updateQuickTerminal: vi.fn(), + activateQuickTerminal: vi.fn(), + removeQuickTerminal: vi.fn(), renameQuickChatSession: vi.fn(), openQuickChat: vi.fn(), agentProfiles: { items: [] }, @@ -60,10 +79,17 @@ function makeStore(overrides: Partial = {}): MockStore { return { isOpen: true, sessions: [], + terminalTabs: [], activeSessionId: "", + activeKind: "conversation", + activeTerminalTabId: null, closeQuickChat: vi.fn(), closeQuickChatSession: vi.fn(), setActiveQuickChatSession: vi.fn(), + createQuickTerminal: vi.fn(), + updateQuickTerminal: vi.fn(), + activateQuickTerminal: vi.fn(), + removeQuickTerminal: vi.fn(), renameQuickChatSession: vi.fn(), openQuickChat: vi.fn(), agentProfiles: [ @@ -81,16 +107,108 @@ function flushPromises() { beforeEach(() => { vi.clearAllMocks(); + mockDeleteQuickTerminalTab.mockReset(); + mockDeleteQuickTerminalTab.mockResolvedValue(undefined); + mockUpdateQuickTerminalTab.mockReset(); + mockUpdateQuickTerminalTab.mockResolvedValue({ + sequence: 1, + sessionId: null, + status: "running", + }); mockAppState = makeAppState(); }); +describe("useQuickChatModal — terminal close lifecycle", () => { + const terminal = (tabId: string, sessionId: string): QuickTerminalTab => ({ + tabId, + workspaceId: WORKSPACE_ID, + sessionId, + sequence: Number(tabId.slice(-1)), + status: "running", + }); + + it("removes a terminal when the stop endpoint says it is already gone", async () => { + mockAppState.quickChat.terminalTabs = [terminal(TERMINAL_ONE_ID, SESSION_ONE_ID)]; + mockDeleteQuickTerminalTab.mockRejectedValue( + new (await import("@/lib/api/client")).ApiError("gone", 404, null), + ); + + const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); + + await act(async () => result.current.handleCloseTerminal(TERMINAL_ONE_ID)); + + expect(mockDeleteQuickTerminalTab).toHaveBeenCalledWith(TERMINAL_ONE_ID); + expect(mockAppState.removeQuickTerminal).toHaveBeenCalledWith(TERMINAL_ONE_ID); + }); + + it("keeps a terminal and records an error when stopping fails", async () => { + mockAppState.quickChat.terminalTabs = [terminal(TERMINAL_ONE_ID, SESSION_ONE_ID)]; + mockDeleteQuickTerminalTab.mockRejectedValue(new Error("stop failed")); + + const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); + + await act(async () => result.current.handleCloseTerminal(TERMINAL_ONE_ID)); + + expect(mockAppState.removeQuickTerminal).not.toHaveBeenCalled(); + expect(mockAppState.updateQuickTerminal).toHaveBeenCalledWith(TERMINAL_ONE_ID, { + status: "error", + error: "stop failed", + }); + expect(mockToast).toHaveBeenCalled(); + }); + + it("stops only the explicitly closed sibling terminal", async () => { + mockAppState.quickChat.terminalTabs = [ + terminal(TERMINAL_ONE_ID, SESSION_ONE_ID), + terminal("terminal-2", "session-2"), + ]; + + const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); + + await act(async () => result.current.handleCloseTerminal(TERMINAL_ONE_ID)); + + expect(mockDeleteQuickTerminalTab).toHaveBeenCalledTimes(1); + expect(mockDeleteQuickTerminalTab).toHaveBeenCalledWith(TERMINAL_ONE_ID); + expect(mockAppState.removeQuickTerminal).toHaveBeenCalledWith(TERMINAL_ONE_ID); + expect(mockAppState.removeQuickTerminal).not.toHaveBeenCalledWith("terminal-2"); + }); + + it("stops a detached terminal after its late start reports the session", async () => { + const tab: QuickTerminalTab = { + tabId: LATE_TERMINAL_ID, + workspaceId: WORKSPACE_ID, + sessionId: null, + sequence: 1, + status: "connecting", + }; + mockAppState.quickChat.terminalTabs = [tab]; + mockAppState.updateQuickTerminal = vi.fn((_tabId, update) => { + Object.assign(tab, update); + }); + const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); + + act(() => + result.current.handleTerminalStateChange(LATE_TERMINAL_ID, { + status: "running", + sessionId: LATE_SESSION_ID, + exitCode: null, + error: null, + }), + ); + await act(async () => result.current.handleCloseTerminal(LATE_TERMINAL_ID)); + + expect(mockDeleteQuickTerminalTab).toHaveBeenCalledWith(LATE_TERMINAL_ID); + expect(mockAppState.removeQuickTerminal).toHaveBeenCalledWith(LATE_TERMINAL_ID); + }); +}); + describe("useQuickChatModal — setup lifecycle", () => { it("removes a blank placeholder when dismissed from an active session", () => { mockAppState.quickChat.sessions = [ { sessionId: CHAT_SETUP_ID, workspaceId: WORKSPACE_ID, kind: "chat" }, - { sessionId: "session-1", workspaceId: WORKSPACE_ID, kind: "chat" }, + { sessionId: SESSION_ONE_ID, workspaceId: WORKSPACE_ID, kind: "chat" }, ]; - mockAppState.quickChat.activeSessionId = "session-1"; + mockAppState.quickChat.activeSessionId = SESSION_ONE_ID; const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); act(() => result.current.handleOpenChange(false)); @@ -125,15 +243,18 @@ describe("useQuickChatModal — setup lifecycle", () => { it("supersedes an in-flight config start when the user changes tabs", () => { const resetConfigStart = vi.fn(); mockAppState.quickChat.sessions = [ - { sessionId: "session-1", workspaceId: WORKSPACE_ID, kind: "chat" }, + { sessionId: SESSION_ONE_ID, workspaceId: WORKSPACE_ID, kind: "chat" }, ]; - mockAppState.quickChat.activeSessionId = "session-1"; + mockAppState.quickChat.activeSessionId = SESSION_ONE_ID; const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID, resetConfigStart)); - act(() => result.current.setActiveQuickChatSession("session-1")); + act(() => result.current.setActiveQuickChatSession(SESSION_ONE_ID)); expect(resetConfigStart).toHaveBeenCalledTimes(1); - expect(mockAppState.setActiveQuickChatSession).toHaveBeenCalledWith("session-1", WORKSPACE_ID); + expect(mockAppState.setActiveQuickChatSession).toHaveBeenCalledWith( + SESSION_ONE_ID, + WORKSPACE_ID, + ); }); }); @@ -385,16 +506,16 @@ describe("useQuickChatModal — renaming", () => { it("saves the new name to the backing task so other devices pick it up", async () => { mockUpdateTask.mockResolvedValue(undefined); mockAppState.quickChat.sessions = [ - { sessionId: "session-1", workspaceId: WORKSPACE_ID, kind: "chat", taskId: "task-1" }, + { sessionId: SESSION_ONE_ID, workspaceId: WORKSPACE_ID, kind: "chat", taskId: "task-1" }, ]; const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); await act(async () => { - result.current.handleRename("session-1", "Renamed"); + result.current.handleRename(SESSION_ONE_ID, "Renamed"); await flushPromises(); }); - expect(mockAppState.renameQuickChatSession).toHaveBeenCalledWith("session-1", "Renamed"); + expect(mockAppState.renameQuickChatSession).toHaveBeenCalledWith(SESSION_ONE_ID, "Renamed"); expect(mockUpdateTask).toHaveBeenCalledWith("task-1", { title: "Renamed" }); expect(mockToast).not.toHaveBeenCalled(); }); @@ -406,13 +527,13 @@ describe("useQuickChatModal — renaming", () => { it("falls back to taskSessions for a tab that carries no taskId", async () => { mockUpdateTask.mockResolvedValue(undefined); mockAppState.quickChat.sessions = [ - { sessionId: "session-1", workspaceId: WORKSPACE_ID, kind: "chat" }, + { sessionId: SESSION_ONE_ID, workspaceId: WORKSPACE_ID, kind: "chat" }, ]; - mockAppState.taskSessions.items = { "session-1": { task_id: "task-legacy" } }; + mockAppState.taskSessions.items = { [SESSION_ONE_ID]: { task_id: "task-legacy" } }; const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); await act(async () => { - result.current.handleRename("session-1", "Renamed"); + result.current.handleRename(SESSION_ONE_ID, "Renamed"); await flushPromises(); }); @@ -422,17 +543,17 @@ describe("useQuickChatModal — renaming", () => { it("warns that the rename did not sync when the request fails", async () => { mockUpdateTask.mockRejectedValue(new Error("offline")); mockAppState.quickChat.sessions = [ - { sessionId: "session-1", workspaceId: WORKSPACE_ID, kind: "chat", taskId: "task-1" }, + { sessionId: SESSION_ONE_ID, workspaceId: WORKSPACE_ID, kind: "chat", taskId: "task-1" }, ]; const { result } = renderHook(() => useQuickChatModal(WORKSPACE_ID)); await act(async () => { - result.current.handleRename("session-1", "Renamed"); + result.current.handleRename(SESSION_ONE_ID, "Renamed"); await flushPromises(); }); // The label still changed locally — only the sync failed. - expect(mockAppState.renameQuickChatSession).toHaveBeenCalledWith("session-1", "Renamed"); + expect(mockAppState.renameQuickChatSession).toHaveBeenCalledWith(SESSION_ONE_ID, "Renamed"); expect(mockToast).toHaveBeenCalledWith(expect.objectContaining({ variant: "error" })); }); }); diff --git a/apps/web/components/quick-chat/use-quick-chat-modal.ts b/apps/web/components/quick-chat/use-quick-chat-modal.ts index aa170950a6..39d98c352f 100644 --- a/apps/web/components/quick-chat/use-quick-chat-modal.ts +++ b/apps/web/components/quick-chat/use-quick-chat-modal.ts @@ -2,13 +2,20 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useShallow } from "zustand/react/shallow"; +import { useTranslation } from "react-i18next"; import { useAppStore } from "@/components/state-provider"; import { useToast } from "@/components/toast-provider"; import { startQuickChat, type QuickChatRepositoryInput } from "@/lib/api/domains/workspace-api"; +import { + deleteQuickTerminalTab, + updateQuickTerminalTab, +} from "@/lib/api/domains/quick-terminal-api"; +import { ApiError } from "@/lib/api/client"; +import { type PtyTerminalState } from "@/components/settings/pty-terminal-view"; +import { cancelPtyTerminalStart } from "@/components/settings/pty-terminal-lifecycle"; import { isQuickChatSetupSessionId } from "@/lib/state/slices/ui/quick-chat-session"; import { persistQuickChatRename } from "@/lib/quick-chat/rename"; -import type { QuickChatSessionKind } from "@/lib/state/slices/ui/types"; -import { useTranslation } from "react-i18next"; +import type { QuickChatSessionKind, QuickTerminalTab } from "@/lib/state/slices/ui/types"; const noop = () => {}; @@ -23,9 +30,16 @@ function useQuickChatStore(workspaceId: string) { isOpen: s.quickChat.isOpen, sessions: s.quickChat.sessions, activeSessionId: s.quickChat.activeSessionId, + activeKind: s.quickChat.activeKind, + activeTerminalTabId: s.quickChat.activeTerminalTabId, + terminalTabs: s.quickChat.terminalTabs, closeQuickChat: s.closeQuickChat, closeQuickChatSession: s.closeQuickChatSession, setActiveQuickChatSession: s.setActiveQuickChatSession, + createQuickTerminal: s.createQuickTerminal, + updateQuickTerminal: s.updateQuickTerminal, + activateQuickTerminal: s.activateQuickTerminal, + removeQuickTerminal: s.removeQuickTerminal, renameQuickChatSession: s.renameQuickChatSession, openQuickChat: s.openQuickChat, agentProfiles: s.agentProfiles.items ?? [], @@ -36,6 +50,7 @@ function useQuickChatStore(workspaceId: string) { () => ({ ...store, sessions: store.sessions.filter((session) => session.workspaceId === workspaceId), + terminalTabs: store.terminalTabs.filter((tab) => tab.workspaceId === workspaceId), }), [store, workspaceId], ); @@ -43,6 +58,55 @@ function useQuickChatStore(workspaceId: string) { type QuickChatStore = ReturnType; +function persistQuickTerminalState( + store: QuickChatStore, + tabId: string, + state: PtyTerminalState, +): void { + store.updateQuickTerminal(tabId, { + sessionId: state.sessionId, + status: state.status, + exitCode: state.exitCode, + error: state.error, + }); + void updateQuickTerminalTab(tabId, { + sessionId: state.status === "exited" ? null : state.sessionId, + status: state.status, + exitCode: state.exitCode, + error: state.error, + }) + .then((descriptor) => { + store.updateQuickTerminal(tabId, { + sequence: descriptor.sequence, + sessionId: descriptor.sessionId, + status: descriptor.status, + exitCode: descriptor.exitCode, + error: descriptor.error, + }); + }) + .catch((error: unknown) => { + if (error instanceof ApiError && error.status === 404) return; + store.updateQuickTerminal(tabId, { + status: "error", + error: error instanceof Error ? error.message : String(error), + }); + }); +} + +function applyQuickTerminalDescriptor( + store: QuickChatStore, + tabId: string, + descriptor: QuickTerminalTab, +): void { + store.updateQuickTerminal(tabId, { + sequence: descriptor.sequence, + sessionId: descriptor.sessionId, + status: descriptor.status, + exitCode: descriptor.exitCode, + error: descriptor.error, + }); +} + /** * Resolves a tab's backing task. The tab carries `taskId` on every path that * introduces it, but sessions restored by older clients only exist in @@ -59,13 +123,34 @@ function resolveTaskId(store: QuickChatStore, sessionId: string): string | undef function useWorkspaceQuickChat(store: QuickChatStore) { const sessions = store.sessions; - const activeSession = sessions.find((session) => session.sessionId === store.activeSessionId); + const terminalTabs = store.terminalTabs; + const activeSession = + store.activeKind === "conversation" + ? sessions.find((session) => session.sessionId === store.activeSessionId) + : undefined; + const activeTerminalTab = + store.activeKind === "terminal" + ? terminalTabs.find((tab) => tab.tabId === store.activeTerminalTabId) + : undefined; useEffect(() => { - if (store.isOpen && store.activeSessionId !== null && !activeSession) { + if ( + store.isOpen && + store.activeKind === "conversation" && + store.activeSessionId && + !activeSession + ) { store.closeQuickChat(); } - }, [activeSession, store.isOpen, store.activeSessionId, store.closeQuickChat]); - return { sessions, activeSession }; + if ( + store.isOpen && + store.activeKind === "terminal" && + store.activeTerminalTabId && + !activeTerminalTab + ) { + store.closeQuickChat(); + } + }, [activeSession, activeTerminalTab, store]); + return { sessions, terminalTabs, activeSession, activeTerminalTab }; } /** POSTs to start a quick-chat session and returns the response. */ @@ -193,23 +278,81 @@ function useQuickChatSessionClose(store: QuickChatStore, resetPendingStarts: () return { sessionToClose, setSessionToClose, handleCloseTab, handleConfirmClose }; } -export function useQuickChatModal(workspaceId: string, onSupersedeConfigStart = noop) { - const { t } = useTranslation(); +function useQuickTerminalClose(store: QuickChatStore, resetPendingStarts: () => void) { const { toast } = useToast(); - const store = useQuickChatStore(workspaceId); - const { sessions, activeSession } = useWorkspaceQuickChat(store); - const [setupKey, setSetupKey] = useState(0); - const { - pendingAgentId, - reset, - handleSelectAgent: doSelectAgent, - } = useAgentSelection(workspaceId, store); - const resetPendingStarts = useCallback(() => { - reset(); - onSupersedeConfigStart(); - }, [onSupersedeConfigStart, reset]); + const { t } = useTranslation(); + + const handleCloseTerminal = useCallback( + async (tabId: string) => { + resetPendingStarts(); + cancelPtyTerminalStart(tabId); + const tab = store.terminalTabs.find((item) => item.tabId === tabId); + if (!tab) return; + try { + await deleteQuickTerminalTab(tabId); + } catch (error) { + if (error instanceof ApiError && error.status === 404) { + store.removeQuickTerminal(tabId); + return; + } + const message = error instanceof Error ? error.message : String(error); + store.updateQuickTerminal(tabId, { status: "error", error: message }); + toast({ + title: t("sidebar:quickChatTerminals"), + description: t("sidebar:quickChatTerminalError", { error: message }), + variant: "error", + }); + return; + } + store.removeQuickTerminal(tabId); + }, + [resetPendingStarts, store, t, toast], + ); + + return handleCloseTerminal; +} + +type QuickChatTabActionsOptions = { + workspaceId: string; + sessions: QuickChatStore["sessions"]; + activeSession: QuickChatStore["sessions"][number] | undefined; + store: QuickChatStore; + resetPendingStarts: () => void; + setSetupKey: React.Dispatch>; +}; + +function useQuickChatRename(store: QuickChatStore) { + const { toast } = useToast(); + const { t } = useTranslation(); + + return useCallback( + (sessionId: string, name: string) => { + if (!sessionId) return; + store.renameQuickChatSession(sessionId, name); + persistQuickChatRename(sessionId, resolveTaskId(store, sessionId), name).catch(() => { + toast({ + title: t("chat:renameSavedOnThisDeviceOnly"), + description: t("chat:renameSyncFailedDescription"), + variant: "error", + }); + }); + }, + [store, t, toast], + ); +} + +function useQuickChatTabActions({ + workspaceId, + sessions, + activeSession, + store, + resetPendingStarts, + setSetupKey, +}: QuickChatTabActionsOptions) { const { sessionToClose, setSessionToClose, handleCloseTab, handleConfirmClose } = useQuickChatSessionClose(store, resetPendingStarts); + const handleCloseTerminal = useQuickTerminalClose(store, resetPendingStarts); + const handleRename = useQuickChatRename(store); const handleOpenChange = useCallback( (open: boolean) => { @@ -223,15 +366,39 @@ export function useQuickChatModal(workspaceId: string, onSupersedeConfigStart = [resetPendingStarts, sessions, store], ); - // Any picker-bypassing user action while a pick is pending should supersede - // the in-flight start, so the resolved request cleans up its orphan task - // instead of yanking the user back to that session. const handleNewChat = useCallback(() => { resetPendingStarts(); setSetupKey((key) => key + 1); store.openQuickChat("", workspaceId, undefined, "chat"); + }, [resetPendingStarts, setSetupKey, store, workspaceId]); + + const handleNewTerminal = useCallback(() => { + resetPendingStarts(); + store.createQuickTerminal(workspaceId); }, [resetPendingStarts, store, workspaceId]); + const handleActivateTerminal = useCallback( + (tabId: string) => { + resetPendingStarts(); + store.activateQuickTerminal(tabId, workspaceId); + }, + [resetPendingStarts, store, workspaceId], + ); + + const handleTerminalStateChange = useCallback( + (tabId: string, state: PtyTerminalState) => { + persistQuickTerminalState(store, tabId, state); + }, + [store], + ); + + const handleTerminalDescriptorReady = useCallback( + (tabId: string, descriptor: QuickTerminalTab) => { + applyQuickTerminalDescriptor(store, tabId, descriptor); + }, + [store], + ); + const handleSetupKindChange = useCallback( (kind: QuickChatSessionKind) => { resetPendingStarts(); @@ -241,13 +408,7 @@ export function useQuickChatModal(workspaceId: string, onSupersedeConfigStart = setSetupKey((key) => key + 1); store.openQuickChat("", workspaceId, undefined, kind); }, - [activeSession, resetPendingStarts, store, workspaceId], - ); - - const handleSelectAgent = useCallback( - (agentId: string, repositories: QuickChatRepositoryInput[] = []) => - doSelectAgent(agentId, repositories), - [doSelectAgent], + [activeSession, resetPendingStarts, setSetupKey, store, workspaceId], ); const setActiveQuickChatSession = useCallback( @@ -258,42 +419,67 @@ export function useQuickChatModal(workspaceId: string, onSupersedeConfigStart = [resetPendingStarts, store, workspaceId], ); - const handleRename = useCallback( - (sessionId: string, name: string) => { - if (!sessionId) return; - // Show the new label immediately, then save it to the backing task so - // the user's other devices pick it up over the task.updated event. - store.renameQuickChatSession(sessionId, name); - persistQuickChatRename(sessionId, resolveTaskId(store, sessionId), name).catch(() => { - toast({ - title: t("chat:renameSavedOnThisDeviceOnly"), - description: t("chat:renameSyncFailedDescription"), - variant: "error", - }); - }); - }, - [store, toast], + return { + sessionToClose, + setSessionToClose, + handleOpenChange, + handleNewChat, + handleNewTerminal, + handleActivateTerminal, + handleTerminalStateChange, + handleTerminalDescriptorReady, + handleSetupKindChange, + setActiveQuickChatSession, + handleCloseTab, + handleCloseTerminal, + handleConfirmClose, + handleRename, + }; +} + +export function useQuickChatModal(workspaceId: string, onSupersedeConfigStart = noop) { + const store = useQuickChatStore(workspaceId); + const { sessions, terminalTabs, activeSession, activeTerminalTab } = useWorkspaceQuickChat(store); + const [setupKey, setSetupKey] = useState(0); + const { + pendingAgentId, + reset, + handleSelectAgent: doSelectAgent, + } = useAgentSelection(workspaceId, store); + const resetPendingStarts = useCallback(() => { + reset(); + onSupersedeConfigStart(); + }, [onSupersedeConfigStart, reset]); + const tabActions = useQuickChatTabActions({ + workspaceId, + sessions, + activeSession, + store, + resetPendingStarts, + setSetupKey, + }); + + const handleSelectAgent = useCallback( + (agentId: string, repositories: QuickChatRepositoryInput[] = []) => + doSelectAgent(agentId, repositories), + [doSelectAgent], ); return { isOpen: store.isOpen, sessions, + terminalTabs, + activeKind: store.activeKind, + activeTerminalTabId: activeTerminalTab?.tabId ?? null, + activeTerminalTab, activeSessionId: activeSession?.sessionId ?? null, activeSession, - sessionToClose, + ...tabActions, setupKey, activeSessionNeedsAgent: Boolean( activeSession && isQuickChatSetupSessionId(activeSession.sessionId), ), pendingAgentId, - setActiveQuickChatSession, - setSessionToClose, - handleOpenChange, - handleNewChat, - handleSetupKindChange, handleSelectAgent, - handleCloseTab, - handleConfirmClose, - handleRename, }; } diff --git a/apps/web/components/settings/host-shell-dialog.tsx b/apps/web/components/settings/host-shell-dialog.tsx index 1641b83509..5e46203dd1 100644 --- a/apps/web/components/settings/host-shell-dialog.tsx +++ b/apps/web/components/settings/host-shell-dialog.tsx @@ -7,6 +7,7 @@ import { PtyTerminalDialog } from "@/components/settings/pty-terminal-dialog"; type Props = { open: boolean; onOpenChange: (open: boolean) => void; + presentation?: "standard" | "quick"; /** Optional callback when the user clicks Done (e.g. trigger a rescan). */ onClose?: () => void; /** @@ -20,18 +21,25 @@ type Props = { * Opens a PTY-backed terminal running the user's shell on the kandev host. * Used for ad-hoc setup commands that don't fit the install/login flows. */ -export function HostShellDialog({ open, onOpenChange, onClose, initialInput }: Props) { +export function HostShellDialog({ + open, + onOpenChange, + onClose, + initialInput, + presentation = "standard", +}: Props) { const { t } = useTranslation(); return ( ); } diff --git a/apps/web/components/settings/pty-terminal-dialog.tsx b/apps/web/components/settings/pty-terminal-dialog.tsx index 6e2537e8f0..2dd0c7bcf2 100644 --- a/apps/web/components/settings/pty-terminal-dialog.tsx +++ b/apps/web/components/settings/pty-terminal-dialog.tsx @@ -1,14 +1,7 @@ "use client"; -import { useEffect, useRef, useState } from "react"; +import { useState } from "react"; import { useTranslation } from "react-i18next"; -// The WebSocket error handler runs outside React, so it uses the module-level -// `t`, which resolves at call time. Components in this file use the hook. -import { t as translate } from "@/lib/i18n"; -import { Terminal } from "@xterm/xterm"; -import { FitAddon } from "@xterm/addon-fit"; -import { WebLinksAddon } from "@xterm/addon-web-links"; -import "@xterm/xterm/css/xterm.css"; import { Dialog, DialogContent, @@ -19,229 +12,49 @@ import { } from "@kandev/ui/dialog"; import { Button } from "@kandev/ui/button"; import { - agentLoginStreamUrl, - resizeAgentLogin, - stopAgentLogin, - type AgentLoginSession, -} from "@/lib/api"; -import type { ApiRequestOptions } from "@/lib/api"; -import { openExternalLink } from "@/lib/desktop/external-links"; + PtyTerminalView, + type PtySessionStatus, + type PtyTerminalState, + type StartPtySession, +} from "./pty-terminal-view"; -type SessionStatus = "connecting" | "running" | "exited" | "error"; - -type LoginStateSetters = { - setStatus: (s: SessionStatus) => void; - setError: (e: string | null) => void; - setExitCode: (c: number | null) => void; -}; - -/** - * Caller-supplied start function. Returns the same session shape regardless - * of which underlying endpoint (agent-login vs host-shell) is being driven - - * once a session exists, stop/resize/stream all share the same session-ID - * routes on the backend. - */ -export type StartPtySession = ( - size: { cols: number; rows: number }, - options?: ApiRequestOptions, -) => Promise; +export type { StartPtySession } from "./pty-terminal-view"; type Props = { open: boolean; onOpenChange: (open: boolean) => void; title: string; description?: string; - /** data-testid prefix for the terminal container element. */ testIdPrefix?: string; startSession: StartPtySession; - /** Invoked when the user clicks Done. */ onDone?: () => void; - /** - * If set, this text is sent to the shell once the WS connects. Used by - * auth flows that want to pre-fill a command like `claude auth login`. - * No trailing newline appended - the user can review and press Enter. - */ initialInput?: string; - /** - * argv of the actual command running in the PTY (e.g. ["codex", "login", - * "--device-auth"]). Shown above the terminal so the user can see/copy - * it - useful after Ctrl+C drops them into a shell and they want to retry. - */ command?: string[]; + presentation?: "standard" | "quick"; }; -function createTerminal(container: HTMLDivElement): { term: Terminal; fit: FitAddon } { - const term = new Terminal({ - convertEol: true, - cursorBlink: true, - fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, "Courier New", monospace', - fontSize: 13, - theme: { background: "#0b0b0c" }, - }); - const fit = new FitAddon(); - term.loadAddon(fit); - // Make http(s) URLs clickable - agents like codex print OAuth URLs that - // span multiple wrapped lines, and the user shouldn't have to copy/paste. - term.loadAddon( - new WebLinksAddon((event, uri) => { - // Open in a new tab. Holding the modifier (Cmd/Ctrl) is xterm's default - // gesture, but addon-web-links doesn't require it - any click works. - event.preventDefault(); - void openExternalLink(uri).catch(() => undefined); - }), - ); - term.open(container); - fit.fit(); - return { term, fit }; -} - -function wireResize( - container: HTMLDivElement, - fitRef: React.RefObject, - termRef: React.RefObject, - sessionIDRef: React.RefObject, - wsRef: React.RefObject, -): ResizeObserver { - const obs = new ResizeObserver(() => { - if (!fitRef.current || !termRef.current) return; - try { - fitRef.current.fit(); - } catch { - return; - } - const id = sessionIDRef.current; - if (!id) return; - const cols = termRef.current.cols; - const rows = termRef.current.rows; - void resizeAgentLogin(id, { cols, rows }).catch(() => {}); - if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { - wsRef.current.send(JSON.stringify({ type: "resize", cols, rows })); - } - }); - obs.observe(container); - return obs; -} - -function makeWsMessageHandler(term: Terminal, setters: LoginStateSetters) { - return (ev: MessageEvent) => { - if (typeof ev.data === "string") { - try { - const msg = JSON.parse(ev.data) as { type: string; exit_code?: number }; - if (msg.type === "exit") { - setters.setStatus("exited"); - setters.setExitCode(msg.exit_code ?? null); - } - } catch { - // ignore non-JSON text frames - } - return; - } - term.write(new Uint8Array(ev.data as ArrayBuffer)); - }; -} - -function openSessionWebSocket( - sessionID: string, - term: Terminal, - setters: LoginStateSetters, - initialInput: string | undefined, -): WebSocket { - const ws = new WebSocket(agentLoginStreamUrl(sessionID)); - ws.binaryType = "arraybuffer"; - ws.onmessage = makeWsMessageHandler(term, setters); - ws.onerror = () => { - setters.setError(translate("agents:ptyConnectionError")); - setters.setStatus("error"); - }; - if (initialInput) { - ws.addEventListener( - "open", - () => { - ws.send(new TextEncoder().encode(initialInput)); - }, - { once: true }, +function SessionStatus({ + status, + exitCode, + error, +}: Pick) { + const { t } = useTranslation(); + if (status === "connecting") { + return

{t("agents:startingSession")}

; + } + if (status === "exited") { + return ( +

+ {exitCode != null + ? t("agents:sessionEndedWithCode", { code: exitCode }) + : t("agents:sessionEnded")} +

); } - return ws; -} - -type MountArgs = { - container: HTMLDivElement; - startSession: StartPtySession; - setters: LoginStateSetters; - termRef: React.RefObject; - fitRef: React.RefObject; - wsRef: React.RefObject; - sessionIDRef: React.RefObject; - initialInput?: string; -}; - -function mountSession(args: MountArgs): () => void { - const term = createTerminal(args.container); - args.termRef.current = term.term; - args.fitRef.current = term.fit; - let cancelled = false; - // AbortController cancels an in-flight start POST so React StrictMode's - // double-mount can't leave a half-spawned session behind. - const startAbort = new AbortController(); - - void (async () => { - try { - const sess = await args.startSession( - { cols: term.term.cols, rows: term.term.rows }, - { init: { signal: startAbort.signal } }, - ); - if (cancelled) { - await stopAgentLogin(sess.session_id); - return; - } - args.sessionIDRef.current = sess.session_id; - args.wsRef.current = openSessionWebSocket( - sess.session_id, - term.term, - args.setters, - args.initialInput, - ); - args.setters.setStatus("running"); - } catch (err) { - if (err instanceof DOMException && err.name === "AbortError") return; - if (!cancelled) { - args.setters.setError(err instanceof Error ? err.message : String(err)); - args.setters.setStatus("error"); - } - } - })(); - - const resizeObs = wireResize( - args.container, - args.fitRef, - args.termRef, - args.sessionIDRef, - args.wsRef, - ); - const dataDisp = term.term.onData((data) => { - if (args.wsRef.current && args.wsRef.current.readyState === WebSocket.OPEN) { - args.wsRef.current.send(new TextEncoder().encode(data)); - } - }); - - return () => { - cancelled = true; - startAbort.abort(); - resizeObs.disconnect(); - dataDisp.dispose(); - if (args.sessionIDRef.current) { - void stopAgentLogin(args.sessionIDRef.current).catch(() => {}); - args.sessionIDRef.current = null; - } - if (args.wsRef.current) { - args.wsRef.current.close(); - args.wsRef.current = null; - } - term.term.dispose(); - args.termRef.current = null; - args.fitRef.current = null; - }; + if (status === "error" && error) { + return

{error}

; + } + return null; } function PtySessionView({ @@ -249,56 +62,36 @@ function PtySessionView({ testIdPrefix, initialInput, onDone, + presentation, }: { startSession: StartPtySession; testIdPrefix?: string; initialInput?: string; onDone: () => void; + presentation: "standard" | "quick"; }) { - const termContainerRef = useRef(null); - const termRef = useRef(null); - const fitRef = useRef(null); - const wsRef = useRef(null); - const sessionIDRef = useRef(null); + const [state, setState] = useState({ + status: "connecting" as PtySessionStatus, + sessionId: null, + exitCode: null, + error: null, + }); const { t } = useTranslation(); - const [error, setError] = useState(null); - const [status, setStatus] = useState("connecting"); - const [exitCode, setExitCode] = useState(null); - - useEffect(() => { - const container = termContainerRef.current; - if (!container) return; - return mountSession({ - container, - startSession, - setters: { setStatus, setError, setExitCode }, - termRef, - fitRef, - wsRef, - sessionIDRef, - initialInput, - }); - }, [startSession, initialInput]); - return ( <> -
- {status === "connecting" && ( -

{t("agents:startingSession")}

- )} - {status === "exited" && ( -

- {exitCode != null - ? t("agents:sessionEndedWithCode", { code: exitCode }) - : t("agents:sessionEnded")} -

- )} - {status === "error" && error &&

{error}

} - + +