feat(sessions): move the session picker into the desktop right tool panel

Replace the tool rail's Activity tool with a Sessions tool that renders the
full session picker (Activity, This project and Projects tabs, linked-server
selector, add repository), shared with the mobile sheet via RouteSessionPicker.

- A docked panel stays open and follows navigation (picker navigation mode
  'panel'); the floating overlay closes on select (mode 'replace').
- The session page's sessions shortcut and /sessions open the panel; the
  collapsed sidebar opens it when a tool rail is mounted and falls back to
  the modal dialog otherwise.
- useToolPanelToggle is the single panel toggle for the rail, shortcuts and
  sidebar.
- Remove ActivityList, the fixed activity panel width and the window label.
This commit is contained in:
Chris Scott committed 2026-10-25 17:16:36 -04:00
1 parent 82c46bbdb2
commit d26ab578f0
25 files changed
+639 -695

No files matched your search

@@ -1,212 +0,0 @@
import { render, screen, fireEvent } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { MemoryRouter } from 'react-router-dom'
import type { Repo, Session } from '@/api/types'
import type { ActiveWorkItem } from '@/lib/activeWork'
import { ActivityList } from './ActivityList'
const mocks = vi.hoisted(() => ({
useActiveWork: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: mocks.useActiveWork,
}))
const WINDOW_MINUTES = 30
const NOW = Date.now()
function createSession(id: string, title: string, updated = NOW - 60_000): Session {
return {
id,
projectID: 'proj-1',
title,
time: { created: updated - 10000, updated },
location: { directory: `/repos/${id}` },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
function createRepo(id: number, name: string): Repo {
return {
id,
name,
fullPath: `/repos/${id}`,
localPath: `/repos/${id}`,
defaultBranch: 'main',
currentBranch: 'feature/x',
cloneStatus: 'ready',
clonedAt: 0,
}
}
function createItem(
overrides: Partial<ActiveWorkItem> & Pick<ActiveWorkItem, 'state' | 'session' | 'repo'>,
): ActiveWorkItem {
const repoId = overrides.repo?.id ?? 0
return {
key: `${repoId}:${overrides.session.id}`,
serverId: null,
serverName: null,
path: `/repos/${repoId}/sessions/${overrides.session.id}`,
updatedAt: overrides.session.time.updated,
...overrides,
}
}
function setGroups(groups: {
needsInput?: ActiveWorkItem[]
running?: ActiveWorkItem[]
recent?: ActiveWorkItem[]
}) {
mocks.useActiveWork.mockReturnValue({
groups: {
needsInput: groups.needsInput ?? [],
running: groups.running ?? [],
recent: groups.recent ?? [],
},
isLoading: false,
isError: false,
})
}
const renderList = (onNavigate = vi.fn(), path = '/', minutes = WINDOW_MINUTES) =>
render(
<MemoryRouter initialEntries={[path]}>
<ActivityList minutes={minutes} onNavigate={onNavigate} />
</MemoryRouter>,
)
describe('ActivityList', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('renders non-empty groups in needs-input, running, recent order', () => {
setGroups({
needsInput: [createItem({ state: 'needs-input', session: createSession('n1', 'Needs'), repo: createRepo(1, 'Alpha') })],
running: [createItem({ state: 'running', session: createSession('r1', 'Running'), repo: createRepo(2, 'Beta') })],
recent: [createItem({ state: 'recent', session: createSession('c1', 'Recent'), repo: createRepo(3, 'Gamma') })],
})
renderList()
const headings = screen.getAllByRole('heading').map((node) => node.textContent)
expect(headings).toEqual(['Needs input', 'Running', 'Recent'])
})
it('hides empty groups', () => {
setGroups({
running: [createItem({ state: 'running', session: createSession('r1', 'Running'), repo: createRepo(2, 'Beta') })],
})
renderList()
const headings = screen.getAllByRole('heading').map((node) => node.textContent)
expect(headings).toEqual(['Running'])
expect(screen.queryByText('Needs input')).not.toBeInTheDocument()
expect(screen.queryByText('Recent')).not.toBeInTheDocument()
})
it('renders the empty state with the window minutes', () => {
setGroups({})
renderList()
expect(screen.getByText('No active or recent sessions in the last 30 minutes')).toBeInTheDocument()
})
it('renders the empty state with an hour-scale window', () => {
setGroups({})
renderList(vi.fn(), '/', 1440)
expect(screen.getByText('No active or recent sessions in the last 24 hours')).toBeInTheDocument()
})
it('calls onNavigate with the item when a row is clicked', () => {
const onNavigate = vi.fn()
const item = createItem({ state: 'recent', session: createSession('c1', 'Recent'), repo: createRepo(3, 'Gamma') })
setGroups({ recent: [item] })
renderList(onNavigate)
fireEvent.click(screen.getByRole('button', { name: /Recent/ }))
expect(onNavigate).toHaveBeenCalledWith(item)
})
it('labels a worktree session with its worktree branch', () => {
setGroups({
recent: [
createItem({
state: 'recent',
session: createSession('c1', 'Worktree'),
repo: createRepo(3, 'Gamma'),
worktreeBranch: 'feature/wt',
}),
],
})
renderList()
expect(screen.getByRole('button', { name: /Worktree/ })).toHaveTextContent('Gamma · feature/wt')
})
it('marks the currently open session with aria-current', () => {
setGroups({
recent: [
createItem({ state: 'recent', session: createSession('open', 'Open session'), repo: createRepo(7, 'Gamma') }),
createItem({ state: 'recent', session: createSession('other', 'Other session'), repo: createRepo(7, 'Gamma') }),
],
})
renderList(vi.fn(), '/repos/7/sessions/open')
expect(screen.getByRole('button', { name: /Open session/ })).toHaveAttribute('aria-current', 'true')
expect(screen.getByRole('button', { name: /Other session/ })).not.toHaveAttribute('aria-current')
})
it('labels a remote row with its server name and marks it current on its server route', () => {
const item = createItem({
state: 'needs-input',
session: createSession('s1', 'Remote session'),
repo: null,
serverId: 'srv_kitchen',
serverName: 'Kitchen',
path: '/servers/srv_kitchen/sessions/s1',
})
setGroups({ needsInput: [item] })
renderList(vi.fn(), '/servers/srv_kitchen/sessions/s1')
const row = screen.getByRole('button', { name: /Remote session/ })
expect(row).toHaveTextContent('Kitchen')
expect(row).toHaveAttribute('aria-current', 'true')
})
it('shows a loading state', () => {
mocks.useActiveWork.mockReturnValue({
groups: { needsInput: [], running: [], recent: [] },
isLoading: true,
isError: false,
})
renderList()
expect(screen.getByText('Loading activity...')).toBeInTheDocument()
})
it('shows an error state', () => {
mocks.useActiveWork.mockReturnValue({
groups: { needsInput: [], running: [], recent: [] },
isLoading: false,
isError: true,
})
renderList()
expect(screen.getByText("Couldn't load activity.")).toBeInTheDocument()
})
})
@@ -1,175 +0,0 @@
import { useLocation } from 'react-router-dom'
import { CircleAlert, CircleCheck, CircleX } from 'lucide-react'
import { useActiveWork } from '@/hooks/useActiveWork'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { parseRepoRoute, parseServerSessionRoute } from '@/lib/navigation'
import { cn, formatShortRelativeTime, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
import {
ACTIVE_WORK_GROUPS,
MS_PER_MINUTE,
formatActivityEmptyMessage,
type ActiveWorkItem,
} from '@/lib/activeWork'
const UNTITLED_SESSION_TITLE = 'Untitled Session'
const FULL_ICON_CLASS = 'h-4 w-4'
interface ActivityListProps {
/** Activity window in minutes. */
minutes: number
/** Called when a row is chosen; the caller owns navigation so each surface can apply its own history and close rules. */
onNavigate: (item: ActiveWorkItem) => void
}
function isCurrentItem(
item: ActiveWorkItem,
sessionID: string | null,
repoID: number | null,
serverID: string | null,
) {
if (item.session.id !== sessionID) return false
if (item.serverId) return item.serverId === serverID
return item.repo?.id === repoID
}
/** The row's short label: the local repo's name or the owning linked server's name. */
function activityItemLabel(item: ActiveWorkItem): string {
return item.repo ? getRepoDisplayName(item.repo) : item.serverName ?? item.serverId ?? ''
}
/** The row's identifying line: a local repo with its branch, or the owning linked server's name. */
function activityItemLine(item: ActiveWorkItem): string {
if (!item.repo) return activityItemLabel(item)
const branch = item.worktreeBranch ?? getRepoBranchLabel(item.repo)
return branch ? `${getRepoDisplayName(item.repo)} · ${branch}` : getRepoDisplayName(item.repo)
}
function activityRowClass(isCurrent: boolean) {
return cn(
'flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
isCurrent && 'bg-accent',
)
}
function ActivityStateIcon({ item, iconClassName }: { item: ActiveWorkItem; iconClassName: string }) {
if (item.state === 'needs-input') {
return <CircleAlert className={cn(iconClassName, 'text-warning')} aria-hidden="true" />
}
if (item.state === 'running') {
return <SessionStatusIndicator sessionID={item.session.id} />
}
if (item.outcome === 'failed') {
return <CircleX className={cn(iconClassName, 'text-destructive')} aria-hidden="true" />
}
if (item.outcome === 'succeeded') {
return <CircleCheck className={cn(iconClassName, 'text-success')} aria-hidden="true" />
}
return null
}
interface ActivityRowProps {
item: ActiveWorkItem
isCurrent: boolean
onSelect: (item: ActiveWorkItem) => void
}
function ActivityRow({ item, isCurrent, onSelect }: ActivityRowProps) {
return (
<button
type="button"
onClick={() => onSelect(item)}
aria-current={isCurrent ? 'true' : undefined}
className={activityRowClass(isCurrent)}
>
<span className="flex w-5 shrink-0 items-center justify-center">
<ActivityStateIcon item={item} iconClassName={FULL_ICON_CLASS} />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-foreground">
{item.session.title || UNTITLED_SESSION_TITLE}
</span>
<span className="block truncate text-xs text-muted-foreground">{activityItemLine(item)}</span>
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{formatShortRelativeTime(new Date(item.updatedAt))}
</span>
</button>
)
}
interface ActivityGroupProps {
heading: string
items: ActiveWorkItem[]
currentSessionID: string | null
currentRepoId: number | null
currentServerId: string | null
onSelect: (item: ActiveWorkItem) => void
}
function ActivityGroup({
heading,
items,
currentSessionID,
currentRepoId,
currentServerId,
onSelect,
}: ActivityGroupProps) {
if (items.length === 0) return null
return (
<div className="flex flex-col gap-0.5">
<h3 className="px-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground">{heading}</h3>
{items.map((item) => (
<ActivityRow
key={item.key}
item={item}
isCurrent={isCurrentItem(item, currentSessionID, currentRepoId, currentServerId)}
onSelect={onSelect}
/>
))}
</div>
)
}
export function ActivityList({ minutes, onNavigate }: ActivityListProps) {
const location = useLocation()
const { groups, isLoading, isError } = useActiveWork(minutes * MS_PER_MINUTE)
const route = parseRepoRoute(location.pathname)
const serverRoute = parseServerSessionRoute(location.pathname)
const currentSessionID = route.sessionId ?? serverRoute?.sessionId ?? null
if (isLoading) {
return <p className="p-4 text-sm text-muted-foreground">Loading activity...</p>
}
if (isError) {
return <p className="p-4 text-sm text-destructive">Couldn&apos;t load activity.</p>
}
const isEmpty =
groups.needsInput.length === 0 && groups.running.length === 0 && groups.recent.length === 0
if (isEmpty) {
return (
<p className="p-4 text-sm text-muted-foreground">{formatActivityEmptyMessage(minutes)}</p>
)
}
return (
<section className="flex flex-col pb-2">
{ACTIVE_WORK_GROUPS.map((group) => (
<ActivityGroup
key={group.key}
heading={group.heading}
items={groups[group.key]}
currentSessionID={currentSessionID}
currentRepoId={route.repoId}
currentServerId={serverRoute?.serverId ?? null}
onSelect={onNavigate}
/>
))}
</section>
)
}
@@ -4,6 +4,7 @@ import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { TooltipProvider } from '@/components/ui/tooltip'
import { DesktopSidebar } from './DesktopSidebar'
import { useUIState } from '@/stores/uiStateStore'
import * as useDesktopModule from '@/hooks/useDesktop'
import * as useSidebarCollapsedModule from '@/hooks/useSidebarCollapsed'
import * as useAuthModule from '@/hooks/useAuth'
@@ -58,6 +59,7 @@ function createWrapper(initialEntries?: string[]) {
describe('DesktopSidebar', () => {
beforeEach(() => {
vi.clearAllMocks()
useUIState.setState({ isToolRailMounted: false })
})
it('returns null when user is not authenticated', () => {
@@ -288,7 +290,7 @@ describe('DesktopSidebar', () => {
expect(screen.queryByText('Files')).toBeNull()
})
it('opens the sessions picker dialog from the collapsed Sessions item', () => {
it('opens the sessions picker dialog from the collapsed Sessions item when the tool rail is not mounted', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([true, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
@@ -305,4 +307,28 @@ describe('DesktopSidebar', () => {
expect(screen.getByTestId('sessions-picker-dialog')).toBeInTheDocument()
})
it('opens the sessions panel from the collapsed Sessions item when the tool rail is mounted', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([true, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
useUIState.setState({ isToolRailMounted: true })
render(
<>
<DesktopSidebar />
<LocationDisplay />
</>,
{ wrapper: createWrapper(['/repos/5']) },
)
fireEvent.click(screen.getByText('Sessions'))
expect(screen.getByTestId('location').textContent).toBe('/repos/5?panel=sessions')
expect(screen.queryByTestId('sessions-picker-dialog')).toBeNull()
})
})
@@ -8,6 +8,8 @@ import { useUrlParams } from '@/hooks/useUrlParams'
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { useSessionPickerRouteScope } from '@/hooks/useSessionPickerRouteScope'
import { useSessionPickerNavigation } from '@/hooks/useSessionPickerNavigation'
import { useToolPanelToggle } from '@/hooks/useToolPanel'
import { useUIState } from '@/stores/uiStateStore'
import { buildNavModel, type MoreDrawerItem, type NavPrimaryCta } from '@/components/navigation/moreDrawerItems'
import { SessionPickerDialog } from '@/components/session/SessionPickerDialog'
import { DesktopSessionTree } from '@/components/navigation/DesktopSessionTree'
@@ -48,6 +50,8 @@ export function DesktopSidebar() {
const [sidebarWidth, setSidebarWidth] = useSidebarWidth()
const [sessionsOpen, setSessionsOpen] = useState(false)
const { isAuthenticated, isLoading, logout } = useAuth()
const isToolRailMounted = useUIState((state) => state.isToolRailMounted)
const togglePanelTool = useToolPanelToggle()
const isDesktop = useDesktop()
@@ -72,7 +76,8 @@ export function DesktopSidebar() {
p.delete('mobileTab')
}, 'push')
} else if (item.key === 'sessions') {
setSessionsOpen(true)
if (isToolRailMounted) togglePanelTool('sessions')
else setSessionsOpen(true)
}
}
@@ -3,22 +3,44 @@ import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { ReactNode } from 'react'
import { MemoryRouter, useLocation } from 'react-router-dom'
import type { Repo, Session } from '@/api/types'
import type { ActiveWorkItem } from '@/lib/activeWork'
import { stubMatchMedia } from '@/test/test-utils'
import { ToolSidePanel } from './ToolSidePanel'
import { useToolPanel } from '@/hooks/useToolPanel'
import type { SessionPickerNavigation, SessionPickerNavigationOptions } from '@/hooks/useSessionPickerNavigation'
import { useUIState } from '@/stores/uiStateStore'
const activityMocks = vi.hoisted(() => ({
useActiveWork: vi.fn(),
const activeWorkMocks = vi.hoisted(() => ({
useActiveWorkCounts: vi.fn(),
useActivityWindowMinutes: vi.fn(),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActiveWorkCounts: activityMocks.useActiveWorkCounts,
useActivityWindowMinutes: activityMocks.useActivityWindowMinutes,
useActiveWorkCounts: activeWorkMocks.useActiveWorkCounts,
}))
const sessionPickerMocks = vi.hoisted(() => ({
useSessionPickerNavigation: vi.fn(),
}))
vi.mock('@/hooks/useSessionPickerNavigation', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/hooks/useSessionPickerNavigation')>()
return {
...actual,
useSessionPickerNavigation: (options: SessionPickerNavigationOptions) => {
sessionPickerMocks.useSessionPickerNavigation(options)
return actual.useSessionPickerNavigation(options)
},
}
})
vi.mock('@/components/session/RouteSessionPicker', () => ({
RouteSessionPicker: ({ navigation }: { navigation: SessionPickerNavigation }) => (
<div>
route-session-picker
<button type="button" onClick={() => navigation.onNavigate('/repos/2/sessions/other')}>
open other session
</button>
</div>
),
}))
vi.mock('@/components/file-browser/FileBrowser', () => ({
@@ -71,7 +93,13 @@ function LocationProbe() {
)
}
function Harness({ docked }: { docked: boolean }) {
function Harness({
docked,
onDeleteActiveSession,
}: {
docked: boolean
onDeleteActiveSession?: () => void
}) {
const panel = useToolPanel(docked)
return (
<>
@@ -87,6 +115,7 @@ function Harness({ docked }: { docked: boolean }) {
selectedFilePath="src/a.ts"
repoDirectory="/repo"
onSkillLoaded={() => {}}
onDeleteActiveSession={onDeleteActiveSession}
/>
) : null}
<LocationProbe />
@@ -94,10 +123,10 @@ function Harness({ docked }: { docked: boolean }) {
)
}
function renderAt(search: string, docked = true) {
function renderAt(search: string, docked = true, onDeleteActiveSession?: () => void) {
return render(
<MemoryRouter initialEntries={[`/repos/1/sessions/ses_1${search}`]}>
<Harness docked={docked} />
<Harness docked={docked} onDeleteActiveSession={onDeleteActiveSession} />
</MemoryRouter>,
)
}
@@ -114,55 +143,6 @@ function stubNarrowPage(): () => void {
return () => main.remove()
}
const WINDOW_MINUTES = 30
const NOW = Date.now()
function createSession(id: string, title: string, updated = NOW - 60_000): Session {
return {
id,
projectID: 'proj-1',
title,
time: { created: updated - 10000, updated },
location: { directory: `/repos/${id}` },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
function createRepo(id: number, name: string): Repo {
return {
id,
name,
fullPath: `/repos/${id}`,
localPath: `/repos/${id}`,
defaultBranch: 'main',
currentBranch: 'feature/x',
cloneStatus: 'ready',
clonedAt: 0,
}
}
function createActivityItem(id: string, title: string, repoId: number, repoName: string): ActiveWorkItem {
const session = createSession(id, title)
const repo = createRepo(repoId, repoName)
return {
key: `${repoId}:${id}`,
session,
repo,
state: 'recent',
updatedAt: session.time.updated,
path: `/repos/${repoId}/sessions/${id}`,
}
}
function setActivityGroups(items: ActiveWorkItem[] = []) {
activityMocks.useActiveWork.mockReturnValue({
groups: { needsInput: [], running: [], recent: items },
isLoading: false,
isError: false,
})
}
function HomeHarness() {
const panel = useToolPanel(true)
return (
@@ -209,9 +189,8 @@ function RepoHarness() {
beforeEach(() => {
vi.clearAllMocks()
activityMocks.useActiveWorkCounts.mockReturnValue({ needsInput: 0, running: 0 })
activityMocks.useActivityWindowMinutes.mockReturnValue(WINDOW_MINUTES)
setActivityGroups()
activeWorkMocks.useActiveWorkCounts.mockReturnValue({ needsInput: 0, running: 0 })
useUIState.setState({ isToolRailMounted: false })
})
afterEach(() => {
@@ -536,12 +515,12 @@ describe('ToolSidePanel', () => {
expect(screen.getByLabelText('prompt')).toHaveFocus()
})
it('lists the Activity tool first in the rail', () => {
it('lists the Sessions tool first in the rail', () => {
renderAt('')
const rail = screen.getByRole('navigation', { name: 'Tools' })
const buttons = within(rail).getAllByRole('button')
expect(buttons[0]).toHaveAccessibleName('Activity')
expect(buttons[0]).toHaveAccessibleName('Sessions')
})
it('shows only the remote-capable tools on a linked-server route', async () => {
@@ -557,7 +536,7 @@ describe('ToolSidePanel', () => {
within(rail)
.getAllByRole('button')
.map((button) => button.getAttribute('aria-label') ?? button.textContent?.trim()),
).toEqual(['Activity', 'MCP', 'Skills', 'Source Control', 'Terminal'])
).toEqual(['Sessions', 'MCP', 'Skills', 'Source Control', 'Terminal'])
await user.click(screen.getByRole('button', { name: 'MCP' }))
expect(await screen.findByText('mcp-tool')).toBeInTheDocument()
@@ -594,55 +573,81 @@ describe('ToolSidePanel', () => {
expect(search().get('panel')).toBe('skills')
})
it('opens the Activity panel with rows and the window label when clicked', async () => {
it('opens the Sessions panel with the session picker when clicked', async () => {
const user = userEvent.setup()
setActivityGroups([createActivityItem('other', 'Other Session', 2, 'Beta')])
renderAt('')
await user.click(screen.getByRole('button', { name: 'Activity' }))
await user.click(screen.getByRole('button', { name: 'Sessions' }))
expect(await screen.findByText('Other Session')).toBeInTheDocument()
expect(search().get('panel')).toBe('activity')
expect(screen.getByRole('complementary', { name: 'Activity' })).toHaveClass('w-80')
expect(screen.getByText('Last 30 minutes')).toBeInTheDocument()
const panel = await screen.findByRole('complementary', { name: 'Sessions' })
expect(within(panel).getByText('route-session-picker')).toBeInTheDocument()
expect(within(panel).getByRole('heading', { name: 'Sessions' })).toBeInTheDocument()
expect(search().get('panel')).toBe('sessions')
})
it('keeps the Activity panel open when a row navigates to a session', async () => {
it('keeps the docked Sessions panel open when a session is chosen', async () => {
const user = userEvent.setup()
setActivityGroups([createActivityItem('other', 'Other Session', 2, 'Beta')])
renderAt('')
renderAt('?panel=sessions')
await user.click(screen.getByRole('button', { name: 'Activity' }))
await user.click(await screen.findByRole('button', { name: /Other Session/ }))
await user.click(await screen.findByRole('button', { name: 'open other session' }))
await waitFor(() => expect(screen.getByTestId('pathname').textContent).toBe('/repos/2/sessions/other'))
expect(search().get('panel')).toBe('activity')
expect(search().get('panel')).toBe('sessions')
})
it('keeps a worktree session tab when navigating from the Activity panel', async () => {
const user = userEvent.setup()
setActivityGroups([
{
...createActivityItem('wt', 'Worktree Session', 2, 'Beta'),
path: '/repos/2/sessions/wt?repoTab=workspaces',
},
])
renderAt('')
it('builds the docked picker navigation in panel mode', async () => {
renderAt('?panel=sessions')
await user.click(screen.getByRole('button', { name: 'Activity' }))
await user.click(await screen.findByRole('button', { name: /Worktree Session/ }))
await screen.findByText('route-session-picker')
await waitFor(() => expect(screen.getByTestId('pathname').textContent).toBe('/repos/2/sessions/wt'))
expect(search().get('repoTab')).toBe('workspaces')
expect(search().get('panel')).toBe('activity')
expect(sessionPickerMocks.useSessionPickerNavigation).toHaveBeenLastCalledWith(
expect.objectContaining({ mode: 'panel', onClose: expect.any(Function) }),
)
})
it('shows an Activity count pill and extends the accessible name', () => {
activityMocks.useActiveWorkCounts.mockReturnValue({ needsInput: 1, running: 2 })
it('builds the floating picker navigation in replace mode', async () => {
const removePage = stubNarrowPage()
try {
renderAt('?panel=sessions')
const panel = await screen.findByRole('dialog', { name: 'Sessions' })
expect(within(panel).getByText('route-session-picker')).toBeInTheDocument()
expect(sessionPickerMocks.useSessionPickerNavigation).toHaveBeenLastCalledWith(
expect.objectContaining({ mode: 'replace', onClose: expect.any(Function) }),
)
} finally {
removePage()
}
})
it('forwards the delete override to the session picker', async () => {
const onDeleteActiveSession = vi.fn()
renderAt('?panel=sessions', true, onDeleteActiveSession)
await screen.findByText('route-session-picker')
expect(sessionPickerMocks.useSessionPickerNavigation).toHaveBeenLastCalledWith(
expect.objectContaining({ onDeleteActiveSession }),
)
})
it('shows a Sessions count pill and extends the accessible name', () => {
activeWorkMocks.useActiveWorkCounts.mockReturnValue({ needsInput: 1, running: 2 })
renderAt('')
const button = screen.getByRole('button', { name: 'Activity, 1 needs input, 2 running' })
const button = screen.getByRole('button', { name: 'Sessions, 1 needs input, 2 running' })
const pill = within(button).getByText('3')
expect(pill.className).toContain('bg-warning')
})
it('marks the tool rail as mounted only while it renders', () => {
const { unmount } = renderAt('')
expect(useUIState.getState().isToolRailMounted).toBe(true)
unmount()
expect(useUIState.getState().isToolRailMounted).toBe(false)
})
})
@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef } from 'react'
import type { ReactNode, RefObject } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useLocation } from 'react-router-dom'
import { FileBrowser } from '@/components/file-browser/FileBrowser'
import { SourceControlContent } from '@/components/source-control'
import { RemoteSourceControlContent } from '@/components/source-control/RemoteSourceControlContent'
@@ -26,12 +26,12 @@ import type { ModelRef } from '@opencode-manager/shared/opencode'
import { buildToolItems, toolKeyOf, type MoreDrawerItem } from '@/components/navigation/moreDrawerItems'
import { isPanelTool, type ToolPanelState, type PanelTool } from '@/hooks/useToolPanel'
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { ActivityList } from '@/components/activity/ActivityList'
import { ActivityCountPill } from '@/components/activity/ActivityCountPill'
import { withQueryParam } from '@/lib/navigation'
import { RouteSessionPicker } from '@/components/session/RouteSessionPicker'
import { useSessionPickerNavigation } from '@/hooks/useSessionPickerNavigation'
import type { TerminalTarget } from '@/lib/terminal-target'
import { useActiveWorkCounts, useActivityWindowMinutes } from '@/hooks/useActiveWork'
import { formatActivityWindow } from '@/lib/activeWork'
import { useActiveWorkCounts } from '@/hooks/useActiveWork'
import { useUIState } from '@/stores/uiStateStore'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TOOLTIP_OPEN_DELAY_MS } from '@/components/ui/tooltip'
import { restoreOverlayFocus } from '@/lib/overlayFocus'
import { useRestoreFocusOnClose } from '@/hooks/useRestoreFocusOnClose'
@@ -39,10 +39,6 @@ import { cn } from '@/lib/utils'
import { useToolPanelLayout, useToolPanelWidth } from '@/hooks/useToolPanelLayout'
import { isLocalOpenCodeServer, useRouteOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
const PANEL_WIDTH_CLASSES: Partial<Record<PanelTool, string>> = {
activity: 'w-80',
}
interface PanelResizeState {
pointerId: number
startX: number
@@ -132,7 +128,7 @@ function PanelResizeHandle({ width, minWidth, maxWidth, onWidthChange }: PanelRe
)
}
const REMOTE_TOOL_KEYS: ReadonlySet<string> = new Set(['activity', 'mcp', 'skills', 'source-control', 'terminal'])
const REMOTE_TOOL_KEYS: ReadonlySet<string> = new Set(['sessions', 'mcp', 'skills', 'source-control', 'terminal'])
/**
* Escape closes the floating panel, except while a nested menu is open or the terminal owns
@@ -166,33 +162,34 @@ function useFloatingPanelDismiss(
}, [floating, panelRef])
}
function ActivityWindowLabel() {
const minutes = useActivityWindowMinutes()
return (
<span className="shrink-0 text-xs text-muted-foreground">
Last {formatActivityWindow(minutes)}
</span>
)
interface SessionsPanelBodyProps {
docked: boolean
onClose: () => void
onDeleteActiveSession?: () => void
}
function ActivityPanelBody() {
const navigate = useNavigate()
const minutes = useActivityWindowMinutes()
/**
* Session picker shown in the tool panel. While docked, choosing a session keeps the panel open on
* the destination; as an overlay sheet the choice replaces the entry behind it and closes the panel.
*/
function SessionsPanelBody({ docked, onClose, onDeleteActiveSession }: SessionsPanelBodyProps) {
const navigation = useSessionPickerNavigation({
mode: docked ? 'panel' : 'replace',
onClose,
onDeleteActiveSession,
})
return (
<div className="min-h-0 flex-1 overflow-y-auto">
<ActivityList
minutes={minutes}
onNavigate={(item) => navigate(withQueryParam(item.path, 'panel', 'activity'))}
/>
<div className="flex min-h-0 flex-1 flex-col px-3 pb-3">
<RouteSessionPicker navigation={navigation} />
</div>
)
}
function ActivityRailIndicator() {
function SessionsRailIndicator() {
const { needsInput, running } = useActiveWorkCounts()
const total = needsInput + running
const label = total > 0 ? `Activity, ${needsInput} needs input, ${running} running` : 'Activity'
const label = total > 0 ? `Sessions, ${needsInput} needs input, ${running} running` : 'Sessions'
return (
<>
@@ -222,6 +219,11 @@ interface ToolSidePanelProps {
walkthroughSourceRequest?: WalkthroughSourceRequest
walkthroughModel?: ModelRef | null
walkthroughOnOpenSession?: (id: string) => void
/**
* Replaces the session picker's default behaviour after the open session is deleted; the session
* page passes its close handler on linked-server routes.
*/
onDeleteActiveSession?: () => void
}
interface RailButtonProps {
@@ -287,6 +289,7 @@ export function ToolSidePanel({
walkthroughSourceRequest,
walkthroughModel,
walkthroughOnOpenSession,
onDeleteActiveSession,
}: ToolSidePanelProps) {
const { activeTool, toggleTool, closePanel } = panel
const location = useLocation()
@@ -298,8 +301,14 @@ export function ToolSidePanel({
const previousActiveToolRef = useRef(activeTool)
const panelWidth = useToolPanelWidth()
const { docked } = useToolPanelLayout()
const setToolRailMounted = useUIState((state) => state.setToolRailMounted)
const floating = activeTool !== null && !docked
useEffect(() => {
setToolRailMounted(true)
return () => setToolRailMounted(false)
}, [setToolRailMounted])
useRestoreFocusOnClose(floating, panelRef)
useFloatingPanelDismiss(floating, closePanel, panelRef)
@@ -349,7 +358,9 @@ export function ToolSidePanel({
if (tool === 'preview') return <PreviewWorkspace isOpen directory={directory} compact />
if (tool === 'mcp') return repoDirectory ? <RepoMcpContent open directory={repoDirectory} /> : null
if (tool === 'walkthrough') return sessionId ? <ChangesWalkthroughView /> : null
if (tool === 'activity') return <ActivityPanelBody />
if (tool === 'sessions') {
return <SessionsPanelBody docked={docked} onClose={closePanel} onDeleteActiveSession={onDeleteActiveSession} />
}
if (tool === 'terminal') {
return terminalWorkspaceTarget
? <TerminalWorkspace target={terminalWorkspaceTarget} directory={terminalDirectory ?? directory} isOpen onLastTerminalExited={closePanel} />
@@ -390,8 +401,6 @@ export function ToolSidePanel({
}
}
const fixedWidthClass = activeTool ? PANEL_WIDTH_CLASSES[activeTool] : undefined
const panelBody =
activeTool && activeLabel ? (
<>
@@ -414,11 +423,10 @@ export function ToolSidePanel({
docked
? 'relative shrink-0'
: 'fixed inset-y-0 right-11 z-50 w-[min(420px,calc(100vw-2.75rem))] pt-safe pb-safe shadow-2xl',
fixedWidthClass,
)}
style={docked && !fixedWidthClass ? { width: panelWidth.width } : undefined}
style={docked ? { width: panelWidth.width } : undefined}
>
{docked && !fixedWidthClass ? (
{docked ? (
<PanelResizeHandle
width={panelWidth.width}
minWidth={panelWidth.minWidth}
@@ -427,10 +435,7 @@ export function ToolSidePanel({
/>
) : null}
<div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2">
<div className="flex min-w-0 flex-1 items-baseline gap-2">
<h2 className="min-w-0 truncate text-sm font-semibold text-foreground">{activeLabel}</h2>
{activeTool === 'activity' ? <ActivityWindowLabel /> : null}
</div>
<h2 className="min-w-0 flex-1 truncate text-sm font-semibold text-foreground">{activeLabel}</h2>
{activeTool === 'walkthrough' ? (
<>
<ChangesWalkthroughSourcePicker />
@@ -484,7 +489,7 @@ export function ToolSidePanel({
item={item}
active={tool === activeTool}
onClick={() => toggleTool(tool)}
indicator={tool === 'activity' ? <ActivityRailIndicator /> : undefined}
indicator={tool === 'sessions' ? <SessionsRailIndicator /> : undefined}
/>
))}
{actionItems.length > 0 ? <div className="my-1 h-px w-6 shrink-0 bg-border" role="separator" /> : null}
@@ -168,18 +168,18 @@ describe('buildMoreItems', () => {
})
describe('buildToolItems', () => {
it('leads every route with the Activity tool', () => {
it('leads every route with the Sessions tool', () => {
for (const path of ['/', '/repos/42', '/repos/42/sessions/abc', '/assistant', '/schedules']) {
const [first] = buildToolItems(path)
expect(first.key).toBe('activity')
expect(first.label).toBe('Activity')
expect(first.panelTool).toBe('activity')
expect(first.key).toBe('sessions')
expect(first.label).toBe('Sessions')
expect(first.panelTool).toBe('sessions')
}
})
it('returns the session route items without home and account entries', () => {
expect(buildToolItems('/repos/42/sessions/abc').map((item) => item.key)).toEqual([
'activity',
'sessions',
'files',
'mcp',
'skills',
@@ -195,7 +195,7 @@ describe('buildToolItems', () => {
it('returns the linked-server session tools for the tool rail', () => {
expect(buildToolItems('/servers/srv_kitchen/sessions/abc').map((item) => item.key)).toEqual([
'activity',
'sessions',
'mcp',
'skills',
'source-control',
@@ -205,7 +205,7 @@ describe('buildToolItems', () => {
it('returns the linked-server project tools for the tool rail', () => {
expect(buildToolItems('/servers/srv_kitchen/projects').map((item) => item.key)).toEqual([
'activity',
'sessions',
'mcp',
'skills',
'source-control',
@@ -214,7 +214,7 @@ describe('buildToolItems', () => {
})
it('returns the home route tools', () => {
expect(buildToolItems('/').map((item) => item.key)).toEqual(['activity', 'all-schedules', 'files'])
expect(buildToolItems('/').map((item) => item.key)).toEqual(['sessions', 'all-schedules', 'files'])
})
it.each(['/repos/42', '/assistant'])('opens schedules in the panel on %s', (path) => {
@@ -227,8 +227,8 @@ describe('buildToolItems', () => {
expect(secrets?.panelTool).toBeUndefined()
})
it.each(['/schedules', '/repos/42/schedules'])('returns only the Activity tool on %s', (path) => {
expect(buildToolItems(path).map((item) => item.key)).toEqual(['activity'])
it.each(['/schedules', '/repos/42/schedules'])('returns only the Sessions tool on %s', (path) => {
expect(buildToolItems(path).map((item) => item.key)).toEqual(['sessions'])
})
})
@@ -1,5 +1,5 @@
import type { LucideIcon } from 'lucide-react'
import { Activity, BookOpen, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe, KeyRound } from 'lucide-react'
import { BookOpen, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, List, Play, Globe, KeyRound } from 'lucide-react'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
@@ -75,7 +75,7 @@ export function isManagerOnlyNavItem(item: MoreDrawerItem): boolean {
/** Route-scoped tool items, shown in the desktop tool rail instead of the sidebar. */
export function buildToolItems(pathname: string): MoreDrawerItem[] {
const routeItems = buildNavModel(pathname).items.filter((item) => !NON_TOOL_ITEM_KEYS.has(item.key))
return [{ key: 'activity', label: 'Activity', icon: Activity, panelTool: 'activity' }, ...routeItems]
return [{ key: 'sessions', label: 'Sessions', icon: List, panelTool: 'sessions' }, ...routeItems]
}
/** The `?panel=`/`?dialog=` tool identifier an item targets, preferring its panel tool. */
@@ -0,0 +1,34 @@
import { LinkedServersNav } from '@/components/navigation/LinkedServersNav'
import { SessionPickerPanel } from '@/components/session/SessionPickerDialog'
import type { SessionPickerNavigation } from '@/hooks/useSessionPickerNavigation'
import { useSessionPickerRouteScope } from '@/hooks/useSessionPickerRouteScope'
export interface RouteSessionPickerProps {
/** Session and repo handlers built by the host, so choosing a row navigates the same way it hosts. */
navigation: SessionPickerNavigation
/**
* Replaces the panel's internal add-repo dialog with the host's own, letting the host close itself
* first. When omitted the panel opens its own dialog.
*/
onAddRepo?: () => void
}
/**
* Session picker scoped to the route in view, including the linked-server selector. Hosts mount it
* only while visible, so the route scope resolves repos and the remote server only then.
*/
export function RouteSessionPicker({ navigation, onAddRepo }: RouteSessionPickerProps) {
const { currentRepo, activeSessionID, remote } = useSessionPickerRouteScope(true)
return (
<SessionPickerPanel
open
currentRepo={currentRepo}
activeSessionID={activeSessionID}
{...navigation}
remote={remote}
searchTrailing={<LinkedServersNav variant="header" />}
onAddRepo={onAddRepo}
/>
)
}
@@ -1,9 +1,7 @@
import { useState } from 'react'
import { BottomSheet } from '@/components/ui/bottom-sheet'
import { LinkedServersNav } from '@/components/navigation/LinkedServersNav'
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
import { SessionPickerPanel } from '@/components/session/SessionPickerDialog'
import { useSessionPickerRouteScope } from '@/hooks/useSessionPickerRouteScope'
import { RouteSessionPicker } from '@/components/session/RouteSessionPicker'
import { useSessionPickerLocationPrefetch } from '@/hooks/useSessionPickerLocationPrefetch'
import { useSessionPickerNavigation } from '@/hooks/useSessionPickerNavigation'
@@ -14,18 +12,12 @@ interface SessionPickerSheetProps {
export function SessionPickerSheet({ isOpen, onClose }: SessionPickerSheetProps) {
const [addRepoOpen, setAddRepoOpen] = useState(false)
const { currentRepo, activeSessionID, remote } = useSessionPickerRouteScope(isOpen)
const pickerNavigation = useSessionPickerNavigation({ mode: 'replace', onClose })
useSessionPickerLocationPrefetch()
const panel = isOpen ? (
<SessionPickerPanel
open={isOpen}
currentRepo={currentRepo}
activeSessionID={activeSessionID}
{...pickerNavigation}
remote={remote}
searchTrailing={<LinkedServersNav variant="header" />}
<RouteSessionPicker
navigation={pickerNavigation}
onAddRepo={() => {
onClose()
setAddRepoOpen(true)