);
}
@@ -112,7 +119,7 @@ function MobilePanelArea({
}}
>
{currentMobilePanel === "chat" && (
-
+
-
-
+
+
)}
@@ -159,6 +166,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 +289,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,
+ })),
+ 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,
+ })),
+ };
+}
+
+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 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 };
+}
+
+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;
+ }
+ 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,
+ };
+}
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..ab5ab3df45 100644
--- a/apps/web/components/task/passthrough-terminal.tsx
+++ b/apps/web/components/task/passthrough-terminal.tsx
@@ -31,6 +31,14 @@ 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;
};
type AgentTerminalProps = BaseProps & { mode: "agent"; sessionId?: string | null; label?: string };
type ShellTerminalProps = BaseProps & {
@@ -119,7 +127,8 @@ 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 } =
+ props;
const terminalId = mode === "shell" ? props.terminalId : undefined;
const environmentId = mode === "shell" ? props.environmentId : undefined;
const refs = useTerminalRefs();
@@ -137,7 +146,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 +198,7 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
linkHandler,
fontFamily: buildTerminalFontFamily(terminalFontFamily),
fontSize: terminalFontSize ?? undefined,
+ disableWebgl,
onToggleBottomTerminal: toggleBottomTerminal,
sendInput,
keyboardShortcutsRef,
diff --git a/apps/web/components/task/use-passthrough-terminal.ts b/apps/web/components/task/use-passthrough-terminal.ts
index 94dcfd1c4a..429190d6ea 100644
--- a/apps/web/components/task/use-passthrough-terminal.ts
+++ b/apps/web/components/task/use-passthrough-terminal.ts
@@ -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,
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..e3b2896166
--- /dev/null
+++ b/apps/web/hooks/domains/session/use-mobile-terminals.ts
@@ -0,0 +1,40 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { useTerminals } from "./use-terminals";
+import { useUserShells } from "./use-user-shells";
+import { useAppStore } from "@/components/state-provider";
+
+/**
+ * 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 a
+ // primitive dependency (depending on the result object would re-run the
+ // effect every render and continuously cancel the timer).
+ const { isLoaded: shellsLoaded, shells } = useUserShells(environmentId);
+ const addTerminalRef = useRef(result.addTerminal);
+ useEffect(() => {
+ addTerminalRef.current = result.addTerminal;
+ }, [result.addTerminal]);
+ const autoCreatedRef = useRef(null);
+
+ useEffect(() => {
+ if (!environmentId || !shellsLoaded) return;
+ if (autoCreatedRef.current === environmentId) return;
+ if (shells.length > 0) {
+ autoCreatedRef.current = environmentId;
+ return;
+ }
+ autoCreatedRef.current = environmentId;
+ addTerminalRef.current();
+ }, [environmentId, shellsLoaded, shells.length]);
+
+ return { ...result, environmentId };
+}
diff --git a/apps/web/lib/state/store.ts b/apps/web/lib/state/store.ts
index 440804e0d4..3b8effa973 100644
--- a/apps/web/lib/state/store.ts
+++ b/apps/web/lib/state/store.ts
@@ -19,6 +19,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,
@@ -359,16 +360,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;
@@ -383,9 +378,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..286a8f040a
--- /dev/null
+++ b/apps/web/lib/terminal/mobile-active-terminal.test.ts
@@ -0,0 +1,53 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import {
+ setActiveTerminalSender,
+ getActiveTerminalSender,
+ subscribeActiveTerminalSender,
+} 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();
+ });
+
+ it("notifies subscribers on changes only", () => {
+ const listener = vi.fn();
+ const unsubscribe = subscribeActiveTerminalSender(listener);
+ const sender = vi.fn();
+ setActiveTerminalSender(sender);
+ expect(listener).toHaveBeenCalledTimes(1);
+ setActiveTerminalSender(sender); // no-op (same value)
+ expect(listener).toHaveBeenCalledTimes(1);
+ setActiveTerminalSender(null);
+ expect(listener).toHaveBeenCalledTimes(2);
+ unsubscribe();
+ setActiveTerminalSender(vi.fn());
+ expect(listener).toHaveBeenCalledTimes(2);
+ });
+});
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..5a344d8f37
--- /dev/null
+++ b/apps/web/lib/terminal/mobile-active-terminal.ts
@@ -0,0 +1,33 @@
+/**
+ * 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;
+const listeners = new Set<() => void>();
+
+function notify(): void {
+ for (const l of listeners) l();
+}
+
+export function setActiveTerminalSender(sender: Sender | null): void {
+ if (activeSender === sender) return;
+ activeSender = sender;
+ notify();
+}
+
+export function getActiveTerminalSender(): Sender | null {
+ return activeSender;
+}
+
+export function subscribeActiveTerminalSender(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
diff --git a/apps/web/lib/terminal/send-shell-input.ts b/apps/web/lib/terminal/send-shell-input.ts
index 0531398409..5e7f040237 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,32 @@ 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) {
+ activeSender(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();
}