- No task selected
+
+
+
+
+ {isPassthroughMode ? (
+
+ ) : (
+
+ )}
);
}
@@ -70,7 +79,6 @@ type MobilePanelAreaProps = {
activeTaskId: string | null;
isPassthroughMode: boolean;
effectiveSessionId: string | null;
- sessionId?: string | null;
selectedDiff: { path: string; content?: string } | null;
handleOpenFileFromChat: (path: string) => void;
handleClearSelectedDiff: () => void;
@@ -85,7 +93,6 @@ function MobilePanelArea({
activeTaskId,
isPassthroughMode,
effectiveSessionId,
- sessionId,
selectedDiff,
handleOpenFileFromChat,
handleClearSelectedDiff,
@@ -112,12 +119,11 @@ function MobilePanelArea({
}}
>
{currentMobilePanel === "chat" && (
-
+
@@ -147,11 +153,11 @@ function MobilePanelArea({
{currentMobilePanel === "terminal" && (
-
-
+
+
)}
@@ -159,6 +165,53 @@ function MobilePanelArea({
);
}
+type MobileTopBarStickyProps = {
+ activeTaskId: string | null;
+ workspaceId: string | null;
+ taskTitle?: string;
+ effectiveSessionId: string | null;
+ baseBranch?: string;
+ worktreeBranch?: string | null;
+ onMenuClick: () => void;
+ showApproveButton: boolean;
+ onApprove: () => void;
+ isRemoteExecutor?: boolean;
+ remoteExecutorType?: string | null;
+ remoteExecutorName?: string | null;
+ remoteState?: string | null;
+ remoteCreatedAt?: string | null;
+ remoteCheckedAt?: string | null;
+ remoteStatusError?: string | null;
+};
+
+function MobileTopBarSticky(props: MobileTopBarStickyProps) {
+ return (
+
+
+
+ );
+}
+
function useMobilePanelHandlers({
handleSelectDiff,
handlePanelChange,
@@ -235,29 +288,24 @@ export const SessionMobileLayout = memo(function SessionMobileLayout({
return (
- {/* Fixed Top Bar */}
-
-
-
+
{/* Content Area - fixed height panels that manage their own scrolling */}
+
{isRemoteExecutor && (
({
+ id: step.id,
+ title: step.name,
+ color: step.color,
+ position: step.position,
+ events: step.events,
+ // Carry optional step capabilities forward so downstream UI doesn't see
+ // them as missing after a workspace switch (until a full reload).
+ allow_manual_move: step.allow_manual_move,
+ prompt: step.prompt,
+ is_start_step: step.is_start_step,
+ show_in_command_panel: step.show_in_command_panel,
+ agent_profile_id: step.agent_profile_id,
+ })),
+ tasks: snapshot.tasks.map((task) => ({
+ id: task.id,
+ workflowStepId: task.workflow_step_id,
+ title: task.title,
+ description: task.description ?? undefined,
+ position: task.position ?? 0,
+ state: task.state,
+ repositoryId: task.repositories?.[0]?.repository_id ?? undefined,
+ // Carry the full TaskRepository array so the mobile repo picker
+ // (useTaskRepoCount + MobileReposSection) keeps working after a
+ // workspace switch. Without this, the picker silently disappears for
+ // multi-repo tasks because length defaults to 0.
+ repositories: task.repositories?.map((r) => ({
+ id: r.id,
+ repository_id: r.repository_id,
+ base_branch: r.base_branch,
+ checkout_branch: r.checkout_branch,
+ position: r.position,
+ })),
+ primarySessionId: task.primary_session_id ?? undefined,
+ primarySessionState: task.primary_session_state ?? undefined,
+ sessionCount: task.session_count ?? undefined,
+ reviewStatus: task.review_status ?? undefined,
+ primaryExecutorId: task.primary_executor_id ?? undefined,
+ primaryExecutorType: task.primary_executor_type ?? undefined,
+ primaryExecutorName: task.primary_executor_name ?? undefined,
+ isRemoteExecutor: task.is_remote_executor ?? false,
+ updatedAt: task.updated_at,
+ })),
+ };
+}
+
+function sortByUpdatedAtDesc(items: T[]): T[] {
+ return [...items].sort((a, b) => {
+ const aDate = a.updated_at ? new Date(a.updated_at).getTime() : 0;
+ const bDate = b.updated_at ? new Date(b.updated_at).getTime() : 0;
+ return bDate - aDate;
+ });
+}
+
+export function useSheetData(workspaceId: string | null, workflowId: string | null) {
+ const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
+ const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
+ const sessionsById = useAppStore((state) => state.taskSessions.items);
+ const sessionsByTaskId = useAppStore((state) => state.taskSessionsByTask.itemsByTaskId);
+ const gitStatusByEnvId = useAppStore((state) => state.gitStatus.byEnvironmentId);
+ const envIdBySessionId = useAppStore((state) => state.environmentIdBySessionId);
+ const messagesBySession = useAppStore((state) => state.messages.bySession);
+ const { tasks } = useTasks(workflowId);
+ const steps = useAppStore((state) => state.kanban.steps);
+ const workspaces = useAppStore((state) => state.workspaces.items);
+ const repositoriesByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId);
+ const kanbanIsLoading = useAppStore((state) => state.kanban.isLoading ?? false);
+
+ const selectedTaskId = useMemo(() => {
+ if (activeSessionId) return sessionsById[activeSessionId]?.task_id ?? activeTaskId;
+ return activeTaskId;
+ }, [activeSessionId, activeTaskId, sessionsById]);
+
+ const tasksWithRepositories = useMemo(() => {
+ const repositories = workspaceId ? (repositoriesByWorkspace[workspaceId] ?? []) : [];
+ const repositoryPathsById = new Map(
+ repositories.map((repo: Repository) => [repo.id, repo.local_path]),
+ );
+ return tasks.map((task: KanbanState["tasks"][number]) => {
+ const sessionInfo = getSessionInfoForTask(
+ task.id,
+ sessionsByTaskId,
+ gitStatusByEnvId,
+ envIdBySessionId,
+ );
+ return {
+ id: task.id,
+ title: task.title,
+ state: task.state as TaskState | undefined,
+ sessionState:
+ sessionInfo.sessionState ?? (task.primarySessionState as TaskSessionState | undefined),
+ description: task.description,
+ workflowStepId: task.workflowStepId,
+ repositoryPath: task.repositoryId ? repositoryPathsById.get(task.repositoryId) : undefined,
+ diffStats: sessionInfo.diffStats,
+ updatedAt: sessionInfo.updatedAt ?? task.updatedAt,
+ isRemoteExecutor: task.isRemoteExecutor,
+ remoteExecutorType: task.primaryExecutorType ?? undefined,
+ remoteExecutorName: task.primaryExecutorName ?? undefined,
+ primarySessionId: task.primarySessionId ?? null,
+ hasPendingClarification: hasPendingClarificationForSession(
+ messagesBySession,
+ task.primarySessionId,
+ ),
+ };
+ });
+ }, [
+ repositoriesByWorkspace,
+ tasks,
+ workspaceId,
+ sessionsByTaskId,
+ gitStatusByEnvId,
+ envIdBySessionId,
+ messagesBySession,
+ ]);
+
+ const dialogSteps = useMemo(
+ () =>
+ steps.map((step: KanbanState["steps"][number]) => ({
+ id: step.id,
+ title: step.title,
+ color: step.color,
+ events: step.events,
+ })),
+ [steps],
+ );
+
+ return {
+ activeTaskId,
+ selectedTaskId,
+ steps,
+ workspaces,
+ kanbanIsLoading,
+ tasksWithRepositories,
+ dialogSteps,
+ };
+}
+
+type SheetNavOptions = {
+ workspaceId: string | null;
+ store: ReturnType;
+ loadTaskSessionsForTask: (
+ taskId: string,
+ ) => Promise>;
+ setActiveSession: (taskId: string, sessionId: string) => void;
+ setActiveTask: (taskId: string) => void;
+ onOpenChange: (open: boolean) => void;
+};
+
+async function switchWorkspace(newWorkspaceId: string, opts: SheetNavOptions) {
+ const { store, loadTaskSessionsForTask, setActiveSession, setActiveTask, onOpenChange } = opts;
+ store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: true } }));
+ try {
+ const workflowsResponse = await listWorkflows(newWorkspaceId, {
+ cache: "no-store",
+ includeHidden: true,
+ });
+ const newWorkspaceWorkflows = workflowsResponse.workflows ?? [];
+ const firstWorkflow = newWorkspaceWorkflows.find((w) => !w.hidden);
+ if (!firstWorkflow) {
+ store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: false } }));
+ return;
+ }
+ const snapshot = await fetchWorkflowSnapshot(firstWorkflow.id);
+ store.setState((state) => ({
+ ...state,
+ workflows: {
+ ...state.workflows,
+ items: [
+ ...state.workflows.items.filter(
+ (w: { workspaceId: string }) => w.workspaceId !== newWorkspaceId,
+ ),
+ ...newWorkspaceWorkflows.map((w) => ({
+ id: w.id,
+ workspaceId: w.workspace_id,
+ name: w.name,
+ hidden: w.hidden,
+ })),
+ ],
+ activeId: firstWorkflow.id,
+ },
+ kanban: mapSnapshotToKanban(snapshot, firstWorkflow.id),
+ }));
+ const mostRecentTask = sortByUpdatedAtDesc(snapshot.tasks)[0];
+ if (mostRecentTask) {
+ const sessions = await loadTaskSessionsForTask(mostRecentTask.id);
+ const mostRecentSession = sortByUpdatedAtDesc(sessions)[0];
+ if (mostRecentSession) {
+ setActiveSession(mostRecentTask.id, mostRecentSession.id);
+ } else {
+ setActiveTask(mostRecentTask.id);
+ }
+ replaceTaskUrl(mostRecentTask.id);
+ }
+ onOpenChange(false);
+ } catch (error) {
+ console.error("Failed to switch workspace:", error);
+ store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: false } }));
+ }
+}
+
+function mapTaskRepositories(
+ repositories: Task["repositories"],
+): KanbanState["tasks"][number]["repositories"] {
+ return repositories?.map((r) => ({
+ id: r.id,
+ repository_id: r.repository_id,
+ base_branch: r.base_branch,
+ checkout_branch: r.checkout_branch,
+ position: r.position,
+ }));
+}
+
+function mergeSessionFields(
+ task: Task,
+ existing: KanbanState["tasks"][number] | undefined,
+ taskSessionId: string | null,
+) {
+ return {
+ primarySessionId:
+ taskSessionId ?? task.primary_session_id ?? existing?.primarySessionId ?? undefined,
+ primarySessionState: task.primary_session_state ?? existing?.primarySessionState ?? undefined,
+ sessionCount: task.session_count ?? existing?.sessionCount ?? (taskSessionId ? 1 : undefined),
+ reviewStatus: task.review_status ?? existing?.reviewStatus ?? undefined,
+ };
+}
+
+/**
+ * Build the kanban-store representation of a task for an upsert. Session-
+ * derived fields (primarySessionId, sessionCount, etc.) fall through new
+ * DTO → existing entry → meta.taskSessionId — that way an "edit" call doesn't
+ * wipe sessions the existing entry carried, and "create with session" still
+ * sets the primary correctly.
+ */
+function buildKanbanTaskUpsert(
+ task: Task,
+ existing: KanbanState["tasks"][number] | undefined,
+ meta: { taskSessionId?: string | null } | undefined,
+): KanbanState["tasks"][number] {
+ const taskSessionId = meta?.taskSessionId ?? null;
+ return {
+ id: task.id,
+ workflowStepId: task.workflow_step_id,
+ title: task.title,
+ description: task.description,
+ position: task.position ?? 0,
+ state: task.state,
+ repositoryId: task.repositories?.[0]?.repository_id ?? undefined,
+ repositories: mapTaskRepositories(task.repositories),
+ updatedAt: task.updated_at,
+ ...mergeSessionFields(task, existing, taskSessionId),
+ primaryExecutorId: task.primary_executor_id ?? undefined,
+ primaryExecutorType: task.primary_executor_type ?? undefined,
+ primaryExecutorName: task.primary_executor_name ?? undefined,
+ isRemoteExecutor: task.is_remote_executor ?? false,
+ };
+}
+
+function useWorkspaceAndTaskCreatedActions(opts: SheetNavOptions) {
+ const {
+ workspaceId,
+ store,
+ loadTaskSessionsForTask,
+ setActiveSession,
+ setActiveTask,
+ onOpenChange,
+ } = opts;
+
+ const handleWorkspaceChange = useCallback(
+ async (newWorkspaceId: string) => {
+ if (newWorkspaceId === workspaceId) return;
+ await switchWorkspace(newWorkspaceId, {
+ workspaceId,
+ store,
+ loadTaskSessionsForTask,
+ setActiveSession,
+ setActiveTask,
+ onOpenChange,
+ });
+ },
+ // Spread the individual fields rather than the `opts` object so callers
+ // re-passing a fresh literal each render don't defeat memoization.
+ [workspaceId, store, loadTaskSessionsForTask, setActiveSession, setActiveTask, onOpenChange],
+ );
+
+ const handleTaskCreated = useCallback(
+ (task: Task, _mode: "create" | "edit", meta?: { taskSessionId?: string | null }) => {
+ store.setState((state) => {
+ if (state.kanban.workflowId !== task.workflow_id) return state;
+ const existing = state.kanban.tasks.find(
+ (item: KanbanState["tasks"][number]) => item.id === task.id,
+ );
+ const nextTask = buildKanbanTaskUpsert(task, existing, meta);
+ return {
+ ...state,
+ kanban: {
+ ...state.kanban,
+ tasks: state.kanban.tasks.some(
+ (item: KanbanState["tasks"][number]) => item.id === task.id,
+ )
+ ? state.kanban.tasks.map((item: KanbanState["tasks"][number]) =>
+ item.id === task.id ? nextTask : item,
+ )
+ : [...state.kanban.tasks, nextTask],
+ },
+ };
+ });
+ setActiveTask(task.id);
+ if (meta?.taskSessionId) {
+ setActiveSession(task.id, meta.taskSessionId);
+ }
+ replaceTaskUrl(task.id);
+ onOpenChange(false);
+ },
+ [store, setActiveTask, setActiveSession, onOpenChange],
+ );
+
+ return { handleWorkspaceChange, handleTaskCreated };
+}
+
+type SelectTaskOptions = {
+ setActiveTask: (taskId: string) => void;
+ setActiveSession: (taskId: string, sessionId: string) => void;
+ loadTaskSessionsForTask: SheetNavOptions["loadTaskSessionsForTask"];
+ onOpenChange: (open: boolean) => void;
+};
+
+async function selectTaskWithoutPrimarySession(taskId: string, opts: SelectTaskOptions) {
+ const { setActiveTask, setActiveSession, loadTaskSessionsForTask, onOpenChange } = opts;
+ try {
+ const sessions = await loadTaskSessionsForTask(taskId);
+ const sessionId = sessions[0]?.id ?? null;
+ if (sessionId) {
+ setActiveSession(taskId, sessionId);
+ replaceTaskUrl(taskId);
+ onOpenChange(false);
+ return;
+ }
+ // No session — prepare workspace.
+ const { request } = buildPrepareRequest(taskId);
+ try {
+ const resp = await launchSession(request);
+ if (resp.session_id) {
+ setActiveSession(taskId, resp.session_id);
+ replaceTaskUrl(taskId);
+ onOpenChange(false);
+ return;
+ }
+ } catch {
+ // Fall through to default navigation.
+ }
+ } catch (error) {
+ // Loading sessions can reject (network / 5xx). Don't strand the user;
+ // fall back to plain task navigation so URL + state still align with tap.
+ console.error("Failed to load sessions for task:", error);
+ }
+ setActiveTask(taskId);
+ replaceTaskUrl(taskId);
+ onOpenChange(false);
+}
+
+export function useSheetActions(workspaceId: string | null, onOpenChange: (open: boolean) => void) {
+ const setActiveTask = useAppStore((state) => state.setActiveTask);
+ const setActiveSession = useAppStore((state) => state.setActiveSession);
+ const store = useAppStoreApi();
+ const [deletingTaskId, setDeletingTaskId] = useState(null);
+ const { deleteTaskById } = useTaskActions();
+ const archiveAndSwitch = useArchiveAndSwitchTask();
+ const { removeTaskFromBoard, loadTaskSessionsForTask } = useTaskRemoval({ store });
+
+ const handleSelectTask = useCallback(
+ (taskId: string) => {
+ const kanbanTasks = store.getState().kanban.tasks;
+ const task = kanbanTasks.find((t) => t.id === taskId);
+ if (task?.primarySessionId) {
+ setActiveSession(taskId, task.primarySessionId);
+ loadTaskSessionsForTask(taskId);
+ replaceTaskUrl(taskId);
+ onOpenChange(false);
+ return;
+ }
+ void selectTaskWithoutPrimarySession(taskId, {
+ setActiveTask,
+ setActiveSession,
+ loadTaskSessionsForTask,
+ onOpenChange,
+ });
+ },
+ [loadTaskSessionsForTask, setActiveSession, setActiveTask, store, onOpenChange],
+ );
+
+ const [archivingTask, setArchivingTask] = useState<{ id: string; title: string } | null>(null);
+ const [isArchiving, setIsArchiving] = useState(false);
+
+ const handleArchiveTask = useCallback(
+ (taskId: string) => {
+ const task = store.getState().kanban.tasks.find((t) => t.id === taskId);
+ setArchivingTask({ id: taskId, title: task?.title ?? "this task" });
+ },
+ [store],
+ );
+
+ const handleArchiveConfirm = useCallback(async () => {
+ if (!archivingTask) return;
+ setIsArchiving(true);
+ try {
+ await archiveAndSwitch(archivingTask.id);
+ } catch (error) {
+ console.error("Failed to archive task:", error);
+ } finally {
+ setIsArchiving(false);
+ setArchivingTask(null);
+ }
+ }, [archivingTask, archiveAndSwitch]);
+
+ const handleDeleteTask = useCallback(
+ async (taskId: string) => {
+ setDeletingTaskId(taskId);
+ // Capture active state before the async API call — the WS "task.deleted"
+ // handler may clear activeTaskId/activeSessionId before removeTaskFromBoard runs.
+ const { activeTaskId: wasActiveTaskId, activeSessionId: wasActiveSessionId } =
+ store.getState().tasks;
+ try {
+ await deleteTaskById(taskId);
+ await removeTaskFromBoard(taskId, { wasActiveTaskId, wasActiveSessionId });
+ } finally {
+ setDeletingTaskId(null);
+ }
+ },
+ [deleteTaskById, removeTaskFromBoard, store],
+ );
+
+ const { handleWorkspaceChange, handleTaskCreated } = useWorkspaceAndTaskCreatedActions({
+ workspaceId,
+ store,
+ loadTaskSessionsForTask,
+ setActiveSession,
+ setActiveTask,
+ onOpenChange,
+ });
+
+ return {
+ deletingTaskId,
+ handleSelectTask,
+ handleArchiveTask,
+ handleDeleteTask,
+ handleWorkspaceChange,
+ handleTaskCreated,
+ archivingTask,
+ setArchivingTask,
+ isArchiving,
+ handleArchiveConfirm,
+ };
+}
diff --git a/apps/web/components/task/mobile/session-task-switcher-sheet.tsx b/apps/web/components/task/mobile/session-task-switcher-sheet.tsx
index bd77534589..509ced78ce 100644
--- a/apps/web/components/task/mobile/session-task-switcher-sheet.tsx
+++ b/apps/web/components/task/mobile/session-task-switcher-sheet.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useMemo, useState, memo } from "react";
+import { useMemo, useState, memo } from "react";
import { IconPlus } from "@tabler/icons-react";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@kandev/ui/sheet";
import { Button } from "@kandev/ui/button";
@@ -12,25 +12,8 @@ import { useSidebarTaskPrefs } from "@/hooks/domains/sidebar/use-sidebar-task-pr
import { WorkspaceSwitcher } from "../workspace-switcher";
import { TaskCreateDialog } from "@/components/task-create-dialog";
import { TaskArchiveConfirmDialog } from "../task-archive-confirm-dialog";
-import { useAppStore, useAppStoreApi } from "@/components/state-provider";
-import { replaceTaskUrl } from "@/lib/links";
-import { fetchWorkflowSnapshot, listWorkflows } from "@/lib/api";
-import { launchSession } from "@/lib/services/session-launch-service";
-import { buildPrepareRequest } from "@/lib/services/session-launch-helpers";
-import { useTasks } from "@/hooks/use-tasks";
-import { useTaskActions, useArchiveAndSwitchTask } from "@/hooks/use-task-actions";
-import { useTaskRemoval } from "@/hooks/use-task-removal";
-import { getSessionInfoForTask } from "@/lib/utils/session-info";
-import { hasPendingClarificationForSession } from "@/lib/utils/pending-clarification";
-import type {
- TaskState,
- TaskSessionState,
- Workspace,
- Repository,
- Task,
- WorkflowSnapshot,
-} from "@/lib/types/http";
-import type { KanbanState } from "@/lib/state/slices";
+import { useSheetData, useSheetActions } from "./session-task-switcher-sheet-hooks";
+import type { Workspace } from "@/lib/types/http";
type SessionTaskSwitcherSheetProps = {
open: boolean;
@@ -39,361 +22,6 @@ type SessionTaskSwitcherSheetProps = {
workflowId: string | null;
};
-// Helper to map workflow snapshot to kanban state
-function mapSnapshotToKanban(snapshot: WorkflowSnapshot, newWorkflowId: string) {
- return {
- workflowId: newWorkflowId,
- isLoading: false,
- steps: snapshot.steps.map((step) => ({
- id: step.id,
- title: step.name,
- color: step.color,
- position: step.position,
- events: step.events,
- })),
- tasks: snapshot.tasks.map((task) => ({
- id: task.id,
- workflowStepId: task.workflow_step_id,
- title: task.title,
- description: task.description ?? undefined,
- position: task.position ?? 0,
- state: task.state,
- repositoryId: task.repositories?.[0]?.repository_id ?? undefined,
- primarySessionId: task.primary_session_id ?? undefined,
- primarySessionState: task.primary_session_state ?? undefined,
- sessionCount: task.session_count ?? undefined,
- reviewStatus: task.review_status ?? undefined,
- primaryExecutorId: task.primary_executor_id ?? undefined,
- primaryExecutorType: task.primary_executor_type ?? undefined,
- primaryExecutorName: task.primary_executor_name ?? undefined,
- isRemoteExecutor: task.is_remote_executor ?? false,
- updatedAt: task.updated_at,
- })),
- };
-}
-
-// Helper to sort by updated_at descending
-function sortByUpdatedAtDesc(items: T[]): T[] {
- return [...items].sort((a, b) => {
- const aDate = a.updated_at ? new Date(a.updated_at).getTime() : 0;
- const bDate = b.updated_at ? new Date(b.updated_at).getTime() : 0;
- return bDate - aDate;
- });
-}
-
-function useSheetData(workspaceId: string | null, workflowId: string | null) {
- const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
- const activeSessionId = useAppStore((state) => state.tasks.activeSessionId);
- const sessionsById = useAppStore((state) => state.taskSessions.items);
- const sessionsByTaskId = useAppStore((state) => state.taskSessionsByTask.itemsByTaskId);
- const gitStatusByEnvId = useAppStore((state) => state.gitStatus.byEnvironmentId);
- const envIdBySessionId = useAppStore((state) => state.environmentIdBySessionId);
- const messagesBySession = useAppStore((state) => state.messages.bySession);
- const { tasks } = useTasks(workflowId);
- const steps = useAppStore((state) => state.kanban.steps);
- const workspaces = useAppStore((state) => state.workspaces.items);
- const repositoriesByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId);
- const kanbanIsLoading = useAppStore((state) => state.kanban.isLoading ?? false);
-
- const selectedTaskId = useMemo(() => {
- if (activeSessionId) return sessionsById[activeSessionId]?.task_id ?? activeTaskId;
- return activeTaskId;
- }, [activeSessionId, activeTaskId, sessionsById]);
-
- const tasksWithRepositories = useMemo(() => {
- const repositories = workspaceId ? (repositoriesByWorkspace[workspaceId] ?? []) : [];
- const repositoryPathsById = new Map(
- repositories.map((repo: Repository) => [repo.id, repo.local_path]),
- );
- return tasks.map((task: KanbanState["tasks"][number]) => {
- const sessionInfo = getSessionInfoForTask(
- task.id,
- sessionsByTaskId,
- gitStatusByEnvId,
- envIdBySessionId,
- );
- return {
- id: task.id,
- title: task.title,
- state: task.state as TaskState | undefined,
- sessionState:
- sessionInfo.sessionState ?? (task.primarySessionState as TaskSessionState | undefined),
- description: task.description,
- workflowStepId: task.workflowStepId,
- repositoryPath: task.repositoryId ? repositoryPathsById.get(task.repositoryId) : undefined,
- diffStats: sessionInfo.diffStats,
- updatedAt: sessionInfo.updatedAt ?? task.updatedAt,
- isRemoteExecutor: task.isRemoteExecutor,
- remoteExecutorType: task.primaryExecutorType ?? undefined,
- remoteExecutorName: task.primaryExecutorName ?? undefined,
- primarySessionId: task.primarySessionId ?? null,
- hasPendingClarification: hasPendingClarificationForSession(
- messagesBySession,
- task.primarySessionId,
- ),
- };
- });
- }, [
- repositoriesByWorkspace,
- tasks,
- workspaceId,
- sessionsByTaskId,
- gitStatusByEnvId,
- envIdBySessionId,
- messagesBySession,
- ]);
-
- const dialogSteps = useMemo(
- () =>
- steps.map((step: KanbanState["steps"][number]) => ({
- id: step.id,
- title: step.title,
- color: step.color,
- events: step.events,
- })),
- [steps],
- );
-
- return {
- activeTaskId,
- selectedTaskId,
- steps,
- workspaces,
- kanbanIsLoading,
- tasksWithRepositories,
- dialogSteps,
- };
-}
-
-type SheetNavOptions = {
- workspaceId: string | null;
- store: ReturnType;
- loadTaskSessionsForTask: (
- taskId: string,
- ) => Promise>;
- setActiveSession: (taskId: string, sessionId: string) => void;
- setActiveTask: (taskId: string) => void;
- onOpenChange: (open: boolean) => void;
-};
-
-async function switchWorkspace(newWorkspaceId: string, opts: SheetNavOptions) {
- const { store, loadTaskSessionsForTask, setActiveSession, setActiveTask, onOpenChange } = opts;
- store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: true } }));
- try {
- const workflowsResponse = await listWorkflows(newWorkspaceId, {
- cache: "no-store",
- includeHidden: true,
- });
- const newWorkspaceWorkflows = workflowsResponse.workflows ?? [];
- const firstWorkflow = newWorkspaceWorkflows.find((w) => !w.hidden);
- if (!firstWorkflow) {
- store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: false } }));
- return;
- }
- const snapshot = await fetchWorkflowSnapshot(firstWorkflow.id);
- store.setState((state) => ({
- ...state,
- workflows: {
- ...state.workflows,
- items: [
- ...state.workflows.items.filter(
- (w: { workspaceId: string }) => w.workspaceId !== newWorkspaceId,
- ),
- ...newWorkspaceWorkflows.map((w) => ({
- id: w.id,
- workspaceId: w.workspace_id,
- name: w.name,
- hidden: w.hidden,
- })),
- ],
- activeId: firstWorkflow.id,
- },
- kanban: mapSnapshotToKanban(snapshot, firstWorkflow.id),
- }));
- const mostRecentTask = sortByUpdatedAtDesc(snapshot.tasks)[0];
- if (mostRecentTask) {
- const sessions = await loadTaskSessionsForTask(mostRecentTask.id);
- const mostRecentSession = sortByUpdatedAtDesc(sessions)[0];
- if (mostRecentSession) {
- setActiveSession(mostRecentTask.id, mostRecentSession.id);
- } else {
- setActiveTask(mostRecentTask.id);
- }
- replaceTaskUrl(mostRecentTask.id);
- }
- onOpenChange(false);
- } catch (error) {
- console.error("Failed to switch workspace:", error);
- store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: false } }));
- }
-}
-
-function useWorkspaceAndTaskCreatedActions(opts: SheetNavOptions) {
- const { workspaceId, store, setActiveSession, setActiveTask, onOpenChange } = opts;
-
- const handleWorkspaceChange = useCallback(
- async (newWorkspaceId: string) => {
- if (newWorkspaceId === workspaceId) return;
- await switchWorkspace(newWorkspaceId, opts);
- },
- [workspaceId, opts],
- );
-
- const handleTaskCreated = useCallback(
- (task: Task, _mode: "create" | "edit", meta?: { taskSessionId?: string | null }) => {
- store.setState((state) => {
- if (state.kanban.workflowId !== task.workflow_id) return state;
- const nextTask = {
- id: task.id,
- workflowStepId: task.workflow_step_id,
- title: task.title,
- description: task.description,
- position: task.position ?? 0,
- state: task.state,
- repositoryId: task.repositories?.[0]?.repository_id ?? undefined,
- updatedAt: task.updated_at,
- primaryExecutorId: task.primary_executor_id ?? undefined,
- primaryExecutorType: task.primary_executor_type ?? undefined,
- primaryExecutorName: task.primary_executor_name ?? undefined,
- isRemoteExecutor: task.is_remote_executor ?? false,
- };
- return {
- ...state,
- kanban: {
- ...state.kanban,
- tasks: state.kanban.tasks.some(
- (item: KanbanState["tasks"][number]) => item.id === task.id,
- )
- ? state.kanban.tasks.map((item: KanbanState["tasks"][number]) =>
- item.id === task.id ? nextTask : item,
- )
- : [...state.kanban.tasks, nextTask],
- },
- };
- });
- setActiveTask(task.id);
- if (meta?.taskSessionId) {
- setActiveSession(task.id, meta.taskSessionId);
- }
- replaceTaskUrl(task.id);
- onOpenChange(false);
- },
- [store, setActiveTask, setActiveSession, onOpenChange],
- );
-
- return { handleWorkspaceChange, handleTaskCreated };
-}
-
-function useSheetActions(workspaceId: string | null, onOpenChange: (open: boolean) => void) {
- const setActiveTask = useAppStore((state) => state.setActiveTask);
- const setActiveSession = useAppStore((state) => state.setActiveSession);
- const store = useAppStoreApi();
- const [deletingTaskId, setDeletingTaskId] = useState(null);
- const { deleteTaskById } = useTaskActions();
- const archiveAndSwitch = useArchiveAndSwitchTask();
- const { removeTaskFromBoard, loadTaskSessionsForTask } = useTaskRemoval({ store });
-
- const handleSelectTask = useCallback(
- (taskId: string) => {
- const kanbanTasks = store.getState().kanban.tasks;
- const task = kanbanTasks.find((t) => t.id === taskId);
- if (task?.primarySessionId) {
- setActiveSession(taskId, task.primarySessionId);
- loadTaskSessionsForTask(taskId);
- replaceTaskUrl(taskId);
- onOpenChange(false);
- return;
- }
- loadTaskSessionsForTask(taskId).then(async (sessions) => {
- const sessionId = sessions[0]?.id ?? null;
- if (sessionId) {
- setActiveSession(taskId, sessionId);
- replaceTaskUrl(taskId);
- onOpenChange(false);
- return;
- }
- // No session — prepare workspace
- const { request } = buildPrepareRequest(taskId);
- try {
- const resp = await launchSession(request);
- if (resp.session_id) {
- setActiveSession(taskId, resp.session_id);
- }
- } catch {
- // Fall through to default behavior
- }
- setActiveTask(taskId);
- replaceTaskUrl(taskId);
- onOpenChange(false);
- });
- },
- [loadTaskSessionsForTask, setActiveSession, setActiveTask, store, onOpenChange],
- );
-
- const [archivingTask, setArchivingTask] = useState<{ id: string; title: string } | null>(null);
- const [isArchiving, setIsArchiving] = useState(false);
-
- const handleArchiveTask = useCallback(
- (taskId: string) => {
- const task = store.getState().kanban.tasks.find((t) => t.id === taskId);
- setArchivingTask({ id: taskId, title: task?.title ?? "this task" });
- },
- [store],
- );
-
- const handleArchiveConfirm = useCallback(async () => {
- if (!archivingTask) return;
- setIsArchiving(true);
- try {
- await archiveAndSwitch(archivingTask.id);
- } catch (error) {
- console.error("Failed to archive task:", error);
- } finally {
- setIsArchiving(false);
- setArchivingTask(null);
- }
- }, [archivingTask, archiveAndSwitch]);
-
- const handleDeleteTask = useCallback(
- async (taskId: string) => {
- setDeletingTaskId(taskId);
- // Capture active state before the async API call — the WS "task.deleted"
- // handler may clear activeTaskId/activeSessionId before removeTaskFromBoard runs.
- const { activeTaskId: wasActiveTaskId, activeSessionId: wasActiveSessionId } =
- store.getState().tasks;
- try {
- await deleteTaskById(taskId);
- await removeTaskFromBoard(taskId, { wasActiveTaskId, wasActiveSessionId });
- } finally {
- setDeletingTaskId(null);
- }
- },
- [deleteTaskById, removeTaskFromBoard, store],
- );
-
- const { handleWorkspaceChange, handleTaskCreated } = useWorkspaceAndTaskCreatedActions({
- workspaceId,
- store,
- loadTaskSessionsForTask,
- setActiveSession,
- setActiveTask,
- onOpenChange,
- });
-
- return {
- deletingTaskId,
- handleSelectTask,
- handleArchiveTask,
- handleDeleteTask,
- handleWorkspaceChange,
- handleTaskCreated,
- archivingTask,
- setArchivingTask,
- isArchiving,
- handleArchiveConfirm,
- };
-}
-
function MobileTaskList({
tasks,
activeTaskId,
@@ -445,26 +73,8 @@ export const SessionTaskSwitcherSheet = memo(function SessionTaskSwitcherSheet({
workflowId,
}: SessionTaskSwitcherSheetProps) {
const [dialogOpen, setDialogOpen] = useState(false);
- const {
- activeTaskId,
- selectedTaskId,
- workspaces,
- kanbanIsLoading,
- tasksWithRepositories,
- dialogSteps,
- } = useSheetData(workspaceId, workflowId);
- const {
- deletingTaskId,
- handleSelectTask,
- handleArchiveTask,
- handleDeleteTask,
- handleWorkspaceChange,
- handleTaskCreated,
- archivingTask,
- setArchivingTask,
- isArchiving,
- handleArchiveConfirm,
- } = useSheetActions(workspaceId, onOpenChange);
+ const data = useSheetData(workspaceId, workflowId);
+ const actions = useSheetActions(workspaceId, onOpenChange);
return (
@@ -488,23 +98,23 @@ export const SessionTaskSwitcherSheet = memo(function SessionTaskSwitcherSheet({
({ id: w.id, name: w.name }))}
+ workspaces={data.workspaces.map((w: Workspace) => ({ id: w.id, name: w.name }))}
activeWorkspaceId={workspaceId}
- onSelect={handleWorkspaceChange}
+ onSelect={actions.handleWorkspaceChange}
/>
@@ -515,19 +125,19 @@ export const SessionTaskSwitcherSheet = memo(function SessionTaskSwitcherSheet({
mode="create"
workspaceId={workspaceId}
workflowId={workflowId}
- defaultStepId={dialogSteps[0]?.id ?? null}
- steps={dialogSteps}
- onSuccess={handleTaskCreated}
+ defaultStepId={data.dialogSteps[0]?.id ?? null}
+ steps={data.dialogSteps}
+ onSuccess={actions.handleTaskCreated}
/>
{
- if (!open) setArchivingTask(null);
+ if (!open) actions.setArchivingTask(null);
}}
- taskTitle={archivingTask?.title ?? ""}
- isArchiving={isArchiving}
- onConfirm={handleArchiveConfirm}
+ taskTitle={actions.archivingTask?.title ?? ""}
+ isArchiving={actions.isArchiving}
+ onConfirm={actions.handleArchiveConfirm}
/>
);
diff --git a/apps/web/components/task/passthrough-terminal.tsx b/apps/web/components/task/passthrough-terminal.tsx
index dea953cbe1..64eef67b14 100644
--- a/apps/web/components/task/passthrough-terminal.tsx
+++ b/apps/web/components/task/passthrough-terminal.tsx
@@ -31,6 +31,23 @@ type BaseProps = {
autoFocus?: boolean;
pendingCommand?: string | null;
onCommandSent?: () => void;
+ /** Called once the xterm instance is created. Mobile uses this to register
+ * the active key-bar input target. Desktop ignores. */
+ onXtermReady?: (xterm: Terminal) => void;
+ /** Skip the WebGL renderer addon and use xterm's canvas renderer instead.
+ * WebGL miscomputes glyph atlas scaling on mobile (notably after a
+ * desktop→mobile responsive switch) and renders text at multiples of the
+ * intended font size. Mobile callers should pass true. */
+ disableWebgl?: boolean;
+ /** When true, the AttachAddon is configured receive-only — incoming PTY
+ * data still flows to the terminal display, but the consumer is responsible
+ * for forwarding xterm.onData to the WebSocket. Mobile sets this so the
+ * key-bar's modifier transforms can run before bytes go on the wire. */
+ manualInputRouting?: boolean;
+ /** Fires when the dedicated terminal WebSocket reaches the OPEN state.
+ * Mobile uses this to register a key-bar sender that writes raw bytes
+ * directly to this terminal's socket. */
+ onWsReady?: (ws: WebSocket) => void;
};
type AgentTerminalProps = BaseProps & { mode: "agent"; sessionId?: string | null; label?: string };
type ShellTerminalProps = BaseProps & {
@@ -119,7 +136,17 @@ function computeCanConnect(
// 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;
+ const {
+ mode,
+ label,
+ autoFocus,
+ pendingCommand,
+ onCommandSent,
+ onXtermReady,
+ disableWebgl,
+ manualInputRouting,
+ onWsReady,
+ } = props;
const terminalId = mode === "shell" ? props.terminalId : undefined;
const environmentId = mode === "shell" ? props.environmentId : undefined;
const refs = useTerminalRefs();
@@ -137,7 +164,10 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
const wsBaseUrl = useWsBaseUrl();
const [isTerminalReady, setIsTerminalReady] = useState(false);
- const onTerminalReady = useCallback(() => setIsTerminalReady(true), []);
+ const onTerminalReady = useCallback(() => {
+ setIsTerminalReady(true);
+ if (xtermRef.current) onXtermReady?.(xtermRef.current);
+ }, [onXtermReady, xtermRef]);
// Track which terminal target has an active WebSocket connection. The loading
// overlay resets on target switches without needing a separate setState effect.
@@ -186,6 +216,7 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
linkHandler,
fontFamily: buildTerminalFontFamily(terminalFontFamily),
fontSize: terminalFontSize ?? undefined,
+ disableWebgl,
onToggleBottomTerminal: toggleBottomTerminal,
sendInput,
keyboardShortcutsRef,
@@ -208,6 +239,8 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
wsRef,
attachAddonRef,
onConnected,
+ manualInputRouting,
+ onWsReady,
});
usePendingCommand(pendingCommand, isConnected, wsRef, onCommandSent);
diff --git a/apps/web/components/task/session-tab.tsx b/apps/web/components/task/session-tab.tsx
index b8b1be84f3..0412d78606 100644
--- a/apps/web/components/task/session-tab.tsx
+++ b/apps/web/components/task/session-tab.tsx
@@ -21,22 +21,16 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@kandev/ui/alert-dialog";
-import { useAppStore, useAppStoreApi } from "@/components/state-provider";
-import { useToast } from "@/components/toast-provider";
-import { getWebSocketClient } from "@/lib/ws/connection";
+import { useAppStore } from "@/components/state-provider";
+import {
+ useSessionActions,
+ isSessionStoppable as isStoppable,
+ isSessionDeletable as isDeletable,
+ isSessionResumable as isResumable,
+} from "@/hooks/domains/session/use-session-actions";
import type { TaskSessionState } from "@/lib/types/http";
import { useTabMaximizeOnDoubleClick } from "./use-tab-maximize";
-function isStoppable(s: TaskSessionState) {
- return s === "RUNNING" || s === "STARTING" || s === "WAITING_FOR_INPUT";
-}
-function isDeletable(s: TaskSessionState) {
- return s !== "RUNNING" && s !== "STARTING";
-}
-function isResumable(s: TaskSessionState) {
- return s === "COMPLETED" || s === "FAILED" || s === "CANCELLED";
-}
-
function useSessionTabState(sessionId: string | undefined) {
const isPrimary = useAppStore((state) => {
const activeTaskId = state.tasks.activeTaskId;
@@ -98,86 +92,20 @@ function useSessionTabActions(
api: IDockviewPanelHeaderProps["api"],
containerApi: IDockviewPanelHeaderProps["containerApi"],
) {
- const { toast, updateToast } = useToast();
- const removeTaskSession = useAppStore((state) => state.removeTaskSession);
- const appStoreApi = useAppStoreApi();
-
- const wsAction = useCallback(
- async (
- action: string,
- label: string,
- payload: Record,
- timeout = 15000,
- ): Promise => {
- const client = getWebSocketClient();
- if (!client) return false;
- const toastId = toast({ title: `${label}...`, variant: "loading" });
- try {
- await client.request(action, payload, timeout);
- updateToast(toastId, { title: `${label} successful`, variant: "success" });
- return true;
- } catch (error) {
- const msg = error instanceof Error ? error.message : "Unknown error";
- updateToast(toastId, { title: `${label} failed`, description: msg, variant: "error" });
- return false;
- }
- },
- [toast, updateToast],
- );
-
- const handleSetPrimary = useCallback(
- () => sessionId && wsAction("session.set_primary", "Set primary", { session_id: sessionId }),
- [sessionId, wsAction],
- );
- const handleStop = useCallback(
- () => sessionId && wsAction("session.stop", "Stopping session", { session_id: sessionId }),
- [sessionId, wsAction],
- );
- const handleResume = useCallback(
- () =>
- sessionId &&
- taskId &&
- wsAction(
- "session.launch",
- "Resuming session",
- { task_id: taskId, intent: "resume", session_id: sessionId },
- 30000,
- ),
- [sessionId, taskId, wsAction],
- );
- const handleDelete = useCallback(async () => {
- if (!sessionId || !taskId) return;
- // Only mutate local state once the backend confirms the delete — otherwise
- // a transient WS failure leaves the UI desynced from the server.
- const ok = await wsAction("session.delete", "Deleting session", { session_id: sessionId });
- if (!ok) return;
-
- // Switch the active session BEFORE removing from the store so
- // useAutoSessionTab doesn't re-create this panel with the deleted session's ID.
- // Hand off to the most-recently-started remaining session — store ordering
- // is unspecified, so sort explicitly rather than rely on array position.
- const state = appStoreApi.getState();
- if (state.tasks.activeSessionId === sessionId) {
- const sessions = state.taskSessionsByTask.itemsByTaskId[taskId] ?? [];
- const remaining = sessions
- .filter((s) => s.id !== sessionId)
- .sort((a, b) => new Date(b.started_at).getTime() - new Date(a.started_at).getTime());
- if (remaining.length > 0) {
- state.setActiveSessionAuto(taskId, remaining[0].id);
- } else {
- state.clearActiveSession();
- }
- }
-
- removeTaskSession(taskId, sessionId);
+ const onDeleted = useCallback(() => {
const panel = containerApi.getPanel(api.id);
if (panel) containerApi.removePanel(panel);
- }, [sessionId, taskId, wsAction, removeTaskSession, api.id, containerApi, appStoreApi]);
+ }, [api.id, containerApi]);
+ const {
+ setPrimary: handleSetPrimary,
+ stop: handleStop,
+ resume: handleResume,
+ remove: handleDelete,
+ } = useSessionActions({ sessionId, taskId, onDeleted });
const handleCloseOthers = useCallback(() => {
const toClose = api.group.panels.filter((p) => p.id !== api.id);
for (const panel of toClose) containerApi.removePanel(panel);
}, [api, containerApi]);
-
return { handleSetPrimary, handleStop, handleResume, handleDelete, handleCloseOthers };
}
diff --git a/apps/web/components/task/use-passthrough-terminal.ts b/apps/web/components/task/use-passthrough-terminal.ts
index 94dcfd1c4a..f3f13fe3ee 100644
--- a/apps/web/components/task/use-passthrough-terminal.ts
+++ b/apps/web/components/task/use-passthrough-terminal.ts
@@ -6,7 +6,7 @@ import { Unicode11Addon } from "@xterm/addon-unicode11";
import { WebLinksAddon } from "@xterm/addon-web-links";
import { WebglAddon } from "@xterm/addon-webgl";
import { getTerminalTheme } from "@/lib/theme/terminal-theme";
-import { startReconnectLoop } from "./ws-reconnect";
+import { startReconnectLoop, teardownWebSocket } from "./ws-reconnect";
import { matchesShortcut } from "@/lib/keyboard/utils";
import { SHORTCUTS } from "@/lib/keyboard/constants";
import { getShortcut, type StoredShortcutOverrides } from "@/lib/keyboard/shortcut-overrides";
@@ -134,6 +134,7 @@ function initTerminalInstance(
linkHandler?: (event: MouseEvent, uri: string) => void;
fontFamily?: string;
fontSize?: number;
+ disableWebgl?: boolean;
} & TerminalKeyHandlerOptions,
) {
if (refs.isInitializedRef.current || refs.xtermRef.current) return undefined;
@@ -168,7 +169,7 @@ function initTerminalInstance(
}
refs.xtermRef.current = terminal;
refs.fitAddonRef.current = fitAddon;
- deferWebGLAddon(refs);
+ if (!options.disableWebgl) deferWebGLAddon(refs);
exposeBufferReader(termContainer, terminal);
const handleResize = () => {
const rect = termContainer.getBoundingClientRect();
@@ -205,6 +206,7 @@ type TerminalInitHookOptions = TerminalInitOptions &
linkHandler?: (event: MouseEvent, uri: string) => void;
fontFamily?: string;
fontSize?: number;
+ disableWebgl?: boolean;
};
export function useTerminalInit({
@@ -220,6 +222,7 @@ export function useTerminalInit({
linkHandler,
fontFamily,
fontSize,
+ disableWebgl,
onToggleBottomTerminal,
sendInput,
keyboardShortcutsRef,
@@ -254,6 +257,7 @@ export function useTerminalInit({
linkHandler,
fontFamily,
fontSize,
+ disableWebgl,
onToggleBottomTerminal,
sendInput,
keyboardShortcutsRef,
@@ -324,6 +328,13 @@ export type WebSocketConnectionOptions = {
wsRef: React.MutableRefObject;
attachAddonRef: React.MutableRefObject;
onConnected: () => void;
+ /** When true, AttachAddon is created in receive-only mode so callers can
+ * intercept onData themselves (used by mobile to route input through the
+ * key-bar's modifier transform). Defaults to bidirectional. */
+ manualInputRouting?: boolean;
+ /** Fires when the WebSocket reaches the OPEN state. Use to register a sender
+ * that bypasses xterm.onData (mobile key-bar registry). */
+ onWsReady?: (ws: WebSocket) => void;
};
export function buildTerminalWsUrl(
@@ -365,6 +376,8 @@ type ConnectWebSocketOptions = {
onTimeout: (id: ReturnType) => void;
onConnected: () => void;
onSocketClose: (event: CloseEvent) => void;
+ manualInputRouting?: boolean;
+ onWsReady?: (ws: WebSocket) => void;
};
function connectWebSocket({
@@ -382,6 +395,8 @@ function connectWebSocket({
onTimeout,
onConnected,
onSocketClose,
+ manualInputRouting,
+ onWsReady,
}: ConnectWebSocketOptions) {
if (attachAddonRef.current) {
attachAddonRef.current.dispose();
@@ -413,9 +428,13 @@ function connectWebSocket({
return;
}
log("WebSocket connected");
- const attachAddon = new AttachAddon(ws, { bidirectional: true });
+ // Mobile passes manualInputRouting=true so the consumer can intercept
+ // onData and apply key-bar modifier transforms before the bytes go on the
+ // wire — AttachAddon's auto-send would otherwise bypass that path.
+ const attachAddon = new AttachAddon(ws, { bidirectional: !manualInputRouting });
terminal.loadAddon(attachAddon);
attachAddonRef.current = attachAddon;
+ onWsReady?.(ws);
onConnected();
// Send initial resize (forced) so the backend knows our terminal dimensions,
// then one deferred resize to catch layout settling + force a full redraw.
@@ -469,6 +488,8 @@ export function useWebSocketConnection({
wsRef,
attachAddonRef,
onConnected,
+ manualInputRouting,
+ onWsReady,
}: WebSocketConnectionOptions) {
const taskIdRef = useRef(taskId);
@@ -528,27 +549,11 @@ export function useWebSocketConnection({
attachAddonRef,
onConnected,
connectWebSocket,
+ manualInputRouting,
+ onWsReady,
});
- return () => {
- log("WebSocket cleanup");
- stopReconnectLoop();
- if (attachAddonRef.current) {
- attachAddonRef.current.dispose();
- attachAddonRef.current = null;
- }
- if (wsRef.current) {
- // Only close if the connection is actually open or has completed
- // opening. Closing a CONNECTING WebSocket triggers a browser warning
- // ("WebSocket is closed before the connection is established").
- if (
- wsRef.current.readyState === WebSocket.OPEN ||
- wsRef.current.readyState === WebSocket.CLOSING
- ) {
- wsRef.current.close();
- }
- wsRef.current = null;
- }
- };
+ return () => teardownWebSocket(stopReconnectLoop, attachAddonRef, wsRef);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- manualInputRouting/onWsReady should not retrigger reconnect
}, [
sessionId,
environmentId,
diff --git a/apps/web/components/task/ws-reconnect.ts b/apps/web/components/task/ws-reconnect.ts
index f223e4808c..c1ab3c543f 100644
--- a/apps/web/components/task/ws-reconnect.ts
+++ b/apps/web/components/task/ws-reconnect.ts
@@ -2,6 +2,27 @@ import { Terminal } from "@xterm/xterm";
import { AttachAddon } from "@xterm/addon-attach";
import { log } from "./use-passthrough-terminal";
+export function teardownWebSocket(
+ stopReconnectLoop: () => void,
+ attachAddonRef: React.MutableRefObject,
+ wsRef: React.MutableRefObject,
+): void {
+ log("WebSocket cleanup");
+ stopReconnectLoop();
+ if (attachAddonRef.current) {
+ attachAddonRef.current.dispose();
+ attachAddonRef.current = null;
+ }
+ // Only close if the connection is actually open or has completed opening.
+ // Closing a CONNECTING WebSocket triggers a browser warning ("WebSocket is
+ // closed before the connection is established").
+ const ws = wsRef.current;
+ if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CLOSING)) {
+ ws.close();
+ }
+ wsRef.current = null;
+}
+
const STABLE_CONNECTION_MS = 500;
export function reconnectDelayMs(attempt: number): number {
@@ -24,6 +45,8 @@ type ConnectWebSocketFn = (opts: {
onTimeout: (id: ReturnType) => void;
onConnected: () => void;
onSocketClose: (event: CloseEvent) => void;
+ manualInputRouting?: boolean;
+ onWsReady?: (ws: WebSocket) => void;
}) => void;
export type ReconnectLoopOptions = {
@@ -39,6 +62,8 @@ export type ReconnectLoopOptions = {
attachAddonRef: React.MutableRefObject;
onConnected: () => void;
connectWebSocket: ConnectWebSocketFn;
+ manualInputRouting?: boolean;
+ onWsReady?: (ws: WebSocket) => void;
};
export function startReconnectLoop({
@@ -54,6 +79,8 @@ export function startReconnectLoop({
attachAddonRef,
onConnected,
connectWebSocket,
+ manualInputRouting,
+ onWsReady,
}: ReconnectLoopOptions): () => void {
let isMounted = true;
let connectTimeout: ReturnType | null = null;
@@ -77,6 +104,8 @@ export function startReconnectLoop({
fitAndResize,
wsRef,
attachAddonRef,
+ manualInputRouting,
+ onWsReady,
isMountedCheck: () => isMounted,
onTimeout: (id) => {
settleTimeout = id;
diff --git a/apps/web/e2e/helpers/ws-capture.ts b/apps/web/e2e/helpers/ws-capture.ts
index 181fcad61d..86557d61b3 100644
--- a/apps/web/e2e/helpers/ws-capture.ts
+++ b/apps/web/e2e/helpers/ws-capture.ts
@@ -12,10 +12,48 @@ type ParsedFrame = {
};
/**
- * Subscribe to outgoing WS frames on the given page and collect every
- * `shell.input` request with its `{ session_id, data }` payload. Useful for
- * asserting that UI actions translate to the correct escape sequences without
- * depending on xterm paint timing.
+ * PassthroughTerminal's resize frames start with a 0x01 tag byte followed by
+ * a JSON `{cols, rows}` body. A naive "first byte === 0x01" check would
+ * misclassify Ctrl+A (also 0x01) as a resize, so confirm the JSON shape
+ * before discarding.
+ */
+const RESIZE_FRAME_TAG = 0x01;
+
+function isResizeFrame(payload: Buffer | Uint8Array): boolean {
+ if (payload.length < 2 || payload[0] !== RESIZE_FRAME_TAG) return false;
+ try {
+ const tail = new TextDecoder("utf-8", { fatal: false }).decode(
+ (payload as Uint8Array).slice(1),
+ );
+ const parsed = JSON.parse(tail) as { cols?: unknown; rows?: unknown };
+ return typeof parsed?.cols === "number" && typeof parsed?.rows === "number";
+ } catch {
+ return false;
+ }
+}
+
+function decodeBinaryFrame(payload: Buffer | Uint8Array): string | null {
+ if (!payload || payload.length === 0) return null;
+ if (isResizeFrame(payload)) return null;
+ try {
+ return new TextDecoder("utf-8", { fatal: false }).decode(payload as Uint8Array);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Subscribe to outgoing WS frames on the given page and collect every shell
+ * input frame, regardless of which transport carried it:
+ *
+ * - JSON `{action: "shell.input", payload: {session_id, data}}` over the
+ * kandev gateway WS — the per-session default shell.
+ * - Raw binary frames over a PassthroughTerminal's dedicated WS — used by
+ * mobile multi-terminal where the on-screen terminal owns its own
+ * AttachAddon connection. The session ID is unknown for these frames
+ * (the WS is env+terminalId scoped) so an empty string is reported.
+ *
+ * Tests assert on the `data` field, which works the same either way.
*
* Returns a live array that tests can poll via `expect.poll`. Must be called
* before the page navigates, since `framesent` events fire before your next
@@ -25,20 +63,24 @@ export function attachShellInputCapture(page: Page): { frames: ShellInputFrame[]
const frames: ShellInputFrame[] = [];
page.on("websocket", (ws) => {
ws.on("framesent", (event) => {
- const raw =
- typeof event.payload === "string" ? event.payload : (event.payload?.toString("utf8") ?? "");
- if (!raw || !raw.includes('"shell.input"')) return;
- try {
- const msg = JSON.parse(raw) as ParsedFrame;
- if (msg.action !== "shell.input") return;
- const sessionId = msg.payload?.session_id;
- const data = msg.payload?.data;
- if (typeof sessionId === "string" && typeof data === "string") {
- frames.push({ sessionId, data });
+ const payload = event.payload;
+ if (typeof payload === "string") {
+ if (!payload.includes('"shell.input"')) return;
+ try {
+ const msg = JSON.parse(payload) as ParsedFrame;
+ if (msg.action !== "shell.input") return;
+ const sessionId = msg.payload?.session_id;
+ const data = msg.payload?.data;
+ if (typeof sessionId === "string" && typeof data === "string") {
+ frames.push({ sessionId, data });
+ }
+ } catch {
+ /* non-JSON string frames — ignore */
}
- } catch {
- /* non-JSON frames (binary, etc.) — ignore */
+ return;
}
+ const decoded = decodeBinaryFrame(payload);
+ if (decoded) frames.push({ sessionId: "", data: decoded });
});
});
return { frames };
diff --git a/apps/web/hooks/domains/session/use-mobile-terminals.test.ts b/apps/web/hooks/domains/session/use-mobile-terminals.test.ts
new file mode 100644
index 0000000000..0ea08214e0
--- /dev/null
+++ b/apps/web/hooks/domains/session/use-mobile-terminals.test.ts
@@ -0,0 +1,98 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { renderHook, act, waitFor } from "@testing-library/react";
+import { useMobileTerminals, __resetAutoCreatedEnvironmentsForTest } from "./use-mobile-terminals";
+
+const SESSION_ID = "sess-1";
+
+const addTerminalMock = vi.fn();
+let mockEnvironmentId: string | null = null;
+let mockShells: Array<{ terminalId: string; label: string; closable: boolean }> = [];
+let mockShellsLoaded = false;
+
+vi.mock("@/components/state-provider", () => ({
+ useAppStore: (selector: (state: Record) => unknown) =>
+ selector({
+ environmentIdBySessionId: mockEnvironmentId ? { [SESSION_ID]: mockEnvironmentId } : {},
+ }),
+}));
+
+vi.mock("./use-terminals", () => ({
+ useTerminals: () => ({
+ terminals: [],
+ activeTab: undefined,
+ terminalTabValue: "commands",
+ addTerminal: addTerminalMock,
+ removeTerminal: vi.fn(),
+ handleCloseDevTab: vi.fn(),
+ handleCloseTab: vi.fn(),
+ handleRunCommand: vi.fn(),
+ isStoppingDev: false,
+ devProcessId: undefined,
+ devOutput: "",
+ }),
+}));
+
+vi.mock("./use-user-shells", () => ({
+ useUserShells: () => ({
+ shells: mockShells,
+ isLoading: false,
+ isLoaded: mockShellsLoaded,
+ addShell: vi.fn(),
+ removeShell: vi.fn(),
+ }),
+}));
+
+beforeEach(() => {
+ addTerminalMock.mockReset();
+ __resetAutoCreatedEnvironmentsForTest();
+ mockEnvironmentId = "env-A";
+ mockShells = [];
+ mockShellsLoaded = true;
+});
+
+describe("useMobileTerminals auto-create", () => {
+ it("creates a first shell when shells loaded but list is empty", async () => {
+ addTerminalMock.mockResolvedValue(undefined);
+ renderHook(() => useMobileTerminals(SESSION_ID));
+ await waitFor(() => expect(addTerminalMock).toHaveBeenCalledTimes(1));
+ });
+
+ it("does not create a shell when one already exists", async () => {
+ mockShells = [{ terminalId: "shell-1", label: "Terminal", closable: true }];
+ renderHook(() => useMobileTerminals(SESSION_ID));
+ // Wait a tick so any effects had a chance to fire.
+ await new Promise((r) => setTimeout(r, 0));
+ expect(addTerminalMock).not.toHaveBeenCalled();
+ });
+
+ it("does not create when shells are still loading", async () => {
+ mockShellsLoaded = false;
+ renderHook(() => useMobileTerminals(SESSION_ID));
+ await new Promise((r) => setTimeout(r, 0));
+ expect(addTerminalMock).not.toHaveBeenCalled();
+ });
+
+ it("multiple instances for the same env trigger only one creation (module-level guard)", async () => {
+ addTerminalMock.mockResolvedValue(undefined);
+ renderHook(() => useMobileTerminals(SESSION_ID));
+ renderHook(() => useMobileTerminals(SESSION_ID));
+ renderHook(() => useMobileTerminals(SESSION_ID));
+ await waitFor(() => expect(addTerminalMock).toHaveBeenCalledTimes(1));
+ });
+
+ it("clears the guard when addTerminal rejects so a fresh hook retries", async () => {
+ addTerminalMock.mockRejectedValueOnce(new Error("network down"));
+ const first = renderHook(() => useMobileTerminals(SESSION_ID));
+ await waitFor(() => expect(addTerminalMock).toHaveBeenCalledTimes(1));
+ // Let the rejection settle so the .catch handler clears the guard.
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ first.unmount();
+ // A new instance for the same env should now retry creation.
+ addTerminalMock.mockResolvedValueOnce(undefined);
+ renderHook(() => useMobileTerminals(SESSION_ID));
+ await waitFor(() => expect(addTerminalMock).toHaveBeenCalledTimes(2));
+ });
+});
diff --git a/apps/web/hooks/domains/session/use-mobile-terminals.ts b/apps/web/hooks/domains/session/use-mobile-terminals.ts
new file mode 100644
index 0000000000..2995214ad1
--- /dev/null
+++ b/apps/web/hooks/domains/session/use-mobile-terminals.ts
@@ -0,0 +1,73 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { useTerminals } from "./use-terminals";
+import { useUserShells } from "./use-user-shells";
+import { useAppStore } from "@/components/state-provider";
+
+/**
+ * Module-level guard for the auto-create-first-shell effect, keyed by
+ * environmentId. `useMobileTerminals` is called from several places that all
+ * end up rendering the same terminal pane (the pane itself, the picker pill,
+ * the picker sheet content) — a per-instance ref guard would let each one
+ * fire `createUserShell` on first mount, racing into multiple shells. The
+ * Set is shared across instances so only the first effect to run for a given
+ * environment triggers creation.
+ */
+const autoCreatedEnvironments = new Set();
+
+/**
+ * Release the auto-create guard for a specific environment so the next mount
+ * (or shell-list change) re-runs the auto-create effect. Call this when the
+ * user explicitly closes the last terminal in an env — otherwise the pane
+ * shows "Starting terminal…" forever because the guard prevents recreation.
+ */
+export function releaseAutoCreatedEnvironment(environmentId: string): void {
+ autoCreatedEnvironments.delete(environmentId);
+}
+
+/** Test-only: reset the module-level guard so each test starts from scratch. */
+export function __resetAutoCreatedEnvironmentsForTest(): void {
+ autoCreatedEnvironments.clear();
+}
+
+/**
+ * Mobile wrapper around `useTerminals`. Auto-creates a first shell when the
+ * server-side shell list loads empty so the user always sees one terminal
+ * mounted by default. Returns the same interface as `useTerminals`.
+ */
+export function useMobileTerminals(sessionId: string | null) {
+ const environmentId = useAppStore((s) =>
+ sessionId ? (s.environmentIdBySessionId[sessionId] ?? null) : null,
+ );
+ const result = useTerminals({ sessionId, environmentId });
+ // Read user-shell loaded flag directly so the auto-create trigger has
+ // primitive dependencies — depending on `result` would re-run on every
+ // render and would also race against React's effect ordering.
+ const { isLoaded: shellsLoaded, shells } = useUserShells(environmentId);
+ const addTerminalRef = useRef(result.addTerminal);
+ useEffect(() => {
+ addTerminalRef.current = result.addTerminal;
+ }, [result.addTerminal]);
+
+ useEffect(() => {
+ if (!environmentId || !shellsLoaded) return;
+ if (autoCreatedEnvironments.has(environmentId)) return;
+ if (shells.length > 0) {
+ autoCreatedEnvironments.add(environmentId);
+ return;
+ }
+ autoCreatedEnvironments.add(environmentId);
+ // Reset the guard if creation fails so the user gets a retry on the next
+ // render cycle (e.g. after the WS reconnects). `addTerminal` returns void
+ // but its inner promise can still reject; guard defensively.
+ const promise = addTerminalRef.current() as unknown;
+ if (promise && typeof (promise as Promise).catch === "function") {
+ (promise as Promise).catch(() => {
+ autoCreatedEnvironments.delete(environmentId);
+ });
+ }
+ }, [environmentId, shellsLoaded, shells.length]);
+
+ return { ...result, environmentId };
+}
diff --git a/apps/web/hooks/domains/session/use-session-actions.test.ts b/apps/web/hooks/domains/session/use-session-actions.test.ts
new file mode 100644
index 0000000000..48a037a62e
--- /dev/null
+++ b/apps/web/hooks/domains/session/use-session-actions.test.ts
@@ -0,0 +1,163 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { renderHook, waitFor } from "@testing-library/react";
+import {
+ isSessionStoppable,
+ isSessionDeletable,
+ isSessionResumable,
+ useSessionActions,
+} from "./use-session-actions";
+
+const mockToast = vi.fn().mockReturnValue("toast-1");
+const mockUpdateToast = vi.fn();
+const mockRequest = vi.fn();
+const mockRemoveTaskSession = vi.fn();
+const mockSetActiveSessionAuto = vi.fn();
+const mockClearActiveSession = vi.fn();
+
+let mockState: Record = {};
+
+vi.mock("@/components/toast-provider", () => ({
+ useToast: () => ({ toast: mockToast, updateToast: mockUpdateToast }),
+}));
+
+vi.mock("@/lib/ws/connection", () => ({
+ getWebSocketClient: () => ({ request: mockRequest }),
+}));
+
+vi.mock("@/components/state-provider", () => ({
+ useAppStore: (selector: (state: Record) => unknown) =>
+ selector({
+ removeTaskSession: mockRemoveTaskSession,
+ }),
+ useAppStoreApi: () => ({
+ getState: () => mockState,
+ }),
+}));
+
+describe("session state predicates", () => {
+ it("isSessionStoppable returns true for active states", () => {
+ expect(isSessionStoppable("RUNNING")).toBe(true);
+ expect(isSessionStoppable("STARTING")).toBe(true);
+ expect(isSessionStoppable("WAITING_FOR_INPUT")).toBe(true);
+ expect(isSessionStoppable("COMPLETED")).toBe(false);
+ expect(isSessionStoppable("FAILED")).toBe(false);
+ });
+
+ it("isSessionDeletable returns false for in-flight states", () => {
+ expect(isSessionDeletable("RUNNING")).toBe(false);
+ expect(isSessionDeletable("STARTING")).toBe(false);
+ expect(isSessionDeletable("WAITING_FOR_INPUT")).toBe(true);
+ expect(isSessionDeletable("COMPLETED")).toBe(true);
+ expect(isSessionDeletable("FAILED")).toBe(true);
+ });
+
+ it("isSessionResumable returns true for terminal states", () => {
+ expect(isSessionResumable("COMPLETED")).toBe(true);
+ expect(isSessionResumable("FAILED")).toBe(true);
+ expect(isSessionResumable("CANCELLED")).toBe(true);
+ expect(isSessionResumable("RUNNING")).toBe(false);
+ expect(isSessionResumable("STARTING")).toBe(false);
+ });
+});
+
+describe("useSessionActions", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockToast.mockReturnValue("toast-1");
+ mockRequest.mockResolvedValue(undefined);
+ mockState = {
+ tasks: { activeSessionId: null },
+ taskSessionsByTask: { itemsByTaskId: {} },
+ setActiveSessionAuto: mockSetActiveSessionAuto,
+ clearActiveSession: mockClearActiveSession,
+ };
+ });
+
+ it("setPrimary dispatches session.set_primary with session id", async () => {
+ const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" }));
+ await result.current.setPrimary();
+ expect(mockRequest).toHaveBeenCalledWith("session.set_primary", { session_id: "s1" }, 15000);
+ });
+
+ it("stop dispatches session.stop", async () => {
+ const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" }));
+ await result.current.stop();
+ expect(mockRequest).toHaveBeenCalledWith("session.stop", { session_id: "s1" }, 15000);
+ });
+
+ it("resume dispatches session.launch with intent=resume and 30s timeout", async () => {
+ const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" }));
+ await result.current.resume();
+ expect(mockRequest).toHaveBeenCalledWith(
+ "session.launch",
+ { task_id: "t1", intent: "resume", session_id: "s1" },
+ 30000,
+ );
+ });
+
+ it("remove deletes via WS, removes from store, and runs onDeleted callback", async () => {
+ const onDeleted = vi.fn();
+ const { result } = renderHook(() =>
+ useSessionActions({ sessionId: "s1", taskId: "t1", onDeleted }),
+ );
+ await result.current.remove();
+ await waitFor(() => expect(onDeleted).toHaveBeenCalled());
+ expect(mockRequest).toHaveBeenCalledWith("session.delete", { session_id: "s1" }, 15000);
+ expect(mockRemoveTaskSession).toHaveBeenCalledWith("t1", "s1");
+ });
+
+ it("remove no-ops when WS request fails (store untouched)", async () => {
+ mockRequest.mockRejectedValueOnce(new Error("network down"));
+ const onDeleted = vi.fn();
+ const { result } = renderHook(() =>
+ useSessionActions({ sessionId: "s1", taskId: "t1", onDeleted }),
+ );
+ await result.current.remove();
+ expect(mockRemoveTaskSession).not.toHaveBeenCalled();
+ expect(onDeleted).not.toHaveBeenCalled();
+ });
+
+ it("remove hands off to most-recent remaining session when active was deleted", async () => {
+ mockState = {
+ tasks: { activeSessionId: "s1" },
+ taskSessionsByTask: {
+ itemsByTaskId: {
+ t1: [
+ { id: "s1", started_at: "2025-01-01T00:00:00Z" },
+ { id: "s2", started_at: "2025-01-02T00:00:00Z" },
+ { id: "s3", started_at: "2025-01-03T00:00:00Z" },
+ ],
+ },
+ },
+ setActiveSessionAuto: mockSetActiveSessionAuto,
+ clearActiveSession: mockClearActiveSession,
+ };
+ const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" }));
+ await result.current.remove();
+ expect(mockSetActiveSessionAuto).toHaveBeenCalledWith("t1", "s3");
+ expect(mockClearActiveSession).not.toHaveBeenCalled();
+ });
+
+ it("remove clears active session when no other sessions remain", async () => {
+ mockState = {
+ tasks: { activeSessionId: "s1" },
+ taskSessionsByTask: {
+ itemsByTaskId: { t1: [{ id: "s1", started_at: "2025-01-01T00:00:00Z" }] },
+ },
+ setActiveSessionAuto: mockSetActiveSessionAuto,
+ clearActiveSession: mockClearActiveSession,
+ };
+ const { result } = renderHook(() => useSessionActions({ sessionId: "s1", taskId: "t1" }));
+ await result.current.remove();
+ expect(mockClearActiveSession).toHaveBeenCalled();
+ expect(mockSetActiveSessionAuto).not.toHaveBeenCalled();
+ });
+
+ it("actions no-op when sessionId is missing", async () => {
+ const { result } = renderHook(() => useSessionActions({ sessionId: null, taskId: "t1" }));
+ await result.current.setPrimary();
+ await result.current.stop();
+ await result.current.remove();
+ expect(mockRequest).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/hooks/domains/session/use-session-actions.ts b/apps/web/hooks/domains/session/use-session-actions.ts
new file mode 100644
index 0000000000..1124af35e8
--- /dev/null
+++ b/apps/web/hooks/domains/session/use-session-actions.ts
@@ -0,0 +1,112 @@
+"use client";
+
+import { useCallback } from "react";
+import { useAppStore, useAppStoreApi } from "@/components/state-provider";
+import { useToast } from "@/components/toast-provider";
+import { getWebSocketClient } from "@/lib/ws/connection";
+import type { TaskSessionState } from "@/lib/types/http";
+
+export function isSessionStoppable(s: TaskSessionState): boolean {
+ return s === "RUNNING" || s === "STARTING" || s === "WAITING_FOR_INPUT";
+}
+export function isSessionDeletable(s: TaskSessionState): boolean {
+ return s !== "RUNNING" && s !== "STARTING";
+}
+export function isSessionResumable(s: TaskSessionState): boolean {
+ return s === "COMPLETED" || s === "FAILED" || s === "CANCELLED";
+}
+
+type SessionActionsArgs = {
+ sessionId: string | null | undefined;
+ taskId: string | null;
+ /** Optional callback after a successful delete (e.g. close a tab/panel). */
+ onDeleted?: () => void;
+};
+
+type WsActionFn = (
+ action: string,
+ label: string,
+ payload: Record,
+ timeout?: number,
+) => Promise;
+
+function useWsAction(): WsActionFn {
+ const { toast, updateToast } = useToast();
+ return useCallback(
+ async (action, label, payload, timeout = 15000) => {
+ const client = getWebSocketClient();
+ if (!client) return false;
+ const toastId = toast({ title: `${label}...`, variant: "loading" });
+ try {
+ await client.request(action, payload, timeout);
+ updateToast(toastId, { title: `${label} successful`, variant: "success" });
+ return true;
+ } catch (error) {
+ const msg = error instanceof Error ? error.message : "Unknown error";
+ updateToast(toastId, { title: `${label} failed`, description: msg, variant: "error" });
+ return false;
+ }
+ },
+ [toast, updateToast],
+ );
+}
+
+/**
+ * Shared lifecycle actions for a session (set-primary, stop, resume, delete).
+ * Handles backend coordination + local store cleanup. Caller can pass
+ * `onDeleted` to perform UI-specific teardown (e.g. dockview panel removal).
+ */
+export function useSessionActions({ sessionId, taskId, onDeleted }: SessionActionsArgs) {
+ const wsAction = useWsAction();
+ const removeTaskSession = useAppStore((state) => state.removeTaskSession);
+ const appStoreApi = useAppStoreApi();
+
+ const setPrimary = useCallback(
+ () => sessionId && wsAction("session.set_primary", "Set primary", { session_id: sessionId }),
+ [sessionId, wsAction],
+ );
+
+ const stop = useCallback(
+ () => sessionId && wsAction("session.stop", "Stopping session", { session_id: sessionId }),
+ [sessionId, wsAction],
+ );
+
+ const resume = useCallback(
+ () =>
+ sessionId &&
+ taskId &&
+ wsAction(
+ "session.launch",
+ "Resuming session",
+ { task_id: taskId, intent: "resume", session_id: sessionId },
+ 30000,
+ ),
+ [sessionId, taskId, wsAction],
+ );
+
+ const remove = useCallback(async () => {
+ if (!sessionId || !taskId) return;
+ const ok = await wsAction("session.delete", "Deleting session", { session_id: sessionId });
+ if (!ok) return;
+
+ // Switch the active session BEFORE removing from the store so callers
+ // observing activeSessionId don't briefly point at a deleted session.
+ const state = appStoreApi.getState();
+ if (state.tasks.activeSessionId === sessionId) {
+ const sessions = state.taskSessionsByTask.itemsByTaskId[taskId] ?? [];
+ const remaining = sessions
+ .filter((s) => s.id !== sessionId)
+ .sort((a, b) => new Date(b.started_at).getTime() - new Date(a.started_at).getTime());
+ if (remaining.length > 0) {
+ state.setActiveSessionAuto(taskId, remaining[0].id);
+ } else {
+ state.clearActiveSession();
+ }
+ }
+
+ removeTaskSession(taskId, sessionId);
+ onDeleted?.();
+ }, [sessionId, taskId, wsAction, removeTaskSession, appStoreApi, onDeleted]);
+
+ return { setPrimary, stop, resume, remove };
+}
diff --git a/apps/web/lib/state/store.ts b/apps/web/lib/state/store.ts
index f697e22b12..b87867ce0f 100644
--- a/apps/web/lib/state/store.ts
+++ b/apps/web/lib/state/store.ts
@@ -20,6 +20,7 @@ import type {
} from "@/lib/types/github";
import type { SystemHealthResponse } from "@/lib/types/health";
import type { UISliceActions as UIA } from "./slices/ui/types";
+import type * as UISliceTypes from "./slices/ui/types";
import { mergeInitialState } from "./default-state";
import {
createKanbanSlice,
@@ -361,16 +362,10 @@ export type AppState = {
setConnectionStatus: (status: ConnectionState["status"], error?: string | null) => void;
setMobileKanbanColumnIndex: (index: number) => void;
setMobileKanbanMenuOpen: (open: boolean) => void;
- setMobileSessionPanel: (
- sessionId: string,
- panel: import("./slices/ui/types").MobileSessionPanel,
- ) => void;
+ setMobileSessionPanel: (sessionId: string, panel: UISliceTypes.MobileSessionPanel) => void;
setMobileSessionTaskSwitcherOpen: (open: boolean) => void;
setPlanMode: (sessionId: string, enabled: boolean) => void;
- setActiveDocument: (
- sessionId: string,
- doc: import("./slices/ui/types").ActiveDocument | null,
- ) => void;
+ setActiveDocument: (sessionId: string, doc: UISliceTypes.ActiveDocument | null) => void;
setSystemHealth: (response: SystemHealthResponse) => void;
setSystemHealthLoading: (loading: boolean) => void;
invalidateSystemHealth: () => void;
@@ -385,9 +380,7 @@ export type AppState = {
closeConfigChatSession: (sessionId: string) => void;
setActiveConfigChatSession: (sessionId: string) => void;
renameConfigChatSession: (sessionId: string, name: string) => void;
- setSessionFailureNotification: (
- n: import("./slices/ui/types").SessionFailureNotification | null,
- ) => void;
+ setSessionFailureNotification: (n: UISliceTypes.SessionFailureNotification | null) => void;
toggleBottomTerminal: () => void;
openBottomTerminalWithCommand: (command: string) => void;
clearBottomTerminalCommand: () => void;
diff --git a/apps/web/lib/terminal/mobile-active-terminal.test.ts b/apps/web/lib/terminal/mobile-active-terminal.test.ts
new file mode 100644
index 0000000000..4f9a6fa4eb
--- /dev/null
+++ b/apps/web/lib/terminal/mobile-active-terminal.test.ts
@@ -0,0 +1,34 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { setActiveTerminalSender, getActiveTerminalSender } from "./mobile-active-terminal";
+
+describe("mobile active terminal sender registry", () => {
+ beforeEach(() => {
+ setActiveTerminalSender(null);
+ });
+
+ it("returns null when no sender is registered", () => {
+ expect(getActiveTerminalSender()).toBeNull();
+ });
+
+ it("returns the registered sender", () => {
+ const sender = vi.fn();
+ setActiveTerminalSender(sender);
+ expect(getActiveTerminalSender()).toBe(sender);
+ sender("hi");
+ expect(sender).toHaveBeenCalledWith("hi");
+ });
+
+ it("replaces a previously registered sender", () => {
+ const a = vi.fn();
+ const b = vi.fn();
+ setActiveTerminalSender(a);
+ setActiveTerminalSender(b);
+ expect(getActiveTerminalSender()).toBe(b);
+ });
+
+ it("clears the sender when null is set", () => {
+ setActiveTerminalSender(vi.fn());
+ setActiveTerminalSender(null);
+ expect(getActiveTerminalSender()).toBeNull();
+ });
+});
diff --git a/apps/web/lib/terminal/mobile-active-terminal.ts b/apps/web/lib/terminal/mobile-active-terminal.ts
new file mode 100644
index 0000000000..24ce45b0c0
--- /dev/null
+++ b/apps/web/lib/terminal/mobile-active-terminal.ts
@@ -0,0 +1,21 @@
+/**
+ * Tracks the current input target for the mobile terminal key-bar.
+ *
+ * Mobile renders multiple terminals via PassthroughTerminal, each with its own
+ * WebSocket. The shared key-bar (Ctrl, ^C, arrow keys, etc.) needs to dispatch
+ * keystrokes to whichever terminal is on screen, not the per-session default
+ * shell. The active terminal registers a `paste` sender on mount; the key-bar
+ * reads from this registry and falls back to the default shell otherwise.
+ */
+
+type Sender = (data: string) => void;
+
+let activeSender: Sender | null = null;
+
+export function setActiveTerminalSender(sender: Sender | null): void {
+ activeSender = sender;
+}
+
+export function getActiveTerminalSender(): Sender | null {
+ return activeSender;
+}
diff --git a/apps/web/lib/terminal/send-shell-input.test.ts b/apps/web/lib/terminal/send-shell-input.test.ts
index 8009ee8eea..02f921fbdc 100644
--- a/apps/web/lib/terminal/send-shell-input.test.ts
+++ b/apps/web/lib/terminal/send-shell-input.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { useShellModifiersStore } from "./shell-modifiers";
+import { setActiveTerminalSender } from "./mobile-active-terminal";
const sendMock = vi.fn();
let clientFactory: () => { send: typeof sendMock } | null = () => ({ send: sendMock });
@@ -17,6 +18,7 @@ beforeEach(() => {
sendMock.mockReset();
clientFactory = () => ({ send: sendMock });
useShellModifiersStore.getState().reset();
+ setActiveTerminalSender(null);
});
function lastFrameData(): string | undefined {
@@ -77,4 +79,37 @@ describe("sendShellInput", () => {
expect(sendMock).not.toHaveBeenCalled();
expect(useShellModifiersStore.getState().ctrl).toEqual({ latched: true, sticky: false });
});
+
+ describe("with an active mobile terminal sender registered", () => {
+ it("routes input through the active sender and bypasses WS", () => {
+ const sender = vi.fn();
+ setActiveTerminalSender(sender);
+ sendShellInput(SESSION, "ls");
+ expect(sender).toHaveBeenCalledWith("ls");
+ expect(sendMock).not.toHaveBeenCalled();
+ });
+
+ it("applies modifiers and consumes them after a successful sender call", () => {
+ const sender = vi.fn();
+ setActiveTerminalSender(sender);
+ useShellModifiersStore.getState().toggleCtrl();
+ sendShellInput(SESSION, "c");
+ expect(sender).toHaveBeenCalledWith("\x03");
+ expect(useShellModifiersStore.getState().ctrl).toEqual({ latched: false, sticky: false });
+ });
+
+ it("falls back to WS when the sender throws", () => {
+ const sender = vi.fn(() => {
+ throw new Error("xterm gone");
+ });
+ setActiveTerminalSender(sender);
+ sendShellInput(SESSION, "ls");
+ expect(sender).toHaveBeenCalledWith("ls");
+ expect(sendMock).toHaveBeenCalledWith({
+ type: "request",
+ action: "shell.input",
+ payload: { session_id: SESSION, data: "ls" },
+ });
+ });
+ });
});
diff --git a/apps/web/lib/terminal/send-shell-input.ts b/apps/web/lib/terminal/send-shell-input.ts
index 0531398409..9e6c75c36f 100644
--- a/apps/web/lib/terminal/send-shell-input.ts
+++ b/apps/web/lib/terminal/send-shell-input.ts
@@ -1,5 +1,6 @@
import { getWebSocketClient } from "@/lib/ws/connection";
import { applyShellModifiers } from "./apply-shell-modifiers";
+import { getActiveTerminalSender } from "./mobile-active-terminal";
import { useShellModifiersStore, isActive } from "./shell-modifiers";
/**
@@ -9,20 +10,46 @@ import { useShellModifiersStore, isActive } from "./shell-modifiers";
* Used by both the virtual key-bar and xterm's own `onData` callback so that
* a Ctrl latch set from the key-bar modifies the next character the user
* types on the OS keyboard — which is the whole point of the modifier.
+ *
+ * Mobile multi-terminal: when a PassthroughTerminal is registered as the
+ * active key-bar target, route input through it (xterm.paste → onData → its
+ * dedicated WS) instead of the per-session default shell. Falls back to the
+ * default `shell.input` action when no active terminal is registered.
*/
export function sendShellInput(sessionId: string, data: string): void {
if (!data) return;
- const client = getWebSocketClient();
- if (!client) return; // keep modifiers armed; the user can retry once reconnected
const store = useShellModifiersStore.getState();
const ctrlActive = isActive(store.ctrl);
const shiftActive = isActive(store.shift);
const transformed = applyShellModifiers(data, { ctrl: ctrlActive, shift: shiftActive });
- client.send({
- type: "request",
- action: "shell.input",
- payload: { session_id: sessionId, data: transformed },
- });
+
+ const activeSender = getActiveTerminalSender();
+ if (activeSender) {
+ try {
+ activeSender(transformed);
+ } catch (err) {
+ // A stale registry entry (e.g. xterm disposed mid-frame) shouldn't
+ // silently drop the keystroke nor consume modifiers. Fall through to
+ // the WS path so the input still has a chance of landing.
+ console.error("Active terminal sender threw, falling back to shell.input:", err);
+ const client = getWebSocketClient();
+ if (!client) return;
+ client.send({
+ type: "request",
+ action: "shell.input",
+ payload: { session_id: sessionId, data: transformed },
+ });
+ }
+ } else {
+ const client = getWebSocketClient();
+ if (!client) return; // keep modifiers armed; user can retry once reconnected
+ client.send({
+ type: "request",
+ action: "shell.input",
+ payload: { session_id: sessionId, data: transformed },
+ });
+ }
+
if (ctrlActive) store.consumeCtrl();
if (shiftActive) store.consumeShift();
}
diff --git a/apps/web/lib/ui/state-labels.test.ts b/apps/web/lib/ui/state-labels.test.ts
new file mode 100644
index 0000000000..503b30824a
--- /dev/null
+++ b/apps/web/lib/ui/state-labels.test.ts
@@ -0,0 +1,48 @@
+import { describe, it, expect } from "vitest";
+import { formatTaskStateLabel, formatTaskSessionStateLabel } from "./state-labels";
+import type { TaskState, TaskSessionState } from "@/lib/types/http";
+
+describe("formatTaskStateLabel", () => {
+ it("maps known task states to human labels", () => {
+ expect(formatTaskStateLabel("IN_PROGRESS")).toBe("In progress");
+ expect(formatTaskStateLabel("WAITING_FOR_INPUT")).toBe("Waiting for input");
+ expect(formatTaskStateLabel("TODO")).toBe("To do");
+ expect(formatTaskStateLabel("COMPLETED")).toBe("Completed");
+ expect(formatTaskStateLabel("FAILED")).toBe("Failed");
+ expect(formatTaskStateLabel("CANCELLED")).toBe("Cancelled");
+ expect(formatTaskStateLabel("BLOCKED")).toBe("Blocked");
+ expect(formatTaskStateLabel("REVIEW")).toBe("Review");
+ expect(formatTaskStateLabel("CREATED")).toBe("Created");
+ expect(formatTaskStateLabel("SCHEDULING")).toBe("Scheduling");
+ });
+
+ it("returns 'Not started' for null/undefined", () => {
+ expect(formatTaskStateLabel(null)).toBe("Not started");
+ expect(formatTaskStateLabel(undefined)).toBe("Not started");
+ });
+
+ it("falls back to the raw value for unknown states", () => {
+ expect(formatTaskStateLabel("UNKNOWN_FUTURE" as TaskState)).toBe("UNKNOWN_FUTURE");
+ });
+});
+
+describe("formatTaskSessionStateLabel", () => {
+ it("maps known session states", () => {
+ expect(formatTaskSessionStateLabel("RUNNING")).toBe("Running");
+ expect(formatTaskSessionStateLabel("STARTING")).toBe("Starting");
+ expect(formatTaskSessionStateLabel("WAITING_FOR_INPUT")).toBe("Waiting for input");
+ expect(formatTaskSessionStateLabel("COMPLETED")).toBe("Completed");
+ expect(formatTaskSessionStateLabel("FAILED")).toBe("Failed");
+ expect(formatTaskSessionStateLabel("CANCELLED")).toBe("Cancelled");
+ expect(formatTaskSessionStateLabel("CREATED")).toBe("Created");
+ });
+
+ it("returns empty string for null/undefined", () => {
+ expect(formatTaskSessionStateLabel(null)).toBe("");
+ expect(formatTaskSessionStateLabel(undefined)).toBe("");
+ });
+
+ it("falls back to the raw value for unknown states", () => {
+ expect(formatTaskSessionStateLabel("UNKNOWN" as TaskSessionState)).toBe("UNKNOWN");
+ });
+});
diff --git a/apps/web/lib/ui/state-labels.ts b/apps/web/lib/ui/state-labels.ts
new file mode 100644
index 0000000000..8eb5e457f2
--- /dev/null
+++ b/apps/web/lib/ui/state-labels.ts
@@ -0,0 +1,34 @@
+import type { TaskState, TaskSessionState } from "@/lib/types/http";
+
+const TASK_STATE_LABELS: Record = {
+ CREATED: "Created",
+ SCHEDULING: "Scheduling",
+ TODO: "To do",
+ IN_PROGRESS: "In progress",
+ REVIEW: "Review",
+ BLOCKED: "Blocked",
+ WAITING_FOR_INPUT: "Waiting for input",
+ COMPLETED: "Completed",
+ FAILED: "Failed",
+ CANCELLED: "Cancelled",
+};
+
+const TASK_SESSION_STATE_LABELS: Record = {
+ CREATED: "Created",
+ STARTING: "Starting",
+ RUNNING: "Running",
+ WAITING_FOR_INPUT: "Waiting for input",
+ COMPLETED: "Completed",
+ FAILED: "Failed",
+ CANCELLED: "Cancelled",
+};
+
+export function formatTaskStateLabel(state: TaskState | null | undefined): string {
+ if (!state) return "Not started";
+ return TASK_STATE_LABELS[state] ?? state;
+}
+
+export function formatTaskSessionStateLabel(state: TaskSessionState | null | undefined): string {
+ if (!state) return "";
+ return TASK_SESSION_STATE_LABELS[state] ?? state;
+}