Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
import {
createContext,
memo,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import type { CSSProperties, MouseEvent as ReactMouseEvent, ReactNode } from "react";
import {
Archive,
ArchiveRestore,
AlertTriangle,
ChevronDown,
ListChecks,
MessageCircleDashed,
MoreHorizontal,
MoveRight,
PanelsTopLeft,
Pencil,
Pin,
PinOff,
Plus,
Square,
SquareCheckBig,
SquareMinus,
Trash2,
Ungroup,
Unplug,
X,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
HoverHint,
} from "@/components/ui/tooltip";
import { MAX_WORKBENCH_PANES } from "@/components/workbench/workbench-model";
import { SidebarTopicRename } from "@/components/SidebarTopicRename";
import { ArchiveConfirm } from "@/components/ArchiveConfirm";
import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus";
import { LoadingRing } from "@/components/ui/loading-ring";
import {
SIDEBAR_SELECTION_ITEM_CLASS,
SidebarSelectionHighlight,
} from "@/components/SidebarSelectionHighlight";
import {
COLLAPSED_CHATS_VISIBLE_COUNT,
displayTitle,
groupSessions,
isCollapsedProject,
isFoldableChatsGroup,
isFoldedChatsGroup,
limitGroups,
visibleSessionsForGroup,
type ChatGroupLabels,
} from "@/lib/chat-groups";
import { deriveTemporaryChatTitle } from "@/lib/temporary-chat";
import { sessionHandleColor } from "@/lib/session-handle";
import {
clearDraggedSession,
hasDraggedSession,
readDraggedSession,
writeDraggedSession,
} from "@/lib/session-drag";
import { cn } from "@/lib/utils";
import type { ChatSummary, SidebarDensity, SidebarSortMode } from "@/lib/types";
const INITIAL_VISIBLE_SESSIONS = 160;
const VISIBLE_SESSIONS_INCREMENT = 160;
const ACTION_MENU_CONTENT_CLASS = "w-[11rem] min-w-[11rem] whitespace-nowrap";
const COLLAPSED_PANE_GROUPS_STORAGE_KEY = "nanobot-webui.collapsed-pane-groups.v1";
const DETACH_PANE_DROP_TARGET = "__sidebar-standalone__";
interface SidebarActionMenuController {
openId: string | null;
onOpenChange: (id: string, open: boolean) => void;
openFromContextMenu: (event: ReactMouseEvent<HTMLElement>, id: string) => void;
}
const SidebarActionMenuEscapeContext = createContext<(() => void) | undefined>(undefined);
function SidebarActionMenuContent({
children,
portalContainer,
}: {
children: ReactNode;
portalContainer?: HTMLElement | null;
}) {
const restoreFocusOnEscape = useRef(false);
const markEscape = () => { restoreFocusOnEscape.current = true; };
return (
<SidebarActionMenuEscapeContext.Provider value={markEscape}>
<DropdownMenuContent
align="end"
className={ACTION_MENU_CONTENT_CLASS}
portalContainer={portalContainer}
onEscapeKeyDown={markEscape}
onCloseAutoFocus={(event) => {
// Actions can open a dialog or remove the trigger. Only Escape returns
// to it; Radix still owns the trigger and outside-interaction handling.
if (!restoreFocusOnEscape.current) event.preventDefault();
restoreFocusOnEscape.current = false;
}}
>
{children}
</DropdownMenuContent>
</SidebarActionMenuEscapeContext.Provider>
);
}
function SidebarSessionHandle({ handle }: { handle: ChatSummary["handle"] }) {
if (!handle) return null;
return (
<span
data-sidebar-session-handle
className="flex max-w-20 shrink-0 items-center overflow-hidden whitespace-nowrap font-mono text-[11px] font-medium leading-5"
>
<span
data-sidebar-session-handle-underline
className="inline border-b-2 text-sidebar-muted-foreground"
style={{
"--sidebar-session-handle-color": sessionHandleColor(handle.id),
borderBottomColor: "var(--sidebar-session-handle-color)",
} as CSSProperties}
>
@{handle.name}
</span>
</span>
);
}
function readCollapsedPaneGroups(): Set<string> {
try {
const value = JSON.parse(window.localStorage.getItem(
COLLAPSED_PANE_GROUPS_STORAGE_KEY,
) ?? "[]") as unknown;
return new Set(Array.isArray(value)
? value.filter((key): key is string => typeof key === "string")
: []);
} catch {
return new Set();
}
}
function writeCollapsedPaneGroups(groups: ReadonlySet<string>): void {
try {
window.localStorage.setItem(
COLLAPSED_PANE_GROUPS_STORAGE_KEY,
JSON.stringify(Array.from(groups)),
);
} catch {
// Local UI preferences should not block the sidebar.
}
}
interface PaneGroupTarget {
key: string;
title: string;
paneCount: number;
atCapacity: boolean;
}
export interface SidebarPaneGroup {
tabKey: string;
title: string;
activePaneKey: string;
visible?: boolean;
panes: Array<{
key: string;
chatId: string;
title: string;
handle?: ChatSummary["handle"];
projectLocked?: ChatSummary["projectLocked"];
}>;
}
export interface SidebarDeleteItem {
key: string;
label: string;
}
export type SidebarDeleteDecision = (confirmed: boolean) => void;
function droppablePaneKey(
dataTransfer: DataTransfer,
group: SidebarPaneGroup,
): string | null {
if (group.panes.length >= MAX_WORKBENCH_PANES
|| !hasDraggedSession(dataTransfer)) return null;
const paneKey = readDraggedSession(dataTransfer);
if (!paneKey || group.panes.some((pane) => pane.key === paneKey)) return null;
return paneKey;
}
function detachablePaneSource(
dataTransfer: DataTransfer,
groups: Record<string, SidebarPaneGroup>,
): { paneKey: string; tabKey: string } | null {
if (!hasDraggedSession(dataTransfer)) return null;
const paneKey = readDraggedSession(dataTransfer);
if (!paneKey) return null;
const source = Object.values(groups).find((group) => (
(group.visible ?? group.panes.length > 1)
&& group.panes.some((pane) => pane.key === paneKey)
));
return source ? { paneKey, tabKey: source.tabKey } : null;
}
function isWorkbenchTabSurface(target: EventTarget | null): boolean {
return target instanceof Element
&& target.closest("[data-workbench-tab-surface]") !== null;
}
interface ChatListProps {
sessions: ChatSummary[];
temporarySessions?: ChatSummary[];
activeKey: string | null;
onSelect: (key: string) => void;
onCloseTemporaryChat?: (key: string) => void;
onRequestDelete: (key: string, label: string, onDecision?: SidebarDeleteDecision) => void;
onRequestDeleteMany?: (items: SidebarDeleteItem[], onDecision?: SidebarDeleteDecision) => void;
onTogglePin: (key: string) => void;
onRequestRename: (key: string, title: string) => Promise<void>;
onRequestRenameTab?: (key: string, label: string) => void;
onToggleArchive: (key: string) => void;
onArchiveMany?: (keys: string[], archive: boolean) => void;
paneGroups?: Record<string, SidebarPaneGroup>;
onSelectPane?: (tabKey: string, paneKey: string) => void;
onCreateTab?: (paneKey: string) => void;
onDetachPane?: (tabKey: string, paneKey: string) => void;
onDissolveTab?: (tabKey: string) => void;
onAttachPane?: (
paneKey: string,
tabKey: string,
) => void;
onToggleGroup?: (groupId: string) => void;
onRequestRenameProject?: (projectKey: string, label: string) => void;
onNewChatInProject?: (projectPath: string, projectName: string) => void;
pinnedKeys?: string[];
archivedKeys?: string[];
pinnedPaneKeys?: string[];
archivedPaneKeys?: string[];
sessionOrder?: string[];
titleOverrides?: Record<string, string>;
projectNameOverrides?: Record<string, string>;
collapsedGroups?: Record<string, boolean>;
runningChatIds?: string[];
updatedChatIds?: string[];
recoveryChatIds?: string[];
density?: SidebarDensity;
sort?: SidebarSortMode;
showArchived?: boolean;
defaultWorkspacePath?: string | null;
actionMenuPortalContainer?: HTMLElement | null;
loading?: boolean;
initialLoading?: boolean;
emptyLabel?: string;
}
export const ChatList = memo(function ChatList({
sessions,
temporarySessions = [],
activeKey,
onSelect,
onCloseTemporaryChat,
onRequestDelete,
onRequestDeleteMany,
onTogglePin,
onRequestRename,
onRequestRenameTab,
onToggleArchive,
onArchiveMany,
paneGroups = {},
onSelectPane,
onCreateTab,
onDetachPane,
onDissolveTab,
onAttachPane,
onToggleGroup,
onRequestRenameProject,
onNewChatInProject,
pinnedKeys = [],
archivedKeys = [],
pinnedPaneKeys = [],
archivedPaneKeys = [],
sessionOrder = [],
titleOverrides = {},
projectNameOverrides = {},
collapsedGroups = {},
runningChatIds = [],
updatedChatIds = [],
recoveryChatIds = [],
density = "comfortable",
sort = "updated_desc",
showArchived = false,
defaultWorkspacePath,
actionMenuPortalContainer,
loading,
initialLoading = loading,
emptyLabel,
}: ChatListProps) {
const { t } = useTranslation();
const [visibleLimit, setVisibleLimit] = useState(INITIAL_VISIBLE_SESSIONS);
const scrollViewportRef = useRef<HTMLDivElement>(null);
const selectionBarRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const viewport = scrollViewportRef.current;
if (!viewport) return;
const updateEdges = () => {
const remaining = viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop;
viewport.style.setProperty("--sidebar-fade-top", `${Math.min(8, Math.max(0, viewport.scrollTop))}px`);
viewport.style.setProperty("--sidebar-fade-bottom", `${Math.min(8, Math.max(0, remaining))}px`);
};
let idleTimer: ReturnType<typeof setTimeout> | undefined;
const onScroll = () => {
updateEdges();
viewport.dataset.scrolling = "true";
clearTimeout(idleTimer);
idleTimer = setTimeout(() => { delete viewport.dataset.scrolling; }, 800);
};
updateEdges();
viewport.addEventListener("scroll", onScroll, { passive: true });
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updateEdges);
observer?.observe(viewport);
if (viewport.firstElementChild) observer?.observe(viewport.firstElementChild);
return () => {
viewport.removeEventListener("scroll", onScroll);
clearTimeout(idleTimer);
delete viewport.dataset.scrolling;
observer?.disconnect();
};
}, [loading, sessions.length, temporarySessions.length]);
const layoutRowRefs = useRef(new Map<string, HTMLElement>());
const pendingLayoutRectsRef = useRef<Map<string, DOMRect> | null>(null);
const layoutAnimationsRef = useRef(new Map<string, Animation>());
const [collapsedPaneGroups, setCollapsedPaneGroups] = useState<Set<string>>(
readCollapsedPaneGroups,
);
const [paneDropTarget, setPaneDropTarget] = useState<string | null>(null);
const [deleteSelectionMode, setDeleteSelectionMode] = useState(false);
const [deleteConfirmationPending, setDeleteConfirmationPending] = useState(false);
const [pendingArchive, setPendingArchive] = useState<{
keys: string[];
archive: boolean;
} | null>(null);
const [openActionMenuId, setOpenActionMenuId] = useState<string | null>(null);
const [renamingTopic, setRenamingTopic] = useState<{ key: string } | null>(null);
const renamingKey = renamingTopic?.key ?? null;
const previousRenamingKeyRef = useRef<string | null>(null);
const beginRename = (key: string) => setRenamingTopic({ key });
const endRename = () => {
setRenamingTopic((current) => current === renamingTopic ? null : current);
};
useLayoutEffect(() => {
const previousKey = previousRenamingKeyRef.current;
previousRenamingKeyRef.current = renamingKey;
if (renamingKey !== null || previousKey === null) return;
const row = Array.from(scrollViewportRef.current?.querySelectorAll<HTMLElement>(
"[data-chat-row]",
) ?? []).find((element) => element.dataset.chatRow === previousKey);
row?.querySelector<HTMLButtonElement>("button")?.focus({ preventScroll: true });
}, [renamingKey]);
const [selectedDeleteKeys, setSelectedDeleteKeys] = useState<Set<string>>(
() => new Set(),
);
const deleteSelectionAnchorRef = useRef<string | null>(null);
const selectionConfirmationPending = pendingArchive !== null || deleteConfirmationPending;
const closeDeleteSelection = useCallback(() => {
setDeleteSelectionMode(false);
setSelectedDeleteKeys(new Set());
deleteSelectionAnchorRef.current = null;
}, []);
useEffect(() => {
const clearPaneDropTarget = () => setPaneDropTarget(null);
window.addEventListener("dragend", clearPaneDropTarget);
window.addEventListener("drop", clearPaneDropTarget);
return () => {
window.removeEventListener("dragend", clearPaneDropTarget);
window.removeEventListener("drop", clearPaneDropTarget);
};
}, []);
const deleteItemsByKey = useMemo(() => {
const items = new Map<string, SidebarDeleteItem>();
for (const group of Object.values(paneGroups)) {
for (const pane of group.panes) {
items.set(pane.key, { key: pane.key, label: pane.title });
}
}
for (const session of sessions) {
if (items.has(session.key)) continue;
items.set(session.key, {
key: session.key,
label: displayTitle(session, titleOverrides, t("chat.newChat")),
});
}
return items;
}, [paneGroups, sessions, t, titleOverrides]);
const archivableKeys = useMemo(() => {
const keys = new Set(sessions
.filter((session) => session.projectLocked !== false)
.map((session) => session.key));
for (const group of Object.values(paneGroups)) {
for (const pane of group.panes) {
if (pane.projectLocked === true) keys.add(pane.key);
else keys.delete(pane.key);
}
}
return keys;
}, [paneGroups, sessions]);
const paneGroupTargets = useMemo(() => Array.from(new Map(
Object.values(paneGroups)
.filter((group) => group.visible ?? group.panes.length > 1)
.map((group) => [group.tabKey, {
key: group.tabKey,
title: group.title,
paneCount: group.panes.length,
atCapacity: group.panes.length >= MAX_WORKBENCH_PANES,
}]),
).values()), [paneGroups]);
const labels = useMemo<ChatGroupLabels>(() => ({
pinned: t("chat.groups.pinned"),
all: t("chat.groups.all"),
today: t("chat.groups.today"),
yesterday: t("chat.groups.yesterday"),
earlier: t("chat.groups.earlier"),
archived: t("chat.groups.archived"),
projects: t("chat.groups.projects"),
fallbackTitle: t("chat.newChat"),
}), [t]);
const groups = useMemo(
() => groupSessions(sessions, labels, {
pinnedKeys,
archivedKeys,
titleOverrides,
projectNameOverrides,
sessionOrder,
showArchived,
sort,
defaultWorkspacePath,
}),
[
archivedKeys,
labels,
pinnedKeys,
sessions,
showArchived,
sort,
titleOverrides,
projectNameOverrides,
sessionOrder,
defaultWorkspacePath,
],
);
const limitedGroups = useMemo(
() => limitGroups(groups, visibleLimit, activeKey, collapsedGroups),
[activeKey, collapsedGroups, groups, visibleLimit],
);
const totalSessionCount = useMemo(
() => groups.reduce(
(total, group) =>
total + (isCollapsedProject(group, collapsedGroups) ? 0 : group.sessions.length),
0,
),
[collapsedGroups, groups],
);
const visibleSessionCount = useMemo(
() => limitedGroups.reduce((total, group) => total + group.sessions.length, 0),
[limitedGroups],
);
const pinned = useMemo(() => new Set(pinnedKeys), [pinnedKeys]);
const archived = useMemo(() => new Set(archivedKeys), [archivedKeys]);
const pinnedPanes = useMemo(() => new Set(pinnedPaneKeys), [pinnedPaneKeys]);
const archivedPanes = useMemo(() => new Set(archivedPaneKeys), [archivedPaneKeys]);
const hiddenSessionCount = Math.max(0, totalSessionCount - visibleSessionCount);
const handleActionMenuOpenChange = useCallback((id: string, open: boolean) => {
setOpenActionMenuId((current) => {
if (open) return id;
return current === id ? null : current;
});
}, []);
const openActionMenuFromContextMenu = useCallback((
event: ReactMouseEvent<HTMLElement>,
id: string,
) => {
event.preventDefault();
event.stopPropagation();
if (deleteSelectionMode) return;
setOpenActionMenuId(id);
}, [deleteSelectionMode]);
const actionMenus: SidebarActionMenuController = {
openId: openActionMenuId,
onOpenChange: handleActionMenuOpenChange,
openFromContextMenu: openActionMenuFromContextMenu,
};
useEffect(() => {
setVisibleLimit(INITIAL_VISIBLE_SESSIONS);
}, [showArchived, sort]);
useEffect(() => {
if (!deleteSelectionMode) return;
setOpenActionMenuId(null);
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape" || selectionConfirmationPending) return;
closeDeleteSelection();
};
const onClick = (event: MouseEvent) => {
if (selectionConfirmationPending) return;
const target = event.target;
if (target instanceof Node && selectionBarRef.current?.contains(target)) return;
const row = target instanceof Element
? target.closest("[data-chat-row], [data-workbench-tab]")
: null;
if (row && scrollViewportRef.current?.contains(row)) return;
closeDeleteSelection();
};
window.addEventListener("keydown", onKeyDown);
document.addEventListener("click", onClick, true);
return () => {
window.removeEventListener("keydown", onKeyDown);
document.removeEventListener("click", onClick, true);
};
}, [closeDeleteSelection, deleteSelectionMode, selectionConfirmationPending]);
useEffect(() => {
writeCollapsedPaneGroups(collapsedPaneGroups);
}, [collapsedPaneGroups]);
useEffect(() => {
if (loading) return;
setCollapsedPaneGroups((current) => {
const next = new Set(Array.from(current).filter((key) => (
paneGroups[key]?.visible ?? ((paneGroups[key]?.panes.length ?? 0) > 1)
)));
if (next.size === current.size && Array.from(next).every((key) => current.has(key))) {
return current;
}
return next;
});
}, [loading, paneGroups]);
const measureLayoutRows = useCallback(() => {
const rects = new Map<string, DOMRect>();
for (const [key, row] of layoutRowRefs.current) {
rects.set(key, row.getBoundingClientRect());
}
return rects;
}, []);
const captureLayout = useCallback(() => {
for (const animation of layoutAnimationsRef.current.values()) animation.cancel();
layoutAnimationsRef.current.clear();
pendingLayoutRectsRef.current = measureLayoutRows();
}, [measureLayoutRows]);
const togglePaneGroup = useCallback((key: string) => {
captureLayout();
setCollapsedPaneGroups((current) => {
const next = new Set(current);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
}, [captureLayout]);
const toggleProjectGroup = useCallback((key: string) => {
if (!onToggleGroup) return;
captureLayout();
onToggleGroup(key);
}, [captureLayout, onToggleGroup]);
useLayoutEffect(() => {
const previousRects = pendingLayoutRectsRef.current;
if (!previousRects) return;
pendingLayoutRectsRef.current = null;
const nextRects = measureLayoutRows();
const reduceMotion = typeof window.matchMedia === "function"
&& window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if (reduceMotion) return;
for (const [key, nextRect] of nextRects) {
const previousRect = previousRects.get(key);
const row = layoutRowRefs.current.get(key);
if (!previousRect || !row || typeof row.animate !== "function") continue;
const deltaY = previousRect.top - nextRect.top;
if (Math.abs(deltaY) < 0.5) continue;
const animation = row.animate(
[
{ transform: `translateY(${deltaY}px)` },
{ transform: "translateY(0)" },
],
{
duration: 180,
easing: "cubic-bezier(0.2, 0, 0, 1)",
},
);
layoutAnimationsRef.current.set(key, animation);
animation.addEventListener("finish", () => {
if (layoutAnimationsRef.current.get(key) === animation) {
layoutAnimationsRef.current.delete(key);
}
}, { once: true });
}
}, [collapsedGroups, collapsedPaneGroups, measureLayoutRows]);
useEffect(() => () => {
for (const animation of layoutAnimationsRef.current.values()) animation.cancel();
}, []);
if (initialLoading && sessions.length === 0 && temporarySessions.length === 0) {
return (
<SkeletonStatus label={t("chat.loading")} className="px-2 py-1.5">
<div className="flex h-8 items-center px-2"><div className="h-2.5 w-14 rounded bg-sidebar-muted-foreground/15" /></div>
<div className="space-y-0.5">
{[64, 76, 56, 70, 60, 72].map((width, index) => (
<div key={index} data-chat-skeleton-row className={cn("flex items-center gap-1 px-2", density === "compact" ? "h-[30px]" : "h-[34px]", "[@media(pointer:coarse)]:h-11")}>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<div className="h-2.5 w-10 shrink-0 rounded bg-sidebar-muted-foreground/15" />
<div className="h-3 rounded bg-sidebar-muted-foreground/20" style={{ width: `${width}%` }} />
</div>
<div className="h-4 w-4 shrink-0" /><div className="h-6 w-6 shrink-0" />
</div>
))}
</div>
</SkeletonStatus>
);
}
if (sessions.length === 0 && temporarySessions.length === 0) {
return (
<div className="px-3 py-6 text-[12px] leading-5 text-sidebar-muted-foreground">
{emptyLabel ?? t("chat.noSessions")}
</div>
);
}
const running = new Set(runningChatIds);
const updated = new Set(updatedChatIds);
const recovery = new Set(recoveryChatIds);
const compact = density === "compact";
const firstProjectGroupIndex = limitedGroups.findIndex((group) => group.kind === "project");
const selectableDeleteKeys = Array.from(new Set(limitedGroups.flatMap((group) => (
group.sessions.flatMap((session) => {
const paneGroup = paneGroups[session.key];
const isWorkbenchTab = paneGroup?.visible
?? ((paneGroup?.panes.length ?? 0) > 1);
return isWorkbenchTab
? paneGroup?.panes.map((pane) => pane.key) ?? [session.key]
: [session.key];
})
))));
const beginDeleteSelection = (keys: string[]) => {
const validKeys = keys.filter((key) => deleteItemsByKey.has(key));
setDeleteSelectionMode(true);
setSelectedDeleteKeys(new Set(validKeys));
deleteSelectionAnchorRef.current = validKeys[0] ?? null;
};
const toggleDeleteSelection = (
keys: string[],
shiftKey = false,
targetKey = keys[0],
) => {
if (selectionConfirmationPending) return;
const validKeys = keys.filter((key) => deleteItemsByKey.has(key));
const anchorKey = deleteSelectionAnchorRef.current;
const range = shiftKey && anchorKey && targetKey
? selectionRange(selectableDeleteKeys, anchorKey, targetKey)
: null;
setSelectedDeleteKeys((current) => {
const next = new Set(current);
if (range) {
for (const key of range) next.add(key);
for (const key of validKeys) next.add(key);
return next;
}
const remove = validKeys.length > 0 && validKeys.every((key) => next.has(key));
for (const key of validKeys) {
if (remove) next.delete(key);
else next.add(key);
}
return next;
});
if (!range) deleteSelectionAnchorRef.current = targetKey ?? null;
};
const requestDeleteItems = (items: SidebarDeleteItem[], onDecision?: SidebarDeleteDecision) => {
if (items.length === 0) return;
if (onRequestDeleteMany) onRequestDeleteMany(items, onDecision);
else if (items.length === 1) onRequestDelete(items[0].key, items[0].label, onDecision);
};
const requestDeleteKeys = (keys: string[], onDecision?: SidebarDeleteDecision) => {
requestDeleteItems(keys
.map((key) => deleteItemsByKey.get(key))
.filter((item): item is SidebarDeleteItem => item !== undefined), onDecision);
};
const confirmDeleteSelection = () => {
setDeleteConfirmationPending(true);
requestDeleteKeys(Array.from(selectedDeleteKeys), (confirmed) => {
setDeleteConfirmationPending(false);
if (confirmed) closeDeleteSelection();
});
};
const selectedArchiveKeys = Array.from(selectedDeleteKeys).filter((key) => archivableKeys.has(key));
const allSelectedArchived = selectedArchiveKeys.length > 0
&& selectedArchiveKeys.every((key) => archivedPanes.has(key) || archived.has(key));
return (
<div ref={scrollViewportRef} className="sidebar-scroll-fade sidebar-scrollbar h-full min-h-0 min-w-0 overflow-x-hidden overflow-y-auto overscroll-contain pb-2">
<SidebarSelectionHighlight
scope="chats"
activeId={activeKey}
targetSelector="[data-chat-row]:has([aria-current])"
data-chat-list-content
data-pane-detach-target={
paneDropTarget === DETACH_PANE_DROP_TARGET ? "true" : undefined
}
onDragEnter={(event) => {
if (isWorkbenchTabSurface(event.target)) {
setPaneDropTarget((current) => (
current === DETACH_PANE_DROP_TARGET ? null : current
));
return;
}
const source = onDetachPane && !deleteSelectionMode
? detachablePaneSource(event.dataTransfer, paneGroups)
: null;
if (!source) return;
event.preventDefault();
event.dataTransfer.dropEffect = "move";
setPaneDropTarget(DETACH_PANE_DROP_TARGET);
}}
onDragOver={(event) => {
if (isWorkbenchTabSurface(event.target)) {
setPaneDropTarget((current) => (
current === DETACH_PANE_DROP_TARGET ? null : current
));
return;
}
const source = onDetachPane && !deleteSelectionMode
? detachablePaneSource(event.dataTransfer, paneGroups)
: null;
if (!source) return;
event.preventDefault();
event.dataTransfer.dropEffect = "move";
setPaneDropTarget(DETACH_PANE_DROP_TARGET);
}}
onDragLeave={(event) => {
const nextTarget = event.relatedTarget;
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
setPaneDropTarget((current) => (
current === DETACH_PANE_DROP_TARGET ? null : current
));
}}
onDrop={(event) => {
if (isWorkbenchTabSurface(event.target)) return;
const source = onDetachPane && !deleteSelectionMode
? detachablePaneSource(event.dataTransfer, paneGroups)
: null;
if (!source || !onDetachPane) return;
event.preventDefault();
setPaneDropTarget(null);
clearDraggedSession();
onDetachPane(source.tabKey, source.paneKey);
}}
className={cn(
"relative min-w-0 space-y-3 rounded-panel px-2 py-1.5",
"transition-[background-color,box-shadow]",
paneDropTarget === DETACH_PANE_DROP_TARGET
&& "bg-primary/[0.05] ring-1 ring-inset ring-primary/25",
)}
>
{temporarySessions.length > 0 ? (
<TemporaryChatSection
sessions={temporarySessions}
activeKey={activeKey}
running={running}
onSelect={onSelect}
onClose={onCloseTemporaryChat}
/>
) : null}
{limitedGroups.map((group, index) => {
const foldableChatsGroup = isFoldableChatsGroup(group);
const foldedChatsGroup = isFoldedChatsGroup(group, collapsedGroups);
const visibleSessions = visibleSessionsForGroup(
group,
activeKey,
collapsedGroups,
);
const hiddenInGroup = Math.max(0, group.sessions.length - visibleSessions.length);
const canToggleFold = group.sessions.length > COLLAPSED_CHATS_VISIBLE_COUNT;
const projectCollapsed = group.kind === "project"
&& Boolean(collapsedGroups[group.id]);
return (
<section key={group.id} aria-label={group.label} className="relative z-[1]">
{index === firstProjectGroupIndex ? (
<div className="px-2 pb-2 pt-2 text-[11px] font-medium leading-4 text-sidebar-muted-foreground">
{labels.projects}
</div>
) : null}
<div>
<div
ref={(element) => {
const key = `group:${group.id}`;
if (element) layoutRowRefs.current.set(key, element);
else layoutRowRefs.current.delete(key);
}}
data-sidebar-group-header={group.id}
>
{group.kind === "project" ? (
<ProjectGroupHeader
label={group.label}
active={group.sessions.some((session) => session.key === activeKey)}
path={group.projectPath}
actionMenuId={`project:${group.id}`}
actionMenus={actionMenus}
collapsed={projectCollapsed}
onToggle={() => toggleProjectGroup(group.id)}
onRequestRename={
group.projectKey && onRequestRenameProject
? () => onRequestRenameProject(group.projectKey ?? "", group.label)
: undefined
}
onNewChat={
group.projectPath && onNewChatInProject
? () => onNewChatInProject(group.projectPath ?? "", group.label)
: undefined
}
actionMenuPortalContainer={actionMenuPortalContainer}
/>
) : (
<ChatsGroupHeader label={group.label} />
)}
</div>
{projectCollapsed ? null : (
<div
data-sidebar-project-surface={group.kind === "project" ? "true" : undefined}
className={cn(
group.kind === "project"
&& "sidebar-child-list ms-4 pb-1",
)}
>
<ul className="space-y-0.5">
{visibleSessions.map((s) => {
const topicActive = s.key === activeKey;
const paneGroup = paneGroups[s.key];
const title = displayTitle(s, titleOverrides, t("chat.newChat"));
const resolvedPaneGroup = paneGroup ?? {
tabKey: s.key,
title,
activePaneKey: s.key,
panes: [{ key: s.key, chatId: s.chatId, title }],
};
const isWorkbenchTab = paneGroup?.visible
?? ((paneGroup?.panes.length ?? 0) > 1);
const paneGroupCollapsed = isWorkbenchTab
&& collapsedPaneGroups.has(s.key);
const paneGroupId = `sidebar-pane-group-${s.key.replace(
/[^a-zA-Z0-9_-]/g,
"-",
)}`;
const tabDeleteKeys = resolvedPaneGroup.panes.map((pane) => pane.key);
const tabSelected = tabDeleteKeys.every((key) => (
selectedDeleteKeys.has(key)
));
const tabPartiallySelected = !tabSelected && tabDeleteKeys.some((key) => (
selectedDeleteKeys.has(key)
));
if (isWorkbenchTab) {
return (
<li
key={s.key}
ref={(element) => {
if (element) layoutRowRefs.current.set(s.key, element);
else layoutRowRefs.current.delete(s.key);
}}
data-sidebar-tab-group="true"
data-pane-group-collapsed={paneGroupCollapsed ? "true" : undefined}
data-pane-drop-target={
paneDropTarget === resolvedPaneGroup.tabKey ? "true" : undefined
}
className="relative min-w-0"
>
<div
data-workbench-tab-surface
onDragEnter={(event) => {
const paneKey = onAttachPane && !deleteSelectionMode
? droppablePaneKey(event.dataTransfer, resolvedPaneGroup)
: null;
if (!paneKey) return;
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = "move";
setPaneDropTarget(resolvedPaneGroup.tabKey);
}}
onDragOver={(event) => {
const paneKey = onAttachPane && !deleteSelectionMode
? droppablePaneKey(event.dataTransfer, resolvedPaneGroup)
: null;
if (!paneKey) return;
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = "move";
setPaneDropTarget(resolvedPaneGroup.tabKey);
}}
onDragLeave={(event) => {
const nextTarget = event.relatedTarget;
if (nextTarget instanceof Node
&& event.currentTarget.contains(nextTarget)) return;
setPaneDropTarget((current) => (
current === resolvedPaneGroup.tabKey ? null : current
));
}}
onDrop={(event) => {
const paneKey = onAttachPane && !deleteSelectionMode
? droppablePaneKey(event.dataTransfer, resolvedPaneGroup)
: null;
if (!paneKey || !onAttachPane) return;
event.preventDefault();
event.stopPropagation();
setPaneDropTarget(null);
clearDraggedSession();
onAttachPane(paneKey, resolvedPaneGroup.tabKey);
}}
className={cn(
"min-w-0 transition-[background-color,box-shadow]",
deleteSelectionMode && (tabSelected || tabPartiallySelected)
&& "ring-1 ring-inset ring-sidebar-foreground/25",
paneDropTarget === resolvedPaneGroup.tabKey
&& "bg-primary/[0.09] ring-2 ring-inset ring-primary/35 dark:bg-primary/[0.14]",
)}
>
<WorkbenchTabHeader
active={topicActive}
title={title}
actionMenuId={`tab:${resolvedPaneGroup.tabKey}`}
actionMenus={actionMenus}
controlsId={paneGroupId}
collapsed={paneGroupCollapsed}
deleteSelectionMode={deleteSelectionMode}
selected={tabSelected}
partiallySelected={tabPartiallySelected}
onToggle={() => togglePaneGroup(s.key)}
onToggleSelection={(shiftKey) => toggleDeleteSelection(
tabDeleteKeys,
shiftKey,
tabDeleteKeys[0],
)}
onRequestRename={onRequestRenameTab
? () => onRequestRenameTab(s.key, title)
: undefined}
onDissolve={onDissolveTab
? () => onDissolveTab(resolvedPaneGroup.tabKey)
: undefined}
onRequestDelete={() => requestDeleteKeys(tabDeleteKeys)}
actionMenuPortalContainer={actionMenuPortalContainer}
/>
{!paneGroupCollapsed ? (
<ActivePaneRows
id={paneGroupId}
group={resolvedPaneGroup}
tabTitle={title}
tabActive={topicActive}
compact={compact}
running={running}
updated={updated}
recovery={recovery}
onSelectPane={onSelectPane}
onRequestDelete={onRequestDelete}
onRequestRename={onRequestRename}
renamingKey={renamingKey}
onBeginRename={beginRename}
onEndRename={endRename}
onTogglePin={onTogglePin}
onToggleArchive={onToggleArchive}
pinned={pinnedPanes}
archived={archivedPanes}
onDetachPane={onDetachPane}
moveTargets={paneGroupTargets.filter((target) => (
target.key !== resolvedPaneGroup.tabKey
))}
onAttachPane={onAttachPane}
deleteSelectionMode={deleteSelectionMode}
selectedDeleteKeys={selectedDeleteKeys}
onToggleDeleteSelection={toggleDeleteSelection}
onBeginDeleteSelection={beginDeleteSelection}
actionMenuPortalContainer={actionMenuPortalContainer}
actionMenus={actionMenus}
/>
) : null}
</div>
</li>
);
}
const isPinned = pinned.has(s.key);
const isArchived = archived.has(s.key);
const activityState = running.has(s.chatId)
? "running"
: recovery.has(s.chatId)
? "recovery"
: updated.has(s.chatId) && !topicActive
? "updated"
: null;
const hasPaneMoveTarget = Boolean(onAttachPane)
&& paneGroupTargets.some((target) => (
target.key !== paneGroup?.tabKey && !target.atCapacity
));
const canDragSession = !deleteSelectionMode
&& (!topicActive || hasPaneMoveTarget);
const actionMenuId = `session:${s.key}`;
return (
<li
key={s.key}
ref={(element) => {
if (element) layoutRowRefs.current.set(s.key, element);
else layoutRowRefs.current.delete(s.key);
}}
className="relative min-w-0"
>
<div
data-chat-row={s.key}
data-sidebar-tab={s.key}
onContextMenu={(event) => (
actionMenus.openFromContextMenu(event, actionMenuId)
)}
className={cn(
"group flex min-w-0 max-w-full items-center gap-1 rounded-control px-2 text-ui",
SIDEBAR_SELECTION_ITEM_CLASS,
compact ? "min-h-7" : "min-h-8",
topicActive
? "text-sidebar-foreground"
: "text-sidebar-content media-hover:hover:text-sidebar-accent-foreground",
deleteSelectionMode && (tabSelected || tabPartiallySelected)
&& "bg-sidebar-accent/55 text-sidebar-accent-foreground",
)}
>
{renamingKey === s.key ? (
<SidebarTopicRename
key={s.key}
title={title}
onSave={(nextTitle) => onRequestRename(s.key, nextTitle)}
onClose={endRename}
/>
) : <button
type="button"
onClick={(event) => {
if (deleteSelectionMode) {
toggleDeleteSelection(tabDeleteKeys, event.shiftKey, s.key);
return;
}
onSelect(s.key);
}}
draggable={canDragSession}
onDragStart={(event) => {
if (!canDragSession) {
event.preventDefault();
return;
}
writeDraggedSession(event.dataTransfer, s.key);
}}
onDragEnd={clearDraggedSession}
aria-current={topicActive ? "page" : undefined}
aria-pressed={deleteSelectionMode ? tabSelected : undefined}
className={cn(
"flex min-w-0 flex-1 items-center gap-2 overflow-hidden text-left",
canDragSession && "cursor-grab active:cursor-grabbing",
deleteSelectionMode && "cursor-default",
compact ? "py-1" : "py-1.5",
)}
>
{deleteSelectionMode ? (
<SelectionIndicator
checked={tabSelected}
partial={tabPartiallySelected}
/>
) : null}
<span className="relative flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
<SidebarSessionHandle handle={s.handle} />
<span className="min-w-0 flex-1 truncate font-normal leading-5">
{title}
</span>
{isPinned ? <PinnedChatIndicator /> : null}
</span>
</button>}
<SessionActivityIndicator state={activityState} />
{!deleteSelectionMode && renamingKey !== s.key ? (
<DropdownMenu
modal={false}
open={actionMenus.openId === actionMenuId}
onOpenChange={(open) => (
actionMenus.onOpenChange(actionMenuId, open)
)}
>
<DropdownMenuTrigger
className={cn(
"sidebar-action-trigger touch-target inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-sidebar-muted-foreground opacity-0 transition-opacity",
"media-hover:hover:text-sidebar-foreground media-hover:group-hover:opacity-100",
"focus-visible:opacity-100 data-[state=open]:opacity-100",
)}
aria-label={t("chat.actions", { title })}
>
<MoreHorizontal className="h-3.5 w-3.5" />
</DropdownMenuTrigger>
<SidebarActionMenuContent
portalContainer={actionMenuPortalContainer}
>
<DropdownMenuItem onSelect={() => onTogglePin(s.key)}>
{isPinned ? (
<PinOff className="h-4 w-4 shrink-0" />
) : (
<Pin className="h-4 w-4 shrink-0" />
)}
{isPinned ? t("chat.unpin") : t("chat.pin")}
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => beginRename(s.key)}
>
<Pencil className="h-4 w-4 shrink-0" />
{t("chat.rename")}
</DropdownMenuItem>
{s.projectLocked !== false ? (
<DropdownMenuItem onSelect={() => onToggleArchive(s.key)}>
{isArchived ? (
<ArchiveRestore className="h-4 w-4 shrink-0" />
) : (
<Archive className="h-4 w-4 shrink-0" />
)}
{isArchived ? t("chat.unarchive") : t("chat.archive")}
</DropdownMenuItem>
) : null}
{paneGroup && onCreateTab ? (
<DropdownMenuItem onSelect={() => onCreateTab(s.key)}>
<PanelsTopLeft className="h-4 w-4 shrink-0" aria-hidden />
{t("workbench.createGroup")}
</DropdownMenuItem>
) : null}
{paneGroup && onAttachPane ? (
<MoveToGroupSubmenu
targets={paneGroupTargets.filter((target) => (
target.key !== paneGroup.tabKey
))}
onMove={(targetKey) => onAttachPane(s.key, targetKey)}
/>
) : null}
<DropdownMenuItem
onSelect={() => beginDeleteSelection(tabDeleteKeys)}
>
<ListChecks className="h-4 w-4 shrink-0" />
{t("chat.select", { defaultValue: "Select" })}
</DropdownMenuItem>
<DropdownMenuItem
tone="destructive"
onSelect={() => {
window.setTimeout(() => requestDeleteKeys(tabDeleteKeys), 0);
}}
>
<Trash2 className="h-4 w-4 shrink-0" />
{t("chat.delete")}
</DropdownMenuItem>
</SidebarActionMenuContent>
</DropdownMenu>
) : null}
</div>
</li>
);
})}
</ul>
{foldableChatsGroup && canToggleFold ? (
<ChatsFoldFooter
folded={foldedChatsGroup}
hiddenCount={hiddenInGroup}
onToggle={() => onToggleGroup?.(group.id)}
/>
) : null}
</div>
)}
</div>
</section>
);
})}
{hiddenSessionCount > 0 ? (
<div className="relative z-[1] px-2 pb-2 pt-1">
<button
type="button"
onClick={() =>
setVisibleLimit((limit) =>
Math.min(totalSessionCount, limit + VISIBLE_SESSIONS_INCREMENT),
)
}
className="h-8 w-full rounded-full text-[12px] font-medium text-sidebar-muted-foreground transition-colors media-hover:hover:bg-sidebar-accent/65 media-hover:hover:text-sidebar-muted-foreground"
>
{t("chat.showMore", { count: hiddenSessionCount })}
</button>
</div>
) : null}
{deleteSelectionMode ? (
<div
ref={selectionBarRef}
data-testid="delete-selection-bar"
aria-busy={deleteConfirmationPending}
className="sticky bottom-2 z-30 mx-1 mt-3 flex min-h-11 items-center gap-1 rounded-floating border border-sidebar-border/80 bg-popover/95 p-1.5 pl-3 shadow-[0_10px_30px_rgba(15,23,42,0.14)] backdrop-blur-xl"
>
<span className="min-w-0 flex-1 truncate pr-2 text-[12.5px] font-medium text-foreground/85">
{t("chat.selectedCount", {
defaultValue: "{{count}} selected",
count: selectedDeleteKeys.size,
})}
</span>
{onArchiveMany && (selectedDeleteKeys.size === 0 || selectedArchiveKeys.length > 0) ? (
<HoverHint content={t(allSelectedArchived ? "chat.unarchive" : "chat.archive")}>
<button
type="button"
aria-label={t(allSelectedArchived ? "chat.unarchive" : "chat.archive")}
disabled={selectedDeleteKeys.size === 0 || deleteConfirmationPending}
onClick={() => setPendingArchive({
keys: selectedArchiveKeys,
archive: !allSelectedArchived,
})}
className="touch-target inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-foreground transition-colors media-hover:hover:bg-sidebar-accent disabled:pointer-events-none disabled:opacity-40"
>
{allSelectedArchived
? <ArchiveRestore className="h-4 w-4" aria-hidden />
: <Archive className="h-4 w-4" aria-hidden />}
</button>
</HoverHint>
) : null}
<HoverHint content={t("chat.delete")}>
<button
type="button"
aria-label={t("chat.delete")}
disabled={selectedDeleteKeys.size === 0 || deleteConfirmationPending}
onClick={confirmDeleteSelection}
className="touch-target inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-destructive transition-colors media-hover:hover:bg-destructive/10 disabled:pointer-events-none disabled:opacity-40"
>
<Trash2 className="h-4 w-4" aria-hidden />
</button>
</HoverHint>
</div>
) : null}
{pendingArchive ? (
<ArchiveConfirm
count={pendingArchive.keys.length}
archive={pendingArchive.archive}
onCancel={() => setPendingArchive(null)}
onConfirm={() => {
onArchiveMany?.(pendingArchive.keys, pendingArchive.archive);
setPendingArchive(null);
closeDeleteSelection();
}}
/>
) : null}
</SidebarSelectionHighlight>
</div>
);
});
function WorkbenchTabHeader({
active,
title,
actionMenuId,
actionMenus,
controlsId,
collapsed,
deleteSelectionMode,
selected,
partiallySelected,
onToggle,
onToggleSelection,
onRequestRename,
onDissolve,
onRequestDelete,
actionMenuPortalContainer,
}: {
active: boolean;
title: string;
actionMenuId: string;
actionMenus: SidebarActionMenuController;
controlsId: string;
collapsed: boolean;
deleteSelectionMode: boolean;
selected: boolean;
partiallySelected: boolean;
onToggle: () => void;
onToggleSelection: (shiftKey: boolean) => void;
onRequestRename?: () => void;
onDissolve?: () => void;
onRequestDelete: () => void;
actionMenuPortalContainer?: HTMLElement | null;
}) {
const { t } = useTranslation();
const disclosureLabel = t(
collapsed ? "workbench.expandTabGroup" : "workbench.collapseTabGroup",
{ title },
);
return (
<div
data-workbench-tab
onContextMenu={(event) => actionMenus.openFromContextMenu(event, actionMenuId)}
className={cn(
"group/tab flex min-h-8 min-w-0 items-center gap-0.5 rounded-control px-2",
active ? "text-sidebar-foreground" : "text-sidebar-content",
)}
>
{!deleteSelectionMode ? (
<HoverHint side="top" align="start" contentClassName="max-w-80 break-words" content={disclosureLabel}>
<button
type="button"
aria-expanded={!collapsed}
aria-controls={controlsId}
aria-label={disclosureLabel}
onClick={onToggle}
className={cn(
"relative inline-flex h-6 w-3.5 shrink-0 items-center justify-center rounded-md before:absolute before:-inset-x-1 before:inset-y-0",
"text-sidebar-muted-foreground transition-[color] duration-150 ease-out",
"media-hover:hover:text-sidebar-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60",
"motion-reduce:transition-none ",
)}
>
<ChevronDown
aria-hidden
className={cn(
"relative -start-1 h-3.5 w-3.5 transition-transform duration-200 ease-out motion-reduce:transition-none",
collapsed && "-rotate-90",
)}
/>
</button>
</HoverHint>
) : null}
<HoverHint side="top" align="start" contentClassName="max-w-80 break-words" content={title}>
<button
type="button"
onClick={(event) => {
if (deleteSelectionMode) onToggleSelection(event.shiftKey);
else onToggle();
}}
draggable={false}
aria-label={t("workbench.tabAria", { title })}
aria-expanded={deleteSelectionMode ? undefined : !collapsed}
aria-controls={deleteSelectionMode ? undefined : controlsId}
aria-pressed={deleteSelectionMode ? selected : undefined}
className={cn(
"flex min-w-0 flex-1 items-center gap-2 overflow-hidden py-1 text-left",
"text-[13px] leading-5",
active ? "font-medium" : "font-normal",
deleteSelectionMode && "cursor-default",
)}
>
{deleteSelectionMode ? (
<SelectionIndicator checked={selected} partial={partiallySelected} />
) : null}
<span className="min-w-0 flex-1 truncate">{title}</span>
</button>
</HoverHint>
{!deleteSelectionMode ? (
<>
<DropdownMenu
modal={false}
open={actionMenus.openId === actionMenuId}
onOpenChange={(open) => actionMenus.onOpenChange(actionMenuId, open)}
>
<DropdownMenuTrigger
className={cn(
"sidebar-action-trigger touch-target inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md",
"text-sidebar-muted-foreground opacity-0 transition-opacity",
"media-hover:hover:text-sidebar-foreground media-hover:group-hover/tab:opacity-100",
"focus-visible:opacity-100 data-[state=open]:opacity-100",
)}
aria-label={t("chat.actions", { title })}
>
<MoreHorizontal className="h-3.5 w-3.5" />
</DropdownMenuTrigger>
<SidebarActionMenuContent
portalContainer={actionMenuPortalContainer}
>
{onRequestRename ? (
<DropdownMenuItem onSelect={onRequestRename}>
<Pencil className="h-4 w-4 shrink-0" />
{t("chat.rename")}
</DropdownMenuItem>
) : null}
{onDissolve ? (
<DropdownMenuItem onSelect={onDissolve}>
<Ungroup className="h-4 w-4 shrink-0" />
{t("workbench.dissolveTab")}
</DropdownMenuItem>
) : null}
<DropdownMenuItem
tone="destructive"
onSelect={() => window.setTimeout(onRequestDelete, 0)}
className="whitespace-nowrap"
>
<Trash2 className="h-4 w-4 shrink-0" />
{t("workbench.deleteConversations")}
</DropdownMenuItem>
</SidebarActionMenuContent>
</DropdownMenu>
</>
) : null}
</div>
);
}
function ActivePaneRows({
id,
group,
tabTitle,
tabActive,
compact,
running,
updated,
recovery,
onSelectPane,
onRequestDelete,
onRequestRename,
renamingKey,
onBeginRename,
onEndRename,
onTogglePin,
onToggleArchive,
pinned,
archived,
onDetachPane,
moveTargets,
onAttachPane,
deleteSelectionMode,
selectedDeleteKeys,
onToggleDeleteSelection,
onBeginDeleteSelection,
actionMenuPortalContainer,
actionMenus,
}: {
id: string;
group: SidebarPaneGroup;
tabTitle: string;
tabActive: boolean;
compact: boolean;
running: ReadonlySet<string>;
updated: ReadonlySet<string>;
recovery: ReadonlySet<string>;
onSelectPane?: (tabKey: string, paneKey: string) => void;
onRequestDelete: (key: string, label: string) => void;
onRequestRename: (key: string, title: string) => Promise<void>;
renamingKey: string | null;
onBeginRename: (key: string) => void;
onEndRename: () => void;
onTogglePin: (key: string) => void;
onToggleArchive: (key: string) => void;
pinned: ReadonlySet<string>;
archived: ReadonlySet<string>;
onDetachPane?: (tabKey: string, paneKey: string) => void;
moveTargets: PaneGroupTarget[];
onAttachPane?: (
paneKey: string,
tabKey: string,
) => void;
deleteSelectionMode: boolean;
selectedDeleteKeys: ReadonlySet<string>;
onToggleDeleteSelection: (
keys: string[],
shiftKey?: boolean,
targetKey?: string,
) => void;
onBeginDeleteSelection: (keys: string[]) => void;
actionMenuPortalContainer?: HTMLElement | null;
actionMenus: SidebarActionMenuController;
}) {
const { t } = useTranslation();
const panes = group.panes;
return (
<ul
id={id}
aria-label={t("workbench.panesInTab", { title: tabTitle })}
className="sidebar-child-list ms-4 space-y-0.5 pb-1"
>
{panes.map((pane) => {
const active = tabActive && pane.key === group.activePaneKey;
const activityState = running.has(pane.chatId)
? "running"
: recovery.has(pane.chatId)
? "recovery"
: updated.has(pane.chatId) && !active
? "updated"
: null;
const paneActionsLabel = t("workbench.paneActions", { title: pane.title });
const selected = selectedDeleteKeys.has(pane.key);
const isPinned = pinned.has(pane.key);
const isArchived = archived.has(pane.key);
const hasPaneMoveTarget = Boolean(onAttachPane)
&& moveTargets.some((target) => !target.atCapacity);
const canDragSession = !deleteSelectionMode
&& (!active || Boolean(onDetachPane) || hasPaneMoveTarget);
const actionMenuId = `pane:${pane.key}`;
return (
<li
key={pane.key}
className="relative min-w-0"
>
<div
data-chat-row={pane.key}
data-sidebar-pane={pane.key}
onContextMenu={(event) => (
actionMenus.openFromContextMenu(event, actionMenuId)
)}
className={cn(
"group/pane flex min-w-0 max-w-full items-center gap-1 rounded-control px-2 text-ui",
SIDEBAR_SELECTION_ITEM_CLASS,
compact ? "min-h-7" : "min-h-8",
active
? "text-sidebar-foreground"
: "text-sidebar-content media-hover:hover:text-sidebar-accent-foreground",
deleteSelectionMode && selected
&& "bg-sidebar-accent/55 text-sidebar-accent-foreground",
)}
>
{renamingKey === pane.key ? (
<SidebarTopicRename
key={pane.key}
title={pane.title}
onSave={(nextTitle) => onRequestRename(pane.key, nextTitle)}
onClose={onEndRename}
/>
) : <button
type="button"
onClick={(event) => {
if (deleteSelectionMode) {
onToggleDeleteSelection([pane.key], event.shiftKey, pane.key);
return;
}
onSelectPane?.(group.tabKey, pane.key);
}}
draggable={canDragSession}
onDragStart={(event) => {
if (!canDragSession) {
event.preventDefault();
return;
}
writeDraggedSession(event.dataTransfer, pane.key);
}}
onDragEnd={clearDraggedSession}
aria-current={active ? "true" : undefined}
aria-pressed={deleteSelectionMode ? selected : undefined}
className={cn(
"flex min-w-0 flex-1 items-center gap-2 overflow-hidden text-left font-normal leading-5",
canDragSession && "cursor-grab active:cursor-grabbing",
compact ? "py-1" : "py-1.5",
deleteSelectionMode && "cursor-default",
)}
>
{deleteSelectionMode ? (
<SelectionIndicator checked={selected} partial={false} />
) : null}
<span className="relative flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
<SidebarSessionHandle handle={pane.handle} />
<span className="min-w-0 flex-1 truncate">{pane.title}</span>
{isPinned ? <PinnedChatIndicator /> : null}
</span>
</button>}
<SessionActivityIndicator state={activityState} />
{!deleteSelectionMode && renamingKey !== pane.key ? <DropdownMenu
modal={false}
open={actionMenus.openId === actionMenuId}
onOpenChange={(open) => actionMenus.onOpenChange(actionMenuId, open)}
>
<DropdownMenuTrigger
className={cn(
"sidebar-action-trigger touch-target inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-sidebar-muted-foreground opacity-0 transition-opacity",
"media-hover:hover:text-sidebar-foreground media-hover:group-hover/pane:opacity-100",
"focus-visible:opacity-100 data-[state=open]:opacity-100",
)}
aria-label={paneActionsLabel}
>
<MoreHorizontal className="h-3.5 w-3.5" />
</DropdownMenuTrigger>
<SidebarActionMenuContent
portalContainer={actionMenuPortalContainer}
>
<DropdownMenuItem onSelect={() => onTogglePin(pane.key)}>
{isPinned ? (
<PinOff className="h-4 w-4 shrink-0" />
) : (
<Pin className="h-4 w-4 shrink-0" />
)}
{isPinned ? t("chat.unpin") : t("chat.pin")}
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => onBeginRename(pane.key)}
>
<Pencil className="h-4 w-4 shrink-0" />
{t("chat.rename")}
</DropdownMenuItem>
{pane.projectLocked === true ? (
<DropdownMenuItem onSelect={() => onToggleArchive(pane.key)}>
{isArchived ? (
<ArchiveRestore className="h-4 w-4 shrink-0" />
) : (
<Archive className="h-4 w-4 shrink-0" />
)}
{isArchived ? t("chat.unarchive") : t("chat.archive")}
</DropdownMenuItem>
) : null}
{onDetachPane ? (
<DropdownMenuItem onSelect={() => onDetachPane(group.tabKey, pane.key)}>
<Unplug className="h-4 w-4 shrink-0" />
{t("workbench.detachPane", { title: pane.title })}
</DropdownMenuItem>
) : null}
{onAttachPane ? (
<MoveToGroupSubmenu
targets={moveTargets}
onMove={(targetKey) => onAttachPane(pane.key, targetKey)}
/>
) : null}
<DropdownMenuItem
onSelect={() => onBeginDeleteSelection([pane.key])}
>
<ListChecks className="h-4 w-4 shrink-0" />
{t("chat.select", { defaultValue: "Select" })}
</DropdownMenuItem>
<DropdownMenuItem
tone="destructive"
onSelect={() => {
window.setTimeout(() => onRequestDelete(pane.key, pane.title), 0);
}}
>
<Trash2 className="h-4 w-4 shrink-0" />
{t("chat.delete")}
</DropdownMenuItem>
</SidebarActionMenuContent>
</DropdownMenu> : null}
</div>
</li>
);
})}
</ul>
);
}
function selectionRange(order: string[], anchorKey: string, targetKey: string): string[] | null {
const anchorIndex = order.indexOf(anchorKey);
const targetIndex = order.indexOf(targetKey);
if (anchorIndex < 0 || targetIndex < 0) return null;
const start = Math.min(anchorIndex, targetIndex);
const end = Math.max(anchorIndex, targetIndex);
return order.slice(start, end + 1);
}
function SelectionIndicator({
checked,
partial,
}: {
checked: boolean;
partial: boolean;
}) {
const Icon = partial ? SquareMinus : checked ? SquareCheckBig : Square;
return (
<Icon
aria-hidden
className={cn(
"h-4 w-4 shrink-0",
checked || partial ? "text-primary" : "text-sidebar-muted-foreground",
)}
/>
);
}
function MoveToGroupSubmenu({
targets,
onMove,
}: {
targets: PaneGroupTarget[];
onMove: (targetKey: string) => void;
}) {
const { t } = useTranslation();
// Radix sends Escape only to the topmost submenu before closing the root.
const onEscapeKeyDown = useContext(SidebarActionMenuEscapeContext);
if (targets.length === 0) return null;
return (
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<MoveRight className="h-4 w-4 shrink-0" aria-hidden />
{t("workbench.moveTo")}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent onEscapeKeyDown={onEscapeKeyDown}>
{targets.map((target) => (
<DropdownMenuItem
key={target.key}
disabled={target.atCapacity}
onSelect={() => onMove(target.key)}
>
<span className="min-w-0 max-w-56 flex-1 truncate">{target.title}</span>
<span className="shrink-0 tabular-nums text-sidebar-muted-foreground">
{target.paneCount}/{MAX_WORKBENCH_PANES}
</span>
</DropdownMenuItem>
))}
</DropdownMenuSubContent>
</DropdownMenuSub>
);
}
function TemporaryChatSection({
sessions,
activeKey,
running,
onSelect,
onClose,
}: {
sessions: ChatSummary[];
activeKey: string | null;
running: ReadonlySet<string>;
onSelect: (key: string) => void;
onClose?: (key: string) => void;
}) {
const { t } = useTranslation();
return (
<section aria-label={t("temporaryChat.sectionTitle")} className="relative z-[1]">
<ChatsGroupHeader label={t("temporaryChat.sectionTitle")} />
<ul className="space-y-0.5">
{sessions.map((session) => {
const active = session.key === activeKey;
const title = deriveTemporaryChatTitle(session.preview, t("temporaryChat.title"));
return (
<li key={session.key} className="min-w-0">
<div
data-temporary-chat-row={session.key}
data-chat-row={session.key}
className={cn(
"group flex min-h-8 min-w-0 max-w-full items-center gap-2 rounded-control px-2 text-ui",
SIDEBAR_SELECTION_ITEM_CLASS,
active
? "text-sidebar-accent-foreground"
: "text-sidebar-content settings-hover media-hover:hover:text-sidebar-accent-foreground",
)}
>
<button
type="button"
onClick={() => onSelect(session.key)}
aria-current={active ? "page" : undefined}
className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden py-1.5 text-left"
>
<MessageCircleDashed
className="h-3.5 w-3.5 shrink-0 text-[hsl(var(--temporary-foreground))]"
aria-hidden
/>
<span className="min-w-0 flex-1 truncate font-normal leading-5">
{title}
</span>
</button>
<SessionActivityIndicator state={running.has(session.chatId) ? "running" : null} />
{onClose ? (
<button
type="button"
aria-label={t("temporaryChat.closeAction", { title })}
onClick={() => onClose(session.key)}
className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-sidebar-muted-foreground transition-colors media-hover:hover:text-destructive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60"
>
<X className="h-3.5 w-3.5" aria-hidden />
</button>
) : null}
</div>
</li>
);
})}
</ul>
</section>
);
}
function ProjectGroupHeader({
active,
label,
path,
actionMenuId,
actionMenus,
collapsed,
onToggle,
onRequestRename,
onNewChat,
actionMenuPortalContainer,
}: {
active: boolean;
label: string;
path?: string;
actionMenuId: string;
actionMenus: SidebarActionMenuController;
collapsed: boolean;
onToggle: () => void;
onRequestRename?: () => void;
onNewChat?: () => void;
actionMenuPortalContainer?: HTMLElement | null;
}) {
const { t } = useTranslation();
const projectButton = (
<button
type="button"
aria-expanded={!collapsed}
onClick={onToggle}
className={cn(
"flex min-w-0 flex-1 items-center gap-2 rounded-control py-1 text-left transition-colors media-hover:hover:text-sidebar-foreground",
active ? "font-medium text-sidebar-foreground" : "font-normal",
)}
>
<span className="min-w-0 flex-1 truncate">{label}</span>
</button>
);
const disclosureLabel = `${t("chat.groups.projects")}: ${label}`;
return (
<div
onContextMenu={onRequestRename || onNewChat
? (event) => actionMenus.openFromContextMenu(event, actionMenuId)
: undefined}
className="group flex min-h-8 min-w-0 items-center gap-0.5 rounded-control px-2 text-[13px] leading-5 text-sidebar-content"
>
<HoverHint side="top" align="start" contentClassName="max-w-80 break-words" content={disclosureLabel}>
<button
type="button"
aria-expanded={!collapsed}
aria-label={disclosureLabel}
onClick={onToggle}
className={cn(
"relative inline-flex h-6 w-3.5 shrink-0 items-center justify-center rounded-md before:absolute before:-inset-x-1 before:inset-y-0",
"text-sidebar-muted-foreground transition-[color] duration-150 ease-out",
"media-hover:hover:text-sidebar-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60",
"motion-reduce:transition-none ",
)}
>
<ChevronDown
data-sidebar-project-disclosure-icon
aria-hidden
className={cn(
"relative -start-1 h-3.5 w-3.5 transition-transform duration-200 ease-out motion-reduce:transition-none",
collapsed && "-rotate-90",
)}
/>
</button>
</HoverHint>
{path ? (
<HoverHint side="top" align="start" contentClassName="max-w-72 break-words" content={path}>
{projectButton}
</HoverHint>
) : projectButton}
{onRequestRename || onNewChat ? (
<DropdownMenu
modal={false}
open={actionMenus.openId === actionMenuId}
onOpenChange={(open) => actionMenus.onOpenChange(actionMenuId, open)}
>
<DropdownMenuTrigger
className={cn(
"sidebar-action-trigger touch-target inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-sidebar-muted-foreground opacity-0 transition-opacity",
"media-hover:hover:text-sidebar-foreground media-hover:group-hover:opacity-100 focus-visible:opacity-100",
"data-[state=open]:opacity-100",
)}
aria-label={t("chat.actions", { title: label })}
onClick={(event) => event.stopPropagation()}
>
<MoreHorizontal className="h-3.5 w-3.5" />
</DropdownMenuTrigger>
<SidebarActionMenuContent
portalContainer={actionMenuPortalContainer}
>
{onNewChat ? (
<DropdownMenuItem onSelect={onNewChat}>
<Plus className="h-4 w-4 shrink-0" aria-hidden />
{t("sidebar.newChat")}
</DropdownMenuItem>
) : null}
{onRequestRename ? (
<DropdownMenuItem onSelect={onRequestRename}>
<Pencil className="h-4 w-4 shrink-0" />
{t("chat.rename")}
</DropdownMenuItem>
) : null}
</SidebarActionMenuContent>
</DropdownMenu>
) : null}
</div>
);
}
function ChatsGroupHeader({ label }: { label: string }) {
return (
<div data-theme-ink className="px-2 pb-2 pt-2 text-[11px] font-medium leading-4 text-sidebar-muted-foreground">
{label}
</div>
);
}
function PinnedChatIndicator() {
return (
<span
data-sidebar-pinned-indicator
aria-hidden="true"
className="inline-flex shrink-0 items-center text-sidebar-muted-foreground"
>
<Pin className="h-3.5 w-3.5" aria-hidden="true" />
</span>
);
}
function ChatsFoldFooter({
folded,
hiddenCount,
onToggle,
}: {
folded: boolean;
hiddenCount: number;
onToggle: () => void;
}) {
const { t, i18n } = useTranslation();
const collapsedFallback = i18n.resolvedLanguage?.startsWith("zh")
? `已折叠 ${hiddenCount} 个对话`
: `${hiddenCount} hidden topics`;
return (
<div className="pb-1 pt-1">
<button
type="button"
onClick={onToggle}
className="h-7 w-full rounded-control text-left text-[12px] font-medium text-sidebar-muted-foreground transition-colors media-hover:hover:bg-sidebar-accent/50 media-hover:hover:text-sidebar-muted-foreground"
>
<span className="px-2">
{folded
? t("chat.collapsed", {
count: hiddenCount,
defaultValue: collapsedFallback,
})
: t("chat.showLess")}
</span>
</button>
</div>
);
}
function SessionActivityIndicator({
state,
}: {
state: "running" | "updated" | "recovery" | null;
}) {
const { t } = useTranslation();
if (state === "recovery") {
const label = t("chat.activity.recovery", {
defaultValue: "This conversation needs your attention",
});
return (
<HoverHint side="top" align="start" contentClassName="max-w-80 break-words" content={label}>
<span
role="img"
aria-label={label}
className="grid h-4 w-4 shrink-0 place-items-center text-[#ff8a3d]"
>
<AlertTriangle className="h-3.5 w-3.5" strokeWidth={2} aria-hidden />
</span>
</HoverHint>
);
}
if (state === "running") {
const label = t("chat.activity.running");
return (
<HoverHint side="top" align="start" contentClassName="max-w-80 break-words" content={label}>
<span
role="img"
aria-label={label}
className="grid h-4 w-4 shrink-0 place-items-center"
>
<LoadingRing className="h-3 w-3 text-sidebar-muted-foreground" />
</span>
</HoverHint>
);
}
if (state === "updated") {
const label = t("chat.activity.updated");
return (
<HoverHint side="top" align="start" contentClassName="max-w-80 break-words" content={label}>
<span
role="img"
aria-label={label}
className="grid h-4 w-4 shrink-0 place-items-center"
>
<span className="h-2 w-2 rounded-full bg-[#ff8a3d] shadow-[0_0_0_2px_rgba(255,138,61,0.16)]" />
</span>
</HoverHint>
);
}
return <span className="h-4 w-4 shrink-0" aria-hidden="true" />;
}