feat(servers): bring linked-server sessions to parity with local

Add a read-only Source Control panel for linked servers backed by the OpenCode VCS API, broadcast remote events to every client, include recent linked-server sessions in Activity with per-server sidebar indicators, and enable the session picker, tool shortcuts, mobile activity, remote Skills panel and remote permission prompt titles.
This commit is contained in:
Chris Scott committed 2026-10-18 21:46:14 -04:00
1 parent 9ec2ed5903
commit 7874afdab9
38 files changed
+1506 -279

No files matched your search

@@ -0,0 +1,30 @@
import { ActivitySpinner } from '@/components/ui/activity-spinner'
import { cn } from '@/lib/utils'
/**
* Renders nothing unless a repo or linked server has an active session, then shows the braille
* spinner in the state colour (info while running, warning when a session needs input).
*/
export function ActivityStateIndicator({
state,
className,
}: {
state: 'needs-input' | 'running' | null
className?: string
}) {
if (state === null) return null
return (
<span
role="img"
aria-label={state === 'needs-input' ? 'Session needs input' : 'Sessions running'}
className={cn(
'inline-flex shrink-0 items-center',
state === 'needs-input' ? 'text-warning' : 'text-info',
className,
)}
>
<ActivitySpinner />
</span>
)
}
@@ -1,23 +1,12 @@
import { ActivitySpinner } from '@/components/ui/activity-spinner'
import { ActivityStateIndicator } from '@/components/activity/ActivityStateIndicator'
import { useRepoActivityState } from '@/hooks/useActiveWork'
import { cn } from '@/lib/utils'
import type { Repo } from '@/api/types'
/**
* Renders nothing unless a session in the repo is active, then shows the braille spinner in the
* state colour (info while running, warning when a session needs input).
* Shows the repo's activity spinner while a session in it needs input or is running.
*/
export function RepoActivityIndicator({ repo, className }: { repo: Repo; className?: string }) {
const state = useRepoActivityState(repo)
if (state === null) return null
return (
<span
role="img"
aria-label={state === 'needs-input' ? 'Session needs input' : 'Sessions running'}
className={cn('inline-flex shrink-0 items-center', state === 'needs-input' ? 'text-warning' : 'text-info', className)}
>
<ActivitySpinner />
</span>
)
return <ActivityStateIndicator state={state} className={className} />
}
@@ -28,6 +28,19 @@ interface FileDiffViewProps {
isMobile?: boolean;
}
export interface FileDiffContentProps {
filePath: string;
diff: string | null;
status: GitFileStatusType;
additions: number;
deletions: number;
isBinary?: boolean;
onBack?: () => void;
onClose?: () => void;
onOpenFile?: (path: string, lineNumber?: number) => void;
isMobile?: boolean;
}
const statusConfig: Record<
GitFileStatusType,
{ icon: typeof FileText; color: string; bgColor: string; label: string }
@@ -70,54 +83,24 @@ const statusConfig: Record<
},
};
export function FileDiffView({
repoId,
export function FileDiffContent({
filePath,
includeStaged,
commitHash,
diff,
status,
additions,
deletions,
isBinary = false,
onBack,
onClose,
onOpenFile,
isMobile = false,
}: FileDiffViewProps) {
const workingDiff = useFileDiff(repoId, filePath, includeStaged);
const commitDiff = useCommitFileDiff(repoId, commitHash, filePath);
const { data: diffData, isLoading, error } = commitHash ? commitDiff : workingDiff;
}: FileDiffContentProps) {
const fileName = filePath.split("/").pop() || filePath;
const dirPath = filePath.includes("/")
? filePath.substring(0, filePath.lastIndexOf("/"))
: "";
if (isLoading) {
return (
<div className="flex items-center justify-center h-full py-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
);
}
if (error) {
return (
<div className="flex flex-col items-center justify-center h-full py-8 text-muted-foreground">
<FileText className="w-8 h-8 mb-2 opacity-50" />
<p className="text-sm">Failed to load diff</p>
<p className="text-xs mt-1">{error.message}</p>
{onBack && (
<Button variant="ghost" size="sm" onClick={onBack} className="mt-4">
<ArrowLeft className="w-4 h-4 mr-2" />
Back
</Button>
)}
</div>
);
}
if (!diffData) {
return null;
}
const config = statusConfig[diffData.status];
const config = statusConfig[status];
const Icon = config.icon;
return (
@@ -178,15 +161,15 @@ export function FileDiffView({
>
{config.label}
</span>
{!diffData.isBinary && (
{!isBinary && (
<>
<span className="text-diff-add">+{diffData.additions}</span>
<span className="text-diff-delete">-{diffData.deletions}</span>
<span className="text-diff-add">+{additions}</span>
<span className="text-diff-delete">-{deletions}</span>
</>
)}
{diffData.diff && (
{diff && (
<CopyButton
content={diffData.diff || ""}
content={diff}
title="Copy diff"
iconSize="sm"
variant="ghost"
@@ -207,18 +190,18 @@ export function FileDiffView({
</div>
<div className="flex-1 overflow-y-auto overflow-x-hidden min-h-0">
{diffData.isBinary ? (
{isBinary ? (
<div className="flex items-center justify-center h-full text-muted-foreground bg-muted/20">
<p className="text-sm">Binary file - cannot display diff</p>
</div>
) : !diffData.diff ? (
) : !diff ? (
<div className="flex items-center justify-center h-full text-muted-foreground bg-muted/20">
<p className="text-sm">No changes to display</p>
</div>
) : (
<div className="border-t border-border/30">
<DiffLines
diff={diffData.diff}
diff={diff}
showLineNumbers={!isMobile}
onLineClick={
onOpenFile
@@ -232,3 +215,61 @@ export function FileDiffView({
</div>
);
}
export function FileDiffView({
repoId,
filePath,
includeStaged,
commitHash,
onBack,
onClose,
onOpenFile,
isMobile = false,
}: FileDiffViewProps) {
const workingDiff = useFileDiff(repoId, filePath, includeStaged);
const commitDiff = useCommitFileDiff(repoId, commitHash, filePath);
const { data: diffData, isLoading, error } = commitHash ? commitDiff : workingDiff;
if (isLoading) {
return (
<div className="flex items-center justify-center h-full py-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
);
}
if (error) {
return (
<div className="flex flex-col items-center justify-center h-full py-8 text-muted-foreground">
<FileText className="w-8 h-8 mb-2 opacity-50" />
<p className="text-sm">Failed to load diff</p>
<p className="text-xs mt-1">{error.message}</p>
{onBack && (
<Button variant="ghost" size="sm" onClick={onBack} className="mt-4">
<ArrowLeft className="w-4 h-4 mr-2" />
Back
</Button>
)}
</div>
);
}
if (!diffData) {
return null;
}
return (
<FileDiffContent
filePath={filePath}
diff={diffData.diff}
status={diffData.status}
additions={diffData.additions}
deletions={diffData.deletions}
isBinary={diffData.isBinary}
onBack={onBack}
onClose={onClose}
onOpenFile={onOpenFile}
isMobile={isMobile}
/>
);
}
@@ -6,6 +6,7 @@ import { LinkedServersNav } from './LinkedServersNav'
const mocks = vi.hoisted(() => ({
useOpenCodeServers: vi.fn(),
useOpenCodeServerStatuses: vi.fn(),
useServerActivityState: vi.fn(),
}))
vi.mock('@/hooks/useOpenCodeServers', () => ({
@@ -13,6 +14,10 @@ vi.mock('@/hooks/useOpenCodeServers', () => ({
useOpenCodeServerStatuses: mocks.useOpenCodeServerStatuses,
}))
vi.mock('@/hooks/useActiveWork', () => ({
useServerActivityState: mocks.useServerActivityState,
}))
const kitchen = {
id: 'srv_kitchen',
name: 'Kitchen',
@@ -46,6 +51,7 @@ describe('LinkedServersNav', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useOpenCodeServers.mockReturnValue({ servers: [], isLoading: false })
mocks.useServerActivityState.mockReturnValue(null)
mocks.useOpenCodeServerStatuses.mockReturnValue({
statuses: [],
statusById: { srv_kitchen: { serverId: 'srv_kitchen', connected: true, version: null, error: null } },
@@ -117,4 +123,32 @@ describe('LinkedServersNav', () => {
expect(onNavigate).toHaveBeenCalledWith('/servers/srv_kitchen')
})
it('shows the activity indicator only for the server with an active session', () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen, office], isLoading: false })
mocks.useServerActivityState.mockImplementation((serverId: string) =>
serverId === 'srv_kitchen' ? 'needs-input' : null,
)
renderNav()
expect(mocks.useServerActivityState).toHaveBeenCalledWith('srv_kitchen')
expect(mocks.useServerActivityState).toHaveBeenCalledWith('srv_office')
expect(screen.getByRole('img', { name: 'Session needs input' })).toBeInTheDocument()
expect(screen.queryByRole('img', { name: 'Sessions running' })).not.toBeInTheDocument()
expect(screen.getByRole('img', { name: 'Connected' })).toBeInTheDocument()
})
it('shows the running indicator in the sheet variant', () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
mocks.useServerActivityState.mockReturnValue('running')
render(
<MemoryRouter>
<LinkedServersNav variant="sheet" />
</MemoryRouter>,
)
expect(screen.getByRole('img', { name: 'Sessions running' })).toBeInTheDocument()
})
})
@@ -1,6 +1,9 @@
import { Link, useLocation } from 'react-router-dom'
import { Server } from 'lucide-react'
import type { OpenCodeServer } from '@opencode-manager/shared/schemas'
import { useOpenCodeServers, useOpenCodeServerStatuses } from '@/hooks/useOpenCodeServers'
import { useServerActivityState } from '@/hooks/useActiveWork'
import { ActivityStateIndicator } from '@/components/activity/ActivityStateIndicator'
import { SidebarSection } from '@/components/ui/sidebar'
import { getServerPath } from '@/lib/navigation'
import { cn } from '@/lib/utils'
@@ -31,6 +34,52 @@ function ServerConnectionDot({ connected }: { connected: boolean }) {
)
}
interface LinkedServerRowProps {
server: OpenCodeServer
variant: 'sidebar' | 'sheet'
path: string
active: boolean
connected: boolean
onNavigate?: (path: string) => void
}
function LinkedServerRow({ server, variant, path, active, connected, onNavigate }: LinkedServerRowProps) {
const activity = useServerActivityState(server.id)
const className = cn(
'flex items-center gap-3 rounded-md p-2.5 text-sm transition-colors duration-150',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
active ? 'bg-accent text-accent-foreground' : 'text-foreground hover:bg-accent/50',
variant === 'sheet' && 'mx-2 p-2 text-left',
)
const content = (
<>
<Server className="h-5 w-5 shrink-0" />
<span className="min-w-0 flex-1 truncate">{server.name}</span>
<ActivityStateIndicator state={activity} />
<ServerConnectionDot connected={connected} />
</>
)
if (onNavigate) {
return (
<button
type="button"
onClick={() => onNavigate(path)}
aria-current={active ? 'page' : undefined}
className={className}
>
{content}
</button>
)
}
return (
<Link to={path} className={className}>
{content}
</Link>
)
}
export function LinkedServersNav({ variant = 'sidebar', onNavigate }: LinkedServersNavProps) {
const location = useLocation()
const { servers, isLoading } = useOpenCodeServers()
@@ -71,40 +120,17 @@ export function LinkedServersNav({ variant = 'sidebar', onNavigate }: LinkedServ
const rows = enabledServers.map((server) => {
const path = getServerPath(server.id)
const active = isActiveServerPath(location.pathname, path)
const connected = statusById[server.id]?.connected ?? false
const className = cn(
'flex items-center gap-3 rounded-md p-2.5 text-sm transition-colors duration-150',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
active ? 'bg-accent text-accent-foreground' : 'text-foreground hover:bg-accent/50',
variant === 'sheet' && 'mx-2 p-2 text-left',
)
const content = (
<>
<Server className="h-5 w-5 shrink-0" />
<span className="min-w-0 flex-1 truncate">{server.name}</span>
<ServerConnectionDot connected={connected} />
</>
)
if (onNavigate) {
return (
<button
key={server.id}
type="button"
onClick={() => onNavigate(path)}
aria-current={active ? 'page' : undefined}
className={className}
>
{content}
</button>
)
}
return (
<Link key={server.id} to={path} className={className}>
{content}
</Link>
<LinkedServerRow
key={server.id}
server={server}
variant={variant}
path={path}
active={isActiveServerPath(location.pathname, path)}
connected={statusById[server.id]?.connected ?? false}
onNavigate={onNavigate}
/>
)
})
@@ -416,14 +416,14 @@ describe('MoreDrawer', () => {
expect(screen.getByText('Settings')).toBeInTheDocument()
expect(screen.getByText('Logout')).toBeInTheDocument()
expect(screen.getByText('Terminal')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Activity' })).toBeInTheDocument()
expect(screen.getByText('Repos')).toBeInTheDocument()
expect(screen.queryByText('Files')).not.toBeInTheDocument()
expect(screen.queryByText('Source Control')).not.toBeInTheDocument()
expect(screen.getByText('Source Control')).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', () => {
@@ -14,7 +14,7 @@ import { useMarkAllScheduleRunsViewed, useUnreadScheduleRuns } from '@/hooks/use
import { buildMoreItems, buildNavModel, isManagerOnlyNavItem, isSessionDetailPath, type MoreDrawerItem } from './moreDrawerItems'
import { useSwipeBack } from '@/hooks/useMobile'
import { cn, getRepoDisplayName } from '@/lib/utils'
import { getPathWithReturnTo, isAssistantPath } from '@/lib/navigation'
import { getPathWithReturnTo, isAssistantPath, parseServerSessionRoute } from '@/lib/navigation'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { isLocalOpenCodeServer, useRouteOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
@@ -77,6 +77,7 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const { logout } = useAuth()
const { data: health } = useServerHealth()
const isSessionDetail = isSessionDetailPath(location.pathname)
const isRemoteSessionDetail = parseServerSessionRoute(location.pathname) !== null
const isAssistantRoute = isAssistantPath(location.pathname)
const isAssistantSession = isSessionDetail && searchParams.get('assistant') === '1'
const isRemoteRoute = !isLocalOpenCodeServer(useRouteOpenCodeServerId())
@@ -205,11 +206,11 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
/>
</div>
)}
{isOpen && !isRemoteRoute && (
{isOpen && (
<CompactActivityList onNavigate={(path) => navigate(path)} />
)}
<MenuSection>
{isSessionDetail && !isRemoteRoute && (
{(isSessionDetail || isRemoteSessionDetail) && (
<MenuRow icon={FolderGit2} label="Repos" onClick={() => openMobileSheet('repos')} trailing />
)}
{assistantCta?.to && (
@@ -52,6 +52,7 @@ vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActivityWindowMinutes: activityMocks.useActivityWindowMinutes,
useRepoActivityState: () => null,
useServerActivityState: () => null,
}))
vi.mock('@/api/repos')
@@ -27,6 +27,11 @@ vi.mock('@/components/file-browser/FileBrowser', () => ({
vi.mock('@/components/source-control', () => ({
SourceControlContent: () => <div>source-control-tool</div>,
}))
vi.mock('@/components/source-control/RemoteSourceControlContent', () => ({
RemoteSourceControlContent: ({ serverId, directory }: { serverId: string; directory: string }) => (
<div>remote-source-control-tool {serverId} {directory}</div>
),
}))
vi.mock('@/components/terminal/TerminalPanel', () => ({
TerminalWorkspace: () => <div>terminal-tool</div>,
}))
@@ -360,12 +365,43 @@ describe('ToolSidePanel', () => {
within(rail)
.getAllByRole('button')
.map((button) => button.getAttribute('aria-label') ?? button.textContent?.trim()),
).toEqual(['Activity', 'MCP', 'Skills', 'Terminal'])
).toEqual(['Activity', 'MCP', 'Skills', 'Source Control', 'Terminal'])
await user.click(screen.getByRole('button', { name: 'MCP' }))
expect(await screen.findByText('mcp-tool')).toBeInTheDocument()
})
it('opens the remote source control panel for a linked-server session', async () => {
const user = userEvent.setup()
render(
<MemoryRouter initialEntries={['/servers/srv_kitchen/sessions/ses_remote']}>
<RemoteHarness />
</MemoryRouter>,
)
await user.click(screen.getByRole('button', { name: 'Source Control' }))
expect(
await screen.findByText('remote-source-control-tool srv_kitchen /home/me/app'),
).toBeInTheDocument()
expect(search().get('panel')).toBe('sourceControl')
expect(screen.queryByText('source-control-tool')).not.toBeInTheDocument()
})
it('opens the skills panel for a linked-server session', async () => {
const user = userEvent.setup()
render(
<MemoryRouter initialEntries={['/servers/srv_kitchen/sessions/ses_remote']}>
<RemoteHarness />
</MemoryRouter>,
)
await user.click(screen.getByRole('button', { name: 'Skills' }))
expect(await screen.findByText('skills-tool')).toBeInTheDocument()
expect(search().get('panel')).toBe('skills')
})
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')])
@@ -4,6 +4,7 @@ import { X } from 'lucide-react'
import { useLocation, useNavigate } from 'react-router-dom'
import { FileBrowser } from '@/components/file-browser/FileBrowser'
import { SourceControlContent } from '@/components/source-control'
import { RemoteSourceControlContent } from '@/components/source-control/RemoteSourceControlContent'
import { TerminalWorkspace } from '@/components/terminal/TerminalPanel'
import {
ChangesWalkthroughCancel,
@@ -38,7 +39,7 @@ const PANEL_WIDTH_CLASSES: Partial<Record<PanelTool, string>> = {
activity: 'w-80',
}
const REMOTE_TOOL_KEYS: ReadonlySet<string> = new Set(['activity', 'mcp', 'skills', 'terminal'])
const REMOTE_TOOL_KEYS: ReadonlySet<string> = new Set(['activity', 'mcp', 'skills', 'source-control', 'terminal'])
function ActivityWindowLabel() {
const minutes = useActivityWindowMinutes()
@@ -163,7 +164,8 @@ export function ToolSidePanel({
const { activeTool, toggleTool, closePanel } = panel
const location = useLocation()
const openNavItem = useOpenNavItem()
const isRemoteRoute = !isLocalOpenCodeServer(useRouteOpenCodeServerId())
const routeServerId = useRouteOpenCodeServerId()
const isRemoteRoute = !isLocalOpenCodeServer(routeServerId)
const railRef = useRef<HTMLElement>(null)
const previousActiveToolRef = useRef(activeTool)
@@ -212,25 +214,34 @@ export function ToolSidePanel({
? <TerminalWorkspace target={terminalWorkspaceTarget} directory={terminalDirectory ?? directory} isOpen />
: null
}
if (tool === 'skills') {
return sessionId ? (
<RepoSkillsContent
open
repoId={repoId}
sessionId={sessionId}
directory={repoDirectory}
onSkillLoaded={onSkillLoaded}
onDone={closePanel}
/>
) : (
<RepoSkillsContent open repoId={repoId} onDone={closePanel} />
)
}
if (tool === 'sourceControl') {
if (isRemoteRoute) {
return repoDirectory
? <RemoteSourceControlContent serverId={routeServerId} directory={repoDirectory} compact />
: null
}
return repoId === undefined
? null
: <SourceControlContent repoId={repoId} isOpen currentBranch={currentBranch} compact />
}
if (repoId === undefined) return null
switch (tool) {
case 'sourceControl':
return <SourceControlContent repoId={repoId} isOpen currentBranch={currentBranch} compact />
case 'actions':
return <RepoActionsContent repoId={repoId} directory={directory} open />
case 'skills':
return sessionId ? (
<RepoSkillsContent
open
repoId={repoId}
sessionId={sessionId}
directory={repoDirectory}
onSkillLoaded={onSkillLoaded}
onDone={closePanel}
/>
) : (
<RepoSkillsContent open repoId={repoId} onDone={closePanel} />
)
case 'schedules':
return <RepoSchedulesContent repoId={repoId} embedded />
}
@@ -64,7 +64,15 @@ describe('buildMoreItems', () => {
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'])
expect(items.map((item) => item.key)).toEqual([
'home',
'mcp',
'skills',
'source-control',
'terminal',
'settings',
'logout',
])
})
it('omits the Actions item for an Assistant session', () => {
@@ -174,6 +182,7 @@ describe('buildToolItems', () => {
'activity',
'mcp',
'skills',
'source-control',
'terminal',
])
})
@@ -58,7 +58,6 @@ const NON_TOOL_ITEM_KEYS = new Set(['home', 'settings', 'logout'])
const MANAGER_ONLY_ITEM_KEYS: ReadonlySet<string> = new Set([
'files',
'source-control',
'preview',
'walkthrough',
'actions',
@@ -92,6 +91,7 @@ function buildRouteNavModel(pathname: string): NavModel {
items: [
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
...baseItems,
],
@@ -38,7 +38,7 @@ type RepoSkillsDialogProps = {
type RepoSkillsContentProps = {
open: boolean
repoId: number
repoId?: number
onDone: () => void
} & RepoSkillsSessionProps
@@ -0,0 +1,114 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RemoteSourceControlContent } from './RemoteSourceControlContent'
const mocks = vi.hoisted(() => ({
getVcsInfo: vi.fn(),
listVcsStatus: vi.fn(),
getVcsDiff: vi.fn(),
}))
vi.mock('@/api/opencode', () => ({
getVcsInfo: mocks.getVcsInfo,
listVcsStatus: mocks.listVcsStatus,
getVcsDiff: mocks.getVcsDiff,
}))
const WORKING_FILES = [
{ file: 'src/app.ts', additions: 3, deletions: 1, status: 'modified' as const },
{ file: 'src/new.ts', additions: 5, deletions: 0, status: 'added' as const },
]
const WORKING_DIFF = [
{
file: 'src/app.ts',
patch: '@@ -1,2 +1,2 @@\n-old line\n+new line',
additions: 1,
deletions: 1,
status: 'modified' as const,
},
]
const BRANCH_DIFF = [
{
file: 'src/branch-only.ts',
patch: '@@ -1,1 +1,2 @@\n branch file\n+extra branch line',
additions: 1,
deletions: 0,
status: 'added' as const,
},
]
function renderContent() {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
return render(
<QueryClientProvider client={queryClient}>
<RemoteSourceControlContent serverId="srv_kitchen" directory="/home/me/app" />
</QueryClientProvider>,
)
}
describe('RemoteSourceControlContent', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.getVcsInfo.mockResolvedValue({
provider: 'github',
branch: { current: 'feature/remote', default: 'main' },
})
mocks.listVcsStatus.mockResolvedValue(WORKING_FILES)
mocks.getVcsDiff.mockImplementation((_directory: string, mode: string) =>
Promise.resolve(mode === 'branch' ? BRANCH_DIFF : WORKING_DIFF),
)
})
it('lists the working-copy changes with the current branch', async () => {
renderContent()
expect(await screen.findByText('app.ts')).toBeInTheDocument()
expect(screen.getByText('new.ts')).toBeInTheDocument()
expect(screen.getByText('feature/remote')).toBeInTheDocument()
expect(mocks.listVcsStatus).toHaveBeenCalledWith('/home/me/app', 'srv_kitchen')
})
it('switches to branch changes and lists the diff files', async () => {
const user = userEvent.setup()
renderContent()
await user.click(await screen.findByRole('button', { name: 'Branch changes' }))
expect(await screen.findByText('branch-only.ts')).toBeInTheDocument()
expect(screen.queryByText('new.ts')).not.toBeInTheDocument()
expect(mocks.getVcsDiff).toHaveBeenCalledWith('/home/me/app', 'branch', 'srv_kitchen')
})
it('shows the patch after selecting a changed file', async () => {
const user = userEvent.setup()
renderContent()
await user.click(await screen.findByText('app.ts'))
expect(await screen.findByText('new line')).toBeInTheDocument()
expect(mocks.getVcsDiff).toHaveBeenCalledWith('/home/me/app', 'working', 'srv_kitchen')
await user.click(screen.getByRole('button', { name: 'Back to changed files' }))
expect(await screen.findByText('new.ts')).toBeInTheDocument()
})
it('shows an empty state when the working copy has no changes', async () => {
mocks.listVcsStatus.mockResolvedValue([])
renderContent()
expect(await screen.findByText('No working changes')).toBeInTheDocument()
})
it('reports a failed status load', async () => {
mocks.listVcsStatus.mockRejectedValue(new Error('vcs unavailable'))
renderContent()
expect(await screen.findByText('Failed to load changes')).toBeInTheDocument()
expect(screen.getByText('vcs unavailable')).toBeInTheDocument()
})
})
@@ -0,0 +1,258 @@
import { useMemo, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { ArrowLeft, FileText, GitBranch, Loader2, RefreshCw } from 'lucide-react'
import {
getVcsDiff,
getVcsInfo,
listVcsStatus,
type VcsFileDiff,
type VcsFileStatus,
} from '@/api/opencode'
import { FileDiffContent } from '@/components/file-browser/FileDiffView'
import { GitFlatFileList } from './GitFlatFileList'
import { SourceControlDialog } from './SourceControlPanel'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { serverScopedKey } from '@/lib/serverScope'
import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen'
import { useMobile } from '@/hooks/useMobile'
import { GIT_UI_COLORS } from '@/lib/git-status-styles'
import type { GitFileStatus } from '@/types/git'
type VcsMode = 'working' | 'branch'
const MODES: ReadonlyArray<{ id: VcsMode; label: string }> = [
{ id: 'working', label: 'Working changes' },
{ id: 'branch', label: 'Branch changes' },
]
interface RemoteSourceControlContentProps {
serverId: string
directory: string
compact?: boolean
}
function toGitFileStatus(entry: VcsFileStatus | VcsFileDiff): GitFileStatus {
return {
path: entry.file,
status: entry.status,
staged: false,
additions: entry.additions,
deletions: entry.deletions,
}
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : 'Failed to load source control'
}
export function RemoteSourceControlContent({
serverId,
directory,
compact = false,
}: RemoteSourceControlContentProps) {
const queryClient = useQueryClient()
const [mode, setMode] = useState<VcsMode>('working')
const [selectedFile, setSelectedFile] = useState<string | undefined>()
const vcsKey = useMemo(
() => serverScopedKey(['opencode', 'vcs', directory], serverId),
[directory, serverId],
)
const infoQuery = useQuery({
queryKey: [...vcsKey, 'info'],
queryFn: () => getVcsInfo(directory, serverId),
retry: false,
})
const statusQuery = useQuery({
queryKey: [...vcsKey, 'status'],
queryFn: () => listVcsStatus(directory, serverId),
enabled: mode === 'working',
retry: false,
})
const diffQuery = useQuery({
queryKey: [...vcsKey, 'diff', mode],
queryFn: () => getVcsDiff(directory, mode, serverId),
enabled: mode === 'branch' || selectedFile !== undefined,
retry: false,
})
const listQuery = mode === 'working' ? statusQuery : diffQuery
const files = useMemo(
() =>
mode === 'working'
? (statusQuery.data ?? []).map(toGitFileStatus)
: (diffQuery.data ?? []).map(toGitFileStatus),
[mode, statusQuery.data, diffQuery.data],
)
const selectedDiff =
selectedFile === undefined
? undefined
: diffQuery.data?.find((entry) => entry.file === selectedFile)
const refresh = () => {
void queryClient.invalidateQueries({ queryKey: vcsKey, refetchType: 'none' })
void infoQuery.refetch({ cancelRefetch: false })
void (mode === 'working' ? statusQuery : diffQuery).refetch({ cancelRefetch: false })
if (mode === 'working' && selectedFile !== undefined) {
void diffQuery.refetch({ cancelRefetch: false })
}
}
useRefreshOnOpen(true, refresh)
const branch = infoQuery.data?.branch.current ?? infoQuery.data?.branch.default ?? 'unknown'
const isRefreshing = infoQuery.isFetching || listQuery.isFetching || diffQuery.isFetching
const selectMode = (next: VcsMode) => {
if (next === mode) return
setSelectedFile(undefined)
setMode(next)
}
if (selectedFile !== undefined) {
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex shrink-0 items-center gap-2 border-b border-border px-3 py-2">
<Button
variant="ghost"
size="sm"
onClick={() => setSelectedFile(undefined)}
className="h-7 w-7 p-0"
aria-label="Back to changed files"
>
<ArrowLeft className="h-4 w-4" />
</Button>
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
{selectedFile}
</span>
</div>
<div className="min-h-0 flex-1">
{diffQuery.isLoading ? (
<div className="flex h-full items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : diffQuery.error ? (
<div className="flex flex-col items-center justify-center h-full py-8 text-muted-foreground">
<FileText className="mb-2 h-8 w-8 opacity-50" />
<p className="text-sm">Failed to load diff</p>
<p className="text-xs mt-1">{errorMessage(diffQuery.error)}</p>
</div>
) : (
<FileDiffContent
filePath={selectedFile}
diff={selectedDiff?.patch ?? null}
status={selectedDiff?.status ?? 'modified'}
additions={selectedDiff?.additions ?? 0}
deletions={selectedDiff?.deletions ?? 0}
onBack={() => setSelectedFile(undefined)}
isMobile={compact}
/>
)}
</div>
</div>
)
}
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex shrink-0 items-center justify-between gap-2 border-b border-border px-3 py-2">
<div className="flex min-w-0 items-center gap-2">
<GitBranch className={cn('h-4 w-4 shrink-0', GIT_UI_COLORS.current)} />
<span className={cn('truncate text-sm font-medium', GIT_UI_COLORS.current)}>{branch}</span>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={refresh}
disabled={isRefreshing}
className="h-7 w-7 p-0"
aria-label="Refresh source control"
title="Refresh"
>
<RefreshCw className={cn('h-4 w-4', isRefreshing && 'animate-spin')} />
</Button>
</div>
</div>
<div className="flex shrink-0 border-b border-border">
{MODES.map((entry) => (
<button
key={entry.id}
type="button"
onClick={() => selectMode(entry.id)}
aria-pressed={mode === entry.id}
className={cn(
'flex-1 whitespace-nowrap px-3 py-2 text-sm transition-colors border-b-2 -mb-px',
mode === entry.id
? 'border-primary text-foreground'
: 'border-transparent text-muted-foreground hover:bg-accent hover:text-foreground',
)}
>
{entry.label}
</button>
))}
</div>
<div className="min-h-0 flex-1 overflow-y-auto">
{listQuery.isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : listQuery.error ? (
<div className="flex flex-col items-center justify-center gap-3 px-4 py-8 text-center text-muted-foreground">
<FileText className="h-8 w-8 opacity-50" />
<div>
<p className="text-sm">Failed to load changes</p>
<p className="text-xs mt-1">{errorMessage(listQuery.error)}</p>
</div>
<Button variant="outline" size="sm" onClick={refresh}>
<RefreshCw className="mr-1 h-4 w-4" />
Retry
</Button>
</div>
) : files.length === 0 ? (
<div className="flex flex-col items-center justify-center px-4 py-8 text-center text-muted-foreground">
<p className="text-sm">
{mode === 'working' ? 'No working changes' : 'No branch changes'}
</p>
</div>
) : (
<GitFlatFileList
files={files}
staged={false}
onSelect={(path) => setSelectedFile(path)}
readOnly
/>
)}
</div>
</div>
)
}
interface RemoteSourceControlPanelProps {
serverId: string
directory: string
isOpen: boolean
onClose: () => void
}
export function RemoteSourceControlPanel({
serverId,
directory,
isOpen,
onClose,
}: RemoteSourceControlPanelProps) {
const isMobile = useMobile()
return (
<SourceControlDialog isOpen={isOpen} onClose={onClose} title="Source Control">
<RemoteSourceControlContent serverId={serverId} directory={directory} compact={isMobile} />
</SourceControlDialog>
)
}
@@ -1,4 +1,5 @@
import { useState } from 'react'
import type { ReactNode } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { FetchError } from '@opencode-manager/shared'
import { useGitStatus, getApiErrorMessage } from '@/api/git'
@@ -287,6 +288,32 @@ export function SourceControlPanel({
}: SourceControlPanelProps) {
const isMobile = useMobile()
return (
<SourceControlDialog
isOpen={isOpen}
onClose={onClose}
title={isMobile && repoName ? repoName : 'Source Control'}
>
<SourceControlContent
repoId={repoId}
isOpen={isOpen}
currentBranch={currentBranch}
compact={isMobile}
/>
</SourceControlDialog>
)
}
interface SourceControlDialogProps {
isOpen: boolean
onClose: () => void
title: string
children: ReactNode
}
export function SourceControlDialog({ isOpen, onClose, title, children }: SourceControlDialogProps) {
const isMobile = useMobile()
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent
@@ -303,7 +330,7 @@ export function SourceControlPanel({
)}>
<DialogTitle className="flex items-center gap-2">
<GitBranch className="w-5 h-5" />
{isMobile && repoName ? repoName : 'Source Control'}
{title}
</DialogTitle>
{isMobile && (
<Button
@@ -317,12 +344,7 @@ export function SourceControlPanel({
)}
</DialogHeader>
<div className="flex-1 overflow-hidden pb-0">
<SourceControlContent
repoId={repoId}
isOpen={isOpen}
currentBranch={currentBranch}
compact={isMobile}
/>
{children}
</div>
</DialogContent>
</Dialog>
@@ -1,4 +1,5 @@
export { SourceControlPanel, SourceControlContent } from './SourceControlPanel'
export { RemoteSourceControlPanel } from './RemoteSourceControlContent'
export { ChangesTab } from './ChangesTab'
export { CommitsTab } from './CommitsTab'
export { BranchesTab } from './BranchesTab'