Merge upstream main into feat/subagent-cost-rollup

This commit is contained in:
igorvelho
2026-08-25 23:09:44 +01:00
156 changed files with 5084 additions and 4690 deletions
File diff suppressed because it is too large Load Diff
+70 -401
View File
@@ -1,10 +1,8 @@
import React, { useRef, useEffect } from 'react';
import { animate, motion, useMotionValue } from 'motion/react';
import React from 'react';
import { Header } from './Header';
import { Sidebar } from './Sidebar';
import { SidebarTopBar } from './SidebarTopBar';
import { TitlebarLeftControls } from './TitlebarLeftControls';
import { ProjectContextPanel } from './RightSidebarTabs';
import { ContextPanel } from './ContextPanel';
import { ContextPanelRail } from './ContextPanelRail';
import { ErrorBoundary } from '../ui/ErrorBoundary';
@@ -18,8 +16,6 @@ import { ArchiveView } from '@/components/views/ArchiveView';
import { WorktreesView } from '@/components/views/WorktreesView';
import { DiffWorkerProvider } from '@/contexts/DiffWorkerProvider';
import { MultiRunLauncher } from '@/components/multirun';
import { TerminalView } from '@/components/views/TerminalView';
import { DrawerProvider } from '@/contexts/DrawerContext';
import { useUIStore } from '@/stores/useUIStore';
import { useSessionUIStore } from '@/sync/session-ui-store';
@@ -30,24 +26,17 @@ import { lazyWithChunkRecovery } from '@/lib/chunkLoadRecovery';
import { ChatView } from '@/components/views/ChatView';
// Keep TerminalView eager: the bottom dock reserves its height immediately, so
// suspending here leaves a large blank panel on slower machines.
// Other heavy views stay on-demand to reduce initial bundle parse time:
// DiffView/FilesView pull the CodeMirror and @pierre/diffs stacks into the
// startup graph when imported statically.
const PlanView = lazyWithChunkRecovery(() => import('@/components/views/PlanView').then(m => ({ default: m.PlanView })));
const GitView = lazyWithChunkRecovery(() => import('@/components/views/GitView').then(m => ({ default: m.GitView })));
const DiffView = lazyWithChunkRecovery(() => import('@/components/views/DiffView').then(m => ({ default: m.DiffView })));
const FilesView = lazyWithChunkRecovery(() => import('@/components/views/FilesView').then(m => ({ default: m.FilesView })));
const DiagramView = lazyWithChunkRecovery(() => import('@/components/views/DiagramView').then(m => ({ default: m.DiagramView })));
const SettingsView = lazyWithChunkRecovery(() => import('@/components/views/SettingsView').then(m => ({ default: m.SettingsView })));
const SettingsWindow = lazyWithChunkRecovery(() => import('@/components/views/SettingsWindow').then(m => ({ default: m.SettingsWindow })));
/**
* Desktop-surface layout: the chat owns the main area, and every other
* surface (git, diff, files, terminal, ...) opens in the ContextPanel via the
* rail. Phone-sized viewports run the separate MobileApp shell — a viewport
* crossing the threshold reloads into it (see watchHostedSurfaceViewport).
*/
export const MainLayout: React.FC = () => {
const isSidebarOpen = useUIStore((state) => state.isSidebarOpen);
const activeSurface = useUIStore((state) => state.activeSurface);
const setIsMobile = useUIStore((state) => state.setIsMobile);
const isSessionSwitcherOpen = useUIStore((state) => state.isSessionSwitcherOpen);
const isSettingsDialogOpen = useUIStore((state) => state.isSettingsDialogOpen);
const setSettingsDialogOpen = useUIStore((state) => state.setSettingsDialogOpen);
// Mount the windowed settings dialog only after its first open: rendering
@@ -67,10 +56,9 @@ export const MainLayout: React.FC = () => {
const isScheduledTasksPageOpen = useUIStore((state) => state.isScheduledTasksDialogOpen);
const isArchivePageOpen = useUIStore((state) => state.isArchivePageOpen);
const worktreesPageProjectId = useUIStore((state) => state.worktreesPageProjectId);
// Any full-page surface replacing the chat area. While open, the chat and
// secondary views are fully hidden (not just covered) so none of their
// floating chrome bleeds through, and selecting a session / draft / main
// tab anywhere closes the surface.
// Any full-page surface replacing the chat area. While open, the chat is
// fully hidden (not just covered) so none of its floating chrome bleeds
// through, and selecting a session or draft anywhere closes the surface.
const isSurfacePageOpen = isScheduledTasksPageOpen || isArchivePageOpen || Boolean(worktreesPageProjectId) || isMultiRunLauncherOpen;
React.useEffect(() => {
@@ -82,166 +70,11 @@ export const MainLayout: React.FC = () => {
const draftOpened = Boolean(state.newSessionDraft?.open) && state.newSessionDraft !== prev.newSessionDraft;
if (sessionSelected || draftOpened) closeSurfacePages();
});
const unsubscribeTab = useUIStore.subscribe((state, prev) => {
if (state.activeSurface !== prev.activeSurface) closeSurfacePages();
});
return () => {
unsubscribeSession();
unsubscribeTab();
};
}, []);
const { isMobile } = useDeviceInfo();
const mobilePanelsResetRef = React.useRef(false);
// Mobile drawer state
const [mobileLeftDrawerOpen, setMobileLeftDrawerOpen] = React.useState(false);
const [mobileRightSidebarOpen, setMobileRightSidebarOpen] = React.useState(false);
const [mobileLeftDrawerVisible, setMobileLeftDrawerVisible] = React.useState(false);
const [mobileRightDrawerVisible, setMobileRightDrawerVisible] = React.useState(false);
const setMobileSessionPanelOpen = React.useCallback((open: boolean) => {
setMobileLeftDrawerOpen(open);
useUIStore.getState().setSessionSwitcherOpen(open);
}, []);
const initialDrawerWidthRef = React.useRef(typeof window === 'undefined' ? 0 : window.innerWidth);
// Left drawer motion value
const leftDrawerX = useMotionValue(-initialDrawerWidthRef.current);
const leftDrawerWidth = useRef(0);
// Right drawer motion value
const rightDrawerX = useMotionValue(initialDrawerWidthRef.current);
const rightDrawerWidth = useRef(0);
// Compute drawer width
useEffect(() => {
if (isMobile) {
leftDrawerWidth.current = window.innerWidth;
rightDrawerWidth.current = window.innerWidth;
}
}, [isMobile]);
// Sync left drawer state and motion value
useEffect(() => {
if (!isMobile) {
setMobileLeftDrawerVisible(false);
return;
}
if (mobileLeftDrawerOpen) {
setMobileLeftDrawerVisible(true);
}
animate(leftDrawerX, mobileLeftDrawerOpen ? 0 : -leftDrawerWidth.current, {
type: 'spring',
stiffness: 400,
damping: 35,
mass: 0.8,
});
}, [mobileLeftDrawerOpen, isMobile, leftDrawerX]);
// Sync right drawer state and motion value
useEffect(() => {
if (!isMobile) {
setMobileRightDrawerVisible(false);
return;
}
if (mobileRightSidebarOpen) {
setMobileRightDrawerVisible(true);
}
animate(rightDrawerX, mobileRightSidebarOpen ? 0 : rightDrawerWidth.current, {
type: 'spring',
stiffness: 400,
damping: 35,
mass: 0.8,
});
}, [isMobile, mobileRightSidebarOpen, rightDrawerX]);
useEffect(() => {
if (!isMobile) return;
return leftDrawerX.on('change', (value) => {
const width = leftDrawerWidth.current || initialDrawerWidthRef.current;
const visible = mobileLeftDrawerOpen || value > -width + 0.5;
setMobileLeftDrawerVisible((previous) => previous === visible ? previous : visible);
});
}, [isMobile, leftDrawerX, mobileLeftDrawerOpen]);
useEffect(() => {
if (!isMobile) return;
return rightDrawerX.on('change', (value) => {
const width = rightDrawerWidth.current || initialDrawerWidthRef.current;
const visible = mobileRightSidebarOpen || value < width - 0.5;
setMobileRightDrawerVisible((previous) => previous === visible ? previous : visible);
});
}, [isMobile, mobileRightSidebarOpen, rightDrawerX]);
// Sync session switcher close events to left drawer.
useEffect(() => {
if (isMobile && !isSessionSwitcherOpen && mobileLeftDrawerOpen) {
setMobileSessionPanelOpen(false);
}
}, [isSessionSwitcherOpen, isMobile, mobileLeftDrawerOpen, setMobileSessionPanelOpen]);
useEffect(() => {
if (!isMobile) {
mobilePanelsResetRef.current = false;
return;
}
if (mobilePanelsResetRef.current) {
return;
}
mobilePanelsResetRef.current = true;
setMobileSessionPanelOpen(false);
setMobileRightSidebarOpen(false);
}, [isMobile, setMobileSessionPanelOpen]);
useEffect(() => {
if (!isMobile || activeSurface !== 'chat' || mobileLeftDrawerOpen || mobileRightSidebarOpen || isSettingsDialogOpen) {
return;
}
let disposed = false;
let timeoutId: number | undefined;
const scheduleDraftOpen = (delayMs: number) => {
timeoutId = window.setTimeout(() => {
if (disposed) {
return;
}
const sessionState = useSessionUIStore.getState();
const uiState = useUIStore.getState();
if (uiState.activeMainTab !== 'chat' || uiState.isSettingsDialogOpen || sessionState.currentSessionId || sessionState.newSessionDraft?.open) {
return;
}
if (sessionState.isLoading) {
scheduleDraftOpen(250);
return;
}
sessionState.openNewSessionDraft({ automatic: true });
}, delayMs);
};
scheduleDraftOpen(500);
return () => {
disposed = true;
if (timeoutId !== undefined) {
window.clearTimeout(timeoutId);
}
};
}, [activeSurface, isMobile, isSettingsDialogOpen, mobileLeftDrawerOpen, mobileRightSidebarOpen]);
// Ensure mobile drawers are closed when opening full-screen settings
useEffect(() => {
if (!isMobile || !isSettingsDialogOpen) {
return;
}
setMobileSessionPanelOpen(false);
setMobileRightSidebarOpen(false);
}, [isMobile, isSettingsDialogOpen, setMobileSessionPanelOpen]);
useUpdatePolling();
@@ -252,247 +85,83 @@ export const MainLayout: React.FC = () => {
}
}, [isMobile, setIsMobile]);
const handleToggleMobileRightDrawer = React.useCallback(() => {
if (mobileLeftDrawerOpen) {
setMobileSessionPanelOpen(false);
}
setMobileRightSidebarOpen(!mobileRightSidebarOpen);
}, [mobileLeftDrawerOpen, mobileRightSidebarOpen, setMobileSessionPanelOpen]);
const secondaryView = React.useMemo(() => {
// Desktop surfaces live in the context panel; the only full-view
// overlays left there are the terminal (promoted by project actions)
// and the diagram viewer. Mobile keeps the full tab set.
if (!isMobile && activeSurface !== 'terminal' && activeSurface !== 'diagram') {
return null;
}
switch (activeSurface) {
case 'plan':
return <React.Suspense fallback={null}><PlanView /></React.Suspense>;
case 'git':
return <React.Suspense fallback={null}><GitView isActive={!mobileRightSidebarOpen} /></React.Suspense>;
case 'diff':
return <React.Suspense fallback={null}><DiffView /></React.Suspense>;
case 'terminal':
return <TerminalView />;
case 'files':
return <React.Suspense fallback={null}><FilesView /></React.Suspense>;
case 'context':
return <React.Suspense fallback={null}><ProjectContextPanel /></React.Suspense>;
case 'diagram':
return <React.Suspense fallback={null}><DiagramView /></React.Suspense>;
default:
return null;
}
}, [activeSurface, isMobile, mobileRightSidebarOpen]);
const isChatActive = activeSurface === 'chat';
return (
<DiffWorkerProvider>
<div
data-page-scroll-lock="true"
className={cn(
'main-content-safe-area',
isMobile ? 'flex h-[100dvh] flex-col' : 'relative flex h-[100dvh]',
'bg-background'
)}
className="main-content-safe-area relative flex h-[100dvh] bg-background"
>
<CommandPalette />
<HelpDialog />
<OpenCodeStatusDialog />
<SessionDialogs />
{isMobile ? (
<DrawerProvider value={{
leftDrawerOpen: mobileLeftDrawerOpen,
rightDrawerOpen: mobileRightSidebarOpen,
toggleLeftDrawer: () => {
const nextOpen = !mobileLeftDrawerOpen;
if (mobileRightSidebarOpen) {
setMobileRightSidebarOpen(false);
}
setMobileSessionPanelOpen(nextOpen);
},
toggleRightDrawer: handleToggleMobileRightDrawer,
leftDrawerX,
rightDrawerX,
leftDrawerWidth,
rightDrawerWidth,
setMobileLeftDrawerOpen: setMobileSessionPanelOpen,
setRightSidebarOpen: setMobileRightSidebarOpen,
}}>
{/* Mobile: header + drawer mode */}
{!isSettingsDialogOpen && <Header
onToggleLeftDrawer={() => {
const nextOpen = !mobileLeftDrawerOpen;
if (mobileRightSidebarOpen) {
setMobileRightSidebarOpen(false);
}
setMobileSessionPanelOpen(nextOpen);
}}
onToggleRightDrawer={() => {
handleToggleMobileRightDrawer();
}}
leftDrawerOpen={mobileLeftDrawerOpen}
rightDrawerOpen={mobileRightSidebarOpen}
/>}
{/* Main content area (fixed) */}
<div
data-page-scroll-lock="true"
className={cn(
'flex flex-1 overflow-hidden relative',
isSettingsDialogOpen && 'hidden'
)}
{/* Persistent top-left controls (toggle + project actions) that
stay put while the sidebar/header animate beneath them. */}
<TitlebarLeftControls />
{/* Full-height Sidebar beside [Header above (chat | RightSidebar)] */}
<div className="flex flex-1 overflow-hidden" data-page-scroll-lock="true">
<Sidebar
isOpen={isSidebarOpen}
isMobile={isMobile}
className="border-border"
topBar={<SidebarTopBar />}
>
<main className="w-full h-full overflow-hidden bg-background relative" data-page-scroll-lock="true">
<div className={cn('absolute inset-0', (!isChatActive || isSurfacePageOpen) && 'invisible')}>
<ErrorBoundary><ChatView active={isChatActive && !isSettingsDialogOpen && !isSurfacePageOpen} /></ErrorBoundary>
</div>
{secondaryView && (
<div className={cn('absolute inset-0', isSurfacePageOpen && 'invisible')}>
<ErrorBoundary>{secondaryView}</ErrorBoundary>
</div>
)}
{isMultiRunLauncherOpen && (
<div className="absolute inset-0 z-10 bg-background">
<ErrorBoundary>
<MultiRunLauncher
initialPrompt={multiRunLauncherPrefillPrompt}
onCreated={() => setMultiRunLauncherOpen(false)}
onCancel={() => setMultiRunLauncherOpen(false)}
/>
</ErrorBoundary>
</div>
)}
<ErrorBoundary><ScheduledTasksDialog /></ErrorBoundary>
<ErrorBoundary><ArchiveView /></ErrorBoundary>
<ErrorBoundary><WorktreesView /></ErrorBoundary>
{/* Always mount SessionSidebar on mobile to match desktop behavior.
Conditional mount (mobileLeftDrawerVisible && ...) caused a
data-loading cascade on every drawer open: paginated sessions
fetch, worktree discovery, repo status, PR status, and 10+ memo
recomputations. On Android PWA this manifested as a >10s delay
before the drawer became interactive (issue #1695). Visibility is
controlled by the leftDrawerX transform (off-screen when closed).
The invisible class matters when fully hidden: leftDrawerWidth is
not recomputed on resize/rotation, so a closed drawer translated by
the old width could otherwise peek into the viewport; it also keeps
the off-screen sidebar out of the tab order and skips painting it. */}
<motion.div
className={cn(
'absolute inset-0 z-20 bg-sidebar',
!mobileLeftDrawerVisible && 'pointer-events-none invisible',
)}
data-page-scroll-lock="true"
style={{ x: leftDrawerX }}
aria-hidden={!mobileLeftDrawerOpen}
>
<ErrorBoundary>
<SessionSidebar mobileVariant isVisible={mobileLeftDrawerVisible} />
</ErrorBoundary>
</motion.div>
{mobileRightDrawerVisible && (
<motion.div className="absolute inset-0 z-20 bg-sidebar" data-page-scroll-lock="true" style={{ x: rightDrawerX }} aria-hidden={!mobileRightSidebarOpen}>
<ErrorBoundary>
<React.Suspense fallback={null}><GitView isActive={mobileRightSidebarOpen} /></React.Suspense>
</ErrorBoundary>
</motion.div>
)}
</main>
</div>
{/* Mobile settings: full screen */}
{isSettingsDialogOpen && (
<div
className="absolute inset-0 z-10 bg-background"
style={{ paddingTop: 'var(--oc-safe-area-top, 0px)' }}
>
<ErrorBoundary>
<React.Suspense fallback={null}>
<SettingsView onClose={() => setSettingsDialogOpen(false)} />
</React.Suspense>
</ErrorBoundary>
</div>
)}
</DrawerProvider>
) : (
<>
{/* Persistent top-left controls (toggle + project actions) that
stay put while the sidebar/header animate beneath them. */}
<TitlebarLeftControls />
{/* Desktop: full-height Sidebar beside [Header above (chat | RightSidebar)] */}
<div className="flex flex-1 overflow-hidden" data-page-scroll-lock="true">
<Sidebar
isOpen={isSidebarOpen}
isMobile={isMobile}
className="border-border"
topBar={<SidebarTopBar />}
>
<SessionSidebar isVisible={isSidebarOpen} />
</Sidebar>
<div className="relative flex flex-1 min-w-0 flex-col overflow-hidden bg-background" data-page-scroll-lock="true">
<Header />
<div className="relative flex flex-1 min-h-0 overflow-hidden bg-background" data-page-scroll-lock="true">
<div className="relative flex flex-1 min-w-0 flex-col overflow-hidden border-t border-border bg-background" data-page-scroll-lock="true">
<div className="flex flex-1 min-h-0 overflow-hidden" data-page-scroll-lock="true">
{/* Holds the chat and the context panel together, so its
width does not move when the context panel opens. The
work-status panel measures this rather than the chat,
which the context panel animates. */}
<div className="relative flex flex-1 min-h-0 min-w-0 overflow-hidden" data-page-scroll-lock="true" data-chat-area="true">
<main className="flex-1 overflow-hidden bg-background relative" data-page-scroll-lock="true">
<div className={cn('absolute inset-0', (!isChatActive || isSurfacePageOpen) && 'invisible')}>
<ErrorBoundary><ChatView active={isChatActive && !isSettingsDialogOpen && !isSurfacePageOpen} /></ErrorBoundary>
<SessionSidebar isVisible={isSidebarOpen} />
</Sidebar>
<div className="relative flex flex-1 min-w-0 flex-col overflow-hidden bg-background" data-page-scroll-lock="true">
<Header />
<div className="relative flex flex-1 min-h-0 overflow-hidden bg-background" data-page-scroll-lock="true">
<div className="relative flex flex-1 min-w-0 flex-col overflow-hidden border-t border-border bg-background" data-page-scroll-lock="true">
<div className="flex flex-1 min-h-0 overflow-hidden" data-page-scroll-lock="true">
{/* Holds the chat and the context panel together, so its
width does not move when the context panel opens. The
work-status panel measures this rather than the chat,
which the context panel animates. */}
<div className="relative flex flex-1 min-h-0 min-w-0 overflow-hidden" data-page-scroll-lock="true" data-chat-area="true">
<main className="flex-1 overflow-hidden bg-background relative" data-page-scroll-lock="true">
<div className={cn('absolute inset-0', isSurfacePageOpen && 'invisible')}>
<ErrorBoundary><ChatView active={!isSettingsDialogOpen && !isSurfacePageOpen} /></ErrorBoundary>
</div>
{isMultiRunLauncherOpen && (
<div className="absolute inset-0 z-10 bg-background">
<ErrorBoundary>
{/* isWindowed: the app Header already shows the surface
title, so skip the launcher's own title bar. */}
<MultiRunLauncher
isWindowed
initialPrompt={multiRunLauncherPrefillPrompt}
onCreated={() => setMultiRunLauncherOpen(false)}
onCancel={() => setMultiRunLauncherOpen(false)}
/>
</ErrorBoundary>
</div>
{secondaryView && (
<div className={cn('absolute inset-0', isSurfacePageOpen && 'invisible')}>
<ErrorBoundary>{secondaryView}</ErrorBoundary>
</div>
)}
{isMultiRunLauncherOpen && (
<div className="absolute inset-0 z-10 bg-background">
<ErrorBoundary>
{/* isWindowed: the app Header already shows the surface
title, so skip the launcher's own title bar. */}
<MultiRunLauncher
isWindowed
initialPrompt={multiRunLauncherPrefillPrompt}
onCreated={() => setMultiRunLauncherOpen(false)}
onCancel={() => setMultiRunLauncherOpen(false)}
/>
</ErrorBoundary>
</div>
)}
<ErrorBoundary><ScheduledTasksDialog /></ErrorBoundary>
<ErrorBoundary><ArchiveView /></ErrorBoundary>
<ErrorBoundary><WorktreesView /></ErrorBoundary>
</main>
<ContextPanel />
</div>
)}
<ErrorBoundary><ScheduledTasksDialog /></ErrorBoundary>
<ErrorBoundary><ArchiveView /></ErrorBoundary>
<ErrorBoundary><WorktreesView /></ErrorBoundary>
</main>
<ContextPanel />
</div>
</div>
<div className="border-t border-border" data-page-scroll-lock="true">
<ErrorBoundary><ContextPanelRail /></ErrorBoundary>
</div>
</div>
<div className="border-t border-border" data-page-scroll-lock="true">
<ErrorBoundary><ContextPanelRail /></ErrorBoundary>
</div>
</div>
</div>
</div>
{/* Desktop settings: windowed dialog with blur */}
{settingsWindowMounted ? (
<React.Suspense fallback={null}>
<SettingsWindow
open={isSettingsDialogOpen}
onOpenChange={setSettingsDialogOpen}
/>
</React.Suspense>
) : null}
</>
)}
</div>
</DiffWorkerProvider>
{/* Settings: windowed dialog with blur */}
{settingsWindowMounted ? (
<React.Suspense fallback={null}>
<SettingsWindow
open={isSettingsDialogOpen}
onOpenChange={setSettingsDialogOpen}
/>
</React.Suspense>
) : null}
</div>
</DiffWorkerProvider>
);
};
@@ -0,0 +1,426 @@
import React from 'react';
import {
DndContext,
MouseSensor,
TouchSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
type Modifier,
} from '@dnd-kit/core';
import {
SortableContext,
horizontalListSortingStrategy,
useSortable,
} from '@dnd-kit/sortable';
import { CSS as DndCSS } from '@dnd-kit/utilities';
import { ContextMenu } from '@base-ui/react/context-menu';
import type { Session } from '@opencode-ai/sdk/v2';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { dropdownMenuItemClass, dropdownMenuPopupClass, dropdownMenuSeparatorClass } from '@/components/ui/dropdown-menu.styles';
import { Icon } from '@/components/icon/Icon';
import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n';
import { useSessionTabsStore } from '@/stores/useSessionTabsStore';
import { closeSessionTabAndActivateNeighbour } from '@/lib/sessionTabs';
import { useGlobalSessionsStore, resolveGlobalSessionDirectory } from '@/stores/useGlobalSessionsStore';
import { useSessionUIStore } from '@/sync/session-ui-store';
import { useGlobalSessionStatus } from '@/sync/sync-context';
import { useSessionUnseenCount } from '@/sync/notification-store';
const restrictToXAxis: Modifier = ({ transform }) => ({ ...transform, y: 0 });
type SessionTab = { id: string; session: Session };
export type SessionTabMenuComponents = {
Item: React.ComponentType<{
className?: string;
disabled?: boolean;
onClick?: React.MouseEventHandler;
children?: React.ReactNode;
}>;
Separator: React.ComponentType<{ className?: string }>;
};
export type SessionTabMenuArgs = {
session: Session;
isActive: boolean;
select: () => void;
closeOtherTabs: () => void;
/** Menu primitives for the surface the menu opens in (dropdown or context menu). */
components: SessionTabMenuComponents;
};
const dropdownComponents: SessionTabMenuComponents = {
Item: DropdownMenuItem,
Separator: DropdownMenuSeparator,
};
const contextComponents: SessionTabMenuComponents = {
Item: ({ className, ...props }) => (
<ContextMenu.Item className={cn(dropdownMenuItemClass, className)} {...props} />
),
Separator: ({ className, ...props }) => (
<ContextMenu.Separator className={cn(dropdownMenuSeparatorClass, className)} {...props} />
),
};
/**
* One tab, active or not. The tab drags to reorder; the menu and close
* controls sit in a hover-revealed overlay at the tab's end (menu first,
* close after it). One session menu — supplied by the header via
* `renderMenu` — backs both the "..." dropdown and the right-click context
* menu, which opens under the cursor without changing the active tab. The
* dropdown's anchor overlay stays mounted through the close animation so the
* popup never flashes detached. While the active tab is renaming, the
* overlay is suppressed entirely — only the rename controls show.
*/
const SessionTabItem: React.FC<{
tab: SessionTab;
isActive: boolean;
suppressControls: boolean;
onSelect: (tab: SessionTab) => void;
onClose: (id: string) => void;
renderMenu: (args: SessionTabMenuArgs) => React.ReactNode;
closeOtherTabs: (id: string) => void;
onMenuOpenChangeComplete?: (open: boolean) => void;
children?: React.ReactNode;
}> = ({ tab, isActive, suppressControls, onSelect, onClose, renderMenu, closeOtherTabs, onMenuOpenChangeComplete, children }) => {
const { t } = useI18n();
const [menuOpen, setMenuOpen] = React.useState(false);
// Keeps the overlay (the dropdown's anchor) mounted through the close animation.
const [menuVisible, setMenuVisible] = React.useState(false);
const [contextMenuOpen, setContextMenuOpen] = React.useState(false);
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: tab.id });
const title = tab.session.title?.trim() || t('sessions.sidebar.session.untitled');
const overlayVisible = !suppressControls && (menuOpen || menuVisible);
// Session state for the dot and the hover tooltip.
const sessionStatus = useGlobalSessionStatus(tab.id);
const isStreaming = sessionStatus?.type === 'busy' || sessionStatus?.type === 'retry';
const unseenCount = useSessionUnseenCount(tab.id);
const showUnread = unseenCount > 0 && !isActive && !isStreaming;
const showDot = isStreaming || showUnread;
const dotLabel = isStreaming
? t('sessions.sidebar.session.status.active')
: t('sessions.sidebar.session.status.unread');
const menuArgsFor = (components: SessionTabMenuComponents): SessionTabMenuArgs => ({
session: tab.session,
isActive,
select: () => onSelect(tab),
closeOtherTabs: () => closeOtherTabs(tab.id),
components,
});
return (
<div
ref={setNodeRef}
style={{ transform: DndCSS.Translate.toString(transform), transition }}
className={cn('session-tab-slot flex h-7 w-44 shrink-0 touch-none', isDragging && 'z-10 opacity-60')}
data-active={isActive ? 'true' : 'false'}
{...(isActive ? { 'data-active-session-tab': true } : {})}
{...attributes}
{...listeners}
>
<ContextMenu.Root
open={contextMenuOpen}
onOpenChange={setContextMenuOpen}
onOpenChangeComplete={(open) => onMenuOpenChangeComplete?.(open)}
>
<ContextMenu.Trigger
render={(triggerProps) => (
<div
{...triggerProps}
role="tab"
aria-selected={isActive}
tabIndex={isActive ? undefined : 0}
onClick={isActive ? undefined : () => onSelect(tab)}
onKeyDown={isActive ? undefined : (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
onSelect(tab);
}
}}
onAuxClick={(event) => {
if (event.button === 1) {
event.preventDefault();
onClose(tab.id);
}
}}
data-controls-open={overlayVisible ? 'true' : 'false'}
className={cn(
'session-tab group/session-tab relative flex h-7 w-full min-w-0 select-none items-center rounded-md px-2',
'transition-colors duration-75',
isActive
? 'bg-interactive-selection'
: cn(
'cursor-pointer text-muted-foreground hover:bg-interactive-hover hover:text-foreground',
overlayVisible && 'bg-interactive-hover text-foreground',
),
)}
>
<div className={cn(
'flex min-w-0 flex-1 items-center',
!suppressControls && 'group-hover/session-tab:pr-10',
overlayVisible && 'pr-10',
)}
>
<div className={cn(
'min-w-0 flex-1 overflow-hidden whitespace-nowrap',
!suppressControls && 'session-tab-title',
)}
>
{isActive ? children : (
<span className="text-[13px] font-medium leading-4">{title}</span>
)}
</div>
{showDot ? (
<span
className={cn(
'ml-1.5 h-1.5 w-1.5 shrink-0 rounded-full',
isStreaming ? 'bg-primary' : 'bg-[var(--status-info)]',
!suppressControls && 'group-hover/session-tab:opacity-0',
overlayVisible && 'opacity-0',
)}
aria-label={dotLabel}
/>
) : null}
</div>
{!suppressControls ? (
<div
onClick={(event) => event.stopPropagation()}
onPointerDown={(event) => event.stopPropagation()}
className={cn(
'absolute right-1 top-1/2 hidden -translate-y-1/2 items-center gap-0.5',
'opacity-0 transition-opacity duration-150',
'group-hover/session-tab:flex group-hover/session-tab:opacity-100',
overlayVisible && 'flex opacity-100',
)}
>
<DropdownMenu
open={menuOpen}
onOpenChange={(open) => {
setMenuOpen(open);
if (open) setMenuVisible(true);
}}
onOpenChangeComplete={(open) => {
if (!open) setMenuVisible(false);
onMenuOpenChangeComplete?.(open);
}}
>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label={t('header.sessionTabs.tabMenuAria')}
className="flex size-5 items-center justify-center rounded text-muted-foreground hover:text-foreground"
>
<Icon name="more" className="size-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="min-w-[190px]">
{renderMenu(menuArgsFor(dropdownComponents))}
</DropdownMenuContent>
</DropdownMenu>
<button
type="button"
aria-label={t('header.sessionTabs.closeTab')}
onClick={() => onClose(tab.id)}
className="flex size-5 items-center justify-center rounded text-muted-foreground hover:text-foreground"
>
<Icon name="close" className="size-4" />
</button>
</div>
) : null}
</div>
)}
/>
<ContextMenu.Portal>
<ContextMenu.Positioner className="app-region-no-drag z-50">
<ContextMenu.Popup
data-slot="dropdown-menu-content"
style={{ color: 'var(--surface-elevated-foreground)' }}
className={cn(dropdownMenuPopupClass, 'min-w-[190px]')}
>
{renderMenu(menuArgsFor(contextComponents))}
</ContextMenu.Popup>
</ContextMenu.Positioner>
</ContextMenu.Portal>
</ContextMenu.Root>
</div>
);
};
/**
* The header's horizontal working set of sessions (web/desktop only).
*
* Every session the user opens joins the strip once; the tab whose session is
* current renders `children` — the header's title/rename block — inside a
* selected pill. Closing a tab only removes it from the strip; closing the
* active one activates its neighbour. Ids whose session has not loaded (or
* was archived/deleted) stay in the store but do not render, so a partial
* session list never destroys the working set.
*/
export const SessionTabsStrip: React.FC<{
/** Menu items for one tab's session, supplied by the header. */
renderMenu: (args: SessionTabMenuArgs) => React.ReactNode;
/** Fires when a tab menu finishes opening/closing (deferred rename hook). */
onMenuOpenChangeComplete?: (open: boolean) => void;
/** While the active tab renames, its hover controls stay hidden. */
suppressActiveTabControls?: boolean;
children: React.ReactNode;
}> = ({ renderMenu, onMenuOpenChangeComplete, suppressActiveTabControls = false, children }) => {
const { t } = useI18n();
const tabIds = useSessionTabsStore((state) => state.tabIds);
const ensureTab = useSessionTabsStore((state) => state.ensureTab);
const closeOtherTabs = useSessionTabsStore((state) => state.closeOtherTabs);
const reorderTabs = useSessionTabsStore((state) => state.reorderTabs);
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
const setCurrentSession = useSessionUIStore((state) => state.setCurrentSession);
const activeSessions = useGlobalSessionsStore((state) => state.activeSessions);
// Opening a session anywhere (sidebar, palette, deep link) adds its tab.
React.useEffect(() => {
if (currentSessionId) ensureTab(currentSessionId);
}, [currentSessionId, ensureTab]);
const sessionsById = React.useMemo(() => {
const map = new Map<string, Session>();
for (const session of activeSessions) map.set(session.id, session);
return map;
}, [activeSessions]);
// Only tabs with a known live session render; unknown ids stay stored.
const tabs = React.useMemo<SessionTab[]>(() => {
const list: SessionTab[] = [];
for (const id of tabIds) {
const session = sessionsById.get(id);
if (session) list.push({ id, session });
}
return list;
}, [tabIds, sessionsById]);
const handleSelect = React.useCallback((tab: SessionTab) => {
setCurrentSession(tab.id, resolveGlobalSessionDirectory(tab.session));
}, [setCurrentSession]);
const handleClose = React.useCallback((id: string) => {
closeSessionTabAndActivateNeighbour(id);
}, []);
const handleCloseOthers = React.useCallback((id: string) => {
closeOtherTabs(id);
if (currentSessionId && currentSessionId !== id) {
const kept = tabs.find((tab) => tab.id === id);
if (kept) handleSelect(kept);
}
}, [closeOtherTabs, currentSessionId, handleSelect, tabs]);
const sensors = useSensors(
useSensor(MouseSensor, { activationConstraint: { distance: 8 } }),
useSensor(TouchSensor, { activationConstraint: { delay: 200, tolerance: 6 } }),
);
const handleDragEnd = React.useCallback((event: DragEndEvent) => {
const { active, over } = event;
if (over && active.id !== over.id) {
reorderTabs(String(active.id), String(over.id));
}
}, [reorderTabs]);
// Soft fade at the edges while more tabs hide behind them.
const scrollRef = React.useRef<HTMLDivElement | null>(null);
const [edges, setEdges] = React.useState({ left: false, right: false });
const updateEdges = React.useCallback(() => {
const node = scrollRef.current;
if (!node) return;
const left = node.scrollLeft > 2;
const right = node.scrollLeft + node.clientWidth < node.scrollWidth - 2;
setEdges((prev) => (prev.left === left && prev.right === right ? prev : { left, right }));
}, []);
React.useEffect(() => {
updateEdges();
const node = scrollRef.current;
if (!node || !globalThis.ResizeObserver) return;
const observer = new ResizeObserver(updateEdges);
observer.observe(node);
return () => observer.disconnect();
}, [updateEdges, tabs.length]);
// Keep the active tab in view when it changes.
React.useEffect(() => {
scrollRef.current
?.querySelector('[data-active-session-tab]')
?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
}, [currentSessionId]);
const maskImage = edges.left && edges.right
? 'linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent)'
: edges.left
? 'linear-gradient(to right, transparent, black 24px)'
: edges.right
? 'linear-gradient(to right, black calc(100% - 24px), transparent)'
: undefined;
const tabIdsInOrder = React.useMemo(() => tabs.map((tab) => tab.id), [tabs]);
// A brand-new draft (no session yet) shows as a transient active pill after
// the tabs; it becomes a real tab once the first message creates the session.
const showDraftPill = !currentSessionId || !tabs.some((tab) => tab.id === currentSessionId);
return (
<div className="app-region-no-drag flex h-full min-w-0 flex-1 items-center" role="tablist" aria-label={t('header.sessionTabs.stripAria')}>
<div
ref={scrollRef}
onScroll={updateEdges}
className="session-tabs-scroll flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto overscroll-x-contain"
style={maskImage ? { maskImage, WebkitMaskImage: maskImage } : undefined}
>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
modifiers={[restrictToXAxis]}
onDragEnd={handleDragEnd}
>
<SortableContext items={tabIdsInOrder} strategy={horizontalListSortingStrategy}>
{tabs.map((tab) => (
<SessionTabItem
key={tab.id}
tab={tab}
isActive={tab.id === currentSessionId}
suppressControls={tab.id === currentSessionId && suppressActiveTabControls}
onSelect={handleSelect}
onClose={handleClose}
renderMenu={renderMenu}
closeOtherTabs={handleCloseOthers}
onMenuOpenChangeComplete={onMenuOpenChangeComplete}
>
{tab.id === currentSessionId ? children : null}
</SessionTabItem>
))}
</SortableContext>
</DndContext>
{showDraftPill ? (
<div
role="tab"
aria-selected
className="session-tab-slot flex h-7 w-44 shrink-0 items-center rounded-md bg-interactive-selection px-2"
data-active="true"
>
<div className="min-w-0 flex-1">{children}</div>
</div>
) : null}
</div>
</div>
);
};
@@ -56,10 +56,10 @@ const formatTime = (timestamp: number | null, timeFormatPreference: TimeFormatPr
// Width threshold for mobile vs desktop layout in settings
const MOBILE_WIDTH_THRESHOLD = 550;
// Width threshold for expanded layout (sidebar + chat side by side)
const EXPANDED_LAYOUT_THRESHOLD = 1400;
// Sessions sidebar width in expanded layout
const SESSIONS_SIDEBAR_WIDTH = 280;
// Keep enough room for the chat after adding the persistent sessions sidebar.
const EXPANDED_LAYOUT_THRESHOLD = SESSIONS_SIDEBAR_WIDTH + 520;
const SESSIONS_SIDEBAR_MIN_WIDTH = Math.round(SESSIONS_SIDEBAR_WIDTH * 0.7);
const SESSIONS_SIDEBAR_MAX_WIDTH = 520;