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