feat(web): mobile session/terminal/repo pickers + multi-terminal support

Address parity gaps on mobile by introducing per-pane header pills that
open bottom-sheet pickers, scoped to the relevant view rather than
overloading the left task sheet.

Pickers:
- Sessions pill in chat header → bottom sheet with launch / set-primary
  / stop / resume / delete (with confirm). Pill shows agent label +
  idx/total badge.
- Terminals pill in terminal header → bottom sheet with add / close
  (with confirm) / switch. Replaces an earlier chip-strip prototype.
- Repos pill on the top bar (multi-repo only) → bottom sheet listing
  task repositories; switching jumps to a session on that repo.

Each pill renders with a chevron-down icon + count badge so the
trigger reads as a button, not a status badge.

Multi-terminal:
- New useMobileTerminals hook wraps useTerminals and auto-creates a
  first shell when the env reports zero.
- MobileTerminalPane multi-mounts PassthroughTerminal instances keyed
  by terminalId so switching preserves scrollback. Active xterm
  registers itself in a small mobile-active-terminal sender registry;
  the existing key-bar reroutes input through xterm.paste() so Ctrl /
  ^C / arrows reach whichever terminal is currently visible, not just
  the per-session default shell.
- Skip the WebGL renderer addon on mobile (new disableWebgl prop on
  PassthroughTerminal). The WebGL atlas miscomputed glyph scaling
  after the desktop→mobile responsive switch and rendered text at
  several times the intended font size; the canvas renderer is correct
  and fast enough for shell use.

Refactors:
- Left sheet reverts to a single-purpose task list (the sectioned-hub
  variant was rolled back in favour of per-pane pickers).
- session-task-switcher-sheet-hooks extracted from the sheet to keep
  it under the file-size lint cap.
