feat(ui): dock repo and session tools in a desktop side panel

Add a docked desktop tool panel with an icon rail, driven by the shared panel URL param, and keep the mobile dialogs and drawers. Extract dialog bodies into reusable content components, rename the walkthrough dialog to a sheet, and make walkthrough generation asynchronous with client polling.
This commit is contained in:
Chris Scott committed 2026-10-07 23:58:56 -04:00
1 parent bdbcc60716
commit 485ab940aa
49 files changed
+2631 -1753

No files matched your search

@@ -47,7 +47,6 @@ function createWrapper(initialEntries?: string[]) {
describe('DesktopSidebar', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(useSidebarCollapsedModule.useSidebarSections).mockReturnValue({ isSectionOpen: () => true, toggleSection: vi.fn() })
})
it('returns null when user is not authenticated', () => {
@@ -149,6 +148,24 @@ describe('DesktopSidebar', () => {
expect(screen.getByText('Assistant')).toBeInTheDocument()
})
it.each(['/', '/repos/5', '/repos/5/sessions/abc', '/assistant'])('leaves route tools to the tool rail on %s', (path) => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper([path]) })
for (const label of ['Home', 'Settings', 'Logout']) {
expect(screen.getByText(label)).toBeInTheDocument()
}
for (const label of ['Menu', 'Repos', 'Files', 'MCP', 'Skills', 'Schedules', 'All Schedules', 'Source Control', 'Terminal', 'Walkthrough', 'Preview']) {
expect(screen.queryByText(label)).toBeNull()
}
})
it.each([
['/schedules', 'New Schedule'],
['/repos/5/schedules', 'New Schedule'],
@@ -168,7 +185,7 @@ describe('DesktopSidebar', () => {
expect(screen.getByText('Assistant')).toBeInTheDocument()
})
it('opens dialog items by updating the dialog query param (push) and closes on back', () => {
it('navigates home from the footer', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
@@ -182,18 +199,13 @@ describe('DesktopSidebar', () => {
<DesktopSidebar />
<LocationDisplay />
</>,
{ wrapper: createWrapper(['/repos/5/sessions/abc?assistant=1']) }
{ wrapper: createWrapper(['/repos/5?repoTab=workspaces']) }
)
fireEvent.click(screen.getByText('Files'))
fireEvent.click(screen.getByText('Home'))
expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/abc?assistant=1&dialog=files')
fireEvent.click(screen.getByTestId('back-button'))
expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/abc?assistant=1')
expect(screen.getByTestId('location').textContent).toBe('/')
})
it('opens settings by updating settings query params', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
@@ -216,29 +228,7 @@ describe('DesktopSidebar', () => {
expect(screen.getByTestId('location').textContent).toBe('/?dialog=files&settings=open&settingsTab=account')
})
it('preserves session route as return target when opening schedules', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(
<>
<DesktopSidebar />
<LocationDisplay />
</>,
{ wrapper: createWrapper(['/repos/5/sessions/abc?assistant=1']) }
)
fireEvent.click(screen.getByText('Schedules'))
expect(screen.getByTestId('location').textContent).toBe('/repos/5/schedules?returnTo=%2Frepos%2F5%2Fsessions%2Fabc%3Fassistant%3D1')
})
it('renders both collapsible sections open by default with the account footer', () => {
it('renders the session tree with home and account items in the footer', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
@@ -249,13 +239,13 @@ describe('DesktopSidebar', () => {
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
expect(screen.getByTestId('session-tree')).toBeInTheDocument()
expect(screen.getByText('Files')).toBeInTheDocument()
expect(screen.getByRole('region', { name: 'Sessions' })).toContainElement(screen.getByTestId('session-tree'))
expect(screen.queryByRole('button', { name: 'Sessions' })).toBeNull()
expect(screen.getByText('Home')).toBeInTheDocument()
expect(screen.getByText('Settings')).toBeInTheDocument()
expect(screen.getByText('Logout')).toBeInTheDocument()
})
it('renders the vertical nav list and no session tree when collapsed', () => {
it('renders home, repos and account items and no session tree when collapsed', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([true, vi.fn()])
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
@@ -267,80 +257,9 @@ describe('DesktopSidebar', () => {
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
expect(screen.queryByTestId('session-tree')).toBeNull()
expect(screen.getByText('Files')).toBeInTheDocument()
expect(screen.getByText('Home')).toBeInTheDocument()
expect(screen.getByText('Repos')).toBeInTheDocument()
expect(screen.getByText('Settings')).toBeInTheDocument()
})
it('hides the session tree when the sessions section is collapsed', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.mocked(useSidebarCollapsedModule.useSidebarSections).mockReturnValue({
isSectionOpen: (section) => section !== 'sessions',
toggleSection: vi.fn(),
})
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
expect(screen.queryByTestId('session-tree')).toBeNull()
expect(screen.getByText('Files')).toBeInTheDocument()
})
it('hides the menu items when the menu section is collapsed', () => {
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.mocked(useSidebarCollapsedModule.useSidebarSections).mockReturnValue({
isSectionOpen: (section) => section !== 'menu',
toggleSection: vi.fn(),
})
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
expect(screen.getByTestId('session-tree')).toBeInTheDocument()
expect(screen.queryByText('Files')).toBeNull()
expect(screen.getByText('Settings')).toBeInTheDocument()
})
it('toggles the sessions section from its header', () => {
const toggle = vi.fn()
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.mocked(useSidebarCollapsedModule.useSidebarSections).mockReturnValue({ isSectionOpen: () => true, toggleSection: toggle })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
fireEvent.click(screen.getByRole('button', { name: 'Sessions' }))
expect(toggle).toHaveBeenCalledWith('sessions')
})
it('toggles the menu section from its header', () => {
const toggle = vi.fn()
vi.spyOn(useDesktopModule, 'useDesktop').mockReturnValue(true)
vi.spyOn(useSidebarCollapsedModule, 'useSidebarCollapsed').mockReturnValue([false, vi.fn()])
vi.mocked(useSidebarCollapsedModule.useSidebarSections).mockReturnValue({ isSectionOpen: () => true, toggleSection: toggle })
vi.spyOn(useAuthModule, 'useAuth').mockReturnValue({
isAuthenticated: true,
isLoading: false,
logout: vi.fn(),
} as any)
render(<DesktopSidebar />, { wrapper: createWrapper(['/repos/5']) })
fireEvent.click(screen.getByRole('button', { name: 'Menu' }))
expect(toggle).toHaveBeenCalledWith('menu')
})
})
@@ -1,30 +1,28 @@
import { useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useDesktop } from '@/hooks/useDesktop'
import { useSidebarCollapsed, useSidebarSections } from '@/hooks/useSidebarCollapsed'
import { useSidebarCollapsed } from '@/hooks/useSidebarCollapsed'
import { useAuth } from '@/hooks/useAuth'
import { useUrlParams } from '@/hooks/useUrlParams'
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { buildNavModel, type MoreDrawerItem, type NavPrimaryCta } from '@/components/navigation/moreDrawerItems'
import { getPathWithReturnTo } from '@/lib/navigation'
import { RepoQuickSwitchSheet } from '@/components/navigation/RepoQuickSwitchSheet'
import { DesktopSessionTree } from '@/components/navigation/DesktopSessionTree'
import {
Sidebar,
SidebarCollapsibleSection,
SidebarSection,
SidebarItem,
} from '@/components/ui/sidebar'
import { FolderGit2 } from 'lucide-react'
import { cn } from '@/lib/utils'
const ACCOUNT_ITEM_KEYS = new Set(['settings', 'logout'])
const FOOTER_ITEM_KEYS = new Set(['home', 'settings', 'logout'])
export function DesktopSidebar() {
const location = useLocation()
const navigate = useNavigate()
const { updateParams } = useUrlParams()
const openNavItem = useOpenNavItem()
const [collapsed, toggle] = useSidebarCollapsed()
const { isSectionOpen, toggleSection } = useSidebarSections(['sessions', 'menu'] as const)
const [repoSwitcherOpen, setRepoSwitcherOpen] = useState(false)
const { isAuthenticated, isLoading, logout } = useAuth()
@@ -41,17 +39,8 @@ export function DesktopSidebar() {
const { primary, items } = buildNavModel(location.pathname)
const handleItemClick = (item: MoreDrawerItem) => {
if (item.to) {
const to = item.key === 'schedules'
? getPathWithReturnTo(item.to, `${location.pathname}${location.search}`)
: item.to
navigate(to)
} else if (item.dialog) {
updateParams((p) => {
p.set('dialog', item.dialog!)
p.delete('mobileTab')
}, 'push')
} else if (item.key === 'logout') {
if (openNavItem(item)) return
if (item.key === 'logout') {
logout()
} else if (item.key === 'settings') {
updateParams((p) => {
@@ -64,18 +53,16 @@ export function DesktopSidebar() {
}
}
const [homeItem, ...routeItems] = items
const navItems: MoreDrawerItem[] = [
homeItem,
const footerItems = items.filter((item) => FOOTER_ITEM_KEYS.has(item.key))
const collapsedItems: MoreDrawerItem[] = [
footerItems[0],
{ key: 'repos', label: 'Repos', icon: FolderGit2 },
...routeItems,
...footerItems.slice(1),
]
const toolItems = navItems.filter((item) => !ACCOUNT_ITEM_KEYS.has(item.key))
const accountItems = navItems.filter((item) => ACCOUNT_ITEM_KEYS.has(item.key))
return (
<>
<Sidebar collapsed={collapsed} onToggle={toggle} widthClass='w-72' className='mt-2'>
<Sidebar collapsed={collapsed} onToggle={toggle} className='mt-2'>
{primary.length > 0 && (
<SidebarSection collapsed={collapsed}>
{primary.map((item: NavPrimaryCta) => (
@@ -94,7 +81,7 @@ export function DesktopSidebar() {
{collapsed ? (
<div className="flex flex-col gap-1 p-2 pt-0">
{navItems.map((item: MoreDrawerItem) => (
{collapsedItems.map((item: MoreDrawerItem) => (
<SidebarItem
key={item.key}
icon={item.icon}
@@ -107,39 +94,13 @@ export function DesktopSidebar() {
</div>
) : (
<>
<SidebarCollapsibleSection
label="Sessions"
collapsed={!isSectionOpen('sessions')}
onToggle={() => toggleSection('sessions')}
className={cn('border-t border-border', isSectionOpen('sessions') && 'flex-1')}
>
<section aria-label="Sessions" className="flex min-h-0 flex-1 flex-col border-t border-border">
<h2 className="px-3 py-1.5 text-xs font-medium uppercase tracking-wider text-muted-foreground">Sessions</h2>
<DesktopSessionTree />
</SidebarCollapsibleSection>
<SidebarCollapsibleSection
label="Menu"
collapsed={!isSectionOpen('menu')}
onToggle={() => toggleSection('menu')}
className={cn('border-t border-border', isSectionOpen('sessions') ? 'shrink-0 max-h-[40%]' : 'flex-1')}
contentClassName="overflow-y-auto"
>
<div className="flex flex-col gap-0.5 p-2 pt-0">
{toolItems.map((item: MoreDrawerItem) => (
<SidebarItem
key={item.key}
icon={item.icon}
label={item.label}
collapsed={false}
dense
onClick={() => handleItemClick(item)}
danger={item.danger}
/>
))}
</div>
</SidebarCollapsibleSection>
</section>
<div className="flex gap-1 border-t border-border p-2">
{accountItems.map((item: MoreDrawerItem) => (
{footerItems.map((item: MoreDrawerItem) => (
<SidebarItem
key={item.key}
icon={item.icon}
@@ -11,7 +11,7 @@ import { getRepo } from '@/api/repos'
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
import { SideDrawer, SideDrawerContent } from '@/components/ui/side-drawer'
import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
import { buildMoreItems, buildNavModel } from './moreDrawerItems'
import { buildMoreItems, buildNavModel, isSessionDetailPath } from './moreDrawerItems'
import { useSwipeBack } from '@/hooks/useMobile'
import { getRepoDisplayName } from '@/lib/utils'
import { getPathWithReturnTo, isAssistantPath } from '@/lib/navigation'
@@ -35,7 +35,7 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const { searchParams, updateParams } = useUrlParams()
const { logout } = useAuth()
const { data: health } = useServerHealth()
const isSessionDetail = /^\/repos\/\d+\/sessions\/[^/]+$/.test(location.pathname)
const isSessionDetail = isSessionDetailPath(location.pathname)
const isAssistantRoute = isAssistantPath(location.pathname)
const isAssistantSession = isSessionDetail && searchParams.get('assistant') === '1'
const { commands } = useCommands({ enabled: isSessionDetail })
@@ -0,0 +1,228 @@
import { describe, expect, it, vi } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { ToolSidePanel } from './ToolSidePanel'
import { useToolPanel } from '@/hooks/useToolPanel'
vi.mock('@/components/file-browser/FileBrowser', () => ({
FileBrowser: ({ initialSelectedFile }: { initialSelectedFile?: string }) => <div>files-tool {initialSelectedFile}</div>,
}))
vi.mock('@/components/source-control', () => ({
SourceControlContent: () => <div>source-control-tool</div>,
}))
vi.mock('@/components/terminal/TerminalPanel', () => ({
TerminalWorkspace: () => <div>terminal-tool</div>,
}))
vi.mock('@/components/preview/PreviewPanel', () => ({ PreviewWorkspace: () => <div>preview-tool</div> }))
vi.mock('@/components/schedules/RepoSchedulesContent', () => ({
RepoSchedulesContent: ({ repoId }: { repoId: number }) => <div>schedules-tool {repoId}</div>,
}))
vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpContent: () => <div>mcp-tool</div> }))
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsContent: () => <div>actions-tool</div> }))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsContent: () => <div>skills-tool</div> }))
vi.mock('@/components/session/ChangesWalkthroughSheet', () => ({
ChangesWalkthroughView: ({ sessionId }: { sessionId: string }) => <div>walkthrough-tool {sessionId}</div>,
}))
function LocationProbe() {
const location = useLocation()
return (
<>
<div data-testid="pathname">{location.pathname}</div>
<div data-testid="search">{location.search}</div>
</>
)
}
function Harness({ docked }: { docked: boolean }) {
const panel = useToolPanel(docked)
return (
<>
{docked ? (
<ToolSidePanel
panel={panel}
repoId={1}
sessionId="ses_1"
directory="/repo"
filesBasePath="repo"
currentBranch="main"
selectedFilePath="src/a.ts"
repoDirectory="/repo"
onSkillLoaded={() => {}}
/>
) : null}
<LocationProbe />
</>
)
}
function renderAt(search: string, docked = true) {
return render(
<MemoryRouter initialEntries={[`/repos/1/sessions/ses_1${search}`]}>
<Harness docked={docked} />
</MemoryRouter>,
)
}
function search(): URLSearchParams {
return new URLSearchParams(screen.getByTestId('search').textContent ?? '')
}
function HomeHarness() {
const panel = useToolPanel(true)
return (
<>
<ToolSidePanel panel={panel} filesBasePath="" allowNavigateAboveBase />
<LocationProbe />
</>
)
}
describe('ToolSidePanel', () => {
it('shows the tool name in a tooltip when hovering a rail icon', async () => {
const user = userEvent.setup()
renderAt('')
await user.hover(screen.getByRole('button', { name: 'Terminal' }))
expect(await screen.findByRole('tooltip')).toHaveTextContent('Terminal')
})
it('shows the home route tools without a repo', async () => {
const user = userEvent.setup()
render(
<MemoryRouter initialEntries={['/']}>
<HomeHarness />
</MemoryRouter>,
)
expect(screen.queryByRole('button', { name: 'Terminal' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Files' }))
expect(await screen.findByText(/files-tool/)).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'All Schedules' }))
await waitFor(() => expect(screen.getByTestId('pathname').textContent).toBe('/schedules'))
})
it('moves a panel tool opened as a dialog into the docked panel', async () => {
renderAt('?dialog=walkthrough')
expect(await screen.findByText('walkthrough-tool ses_1')).toBeInTheDocument()
expect(search().get('panel')).toBe('walkthrough')
expect(search().has('dialog')).toBe(false)
})
it('leaves non-panel dialogs alone', async () => {
renderAt('?dialog=resetPermissions&panel=files')
expect(await screen.findByText('files-tool src/a.ts')).toBeInTheDocument()
expect(search().get('dialog')).toBe('resetPermissions')
})
it.each([
['Preview', 'preview-tool'],
['MCP', 'mcp-tool'],
['Actions', 'actions-tool'],
['Skills', 'skills-tool'],
])('opens %s inside the docked panel', async (label, content) => {
const user = userEvent.setup()
renderAt('')
await user.click(screen.getByRole('button', { name: label }))
expect(await screen.findByText(content)).toBeInTheDocument()
expect(screen.getByRole('heading', { name: label })).toBeInTheDocument()
expect(search().has('dialog')).toBe(false)
})
it('moves a preview opened with a port into the panel and keeps its port', async () => {
renderAt('?panel=terminal&terminal=pty-1&dialog=preview&previewPort=5173&previewPath=%2F')
expect(await screen.findByText('preview-tool')).toBeInTheDocument()
expect(search().get('panel')).toBe('preview')
expect(search().get('previewPort')).toBe('5173')
expect(search().has('terminal')).toBe(false)
})
it('toggles tools from the rail and closes the panel', async () => {
const user = userEvent.setup()
renderAt('')
expect(screen.queryByRole('complementary')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Source Control' }))
expect(await screen.findByText('source-control-tool')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Source Control' })).toHaveAttribute('aria-pressed', 'true')
await user.click(screen.getByRole('button', { name: 'Terminal' }))
expect(await screen.findByText('terminal-tool')).toBeInTheDocument()
expect(screen.queryByText('source-control-tool')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Terminal' }))
await waitFor(() => expect(screen.queryByText('terminal-tool')).not.toBeInTheDocument())
expect(search().has('panel')).toBe(false)
await user.click(screen.getByRole('button', { name: 'Files' }))
await user.click(await screen.findByRole('button', { name: 'Close panel' }))
await waitFor(() => expect(search().has('panel')).toBe(false))
})
it('opens non-panel session items from the rail as dialogs', async () => {
const user = userEvent.setup()
renderAt('?panel=files')
await user.click(screen.getByRole('button', { name: 'Reset Permissions' }))
await waitFor(() => expect(search().get('dialog')).toBe('resetPermissions'))
expect(search().get('panel')).toBe('files')
})
it('opens schedules in the panel without leaving the session', async () => {
const user = userEvent.setup()
renderAt('?panel=files')
await user.click(screen.getByRole('button', { name: 'Schedules' }))
expect(await screen.findByText('schedules-tool 1')).toBeInTheDocument()
expect(screen.getByTestId('pathname').textContent).toBe('/repos/1/sessions/ses_1')
expect(search().get('panel')).toBe('schedules')
})
it('drops schedule selection params when switching away from schedules', async () => {
const user = userEvent.setup()
renderAt('?panel=schedules&jobId=4&scheduleTab=runs&runId=9')
await user.click(await screen.findByRole('button', { name: 'Terminal' }))
await waitFor(() => expect(search().get('panel')).toBe('terminal'))
expect(search().has('jobId')).toBe(false)
expect(search().has('scheduleTab')).toBe(false)
expect(search().has('runId')).toBe(false)
})
it('closes a docked schedules panel when the layout is no longer docked', async () => {
renderAt('?panel=schedules&jobId=4', false)
await waitFor(() => expect(search().has('panel')).toBe(false))
expect(search().has('dialog')).toBe(false)
expect(search().has('jobId')).toBe(false)
})
it('drops terminal selection params when switching away from the terminal', async () => {
const user = userEvent.setup()
renderAt('?panel=terminal&terminal=pty-1')
await user.click(await screen.findByRole('button', { name: 'Files' }))
await waitFor(() => expect(search().get('panel')).toBe('files'))
expect(search().has('terminal')).toBe(false)
})
it('falls back to the dialog when not docked', async () => {
renderAt('?panel=sourceControl', false)
await waitFor(() => expect(search().get('dialog')).toBe('sourceControl'))
expect(search().has('panel')).toBe(false)
})
})
@@ -0,0 +1,175 @@
import { X } from 'lucide-react'
import { useLocation } from 'react-router-dom'
import { FileBrowser } from '@/components/file-browser/FileBrowser'
import { SourceControlContent } from '@/components/source-control'
import { TerminalWorkspace } from '@/components/terminal/TerminalPanel'
import { ChangesWalkthroughView } from '@/components/session/ChangesWalkthroughSheet'
import { PreviewWorkspace } from '@/components/preview/PreviewPanel'
import { RepoMcpContent } from '@/components/repo/RepoMcpDialog'
import { RepoActionsContent } from '@/components/repo/RepoActionsDialog'
import { RepoSkillsContent } from '@/components/repo/RepoSkillsDialog'
import { RepoSchedulesContent } from '@/components/schedules/RepoSchedulesContent'
import type { SkillFileInfo } from '@opencode-manager/shared'
import { buildToolItems, type MoreDrawerItem } from '@/components/navigation/moreDrawerItems'
import { isPanelTool, type ToolPanelState, type PanelTool } from '@/hooks/useToolPanel'
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'
interface ToolSidePanelProps {
panel: ToolPanelState
filesBasePath: string | undefined
allowNavigateAboveBase?: boolean
repoId?: number
sessionId?: string
directory?: string
terminalDirectory?: string
repoDirectory?: string
currentBranch?: string
selectedFilePath?: string
onSkillLoaded?: (skill: SkillFileInfo) => void
}
interface RailButtonProps {
item: MoreDrawerItem
active: boolean
onClick: () => void
}
function RailButton({ item, active, onClick }: RailButtonProps) {
const Icon = item.icon
return (
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<button
type="button"
onClick={onClick}
aria-label={item.label}
aria-pressed={active}
className={cn(
'rounded-md p-2 transition-colors',
active
? 'bg-accent text-foreground'
: item.danger
? 'text-muted-foreground hover:bg-destructive/10 hover:text-destructive'
: 'text-muted-foreground hover:bg-accent/60 hover:text-foreground',
)}
>
<Icon className="h-4 w-4" />
</button>
</TooltipTrigger>
<TooltipContent side="left" align="center">
{item.label}
</TooltipContent>
</Tooltip>
)
}
/**
* Desktop-only docked tool panel with its icon rail, rendered to the right of a page's content.
* The rail lists the current route's tool items; repo- and session-scoped tools render only when their context is given.
*/
export function ToolSidePanel({
panel,
filesBasePath,
allowNavigateAboveBase,
repoId,
sessionId,
directory,
terminalDirectory,
repoDirectory,
currentBranch = 'main',
selectedFilePath,
onSkillLoaded,
}: ToolSidePanelProps) {
const { activeTool, toggleTool, closePanel } = panel
const location = useLocation()
const openNavItem = useOpenNavItem()
const panelTools: Array<{ item: MoreDrawerItem; tool: PanelTool }> = []
const actionItems: MoreDrawerItem[] = []
for (const item of buildToolItems(location.pathname)) {
const tool = item.panelTool ?? item.dialog ?? null
if (isPanelTool(tool)) panelTools.push({ item, tool })
else actionItems.push(item)
}
const activeLabel = panelTools.find(({ tool }) => tool === activeTool)?.item.label
if (panelTools.length === 0 && actionItems.length === 0) return null
const renderTool = (tool: PanelTool) => {
if (tool === 'files') {
return (
<FileBrowser
embedded
compact
basePath={filesBasePath || '.'}
allowNavigateAboveBase={allowNavigateAboveBase}
initialSelectedFile={selectedFilePath}
/>
)
}
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 sessionId={sessionId} active /> : null
if (repoId === undefined) return null
switch (tool) {
case 'sourceControl':
return <SourceControlContent repoId={repoId} isOpen currentBranch={currentBranch} compact />
case 'terminal':
return <TerminalWorkspace repoId={repoId} directory={terminalDirectory ?? directory} isOpen />
case 'actions':
return <RepoActionsContent repoId={repoId} directory={directory} open />
case 'skills':
return sessionId ? (
<RepoSkillsContent
open
repoId={repoId}
sessionId={sessionId}
directory={repoDirectory}
onSkillLoaded={onSkillLoaded}
onDone={closePanel}
/>
) : (
<RepoSkillsContent open repoId={repoId} onDone={closePanel} />
)
case 'schedules':
return <RepoSchedulesContent repoId={repoId} embedded />
}
}
return (
<>
{activeTool && activeLabel ? (
<aside
aria-label={activeLabel}
className="flex w-[min(600px,45vw)] shrink-0 flex-col border-l border-border bg-background"
>
<div className="flex shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2">
<h2 className="text-sm font-semibold text-foreground">{activeLabel}</h2>
<button
type="button"
onClick={closePanel}
aria-label="Close panel"
className="rounded-sm p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="flex min-h-0 flex-1 flex-col">{renderTool(activeTool)}</div>
</aside>
) : null}
<TooltipProvider>
<nav aria-label="Tools" className="flex w-11 shrink-0 flex-col items-center gap-1 overflow-y-auto border-l border-border bg-background py-2">
{panelTools.map(({ item, tool }) => (
<RailButton key={item.key} item={item} active={tool === activeTool} onClick={() => toggleTool(tool)} />
))}
{actionItems.length > 0 ? <div className="my-1 h-px w-6 shrink-0 bg-border" role="separator" /> : null}
{actionItems.map((item) => (
<RailButton key={item.key} item={item} active={false} onClick={() => openNavItem(item)} />
))}
</nav>
</TooltipProvider>
</>
)
}
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { buildMoreItems, buildNavModel } from './moreDrawerItems'
import { buildMoreItems, buildNavModel, buildToolItems } from './moreDrawerItems'
describe('buildMoreItems', () => {
it('returns Home + All Schedules + Files + Settings + Logout for root path', () => {
@@ -41,7 +41,7 @@ describe('buildMoreItems', () => {
it('returns session-specific items for /repos/:id/sessions/:sid', () => {
const items = buildMoreItems('/repos/42/sessions/abc')
expect(items).toHaveLength(12)
expect(items).toHaveLength(13)
expect(items[0].key).toBe('home')
expect(items[1].key).toBe('files')
expect(items[2].key).toBe('mcp')
@@ -52,23 +52,26 @@ describe('buildMoreItems', () => {
expect(items[6].key).toBe('source-control')
expect(items[7].key).toBe('terminal')
expect(items[7].dialog).toBe('terminal')
expect(items[8].key).toBe('actions')
expect(items[8].dialog).toBe('actions')
expect(items[9].key).toBe('preview')
expect(items[9].dialog).toBe('preview')
expect(items[10].key).toBe('settings')
expect(items[11].key).toBe('logout')
expect(items[8].key).toBe('walkthrough')
expect(items[8].dialog).toBe('walkthrough')
expect(items[9].key).toBe('actions')
expect(items[9].dialog).toBe('actions')
expect(items[10].key).toBe('preview')
expect(items[10].dialog).toBe('preview')
expect(items[11].key).toBe('settings')
expect(items[12].key).toBe('logout')
})
it('omits the Actions item for an Assistant session', () => {
const items = buildMoreItems('/repos/0/sessions/abc')
expect(items).toHaveLength(11)
expect(items).toHaveLength(12)
expect(items.map((item) => item.key)).not.toContain('actions')
expect(items[7].key).toBe('terminal')
expect(items[8].key).toBe('preview')
expect(items[8].dialog).toBe('preview')
expect(items[9].key).toBe('settings')
expect(items[10].key).toBe('logout')
expect(items[8].key).toBe('walkthrough')
expect(items[9].key).toBe('preview')
expect(items[9].dialog).toBe('preview')
expect(items[10].key).toBe('settings')
expect(items[11].key).toBe('logout')
})
it('returns assistant workspace items for /repos/:id/assistant', () => {
@@ -135,6 +138,35 @@ describe('buildMoreItems', () => {
})
})
describe('buildToolItems', () => {
it('returns the session route items without home and account entries', () => {
expect(buildToolItems('/repos/42/sessions/abc').map((item) => item.key)).toEqual([
'files',
'mcp',
'skills',
'reset-permissions',
'schedules',
'source-control',
'terminal',
'walkthrough',
'actions',
'preview',
])
})
it('returns the home route tools', () => {
expect(buildToolItems('/').map((item) => item.key)).toEqual(['all-schedules', 'files'])
})
it.each(['/repos/42', '/assistant'])('opens schedules in the panel on %s', (path) => {
expect(buildToolItems(path).find((item) => item.key === 'schedules')?.panelTool).toBe('schedules')
})
it.each(['/schedules', '/repos/42/schedules'])('returns nothing on %s', (path) => {
expect(buildToolItems(path)).toEqual([])
})
})
describe('buildNavModel', () => {
it.each([
'/',
@@ -1,5 +1,5 @@
import type { LucideIcon } from 'lucide-react'
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe } from 'lucide-react'
import { BookOpen, Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, SquareTerminal, Settings, LogOut, Bot, Folder, Home, Play, Globe } from 'lucide-react'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
@@ -9,6 +9,7 @@ export interface MoreDrawerItem {
icon: LucideIcon
to?: string
dialog?: string
panelTool?: string
danger?: boolean
}
@@ -46,6 +47,19 @@ function getBaseItems(): MoreDrawerItem[] {
]
}
const SESSION_DETAIL_PATH = /^\/repos\/(\d+)\/sessions\/[^/]+$/
export function isSessionDetailPath(pathname: string): boolean {
return SESSION_DETAIL_PATH.test(pathname)
}
const NON_TOOL_ITEM_KEYS = new Set(['home', 'settings', 'logout'])
/** Route-scoped tool items, shown in the desktop tool rail instead of the sidebar. */
export function buildToolItems(pathname: string): MoreDrawerItem[] {
return buildNavModel(pathname).items.filter((item) => !NON_TOOL_ITEM_KEYS.has(item.key))
}
function buildRouteNavModel(pathname: string): NavModel {
const baseItems = getBaseItems()
@@ -57,7 +71,7 @@ function buildRouteNavModel(pathname: string): NavModel {
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${id}/schedules` },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${id}/schedules`, panelTool: 'schedules' },
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' },
@@ -71,7 +85,7 @@ function buildRouteNavModel(pathname: string): NavModel {
}
}
const sessionDetailMatch = /^\/repos\/(\d+)\/sessions\/[^/]+$/.exec(pathname)
const sessionDetailMatch = SESSION_DETAIL_PATH.exec(pathname)
if (sessionDetailMatch) {
const repoId = sessionDetailMatch[1]
const isAssistantRepo = repoId === String(ASSISTANT_REPO_ID)
@@ -80,9 +94,10 @@ function buildRouteNavModel(pathname: string): NavModel {
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${repoId}/schedules` },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${repoId}/schedules`, panelTool: 'schedules' },
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
{ key: 'walkthrough', label: 'Walkthrough', icon: BookOpen, dialog: 'walkthrough' },
...(isAssistantRepo
? []
: [{ key: 'actions', label: 'Actions', icon: Play, dialog: 'actions' }]),
@@ -102,7 +117,7 @@ function buildRouteNavModel(pathname: string): NavModel {
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: '/repos/0/schedules' },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: '/repos/0/schedules', panelTool: 'schedules' },
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
{ key: 'preview', label: 'Preview', icon: Globe, dialog: 'preview' },