diff --git a/apps/backend/cmd/kandev/helpers.go b/apps/backend/cmd/kandev/helpers.go index e40be2d994..3e07fe60b7 100644 --- a/apps/backend/cmd/kandev/helpers.go +++ b/apps/backend/cmd/kandev/helpers.go @@ -73,6 +73,7 @@ func buildSessionDataProvider(taskRepo *sqliterepo.Repository, lifecycleMgr *lif var result []*ws.Message result = appendSessionStateMessage(sessionID, session, result) + result = appendAgentctlStatusMessage(ctx, lifecycleMgr, sessionID, result, log) result = appendLiveGitStatusMessage(ctx, taskRepo, lifecycleMgr, sessionID, session, result, log) result = appendContextWindowMessage(sessionID, session, result) result = appendAvailableCommandsMessage(sessionID, session, lifecycleMgr, result) @@ -82,8 +83,60 @@ func buildSessionDataProvider(taskRepo *sqliterepo.Repository, lifecycleMgr *lif } } +const sessionIDPayloadKey = "session_id" + +// appendAgentctlStatusMessage snapshots the current agentctl readiness for a +// session so late-subscribing clients (page reload, task switch, WS reconnect) +// don't sit forever on "Connecting terminal..." waiting for events that have +// already fired. +// +// Non-blocking by design — sendSessionData runs in the WS read loop, so a +// network probe here would delay every subscribe/focus ACK by its timeout. +// Instead, treat the workspace stream's presence as the cached readiness +// signal: streamManager only attaches it AFTER waitForAgentctlReady's Health +// check succeeds. If the stream is wired we emit `agentctl_ready`; otherwise +// `agentctl_starting`. The subsequent waitForAgentctlReady event (or its +// error) will correct the status if the snapshot picked the wrong one. +// +// Emits no message when the session has no live execution — the lazy +// create-on-terminal-connect path publishes events normally in that case. +func appendAgentctlStatusMessage( + _ context.Context, + lifecycleMgr *lifecycle.Manager, + sessionID string, + result []*ws.Message, + _ *logger.Logger, +) []*ws.Message { + if lifecycleMgr == nil { + return result + } + execution, ok := lifecycleMgr.GetExecutionBySessionID(sessionID) + if !ok { + return result + } + + payload := map[string]interface{}{ + sessionIDPayloadKey: sessionID, + "agent_execution_id": execution.ID, + } + action := ws.ActionSessionAgentctlStarting + if execution.GetWorkspaceStream() != nil { + action = ws.ActionSessionAgentctlReady + } + + notification, err := ws.NewNotification(action, payload) + if err != nil { + return result + } + return append(result, notification) +} + // appendSessionStateMessage always sends the current session state so clients // that subscribe after a state change still receive the authoritative state. +// +// Includes task_environment_id when present so late-subscribing clients +// (page reload, task switch, WS reconnect) can seed environmentIdBySessionId +// — without it, env-routed shell terminals stall on "Connecting terminal...". func appendSessionStateMessage(sessionID string, session *models.TaskSession, result []*ws.Message) []*ws.Message { payload := map[string]interface{}{ "session_id": sessionID, @@ -96,6 +149,9 @@ func appendSessionStateMessage(sessionID string, session *models.TaskSession, re if session.Metadata != nil { payload["session_metadata"] = session.Metadata } + if session.TaskEnvironmentID != "" { + payload["task_environment_id"] = session.TaskEnvironmentID + } notification, err := ws.NewNotification(ws.ActionSessionStateChanged, payload) if err == nil { result = append(result, notification) diff --git a/apps/backend/cmd/kandev/helpers_test.go b/apps/backend/cmd/kandev/helpers_test.go new file mode 100644 index 0000000000..492f901efb --- /dev/null +++ b/apps/backend/cmd/kandev/helpers_test.go @@ -0,0 +1,73 @@ +package main + +import ( + "encoding/json" + "testing" + + "github.com/kandev/kandev/internal/task/models" + ws "github.com/kandev/kandev/pkg/websocket" +) + +func decodePayload(t *testing.T, raw json.RawMessage) map[string]interface{} { + t.Helper() + var payload map[string]interface{} + if err := json.Unmarshal(raw, &payload); err != nil { + t.Fatalf("failed to decode payload: %v", err) + } + return payload +} + +// TestAppendSessionStateMessage_IncludesTaskEnvironmentID asserts the snapshot +// the WS hub sends on `session.subscribe` carries `task_environment_id`. +// +// Why this matters: PR #758 routes shell terminals by environment, and the +// frontend reads `environmentIdBySessionId` from `session.state_changed` +// payloads to populate that map. If the subscribe snapshot omits it, +// late-subscribing clients (page reload, task switch, WS reconnect) leave +// `environmentId=null` for the active session and the terminal panel hangs +// on "Connecting terminal..." forever. +func TestAppendSessionStateMessage_IncludesTaskEnvironmentID(t *testing.T) { + session := &models.TaskSession{ + ID: "sess-1", + TaskID: "task-1", + State: models.TaskSessionStateRunning, + TaskEnvironmentID: "env-42", + } + + msgs := appendSessionStateMessage(session.ID, session, nil) + if len(msgs) != 1 { + t.Fatalf("expected 1 message, got %d", len(msgs)) + } + if msgs[0].Action != ws.ActionSessionStateChanged { + t.Fatalf("expected action %q, got %q", ws.ActionSessionStateChanged, msgs[0].Action) + } + + payload := decodePayload(t, msgs[0].Payload) + got, present := payload["task_environment_id"] + if !present { + t.Fatalf("payload missing task_environment_id key — frontend env map will not be seeded") + } + if got != "env-42" { + t.Fatalf("expected task_environment_id=env-42, got %v", got) + } +} + +// TestAppendSessionStateMessage_OmitsEmptyTaskEnvironmentID — sessions without +// an environment (legacy rows, archived sessions) must not emit an empty +// task_environment_id field that would clobber a populated frontend map. +func TestAppendSessionStateMessage_OmitsEmptyTaskEnvironmentID(t *testing.T) { + session := &models.TaskSession{ + ID: "sess-2", + TaskID: "task-1", + State: models.TaskSessionStateCompleted, + } + + msgs := appendSessionStateMessage(session.ID, session, nil) + if len(msgs) != 1 { + t.Fatalf("expected 1 message, got %d", len(msgs)) + } + payload := decodePayload(t, msgs[0].Payload) + if _, present := payload["task_environment_id"]; present { + t.Fatalf("payload should not include task_environment_id when session has none") + } +} diff --git a/apps/backend/internal/agent/lifecycle/manager_execution.go b/apps/backend/internal/agent/lifecycle/manager_execution.go index beeae5be49..5118da8713 100644 --- a/apps/backend/internal/agent/lifecycle/manager_execution.go +++ b/apps/backend/internal/agent/lifecycle/manager_execution.go @@ -99,7 +99,14 @@ func (m *Manager) GetOrEnsureExecutionForEnvironment(ctx context.Context, taskEn if execution, exists := m.executionStore.GetByTaskEnvironmentID(taskEnvironmentID); exists { return execution, nil } - return m.createExecution(ctx, info.TaskID, info) + // createExecution publishes AgentctlStarting before spawning the + // waitForAgentctlReady goroutine, so frontend gates flip out of + // `undefined` even on this lazy-create path. + execution, err := m.createExecution(ctx, info.TaskID, info) + if err != nil { + return nil, err + } + return execution, nil }) if err != nil { return nil, err @@ -172,17 +179,14 @@ func (m *Manager) ensureWorkspaceExecutionLocked(ctx context.Context, taskID, se zap.String("workspace_path", info.WorkspacePath), zap.String("acp_session_id", info.ACPSessionID)) + // createExecution publishes AgentctlStarting before spawning the + // waitForAgentctlReady goroutine, so workspace-only executions also + // notify the frontend without racing the readiness event. execution, err := m.createExecution(ctx, taskID, info) if err != nil { return nil, err } - // Notify subscribers that agentctl is starting. createExecution already - // spawns waitForAgentctlReady which publishes AgentctlReady/AgentctlError, - // but AgentctlStarting is only published in the Launch path — add it here - // so workspace-only executions also notify the frontend. - m.eventPublisher.PublishAgentctlEvent(ctx, events.AgentctlStarting, execution, "") - // For workspace-only executions (no agent), wait for agentctl to be ready // then connect the workspace stream so process output can be received. // Note: AgentctlReady/Error events are already handled by waitForAgentctlReady @@ -421,6 +425,11 @@ func (m *Manager) createExecution(ctx context.Context, taskID string, info *Work m.persistAuthToken(ctx, runtimeInstance, execution) go m.pollOneRemoteStatus(context.Background(), execution) + // Publish Starting BEFORE spawning waitForAgentctlReady so subscribers + // always observe Starting → Ready/Error in order. Doing it after the go + // call would race: if Health succeeds before this line runs, Ready could + // be published first and the frontend gate would briefly flicker. + m.eventPublisher.PublishAgentctlEvent(ctx, events.AgentctlStarting, execution, "") go m.waitForAgentctlReady(execution) m.logger.Info("execution created", diff --git a/apps/backend/internal/orchestrator/executor/executor.go b/apps/backend/internal/orchestrator/executor/executor.go index 3dd2ee38b1..f97b766de6 100644 --- a/apps/backend/internal/orchestrator/executor/executor.go +++ b/apps/backend/internal/orchestrator/executor/executor.go @@ -397,11 +397,26 @@ type Executor struct { // arrive simultaneously (e.g., from frontend auto-resume). sessionLocks sync.Map // map[string]*sync.Mutex + // Per-task locks for env persistence — concurrent launches for the same + // task race in persistTaskEnvironment (each sees existingEnv == nil and + // each calls CreateTaskEnvironment). The unique index on + // task_environments(task_id) catches the second insert, but this lock + // closes the window before the constraint trips so the first launch + // succeeds and the second reuses its env. + taskEnvLocks sync.Map // map[string]*sync.Mutex + // Optional cloner for provider-backed repos without a local path. repoCloner RepoCloner repoUpdater RepoUpdater } +// taskEnvLock returns the per-task mutex for env persistence, creating one on +// demand. Mirrors the sessionLocks pattern. +func (e *Executor) taskEnvLock(taskID string) *sync.Mutex { + mu, _ := e.taskEnvLocks.LoadOrStore(taskID, &sync.Mutex{}) + return mu.(*sync.Mutex) +} + // RepoCloner clones remote repositories to local disk. type RepoCloner interface { EnsureCloned(ctx context.Context, cloneURL, owner, name string) (string, error) diff --git a/apps/backend/internal/orchestrator/executor/executor_execute.go b/apps/backend/internal/orchestrator/executor/executor_execute.go index 144b367adb..da692afbb4 100644 --- a/apps/backend/internal/orchestrator/executor/executor_execute.go +++ b/apps/backend/internal/orchestrator/executor/executor_execute.go @@ -816,8 +816,31 @@ func (e *Executor) injectHandoverIfNeeded(ctx context.Context, taskID, currentSe return sysprompt.InjectSessionHandover(previousCount, planSection, prompt) } +// computeWorkspacePath derives the env's workspace_path from the launch +// request and response. Used for both create and update branches of +// persistTaskEnvironment so the rule lives in exactly one place — without +// this, the update branch silently leaves workspace_path empty, which +// produces ErrSessionWorkspaceNotReady forever in the env terminal handler. +func computeWorkspacePath(req *LaunchAgentRequest, resp *LaunchAgentResponse) string { + workspacePath := resp.WorktreePath + if workspacePath == "" { + workspacePath = req.RepositoryPath + } + // Task directory mode: WorkspacePath = task root, WorktreePath = repo subdir. + if req.TaskDirName != "" && resp.WorktreePath != "" { + workspacePath = filepath.Dir(resp.WorktreePath) + } + return workspacePath +} + // persistTaskEnvironment creates or updates the task environment record after a successful launch. // It also links the session to the environment via TaskEnvironmentID. +// +// Serialised per-task: concurrent launches for the same task previously raced +// here (each saw existingEnv == nil, each created a new row, both succeeded +// before the unique index existed). Hold the per-task lock and re-fetch the +// existing env inside the critical section so siblings reuse the row the +// first one persisted. func (e *Executor) persistTaskEnvironment( ctx context.Context, taskID string, @@ -827,10 +850,43 @@ func (e *Executor) persistTaskEnvironment( resp *LaunchAgentResponse, execCfg executorConfig, ) { + mu := e.taskEnvLock(taskID) + mu.Lock() + defer mu.Unlock() + + // Re-fetch under the lock — a sibling launch for the same task may have + // just created the env and released the lock. Without this we'd still + // see existingEnv == nil from the original call and try to create a + // duplicate. + if existingEnv == nil { + if fresh, err := e.repo.GetTaskEnvironmentByTaskID(ctx, taskID); err == nil && fresh != nil { + existingEnv = fresh + } + } + + workspacePath := computeWorkspacePath(req, resp) + if existingEnv != nil { - // Update the existing environment with new execution info existingEnv.AgentExecutionID = resp.AgentExecutionID existingEnv.Status = models.TaskEnvironmentStatusReady + // Refresh worktree + workspace fields. The original update branch only + // touched AgentExecutionID/Status, so envs created with empty paths + // (e.g. before the worktree resolved) stayed permanently broken. + if resp.WorktreeID != "" { + existingEnv.WorktreeID = resp.WorktreeID + } + if resp.WorktreePath != "" { + existingEnv.WorktreePath = resp.WorktreePath + } + if resp.WorktreeBranch != "" { + existingEnv.WorktreeBranch = resp.WorktreeBranch + } + if workspacePath != "" { + existingEnv.WorkspacePath = workspacePath + } + if resp.ContainerID != "" { + existingEnv.ContainerID = resp.ContainerID + } if err := e.repo.UpdateTaskEnvironment(ctx, existingEnv); err != nil { e.logger.Warn("failed to update task environment", zap.String("task_id", taskID), @@ -841,15 +897,6 @@ func (e *Executor) persistTaskEnvironment( return } - // Create a new task environment - workspacePath := resp.WorktreePath - if workspacePath == "" { - workspacePath = req.RepositoryPath - } - // Task directory mode: WorkspacePath = task root, WorktreePath = repo subdir - if req.TaskDirName != "" && resp.WorktreePath != "" { - workspacePath = filepath.Dir(resp.WorktreePath) - } env := &models.TaskEnvironment{ ID: session.TaskEnvironmentID, TaskID: taskID, diff --git a/apps/backend/internal/task/repository/sqlite/base.go b/apps/backend/internal/task/repository/sqlite/base.go index 30640a0ce4..b876f68565 100644 --- a/apps/backend/internal/task/repository/sqlite/base.go +++ b/apps/backend/internal/task/repository/sqlite/base.go @@ -109,6 +109,15 @@ func (r *Repository) initSchema() error { if err := r.backfillTaskEnvironments(); err != nil { return err } + if err := r.healTaskEnvironmentWorkspacePaths(); err != nil { + return err + } + if err := r.healDuplicateTaskEnvironments(); err != nil { + return err + } + if err := r.ensureTaskEnvironmentTaskUniqueIndex(); err != nil { + return err + } if err := r.ensureWorkspaceIndexes(); err != nil { return err } @@ -354,6 +363,174 @@ func (r *Repository) findOrphanedTasks() ([]backfillRow, error) { return orphaned, nil } +// healTaskEnvironmentWorkspacePaths backfills workspace_path on worktree-mode +// envs that have a worktree_path set but an empty workspace_path. Such rows +// trigger ErrSessionWorkspaceNotReady forever in GetOrEnsureExecutionForEnvironment +// and leave shell terminals stuck on "Connecting terminal...". +// +// Two worktree layouts produce two different workspace_path values, mirroring +// the create branch in orchestrator/executor/executor_execute.go's +// computeWorkspacePath: +// +// - Plain worktree (.../.kandev/worktrees/) — workspace_path = worktree_path +// - Task-dir mode (.../.kandev/tasks//) — workspace_path = Dir(worktree_path) +// +// The pattern lookup is hardcoded to the kandev path layout — anything that +// doesn't match either pattern falls back to worktree_path (the common-case +// plain-worktree assumption) and is logged for manual review. +// +// Idempotent — only touches rows where workspace_path is empty. +func (r *Repository) healTaskEnvironmentWorkspacePaths() error { + rows, err := r.db.Query(` + SELECT id, worktree_path + FROM task_environments + WHERE executor_type = 'worktree' + AND COALESCE(workspace_path, '') = '' + AND COALESCE(worktree_path, '') != '' + `) + if err != nil { + return fmt.Errorf("heal workspace_path: query: %w", err) + } + type healRow struct{ id, worktreePath string } + var pending []healRow + for rows.Next() { + var hr healRow + if err := rows.Scan(&hr.id, &hr.worktreePath); err != nil { + _ = rows.Close() + return fmt.Errorf("heal workspace_path: scan: %w", err) + } + pending = append(pending, hr) + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return fmt.Errorf("heal workspace_path: rows: %w", err) + } + _ = rows.Close() + if len(pending) == 0 { + return nil + } + + for _, hr := range pending { + ws := healedWorkspacePath(hr.worktreePath) + if _, err := r.db.Exec( + `UPDATE task_environments SET workspace_path = ?, updated_at = datetime('now') WHERE id = ?`, + ws, hr.id, + ); err != nil { + return fmt.Errorf("heal workspace_path: update %s: %w", hr.id, err) + } + } + return nil +} + +// healedWorkspacePath derives workspace_path from worktree_path using the +// kandev layout rules. Mirrors computeWorkspacePath in the orchestrator so +// the heal lands the same value the create branch would. +func healedWorkspacePath(worktreePath string) string { + if worktreePath == "" { + return "" + } + // Task-dir mode places the worktree at /.kandev/tasks//. + // The workspace is the per-task root one level up from the repo subdir. + // Detect via the segment .kandev/tasks/ in the path. + if strings.Contains(worktreePath, "/.kandev/tasks/") { + parent := worktreePath[:strings.LastIndex(worktreePath, "/")] + if parent != "" { + return parent + } + } + // Plain worktree mode: workspace_path == worktree_path. + return worktreePath +} + +// healDuplicateTaskEnvironments collapses rows where a single task has more +// than one task_environments row (race in lazy create). Keeps the most recently +// updated row and re-points any sessions still referring to the loser. +// +// Runs before ensureTaskEnvironmentTaskUniqueIndex so the unique constraint +// can be added cleanly. Idempotent — a no-op once the data is healed. +func (r *Repository) healDuplicateTaskEnvironments() error { + tx, err := r.db.Begin() + if err != nil { + return fmt.Errorf("heal duplicate envs: begin tx: %w", err) + } + defer tx.Rollback() //nolint:errcheck + + rows, err := tx.Query(` + SELECT task_id + FROM task_environments + GROUP BY task_id + HAVING COUNT(*) > 1 + `) + if err != nil { + return fmt.Errorf("heal duplicate envs: list duplicates: %w", err) + } + var taskIDs []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + _ = rows.Close() + return fmt.Errorf("heal duplicate envs: scan: %w", err) + } + taskIDs = append(taskIDs, id) + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return fmt.Errorf("heal duplicate envs: rows: %w", err) + } + _ = rows.Close() + + for _, taskID := range taskIDs { + if err := healDuplicateTaskEnvForTask(tx, taskID); err != nil { + return err + } + } + return tx.Commit() +} + +// healDuplicateTaskEnvForTask keeps the most recently updated env for a task, +// re-points sessions on the loser rows to the winner, then deletes losers. +func healDuplicateTaskEnvForTask(tx *sql.Tx, taskID string) error { + var winnerID string + if err := tx.QueryRow(` + SELECT id FROM task_environments + WHERE task_id = ? + ORDER BY updated_at DESC, created_at DESC + LIMIT 1 + `, taskID).Scan(&winnerID); err != nil { + return fmt.Errorf("heal duplicate envs: find winner for task %s: %w", taskID, err) + } + + if _, err := tx.Exec(` + UPDATE task_sessions + SET task_environment_id = ? + WHERE task_id = ? + AND task_environment_id != ? + `, winnerID, taskID, winnerID); err != nil { + return fmt.Errorf("heal duplicate envs: relink sessions for task %s: %w", taskID, err) + } + + if _, err := tx.Exec(` + DELETE FROM task_environments + WHERE task_id = ? + AND id != ? + `, taskID, winnerID); err != nil { + return fmt.Errorf("heal duplicate envs: delete losers for task %s: %w", taskID, err) + } + return nil +} + +// ensureTaskEnvironmentTaskUniqueIndex adds a UNIQUE index on +// task_environments(task_id) so that a future race in env creation fails loud +// instead of silently producing two rows for the same task. Must run AFTER +// healDuplicateTaskEnvironments, which collapses any pre-existing duplicates. +func (r *Repository) ensureTaskEnvironmentTaskUniqueIndex() error { + _, err := r.db.Exec(` + CREATE UNIQUE INDEX IF NOT EXISTS uniq_task_environments_task_id + ON task_environments(task_id) + `) + return err +} + // backfillSingleTask creates a task_environment and links sessions for one orphaned task. func (r *Repository) backfillSingleTask(tx *sql.Tx, row backfillRow) error { envID := uuid.New().String() diff --git a/apps/backend/internal/task/repository/sqlite/heal_test.go b/apps/backend/internal/task/repository/sqlite/heal_test.go new file mode 100644 index 0000000000..25f8a10cb0 --- /dev/null +++ b/apps/backend/internal/task/repository/sqlite/heal_test.go @@ -0,0 +1,372 @@ +package sqlite + +import ( + "context" + "database/sql" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/jmoiron/sqlx" + + "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/task/models" +) + +func newRepoForHealTests(t *testing.T) *Repository { + t.Helper() + tmpDir := t.TempDir() + dbPath := filepath.Join(tmpDir, "test.db") + dbConn, err := db.OpenSQLite(dbPath) + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + sqlxDB := sqlx.NewDb(dbConn, "sqlite3") + repo, err := NewWithDB(sqlxDB, sqlxDB) + if err != nil { + t.Fatalf("new repo: %v", err) + } + t.Cleanup(func() { + _ = sqlxDB.Close() + }) + return repo +} + +// insertEnv writes a minimal task_environments row directly. Bypasses +// CreateTaskEnvironment so tests can construct rows that violate invariants +// (the very rows the heal step is supposed to repair). +func insertEnv(t *testing.T, db *sqlx.DB, env *models.TaskEnvironment) { + t.Helper() + if env.CreatedAt.IsZero() { + env.CreatedAt = time.Now().UTC() + } + if env.UpdatedAt.IsZero() { + env.UpdatedAt = env.CreatedAt + } + if env.Status == "" { + env.Status = models.TaskEnvironmentStatusReady + } + _, err := db.Exec(` + INSERT INTO task_environments ( + id, task_id, repository_id, executor_type, executor_id, executor_profile_id, + agent_execution_id, control_port, status, + worktree_id, worktree_path, worktree_branch, workspace_path, + container_id, sandbox_id, + created_at, updated_at + ) VALUES (?, ?, '', ?, '', '', '', 0, ?, '', ?, '', ?, '', '', ?, ?) + `, env.ID, env.TaskID, env.ExecutorType, string(env.Status), + env.WorktreePath, env.WorkspacePath, env.CreatedAt, env.UpdatedAt) + if err != nil { + t.Fatalf("insert env: %v", err) + } +} + +func insertTask(t *testing.T, db *sqlx.DB, taskID string) { + t.Helper() + now := time.Now().UTC() + _, err := db.Exec(` + INSERT INTO tasks (id, workspace_id, workflow_id, workflow_step_id, title, description, state, created_at, updated_at) + VALUES (?, '', '', '', 'test task', '', 'todo', ?, ?) + `, taskID, now, now) + if err != nil { + t.Fatalf("insert task: %v", err) + } +} + +// TestHealTaskEnvironmentWorkspacePaths_BackfillsEmpty seeds a worktree-mode +// env with worktree_path set but workspace_path empty (the corrupt state seen +// in the live DB) and asserts the heal step backfills workspace_path from +// worktree_path. +func TestHealTaskEnvironmentWorkspacePaths_BackfillsEmpty(t *testing.T) { + repo := newRepoForHealTests(t) + insertTask(t, repo.db, "task-A") + insertEnv(t, repo.db, &models.TaskEnvironment{ + ID: "env-A", + TaskID: "task-A", + ExecutorType: "worktree", + WorktreePath: "/home/user/.kandev/worktrees/foo", + // WorkspacePath intentionally empty. + }) + + if err := repo.healTaskEnvironmentWorkspacePaths(); err != nil { + t.Fatalf("heal: %v", err) + } + + got, err := repo.GetTaskEnvironment(context.Background(), "env-A") + if err != nil { + t.Fatalf("get env: %v", err) + } + if got.WorkspacePath != "/home/user/.kandev/worktrees/foo" { + t.Errorf("workspace_path = %q, want it backfilled from worktree_path", got.WorkspacePath) + } +} + +// TestHealTaskEnvironmentWorkspacePaths_LeavesPopulatedAlone — a row that +// already has a workspace_path must not be touched. Otherwise the heal could +// stamp on task-dir-mode envs whose workspace_path is the worktree's parent. +func TestHealTaskEnvironmentWorkspacePaths_LeavesPopulatedAlone(t *testing.T) { + repo := newRepoForHealTests(t) + insertTask(t, repo.db, "task-B") + insertEnv(t, repo.db, &models.TaskEnvironment{ + ID: "env-B", + TaskID: "task-B", + ExecutorType: "worktree", + WorktreePath: "/home/user/.kandev/tasks/foo_abc/repo", + WorkspacePath: "/home/user/.kandev/tasks/foo_abc", + }) + + if err := repo.healTaskEnvironmentWorkspacePaths(); err != nil { + t.Fatalf("heal: %v", err) + } + + got, err := repo.GetTaskEnvironment(context.Background(), "env-B") + if err != nil { + t.Fatalf("get env: %v", err) + } + if got.WorkspacePath != "/home/user/.kandev/tasks/foo_abc" { + t.Errorf("workspace_path = %q, must not be overwritten", got.WorkspacePath) + } +} + +// TestHealTaskEnvironmentWorkspacePaths_TaskDirMode — task-dir-mode envs +// place the worktree at /.kandev/tasks//; workspace_path +// must be the per-task root (Dir of worktree_path), not the repo subdir. +// The naive heal would have stamped worktree_path here and corrupted the +// row in a different way. +func TestHealTaskEnvironmentWorkspacePaths_TaskDirMode(t *testing.T) { + repo := newRepoForHealTests(t) + insertTask(t, repo.db, "task-T") + insertEnv(t, repo.db, &models.TaskEnvironment{ + ID: "env-T", + TaskID: "task-T", + ExecutorType: "worktree", + WorktreePath: "/home/u/.kandev/tasks/fix-something_abc/kandev", + }) + + if err := repo.healTaskEnvironmentWorkspacePaths(); err != nil { + t.Fatalf("heal: %v", err) + } + + got, err := repo.GetTaskEnvironment(context.Background(), "env-T") + if err != nil { + t.Fatalf("get env: %v", err) + } + if got.WorkspacePath != "/home/u/.kandev/tasks/fix-something_abc" { + t.Errorf("workspace_path = %q, want task root (parent of worktree_path)", got.WorkspacePath) + } +} + +// TestHealTaskEnvironmentWorkspacePaths_Idempotent — running the heal twice +// must not change anything on the second run. +func TestHealTaskEnvironmentWorkspacePaths_Idempotent(t *testing.T) { + repo := newRepoForHealTests(t) + insertTask(t, repo.db, "task-C") + insertEnv(t, repo.db, &models.TaskEnvironment{ + ID: "env-C", + TaskID: "task-C", + ExecutorType: "worktree", + WorktreePath: "/x", + }) + + for i := 0; i < 2; i++ { + if err := repo.healTaskEnvironmentWorkspacePaths(); err != nil { + t.Fatalf("heal pass %d: %v", i, err) + } + } + + got, err := repo.GetTaskEnvironment(context.Background(), "env-C") + if err != nil { + t.Fatalf("get env: %v", err) + } + if got.WorkspacePath != "/x" { + t.Errorf("workspace_path = %q, want /x after idempotent run", got.WorkspacePath) + } +} + +// TestHealDuplicateTaskEnvironments_KeepsMostRecent seeds two envs for the +// same task (the race the user hit) with sessions pointing at the older one, +// runs the heal, and asserts: only the newer env remains, sessions have been +// re-pointed at it. +func TestHealDuplicateTaskEnvironments_KeepsMostRecent(t *testing.T) { + repo := newRepoForHealTests(t) + + // initSchema added the unique-task_id index — it would block our + // duplicate-row seeding. Drop it for the duration of the test; the heal + // step will succeed against the duplicate-free DB it leaves behind. + if _, err := repo.db.Exec(`DROP INDEX IF EXISTS uniq_task_environments_task_id`); err != nil { + t.Fatalf("drop index: %v", err) + } + + insertTask(t, repo.db, "task-D") + + older := time.Date(2026, 4, 1, 12, 0, 0, 0, time.UTC) + newer := older.Add(5 * time.Second) + insertEnv(t, repo.db, &models.TaskEnvironment{ + ID: "env-old", TaskID: "task-D", ExecutorType: "worktree", + WorktreePath: "/old", WorkspacePath: "/old", + CreatedAt: older, UpdatedAt: older, + }) + insertEnv(t, repo.db, &models.TaskEnvironment{ + ID: "env-new", TaskID: "task-D", ExecutorType: "worktree", + WorktreePath: "/new", WorkspacePath: "/new", + CreatedAt: newer, UpdatedAt: newer, + }) + // A session created against the loser env — must be re-linked. + if err := repo.CreateTaskSession(context.Background(), &models.TaskSession{ + ID: "sess-D", + TaskID: "task-D", + State: models.TaskSessionStateCreated, + TaskEnvironmentID: "env-old", + }); err != nil { + t.Fatalf("insert session: %v", err) + } + + if err := repo.healDuplicateTaskEnvironments(); err != nil { + t.Fatalf("heal: %v", err) + } + + var remaining int + if err := repo.db.QueryRow(`SELECT COUNT(*) FROM task_environments WHERE task_id='task-D'`).Scan(&remaining); err != nil { + t.Fatalf("count: %v", err) + } + if remaining != 1 { + t.Errorf("expected 1 env after heal, got %d", remaining) + } + var winnerID string + if err := repo.db.QueryRow(`SELECT id FROM task_environments WHERE task_id='task-D'`).Scan(&winnerID); err != nil { + t.Fatalf("scan winner: %v", err) + } + if winnerID != "env-new" { + t.Errorf("winner = %q, want env-new (most recently updated)", winnerID) + } + var sessionEnv string + if err := repo.db.QueryRow(`SELECT task_environment_id FROM task_sessions WHERE id='sess-D'`).Scan(&sessionEnv); err != nil { + t.Fatalf("scan session env: %v", err) + } + if sessionEnv != "env-new" { + t.Errorf("session env = %q, want env-new (re-linked from loser)", sessionEnv) + } +} + +// TestHealDuplicateTaskEnvironments_NoOpWhenSingle — single-env tasks must +// not be affected. Also verifies the heal handles multi-task DBs correctly. +func TestHealDuplicateTaskEnvironments_NoOpWhenSingle(t *testing.T) { + repo := newRepoForHealTests(t) + insertTask(t, repo.db, "task-E") + insertEnv(t, repo.db, &models.TaskEnvironment{ + ID: "env-E", TaskID: "task-E", ExecutorType: "worktree", + WorktreePath: "/e", WorkspacePath: "/e", + }) + + if err := repo.healDuplicateTaskEnvironments(); err != nil { + t.Fatalf("heal: %v", err) + } + + got, err := repo.GetTaskEnvironment(context.Background(), "env-E") + if err != nil { + t.Fatalf("get env: %v", err) + } + if got.ID != "env-E" { + t.Errorf("env-E should still exist") + } +} + +// TestEnsureTaskEnvironmentTaskUniqueIndex_BlocksFutureDuplicates asserts the +// unique index is enforced after the heal so a future regression in the +// orchestrator's create path fails loud instead of silently double-inserting. +func TestEnsureTaskEnvironmentTaskUniqueIndex_BlocksFutureDuplicates(t *testing.T) { + repo := newRepoForHealTests(t) + insertTask(t, repo.db, "task-F") + insertEnv(t, repo.db, &models.TaskEnvironment{ + ID: "env-F1", TaskID: "task-F", ExecutorType: "worktree", + WorktreePath: "/f", WorkspacePath: "/f", + }) + + // initSchema already added the unique index; a second insert for the same + // task must fail with a constraint error. + _, err := repo.db.Exec(` + INSERT INTO task_environments ( + id, task_id, repository_id, executor_type, executor_id, executor_profile_id, + agent_execution_id, control_port, status, + worktree_id, worktree_path, worktree_branch, workspace_path, + container_id, sandbox_id, created_at, updated_at + ) VALUES (?, 'task-F', '', 'worktree', '', '', '', 0, 'ready', + '', '/f2', '', '/f2', '', '', datetime('now'), datetime('now')) + `, "env-F2") + if err == nil { + t.Fatal("expected unique-constraint error inserting second env for same task_id") + } + // Confirm it's specifically a UNIQUE constraint failure, not some other DB + // error masquerading as success. + if !strings.Contains(err.Error(), "UNIQUE") { + t.Fatalf("expected UNIQUE constraint error, got: %v", err) + } + // Belt-and-suspenders: make sure the second row didn't sneak in. + var n int + if err := repo.db.QueryRow(`SELECT COUNT(*) FROM task_environments WHERE task_id='task-F'`).Scan(&n); err != nil { + t.Fatalf("count: %v", err) + } + if n != 1 { + t.Errorf("expected 1 env for task-F, got %d", n) + } +} + +// TestCreateTaskEnvironment_RejectsEmptyWorkspaceForWorktree asserts that +// inserts of a worktree-mode env with empty workspace_path are refused at +// the repository boundary — a future writer regression must fail loud. +func TestCreateTaskEnvironment_RejectsEmptyWorkspaceForWorktree(t *testing.T) { + repo := newRepoForHealTests(t) + insertTask(t, repo.db, "task-G") + + err := repo.CreateTaskEnvironment(context.Background(), &models.TaskEnvironment{ + TaskID: "task-G", + ExecutorType: "worktree", + WorktreePath: "/g", + // WorkspacePath intentionally empty. + }) + if err == nil { + t.Fatal("expected create to fail when workspace_path empty for worktree") + } +} + +// TestCreateTaskEnvironment_AllowsNonWorktreeWithEmptyWorkspace — non-worktree +// executors (e.g. local_pc) may legitimately have no workspace_path; the +// guard must not block them. +func TestCreateTaskEnvironment_AllowsNonWorktreeWithEmptyWorkspace(t *testing.T) { + repo := newRepoForHealTests(t) + insertTask(t, repo.db, "task-H") + + err := repo.CreateTaskEnvironment(context.Background(), &models.TaskEnvironment{ + TaskID: "task-H", + ExecutorType: "local_pc", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +// TestUpdateTaskEnvironment_RejectsClearingWorkspaceForWorktree — symmetric +// guard: a writer must not be able to clear a previously-populated +// workspace_path on a worktree env. +func TestUpdateTaskEnvironment_RejectsClearingWorkspaceForWorktree(t *testing.T) { + repo := newRepoForHealTests(t) + insertTask(t, repo.db, "task-I") + if err := repo.CreateTaskEnvironment(context.Background(), &models.TaskEnvironment{ + ID: "env-I", TaskID: "task-I", ExecutorType: "worktree", + WorktreePath: "/i", WorkspacePath: "/i", + }); err != nil { + t.Fatalf("seed: %v", err) + } + + err := repo.UpdateTaskEnvironment(context.Background(), &models.TaskEnvironment{ + ID: "env-I", TaskID: "task-I", ExecutorType: "worktree", + WorktreePath: "/i", WorkspacePath: "", + }) + if err == nil { + t.Fatal("expected update to fail when clearing workspace_path on worktree env") + } +} + +// silences "imported and not used" if some future refactor drops a use. +var _ = sql.ErrNoRows diff --git a/apps/backend/internal/task/repository/sqlite/task_environment.go b/apps/backend/internal/task/repository/sqlite/task_environment.go index 8661786ac3..4326a61df6 100644 --- a/apps/backend/internal/task/repository/sqlite/task_environment.go +++ b/apps/backend/internal/task/repository/sqlite/task_environment.go @@ -16,6 +16,13 @@ func (r *Repository) CreateTaskEnvironment(ctx context.Context, env *models.Task if env.ID == "" { env.ID = uuid.New().String() } + // Worktree-mode envs must always carry workspace_path. Without it, + // GetOrEnsureExecutionForEnvironment returns ErrSessionWorkspaceNotReady + // forever and the env terminal handler 503s. Reject at the boundary + // instead of letting a corrupt row land. + if env.ExecutorType == string(models.ExecutorTypeWorktree) && env.WorkspacePath == "" { + return fmt.Errorf("create task environment: worktree-mode env requires workspace_path (task=%s)", env.TaskID) + } now := time.Now().UTC() env.CreatedAt = now env.UpdatedAt = now @@ -98,6 +105,12 @@ func (r *Repository) GetTaskEnvironmentByTaskID(ctx context.Context, taskID stri // UpdateTaskEnvironment updates an existing task environment. func (r *Repository) UpdateTaskEnvironment(ctx context.Context, env *models.TaskEnvironment) error { + // Refuse to clear workspace_path on a worktree-mode env. Same rationale + // as CreateTaskEnvironment: empty workspace_path produces permanent 503 + // on shell terminal connect. + if env.ExecutorType == string(models.ExecutorTypeWorktree) && env.WorkspacePath == "" { + return fmt.Errorf("update task environment: worktree-mode env requires workspace_path (id=%s)", env.ID) + } env.UpdatedAt = time.Now().UTC() result, err := r.db.ExecContext(ctx, r.db.Rebind(` diff --git a/apps/web/components/task/passthrough-terminal.tsx b/apps/web/components/task/passthrough-terminal.tsx index ba9c172e3a..2f9bf460df 100644 --- a/apps/web/components/task/passthrough-terminal.tsx +++ b/apps/web/components/task/passthrough-terminal.tsx @@ -96,6 +96,29 @@ function useWsBaseUrl() { }, []); } +/** + * Decide whether the WS effect should attempt to open a terminal connection. + * + * Agent terminals require agentctl readiness — the agent process must be + * subscribed before passthrough I/O is meaningful. + * + * Shell terminals route by env on the backend (PR #758); the env handler + * lazy-creates the execution and waits for remote readiness server-side, + * so gating the client on `agentctlStatus.isReady` here just deadlocks when + * the ready event fired before the client subscribed (page reload, task + * switch, WS reconnect). Only require the routing keys. + */ +function computeCanConnect( + mode: "agent" | "shell", + connectionID: string | null | undefined, + sessionId: string | null | undefined, + isAgentctlReady: boolean, +): boolean { + if (!connectionID || !sessionId) return false; + if (mode === "agent") return isAgentctlReady; + return true; +} + // eslint-disable-next-line max-lines-per-function -- wires many hooks + refs; each block is already its own hook export function PassthroughTerminal(props: PassthroughTerminalProps) { const { mode, label, autoFocus, pendingCommand, onCommandSent } = props; @@ -111,13 +134,8 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) { const { session } = useSession(sessionId); const agentctlStatus = useSessionAgentctl(sessionId); const taskId = session?.task_id ?? null; - // Gate WS connection on agentctl readiness. During a long prepare script - // the backend terminal endpoint isn't accepting connections yet, and - // spamming reconnects burns cycles and confuses the loading state. - // Don't require isActive — restored workspaces (terminal-state sessions) - // have agentctl running but the session state stays COMPLETED/CANCELLED. const connectionID = mode === "agent" ? sessionId : environmentId; - const canConnect = Boolean(connectionID && sessionId && agentctlStatus.isReady); + const canConnect = computeCanConnect(mode, connectionID, sessionId, agentctlStatus.isReady); const wsBaseUrl = useWsBaseUrl(); const [isTerminalReady, setIsTerminalReady] = useState(false); diff --git a/apps/web/e2e/pages/session-page.ts b/apps/web/e2e/pages/session-page.ts index 7a5293425c..c90abb4a3e 100644 --- a/apps/web/e2e/pages/session-page.ts +++ b/apps/web/e2e/pages/session-page.ts @@ -438,6 +438,15 @@ export class SessionPage { await btn.click(); } + /** + * Wait until the shell terminal panel's "Connecting terminal..." overlay + * disappears — i.e. the WebSocket actually opened for that env terminal. + * Use this to detect the "terminal hangs forever on Connecting" bug. + */ + async expectTerminalConnected(timeout = 15_000): Promise { + await this.terminal.getByTestId("passthrough-loading").waitFor({ state: "hidden", timeout }); + } + /** * Wait for the terminal shell to be connected (buffer has content from * the prompt), then type a command and press Enter. diff --git a/apps/web/e2e/tests/terminal/terminal-hanging-on-boot.spec.ts b/apps/web/e2e/tests/terminal/terminal-hanging-on-boot.spec.ts new file mode 100644 index 0000000000..94c54c7e76 --- /dev/null +++ b/apps/web/e2e/tests/terminal/terminal-hanging-on-boot.spec.ts @@ -0,0 +1,228 @@ +import { test, expect } from "../../fixtures/test-base"; +import type { ApiClient } from "../../helpers/api-client"; +import type { SeedData } from "../../fixtures/test-base"; +import { KanbanPage } from "../../pages/kanban-page"; +import { SessionPage } from "../../pages/session-page"; +import type { Page } from "@playwright/test"; + +const DONE_STATES = ["COMPLETED", "WAITING_FOR_INPUT"]; + +/** + * Create a task with the seeded mock agent and wait for it to settle. + * The mock agent processes a "/e2e:simple-message" prompt and finishes, + * so the session reaches COMPLETED before we navigate. This is the same + * pattern used in terminal-env-keyed.spec.ts. + */ +async function createTaskAndWaitForDone( + apiClient: ApiClient, + seedData: SeedData, + title: string, + executorProfileId?: string, +) { + const task = await apiClient.createTaskWithAgent( + seedData.workspaceId, + title, + seedData.agentProfileId, + { + description: "/e2e:simple-message", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repository_ids: [seedData.repositoryId], + ...(executorProfileId ? { executor_profile_id: executorProfileId } : {}), + }, + ); + + await expect + .poll( + async () => { + const { sessions } = await apiClient.listTaskSessions(task.id); + return DONE_STATES.includes(sessions[0]?.state ?? ""); + }, + { timeout: 30_000, message: `Waiting for ${title} session to settle` }, + ) + .toBe(true); + + return task; +} + +/** Navigate via the kanban board to a task by title and wait for the session view. */ +async function navigateToTaskViaKanban(page: Page, title: string): Promise { + const kanban = new KanbanPage(page); + await kanban.goto(); + const card = kanban.taskCardByTitle(title); + await expect(card).toBeVisible({ timeout: 15_000 }); + await card.click(); + await expect(page).toHaveURL(/\/t\//, { timeout: 15_000 }); + const session = new SessionPage(page); + await session.waitForLoad(); + return session; +} + +test.describe("Terminal hangs on Connecting", () => { + /** + * Reproduces: opening a task whose session has already finished sometimes + * leaves the shell terminal panel stuck on "Connecting terminal..." forever. + * + * Why this hangs in current code: the shell terminal gates its WS open on + * `agentctlStatus.isReady` AND a non-null `environmentId`. Both come from + * events the backend only publishes when an execution is created. When the + * user lands on the task page after the agent's `agentctl_ready` event has + * already fired (and was missed because the WS wasn't connected yet), the + * frontend stays in `starting` and never opens the WS — so the backend's + * lazy `GetOrEnsureExecutionForEnvironment` is never invoked. Chicken-egg. + * + * Asserts the loading overlay disappears within a reasonable budget. + */ + test("shell terminal connects on cold load of a finished task", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(60_000); + await createTaskAndWaitForDone(apiClient, seedData, "Cold Load Terminal Task"); + + const session = await navigateToTaskViaKanban(testPage, "Cold Load Terminal Task"); + await session.clickTab("Terminal"); + await session.expectTerminalConnected(); + }); + + /** + * Reproduces: switching from one task to another via the kanban board + * leaves the second task's terminal stuck on "Connecting terminal...". + * + * Two tasks are created and both run to completion before any navigation + * happens — guaranteeing the agentctl events fired with no client connected. + * After landing on task B (the second navigation), the terminal panel must + * connect within a reasonable budget instead of hanging. + */ + test("shell terminal connects after switching tasks via kanban", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(90_000); + await createTaskAndWaitForDone(apiClient, seedData, "Switch Task Alpha"); + await createTaskAndWaitForDone(apiClient, seedData, "Switch Task Beta"); + + const session = await navigateToTaskViaKanban(testPage, "Switch Task Alpha"); + await session.clickTab("Terminal"); + await session.expectTerminalConnected(); + + // Now switch to task Beta via the kanban board — full client-side nav. + const kanban = new KanbanPage(testPage); + await kanban.goto(); + const beta = kanban.taskCardByTitle("Switch Task Beta"); + await expect(beta).toBeVisible({ timeout: 15_000 }); + await beta.click(); + await expect(testPage).toHaveURL(/\/t\//, { timeout: 15_000 }); + + const sessionB = new SessionPage(testPage); + await sessionB.waitForLoad(); + await sessionB.clickTab("Terminal"); + await sessionB.expectTerminalConnected(); + }); + + /** + * Reproduces: hard-reloading the page while viewing a task drops the + * agentctl status the client had cached from the original launch events. + * After reload the snapshot the backend sends on `session.subscribe` + * doesn't replay agentctl status, so the gate stays stuck and the + * terminal panel hangs on "Connecting terminal...". + */ + test("shell terminal reconnects after hard reload", async ({ testPage, apiClient, seedData }) => { + test.setTimeout(60_000); + await createTaskAndWaitForDone(apiClient, seedData, "Reload Terminal Task"); + + const session = await navigateToTaskViaKanban(testPage, "Reload Terminal Task"); + await session.clickTab("Terminal"); + await session.expectTerminalConnected(); + + await testPage.reload(); + const sessionAfter = new SessionPage(testPage); + await sessionAfter.waitForLoad(); + await sessionAfter.clickTab("Terminal"); + await sessionAfter.expectTerminalConnected(); + }); + + /** + * Reproduces: switching between tasks via the in-task sidebar (no full + * navigation) leaves the next task's terminal stuck on "Connecting + * terminal...". Sidebar navigation uses Next.js client-side routing so + * the same React tree mounts a different task — the env+agentctl gate + * has to recompute reactively. PR #755/#758 introduced new state + * dependencies (`environmentIdBySessionId`, `useEnvironmentId`) that + * occasionally read `null` for the just-clicked session. + */ + test("shell terminal connects after switching tasks via sidebar", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(120_000); + await createTaskAndWaitForDone(apiClient, seedData, "Sidebar Switch Alpha"); + await createTaskAndWaitForDone(apiClient, seedData, "Sidebar Switch Beta"); + + const session = await navigateToTaskViaKanban(testPage, "Sidebar Switch Alpha"); + await session.clickTab("Terminal"); + await session.expectTerminalConnected(); + + // In-task sidebar navigation: click the other task while staying on /t/. + const beta = session.taskInSidebar("Sidebar Switch Beta"); + await expect(beta).toBeVisible({ timeout: 15_000 }); + await beta.click(); + // The Terminal tab persists across the switch (env-keyed dockview), so + // the panel must reconnect for the new task's environment. + await session.expectTerminalConnected(); + }); + + /** + * User-reported repro (PT): "quando vou para um local executor o terminal + * nao aparece e depois fica lixado para todas as outras tasks, tenho de + * mandar hard refresh". + * + * Translation: visiting a task that uses a local-executor profile leaves + * its terminal stuck on Connecting AND poisons the terminal for every + * other task visited afterwards — only a hard refresh recovers. + * + * Tasks A and C use the default mock agent profile. Task B uses the + * worktree (local) executor profile. The flow: + * 1. Open A → terminal connects. + * 2. Switch to B (local executor) → its terminal must connect. + * 3. Switch to C (default again) → terminal must STILL connect. + * + * If step 2 hangs, step 3 also hangs without a hard reload — this asserts + * neither task's terminal gets stuck regardless of executor profile mix. + */ + test("local-executor task switch does not poison terminal for other tasks", async ({ + testPage, + apiClient, + seedData, + }) => { + test.setTimeout(150_000); + + await createTaskAndWaitForDone(apiClient, seedData, "Default Exec A"); + await createTaskAndWaitForDone( + apiClient, + seedData, + "Local Exec B", + seedData.worktreeExecutorProfileId, + ); + await createTaskAndWaitForDone(apiClient, seedData, "Default Exec C"); + + const session = await navigateToTaskViaKanban(testPage, "Default Exec A"); + await session.clickTab("Terminal"); + await session.expectTerminalConnected(); + + // Switch to local-executor task via sidebar (in-app nav, no full reload). + const taskB = session.taskInSidebar("Local Exec B"); + await expect(taskB).toBeVisible({ timeout: 15_000 }); + await taskB.click(); + await session.expectTerminalConnected(); + + // Switch to a different default-executor task — must not be poisoned by B. + const taskC = session.taskInSidebar("Default Exec C"); + await expect(taskC).toBeVisible({ timeout: 15_000 }); + await taskC.click(); + await session.expectTerminalConnected(); + }); +});