Merge pull request #471 from chriswritescode-dev/feat/sessions-tool-panel

feat(sessions): move the session picker into the desktop right tool panel
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-25 18:12:29 -04:00
commit 34e1df8944
25 files changed
+659 -703

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,
deleteActiveSessionPath,
}: {
docked: boolean
deleteActiveSessionPath?: string
}) {
const panel = useToolPanel(docked)
return (
<>
@@ -87,6 +115,7 @@ function Harness({ docked }: { docked: boolean }) {
selectedFilePath="src/a.ts"
repoDirectory="/repo"
onSkillLoaded={() => {}}
deleteActiveSessionPath={deleteActiveSessionPath}
/>
) : null}
<LocationProbe />
@@ -94,10 +123,10 @@ function Harness({ docked }: { docked: boolean }) {
)
}
function renderAt(search: string, docked = true) {
function renderAt(search: string, docked = true, deleteActiveSessionPath?: string) {
return render(
<MemoryRouter initialEntries={[`/repos/1/sessions/ses_1${search}`]}>
<Harness docked={docked} />
<Harness docked={docked} deleteActiveSessionPath={deleteActiveSessionPath} />
</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,82 @@ 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 destination to the session picker', async () => {
renderAt('?panel=sessions', true, '/servers/srv_kitchen/projects?directory=%2Fapp')
await screen.findByText('route-session-picker')
expect(sessionPickerMocks.useSessionPickerNavigation).toHaveBeenLastCalledWith(
expect.objectContaining({
deleteActiveSessionPath: '/servers/srv_kitchen/projects?directory=%2Fapp',
}),
)
})
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
deleteActiveSessionPath?: string
}
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, deleteActiveSessionPath }: SessionsPanelBodyProps) {
const navigation = useSessionPickerNavigation({
mode: docked ? 'panel' : 'replace',
onClose,
deleteActiveSessionPath,
})
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
/**
* Path the session picker opens after the open session is deleted; the session page passes the
* remote project path on linked-server routes.
*/
deleteActiveSessionPath?: string
}
interface RailButtonProps {
@@ -287,6 +289,7 @@ export function ToolSidePanel({
walkthroughSourceRequest,
walkthroughModel,
walkthroughOnOpenSession,
deleteActiveSessionPath,
}: 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} deleteActiveSessionPath={deleteActiveSessionPath} />
}
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)
+5 -12
View File
@@ -12,11 +12,8 @@ import { useSettingsDialog } from '@/hooks/useSettingsDialog'
import { useSidebarCollapsed } from '@/hooks/useSidebarCollapsed'
import { useUrlParams } from '@/hooks/useUrlParams'
import {
clearToolPanelParams,
panelToolParam,
resolveToolPanelToggle,
toggleToolDialogParams,
toggleToolPanelParams,
useToolPanelToggle,
type PanelTool,
} from '@/hooks/useToolPanel'
import { isLocalOpenCodeServer, useRouteOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
@@ -37,7 +34,7 @@ import {
export function useGlobalShortcutActions(): void {
const { pathname } = useLocation()
const navigate = useNavigate()
const { searchParams, updateParams, closePushedParams } = useUrlParams()
const { updateParams } = useUrlParams()
const { open: openSettings } = useSettingsDialog()
const isMobile = useMobile()
const serverId = useRouteOpenCodeServerId()
@@ -67,6 +64,7 @@ export function useGlobalShortcutActions(): void {
const toolItems = useMemo(() => buildToolItems(pathname), [pathname])
const [, toggleSidebarCollapsed] = useSidebarCollapsed()
const togglePanelTool = useToolPanelToggle()
const toggleRouteTool = useCallback((tool: PanelTool) => {
if (toolItems.some((item) => toolKeyOf(item) === tool)) {
@@ -74,18 +72,13 @@ export function useGlobalShortcutActions(): void {
updateParams((params) => toggleToolDialogParams(params, tool), 'push')
return
}
const action = resolveToolPanelToggle(panelToolParam(searchParams), tool)
if (action === 'close') {
closePushedParams(clearToolPanelParams)
return
}
updateParams((params) => toggleToolPanelParams(params, tool), action === 'switch' ? 'replace' : 'push')
togglePanelTool(tool)
return
}
if (isRemoteRoute || tool === 'files') return
const host = repoId !== null ? getRepoPath(repoId) : getAssistantPath()
navigate(`${host}${dialogSearch(tool)}`)
}, [toolItems, isMobile, searchParams, updateParams, closePushedParams, navigate, repoId, isRemoteRoute])
}, [toolItems, isMobile, togglePanelTool, updateParams, navigate, repoId, isRemoteRoute])
const newSession = sessionDirectory && !createSession.isPending
? () => createSession.mutate({})
@@ -0,0 +1,268 @@
import type { ReactNode } from 'react'
import { act, renderHook } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { describe, expect, it, vi } from 'vitest'
import type { Repo, Session } from '@/api/types'
import { LocationCatcher } from '@/test/test-utils'
import {
useSessionPickerNavigation,
type SessionPickerNavigationOptions,
} from './useSessionPickerNavigation'
function createSession(id: string): Session {
return {
id,
projectID: 'proj-1',
title: `Session ${id}`,
time: { created: 1, updated: 2 },
location: { directory: '/repos/1' },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
function createRepo(id: number): Repo {
return {
id,
name: `repo-${id}`,
fullPath: `/repos/${id}`,
localPath: `/repos/${id}`,
defaultBranch: 'main',
currentBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
}
}
function renderPickerNavigation(
initialEntries: string[],
options: Omit<SessionPickerNavigationOptions, 'onClose'>,
) {
const onClose = vi.fn()
const capturedPathname: { current: string } = { current: '' }
const capturedSearch: { current: string } = { current: '' }
const capturedNavigationType: { current: string } = { current: '' }
const wrapper = function Wrapper({ children }: { children: ReactNode }) {
return (
<MemoryRouter initialEntries={initialEntries}>
<LocationCatcher
capturedPathname={capturedPathname}
capturedSearch={capturedSearch}
capturedNavigationType={capturedNavigationType}
/>
{children}
</MemoryRouter>
)
}
const rendered = renderHook(() => useSessionPickerNavigation({ ...options, onClose }), { wrapper })
return {
...rendered,
onClose,
location: () =>
`${capturedPathname.current}${capturedSearch.current} ${capturedNavigationType.current}`,
}
}
describe('useSessionPickerNavigation', () => {
describe('panel mode', () => {
it('pushes the chosen session and keeps the panel open', () => {
const { result, onClose, location } = renderPickerNavigation(
['/repos/1/sessions/a?panel=sessions'],
{ mode: 'panel' },
)
act(() => {
result.current.onSelectSession(createSession('b'), createRepo(1))
})
expect(location()).toBe('/repos/1/sessions/b?panel=sessions PUSH')
expect(onClose).not.toHaveBeenCalled()
})
it('keeps the panel param when opening a session on another server', () => {
const { result, onClose, location } = renderPickerNavigation(
['/servers/srv_kitchen/sessions/a?panel=sessions'],
{ mode: 'panel' },
)
act(() => {
result.current.onSelectRemoteSession(createSession('b'), 'srv_hall')
})
expect(location()).toBe('/servers/srv_hall/sessions/b?panel=sessions PUSH')
expect(onClose).not.toHaveBeenCalled()
})
it('does nothing when the chosen local session is already open', () => {
const { result, onClose, location } = renderPickerNavigation(
['/repos/1/sessions/a?panel=sessions'],
{ mode: 'panel' },
)
act(() => {
result.current.onSelectSession(createSession('a'), createRepo(1))
})
expect(location()).toBe('/repos/1/sessions/a?panel=sessions POP')
expect(onClose).not.toHaveBeenCalled()
})
it('does nothing when the chosen remote session is already open', () => {
const { result, onClose, location } = renderPickerNavigation(
['/servers/srv_kitchen/sessions/a?panel=sessions'],
{ mode: 'panel' },
)
act(() => {
result.current.onSelectRemoteSession(createSession('a'), 'srv_kitchen')
})
expect(location()).toBe('/servers/srv_kitchen/sessions/a?panel=sessions POP')
expect(onClose).not.toHaveBeenCalled()
})
it('leaves the path unchanged without a panel param', () => {
const { result, onClose, location } = renderPickerNavigation(
['/repos/1/sessions/a'],
{ mode: 'panel' },
)
act(() => {
result.current.onSelectSession(createSession('b'), createRepo(1))
})
expect(location()).toBe('/repos/1/sessions/b PUSH')
expect(onClose).not.toHaveBeenCalled()
})
it('does not carry an empty panel param', () => {
const { result, location } = renderPickerNavigation(['/repos/1/sessions/a?panel='], {
mode: 'panel',
})
act(() => {
result.current.onSelectRepo(createRepo(2))
})
expect(location()).toBe('/repos/2 PUSH')
})
it('pushes a prepared path with the panel param and keeps the picker open', () => {
const { result, onClose, location } = renderPickerNavigation(
['/repos/1/sessions/a?panel=sessions'],
{ mode: 'panel' },
)
act(() => {
result.current.onNavigate('/repos/1/schedules')
})
expect(location()).toBe('/repos/1/schedules?panel=sessions PUSH')
expect(onClose).not.toHaveBeenCalled()
})
it('opens the delete destination with the panel param and keeps the picker open', () => {
const { result, onClose, location } = renderPickerNavigation(
['/servers/srv_kitchen/sessions/a?panel=sessions'],
{ mode: 'panel', deleteActiveSessionPath: '/servers/srv_kitchen/projects?directory=%2Fapp' },
)
act(() => {
result.current.onDeleteActiveSession()
})
expect(location()).toBe(
'/servers/srv_kitchen/projects?directory=%2Fapp&panel=sessions PUSH',
)
expect(onClose).not.toHaveBeenCalled()
})
it('does nothing when deleting without a destination outside a repo route', () => {
const { result, onClose, location } = renderPickerNavigation(
['/servers/srv_kitchen/sessions/a?panel=sessions'],
{ mode: 'panel' },
)
act(() => {
result.current.onDeleteActiveSession()
})
expect(location()).toBe('/servers/srv_kitchen/sessions/a?panel=sessions POP')
expect(onClose).not.toHaveBeenCalled()
})
it('opens the session list with the panel param when a repo is in view', () => {
const { result, onClose, location } = renderPickerNavigation(
['/repos/1/sessions/a?panel=sessions&repoTab=changes'],
{ mode: 'panel' },
)
act(() => {
result.current.onDeleteActiveSession()
})
expect(location()).toBe('/repos/1?repoTab=changes&panel=sessions PUSH')
expect(onClose).not.toHaveBeenCalled()
})
})
describe('push mode', () => {
it('pushes the chosen session and closes the picker', () => {
const { result, onClose, location } = renderPickerNavigation(
['/repos/1?mobileTab=sessions'],
{ mode: 'push' },
)
act(() => {
result.current.onSelectSession(createSession('b'), createRepo(1))
})
expect(location()).toBe('/repos/1/sessions/b PUSH')
expect(onClose).toHaveBeenCalledTimes(1)
})
it('closes the picker without navigating when the session is already open', () => {
const { result, onClose, location } = renderPickerNavigation(
['/repos/1/sessions/a?mobileTab=sessions'],
{ mode: 'push' },
)
act(() => {
result.current.onSelectSession(createSession('a'), createRepo(1))
})
expect(location()).toBe('/repos/1/sessions/a?mobileTab=sessions POP')
expect(onClose).toHaveBeenCalledTimes(1)
})
})
describe('replace mode', () => {
it('replaces the entry without closing the picker', () => {
const { result, onClose, location } = renderPickerNavigation(
['/repos/1/sessions/a?mobileTab=sessions'],
{ mode: 'replace' },
)
act(() => {
result.current.onSelectSession(createSession('b'), createRepo(1))
})
expect(location()).toBe('/repos/1/sessions/b REPLACE')
expect(onClose).not.toHaveBeenCalled()
})
it('replaces the entry with the delete destination without closing or going back', () => {
const { result, onClose, location } = renderPickerNavigation(
['/servers/srv_kitchen/sessions/a?panel=sessions'],
{ mode: 'replace', deleteActiveSessionPath: '/servers/srv_kitchen/projects?directory=%2Fapp' },
)
act(() => {
result.current.onDeleteActiveSession()
})
expect(location()).toBe('/servers/srv_kitchen/projects?directory=%2Fapp REPLACE')
expect(onClose).not.toHaveBeenCalled()
})
})
})
@@ -14,13 +14,14 @@ import {
export interface SessionPickerNavigationOptions {
/**
* `replace` rewrites the entry the mobile sheet was opened from so Back returns to the page behind
* it; `push` adds an entry and closes the picker.
* `replace` rewrites the entry the picker was opened from so Back returns to the page behind it;
* `push` adds an entry and closes the picker; `panel` adds an entry, carries the current `panel`
* search param onto the destination path and leaves the picker open.
*/
mode: 'push' | 'replace'
mode: 'push' | 'replace' | 'panel'
onClose: () => void
/** Replaces the default delete behaviour of returning to the current repo's session list. */
onDeleteActiveSession?: () => void
/** Where to go after the open session is deleted, instead of the current repo's session list. */
deleteActiveSessionPath?: string
}
export interface SessionPickerNavigation {
@@ -32,18 +33,19 @@ export interface SessionPickerNavigation {
}
/**
* Builds the session picker handlers shared by the mobile sheet, the desktop dialog and the session
* page picker. The route in view comes from the location: choosing the session already open on the
* same server only closes the picker, and an assistant session keeps `?assistant=1` when the chosen
* session belongs to the current repo.
* Builds the session picker handlers shared by the mobile sheet, the desktop dialog, the desktop
* tool panel and the session page picker. The route in view comes from the location: choosing the
* session already open on the same server only closes the picker, and does nothing in `panel` mode
* where the picker stays open. An assistant session keeps `?assistant=1` when the chosen session
* belongs to the current repo.
*
* @param options Navigation mode, the picker's close callback, and an optional delete override.
* @param options Navigation mode, the picker's close callback, and an optional delete destination.
* @returns Handlers for selecting sessions and repos and for following a prepared path.
*/
export function useSessionPickerNavigation({
mode,
onClose,
onDeleteActiveSession: deleteActiveSessionOverride,
deleteActiveSessionPath,
}: SessionPickerNavigationOptions): SessionPickerNavigation {
const navigate = useNavigate()
const { pathname, search } = useLocation()
@@ -52,19 +54,23 @@ export function useSessionPickerNavigation({
const searchParams = new URLSearchParams(search)
const isAssistantSession = searchParams.get('assistant') === '1'
const repoTab = searchParams.get('repoTab') ?? undefined
const panelId = searchParams.get('panel')
const isPanelMode = mode === 'panel'
const open = useCallback(
(path: string) => {
navigate(path, { replace: mode === 'replace' })
navigate(isPanelMode && panelId ? withQueryParam(path, 'panel', panelId) : path, {
replace: mode === 'replace',
})
if (mode === 'push') onClose()
},
[mode, navigate, onClose],
[isPanelMode, mode, navigate, onClose, panelId],
)
const onSelectSession = useCallback(
(session: Session, repo: Repo) => {
if (session.id === activeSessionID && activeServerId === LOCAL_OPENCODE_SERVER_ID) {
onClose()
if (!isPanelMode) onClose()
return
}
const sessionPath = getSessionPath(repo.id, session.id)
@@ -74,32 +80,39 @@ export function useSessionPickerNavigation({
: sessionPath,
)
},
[activeServerId, activeSessionID, currentRepoId, isAssistantSession, onClose, open],
[activeServerId, activeSessionID, currentRepoId, isAssistantSession, isPanelMode, onClose, open],
)
const onSelectRemoteSession = useCallback(
(session: Session, serverId: string) => {
if (session.id === activeSessionID && serverId === activeServerId) {
onClose()
if (!isPanelMode) onClose()
return
}
open(getServerSessionPath(serverId, session.id))
},
[activeServerId, activeSessionID, onClose, open],
[activeServerId, activeSessionID, isPanelMode, onClose, open],
)
const onDeleteActiveSession = useCallback(() => {
if (deleteActiveSessionOverride) {
onClose()
deleteActiveSessionOverride()
if (deleteActiveSessionPath) {
open(deleteActiveSessionPath)
return
}
if (currentRepoId === null) {
onClose()
if (!isPanelMode) onClose()
return
}
open(getSessionListPath(currentRepoId, isAssistantSession, repoTab))
}, [currentRepoId, deleteActiveSessionOverride, isAssistantSession, onClose, open, repoTab])
}, [
currentRepoId,
deleteActiveSessionPath,
isAssistantSession,
isPanelMode,
onClose,
open,
repoTab,
])
const onSelectRepo = useCallback(
(repo: Repo) => {
+61 -6
View File
@@ -2,10 +2,11 @@ import { describe, expect, it } from 'vitest'
import { createElement } from 'react'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'
import { isPanelTool, toggleToolDialogParams, toggleToolPanelParams, useToolPanel } from './useToolPanel'
import { isPanelTool, toggleToolDialogParams, toggleToolPanelParams, useToolPanel, useToolPanelToggle } from './useToolPanel'
describe('activity tool', () => { it('is a panel tool', () => {
expect(isPanelTool('activity')).toBe(true)
describe('sessions tool', () => {
it('is a panel tool', () => {
expect(isPanelTool('sessions')).toBe(true)
})
it('clears without opening a dialog when the panel is not docked', async () => {
@@ -18,13 +19,13 @@ describe('activity tool', () => { it('is a panel tool', () => {
render(
createElement(
MemoryRouter,
{ initialEntries: ['/repos/1/sessions/abc?panel=activity'] },
{ initialEntries: ['/repos/1/sessions/abc?panel=sessions'] },
createElement(Probe),
),
)
await waitFor(() => expect(screen.getByTestId('search').textContent).not.toContain('panel=activity'))
expect(screen.getByTestId('search').textContent).not.toContain('dialog=activity')
await waitFor(() => expect(screen.getByTestId('search').textContent).not.toContain('panel=sessions'))
expect(screen.getByTestId('search').textContent).not.toContain('dialog=sessions')
})
})
@@ -203,3 +204,57 @@ describe('panel history entries', () => {
expect(screen.getByTestId('pathname').textContent).toBe('/repos/2')
})
})
describe('useToolPanelToggle', () => {
function ToggleHarness() {
const toggleTool = useToolPanelToggle()
const { activeTool } = useToolPanel(true)
const location = useLocation()
const navigate = useNavigate()
return createElement(
'div',
null,
createElement('span', { 'data-testid': 'activeTool' }, activeTool ?? ''),
createElement('span', { 'data-testid': 'search' }, location.search),
createElement('button', { onClick: () => toggleTool('files') }, 'open files'),
createElement('button', { onClick: () => toggleTool('terminal') }, 'open terminal'),
createElement('button', { onClick: () => navigate(-1) }, 'back'),
)
}
function renderToggleHarness() {
render(createElement(MemoryRouter, { initialEntries: ['/repos/1/sessions/ses_1'] }, createElement(ToggleHarness)))
}
it('opens the tool with a new history entry', () => {
renderToggleHarness()
fireEvent.click(screen.getByText('open files'))
expect(screen.getByTestId('search').textContent).toBe('?panel=files')
fireEvent.click(screen.getByText('back'))
expect(screen.getByTestId('search').textContent).toBe('')
})
it('switches the open panel in place without a new history entry', () => {
renderToggleHarness()
fireEvent.click(screen.getByText('open files'))
fireEvent.click(screen.getByText('open terminal'))
expect(screen.getByTestId('search').textContent).toBe('?panel=terminal')
fireEvent.click(screen.getByText('back'))
expect(screen.getByTestId('search').textContent).toBe('')
})
it('closes the panel when the tool is already open', () => {
renderToggleHarness()
fireEvent.click(screen.getByText('open files'))
fireEvent.click(screen.getByText('open files'))
expect(screen.getByTestId('activeTool').textContent).toBe('')
expect(screen.getByTestId('search').textContent).toBe('')
})
})
+19 -12
View File
@@ -4,7 +4,7 @@ import { useUrlParams } from './useUrlParams'
const PANEL_PARAM = 'panel'
const PANEL_TOOLS = ['sourceControl', 'files', 'terminal', 'walkthrough', 'preview', 'mcp', 'actions', 'skills', 'schedules', 'activity', 'secrets'] as const
const PANEL_TOOLS = ['sourceControl', 'files', 'terminal', 'walkthrough', 'preview', 'mcp', 'actions', 'skills', 'schedules', 'sessions', 'secrets'] as const
export type PanelTool = (typeof PANEL_TOOLS)[number]
@@ -16,7 +16,7 @@ const TOOL_OWNED_PARAMS: Partial<Record<PanelTool, readonly string[]>> = {
schedules: ['scheduleTab', 'scheduleDialog', 'jobId', 'runId'],
}
const PANEL_ONLY_TOOLS: ReadonlySet<PanelTool> = new Set(['schedules', 'activity'])
const PANEL_ONLY_TOOLS: ReadonlySet<PanelTool> = new Set(['schedules', 'sessions'])
export function isPanelTool(value: string | null): value is PanelTool {
return value !== null && (PANEL_TOOLS as readonly string[]).includes(value)
@@ -63,8 +63,22 @@ export function clearToolPanelParams(params: URLSearchParams): void {
clearToolParams(params)
}
export function panelToolParam(params: URLSearchParams): string | null {
return params.get(PANEL_PARAM)
/**
* Toggles a tool in the desktop tool panel from anywhere outside the panel: closes it when it is already
* open, switches the open panel in place, or opens it with a new history entry.
*/
export function useToolPanelToggle(): (tool: PanelTool) => void {
const { searchParams, updateParams, closePushedParams } = useUrlParams()
const panelParam = searchParams.get(PANEL_PARAM)
return useCallback((tool: PanelTool) => {
const action = resolveToolPanelToggle(panelParam, tool)
if (action === 'close') {
closePushedParams(clearToolPanelParams)
return
}
updateParams((params) => toggleToolPanelParams(params, tool), action === 'switch' ? 'replace' : 'push')
}, [panelParam, updateParams, closePushedParams])
}
export interface ToolPanelState {
@@ -109,14 +123,7 @@ export function useToolPanel(panelAvailable: boolean): ToolPanelState {
closePushedParams(clearToolPanelParams)
}, [closePushedParams])
const toggleTool = useCallback((tool: PanelTool) => {
const action = resolveToolPanelToggle(panelParam, tool)
if (action === 'close') {
closePanel()
return
}
updateParams((params) => toggleToolPanelParams(params, tool), action === 'switch' ? 'replace' : 'push')
}, [panelParam, closePanel, updateParams])
const toggleTool = useToolPanelToggle()
return { activeTool, toggleTool, closePanel }
}
-1
View File
@@ -5,7 +5,6 @@ import { useMobile } from './useMobile'
export const TOOL_PANEL_MIN_WIDTH = 320
export const TOOL_PANEL_MAX_WIDTH = 720
export const TOOL_PANEL_DEFAULT_WIDTH = 600
export const TOOL_PANEL_ACTIVITY_WIDTH = 320
export const TOOL_PANEL_RAIL_WIDTH = 44
export const MAIN_CONTENT_MIN_WIDTH = 420
+4 -34
View File
@@ -9,7 +9,6 @@ import { X, CornerUpLeft, GitBranch, ArrowDown, Server } from "lucide-react";
import { SquareFill } from "@/components/ui/square-fill";
import { Header } from "@/components/ui/header";
import { Badge } from "@/components/ui/badge";
import { SessionPickerDialog } from "@/components/session/SessionPickerDialog";
import { getServerProjectPath, getSessionListPath, getSessionPath } from '@/lib/navigation'
import { FetchError } from '@/api/fetchWrapper'
@@ -84,7 +83,6 @@ import { ChangesWalkthroughSheet, type WalkthroughSourceRequest } from "@/compon
import { ToolSidePanel } from "@/components/navigation/ToolSidePanel";
import type { WalkthroughSource } from "@opencode-manager/shared/schemas";
import { useToolPanel } from "@/hooks/useToolPanel";
import { useSessionPickerNavigation } from "@/hooks/useSessionPickerNavigation";
const OLDER_HISTORY_SCROLL_THRESHOLD_PX = 200
@@ -137,7 +135,6 @@ export function SessionDetail() {
const messageContainerRef = useRef<HTMLDivElement>(null);
const [messageContainer, setMessageContainer] = useState<HTMLDivElement | null>(null);
const promptInputRef = useRef<PromptInputHandle>(null);
const [sessionsDialogOpen, setSessionsDialogOpen] = useState(false);
const [sessionDetailsOpen, setSessionDetailsOpen] = useState(false);
const [fileBrowserOpen, setFileBrowserOpen] = useDialogParam('files');
const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp');
@@ -164,6 +161,7 @@ export function SessionDetail() {
const { open: openMobileSheet } = useMobileTabBar();
const { docked, showRail } = useToolPanelLayout();
const sidePanel = useToolPanel(showRail);
const { activeTool: activePanelTool, toggleTool: togglePanelTool } = sidePanel;
const { keyboardHeight } = useVisualViewport();
const inputBottomOffset = isMobile ? keyboardHeight : 0;
const promptOverlayObserverRef = useRef<ResizeObserver | null>(null);
@@ -224,10 +222,6 @@ export function SessionDetail() {
return findRemoteProjectForDirectory(remoteProjects, sessionDirectory);
}, [isRemoteServer, remoteProjects, sessionDirectory]);
const remoteProjectDirectory = isRemoteServer && sessionDirectory
? remoteProject?.canonical ?? sessionDirectory
: undefined;
const remoteProjectDisplayName = remoteProject ? remoteProjectName(remoteProject) : undefined;
const sessionBranch = useMemo(
@@ -378,8 +372,8 @@ export function SessionDetail() {
openMobileSheet('sessions');
return;
}
setSessionsDialogOpen(true);
}, [isMobile, openMobileSheet]);
if (activePanelTool !== 'sessions') togglePanelTool('sessions');
}, [isMobile, openMobileSheet, activePanelTool, togglePanelTool]);
const handleShowMcpDialog = useCallback(() => setMcpDialogOpen(true), [setMcpDialogOpen]);
const handleShowSkillsDialog = useCallback(() => setSkillsDialogOpen(true), [setSkillsDialogOpen]);
const handleShowWalkthrough = useCallback((source?: WalkthroughSource) => {
@@ -550,12 +544,6 @@ export function SessionDetail() {
navigate(getSessionListPath(repoId, isAssistantSession, tab))
}, [navigate, repoId, isAssistantSession, isRemoteServer, remoteProjectBackPath, location.search])
const pickerNavigation = useSessionPickerNavigation({
mode: 'push',
onClose: () => setSessionsDialogOpen(false),
onDeleteActiveSession: isRemoteServer ? handleCloseSession : undefined,
})
const handleOpenModelDialog = useCallback(() => {
promptInputRef.current?.openModelPicker();
}, [])
@@ -1037,29 +1025,11 @@ export function SessionDetail() {
walkthroughSourceRequest={walkthroughSourceRequest}
walkthroughModel={modelRef}
walkthroughOnOpenSession={handleChildSessionClick}
deleteActiveSessionPath={isRemoteServer ? remoteProjectBackPath : undefined}
/>
)}
</div>
{/* Sessions Picker */}
<SessionPickerDialog
open={sessionsDialogOpen}
onOpenChange={setSessionsDialogOpen}
currentRepo={isRemoteServer ? undefined : repo}
activeSessionID={sessionId || undefined}
remote={
isRemoteServer
? {
serverId,
serverName: linkedServer?.name,
projectDirectory: remoteProjectDirectory,
isPending: sessionLoading,
}
: undefined
}
{...pickerNavigation}
/>
<SessionDetailsSheet
open={sessionDetailsOpen}
onOpenChange={setSessionDetailsOpen}
@@ -140,10 +140,6 @@ vi.mock('@/hooks/useSessionGoals', () => ({
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: vi.fn(() => ({ data: undefined })),
}))
vi.mock('@/components/session/SessionPickerDialog', () => ({
SessionPickerDialog: vi.fn(() => null),
}))
vi.mock('@/components/session/PermissionModeToggle', () => ({
PermissionModeToggle: vi.fn(() => null),
}))
@@ -209,10 +209,6 @@ vi.mock('@/hooks/useSessionGoals', () => ({
vi.mock('@/components/session/SideQuestionDialog', () => ({ SideQuestionDialog: vi.fn(() => null) }))
vi.mock('@/components/session/ChangesWalkthroughSheet', () => ({ ChangesWalkthroughSheet: vi.fn(() => null) }))
vi.mock('@/components/navigation/ToolSidePanel', () => ({ ToolSidePanel: vi.fn(() => null) }))
vi.mock('@/hooks/useToolPanel', () => ({
useToolPanel: vi.fn(() => ({ activeTool: null, toggleTool: vi.fn(), closePanel: vi.fn() })),
}))
vi.mock('@/components/session/SessionPickerDialog', () => ({ SessionPickerDialog: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: vi.fn(() => null) }))
@@ -477,35 +473,31 @@ describe('SessionDetail command actions', () => {
})
})
it('opens the sessions picker dialog from the sessions command on desktop', async () => {
const { SessionPickerDialog } = await import('@/components/session/SessionPickerDialog')
it('opens the sessions panel from the sessions command on desktop', async () => {
const captured = { search: { current: '' }, pathname: { current: '' } }
renderSessionDetail()
renderSessionDetail(captured)
const showSessions = await commandHandler('showSessions')
act(() => {
showSessions()
await act(async () => {
await showSessions()
})
const props = vi.mocked(SessionPickerDialog).mock.calls.at(-1)?.[0] as Record<string, unknown>
expect(props).toMatchObject({ open: true })
await waitFor(() => expect(captured.search.current).toBe('?panel=sessions'))
})
it('opens the mobile sessions sheet instead of the dialog from the sessions command', async () => {
const { SessionPickerDialog } = await import('@/components/session/SessionPickerDialog')
it('opens the mobile sessions sheet instead of the panel from the sessions command', async () => {
mocks.useMobile.mockReturnValue(true)
const captured = { search: { current: '' }, pathname: { current: '' } }
renderSessionDetail(captured)
const showSessions = await commandHandler('showSessions')
act(() => {
showSessions()
await act(async () => {
await showSessions()
})
await waitFor(() => expect(captured.search.current).toBe('?mobileTab=sessions'))
const props = vi.mocked(SessionPickerDialog).mock.calls.at(-1)?.[0] as Record<string, unknown>
expect(props).toMatchObject({ open: false })
})
it('shows the error toast when the transcript fetch fails', async () => {
@@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSessionStatusForSession: vi.fn(),
setToolRailMounted: vi.fn(),
showToast: { error: vi.fn(), success: vi.fn(), info: vi.fn(), loading: vi.fn() },
}))
@@ -114,7 +115,11 @@ vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
vi.mock('@/stores/uiStateStore', () => ({
useUIState: vi.fn((selector?: (state: Record<string, unknown>) => unknown) =>
typeof selector === 'function'
? selector({ isEditingMessage: false })
? selector({
isEditingMessage: false,
isToolRailMounted: false,
setToolRailMounted: mocks.setToolRailMounted,
})
: false
),
}))
@@ -171,10 +176,6 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
}))
vi.mock('@/components/session/SessionPickerDialog', () => ({
SessionPickerDialog: vi.fn(() => null),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: vi.fn(() => null),
}))
@@ -92,7 +92,6 @@ vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: ()
vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: () => null }))
vi.mock('@/components/session/FormPrompt', () => ({ FormPrompt: () => null }))
vi.mock('@/components/session/MinimizedFormIndicator', () => ({ MinimizedFormIndicator: () => null }))
vi.mock('@/components/session/SessionPickerDialog', () => ({ SessionPickerDialog: () => null }))
vi.mock('@/components/session/ChangesWalkthroughSheet', () => ({ ChangesWalkthroughSheet: () => null }))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null }))
vi.mock('@/components/navigation/SessionMoreButton', () => ({ SessionMoreButton: () => null }))
@@ -141,7 +141,6 @@ vi.mock('@/hooks/useSessionGoals', () => ({
vi.mock('@/hooks/useSessionPermissionMode', () => ({
useSessionPermissionMode: vi.fn(() => ({ data: undefined })),
}))
vi.mock('@/components/session/SessionPickerDialog', () => ({ SessionPickerDialog: vi.fn(() => null) }))
vi.mock('@/components/session/PermissionModeToggle', () => ({ PermissionModeToggle: vi.fn(() => null) }))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: vi.fn(() => null) }))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: vi.fn(() => null) }))
@@ -45,7 +45,6 @@ const mocks = vi.hoisted(() => ({
ChangesWalkthroughSheet: vi.fn(() => null),
ToolSidePanel: vi.fn(() => null),
SessionGoalBar: vi.fn(() => null),
SessionPickerDialog: vi.fn(() => null),
SessionMoreButton: vi.fn(() => null),
}))
@@ -137,7 +136,6 @@ vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi
vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: mocks.SessionGoalBar }))
vi.mock('@/components/session/FormPrompt', () => ({ FormPrompt: vi.fn(() => null) }))
vi.mock('@/components/session/MinimizedFormIndicator', () => ({ MinimizedFormIndicator: vi.fn(() => null) }))
vi.mock('@/components/session/SessionPickerDialog', () => ({ SessionPickerDialog: mocks.SessionPickerDialog }))
vi.mock('@/components/session/ChangesWalkthroughSheet', () => ({
ChangesWalkthroughSheet: mocks.ChangesWalkthroughSheet,
}))
@@ -523,31 +521,8 @@ describe('SessionDetail remote server mode', () => {
expect(capturedPathname.current).toBe('/servers/srv_kitchen/sessions/ses_child')
})
it('renders the session picker scoped to the linked server', async () => {
renderRemoteSession()
await waitFor(() => {
expect(screen.getByTestId('message-thread')).toBeInTheDocument()
})
const pickerProps = mocks.SessionPickerDialog.mock.calls.at(-1)?.[0]
expect(pickerProps).toEqual(
expect.objectContaining({
open: false,
currentRepo: undefined,
activeSessionID: 'ses_remote',
remote: {
serverId: 'srv_kitchen',
serverName: 'Kitchen',
projectDirectory: '/home/me/app',
isPending: false,
},
}),
)
})
it('opens the session picker from the sessions shortcut on a remote route', async () => {
renderRemoteSession()
it('opens the sessions panel from the sessions shortcut on a remote route', async () => {
const { capturedSearch } = renderRemoteSession()
await waitFor(() => {
expect(screen.getByTestId('message-thread')).toBeInTheDocument()
@@ -559,25 +534,24 @@ describe('SessionDetail remote server mode', () => {
})
await waitFor(() => {
expect(mocks.SessionPickerDialog.mock.calls.at(-1)?.[0]).toEqual(
expect.objectContaining({ open: true, remote: expect.objectContaining({ serverId: 'srv_kitchen' }) }),
)
expect(capturedSearch.current).toBe('?panel=sessions')
})
})
it('navigates to a session chosen from the remote picker', async () => {
const { capturedPathname } = renderRemoteSession()
it('deletes the active remote session from the tool panel', async () => {
renderRemoteSession()
await waitFor(() => {
expect(screen.getByTestId('message-thread')).toBeInTheDocument()
})
const pickerProps = mocks.SessionPickerDialog.mock.calls.at(-1)?.[0]
act(() => {
pickerProps?.onSelectRemoteSession?.({ ...remoteSession, id: 'ses_other' }, 'srv_kitchen')
})
const panelProps = mocks.ToolSidePanel.mock.calls.at(-1)?.[0] as
| { deleteActiveSessionPath?: string }
| undefined
expect(capturedPathname.current).toBe('/servers/srv_kitchen/sessions/ses_other')
expect(panelProps?.deleteActiveSessionPath).toBe(
'/servers/srv_kitchen/projects?directory=%2Fhome%2Fme%2Fapp',
)
})
it('shows a loader until the session directory is available', async () => {
@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => ({
interruptMutate: vi.fn(),
PromptInput: vi.fn(),
uiState: { isEditingMessage: false },
setToolRailMounted: vi.fn(),
}))
vi.mock('@/config', () => ({
@@ -107,7 +108,11 @@ vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
vi.mock('@/stores/uiStateStore', () => ({
useUIState: vi.fn((selector?: (state: Record<string, unknown>) => unknown) =>
typeof selector === 'function'
? selector({ isEditingMessage: mocks.uiState.isEditingMessage })
? selector({
isEditingMessage: mocks.uiState.isEditingMessage,
isToolRailMounted: false,
setToolRailMounted: mocks.setToolRailMounted,
})
: false
),
}))
@@ -164,10 +169,6 @@ vi.mock('@/hooks/useSessionGoals', () => ({
useResumeSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
useCancelSessionGoal: vi.fn(() => ({ mutate: vi.fn(), isPending: false })),
}))
vi.mock('@/components/session/SessionPickerDialog', () => ({
SessionPickerDialog: vi.fn(() => null),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: vi.fn(() => null),
}))
+8
View File
@@ -3,9 +3,17 @@ import { create } from 'zustand'
interface UIStateStore {
isEditingMessage: boolean
setIsEditingMessage: (isEditing: boolean) => void
/**
* True while a page renders the desktop tool rail, so callers outside the rail know whether
* `?panel=` has a host.
*/
isToolRailMounted: boolean
setToolRailMounted: (mounted: boolean) => void
}
export const useUIState = create<UIStateStore>((set) => ({
isEditingMessage: false,
setIsEditingMessage: (isEditing: boolean) => set({ isEditingMessage: isEditing }),
isToolRailMounted: false,
setToolRailMounted: (mounted: boolean) => set({ isToolRailMounted: mounted }),
}))