From 2e52e96aafbd902fb21497e79df6d5d4756e722d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Almeida?= Date: Wed, 6 May 2026 01:29:14 +0100 Subject: [PATCH] feat(web): mobile session/terminal/repo pickers + multi-terminal support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address parity gaps on mobile by introducing per-pane header pills that open bottom-sheet pickers, scoped to the relevant view rather than overloading the left task sheet. Pickers: - Sessions pill in chat header → bottom sheet with launch / set-primary / stop / resume / delete (with confirm). Pill shows agent label + idx/total badge. - Terminals pill in terminal header → bottom sheet with add / close (with confirm) / switch. Replaces an earlier chip-strip prototype. - Repos pill on the top bar (multi-repo only) → bottom sheet listing task repositories; switching jumps to a session on that repo. Each pill renders with a chevron-down icon + count badge so the trigger reads as a button, not a status badge. Multi-terminal: - New useMobileTerminals hook wraps useTerminals and auto-creates a first shell when the env reports zero. - MobileTerminalPane multi-mounts PassthroughTerminal instances keyed by terminalId so switching preserves scrollback. Active xterm registers itself in a small mobile-active-terminal sender registry; the existing key-bar reroutes input through xterm.paste() so Ctrl / ^C / arrows reach whichever terminal is currently visible, not just the per-session default shell. - Skip the WebGL renderer addon on mobile (new disableWebgl prop on PassthroughTerminal). The WebGL atlas miscomputed glyph scaling after the desktop→mobile responsive switch and rendered text at several times the intended font size; the canvas renderer is correct and fast enough for shell use. Refactors: - Left sheet reverts to a single-purpose task list (the sectioned-hub variant was rolled back in favour of per-pane pickers). - session-task-switcher-sheet-hooks extracted from the sheet to keep it under the file-size lint cap. --- .../task/mobile/mobile-picker-sheet.tsx | 49 ++ .../task/mobile/mobile-pill-button.tsx | 67 +++ .../task/mobile/mobile-repo-pill.tsx | 86 ++++ .../task/mobile/mobile-repos-section.tsx | 195 ++++++++ .../task/mobile/mobile-sessions-section.tsx | 399 ++++++++++++++++ .../task/mobile/mobile-terminal-pane.tsx | 88 ++++ .../task/mobile/mobile-terminals-section.tsx | 249 ++++++++++ .../task/mobile/session-mobile-layout.tsx | 121 +++-- .../task/mobile/session-mobile-top-bar.tsx | 7 + .../session-task-switcher-sheet-hooks.ts | 375 +++++++++++++++ .../mobile/session-task-switcher-sheet.tsx | 436 +----------------- .../components/task/passthrough-terminal.tsx | 17 +- .../task/use-passthrough-terminal.ts | 6 +- .../domains/session/use-mobile-terminals.ts | 40 ++ apps/web/lib/state/store.ts | 15 +- .../terminal/mobile-active-terminal.test.ts | 53 +++ .../lib/terminal/mobile-active-terminal.ts | 33 ++ apps/web/lib/terminal/send-shell-input.ts | 27 +- 18 files changed, 1793 insertions(+), 470 deletions(-) create mode 100644 apps/web/components/task/mobile/mobile-picker-sheet.tsx create mode 100644 apps/web/components/task/mobile/mobile-pill-button.tsx create mode 100644 apps/web/components/task/mobile/mobile-repo-pill.tsx create mode 100644 apps/web/components/task/mobile/mobile-repos-section.tsx create mode 100644 apps/web/components/task/mobile/mobile-sessions-section.tsx create mode 100644 apps/web/components/task/mobile/mobile-terminal-pane.tsx create mode 100644 apps/web/components/task/mobile/mobile-terminals-section.tsx create mode 100644 apps/web/components/task/mobile/session-task-switcher-sheet-hooks.ts create mode 100644 apps/web/hooks/domains/session/use-mobile-terminals.ts create mode 100644 apps/web/lib/terminal/mobile-active-terminal.test.ts create mode 100644 apps/web/lib/terminal/mobile-active-terminal.ts diff --git a/apps/web/components/task/mobile/mobile-picker-sheet.tsx b/apps/web/components/task/mobile/mobile-picker-sheet.tsx new file mode 100644 index 0000000000..177dcae8da --- /dev/null +++ b/apps/web/components/task/mobile/mobile-picker-sheet.tsx @@ -0,0 +1,49 @@ +"use client"; + +import { type ReactNode } from "react"; +import { + Drawer, + DrawerContent, + DrawerDescription, + DrawerHeader, + DrawerTitle, +} from "@kandev/ui/drawer"; + +type MobilePickerSheetProps = { + open: boolean; + onOpenChange: (open: boolean) => void; + title: string; + description?: string; + /** Optional trailing element rendered to the right of the title (e.g. a "+" CTA). */ + headerAction?: ReactNode; + children: ReactNode; +}; + +/** + * Bottom-sheet shell for picker patterns (sessions, terminals, repos). Wraps + * shadcn Drawer with a consistent header layout — picker components only need + * to render their list inside `children`. + */ +export function MobilePickerSheet({ + open, + onOpenChange, + title, + description, + headerAction, + children, +}: MobilePickerSheetProps) { + return ( + + + +
+ {title} + {headerAction} +
+ {description && {description}} +
+
{children}
+
+
+ ); +} diff --git a/apps/web/components/task/mobile/mobile-pill-button.tsx b/apps/web/components/task/mobile/mobile-pill-button.tsx new file mode 100644 index 0000000000..b3034e605f --- /dev/null +++ b/apps/web/components/task/mobile/mobile-pill-button.tsx @@ -0,0 +1,67 @@ +"use client"; + +import { forwardRef, type ReactNode } from "react"; +import { IconChevronDown } from "@tabler/icons-react"; +import { Button } from "@kandev/ui/button"; + +type MobilePillButtonProps = { + /** Optional icon to lead with (e.g. folder, terminal). */ + icon?: ReactNode; + /** Primary visible label. Hidden when `compact` is true. */ + label: string; + /** Optional count badge ("3", "2/4", etc.) shown after the label. */ + count?: string | number; + /** Hide the label, keeping just icon + count + chevron. For tight viewports. */ + compact?: boolean; + /** Stretch the pill to fill its parent's width and left-align the label. + * Use when the pill owns the entire header bar with no other content. */ + fullWidth?: boolean; + /** Whether the picker this opens is currently open. Drives aria-expanded. */ + isOpen?: boolean; + /** Tap handler — opens the associated picker sheet. */ + onClick: () => void; + /** Stable test id. */ + "data-testid"?: string; + /** Accessible label override. Defaults to `label`. */ + ariaLabel?: string; +}; + +/** + * Header trigger for a bottom-sheet picker. Pills look like buttons (background + * + chevron) so users see them as interactive, not a passive status badge. + */ +export const MobilePillButton = forwardRef( + function MobilePillButton( + { icon, label, count, compact, fullWidth, isOpen, onClick, ariaLabel, ...rest }, + ref, + ) { + return ( + + ); + }, +); diff --git a/apps/web/components/task/mobile/mobile-repo-pill.tsx b/apps/web/components/task/mobile/mobile-repo-pill.tsx new file mode 100644 index 0000000000..d0f5af0afa --- /dev/null +++ b/apps/web/components/task/mobile/mobile-repo-pill.tsx @@ -0,0 +1,86 @@ +"use client"; + +import { memo, useEffect, useMemo, useState } from "react"; +import { IconFolder } from "@tabler/icons-react"; +import { useAppStore } from "@/components/state-provider"; +import { MobilePillButton } from "./mobile-pill-button"; +import { MobilePickerSheet } from "./mobile-picker-sheet"; +import { MobileReposSection, useTaskRepoCount } from "./mobile-repos-section"; + +const COMPACT_VIEWPORT_PX = 360; + +/** Returns true once the viewport is narrower than the compact threshold. */ +function useIsCompactViewport(): boolean { + const [isCompact, setIsCompact] = useState(false); + useEffect(() => { + const mql = window.matchMedia(`(max-width: ${COMPACT_VIEWPORT_PX - 1}px)`); + const update = () => setIsCompact(mql.matches); + update(); + mql.addEventListener("change", update); + return () => mql.removeEventListener("change", update); + }, []); + return isCompact; +} + +function useTaskActiveRepoName(taskId: string | null, workspaceId: string | null): string | null { + const workspaceRepos = useAppStore((s) => + workspaceId ? (s.repositories.itemsByWorkspaceId[workspaceId] ?? []) : [], + ); + const activeSessionId = useAppStore((s) => s.tasks.activeSessionId); + const activeRepoId = useAppStore((s) => + activeSessionId ? (s.taskSessions.items[activeSessionId]?.repository_id ?? null) : null, + ); + const taskRepos = useAppStore((s) => { + if (!taskId) return undefined; + const task = s.kanban.tasks.find((t: { id: string }) => t.id === taskId); + return task?.repositories; + }); + return useMemo(() => { + if (!activeRepoId) { + // Fallback to the first task repo when no session is active yet. + const fallback = taskRepos?.[0]?.repository_id; + if (!fallback) return null; + const repo = workspaceRepos.find((r) => r.id === fallback); + return repo?.name ?? repo?.local_path ?? null; + } + const repo = workspaceRepos.find((r) => r.id === activeRepoId); + return repo?.name ?? repo?.local_path ?? null; + }, [activeRepoId, taskRepos, workspaceRepos]); +} + +export const MobileRepoPill = memo(function MobileRepoPill({ + taskId, + workspaceId, +}: { + taskId: string | null; + workspaceId: string | null; +}) { + const repoCount = useTaskRepoCount(taskId); + const activeName = useTaskActiveRepoName(taskId, workspaceId); + const isCompact = useIsCompactViewport(); + const [open, setOpen] = useState(false); + + if (repoCount <= 1) return null; + + const label = activeName ?? "Repo"; + return ( + <> + } + label={label} + compact={isCompact} + isOpen={open} + onClick={() => setOpen(true)} + data-testid="mobile-repo-pill" + ariaLabel={`Active repository: ${label}. Tap to switch.`} + /> + + setOpen(false)} + /> + + + ); +}); diff --git a/apps/web/components/task/mobile/mobile-repos-section.tsx b/apps/web/components/task/mobile/mobile-repos-section.tsx new file mode 100644 index 0000000000..dbb2c7699f --- /dev/null +++ b/apps/web/components/task/mobile/mobile-repos-section.tsx @@ -0,0 +1,195 @@ +"use client"; + +import { memo, useCallback, useMemo } from "react"; +import { IconCheck, IconFolder, IconGitBranch } from "@tabler/icons-react"; +import { useAppStore } from "@/components/state-provider"; +import type { Repository, TaskSession } from "@/lib/types/http"; +import type { KanbanState } from "@/lib/state/slices"; + +type RepoRow = { + taskRepositoryId: string; + repositoryId: string; + name: string; + baseBranch: string; + checkoutBranch?: string; + sessionCount: number; + /** A representative session for this repo, if any (preferring primary). */ + switchToSessionId: string | null; +}; + +function pickSwitchToSession( + sessions: TaskSession[], + repositoryId: string, + primarySessionId: string | null | undefined, +): string | null { + const onRepo = sessions.filter((s) => s.repository_id === repositoryId); + if (onRepo.length === 0) return null; + if (primarySessionId && onRepo.some((s) => s.id === primarySessionId)) return primarySessionId; + // Most recently started session on this repo as fallback. + const sorted = [...onRepo].sort( + (a, b) => new Date(b.started_at).getTime() - new Date(a.started_at).getTime(), + ); + return sorted[0].id; +} + +function buildRepoRows( + taskRepositories: NonNullable, + workspaceRepos: Repository[], + taskSessions: TaskSession[], + primarySessionId: string | null | undefined, +): RepoRow[] { + return [...taskRepositories] + .sort((a, b) => a.position - b.position) + .map((tr) => { + const repo = workspaceRepos.find((r) => r.id === tr.repository_id); + const onRepoSessions = taskSessions.filter((s) => s.repository_id === tr.repository_id); + return { + taskRepositoryId: tr.id, + repositoryId: tr.repository_id, + name: repo?.name ?? repo?.local_path ?? "Repository", + baseBranch: tr.base_branch, + checkoutBranch: tr.checkout_branch, + sessionCount: onRepoSessions.length, + switchToSessionId: pickSwitchToSession(taskSessions, tr.repository_id, primarySessionId), + }; + }); +} + +function useTaskRepoRows(taskId: string | null, workspaceId: string | null): RepoRow[] { + const taskRepositories = useAppStore((s) => { + if (!taskId) return undefined; + const task = s.kanban.tasks.find((t: { id: string }) => t.id === taskId); + return task?.repositories; + }); + const workspaceRepos = useAppStore((s) => + workspaceId ? (s.repositories.itemsByWorkspaceId[workspaceId] ?? []) : [], + ); + const taskSessions = useAppStore((s) => + taskId ? (s.taskSessionsByTask.itemsByTaskId[taskId] ?? []) : [], + ); + const primarySessionId = useAppStore((s) => { + if (!taskId) return null; + const task = s.kanban.tasks.find((t: { id: string }) => t.id === taskId); + return task?.primarySessionId ?? null; + }); + return useMemo( + () => + taskRepositories + ? buildRepoRows(taskRepositories, workspaceRepos, taskSessions, primarySessionId) + : [], + [taskRepositories, workspaceRepos, taskSessions, primarySessionId], + ); +} + +function RepoRowItem({ + row, + isActive, + onSelect, +}: { + row: RepoRow; + isActive: boolean; + onSelect: (row: RepoRow) => void; +}) { + return ( +
onSelect(row)} + onKeyDown={(e) => { + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + onSelect(row); + } + }} + data-testid={`mobile-repo-row-${row.repositoryId}`} + className={`flex items-center gap-2 px-2 py-2 rounded-md cursor-pointer select-none ${ + isActive ? "bg-accent" : "hover:bg-accent/50" + }`} + > + +
+ {row.name} +
+ + + {row.checkoutBranch || row.baseBranch} + + {row.sessionCount > 0 && ( + + {row.sessionCount} session{row.sessionCount === 1 ? "" : "s"} + + )} +
+
+ {isActive && } +
+ ); +} + +export const MobileReposSection = memo(function MobileReposSection({ + taskId, + workspaceId, + onClose, +}: { + taskId: string | null; + workspaceId: string | null; + onClose: () => void; +}) { + const setActiveSession = useAppStore((s) => s.setActiveSession); + const activeSessionId = useAppStore((s) => s.tasks.activeSessionId); + const activeRepoId = useAppStore((s) => + activeSessionId ? (s.taskSessions.items[activeSessionId]?.repository_id ?? null) : null, + ); + const rows = useTaskRepoRows(taskId, workspaceId); + + const handleSelect = useCallback( + (row: RepoRow) => { + if (!taskId) return; + if (row.switchToSessionId) { + setActiveSession(taskId, row.switchToSessionId); + onClose(); + } + // Without an existing session on this repo, the user can switch to the + // Sessions tab and launch one — we don't auto-launch here to avoid + // surprise side effects from a tap that looked like navigation. + }, + [taskId, setActiveSession, onClose], + ); + + if (!taskId) { + return ( +
No active task
+ ); + } + if (rows.length === 0) { + return ( +
+ This task has no repositories. +
+ ); + } + + return ( +
+ {rows.map((row) => ( + + ))} +
+ ); +}); + +/** Returns the count of repositories attached to the active task. */ +export function useTaskRepoCount(taskId: string | null): number { + return ( + useAppStore((s) => { + if (!taskId) return 0; + const task = s.kanban.tasks.find((t: { id: string }) => t.id === taskId); + return task?.repositories?.length ?? 0; + }) ?? 0 + ); +} diff --git a/apps/web/components/task/mobile/mobile-sessions-section.tsx b/apps/web/components/task/mobile/mobile-sessions-section.tsx new file mode 100644 index 0000000000..e74a6b1a4b --- /dev/null +++ b/apps/web/components/task/mobile/mobile-sessions-section.tsx @@ -0,0 +1,399 @@ +"use client"; + +import { memo, useCallback, useMemo, useState } from "react"; +import { IconDotsVertical, IconPlus, IconStar } from "@tabler/icons-react"; +import { Button } from "@kandev/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@kandev/ui/dropdown-menu"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@kandev/ui/alert-dialog"; +import { AgentLogo } from "@/components/agent-logo"; +import { useAppStore } from "@/components/state-provider"; +import { useTaskSessions } from "@/hooks/use-task-sessions"; +import { + useSessionActions, + isSessionStoppable, + isSessionDeletable, + isSessionResumable, +} from "@/hooks/domains/session/use-session-actions"; +import { NewSessionDialog } from "../new-session-dialog"; +import { MobilePillButton } from "./mobile-pill-button"; +import { MobilePickerSheet } from "./mobile-picker-sheet"; +import { formatTaskSessionStateLabel } from "@/lib/ui/state-labels"; +import type { TaskSession, TaskSessionState } from "@/lib/types/http"; +import type { AgentProfileOption } from "@/lib/state/slices"; + +type SessionRow = { + id: string; + agentName: string | null; + agentLabel: string; + state: TaskSessionState | null; + isPrimary: boolean; + index: number; + startedAt: string; +}; + +function buildSessionRows( + sessions: TaskSession[], + agentProfiles: AgentProfileOption[], + primarySessionId: string | null | undefined, +): SessionRow[] { + const sorted = [...sessions].sort( + (a, b) => new Date(a.started_at).getTime() - new Date(b.started_at).getTime(), + ); + return sorted.map((s, idx) => { + const profile = agentProfiles.find((p) => p.id === s.agent_profile_id); + const labelParts = profile?.label.split(" • ") ?? []; + return { + id: s.id, + agentName: profile?.agent_name ?? null, + agentLabel: labelParts[1] || labelParts[0] || profile?.label || "Agent", + state: (s.state as TaskSessionState | undefined) ?? null, + isPrimary: primarySessionId ? s.id === primarySessionId : !!s.is_primary, + index: idx + 1, + startedAt: s.started_at, + }; + }); +} + +const STATE_TONE: Partial> = { + RUNNING: "bg-emerald-500/15 text-emerald-600 dark:text-emerald-400", + STARTING: "bg-emerald-500/15 text-emerald-600 dark:text-emerald-400", + WAITING_FOR_INPUT: "bg-amber-500/15 text-amber-600 dark:text-amber-400", + FAILED: "bg-destructive/15 text-destructive", +}; + +function StateBadge({ state }: { state: TaskSessionState | null }) { + if (!state) return null; + const tone = STATE_TONE[state] ?? "bg-foreground/10 text-muted-foreground"; + return ( + + {formatTaskSessionStateLabel(state)} + + ); +} + +function SessionActionsMenu({ + state, + isPrimary, + showCloseConfirm, + onSetPrimary, + onStop, + onResume, + onAskDelete, +}: { + state: TaskSessionState | null; + isPrimary: boolean; + showCloseConfirm: boolean; + onSetPrimary: () => void; + onStop: () => void; + onResume: () => void; + onAskDelete: () => void; +}) { + return ( + + + + + e.stopPropagation()}> + + Set as Primary + + + {state && isSessionStoppable(state) && ( + + Stop + + )} + {state && isSessionResumable(state) && ( + + Resume + + )} + {state && isSessionDeletable(state) && ( + + {showCloseConfirm ? "Delete" : "Delete"} + + )} + + + ); +} + +function DeleteSessionConfirmDialog({ + open, + onOpenChange, + isPrimary, + isOnlySession, + onConfirm, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + isPrimary: boolean; + isOnlySession: boolean; + onConfirm: () => void; +}) { + return ( + + + + Delete session? + +
+

