mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Merge remote-tracking branch 'origin/feat/linked-opencode-servers' into feat/remote-server-automation
# Conflicts: # backend/src/services/remote-server-events.ts # frontend/src/components/navigation/MoreDrawer.test.tsx # frontend/src/components/navigation/moreDrawerItems.test.ts # frontend/src/lib/opencode-event-stream/openCodeEventStream.ts # frontend/src/pages/SessionDetail.tsx # frontend/src/pages/__tests__/SessionDetail.remote.test.tsx
This commit is contained in:
commit
780d31087b
92 files changed
+3828
-817
No files matched your search
@@ -45,9 +45,12 @@ function createRepo(id: number, name: string): Repo {
|
||||
function createItem(
|
||||
overrides: Partial<ActiveWorkItem> & Pick<ActiveWorkItem, 'state' | 'session' | 'repo'>,
|
||||
): ActiveWorkItem {
|
||||
const repoId = overrides.repo?.id ?? 0
|
||||
return {
|
||||
key: `${overrides.repo.id}:${overrides.session.id}`,
|
||||
path: `/repos/${overrides.repo.id}/sessions/${overrides.session.id}`,
|
||||
key: `${repoId}:${overrides.session.id}`,
|
||||
serverId: null,
|
||||
serverName: null,
|
||||
path: `/repos/${repoId}/sessions/${overrides.session.id}`,
|
||||
updatedAt: overrides.session.time.updated,
|
||||
...overrides,
|
||||
}
|
||||
@@ -175,6 +178,24 @@ describe('ActivityList', () => {
|
||||
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: [] },
|
||||
|
||||
@@ -2,7 +2,7 @@ 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 } from '@/lib/navigation'
|
||||
import { parseRepoRoute, parseServerSessionRoute } from '@/lib/navigation'
|
||||
import { cn, formatShortRelativeTime, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
|
||||
import {
|
||||
ACTIVE_WORK_GROUPS,
|
||||
@@ -28,8 +28,27 @@ interface ActivityListProps {
|
||||
variant?: 'full' | 'compact'
|
||||
}
|
||||
|
||||
function isCurrentItem(item: ActiveWorkItem, sessionID: string | null, repoID: number | null) {
|
||||
return item.repo.id === repoID && item.session.id === sessionID
|
||||
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, compact: boolean) {
|
||||
@@ -63,11 +82,6 @@ interface ActivityRowProps {
|
||||
}
|
||||
|
||||
function ActivityRow({ item, isCurrent, onSelect }: ActivityRowProps) {
|
||||
const branch = item.worktreeBranch ?? getRepoBranchLabel(item.repo)
|
||||
const repoLine = branch
|
||||
? `${getRepoDisplayName(item.repo)} · ${branch}`
|
||||
: getRepoDisplayName(item.repo)
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
@@ -82,7 +96,7 @@ function ActivityRow({ item, isCurrent, onSelect }: ActivityRowProps) {
|
||||
<span className="block truncate text-foreground">
|
||||
{item.session.title || UNTITLED_SESSION_TITLE}
|
||||
</span>
|
||||
<span className="block truncate text-xs text-muted-foreground">{repoLine}</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))}
|
||||
@@ -106,7 +120,7 @@ function CompactActivityRow({ item, isCurrent, onSelect }: ActivityRowProps) {
|
||||
{item.session.title || UNTITLED_SESSION_TITLE}
|
||||
</span>
|
||||
<span className="max-w-[35%] truncate text-xs text-muted-foreground">
|
||||
{getRepoDisplayName(item.repo)}
|
||||
{activityItemLabel(item)}
|
||||
</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{formatShortRelativeTime(new Date(item.updatedAt))}
|
||||
@@ -120,10 +134,18 @@ interface ActivityGroupProps {
|
||||
items: ActiveWorkItem[]
|
||||
currentSessionID: string | null
|
||||
currentRepoId: number | null
|
||||
currentServerId: string | null
|
||||
onSelect: (item: ActiveWorkItem) => void
|
||||
}
|
||||
|
||||
function ActivityGroup({ heading, items, currentSessionID, currentRepoId, onSelect }: ActivityGroupProps) {
|
||||
function ActivityGroup({
|
||||
heading,
|
||||
items,
|
||||
currentSessionID,
|
||||
currentRepoId,
|
||||
currentServerId,
|
||||
onSelect,
|
||||
}: ActivityGroupProps) {
|
||||
if (items.length === 0) return null
|
||||
|
||||
return (
|
||||
@@ -133,7 +155,7 @@ function ActivityGroup({ heading, items, currentSessionID, currentRepoId, onSele
|
||||
<ActivityRow
|
||||
key={item.key}
|
||||
item={item}
|
||||
isCurrent={isCurrentItem(item, currentSessionID, currentRepoId)}
|
||||
isCurrent={isCurrentItem(item, currentSessionID, currentRepoId, currentServerId)}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
))}
|
||||
@@ -152,6 +174,8 @@ export function ActivityList({
|
||||
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) {
|
||||
if (hideWhenEmpty) return null
|
||||
@@ -199,7 +223,7 @@ export function ActivityList({
|
||||
<CompactActivityRow
|
||||
key={item.key}
|
||||
item={item}
|
||||
isCurrent={isCurrentItem(item, route.sessionId, route.repoId)}
|
||||
isCurrent={isCurrentItem(item, currentSessionID, route.repoId, serverRoute?.serverId ?? null)}
|
||||
onSelect={onNavigate}
|
||||
/>
|
||||
))
|
||||
@@ -210,8 +234,9 @@ export function ActivityList({
|
||||
key={group.key}
|
||||
heading={group.heading}
|
||||
items={groups[group.key]}
|
||||
currentSessionID={route.sessionId}
|
||||
currentSessionID={currentSessionID}
|
||||
currentRepoId={route.repoId}
|
||||
currentServerId={serverRoute?.serverId ?? null}
|
||||
onSelect={onNavigate}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useState } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useDesktop } from '@/hooks/useDesktop'
|
||||
import { useSidebarCollapsed } from '@/hooks/useSidebarCollapsed'
|
||||
import { useSidebarWidth } from '@/hooks/useSidebarWidth'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
|
||||
@@ -24,6 +25,7 @@ export function DesktopSidebar() {
|
||||
const { updateParams } = useUrlParams()
|
||||
const openNavItem = useOpenNavItem()
|
||||
const [collapsed, toggle] = useSidebarCollapsed()
|
||||
const [sidebarWidth, setSidebarWidth] = useSidebarWidth()
|
||||
const [repoSwitcherOpen, setRepoSwitcherOpen] = useState(false)
|
||||
const { isAuthenticated, isLoading, logout } = useAuth()
|
||||
|
||||
@@ -63,7 +65,13 @@ export function DesktopSidebar() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Sidebar collapsed={collapsed} onToggle={toggle} className='mt-2'>
|
||||
<Sidebar
|
||||
collapsed={collapsed}
|
||||
onToggle={toggle}
|
||||
width={sidebarWidth}
|
||||
onWidthChange={setSidebarWidth}
|
||||
className='mt-2'
|
||||
>
|
||||
{primary.length > 0 && (
|
||||
<SidebarSection collapsed={collapsed}>
|
||||
{primary.map((item: NavPrimaryCta) => (
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useAuth } from '@/hooks/useAuth'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { getRepo } from '@/api/repos'
|
||||
import type { ActiveWorkItem } from '@/lib/activeWork'
|
||||
import type { UnreadScheduleRun } from '@/api/schedules'
|
||||
|
||||
vi.mock('@/hooks/useAuth')
|
||||
vi.mock('@/hooks/useServerHealth')
|
||||
@@ -32,6 +33,16 @@ vi.mock('@/hooks/useActiveWork', () => ({
|
||||
useRepoActivityState: () => null,
|
||||
}))
|
||||
|
||||
const scheduleMocks = vi.hoisted(() => ({
|
||||
useUnreadScheduleRuns: vi.fn(),
|
||||
useMarkAllScheduleRunsViewed: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
useUnreadScheduleRuns: scheduleMocks.useUnreadScheduleRuns,
|
||||
useMarkAllScheduleRunsViewed: scheduleMocks.useMarkAllScheduleRunsViewed,
|
||||
}))
|
||||
|
||||
function createActiveWorkItem(): ActiveWorkItem {
|
||||
const now = Date.now()
|
||||
return {
|
||||
@@ -61,6 +72,33 @@ function createActiveWorkItem(): ActiveWorkItem {
|
||||
}
|
||||
}
|
||||
|
||||
function createUnreadScheduleRun(): UnreadScheduleRun {
|
||||
const now = Date.now()
|
||||
return {
|
||||
id: 1,
|
||||
jobId: 1,
|
||||
repoId: 1,
|
||||
triggerSource: 'schedule',
|
||||
status: 'completed',
|
||||
startedAt: now - 60000,
|
||||
finishedAt: now - 30000,
|
||||
viewedAt: null,
|
||||
createdAt: now - 60000,
|
||||
sessionId: null,
|
||||
sessionTitle: null,
|
||||
logText: null,
|
||||
responseText: null,
|
||||
errorText: null,
|
||||
runBranch: null,
|
||||
commitHash: null,
|
||||
worktreePath: null,
|
||||
jobName: 'Nightly report',
|
||||
repoName: 'repo1',
|
||||
repoPath: '/path/to/repo1',
|
||||
preview: 'Report ready',
|
||||
}
|
||||
}
|
||||
|
||||
function setActivityGroups(groups: {
|
||||
needsInput?: ActiveWorkItem[]
|
||||
running?: ActiveWorkItem[]
|
||||
@@ -158,6 +196,8 @@ describe('MoreDrawer', () => {
|
||||
})
|
||||
activityMocks.useActivityWindowMinutes.mockReturnValue(30)
|
||||
setActivityGroups({})
|
||||
scheduleMocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 0, failed: 0 } })
|
||||
scheduleMocks.useMarkAllScheduleRunsViewed.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
})
|
||||
|
||||
it('renders Settings and Logout menu items', () => {
|
||||
@@ -361,7 +401,7 @@ describe('MoreDrawer', () => {
|
||||
expect(handleClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('offers the terminal plus account items on a linked-server route', () => {
|
||||
it('offers only the remote-capable project items on a linked-server route', () => {
|
||||
mockAuth()
|
||||
mockServerHealth()
|
||||
setActivityGroups({ recent: [createActiveWorkItem()] })
|
||||
@@ -371,15 +411,35 @@ describe('MoreDrawer', () => {
|
||||
})
|
||||
|
||||
expect(screen.getByText('Home')).toBeInTheDocument()
|
||||
expect(screen.getByText('MCP')).toBeInTheDocument()
|
||||
expect(screen.getByText('Skills')).toBeInTheDocument()
|
||||
expect(screen.getByText('Settings')).toBeInTheDocument()
|
||||
expect(screen.getByText('Logout')).toBeInTheDocument()
|
||||
expect(screen.getByText('Terminal')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Files')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Source Control')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('MCP')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Preview')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Schedules')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Reset Permissions')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Repos')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Assistant' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('heading', { name: 'Activity' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows unread reports and marks them all read', () => {
|
||||
const markAllReportsViewed = vi.fn()
|
||||
mockAuth()
|
||||
mockServerHealth()
|
||||
scheduleMocks.useUnreadScheduleRuns.mockReturnValue({
|
||||
data: { runs: [createUnreadScheduleRun()], total: 1, failed: 0 },
|
||||
})
|
||||
scheduleMocks.useMarkAllScheduleRunsViewed.mockReturnValue({ mutate: markAllReportsViewed, isPending: false })
|
||||
renderMoreDrawer({ initialEntry: '/repos/1/sessions/session-1', routePath: '/repos/:id/sessions/:sessionId' })
|
||||
|
||||
expect(screen.getByText('Nightly report')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Mark all read' }))
|
||||
|
||||
expect(markAllReportsViewed).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,8 @@ import { getRepo } from '@/api/repos'
|
||||
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
|
||||
import { SideDrawer, SideDrawerContent } from '@/components/ui/side-drawer'
|
||||
import { CompactActivityList } from '@/components/activity/CompactActivityList'
|
||||
import { ScheduleReportsList } from '@/components/notifications/ScheduleReportsBell'
|
||||
import { useMarkAllScheduleRunsViewed, useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { buildMoreItems, buildNavModel, isManagerOnlyNavItem, isSessionDetailPath, type MoreDrawerItem } from './moreDrawerItems'
|
||||
import { useSwipeBack } from '@/hooks/useMobile'
|
||||
import { cn, getRepoDisplayName } from '@/lib/utils'
|
||||
@@ -79,6 +81,9 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
|
||||
const isAssistantSession = isSessionDetail && searchParams.get('assistant') === '1'
|
||||
const isRemoteRoute = !isLocalOpenCodeServer(useRouteOpenCodeServerId())
|
||||
const { open: openMobileSheet } = useMobileTabBar()
|
||||
const { data: unreadReports } = useUnreadScheduleRuns()
|
||||
const markAllReportsViewed = useMarkAllScheduleRunsViewed()
|
||||
const total = unreadReports?.total ?? 0
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen && swipeRef.current) {
|
||||
@@ -188,6 +193,18 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
|
||||
)}
|
||||
</div>
|
||||
<SideDrawerContent className="flex flex-col gap-4 pb-3">
|
||||
{total > 0 && (
|
||||
<div className="overflow-hidden rounded-lg border border-border">
|
||||
<ScheduleReportsList
|
||||
runs={unreadReports?.runs ?? []}
|
||||
total={total}
|
||||
rowClassName="py-3"
|
||||
onMarkAllRead={() => markAllReportsViewed.mutate()}
|
||||
markAllPending={markAllReportsViewed.isPending}
|
||||
maxHeightClass=""
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{isOpen && !isRemoteRoute && (
|
||||
<CompactActivityList onNavigate={(path) => navigate(path)} />
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { SessionMoreButton } from './SessionMoreButton'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
open: vi.fn(),
|
||||
useUnreadScheduleRuns: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobileTabBar', () => ({
|
||||
useMobileTabBar: () => ({ open: mocks.open, openSheet: null, close: vi.fn() }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSchedules', () => ({
|
||||
useUnreadScheduleRuns: mocks.useUnreadScheduleRuns,
|
||||
}))
|
||||
|
||||
describe('SessionMoreButton', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('shows the unread report count and opens the drawer', () => {
|
||||
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 4, failed: 0 } })
|
||||
render(<SessionMoreButton />)
|
||||
|
||||
const button = screen.getByRole('button', { name: 'More, 4 unread reports' })
|
||||
expect(screen.getByText('4')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(button)
|
||||
|
||||
expect(mocks.open).toHaveBeenCalledWith('more')
|
||||
})
|
||||
|
||||
it('shows no count when there are no unread reports', () => {
|
||||
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 0, failed: 0 } })
|
||||
render(<SessionMoreButton />)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'More' })).toBeInTheDocument()
|
||||
expect(screen.queryByText('0')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,19 +1,25 @@
|
||||
import { MoreVertical } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScheduleReportsBadge } from '@/components/notifications/ScheduleReportsBadge'
|
||||
import { useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
|
||||
|
||||
export function SessionMoreButton() {
|
||||
const { open } = useMobileTabBar()
|
||||
const { data } = useUnreadScheduleRuns()
|
||||
const total = data?.total ?? 0
|
||||
const failed = data?.failed ?? 0
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => open('more')}
|
||||
className="md:hidden h-10 w-10 p-0 text-foreground border-border hover:bg-accent"
|
||||
aria-label="More"
|
||||
className="relative md:hidden h-10 w-10 p-0 text-foreground border-border hover:bg-accent"
|
||||
aria-label={total > 0 ? `More, ${total} unread reports` : 'More'}
|
||||
>
|
||||
<MoreVertical className="w-5 h-5" />
|
||||
<ScheduleReportsBadge total={total} failed={failed} />
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -149,6 +149,23 @@ function HomeHarness() {
|
||||
)
|
||||
}
|
||||
|
||||
function RemoteHarness() {
|
||||
const panel = useToolPanel(true)
|
||||
return (
|
||||
<>
|
||||
<ToolSidePanel
|
||||
panel={panel}
|
||||
repoId={0}
|
||||
sessionId="ses_remote"
|
||||
directory="/home/me/app"
|
||||
repoDirectory="/home/me/app"
|
||||
filesBasePath={undefined}
|
||||
/>
|
||||
<LocationProbe />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
activityMocks.useActiveWorkCounts.mockReturnValue({ needsInput: 0, running: 0 })
|
||||
@@ -330,6 +347,25 @@ describe('ToolSidePanel', () => {
|
||||
expect(buttons[0]).toHaveAccessibleName('Activity')
|
||||
})
|
||||
|
||||
it('shows only the remote-capable tools on a linked-server route', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/servers/srv_kitchen/sessions/ses_remote']}>
|
||||
<RemoteHarness />
|
||||
</MemoryRouter>,
|
||||
)
|
||||
|
||||
const rail = screen.getByRole('navigation', { name: 'Tools' })
|
||||
expect(
|
||||
within(rail)
|
||||
.getAllByRole('button')
|
||||
.map((button) => button.getAttribute('aria-label') ?? button.textContent?.trim()),
|
||||
).toEqual(['Activity', 'MCP', 'Skills', 'Terminal'])
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'MCP' }))
|
||||
expect(await screen.findByText('mcp-tool')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens the Activity panel with rows and the window label when clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
setActivityGroups([createActivityItem('other', 'Other Session', 2, 'Beta')])
|
||||
|
||||
@@ -32,11 +32,14 @@ import { formatActivityWindow } from '@/lib/activeWork'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { restoreOverlayFocus } from '@/lib/overlayFocus'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { isLocalOpenCodeServer, useRouteOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
|
||||
const PANEL_WIDTH_CLASSES: Partial<Record<PanelTool, string>> = {
|
||||
activity: 'w-80',
|
||||
}
|
||||
|
||||
const REMOTE_TOOL_KEYS: ReadonlySet<string> = new Set(['activity', 'mcp', 'skills', 'terminal'])
|
||||
|
||||
function ActivityWindowLabel() {
|
||||
const minutes = useActivityWindowMinutes()
|
||||
return (
|
||||
@@ -86,7 +89,6 @@ interface ToolSidePanelProps {
|
||||
directory?: string
|
||||
terminalDirectory?: string
|
||||
terminalTarget?: TerminalTarget
|
||||
allowedPanelTools?: readonly PanelTool[]
|
||||
repoDirectory?: string
|
||||
currentBranch?: string
|
||||
selectedFilePath?: string
|
||||
@@ -150,7 +152,6 @@ export function ToolSidePanel({
|
||||
directory,
|
||||
terminalDirectory,
|
||||
terminalTarget,
|
||||
allowedPanelTools,
|
||||
repoDirectory,
|
||||
currentBranch = 'main',
|
||||
selectedFilePath,
|
||||
@@ -162,6 +163,7 @@ export function ToolSidePanel({
|
||||
const { activeTool, toggleTool, closePanel } = panel
|
||||
const location = useLocation()
|
||||
const openNavItem = useOpenNavItem()
|
||||
const isRemoteRoute = !isLocalOpenCodeServer(useRouteOpenCodeServerId())
|
||||
const railRef = useRef<HTMLElement>(null)
|
||||
const previousActiveToolRef = useRef(activeTool)
|
||||
|
||||
@@ -180,13 +182,10 @@ export function ToolSidePanel({
|
||||
const terminalWorkspaceTarget: TerminalTarget | undefined =
|
||||
terminalTarget ?? (repoId === undefined ? undefined : { kind: 'repo', repoId })
|
||||
for (const item of buildToolItems(location.pathname)) {
|
||||
if (isRemoteRoute && !REMOTE_TOOL_KEYS.has(item.key)) continue
|
||||
const tool = toolKeyOf(item)
|
||||
if (isPanelTool(tool)) {
|
||||
if (allowedPanelTools && !allowedPanelTools.includes(tool)) continue
|
||||
panelTools.push({ item, tool })
|
||||
} else {
|
||||
actionItems.push(item)
|
||||
}
|
||||
if (isPanelTool(tool)) panelTools.push({ item, tool })
|
||||
else actionItems.push(item)
|
||||
}
|
||||
const activeLabel = panelTools.find(({ tool }) => tool === activeTool)?.item.label
|
||||
|
||||
|
||||
@@ -62,6 +62,11 @@ describe('buildMoreItems', () => {
|
||||
expect(items[12].key).toBe('logout')
|
||||
})
|
||||
|
||||
it('returns only the server tools a linked server can serve for /servers/:id/sessions/:sid', () => {
|
||||
const items = buildMoreItems('/servers/srv_kitchen/sessions/abc')
|
||||
expect(items.map((item) => item.key)).toEqual(['home', 'mcp', 'skills', 'terminal', 'settings', 'logout'])
|
||||
})
|
||||
|
||||
it('omits the Actions item for an Assistant session', () => {
|
||||
const items = buildMoreItems('/repos/0/sessions/abc')
|
||||
expect(items).toHaveLength(12)
|
||||
@@ -164,17 +169,13 @@ describe('buildToolItems', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('returns the linked server session tools without Manager-only entries', () => {
|
||||
expect(buildToolItems('/servers/srv_kitchen/sessions/ses_1').map((item) => item.key)).toEqual([
|
||||
it('returns the linked-server session tools for the tool rail', () => {
|
||||
expect(buildToolItems('/servers/srv_kitchen/sessions/abc').map((item) => item.key)).toEqual([
|
||||
'activity',
|
||||
'mcp',
|
||||
'skills',
|
||||
'terminal',
|
||||
])
|
||||
expect(buildMoreItems('/servers/srv_kitchen/sessions/ses_1').map((item) => item.key)).toEqual([
|
||||
'home',
|
||||
'terminal',
|
||||
'settings',
|
||||
'logout',
|
||||
])
|
||||
})
|
||||
|
||||
it('returns the home route tools', () => {
|
||||
|
||||
@@ -48,6 +48,7 @@ function getBaseItems(): MoreDrawerItem[] {
|
||||
}
|
||||
|
||||
const SESSION_DETAIL_PATH = /^\/repos\/(\d+)\/sessions\/[^/]+$/
|
||||
const SERVER_SESSION_DETAIL_PATH = /^\/servers\/[^/]+\/sessions\/[^/]+$/
|
||||
|
||||
export function isSessionDetailPath(pathname: string): boolean {
|
||||
return SESSION_DETAIL_PATH.test(pathname)
|
||||
@@ -61,8 +62,6 @@ const MANAGER_ONLY_ITEM_KEYS: ReadonlySet<string> = new Set([
|
||||
'preview',
|
||||
'walkthrough',
|
||||
'actions',
|
||||
'mcp',
|
||||
'skills',
|
||||
'reset-permissions',
|
||||
'schedules',
|
||||
'all-schedules',
|
||||
@@ -87,6 +86,18 @@ export function toolKeyOf(item: MoreDrawerItem): string | null {
|
||||
function buildRouteNavModel(pathname: string): NavModel {
|
||||
const baseItems = getBaseItems()
|
||||
|
||||
if (SERVER_SESSION_DETAIL_PATH.test(pathname)) {
|
||||
return {
|
||||
primary: [getAssistantNavItem()],
|
||||
items: [
|
||||
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
|
||||
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
|
||||
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
|
||||
...baseItems,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
const repoDetailMatch = /^\/repos\/(\d+)$/.exec(pathname)
|
||||
if (repoDetailMatch) {
|
||||
const id = repoDetailMatch[1]
|
||||
@@ -135,17 +146,6 @@ function buildRouteNavModel(pathname: string): NavModel {
|
||||
}
|
||||
}
|
||||
|
||||
const serverSessionMatch = /^\/servers\/[^/]+\/sessions\/[^/]+$/.exec(pathname)
|
||||
if (serverSessionMatch) {
|
||||
return {
|
||||
primary: [],
|
||||
items: [
|
||||
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
|
||||
...baseItems,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
if (isAssistantPath(pathname)) {
|
||||
const items: MoreDrawerItem[] = [
|
||||
{ key: 'files', label: 'Files', icon: Folder, dialog: 'files' },
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface ScheduleReportsBadgeProps {
|
||||
total: number
|
||||
failed: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function ScheduleReportsBadge({ total, failed, className }: ScheduleReportsBadgeProps) {
|
||||
if (total <= 0) return null
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'absolute -top-1 -right-1 min-w-4 rounded-full px-1 text-center text-[10px] font-medium leading-4 text-primary-foreground',
|
||||
failed > 0 ? 'bg-destructive' : 'bg-primary',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{total > 9 ? '9+' : total}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -14,10 +14,6 @@ vi.mock('@/hooks/useSchedules', () => ({
|
||||
useMarkAllScheduleRunsViewed: mocks.useMarkAllScheduleRunsViewed,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: vi.fn(() => false),
|
||||
}))
|
||||
|
||||
function renderBell() {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
@@ -50,7 +46,7 @@ describe('ScheduleReportsBell', () => {
|
||||
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 3, failed: 1 } })
|
||||
renderBell()
|
||||
|
||||
expect(screen.getByTestId('schedule-reports-count')).toHaveClass('bg-destructive')
|
||||
expect(screen.getByText('3')).toHaveClass('bg-destructive')
|
||||
})
|
||||
|
||||
it('renders nothing when there are no unread runs', () => {
|
||||
|
||||
@@ -4,28 +4,11 @@ import { CheckCircle2, Inbox, XCircle } from 'lucide-react'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
|
||||
import { BottomSheet, BottomSheetContent, BottomSheetHeader } from '@/components/ui/bottom-sheet'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { ScheduleReportsBadge } from '@/components/notifications/ScheduleReportsBadge'
|
||||
import { useMarkAllScheduleRunsViewed, useUnreadScheduleRuns } from '@/hooks/useSchedules'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { UnreadScheduleRun } from '@/api/schedules'
|
||||
|
||||
function ScheduleReportsCount({ total, failed }: { total: number; failed: number }) {
|
||||
if (total <= 0) return null
|
||||
|
||||
return (
|
||||
<span
|
||||
data-testid="schedule-reports-count"
|
||||
className={cn(
|
||||
'absolute -top-1 -right-1 min-w-4 rounded-full px-1 text-center text-[10px] font-medium leading-4 text-primary-foreground',
|
||||
failed > 0 ? 'bg-destructive' : 'bg-primary',
|
||||
)}
|
||||
>
|
||||
{total > 9 ? '9+' : total}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function ScheduleReportRow({ run, rowClassName, onClick }: { run: UnreadScheduleRun; rowClassName?: string; onClick: () => void }) {
|
||||
const failed = run.status === 'failed'
|
||||
const StatusIcon = failed ? XCircle : CheckCircle2
|
||||
@@ -66,9 +49,19 @@ interface ScheduleReportsListProps {
|
||||
markAllPending: boolean
|
||||
onNavigate?: () => void
|
||||
showTitle?: boolean
|
||||
maxHeightClass?: string
|
||||
}
|
||||
|
||||
function ScheduleReportsList({ runs, total, rowClassName, onMarkAllRead, markAllPending, onNavigate, showTitle = true }: ScheduleReportsListProps) {
|
||||
export function ScheduleReportsList({
|
||||
runs,
|
||||
total,
|
||||
rowClassName,
|
||||
onMarkAllRead,
|
||||
markAllPending,
|
||||
onNavigate,
|
||||
showTitle = true,
|
||||
maxHeightClass = 'max-h-[60vh]',
|
||||
}: ScheduleReportsListProps) {
|
||||
const navigate = useNavigate()
|
||||
|
||||
const openRun = (runId: number) => {
|
||||
@@ -99,7 +92,7 @@ function ScheduleReportsList({ runs, total, rowClassName, onMarkAllRead, markAll
|
||||
<p className="text-xs text-muted-foreground">New scheduled reports will show up here.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-h-[60vh] overflow-y-auto">
|
||||
<div className={cn('overflow-y-auto', maxHeightClass)}>
|
||||
{runs.map((run) => (
|
||||
<ScheduleReportRow key={run.id} run={run} rowClassName={rowClassName} onClick={() => openRun(run.id)} />
|
||||
))}
|
||||
@@ -117,7 +110,6 @@ function ScheduleReportsList({ runs, total, rowClassName, onMarkAllRead, markAll
|
||||
}
|
||||
|
||||
export function ScheduleReportsBell() {
|
||||
const isMobile = useMobile()
|
||||
const { data } = useUnreadScheduleRuns()
|
||||
const markAllViewed = useMarkAllScheduleRunsViewed()
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -132,44 +124,19 @@ export function ScheduleReportsBell() {
|
||||
|
||||
if (total === 0 && !open) return null
|
||||
|
||||
const trigger = (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={`Reports, ${total} unread`}
|
||||
onClick={isMobile ? () => setOpen(true) : undefined}
|
||||
className="relative h-10 w-10 text-muted-foreground transition-all duration-200 hover:bg-accent hover:text-foreground sm:h-8 sm:w-8"
|
||||
>
|
||||
<Inbox className="h-5 w-5 sm:h-4 sm:w-4" />
|
||||
<ScheduleReportsCount total={total} failed={failed} />
|
||||
</Button>
|
||||
)
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<>
|
||||
{trigger}
|
||||
<BottomSheet isOpen={open} onClose={() => setOpen(false)} ariaLabel="Reports">
|
||||
<BottomSheetHeader title="Reports" />
|
||||
<BottomSheetContent className="px-0 pt-0">
|
||||
<ScheduleReportsList
|
||||
runs={runs}
|
||||
total={total}
|
||||
rowClassName="py-3"
|
||||
onMarkAllRead={markAllRead}
|
||||
markAllPending={markAllViewed.isPending}
|
||||
onNavigate={() => setOpen(false)}
|
||||
showTitle={false}
|
||||
/>
|
||||
</BottomSheetContent>
|
||||
</BottomSheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||
<DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={`Reports, ${total} unread`}
|
||||
className="relative hidden h-10 w-10 text-muted-foreground transition-all duration-200 hover:bg-accent hover:text-foreground sm:h-8 sm:w-8 md:inline-flex"
|
||||
>
|
||||
<Inbox className="h-5 w-5 sm:h-4 sm:w-4" />
|
||||
<ScheduleReportsBadge total={total} failed={failed} />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-96 p-0">
|
||||
<ScheduleReportsList
|
||||
runs={runs}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
import { RepoMcpContent } from './RepoMcpDialog'
|
||||
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getStatus: vi.fn(),
|
||||
connect: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
removeAuth: vi.fn(),
|
||||
startAuth: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/mcp', () => ({ mcpApi: mocks }))
|
||||
|
||||
vi.mock('@/components/settings/McpOAuthDialog', () => ({
|
||||
McpOAuthDialog: () => <div data-testid="mcp-oauth-dialog" />,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() },
|
||||
}))
|
||||
|
||||
function renderContent(serverId: string) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OpenCodeServerProvider serverId={serverId}>{children}</OpenCodeServerProvider>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
return render(<RepoMcpContent open directory="/home/me/app" />, { wrapper })
|
||||
}
|
||||
|
||||
describe('RepoMcpContent', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('reads MCP status from the linked server for the session directory', async () => {
|
||||
mocks.getStatus.mockResolvedValue({
|
||||
server: { status: 'connected', integrationID: 'int_1' },
|
||||
})
|
||||
|
||||
renderContent('srv_kitchen')
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.getStatus).toHaveBeenCalledWith('/home/me/app', 'srv_kitchen')
|
||||
})
|
||||
})
|
||||
|
||||
it('connects and disconnects MCP servers against the linked server', async () => {
|
||||
mocks.getStatus.mockResolvedValue({ server: { status: 'connected' } })
|
||||
mocks.disconnect.mockResolvedValue(undefined)
|
||||
const user = userEvent.setup()
|
||||
|
||||
renderContent('srv_kitchen')
|
||||
|
||||
const toggle = await screen.findByRole('switch')
|
||||
await user.click(toggle)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.disconnect).toHaveBeenCalledWith('server', '/home/me/app', 'srv_kitchen')
|
||||
})
|
||||
})
|
||||
|
||||
it('hides every Manager OAuth action for a linked server', async () => {
|
||||
mocks.getStatus.mockResolvedValue({
|
||||
server: { status: 'connected', integrationID: 'int_1' },
|
||||
authServer: { status: 'needs_auth', error: 'auth required', integrationID: 'int_2' },
|
||||
})
|
||||
|
||||
renderContent('srv_kitchen')
|
||||
|
||||
await screen.findByText('Auth Required')
|
||||
|
||||
expect(screen.queryByTitle('Click for options')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Auth' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Re-authenticate')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Remove Auth')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId('mcp-oauth-dialog')).not.toBeInTheDocument()
|
||||
expect(mocks.removeAuth).not.toHaveBeenCalled()
|
||||
expect(mocks.startAuth).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the Manager OAuth actions for the local server', async () => {
|
||||
mocks.getStatus.mockResolvedValue({
|
||||
server: { status: 'connected', integrationID: 'int_1' },
|
||||
})
|
||||
const user = userEvent.setup()
|
||||
|
||||
renderContent('local')
|
||||
|
||||
expect(await screen.findByTestId('mcp-oauth-dialog')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByTitle('Click for options'))
|
||||
|
||||
expect(await screen.findByText('Re-authenticate')).toBeInTheDocument()
|
||||
expect(screen.getByText('Remove Auth')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -4,7 +4,7 @@ import { RepoMcpServerList } from './RepoMcpServerList'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { McpOAuthDialog } from '@/components/settings/McpOAuthDialog'
|
||||
import { mcpApi, type McpStatus, type McpAuthStartResponse } from '@/api/mcp'
|
||||
import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
import { isLocalOpenCodeServer, useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { invalidateSessionCaches } from '@/lib/queryInvalidation'
|
||||
import { showToast } from '@/lib/toast'
|
||||
@@ -23,6 +23,7 @@ interface RepoMcpContentProps {
|
||||
|
||||
export function RepoMcpContent({ open, directory }: RepoMcpContentProps) {
|
||||
const openCodeServerId = useOpenCodeServerId()
|
||||
const isRemoteServer = !isLocalOpenCodeServer(openCodeServerId)
|
||||
const queryClient = useQueryClient()
|
||||
const [localStatus, setLocalStatus] = useState<Record<string, McpStatus>>({})
|
||||
const [isLoadingStatus, setIsLoadingStatus] = useState(false)
|
||||
@@ -108,36 +109,41 @@ export function RepoMcpContent({ open, directory }: RepoMcpContentProps) {
|
||||
serverIds={serverIds}
|
||||
isLoadingStatus={isLoadingStatus}
|
||||
localStatus={localStatus}
|
||||
oauthAvailable={!isRemoteServer}
|
||||
toggleMutation={toggleMutation}
|
||||
removeAuthMutation={removeAuthMutation}
|
||||
onAuthClick={setAuthDialogServerId}
|
||||
onRemoveAuthClick={setRemoveAuthConfirmServer}
|
||||
/>
|
||||
|
||||
<DeleteDialog
|
||||
open={!!removeAuthConfirmServer}
|
||||
onOpenChange={() => setRemoveAuthConfirmServer(null)}
|
||||
onConfirm={() => {
|
||||
if (removeAuthConfirmServer) {
|
||||
removeAuthMutation.mutate(removeAuthConfirmServer)
|
||||
}
|
||||
}}
|
||||
onCancel={() => setRemoveAuthConfirmServer(null)}
|
||||
title="Remove Authentication"
|
||||
description="This will remove the OAuth credentials for this MCP server at this location. You will need to re-authenticate to use this server here again."
|
||||
itemName={removeAuthConfirmServer ? formatMcpServerName(removeAuthConfirmServer) : ''}
|
||||
isDeleting={removeAuthMutation.isPending}
|
||||
/>
|
||||
{!isRemoteServer && (
|
||||
<DeleteDialog
|
||||
open={!!removeAuthConfirmServer}
|
||||
onOpenChange={() => setRemoveAuthConfirmServer(null)}
|
||||
onConfirm={() => {
|
||||
if (removeAuthConfirmServer) {
|
||||
removeAuthMutation.mutate(removeAuthConfirmServer)
|
||||
}
|
||||
}}
|
||||
onCancel={() => setRemoveAuthConfirmServer(null)}
|
||||
title="Remove Authentication"
|
||||
description="This will remove the OAuth credentials for this MCP server at this location. You will need to re-authenticate to use this server here again."
|
||||
itemName={removeAuthConfirmServer ? formatMcpServerName(removeAuthConfirmServer) : ''}
|
||||
isDeleting={removeAuthMutation.isPending}
|
||||
/>
|
||||
)}
|
||||
|
||||
<McpOAuthDialog
|
||||
open={!!authDialogServerId}
|
||||
onOpenChange={(o) => !o && setAuthDialogServerId(null)}
|
||||
serverName={authDialogServerId || ''}
|
||||
onStartAuth={handleOAuthStartAuth}
|
||||
onCheckStatus={handleOAuthCheckStatus}
|
||||
onSuccess={handleOAuthSuccess}
|
||||
directory={directory}
|
||||
/>
|
||||
{!isRemoteServer && (
|
||||
<McpOAuthDialog
|
||||
open={!!authDialogServerId}
|
||||
onOpenChange={(o) => !o && setAuthDialogServerId(null)}
|
||||
serverName={authDialogServerId || ''}
|
||||
onStartAuth={handleOAuthStartAuth}
|
||||
onCheckStatus={handleOAuthCheckStatus}
|
||||
onSuccess={handleOAuthSuccess}
|
||||
directory={directory}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ interface RepoMcpServerListProps {
|
||||
serverIds: string[]
|
||||
isLoadingStatus: boolean
|
||||
localStatus: Record<string, McpStatus>
|
||||
oauthAvailable: boolean
|
||||
toggleMutation: {
|
||||
mutate: (variables: { serverId: string; enable: boolean }) => void
|
||||
isPending: boolean
|
||||
@@ -29,6 +30,7 @@ export function RepoMcpServerList({
|
||||
serverIds,
|
||||
isLoadingStatus,
|
||||
localStatus,
|
||||
oauthAvailable,
|
||||
toggleMutation,
|
||||
removeAuthMutation,
|
||||
onAuthClick,
|
||||
@@ -56,7 +58,8 @@ export function RepoMcpServerList({
|
||||
const failed = status?.status === 'failed'
|
||||
const isOAuthServer = !!status?.integrationID
|
||||
const connectedWithOAuth = isOAuthServer && isConnected
|
||||
const showAuthButton = needsAuth || (isOAuthServer && failed)
|
||||
const showAuthButton = oauthAvailable && (needsAuth || (isOAuthServer && failed))
|
||||
const showOAuthMenu = oauthAvailable && (showAuthButton || connectedWithOAuth)
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -68,7 +71,7 @@ export function RepoMcpServerList({
|
||||
<p className="text-sm font-medium truncate">
|
||||
{formatMcpServerName(serverId)}
|
||||
</p>
|
||||
{(showAuthButton || connectedWithOAuth) ? (
|
||||
{showOAuthMenu ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
|
||||
@@ -4,10 +4,12 @@ import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
import { RepoSkillsDialog } from './RepoSkillsDialog'
|
||||
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
|
||||
import type { SkillFileInfo } from '@opencode-manager/shared'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listManagedSkills: vi.fn(),
|
||||
listSkills: vi.fn(),
|
||||
activateSkill: vi.fn(),
|
||||
}))
|
||||
|
||||
@@ -20,6 +22,7 @@ vi.mock('@/api/settings', () => ({
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
activateSkill: mocks.activateSkill,
|
||||
listSkills: mocks.listSkills,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
@@ -260,4 +263,70 @@ describe('RepoSkillsDialog', () => {
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('linked server', () => {
|
||||
const remoteSkill = {
|
||||
id: 'sk_1',
|
||||
name: 'remote-skill',
|
||||
description: 'From the server',
|
||||
path: '/home/me/app/.opencode/skills/remote-skill/SKILL.md',
|
||||
content: 'Remote body',
|
||||
}
|
||||
|
||||
const renderRemote = (onSkillLoaded = vi.fn(), onOpenChange = vi.fn()) =>
|
||||
render(
|
||||
<OpenCodeServerProvider serverId="srv_kitchen">
|
||||
<RepoSkillsDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
repoId={0}
|
||||
sessionId="ses_remote"
|
||||
directory="/home/me/app"
|
||||
onSkillLoaded={onSkillLoaded}
|
||||
/>
|
||||
</OpenCodeServerProvider>,
|
||||
{ wrapper: createWrapper() },
|
||||
)
|
||||
|
||||
it('lists skills from the linked server and hides install and delete actions', async () => {
|
||||
mocks.listSkills.mockResolvedValue([remoteSkill])
|
||||
|
||||
renderRemote()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('remote-skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
expect(mocks.listSkills).toHaveBeenCalledWith('/home/me/app', 'srv_kitchen')
|
||||
expect(mocks.listManagedSkills).not.toHaveBeenCalled()
|
||||
expect(screen.queryByRole('button', { name: /install skill/i })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Actions for remote-skill' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('loads a linked-server skill into the current session', async () => {
|
||||
mocks.listSkills.mockResolvedValue([remoteSkill])
|
||||
mocks.activateSkill.mockReturnValue(new Promise(() => {}))
|
||||
const onSkillLoaded = vi.fn()
|
||||
const onOpenChange = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
|
||||
renderRemote(onSkillLoaded, onOpenChange)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('remote-skill')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
await user.click(screen.getByText('remote-skill').closest('[class*="cursor-pointer"]')!)
|
||||
|
||||
expect(mocks.activateSkill).toHaveBeenCalledWith('ses_remote', 'remote-skill', 'srv_kitchen')
|
||||
expect(onSkillLoaded).toHaveBeenCalledWith({
|
||||
name: 'remote-skill',
|
||||
description: 'From the server',
|
||||
body: 'Remote body',
|
||||
scope: 'project',
|
||||
location: '/home/me/app/.opencode/skills/remote-skill/SKILL.md',
|
||||
})
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { Download } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
@@ -7,10 +7,24 @@ import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { SkillLibraryList } from '@/components/skills/SkillLibraryList'
|
||||
import { SkillInstallDialog } from '@/components/settings/SkillInstallDialog'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { listSkills } from '@/api/opencode'
|
||||
import { useLoadSkill } from '@/hooks/useOpenCode'
|
||||
import { useDeleteSkill } from '@/hooks/useDeleteSkill'
|
||||
import { invalidateSkillCaches } from '@/lib/queryInvalidation'
|
||||
import { isLocalOpenCodeServer, useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import type { SkillFileInfo } from '@opencode-manager/shared'
|
||||
import type { SkillInfo } from '@opencode-manager/shared/opencode'
|
||||
|
||||
function toRemoteSkillFileInfo(skill: SkillInfo): SkillFileInfo {
|
||||
return {
|
||||
name: skill.name,
|
||||
description: skill.description ?? '',
|
||||
body: skill.content,
|
||||
scope: 'project',
|
||||
location: skill.path,
|
||||
}
|
||||
}
|
||||
|
||||
type RepoSkillsSessionProps =
|
||||
| { sessionId: string; directory?: string; onSkillLoaded?: (skill: SkillFileInfo) => void }
|
||||
@@ -37,19 +51,42 @@ export function RepoSkillsContent({
|
||||
onDone,
|
||||
}: RepoSkillsContentProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const serverId = useOpenCodeServerId()
|
||||
const isRemoteServer = !isLocalOpenCodeServer(serverId)
|
||||
const [installDialogOpen, setInstallDialogOpen] = useState(false)
|
||||
const { deleteSkill, setDeleteSkill, confirmDelete, isDeleting } = useDeleteSkill()
|
||||
const skillsQueryKey = directory ? ['settings', 'skills', 'directory', directory] : ['settings', 'skills', repoId]
|
||||
|
||||
const { isLoading, data, error } = useQuery({
|
||||
const { isLoading: isLocalLoading, data: localSkills, error: localError } = useQuery({
|
||||
queryKey: skillsQueryKey,
|
||||
queryFn: () => settingsApi.listManagedSkills(repoId, directory),
|
||||
enabled: open && (!!repoId || !!directory),
|
||||
enabled: open && !isRemoteServer && (!!repoId || !!directory),
|
||||
staleTime: 30000,
|
||||
})
|
||||
|
||||
const { isLoading: isRemoteLoading, data: remoteSkillInfos, error: remoteError } = useQuery({
|
||||
queryKey: serverScopedKey(['opencode', 'skills', directory], serverId),
|
||||
queryFn: () => listSkills(directory, serverId),
|
||||
enabled: open && isRemoteServer && Boolean(directory),
|
||||
staleTime: 30000,
|
||||
})
|
||||
|
||||
const remoteSkills = useMemo(
|
||||
() => remoteSkillInfos?.map(toRemoteSkillFileInfo),
|
||||
[remoteSkillInfos],
|
||||
)
|
||||
const skills = isRemoteServer ? remoteSkills : localSkills
|
||||
const isLoading = isRemoteServer ? isRemoteLoading : isLocalLoading
|
||||
const error = isRemoteServer ? remoteError : localError
|
||||
|
||||
const canLoad = !!sessionId
|
||||
const loadSkill = useLoadSkill(sessionId)
|
||||
const description = isRemoteServer
|
||||
? canLoad ? 'Load a skill from this server into the current session' : 'Skills available on this server'
|
||||
: canLoad ? 'Search and load a skill into the current session' : 'Skills available for this repository'
|
||||
const emptyHint = isRemoteServer
|
||||
? 'This server exposes no skills for this location.'
|
||||
: 'Install a skill or add one to .opencode/skills/<name>/SKILL.md.'
|
||||
|
||||
const handleLoad = (skill: SkillFileInfo) => {
|
||||
loadSkill.mutate({ skillName: skill.name })
|
||||
@@ -65,43 +102,49 @@ export function RepoSkillsContent({
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex shrink-0 items-center justify-between gap-2 px-4 py-3 sm:px-6">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{canLoad ? 'Search and load a skill into the current session' : 'Skills available for this repository'}
|
||||
{description}
|
||||
</p>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setInstallDialogOpen(true)}>
|
||||
<Download className="h-4 w-4 mr-1" />
|
||||
Install Skill
|
||||
</Button>
|
||||
{!isRemoteServer && (
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setInstallDialogOpen(true)}>
|
||||
<Download className="h-4 w-4 mr-1" />
|
||||
Install Skill
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-4 sm:p-6">
|
||||
<SkillLibraryList
|
||||
isLoading={isLoading}
|
||||
data={data}
|
||||
data={skills}
|
||||
error={error as Error | null}
|
||||
primaryAction={canLoad ? { label: 'Load', onClick: handleLoad } : undefined}
|
||||
rowActions={[{ label: 'Delete', onClick: setDeleteSkill, destructive: true }]}
|
||||
rowActions={isRemoteServer ? [] : [{ label: 'Delete', onClick: setDeleteSkill, destructive: true }]}
|
||||
emptyTitle="No skills found"
|
||||
emptyHint="Install a skill or add one to .opencode/skills/<name>/SKILL.md."
|
||||
emptyHint={emptyHint}
|
||||
maxHeightClassName="max-h-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<SkillInstallDialog
|
||||
open={installDialogOpen}
|
||||
onOpenChange={setInstallDialogOpen}
|
||||
onInstalled={handleInstalled}
|
||||
/>
|
||||
{!isRemoteServer && (
|
||||
<SkillInstallDialog
|
||||
open={installDialogOpen}
|
||||
onOpenChange={setInstallDialogOpen}
|
||||
onInstalled={handleInstalled}
|
||||
/>
|
||||
)}
|
||||
|
||||
<DeleteDialog
|
||||
open={deleteSkill !== null}
|
||||
onOpenChange={(isOpen) => !isOpen && setDeleteSkill(null)}
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => setDeleteSkill(null)}
|
||||
title="Delete Skill"
|
||||
description="Delete this managed skill directory and bundled files? This action cannot be undone."
|
||||
itemName={deleteSkill?.name}
|
||||
isDeleting={isDeleting}
|
||||
/>
|
||||
{!isRemoteServer && (
|
||||
<DeleteDialog
|
||||
open={deleteSkill !== null}
|
||||
onOpenChange={(isOpen) => !isOpen && setDeleteSkill(null)}
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={() => setDeleteSkill(null)}
|
||||
title="Delete Skill"
|
||||
description="Delete this managed skill directory and bundled files? This action cannot be undone."
|
||||
itemName={deleteSkill?.name}
|
||||
isDeleting={isDeleting}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { ContextUsageIndicator } from './ContextUsageIndicator'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useContextUsage: vi.fn(),
|
||||
useMobile: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useContextUsage', () => ({
|
||||
useContextUsage: mocks.useContextUsage,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: mocks.useMobile,
|
||||
}))
|
||||
|
||||
function renderIndicator() {
|
||||
return render(<ContextUsageIndicator sessionID="ses_1" isConnected={true} />)
|
||||
}
|
||||
|
||||
describe('ContextUsageIndicator', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders tokens and percentage on desktop', () => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
mocks.useContextUsage.mockReturnValue({ usage: { totalTokens: 1234, usagePercentage: 42 }, isLoading: false })
|
||||
renderIndicator()
|
||||
|
||||
expect(screen.getByText('1,234 (42%)')).toBeInTheDocument()
|
||||
expect(screen.queryByText('42%')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders only the percentage on mobile', () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
mocks.useContextUsage.mockReturnValue({ usage: { totalTokens: 1234, usagePercentage: 42 }, isLoading: false })
|
||||
renderIndicator()
|
||||
|
||||
expect(screen.getByText('42%')).toBeInTheDocument()
|
||||
expect(screen.queryByText('1,234 (42%)')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders only the token count on mobile without a percentage', () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
mocks.useContextUsage.mockReturnValue({ usage: { totalTokens: 1234, usagePercentage: null }, isLoading: false })
|
||||
renderIndicator()
|
||||
|
||||
expect(screen.getByText('1,234')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useContextUsage } from '@/hooks/useContextUsage'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
|
||||
interface ContextUsageIndicatorProps {
|
||||
directory?: string
|
||||
@@ -22,6 +23,7 @@ export function ContextUsageIndicator({
|
||||
revertMessageID,
|
||||
}: ContextUsageIndicatorProps) {
|
||||
const { usage, isLoading } = useContextUsage(sessionID, directory, revertMessageID)
|
||||
const isMobile = useMobile()
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -43,14 +45,18 @@ export function ContextUsageIndicator({
|
||||
return null
|
||||
}
|
||||
|
||||
const tokenText = usage.usagePercentage === null
|
||||
const compactText = usage.usagePercentage === null
|
||||
? usage.totalTokens.toLocaleString()
|
||||
: `${usage.usagePercentage}%`
|
||||
|
||||
const fullText = usage.usagePercentage === null
|
||||
? usage.totalTokens.toLocaleString()
|
||||
: `${usage.totalTokens.toLocaleString()} (${usage.usagePercentage}%)`
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`text-xs font-medium whitespace-nowrap ${getUsageTextColor(usage.usagePercentage ?? 0)}`}>
|
||||
{tokenText}
|
||||
{isMobile ? compactText : fullText}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -136,6 +136,8 @@ function activeWorkItem(
|
||||
key: `${directory}:${id}`,
|
||||
session: itemSession,
|
||||
repo: itemRepo,
|
||||
serverId: null,
|
||||
serverName: null,
|
||||
state,
|
||||
updatedAt: itemSession.time.updated,
|
||||
path: `/repos/${itemRepo.id}/sessions/${id}`,
|
||||
@@ -877,4 +879,76 @@ describe('SessionPickerDialog', () => {
|
||||
pinned: true,
|
||||
})
|
||||
})
|
||||
|
||||
describe('linked-server mode', () => {
|
||||
beforeEach(() => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a')]
|
||||
mocks.sessionsData = [session('ses_remote', 'Remote session', '/home/me/app')]
|
||||
})
|
||||
|
||||
it('lists the project sessions without Manager-only tabs and reports the chosen server session', async () => {
|
||||
const onSelectRemoteSession = vi.fn()
|
||||
renderPicker({
|
||||
remote: {
|
||||
serverId: 'srv_kitchen',
|
||||
serverName: 'Kitchen',
|
||||
projectDirectory: '/home/me/app',
|
||||
},
|
||||
onSelectRemoteSession,
|
||||
})
|
||||
|
||||
expect(screen.queryByRole('tab', { name: 'Projects' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: 'Active' })).toBeInTheDocument()
|
||||
|
||||
const row = await screen.findByRole('option', { name: /Remote session/ })
|
||||
expect(row).toHaveTextContent('Kitchen')
|
||||
|
||||
fireEvent.click(row)
|
||||
|
||||
expect(onSelectRemoteSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'ses_remote' }),
|
||||
'srv_kitchen',
|
||||
)
|
||||
})
|
||||
|
||||
it('navigates a remote active work row through the owning server', async () => {
|
||||
const onSelectRemoteSession = vi.fn()
|
||||
mocks.activeWorkGroups = {
|
||||
needsInput: [
|
||||
{
|
||||
key: '/home/me/app/ses_remote',
|
||||
session: session('ses_remote', 'Remote pending', '/home/me/app'),
|
||||
repo: null,
|
||||
serverId: 'srv_kitchen',
|
||||
serverName: 'Kitchen',
|
||||
state: 'needs-input',
|
||||
updatedAt: Date.now(),
|
||||
path: '/servers/srv_kitchen/sessions/ses_remote',
|
||||
},
|
||||
],
|
||||
running: [],
|
||||
recent: [],
|
||||
}
|
||||
renderPicker({
|
||||
remote: {
|
||||
serverId: 'srv_kitchen',
|
||||
serverName: 'Kitchen',
|
||||
projectDirectory: '/home/me/app',
|
||||
},
|
||||
onSelectRemoteSession,
|
||||
})
|
||||
openActiveTab()
|
||||
|
||||
const row = await screen.findByRole('option', { name: /Remote pending/ })
|
||||
expect(row).toHaveTextContent('Kitchen')
|
||||
expect(screen.queryByRole('button', { name: 'Session actions' })).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(row)
|
||||
|
||||
expect(onSelectRemoteSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'ses_remote' }),
|
||||
'srv_kitchen',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -48,6 +48,7 @@ const NEAR_BOTTOM_PX = 240
|
||||
type SessionPickerTab = 'active' | 'sessions' | 'projects'
|
||||
|
||||
const SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions', 'projects']
|
||||
const REMOTE_SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions']
|
||||
|
||||
const SESSION_PICKER_TAB_LABELS: Record<SessionPickerTab, string> = {
|
||||
active: 'Active',
|
||||
@@ -55,9 +56,15 @@ const SESSION_PICKER_TAB_LABELS: Record<SessionPickerTab, string> = {
|
||||
projects: 'Projects',
|
||||
}
|
||||
|
||||
function nextSessionPickerTab(tab: SessionPickerTab): SessionPickerTab {
|
||||
const index = SESSION_PICKER_TABS.indexOf(tab)
|
||||
return SESSION_PICKER_TABS[(index + 1) % SESSION_PICKER_TABS.length]
|
||||
function nextSessionPickerTab(tab: SessionPickerTab, tabs: SessionPickerTab[]): SessionPickerTab {
|
||||
const index = tabs.indexOf(tab)
|
||||
return tabs[(index + 1) % tabs.length]
|
||||
}
|
||||
|
||||
interface RemotePickerScope {
|
||||
serverId: string
|
||||
serverName?: string
|
||||
projectDirectory?: string
|
||||
}
|
||||
|
||||
interface SessionPickerDialogProps {
|
||||
@@ -66,14 +73,19 @@ interface SessionPickerDialogProps {
|
||||
currentRepo: Repo | undefined
|
||||
activeSessionID?: string
|
||||
onSelectSession: (session: Session, repo: Repo) => void
|
||||
onSelectRemoteSession?: (session: Session, serverId: string) => void
|
||||
onDeleteActiveSession: () => void
|
||||
onSelectRepo: (repo: Repo) => void
|
||||
/** Set on a linked-server route to list that server's sessions instead of Manager repos. */
|
||||
remote?: RemotePickerScope
|
||||
}
|
||||
|
||||
interface SessionPickerRow {
|
||||
key: string
|
||||
session: Session
|
||||
repo: Repo
|
||||
repo?: Repo
|
||||
serverId?: string
|
||||
serverName?: string
|
||||
updatedAt?: number
|
||||
}
|
||||
|
||||
@@ -87,14 +99,11 @@ function buildSections(
|
||||
sessions: Session[],
|
||||
pinnedKeys: ReadonlySet<string>,
|
||||
keyFn: (session: Session) => string,
|
||||
resolveRepo: (session: Session) => Repo | undefined,
|
||||
resolveRepo?: (session: Session) => Repo | undefined,
|
||||
): SessionPickerSection[] {
|
||||
const { pinned, today, older } = partitionSessions(sessions, pinnedKeys, keyFn)
|
||||
const toRows = (group: Session[]): SessionPickerRow[] =>
|
||||
group.flatMap((session) => {
|
||||
const repo = resolveRepo(session)
|
||||
return repo ? [{ key: keyFn(session), session, repo }] : []
|
||||
})
|
||||
group.map((session) => ({ key: keyFn(session), session, repo: resolveRepo?.(session) }))
|
||||
|
||||
const sections: SessionPickerSection[] = []
|
||||
const pinnedRows = toRows(pinned)
|
||||
@@ -189,6 +198,7 @@ interface SessionPickerRowItemProps {
|
||||
isPinned: boolean
|
||||
isPendingDelete: boolean
|
||||
showRepo: boolean
|
||||
showActions: boolean
|
||||
label?: string
|
||||
onOpen: (row: SessionPickerRow) => void
|
||||
onHover: (index: number) => void
|
||||
@@ -206,6 +216,7 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
|
||||
isPinned,
|
||||
isPendingDelete,
|
||||
showRepo,
|
||||
showActions,
|
||||
label,
|
||||
onOpen,
|
||||
onHover,
|
||||
@@ -263,13 +274,18 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
|
||||
: 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{showRepo && <span className="max-w-32 truncate">{getRepoDisplayName(row.repo)}</span>}
|
||||
{showRepo && row.repo ? (
|
||||
<span className="max-w-32 truncate">{getRepoDisplayName(row.repo)}</span>
|
||||
) : null}
|
||||
{showRepo && !row.repo && (row.serverName || row.serverId) ? (
|
||||
<span className="max-w-32 truncate">{row.serverName ?? row.serverId}</span>
|
||||
) : null}
|
||||
{!showRepo && label && <span className="max-w-32 truncate">{label}</span>}
|
||||
<span>{formatShortRelativeTime(new Date(row.updatedAt ?? row.session.time.updated))}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center pr-1">
|
||||
<DropdownMenu>
|
||||
{row.serverId || !showActions ? null : <DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
@@ -291,7 +307,7 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => onRequestDelete(row.session)}>Delete</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</DropdownMenu>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -301,6 +317,7 @@ interface SessionPickerRowActionsOptions {
|
||||
directories: string[]
|
||||
activeSessionID?: string
|
||||
onSelectSession: (session: Session, repo: Repo) => void
|
||||
onSelectRemoteSession?: (session: Session, serverId: string) => void
|
||||
onDeleteActiveSession: () => void
|
||||
}
|
||||
|
||||
@@ -325,6 +342,7 @@ function useSessionPickerRowActions({
|
||||
directories,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
onSelectRemoteSession,
|
||||
onDeleteActiveSession,
|
||||
}: SessionPickerRowActionsOptions): SessionPickerRowActions {
|
||||
const { data: sessionPins } = useSessionPins()
|
||||
@@ -341,9 +359,13 @@ function useSessionPickerRowActions({
|
||||
const openRow = useCallback(
|
||||
(row: SessionPickerRow | undefined) => {
|
||||
if (!row) return
|
||||
onSelectSession(row.session, row.repo)
|
||||
if (row.serverId) {
|
||||
onSelectRemoteSession?.(row.session, row.serverId)
|
||||
return
|
||||
}
|
||||
if (row.repo) onSelectSession(row.session, row.repo)
|
||||
},
|
||||
[onSelectSession],
|
||||
[onSelectSession, onSelectRemoteSession],
|
||||
)
|
||||
|
||||
const performDelete = useCallback(
|
||||
@@ -358,7 +380,7 @@ function useSessionPickerRowActions({
|
||||
|
||||
const deleteRow = useCallback(
|
||||
(row: SessionPickerRow | undefined) => {
|
||||
if (!row) return
|
||||
if (!row || row.serverId) return
|
||||
if (pendingDeleteKey !== row.key) {
|
||||
setPendingDeleteKey(row.key)
|
||||
return
|
||||
@@ -372,6 +394,7 @@ function useSessionPickerRowActions({
|
||||
|
||||
const handleTogglePin = useCallback(
|
||||
(row: SessionPickerRow) => {
|
||||
if (row.serverId) return
|
||||
togglePin.mutate({
|
||||
sessionId: row.session.id,
|
||||
directory: row.session.location.directory,
|
||||
@@ -431,6 +454,7 @@ interface SessionPickerListProps {
|
||||
pinnedKeys: ReadonlySet<string>
|
||||
pendingDeleteKey: string | null
|
||||
showRepo: boolean
|
||||
showRowActions?: boolean
|
||||
labelFor?: (row: SessionPickerRow) => string | undefined
|
||||
emptyState: React.ReactNode
|
||||
onOpenRow: (row: SessionPickerRow) => void
|
||||
@@ -455,6 +479,7 @@ function SessionPickerList({
|
||||
pinnedKeys,
|
||||
pendingDeleteKey,
|
||||
showRepo,
|
||||
showRowActions = true,
|
||||
labelFor,
|
||||
emptyState,
|
||||
onOpenRow,
|
||||
@@ -504,6 +529,7 @@ function SessionPickerList({
|
||||
isPinned={pinnedKeys.has(row.key)}
|
||||
isPendingDelete={pendingDeleteKey === row.key}
|
||||
showRepo={showRepo}
|
||||
showActions={showRowActions}
|
||||
label={labelFor?.(row)}
|
||||
onOpen={onOpenRow}
|
||||
onHover={onHoverRow}
|
||||
@@ -527,6 +553,7 @@ interface SessionPickerContentProps {
|
||||
currentRepo: Repo | undefined
|
||||
activeSessionID?: string
|
||||
onSelectSession: (session: Session, repo: Repo) => void
|
||||
onSelectRemoteSession?: (session: Session, serverId: string) => void
|
||||
onDeleteActiveSession: () => void
|
||||
switchHint: string
|
||||
searchInputRef: React.RefObject<HTMLInputElement | null>
|
||||
@@ -538,6 +565,7 @@ function SessionPickerContent({
|
||||
currentRepo,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
onSelectRemoteSession,
|
||||
onDeleteActiveSession,
|
||||
switchHint,
|
||||
searchInputRef,
|
||||
@@ -616,11 +644,18 @@ function SessionPickerContent({
|
||||
directories,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
onSelectRemoteSession,
|
||||
onDeleteActiveSession,
|
||||
})
|
||||
|
||||
const sections = useMemo(
|
||||
() => buildSections(filteredSessions, pinnedKeys, getSessionKey, resolveRepo),
|
||||
() =>
|
||||
buildSections(
|
||||
filteredSessions.filter((session) => Boolean(resolveRepo(session))),
|
||||
pinnedKeys,
|
||||
getSessionKey,
|
||||
resolveRepo,
|
||||
),
|
||||
[filteredSessions, pinnedKeys, resolveRepo],
|
||||
)
|
||||
const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
|
||||
@@ -787,6 +822,7 @@ interface ActivePickerContentProps {
|
||||
open: boolean
|
||||
activeSessionID?: string
|
||||
onSelectSession: (session: Session, repo: Repo) => void
|
||||
onSelectRemoteSession?: (session: Session, serverId: string) => void
|
||||
onDeleteActiveSession: () => void
|
||||
switchHint: string
|
||||
searchInputRef: React.RefObject<HTMLInputElement | null>
|
||||
@@ -796,6 +832,7 @@ function ActivePickerContent({
|
||||
open,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
onSelectRemoteSession,
|
||||
onDeleteActiveSession,
|
||||
switchHint,
|
||||
searchInputRef,
|
||||
@@ -815,7 +852,14 @@ function ActivePickerContent({
|
||||
const rows: SessionPickerRow[] = []
|
||||
for (const item of groups[definition.key]) {
|
||||
if (needle && !(item.session.title ?? '').toLowerCase().includes(needle)) continue
|
||||
rows.push({ key: item.key, session: item.session, repo: item.repo, updatedAt: item.updatedAt })
|
||||
rows.push({
|
||||
key: item.key,
|
||||
session: item.session,
|
||||
repo: item.repo ?? undefined,
|
||||
serverId: item.serverId ?? undefined,
|
||||
serverName: item.serverName ?? undefined,
|
||||
updatedAt: item.updatedAt,
|
||||
})
|
||||
}
|
||||
return rows.length > 0 ? [{ id: definition.key, heading: definition.heading, rows }] : []
|
||||
})
|
||||
@@ -838,7 +882,10 @@ function ActivePickerContent({
|
||||
} = usePickerCursor(rows, defaultCursorKey)
|
||||
|
||||
const directories = useMemo(
|
||||
() => Array.from(new Set(rows.map((row) => row.session.location.directory))),
|
||||
() =>
|
||||
Array.from(
|
||||
new Set(rows.filter((row) => !row.serverId).map((row) => row.session.location.directory)),
|
||||
),
|
||||
[rows],
|
||||
)
|
||||
|
||||
@@ -855,6 +902,7 @@ function ActivePickerContent({
|
||||
directories,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
onSelectRemoteSession,
|
||||
onDeleteActiveSession,
|
||||
})
|
||||
|
||||
@@ -934,14 +982,179 @@ function ActivePickerContent({
|
||||
)
|
||||
}
|
||||
|
||||
const EMPTY_PINNED_KEYS: ReadonlySet<string> = new Set()
|
||||
|
||||
interface RemoteSessionPickerContentProps {
|
||||
open: boolean
|
||||
serverName?: string
|
||||
projectDirectory?: string
|
||||
activeSessionID?: string
|
||||
onSelectSession: (session: Session) => void
|
||||
switchHint: string
|
||||
searchInputRef: React.RefObject<HTMLInputElement | null>
|
||||
}
|
||||
|
||||
function RemoteSessionPickerContent({
|
||||
open,
|
||||
serverName,
|
||||
projectDirectory,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
switchHint,
|
||||
searchInputRef,
|
||||
}: RemoteSessionPickerContentProps) {
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const listId = useId()
|
||||
const optionBaseId = useId()
|
||||
|
||||
const {
|
||||
query,
|
||||
setQuery,
|
||||
trimmedQuery,
|
||||
filteredSessions,
|
||||
isSearchPending,
|
||||
isLoading,
|
||||
fetchNextPage,
|
||||
isFetchingNextPage,
|
||||
isFetchNextPageError,
|
||||
canFetchNextPage,
|
||||
} = useSessionSearch(projectDirectory ? [projectDirectory] : [])
|
||||
|
||||
const sections = useMemo(
|
||||
() => buildSections(filteredSessions, EMPTY_PINNED_KEYS, getSessionKey),
|
||||
[filteredSessions],
|
||||
)
|
||||
const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
|
||||
|
||||
const activeRow = useMemo(
|
||||
() => rows.find((row) => row.session.id === activeSessionID),
|
||||
[rows, activeSessionID],
|
||||
)
|
||||
const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null
|
||||
|
||||
const {
|
||||
rowIndexByKey,
|
||||
cursorIndex,
|
||||
cursorRow,
|
||||
registerRef,
|
||||
moveCursor,
|
||||
resetCursor,
|
||||
} = usePickerCursor(rows, defaultCursorKey)
|
||||
|
||||
const openRow = useCallback(
|
||||
(row: SessionPickerRow | undefined) => {
|
||||
if (row) onSelectSession(row.session)
|
||||
},
|
||||
[onSelectSession],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
resetCursor()
|
||||
}, [trimmedQuery, resetCursor])
|
||||
|
||||
const handleSearchKeyDown = usePickerKeyNav({
|
||||
rows,
|
||||
cursorIndex,
|
||||
cursorRow,
|
||||
moveCursor,
|
||||
onOpenRow: openRow,
|
||||
})
|
||||
|
||||
const handleListScroll = useCallback(
|
||||
(event: React.UIEvent<HTMLDivElement>) => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget
|
||||
if (scrollHeight - scrollTop - clientHeight <= NEAR_BOTTOM_PX && canFetchNextPage) {
|
||||
void fetchNextPage()
|
||||
}
|
||||
},
|
||||
[canFetchNextPage, fetchNextPage],
|
||||
)
|
||||
|
||||
const labelFor = useCallback(() => serverName, [serverName])
|
||||
|
||||
return (
|
||||
<div className="mt-4 flex min-h-0 flex-1 flex-col">
|
||||
<PickerSearchBar
|
||||
inputRef={searchInputRef}
|
||||
listId={listId}
|
||||
open={open}
|
||||
activeDescendantId={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
onKeyDown={handleSearchKeyDown}
|
||||
placeholder="Search sessions..."
|
||||
name="remote-session-picker-search"
|
||||
/>
|
||||
|
||||
<SessionPickerList
|
||||
listRef={listRef}
|
||||
listId={listId}
|
||||
optionBaseId={optionBaseId}
|
||||
ariaLabel="Sessions"
|
||||
sections={sections}
|
||||
rows={rows}
|
||||
rowIndexByKey={rowIndexByKey}
|
||||
cursorIndex={cursorIndex}
|
||||
activeSessionID={activeSessionID}
|
||||
pinnedKeys={EMPTY_PINNED_KEYS}
|
||||
pendingDeleteKey={null}
|
||||
showRepo={false}
|
||||
showRowActions={false}
|
||||
labelFor={labelFor}
|
||||
emptyState={
|
||||
isLoading
|
||||
? 'Loading sessions...'
|
||||
: isSearchPending
|
||||
? 'Searching sessions...'
|
||||
: trimmedQuery
|
||||
? 'No sessions found'
|
||||
: 'No sessions yet'
|
||||
}
|
||||
onOpenRow={openRow}
|
||||
onHoverRow={moveCursor}
|
||||
onTogglePin={() => undefined}
|
||||
onRequestDelete={() => undefined}
|
||||
registerRef={registerRef}
|
||||
onScroll={handleListScroll}
|
||||
>
|
||||
{isFetchNextPageError && (
|
||||
<div className="flex flex-col items-center gap-2 py-4">
|
||||
<p className="text-sm text-muted-foreground">Failed to load more sessions</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
void fetchNextPage()
|
||||
}}
|
||||
disabled={isFetchingNextPage}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{isFetchingNextPage && rows.length > 0 && (
|
||||
<div className="py-4 text-center text-sm text-muted-foreground">Loading more sessions...</div>
|
||||
)}
|
||||
</SessionPickerList>
|
||||
|
||||
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
|
||||
↑↓ move · Enter open
|
||||
{switchHint ? ` · ${switchHint} sessions` : ''}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function SessionPickerDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
currentRepo,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
onSelectRemoteSession,
|
||||
onDeleteActiveSession,
|
||||
onSelectRepo,
|
||||
remote,
|
||||
}: SessionPickerDialogProps) {
|
||||
const searchInputRef = useRef<HTMLInputElement>(null)
|
||||
const activeSearchInputRef = useRef<HTMLInputElement>(null)
|
||||
@@ -960,6 +1173,8 @@ export function SessionPickerDialog({
|
||||
},
|
||||
[preferences],
|
||||
)
|
||||
const isRemote = remote !== undefined
|
||||
const pickerTabs = isRemote ? REMOTE_SESSION_PICKER_TABS : SESSION_PICKER_TABS
|
||||
const [tab, setTab] = useState<SessionPickerTab>('sessions')
|
||||
const [prevOpen, setPrevOpen] = useState(open)
|
||||
|
||||
@@ -968,10 +1183,12 @@ export function SessionPickerDialog({
|
||||
if (open) setTab('sessions')
|
||||
}
|
||||
|
||||
const activeTab: SessionPickerTab = isRemote && tab === 'projects' ? 'sessions' : tab
|
||||
|
||||
const toggleTab = useCallback(() => {
|
||||
focusSearchAfterSwitchRef.current = true
|
||||
setTab((current) => nextSessionPickerTab(current))
|
||||
}, [])
|
||||
setTab((current) => nextSessionPickerTab(current, pickerTabs))
|
||||
}, [pickerTabs])
|
||||
|
||||
useShortcutActions({ switchPickerTab: open ? toggleTab : undefined })
|
||||
|
||||
@@ -983,12 +1200,12 @@ export function SessionPickerDialog({
|
||||
if (!hasFinePointer && !focusSearchAfterSwitchRef.current) return
|
||||
const frame = requestAnimationFrame(() => {
|
||||
focusSearchAfterSwitchRef.current = false
|
||||
if (tab === 'projects') projectSearchInputRef.current?.focus()
|
||||
else if (tab === 'active') activeSearchInputRef.current?.focus()
|
||||
if (activeTab === 'projects') projectSearchInputRef.current?.focus()
|
||||
else if (activeTab === 'active') activeSearchInputRef.current?.focus()
|
||||
else searchInputRef.current?.focus()
|
||||
})
|
||||
return () => cancelAnimationFrame(frame)
|
||||
}, [open, tab, hasFinePointer])
|
||||
}, [open, activeTab, hasFinePointer])
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -1006,16 +1223,16 @@ export function SessionPickerDialog({
|
||||
}}
|
||||
>
|
||||
<Tabs
|
||||
value={tab}
|
||||
value={activeTab}
|
||||
onValueChange={(value) => setTab(value as SessionPickerTab)}
|
||||
className="flex min-h-0 w-full min-w-0 flex-1 flex-col gap-0"
|
||||
>
|
||||
<div className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
|
||||
<DialogTitle className="sr-only">{SESSION_PICKER_TAB_LABELS[tab]}</DialogTitle>
|
||||
<DialogTitle className="sr-only">{SESSION_PICKER_TAB_LABELS[activeTab]}</DialogTitle>
|
||||
<TabsList>
|
||||
<TabsTrigger value="active">Active</TabsTrigger>
|
||||
<TabsTrigger value="sessions">Sessions</TabsTrigger>
|
||||
<TabsTrigger value="projects">Projects</TabsTrigger>
|
||||
{isRemote ? null : <TabsTrigger value="projects">Projects</TabsTrigger>}
|
||||
</TabsList>
|
||||
</div>
|
||||
<TabsContent
|
||||
@@ -1026,6 +1243,7 @@ export function SessionPickerDialog({
|
||||
open={open}
|
||||
activeSessionID={activeSessionID}
|
||||
onSelectSession={onSelectSession}
|
||||
onSelectRemoteSession={onSelectRemoteSession}
|
||||
onDeleteActiveSession={onDeleteActiveSession}
|
||||
switchHint={switchHint}
|
||||
searchInputRef={activeSearchInputRef}
|
||||
@@ -1035,29 +1253,44 @@ export function SessionPickerDialog({
|
||||
value="sessions"
|
||||
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
|
||||
>
|
||||
<SessionPickerContent
|
||||
open={open}
|
||||
currentRepo={currentRepo}
|
||||
activeSessionID={activeSessionID}
|
||||
onSelectSession={onSelectSession}
|
||||
onDeleteActiveSession={onDeleteActiveSession}
|
||||
switchHint={switchHint}
|
||||
searchInputRef={searchInputRef}
|
||||
hasFinePointer={hasFinePointer}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent
|
||||
value="projects"
|
||||
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
|
||||
>
|
||||
<ProjectPickerContent
|
||||
open={open}
|
||||
currentRepo={currentRepo}
|
||||
onSelectRepo={onSelectRepo}
|
||||
switchHint={switchHint}
|
||||
searchInputRef={projectSearchInputRef}
|
||||
/>
|
||||
{remote ? (
|
||||
<RemoteSessionPickerContent
|
||||
open={open}
|
||||
serverName={remote.serverName}
|
||||
projectDirectory={remote.projectDirectory}
|
||||
activeSessionID={activeSessionID}
|
||||
onSelectSession={(session) => onSelectRemoteSession?.(session, remote.serverId)}
|
||||
switchHint={switchHint}
|
||||
searchInputRef={searchInputRef}
|
||||
/>
|
||||
) : (
|
||||
<SessionPickerContent
|
||||
open={open}
|
||||
currentRepo={currentRepo}
|
||||
activeSessionID={activeSessionID}
|
||||
onSelectSession={onSelectSession}
|
||||
onSelectRemoteSession={onSelectRemoteSession}
|
||||
onDeleteActiveSession={onDeleteActiveSession}
|
||||
switchHint={switchHint}
|
||||
searchInputRef={searchInputRef}
|
||||
hasFinePointer={hasFinePointer}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
{isRemote ? null : (
|
||||
<TabsContent
|
||||
value="projects"
|
||||
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
|
||||
>
|
||||
<ProjectPickerContent
|
||||
open={open}
|
||||
currentRepo={currentRepo}
|
||||
onSelectRepo={onSelectRepo}
|
||||
switchHint={switchHint}
|
||||
searchInputRef={projectSearchInputRef}
|
||||
/>
|
||||
</TabsContent>
|
||||
)}
|
||||
</Tabs>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { buildOpenCodeServerLink, type OpenCodeServer, type OpenCodeServerTestResult } from '@opencode-manager/shared/schemas'
|
||||
import { buildOpenCodeServerLink, OPENCODE_SERVER_LINK_VERSION, type OpenCodeServer, type OpenCodeServerTestResult } from '@opencode-manager/shared/schemas'
|
||||
import { OpenCodeServerDialog, type OpenCodeServerFormValues } from './OpenCodeServerDialog'
|
||||
|
||||
const testResult: OpenCodeServerTestResult = {
|
||||
@@ -90,6 +90,20 @@ describe('OpenCodeServerDialog', () => {
|
||||
expect(screen.queryByText(/Pairing with/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('explains that a pairing link from an unsupported version cannot be used', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
const outdated = pairingLink.replace(`v=${OPENCODE_SERVER_LINK_VERSION}`, 'v=1')
|
||||
await user.type(screen.getByLabelText('Pairing link'), outdated)
|
||||
await user.click(screen.getByRole('button', { name: 'Use link' }))
|
||||
|
||||
expect(screen.getByRole('alert')).toHaveTextContent(
|
||||
`This pairing link uses link version 1, but this Manager expects version ${OPENCODE_SERVER_LINK_VERSION}. Update the Manager or the ocm CLI and generate a new QR code.`,
|
||||
)
|
||||
expect(screen.queryByText(/Pairing with/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('sends clearPassword when the stored password is explicitly cleared', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onSubmit } = renderDialog({ server: savedServer })
|
||||
|
||||
@@ -4,8 +4,10 @@ import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { z } from 'zod'
|
||||
import { AlertTriangle, CheckCircle2, Loader2, ScanLine, XCircle } from 'lucide-react'
|
||||
import {
|
||||
OPENCODE_SERVER_DEFAULT_USERNAME,
|
||||
OPENCODE_SERVER_LINK_VERSION,
|
||||
OPENCODE_SERVER_USERNAME,
|
||||
parseOpenCodeServerLink,
|
||||
readOpenCodeServerLinkVersion,
|
||||
type OpenCodeServer,
|
||||
type OpenCodeServerLink,
|
||||
type OpenCodeServerTestResult,
|
||||
@@ -110,7 +112,7 @@ function buildDefaultValues(server?: OpenCodeServer | null): ServerFormValues {
|
||||
return {
|
||||
name: server?.name ?? '',
|
||||
baseUrl: server?.baseUrl ?? '',
|
||||
username: server?.username ?? OPENCODE_SERVER_DEFAULT_USERNAME,
|
||||
username: server?.username ?? OPENCODE_SERVER_USERNAME,
|
||||
password: '',
|
||||
enabled: server?.enabled ?? true,
|
||||
}
|
||||
@@ -177,7 +179,10 @@ export function OpenCodeServerDialog({
|
||||
const applyPairingLink = (text: string) => {
|
||||
const link = parseOpenCodeServerLink(text)
|
||||
if (!link) {
|
||||
setLinkError('That is not a valid OpenCode pairing link.')
|
||||
const version = readOpenCodeServerLinkVersion(text)
|
||||
setLinkError(version !== null && version !== OPENCODE_SERVER_LINK_VERSION
|
||||
? `This pairing link uses link version ${version}, but this Manager expects version ${OPENCODE_SERVER_LINK_VERSION}. Update the Manager or the ocm CLI and generate a new QR code.`
|
||||
: 'That is not a valid OpenCode pairing link.')
|
||||
return
|
||||
}
|
||||
setPairingLink(link)
|
||||
@@ -264,7 +269,7 @@ export function OpenCodeServerDialog({
|
||||
setLinkInput(event.target.value)
|
||||
setLinkError(null)
|
||||
}}
|
||||
placeholder="ocm://link?v=1&kind=opencode&..."
|
||||
placeholder={`ocm://link?v=${OPENCODE_SERVER_LINK_VERSION}&kind=opencode&...`}
|
||||
rows={2}
|
||||
className="font-mono"
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest'
|
||||
import { render, waitFor, act } from '@testing-library/react'
|
||||
import { QrCodeScanner } from './QrCodeScanner'
|
||||
|
||||
const { decodeMock } = vi.hoisted(() => ({ decodeMock: vi.fn() }))
|
||||
|
||||
vi.mock('jsqr', () => ({ default: decodeMock }))
|
||||
|
||||
const frameQueue: FrameRequestCallback[] = []
|
||||
const requestFrame = vi.fn((callback: FrameRequestCallback) => {
|
||||
frameQueue.push(callback)
|
||||
return frameQueue.length
|
||||
})
|
||||
const cancelFrame = vi.fn()
|
||||
|
||||
const imageDataMock = vi.fn((_x: number, _y: number, width: number, height: number) => ({
|
||||
data: new Uint8ClampedArray(width * height * 4),
|
||||
width,
|
||||
height,
|
||||
}))
|
||||
|
||||
const contextMock = {
|
||||
drawImage: vi.fn(),
|
||||
getImageData: imageDataMock,
|
||||
}
|
||||
|
||||
const getUserMediaMock = vi.fn(async () => ({ getTracks: () => [] }))
|
||||
const originalGetContext = HTMLCanvasElement.prototype.getContext
|
||||
|
||||
async function runFrame(timestamp: number) {
|
||||
await waitFor(() => expect(frameQueue.length).toBeGreaterThan(0))
|
||||
const callback = frameQueue.shift()
|
||||
await act(async () => {
|
||||
callback?.(timestamp)
|
||||
})
|
||||
}
|
||||
|
||||
function renderScanner() {
|
||||
return render(<QrCodeScanner open onOpenChange={vi.fn()} onResult={vi.fn()} />)
|
||||
}
|
||||
|
||||
describe('QrCodeScanner', () => {
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(HTMLMediaElement.prototype, 'play', {
|
||||
configurable: true,
|
||||
value: () => Promise.resolve(),
|
||||
})
|
||||
Object.defineProperty(HTMLMediaElement.prototype, 'readyState', {
|
||||
configurable: true,
|
||||
get: () => 4,
|
||||
})
|
||||
Object.defineProperty(HTMLVideoElement.prototype, 'videoWidth', {
|
||||
configurable: true,
|
||||
get: () => 1280,
|
||||
})
|
||||
Object.defineProperty(HTMLVideoElement.prototype, 'videoHeight', {
|
||||
configurable: true,
|
||||
get: () => 720,
|
||||
})
|
||||
Object.defineProperty(window, 'isSecureContext', {
|
||||
configurable: true,
|
||||
value: true,
|
||||
})
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
frameQueue.length = 0
|
||||
decodeMock.mockReturnValue(null)
|
||||
HTMLCanvasElement.prototype.getContext = vi.fn(
|
||||
() => contextMock,
|
||||
) as unknown as HTMLCanvasElement['getContext']
|
||||
Object.defineProperty(navigator, 'mediaDevices', {
|
||||
configurable: true,
|
||||
value: { getUserMedia: getUserMediaMock },
|
||||
})
|
||||
vi.stubGlobal('requestAnimationFrame', requestFrame)
|
||||
vi.stubGlobal('cancelAnimationFrame', cancelFrame)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
HTMLCanvasElement.prototype.getContext = originalGetContext
|
||||
})
|
||||
|
||||
it('decodes at most once per 100ms of animation frames', async () => {
|
||||
renderScanner()
|
||||
|
||||
await runFrame(100)
|
||||
expect(decodeMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
await runFrame(130)
|
||||
await runFrame(160)
|
||||
await runFrame(190)
|
||||
expect(decodeMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
await runFrame(200)
|
||||
expect(decodeMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('only resizes the canvas when the scan dimensions change', async () => {
|
||||
const widthSetter = vi.spyOn(HTMLCanvasElement.prototype, 'width', 'set')
|
||||
const heightSetter = vi.spyOn(HTMLCanvasElement.prototype, 'height', 'set')
|
||||
|
||||
renderScanner()
|
||||
|
||||
await runFrame(100)
|
||||
expect(widthSetter).toHaveBeenCalledTimes(1)
|
||||
expect(heightSetter).toHaveBeenCalledTimes(1)
|
||||
expect(imageDataMock).toHaveBeenNthCalledWith(1, 0, 0, 640, 360)
|
||||
|
||||
await runFrame(250)
|
||||
expect(widthSetter).toHaveBeenCalledTimes(1)
|
||||
expect(heightSetter).toHaveBeenCalledTimes(1)
|
||||
expect(imageDataMock).toHaveBeenNthCalledWith(2, 0, 0, 640, 360)
|
||||
|
||||
widthSetter.mockRestore()
|
||||
heightSetter.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import jsQR from 'jsqr'
|
||||
import { AlertCircle, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
@@ -11,6 +10,11 @@ import {
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
|
||||
const MAX_SCAN_DIMENSION = 640
|
||||
const DECODE_INTERVAL_MS = 100
|
||||
|
||||
type QrDecoder = typeof import('jsqr')['default']
|
||||
|
||||
interface QrCodeScannerProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
@@ -32,8 +36,18 @@ function describeCameraError(error: unknown): string {
|
||||
return 'The camera could not be started. Paste the pairing link instead.'
|
||||
}
|
||||
|
||||
function fitScanDimensions(width: number, height: number): { width: number; height: number } {
|
||||
const longest = Math.max(width, height)
|
||||
if (longest <= MAX_SCAN_DIMENSION) {
|
||||
return { width, height }
|
||||
}
|
||||
const scale = MAX_SCAN_DIMENSION / longest
|
||||
return { width: Math.round(width * scale), height: Math.round(height * scale) }
|
||||
}
|
||||
|
||||
export function QrCodeScanner({ open, onOpenChange, onResult }: QrCodeScannerProps) {
|
||||
const videoRef = useRef<HTMLVideoElement>(null)
|
||||
const decoderRef = useRef<QrDecoder | null>(null)
|
||||
const onResultRef = useRef(onResult)
|
||||
onResultRef.current = onResult
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -48,6 +62,9 @@ export function QrCodeScanner({ open, onOpenChange, onResult }: QrCodeScannerPro
|
||||
let frameId: number | null = null
|
||||
let cancelled = false
|
||||
let decoded = false
|
||||
let lastDecodeAt = Number.NEGATIVE_INFINITY
|
||||
let canvasWidth = 0
|
||||
let canvasHeight = 0
|
||||
const canvas = document.createElement('canvas')
|
||||
const context = canvas.getContext('2d', { willReadFrequently: true })
|
||||
|
||||
@@ -60,18 +77,35 @@ export function QrCodeScanner({ open, onOpenChange, onResult }: QrCodeScannerPro
|
||||
stream = null
|
||||
}
|
||||
|
||||
const scanFrame = () => {
|
||||
const scanFrame = (timestamp: number) => {
|
||||
if (cancelled || decoded) return
|
||||
const video = videoRef.current
|
||||
if (!video || !context || video.readyState < video.HAVE_ENOUGH_DATA) {
|
||||
if (timestamp - lastDecodeAt < DECODE_INTERVAL_MS) {
|
||||
frameId = requestAnimationFrame(scanFrame)
|
||||
return
|
||||
}
|
||||
canvas.width = video.videoWidth
|
||||
canvas.height = video.videoHeight
|
||||
context.drawImage(video, 0, 0, canvas.width, canvas.height)
|
||||
const imageData = context.getImageData(0, 0, canvas.width, canvas.height)
|
||||
const code = jsQR(imageData.data, imageData.width, imageData.height)
|
||||
const video = videoRef.current
|
||||
const decoder = decoderRef.current
|
||||
if (!video || !context || !decoder || video.readyState < video.HAVE_ENOUGH_DATA) {
|
||||
frameId = requestAnimationFrame(scanFrame)
|
||||
return
|
||||
}
|
||||
const size = fitScanDimensions(video.videoWidth, video.videoHeight)
|
||||
if (size.width < 1 || size.height < 1) {
|
||||
frameId = requestAnimationFrame(scanFrame)
|
||||
return
|
||||
}
|
||||
lastDecodeAt = timestamp
|
||||
if (size.width !== canvasWidth || size.height !== canvasHeight) {
|
||||
canvas.width = size.width
|
||||
canvas.height = size.height
|
||||
canvasWidth = size.width
|
||||
canvasHeight = size.height
|
||||
}
|
||||
context.drawImage(video, 0, 0, size.width, size.height)
|
||||
const imageData = context.getImageData(0, 0, size.width, size.height)
|
||||
const code = decoder(imageData.data, imageData.width, imageData.height, {
|
||||
inversionAttempts: 'dontInvert',
|
||||
})
|
||||
if (code?.data) {
|
||||
decoded = true
|
||||
stopCamera()
|
||||
@@ -82,6 +116,14 @@ export function QrCodeScanner({ open, onOpenChange, onResult }: QrCodeScannerPro
|
||||
frameId = requestAnimationFrame(scanFrame)
|
||||
}
|
||||
|
||||
const loadDecoder = async (): Promise<QrDecoder> => {
|
||||
if (!decoderRef.current) {
|
||||
const module = await import('jsqr')
|
||||
decoderRef.current = module.default
|
||||
}
|
||||
return decoderRef.current
|
||||
}
|
||||
|
||||
const startCamera = async () => {
|
||||
if (!navigator.mediaDevices?.getUserMedia) {
|
||||
setError('Camera access is not available in this browser. Paste the pairing link instead.')
|
||||
@@ -93,6 +135,15 @@ export function QrCodeScanner({ open, onOpenChange, onResult }: QrCodeScannerPro
|
||||
setIsStarting(false)
|
||||
return
|
||||
}
|
||||
try {
|
||||
await loadDecoder()
|
||||
} catch {
|
||||
if (cancelled) return
|
||||
setError('The QR decoder could not be loaded. Paste the pairing link instead.')
|
||||
setIsStarting(false)
|
||||
return
|
||||
}
|
||||
if (cancelled) return
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({
|
||||
video: { facingMode: 'environment' },
|
||||
|
||||
@@ -2,8 +2,13 @@ import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { Sidebar, SidebarSection, SidebarItem, SidebarCollapseToggle } from './sidebar'
|
||||
import { TooltipProvider } from './tooltip'
|
||||
import { SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH } from '@/hooks/useSidebarWidth'
|
||||
import { Folder } from 'lucide-react'
|
||||
|
||||
Element.prototype.setPointerCapture ??= () => {}
|
||||
Element.prototype.hasPointerCapture ??= () => false
|
||||
Element.prototype.releasePointerCapture ??= () => {}
|
||||
|
||||
describe('Sidebar', () => {
|
||||
it('renders children', () => {
|
||||
render(
|
||||
@@ -34,6 +39,153 @@ describe('Sidebar', () => {
|
||||
|
||||
expect(container.firstChild).toHaveClass('w-60')
|
||||
})
|
||||
|
||||
it('renders an inline width instead of the width class when width is provided', () => {
|
||||
const { container } = render(
|
||||
<Sidebar collapsed={false} onToggle={vi.fn()} width={320} onWidthChange={vi.fn()}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const aside = container.firstChild as HTMLElement
|
||||
expect(aside.style.width).toBe('320px')
|
||||
expect(aside).not.toHaveClass('w-60')
|
||||
})
|
||||
|
||||
it('keeps the collapsed width class when collapsed even if width is provided', () => {
|
||||
const { container } = render(
|
||||
<Sidebar collapsed={true} onToggle={vi.fn()} width={320} onWidthChange={vi.fn()}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const aside = container.firstChild as HTMLElement
|
||||
expect(aside).toHaveClass('w-14')
|
||||
expect(aside.style.width).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Sidebar resize handle', () => {
|
||||
it('is not rendered when collapsed', () => {
|
||||
render(
|
||||
<Sidebar collapsed={true} onToggle={vi.fn()} width={320} onWidthChange={vi.fn()}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
expect(screen.queryByRole('separator')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('is not rendered without onWidthChange', () => {
|
||||
render(
|
||||
<Sidebar collapsed={false} onToggle={vi.fn()} width={320}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
expect(screen.queryByRole('separator')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('exposes the current width via aria attributes', () => {
|
||||
render(
|
||||
<Sidebar collapsed={false} onToggle={vi.fn()} width={320} onWidthChange={vi.fn()}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
expect(handle).toHaveAttribute('aria-valuenow', '320')
|
||||
expect(handle).toHaveAttribute('aria-valuemin', String(SIDEBAR_MIN_WIDTH))
|
||||
expect(handle).toHaveAttribute('aria-valuemax', String(SIDEBAR_MAX_WIDTH))
|
||||
expect(handle).toHaveAttribute('aria-orientation', 'vertical')
|
||||
})
|
||||
|
||||
it('reports the dragged width from the first pointer move', () => {
|
||||
const handleWidthChange = vi.fn()
|
||||
const { container } = render(
|
||||
<Sidebar collapsed={false} width={300} onWidthChange={handleWidthChange}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
fireEvent.pointerDown(handle, { button: 0, pointerId: 1, clientX: 300 })
|
||||
fireEvent.pointerMove(handle, { pointerId: 1, clientX: 340 })
|
||||
|
||||
expect(handleWidthChange).toHaveBeenCalledWith(340)
|
||||
expect(container.firstChild).toHaveClass('transition-none')
|
||||
})
|
||||
|
||||
it('ignores pointer moves from another pointer id', () => {
|
||||
const handleWidthChange = vi.fn()
|
||||
render(
|
||||
<Sidebar collapsed={false} width={300} onWidthChange={handleWidthChange}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
fireEvent.pointerDown(handle, { button: 0, pointerId: 1, clientX: 300 })
|
||||
fireEvent.pointerMove(handle, { pointerId: 2, clientX: 400 })
|
||||
|
||||
expect(handleWidthChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stops reporting after pointer up and restores the transition classes', () => {
|
||||
const handleWidthChange = vi.fn()
|
||||
const { container } = render(
|
||||
<Sidebar collapsed={false} width={300} onWidthChange={handleWidthChange}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
fireEvent.pointerDown(handle, { button: 0, pointerId: 1, clientX: 300 })
|
||||
fireEvent.pointerUp(handle, { pointerId: 1, clientX: 320 })
|
||||
fireEvent.pointerMove(handle, { pointerId: 1, clientX: 360 })
|
||||
|
||||
expect(handleWidthChange).not.toHaveBeenCalled()
|
||||
expect(container.firstChild).toHaveClass('transition-[width]')
|
||||
})
|
||||
|
||||
it('adjusts the width from the keyboard', () => {
|
||||
const handleWidthChange = vi.fn()
|
||||
render(
|
||||
<Sidebar collapsed={false} width={300} onWidthChange={handleWidthChange}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
const handle = screen.getByRole('separator', { name: 'Resize sidebar' })
|
||||
|
||||
fireEvent.keyDown(handle, { key: 'ArrowRight' })
|
||||
expect(handleWidthChange).toHaveBeenLastCalledWith(316)
|
||||
|
||||
fireEvent.keyDown(handle, { key: 'ArrowLeft' })
|
||||
expect(handleWidthChange).toHaveBeenLastCalledWith(284)
|
||||
|
||||
fireEvent.keyDown(handle, { key: 'ArrowRight', shiftKey: true })
|
||||
expect(handleWidthChange).toHaveBeenLastCalledWith(364)
|
||||
|
||||
fireEvent.keyDown(handle, { key: 'Home' })
|
||||
expect(handleWidthChange).toHaveBeenLastCalledWith(SIDEBAR_MIN_WIDTH)
|
||||
|
||||
fireEvent.keyDown(handle, { key: 'End' })
|
||||
expect(handleWidthChange).toHaveBeenLastCalledWith(SIDEBAR_MAX_WIDTH)
|
||||
})
|
||||
|
||||
it('ignores unhandled keys', () => {
|
||||
const handleWidthChange = vi.fn()
|
||||
render(
|
||||
<Sidebar collapsed={false} width={300} onWidthChange={handleWidthChange}>
|
||||
<div>Content</div>
|
||||
</Sidebar>
|
||||
)
|
||||
|
||||
fireEvent.keyDown(screen.getByRole('separator', { name: 'Resize sidebar' }), { key: 'a' })
|
||||
|
||||
expect(handleWidthChange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('SidebarSection', () => {
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
SIDEBAR_MAX_WIDTH,
|
||||
SIDEBAR_MIN_WIDTH,
|
||||
} from '@/hooks/useSidebarWidth'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
|
||||
export interface SidebarProps {
|
||||
@@ -11,6 +16,14 @@ export interface SidebarProps {
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
ariaLabel?: string
|
||||
width?: number
|
||||
onWidthChange?: (width: number) => void
|
||||
}
|
||||
|
||||
interface SidebarDragState {
|
||||
pointerId: number
|
||||
startX: number
|
||||
startWidth: number
|
||||
}
|
||||
|
||||
export function Sidebar({
|
||||
@@ -21,17 +34,112 @@ export function Sidebar({
|
||||
className,
|
||||
children,
|
||||
ariaLabel = 'Sidebar',
|
||||
width,
|
||||
onWidthChange,
|
||||
}: SidebarProps) {
|
||||
const dragRef = useRef<SidebarDragState | null>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
|
||||
const handlePointerDown = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0 || width === undefined || !onWidthChange) {
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
event.currentTarget.setPointerCapture?.(event.pointerId)
|
||||
dragRef.current = {
|
||||
pointerId: event.pointerId,
|
||||
startX: event.clientX,
|
||||
startWidth: width,
|
||||
}
|
||||
setIsDragging(true)
|
||||
},
|
||||
[onWidthChange, width]
|
||||
)
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
const drag = dragRef.current
|
||||
if (!drag || drag.pointerId !== event.pointerId || !onWidthChange) {
|
||||
return
|
||||
}
|
||||
onWidthChange(drag.startWidth + event.clientX - drag.startX)
|
||||
},
|
||||
[onWidthChange]
|
||||
)
|
||||
|
||||
const handlePointerEnd = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
|
||||
const drag = dragRef.current
|
||||
if (!drag || drag.pointerId !== event.pointerId) {
|
||||
return
|
||||
}
|
||||
if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {
|
||||
event.currentTarget.releasePointerCapture?.(event.pointerId)
|
||||
}
|
||||
dragRef.current = null
|
||||
setIsDragging(false)
|
||||
}, [])
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (!onWidthChange || width === undefined) {
|
||||
return
|
||||
}
|
||||
const step = event.shiftKey ? 64 : 16
|
||||
let nextWidth: number
|
||||
switch (event.key) {
|
||||
case 'ArrowLeft':
|
||||
nextWidth = width - step
|
||||
break
|
||||
case 'ArrowRight':
|
||||
nextWidth = width + step
|
||||
break
|
||||
case 'Home':
|
||||
nextWidth = SIDEBAR_MIN_WIDTH
|
||||
break
|
||||
case 'End':
|
||||
nextWidth = SIDEBAR_MAX_WIDTH
|
||||
break
|
||||
default:
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
onWidthChange(nextWidth)
|
||||
},
|
||||
[onWidthChange, width]
|
||||
)
|
||||
|
||||
const showResizeHandle = !collapsed && width !== undefined && onWidthChange !== undefined
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
'relative z-20 flex-shrink-0 border-r border-border bg-card/50 backdrop-blur-sm h-full flex flex-col pt-safe pb-safe transition-[width] duration-200',
|
||||
collapsed ? collapsedWidthClass : widthClass,
|
||||
'relative z-20 flex-shrink-0 border-r border-border bg-card/50 backdrop-blur-sm h-full flex flex-col pt-safe pb-safe',
|
||||
isDragging ? 'transition-none select-none' : 'transition-[width] duration-200',
|
||||
collapsed ? collapsedWidthClass : width === undefined ? widthClass : undefined,
|
||||
className
|
||||
)}
|
||||
style={!collapsed && width !== undefined ? { width } : undefined}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
{onToggle && <SidebarCollapseToggle collapsed={collapsed} onToggle={onToggle} />}
|
||||
{showResizeHandle && (
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label="Resize sidebar"
|
||||
tabIndex={0}
|
||||
aria-valuenow={width}
|
||||
aria-valuemin={SIDEBAR_MIN_WIDTH}
|
||||
aria-valuemax={SIDEBAR_MAX_WIDTH}
|
||||
className="absolute inset-y-0 -right-1 z-10 w-2 cursor-col-resize touch-none bg-transparent hover:bg-highlight/30 focus-visible:bg-highlight/30 focus-visible:outline-none"
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerEnd}
|
||||
onPointerCancel={handlePointerEnd}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
)}
|
||||
{children}
|
||||
</aside>
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user