feat(quick-terminal): unify terminal and chat tabs (#2235)

This commit is contained in:
Carlos Florêncio
2026-08-06 11:16:29 +01:00
committed by GitHub
parent e4dc91eb0f
commit 32ccb02895
106 changed files with 7341 additions and 761 deletions
@@ -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) {
@@ -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")
}
}
+57 -11
View File
@@ -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{})
@@ -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)
@@ -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)
+9 -9
View File
@@ -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)
@@ -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,
+14
View File
@@ -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,
@@ -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,
}
+12 -10
View File
@@ -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
}
@@ -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)
}
}
@@ -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:"-"`
}
@@ -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
}
@@ -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)
}
}
@@ -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
}
}
@@ -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)
}
}
+8 -8
View File
@@ -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.
+19 -10
View File
@@ -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: {},
},
},
};
@@ -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();
});
});
@@ -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 (
<Tooltip>
<Tooltip open={tooltipOpen} onOpenChange={handleTooltipOpenChange}>
<TooltipTrigger asChild>
<button
type="button"
onClick={onClick}
onPointerEnter={() => {
hoveredRef.current = true;
setTooltipOpen(true);
}}
onPointerLeave={() => {
hoveredRef.current = false;
setTooltipOpen(false);
}}
onFocus={() => {
hoveredRef.current = false;
setTooltipOpen(false);
}}
aria-label={label}
data-testid={testId}
className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground/70 hover:bg-muted hover:text-foreground cursor-pointer"
@@ -86,11 +117,12 @@ export function AppSidebarNewTaskItem({ collapsed }: AppSidebarNewTaskItemProps)
const setActiveSession = useAppStore((s) => s.setActiveSession);
const inOffice = useInOffice();
const handleOpenQuickChat = useQuickChatLauncher(workspaceId);
const handleOpenQuickTerminal = useQuickTerminalLauncher(workspaceId);
const [open, setOpen] = useState(false);
useNewTaskCreationRequest(workspaceId, setOpen);
const canOpenQuickChat = !collapsed && !!workspaceId;
const actionInsetClass = canOpenQuickChat ? ONE_ROW_ACTION_INSET_CLASS : undefined;
const canOpenRowActions = !collapsed && !!workspaceId;
const actionInsetClass = canOpenRowActions ? ROW_ACTION_INSET_CLASS : undefined;
const handleRegularTaskCreated = useCallback(
(
task: Task,
@@ -121,8 +153,14 @@ export function AppSidebarNewTaskItem({ collapsed }: AppSidebarNewTaskItemProps)
testId="create-task-button"
className={actionInsetClass}
/>
{canOpenQuickChat && (
{canOpenRowActions && (
<div className="absolute right-1.5 top-1/2 -translate-y-1/2 flex items-center gap-1 sidebar-fade-in">
<RowActionButton
icon={IconTerminal2}
label={t("sidebar:quickTerminal")}
testId="sidebar-quick-terminal-shortcut"
onClick={handleOpenQuickTerminal}
/>
<RowActionButton
icon={IconMessageCircle}
label={t("sidebar:quickChat")}
@@ -225,11 +225,8 @@ describe("Workspace settings order", () => {
expect(automationsIndex).toBeGreaterThanOrEqual(0);
expect(secretsIndex).toBeGreaterThan(automationsIndex);
// Anchored so the leaf must be labelled exactly "Secrets" — a rename to
// "Workspace Secrets" has to fail here. `ByRoleOptions` has no `exact`
// flag; a RegExp is how ByRole expresses a strict accessible-name match.
expect(screen.getByRole("link", { name: /^Secrets$/ })).toBeTruthy();
expect(screen.queryByRole("link", { name: /^Workspace Secrets$/ })).toBeNull();
expect(screen.getByRole("link", { name: "Secrets" })).toBeTruthy();
expect(screen.queryByRole("link", { name: "Workspace Secrets" })).toBeNull();
});
});
@@ -29,7 +29,10 @@ vi.mock("./mobile-menu-sheet", () => ({
MobileMenuSheet: () => null,
}));
const quickChatMocks = vi.hoisted(() => ({ openQuickChat: vi.fn() }));
const quickChatMocks = vi.hoisted(() => ({
openQuickChat: vi.fn(),
openQuickTerminal: vi.fn(),
}));
const statusDrawerState = vi.hoisted(() => ({
issueSeverity: "none" as "none" | "unstable" | "lost",
}));
@@ -38,16 +41,23 @@ vi.mock("@/hooks/use-quick-chat-launcher", () => ({
useQuickChatLauncher: () => quickChatMocks.openQuickChat,
}));
vi.mock("@/hooks/use-quick-terminal-launcher", () => ({
useQuickTerminalLauncher: () => quickChatMocks.openQuickTerminal,
}));
vi.mock("@/components/app-status-bar/app-status-surface-provider", () => ({
useAppStatusDrawer: () => statusDrawerState,
}));
const LEFT_ACTIONS_TEST_ID = "topbar-left-actions";
const QUICK_CHAT_TEST_ID = "mobile-quick-chat-button";
const QUICK_TERMINAL_TEST_ID = "mobile-quick-terminal-button";
const ACTIVE_WORKSPACE_ID = "workspace-1";
afterEach(() => {
cleanup();
quickChatMocks.openQuickChat.mockClear();
quickChatMocks.openQuickTerminal.mockClear();
statusDrawerState.issueSeverity = "none";
});
@@ -68,10 +78,10 @@ function renderHeader(title: string, workspaceId?: string, onSearchChange?: () =
describe("KanbanHeaderMobile", () => {
it("links the Kandev brand home and omits the redundant Home title", () => {
renderHeader("Home", "workspace-1");
renderHeader("Home", ACTIVE_WORKSPACE_ID);
expect(screen.getByRole("link", { name: "Kandev home" }).getAttribute("href")).toBe(
"/?home=overview&workspaceId=workspace-1",
`/?home=overview&workspaceId=${ACTIVE_WORKSPACE_ID}`,
);
expect(screen.getByTestId(LEFT_ACTIONS_TEST_ID).textContent).toBe("");
});
@@ -86,16 +96,28 @@ describe("KanbanHeaderMobile", () => {
});
it("opens quick chat from the header action when a workspace is active", () => {
renderHeader("Home", "workspace-1");
renderHeader("Home", ACTIVE_WORKSPACE_ID);
fireEvent.click(screen.getByTestId(QUICK_CHAT_TEST_ID));
expect(quickChatMocks.openQuickChat).toHaveBeenCalledTimes(1);
});
it("opens quick terminal immediately before quick chat", () => {
renderHeader("Home", ACTIVE_WORKSPACE_ID);
const terminal = screen.getByTestId(QUICK_TERMINAL_TEST_ID);
const quickChat = screen.getByTestId(QUICK_CHAT_TEST_ID);
expect(terminal.nextElementSibling).toBe(quickChat);
fireEvent.click(terminal);
expect(quickChatMocks.openQuickTerminal).toHaveBeenCalledTimes(1);
});
it("hides the quick chat action without an active workspace", () => {
renderHeader("Home");
expect(screen.queryByTestId(QUICK_CHAT_TEST_ID)).toBeNull();
expect(screen.queryByTestId(QUICK_TERMINAL_TEST_ID)).toBeNull();
});
it("places quick chat immediately before search", () => {
@@ -1,7 +1,8 @@
"use client";
import { Button } from "@kandev/ui/button";
import { IconMenu2, IconMessageCircle, IconSearch } from "@tabler/icons-react";
import { IconMenu2, IconMessageCircle, IconSearch, IconTerminal2 } from "@tabler/icons-react";
import { useTranslation } from "react-i18next";
import Link from "@/components/routing/app-link";
import { PageTopbar } from "@/components/page-topbar";
import { TopbarMetrics } from "@/components/system-metrics/topbar-metrics";
@@ -12,9 +13,9 @@ import { useAppStore } from "@/components/state-provider";
import { useAppStatusDrawer } from "@/components/app-status-bar/app-status-surface-provider";
import { useConnectionIssueCopy } from "@/components/app-status-bar/connection-status-item";
import { useQuickChatLauncher } from "@/hooks/use-quick-chat-launcher";
import { useQuickTerminalLauncher } from "@/hooks/use-quick-terminal-launcher";
import { workspaceHomeHref } from "@/components/app-sidebar/app-sidebar-workspace-navigation";
import { cn } from "@/lib/utils";
import { useTranslation } from "react-i18next";
type KanbanHeaderMobileProps = {
workspaceId?: string;
@@ -50,6 +51,7 @@ function MobileHeaderActions({
onSearchChange,
isSearchOpen,
handleOpenQuickChat,
handleOpenQuickTerminal,
toggleSearch,
setMenuOpen,
}: {
@@ -59,6 +61,7 @@ function MobileHeaderActions({
onSearchChange?: (query: string) => void;
isSearchOpen: boolean;
handleOpenQuickChat: () => void;
handleOpenQuickTerminal: () => void;
toggleSearch: () => void;
setMenuOpen: (open: boolean) => void;
}) {
@@ -74,13 +77,25 @@ function MobileHeaderActions({
currentPage={currentPage}
/>
<TopbarMetrics size="lg" />
{workspaceId && (
<Button
variant="outline"
size="icon-lg"
onClick={handleOpenQuickTerminal}
className="!size-11 cursor-pointer"
aria-label={t("sidebar:quickTerminal")}
data-testid="mobile-quick-terminal-button"
>
<IconTerminal2 className="h-4 w-4" />
</Button>
)}
{workspaceId && (
<Button
variant="outline"
size="icon-lg"
onClick={handleOpenQuickChat}
className="cursor-pointer"
aria-label={t("common:commandQuickChat")}
className="!size-11 cursor-pointer"
aria-label={t("sidebar:quickChat")}
data-testid="mobile-quick-chat-button"
>
<IconMessageCircle className="h-4 w-4" />
@@ -148,6 +163,7 @@ export function KanbanHeaderMobile({
const isSearchOpen = useAppStore((state) => state.mobileKanban.isSearchOpen);
const setSearchOpen = useAppStore((state) => state.setMobileKanbanSearchOpen);
const handleOpenQuickChat = useQuickChatLauncher(workspaceId);
const handleOpenQuickTerminal = useQuickTerminalLauncher(workspaceId);
const isHome = title === "Home";
const toggleSearch = () => {
@@ -186,6 +202,7 @@ export function KanbanHeaderMobile({
onSearchChange={onSearchChange}
isSearchOpen={isSearchOpen}
handleOpenQuickChat={handleOpenQuickChat}
handleOpenQuickTerminal={handleOpenQuickTerminal}
toggleSearch={toggleSearch}
setMenuOpen={setMenuOpen}
/>
+36 -14
View File
@@ -10,8 +10,10 @@ import {
IconLayoutKanban,
IconMenu2,
IconMessageCircle,
IconTerminal2,
IconTimeline,
} from "@tabler/icons-react";
import { useTranslation } from "react-i18next";
import { PageTopbar } from "@/components/page-topbar";
import { KanbanDisplayDropdown } from "../kanban-display-dropdown";
import { ReleaseNotesDialog } from "../release-notes/release-notes-dialog";
@@ -28,9 +30,9 @@ import { useKanbanDisplaySettings } from "@/hooks/use-kanban-display-settings";
import { useReleaseNotes } from "@/hooks/use-release-notes";
import { useSystemHealthIndicator } from "@/hooks/use-system-health-indicator";
import { useQuickChatLauncher } from "@/hooks/use-quick-chat-launcher";
import { useQuickTerminalLauncher } from "@/hooks/use-quick-terminal-launcher";
import { TopbarMetrics } from "@/components/system-metrics/topbar-metrics";
import type { ComponentProps, RefObject } from "react";
import { useTranslation } from "react-i18next";
type KanbanHeaderProps = {
workspaceId?: string;
@@ -141,6 +143,38 @@ function useIsHeaderNarrow(ref: RefObject<HTMLElement | null>): boolean {
return isNarrow;
}
function TabletQuickActions({ workspaceId }: { workspaceId?: string }) {
const { t } = useTranslation();
const handleOpenQuickChat = useQuickChatLauncher(workspaceId);
const handleOpenQuickTerminal = useQuickTerminalLauncher(workspaceId);
if (!workspaceId) return null;
return (
<>
<Button
variant="outline"
size="icon-lg"
onClick={handleOpenQuickTerminal}
className="!size-11 cursor-pointer"
aria-label={t("sidebar:quickTerminal")}
data-testid="tablet-quick-terminal-button"
>
<IconTerminal2 className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon-lg"
onClick={handleOpenQuickChat}
className="!size-11 cursor-pointer"
aria-label={t("sidebar:quickChat")}
data-testid="tablet-quick-chat-button"
>
<IconMessageCircle className="h-4 w-4" />
</Button>
</>
);
}
function TabletHeader({
title,
workspaceLabel,
@@ -172,7 +206,6 @@ function TabletHeader({
}) {
const { t } = useTranslation();
const isHome = title === "Home";
const handleOpenQuickChat = useQuickChatLauncher(workspaceId);
return (
<PageTopbar
@@ -199,18 +232,7 @@ function TabletHeader({
currentPage={currentPage}
/>
<TopbarMetrics size="lg" />
{workspaceId && (
<Button
variant="outline"
size="icon-lg"
onClick={handleOpenQuickChat}
className="cursor-pointer"
aria-label={t("common:commandQuickChat")}
data-testid="tablet-quick-chat-button"
>
<IconMessageCircle className="h-4 w-4" />
</Button>
)}
<TabletQuickActions workspaceId={workspaceId} />
<TooltipProvider>
<ViewToggleGroup toggleValue={toggleValue} onValueChange={handleViewChange} size="lg" />
</TooltipProvider>
@@ -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);
});
});
@@ -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();
});
}
@@ -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 <div data-testid="mock-quick-terminal-view" data-tab-id={tab.tabId} />;
},
}));
vi.mock("@kandev/ui/dialog", () => ({
Dialog: ({ open, children }: { open: boolean; children: React.ReactNode }) =>
open ? <div data-testid="quick-chat-dialog">{children}</div> : null,
DialogContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));
vi.mock("@kandev/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuSeparator: () => <hr />,
DropdownMenuItem: ({
children,
onSelect,
...props
}: {
children: React.ReactNode;
onSelect?: () => void;
[key: string]: unknown;
}) => (
<button type="button" {...props} onClick={() => onSelect?.()}>
{children}
</button>
),
}));
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: () => <div data-testid="quick-chat-session-view" />,
}));
vi.mock("./quick-chat-setup", () => ({
QuickChatSetup: () => <div data-testid="quick-chat-setup" />,
}));
vi.mock("@/components/config-chat/config-chat-setup", () => ({
ConfigChatSetup: () => <div data-testid="config-chat-setup" />,
}));
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(<QuickChatModal workspaceId={WORKSPACE_ID} />);
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();
});
});
@@ -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 (
<div className="flex items-center gap-1 px-2 py-1 border-b bg-muted/20">
<div className="flex items-center gap-1 overflow-x-auto flex-1 scrollbar-hide">
@@ -58,7 +76,7 @@ function QuickChatTabs({
<QuickChatTabItem
key={s.sessionId || `new-${index}`}
name={tabName}
isActive={s.sessionId === activeSessionId}
isActive={activeKind === "conversation" && s.sessionId === activeSessionId}
isRenameable={!isQuickChatSetupSessionId(s.sessionId)}
kind={s.kind}
onActivate={() => onTabChange(s.sessionId)}
@@ -67,15 +85,17 @@ function QuickChatTabs({
/>
);
})}
<Button
size="icon"
variant="ghost"
className="h-11 w-11 shrink-0 cursor-pointer sm:h-6 sm:w-6"
onClick={onNewChat}
aria-label={t("chat:startNewChat")}
>
<IconPlus className="h-4 w-4 sm:h-3.5 sm:w-3.5" />
</Button>
{terminalTabs.map((tab) => (
<QuickTerminalTabItem
key={tab.tabId}
sequence={tab.sequence}
isActive={activeKind === "terminal" && tab.tabId === activeTerminalTabId}
error={tab.error}
onActivate={() => onTerminalActivate(tab.tabId)}
onClose={() => onTerminalClose(tab.tabId)}
/>
))}
<QuickTabAddMenu onNewAgent={onNewChat} onNewTerminal={onNewTerminal} />
</div>
{/* 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"
>
<IconX className="h-3.5 w-3.5" />
@@ -93,6 +113,97 @@ function QuickChatTabs({
);
}
type QuickChatContentProps = {
workspaceId: string;
configChat: ReturnType<typeof useConfigChat>;
quickChat: ReturnType<typeof useQuickChatModal>;
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 (
<>
<QuickChatTabs
sessions={quickChat.sessions}
terminalTabs={quickChat.terminalTabs}
activeKind={quickChat.activeKind}
activeSessionId={quickChat.activeSessionId}
activeTerminalTabId={quickChat.activeTerminalTabId}
onTabChange={quickChat.setActiveQuickChatSession}
onTabClose={quickChat.handleCloseTab}
onNewChat={quickChat.handleNewChat}
onNewTerminal={quickChat.handleNewTerminal}
onTerminalActivate={quickChat.handleActivateTerminal}
onTerminalClose={quickChat.handleCloseTerminal}
onRename={quickChat.handleRename}
onCloseModal={() => quickChat.handleOpenChange(false)}
/>
{quickChat.activeKind === "terminal" && quickChat.activeTerminalTab && (
<QuickTerminalTabView
key={quickChat.activeTerminalTab.tabId}
tab={quickChat.activeTerminalTab}
onStateChange={(state) =>
quickChat.handleTerminalStateChange(quickChat.activeTerminalTab!.tabId, state)
}
onDescriptorReady={(descriptor) =>
quickChat.handleTerminalDescriptorReady(quickChat.activeTerminalTab!.tabId, descriptor)
}
/>
)}
{quickChat.activeKind === "conversation" &&
quickChat.activeSessionId &&
quickChat.activeSession &&
!quickChat.activeSessionNeedsAgent && (
<QuickChatSessionView
session={quickChat.activeSession}
onInitialPromptSent={() =>
setQuickChatInitialPrompt(quickChat.activeSessionId!, undefined)
}
/>
)}
{quickChat.activeKind === "conversation" &&
quickChat.activeSessionNeedsAgent &&
setupKind === "chat" && (
<QuickChatSetup
key={`${workspaceId}:${quickChat.setupKey}`}
workspaceId={workspaceId}
canCreateConfigurationChat={canCreateConfigurationChat}
pendingAgentId={quickChat.pendingAgentId}
onStart={quickChat.handleSelectAgent}
onCancel={() => quickChat.handleOpenChange(false)}
onKindChange={quickChat.handleSetupKindChange}
/>
)}
{quickChat.activeKind === "conversation" &&
quickChat.activeSessionNeedsAgent &&
setupKind === "config" && (
<ConfigChatSetup
key={`${workspaceId}:config:${quickChat.setupKey}`}
defaultProfileId={configChat.defaultProfileId}
isStarting={configChat.isStarting}
error={configChat.error}
onStart={(profileId, prompt) => 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 (
<>
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<Dialog open={quickChat.isOpen} onOpenChange={quickChat.handleOpenChange}>
<DialogContent
className="!left-0 !top-0 !h-dvh !max-h-dvh !w-screen !max-w-none !translate-x-0 !translate-y-0 flex flex-col gap-0 p-0 shadow-2xl sm:!left-1/2 sm:!top-1/2 sm:!h-[85vh] sm:!max-h-[85vh] sm:!w-[var(--quick-chat-width)] sm:!max-w-[calc(100vw-2rem)] sm:!-translate-x-1/2 sm:!-translate-y-1/2"
className="!left-0 !top-0 !h-dvh !max-h-dvh !w-screen !max-w-none !translate-x-0 !translate-y-0 flex flex-col gap-0 p-0 pt-safe pb-safe shadow-2xl sm:!left-1/2 sm:!top-1/2 sm:!h-[85vh] sm:!max-h-[85vh] sm:!w-[var(--quick-chat-width)] sm:!max-w-[calc(100vw-2rem)] sm:!-translate-x-1/2 sm:!-translate-y-1/2"
style={{ "--quick-chat-width": `${width}px` } as CSSProperties}
showCloseButton={false}
overlayClassName="bg-black/20"
@@ -162,50 +252,19 @@ export const QuickChatModal = memo(function QuickChatModal({ workspaceId }: Quic
<DialogTitle className="sr-only">{t("common:commandQuickChat")}</DialogTitle>
<QuickChatResizeHandle edge="left" {...leftResizeHandleProps} />
<QuickChatResizeHandle edge="right" {...rightResizeHandleProps} />
<QuickChatTabs
sessions={sessions}
activeSessionId={activeSessionId || ""}
onTabChange={setActiveQuickChatSession}
onTabClose={handleCloseTab}
onNewChat={handleNewChat}
onRename={handleRename}
onCloseModal={() => handleOpenChange(false)}
<QuickChatContent
workspaceId={workspaceId}
configChat={configChat}
quickChat={quickChat}
setQuickChatInitialPrompt={setQuickChatInitialPrompt}
/>
{activeSessionId && activeSession && !activeSessionNeedsAgent && (
<QuickChatSessionView
session={activeSession}
onInitialPromptSent={() => setQuickChatInitialPrompt(activeSessionId, undefined)}
/>
)}
{activeSessionNeedsAgent && setupKind === "chat" && (
<QuickChatSetup
key={`${workspaceId}:${setupKey}`}
workspaceId={workspaceId}
canCreateConfigurationChat={canCreateConfigurationChat}
pendingAgentId={pendingAgentId}
onStart={handleSelectAgent}
onCancel={() => handleOpenChange(false)}
onKindChange={handleSetupKindChange}
/>
)}
{activeSessionNeedsAgent && setupKind === "config" && (
<ConfigChatSetup
key={`${workspaceId}:config:${setupKey}`}
defaultProfileId={configChat.defaultProfileId}
isStarting={configChat.isStarting}
error={configChat.error}
onStart={(profileId, prompt) => configChat.startSession(profileId, prompt)}
onCancel={() => handleOpenChange(false)}
onKindChange={handleSetupKindChange}
/>
)}
</DialogContent>
</Dialog>
<QuickChatDeleteDialog
sessionToDelete={sessionToClose}
onOpenChange={(open) => !open && setSessionToClose(null)}
onConfirm={handleConfirmClose}
sessionToDelete={quickChat.sessionToClose}
onOpenChange={(open) => !open && quickChat.setSessionToClose(null)}
onConfirm={quickChat.handleConfirmClose}
/>
</>
);
@@ -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(
<QuickChatProvider>
<button type="button">launch</button>
</QuickChatProvider>,
);
const launcher = document.querySelector("button") as HTMLButtonElement;
launcher.focus();
captureQuickChatLauncherFocus();
providerState.quickChat.isOpen = false;
rerender(
<QuickChatProvider>
<button type="button">launch</button>
</QuickChatProvider>,
);
expect(document.activeElement).toBe(launcher);
});
});
@@ -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();
});
});
@@ -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 (
<>
@@ -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;
}) => (
<button type="button" onClick={onSelect}>
{children}
</button>
),
}));
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<Parameters<typeof QuickChatTabItem>[0]> = {}) {
@@ -23,6 +51,15 @@ function startEditing(label: HTMLElement) {
}
describe("QuickChatTabItem rename", () => {
it("starts renaming from the tab context menu", () => {
const { getByRole, getByLabelText } = render(<QuickChatTabItem {...makeProps()} />);
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(
<QuickChatTabItem
@@ -1,9 +1,16 @@
"use client";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { IconSparkles, IconX } from "@tabler/icons-react";
import type { QuickChatSessionKind } from "@/lib/state/slices/ui/types";
import { useTranslation } from "react-i18next";
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuTrigger,
} from "@kandev/ui/context-menu";
import type { QuickChatSessionKind } from "@/lib/state/slices/ui/types";
type QuickChatTabItemProps = {
name: string;
@@ -15,7 +22,22 @@ type QuickChatTabItemProps = {
onRename: (name: string) => 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 (
<ContextMenu>
<ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
<ContextMenuContent>
<ContextMenuItem className="min-h-11 cursor-pointer sm:min-h-7" onSelect={onRename}>
{t("common:rename")}
</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
);
}
/** 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 = (
<div
data-testid="quick-chat-tab"
className={`flex items-center gap-1 rounded transition-colors whitespace-nowrap ${
@@ -124,4 +146,8 @@ export const QuickChatTabItem = memo(function QuickChatTabItem({
</button>
</div>
);
if (!isRenameable) return tabContent;
return <RenameContextMenu onRename={handleStartEdit}>{tabContent}</RenameContextMenu>;
});
@@ -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 }) => <div>{children}</div>,
DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
DropdownMenuSeparator: () => <hr />,
DropdownMenuItem: ({
children,
onSelect,
...props
}: {
children: React.ReactNode;
onSelect?: () => void;
[key: string]: unknown;
}) => (
<button type="button" {...props} onClick={() => onSelect?.()}>
{children}
</button>
),
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, values?: { count?: number; error?: string }) => {
const messages: Record<string, string> = {
"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(<QuickTabAddMenu onNewAgent={vi.fn()} onNewTerminal={onNewTerminal} />);
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);
});
});
@@ -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 (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
size="icon"
variant="ghost"
className="h-11 w-11 shrink-0 cursor-pointer sm:h-6 sm:w-6"
aria-label={t("sidebar:quickChatAdd")}
data-testid="quick-chat-add-menu-trigger"
>
<IconPlus className="h-4 w-4 sm:h-3.5 sm:w-3.5" aria-hidden />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<DropdownMenuLabel className="text-xs text-muted-foreground">
{t("common:agents")}
</DropdownMenuLabel>
<DropdownMenuItem
onSelect={onNewAgent}
className="min-h-11 cursor-pointer gap-1.5 sm:min-h-7"
data-testid="quick-chat-new-agent"
>
<IconMessagePlus className="h-3.5 w-3.5 shrink-0" aria-hidden />
<span className="flex-1 truncate">{t("sidebar:quickChatNewAgent")}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuLabel className="text-xs text-muted-foreground">
{t("sidebar:quickChatTerminals")}
</DropdownMenuLabel>
<DropdownMenuItem
onSelect={onNewTerminal}
className="min-h-11 cursor-pointer gap-1.5 sm:min-h-7"
data-testid="quick-chat-new-terminal"
>
<IconTerminal2 className="h-3.5 w-3.5 shrink-0" aria-hidden />
<span className="flex-1 truncate">{t("sidebar:quickChatNewTerminal")}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
@@ -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 (
<div
data-testid="quick-terminal-tab"
data-terminal-sequence={sequence}
className={`flex shrink-0 items-center gap-1 rounded transition-colors ${
isActive
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:bg-muted"
}`}
>
<button
type="button"
onClick={onActivate}
aria-label={label}
aria-current={isActive ? "page" : undefined}
className="flex h-11 min-w-0 cursor-pointer items-center gap-1.5 px-2.5 text-xs sm:h-6"
>
<IconTerminal2 className="h-3.5 w-3.5 shrink-0" aria-hidden />
<span>{label}</span>
{error && <IconAlertCircle className="h-3.5 w-3.5 shrink-0" aria-hidden />}
</button>
<button
type="button"
aria-label={closeLabel}
title={closeLabel}
className="flex h-11 w-11 shrink-0 cursor-pointer items-center justify-center opacity-60 hover:opacity-100 sm:h-6 sm:w-6"
onClick={onClose}
>
<IconX className="h-3 w-3" aria-hidden />
</button>
</div>
);
});
@@ -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<unknown>;
clientId?: string;
lifecycle: string;
}) => (
<button
type="button"
data-testid="pty-view-probe"
data-lifecycle={props.lifecycle}
onClick={() => props.startSession({ cols: 80, rows: 24 }, { clientId: props.clientId })}
>
start
</button>
),
}));
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(<QuickTerminalTabView tab={tab} onStateChange={onStateChange} />);
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(<QuickTerminalTabView tab={tab} onStateChange={vi.fn()} />);
expect(screen.getByRole("status").textContent).toContain("Connecting to terminal…");
rerender(
<QuickTerminalTabView
tab={{ ...tab, status: "error", error: "Unable to reattach." }}
onStateChange={vi.fn()}
/>,
);
expect(screen.getByRole("alert").textContent).toContain("Terminal error: Unable to reattach.");
rerender(
<QuickTerminalTabView
tab={{ ...tab, status: "exited", exitCode: 7 }}
onStateChange={vi.fn()}
/>,
);
expect(screen.getByRole("status").textContent).toContain("Terminal exited with code 7.");
});
});
@@ -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 (
<p
role="status"
aria-live="polite"
data-testid="quick-terminal-status"
className="shrink-0 px-2 pb-1 text-xs text-muted-foreground"
>
{t("sidebar:quickChatTerminalConnecting")}
</p>
);
}
if (tab.status === "error" || tab.error) {
return (
<p
role="alert"
data-testid="quick-terminal-status"
className="shrink-0 px-2 pb-1 text-xs text-destructive"
>
{t("sidebar:quickChatTerminalError", {
error: tab.error || t("sidebar:quickChatTerminalUnknownError"),
})}
</p>
);
}
if (tab.status === "exited") {
return (
<p
role="status"
aria-live="polite"
data-testid="quick-terminal-status"
className="shrink-0 px-2 pb-1 text-xs text-muted-foreground"
>
{tab.exitCode == null
? t("sidebar:quickChatTerminalExited")
: t("sidebar:quickChatTerminalExitedWithCode", { code: tab.exitCode })}
</p>
);
}
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<StartPtySession>(
(size, options) => startHostShell(size, options),
[],
);
return (
<div
className="flex min-h-0 flex-1 flex-col overflow-hidden"
data-testid="quick-terminal-tab-panel"
data-terminal-tab-id={tab.tabId}
>
{shouldRenderTerminal && (
<PtyTerminalView
startSession={startSession}
sessionId={tab.sessionId}
clientId={tab.tabId}
ownerId={tab.tabId}
lifecycle="detach-on-unmount"
testIdPrefix="quick-terminal"
className="h-full min-h-0 flex-1 rounded-md bg-[#0b0b0c] p-2 overflow-hidden"
onStateChange={onStateChange}
/>
)}
<QuickTerminalLifecycleStatus tab={tab} />
</div>
);
}
@@ -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<typeof makeAppState>;
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<typeof useAgentSelection>[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> = {}): 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" }));
});
});
@@ -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<typeof useQuickChatStore>;
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<React.SetStateAction<number>>;
};
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,
};
}
@@ -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 (
<PtyTerminalDialog
open={open}
onOpenChange={onOpenChange}
title={t("agents:hostTerminal")}
title={presentation === "quick" ? t("sidebar:quickTerminal") : t("agents:hostTerminal")}
description={t("agents:hostTerminalDescription")}
testIdPrefix="host-shell"
startSession={startHostShell}
onDone={onClose}
initialInput={initialInput}
presentation={presentation}
/>
);
}
@@ -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<AgentLoginSession>;
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<FitAddon | null>,
termRef: React.RefObject<Terminal | null>,
sessionIDRef: React.RefObject<string | null>,
wsRef: React.RefObject<WebSocket | null>,
): 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<PtyTerminalState, "status" | "exitCode" | "error">) {
const { t } = useTranslation();
if (status === "connecting") {
return <p className="text-xs text-muted-foreground">{t("agents:startingSession")}</p>;
}
if (status === "exited") {
return (
<p className="text-xs text-muted-foreground">
{exitCode != null
? t("agents:sessionEndedWithCode", { code: exitCode })
: t("agents:sessionEnded")}
</p>
);
}
return ws;
}
type MountArgs = {
container: HTMLDivElement;
startSession: StartPtySession;
setters: LoginStateSetters;
termRef: React.RefObject<Terminal | null>;
fitRef: React.RefObject<FitAddon | null>;
wsRef: React.RefObject<WebSocket | null>;
sessionIDRef: React.RefObject<string | null>;
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 <p className="text-xs text-destructive">{error}</p>;
}
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<HTMLDivElement | null>(null);
const termRef = useRef<Terminal | null>(null);
const fitRef = useRef<FitAddon | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const sessionIDRef = useRef<string | null>(null);
const [state, setState] = useState<PtyTerminalState>({
status: "connecting" as PtySessionStatus,
sessionId: null,
exitCode: null,
error: null,
});
const { t } = useTranslation();
const [error, setError] = useState<string | null>(null);
const [status, setStatus] = useState<SessionStatus>("connecting");
const [exitCode, setExitCode] = useState<number | null>(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 (
<>
<div
ref={termContainerRef}
data-testid={`${testIdPrefix ?? "pty"}-terminal`}
className="h-[420px] rounded-md bg-[#0b0b0c] p-2 overflow-hidden"
<PtyTerminalView
startSession={startSession}
testIdPrefix={testIdPrefix}
initialInput={initialInput}
className={
presentation === "quick"
? "min-h-0 flex-1 rounded-md bg-[#0b0b0c] p-2 overflow-hidden"
: "h-[420px] rounded-md bg-[#0b0b0c] p-2 overflow-hidden"
}
onStateChange={setState}
/>
{status === "connecting" && (
<p className="text-xs text-muted-foreground">{t("agents:startingSession")}</p>
)}
{status === "exited" && (
<p className="text-xs text-muted-foreground">
{exitCode != null
? t("agents:sessionEndedWithCode", { code: exitCode })
: t("agents:sessionEnded")}
</p>
)}
{status === "error" && error && <p className="text-xs text-destructive">{error}</p>}
<DialogFooter>
<SessionStatus {...state} />
<DialogFooter className={presentation === "quick" ? "shrink-0" : undefined}>
<Button
type="button"
onClick={onDone}
@@ -312,11 +105,7 @@ function PtySessionView({
);
}
/**
* Generic dialog that hosts a PTY-backed terminal. Mounts the inner
* `<PtySessionView>` only while `open` is true - closing the dialog unmounts
* it, which fires cleanup (stop session, dispose terminal).
*/
/** Dialog wrapper used by agent-login and host-shell settings flows. */
export function PtyTerminalDialog({
open,
onOpenChange,
@@ -327,17 +116,21 @@ export function PtyTerminalDialog({
onDone,
initialInput,
command,
presentation = "standard",
}: Props) {
const handleDone = () => {
onDone?.();
onOpenChange(false);
};
const cmdLine = command && command.length > 0 ? command.join(" ") : null;
const dialogClassName =
presentation === "quick"
? "!left-0 !top-0 !h-dvh !max-h-dvh !w-screen !max-w-none !translate-x-0 !translate-y-0 flex flex-col gap-3 overflow-hidden p-4 [padding-top:max(1rem,env(safe-area-inset-top))] [padding-bottom:max(1rem,env(safe-area-inset-bottom))] sm:!left-1/2 sm:!top-1/2 sm:!h-[85dvh] sm:!max-h-[85dvh] sm:!w-[min(1100px,calc(100vw-2rem))] sm:!max-w-none sm:!-translate-x-1/2 sm:!-translate-y-1/2"
: "sm:max-w-[820px]";
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[820px]">
<DialogContent className={dialogClassName}>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
{description && <DialogDescription>{description}</DialogDescription>}
@@ -359,6 +152,7 @@ export function PtyTerminalDialog({
testIdPrefix={testIdPrefix}
initialInput={initialInput}
onDone={handleDone}
presentation={presentation}
/>
)}
</DialogContent>
@@ -0,0 +1,9 @@
export type PendingPtyStart = { cancelled: boolean };
export const pendingPtyStarts = new Map<string, PendingPtyStart>();
/** Marks a detached terminal start as explicitly closed. */
export function cancelPtyTerminalStart(ownerId: string): void {
const pending = pendingPtyStarts.get(ownerId);
if (pending) pending.cancelled = true;
}
@@ -0,0 +1,340 @@
import { act, cleanup, render, waitFor } from "@testing-library/react";
import { StrictMode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => {
const sockets: MockWebSocket[] = [];
const terminals: MockTerminal[] = [];
class MockTerminal {
cols = 80;
rows = 24;
loadAddon = vi.fn();
open = vi.fn();
write = vi.fn();
dispose = vi.fn();
onData = vi.fn(() => ({ dispose: vi.fn() }));
constructor() {
terminals.push(this);
}
}
class MockWebSocket {
static readonly OPEN = 1;
static readonly CLOSED = 3;
readyState = MockWebSocket.OPEN;
binaryType = "";
onmessage: ((event: MessageEvent) => void) | null = null;
onclose: (() => void) | null = null;
onerror: (() => void) | null = null;
send = vi.fn();
close = vi.fn(() => {
this.readyState = MockWebSocket.CLOSED;
this.onclose?.();
});
addEventListener = vi.fn((type: string, listener: EventListener) => {
if (type === "open") queueMicrotask(() => listener(new Event("open")));
});
constructor() {
sockets.push(this);
}
}
return {
stopAgentLogin: vi.fn().mockResolvedValue(undefined),
getAgentLoginStatus: vi.fn(),
resizeAgentLogin: vi.fn().mockResolvedValue(undefined),
sockets,
terminals,
resizeCallbacks: [] as ResizeObserverCallback[],
MockTerminal,
MockWebSocket,
};
});
vi.mock("@xterm/xterm", () => ({ Terminal: mocks.MockTerminal }));
vi.mock("@xterm/addon-fit", () => ({
FitAddon: class {
fit = vi.fn();
},
}));
vi.mock("@xterm/addon-web-links", () => ({ WebLinksAddon: class {} }));
vi.mock("@/lib/desktop/external-links", () => ({ openExternalLink: vi.fn() }));
vi.mock("@/lib/api", () => ({
agentLoginStreamUrl: vi.fn((sessionId: string) => `ws://api.test/${sessionId}`),
getAgentLoginStatus: mocks.getAgentLoginStatus,
resizeAgentLogin: mocks.resizeAgentLogin,
stopAgentLogin: mocks.stopAgentLogin,
}));
import { PtyTerminalView, type StartPtySession } from "./pty-terminal-view";
import { cancelPtyTerminalStart } from "./pty-terminal-lifecycle";
const session = {
session_id: "session-1",
agent_id: "_host_shell",
cmd: ["/bin/bash"],
running: true,
started_at: "2026-08-04T00:00:00Z",
};
function startSession(): ReturnType<StartPtySession> {
return Promise.resolve(session);
}
beforeEach(() => {
mocks.stopAgentLogin.mockClear();
mocks.getAgentLoginStatus.mockReset();
mocks.resizeAgentLogin.mockClear();
mocks.sockets.length = 0;
mocks.terminals.length = 0;
mocks.resizeCallbacks.length = 0;
vi.stubGlobal("WebSocket", mocks.MockWebSocket);
vi.stubGlobal(
"ResizeObserver",
class {
observe = vi.fn();
disconnect = vi.fn();
constructor(callback: ResizeObserverCallback) {
mocks.resizeCallbacks.push(callback);
}
},
);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
describe("PtyTerminalView lifecycle", () => {
it("stops a standard-dialog session when the view unmounts", async () => {
const view = render(<PtyTerminalView startSession={startSession} />);
await waitFor(() => expect(mocks.sockets).toHaveLength(1));
view.unmount();
await waitFor(() => expect(mocks.stopAgentLogin).toHaveBeenCalledWith("session-1"));
});
it("detaches a quick-tab session without stopping it", async () => {
const view = render(
<PtyTerminalView
startSession={startSession}
lifecycle="detach-on-unmount"
ownerId="tab-1"
clientId="6f2d7f2d-0d0c-4c9b-8b73-1c53a5ed5b6b"
/>,
);
await waitFor(() => expect(mocks.sockets).toHaveLength(1));
view.unmount();
await act(async () => {});
expect(mocks.stopAgentLogin).not.toHaveBeenCalled();
expect(mocks.sockets[0]?.close).toHaveBeenCalledTimes(1);
});
it("reports a detached late start so the tab retains its session identity", async () => {
let resolveStart: ((value: typeof session) => void) | undefined;
const start = vi.fn(
() =>
new Promise<typeof session>((resolve) => {
resolveStart = resolve;
}),
);
const onStateChange = vi.fn();
const view = render(
<PtyTerminalView
startSession={start}
lifecycle="detach-on-unmount"
ownerId="tab-late-start"
onStateChange={onStateChange}
/>,
);
await waitFor(() => expect(start).toHaveBeenCalled());
view.unmount();
await act(async () => resolveStart?.(session));
expect(onStateChange).toHaveBeenLastCalledWith({
status: "running",
sessionId: "session-1",
exitCode: null,
error: null,
});
expect(mocks.stopAgentLogin).not.toHaveBeenCalled();
});
it("attaches to an existing session without starting or stopping it on detach", async () => {
mocks.getAgentLoginStatus.mockResolvedValueOnce(session);
const start = vi.fn(startSession);
const view = render(
<PtyTerminalView
startSession={start}
sessionId="session-1"
lifecycle="detach-on-unmount"
ownerId="tab-1"
/>,
);
await waitFor(() => expect(mocks.sockets).toHaveLength(1));
expect(start).not.toHaveBeenCalled();
expect(mocks.getAgentLoginStatus).toHaveBeenCalledWith("session-1");
view.unmount();
expect(mocks.stopAgentLogin).not.toHaveBeenCalled();
});
});
describe("PtyTerminalView lifecycle races", () => {
it("stops a detached start that is explicitly cancelled after unmount", async () => {
let resolveStart: ((value: typeof session) => void) | undefined;
const start = vi.fn(
() =>
new Promise<typeof session>((resolve) => {
resolveStart = resolve;
}),
);
const view = render(
<PtyTerminalView startSession={start} lifecycle="detach-on-unmount" ownerId="tab-pending" />,
);
await waitFor(() => expect(start).toHaveBeenCalled());
view.unmount();
cancelPtyTerminalStart("tab-pending");
await act(async () => resolveStart?.(session));
await waitFor(() => expect(mocks.stopAgentLogin).toHaveBeenCalledWith("session-1"));
});
it("does not claim the first StrictMode mount after a detached replay", async () => {
const start = vi.fn(startSession);
const view = render(
<StrictMode>
<PtyTerminalView startSession={start} lifecycle="detach-on-unmount" ownerId="tab-1" />
</StrictMode>,
);
await waitFor(() => expect(mocks.sockets).toHaveLength(1));
expect(start).toHaveBeenCalledTimes(2);
expect(mocks.stopAgentLogin).not.toHaveBeenCalled();
view.unmount();
});
it("stops a superseded StrictMode start in the standard dialog lifecycle", async () => {
const resolvers: Array<(value: typeof session) => void> = [];
const start = vi.fn(
() =>
new Promise<typeof session>((resolve) => {
resolvers.push(resolve);
}),
);
const view = render(
<StrictMode>
<PtyTerminalView startSession={start} />
</StrictMode>,
);
await waitFor(() => expect(start).toHaveBeenCalledTimes(2));
await act(async () => resolvers[0]?.(session));
await waitFor(() => expect(mocks.stopAgentLogin).toHaveBeenCalledWith("session-1"));
await act(async () => resolvers[1]?.(session));
await waitFor(() => expect(mocks.sockets).toHaveLength(1));
view.unmount();
});
it("reports a missing attached session without attempting replacement", async () => {
mocks.getAgentLoginStatus.mockRejectedValueOnce({ status: 404 });
const onStateChange = vi.fn();
const start = vi.fn(startSession);
const view = render(
<PtyTerminalView
startSession={start}
sessionId="missing-session"
lifecycle="detach-on-unmount"
onStateChange={onStateChange}
/>,
);
await waitFor(() =>
expect(onStateChange).toHaveBeenLastCalledWith({
status: "exited",
sessionId: "missing-session",
exitCode: null,
error: "Session is no longer available.",
}),
);
expect(start).not.toHaveBeenCalled();
expect(mocks.sockets).toHaveLength(0);
view.unmount();
});
});
describe("PtyTerminalView resize lifecycle", () => {
it("disarms resize after a WebSocket exit", async () => {
const onStateChange = vi.fn();
const view = render(
<PtyTerminalView startSession={startSession} onStateChange={onStateChange} />,
);
await waitFor(() => expect(mocks.sockets).toHaveLength(1));
act(() => {
mocks.sockets[0]?.onmessage?.({
data: JSON.stringify({ type: "exit", exit_code: 7 }),
} as MessageEvent);
});
expect(onStateChange).toHaveBeenLastCalledWith({
status: "exited",
sessionId: "session-1",
exitCode: 7,
error: null,
});
mocks.resizeAgentLogin.mockClear();
act(() => mocks.resizeCallbacks[0]?.([], {} as ResizeObserver));
expect(mocks.resizeAgentLogin).not.toHaveBeenCalled();
view.unmount();
});
it("disarms resize after the WebSocket closes", async () => {
const view = render(<PtyTerminalView startSession={startSession} />);
await waitFor(() => expect(mocks.sockets).toHaveLength(1));
mocks.sockets[0]?.onclose?.();
act(() => mocks.resizeCallbacks[0]?.([], {} as ResizeObserver));
expect(mocks.resizeAgentLogin).not.toHaveBeenCalled();
view.unmount();
});
});
describe("PtyTerminalView initial input", () => {
it("sends initial input only when a new session is started", async () => {
const view = render(
<PtyTerminalView startSession={startSession} initialInput={"echo NEW_SESSION\n"} />,
);
await waitFor(() => expect(mocks.sockets).toHaveLength(1));
await waitFor(() =>
expect(mocks.sockets[0]?.send).toHaveBeenCalledWith(
new TextEncoder().encode("echo NEW_SESSION\n"),
),
);
view.unmount();
mocks.sockets.length = 0;
mocks.getAgentLoginStatus.mockResolvedValueOnce(session);
const attached = render(
<PtyTerminalView
startSession={startSession}
sessionId="session-1"
lifecycle="detach-on-unmount"
initialInput={"echo SHOULD_NOT_SEND\n"}
/>,
);
await waitFor(() => expect(mocks.sockets).toHaveLength(1));
expect(mocks.sockets[0]?.send).not.toHaveBeenCalled();
attached.unmount();
});
});
@@ -0,0 +1,392 @@
"use client";
import { useEffect, useRef, type MutableRefObject } from "react";
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 { t as translate } from "@/lib/i18n";
import {
agentLoginStreamUrl,
getAgentLoginStatus,
resizeAgentLogin,
stopAgentLogin,
type AgentLoginSession,
type ApiRequestOptions,
} from "@/lib/api";
import { openExternalLink } from "@/lib/desktop/external-links";
import { clearBufferReader, exposeBufferReader } from "@/components/task/terminal-buffer-reader";
import { pendingPtyStarts, type PendingPtyStart } from "./pty-terminal-lifecycle";
export type PtySessionStatus = "connecting" | "running" | "exited" | "error";
export type PtyTerminalState = {
status: PtySessionStatus;
sessionId: string | null;
exitCode: number | null;
error: string | null;
};
export type PtyStartOptions = ApiRequestOptions & { clientId?: string };
export type StartPtySession = (
size: { cols: number; rows: number },
options?: PtyStartOptions,
) => Promise<AgentLoginSession>;
export type PtyTerminalLifecycle = "stop-on-unmount" | "detach-on-unmount";
type PtyTerminalViewProps = {
startSession: StartPtySession;
sessionId?: string | null;
clientId?: string;
/** Stable owner key used to cancel a start when a tab is explicitly closed. */
ownerId?: string;
lifecycle?: PtyTerminalLifecycle;
initialInput?: string;
testIdPrefix?: string;
className?: string;
onStateChange?: (state: PtyTerminalState) => void;
};
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);
term.loadAddon(
new WebLinksAddon((event, uri) => {
event.preventDefault();
void openExternalLink(uri).catch(() => undefined);
}),
);
term.open(container);
exposeBufferReader(container, term);
fit.fit();
return { term, fit };
}
function wireResize(
container: HTMLDivElement,
fitRef: MutableRefObject<FitAddon | null>,
termRef: MutableRefObject<Terminal | null>,
sessionIdRef: MutableRefObject<string | null>,
wsRef: MutableRefObject<WebSocket | null>,
): ResizeObserver {
const observer = new ResizeObserver(() => {
if (!fitRef.current || !termRef.current) return;
try {
fitRef.current.fit();
} catch {
return;
}
const sessionId = sessionIdRef.current;
if (!sessionId) return;
const size = { cols: termRef.current.cols, rows: termRef.current.rows };
void resizeAgentLogin(sessionId, size).catch(() => undefined);
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify({ type: "resize", ...size }));
}
});
observer.observe(container);
return observer;
}
function reportExit(
sessionId: string,
exitCode: number | null,
report: (state: PtyTerminalState) => void,
disarm: () => void,
) {
disarm();
report({ status: "exited", sessionId, exitCode, error: null });
}
function openSessionWebSocket(
sessionId: string,
term: Terminal,
initialInput: string | undefined,
report: (state: PtyTerminalState) => void,
disarm: () => void,
): WebSocket {
const ws = new WebSocket(agentLoginStreamUrl(sessionId));
ws.binaryType = "arraybuffer";
ws.onmessage = (event) => {
if (typeof event.data === "string") {
try {
const message = JSON.parse(event.data) as { type: string; exit_code?: number };
if (message.type === "exit") {
reportExit(sessionId, message.exit_code ?? null, report, disarm);
}
} catch {
// Ignore non-JSON text frames.
}
return;
}
term.write(new Uint8Array(event.data as ArrayBuffer));
};
ws.onerror = () => {
disarm();
report({
status: "error",
sessionId,
exitCode: null,
error: translate("agents:ptyConnectionError"),
});
};
ws.onclose = () => {
disarm();
};
if (initialInput) {
ws.addEventListener("open", () => ws.send(new TextEncoder().encode(initialInput)), {
once: true,
});
}
return ws;
}
type MountArgs = {
container: HTMLDivElement;
startSession: StartPtySession;
initialSessionId: string | null;
clientId?: string;
ownerId?: string;
lifecycle: PtyTerminalLifecycle;
initialInput?: string;
report: (state: PtyTerminalState) => void;
termRef: MutableRefObject<Terminal | null>;
fitRef: MutableRefObject<FitAddon | null>;
wsRef: MutableRefObject<WebSocket | null>;
sessionIdRef: MutableRefObject<string | null>;
mountGenerationRef: MutableRefObject<number>;
};
type LateStartContext = {
mountGeneration: number;
currentGeneration: number;
hasAttachIdentity: boolean;
};
function shouldStopLateStart(
lifecycle: PtyTerminalLifecycle,
pending: PendingPtyStart | null,
cancelled: boolean,
context: LateStartContext,
): boolean {
if (pending?.cancelled) return true;
if (lifecycle !== "stop-on-unmount" || !cancelled) return false;
return !context.hasAttachIdentity || context.mountGeneration === context.currentGeneration;
}
function registerPendingStart(ownerId?: string): PendingPtyStart | null {
if (!ownerId) return null;
const pending: PendingPtyStart = { cancelled: false };
pendingPtyStarts.set(ownerId, pending);
return pending;
}
function clearPendingStart(ownerId: string | undefined, pending: PendingPtyStart | null): void {
if (ownerId && pendingPtyStarts.get(ownerId) === pending) pendingPtyStarts.delete(ownerId);
}
async function resolveSession(
args: MountArgs,
term: Terminal,
isAttached: boolean,
): Promise<AgentLoginSession> {
if (isAttached) return getAgentLoginStatus(args.initialSessionId as string);
return args.startSession(
{ cols: term.cols, rows: term.rows },
args.clientId ? { clientId: args.clientId } : undefined,
);
}
async function stopIfLateStart(
args: MountArgs,
pending: PendingPtyStart | null,
cancelled: boolean,
mountGeneration: number,
sessionId: string,
): Promise<boolean> {
const shouldStop = shouldStopLateStart(args.lifecycle, pending, cancelled, {
mountGeneration,
currentGeneration: args.mountGenerationRef.current,
hasAttachIdentity: Boolean(args.ownerId ?? args.initialSessionId),
});
if (!shouldStop) return false;
await stopAgentLogin(sessionId).catch(() => undefined);
return true;
}
function reportSession(
args: MountArgs,
session: AgentLoginSession,
term: Terminal,
isAttached: boolean,
): void {
args.sessionIdRef.current = session.session_id;
reportSessionState(args, session);
args.wsRef.current = openSessionWebSocket(
session.session_id,
term,
isAttached ? undefined : args.initialInput,
args.report,
() => {
args.sessionIdRef.current = null;
},
);
}
function reportSessionState(args: MountArgs, session: AgentLoginSession): void {
args.report({
status: session.running ? "running" : "exited",
sessionId: session.session_id,
exitCode: session.exit_code ?? null,
error: null,
});
}
function reportSessionError(args: MountArgs, error: unknown, cancelled: boolean): void {
if (cancelled) return;
const isMissing = isNotFoundError(error);
args.report({
status: isMissing ? "exited" : "error",
sessionId: args.initialSessionId,
exitCode: null,
error: isMissing ? translate("agents:sessionUnavailable") : errorMessage(error),
});
}
async function attachOrStart(args: MountArgs, cancelledRef: { value: boolean }): Promise<void> {
const term = args.termRef.current;
if (!term) return;
const pending = registerPendingStart(args.ownerId);
const mountGeneration = ++args.mountGenerationRef.current;
const isAttached = Boolean(args.initialSessionId);
try {
const session = await resolveSession(args, term, isAttached);
if (
await stopIfLateStart(args, pending, cancelledRef.value, mountGeneration, session.session_id)
) {
clearPendingStart(args.ownerId, pending);
return;
}
clearPendingStart(args.ownerId, pending);
// A detached mount that finished after cleanup leaves the session alive
// for its tab owner, but must not attach a WebSocket or xterm instance to
// the disposed StrictMode generation. A later mount will reattach through
// the stable client/session identity.
if (cancelledRef.value) {
// A Quick Chat terminal may detach while its start request is in
// flight. Keep the resolved identity in the tab store so an explicit
// close can still stop the PTY. Do not attach a socket to the disposed
// terminal; a later mount will reattach through the stored identity.
if (args.lifecycle === "detach-on-unmount") reportSessionState(args, session);
return;
}
reportSession(args, session, term, isAttached);
} catch (error) {
clearPendingStart(args.ownerId, pending);
const detachedQuickTab =
args.lifecycle === "detach-on-unmount" && cancelledRef.value && !pending?.cancelled;
reportSessionError(args, error, cancelledRef.value && !detachedQuickTab);
}
}
function isNotFoundError(error: unknown): boolean {
return typeof error === "object" && error !== null && "status" in error
? (error as { status?: unknown }).status === 404
: false;
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function mountSession(args: MountArgs): () => void {
const terminal = createTerminal(args.container);
args.termRef.current = terminal.term;
args.fitRef.current = terminal.fit;
const cancelledRef = { value: false };
void attachOrStart(args, cancelledRef);
const resizeObserver = wireResize(
args.container,
args.fitRef,
args.termRef,
args.sessionIdRef,
args.wsRef,
);
const dataDisposable = terminal.term.onData((data) => {
if (args.wsRef.current?.readyState === WebSocket.OPEN) {
args.wsRef.current.send(new TextEncoder().encode(data));
}
});
return () => {
cancelledRef.value = true;
resizeObserver.disconnect();
dataDisposable.dispose();
if (args.lifecycle === "stop-on-unmount" && args.sessionIdRef.current) {
void stopAgentLogin(args.sessionIdRef.current).catch(() => undefined);
}
args.wsRef.current?.close();
args.wsRef.current = null;
clearBufferReader(args.container);
terminal.term.dispose();
args.termRef.current = null;
args.fitRef.current = null;
};
}
export function PtyTerminalView({
startSession,
sessionId,
clientId,
ownerId,
lifecycle = "stop-on-unmount",
initialInput,
testIdPrefix = "pty",
className = "h-[420px] rounded-md bg-[#0b0b0c] p-2 overflow-hidden",
onStateChange,
}: PtyTerminalViewProps) {
const containerRef = useRef<HTMLDivElement | null>(null);
const termRef = useRef<Terminal | null>(null);
const fitRef = useRef<FitAddon | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const sessionIdRef = useRef<string | null>(null);
const initialSessionIdRef = useRef(sessionId ?? null);
const mountGenerationRef = useRef(0);
const reportRef = useRef(onStateChange);
reportRef.current = onStateChange;
useEffect(() => {
const container = containerRef.current;
if (!container) return undefined;
return mountSession({
container,
startSession,
initialSessionId: initialSessionIdRef.current,
clientId,
ownerId,
lifecycle,
initialInput,
report: (state) => reportRef.current?.(state),
termRef,
fitRef,
wsRef,
sessionIdRef,
mountGenerationRef,
});
}, [clientId, initialInput, lifecycle, ownerId, startSession]);
return <div ref={containerRef} data-testid={`${testIdPrefix}-terminal`} className={className} />;
}
@@ -182,7 +182,8 @@ async function openQuickChatWithAgent(page: Page): Promise<{
await expect(dialog).toBeVisible({ timeout: 10_000 });
const setup = dialog.getByTestId("quick-chat-setup");
if (!(await setup.isVisible({ timeout: 1_000 }).catch(() => false))) {
await dialog.getByLabel("Start new chat").click();
await dialog.getByTestId("quick-chat-add-menu-trigger").click();
await page.getByTestId("quick-chat-new-agent").click();
}
await expect(setup).toBeVisible({ timeout: 5_000 });
@@ -34,8 +34,8 @@ async function openQuickChatWithAgent(page: Page): Promise<Locator> {
const setup = dialog.getByTestId("quick-chat-setup");
if (!(await setup.isVisible({ timeout: 1_000 }).catch(() => false))) {
await dialog.getByLabel("Start new chat").click();
await page.getByRole("menu", { name: "New chat" }).getByText("Quick chat").click();
await dialog.getByTestId("quick-chat-add-menu-trigger").click();
await page.getByTestId("quick-chat-new-agent").click();
}
await expect(setup).toBeVisible({ timeout: 5_000 });
@@ -22,13 +22,13 @@ test.describe("Quick Chat entry points on mobile", () => {
await testPage.waitForLoadState("networkidle");
await assertNoDocumentHorizontalOverflow(testPage);
await testPage.getByTestId("mobile-quick-chat-button").click();
await testPage.getByTestId("mobile-quick-chat-button").tap();
const dialog = testPage.getByRole("dialog", { name: "Quick Chat" });
await expect(dialog.getByTestId("quick-chat-setup")).toBeVisible({ timeout: 10_000 });
await assertNoDocumentHorizontalOverflow(testPage);
await dialog.getByTestId("quick-chat-close").click();
await dialog.getByTestId("quick-chat-close").tap();
await expect(dialog).not.toBeVisible();
});
@@ -59,10 +59,10 @@ test.describe("Quick Chat entry points on mobile", () => {
const session = new SessionPage(testPage);
await session.waitForLoad();
await testPage.getByTestId("mobile-session-menu").click();
await testPage.getByTestId("mobile-session-menu").tap();
const sheet = testPage.getByRole("dialog", { name: "Tasks" });
await expect(sheet).toBeVisible();
await testPage.getByTestId("mobile-sheet-quick-chat").click();
await testPage.getByTestId("mobile-sheet-quick-chat").tap();
const dialog = testPage.getByRole("dialog", { name: "Quick Chat" });
await expect(dialog.getByTestId("quick-chat-setup")).toBeVisible({ timeout: 10_000 });
@@ -34,7 +34,8 @@ test.describe("Quick Chat repository context on mobile", () => {
await expect(dialog.locator(".tiptap.ProseMirror")).toBeVisible({ timeout: 30_000 });
await assertNoDocumentHorizontalOverflow(testPage);
await dialog.getByLabel("Start new chat").click();
await dialog.getByTestId("quick-chat-add-menu-trigger").click();
await testPage.getByTestId("quick-chat-new-agent").click();
await expect(dialog.getByTestId("quick-chat-setup")).toBeVisible({ timeout: 5_000 });
const secondAgentSelector = dialog.getByTestId("agent-profile-selector");
if (await secondAgentSelector.getByText("Select agent", { exact: false }).isVisible()) {
@@ -81,17 +81,19 @@ test.describe("Quick Chat cross-device sync", () => {
// Device A starts a second chat while B is already open and idle. B must
// learn about it from the task event alone — no reload, no navigation.
await dialogA.getByLabel("Start new chat").click();
await dialogA.getByTestId("quick-chat-add-menu-trigger").click();
await testPage.getByTestId("quick-chat-new-agent").click();
await startQuickChatFromSetup(dialogA, testPage);
await expect(dialogA.getByTestId("quick-chat-tab")).toHaveCount(2);
await expect(dialogB.getByTestId("quick-chat-tab")).toHaveCount(2, { timeout: 30_000 });
// Renaming on A must re-label the same tab on B, because the name now
// lives on the backing task rather than in A's localStorage.
// Renaming from the tab context menu on A must re-label the same tab on B,
// because the name now lives on the backing task rather than localStorage.
const renamed = "Renamed from desktop";
const activeTabA = dialogA.getByTestId("quick-chat-tab").last();
await activeTabA.dblclick();
await activeTabA.click({ button: "right" });
await testPage.getByRole("menuitem", { name: "Rename", exact: true }).click();
const renameInput = dialogA.locator('[data-testid="quick-chat-tab"] input');
await expect(renameInput).toBeVisible({ timeout: 5_000 });
await renameInput.fill(renamed);
@@ -122,7 +124,8 @@ test.describe("Quick Chat cross-device sync", () => {
await testPage.setViewportSize(DESKTOP_VIEWPORT);
const dialogA = await openQuickChatWithAgent(testPage);
await dialogA.getByLabel("Start new chat").click();
await dialogA.getByTestId("quick-chat-add-menu-trigger").click();
await testPage.getByTestId("quick-chat-new-agent").click();
await startQuickChatFromSetup(dialogA, testPage);
await expect(dialogA.getByTestId("quick-chat-tab")).toHaveCount(2);
+13 -9
View File
@@ -28,7 +28,8 @@ export async function openQuickChatSetup(page: Page, navigateHome = true): Promi
// If a stale session tab is showing, click "+" to start a fresh setup form.
const setup = dialog.getByTestId("quick-chat-setup");
if (!(await setup.isVisible({ timeout: 1_000 }).catch(() => false))) {
await dialog.getByLabel("Start new chat").click();
await dialog.getByTestId("quick-chat-add-menu-trigger").click();
await page.getByTestId("quick-chat-new-agent").click();
}
await expect(setup).toBeVisible({ timeout: 5_000 });
return dialog;
@@ -36,19 +37,22 @@ export async function openQuickChatSetup(page: Page, navigateHome = true): Promi
export async function selectAgentIfNeeded(dialog: Locator, page: Page) {
const selector = dialog.getByTestId("agent-profile-selector");
if (
await selector
.getByText("Select agent", { exact: false })
.isVisible()
.catch(() => false)
) {
await expect(selector).toBeVisible({ timeout: 10_000 });
await expect(async () => {
const text = await selector.innerText();
if (!text.includes("Select agent")) return;
await selector.click();
await page.getByRole("option").first().click();
}
const option = page.getByRole("option").first();
await expect(option).toBeVisible({ timeout: 2_000 });
await option.click();
await expect(selector).not.toContainText("Select agent", { timeout: 2_000 });
}).toPass({ timeout: 10_000, intervals: [250, 500, 1_000] });
}
export async function startQuickChatFromSetup(dialog: Locator, page: Page) {
await selectAgentIfNeeded(dialog, page);
await expect(dialog.getByTestId("quick-chat-start")).toBeEnabled({ timeout: 10_000 });
await dialog.getByTestId("quick-chat-start").click();
// Wait for chat input to appear AND become editable. Eager init means the
+5 -4
View File
@@ -97,7 +97,8 @@ test.describe("Quick Chat", () => {
await configTab.getByRole("button").first().click();
await expect(configTab).toHaveClass(/bg-background/);
await dialog.getByRole("button", { name: "Start new chat" }).click();
await dialog.getByTestId("quick-chat-add-menu-trigger").click();
await testPage.getByTestId("quick-chat-new-agent").click();
const newSetup = dialog.getByTestId("quick-chat-setup");
await expect(newSetup).toBeVisible();
await expect(newSetup.getByRole("switch", { name: "Configuration chat" })).toHaveCount(0);
@@ -158,7 +159,7 @@ test.describe("Quick Chat", () => {
);
const tab = dialog.getByTestId("quick-chat-tab").last();
const newChat = dialog.getByLabel("Start new chat");
const newChat = dialog.getByTestId("quick-chat-add-menu-trigger");
const tabBox = await tab.boundingBox();
const newChatBox = await newChat.boundingBox();
expect(newChatBox!.x - (tabBox!.x + tabBox!.width)).toBeLessThanOrEqual(8);
@@ -454,8 +455,8 @@ test.describe("Quick Chat", () => {
});
// Create a new tab.
const newChatBtn = dialog.getByLabel("Start new chat");
await newChatBtn.click();
await dialog.getByTestId("quick-chat-add-menu-trigger").click();
await testPage.getByTestId("quick-chat-new-agent").click();
// Setup guidance remains visible for every new chat.
await expect(dialog.getByTestId("quick-chat-setup")).toBeVisible({ timeout: 5_000 });
@@ -67,8 +67,8 @@ async function openQuickChatWithAgent(page: Page): Promise<Locator> {
const setup = dialog.getByTestId("quick-chat-setup");
if (!(await setup.isVisible({ timeout: 1_000 }).catch(() => false))) {
await dialog.getByLabel("Start new chat").click();
await page.getByRole("menu", { name: "New chat" }).getByText("Quick chat").click();
await dialog.getByTestId("quick-chat-add-menu-trigger").click();
await page.getByTestId("quick-chat-new-agent").click();
}
await expect(setup).toBeVisible({ timeout: 5_000 });
@@ -1,109 +1,153 @@
import { test, expect } from "../../fixtures/test-base";
/**
* End-to-end coverage for the host shell PTY - the dialog opened by the
* "Terminal" button on the Agents settings page (and by the auth-recovery
* banner when an agent has no registered LoginCommand).
*
* POST /api/v1/host-shell/start spawns $SHELL under a PTY
* WS /api/v1/agent-login/sessions/:id/stream same routes as the
* login PTY (shared manager)
* POST /api/v1/agent-login/sessions/:id/stop terminates the session
*/
test.describe("host shell PTY", () => {
test("start → run a command → stop", async ({ backend }) => {
test.setTimeout(15_000);
type HostShellSession = {
session_id: string;
agent_id: string;
cmd: string[];
running: boolean;
};
const startRes = await fetch(`${backend.baseUrl}/api/v1/host-shell/start`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ cols: 80, rows: 24 }),
});
expect(startRes.status).toBe(200);
const session = (await startRes.json()) as {
session_id: string;
agent_id: string;
cmd: string[];
running: boolean;
};
expect(session.session_id).toBeTruthy();
expect(session.running).toBe(true);
// The agent_id is the synthetic key the manager uses for shell sessions.
expect(session.agent_id).toBe("_host_shell");
// Cmd should be some shell binary - exact path varies by host.
expect(session.cmd.length).toBeGreaterThan(0);
type HostShellStream = {
ws: WebSocket;
getOutput: () => string;
hasExited: () => boolean;
};
const wsUrl =
backend.baseUrl.replace(/^http/, "ws") +
`/api/v1/agent-login/sessions/${session.session_id}/stream`;
const ws = new WebSocket(wsUrl);
ws.binaryType = "arraybuffer";
async function startHostShell(baseUrl: string, clientId?: string): Promise<HostShellSession> {
const response = await fetch(`${baseUrl}/api/v1/host-shell/start`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ cols: 80, rows: 24, ...(clientId ? { client_id: clientId } : {}) }),
});
expect(response.status).toBe(200);
return (await response.json()) as HostShellSession;
}
let received = "";
let exitedCleanly = false;
ws.addEventListener("message", (ev) => {
if (typeof ev.data === "string") {
try {
const msg = JSON.parse(ev.data);
if (msg.type === "exit") exitedCleanly = true;
} catch {
// ignore
}
return;
async function stopHostShell(baseUrl: string, sessionId: string): Promise<void> {
await fetch(`${baseUrl}/api/v1/agent-login/sessions/${sessionId}/stop`, {
method: "POST",
});
}
async function openHostShellStream(baseUrl: string, sessionId: string): Promise<HostShellStream> {
const wsUrl = baseUrl.replace(/^http/, "ws") + `/api/v1/agent-login/sessions/${sessionId}/stream`;
const ws = new WebSocket(wsUrl);
ws.binaryType = "arraybuffer";
let output = "";
let exited = false;
ws.addEventListener("message", (event) => {
if (typeof event.data === "string") {
try {
if ((JSON.parse(event.data) as { type?: string }).type === "exit") exited = true;
} catch {
// Ignore non-JSON control frames.
}
received += new TextDecoder().decode(new Uint8Array(ev.data as ArrayBuffer));
});
await new Promise<void>((resolve, reject) => {
ws.addEventListener("open", () => resolve(), { once: true });
ws.addEventListener("error", () => reject(new Error("ws error")), { once: true });
});
// Give the shell a moment to print its prompt, then run a marker.
await new Promise((r) => setTimeout(r, 300));
ws.send(new TextEncoder().encode("echo HELLO_FROM_HOST_SHELL\n"));
await waitFor(() => received.includes("HELLO_FROM_HOST_SHELL"), 8_000, "shell echo");
const stopRes = await fetch(
`${backend.baseUrl}/api/v1/agent-login/sessions/${session.session_id}/stop`,
{ method: "POST" },
);
expect(stopRes.status).toBe(200);
await waitFor(() => exitedCleanly, 5_000, "exit message");
ws.close();
return;
}
output += new TextDecoder().decode(new Uint8Array(event.data as ArrayBuffer));
});
test("a second start while one is running returns the same session (idempotent)", async ({
backend,
}) => {
test.setTimeout(10_000);
const first = (await (
await fetch(`${backend.baseUrl}/api/v1/host-shell/start`, {
method: "POST",
body: JSON.stringify({ cols: 80, rows: 24 }),
})
).json()) as { session_id: string };
const second = (await (
await fetch(`${backend.baseUrl}/api/v1/host-shell/start`, {
method: "POST",
body: JSON.stringify({ cols: 80, rows: 24 }),
})
).json()) as { session_id: string };
expect(second.session_id).toBe(first.session_id);
await fetch(`${backend.baseUrl}/api/v1/agent-login/sessions/${first.session_id}/stop`, {
method: "POST",
await new Promise<void>((resolve, reject) => {
ws.addEventListener("open", () => resolve(), { once: true });
ws.addEventListener("error", () => reject(new Error("host shell websocket error")), {
once: true,
});
});
});
return { ws, getOutput: () => output, hasExited: () => exited };
}
async function waitFor(check: () => boolean, timeoutMs: number, label: string) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (check()) return;
await new Promise((r) => setTimeout(r, 50));
}
throw new Error(`Timed out waiting for ${label}`);
await expect.poll(check, { timeout: timeoutMs, message: `Wait for ${label}` }).toBe(true);
}
test.describe("host shell PTY", () => {
test("starts, streams a command, and stops with the legacy singleton identity", async ({
backend,
}) => {
test.setTimeout(15_000);
const session = await startHostShell(backend.baseUrl);
try {
expect(session.session_id).toBeTruthy();
expect(session.agent_id).toBe("_host_shell");
expect(session.running).toBe(true);
expect(session.cmd.length).toBeGreaterThan(0);
const stream = await openHostShellStream(backend.baseUrl, session.session_id);
try {
stream.ws.send(new TextEncoder().encode("echo HELLO_FROM_HOST_SHELL\n"));
await waitFor(
() => stream.getOutput().includes("HELLO_FROM_HOST_SHELL"),
8_000,
"shell echo",
);
await stopHostShell(backend.baseUrl, session.session_id);
await waitFor(() => stream.hasExited(), 5_000, "legacy shell exit");
} finally {
stream.ws.close();
}
} finally {
await stopHostShell(backend.baseUrl, session.session_id);
}
});
test("is idempotent per client while distinct clients get independent PTYs", async ({
backend,
}) => {
test.setTimeout(20_000);
const clientA = "11111111-1111-4111-8111-111111111111";
const clientB = "22222222-2222-4222-8222-222222222222";
const first = await startHostShell(backend.baseUrl, clientA);
let otherClient: HostShellSession | undefined;
let streamA: HostShellStream | undefined;
let streamB: HostShellStream | undefined;
try {
const sameClient = await startHostShell(backend.baseUrl, clientA);
otherClient = await startHostShell(backend.baseUrl, clientB);
expect(sameClient.session_id).toBe(first.session_id);
expect(otherClient.session_id).not.toBe(first.session_id);
expect(otherClient.agent_id).toBe("_host_shell");
streamA = await openHostShellStream(backend.baseUrl, first.session_id);
streamB = await openHostShellStream(backend.baseUrl, otherClient.session_id);
streamA.ws.send(new TextEncoder().encode("echo CLIENT_A_MARKER\n"));
streamB.ws.send(new TextEncoder().encode("echo CLIENT_B_MARKER\n"));
await waitFor(() => streamA!.getOutput().includes("CLIENT_A_MARKER"), 8_000, "client A");
await waitFor(() => streamB!.getOutput().includes("CLIENT_B_MARKER"), 8_000, "client B");
expect(streamA.getOutput()).not.toContain("CLIENT_B_MARKER");
expect(streamB.getOutput()).not.toContain("CLIENT_A_MARKER");
await stopHostShell(backend.baseUrl, first.session_id);
await waitFor(() => streamA!.hasExited(), 5_000, "client A exit");
streamB.ws.send(new TextEncoder().encode("echo CLIENT_B_AFTER_A_STOP\n"));
await waitFor(
() => streamB!.getOutput().includes("CLIENT_B_AFTER_A_STOP"),
8_000,
"client B after A stop",
);
expect(streamB.hasExited()).toBe(false);
} finally {
streamA?.ws.close();
streamB?.ws.close();
await stopHostShell(backend.baseUrl, first.session_id);
if (otherClient) await stopHostShell(backend.baseUrl, otherClient.session_id);
}
});
test("rejects malformed client IDs and preserves omitted-client compatibility", async ({
backend,
}) => {
const invalid = await fetch(`${backend.baseUrl}/api/v1/host-shell/start`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ cols: 80, rows: 24, client_id: "not-a-uuid" }),
});
expect(invalid.status).toBe(400);
const first = await startHostShell(backend.baseUrl);
try {
const second = await startHostShell(backend.baseUrl);
expect(second.session_id).toBe(first.session_id);
} finally {
await stopHostShell(backend.baseUrl, first.session_id);
}
});
});
@@ -47,7 +47,9 @@ async function startRenameViaContextMenu(testPage: Page, node: ReturnType<Page["
// the row is the only one with this className combo; locate via role.
const input = node.getByRole("textbox");
await expect(input).toBeVisible({ timeout: 2_000 });
await expect(input).toBeFocused({ timeout: 2_000 });
// The rename input is focused in an effect after the row switches into
// edit mode; allow a little extra time when the browser is under CI load.
await expect(input).toBeFocused({ timeout: 5_000 });
return input;
}
@@ -15,12 +15,16 @@ import { KanbanPage } from "../../pages/kanban-page";
useRegularMode();
async function expectWheelScrollsListInsideDialog(testPage: Page) {
const list = testPage.locator("[cmdk-list]").first();
// Closed Radix popovers stay mounted, so target the currently visible
// command list instead of whichever list happens to be first in the DOM.
const list = testPage.locator("[cmdk-list]:visible").last();
await expect(list).toBeVisible();
await expect
.poll(() => list.evaluate((el) => Boolean(el.closest('[data-testid="create-task-dialog"]'))))
.toBe(true);
// Selector data arrives asynchronously after the popover opens. Wait for
// the list to lay out its overflow before sending a wheel event.
await expect
.poll(
() =>
@@ -52,6 +56,7 @@ async function expectWheelScrollsListInsideDialog(testPage: Page) {
});
expect(await list.evaluate((el) => el.scrollTop)).toBe(0);
await expect.poll(() => list.boundingBox(), { timeout: 5_000 }).toBeTruthy();
const box = await list.boundingBox();
if (!box) throw new Error("selector list has no bounding box");
await testPage.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
@@ -0,0 +1,180 @@
import { type Page } from "@playwright/test";
import { expect, test } from "../../fixtures/test-base";
import { assertNoDocumentHorizontalOverflow } from "../../helpers/layout-assertions";
async function readQuickTerminalBuffer(page: Page): Promise<string> {
return page.evaluate(() => {
const container = document.querySelector('[data-testid="quick-terminal-terminal"]') as
| (HTMLDivElement & { __xtermReadBuffer?: () => string })
| null;
return container?.__xtermReadBuffer?.() ?? "";
});
}
async function waitForTerminalReady(page: Page) {
await expect
.poll(() => readQuickTerminalBuffer(page), {
timeout: 15_000,
message: "Waiting for mobile Quick Chat terminal shell prompt",
})
.not.toBe("");
}
async function sendCommand(page: Page, command: string, marker: string) {
await page.getByTestId("quick-terminal-terminal").tap();
await page.keyboard.type(`${command} ${marker}`);
await page.keyboard.press("Enter");
await expect
.poll(() => readQuickTerminalBuffer(page), {
timeout: 10_000,
message: `Waiting for mobile terminal marker ${marker}`,
})
.toContain(marker);
}
async function closeSurvivingQuickTerminals(page: Page) {
const dialog = page.getByRole("dialog", { name: "Quick Chat" });
if (!(await dialog.isVisible().catch(() => false))) {
const launcher = page.getByTestId("mobile-quick-terminal-button");
if (await launcher.isVisible().catch(() => false)) await launcher.tap();
}
if (!(await dialog.isVisible().catch(() => false))) return;
const tabs = dialog.locator('[data-testid="quick-terminal-tab"]');
for (let attempts = 0; attempts < 8; attempts += 1) {
const count = await tabs.count();
if (count === 0) return;
await tabs
.nth(count - 1)
.getByRole("button", { name: /^Close Terminal \d+$/ })
.tap();
await expect(tabs).toHaveCount(count - 1, { timeout: 10_000 });
}
}
test.describe("mobile quick terminal tabs", () => {
test("uses a safe full-height surface, touch-safe menu, and contained terminal scroll", async ({
testPage,
}) => {
await testPage.goto("/");
try {
const terminalButton = testPage.getByTestId("mobile-quick-terminal-button");
const quickChatButton = testPage.getByTestId("mobile-quick-chat-button");
await expect(terminalButton).toBeVisible();
await expect(quickChatButton).toBeVisible();
for (const button of [terminalButton, quickChatButton]) {
const buttonBox = await button.boundingBox();
expect(buttonBox).not.toBeNull();
expect(buttonBox!.width).toBeGreaterThanOrEqual(44);
expect(buttonBox!.height).toBeGreaterThanOrEqual(44);
}
await terminalButton.tap();
const dialog = testPage.getByRole("dialog", { name: "Quick Chat" });
await expect(dialog).toBeVisible();
await expect(dialog).toHaveClass(/pt-safe/);
await expect(dialog).toHaveClass(/pb-safe/);
await expect(dialog.getByTestId("quick-terminal-tab-panel")).toBeVisible();
await waitForTerminalReady(testPage);
await sendCommand(testPage, "echo", "MOBILE_TERMINAL_ONE");
const firstClose = dialog
.locator('[data-testid="quick-terminal-tab"][data-terminal-sequence="1"]')
.getByRole("button", { name: "Close Terminal 1" });
const firstCloseBox = await firstClose.boundingBox();
expect(firstCloseBox).not.toBeNull();
expect(firstCloseBox!.width).toBeGreaterThanOrEqual(44);
expect(firstCloseBox!.height).toBeGreaterThanOrEqual(44);
// A mobile reload restores the durable descriptor and reattaches the
// detached PTY before the user creates any additional terminal.
await testPage.reload();
await expect(terminalButton).toBeVisible();
await terminalButton.tap();
await expect(dialog).toBeVisible();
await expect(dialog.locator('[data-testid="quick-terminal-tab"]')).toHaveCount(1);
await expect.poll(() => readQuickTerminalBuffer(testPage)).toContain("MOBILE_TERMINAL_ONE");
const viewport = testPage.viewportSize();
const dialogBox = await dialog.boundingBox();
const terminalBox = await dialog.getByTestId("quick-terminal-terminal").boundingBox();
expect(viewport).not.toBeNull();
expect(dialogBox).not.toBeNull();
expect(terminalBox).not.toBeNull();
expect(dialogBox!.x).toBeGreaterThanOrEqual(-1);
expect(dialogBox!.y).toBeGreaterThanOrEqual(-1);
expect(dialogBox!.x + dialogBox!.width).toBeLessThanOrEqual(viewport!.width + 1);
expect(dialogBox!.y + dialogBox!.height).toBeLessThanOrEqual(viewport!.height + 1);
expect(dialogBox!.width).toBeGreaterThanOrEqual(viewport!.width - 8);
expect(dialogBox!.height).toBeGreaterThanOrEqual(viewport!.height - 8);
expect(terminalBox!.x).toBeGreaterThanOrEqual(dialogBox!.x - 1);
expect(terminalBox!.x + terminalBox!.width).toBeLessThanOrEqual(
dialogBox!.x + dialogBox!.width + 1,
);
expect(terminalBox!.y).toBeGreaterThanOrEqual(dialogBox!.y - 1);
expect(terminalBox!.y + terminalBox!.height).toBeLessThanOrEqual(
dialogBox!.y + dialogBox!.height + 1,
);
await assertNoDocumentHorizontalOverflow(testPage, "mobile shared Quick Chat");
// The plus trigger and bottom-sheet rows retain the touch-safe 44px target.
const addTrigger = dialog.getByTestId("quick-chat-add-menu-trigger");
const triggerBox = await addTrigger.boundingBox();
expect(triggerBox).not.toBeNull();
expect(triggerBox!.width).toBeGreaterThanOrEqual(44);
expect(triggerBox!.height).toBeGreaterThanOrEqual(44);
await addTrigger.tap();
await expect(testPage.getByText("Agents", { exact: true })).toBeVisible();
const menu = testPage.locator('[data-slot="dropdown-menu-content"]');
await expect(menu).toBeVisible();
await expect(menu.getByRole("menuitem", { name: "Terminal 1", exact: true })).toHaveCount(0);
const menuBox = await menu.boundingBox();
expect(menuBox).not.toBeNull();
expect(menuBox!.y).toBeGreaterThan(viewport!.height / 2);
expect(menuBox!.y + menuBox!.height).toBeLessThanOrEqual(viewport!.height + 1);
const newTerminal = testPage.getByTestId("quick-chat-new-terminal");
await expect
.poll(async () => (await newTerminal.boundingBox())?.height ?? 0, {
message: "Waiting for the mobile menu row animation to settle",
})
.toBeGreaterThanOrEqual(44);
await newTerminal.tap();
await expect(dialog.locator('[data-testid="quick-terminal-tab"]')).toHaveCount(2);
await waitForTerminalReady(testPage);
await sendCommand(testPage, "echo", "MOBILE_TERMINAL_TWO");
await sendCommand(testPage, "seq 1 160; echo", "MOBILE_SCROLL_MARKER");
const xtermViewport = dialog
.getByTestId("quick-terminal-terminal")
.locator(".xterm-viewport");
await expect
.poll(() =>
xtermViewport.evaluate((element) => element.scrollHeight >= element.clientHeight),
)
.toBe(true);
await assertNoDocumentHorizontalOverflow(testPage, "mobile shared terminal tabs");
// Explicit close stops one sibling and returns to the first tab.
await dialog
.locator('[data-testid="quick-terminal-tab"][data-terminal-sequence="2"]')
.getByRole("button", { name: "Close Terminal 2" })
.tap();
await expect(dialog.locator('[data-testid="quick-terminal-tab"]')).toHaveCount(1);
await expect.poll(() => readQuickTerminalBuffer(testPage)).toContain("MOBILE_TERMINAL_ONE");
await dialog.getByTestId("quick-chat-close").tap();
await expect(dialog).toBeHidden();
await expect(terminalButton).toBeFocused();
// Reopening through the mobile launcher selects the same terminal tab.
await terminalButton.tap();
await expect(dialog).toBeVisible();
await expect(dialog.locator('[data-testid="quick-terminal-tab"]')).toHaveCount(1);
await expect.poll(() => readQuickTerminalBuffer(testPage)).toContain("MOBILE_TERMINAL_ONE");
await dialog.getByTestId("quick-chat-close").tap();
await expect(dialog).toBeHidden();
} finally {
await closeSurvivingQuickTerminals(testPage);
}
});
});
@@ -0,0 +1,190 @@
import { type Locator, type Page } from "@playwright/test";
import { expect, test } from "../../fixtures/test-base";
import { assertLocatorWithinViewportX } from "../../helpers/layout-assertions";
const QUICK_CHAT_TITLE = "Quick Chat";
async function readQuickTerminalBuffer(page: Page): Promise<string> {
return page.evaluate(() => {
const container = document.querySelector('[data-testid="quick-terminal-terminal"]') as
| (HTMLDivElement & { __xtermReadBuffer?: () => string })
| null;
return container?.__xtermReadBuffer?.() ?? "";
});
}
async function waitForTerminalReady(page: Page) {
await expect
.poll(() => readQuickTerminalBuffer(page), {
timeout: 15_000,
message: "Waiting for Quick Chat terminal shell prompt",
})
.not.toBe("");
}
async function sendMarker(page: Page, marker: string) {
await page.getByTestId("quick-terminal-terminal").click();
await page.keyboard.type(`echo ${marker}`);
await page.keyboard.press("Enter");
await expect
.poll(() => readQuickTerminalBuffer(page), {
timeout: 10_000,
message: `Waiting for terminal marker ${marker}`,
})
.toContain(marker);
}
function terminalTab(dialog: Locator, sequence: number) {
return dialog.locator(`[data-testid="quick-terminal-tab"][data-terminal-sequence="${sequence}"]`);
}
async function closeSurvivingQuickTerminals(page: Page, launcherTestId: string) {
const dialog = page.getByRole("dialog", { name: QUICK_CHAT_TITLE });
if (!(await dialog.isVisible().catch(() => false))) {
const launcher = page.getByTestId(launcherTestId);
if (await launcher.isVisible().catch(() => false)) await launcher.click();
}
if (!(await dialog.isVisible().catch(() => false))) return;
const tabs = dialog.locator('[data-testid="quick-terminal-tab"]');
for (let attempts = 0; attempts < 8; attempts += 1) {
const count = await tabs.count();
if (count === 0) return;
await tabs
.nth(count - 1)
.getByRole("button", { name: /^Close Terminal \d+$/ })
.click();
await expect(tabs).toHaveCount(count - 1, { timeout: 10_000 });
}
}
test.describe("quick terminal tabs", () => {
test("creates, detaches, reuses, switches, and closes independent terminals", async ({
testPage,
}) => {
await testPage.goto("/");
try {
const terminalButton = testPage.getByTestId("sidebar-quick-terminal-shortcut");
const quickChatButton = testPage.getByTestId("sidebar-quick-chat-shortcut");
await expect(terminalButton).toBeVisible();
await expect(quickChatButton).toBeVisible();
expect(
await terminalButton.evaluate((element) =>
element.nextElementSibling?.getAttribute("data-testid"),
),
).toBe("sidebar-quick-chat-shortcut");
await terminalButton.click();
const dialog = testPage.getByRole("dialog", { name: QUICK_CHAT_TITLE });
await expect(dialog).toBeVisible();
await expect(dialog.getByTestId("quick-terminal-tab-panel")).toBeVisible();
await expect(dialog.getByTestId("quick-terminal-terminal")).toBeVisible();
await expect(dialog.getByTestId("host-shell-done")).toHaveCount(0);
await waitForTerminalReady(testPage);
await sendMarker(testPage, "QUICK_TERMINAL_ONE");
await expect(dialog.locator('[data-testid="quick-terminal-tab"]')).toHaveCount(1);
// The descriptor and detached PTY survive a full page reload. The
// launcher must reattach the existing session instead of creating a
// second terminal, including the buffered marker output.
await testPage.reload();
await expect(terminalButton).toBeVisible();
await terminalButton.click();
await expect(dialog).toBeVisible();
await expect(dialog.locator('[data-testid="quick-terminal-tab"]')).toHaveCount(1);
await expect(dialog.getByTestId("quick-terminal-tab-panel")).toBeVisible();
await expect.poll(() => readQuickTerminalBuffer(testPage)).toContain("QUICK_TERMINAL_ONE");
// Dismissing the shared surface detaches the terminal but does not stop it.
await testPage.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await expect(terminalButton).toBeFocused();
await expect(testPage.getByRole("tooltip", { name: "Quick terminal" })).toHaveCount(0);
await terminalButton.click();
await expect(dialog).toBeVisible();
await expect(dialog.locator('[data-testid="quick-terminal-tab"]')).toHaveCount(1);
await expect.poll(() => readQuickTerminalBuffer(testPage)).toContain("QUICK_TERMINAL_ONE");
// The grouped menu's New Terminal action always creates a second PTY.
await dialog.getByTestId("quick-chat-add-menu-trigger").click();
await expect(testPage.getByText("Agents", { exact: true })).toBeVisible();
await expect(testPage.getByText("Terminals", { exact: true })).toBeVisible();
await testPage.getByTestId("quick-chat-new-terminal").click();
await expect(dialog.locator('[data-testid="quick-terminal-tab"]')).toHaveCount(2);
await waitForTerminalReady(testPage);
await sendMarker(testPage, "QUICK_TERMINAL_TWO");
const firstTab = terminalTab(dialog, 1);
const secondTab = terminalTab(dialog, 2);
await firstTab.getByRole("button", { name: "Terminal 1", exact: true }).click();
await expect.poll(() => readQuickTerminalBuffer(testPage)).toContain("QUICK_TERMINAL_ONE");
await secondTab.getByRole("button", { name: "Terminal 2", exact: true }).click();
await expect.poll(() => readQuickTerminalBuffer(testPage)).toContain("QUICK_TERMINAL_TWO");
// Closing one tab stops/removes only that tab and falls back to its sibling.
await secondTab.getByRole("button", { name: "Close Terminal 2" }).click();
await expect(dialog.locator('[data-testid="quick-terminal-tab"]')).toHaveCount(1);
await expect.poll(() => readQuickTerminalBuffer(testPage)).toContain("QUICK_TERMINAL_ONE");
// The chat launcher switches content kind without discarding the terminal.
await testPage.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await quickChatButton.click();
await expect(dialog.getByTestId("quick-chat-setup")).toBeVisible({ timeout: 10_000 });
await expect(firstTab).toBeVisible();
await firstTab.getByRole("button", { name: "Terminal 1", exact: true }).click();
await expect(dialog.getByTestId("quick-terminal-tab-panel")).toBeVisible();
const dialogBox = await dialog.boundingBox();
expect(dialogBox).not.toBeNull();
expect(dialogBox!.width).toBeGreaterThan(820);
expect(dialogBox!.height).toBeGreaterThan(420);
await assertLocatorWithinViewportX(dialog, "desktop shared Quick Chat dialog");
await testPage.keyboard.press("Escape");
await expect(dialog).toBeHidden();
} finally {
await closeSurvivingQuickTerminals(testPage, "sidebar-quick-terminal-shortcut");
}
});
test("keeps tablet launcher order and 44px hit targets", async ({ tabletTestPage }) => {
const testPage = tabletTestPage;
await testPage.goto("/");
try {
const terminalButton = testPage.getByTestId("tablet-quick-terminal-button");
const quickChatButton = testPage.getByTestId("tablet-quick-chat-button");
await expect(terminalButton).toBeVisible();
await expect(quickChatButton).toBeVisible();
expect(
await terminalButton.evaluate((element) =>
element.nextElementSibling?.getAttribute("data-testid"),
),
).toBe("tablet-quick-chat-button");
for (const button of [terminalButton, quickChatButton]) {
const box = await button.boundingBox();
expect(box).not.toBeNull();
expect(box!.width).toBeGreaterThanOrEqual(44);
expect(box!.height).toBeGreaterThanOrEqual(44);
}
await terminalButton.click();
const dialog = testPage.getByRole("dialog", { name: QUICK_CHAT_TITLE });
await expect(dialog).toBeVisible();
await expect(dialog.getByTestId("quick-terminal-terminal")).toBeVisible();
const dialogBox = await dialog.boundingBox();
expect(dialogBox).not.toBeNull();
expect(dialogBox!.width).toBeGreaterThan(500);
expect(dialogBox!.height).toBeGreaterThan(420);
await assertLocatorWithinViewportX(dialog, "tablet shared Quick Chat dialog");
await testPage.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await expect(terminalButton).toBeFocused();
} finally {
await closeSurvivingQuickTerminals(testPage, "tablet-quick-terminal-button");
}
});
});
@@ -1,5 +1,6 @@
import { useCallback } from "react";
import { useAppStore } from "@/components/state-provider";
import { captureQuickChatLauncherFocus } from "@/components/quick-chat/quick-chat-focus";
import type { QuickChatSessionKind } from "@/lib/state/slices/ui/types";
/**
@@ -16,6 +17,7 @@ export function useQuickChatLauncher(
const handleOpenQuickChat = useCallback(() => {
if (!workspaceId) return;
captureQuickChatLauncherFocus();
// If there's an existing session, open it. Otherwise just open the modal with agent picker
const matchingSessions = quickChatSessions.filter(
+16 -1
View File
@@ -2,11 +2,13 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
const mockListQuickChatSessions = vi.hoisted(() => vi.fn());
const mockListQuickTerminalTabs = vi.hoisted(() => vi.fn());
const mockUpdateTask = vi.hoisted(() => vi.fn());
const mockState = vi.hoisted(() => ({
value: {} as {
connection: { status: string };
syncQuickChatSessions: unknown;
syncQuickTerminalTabs: unknown;
setTaskSession: unknown;
},
}));
@@ -19,6 +21,11 @@ vi.mock("@/lib/api/domains/workspace-api", () => ({
listQuickChatSessions: (...args: unknown[]) => mockListQuickChatSessions(...args),
}));
vi.mock("@/lib/api/domains/quick-terminal-api", () => ({
listQuickTerminalTabs: (...args: unknown[]) => mockListQuickTerminalTabs(...args),
toQuickTerminalTab: (tab: unknown) => tab,
}));
vi.mock("@/lib/api/domains/kanban-api", () => ({
updateTask: (...args: unknown[]) => mockUpdateTask(...args),
}));
@@ -27,10 +34,16 @@ import { useQuickChatResync } from "./use-quick-chat-resync";
import { getStoredQuickChatNames, setStoredQuickChatName } from "@/lib/local-storage";
const syncQuickChatSessions = vi.fn();
const syncQuickTerminalTabs = vi.fn();
const setTaskSession = vi.fn();
function setConnection(status: string) {
mockState.value = { connection: { status }, syncQuickChatSessions, setTaskSession };
mockState.value = {
connection: { status },
syncQuickChatSessions,
syncQuickTerminalTabs,
setTaskSession,
};
}
beforeEach(() => {
@@ -51,6 +64,7 @@ beforeEach(() => {
],
task_sessions: [{ id: "session-1", task_id: "task-1" }],
});
mockListQuickTerminalTabs.mockResolvedValue({ tabs: [] });
});
describe("useQuickChatResync", () => {
@@ -68,6 +82,7 @@ describe("useQuickChatResync", () => {
agentProfileId: "agent-1",
},
]);
expect(syncQuickTerminalTabs).toHaveBeenCalledWith("ws-1", []);
});
// A tab without its session row renders but cannot subscribe or accept
+6 -3
View File
@@ -3,6 +3,7 @@
import { useEffect, useRef } from "react";
import { useAppStore } from "@/components/state-provider";
import { listQuickChatSessions } from "@/lib/api/domains/workspace-api";
import { listQuickTerminalTabs, toQuickTerminalTab } from "@/lib/api/domains/quick-terminal-api";
import { getStoredQuickChatNames } from "@/lib/local-storage";
import { toQuickChatSessions } from "@/lib/quick-chat/map-sessions";
import { migrateStoredQuickChatNames } from "@/lib/quick-chat/rename";
@@ -19,6 +20,7 @@ import { migrateStoredQuickChatNames } from "@/lib/quick-chat/rename";
export function useQuickChatResync(workspaceId: string | null): void {
const connectionStatus = useAppStore((state) => state.connection.status);
const syncQuickChatSessions = useAppStore((state) => state.syncQuickChatSessions);
const syncQuickTerminalTabs = useAppStore((state) => state.syncQuickTerminalTabs);
const setTaskSession = useAppStore((state) => state.setTaskSession);
// Resync once per connection, not on every unrelated status re-render.
const lastSyncedConnection = useRef<string | null>(null);
@@ -32,8 +34,8 @@ export function useQuickChatResync(workspaceId: string | null): void {
lastSyncedConnection.current = workspaceId;
let cancelled = false;
listQuickChatSessions(workspaceId)
.then((response) => {
Promise.all([listQuickChatSessions(workspaceId), listQuickTerminalTabs(workspaceId)])
.then(([response, terminalResponse]) => {
if (cancelled) return;
const sessions = toQuickChatSessions(response.sessions);
// Store the session rows before the tabs. A tab without its row cannot
@@ -43,6 +45,7 @@ export function useQuickChatResync(workspaceId: string | null): void {
setTaskSession(taskSession);
}
syncQuickChatSessions(workspaceId, sessions);
syncQuickTerminalTabs(workspaceId, terminalResponse.tabs.map(toQuickTerminalTab));
// Renames made before names were stored server-side live only in this
// browser; push them up once so they reach the user's other devices.
void migrateStoredQuickChatNames(sessions, getStoredQuickChatNames());
@@ -55,5 +58,5 @@ export function useQuickChatResync(workspaceId: string | null): void {
return () => {
cancelled = true;
};
}, [connectionStatus, workspaceId, setTaskSession, syncQuickChatSessions]);
}, [connectionStatus, workspaceId, setTaskSession, syncQuickChatSessions, syncQuickTerminalTabs]);
}
@@ -0,0 +1,34 @@
import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
const reuseOrCreateQuickTerminal = vi.fn();
let state = { reuseOrCreateQuickTerminal };
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (value: typeof state) => unknown) => selector(state),
}));
import { useQuickTerminalLauncher } from "./use-quick-terminal-launcher";
describe("useQuickTerminalLauncher", () => {
beforeEach(() => {
reuseOrCreateQuickTerminal.mockReset();
state = { reuseOrCreateQuickTerminal };
});
it("reuses or creates the terminal for the requested workspace", () => {
const { result } = renderHook(() => useQuickTerminalLauncher("workspace-1"));
act(() => result.current());
expect(reuseOrCreateQuickTerminal).toHaveBeenCalledWith("workspace-1");
});
it("does not launch without a workspace", () => {
const { result } = renderHook(() => useQuickTerminalLauncher(null));
act(() => result.current());
expect(reuseOrCreateQuickTerminal).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,16 @@
"use client";
import { useCallback } from "react";
import { useAppStore } from "@/components/state-provider";
import { captureQuickChatLauncherFocus } from "@/components/quick-chat/quick-chat-focus";
/** Opens or re-selects a workspace's terminal in the shared Quick Chat surface. */
export function useQuickTerminalLauncher(workspaceId?: string | null) {
const reuseOrCreateQuickTerminal = useAppStore((state) => state.reuseOrCreateQuickTerminal);
return useCallback(() => {
if (!workspaceId) return;
captureQuickChatLauncherFocus();
reuseOrCreateQuickTerminal(workspaceId);
}, [reuseOrCreateQuickTerminal, workspaceId]);
}
@@ -0,0 +1,84 @@
import { getBackendConfig } from "@/lib/config";
import { fetchJson, type ApiRequestOptions } from "../client";
export type AgentLoginSession = {
session_id: string;
agent_id: string;
cmd: string[];
running: boolean;
started_at: string;
finished_at?: string;
exit_code?: number;
};
export type HostShellStartOptions = ApiRequestOptions & {
/** Stable browser-local identity used to isolate Quick Chat terminal tabs. */
clientId?: string;
};
export async function startAgentLogin(
agentName: string,
size: { cols: number; rows: number },
options?: ApiRequestOptions,
): Promise<AgentLoginSession> {
return fetchJson<AgentLoginSession>(`/api/v1/agent-login/agents/${agentName}/start`, {
...options,
init: {
method: "POST",
body: JSON.stringify(size),
...(options?.init ?? {}),
},
});
}
export async function stopAgentLogin(sessionID: string): Promise<void> {
await fetchJson<{ ok: boolean }>(`/api/v1/agent-login/sessions/${sessionID}/stop`, {
init: { method: "POST" },
});
}
export async function resizeAgentLogin(
sessionID: string,
size: { cols: number; rows: number },
): Promise<void> {
await fetchJson<{ ok: boolean }>(`/api/v1/agent-login/sessions/${sessionID}/resize`, {
init: { method: "POST", body: JSON.stringify(size) },
});
}
/**
* Build the bi-directional WS URL for streaming a login session.
* Derives the host from the backend config (NOT window.location) so dev mode
* — where the browser is on :37429 and the API is on :38429 — routes to the
* Go backend, not the web dev server.
*/
export function agentLoginStreamUrl(sessionID: string): string {
const { apiBaseUrl } = getBackendConfig();
const url = new URL(apiBaseUrl);
const proto = url.protocol === "https:" ? "wss:" : "ws:";
return `${proto}//${url.host}/api/v1/agent-login/sessions/${sessionID}/stream`;
}
/**
* Start a plain host shell PTY (spawns $SHELL, or bash/sh fallback). Reuses
* the same session manager as agent-login, so stop/resize/stream all use the
* same session-ID-based endpoints.
*/
export async function startHostShell(
size: { cols: number; rows: number },
options?: HostShellStartOptions,
): Promise<AgentLoginSession> {
const { clientId, ...requestOptions } = options ?? {};
return fetchJson<AgentLoginSession>("/api/v1/host-shell/start", {
...requestOptions,
init: {
method: "POST",
body: JSON.stringify({ ...size, ...(clientId ? { client_id: clientId } : {}) }),
...(requestOptions.init ?? {}),
},
});
}
export async function getAgentLoginStatus(sessionID: string): Promise<AgentLoginSession> {
return fetchJson<AgentLoginSession>(`/api/v1/agent-login/sessions/${sessionID}/status`);
}
@@ -0,0 +1,103 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/config", () => ({
getBackendConfig: () => ({ apiBaseUrl: "http://api.test" }),
}));
import {
createQuickTerminalTab,
deleteQuickTerminalTab,
listQuickTerminalTabs,
toQuickTerminalTab,
updateQuickTerminalTab,
} from "./quick-terminal-api";
type FetchInput = Parameters<typeof fetch>[0];
type FetchInit = Parameters<typeof fetch>[1];
const fetchSpy = vi.fn<(...args: [FetchInput, FetchInit?]) => Promise<Response>>();
const DESCRIPTORS_URL = "http://api.test/api/v1/quick-terminal-tabs";
const WORKSPACE_ID = "workspace-1";
beforeEach(() => {
fetchSpy.mockReset();
vi.stubGlobal("fetch", fetchSpy);
});
afterEach(() => vi.unstubAllGlobals());
function jsonResponse(body: unknown): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
function lastCall(): { url: string; init: FetchInit | undefined } {
const call = fetchSpy.mock.calls.at(-1);
if (!call) throw new Error("expected fetch to have been called");
return { url: String(call[0]), init: call[1] };
}
describe("quick terminal descriptor api", () => {
it("lists descriptors by workspace and maps the wire shape", async () => {
fetchSpy.mockResolvedValueOnce(
jsonResponse({
tabs: [
{
tabId: "tab-1",
workspaceId: WORKSPACE_ID,
sessionId: "session-1",
sequence: 2,
status: "running",
error: "",
},
],
}),
);
const response = await listQuickTerminalTabs("workspace 1");
expect(lastCall().url).toBe(
"http://api.test/api/v1/quick-terminal-tabs?workspace_id=workspace+1",
);
expect(response.tabs).toHaveLength(1);
expect(toQuickTerminalTab(response.tabs[0])).toEqual({
tabId: "tab-1",
workspaceId: WORKSPACE_ID,
sessionId: "session-1",
sequence: 2,
status: "running",
});
});
it("persists create, lifecycle, and delete requests independently of chat APIs", async () => {
const tabId = "6f2d7f2d-0d0c-4c9b-8b73-1c53a5ed5b6b";
fetchSpy.mockResolvedValueOnce(jsonResponse({ tabId }));
await createQuickTerminalTab(tabId, WORKSPACE_ID);
expect(lastCall().url).toBe(DESCRIPTORS_URL);
expect(lastCall().init?.method).toBe("POST");
expect(JSON.parse(String(lastCall().init?.body))).toEqual({
tab_id: tabId,
workspace_id: WORKSPACE_ID,
});
fetchSpy.mockResolvedValueOnce(jsonResponse({ tabId, status: "running" }));
await updateQuickTerminalTab(tabId, {
sessionId: "session-1",
status: "running",
});
expect(lastCall().url).toBe(`${DESCRIPTORS_URL}/${tabId}`);
expect(lastCall().init?.method).toBe("PATCH");
expect(JSON.parse(String(lastCall().init?.body))).toEqual({
session_id: "session-1",
status: "running",
exit_code: null,
error: "",
});
fetchSpy.mockResolvedValueOnce(jsonResponse({ ok: true }));
await deleteQuickTerminalTab(tabId);
expect(lastCall().url).toBe(`${DESCRIPTORS_URL}/${tabId}`);
expect(lastCall().init?.method).toBe("DELETE");
});
});
@@ -0,0 +1,91 @@
import { fetchJson, type ApiRequestOptions } from "../client";
import type { QuickTerminalStatus, QuickTerminalTab } from "@/lib/state/slices/ui/types";
export type QuickTerminalTabResponse = {
tabId: string;
workspaceId: string;
sessionId: string | null;
sequence: number;
status: QuickTerminalStatus;
exitCode?: number;
error?: string;
};
export type ListQuickTerminalTabsResponse = {
tabs: QuickTerminalTabResponse[];
};
export type QuickTerminalLifecycleUpdate = {
sessionId?: string | null;
status: QuickTerminalStatus;
exitCode?: number | null;
error?: string | null;
};
export async function listQuickTerminalTabs(
workspaceId: string,
options?: ApiRequestOptions,
): Promise<ListQuickTerminalTabsResponse> {
const params = new URLSearchParams({ workspace_id: workspaceId });
return fetchJson<ListQuickTerminalTabsResponse>(
`/api/v1/quick-terminal-tabs?${params.toString()}`,
options,
);
}
export async function createQuickTerminalTab(
tabId: string,
workspaceId: string,
options?: ApiRequestOptions,
): Promise<QuickTerminalTabResponse> {
return fetchJson<QuickTerminalTabResponse>("/api/v1/quick-terminal-tabs", {
...options,
init: {
method: "POST",
body: JSON.stringify({ tab_id: tabId, workspace_id: workspaceId }),
...(options?.init ?? {}),
},
});
}
export async function updateQuickTerminalTab(
tabId: string,
update: QuickTerminalLifecycleUpdate,
options?: ApiRequestOptions,
): Promise<QuickTerminalTabResponse> {
return fetchJson<QuickTerminalTabResponse>(`/api/v1/quick-terminal-tabs/${tabId}`, {
...options,
init: {
method: "PATCH",
body: JSON.stringify({
session_id: update.sessionId ?? null,
status: update.status,
exit_code: update.exitCode ?? null,
error: update.error ?? "",
}),
...(options?.init ?? {}),
},
});
}
export async function deleteQuickTerminalTab(
tabId: string,
options?: ApiRequestOptions,
): Promise<void> {
await fetchJson<{ ok: boolean }>(`/api/v1/quick-terminal-tabs/${tabId}`, {
...options,
init: { method: "DELETE", ...(options?.init ?? {}) },
});
}
export function toQuickTerminalTab(tab: QuickTerminalTabResponse): QuickTerminalTab {
return {
tabId: tab.tabId,
workspaceId: tab.workspaceId,
sessionId: tab.sessionId,
sequence: tab.sequence,
status: tab.status,
...(tab.exitCode === undefined ? {} : { exitCode: tab.exitCode }),
...(tab.error ? { error: tab.error } : {}),
};
}
@@ -7,6 +7,7 @@ vi.mock("@/lib/config", () => ({
import {
fetchMessageQueueSettings,
fetchSleepInhibitionSettings,
startHostShell,
updateMessageQueueSettings,
updateSleepInhibitionSettings,
} from "./settings-api";
@@ -103,3 +104,34 @@ describe("sleep inhibition settings api", () => {
expect(lastCall().init?.body).toBe(JSON.stringify({ enabled: true }));
});
});
describe("startHostShell", () => {
it("serializes a client id alongside the terminal size", async () => {
const clientId = "6f2d7f2d-0d0c-4c9b-8b73-1c53a5ed5b6b";
fetchSpy.mockResolvedValueOnce(
jsonResponse({
session_id: "session-1",
agent_id: "_host_shell",
cmd: ["/bin/bash"],
running: true,
started_at: "2026-08-04T00:00:00Z",
}),
);
await startHostShell({ cols: 80, rows: 24 }, { clientId });
expect(JSON.parse(String(lastCall().init?.body))).toEqual({
cols: 80,
rows: 24,
client_id: clientId,
});
});
it("preserves the legacy request shape without a client id", async () => {
fetchSpy.mockResolvedValueOnce(jsonResponse({}));
await startHostShell({ cols: 80, rows: 24 });
const fetchCall = vi.mocked(fetch).mock.calls[0];
expect(JSON.parse(String(fetchCall?.[1]?.body))).toEqual({ cols: 80, rows: 24 });
});
});
+9 -72
View File
@@ -31,6 +31,15 @@ export {
fetchSleepInhibitionSettings,
updateSleepInhibitionSettings,
} from "./sleep-inhibition-api";
export {
agentLoginStreamUrl,
getAgentLoginStatus,
resizeAgentLogin,
startAgentLogin,
startHostShell,
stopAgentLogin,
} from "./host-shell-api";
export type { AgentLoginSession, HostShellStartOptions } from "./host-shell-api";
// User settings
export async function fetchUserSettings(options?: ApiRequestOptions) {
@@ -317,78 +326,6 @@ export async function getInstallJob(
return fetchJson<InstallJob>(`/api/v1/agent-install/jobs/${jobId}`, options);
}
export type AgentLoginSession = {
session_id: string;
agent_id: string;
cmd: string[];
running: boolean;
started_at: string;
finished_at?: string;
exit_code?: number;
};
export async function startAgentLogin(
agentName: string,
size: { cols: number; rows: number },
options?: ApiRequestOptions,
): Promise<AgentLoginSession> {
return fetchJson<AgentLoginSession>(`/api/v1/agent-login/agents/${agentName}/start`, {
...options,
init: {
method: "POST",
body: JSON.stringify(size),
...(options?.init ?? {}),
},
});
}
export async function stopAgentLogin(sessionID: string): Promise<void> {
await fetchJson<{ ok: boolean }>(`/api/v1/agent-login/sessions/${sessionID}/stop`, {
init: { method: "POST" },
});
}
export async function resizeAgentLogin(
sessionID: string,
size: { cols: number; rows: number },
): Promise<void> {
await fetchJson<{ ok: boolean }>(`/api/v1/agent-login/sessions/${sessionID}/resize`, {
init: { method: "POST", body: JSON.stringify(size) },
});
}
/**
* Build the bi-directional WS URL for streaming a login session.
* Derives the host from the backend config (NOT window.location) so dev mode
* — where the browser is on :37429 and the API is on :38429 — routes to the
* Go backend, not the web dev server.
*/
export function agentLoginStreamUrl(sessionID: string): string {
const { apiBaseUrl } = getBackendConfig();
const url = new URL(apiBaseUrl);
const proto = url.protocol === "https:" ? "wss:" : "ws:";
return `${proto}//${url.host}/api/v1/agent-login/sessions/${sessionID}/stream`;
}
/**
* Start a plain host shell PTY (spawns $SHELL, or bash/sh fallback). Reuses
* the same session manager as agent-login, so stop/resize/stream all use the
* same session-ID-based endpoints.
*/
export async function startHostShell(
size: { cols: number; rows: number },
options?: ApiRequestOptions,
): Promise<AgentLoginSession> {
return fetchJson<AgentLoginSession>("/api/v1/host-shell/start", {
...options,
init: {
method: "POST",
body: JSON.stringify(size),
...(options?.init ?? {}),
},
});
}
export async function createCustomTUIAgent(
payload: { display_name: string; model?: string; command: string; description?: string },
options?: ApiRequestOptions,
+1
View File
@@ -6,6 +6,7 @@ export * from "./domains/kanban-api";
export * from "./domains/session-api";
export * from "./domains/workspace-api";
export * from "./domains/settings-api";
export * from "./domains/quick-terminal-api";
export * from "./domains/agent-update-api";
export * from "./domains/process-api";
export * from "./domains/workflow-api";
@@ -7,7 +7,7 @@ function source(relativePath: string): string {
describe("programmatic external links", () => {
it.each([
["../../components/settings/pty-terminal-dialog.tsx", "PTY login links"],
["../../components/settings/pty-terminal-view.tsx", "PTY terminal links"],
["../../hooks/use-terminal-link-handler.ts", "terminal links"],
["../../components/task/browser-panel.tsx", "browser panel tabs"],
])("routes %s through the shared desktop-aware opener", (path) => {
@@ -7,6 +7,8 @@ import { defaultState, mergeInitialState } from "@/lib/state/default-state";
import type { AppState } from "@/lib/state/store";
import type { MCPAttachmentHistory } from "@/lib/state/slices/session-runtime/types";
const TERMINAL_TAB_ID = "terminal-1";
function makeDraft(): AppState {
// hydrateUI only touches UI-slice fields; an empty object cast satisfies
// the rest without dragging the full AppState shape into this test.
@@ -125,6 +127,38 @@ describe("hydrateUI — typed quick chat sessions", () => {
expect(result.quickChat.sessions.map((s) => s.name)).toEqual(["Renamed A", "Original B"]);
});
});
describe("hydrateUI — quick chat lifecycle", () => {
it("restores server-owned terminal tabs during a fresh hydration", () => {
const result = produce(makeDraft(), (draft: Draft<AppState>) => {
hydrateUI(draft, {
quickChat: {
isOpen: false,
activeSessionId: null,
sessions: [],
terminalTabs: [
{
tabId: TERMINAL_TAB_ID,
workspaceId: "ws-1",
sessionId: "pty-1",
sequence: 1,
status: "running",
},
],
activeKind: "terminal",
activeTerminalTabId: TERMINAL_TAB_ID,
lastTerminalTabIdByWorkspace: { "ws-1": TERMINAL_TAB_ID },
},
});
});
expect(result.quickChat.terminalTabs).toEqual([
expect.objectContaining({ tabId: TERMINAL_TAB_ID, sessionId: "pty-1" }),
]);
expect(result.quickChat.activeKind).toBe("terminal");
expect(result.quickChat.activeTerminalTabId).toBe(TERMINAL_TAB_ID);
});
it("clears stale quick chat sessions when the backend returns none", () => {
const result = produce(makeDraft(), (draft: Draft<AppState>) => {
@@ -134,6 +168,10 @@ describe("hydrateUI — typed quick chat sessions", () => {
sessions: [
{ sessionId: "stale-session", workspaceId: "ws-1", name: "Stale", kind: "chat" },
],
terminalTabs: [],
activeKind: "conversation",
activeTerminalTabId: null,
lastTerminalTabIdByWorkspace: {},
};
hydrateUI(draft, {
quickChat: {
@@ -148,6 +186,78 @@ describe("hydrateUI — typed quick chat sessions", () => {
expect(result.quickChat.isOpen).toBe(false);
expect(result.quickChat.activeSessionId).toBeNull();
});
it("preserves browser-local terminal tabs when server conversations resync", () => {
const result = produce(makeDraft(), (draft: Draft<AppState>) => {
draft.quickChat = {
isOpen: true,
activeSessionId: "chat-1",
sessions: [{ sessionId: "chat-1", workspaceId: "ws-1", kind: "chat" }],
terminalTabs: [
{
tabId: TERMINAL_TAB_ID,
workspaceId: "ws-1",
sessionId: "pty-1",
sequence: 1,
status: "running",
},
],
activeKind: "terminal",
activeTerminalTabId: TERMINAL_TAB_ID,
lastTerminalTabIdByWorkspace: { "ws-1": TERMINAL_TAB_ID },
};
hydrateUI(draft, {
quickChat: {
isOpen: false,
activeSessionId: null,
sessions: [],
},
});
});
expect(result.quickChat.sessions).toEqual([]);
expect(result.quickChat.terminalTabs).toHaveLength(1);
expect(result.quickChat.activeKind).toBe("terminal");
expect(result.quickChat.activeTerminalTabId).toBe(TERMINAL_TAB_ID);
expect(result.quickChat.isOpen).toBe(true);
});
});
describe("hydrateUI — terminal descriptor reconciliation", () => {
it("treats an empty server terminal list as authoritative during hydration", () => {
const result = produce(makeDraft(), (draft: Draft<AppState>) => {
draft.quickChat = {
isOpen: true,
activeSessionId: null,
sessions: [],
terminalTabs: [
{
tabId: TERMINAL_TAB_ID,
workspaceId: "ws-1",
sessionId: "pty-stale",
sequence: 1,
status: "running",
},
],
activeKind: "terminal",
activeTerminalTabId: TERMINAL_TAB_ID,
lastTerminalTabIdByWorkspace: { "ws-1": TERMINAL_TAB_ID },
};
hydrateUI(draft, {
quickChat: {
isOpen: false,
activeSessionId: null,
sessions: [],
terminalTabs: [],
},
});
});
expect(result.quickChat.terminalTabs).toEqual([]);
expect(result.quickChat.activeKind).toBe("conversation");
expect(result.quickChat.activeTerminalTabId).toBeNull();
expect(result.quickChat.isOpen).toBe(false);
});
});
describe("mergeInitialState — quick chat name overlay", () => {
+87 -12
View File
@@ -1,7 +1,10 @@
import type { Draft } from "immer";
import type { AppState, HydrationState } from "../store";
import { migrateSidebarViewDraft, migrateView } from "../slices/ui/ui-slice";
import { applyStoredQuickChatNames } from "@/lib/state/slices/ui/quick-chat-sync";
import {
applyStoredQuickChatNames,
reconcileQuickTerminalTabs,
} from "@/lib/state/slices/ui/quick-chat-sync";
import { deepMerge, mergeSessionMap, mergeLoadingState } from "./merge-strategies";
/**
@@ -231,22 +234,15 @@ export function hydrateUI(draft: Draft<AppState>, state: HydrationState): void {
if (state.quickChat) {
// Merge quick chat sessions, preserving isOpen from client
if (state.quickChat.sessions) {
const previousSessions = draft.quickChat.sessions;
const previousActiveSessionId = draft.quickChat.activeSessionId;
// Local renames live in localStorage and override the SSR-provided name
// (which derives from the backend task title). Apply on every hydration
// so a renamed chat keeps its local name across reloads and tab switches.
draft.quickChat.sessions = applyStoredQuickChatNames(state.quickChat.sessions);
// Validate activeSessionId exists in sessions after merge
if (
draft.quickChat.activeSessionId &&
!draft.quickChat.sessions.some((s) => s.sessionId === draft.quickChat.activeSessionId)
) {
draft.quickChat.activeSessionId = draft.quickChat.sessions[0]?.sessionId ?? null;
}
// Close quick chat if no sessions remain
if (draft.quickChat.sessions.length === 0) {
draft.quickChat.isOpen = false;
}
restoreQuickChatSelection(draft, previousSessions, previousActiveSessionId);
}
if (state.quickChat.terminalTabs) hydrateQuickTerminalState(draft, state.quickChat);
}
if (state.connection) {
const { status: _status, ...rest } = state.connection || {};
@@ -256,6 +252,85 @@ export function hydrateUI(draft: Draft<AppState>, state: HydrationState): void {
}
}
function hydrateQuickTerminalState(
draft: Draft<AppState>,
quickChat: NonNullable<HydrationState["quickChat"]>,
): void {
const terminalTabs = quickChat.terminalTabs;
if (!terminalTabs) return;
const workspaceIds = new Set(terminalTabs.map((tab) => tab.workspaceId));
for (const tab of draft.quickChat.terminalTabs) workspaceIds.add(tab.workspaceId);
for (const session of quickChat.sessions ?? []) workspaceIds.add(session.workspaceId);
for (const workspaceId of workspaceIds) {
const tabs = terminalTabs.filter((tab) => tab.workspaceId === workspaceId);
draft.quickChat = reconcileQuickTerminalTabs(draft.quickChat, workspaceId, tabs);
}
const activeTerminalTabId = quickChat.activeTerminalTabId;
if (
quickChat.activeKind === "terminal" &&
activeTerminalTabId &&
draft.quickChat.terminalTabs.some((tab) => tab.tabId === activeTerminalTabId)
) {
draft.quickChat.activeKind = "terminal";
draft.quickChat.activeTerminalTabId = activeTerminalTabId;
}
for (const [workspaceId, tabId] of Object.entries(quickChat.lastTerminalTabIdByWorkspace ?? {})) {
if (draft.quickChat.terminalTabs.some((tab) => tab.tabId === tabId)) {
draft.quickChat.lastTerminalTabIdByWorkspace[workspaceId] = tabId;
}
}
}
function restoreQuickChatSelection(
draft: Draft<AppState>,
previousSessions: AppState["quickChat"]["sessions"],
previousActiveSessionId: string | null,
): void {
draft.quickChat.terminalTabs ??= [];
draft.quickChat.activeKind ??= "conversation";
draft.quickChat.activeTerminalTabId ??= null;
draft.quickChat.lastTerminalTabIdByWorkspace ??= {};
if (draft.quickChat.activeKind === "terminal") {
if (
draft.quickChat.activeTerminalTabId &&
draft.quickChat.terminalTabs.some((tab) => tab.tabId === draft.quickChat.activeTerminalTabId)
) {
return;
}
draft.quickChat.activeKind = "conversation";
}
if (
draft.quickChat.activeSessionId &&
draft.quickChat.sessions.some(
(session) => session.sessionId === draft.quickChat.activeSessionId,
)
) {
return;
}
const previousWorkspaceId = previousSessions.find(
(session) => session.sessionId === previousActiveSessionId,
)?.workspaceId;
const fallbackSession =
draft.quickChat.sessions.find((session) => session.workspaceId === previousWorkspaceId) ??
draft.quickChat.sessions[0];
if (fallbackSession) {
draft.quickChat.activeSessionId = fallbackSession.sessionId;
draft.quickChat.activeKind = "conversation";
return;
}
const fallbackTerminal = draft.quickChat.terminalTabs.find(
(tab) => tab.workspaceId === previousWorkspaceId,
);
if (fallbackTerminal) {
draft.quickChat.activeKind = "terminal";
draft.quickChat.activeTerminalTabId = fallbackTerminal.tabId;
return;
}
draft.quickChat.activeSessionId = null;
if (draft.quickChat.terminalTabs.length === 0) draft.quickChat.isOpen = false;
}
/**
* Hydrates the app state with SSR data using smart merge strategies.
*
@@ -10,6 +10,45 @@ const WORKSPACE_B = "workspace-b";
const SESSION_A = "session-a";
const SESSION_B = "session-b";
type TerminalActions = {
reuseOrCreateQuickTerminal: (workspaceId: string) => string;
createQuickTerminal: (workspaceId: string) => string;
activateQuickTerminal: (tabId: string, workspaceId: string) => void;
updateQuickTerminal: (
tabId: string,
update: {
sessionId?: string | null;
status?: "connecting" | "running" | "exited" | "error";
exitCode?: number;
error?: string;
},
) => void;
removeQuickTerminal: (tabId: string) => void;
};
function withTerminalActions(store: ReturnType<typeof makeStore>) {
return store.getState() as typeof store extends { getState: () => infer State }
? State & TerminalActions
: never;
}
function terminalState(store: ReturnType<typeof makeStore>) {
return store.getState().quickChat as unknown as {
terminalTabs: Array<{
tabId: string;
workspaceId: string;
sessionId: string | null;
sequence: number;
status: "connecting" | "running" | "exited" | "error";
exitCode?: number;
error?: string;
}>;
activeKind: "conversation" | "terminal";
activeTerminalTabId: string | null;
lastTerminalTabIdByWorkspace: Record<string, string>;
};
}
function makeStore() {
return create<UISlice>()(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -143,3 +182,106 @@ describe("configuration quick chat uniqueness", () => {
});
});
});
describe("quick terminal tabs", () => {
it("reuses the workspace terminal and always-new appends a distinct tab", () => {
const store = makeStore();
const actions = withTerminalActions(store);
const firstId = actions.reuseOrCreateQuickTerminal(WORKSPACE_A);
const reusedId = actions.reuseOrCreateQuickTerminal(WORKSPACE_A);
const secondId = actions.createQuickTerminal(WORKSPACE_A);
expect(reusedId).toBe(firstId);
expect(secondId).not.toBe(firstId);
expect(terminalState(store).terminalTabs.map((tab) => tab.sequence)).toEqual([1, 2]);
expect(terminalState(store).activeTerminalTabId).toBe(secondId);
expect(terminalState(store).activeKind).toBe("terminal");
});
it("keeps terminal selection per workspace and does not overwrite the last terminal", () => {
const store = makeStore();
const actions = withTerminalActions(store);
const firstTerminal = actions.createQuickTerminal(WORKSPACE_A);
const workspaceBTerminal = actions.createQuickTerminal(WORKSPACE_B);
store.getState().openQuickChat(SESSION_A, WORKSPACE_A, undefined, "chat");
actions.activateQuickTerminal(firstTerminal, WORKSPACE_A);
store.getState().setActiveQuickChatSession(SESSION_A, WORKSPACE_A);
expect(terminalState(store).activeKind).toBe("conversation");
expect(terminalState(store).activeTerminalTabId).toBe(firstTerminal);
expect(terminalState(store).lastTerminalTabIdByWorkspace).toMatchObject({
[WORKSPACE_A]: firstTerminal,
[WORKSPACE_B]: workspaceBTerminal,
});
});
it("updates lifecycle state without changing terminal identity", () => {
const store = makeStore();
const actions = withTerminalActions(store);
const tabId = actions.createQuickTerminal(WORKSPACE_A);
actions.updateQuickTerminal(tabId, {
sessionId: "pty-1",
status: "running",
});
actions.updateQuickTerminal(tabId, {
status: "exited",
exitCode: 7,
});
expect(terminalState(store).terminalTabs[0]).toMatchObject({
tabId,
sessionId: "pty-1",
status: "exited",
exitCode: 7,
});
});
it("falls back to adjacent terminals, then a conversation, and finally closes", () => {
const store = makeStore();
const actions = withTerminalActions(store);
store.getState().openQuickChat(SESSION_A, WORKSPACE_A, undefined, "chat");
const firstId = actions.createQuickTerminal(WORKSPACE_A);
const secondId = actions.createQuickTerminal(WORKSPACE_A);
actions.removeQuickTerminal(secondId);
expect(terminalState(store).activeTerminalTabId).toBe(firstId);
expect(terminalState(store).activeKind).toBe("terminal");
actions.removeQuickTerminal(firstId);
expect(store.getState().quickChat.activeSessionId).toBe(SESSION_A);
expect(terminalState(store).activeKind).toBe("conversation");
store.getState().closeQuickChatSession(SESSION_A);
expect(store.getState().quickChat.isOpen).toBe(false);
});
it("keeps the terminal selected when its retained conversation closes", () => {
const store = makeStore();
const actions = withTerminalActions(store);
store.getState().openQuickChat(SESSION_A, WORKSPACE_A, undefined, "chat");
store.getState().openQuickChat(SESSION_B, WORKSPACE_A, undefined, "chat");
const terminalId = actions.createQuickTerminal(WORKSPACE_A);
store.getState().closeQuickChatSession(SESSION_B);
expect(terminalState(store).activeKind).toBe("terminal");
expect(terminalState(store).activeTerminalTabId).toBe(terminalId);
expect(store.getState().quickChat.isOpen).toBe(true);
});
it("falls back to the final conversation in rendered order", () => {
const store = makeStore();
const actions = withTerminalActions(store);
store.getState().openQuickChat(SESSION_A, WORKSPACE_A, undefined, "chat");
store.getState().openQuickChat(SESSION_B, WORKSPACE_A, undefined, "config");
const terminalId = actions.createQuickTerminal(WORKSPACE_A);
actions.removeQuickTerminal(terminalId);
expect(store.getState().quickChat.activeSessionId).toBe(SESSION_B);
expect(terminalState(store).activeKind).toBe("conversation");
});
});
@@ -1,11 +1,12 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import {
reconcileQuickTerminalTabs,
reconcileQuickChatSessions,
removeQuickChatSessionsForTask,
upsertQuickChatSession,
} from "./quick-chat-sync";
import { getQuickChatSetupSessionId } from "./quick-chat-session";
import type { QuickChatSession, QuickChatState } from "./types";
import type { QuickChatSession, QuickChatState, QuickTerminalTab } from "./types";
const mockStoredNames = vi.hoisted(() => ({ value: {} as Record<string, string> }));
@@ -16,6 +17,7 @@ vi.mock("@/lib/local-storage", () => ({
const WS = "ws-1";
const OTHER_WS = "ws-2";
const SETUP_ID = getQuickChatSetupSessionId(WS, "chat");
const STALE_TERMINAL_ID = "stale-terminal";
function chat(sessionId: string, overrides: Partial<QuickChatSession> = {}): QuickChatSession {
return {
@@ -28,7 +30,16 @@ function chat(sessionId: string, overrides: Partial<QuickChatSession> = {}): Qui
}
function state(sessions: QuickChatSession[], overrides: Partial<QuickChatState> = {}) {
return { isOpen: true, sessions, activeSessionId: null, ...overrides };
return {
isOpen: true,
sessions,
activeSessionId: null,
terminalTabs: [],
activeKind: "conversation" as const,
activeTerminalTabId: null,
lastTerminalTabIdByWorkspace: {},
...overrides,
};
}
beforeEach(() => {
@@ -125,7 +136,63 @@ describe("reconcileQuickChatSessions", () => {
expect(after.activeSessionId).toBeNull();
expect(after.isOpen).toBe(false);
});
});
describe("reconcileQuickTerminalTabs", () => {
function terminal(tabId: string, overrides: Partial<QuickTerminalTab> = {}): QuickTerminalTab {
return {
tabId,
workspaceId: WS,
sessionId: `pty-${tabId}`,
sequence: 1,
status: "running",
...overrides,
};
}
it("restores server descriptors and drops established tabs the server removed", () => {
const pending = terminal("pending", { sessionId: null, status: "connecting", sequence: 3 });
const removed = terminal("removed", { sequence: 1 });
const foreign = terminal("foreign", { workspaceId: OTHER_WS, sequence: 4 });
const before = state([], {
terminalTabs: [foreign, removed, pending],
activeKind: "terminal",
activeTerminalTabId: removed.tabId,
lastTerminalTabIdByWorkspace: { [WS]: removed.tabId, [OTHER_WS]: foreign.tabId },
});
const restored = terminal("restored", { sequence: 2, sessionId: "pty-restored" });
const after = reconcileQuickTerminalTabs(before, WS, [restored]);
expect(after.terminalTabs).toEqual([foreign, restored, pending]);
expect(after.terminalTabs).not.toContainEqual(removed);
expect(after.activeKind).toBe("terminal");
expect(after.activeTerminalTabId).toBe(restored.tabId);
expect(after.lastTerminalTabIdByWorkspace[WS]).toBe(restored.tabId);
expect(after.lastTerminalTabIdByWorkspace[OTHER_WS]).toBe(foreign.tabId);
});
it("uses a conversation or closes when the active workspace has no terminal left", () => {
const before = state([chat("chat-a")], {
activeKind: "terminal",
activeSessionId: "chat-a",
activeTerminalTabId: "removed",
terminalTabs: [terminal("removed")],
lastTerminalTabIdByWorkspace: { [WS]: "removed" },
});
const conversation = reconcileQuickTerminalTabs(before, WS, []);
expect(conversation.activeKind).toBe("conversation");
expect(conversation.activeSessionId).toBe("chat-a");
expect(conversation.isOpen).toBe(true);
const closed = reconcileQuickTerminalTabs({ ...before, sessions: [] }, WS, []);
expect(closed.isOpen).toBe(false);
expect(closed.activeSessionId).toBeNull();
});
});
describe("reconcileQuickChatSessions — selection preservation", () => {
it("leaves a never-selected active tab unset instead of promoting one", () => {
// A background resync must not decide which tab is "current" for a user who
// has not opened quick chat at all.
@@ -147,6 +214,110 @@ describe("reconcileQuickChatSessions", () => {
expect(after.activeSessionId).toBe("foreign");
expect(after.isOpen).toBe(true);
});
it("preserves local terminal tabs and active terminal selection during resync", () => {
const terminal: QuickTerminalTab = {
tabId: "terminal-a",
workspaceId: WS,
sessionId: "pty-a",
sequence: 1,
status: "running",
};
const before = state([], {
activeKind: "terminal",
activeTerminalTabId: terminal.tabId,
terminalTabs: [terminal],
lastTerminalTabIdByWorkspace: { [WS]: terminal.tabId },
});
const after = reconcileQuickChatSessions(before, WS, []);
expect(after.terminalTabs).toEqual([terminal]);
expect(after.activeKind).toBe("terminal");
expect(after.activeTerminalTabId).toBe(terminal.tabId);
expect(after.isOpen).toBe(true);
});
it("falls back to a local terminal when the active conversation disappears", () => {
const terminal: QuickTerminalTab = {
tabId: "terminal-a",
workspaceId: WS,
sessionId: "pty-a",
sequence: 1,
status: "running",
};
const before = state([chat("a")], {
activeSessionId: "a",
terminalTabs: [terminal],
});
const after = reconcileQuickChatSessions(before, WS, []);
expect(after.activeKind).toBe("terminal");
expect(after.activeTerminalTabId).toBe(terminal.tabId);
expect(after.isOpen).toBe(true);
});
});
describe("reconcileQuickChatSessions — stale terminal recovery", () => {
it("recovers a stale terminal selection within its previous workspace", () => {
const workspaceTerminal: QuickTerminalTab = {
tabId: "terminal-a",
workspaceId: WS,
sessionId: "pty-a",
sequence: 1,
status: "running",
};
const otherWorkspaceTerminal: QuickTerminalTab = {
...workspaceTerminal,
tabId: "terminal-b",
workspaceId: OTHER_WS,
};
const before = state([chat("chat-a")], {
activeKind: "terminal",
activeSessionId: "chat-a",
activeTerminalTabId: STALE_TERMINAL_ID,
terminalTabs: [otherWorkspaceTerminal, workspaceTerminal],
lastTerminalTabIdByWorkspace: {
[WS]: STALE_TERMINAL_ID,
[OTHER_WS]: otherWorkspaceTerminal.tabId,
},
});
const after = reconcileQuickChatSessions(before, WS, [chat("chat-a")]);
expect(after.activeKind).toBe("terminal");
expect(after.activeTerminalTabId).toBe(workspaceTerminal.tabId);
});
it("switches back to conversation mode when a stale terminal has no replacement", () => {
const before = state([chat("chat-a")], {
activeKind: "terminal",
activeSessionId: "chat-a",
activeTerminalTabId: STALE_TERMINAL_ID,
lastTerminalTabIdByWorkspace: { [WS]: STALE_TERMINAL_ID },
});
const after = reconcileQuickChatSessions(before, WS, [chat("chat-a")]);
expect(after.activeKind).toBe("conversation");
expect(after.activeSessionId).toBe("chat-a");
});
it("closes when stale terminal recovery has no conversation or terminal left", () => {
const before = state([], {
isOpen: true,
activeKind: "terminal",
activeTerminalTabId: STALE_TERMINAL_ID,
lastTerminalTabIdByWorkspace: { [WS]: STALE_TERMINAL_ID },
});
const after = reconcileQuickChatSessions(before, WS, []);
expect(after.activeKind).toBe("conversation");
expect(after.activeSessionId).toBeNull();
expect(after.isOpen).toBe(false);
});
});
describe("upsertQuickChatSession", () => {
+125 -4
View File
@@ -1,6 +1,6 @@
import { getStoredQuickChatNames } from "@/lib/local-storage";
import { isQuickChatSetupSessionId } from "./quick-chat-session";
import type { QuickChatSession, QuickChatState } from "./types";
import type { QuickChatSession, QuickChatState, QuickTerminalTab } from "./types";
/**
* Applies locally stored tab renames over a server-provided session list.
@@ -69,6 +69,70 @@ export function reconcileQuickChatSessions(
]);
}
/**
* Reconciles one workspace's server-owned terminal descriptors. A local tab
* that is still creating its descriptor is retained briefly so a socket
* reconnect cannot erase it before the POST response lands; every established
* descriptor follows the server list, including deletions from another client.
*/
export function reconcileQuickTerminalTabs(
state: QuickChatState,
workspaceId: string,
serverTabs: QuickTerminalTab[],
): QuickChatState {
const otherWorkspaces = state.terminalTabs.filter((tab) => tab.workspaceId !== workspaceId);
const serverById = new Map(serverTabs.map((tab) => [tab.tabId, tab]));
const pendingLocal = state.terminalTabs.filter(
(tab) =>
tab.workspaceId === workspaceId &&
!serverById.has(tab.tabId) &&
tab.status === "connecting" &&
!tab.sessionId,
);
const nextTabs = [
...otherWorkspaces,
...[...serverTabs].sort((a, b) => a.sequence - b.sequence),
...pendingLocal,
];
const validIds = new Set(nextTabs.map((tab) => tab.tabId));
const lastTerminalTabIdByWorkspace = { ...state.lastTerminalTabIdByWorkspace };
for (const [workspace, tabId] of Object.entries(lastTerminalTabIdByWorkspace)) {
if (!validIds.has(tabId)) delete lastTerminalTabIdByWorkspace[workspace];
}
const next: QuickChatState = {
...state,
terminalTabs: nextTabs,
lastTerminalTabIdByWorkspace,
};
if (next.activeKind !== "terminal") return next;
const active = nextTabs.find((tab) => tab.tabId === next.activeTerminalTabId);
if (active) {
next.lastTerminalTabIdByWorkspace[active.workspaceId] = active.tabId;
return next;
}
const previousWorkspaceId =
state.terminalTabs.find((tab) => tab.tabId === state.activeTerminalTabId)?.workspaceId ??
workspaceId;
const replacement = nextTabs
.filter((tab) => tab.workspaceId === previousWorkspaceId)
.sort((a, b) => a.sequence - b.sequence)[0];
if (replacement) {
next.activeTerminalTabId = replacement.tabId;
next.lastTerminalTabIdByWorkspace[replacement.workspaceId] = replacement.tabId;
return next;
}
const conversation = next.sessions.find((session) => session.workspaceId === previousWorkspaceId);
next.activeKind = "conversation";
next.activeTerminalTabId = null;
next.activeSessionId = conversation?.sessionId ?? null;
next.isOpen = conversation ? next.isOpen : false;
return next;
}
/**
* Adds or updates a single quick-chat tab observed on the wire.
*
@@ -104,10 +168,53 @@ export function removeQuickChatSessionsForTask(
* local tab close does: fall back to another tab in the same workspace, and
* close the modal only when nothing is left to show.
*/
function preserveTerminalSelection(
state: QuickChatState,
sessions: QuickChatSession[],
): QuickChatState | null {
if (state.activeKind !== "terminal") return null;
const active = state.terminalTabs.find((tab) => tab.tabId === state.activeTerminalTabId);
if (active) return { ...state, sessions };
const previousWorkspaceId =
Object.entries(state.lastTerminalTabIdByWorkspace).find(
([, tabId]) => tabId === state.activeTerminalTabId,
)?.[0] ??
state.terminalTabs.find((tab) => tab.tabId === state.activeTerminalTabId)?.workspaceId;
const terminal = state.terminalTabs.find(
(tab) => !previousWorkspaceId || tab.workspaceId === previousWorkspaceId,
);
if (!terminal) {
const conversation =
sessions.find((session) => session.workspaceId === previousWorkspaceId) ??
sessions.find((session) => session.sessionId === state.activeSessionId) ??
sessions[0];
return {
...state,
sessions,
activeKind: "conversation",
activeTerminalTabId: null,
activeSessionId: conversation?.sessionId ?? null,
isOpen: conversation ? state.isOpen : false,
};
}
return {
...state,
sessions,
activeTerminalTabId: terminal.tabId,
lastTerminalTabIdByWorkspace: {
...state.lastTerminalTabIdByWorkspace,
[terminal.workspaceId]: terminal.tabId,
},
};
}
function withValidActiveSession(
state: QuickChatState,
sessions: QuickChatSession[],
): QuickChatState {
const terminalSelection = preserveTerminalSelection(state, sessions);
if (terminalSelection) return terminalSelection;
const active = state.activeSessionId;
// No tab was ever selected: leave it unset rather than silently promoting one
// on a background resync. Same invariant `hydrateUI` guards on.
@@ -115,15 +222,29 @@ function withValidActiveSession(
if (sessions.some((session) => session.sessionId === active)) {
return { ...state, sessions };
}
const previousWorkspaceId = state.sessions.find(
(session) => session.sessionId === active,
)?.workspaceId;
const previousWorkspaceId =
state.sessions.find((session) => session.sessionId === active)?.workspaceId ??
state.terminalTabs.find((tab) => tab.tabId === state.activeTerminalTabId)?.workspaceId;
const fallback =
sessions.find((session) => session.workspaceId === previousWorkspaceId) ?? sessions[0];
const terminalFallback = state.terminalTabs.find(
(tab) => tab.workspaceId === previousWorkspaceId,
);
if (!fallback && terminalFallback) {
return {
...state,
sessions,
activeKind: "terminal",
activeTerminalTabId: terminalFallback.tabId,
isOpen: state.isOpen,
};
}
return {
...state,
sessions,
activeSessionId: fallback?.sessionId ?? null,
activeKind: "conversation",
activeTerminalTabId: null,
isOpen: fallback ? state.isOpen : false,
};
}
@@ -0,0 +1,175 @@
import type { Draft } from "immer";
import type { QuickChatState, QuickTerminalTab, QuickTerminalUpdate, UISlice } from "./types";
type ImmerSet = (recipe: (draft: Draft<UISlice>) => void) => void;
function createQuickTerminalId(): string {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
const bytes = new Uint8Array(16);
if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
crypto.getRandomValues(bytes);
} else {
for (let index = 0; index < bytes.length; index += 1) {
bytes[index] = Math.floor(Math.random() * 256);
}
}
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
function findWorkspaceTerminal(
terminals: QuickTerminalTab[],
workspaceId: string,
tabId: string | null | undefined,
): QuickTerminalTab | undefined {
return terminals.find(
(tab) => tab.workspaceId === workspaceId && (!tabId || tab.tabId === tabId),
);
}
export function activateConversationDraft(
quickChat: QuickChatState,
sessionId: string,
workspaceId: string,
): void {
const session = quickChat.sessions.find((item) => item.sessionId === sessionId);
if (!session || session.workspaceId !== workspaceId) return;
quickChat.activeKind = "conversation";
quickChat.activeSessionId = sessionId;
quickChat.isOpen = true;
}
export function activateTerminalDraft(quickChat: QuickChatState, tab: QuickTerminalTab): void {
quickChat.activeKind = "terminal";
quickChat.activeTerminalTabId = tab.tabId;
quickChat.lastTerminalTabIdByWorkspace[tab.workspaceId] = tab.tabId;
quickChat.isOpen = true;
}
function findTerminalFallback(
terminals: QuickTerminalTab[],
workspaceId: string,
removedSequence: number,
): QuickTerminalTab | undefined {
const sameWorkspace = terminals.filter((tab) => tab.workspaceId === workspaceId);
return (
sameWorkspace.find((tab) => tab.sequence > removedSequence) ??
[...sameWorkspace].sort((a, b) => b.sequence - a.sequence)[0]
);
}
export function activateWorkspaceFallback(quickChat: QuickChatState, workspaceId?: string): void {
if (!workspaceId) {
quickChat.activeSessionId = null;
quickChat.isOpen = false;
return;
}
const conversations = quickChat.sessions.filter((session) => session.workspaceId === workspaceId);
const conversation = conversations[conversations.length - 1];
if (conversation) {
activateConversationDraft(quickChat, conversation.sessionId, workspaceId);
return;
}
const terminal = quickChat.terminalTabs.find((tab) => tab.workspaceId === workspaceId);
if (terminal) {
activateTerminalDraft(quickChat, terminal);
return;
}
quickChat.activeSessionId = null;
quickChat.activeKind = "conversation";
quickChat.activeTerminalTabId = null;
quickChat.isOpen = false;
}
function createQuickTerminalDraft(quickChat: QuickChatState, workspaceId: string): string {
const workspaceTerminals = quickChat.terminalTabs.filter(
(tab) => tab.workspaceId === workspaceId,
);
const sequence = workspaceTerminals.reduce((max, tab) => Math.max(max, tab.sequence), 0) + 1;
const tab: QuickTerminalTab = {
tabId: createQuickTerminalId(),
workspaceId,
sessionId: null,
sequence,
status: "connecting",
};
quickChat.terminalTabs.push(tab);
activateTerminalDraft(quickChat, tab);
return tab.tabId;
}
export function buildQuickTerminalActions(set: ImmerSet) {
return {
reuseOrCreateQuickTerminal: (workspaceId: string) => {
let tabId = "";
set((draft) => {
const lastId = draft.quickChat.lastTerminalTabIdByWorkspace[workspaceId];
const existing = findWorkspaceTerminal(draft.quickChat.terminalTabs, workspaceId, lastId);
const fallback =
existing ?? findWorkspaceTerminal(draft.quickChat.terminalTabs, workspaceId, undefined);
tabId = fallback?.tabId ?? createQuickTerminalDraft(draft.quickChat, workspaceId);
if (fallback) activateTerminalDraft(draft.quickChat, fallback);
});
return tabId;
},
createQuickTerminal: (workspaceId: string) => {
let tabId = "";
set((draft) => {
tabId = createQuickTerminalDraft(draft.quickChat, workspaceId);
});
return tabId;
},
updateQuickTerminal: (tabId: string, update: QuickTerminalUpdate) =>
set((draft) => {
const tab = draft.quickChat.terminalTabs.find((item) => item.tabId === tabId);
if (!tab) return;
if ("sequence" in update && update.sequence !== undefined) tab.sequence = update.sequence;
if ("sessionId" in update) tab.sessionId = update.sessionId ?? null;
if (update.status) tab.status = update.status;
if ("exitCode" in update) {
if (update.exitCode == null) delete tab.exitCode;
else tab.exitCode = update.exitCode;
}
if ("error" in update) {
if (!update.error) delete tab.error;
else tab.error = update.error;
}
}),
activateQuickTerminal: (tabId: string, workspaceId: string) =>
set((draft) => {
const tab = draft.quickChat.terminalTabs.find((item) => item.tabId === tabId);
if (!tab || tab.workspaceId !== workspaceId) return;
activateTerminalDraft(draft.quickChat, tab);
}),
removeQuickTerminal: (tabId: string) =>
set((draft) => {
const index = draft.quickChat.terminalTabs.findIndex((tab) => tab.tabId === tabId);
if (index === -1) return;
const closing = draft.quickChat.terminalTabs[index];
draft.quickChat.terminalTabs.splice(index, 1);
const replacement = findTerminalFallback(
draft.quickChat.terminalTabs,
closing.workspaceId,
closing.sequence,
);
if (draft.quickChat.lastTerminalTabIdByWorkspace[closing.workspaceId] === tabId) {
if (replacement) {
draft.quickChat.lastTerminalTabIdByWorkspace[closing.workspaceId] = replacement.tabId;
} else {
delete draft.quickChat.lastTerminalTabIdByWorkspace[closing.workspaceId];
}
}
if (
draft.quickChat.activeKind === "terminal" &&
draft.quickChat.activeTerminalTabId === tabId
) {
if (replacement) activateTerminalDraft(draft.quickChat, replacement);
else activateWorkspaceFallback(draft.quickChat, closing.workspaceId);
}
}),
};
}
+33
View File
@@ -96,6 +96,26 @@ export type SystemHealthState = {
export type QuickChatSessionKind = "chat" | "config";
export type QuickTerminalStatus = "connecting" | "running" | "exited" | "error";
export type QuickTerminalTab = {
tabId: string;
workspaceId: string;
sessionId: string | null;
sequence: number;
status: QuickTerminalStatus;
exitCode?: number;
error?: string;
};
export type QuickTerminalUpdate = {
sequence?: number;
sessionId?: string | null;
status?: QuickTerminalStatus;
exitCode?: number | null;
error?: string | null;
};
export type QuickChatSession = {
kind: QuickChatSessionKind;
sessionId: string;
@@ -107,10 +127,16 @@ export type QuickChatSession = {
initialPrompt?: string;
};
export type QuickChatActiveKind = "conversation" | "terminal";
export type QuickChatState = {
isOpen: boolean;
sessions: QuickChatSession[];
activeSessionId: string | null;
terminalTabs: QuickTerminalTab[];
activeKind: QuickChatActiveKind;
activeTerminalTabId: string | null;
lastTerminalTabIdByWorkspace: Record<string, string>;
};
export type SessionFailureNotification = {
@@ -252,12 +278,19 @@ export type UISliceActions = {
kind?: QuickChatSessionKind,
taskId?: string,
) => void;
reuseOrCreateQuickTerminal: (workspaceId: string) => string;
createQuickTerminal: (workspaceId: string) => string;
updateQuickTerminal: (tabId: string, update: QuickTerminalUpdate) => void;
activateQuickTerminal: (tabId: string, workspaceId: string) => void;
removeQuickTerminal: (tabId: string) => void;
closeQuickChat: () => void;
closeQuickChatSession: (sessionId: string) => void;
setActiveQuickChatSession: (sessionId: string, workspaceId: string) => void;
renameQuickChatSession: (sessionId: string, name: string) => void;
/** Replaces a workspace's quick-chat tabs with the server's authoritative list. */
syncQuickChatSessions: (workspaceId: string, sessions: QuickChatSession[]) => void;
/** Replaces a workspace's terminal descriptors with the server's list. */
syncQuickTerminalTabs: (workspaceId: string, tabs: QuickTerminalTab[]) => void;
/** Adds or updates a tab observed on the wire, without stealing focus. */
upsertQuickChatSessionFromEvent: (session: QuickChatSession) => void;
/** Drops tabs whose backing task was deleted (possibly on another device). */
+43 -5
View File
@@ -22,9 +22,15 @@ import type { ActiveDocument, QuickChatSession, UISlice, UISliceState } from "./
import { getQuickChatSetupSessionId } from "./quick-chat-session";
import {
reconcileQuickChatSessions,
reconcileQuickTerminalTabs,
removeQuickChatSessionsForTask,
upsertQuickChatSession,
} from "./quick-chat-sync";
import {
activateConversationDraft,
activateWorkspaceFallback,
buildQuickTerminalActions,
} from "./quick-terminal-actions";
/** Default sidebar view state: the single built-in "All tasks" view, active, no draft. */
function createDefaultSidebarState(): UISliceState["sidebarViews"] {
@@ -107,7 +113,15 @@ export const defaultUIState: UISliceState = {
reviewPRSelection: { selectedKeyByTaskId: {} },
documentPanel: { activeDocumentBySessionId: {} },
systemHealth: { issues: [], checks: [], healthy: true, loaded: false, loading: false },
quickChat: { isOpen: false, sessions: [], activeSessionId: null },
quickChat: {
isOpen: false,
sessions: [],
activeSessionId: null,
terminalTabs: [],
activeKind: "conversation",
activeTerminalTabId: null,
lastTerminalTabIdByWorkspace: {},
},
sessionFailureNotification: null,
taskDeletedNotification: null,
updateAvailableNotification: null,
@@ -333,6 +347,7 @@ function buildOpenQuickChatAction(set: ImmerSet) {
if (existingConfigSession) {
draft.quickChat.isOpen = true;
draft.quickChat.activeSessionId = existingConfigSession.sessionId;
draft.quickChat.activeKind = "conversation";
return;
}
const setupSessionId = getQuickChatSetupSessionId(workspaceId, kind);
@@ -341,6 +356,7 @@ function buildOpenQuickChatAction(set: ImmerSet) {
}
draft.quickChat.isOpen = true;
draft.quickChat.activeSessionId = setupSessionId;
draft.quickChat.activeKind = "conversation";
return;
}
const existing = draft.quickChat.sessions.find((session) => session.sessionId === sessionId);
@@ -353,6 +369,7 @@ function buildOpenQuickChatAction(set: ImmerSet) {
}
draft.quickChat.isOpen = true;
draft.quickChat.activeSessionId = sessionId;
draft.quickChat.activeKind = "conversation";
});
}
@@ -382,7 +399,10 @@ function buildQuickChatActions(set: ImmerSet) {
} else {
draft.quickChat.sessions.push({ sessionId, workspaceId, agentProfileId, kind, taskId });
}
if (shouldActivate) draft.quickChat.activeSessionId = sessionId;
if (shouldActivate) {
draft.quickChat.activeSessionId = sessionId;
draft.quickChat.activeKind = "conversation";
}
}),
openQuickChat: buildOpenQuickChatAction(set),
closeQuickChat: () =>
@@ -397,18 +417,31 @@ function buildQuickChatActions(set: ImmerSet) {
draft.quickChat.sessions = draft.quickChat.sessions.filter(
(session) => session.sessionId !== sessionId,
);
if (draft.quickChat.activeSessionId !== sessionId) return;
if (
draft.quickChat.activeKind !== "conversation" ||
draft.quickChat.activeSessionId !== sessionId
) {
return;
}
const nextSession = draft.quickChat.sessions.find(
(session) => session.workspaceId === closingSession?.workspaceId,
);
draft.quickChat.activeSessionId = nextSession?.sessionId ?? null;
if (!nextSession) draft.quickChat.isOpen = false;
if (nextSession) {
activateConversationDraft(
draft.quickChat,
nextSession.sessionId,
nextSession.workspaceId,
);
} else {
activateWorkspaceFallback(draft.quickChat, closingSession?.workspaceId);
}
}),
setActiveQuickChatSession: (sessionId: string, workspaceId: string) =>
set((draft) => {
const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
if (!session || session.workspaceId !== workspaceId) return;
draft.quickChat.activeSessionId = sessionId;
draft.quickChat.activeKind = "conversation";
}),
// Optimistic only. Persisting the name is `persistQuickChatRename`'s job,
// so the backing task title stays the shared source of truth.
@@ -421,6 +454,10 @@ function buildQuickChatActions(set: ImmerSet) {
set((draft) => {
draft.quickChat = reconcileQuickChatSessions(draft.quickChat, workspaceId, sessions);
}),
syncQuickTerminalTabs: (workspaceId: string, tabs: UISliceState["quickChat"]["terminalTabs"]) =>
set((draft) => {
draft.quickChat = reconcileQuickTerminalTabs(draft.quickChat, workspaceId, tabs);
}),
upsertQuickChatSessionFromEvent: (session: QuickChatSession) =>
set((draft) => {
draft.quickChat = upsertQuickChatSession(draft.quickChat, session);
@@ -457,6 +494,7 @@ export const createUISlice: StateCreator<UISlice, [["zustand/immer", never]], []
...buildSystemHealthActions(set),
...buildDismissedAgentErrors(set),
...buildNotificationActions(set),
...buildQuickTerminalActions(set),
...buildQuickChatActions(set),
setRightPanelActiveTab: (sessionId, tab) =>
set((draft) => {
+8 -1
View File
@@ -344,7 +344,13 @@ export type AppState = KanbanSlice & {
invalidateSystemHealth: () => void;
openQuickChat: UIA["openQuickChat"];
addQuickChatSession: UIA["addQuickChatSession"];
reuseOrCreateQuickTerminal: UIA["reuseOrCreateQuickTerminal"];
createQuickTerminal: UIA["createQuickTerminal"];
updateQuickTerminal: UIA["updateQuickTerminal"];
activateQuickTerminal: UIA["activateQuickTerminal"];
removeQuickTerminal: UIA["removeQuickTerminal"];
syncQuickChatSessions: UIA["syncQuickChatSessions"];
syncQuickTerminalTabs: UIA["syncQuickTerminalTabs"];
upsertQuickChatSessionFromEvent: UIA["upsertQuickChatSessionFromEvent"];
removeQuickChatSessionsForTask: UIA["removeQuickChatSessionsForTask"];
closeQuickChat: () => void;
@@ -534,7 +540,8 @@ export type AppState = KanbanSlice & {
// only have one piece of it (e.g. update notification settings from the
// settings boot payload) must be able to pass a partial `system` object
// without fabricating placeholder values for the rest.
export type HydrationState = Omit<Partial<AppState>, "system"> & {
export type HydrationState = Omit<Partial<AppState>, "system" | "quickChat"> & {
quickChat?: Partial<AppState["quickChat"]>;
system?: Partial<AppState["system"]>;
};
+1
View File
@@ -179,6 +179,7 @@
"selectAModelShort": "Select a model",
"sessionEnded": "Session ended.",
"sessionEndedWithCode": "Session ended (exit {{code}}).",
"sessionUnavailable": "Session is no longer available.",
"setupProfile": "Setup Profile",
"signInToAgent": "Sign in: {{name}}",
"startMode": "Start mode",
+1
View File
@@ -97,6 +97,7 @@
"reload": "Reload",
"reloadTheApplicationToTryAgain": "Reload the application to try again.",
"requestFailed": "Request failed",
"rename": "Rename",
"reset": "Reset",
"resetWatchChecking": "Checking how many tasks would be deleted…",
"resetWatchDeleteAllTasks": "This will delete every task previously created by the watch, including archived tasks. The watch's polling cursor is also cleared so the next check re-imports every currently-matching item. This cannot be undone.",
+15
View File
@@ -56,6 +56,21 @@
"profileAndPassword": "Profile & Password",
"projects": "Projects",
"quickChat": "Quick Chat",
"quickTerminal": "Quick terminal",
"quickChatTerminals": "Terminals",
"quickChatNewAgent": "New Agent",
"quickChatNewTerminal": "New Terminal",
"quickChatClose": "Close quick chat",
"quickChatTerminalTab_one": "Terminal {{count}}",
"quickChatTerminalTab_other": "Terminal {{count}}",
"quickChatCloseTerminal_one": "Close Terminal {{count}}",
"quickChatCloseTerminal_other": "Close Terminal {{count}}",
"quickChatTerminalError": "Terminal error: {{error}}",
"quickChatTerminalUnknownError": "The terminal could not be started.",
"quickChatTerminalConnecting": "Connecting to terminal…",
"quickChatTerminalExited": "Terminal exited.",
"quickChatTerminalExitedWithCode": "Terminal exited with code {{code}}.",
"quickChatAdd": "Add or switch tab",
"reconnecting": "Reconnecting",
"reconnectingToKandev": "Reconnecting to Kandev",
"repositories": "Repositories",
+1
View File
@@ -179,6 +179,7 @@
"selectAModelShort": "Śēĺēćţ à ḿōďēĺ",
"sessionEnded": "Śēśśĩōń ēńďēď.",
"sessionEndedWithCode": "Śēśśĩōń ēńďēď (ēxĩţ {{code}}).",
"sessionUnavailable": "Śēśśĩōń ĩś ńō ĺōńĝēŕ àvàĩĺàƀĺē.",
"setupProfile": "Śēţũƥ Ƥŕōƒĩĺē",
"signInToAgent": "Śĩĝń ĩń: {{name}}",
"startMode": "Śţàŕţ ḿōďē",
+1
View File
@@ -97,6 +97,7 @@
"reload": "Ŕēĺōàď",
"reloadTheApplicationToTryAgain": "Ŕēĺōàď ţĥē àƥƥĺĩćàţĩōń ţō ţŕŷ àĝàĩń.",
"requestFailed": "Ŕēqũēśţ ƒàĩĺēď",
"rename": "Ŕēńàḿē",
"reset": "Ŕēśēţ",
"resetWatchChecking": "Ćĥēćķĩńĝ ĥōŵ ḿàńŷ ţàśķś ŵōũĺď ƀē ďēĺēţēď…",
"resetWatchDeleteAllTasks": "Ţĥĩś ŵĩĺĺ ďēĺēţē ēvēŕŷ ţàśķ ƥŕēvĩōũśĺŷ ćŕēàţēď ƀŷ ţĥē ŵàţćĥ, ĩńćĺũďĩńĝ àŕćĥĩvēď ţàśķś. Ţĥē ŵàţćĥ'ś ƥōĺĺĩńĝ ćũŕśōŕ ĩś àĺśō ćĺēàŕēď śō ţĥē ńēxţ ćĥēćķ ŕē-ĩḿƥōŕţś ēvēŕŷ ćũŕŕēńţĺŷ-ḿàţćĥĩńĝ ĩţēḿ. Ţĥĩś ćàńńōţ ƀē ũńďōńē.",
+15
View File
@@ -56,6 +56,21 @@
"profileAndPassword": "Ƥŕōƒĩĺē & Ƥàśśŵōŕď",
"projects": "Ƥŕōĵēćţś",
"quickChat": "Qũĩćķ Ćĥàţ",
"quickTerminal": "Qũĩćķ ţēŕḿĩńàĺ",
"quickChatTerminals": "Ţēŕḿĩńàĺś",
"quickChatNewAgent": "Ńēŵ Àĝēńţ",
"quickChatNewTerminal": "Ńēŵ Ţēŕḿĩńàĺ",
"quickChatClose": "Ćĺōśē qũĩćķ ćĥàţ",
"quickChatTerminalTab_one": "Ţēŕḿĩńàĺ {{count}}",
"quickChatTerminalTab_other": "Ţēŕḿĩńàĺ {{count}}",
"quickChatCloseTerminal_one": "Ćĺōśē Ţēŕḿĩńàĺ {{count}}",
"quickChatCloseTerminal_other": "Ćĺōśē Ţēŕḿĩńàĺ {{count}}",
"quickChatTerminalError": "Ţēŕḿĩńàĺ ēŕŕōŕ: {{error}}",
"quickChatTerminalUnknownError": "Ţĥē ţēŕḿĩńàĺ ćōũĺď ńōţ ƀē śţàŕţēď.",
"quickChatTerminalConnecting": "Ćōńńēćţĩńĝ ţō ţēŕḿĩńàĺ…",
"quickChatTerminalExited": "Ţēŕḿĩńàĺ ēxĩţēď.",
"quickChatTerminalExitedWithCode": "Ţēŕḿĩńàĺ ēxĩţēď ŵĩţĥ ćōďē {{code}}.",
"quickChatAdd": "Àďď ōŕ śŵĩţćĥ ţàƀ",
"reconnecting": "Ŕēćōńńēćţĩńĝ",
"reconnectingToKandev": "Ŕēćōńńēćţĩńĝ ţō Ķàńďēv",
"repositories": "Ŕēƥōśĩţōŕĩēś",
+1
View File
@@ -168,6 +168,7 @@
"selectAModel": "选择模型…",
"sessionEnded": "会话已结束。",
"sessionEndedWithCode": "会话已结束(退出码 {{code}})。",
"sessionUnavailable": "会话已不再可用。",
"setupProfile": "设置配置",
"signInToAgent": "登录:{{name}}",
"startingSession": "正在启动会话…",
+13
View File
@@ -5,6 +5,19 @@
"collapseQueuedMessages": "折叠排队中的消息",
"clearAll": "全部清除",
"clearAllQueuedMessages": "清除所有排队中的消息",
"attachmentUploadPending": "正在上传附件…",
"attachmentUploadPendingSubmit": "请等待附件上传完成后再发送。",
"attachmentUploadFailed": "附件上传失败",
"retryAttachmentUpload": "重试上传附件",
"attachmentPreviewAlt": "预览",
"attachmentMessageAlt": "附件 {{index}}",
"attachmentFallbackName": "附件",
"attachmentPreviewFullAlt": "完整尺寸预览",
"attachmentDeliveryMode": "附件传递方式",
"attachmentDeliveryPrompt": "提示词",
"attachmentDeliveryFile": "文件",
"attachmentDeliveryPromptDescription": "作为提示词上下文发送,以便进行视觉理解。代理不会获得文件路径。",
"attachmentDeliveryPathDescription": "上传到工作区,以便代理读取或编辑该文件。",
"editQueuedMessage": "编辑排队中的消息",
"expandMessage": "展开消息",
"failedToClearQueuedMessages": "清除排队中的消息失败。",
+1
View File
@@ -62,6 +62,7 @@
"presetIconTool": "工具",
"prompts": "提示词",
"requestFailed": "请求失败",
"rename": "重命名",
"reset": "重置",
"resetWatchChecking": "正在检查将删除多少任务…",
"resetWatchDeleteAllTasks": "这会删除此前由此监控创建的所有任务,包括已归档任务。监控的轮询游标也会被清除,因此下次检查会重新导入当前所有匹配项。此操作无法撤销。",
+15
View File
@@ -55,6 +55,21 @@
"profileAndPassword": "个人资料与密码",
"projects": "项目",
"quickChat": "快速聊天",
"quickTerminal": "快速终端",
"quickChatTerminals": "终端",
"quickChatNewAgent": "新建代理",
"quickChatNewTerminal": "新建终端",
"quickChatClose": "关闭快速聊天",
"quickChatTerminalTab_one": "终端 {{count}}",
"quickChatTerminalTab_other": "终端 {{count}}",
"quickChatCloseTerminal_one": "关闭终端 {{count}}",
"quickChatCloseTerminal_other": "关闭终端 {{count}}",
"quickChatTerminalError": "终端错误:{{error}}",
"quickChatTerminalUnknownError": "终端无法启动。",
"quickChatTerminalConnecting": "正在连接终端…",
"quickChatTerminalExited": "终端已退出。",
"quickChatTerminalExitedWithCode": "终端已退出,代码为 {{code}}。",
"quickChatAdd": "添加或切换标签页",
"reconnecting": "正在重连",
"reconnectingToKandev": "正在重新连接到 Kandev",
"retry": "重试",
@@ -0,0 +1,47 @@
# ADR-2026-08-05-server-owned-quick-terminal-descriptors: Server-Owned Quick Terminal Descriptors
**Status:** accepted
**Date:** 2026-08-05
**Area:** backend, frontend, protocol, security
## Context
Quick Terminal currently keeps its tab descriptors only in the browser's in-memory Zustand
store. A page reload therefore removes the UI identity even though a detached host-shell PTY can
still be alive in backend memory. Browser storage would repair refreshes for one device, but it
would create a second source of truth and would not support the selected server-backed lifecycle.
## Decision
Kandev stores Quick Terminal descriptors in a backend-owned, authenticated user/workspace-scoped
store. The descriptor owns the browser-generated UUID, stable workspace sequence, latest host-shell
session association, and bounded lifecycle snapshot. Quick Terminal boot and resync read that
store, while lifecycle mutations update it and explicit descriptor deletion owns stopping/removing
the tab.
The host-shell PTY manager remains the runtime owner of processes and rolling output. Its entries
are intentionally ephemeral: after a backend restart, persisted descriptors remain discoverable but
their missing session is marked exited/unavailable and is never replaced implicitly. Session IDs
are accepted for a descriptor only when the backend can prove that the manager entry belongs to the
descriptor's bounded client key.
## Consequences
- Reloads, browser restarts, and another client for the same authenticated user/workspace can
restore terminal tabs without duplicating host shells.
- Descriptor membership and sequence allocation are protected by backend authorization and durable
storage rather than client-controlled browser state.
- A backend restart loses PTY output and requires an explicit new shell, but it does not silently
erase the user's tab strip.
- Lifecycle writes add API and persistence work to terminal creation, reattachment, exit, and
close; failures must remain visible and must not affect sibling tabs.
## Alternatives Considered
1. **Keep descriptors in memory only.** Rejected because refresh loses the tab and makes a live
detached PTY unreachable.
2. **Use sessionStorage or localStorage.** Rejected because it is device-local, can become stale,
cannot coordinate authenticated clients, and would compete with the backend as the durable owner.
3. **Add descriptors to the general user-settings JSON blob.** Rejected because terminal rows have
independent create/update/delete lifecycle, per-workspace sequence allocation, and concurrent
sibling mutations that are clearer and safer in a dedicated descriptor store.
+1
View File
@@ -122,3 +122,4 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 2026-08-04-navigation-manifest-boundaries | [Centralize Navigation and Namespace Plugin Destinations](2026-08-04-navigation-manifest-boundaries.md) | accepted | frontend | 2026-08-04 |
| 2026-08-04-remote-contribution-bindings | [Bind Remote Contributions to Target Repositories](2026-08-04-remote-contribution-bindings.md) | accepted | backend, protocol, security, GitHub, GitLab | 2026-08-04 |
| 2026-08-03-scope-and-merge-repository-secrets | [Scope and Merge Repository Secrets](2026-08-03-scope-and-merge-repository-secrets.md) | accepted | backend, frontend, security, protocol | 2026-08-03 |
| 2026-08-05-server-owned-quick-terminal-descriptors | [Server-Owned Quick Terminal Descriptors](2026-08-05-server-owned-quick-terminal-descriptors.md) | accepted | backend, frontend, protocol, security | 2026-08-05 |
@@ -0,0 +1,185 @@
---
spec: docs/specs/quick-terminal/spec.md
created: 2026-08-05
status: complete
---
# Implementation Plan: Quick Terminal Refresh Persistence
## Overview
Quick Terminal currently loses its tab descriptors on a full page reload because they exist only
in the in-memory Zustand UI slice. This repair adds a backend-owned descriptor lifecycle scoped to
the authenticated user and workspace, returns those descriptors through boot and resync, and
reattaches a live host-shell session through the existing PTY status/stream routes. The PTY remains
ephemeral across backend restarts; a stale descriptor is retained as exited/unavailable and never
starts a replacement implicitly.
The work is sequential: the descriptor storage and backend contract must exist before frontend
hydration can consume it, and the browser/E2E proof depends on both sides of that contract.
## Confirmed root cause
`quick-terminal-actions.ts` creates `QuickTerminalTab` descriptors only in
`quickChat.terminalTabs`. `StateProvider` creates a new store on reload, while
`addQuickChatState` restores only task-backed conversation sessions. The host-shell manager may
still hold the detached PTY, but no `tabId`/`sessionId` descriptor is booted back into the frontend,
so the shared dialog has no terminal tab to render or attach.
## Backend
### Descriptor storage and service
- Add a `quickterminal` backend package with model, SQLite repository, service, and focused tests.
- Create a durable `quick_terminal_tabs` table with `tab_id`, `user_id`, `workspace_id`, nullable
`session_id`, positive workspace-local `sequence`, lifecycle status, nullable exit code/error,
and created/updated timestamps. Enforce user/workspace/tab and user/workspace/sequence
uniqueness, index user/workspace listing, and allocate sequences atomically without reuse.
- Resolve the authenticated user from `authn.IdentityFromContext`; preserve the synthetic default
identity when authentication is disabled. Every read and mutation must authorize the workspace
through `taskService.AuthorizeWorkspaceAccess` and scope the repository query by user ID.
- Reconcile rows against the `loginpty.Manager`: a live host-shell manager entry keyed by the
descriptor's UUID supplies the current session and running state; a missing entry clears the
session association and yields exited/unavailable without creating a PTY.
- Bound and validate all IDs and lifecycle fields at the service boundary. A client may update only
its own descriptor and may associate only the manager session whose bounded host-shell key
matches that descriptor.
### API and boot contract
- Register `GET`, `POST`, `PATCH`, and `DELETE /api/v1/quick-terminal-tabs` routes in a dedicated
handler/controller layer. `POST` is idempotent for a user/tab UUID; `DELETE` stops the associated
live host shell best-effort before removing the row and treats a missing row as already closed.
- Keep `/api/v1/host-shell/start` and the existing agent-login session status, stream, resize, and
stop routes compatible. Preserve the legacy singleton host-shell behavior when `client_id` is
omitted and keep `_host_shell` as the public agent identity.
- Expose the minimal manager lookup/key helper needed by the descriptor service without changing
`Manager.Start` callers or exit-callback semantics.
- Wire the repository/service into `backendapp/storage.go`, `backendapp/types.go`, route
registration, and `boot_state.go`. `quickChat.terminalTabs` must be present for the resolved
workspace and use the same reconciliation service as HTTP resync.
## Frontend
### API and wire mapping
- Add `apps/web/lib/api/domains/quick-terminal-api.ts` and the matching HTTP descriptor types.
Export list/create/update/delete calls through the API barrel; do not send descriptors through
Quick Chat task rename/delete/sync APIs.
- Map the backend snake-case descriptor payload into the existing `QuickTerminalTab` shape and
include terminal descriptors in the boot `HydrationState` and workspace resync response.
### State and hydration
- Extend the UI slice with server-descriptor adoption/reconciliation actions that preserve local
active-kind and last-terminal selection, keep setup/chat placeholders local, and never discard a
sibling terminal during conversation resync.
- Make new terminal creation persist the browser-generated UUID before starting a shell, and make
lifecycle/session updates durable without replacing a server descriptor with an empty local
array. Failed descriptor writes remain visible as an understandable terminal error and do not
affect siblings.
- On boot, reload, workspace switch, and socket reconnect, reconcile by `tabId` and workspace.
Preserve backend ordering/sequence, restore a live `sessionId`, and mark stale sessions
exited/unavailable without implicit replacement.
### Terminal lifecycle and shared dialog
- Update `use-quick-chat-modal.ts` and the terminal tab view to persist start/reattach/exit/error
state and to delete the server descriptor on explicit close. A stop/delete 404 is already
stopped; other failures retain the descriptor and surface the localized error.
- Ensure a restored `exited`/`error`/unavailable descriptor does not pass through the PTY view's
start-on-mount path. Only a newly created `connecting` descriptor may start a shell without a
session; a restored live descriptor attaches by `sessionId`.
- Preserve the existing detach-on-unmount and late-start ownership guarantees: a detached start
that resolves still records its session and a later explicit close stops it; switching tabs or
dismissing the dialog never stops it.
- Keep the existing one-dialog desktop/tablet/phone geometry, lazy xterm loading, focus return,
fixed terminal labels, and touch-safe controls unchanged.
## Tests
- **What:** descriptor schema, atomic sequence allocation, user/workspace isolation, idempotent
create, live-session reconciliation, stale-session clearing, and close/delete semantics.
**Files:** `apps/backend/internal/quickterminal/repository/sqlite_test.go`,
`apps/backend/internal/quickterminal/service/service_test.go`, and
`apps/backend/internal/quickterminal/handlers/handlers_test.go`.
**How:** real SQLite repository tests plus table-driven service and `httptest` handler tests;
include two users, two workspaces, duplicate tab IDs, missing PTYs, and stop/delete 404s.
- **What:** boot payload and workspace resync return persisted terminal descriptors without
erasing conversations or terminals from another workspace.
**Files:** `apps/backend/internal/backendapp/helpers_test.go`,
`apps/web/lib/state/hydration/hydrator.test.ts`, and
`apps/web/lib/state/slices/ui/quick-chat-sync.test.ts`.
**How:** boot fixtures with a live and stale descriptor, then pure state reconciliation tests
with empty server conversation lists and multiple workspaces.
- **What:** browser API mapping and store actions persist create/update/remove while retaining
active terminal selection and preventing an exited descriptor from starting a replacement.
**Files:** `apps/web/lib/api/domains/quick-terminal-api.test.ts`,
`apps/web/lib/state/slices/ui/quick-chat-actions.test.ts`,
`apps/web/components/quick-chat/use-quick-chat-modal.test.ts`,
`apps/web/components/quick-chat/quick-terminal-tab-view.test.tsx`, and
`apps/web/components/settings/pty-terminal-view.test.tsx`.
**How:** mocked API, xterm, WebSocket, ResizeObserver, and StrictMode tests; cover reload
reattachment, stale-session no-start, detached late start followed by close, natural exit, 404
close, and sibling isolation.
## E2E Tests
- **Scenario:** GIVEN a running terminal with marker output, WHEN the user reloads the page and
opens Quick Chat, THEN exactly one terminal tab with the same sequence reconnects to the same
PTY and replays the marker without a second shell.
**File:** `apps/web/e2e/tests/terminal/quick-terminal.spec.ts`.
**What to verify:** shared dialog identity, tab count/label, marker output, no standalone
terminal dialog/footer, and cleanup that explicitly closes every surviving terminal in `finally`.
- **Scenario:** GIVEN a persisted descriptor after the backend has restarted, WHEN the user opens
Quick Chat, THEN the tab is visible as exited/unavailable and **New Terminal** is required for a
new shell.
**File:** `apps/web/e2e/tests/terminal/quick-terminal.spec.ts` (or a focused backend fixture
helper if a process restart cannot preserve the test database).
**What to verify:** accessible lifecycle status, no implicit new PTY, explicit replacement, and
workspace filtering.
- **Scenario:** GIVEN a phone viewport, WHEN the user reloads and reopens the shared surface, THEN
the persisted terminal remains contained in the dynamic viewport and the terminal strip/menu
retains its touch-safe controls and zero document horizontal overflow.
**File:** `apps/web/e2e/tests/terminal/mobile-quick-terminal.spec.ts`.
**What to verify:** same-session marker, terminal panel height, 44px controls/menu rows, focus/
dismissal, and teardown of all surviving tabs.
## Verification Results
- Backend: `go test ./internal/backendapp ./internal/quickterminal/... ./internal/agent/loginpty/... -count=1` passed (279 test cases/subcases); `make -C apps/backend lint` passed with 0 issues.
- Frontend: focused Vitest passed (9 files, 124 tests); web typecheck, changed-file ESLint, i18n ratchet, and i18n checks passed. The i18n check retained its existing advisory 657 zh-cn catalog issues and 5 orphan English keys.
- E2E: managed desktop Chromium `quick-terminal.spec.ts` passed 2/2; managed Pixel 5 `mobile-quick-terminal.spec.ts` passed 1/1. Both runs included reload/reattachment and explicit terminal cleanup.
## Implementation Waves And Parallel Candidates
Wave 1:
- [x] [Task 01: Persist Quick Terminal descriptors](task-01-persist-descriptors.md) (`done`)
Wave 2:
- [x] [Task 02: Expose descriptor API and boot state](task-02-descriptor-api-boot.md) (`done`)
Wave 3:
- [x] [Task 03: Reconcile descriptors in the web app](task-03-web-descriptor-reconciliation.md) (`done`)
Wave 4:
- [x] [Task 04: Prove refresh reattachment](task-04-refresh-reattachment-e2e.md) (`done`)
All tasks are sequential. The backend schema, host-shell manager lookup, boot payload, frontend
hydration, and E2E fixtures share the same lifecycle contract, so no task is parallel-safe.
## Risks
- A durable row can outlive its in-memory PTY. Reconciliation must clear stale session IDs and must
not turn a refresh into an implicit new shell.
- Create, start, detach, late completion, exit, and explicit close can race. Stable UUIDs and
server-side idempotency must prevent duplicate sessions and orphaned descriptors.
- Multiple authenticated clients can mutate sibling tabs concurrently. Repository updates must be
row-scoped and sequence allocation must not overwrite unrelated descriptors.
- Host-shell permissions remain those of the backend user and are not task-worktree isolated.
- The existing rolling output buffer remains bounded and non-durable; a refresh after output has
aged out may restore the tab without restoring all prior text.
@@ -0,0 +1,65 @@
---
id: "01-persist-descriptors"
title: "Persist Quick Terminal descriptors"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/quick-terminal/spec.md"
---
# Task 01: Persist Quick Terminal descriptors
## Acceptance
- A durable SQLite repository stores user/workspace/tab identity, non-reused sequence, session
association, and bounded lifecycle fields with user/workspace uniqueness.
- Repository/service operations are idempotent where specified, authorize ownership through the
supplied user/workspace boundary, and reconcile live versus stale host-shell sessions without
starting a replacement.
- The host-shell manager exposes only the bounded lookup/key helper required by this service;
existing agent-login uniqueness and public agent identity remain unchanged.
## Verification
```bash
(cd apps/backend && go test ./internal/quickterminal/... ./internal/agent/loginpty/...)
```
## Files likely touched
- `apps/backend/internal/quickterminal/models/tab.go` (new)
- `apps/backend/internal/quickterminal/repository/sqlite.go` (new)
- `apps/backend/internal/quickterminal/repository/sqlite_test.go` (new)
- `apps/backend/internal/quickterminal/service.go` (new)
- `apps/backend/internal/quickterminal/service_test.go` (new)
- `apps/backend/internal/quickterminal/handler_test.go` (new)
- `apps/backend/internal/agent/loginpty/manager.go`
- `apps/backend/internal/agent/loginpty/manager_test.go`
## Dependencies
None.
## Parallelism
Sequential. The repository and manager lookup form the backend contract consumed by every later
task.
## Inputs
- Spec sections: Data model, State machine, Permissions, Failure modes, and Persistence guarantees.
- ADR-2026-08-05-server-owned-quick-terminal-descriptors.
- Existing `apps/backend/internal/terminal/repository` schema and test patterns.
- Existing `loginpty.Manager.StartWithKey` internal-key separation and rolling-buffer lifecycle.
## Output contract
Report model/repository/service files, migration/ownership decisions, exact test result, and any
backend contract risk. Update this task and the parent plan only after the focused tests pass.
## Results
- Implemented durable user/workspace/tab descriptors, atomic non-reused sequences, lifecycle reconciliation, and manager-key ownership checks.
- Added host-shell client-ID idempotency while preserving the legacy singleton and stable `_host_shell` public identity; native Windows shell selection now covers PowerShell, `COMSPEC`, and `cmd.exe`.
- `(cd apps/backend && go test ./internal/quickterminal/... ./internal/agent/loginpty/... -count=1)` passed (21 test cases/subcases).
@@ -0,0 +1,63 @@
---
id: "02-descriptor-api-boot"
title: "Expose descriptor API and boot state"
status: done
wave: 2
depends_on: ["01-persist-descriptors"]
plan: "plan.md"
spec: "../../specs/quick-terminal/spec.md"
---
# Task 02: Expose descriptor API and boot state
## Acceptance
- Authenticated GET/POST/PATCH/DELETE descriptor routes implement the documented idempotency,
workspace authorization, lifecycle validation, best-effort stop, and already-closed behavior.
- Quick Chat boot includes the resolved workspace's persisted terminal descriptors, reconciled with
the same live login-PTY manager used by the API; task-backed conversation boot remains unchanged.
- The repository/service is wired into storage and route construction without changing the legacy
host-shell or Agents login endpoints.
## Verification
```bash
(cd apps/backend && go test ./internal/quickterminal/...)
(cd apps/backend && go test ./internal/backendapp -run 'TestBootPayloadRestoresQuickChat|Test.*QuickTerminal')
```
## Files likely touched
- `apps/backend/internal/quickterminal/handler_test.go` (new)
- `apps/backend/internal/backendapp/storage.go`
- `apps/backend/internal/backendapp/types.go`
- `apps/backend/internal/backendapp/helpers.go`
- `apps/backend/internal/backendapp/boot_state.go`
- `apps/backend/internal/backendapp/helpers_test.go`
- `apps/backend/internal/backendapp/boot_state_routes_test.go` (if route wiring coverage belongs there)
## Dependencies
Task 01.
## Parallelism
Sequential. Route, boot, auth, and storage wiring must agree on one descriptor contract.
## Inputs
- Spec API surface and boot/resync requirements.
- Task 01 service/repository interfaces.
- Existing user/task workspace authorization and `userhandlers.RegisterRoutes` patterns.
- Existing Quick Chat boot fixtures in `apps/backend/internal/backendapp/helpers_test.go`.
## Output contract
Report routes, boot payload shape, auth/workspace isolation evidence, exact backend tests, and any
compatibility note for legacy clients. Synchronize task/plan status and results.
## Results
- Registered the authenticated descriptor GET/POST/PATCH/DELETE routes, wired SQLite storage and the shared login-PTY manager, and added boot-state restoration with stale-session reconciliation.
- `(cd apps/backend && go test ./internal/backendapp ./internal/quickterminal/... ./internal/agent/loginpty/... -count=1)` passed (279 test cases/subcases).
- `(cd apps/backend && make lint)` passed with 0 issues; legacy agent-login and host-shell routes remain covered by the same backend suite.
@@ -0,0 +1,83 @@
---
id: "03-web-descriptor-reconciliation"
title: "Reconcile descriptors in the web app"
status: done
wave: 3
depends_on: ["02-descriptor-api-boot"]
plan: "plan.md"
spec: "../../specs/quick-terminal/spec.md"
---
# Task 03: Reconcile descriptors in the web app
## Acceptance
- Web API types and calls map the server descriptor contract without routing terminal rows through
Quick Chat conversation APIs.
- Boot, workspace resync, and reconnect preserve persisted terminals, active-kind/last-terminal
selection, and sibling isolation while adopting server sequence/session/status values.
- New terminal creation and lifecycle changes persist the descriptor; restored exited/error or
unavailable tabs render status and never start a replacement implicitly.
- Detach-on-unmount, StrictMode replay, late start resolution, natural exit disarming, explicit
close/404 handling, and existing Agents stop-on-unmount behavior remain correct.
## Verification
```bash
(cd apps && pnpm install --frozen-lockfile)
(cd apps && pnpm --filter @kandev/web exec vitest run lib/api/domains/quick-terminal-api.test.ts lib/state/slices/ui/quick-chat-actions.test.ts lib/state/slices/ui/quick-chat-sync.test.ts lib/state/hydration/hydrator.test.ts components/quick-chat/use-quick-chat-modal.test.ts components/quick-chat/quick-terminal-tab-view.test.tsx components/settings/pty-terminal-view.test.tsx)
(cd apps/web && pnpm run typecheck)
(cd apps && pnpm --filter @kandev/web exec eslint lib/api/domains/quick-terminal-api.ts lib/types/http-quick-terminal.ts lib/state/slices/ui/types.ts lib/state/slices/ui/quick-terminal-actions.ts lib/state/slices/ui/quick-chat-sync.ts lib/state/default-state.ts lib/state/hydration/hydrator.ts hooks/use-quick-chat-resync.ts components/quick-chat/use-quick-chat-modal.ts components/quick-chat/quick-terminal-tab-view.tsx components/settings/pty-terminal-view.tsx)
(cd apps && pnpm --filter @kandev/web run i18n:ratchet)
(cd apps && pnpm --filter @kandev/web run i18n:check)
```
## Files likely touched
- `apps/web/lib/types/http-quick-terminal.ts` (new)
- `apps/web/lib/api/domains/quick-terminal-api.ts` (new)
- `apps/web/lib/api/domains/quick-terminal-api.test.ts` (new)
- `apps/web/lib/api/index.ts`
- `apps/web/lib/state/slices/ui/types.ts`
- `apps/web/lib/state/slices/ui/quick-terminal-actions.ts`
- `apps/web/lib/state/slices/ui/quick-chat-sync.ts`
- `apps/web/lib/state/slices/ui/quick-chat-sync.test.ts`
- `apps/web/lib/state/default-state.ts`
- `apps/web/lib/state/hydration/hydrator.ts`
- `apps/web/lib/state/hydration/hydrator.test.ts`
- `apps/web/hooks/use-quick-chat-resync.ts`
- `apps/web/hooks/use-quick-terminal-launcher.ts`
- `apps/web/components/quick-chat/use-quick-chat-modal.ts`
- `apps/web/components/quick-chat/use-quick-chat-modal.test.ts`
- `apps/web/components/quick-chat/quick-terminal-tab-view.tsx`
- `apps/web/components/quick-chat/quick-terminal-tab-view.test.tsx`
- `apps/web/components/settings/pty-terminal-view.tsx`
- `apps/web/components/settings/pty-terminal-view.test.tsx`
- `apps/web/src/locales/en/sidebar.json`
## Dependencies
Task 02.
## Parallelism
Sequential. API, hydration, store, lifecycle, and modal ownership share the same tab identity and
must be implemented as one frontend contract.
## Inputs
- Spec Data model, API surface, State machine, Failure modes, and Scenarios.
- Existing `QuickTerminalTab`, `quick-terminal-actions`, `quick-chat-sync`, and detachable PTY
lifecycle behavior.
- Existing server conversation resync and localized terminal lifecycle status components.
## Output contract
Report changed frontend files, behavior for stale sessions and late starts, exact focused test/lint/
typecheck/i18n outcomes, and any unresolved concurrency risk. Synchronize task/plan status.
## Results
- Added the descriptor API mapping, boot/resync reconciliation, durable lifecycle updates, restored-session attach behavior, stale-session status UI, and descriptor-owned close flow.
- `(cd apps && pnpm --filter @kandev/web exec vitest run --run lib/api/domains/quick-terminal-api.test.ts lib/state/slices/ui/quick-chat-actions.test.ts lib/state/slices/ui/quick-chat-sync.test.ts lib/state/hydration/hydrator.test.ts hooks/use-quick-chat-resync.test.ts components/quick-chat/quick-terminal-tab-view.test.tsx components/quick-chat/use-quick-chat-modal.test.ts components/settings/pty-terminal-view.test.tsx components/app-sidebar/app-sidebar-new-task-item.test.tsx)` passed (9 files, 124 tests).
- Web typecheck, changed-file ESLint, i18n ratchet, and i18n checks passed. The i18n check reported only the existing advisory 657 zh-cn catalog issues and 5 orphan English keys.
@@ -0,0 +1,59 @@
---
id: "04-refresh-reattachment-e2e"
title: "Prove refresh reattachment"
status: done
wave: 4
depends_on: ["03-web-descriptor-reconciliation"]
plan: "plan.md"
spec: "../../specs/quick-terminal/spec.md"
---
# Task 04: Prove refresh reattachment
## Acceptance
- Desktop E2E creates a terminal, writes a marker, reloads, reopens Quick Chat, and verifies one
same-sequence tab reattaches to the same marker-bearing PTY without duplication.
- Mobile E2E covers reload/reopen containment, touch-safe controls, internal terminal scrolling,
focus/dismissal, and zero document horizontal overflow.
- Every scenario explicitly closes/stops all surviving terminal descriptors in `finally` so worker
state does not leak into the next test.
## Verification
```bash
(cd apps/web && pnpm e2e --project=chromium tests/terminal/quick-terminal.spec.ts)
(cd apps/web && pnpm e2e --project=mobile-chrome tests/terminal/mobile-quick-terminal.spec.ts)
```
## Files likely touched
- `apps/web/e2e/tests/terminal/quick-terminal.spec.ts`
- `apps/web/e2e/tests/terminal/mobile-quick-terminal.spec.ts`
- `apps/web/e2e/helpers/layout-assertions.ts` (only if a shared assertion is needed)
## Dependencies
Task 03.
## Parallelism
Sequential. These tests share the persisted descriptor and backend worker lifecycle with the
implementation tasks.
## Inputs
- Spec refresh, backend-restart, cross-client, mobile, and cleanup scenarios.
- Existing `closeSurvivingQuickTerminals` helper and marker-buffer assertions.
- Existing Pixel 5 project configuration and backend fixture reset/restart behavior.
## Output contract
Report exact Playwright commands, pass counts, browser/viewport evidence, teardown evidence, and
any environment-only limitations. Synchronize task/plan status and verification results.
## Results
- `(cd apps/web && pnpm e2e:run --host --project chromium tests/terminal/quick-terminal.spec.ts)` passed (2/2), including reload/reopen and marker replay.
- `(cd apps/web && pnpm e2e:run --host --project mobile-chrome tests/terminal/mobile-quick-terminal.spec.ts)` passed (1/1) on the Pixel 5 project, including dynamic-viewport containment, touch-safe controls, internal scrolling, focus/dismissal, and zero horizontal overflow.
- Both managed runs completed fixture teardown, and the tests explicitly closed surviving terminal descriptors in `finally` blocks.
+297
View File
@@ -0,0 +1,297 @@
---
spec: docs/specs/quick-terminal/spec.md
created: 2026-08-03
updated: 2026-08-04
status: completed
---
# Implementation Plan: Quick Chat and Terminal Tabs
## Overview
The shipped Quick Terminal baseline already exposes the host PTY from desktop, tablet, and phone,
but it owns a separate provider/dialog and the backend permits only one host shell. This revision
keeps those launchers while moving terminal content into the existing workspace-scoped Quick Chat
tab surface. The backend first gains per-tab idempotent host-shell sessions, then the frontend
separates reusable PTY rendering from stop-on-dialog-close ownership, adds browser-local terminal
tab state, and replaces the Quick Chat plus action with a grouped creation menu.
Tasks 01–03 remain the completed record of the shipped baseline. Tasks 04–07 complete this
revision's backend, lifecycle, shared-tab, and viewport verification work.
## Backend
### Per-tab host-shell idempotency
- Extend the optional JSON body handled by
`apps/backend/internal/agent/loginpty/handlers.go:httpStartHostShell` with
`client_id: string`.
- Preserve the legacy singleton key when `client_id` is omitted so
**Settings → Agents** and older clients remain idempotent exactly as they are today.
- When `client_id` is present, derive a bounded internal session key from
`_host_shell` plus that client ID. Repeated starts for one client ID return the same running PTY;
distinct client IDs create independent PTYs.
- Keep the public `agent_id` in the returned `Status` equal to `_host_shell`. Add an internal
manager key/owner distinction rather than exposing the client id as an agent identity or passing
it to the discovery-cache exit callback.
- Require a present client ID to parse as a UUID and reject malformed values with
`400 Bad Request`; do not use a
client-provided value as a command, path, environment variable, or log field without bounding it.
- Leave the session-ID status, stream, resize, and stop routes unchanged. Stopping one per-tab
session must not remove another tab's session or an agent-login session.
### Manager lifecycle
- Extend `apps/backend/internal/agent/loginpty/manager.go` so uniqueness is keyed separately from
the stable logical `AgentID`. Existing `Manager.Start(agentID, ...)` callers retain one active
login PTY per agent.
- Store the internal key on `Session` for manager-map cleanup; continue indexing the public
session route by the generated session ID.
- Preserve the existing idle timeout, hard timeout, 16 KB rolling output buffer, subscriber
detach/reconnect behavior, and exit callback semantics.
## Frontend
### Host-shell client and reusable PTY view
- Extend `apps/web/lib/api/domains/settings-api.ts:startHostShell` with an optional
`clientId`/request field serialized as `client_id`. Agent-login start requests remain unchanged.
- Extract the xterm/resize/WebSocket portion of
`apps/web/components/settings/pty-terminal-dialog.tsx` into a reusable terminal view, likely
`apps/web/components/settings/pty-terminal-view.tsx`.
- Give the extracted view an explicit lifecycle contract:
- the default dialog mode starts a session and stops it on unmount, preserving every Agents/login
caller;
- the Quick Chat tab mode can start with a stable client ID or attach to a stored session ID,
reports start/exit/error changes to the tab store, and only closes its WebSocket/xterm on
unmount;
- explicit terminal-tab close remains the owner of the stop request.
- Preserve the StrictMode mount-generation guard. A pending start that resolves after its tab was
explicitly removed must be stopped; a view that merely detached because of a tab switch or dialog
dismissal must not stop it.
- Reattachment uses the existing status/stream routes and buffered output. A missing session is
reported as exited/unavailable and does not trigger an implicit replacement.
- Keep `PtyTerminalDialog` and `HostShellDialog` as wrappers for the Agents-page and login/auth
surfaces; remove only their use as the standalone Quick Terminal presentation.
### Shared workspace tab state
- Extend `apps/web/lib/state/slices/ui/types.ts` with a discriminated
`QuickTerminalTab` descriptor matching the spec: `tabId`, `workspaceId`, `sessionId`,
`sequence`, `status`, optional `exitCode`, and optional `error`.
- Keep backend-restored conversation sessions in `quickChat.sessions`. Add browser-local terminal
tabs and explicit active-kind/last-terminal state instead of widening
`QuickChatSessionKind = "chat" | "config"`; terminal tabs have no task/session-message contract.
- Add focused UI-slice actions for:
- reuse-or-create terminal launch for a workspace;
- always-new terminal creation from the add menu;
- terminal session/status updates;
- terminal activation;
- explicit terminal removal and adjacent same-workspace fallback, closing the modal only when no
conversation, setup, or terminal tab remains.
- Conversation activation preserves the existing `chat` versus `config` launcher filtering
without discarding the last active terminal. Terminal activation does not overwrite conversation
selection. This lets each launcher restore its own matching content.
- Generate the stable tab/client ID in the browser with `crypto.randomUUID()`. Assign terminal
sequence labels within a workspace without colliding with another open terminal.
- Update `apps/web/lib/state/slices/ui/quick-chat-sync.ts`,
`apps/web/lib/state/default-state.ts`, and
`apps/web/lib/state/hydration/hydrator.ts` only as needed to ensure boot/resync replacement of
server conversation sessions preserves local terminal descriptors and active-terminal state.
Terminal descriptors must never be sent to Quick Chat rename/delete/sync APIs.
### One Quick Chat dialog
- Update `apps/web/components/quick-chat/quick-chat-modal.tsx` to derive a shared active tab from
the conversation and terminal state. Render:
- `QuickChatSessionView`, `QuickChatSetup`, or `ConfigChatSetup` for conversation tabs;
- a new `apps/web/components/quick-chat/quick-terminal-tab-view.tsx` for terminal tabs.
- Generalize `QuickChatTabItem` or introduce a sibling tab item so terminal tabs show an accessible
terminal icon and fixed `Terminal N` label without entering chat rename/delete code.
- Terminal tab close calls the shared stop endpoint. Treat `404 session not found` as already
stopped; retain the tab and surface an error for other failures. Closing a chat tab continues to
use its confirmation dialog and backing-task deletion.
- Dismissing the modal removes abandoned chat setup placeholders as today but retains terminal
descriptors and sessions. Switching tabs only detaches the selected terminal view.
- Keep the current horizontal overflow owner for the tab strip and the current resizable
tablet/desktop and full-height phone dialog geometry. The terminal fills the content region below
the strip and does not render a nested `Dialog`, title, description, or Done footer.
### Grouped plus menu
- Replace the direct plus-button `onNewChat` handler with a Radix
`DropdownMenu` implemented in a focused component such as
`apps/web/components/quick-chat/quick-tab-add-menu.tsx`.
- Mirror the task-detail add-menu information hierarchy without importing task/Dockview state:
- **Agents** label and **New Agent**;
- separator;
- **Terminals** label and **New Terminal**.
- Keep existing conversation and terminal tabs selectable from the horizontal tab strip; the
creation menu does not duplicate those rows.
- Keep the plus trigger at least 44×44 px on phone. Reuse the existing global Radix menu mobile
treatment so the menu becomes a contained, safe-area-aware bottom sheet with 44 px rows on
coarse/narrow viewports.
### Launcher and provider ownership
- Change `apps/web/hooks/use-quick-terminal-launcher.ts` to accept the active workspace ID and
dispatch the reuse-or-create action into the shared tab store.
- Update the sidebar, tablet header, and phone header callers to pass their workspace ID. Keep their
current visibility, order, test IDs, accessible labels, and hitboxes.
- Extend `apps/web/components/quick-chat/quick-chat-provider.tsx` so workspace resolution considers
the active terminal as well as the active conversation and so one provider renders the only
shared dialog.
- Move launcher focus capture/restoration into the shared provider/launcher contract. Preserve the
pointer-only sidebar tooltip behavior after focus returns.
- Remove `QuickTerminalProvider` from `apps/web/src/app-shell.tsx` and
`apps/web/app/layout.tsx`; delete the provider component/test after its focus and lazy-loading
responsibilities are covered by the shared provider. Keep terminal code lazy enough that xterm
does not enter the initial application bundle before a terminal tab is rendered.
### Internationalization
- Add render-time translations for **Agents**, **Terminals**, **New Agent**, **New Terminal**,
`Terminal {{count}}`, terminal-tab accessible labels, and terminal lifecycle errors in the
appropriate English namespace.
- Do not translate tab IDs, backend session IDs, or enum discriminants. Use `count` for numbered or
plural copy and include the changed paths in the i18n ratchet check.
### Mobile design contract
- **Desktop outcome:** the sidebar terminal launcher opens the shared large Quick Chat dialog on the
last terminal or a first new terminal; the plus menu creates either content kind while the tab
strip switches between existing content.
- **Mobile entry point:** the existing 44 px Home/Tasks terminal and Quick Chat actions remain. The
terminal action selects terminal content inside the same full-height dialog as Quick Chat.
- **Nearest shipped exemplars:** `quick-chat-modal.tsx` owns the full-height phone/floating wider
surface and horizontal tab strip; `dockview-add-panel-items.tsx`,
`session-reopen-menu.tsx`, and `terminal-reopen-menu.tsx` supply the grouped menu hierarchy;
the global Radix menu treatment supplies the phone bottom sheet.
- **Hierarchy and primary action:** the fixed strip identifies the active tab; the selected chat or
terminal is the sole content focus. The plus control is the visible creation overflow and the
phone close control remains fixed.
- **Presentation rationale:** conversations and terminals are frequently revisited dense content,
so they share a full-height phone workspace rather than nesting another dialog or temporary
drawer. Only the short creation choice rises in the menu bottom sheet.
- **Geometry:** `100dvh` on phone, current bounded `85vh` floating geometry on wider viewports,
one selected-content scroll owner, safe-area clearance, a horizontally scrollable tab strip, and
no document horizontal overflow.
- **Shared logic:** terminal identity, lifecycle, workspace filtering, active selection, and API
behavior are shared across viewports; only launcher placement and existing responsive dialog/menu
presentation differ.
- **Mobile proof:** Pixel 5 coverage taps both launchers, opens the grouped menu, creates and switches
terminal tabs, verifies 44 px controls/menu rows, terminal containment, internal scrolling,
dismissal, focus return, and zero document horizontal overflow.
## Tests
- **What:** a host-shell client ID is idempotent for one tab while distinct IDs create independent
sessions and legacy starts remain singleton.
**Files:** `apps/backend/internal/agent/loginpty/manager_test.go` and a focused
`apps/backend/internal/agent/loginpty/handlers_test.go`.
**How:** table-driven manager and `httptest` handler tests cover same/different/missing/invalid
keys, independent stop, stable public agent ID, and unchanged agent-login uniqueness.
- **What:** standard PTY dialogs stop on unmount while Quick Chat terminal views detach, reattach,
and stop only after explicit tab close.
**Files:** new focused tests beside
`apps/web/components/settings/pty-terminal-view.tsx` and
`apps/web/components/quick-chat/quick-terminal-tab-view.tsx`.
**How:** mock xterm, WebSocket, ResizeObserver, and API calls; exercise StrictMode replay, pending
start removal, detached reattachment, exit, 404 stop, and sibling isolation.
- **What:** store actions implement reuse-or-create versus always-new behavior, per-workspace last
selection, deterministic close fallback, and server reconciliation that preserves terminal tabs.
**Files:** `apps/web/lib/state/slices/ui/quick-chat-actions.test.ts`,
`apps/web/lib/state/slices/ui/quick-chat-sync.test.ts`, and
`apps/web/lib/state/hydration/hydrator.test.ts`.
**How:** pure Zustand/helper tests with two workspaces, several chat kinds, several terminal IDs,
and empty server resync.
- **What:** the shared modal renders mixed tabs and a grouped creation menu, while both launcher
kinds select the intended last tab and restore focus; conversation tabs also expose context-menu
rename.
**Files:** `apps/web/components/quick-chat/quick-chat-modal.test.ts`, a new menu component test,
`apps/web/hooks/use-quick-chat-launcher.test.ts`, the replacement terminal-launcher/provider
tests, and existing sidebar/mobile-header component tests.
**How:** mocked store/API/component tests assert menu grouping, creation callbacks, context-menu
rename, accessible labels, workspace gating, focus restoration, and tooltip behavior.
## E2E Tests
- **Scenario:** first terminal launch creates one tab; dismissing and reopening via the sidebar
selects the same session and replays its marker output.
**File:** `apps/web/e2e/tests/terminal/quick-terminal.spec.ts`.
**What to verify:** shared Quick Chat dialog identity, one tab after reopen, same terminal marker,
no standalone Quick Terminal dialog/footer, focus return, and no stale tooltip.
- **Scenario:** the plus menu creates a second independent terminal and switches existing chats and
terminals without duplication.
**File:** `apps/web/e2e/tests/terminal/quick-terminal.spec.ts`.
**What to verify:** grouped labels/rows, distinct terminal labels and command output, terminal
shortcut reuse, Quick Chat shortcut selection, tab close stopping only one session, and fallback.
- **Scenario:** the low-level host-shell API supports same-key idempotency, different-key
concurrency, independent command streams, independent stop, and omitted-key compatibility.
**File:** `apps/web/e2e/tests/settings/host-shell-pty.spec.ts`.
**What to verify:** response/session identities and live WebSocket command markers for two PTYs.
- **Scenario:** phone users can open the shared surface, invoke the add menu as a touch-safe bottom
sheet, create/switch terminals, dismiss, and return to the launcher.
**File:** `apps/web/e2e/tests/terminal/mobile-quick-terminal.spec.ts`.
**What to verify:** 44 px controls/menu rows, dynamic-viewport containment, terminal height,
safe-area/internal scrolling, same-session reopen, and zero document horizontal overflow.
- Re-run the existing Quick Chat desktop/mobile happy paths affected by the shared dialog:
`apps/web/e2e/tests/chat/quick-chat.spec.ts` and the relevant
`apps/web/e2e/tests/chat/mobile-quick-chat-entry.spec.ts` scenarios.
## Verification Results
Completed. Tasks 04–06 record the backend, lifecycle, state, UI, typecheck, lint, and i18n
results. Task 07 records the final managed desktop run (20 passed) and Pixel 5 run (5 passed),
including backend/Vite rebuilds and worker teardown evidence.
## Implementation Waves And Parallel Candidates
Historical shipped baseline:
- [x] [Task 01: Build the shared Quick Terminal UI](task-01-quick-terminal-ui.md) (`done`)
- [x] [Task 02: Prove Quick Terminal across viewports](task-02-quick-terminal-e2e.md) (`done`)
- [x] [Task 03: Fix Quick Terminal startup race](task-03-fix-quick-terminal-startup-race.md) (`done`)
Revision wave 4:
- [x] [Task 04: Add per-tab host-shell sessions](task-04-per-tab-host-shell-sessions.md)
(`done`)
Revision wave 5:
- [x] [Task 05: Extract detachable PTY lifecycle](task-05-detachable-pty-lifecycle.md)
(`done`)
Revision wave 6:
- [x] [Task 06: Unify Quick Chat and terminal tabs](task-06-unified-quick-tabs.md)
(`done`)
Revision wave 7:
- [x] [Task 07: Prove shared tabs across viewports](task-07-shared-tabs-e2e.md)
(`done`)
Tasks 04–07 are sequential because each consumes the contract established by the preceding task and
the frontend tasks share PTY/dialog files. The task files are suitable handoff packets, but this
plan does not itself authorize subagent execution.
## Risks
- The login PTY manager enforces one login process per agent for credential safety. Per-tab host
shells must add a separate idempotency key without relaxing that invariant or changing the public
agent identity delivered to exit callbacks.
- A hidden terminal is intentionally alive without a subscriber. Its output is recoverable only
from the existing 16 KB rolling buffer, and it can expire under the existing 10-minute idle or
30-minute hard timeout.
- Start, detach, explicit close, StrictMode replay, and late async completion can race. Stable
client IDs plus explicit ownership tests are required to avoid leaked or accidentally stopped
sibling sessions.
- Backend Quick Chat hydration/resync is authoritative only for conversation sessions. A naive array
replacement can erase local terminal tabs or activate a tab from another workspace.
- xterm measures its mounted container. Reattachment and the selected-tab layout must fit only after
the content region has non-zero dimensions and must tolerate phone browser chrome and the
on-screen keyboard.
- Quick terminals execute with the backend host user's permissions. The shared dialog must not imply
task-worktree isolation or route terminal descriptors through conversation persistence APIs.
@@ -0,0 +1,99 @@
---
id: "01-quick-terminal-ui"
title: "Build the shared Quick Terminal UI"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/quick-terminal/spec.md"
---
# Task 01: Build the shared Quick Terminal UI
## Acceptance
- One global, lazy-loaded launcher opens the existing host shell in an opt-in Quick Terminal
presentation; current Agents/login dialog dimensions and cleanup behavior remain unchanged.
- With an active workspace, the expanded desktop New Task row and the tablet/phone Home and Tasks
headers show an accessible Quick Terminal action immediately before Quick Chat; the action is
absent in collapsed or workspace-less states.
- Tablet/desktop receive a larger contained floating terminal, while phone receives a safe-area-aware
full-height surface with one flexible xterm body and translated new copy.
## Verification
From the repository worktree:
```bash
cd apps && pnpm install --frozen-lockfile
cd apps && pnpm --filter @kandev/web test -- components/quick-terminal/quick-terminal-provider.test.tsx components/app-sidebar/app-sidebar-new-task-item.test.tsx components/kanban/kanban-header-mobile.test.tsx
cd apps/web && pnpm run typecheck
cd apps && pnpm --filter @kandev/web exec eslint components/settings/pty-terminal-dialog.tsx components/settings/host-shell-dialog.tsx components/quick-terminal/quick-terminal-provider.tsx hooks/use-quick-terminal-launcher.ts components/app-sidebar/app-sidebar-new-task-item.tsx components/kanban/kanban-header.tsx components/kanban/kanban-header-mobile.tsx app/layout.tsx src/app-shell.tsx
cd apps && pnpm --filter @kandev/web i18n:ratchet
```
## Files likely touched
- `apps/web/components/settings/pty-terminal-dialog.tsx`
- `apps/web/components/settings/host-shell-dialog.tsx`
- `apps/web/components/quick-terminal/quick-terminal-provider.tsx`
- `apps/web/components/quick-terminal/quick-terminal-provider.test.tsx`
- `apps/web/hooks/use-quick-terminal-launcher.ts`
- `apps/web/app/layout.tsx`
- `apps/web/src/app-shell.tsx`
- `apps/web/components/app-sidebar/app-sidebar-new-task-item.tsx`
- `apps/web/components/app-sidebar/app-sidebar-new-task-item.test.tsx`
- `apps/web/components/kanban/kanban-header.tsx`
- `apps/web/components/kanban/kanban-header-mobile.tsx`
- `apps/web/components/kanban/kanban-header-mobile.test.tsx`
- `apps/web/src/locales/en/sidebar.json`
- `docs/plans/quick-terminal/plan.md` (status/results only)
- `docs/plans/quick-terminal/task-01-quick-terminal-ui.md` (status/results only)
## Dependencies
None.
## Parallelism
Sequential. The provider, shared dialog props, and launcher placements form one frontend contract
and touch shared layout/header files.
## Inputs
- Spec: `What`, `Failure modes`, and all `Scenarios` in
`docs/specs/quick-terminal/spec.md`.
- Plan: `Responsive PTY presentation`, `Global launcher ownership`, `Desktop sidebar action`,
`Tablet and phone actions`, `Mobile design contract`, and `Risks` in `plan.md`.
- Existing patterns: `apps/web/components/settings/host-shell-dialog.tsx`,
`apps/web/components/settings/pty-terminal-dialog.tsx`,
`apps/web/components/quick-chat/quick-chat-modal.tsx`, and the Quick Chat actions in the sidebar
and Kanban headers.
## Implementation notes
- Follow TDD: add the provider/sidebar/mobile-header component assertions and observe them fail before
changing production components.
- Keep the Quick Terminal presentation opt-in. Do not alter the default layout used by Agents,
agent-login, installed-agent, profile-status, or chat recovery callers.
- Lazy-load the PTY-bearing host-shell component from the global provider so the initial root bundle
does not eagerly include xterm.
- Use `useTranslation()` at render time for all new accessible labels/tooltips. Do not translate
identifiers or call `t()` at module scope.
## Output contract
Report behavior implemented, files changed, exact command outcomes, blockers, residual risks, and
the task/plan status update in this conversation. Set this task to `in_progress` before production or
test changes, then replace `## Results` and mark it `done` only after every acceptance condition and
targeted command passes.
## Results
- `cd apps && pnpm install --frozen-lockfile` — passed; workspace dependencies installed.
- `cd apps && pnpm --filter @kandev/web test -- --run components/quick-terminal/quick-terminal-provider.test.tsx components/app-sidebar/app-sidebar-new-task-item.test.tsx components/kanban/kanban-header-mobile.test.tsx` — passed; 3 files, 23 tests.
- `cd apps/web && pnpm run typecheck` — passed.
- `cd apps && pnpm --filter @kandev/web exec eslint components/settings/pty-terminal-dialog.tsx components/settings/host-shell-dialog.tsx components/quick-terminal/quick-terminal-provider.tsx hooks/use-quick-terminal-launcher.ts components/app-sidebar/app-sidebar-new-task-item.tsx components/kanban/kanban-header.tsx components/kanban/kanban-header-mobile.tsx app/layout.tsx` — passed with no warnings or errors after extracting tablet actions.
- `cd apps && pnpm --filter @kandev/web i18n:ratchet` — passed; 2 added and 7 modified files clean.
- Security/trust and external side effects: starts and stops the existing host-shell session and
accepts shell commands; no new backend or authorization policy was added.
@@ -0,0 +1,87 @@
---
id: "02-quick-terminal-e2e"
title: "Prove Quick Terminal across viewports"
status: done
wave: 2
depends_on: ["01-quick-terminal-ui"]
plan: "plan.md"
spec: "../../specs/quick-terminal/spec.md"
---
# Task 02: Prove Quick Terminal across viewports
## Acceptance
- Desktop and tablet UI tests prove launcher order, usable hit targets, larger floating-dialog
geometry, viewport containment, PTY mount, dismissal, and focus return.
- Pixel 5 coverage proves touch access to a full-height terminal with safe contained geometry, no
document horizontal overflow, dismissal, and focus return.
- The existing host-shell integration scenarios still prove command I/O, idempotent start, and clean
stop after the shared dialog change.
## Verification
From the repository worktree:
```bash
cd apps && pnpm install --frozen-lockfile
cd apps/web && pnpm e2e:run tests/terminal/quick-terminal.spec.ts tests/settings/host-shell-pty.spec.ts
cd apps/web && pnpm e2e:run --project mobile-chrome tests/terminal/mobile-quick-terminal.spec.ts
```
Confirm each managed-runner invocation discovers the intended tests, rebuilds the production Vite
assets, and tears down its worker-scoped backend/session state.
## Files likely touched
- `apps/web/e2e/tests/terminal/quick-terminal.spec.ts`
- `apps/web/e2e/tests/terminal/mobile-quick-terminal.spec.ts`
- `apps/web/e2e/tests/settings/host-shell-pty.spec.ts` (only if selector/lifecycle coverage needs a
focused update)
- `docs/plans/quick-terminal/plan.md` (status/results only)
- `docs/plans/quick-terminal/task-02-quick-terminal-e2e.md` (status/results only)
## Dependencies
- Task 01 must be done so the provider, launchers, responsive presentation, and stable test IDs exist.
## Parallelism
Sequential. These scenarios share the Quick Terminal surface and host-shell lifecycle, and the
managed E2E runner owns the same build/test artifact pipeline.
## Inputs
- Spec: every `Scenarios` item in `docs/specs/quick-terminal/spec.md`.
- Plan: `E2E Tests`, `Mobile design contract`, and `Risks` in `plan.md`.
- Existing patterns: `apps/web/e2e/tests/settings/host-shell-pty.spec.ts`,
`apps/web/e2e/tests/chat/mobile-quick-chat-entry.spec.ts`, and the animation-aware geometry guidance
in `.agents/skills/e2e/SKILL.md`.
## Implementation notes
- Follow E2E TDD: add each focused Playwright scenario and observe its launcher/geometry assertion
fail before completing the corresponding production behavior.
- Exercise the feature through visible UI controls. API calls may seed workspace preconditions but
must not replace launcher, dialog, dismissal, or focus assertions.
- Wait for finite dialog animations before measuring. Use bounding boxes and `elementFromPoint()`
for containment/hit-target proof rather than fixed sleeps.
- Use `.tap()` in the mobile spec and let the `mobile-chrome` project supply its Pixel 5 device.
- Scope terminal locators to the Quick Terminal dialog because other terminal/xterm instances may be
mounted elsewhere in the app.
## Output contract
Report discovered test counts, exact commands and outcomes, rendered desktop/tablet/phone geometry,
artifact paths on failure, teardown evidence, blockers, residual risks, and the task/plan status
update in this conversation. Set this task to `in_progress` before test edits, then replace
`## Results` and mark it `done` only after every acceptance condition and targeted command passes.
## Results
- `cd apps/web && pnpm exec playwright test --config e2e/playwright.config.ts --project=chromium tests/terminal/quick-terminal.spec.ts` — passed; 2 desktop/tablet tests.
- `cd apps/web && pnpm exec playwright test --config e2e/playwright.config.ts --project=mobile-chrome tests/terminal/mobile-quick-terminal.spec.ts` — passed; 1 Pixel 5 test.
- `cd apps/web && pnpm e2e:run tests/terminal/quick-terminal.spec.ts tests/settings/host-shell-pty.spec.ts` — passed; managed Docker runner rebuilt backend/Vite/plugin assets, ran 4 tests (2 host-shell lifecycle + 2 desktop/tablet UI), and tore down the worker backend.
- `cd apps/web && pnpm e2e:run --project mobile-chrome tests/terminal/mobile-quick-terminal.spec.ts` — passed; managed Docker runner rebuilt assets, ran 1 Pixel 5 test, and tore down the worker backend.
- Rendered checks covered the 1280px desktop floating surface, 700px tablet floating surface, and Pixel 5 full-height surface; all dialog/terminal bounds remained within the viewport, with zero mobile document horizontal overflow.
- No failure artifacts or residual host-shell sessions remained after the managed runs.
@@ -0,0 +1,57 @@
---
id: "03-fix-quick-terminal-startup-race"
title: "Fix Quick Terminal startup race"
status: done
wave: 3
depends_on: ["01-quick-terminal-ui", "02-quick-terminal-e2e"]
plan: "plan.md"
spec: "../../specs/quick-terminal/spec.md"
---
# Task 03: Fix Quick Terminal startup race
## Acceptance
- StrictMode effect replay cannot stop the session owned by the current terminal mount.
- A live Quick Terminal accepts input after startup and resize requests remain successful.
- A natural PTY exit clears the client session identity and stops further resize requests.
- Restored launcher focus does not reopen its tooltip, while pointer hover still shows it.
- Existing Agents-page terminal cleanup remains unchanged outside the shared lifecycle fix.
## Files
- `apps/web/components/settings/pty-terminal-dialog.tsx`
- `apps/web/components/app-sidebar/app-sidebar-new-task-item.tsx`
- `apps/web/components/app-sidebar/app-sidebar-new-task-item.test.tsx`
- `apps/web/e2e/tests/terminal/quick-terminal.spec.ts`
- `apps/web/e2e/tests/terminal/mobile-quick-terminal.spec.ts`
- `docs/specs/quick-terminal/spec.md`
- `docs/plans/quick-terminal/plan.md`
## Verification
```bash
cd apps/web && pnpm exec vitest run components/quick-terminal/quick-terminal-provider.test.tsx components/app-sidebar/app-sidebar-new-task-item.test.tsx components/kanban/kanban-header-mobile.test.tsx
cd apps/web && pnpm run typecheck
cd apps/web && pnpm exec eslint components/app-sidebar/app-sidebar-new-task-item.tsx components/app-sidebar/app-sidebar-new-task-item.test.tsx e2e/tests/terminal/quick-terminal.spec.ts
cd apps && pnpm --filter @kandev/web run i18n:ratchet
cd apps && pnpm --filter @kandev/web run i18n:check
cd apps/web && pnpm e2e:run tests/terminal/quick-terminal.spec.ts tests/settings/host-shell-pty.spec.ts
cd apps/web && pnpm e2e:run --project mobile-chrome tests/terminal/mobile-quick-terminal.spec.ts
cd apps/backend && go test ./internal/agent/loginpty
```
## Root-cause reproduction
An isolated dev browser reproduced two `/host-shell/start` requests followed by a stop for the
shared session, `Session ended (exit -1)`, and resize 404s. After the generation guard, the same
surface accepted `echo quick-terminal-fixed` and the resize request returned 200.
## Results
- Added mount-generation ownership so StrictMode replay cannot stop the active session.
- Cleared the client session identity on PTY exit/close to stop stale resize requests.
- Added browser coverage for shell readiness and command input/output.
- Made the sidebar action tooltip pointer-driven and covered focus/hover behavior.
- Passed focused component tests, typecheck, targeted lint, i18n checks, Chromium and Pixel 5 E2E,
and backend PTY tests.

Some files were not shown because too many files have changed in this diff Show More