Chats tab in the session picker (phone sheet and desktop

This commit is contained in:
Chris Scott committed 2026-11-07 15:54:59 -05:00
1 parent ccb150d5e6
commit 5846ee3c20
5 files changed
+729 -279

No files matched your search

@@ -0,0 +1,217 @@
import { useCallback, useEffect, useId, useMemo, useState } from 'react'
import type { Session } from '@/api/types'
import { Button } from '@/components/ui/button'
import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog'
import {
SessionPickerList,
type SessionPickerRow,
type SessionPickerSection,
} from '@/components/session/SessionPickerList'
import {
PickerSearchBar,
optionId,
usePickerCursor,
usePickerKeyNav,
} from '@/components/session/usePickerKeyboardNav'
import { useChatSessions, useDeleteChatSession, type ChatSessionRow } from '@/hooks/useChats'
import { useToggleSessionPin } from '@/hooks/useSessionPins'
interface ChatPickerContentProps {
open: boolean
activeSessionID?: string
onNavigate: (path: string) => void
onDeleteActiveSession: () => void
searchInputRef: React.RefObject<HTMLInputElement | null>
searchTrailing?: React.ReactNode
}
/**
* Chat sessions for the shared session picker: newest first, filtered by title, with pin and
* confirm-before-delete actions on the same row menu as every other picker list.
*/
export function ChatPickerContent({
open,
activeSessionID,
onNavigate,
onDeleteActiveSession,
searchInputRef,
searchTrailing,
}: ChatPickerContentProps) {
const { rows: chatRows, hasMore, showMore, isLoading, isError } = useChatSessions(10)
const listId = useId()
const optionBaseId = useId()
const togglePin = useToggleSessionPin()
const deleteChatSession = useDeleteChatSession()
const [query, setQuery] = useState('')
const [chatToDelete, setChatToDelete] = useState<ChatSessionRow | null>(null)
const trimmedQuery = query.trim()
const pinnedKeys = useMemo(
() => new Set(chatRows.filter((row) => row.isPinned).map((row) => row.key)),
[chatRows],
)
const rowByKey = useMemo(() => new Map(chatRows.map((row) => [row.key, row])), [chatRows])
const sections = useMemo<SessionPickerSection[]>(() => {
const needle = trimmedQuery.toLowerCase()
const filtered = needle
? chatRows.filter((row) => (row.session.title ?? '').toLowerCase().includes(needle))
: chatRows
return filtered.length > 0 ? [{ id: 'chats', heading: 'Chats', rows: filtered }] : []
}, [chatRows, trimmedQuery])
const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
const activeRow = useMemo(
() => rows.find((row) => row.session.id === activeSessionID),
[rows, activeSessionID],
)
const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null
const {
rowIndexByKey,
cursorIndex,
cursorRow,
registerRef,
moveCursor,
resetCursor,
} = usePickerCursor(rows, defaultCursorKey)
const openRow = useCallback(
(row: SessionPickerRow | undefined) => {
if (!row) return
const chatRow = rowByKey.get(row.key)
if (chatRow) onNavigate(chatRow.path)
},
[rowByKey, onNavigate],
)
const requestDeleteRow = useCallback(
(row: SessionPickerRow | undefined) => {
const chatRow = row ? rowByKey.get(row.key) : undefined
if (chatRow) setChatToDelete(chatRow)
},
[rowByKey],
)
const handleRequestDelete = useCallback(
(session: Session) => {
const chatRow = chatRows.find((row) => row.session.id === session.id)
if (chatRow) setChatToDelete(chatRow)
},
[chatRows],
)
const handleTogglePin = useCallback(
(row: SessionPickerRow) => {
const chatRow = rowByKey.get(row.key)
if (!chatRow) return
togglePin.mutate({
sessionId: chatRow.session.id,
directory: chatRow.session.location.directory,
pinned: !pinnedKeys.has(chatRow.key),
})
},
[rowByKey, pinnedKeys, togglePin],
)
useEffect(() => {
resetCursor()
}, [trimmedQuery, resetCursor])
const handleSearchKeyDown = usePickerKeyNav({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow: openRow,
onDeleteRow: requestDeleteRow,
})
const confirmDelete = useCallback(() => {
if (!chatToDelete) return
if (chatToDelete.session.id === activeSessionID) onDeleteActiveSession()
void deleteChatSession
.mutateAsync({
chatId: chatToDelete.chat.id,
sessionId: chatToDelete.session.id,
directory: chatToDelete.session.location.directory,
})
.catch(() => undefined)
.finally(() => setChatToDelete(null))
}, [chatToDelete, activeSessionID, onDeleteActiveSession, deleteChatSession])
const emptyState = isLoading
? 'Loading chats...'
: isError
? 'Failed to load chats'
: trimmedQuery
? 'No chats found'
: 'No chats yet'
return (
<>
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<PickerSearchBar
inputRef={searchInputRef}
listId={listId}
open={open}
activeDescendantId={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
value={query}
onChange={setQuery}
onKeyDown={handleSearchKeyDown}
placeholder="Search chats..."
name="chat-picker-search"
trailing={searchTrailing}
/>
<SessionPickerList
listId={listId}
optionBaseId={optionBaseId}
ariaLabel="Chats"
sections={sections}
rows={rows}
rowIndexByKey={rowIndexByKey}
cursorIndex={cursorIndex}
activeSessionID={activeSessionID}
pinnedKeys={pinnedKeys}
pendingDeleteKey={null}
showRepo={false}
emptyState={emptyState}
onOpenRow={openRow}
onHoverRow={moveCursor}
onTogglePin={handleTogglePin}
onRequestDelete={handleRequestDelete}
registerRef={registerRef}
>
{hasMore && (
<div className="flex justify-center py-4">
<Button
variant="outline"
size="sm"
onClick={() => {
void showMore()
}}
>
Show more
</Button>
</div>
)}
</SessionPickerList>
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
↑↓ move · Enter open · Ctrl+D delete
</div>
</div>
<DeleteSessionDialog
open={chatToDelete !== null}
onOpenChange={(nextOpen) => {
if (!nextOpen) setChatToDelete(null)
}}
onConfirm={confirmDelete}
onCancel={() => setChatToDelete(null)}
isDeleting={deleteChatSession.isPending}
/>
</>
)
}
@@ -5,6 +5,7 @@ import { render, screen, fireEvent, waitFor, act, within } from '@testing-librar
import userEvent from '@testing-library/user-event'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import type { Repo, Session } from '@/api/types'
import type { ChatSessionRow } from '@/hooks/useChats'
import type { ActiveWorkGroups, ActiveWorkItem, ActiveWorkState } from '@/lib/activeWork'
import { stubMatchMedia } from '@/test/test-utils'
import { makeRepo, makeSession } from '@/test/fixtures/session-picker'
@@ -33,6 +34,15 @@ const mocks = vi.hoisted(() => ({
repos: [] as Repo[],
activeWorkGroups: { needsInput: [], running: [], recent: [] } as ActiveWorkGroups,
activeWorkWindowMs: 0,
chatRows: [] as ChatSessionRow[],
chatHasMore: false,
chatIsLoading: false,
chatIsError: false,
chatError: undefined as Error | undefined,
createdChatId: '20260101-120000-abc123',
showMoreChats: vi.fn(),
createChatMock: vi.fn(),
deleteChatSessionMock: vi.fn(),
preferences: undefined as
| {
leaderKey?: string
@@ -113,6 +123,32 @@ vi.mock('@/hooks/useSessionPins', () => ({
useToggleSessionPin: () => ({ mutate: mocks.togglePinMock }),
}))
vi.mock('@/hooks/useChats', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useChats')>()
return {
...actual,
useChatSessions: () => ({
rows: mocks.chatRows,
hasMore: mocks.chatHasMore,
showMore: mocks.showMoreChats,
isLoading: mocks.chatIsLoading,
isError: mocks.chatIsError,
error: mocks.chatError,
}),
useCreateChat: (onCreated?: (path: string) => void) => ({
mutate: () => {
mocks.createChatMock()
onCreated?.(`/chats/${mocks.createdChatId}/sessions/ses_new`)
},
isPending: false,
}),
useDeleteChatSession: () => ({
mutateAsync: mocks.deleteChatSessionMock,
isPending: false,
}),
}
})
vi.mock('@/components/navigation/RemoteProjectNav', () => ({
RemoteProjectNavList: ({ serverId }: { serverId: string }) => (
<div data-testid="remote-project-nav" data-server={serverId} />
@@ -157,6 +193,23 @@ function activeWorkItem(
}
}
function makeChatRow(
sessionId: string,
title: string,
directory: string,
updated: number,
chatId: string,
): ChatSessionRow {
const session = makeSession(sessionId, title, directory, updated)
return {
key: `${directory}:${sessionId}`,
session,
chat: { id: chatId, directory, filesPath: `${directory}/.chats/${chatId}`, createdAt: updated },
path: `/chats/${chatId}/sessions/${sessionId}`,
isPinned: false,
}
}
function renderWithClient(ui: React.ReactElement, serverId?: string) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const directory = mocks.repos[0]?.fullPath
@@ -205,6 +258,10 @@ const openActiveTab = () => {
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Activity' }))
}
const openChatsTab = () => {
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Chats' }))
}
describe('SessionPickerDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -225,6 +282,12 @@ describe('SessionPickerDialog', () => {
mocks.sessionsData = []
mocks.activeWorkGroups = { needsInput: [], running: [], recent: [] }
mocks.activeWorkWindowMs = 0
mocks.chatRows = []
mocks.chatHasMore = false
mocks.chatIsLoading = false
mocks.chatIsError = false
mocks.chatError = undefined
mocks.deleteChatSessionMock.mockResolvedValue(undefined)
mocks.preferences = undefined
})
@@ -669,11 +732,12 @@ describe('SessionPickerDialog', () => {
expect(screen.getByRole('option', { name: /Active session/ })).toHaveAttribute('aria-selected', 'true')
})
it('renders an Activity/Sessions/Projects tab switcher and defaults to the sessions tab', () => {
it('renders an Activity/Sessions/Chats/Projects tab switcher and defaults to the sessions tab', () => {
renderPicker()
expect(screen.getByRole('tab', { name: 'This project' })).toHaveAttribute('aria-selected', 'true')
expect(screen.getByRole('tab', { name: 'Activity' })).toHaveAttribute('aria-selected', 'false')
expect(screen.getByRole('tab', { name: 'Chats' })).toHaveAttribute('aria-selected', 'false')
expect(screen.getByRole('tab', { name: 'Projects' })).toHaveAttribute('aria-selected', 'false')
expect(combobox()).toHaveAttribute('placeholder', 'Search sessions...')
})
@@ -714,6 +778,8 @@ describe('SessionPickerDialog', () => {
await user.click(screen.getByPlaceholderText('Search sessions...'))
await user.keyboard('{Control>}s{/Control}')
await waitFor(() => expect(screen.getByPlaceholderText('Search chats...')).toHaveFocus())
await user.keyboard('{Control>}s{/Control}')
await waitFor(() => expect(screen.getByPlaceholderText('Search projects...')).toHaveFocus())
})
@@ -726,6 +792,8 @@ describe('SessionPickerDialog', () => {
await user.click(screen.getByPlaceholderText('Search sessions...'))
await user.keyboard('{Control>}s{/Control}')
await waitFor(() => expect(screen.getByPlaceholderText('Search chats...')).toHaveFocus())
await user.keyboard('{Control>}s{/Control}')
await waitFor(() => expect(screen.getByPlaceholderText('Search projects...')).toHaveFocus())
})
@@ -826,11 +894,14 @@ describe('SessionPickerDialog', () => {
expect(screen.getByText('No projects found')).toBeInTheDocument()
})
it('cycles Activity, Sessions and Projects with the default Ctrl+S binding', async () => {
it('cycles Sessions, Chats, Projects and Activity with the default Ctrl+S binding', async () => {
renderPicker()
expect(screen.getByRole('tab', { name: 'This project', selected: true })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 's', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Chats', selected: true })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 's', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Projects', selected: true })).toBeInTheDocument()
@@ -847,6 +918,9 @@ describe('SessionPickerDialog', () => {
expect(screen.getByText(/Ctrl\+G projects/)).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 'g', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Chats', selected: true })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 'g', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Projects', selected: true })).toBeInTheDocument()
@@ -1013,6 +1087,124 @@ describe('SessionPickerDialog', () => {
})
})
describe('chats tab', () => {
const chatFixture = () => [
makeChatRow('ses_new', 'Newest chat', '/w/chat-newest', 3000, '20260103-100000-cccccc'),
makeChatRow('ses_mid', 'Middle chat', '/w/chat-mid', 2000, '20260102-100000-bbbbbb'),
makeChatRow('ses_old', 'Oldest chat', '/w/chat-old', 1000, '20260101-100000-aaaaaa'),
]
it('lists chat sessions newest first in the order the hook returns them', async () => {
mocks.chatRows = chatFixture()
renderPicker()
openChatsTab()
const options = await screen.findAllByRole('option')
expect(options).toHaveLength(3)
expect(options[0]).toHaveTextContent('Newest chat')
expect(options[1]).toHaveTextContent('Middle chat')
expect(options[2]).toHaveTextContent('Oldest chat')
})
it('filters chats by title without matching other tabs', async () => {
mocks.chatRows = chatFixture()
renderPicker()
openChatsTab()
await screen.findByRole('option', { name: /Newest chat/ })
fireEvent.change(combobox(), { target: { value: 'middle' } })
expect(screen.queryByRole('option', { name: /Newest chat/ })).not.toBeInTheDocument()
expect(screen.getByRole('option', { name: /Middle chat/ })).toBeInTheDocument()
fireEvent.change(combobox(), { target: { value: 'zzz' } })
expect(screen.getByText('No chats found')).toBeInTheDocument()
})
it('shows the show more action and forwards it to the chats hook', async () => {
mocks.chatRows = chatFixture()
mocks.chatHasMore = true
renderPicker()
openChatsTab()
await screen.findByRole('option', { name: /Newest chat/ })
fireEvent.click(screen.getByRole('button', { name: 'Show more' }))
expect(mocks.showMoreChats).toHaveBeenCalledTimes(1)
})
it('creates a chat from the header action and navigates to its new session', async () => {
const onNavigate = vi.fn()
renderPicker({ onNavigate })
openChatsTab()
fireEvent.click(await screen.findByRole('button', { name: 'New chat' }))
expect(mocks.createChatMock).toHaveBeenCalledTimes(1)
expect(onNavigate).toHaveBeenCalledWith(
`/chats/${mocks.createdChatId}/sessions/ses_new`,
)
})
it('pins a chat from the shared row menu', async () => {
mocks.chatRows = [chatFixture()[0]]
renderPicker()
const user = userEvent.setup()
openChatsTab()
await screen.findByRole('option', { name: /Newest chat/ })
await user.click(screen.getByRole('button', { name: 'Session actions' }))
await user.click(await screen.findByText('Pin'))
expect(mocks.togglePinMock).toHaveBeenCalledWith({
sessionId: 'ses_new',
directory: '/w/chat-newest',
pinned: true,
})
})
it('opens the delete confirmation with Ctrl+D', async () => {
mocks.chatRows = [chatFixture()[0]]
renderPicker()
openChatsTab()
await screen.findByRole('option', { name: /Newest chat/ })
fireEvent.keyDown(combobox(), { key: 'd', ctrlKey: true })
expect(await screen.findByRole('dialog', { name: 'Delete Session' })).toBeInTheDocument()
expect(mocks.deleteChatSessionMock).not.toHaveBeenCalled()
})
it('deletes a chat session after confirmation and clears the active session first', async () => {
mocks.chatRows = [chatFixture()[0]]
const { onDeleteActiveSession } = renderPicker({ activeSessionID: 'ses_new' })
const user = userEvent.setup()
openChatsTab()
await screen.findByRole('option', { name: /Newest chat/ })
await user.click(screen.getByRole('button', { name: 'Session actions' }))
await user.click(await screen.findByText('Delete'))
const dialog = await screen.findByRole('dialog', { name: 'Delete Session' })
await user.click(within(dialog).getByRole('button', { name: 'Delete' }))
await waitFor(() =>
expect(mocks.deleteChatSessionMock).toHaveBeenCalledWith({
chatId: '20260103-100000-cccccc',
sessionId: 'ses_new',
directory: '/w/chat-newest',
}),
)
expect(onDeleteActiveSession).toHaveBeenCalledTimes(1)
expect(onDeleteActiveSession.mock.invocationCallOrder[0]).toBeLessThan(
mocks.deleteChatSessionMock.mock.invocationCallOrder[0],
)
})
})
describe('linked-server mode', () => {
beforeEach(() => {
mocks.repos = [makeRepo(1, 'alpha', '/w/a')]
@@ -1032,6 +1224,7 @@ describe('SessionPickerDialog', () => {
expect(screen.getByRole('tab', { name: 'Projects' })).toBeInTheDocument()
expect(screen.getByRole('tab', { name: 'Activity' })).toBeInTheDocument()
expect(screen.queryByRole('tab', { name: 'Chats' })).not.toBeInTheDocument()
const row = await screen.findByRole('option', { name: /Remote session/ })
expect(row).toHaveTextContent('Kitchen')
@@ -1,7 +1,7 @@
import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { format, startOfDay } from 'date-fns'
import { ChevronsUpDown, MoreHorizontal, Pin, PinOff, Plus } from 'lucide-react'
import { ChevronsUpDown, Plus } from 'lucide-react'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { OpenCodeServerProvider, useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
import { openCodeLocationQueryOptions } from '@/lib/openCodeLocation'
@@ -9,18 +9,17 @@ import type { Repo, Session } from '@/api/types'
import { ACTIVE_WORK_GROUPS, MS_PER_MINUTE, formatActivityEmptyMessage } from '@/lib/activeWork'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog'
import { ChatPickerContent } from '@/components/session/ChatPickerContent'
import {
SessionPickerList,
type SessionPickerRow,
type SessionPickerSection,
} from '@/components/session/SessionPickerList'
import { ProjectPickerContent } from '@/components/session/ProjectPickerContent'
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
import { LocalRepoNewSessionButton } from '@/components/navigation/RepoSessionNav'
import { LocalRepoNewSessionButton, NewChatButton } from '@/components/navigation/RepoSessionNav'
import { RemoteProjectNavList } from '@/components/navigation/RemoteProjectNav'
import {
PickerSearchBar,
@@ -36,25 +35,25 @@ import { useSessionSearch } from '@/hooks/useSessionSearch'
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
import { useSettings } from '@/hooks/useSettings'
import { buildPinnedSessionKeys, getSessionKey } from '@/lib/sessionKey'
import { formatShortcutLabel, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
import { cn, formatShortRelativeTime, getRepoDisplayName } from '@/lib/utils'
import { cn } from '@/lib/utils'
import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
const ALL_PROJECTS_STORAGE_KEY = 'oc:session-picker:all-projects'
const UNTITLED_SESSION_TITLE = 'Untitled Session'
const NEAR_BOTTOM_PX = 240
type SessionPickerTab = 'active' | 'sessions' | 'projects'
type SessionPickerTab = 'active' | 'sessions' | 'chats' | 'projects'
const SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions', 'projects']
const SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions', 'chats', 'projects']
const REMOTE_SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions', 'projects']
const SESSION_PICKER_TAB_LABELS: Record<SessionPickerTab, string> = {
active: 'Activity',
sessions: 'Sessions',
chats: 'Chats',
projects: 'Projects',
}
@@ -84,21 +83,6 @@ type SessionPickerDialogProps = Omit<
onOpenChange: (open: boolean) => void
}
interface SessionPickerRow {
key: string
session: Session
repo?: Repo
serverId?: string
serverName?: string
updatedAt?: number
}
interface SessionPickerSection {
id: string
heading: string
rows: SessionPickerRow[]
}
function buildSections(
sessions: Session[],
pinnedKeys: ReadonlySet<string>,
@@ -180,143 +164,6 @@ function sessionWorktreeLabel(session: Session, canonical: string | undefined):
return segments[segments.length - 1]
}
function SessionPickerGutter({ sessionID, isActive }: { sessionID: string; isActive: boolean }) {
const status = useSessionStatusForSession(sessionID)
if (status.type !== 'idle') {
return (
<SessionStatusIndicator sessionID={sessionID} />
)
}
if (isActive) {
return <span aria-hidden="true">●</span>
}
return null
}
interface SessionPickerRowItemProps {
row: SessionPickerRow
index: number
optionId: string
isCursor: boolean
isActive: boolean
isPinned: boolean
isPendingDelete: boolean
showRepo: boolean
showActions: boolean
label?: string
onOpen: (row: SessionPickerRow) => void
onHover: (index: number) => void
onTogglePin: (row: SessionPickerRow) => void
onRequestDelete: (session: Session) => void
registerRef: (key: string, node: HTMLDivElement | null) => void
}
const SessionPickerRowItem = memo(function SessionPickerRowItem({
row,
index,
optionId,
isCursor,
isActive,
isPinned,
isPendingDelete,
showRepo,
showActions,
label,
onOpen,
onHover,
onTogglePin,
onRequestDelete,
registerRef,
}: SessionPickerRowItemProps) {
return (
<div
ref={(node) => registerRef(row.key, node)}
role="presentation"
onPointerMove={(event) => {
if (event.pointerType === 'mouse') onHover(index)
}}
className={cn(
'group flex items-center rounded-md text-sm min-h-8 pointer-coarse:min-h-11',
isPendingDelete
? 'bg-destructive text-destructive-foreground'
: isCursor
? 'bg-primary text-primary-foreground'
: 'hover:bg-accent',
)}
>
<div
role="option"
id={optionId}
aria-selected={isCursor}
onClick={() => onOpen(row)}
className="flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-2"
>
<span className="flex w-4 shrink-0 items-center justify-center">
<SessionPickerGutter sessionID={row.session.id} isActive={isActive} />
</span>
<span
className={cn(
'min-w-0 flex-1 truncate',
isPendingDelete
? 'text-destructive-foreground'
: isCursor
? 'text-primary-foreground'
: isActive
? 'text-primary'
: 'text-foreground',
)}
>
{isPendingDelete ? 'Press Ctrl+D again to confirm' : row.session.title || UNTITLED_SESSION_TITLE}
</span>
<span
className={cn(
'flex shrink-0 items-center gap-2 text-xs',
isPendingDelete
? 'text-destructive-foreground/80'
: isCursor
? 'text-primary-foreground/80'
: 'text-muted-foreground',
)}
>
{showRepo && row.repo ? (
<span className="max-w-32 truncate">{getRepoDisplayName(row.repo)}</span>
) : null}
{showRepo && !row.repo && (row.serverName || row.serverId) ? (
<span className="max-w-32 truncate">{row.serverName ?? row.serverId}</span>
) : null}
{!showRepo && label && <span className="max-w-32 truncate">{label}</span>}
<span>{formatShortRelativeTime(new Date(row.updatedAt ?? row.session.time.updated))}</span>
</span>
</div>
<div className="flex shrink-0 items-center pr-1">
{row.serverId || !showActions ? null : <DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
aria-label="Session actions"
onClick={(event) => event.stopPropagation()}
className={cn(
'h-7 w-7 p-0 shrink-0 pointer-coarse:h-11 pointer-coarse:w-11 pointer-coarse:opacity-100',
isCursor || isPendingDelete ? 'opacity-100' : 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100',
)}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="z-[200]" onClick={(event) => event.stopPropagation()}>
<DropdownMenuItem onClick={() => onTogglePin(row)}>
{isPinned ? <PinOff className="h-4 w-4 mr-2" /> : <Pin className="h-4 w-4 mr-2" />}
{isPinned ? 'Unpin' : 'Pin'}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onRequestDelete(row.session)}>Delete</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>}
</div>
</div>
)
})
interface SessionPickerRowActionsOptions {
directories: string[]
activeSessionID?: string
@@ -446,112 +293,6 @@ function useSessionPickerRowActions({
}
}
interface SessionPickerListProps {
listId: string
optionBaseId: string
ariaLabel: string
sections: SessionPickerSection[]
rows: SessionPickerRow[]
rowIndexByKey: ReadonlyMap<string, number>
cursorIndex: number
activeSessionID?: string
pinnedKeys: ReadonlySet<string>
pendingDeleteKey: string | null
showRepo: boolean
showRowActions?: boolean
labelFor?: (row: SessionPickerRow) => string | undefined
emptyState: React.ReactNode
onOpenRow: (row: SessionPickerRow) => void
onHoverRow: (index: number) => void
onTogglePin: (row: SessionPickerRow) => void
onRequestDelete: (session: Session) => void
registerRef: (key: string, node: HTMLDivElement | null) => void
listRef?: React.RefObject<HTMLDivElement | null>
onScroll?: (event: React.UIEvent<HTMLDivElement>) => void
children?: React.ReactNode
}
function SessionPickerList({
listId,
optionBaseId,
ariaLabel,
sections,
rows,
rowIndexByKey,
cursorIndex,
activeSessionID,
pinnedKeys,
pendingDeleteKey,
showRepo,
showRowActions = true,
labelFor,
emptyState,
onOpenRow,
onHoverRow,
onTogglePin,
onRequestDelete,
registerRef,
listRef,
onScroll,
children,
}: SessionPickerListProps) {
return (
<div
ref={listRef}
role="listbox"
id={listId}
aria-label={ariaLabel}
onScroll={onScroll}
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
>
{rows.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">{emptyState}</div>
) : (
<>
{sections.map((section) => (
<div
key={section.id}
role="group"
aria-labelledby={`${optionBaseId}-heading-${section.id}`}
>
<div
id={`${optionBaseId}-heading-${section.id}`}
className="pl-8 pr-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground"
>
{section.heading}
</div>
{section.rows.map((row) => {
const index = rowIndexByKey.get(row.key) ?? -1
return (
<SessionPickerRowItem
key={row.key}
row={row}
index={index}
optionId={optionId(optionBaseId, index)}
isCursor={index === cursorIndex}
isActive={row.session.id === activeSessionID}
isPinned={pinnedKeys.has(row.key)}
isPendingDelete={pendingDeleteKey === row.key}
showRepo={showRepo}
showActions={showRowActions}
label={labelFor?.(row)}
onOpen={onOpenRow}
onHover={onHoverRow}
onTogglePin={onTogglePin}
onRequestDelete={onRequestDelete}
registerRef={registerRef}
/>
)
})}
</div>
))}
{children}
</>
)}
</div>
)
}
interface SessionPickerContentProps {
open: boolean
currentRepo: Repo | undefined
@@ -1240,6 +981,7 @@ function SessionPickerPanelBody({
}: SessionPickerPanelProps) {
const searchInputRef = useRef<HTMLInputElement>(null)
const activeSearchInputRef = useRef<HTMLInputElement>(null)
const chatsSearchInputRef = useRef<HTMLInputElement>(null)
const projectSearchInputRef = useRef<HTMLInputElement>(null)
const focusSearchAfterSwitchRef = useRef(false)
const scopePressRef = useRef(false)
@@ -1267,14 +1009,18 @@ function SessionPickerPanelBody({
if (open) setActiveTab('sessions')
}
if (isRemote && activeTab === 'chats') setActiveTab('sessions')
const scopeEnabled = !isRemote && Boolean(currentRepo)
const allProjects = scopeEnabled ? allProjectsPreference : true
const readyRepo = scopeEnabled && currentRepo && isRepoReady(currentRepo) ? currentRepo : undefined
const toggleTab = useCallback(() => {
focusSearchAfterSwitchRef.current = true
setActiveTab((current) => nextSessionPickerTab(current, SESSION_PICKER_TABS))
}, [])
setActiveTab((current) =>
nextSessionPickerTab(current, isRemote ? REMOTE_SESSION_PICKER_TABS : SESSION_PICKER_TABS),
)
}, [isRemote])
useShortcutActions({ switchPickerTab: open ? toggleTab : undefined })
@@ -1288,6 +1034,7 @@ function SessionPickerPanelBody({
focusSearchAfterSwitchRef.current = false
if (activeTab === 'projects') projectSearchInputRef.current?.focus()
else if (activeTab === 'active') activeSearchInputRef.current?.focus()
else if (activeTab === 'chats') chatsSearchInputRef.current?.focus()
else searchInputRef.current?.focus()
})
return () => cancelAnimationFrame(frame)
@@ -1326,6 +1073,7 @@ function SessionPickerPanelBody({
}
const sessionsTrailing = withTrailing(newSessionButton)
const chatsTrailing = withTrailing(<NewChatButton onOpenSession={onNavigate} />)
const projectsTrailing = withTrailing(addRepoButton)
const canToggleScope = scopeEnabled && activeTab === 'sessions'
@@ -1362,7 +1110,7 @@ function SessionPickerPanelBody({
>
<div className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
{renderTitle?.(SESSION_PICKER_TAB_LABELS[activeTab])}
<TabsList className="grid w-full grid-cols-3">
<TabsList className={cn('grid w-full', isRemote ? 'grid-cols-3' : 'grid-cols-4')}>
<TabsTrigger value="active">{SESSION_PICKER_TAB_LABELS.active}</TabsTrigger>
<TabsTrigger
value="sessions"
@@ -1375,6 +1123,7 @@ function SessionPickerPanelBody({
<ChevronsUpDown aria-hidden="true" className="ml-1 h-3 w-3 shrink-0 opacity-60" />
)}
</TabsTrigger>
{!isRemote && <TabsTrigger value="chats">{SESSION_PICKER_TAB_LABELS.chats}</TabsTrigger>}
<TabsTrigger value="projects">{SESSION_PICKER_TAB_LABELS.projects}</TabsTrigger>
</TabsList>
</div>
@@ -1428,6 +1177,21 @@ function SessionPickerPanelBody({
/>
)}
</TabsContent>
{!remote && (
<TabsContent
value="chats"
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
>
<ChatPickerContent
open={open}
activeSessionID={activeSessionID}
onNavigate={onNavigate}
onDeleteActiveSession={onDeleteActiveSession}
searchInputRef={chatsSearchInputRef}
searchTrailing={chatsTrailing}
/>
</TabsContent>
)}
<TabsContent
value="projects"
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
@@ -0,0 +1,274 @@
import { memo } from 'react'
import { MoreHorizontal, Pin, PinOff } from 'lucide-react'
import type { Repo, Session } from '@/api/types'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { optionId } from '@/components/session/usePickerKeyboardNav'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { cn, formatShortRelativeTime, getRepoDisplayName } from '@/lib/utils'
const UNTITLED_SESSION_TITLE = 'Untitled Session'
export interface SessionPickerRow {
key: string
session: Session
repo?: Repo
serverId?: string
serverName?: string
updatedAt?: number
}
export interface SessionPickerSection {
id: string
heading: string
rows: SessionPickerRow[]
}
function SessionPickerGutter({ sessionID, isActive }: { sessionID: string; isActive: boolean }) {
const status = useSessionStatusForSession(sessionID)
if (status.type !== 'idle') {
return (
<SessionStatusIndicator sessionID={sessionID} />
)
}
if (isActive) {
return <span aria-hidden="true">●</span>
}
return null
}
interface SessionPickerRowItemProps {
row: SessionPickerRow
index: number
optionId: string
isCursor: boolean
isActive: boolean
isPinned: boolean
isPendingDelete: boolean
showRepo: boolean
showActions: boolean
label?: string
onOpen: (row: SessionPickerRow) => void
onHover: (index: number) => void
onTogglePin: (row: SessionPickerRow) => void
onRequestDelete: (session: Session) => void
registerRef: (key: string, node: HTMLDivElement | null) => void
}
const SessionPickerRowItem = memo(function SessionPickerRowItem({
row,
index,
optionId,
isCursor,
isActive,
isPinned,
isPendingDelete,
showRepo,
showActions,
label,
onOpen,
onHover,
onTogglePin,
onRequestDelete,
registerRef,
}: SessionPickerRowItemProps) {
return (
<div
ref={(node) => registerRef(row.key, node)}
role="presentation"
onPointerMove={(event) => {
if (event.pointerType === 'mouse') onHover(index)
}}
className={cn(
'group flex items-center rounded-md text-sm min-h-8 pointer-coarse:min-h-11',
isPendingDelete
? 'bg-destructive text-destructive-foreground'
: isCursor
? 'bg-primary text-primary-foreground'
: 'hover:bg-accent',
)}
>
<div
role="option"
id={optionId}
aria-selected={isCursor}
onClick={() => onOpen(row)}
className="flex min-w-0 flex-1 cursor-pointer items-center gap-2 px-2"
>
<span className="flex w-4 shrink-0 items-center justify-center">
<SessionPickerGutter sessionID={row.session.id} isActive={isActive} />
</span>
<span
className={cn(
'min-w-0 flex-1 truncate',
isPendingDelete
? 'text-destructive-foreground'
: isCursor
? 'text-primary-foreground'
: isActive
? 'text-primary'
: 'text-foreground',
)}
>
{isPendingDelete ? 'Press Ctrl+D again to confirm' : row.session.title || UNTITLED_SESSION_TITLE}
</span>
<span
className={cn(
'flex shrink-0 items-center gap-2 text-xs',
isPendingDelete
? 'text-destructive-foreground/80'
: isCursor
? 'text-primary-foreground/80'
: 'text-muted-foreground',
)}
>
{showRepo && row.repo ? (
<span className="max-w-32 truncate">{getRepoDisplayName(row.repo)}</span>
) : null}
{showRepo && !row.repo && (row.serverName || row.serverId) ? (
<span className="max-w-32 truncate">{row.serverName ?? row.serverId}</span>
) : null}
{!showRepo && label && <span className="max-w-32 truncate">{label}</span>}
<span>{formatShortRelativeTime(new Date(row.updatedAt ?? row.session.time.updated))}</span>
</span>
</div>
<div className="flex shrink-0 items-center pr-1">
{row.serverId || !showActions ? null : <DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
aria-label="Session actions"
onClick={(event) => event.stopPropagation()}
className={cn(
'h-7 w-7 p-0 shrink-0 pointer-coarse:h-11 pointer-coarse:w-11 pointer-coarse:opacity-100',
isCursor || isPendingDelete ? 'opacity-100' : 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100',
)}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="z-[200]" onClick={(event) => event.stopPropagation()}>
<DropdownMenuItem onClick={() => onTogglePin(row)}>
{isPinned ? <PinOff className="h-4 w-4 mr-2" /> : <Pin className="h-4 w-4 mr-2" />}
{isPinned ? 'Unpin' : 'Pin'}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => onRequestDelete(row.session)}>Delete</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>}
</div>
</div>
)
})
interface SessionPickerListProps {
listId: string
optionBaseId: string
ariaLabel: string
sections: SessionPickerSection[]
rows: SessionPickerRow[]
rowIndexByKey: ReadonlyMap<string, number>
cursorIndex: number
activeSessionID?: string
pinnedKeys: ReadonlySet<string>
pendingDeleteKey: string | null
showRepo: boolean
showRowActions?: boolean
labelFor?: (row: SessionPickerRow) => string | undefined
emptyState: React.ReactNode
onOpenRow: (row: SessionPickerRow) => void
onHoverRow: (index: number) => void
onTogglePin: (row: SessionPickerRow) => void
onRequestDelete: (session: Session) => void
registerRef: (key: string, node: HTMLDivElement | null) => void
listRef?: React.RefObject<HTMLDivElement | null>
onScroll?: (event: React.UIEvent<HTMLDivElement>) => void
children?: React.ReactNode
}
export function SessionPickerList({
listId,
optionBaseId,
ariaLabel,
sections,
rows,
rowIndexByKey,
cursorIndex,
activeSessionID,
pinnedKeys,
pendingDeleteKey,
showRepo,
showRowActions = true,
labelFor,
emptyState,
onOpenRow,
onHoverRow,
onTogglePin,
onRequestDelete,
registerRef,
listRef,
onScroll,
children,
}: SessionPickerListProps) {
return (
<div
ref={listRef}
role="listbox"
id={listId}
aria-label={ariaLabel}
onScroll={onScroll}
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
>
{rows.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">{emptyState}</div>
) : (
<>
{sections.map((section) => (
<div
key={section.id}
role="group"
aria-labelledby={`${optionBaseId}-heading-${section.id}`}
>
<div
id={`${optionBaseId}-heading-${section.id}`}
className="pl-8 pr-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground"
>
{section.heading}
</div>
{section.rows.map((row) => {
const index = rowIndexByKey.get(row.key) ?? -1
return (
<SessionPickerRowItem
key={row.key}
row={row}
index={index}
optionId={optionId(optionBaseId, index)}
isCursor={index === cursorIndex}
isActive={row.session.id === activeSessionID}
isPinned={pinnedKeys.has(row.key)}
isPendingDelete={pendingDeleteKey === row.key}
showRepo={showRepo}
showActions={showRowActions}
label={labelFor?.(row)}
onOpen={onOpenRow}
onHover={onHoverRow}
onTogglePin={onTogglePin}
onRequestDelete={onRequestDelete}
registerRef={registerRef}
/>
)
})}
</div>
))}
{children}
</>
)}
</div>
)
}
@@ -203,12 +203,13 @@ describe('SessionPickerSheet', () => {
Reflect.deleteProperty(window, 'matchMedia')
})
it('renders the picker in a bottom sheet with Activity, Sessions and Projects tabs', () => {
it('renders the picker in a bottom sheet with Activity, Sessions, Chats and Projects tabs', () => {
renderSheet(['/'])
expect(screen.getByRole('dialog', { name: 'Sessions' })).toBeInTheDocument()
expect(screen.getByRole('tab', { name: 'Activity' })).toBeInTheDocument()
expect(screen.getByRole('tab', { name: 'Sessions', selected: true })).toBeInTheDocument()
expect(screen.getByRole('tab', { name: 'Chats' })).toBeInTheDocument()
expect(screen.getByRole('tab', { name: 'Projects' })).toBeInTheDocument()
expect(screen.getByTestId('linked-servers-nav')).toBeInTheDocument()
})
@@ -267,6 +268,7 @@ describe('SessionPickerSheet', () => {
expect(mocks.lastAllDirectories).toBe(true)
expect(screen.getByTestId('linked-servers-nav')).toBeInTheDocument()
expect(screen.queryByRole('tab', { name: 'This project' })).not.toBeInTheDocument()
expect(screen.queryByRole('tab', { name: 'Chats' })).not.toBeInTheDocument()
fireEvent.click(row)