import { useRef, useState } from 'react' import { IconArchive, IconEdit, IconHistory, IconPin, IconPinFilled } from '@tabler/icons-react' import { useArchiveWorkspaceSession, useWorkspaceSessions } from './api' import { useWorkspaceHarness } from '@/client/features/workspace/api' import { useWorkspaceId } from '@/client/features/workspace/workspace-context' import { useSelectedSession, useCurrentTabId, usePinnedSession } from '@/client/features/chat/sessions/use-selected-session' import { cn } from '@/client/lib/cn' import { isSessionRunning, liveStore, useLive } from '@/client/features/chat/chat-store' import type { SessionInfo, WorkspaceTabId } from '@/lib/types' import { Button } from '@/client/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/client/components/ui/tooltip' import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from '@/client/components/ui/dropdown-menu' import { Spinner } from '@/client/components/ui/spinner' type ChatSelectorProps = { className?: string } type SessionSelectorProps = ChatSelectorProps & { sessions: SessionInfo[] } type ChatSessionGroup = { key: string label: string sessions: SessionInfo[] } // One tiny text badge per row at most: a cron/subagent flavor wins; otherwise // an external origin shows its provider lowercase (e.g. "irc", "telegram"). // Plain app chats get none. export function sessionBadge(session: SessionInfo): string | null { if (session.flavor === 'cron' || session.flavor === 'subagent') return session.flavor const provider = session.origin?.provider.trim().toLowerCase() return provider ? provider : null } type ChatSessionItemProps = { active: boolean canArchive: boolean confirmingArchive: boolean onArchive: (sessionId: string) => Promise onRequestArchive: (sessionId: string) => void onSelect: (sessionId: string) => void session: SessionInfo workspaceId: string } // One chat row inside the selector menu (summary, flavor/origin badge, running // spinner, archive affordance). Exported for the /dev/chat-states catalog. export function ChatSessionItem({ active, canArchive, confirmingArchive, onArchive, onRequestArchive, onSelect, session, workspaceId }: ChatSessionItemProps) { const pendingRef = useRef(false) const [pending, setPending] = useState(false) const running = useLive(state => isSessionRunning(state.activity, workspaceId, session.sessionId)) const badge = sessionBadge(session) function handleRequestArchive() { onRequestArchive(session.sessionId) } async function handleConfirmArchive() { if (pendingRef.current) return pendingRef.current = true setPending(true) try { await onArchive(session.sessionId) } catch { // The archive request already reported the failure. } finally { pendingRef.current = false setPending(false) } } return (
onSelect(session.sessionId)} >
{session.summary} {badge && {badge}}
{running && ( )} {canArchive && (
{confirmingArchive ? ( ) : ( event.stopPropagation()} > } /> Archive chat )}
)}
) } function localDateKey(date: Date): string { return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}` } function calendarDayNumber(date: Date): number { return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86_400_000 } function formatGroupLabel(date: Date, now: Date): string { const daysAgo = calendarDayNumber(now) - calendarDayNumber(date) if (daysAgo === 0) return 'Today' if (daysAgo === 1) return 'Yesterday' if (daysAgo >= 2 && daysAgo <= 5) return `${daysAgo} days ago` return date.toLocaleDateString([], { month: 'short', day: 'numeric', ...(date.getFullYear() === now.getFullYear() ? {} : { year: 'numeric' }) }) } export function groupSessionsByDate(sessions: SessionInfo[], now = new Date()): ChatSessionGroup[] { const groups = new Map() for (const session of sessions.slice().sort((a, b) => b.lastModified - a.lastModified)) { const date = new Date(session.lastModified) const key = localDateKey(date) const group = groups.get(key) if (group) { group.sessions.push(session) continue } groups.set(key, { key, label: formatGroupLabel(date, now), sessions: [session] }) } return [...groups.values()] } export function groupSessionsForTab( sessions: SessionInfo[], tabId: WorkspaceTabId, now = new Date() ): ChatSessionGroup[] { return groupSessionsByDate( sessions.filter(session => tabId === 'overview' ? !session.tabId?.startsWith('views/') : session.tabId === tabId ), now ) } export function ChatSelector({ className }: ChatSelectorProps) { const workspaceId = useWorkspaceId() const { pinnedSessionId, loaded, pin, unpin } = usePinnedSession() const [selectedSessionId] = useSelectedSession() const { data: sessions = [] } = useWorkspaceSessions(workspaceId) if (!loaded) return null if (pinnedSessionId) { const title = sessions.find(session => session.sessionId === pinnedSessionId)?.summary if (!title) return null return (
{title} } /> Unpin chat
) } return (
{selectedSessionId && ( pin(selectedSessionId)} aria-label="Pin chat to workspace" aria-pressed={false} > } /> Pin chat to workspace )}
) } function SessionSelector({ className, sessions }: SessionSelectorProps) { const workspaceId = useWorkspaceId() const tabId = useCurrentTabId() const [selectedSessionId, selectSession] = useSelectedSession() const [confirmingSessionId, setConfirmingSessionId] = useState(null) const canArchive = useWorkspaceHarness(workspaceId).data?.supportsArchiving === true const archiveSession = useArchiveWorkspaceSession(workspaceId) const sessionGroups = groupSessionsForTab(sessions, tabId) if (sessionGroups.length === 0 && !selectedSessionId) return null function handleMenuOpenChange(open: boolean) { if (!open) setConfirmingSessionId(null) } async function handleArchive(sessionId: string) { setConfirmingSessionId(null) await archiveSession.mutateAsync(sessionId) const store = liveStore.getState() store.clearAttachments(workspaceId, sessionId) store.clearPreviewsForSession(workspaceId, sessionId) if (selectedSessionId === sessionId) { selectSession(null) } } return selectedSessionId ? ( selectSession(null)} className={className} > } /> New chat ) : ( } /> } /> History
{sessionGroups.map(group => ( {group.label} {group.sessions.map(session => ( ))} ))}
) }