This will permanently delete the conversation history with this session.

+ {isPrimary && !isOnlySession && ( +

+ This is the primary session. Another session will be set as primary. +

+ )} + {isOnlySession && ( +

This is the only session for this task.

+ )} +
+
+
+ + Cancel + { + onOpenChange(false); + onConfirm(); + }} + className="cursor-pointer bg-destructive text-destructive-foreground hover:bg-destructive/90" + > + Delete + + +
+
+ ); +} + +function SessionRowItem({ + row, + taskId, + isActive, + totalSessions, + onSelect, +}: { + row: SessionRow; + taskId: string; + isActive: boolean; + totalSessions: number; + onSelect: (sessionId: string) => void; +}) { + const [confirmDelete, setConfirmDelete] = useState(false); + const actions = useSessionActions({ sessionId: row.id, taskId }); + const isOnly = totalSessions === 1; + const showBadges = totalSessions > 1; + + return ( + <> +
onSelect(row.id)} + onKeyDown={(e) => { + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + onSelect(row.id); + } + }} + data-testid={`mobile-session-row-${row.id}`} + className={`flex items-center gap-2 px-2 py-2 rounded-md cursor-pointer select-none ${ + isActive ? "bg-accent" : "hover:bg-accent/50" + }`} + > + {row.isPrimary && showBadges && ( + + )} + {showBadges && ( + + {row.index} + + )} + {row.agentName && } + {row.agentLabel} + + void actions.setPrimary()} + onStop={() => void actions.stop()} + onResume={() => void actions.resume()} + onAskDelete={() => setConfirmDelete(true)} + /> +
+ void actions.remove()} + /> + + ); +} + +function useSessionRows(taskId: string | null) { + const agentProfiles = useAppStore((s) => s.agentProfiles.items); + const primarySessionId = useAppStore((s) => { + if (!taskId) return null; + const task = s.kanban.tasks.find((t: { id: string }) => t.id === taskId); + return task?.primarySessionId ?? null; + }); + const { sessions, isLoading } = useTaskSessions(taskId); + const rows = useMemo( + () => buildSessionRows(sessions, agentProfiles, primarySessionId), + [sessions, agentProfiles, primarySessionId], + ); + return { rows, isLoading, primarySessionId }; +} + +const MobileSessionsList = memo(function MobileSessionsList({ + taskId, + onClose, +}: { + taskId: string | null; + onClose: () => void; +}) { + const setActiveSession = useAppStore((s) => s.setActiveSession); + const activeSessionId = useAppStore((s) => s.tasks.activeSessionId); + const { rows, isLoading } = useSessionRows(taskId); + const [launchOpen, setLaunchOpen] = useState(false); + + const handleSelect = useCallback( + (sessionId: string) => { + if (!taskId) return; + setActiveSession(taskId, sessionId); + onClose(); + }, + [taskId, setActiveSession, onClose], + ); + + if (!taskId) { + return ( +
No active task
+ ); + } + + return ( +
+
+ + {rows.length} session{rows.length === 1 ? "" : "s"} + + +
+
+ {isLoading && rows.length === 0 && ( +
+ Loading sessions… +
+ )} + {!isLoading && rows.length === 0 && ( +
+ No sessions yet. Launch one to get started. +
+ )} + {rows.map((row) => ( + + ))} +
+ {launchOpen && ( + + )} +
+ ); +}); + +function useActiveSessionPillLabel(taskId: string | null): { + label: string; + count: string | undefined; +} { + const activeSessionId = useAppStore((s) => s.tasks.activeSessionId); + const { rows } = useSessionRows(taskId); + const activeRow = rows.find((r) => r.id === activeSessionId); + const total = rows.length; + const idx = activeRow?.index; + let count: string | undefined; + if (total > 1 && idx) count = `${idx}/${total}`; + else if (total > 1) count = `${total}`; + return { label: activeRow?.agentLabel ?? "Session", count }; +} + +export const MobileSessionsPicker = memo(function MobileSessionsPicker({ + taskId, + compact, + fullWidth, +}: { + taskId: string | null; + compact?: boolean; + fullWidth?: boolean; +}) { + const [open, setOpen] = useState(false); + const { label, count } = useActiveSessionPillLabel(taskId); + if (!taskId) return null; + return ( + <> + setOpen(true)} + data-testid="mobile-sessions-pill" + ariaLabel={`Active session: ${label}. Tap to switch.`} + /> + + setOpen(false)} /> + + + ); +}); diff --git a/apps/web/components/task/mobile/mobile-terminal-pane.tsx b/apps/web/components/task/mobile/mobile-terminal-pane.tsx new file mode 100644 index 0000000000..ece48382b4 --- /dev/null +++ b/apps/web/components/task/mobile/mobile-terminal-pane.tsx @@ -0,0 +1,88 @@ +"use client"; + +import { memo, useEffect, useRef } from "react"; +import { PassthroughTerminal } from "../passthrough-terminal"; +import { useMobileTerminals } from "@/hooks/domains/session/use-mobile-terminals"; +import { setActiveTerminalSender } from "@/lib/terminal/mobile-active-terminal"; +import { MobileTerminalsPicker } from "./mobile-terminals-section"; +import type { Terminal as XtermTerminal } from "@xterm/xterm"; +import type { Terminal } from "@/hooks/domains/session/use-terminals"; + +function TerminalSlot({ + terminal, + environmentId, + isActive, +}: { + terminal: Terminal; + environmentId: string | null; + isActive: boolean; +}) { + const xtermRef = useRef(null); + + // Register the active terminal sender so the mobile key-bar can target this + // xterm via paste(), which routes through xterm.onData → AttachAddon → WS. + useEffect(() => { + if (!isActive) return; + const xterm = xtermRef.current; + if (!xterm) return; + const sender = (data: string) => xterm.paste(data); + setActiveTerminalSender(sender); + return () => setActiveTerminalSender(null); + }, [isActive, terminal.id]); + + return ( +
+ { + xtermRef.current = x; + }} + /> +
+ ); +} + +export const MobileTerminalPane = memo(function MobileTerminalPane({ + sessionId, +}: { + sessionId: string | null; +}) { + const { terminals, terminalTabValue, environmentId } = useMobileTerminals(sessionId); + const activeId = terminals.find((t) => t.id === terminalTabValue)?.id ?? terminals[0]?.id; + + if (!sessionId || !environmentId) { + return ( +
+ Terminal unavailable — no active session. +
+ ); + } + + return ( +
+
+ +
+
+ {terminals.length === 0 && ( +
+ Starting terminal… +
+ )} + {terminals.map((t) => ( + + ))} +
+
+ ); +}); diff --git a/apps/web/components/task/mobile/mobile-terminals-section.tsx b/apps/web/components/task/mobile/mobile-terminals-section.tsx new file mode 100644 index 0000000000..c8952a09e2 --- /dev/null +++ b/apps/web/components/task/mobile/mobile-terminals-section.tsx @@ -0,0 +1,249 @@ +"use client"; + +import { memo, useCallback, useState } from "react"; +import { IconPlus, IconTerminal2, IconX } from "@tabler/icons-react"; +import { Button } from "@kandev/ui/button"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@kandev/ui/alert-dialog"; +import { useAppStore } from "@/components/state-provider"; +import { useMobileTerminals } from "@/hooks/domains/session/use-mobile-terminals"; +import { stopUserShell } from "@/lib/api/domains/user-shell-api"; +import { useUserShells } from "@/hooks/domains/session/use-user-shells"; +import { MobilePillButton } from "./mobile-pill-button"; +import { MobilePickerSheet } from "./mobile-picker-sheet"; +import type { Terminal } from "@/hooks/domains/session/use-terminals"; + +function TerminalRow({ + terminal, + isActive, + isRunning, + onSelect, + onAskClose, +}: { + terminal: Terminal; + isActive: boolean; + isRunning: boolean; + onSelect: (id: string) => void; + onAskClose: (terminal: Terminal) => void; +}) { + return ( +
onSelect(terminal.id)} + onKeyDown={(e) => { + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + onSelect(terminal.id); + } + }} + data-testid={`mobile-terminal-row-${terminal.id}`} + className={`flex items-center gap-2 px-2 py-2 rounded-md cursor-pointer select-none ${ + isActive ? "bg-accent" : "hover:bg-accent/50" + }`} + > + + {terminal.label} + {isRunning && ( + + running + + )} + {terminal.closable && ( + + )} +
+ ); +} + +function CloseTerminalConfirmDialog({ + terminal, + onOpenChange, + onConfirm, +}: { + terminal: Terminal | null; + onOpenChange: (open: boolean) => void; + onConfirm: () => void; +}) { + return ( + + + + Close terminal? + + {`This stops the “${terminal?.label ?? ""}” shell and any process it's running.`} + + + + Cancel + { + onOpenChange(false); + onConfirm(); + }} + className="cursor-pointer bg-destructive text-destructive-foreground hover:bg-destructive/90" + > + Close terminal + + + + + ); +} + +const MobileTerminalsList = memo(function MobileTerminalsList({ + sessionId, + onClose, +}: { + sessionId: string | null; + onClose: () => void; +}) { + const { terminals, terminalTabValue, addTerminal, removeTerminal, environmentId } = + useMobileTerminals(sessionId); + const { shells } = useUserShells(environmentId); + const setRightPanelActiveTab = useAppStore((s) => s.setRightPanelActiveTab); + const [pendingClose, setPendingClose] = useState(null); + + const isShellRunning = useCallback( + (id: string) => shells.find((s) => s.terminalId === id)?.running ?? false, + [shells], + ); + + const handleSelect = useCallback( + (id: string) => { + if (sessionId) setRightPanelActiveTab(sessionId, id); + onClose(); + }, + [sessionId, setRightPanelActiveTab, onClose], + ); + + const handleConfirmClose = useCallback(() => { + const t = pendingClose; + if (!t) return; + removeTerminal(t.id); + if (environmentId) { + stopUserShell(environmentId, t.id).catch((err) => { + console.error("Failed to stop terminal:", err); + }); + } + setPendingClose(null); + }, [pendingClose, removeTerminal, environmentId]); + + const handleAskClose = useCallback((terminal: Terminal) => { + setPendingClose(terminal); + }, []); + + if (!sessionId) { + return ( +
No active session
+ ); + } + + return ( +
+
+ + {terminals.length} terminal{terminals.length === 1 ? "" : "s"} + + +
+
+ {terminals.length === 0 && ( +
+ No terminals yet. +
+ )} + {terminals.map((t) => ( + + ))} +
+ { + if (!open) setPendingClose(null); + }} + onConfirm={handleConfirmClose} + /> +
+ ); +}); + +function useActiveTerminalPillLabel(sessionId: string | null): { + label: string; + count: string | undefined; +} { + const { terminals, terminalTabValue } = useMobileTerminals(sessionId); + const activeIdx = terminals.findIndex((t) => t.id === terminalTabValue); + const idx = activeIdx >= 0 ? activeIdx : 0; + const active = terminals[idx]; + const total = terminals.length; + let count: string | undefined; + if (total > 1) count = `${idx + 1}/${total}`; + return { label: active?.label ?? "Terminal", count }; +} + +export const MobileTerminalsPicker = memo(function MobileTerminalsPicker({ + sessionId, + compact, + fullWidth, +}: { + sessionId: string | null; + compact?: boolean; + fullWidth?: boolean; +}) { + const [open, setOpen] = useState(false); + const { label, count } = useActiveTerminalPillLabel(sessionId); + if (!sessionId) return null; + return ( + <> + setOpen(true)} + data-testid="mobile-terminals-pill" + ariaLabel={`Active terminal: ${label}. Tap to switch.`} + /> + + setOpen(false)} /> + + + ); +}); diff --git a/apps/web/components/task/mobile/session-mobile-layout.tsx b/apps/web/components/task/mobile/session-mobile-layout.tsx index 60244b822b..3cd313f36b 100644 --- a/apps/web/components/task/mobile/session-mobile-layout.tsx +++ b/apps/web/components/task/mobile/session-mobile-layout.tsx @@ -8,9 +8,10 @@ import { TaskChatPanel } from "../task-chat-panel"; import { TaskPlanPanel } from "../task-plan-panel"; import { TaskChangesPanel } from "../task-changes-panel"; import { TaskFilesPanel } from "../task-files-panel"; -import { ShellTerminal } from "../shell-terminal"; import { PassthroughTerminal } from "../passthrough-terminal"; import { MobileTerminalKeybar, KEYBAR_HEIGHT_PX } from "./mobile-terminal-keybar"; +import { MobileTerminalPane } from "./mobile-terminal-pane"; +import { MobileSessionsPicker } from "./mobile-sessions-section"; import { SessionPanelContent } from "@kandev/ui/pannel-session"; import { useSessionLayoutState } from "@/hooks/use-session-layout-state"; import { useVisualViewportOffset } from "@/hooks/use-visual-viewport-offset"; @@ -48,19 +49,25 @@ function MobileChatPanelContent({ sessionId?: string | null; onOpenFile: (path: string) => void; }) { - if (activeTaskId && isPassthroughMode) { + if (!activeTaskId) { return ( -
- +
+ No task selected
); } - if (activeTaskId) { - return ; - } return ( -
- No task selected +
+
+ +
+ {isPassthroughMode ? ( +
+ +
+ ) : ( + + )}
); } @@ -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(); }