This commit is contained in:
José Almeida
2026-05-06 01:29:14 +01:00
parent 774a80e26e
commit 2e52e96aaf
18 changed files with 1793 additions and 470 deletions
@@ -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 (
<Drawer open={open} onOpenChange={onOpenChange}>
<DrawerContent>
<DrawerHeader className="text-left pb-2">
<div className="flex items-center justify-between gap-2">
<DrawerTitle className="text-sm">{title}</DrawerTitle>
{headerAction}
</div>
{description && <DrawerDescription>{description}</DrawerDescription>}
</DrawerHeader>
<div className="flex-1 min-h-0 overflow-y-auto px-2 pb-4">{children}</div>
</DrawerContent>
</Drawer>
);
}
@@ -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<HTMLButtonElement, MobilePillButtonProps>(
function MobilePillButton(
{ icon, label, count, compact, fullWidth, isOpen, onClick, ariaLabel, ...rest },
ref,
) {
return (
<Button
ref={ref}
type="button"
variant="outline"
size="sm"
className={`h-8 px-3 gap-2 cursor-pointer ${fullWidth ? "w-full justify-between" : ""}`}
aria-label={ariaLabel ?? label}
aria-haspopup="dialog"
aria-expanded={isOpen ?? false}
title={label}
onClick={onClick}
data-testid={rest["data-testid"]}
>
<span className="flex items-center gap-2 min-w-0">
{icon}
{!compact && (
<span className={`text-xs truncate ${fullWidth ? "" : "max-w-[120px]"}`}>{label}</span>
)}
{count !== undefined && count !== "" && (
<span className="text-[10px] font-medium px-1 py-0.5 rounded bg-foreground/10 text-muted-foreground leading-none shrink-0">
{count}
</span>
)}
</span>
<IconChevronDown className="h-3.5 w-3.5 shrink-0 opacity-70" />
</Button>
);
},
);
@@ -0,0 +1,86 @@
"use client";
import { memo, useEffect, useMemo, useState } from "react";
import { IconFolder } from "@tabler/icons-react";
import { useAppStore } from "@/components/state-provider";
import { MobilePillButton } from "./mobile-pill-button";
import { MobilePickerSheet } from "./mobile-picker-sheet";
import { MobileReposSection, useTaskRepoCount } from "./mobile-repos-section";
const COMPACT_VIEWPORT_PX = 360;
/** Returns true once the viewport is narrower than the compact threshold. */
function useIsCompactViewport(): boolean {
const [isCompact, setIsCompact] = useState(false);
useEffect(() => {
const mql = window.matchMedia(`(max-width: ${COMPACT_VIEWPORT_PX - 1}px)`);
const update = () => setIsCompact(mql.matches);
update();
mql.addEventListener("change", update);
return () => mql.removeEventListener("change", update);
}, []);
return isCompact;
}
function useTaskActiveRepoName(taskId: string | null, workspaceId: string | null): string | null {
const workspaceRepos = useAppStore((s) =>
workspaceId ? (s.repositories.itemsByWorkspaceId[workspaceId] ?? []) : [],
);
const activeSessionId = useAppStore((s) => s.tasks.activeSessionId);
const activeRepoId = useAppStore((s) =>
activeSessionId ? (s.taskSessions.items[activeSessionId]?.repository_id ?? null) : null,
);
const taskRepos = useAppStore((s) => {
if (!taskId) return undefined;
const task = s.kanban.tasks.find((t: { id: string }) => t.id === taskId);
return task?.repositories;
});
return useMemo(() => {
if (!activeRepoId) {
// Fallback to the first task repo when no session is active yet.
const fallback = taskRepos?.[0]?.repository_id;
if (!fallback) return null;
const repo = workspaceRepos.find((r) => r.id === fallback);
return repo?.name ?? repo?.local_path ?? null;
}
const repo = workspaceRepos.find((r) => r.id === activeRepoId);
return repo?.name ?? repo?.local_path ?? null;
}, [activeRepoId, taskRepos, workspaceRepos]);
}
export const MobileRepoPill = memo(function MobileRepoPill({
taskId,
workspaceId,
}: {
taskId: string | null;
workspaceId: string | null;
}) {
const repoCount = useTaskRepoCount(taskId);
const activeName = useTaskActiveRepoName(taskId, workspaceId);
const isCompact = useIsCompactViewport();
const [open, setOpen] = useState(false);
if (repoCount <= 1) return null;
const label = activeName ?? "Repo";
return (
<>
<MobilePillButton
icon={<IconFolder className="h-3.5 w-3.5 shrink-0" />}
label={label}
compact={isCompact}
isOpen={open}
onClick={() => setOpen(true)}
data-testid="mobile-repo-pill"
ariaLabel={`Active repository: ${label}. Tap to switch.`}
/>
<MobilePickerSheet open={open} onOpenChange={setOpen} title="Repositories">
<MobileReposSection
taskId={taskId}
workspaceId={workspaceId}
onClose={() => setOpen(false)}
/>
</MobilePickerSheet>
</>
);
});
@@ -0,0 +1,195 @@
"use client";
import { memo, useCallback, useMemo } from "react";
import { IconCheck, IconFolder, IconGitBranch } from "@tabler/icons-react";
import { useAppStore } from "@/components/state-provider";
import type { Repository, TaskSession } from "@/lib/types/http";
import type { KanbanState } from "@/lib/state/slices";
type RepoRow = {
taskRepositoryId: string;
repositoryId: string;
name: string;
baseBranch: string;
checkoutBranch?: string;
sessionCount: number;
/** A representative session for this repo, if any (preferring primary). */
switchToSessionId: string | null;
};
function pickSwitchToSession(
sessions: TaskSession[],
repositoryId: string,
primarySessionId: string | null | undefined,
): string | null {
const onRepo = sessions.filter((s) => s.repository_id === repositoryId);
if (onRepo.length === 0) return null;
if (primarySessionId && onRepo.some((s) => s.id === primarySessionId)) return primarySessionId;
// Most recently started session on this repo as fallback.
const sorted = [...onRepo].sort(
(a, b) => new Date(b.started_at).getTime() - new Date(a.started_at).getTime(),
);
return sorted[0].id;
}
function buildRepoRows(
taskRepositories: NonNullable<KanbanState["tasks"][number]["repositories"]>,
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 (
<div
role="button"
tabIndex={0}
onClick={() => 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"
}`}
>
<IconFolder className="h-4 w-4 text-muted-foreground shrink-0" />
<div className="flex flex-col min-w-0 flex-1">
<span className="text-sm truncate">{row.name}</span>
<div className="flex items-center gap-1 min-w-0">
<IconGitBranch className="h-3 w-3 text-muted-foreground shrink-0" />
<span className="text-[11px] text-muted-foreground truncate">
{row.checkoutBranch || row.baseBranch}
</span>
{row.sessionCount > 0 && (
<span className="text-[10px] font-medium px-1.5 py-0.5 rounded bg-foreground/10 text-muted-foreground leading-none ml-1 shrink-0">
{row.sessionCount} session{row.sessionCount === 1 ? "" : "s"}
</span>
)}
</div>
</div>
{isActive && <IconCheck className="h-4 w-4 text-foreground shrink-0" />}
</div>
);
}
export const MobileReposSection = memo(function MobileReposSection({
taskId,
workspaceId,
onClose,
}: {
taskId: string | null;
workspaceId: string | null;
onClose: () => void;
}) {
const setActiveSession = useAppStore((s) => s.setActiveSession);
const activeSessionId = useAppStore((s) => s.tasks.activeSessionId);
const activeRepoId = useAppStore((s) =>
activeSessionId ? (s.taskSessions.items[activeSessionId]?.repository_id ?? null) : null,
);
const rows = useTaskRepoRows(taskId, workspaceId);
const handleSelect = useCallback(
(row: RepoRow) => {
if (!taskId) return;
if (row.switchToSessionId) {
setActiveSession(taskId, row.switchToSessionId);
onClose();
}
// Without an existing session on this repo, the user can switch to the
// Sessions tab and launch one — we don't auto-launch here to avoid
// surprise side effects from a tap that looked like navigation.
},
[taskId, setActiveSession, onClose],
);
if (!taskId) {
return (
<div className="text-xs text-muted-foreground px-2 py-6 text-center">No active task</div>
);
}
if (rows.length === 0) {
return (
<div className="text-xs text-muted-foreground px-2 py-6 text-center">
This task has no repositories.
</div>
);
}
return (
<div className="flex flex-col gap-0.5 px-1">
{rows.map((row) => (
<RepoRowItem
key={row.taskRepositoryId}
row={row}
isActive={row.repositoryId === activeRepoId}
onSelect={handleSelect}
/>
))}
</div>
);
});
/** 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
);
}
@@ -0,0 +1,399 @@
"use client";
import { memo, useCallback, useMemo, useState } from "react";
import { IconDotsVertical, IconPlus, IconStar } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@kandev/ui/dropdown-menu";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@kandev/ui/alert-dialog";
import { AgentLogo } from "@/components/agent-logo";
import { useAppStore } from "@/components/state-provider";
import { useTaskSessions } from "@/hooks/use-task-sessions";
import {
useSessionActions,
isSessionStoppable,
isSessionDeletable,
isSessionResumable,
} from "@/hooks/domains/session/use-session-actions";
import { NewSessionDialog } from "../new-session-dialog";
import { MobilePillButton } from "./mobile-pill-button";
import { MobilePickerSheet } from "./mobile-picker-sheet";
import { formatTaskSessionStateLabel } from "@/lib/ui/state-labels";
import type { TaskSession, TaskSessionState } from "@/lib/types/http";
import type { AgentProfileOption } from "@/lib/state/slices";
type SessionRow = {
id: string;
agentName: string | null;
agentLabel: string;
state: TaskSessionState | null;
isPrimary: boolean;
index: number;
startedAt: string;
};
function buildSessionRows(
sessions: TaskSession[],
agentProfiles: AgentProfileOption[],
primarySessionId: string | null | undefined,
): SessionRow[] {
const sorted = [...sessions].sort(
(a, b) => new Date(a.started_at).getTime() - new Date(b.started_at).getTime(),
);
return sorted.map((s, idx) => {
const profile = agentProfiles.find((p) => p.id === s.agent_profile_id);
const labelParts = profile?.label.split(" • ") ?? [];
return {
id: s.id,
agentName: profile?.agent_name ?? null,
agentLabel: labelParts[1] || labelParts[0] || profile?.label || "Agent",
state: (s.state as TaskSessionState | undefined) ?? null,
isPrimary: primarySessionId ? s.id === primarySessionId : !!s.is_primary,
index: idx + 1,
startedAt: s.started_at,
};
});
}
const STATE_TONE: Partial<Record<TaskSessionState, string>> = {
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 (
<span className={`text-[10px] font-medium px-1.5 py-0.5 rounded leading-none ${tone}`}>
{formatTaskSessionStateLabel(state)}
</span>
);
}
function SessionActionsMenu({
state,
isPrimary,
showCloseConfirm,
onSetPrimary,
onStop,
onResume,
onAskDelete,
}: {
state: TaskSessionState | null;
isPrimary: boolean;
showCloseConfirm: boolean;
onSetPrimary: () => void;
onStop: () => void;
onResume: () => void;
onAskDelete: () => void;
}) {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon-sm"
className="cursor-pointer h-7 w-7"
onClick={(e) => e.stopPropagation()}
aria-label="Session actions"
>
<IconDotsVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" onClick={(e) => e.stopPropagation()}>
<DropdownMenuItem
className="cursor-pointer"
onSelect={onSetPrimary}
disabled={isPrimary || !state || !isSessionStoppable(state)}
>
Set as Primary
</DropdownMenuItem>
<DropdownMenuSeparator />
{state && isSessionStoppable(state) && (
<DropdownMenuItem className="cursor-pointer" onSelect={onStop}>
Stop
</DropdownMenuItem>
)}
{state && isSessionResumable(state) && (
<DropdownMenuItem className="cursor-pointer" onSelect={onResume}>
Resume
</DropdownMenuItem>
)}
{state && isSessionDeletable(state) && (
<DropdownMenuItem
className="cursor-pointer text-destructive focus:text-destructive"
onSelect={onAskDelete}
>
{showCloseConfirm ? "Delete" : "Delete"}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
);
}
function DeleteSessionConfirmDialog({
open,
onOpenChange,
isPrimary,
isOnlySession,
onConfirm,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
isPrimary: boolean;
isOnlySession: boolean;
onConfirm: () => void;
}) {
return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete session?</AlertDialogTitle>
<AlertDialogDescription asChild>
<div>
<p>This will permanently delete the conversation history with this session.</p>
{isPrimary && !isOnlySession && (
<p className="mt-2 font-medium">
This is the primary session. Another session will be set as primary.
</p>
)}
{isOnlySession && (
<p className="mt-2 font-medium">This is the only session for this task.</p>
)}
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel className="cursor-pointer">Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
onOpenChange(false);
onConfirm();
}}
className="cursor-pointer bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
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 (
<>
<div
role="button"
tabIndex={0}
onClick={() => 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 && (
<IconStar className="h-3.5 w-3.5 fill-foreground/60 stroke-0 shrink-0" />
)}
{showBadges && (
<span className="text-[11px] font-medium leading-none text-muted-foreground bg-foreground/10 rounded px-1.5 py-0.5 shrink-0">
{row.index}
</span>
)}
{row.agentName && <AgentLogo agentName={row.agentName} size={16} className="shrink-0" />}
<span className="text-sm truncate flex-1">{row.agentLabel}</span>
<StateBadge state={row.state} />
<SessionActionsMenu
state={row.state}
isPrimary={row.isPrimary}
showCloseConfirm
onSetPrimary={() => void actions.setPrimary()}
onStop={() => void actions.stop()}
onResume={() => void actions.resume()}
onAskDelete={() => setConfirmDelete(true)}
/>
</div>
<DeleteSessionConfirmDialog
open={confirmDelete}
onOpenChange={setConfirmDelete}
isPrimary={row.isPrimary}
isOnlySession={isOnly}
onConfirm={() => 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 (
<div className="text-xs text-muted-foreground px-2 py-6 text-center">No active task</div>
);
}
return (
<div className="flex flex-col gap-2 px-1">
<div className="flex items-center justify-between px-1">
<span className="text-xs font-medium text-muted-foreground">
{rows.length} session{rows.length === 1 ? "" : "s"}
</span>
<Button
size="sm"
variant="outline"
className="h-7 gap-1 cursor-pointer"
onClick={() => setLaunchOpen(true)}
data-testid="mobile-launch-session"
>
<IconPlus className="h-4 w-4" />
New session
</Button>
</div>
<div className="flex flex-col gap-0.5">
{isLoading && rows.length === 0 && (
<div className="text-xs text-muted-foreground px-2 py-4 text-center">
Loading sessions…
</div>
)}
{!isLoading && rows.length === 0 && (
<div className="text-xs text-muted-foreground px-2 py-4 text-center">
No sessions yet. Launch one to get started.
</div>
)}
{rows.map((row) => (
<SessionRowItem
key={row.id}
row={row}
taskId={taskId}
isActive={row.id === activeSessionId}
totalSessions={rows.length}
onSelect={handleSelect}
/>
))}
</div>
{launchOpen && (
<NewSessionDialog open={launchOpen} onOpenChange={setLaunchOpen} taskId={taskId} />
)}
</div>
);
});
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 (
<>
<MobilePillButton
label={label}
count={count}
compact={compact}
fullWidth={fullWidth}
isOpen={open}
onClick={() => setOpen(true)}
data-testid="mobile-sessions-pill"
ariaLabel={`Active session: ${label}. Tap to switch.`}
/>
<MobilePickerSheet open={open} onOpenChange={setOpen} title="Sessions">
<MobileSessionsList taskId={taskId} onClose={() => setOpen(false)} />
</MobilePickerSheet>
</>
);
});
@@ -0,0 +1,88 @@
"use client";
import { memo, useEffect, useRef } from "react";
import { PassthroughTerminal } from "../passthrough-terminal";
import { useMobileTerminals } from "@/hooks/domains/session/use-mobile-terminals";
import { setActiveTerminalSender } from "@/lib/terminal/mobile-active-terminal";
import { MobileTerminalsPicker } from "./mobile-terminals-section";
import type { Terminal as XtermTerminal } from "@xterm/xterm";
import type { Terminal } from "@/hooks/domains/session/use-terminals";
function TerminalSlot({
terminal,
environmentId,
isActive,
}: {
terminal: Terminal;
environmentId: string | null;
isActive: boolean;
}) {
const xtermRef = useRef<XtermTerminal | null>(null);
// Register the active terminal sender so the mobile key-bar can target this
// xterm via paste(), which routes through xterm.onData → AttachAddon → WS.
useEffect(() => {
if (!isActive) return;
const xterm = xtermRef.current;
if (!xterm) return;
const sender = (data: string) => xterm.paste(data);
setActiveTerminalSender(sender);
return () => setActiveTerminalSender(null);
}, [isActive, terminal.id]);
return (
<div className={`absolute inset-0 ${isActive ? "block" : "hidden"}`}>
<PassthroughTerminal
mode="shell"
environmentId={environmentId}
terminalId={terminal.id}
label={terminal.label}
autoFocus={isActive}
disableWebgl
onXtermReady={(x) => {
xtermRef.current = x;
}}
/>
</div>
);
}
export const MobileTerminalPane = memo(function MobileTerminalPane({
sessionId,
}: {
sessionId: string | null;
}) {
const { terminals, terminalTabValue, environmentId } = useMobileTerminals(sessionId);
const activeId = terminals.find((t) => t.id === terminalTabValue)?.id ?? terminals[0]?.id;
if (!sessionId || !environmentId) {
return (
<div className="flex-1 flex items-center justify-center text-xs text-muted-foreground">
Terminal unavailable — no active session.
</div>
);
}
return (
<div className="flex-1 min-h-0 flex flex-col">
<div className="flex items-center px-1 py-2 border-b border-border">
<MobileTerminalsPicker sessionId={sessionId} fullWidth />
</div>
<div className="relative flex-1 min-h-0">
{terminals.length === 0 && (
<div className="absolute inset-0 flex items-center justify-center text-xs text-muted-foreground">
Starting terminal…
</div>
)}
{terminals.map((t) => (
<TerminalSlot
key={t.id}
terminal={t}
environmentId={environmentId}
isActive={t.id === activeId}
/>
))}
</div>
</div>
);
});
@@ -0,0 +1,249 @@
"use client";
import { memo, useCallback, useState } from "react";
import { IconPlus, IconTerminal2, IconX } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@kandev/ui/alert-dialog";
import { useAppStore } from "@/components/state-provider";
import { useMobileTerminals } from "@/hooks/domains/session/use-mobile-terminals";
import { stopUserShell } from "@/lib/api/domains/user-shell-api";
import { useUserShells } from "@/hooks/domains/session/use-user-shells";
import { MobilePillButton } from "./mobile-pill-button";
import { MobilePickerSheet } from "./mobile-picker-sheet";
import type { Terminal } from "@/hooks/domains/session/use-terminals";
function TerminalRow({
terminal,
isActive,
isRunning,
onSelect,
onAskClose,
}: {
terminal: Terminal;
isActive: boolean;
isRunning: boolean;
onSelect: (id: string) => void;
onAskClose: (terminal: Terminal) => void;
}) {
return (
<div
role="button"
tabIndex={0}
onClick={() => 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"
}`}
>
<IconTerminal2 className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="text-sm truncate flex-1">{terminal.label}</span>
{isRunning && (
<span className="text-[10px] font-medium px-1.5 py-0.5 rounded bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 leading-none">
running
</span>
)}
{terminal.closable && (
<Button
variant="ghost"
size="icon-sm"
aria-label={`Close ${terminal.label}`}
className="cursor-pointer h-7 w-7"
onClick={(e) => {
e.stopPropagation();
onAskClose(terminal);
}}
>
<IconX className="h-4 w-4" />
</Button>
)}
</div>
);
}
function CloseTerminalConfirmDialog({
terminal,
onOpenChange,
onConfirm,
}: {
terminal: Terminal | null;
onOpenChange: (open: boolean) => void;
onConfirm: () => void;
}) {
return (
<AlertDialog open={terminal !== null} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Close terminal?</AlertDialogTitle>
<AlertDialogDescription>
{`This stops the “${terminal?.label ?? ""}” shell and any process it's running.`}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel className="cursor-pointer">Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
onOpenChange(false);
onConfirm();
}}
className="cursor-pointer bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
Close terminal
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
const MobileTerminalsList = memo(function MobileTerminalsList({
sessionId,
onClose,
}: {
sessionId: string | null;
onClose: () => void;
}) {
const { terminals, terminalTabValue, addTerminal, removeTerminal, environmentId } =
useMobileTerminals(sessionId);
const { shells } = useUserShells(environmentId);
const setRightPanelActiveTab = useAppStore((s) => s.setRightPanelActiveTab);
const [pendingClose, setPendingClose] = useState<Terminal | null>(null);
const isShellRunning = useCallback(
(id: string) => shells.find((s) => s.terminalId === id)?.running ?? false,
[shells],
);
const handleSelect = useCallback(
(id: string) => {
if (sessionId) setRightPanelActiveTab(sessionId, id);
onClose();
},
[sessionId, setRightPanelActiveTab, onClose],
);
const handleConfirmClose = useCallback(() => {
const t = pendingClose;
if (!t) return;
removeTerminal(t.id);
if (environmentId) {
stopUserShell(environmentId, t.id).catch((err) => {
console.error("Failed to stop terminal:", err);
});
}
setPendingClose(null);
}, [pendingClose, removeTerminal, environmentId]);
const handleAskClose = useCallback((terminal: Terminal) => {
setPendingClose(terminal);
}, []);
if (!sessionId) {
return (
<div className="text-xs text-muted-foreground px-2 py-6 text-center">No active session</div>
);
}
return (
<div className="flex flex-col gap-2 px-1">
<div className="flex items-center justify-between px-1">
<span className="text-xs font-medium text-muted-foreground">
{terminals.length} terminal{terminals.length === 1 ? "" : "s"}
</span>
<Button
size="sm"
variant="outline"
className="h-7 gap-1 cursor-pointer"
onClick={addTerminal}
data-testid="mobile-add-terminal"
>
<IconPlus className="h-4 w-4" />
New terminal
</Button>
</div>
<div className="flex flex-col gap-0.5">
{terminals.length === 0 && (
<div className="text-xs text-muted-foreground px-2 py-4 text-center">
No terminals yet.
</div>
)}
{terminals.map((t) => (
<TerminalRow
key={t.id}
terminal={t}
isActive={t.id === terminalTabValue}
isRunning={isShellRunning(t.id)}
onSelect={handleSelect}
onAskClose={handleAskClose}
/>
))}
</div>
<CloseTerminalConfirmDialog
terminal={pendingClose}
onOpenChange={(open) => {
if (!open) setPendingClose(null);
}}
onConfirm={handleConfirmClose}
/>
</div>
);
});
function useActiveTerminalPillLabel(sessionId: string | null): {
label: string;
count: string | undefined;
} {
const { terminals, terminalTabValue } = useMobileTerminals(sessionId);
const activeIdx = terminals.findIndex((t) => t.id === terminalTabValue);
const idx = activeIdx >= 0 ? activeIdx : 0;
const active = terminals[idx];
const total = terminals.length;
let count: string | undefined;
if (total > 1) count = `${idx + 1}/${total}`;
return { label: active?.label ?? "Terminal", count };
}
export const MobileTerminalsPicker = memo(function MobileTerminalsPicker({
sessionId,
compact,
fullWidth,
}: {
sessionId: string | null;
compact?: boolean;
fullWidth?: boolean;
}) {
const [open, setOpen] = useState(false);
const { label, count } = useActiveTerminalPillLabel(sessionId);
if (!sessionId) return null;
return (
<>
<MobilePillButton
label={label}
count={count}
compact={compact}
fullWidth={fullWidth}
isOpen={open}
onClick={() => setOpen(true)}
data-testid="mobile-terminals-pill"
ariaLabel={`Active terminal: ${label}. Tap to switch.`}
/>
<MobilePickerSheet open={open} onOpenChange={setOpen} title="Terminals">
<MobileTerminalsList sessionId={sessionId} onClose={() => setOpen(false)} />
</MobilePickerSheet>
</>
);
});
@@ -8,9 +8,10 @@ import { TaskChatPanel } from "../task-chat-panel";
import { TaskPlanPanel } from "../task-plan-panel";
import { TaskChangesPanel } from "../task-changes-panel";
import { TaskFilesPanel } from "../task-files-panel";
import { ShellTerminal } from "../shell-terminal";
import { PassthroughTerminal } from "../passthrough-terminal";
import { MobileTerminalKeybar, KEYBAR_HEIGHT_PX } from "./mobile-terminal-keybar";
import { MobileTerminalPane } from "./mobile-terminal-pane";
import { MobileSessionsPicker } from "./mobile-sessions-section";
import { SessionPanelContent } from "@kandev/ui/pannel-session";
import { useSessionLayoutState } from "@/hooks/use-session-layout-state";
import { useVisualViewportOffset } from "@/hooks/use-visual-viewport-offset";
@@ -48,19 +49,25 @@ function MobileChatPanelContent({
sessionId?: string | null;
onOpenFile: (path: string) => void;
}) {
if (activeTaskId && isPassthroughMode) {
if (!activeTaskId) {
return (
<div className="flex-1 min-h-0">
<PassthroughTerminal key={effectiveSessionId} sessionId={sessionId} mode="agent" />
<div className="flex-1 flex items-center justify-center text-muted-foreground">
No task selected
</div>
);
}
if (activeTaskId) {
return <TaskChatPanel sessionId={sessionId} onOpenFile={onOpenFile} />;
}
return (
<div className="flex-1 flex items-center justify-center text-muted-foreground">
No task selected
<div className="flex-1 min-h-0 flex flex-col">
<div className="flex items-center px-1 py-2">
<MobileSessionsPicker taskId={activeTaskId} fullWidth />
</div>
{isPassthroughMode ? (
<div className="flex-1 min-h-0">
<PassthroughTerminal key={effectiveSessionId} sessionId={sessionId} mode="agent" />
</div>
) : (
<TaskChatPanel sessionId={sessionId} onOpenFile={onOpenFile} />
)}
</div>
);
}
@@ -112,7 +119,7 @@ function MobilePanelArea({
}}
>
{currentMobilePanel === "chat" && (
<div className="flex-1 min-h-0 flex flex-col p-2">
<div className="flex-1 min-h-0 flex flex-col px-2 pb-2">
<MobileChatPanelContent
activeTaskId={activeTaskId}
isPassthroughMode={isPassthroughMode}
@@ -147,11 +154,11 @@ function MobilePanelArea({
{currentMobilePanel === "terminal" && (
<div
data-testid="terminal-panel"
className="flex-1 min-h-0 flex flex-col p-2"
className="flex-1 min-h-0 flex flex-col px-2"
style={{ paddingBottom: terminalPaddingBottom }}
>
<SessionPanelContent className="p-0 flex-1 min-h-0">
<ShellTerminal key={effectiveSessionId} sessionId={effectiveSessionId ?? undefined} />
<SessionPanelContent className="p-0 flex-1 min-h-0 flex flex-col">
<MobileTerminalPane key={effectiveSessionId} sessionId={effectiveSessionId} />
</SessionPanelContent>
</div>
)}
@@ -159,6 +166,53 @@ function MobilePanelArea({
);
}
type MobileTopBarStickyProps = {
activeTaskId: string | null;
workspaceId: string | null;
taskTitle?: string;
effectiveSessionId: string | null;
baseBranch?: string;
worktreeBranch?: string | null;
onMenuClick: () => void;
showApproveButton: boolean;
onApprove: () => void;
isRemoteExecutor?: boolean;
remoteExecutorType?: string | null;
remoteExecutorName?: string | null;
remoteState?: string | null;
remoteCreatedAt?: string | null;
remoteCheckedAt?: string | null;
remoteStatusError?: string | null;
};
function MobileTopBarSticky(props: MobileTopBarStickyProps) {
return (
<div
className="fixed top-0 left-0 right-0 z-40 bg-background border-b border-border"
style={{ paddingTop: "env(safe-area-inset-top, 0px)" }}
>
<SessionMobileTopBar
taskId={props.activeTaskId}
workspaceId={props.workspaceId}
taskTitle={props.taskTitle}
sessionId={props.effectiveSessionId}
baseBranch={props.baseBranch}
worktreeBranch={props.worktreeBranch}
onMenuClick={props.onMenuClick}
showApproveButton={props.showApproveButton}
onApprove={props.onApprove}
isRemoteExecutor={props.isRemoteExecutor}
remoteExecutorType={props.remoteExecutorType}
remoteExecutorName={props.remoteExecutorName}
remoteState={props.remoteState}
remoteCreatedAt={props.remoteCreatedAt}
remoteCheckedAt={props.remoteCheckedAt}
remoteStatusError={props.remoteStatusError}
/>
</div>
);
}
function useMobilePanelHandlers({
handleSelectDiff,
handlePanelChange,
@@ -235,29 +289,24 @@ export const SessionMobileLayout = memo(function SessionMobileLayout({
return (
<div className="h-dvh relative bg-background">
{/* Fixed Top Bar */}
<div
className="fixed top-0 left-0 right-0 z-40 bg-background border-b border-border"
style={{ paddingTop: "env(safe-area-inset-top, 0px)" }}
>
<SessionMobileTopBar
taskId={activeTaskId}
taskTitle={taskTitle}
sessionId={effectiveSessionId}
baseBranch={baseBranch}
worktreeBranch={worktreeBranch}
onMenuClick={handleMenuClick}
showApproveButton={showApproveButton}
onApprove={handleApprove}
isRemoteExecutor={isRemoteExecutor}
remoteExecutorType={remoteExecutorType}
remoteExecutorName={remoteExecutorName}
remoteState={remoteState}
remoteCreatedAt={remoteCreatedAt}
remoteCheckedAt={remoteCheckedAt}
remoteStatusError={remoteStatusError}
/>
</div>
<MobileTopBarSticky
activeTaskId={activeTaskId}
workspaceId={workspaceId}
taskTitle={taskTitle}
effectiveSessionId={effectiveSessionId}
baseBranch={baseBranch}
worktreeBranch={worktreeBranch}
onMenuClick={handleMenuClick}
showApproveButton={showApproveButton}
onApprove={handleApprove}
isRemoteExecutor={isRemoteExecutor}
remoteExecutorType={remoteExecutorType}
remoteExecutorName={remoteExecutorName}
remoteState={remoteState}
remoteCreatedAt={remoteCreatedAt}
remoteCheckedAt={remoteCheckedAt}
remoteStatusError={remoteStatusError}
/>
{/* Content Area - fixed height panels that manage their own scrolling */}
<MobilePanelArea
@@ -15,9 +15,11 @@ import {
computeUncommittedStats,
useMobileGitActions,
} from "./session-mobile-top-bar-git-controls";
import { MobileRepoPill } from "./mobile-repo-pill";
type SessionMobileTopBarProps = {
taskId?: string | null;
workspaceId?: string | null;
taskTitle?: string;
sessionId?: string | null;
baseBranch?: string;
@@ -63,6 +65,7 @@ function MobileTaskTitle({
type MobileTopBarActionsProps = {
taskId?: string | null;
workspaceId?: string | null;
isRemoteExecutor?: boolean;
remoteExecutorType?: string | null;
remoteExecutorName?: string | null;
@@ -87,6 +90,7 @@ type MobileTopBarActionsProps = {
function MobileTopBarActions({
taskId,
workspaceId,
isRemoteExecutor,
remoteExecutorType,
remoteExecutorName,
@@ -110,6 +114,7 @@ function MobileTopBarActions({
}: MobileTopBarActionsProps) {
return (
<div className="flex items-center gap-1">
<MobileRepoPill taskId={taskId ?? null} workspaceId={workspaceId ?? null} />
{isRemoteExecutor && (
<RemoteCloudTooltip
taskId={taskId ?? ""}
@@ -156,6 +161,7 @@ function MobileTopBarActions({
export const SessionMobileTopBar = memo(function SessionMobileTopBar({
taskId,
workspaceId,
taskTitle,
sessionId,
baseBranch,
@@ -212,6 +218,7 @@ export const SessionMobileTopBar = memo(function SessionMobileTopBar({
</div>
<MobileTopBarActions
taskId={taskId}
workspaceId={workspaceId}
isRemoteExecutor={isRemoteExecutor}
remoteExecutorType={remoteExecutorType}
remoteExecutorName={remoteExecutorName}
@@ -0,0 +1,375 @@
"use client";
import { useCallback, useMemo, useState } from "react";
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,
Repository,
Task,
WorkflowSnapshot,
} from "@/lib/types/http";
import type { KanbanState } from "@/lib/state/slices";
// Map workflow snapshot to kanban state on workspace switch.
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,
})),
};
}
function sortByUpdatedAtDesc<T extends { updated_at?: string | null }>(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<typeof useAppStoreApi>;
loadTaskSessionsForTask: (
taskId: string,
) => Promise<Array<{ id: string; updated_at?: string | null }>>;
setActiveSession: (taskId: string, sessionId: string) => void;
setActiveTask: (taskId: string) => void;
onOpenChange: (open: boolean) => void;
};
async function switchWorkspace(newWorkspaceId: string, opts: SheetNavOptions) {
const { store, loadTaskSessionsForTask, setActiveSession, setActiveTask, onOpenChange } = opts;
store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: true } }));
try {
const workflowsResponse = await listWorkflows(newWorkspaceId, {
cache: "no-store",
includeHidden: true,
});
const newWorkspaceWorkflows = workflowsResponse.workflows ?? [];
const firstWorkflow = newWorkspaceWorkflows.find((w) => !w.hidden);
if (!firstWorkflow) {
store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: false } }));
return;
}
const snapshot = await fetchWorkflowSnapshot(firstWorkflow.id);
store.setState((state) => ({
...state,
workflows: {
...state.workflows,
items: [
...state.workflows.items.filter(
(w: { workspaceId: string }) => w.workspaceId !== newWorkspaceId,
),
...newWorkspaceWorkflows.map((w) => ({
id: w.id,
workspaceId: w.workspace_id,
name: w.name,
hidden: w.hidden,
})),
],
activeId: firstWorkflow.id,
},
kanban: mapSnapshotToKanban(snapshot, firstWorkflow.id),
}));
const mostRecentTask = sortByUpdatedAtDesc(snapshot.tasks)[0];
if (mostRecentTask) {
const sessions = await loadTaskSessionsForTask(mostRecentTask.id);
const mostRecentSession = sortByUpdatedAtDesc(sessions)[0];
if (mostRecentSession) {
setActiveSession(mostRecentTask.id, mostRecentSession.id);
} else {
setActiveTask(mostRecentTask.id);
}
replaceTaskUrl(mostRecentTask.id);
}
onOpenChange(false);
} catch (error) {
console.error("Failed to switch workspace:", error);
store.setState((state) => ({ ...state, kanban: { ...state.kanban, isLoading: false } }));
}
}
function useWorkspaceAndTaskCreatedActions(opts: SheetNavOptions) {
const { workspaceId, store, setActiveSession, setActiveTask, onOpenChange } = opts;
const handleWorkspaceChange = useCallback(
async (newWorkspaceId: string) => {
if (newWorkspaceId === workspaceId) return;
await switchWorkspace(newWorkspaceId, opts);
},
[workspaceId, opts],
);
const handleTaskCreated = useCallback(
(task: Task, _mode: "create" | "edit", meta?: { taskSessionId?: string | null }) => {
store.setState((state) => {
if (state.kanban.workflowId !== task.workflow_id) return state;
const nextTask = {
id: task.id,
workflowStepId: task.workflow_step_id,
title: task.title,
description: task.description,
position: task.position ?? 0,
state: task.state,
repositoryId: task.repositories?.[0]?.repository_id ?? undefined,
updatedAt: task.updated_at,
primaryExecutorId: task.primary_executor_id ?? undefined,
primaryExecutorType: task.primary_executor_type ?? undefined,
primaryExecutorName: task.primary_executor_name ?? undefined,
isRemoteExecutor: task.is_remote_executor ?? false,
};
return {
...state,
kanban: {
...state.kanban,
tasks: state.kanban.tasks.some(
(item: KanbanState["tasks"][number]) => item.id === task.id,
)
? state.kanban.tasks.map((item: KanbanState["tasks"][number]) =>
item.id === task.id ? nextTask : item,
)
: [...state.kanban.tasks, nextTask],
},
};
});
setActiveTask(task.id);
if (meta?.taskSessionId) {
setActiveSession(task.id, meta.taskSessionId);
}
replaceTaskUrl(task.id);
onOpenChange(false);
},
[store, setActiveTask, setActiveSession, onOpenChange],
);
return { handleWorkspaceChange, handleTaskCreated };
}
export function useSheetActions(workspaceId: string | null, onOpenChange: (open: boolean) => void) {
const setActiveTask = useAppStore((state) => state.setActiveTask);
const setActiveSession = useAppStore((state) => state.setActiveSession);
const store = useAppStoreApi();
const [deletingTaskId, setDeletingTaskId] = useState<string | null>(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,
};
}
@@ -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<T extends { updated_at?: string | null }>(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<typeof useAppStoreApi>;
loadTaskSessionsForTask: (
taskId: string,
) => Promise<Array<{ id: string; updated_at?: string | null }>>;
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<string | null>(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 (
<Sheet open={open} onOpenChange={onOpenChange}>
@@ -488,23 +98,23 @@ export const SessionTaskSwitcherSheet = memo(function SessionTaskSwitcherSheet({
</div>
<div className="pt-2">
<WorkspaceSwitcher
workspaces={workspaces.map((w: Workspace) => ({ 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}
/>
</div>
</SheetHeader>
<div className="flex-1 min-h-0 overflow-y-auto p-2">
<MobileTaskList
tasks={tasksWithRepositories}
activeTaskId={activeTaskId}
selectedTaskId={selectedTaskId}
onSelectTask={handleSelectTask}
onArchiveTask={handleArchiveTask}
onDeleteTask={handleDeleteTask}
deletingTaskId={deletingTaskId}
isLoading={kanbanIsLoading}
tasks={data.tasksWithRepositories}
activeTaskId={data.activeTaskId}
selectedTaskId={data.selectedTaskId}
onSelectTask={actions.handleSelectTask}
onArchiveTask={actions.handleArchiveTask}
onDeleteTask={actions.handleDeleteTask}
deletingTaskId={actions.deletingTaskId}
isLoading={data.kanbanIsLoading}
/>
</div>
</SheetContent>
@@ -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}
/>
<TaskArchiveConfirmDialog
open={archivingTask !== null}
open={actions.archivingTask !== null}
onOpenChange={(open) => {
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}
/>
</Sheet>
);
@@ -31,6 +31,14 @@ type BaseProps = {
autoFocus?: boolean;
pendingCommand?: string | null;
onCommandSent?: () => void;
/** Called once the xterm instance is created. Mobile uses this to register
* the active key-bar input target. Desktop ignores. */
onXtermReady?: (xterm: Terminal) => void;
/** Skip the WebGL renderer addon and use xterm's canvas renderer instead.
* WebGL miscomputes glyph atlas scaling on mobile (notably after a
* desktop→mobile responsive switch) and renders text at multiples of the
* intended font size. Mobile callers should pass true. */
disableWebgl?: boolean;
};
type AgentTerminalProps = BaseProps & { mode: "agent"; sessionId?: string | null; label?: string };
type ShellTerminalProps = BaseProps & {
@@ -119,7 +127,8 @@ function computeCanConnect(
// eslint-disable-next-line max-lines-per-function -- wires many hooks + refs; each block is already its own hook
export function PassthroughTerminal(props: PassthroughTerminalProps) {
const { mode, label, autoFocus, pendingCommand, onCommandSent } = props;
const { mode, label, autoFocus, pendingCommand, onCommandSent, onXtermReady, disableWebgl } =
props;
const terminalId = mode === "shell" ? props.terminalId : undefined;
const environmentId = mode === "shell" ? props.environmentId : undefined;
const refs = useTerminalRefs();
@@ -137,7 +146,10 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
const wsBaseUrl = useWsBaseUrl();
const [isTerminalReady, setIsTerminalReady] = useState(false);
const onTerminalReady = useCallback(() => setIsTerminalReady(true), []);
const onTerminalReady = useCallback(() => {
setIsTerminalReady(true);
if (xtermRef.current) onXtermReady?.(xtermRef.current);
}, [onXtermReady, xtermRef]);
// Track which terminal target has an active WebSocket connection. The loading
// overlay resets on target switches without needing a separate setState effect.
@@ -186,6 +198,7 @@ export function PassthroughTerminal(props: PassthroughTerminalProps) {
linkHandler,
fontFamily: buildTerminalFontFamily(terminalFontFamily),
fontSize: terminalFontSize ?? undefined,
disableWebgl,
onToggleBottomTerminal: toggleBottomTerminal,
sendInput,
keyboardShortcutsRef,
@@ -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,
@@ -0,0 +1,40 @@
"use client";
import { useEffect, useRef } from "react";
import { useTerminals } from "./use-terminals";
import { useUserShells } from "./use-user-shells";
import { useAppStore } from "@/components/state-provider";
/**
* Mobile wrapper around `useTerminals`. Auto-creates a first shell when the
* server-side shell list loads empty so the user always sees one terminal
* mounted by default. Returns the same interface as `useTerminals`.
*/
export function useMobileTerminals(sessionId: string | null) {
const environmentId = useAppStore((s) =>
sessionId ? (s.environmentIdBySessionId[sessionId] ?? null) : null,
);
const result = useTerminals({ sessionId, environmentId });
// Read user-shell loaded flag directly so the auto-create trigger has a
// primitive dependency (depending on the result object would re-run the
// effect every render and continuously cancel the timer).
const { isLoaded: shellsLoaded, shells } = useUserShells(environmentId);
const addTerminalRef = useRef(result.addTerminal);
useEffect(() => {
addTerminalRef.current = result.addTerminal;
}, [result.addTerminal]);
const autoCreatedRef = useRef<string | null>(null);
useEffect(() => {
if (!environmentId || !shellsLoaded) return;
if (autoCreatedRef.current === environmentId) return;
if (shells.length > 0) {
autoCreatedRef.current = environmentId;
return;
}
autoCreatedRef.current = environmentId;
addTerminalRef.current();
}, [environmentId, shellsLoaded, shells.length]);
return { ...result, environmentId };
}
+4 -11
View File
@@ -19,6 +19,7 @@ import type {
} from "@/lib/types/github";
import type { SystemHealthResponse } from "@/lib/types/health";
import type { UISliceActions as UIA } from "./slices/ui/types";
import type * as UISliceTypes from "./slices/ui/types";
import { mergeInitialState } from "./default-state";
import {
createKanbanSlice,
@@ -359,16 +360,10 @@ export type AppState = {
setConnectionStatus: (status: ConnectionState["status"], error?: string | null) => void;
setMobileKanbanColumnIndex: (index: number) => void;
setMobileKanbanMenuOpen: (open: boolean) => void;
setMobileSessionPanel: (
sessionId: string,
panel: import("./slices/ui/types").MobileSessionPanel,
) => void;
setMobileSessionPanel: (sessionId: string, panel: UISliceTypes.MobileSessionPanel) => void;
setMobileSessionTaskSwitcherOpen: (open: boolean) => void;
setPlanMode: (sessionId: string, enabled: boolean) => void;
setActiveDocument: (
sessionId: string,
doc: import("./slices/ui/types").ActiveDocument | null,
) => void;
setActiveDocument: (sessionId: string, doc: UISliceTypes.ActiveDocument | null) => void;
setSystemHealth: (response: SystemHealthResponse) => void;
setSystemHealthLoading: (loading: boolean) => void;
invalidateSystemHealth: () => void;
@@ -383,9 +378,7 @@ export type AppState = {
closeConfigChatSession: (sessionId: string) => void;
setActiveConfigChatSession: (sessionId: string) => void;
renameConfigChatSession: (sessionId: string, name: string) => void;
setSessionFailureNotification: (
n: import("./slices/ui/types").SessionFailureNotification | null,
) => void;
setSessionFailureNotification: (n: UISliceTypes.SessionFailureNotification | null) => void;
toggleBottomTerminal: () => void;
openBottomTerminalWithCommand: (command: string) => void;
clearBottomTerminalCommand: () => void;
@@ -0,0 +1,53 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import {
setActiveTerminalSender,
getActiveTerminalSender,
subscribeActiveTerminalSender,
} from "./mobile-active-terminal";
describe("mobile active terminal sender registry", () => {
beforeEach(() => {
setActiveTerminalSender(null);
});
it("returns null when no sender is registered", () => {
expect(getActiveTerminalSender()).toBeNull();
});
it("returns the registered sender", () => {
const sender = vi.fn();
setActiveTerminalSender(sender);
expect(getActiveTerminalSender()).toBe(sender);
sender("hi");
expect(sender).toHaveBeenCalledWith("hi");
});
it("replaces a previously registered sender", () => {
const a = vi.fn();
const b = vi.fn();
setActiveTerminalSender(a);
setActiveTerminalSender(b);
expect(getActiveTerminalSender()).toBe(b);
});
it("clears the sender when null is set", () => {
setActiveTerminalSender(vi.fn());
setActiveTerminalSender(null);
expect(getActiveTerminalSender()).toBeNull();
});
it("notifies subscribers on changes only", () => {
const listener = vi.fn();
const unsubscribe = subscribeActiveTerminalSender(listener);
const sender = vi.fn();
setActiveTerminalSender(sender);
expect(listener).toHaveBeenCalledTimes(1);
setActiveTerminalSender(sender); // no-op (same value)
expect(listener).toHaveBeenCalledTimes(1);
setActiveTerminalSender(null);
expect(listener).toHaveBeenCalledTimes(2);
unsubscribe();
setActiveTerminalSender(vi.fn());
expect(listener).toHaveBeenCalledTimes(2);
});
});
@@ -0,0 +1,33 @@
/**
* Tracks the current input target for the mobile terminal key-bar.
*
* Mobile renders multiple terminals via PassthroughTerminal, each with its own
* WebSocket. The shared key-bar (Ctrl, ^C, arrow keys, etc.) needs to dispatch
* keystrokes to whichever terminal is on screen, not the per-session default
* shell. The active terminal registers a `paste` sender on mount; the key-bar
* reads from this registry and falls back to the default shell otherwise.
*/
type Sender = (data: string) => void;
let activeSender: Sender | null = null;
const listeners = new Set<() => void>();
function notify(): void {
for (const l of listeners) l();
}
export function setActiveTerminalSender(sender: Sender | null): void {
if (activeSender === sender) return;
activeSender = sender;
notify();
}
export function getActiveTerminalSender(): Sender | null {
return activeSender;
}
export function subscribeActiveTerminalSender(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
+20 -7
View File
@@ -1,5 +1,6 @@
import { getWebSocketClient } from "@/lib/ws/connection";
import { applyShellModifiers } from "./apply-shell-modifiers";
import { getActiveTerminalSender } from "./mobile-active-terminal";
import { useShellModifiersStore, isActive } from "./shell-modifiers";
/**
@@ -9,20 +10,32 @@ import { useShellModifiersStore, isActive } from "./shell-modifiers";
* Used by both the virtual key-bar and xterm's own `onData` callback so that
* a Ctrl latch set from the key-bar modifies the next character the user
* types on the OS keyboard — which is the whole point of the modifier.
*
* Mobile multi-terminal: when a PassthroughTerminal is registered as the
* active key-bar target, route input through it (xterm.paste → onData → its
* dedicated WS) instead of the per-session default shell. Falls back to the
* default `shell.input` action when no active terminal is registered.
*/
export function sendShellInput(sessionId: string, data: string): void {
if (!data) return;
const client = getWebSocketClient();
if (!client) return; // keep modifiers armed; the user can retry once reconnected
const store = useShellModifiersStore.getState();
const ctrlActive = isActive(store.ctrl);
const shiftActive = isActive(store.shift);
const transformed = applyShellModifiers(data, { ctrl: ctrlActive, shift: shiftActive });
client.send({
type: "request",
action: "shell.input",
payload: { session_id: sessionId, data: transformed },
});
const activeSender = getActiveTerminalSender();
if (activeSender) {
activeSender(transformed);
} else {
const client = getWebSocketClient();
if (!client) return; // keep modifiers armed; user can retry once reconnected
client.send({
type: "request",
action: "shell.input",
payload: { session_id: sessionId, data: transformed },
});
}
if (ctrlActive) store.consumeCtrl();
if (shiftActive) store.consumeShift();
}