diff --git a/backend/src/services/sse-aggregator.ts b/backend/src/services/sse-aggregator.ts index 41b33d1d..298152da 100644 --- a/backend/src/services/sse-aggregator.ts +++ b/backend/src/services/sse-aggregator.ts @@ -520,12 +520,17 @@ class SSEAggregator { this.notifyServerEvent(LOCAL_OPENCODE_SERVER_ID, directory, event) } - private writeEnvelopeToClients(clientIds: Iterable, directory: string | null, payloadJson: string): void { + private writeEnvelopeToClients( + clientIds: Iterable, + directory: string | null, + payloadJson: string, + serverId?: string, + ): void { let frame: Uint8Array | null = null for (const clientId of clientIds) { const client = this.clients.get(clientId) if (!client) continue - frame ??= encodeSSEFrame('message', serializeEnvelope(directory, payloadJson)) + frame ??= encodeSSEFrame('message', serializeEnvelope(directory, payloadJson, serverId)) this.writeFrame(client, frame, 'Failed to send to client') } } @@ -543,16 +548,7 @@ class SSEAggregator { } deliverRemoteEnvelope(serverId: string, directory: string | null, payloadJson: string): void { - const clientIds = directory === null - ? this.clientIdsForServer(serverId) - : Array.from(this.directoryClients.get(buildServerDirectoryKey(serverId, directory)) ?? []) - if (clientIds.length === 0) return - const frame = encodeSSEFrame('message', serializeEnvelope(directory, payloadJson, serverId)) - for (const clientId of clientIds) { - const client = this.clients.get(clientId) - if (!client) continue - this.writeFrame(client, frame, 'Failed to send remote event to client') - } + this.writeEnvelopeToClients(this.clients.keys(), directory, payloadJson, serverId) } deliverRemoteEnvelopeToClient(clientId: string, serverId: string, directory: string, payloadJson: string): void { diff --git a/backend/test/services/remote-server-events.test.ts b/backend/test/services/remote-server-events.test.ts index 0fbb7803..67a27979 100644 --- a/backend/test/services/remote-server-events.test.ts +++ b/backend/test/services/remote-server-events.test.ts @@ -234,7 +234,7 @@ describe('RemoteServerEventHub event delivery', () => { expect(sources.sources[1]?.init).toBeUndefined() }) - it('delivers a located event only to clients subscribed to that server and directory, with a serverId envelope', () => { + it('broadcasts a located event to every client with a serverId envelope', () => { const remoteClient = createCapturingClient() const otherServerClient = createCapturingClient() const localClient = createCapturingClient() @@ -252,7 +252,7 @@ describe('RemoteServerEventHub event delivery', () => { source.message(remoteEvent('session.idle', { sessionID: 'ses_1' }, '/repo')) - expect(remoteClient.frames.map(parseFrame)).toEqual([{ + const envelope = { directory: '/repo', serverId: 'srv_a', payload: { @@ -262,9 +262,10 @@ describe('RemoteServerEventHub event delivery', () => { location: { directory: '/repo' }, data: { sessionID: 'ses_1' }, }, - }]) - expect(otherServerClient.frames).toHaveLength(0) - expect(localClient.frames).toHaveLength(0) + } + expect(remoteClient.frames.map(parseFrame)).toEqual([envelope]) + expect(otherServerClient.frames.map(parseFrame)).toEqual([envelope]) + expect(localClient.frames.map(parseFrame)).toEqual([envelope]) expect(listener).not.toHaveBeenCalled() expect(sseAggregator.getActiveSessions()).toEqual({}) }) @@ -321,7 +322,7 @@ describe('RemoteServerEventHub event delivery', () => { }]) }) - it('falls back to every client holding any key of the server when the directory is unknown', () => { + it('broadcasts to every client when the directory is unknown', () => { const subscribedA = createCapturingClient() const otherDirectoryA = createCapturingClient() const subscribedB = createCapturingClient() @@ -339,7 +340,7 @@ describe('RemoteServerEventHub event delivery', () => { } expect(subscribedA.frames.map(parseFrame)).toEqual([envelope]) expect(otherDirectoryA.frames.map(parseFrame)).toEqual([envelope]) - expect(subscribedB.frames).toHaveLength(0) + expect(subscribedB.frames.map(parseFrame)).toEqual([envelope]) }) it('keeps the raw upstream payload in the remote envelope and re-serializes multi-line payloads', () => { diff --git a/backend/test/services/sse-aggregator-remote.test.ts b/backend/test/services/sse-aggregator-remote.test.ts index 66cc60f5..5e9fbbb6 100644 --- a/backend/test/services/sse-aggregator-remote.test.ts +++ b/backend/test/services/sse-aggregator-remote.test.ts @@ -75,24 +75,29 @@ describe('SSEAggregator remote envelope delivery', () => { sseAggregator.setScheduledSessionsResolver(() => []) }) - it('delivers a remote envelope only to clients subscribed to that server and directory', () => { + it('broadcasts a located remote envelope to every connected client whatever they are subscribed to', () => { const subscribed = createCapturingClient() const otherDirectory = createCapturingClient() + const otherServer = createCapturingClient() const local = createCapturingClient() + const unsubscribed = createCapturingClient() sseAggregator.addClient('remote-key', subscribed.callback, subscribed.writeFrame, ['srv_a|/repo']) sseAggregator.addClient('other-dir', otherDirectory.callback, otherDirectory.writeFrame, ['srv_a|/other']) + sseAggregator.addClient('other-server', otherServer.callback, otherServer.writeFrame, ['srv_b|/repo']) sseAggregator.addClient('local-dir', local.callback, local.writeFrame, ['/repo']) + sseAggregator.addClient('no-directories', unsubscribed.callback, unsubscribed.writeFrame, []) sseAggregator.deliverRemoteEnvelope('srv_a', '/repo', PAYLOAD) - expect(subscribed.frames).toEqual([ - `event: message\ndata: {"directory":"/repo","serverId":"srv_a","payload":${PAYLOAD}}\n\n`, - ]) - expect(otherDirectory.frames).toHaveLength(0) - expect(local.frames).toHaveLength(0) + const expected = { directory: '/repo', serverId: 'srv_a', payload: JSON.parse(PAYLOAD) } + expect(subscribed.frames.map(parseFrame)).toEqual([expected]) + expect(otherDirectory.frames.map(parseFrame)).toEqual([expected]) + expect(otherServer.frames.map(parseFrame)).toEqual([expected]) + expect(local.frames.map(parseFrame)).toEqual([expected]) + expect(unsubscribed.frames.map(parseFrame)).toEqual([expected]) }) - it('broadcasts a directory-less remote envelope to every client holding any key of that server', () => { + it('broadcasts a directory-less remote envelope to every connected client', () => { const first = createCapturingClient() const second = createCapturingClient() const otherServer = createCapturingClient() @@ -107,8 +112,8 @@ describe('SSEAggregator remote envelope delivery', () => { const expected = { directory: null, serverId: 'srv_a', payload: JSON.parse(PAYLOAD) } expect(first.frames.map(parseFrame)).toEqual([expected]) expect(second.frames.map(parseFrame)).toEqual([expected]) - expect(otherServer.frames).toHaveLength(0) - expect(local.frames).toHaveLength(0) + expect(otherServer.frames.map(parseFrame)).toEqual([expected]) + expect(local.frames.map(parseFrame)).toEqual([expected]) }) it('skips a targeted remote envelope once the client unsubscribed', () => { diff --git a/frontend/src/App.permission-dialog.test.tsx b/frontend/src/App.permission-dialog.test.tsx index df89ba60..86a7edfa 100644 --- a/frontend/src/App.permission-dialog.test.tsx +++ b/frontend/src/App.permission-dialog.test.tsx @@ -1,11 +1,12 @@ -import { render, screen, fireEvent } from '@testing-library/react' +import { render, screen, fireEvent, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import type { PermissionRequest } from '@opencode-manager/shared/opencode' const mocks = vi.hoisted(() => ({ usePermissions: vi.fn(), getRepoIdForSession: vi.fn(), - useSession: vi.fn(), + sessionQueryOptions: vi.fn(), navigateToCurrent: vi.fn(), PermissionRequestDialog: vi.fn(), })) @@ -15,7 +16,7 @@ vi.mock('@/contexts/EventContext', () => ({ useEventContext: () => ({ getRepoIdForSession: mocks.getRepoIdForSession }), })) -vi.mock('@/hooks/useOpenCode', () => ({ useSession: mocks.useSession })) +vi.mock('@/hooks/useOpenCode', () => ({ sessionQueryOptions: mocks.sessionQueryOptions })) vi.mock('@/components/session/PermissionRequestDialog', () => ({ PermissionRequestDialog: mocks.PermissionRequestDialog, @@ -50,6 +51,7 @@ const localPermission: PendingPermission = { interface DialogProps { permission: PermissionRequest | null + sessionTitle?: string onOpenSession?: () => void } @@ -66,7 +68,12 @@ function renderWrapper(permission: PendingPermission) { currentIsFromDifferentSession: false, }) - render() + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + render( + + + , + ) return mocks.PermissionRequestDialog.mock.calls.at(-1)?.[0] as DialogProps } @@ -74,7 +81,11 @@ function renderWrapper(permission: PendingPermission) { describe('PermissionDialogWrapper', () => { beforeEach(() => { vi.clearAllMocks() - mocks.useSession.mockReturnValue({ data: undefined }) + mocks.sessionQueryOptions.mockImplementation((sessionID: string | undefined, directory?: string, serverId?: string) => ({ + queryKey: ['session', sessionID ?? null, directory ?? null, serverId ?? null], + queryFn: async () => ({ title: 'Kitchen deploy' }), + enabled: !!sessionID, + })) mocks.PermissionRequestDialog.mockReturnValue(
) }) @@ -86,7 +97,18 @@ describe('PermissionDialogWrapper', () => { expect(props.permission).toEqual(remotePermission) expect(props.onOpenSession).toBe(mocks.navigateToCurrent) expect(mocks.getRepoIdForSession).not.toHaveBeenCalled() - expect(mocks.useSession).toHaveBeenCalledWith(undefined, '/srv/app') + expect(mocks.sessionQueryOptions).toHaveBeenCalledWith('ses_remote', '/srv/app', 'srv_kitchen') + }) + + it('resolves the remote session title from the permission server', async () => { + mocks.getRepoIdForSession.mockReturnValue(null) + + renderWrapper(remotePermission) + + await waitFor(() => { + const latest = mocks.PermissionRequestDialog.mock.calls.at(-1)?.[0] as DialogProps + expect(latest.sessionTitle).toBe('Kitchen deploy') + }) }) it('offers the session for a local permission resolved through its Manager repo', () => { @@ -96,7 +118,7 @@ describe('PermissionDialogWrapper', () => { expect(props.onOpenSession).toBe(mocks.navigateToCurrent) expect(mocks.getRepoIdForSession).toHaveBeenCalledWith('ses_local') - expect(mocks.useSession).toHaveBeenCalledWith('ses_local', '/srv/app') + expect(mocks.sessionQueryOptions).toHaveBeenCalledWith('ses_local', '/srv/app', 'local') }) it('hides the session action for a local permission without a Manager repo', () => { diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f020528b..a6a71151 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,5 +1,5 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query' import { createBrowserRouter, RouterProvider, Outlet, useNavigate, useLocation, useParams, Navigate } from 'react-router-dom' import { useEffect, useRef, useCallback, type ReactNode } from 'react' import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas' @@ -40,7 +40,7 @@ import { useAuth } from '@/hooks/useAuth' import { useOpenCodeFailureToast } from '@/hooks/useOpenCodeFailureToast' import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions' import { useGlobalShortcutActions } from '@/hooks/useGlobalShortcutActions' -import { useSession } from '@/hooks/useOpenCode' +import { sessionQueryOptions } from '@/hooks/useOpenCode' import { RestartServerDialog } from '@/components/settings/RestartServerDialog' const queryClient = new QueryClient({ @@ -115,9 +115,12 @@ export function PermissionDialogWrapper() { } = usePermissions() const { getRepoIdForSession } = useEventContext() const isRemotePermission = currentPermission !== null && !isLocalOpenCodeServer(currentPermission.serverId) - const { data: session } = useSession( - isRemotePermission ? undefined : currentPermission?.sessionID, - currentDirectory ?? undefined, + const { data: session } = useQuery( + sessionQueryOptions( + currentPermission?.sessionID, + currentDirectory ?? undefined, + currentPermission?.serverId ?? LOCAL_OPENCODE_SERVER_ID, + ), ) const canOpenCurrentSession = currentPermission !== null diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 84a10121..e8ba22f2 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -37,6 +37,14 @@ export type OpenCodeLocationInfo = Awaited>[number] +export type VcsInfo = Awaited>['data'] + +export type VcsFileStatus = Awaited>['data'][number] + +export type VcsFileDiff = Awaited>['data'][number] + +export type VcsDiffMode = 'working' | 'branch' | 'committed' + export interface SessionPage { items: SessionInfo[] nextCursor?: string @@ -333,6 +341,28 @@ export async function listSkills(directory?: string, serverId?: string): Promise return data } +export async function getVcsInfo(directory: string, serverId?: string): Promise { + const { data } = await callOpenCode((api) => api.vcs.get(openCodeLocation(directory)), serverId) + return data +} + +export async function listVcsStatus(directory: string, serverId?: string): Promise { + const { data } = await callOpenCode((api) => api.vcs.status(openCodeLocation(directory)), serverId) + return data +} + +export async function getVcsDiff( + directory: string, + mode: VcsDiffMode, + serverId?: string, +): Promise { + const { data } = await callOpenCode( + (api) => api.vcs.diff({ ...openCodeLocation(directory), mode }), + serverId, + ) + return data +} + export async function listPendingPermissions( directory: string, serverId?: string, diff --git a/frontend/src/components/activity/ActivityStateIndicator.tsx b/frontend/src/components/activity/ActivityStateIndicator.tsx new file mode 100644 index 00000000..f235a5c8 --- /dev/null +++ b/frontend/src/components/activity/ActivityStateIndicator.tsx @@ -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 ( + + + + ) +} diff --git a/frontend/src/components/activity/RepoActivityIndicator.tsx b/frontend/src/components/activity/RepoActivityIndicator.tsx index e1de6906..e2fcae2a 100644 --- a/frontend/src/components/activity/RepoActivityIndicator.tsx +++ b/frontend/src/components/activity/RepoActivityIndicator.tsx @@ -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 ( - - - - ) + return } diff --git a/frontend/src/components/file-browser/FileDiffView.tsx b/frontend/src/components/file-browser/FileDiffView.tsx index c4193ba2..481b02cf 100644 --- a/frontend/src/components/file-browser/FileDiffView.tsx +++ b/frontend/src/components/file-browser/FileDiffView.tsx @@ -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 ( -
- -
- ); - } - - if (error) { - return ( -
- -

Failed to load diff

-

{error.message}

- {onBack && ( - - )} -
- ); - } - - 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} - {!diffData.isBinary && ( + {!isBinary && ( <> - +{diffData.additions} - -{diffData.deletions} + +{additions} + -{deletions} )} - {diffData.diff && ( + {diff && (
- {diffData.isBinary ? ( + {isBinary ? (

Binary file - cannot display diff

- ) : !diffData.diff ? ( + ) : !diff ? (

No changes to display

) : (
); } + +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 ( +
+ +
+ ); + } + + if (error) { + return ( +
+ +

Failed to load diff

+

{error.message}

+ {onBack && ( + + )} +
+ ); + } + + if (!diffData) { + return null; + } + + return ( + + ); +} diff --git a/frontend/src/components/navigation/LinkedServersNav.test.tsx b/frontend/src/components/navigation/LinkedServersNav.test.tsx index a206b8be..009e02f9 100644 --- a/frontend/src/components/navigation/LinkedServersNav.test.tsx +++ b/frontend/src/components/navigation/LinkedServersNav.test.tsx @@ -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( + + + , + ) + + expect(screen.getByRole('img', { name: 'Sessions running' })).toBeInTheDocument() + }) }) diff --git a/frontend/src/components/navigation/LinkedServersNav.tsx b/frontend/src/components/navigation/LinkedServersNav.tsx index 360b32ad..3e9e2d61 100644 --- a/frontend/src/components/navigation/LinkedServersNav.tsx +++ b/frontend/src/components/navigation/LinkedServersNav.tsx @@ -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.name} + + + + ) + + if (onNavigate) { + return ( + + ) + } + + return ( + + {content} + + ) +} + 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.name} - - - ) - - if (onNavigate) { - return ( - - ) - } return ( - - {content} - + ) }) diff --git a/frontend/src/components/navigation/MoreDrawer.test.tsx b/frontend/src/components/navigation/MoreDrawer.test.tsx index 86556dac..1f4032ab 100644 --- a/frontend/src/components/navigation/MoreDrawer.test.tsx +++ b/frontend/src/components/navigation/MoreDrawer.test.tsx @@ -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', () => { diff --git a/frontend/src/components/navigation/MoreDrawer.tsx b/frontend/src/components/navigation/MoreDrawer.tsx index 83582333..2499d122 100644 --- a/frontend/src/components/navigation/MoreDrawer.tsx +++ b/frontend/src/components/navigation/MoreDrawer.tsx @@ -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) { />
)} - {isOpen && !isRemoteRoute && ( + {isOpen && ( navigate(path)} /> )} - {isSessionDetail && !isRemoteRoute && ( + {(isSessionDetail || isRemoteSessionDetail) && ( openMobileSheet('repos')} trailing /> )} {assistantCta?.to && ( diff --git a/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx b/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx index 2bbf856c..86eb5b09 100644 --- a/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx +++ b/frontend/src/components/navigation/RepoQuickSwitchSheet.test.tsx @@ -52,6 +52,7 @@ vi.mock('@/hooks/useActiveWork', () => ({ useActiveWork: activityMocks.useActiveWork, useActivityWindowMinutes: activityMocks.useActivityWindowMinutes, useRepoActivityState: () => null, + useServerActivityState: () => null, })) vi.mock('@/api/repos') diff --git a/frontend/src/components/navigation/ToolSidePanel.test.tsx b/frontend/src/components/navigation/ToolSidePanel.test.tsx index eb4cd2a2..32ec9584 100644 --- a/frontend/src/components/navigation/ToolSidePanel.test.tsx +++ b/frontend/src/components/navigation/ToolSidePanel.test.tsx @@ -27,6 +27,11 @@ vi.mock('@/components/file-browser/FileBrowser', () => ({ vi.mock('@/components/source-control', () => ({ SourceControlContent: () =>
source-control-tool
, })) +vi.mock('@/components/source-control/RemoteSourceControlContent', () => ({ + RemoteSourceControlContent: ({ serverId, directory }: { serverId: string; directory: string }) => ( +
remote-source-control-tool {serverId} {directory}
+ ), +})) vi.mock('@/components/terminal/TerminalPanel', () => ({ TerminalWorkspace: () =>
terminal-tool
, })) @@ -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( + + + , + ) + + 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( + + + , + ) + + 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')]) diff --git a/frontend/src/components/navigation/ToolSidePanel.tsx b/frontend/src/components/navigation/ToolSidePanel.tsx index 97d28701..ac629b71 100644 --- a/frontend/src/components/navigation/ToolSidePanel.tsx +++ b/frontend/src/components/navigation/ToolSidePanel.tsx @@ -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> = { activity: 'w-80', } -const REMOTE_TOOL_KEYS: ReadonlySet = new Set(['activity', 'mcp', 'skills', 'terminal']) +const REMOTE_TOOL_KEYS: ReadonlySet = 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(null) const previousActiveToolRef = useRef(activeTool) @@ -212,25 +214,34 @@ export function ToolSidePanel({ ? : null } + if (tool === 'skills') { + return sessionId ? ( + + ) : ( + + ) + } + if (tool === 'sourceControl') { + if (isRemoteRoute) { + return repoDirectory + ? + : null + } + return repoId === undefined + ? null + : + } if (repoId === undefined) return null switch (tool) { - case 'sourceControl': - return case 'actions': return - case 'skills': - return sessionId ? ( - - ) : ( - - ) case 'schedules': return } diff --git a/frontend/src/components/navigation/moreDrawerItems.test.ts b/frontend/src/components/navigation/moreDrawerItems.test.ts index 41afe8f6..18a2b146 100644 --- a/frontend/src/components/navigation/moreDrawerItems.test.ts +++ b/frontend/src/components/navigation/moreDrawerItems.test.ts @@ -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', ]) }) diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts index 9280bdc6..8847f3f2 100644 --- a/frontend/src/components/navigation/moreDrawerItems.ts +++ b/frontend/src/components/navigation/moreDrawerItems.ts @@ -58,7 +58,6 @@ const NON_TOOL_ITEM_KEYS = new Set(['home', 'settings', 'logout']) const MANAGER_ONLY_ITEM_KEYS: ReadonlySet = 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, ], diff --git a/frontend/src/components/repo/RepoSkillsDialog.tsx b/frontend/src/components/repo/RepoSkillsDialog.tsx index 6307a8aa..38aef921 100644 --- a/frontend/src/components/repo/RepoSkillsDialog.tsx +++ b/frontend/src/components/repo/RepoSkillsDialog.tsx @@ -38,7 +38,7 @@ type RepoSkillsDialogProps = { type RepoSkillsContentProps = { open: boolean - repoId: number + repoId?: number onDone: () => void } & RepoSkillsSessionProps diff --git a/frontend/src/components/source-control/RemoteSourceControlContent.test.tsx b/frontend/src/components/source-control/RemoteSourceControlContent.test.tsx new file mode 100644 index 00000000..c742161a --- /dev/null +++ b/frontend/src/components/source-control/RemoteSourceControlContent.test.tsx @@ -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( + + + , + ) +} + +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() + }) +}) diff --git a/frontend/src/components/source-control/RemoteSourceControlContent.tsx b/frontend/src/components/source-control/RemoteSourceControlContent.tsx new file mode 100644 index 00000000..645fa10c --- /dev/null +++ b/frontend/src/components/source-control/RemoteSourceControlContent.tsx @@ -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('working') + const [selectedFile, setSelectedFile] = useState() + + 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 ( +
+
+ + + {selectedFile} + +
+
+ {diffQuery.isLoading ? ( +
+ +
+ ) : diffQuery.error ? ( +
+ +

Failed to load diff

+

{errorMessage(diffQuery.error)}

+
+ ) : ( + setSelectedFile(undefined)} + isMobile={compact} + /> + )} +
+
+ ) + } + + return ( +
+
+
+ + {branch} +
+
+ +
+
+ +
+ {MODES.map((entry) => ( + + ))} +
+ +
+ {listQuery.isLoading ? ( +
+ +
+ ) : listQuery.error ? ( +
+ +
+

Failed to load changes

+

{errorMessage(listQuery.error)}

+
+ +
+ ) : files.length === 0 ? ( +
+

+ {mode === 'working' ? 'No working changes' : 'No branch changes'} +

+
+ ) : ( + setSelectedFile(path)} + readOnly + /> + )} +
+
+ ) +} + +interface RemoteSourceControlPanelProps { + serverId: string + directory: string + isOpen: boolean + onClose: () => void +} + +export function RemoteSourceControlPanel({ + serverId, + directory, + isOpen, + onClose, +}: RemoteSourceControlPanelProps) { + const isMobile = useMobile() + + return ( + + + + ) +} diff --git a/frontend/src/components/source-control/SourceControlPanel.tsx b/frontend/src/components/source-control/SourceControlPanel.tsx index df27ce52..6871f594 100644 --- a/frontend/src/components/source-control/SourceControlPanel.tsx +++ b/frontend/src/components/source-control/SourceControlPanel.tsx @@ -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 ( + + + + ) +} + +interface SourceControlDialogProps { + isOpen: boolean + onClose: () => void + title: string + children: ReactNode +} + +export function SourceControlDialog({ isOpen, onClose, title, children }: SourceControlDialogProps) { + const isMobile = useMobile() + return ( !open && onClose()}> - {isMobile && repoName ? repoName : 'Source Control'} + {title} {isMobile && ( diff --git a/frontend/src/components/source-control/index.ts b/frontend/src/components/source-control/index.ts index 9611420a..78e99ee8 100644 --- a/frontend/src/components/source-control/index.ts +++ b/frontend/src/components/source-control/index.ts @@ -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' diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 390cad16..1f07ef46 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -817,6 +817,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { } case 'session.idle': { useSessionStatus.getState().setSessionServer(event.data.sessionID, serverId) + rememberSessionDirectory(event.data.sessionID, event.directory, serverId) useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' }) break } @@ -831,7 +832,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { useSessionStatus.getState().setSessionServer(event.data.sessionID, serverId) useSessionStatus.getState().setOutcome(event.data.sessionID, 'succeeded') useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' }) - invalidateSessionListCachesDebounced(queryClient, event.directory) + invalidateSessionListCachesDebounced(queryClient, event.directory, serverId) queryClient.invalidateQueries({ queryKey: changeWalkthroughQueryKey(event.data.sessionID) }) break } @@ -839,7 +840,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { useSessionStatus.getState().setSessionServer(event.data.sessionID, serverId) useSessionStatus.getState().setOutcome(event.data.sessionID, 'failed') useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' }) - invalidateSessionListCachesDebounced(queryClient, event.directory) + invalidateSessionListCachesDebounced(queryClient, event.directory, serverId) queryClient.invalidateQueries({ queryKey: changeWalkthroughQueryKey(event.data.sessionID) }) break } @@ -847,18 +848,18 @@ export function EventProvider({ children }: { children: React.ReactNode }) { useSessionStatus.getState().setSessionServer(event.data.sessionID, serverId) useSessionStatus.getState().setOutcome(event.data.sessionID, 'interrupted') useSessionStatus.getState().setStatus(event.data.sessionID, { type: 'idle' }) - invalidateSessionListCachesDebounced(queryClient, event.directory) + invalidateSessionListCachesDebounced(queryClient, event.directory, serverId) queryClient.invalidateQueries({ queryKey: changeWalkthroughQueryKey(event.data.sessionID) }) break } case 'session.deleted': { useSessionStatus.getState().forgetSession(event.data.sessionID) - invalidateSessionListCachesDebounced(queryClient, event.directory) + invalidateSessionListCachesDebounced(queryClient, event.directory, serverId) break } case 'session.created': { useSessionStatus.getState().setSessionServer(event.data.sessionID, serverId) - invalidateSessionListCachesDebounced(queryClient, event.directory) + invalidateSessionListCachesDebounced(queryClient, event.directory, serverId) if (typeof event.data.parentID === 'string') { useSessionStatus.getState().setSessionParent(event.data.sessionID, event.data.parentID) } @@ -868,7 +869,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { case 'session.renamed': case 'session.moved': case 'session.metadata.updated': - invalidateSessionListCachesDebounced(queryClient, event.directory) + invalidateSessionListCachesDebounced(queryClient, event.directory, serverId) break case 'shell.created': { const info = event.data.info @@ -923,6 +924,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { setSSHHostKeyRequest(event.properties) break case 'vcs.branch.updated': { + if (!isLocalOpenCodeServer(serverId)) break const repo = reposRef.current?.find((candidate) => repoMatchesDirectory(candidate, event.directory)) if (!repo) { queryClient.invalidateQueries({ queryKey: ['repo', 'siblings'] }) @@ -966,6 +968,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) { ) void reconcilePendingActionsForDirectories(directories) void syncRunningShells(directories) + invalidateSessionListCachesDebounced(queryClient, undefined, serverId) invalidateQueryKeysDebounced( queryClient, LOCATION_CATALOG_QUERY_KEYS.map((key) => serverScopedKey(key, serverId)), diff --git a/frontend/src/hooks/useActiveWork.test.tsx b/frontend/src/hooks/useActiveWork.test.tsx index 3337459b..1b933c92 100644 --- a/frontend/src/hooks/useActiveWork.test.tsx +++ b/frontend/src/hooks/useActiveWork.test.tsx @@ -13,6 +13,7 @@ const WINDOW_MS = 60 * MS_PER_MINUTE const mocks = vi.hoisted(() => ({ listSessionPage: vi.fn(), + listRemoteSessionPage: vi.fn(), getSession: vi.fn(), getRepoSiblings: vi.fn(), useNavigableRepos: vi.fn(), @@ -23,7 +24,10 @@ vi.mock('@/api/opencode', async (importOriginal) => { const actual = await importOriginal() return { ...actual, - listSessionPage: mocks.listSessionPage, + listSessionPage: (input: Parameters[0], serverId?: string) => + serverId === undefined || serverId === 'local' + ? mocks.listSessionPage(input, serverId) + : mocks.listRemoteSessionPage(input, serverId), getSession: mocks.getSession, } }) @@ -103,6 +107,8 @@ const recentIDs = (groups: { recent: Array<{ session: SessionInfo }> }): string[ describe('useActiveWork', () => { beforeEach(() => { mocks.listSessionPage.mockReset() + mocks.listRemoteSessionPage.mockReset() + mocks.listRemoteSessionPage.mockResolvedValue({ items: [] }) mocks.getSession.mockReset() mocks.getRepoSiblings.mockReset() mocks.getRepoSiblings.mockResolvedValue([]) @@ -308,6 +314,69 @@ describe('useActiveWork', () => { expect(row.path).toBe('/servers/srv_kitchen/sessions/ses_remote') }) + it('includes recent sessions from an enabled linked server with its server label and path', async () => { + const now = Date.now() + mocks.listSessionPage.mockResolvedValue({ items: [] }) + mocks.listRemoteSessionPage.mockResolvedValue({ + items: [session('ses_remote_recent', now - 500, null, '/home/me/app')], + }) + + const { result } = renderHook(() => useActiveWork(WINDOW_MS), { + wrapper: createWrapper(createQueryClient()), + }) + + await waitFor(() => expect(recentIDs(result.current.groups)).toContain('ses_remote_recent')) + + const row = result.current.groups.recent[0] + expect(row.serverId).toBe('srv_kitchen') + expect(row.serverName).toBe('Kitchen') + expect(row.repo).toBeNull() + expect(row.path).toBe('/servers/srv_kitchen/sessions/ses_remote_recent') + expect(mocks.listRemoteSessionPage).toHaveBeenCalledWith( + { limit: 50, order: 'desc', includeChildren: true }, + 'srv_kitchen', + ) + expect(result.current.isError).toBe(false) + }) + + it('rolls a listed remote child up to a root fetched from the same server', async () => { + const now = Date.now() + mocks.listSessionPage.mockResolvedValue({ items: [] }) + mocks.listRemoteSessionPage.mockResolvedValue({ + items: [session('ses_remote_child', now - 500, 'ses_remote_root', '/home/me/app')], + }) + mocks.getSession.mockImplementation(async (id: string, serverId?: string) => { + if (serverId !== 'srv_kitchen') throw new Error('local lookup for a remote session') + if (id === 'ses_remote_root') return session('ses_remote_root', now - 1500, null, '/home/me/app') + throw new Error(`unexpected session ${id}`) + }) + + const { result } = renderHook(() => useActiveWork(WINDOW_MS), { + wrapper: createWrapper(createQueryClient()), + }) + + await waitFor(() => expect(result.current.groups.recent.map((item) => item.session.id)).toEqual(['ses_remote_root'])) + + expect(result.current.groups.recent[0].serverId).toBe('srv_kitchen') + expect(mocks.getSession).toHaveBeenCalledWith('ses_remote_root', 'srv_kitchen') + expect(mocks.getSession).not.toHaveBeenCalledWith('ses_remote_root', 'local') + }) + + it('keeps the local list when a linked server fails to load', async () => { + const now = Date.now() + mocks.listSessionPage.mockResolvedValue({ items: [session('local_recent', now - 500)] }) + mocks.listRemoteSessionPage.mockRejectedValue(new Error('server unreachable')) + + const { result } = renderHook(() => useActiveWork(WINDOW_MS), { + wrapper: createWrapper(createQueryClient()), + }) + + await waitFor(() => expect(recentIDs(result.current.groups)).toContain('local_recent')) + + expect(result.current.isError).toBe(false) + expect(recentIDs(result.current.groups)).not.toContain('ses_remote_recent') + }) + it('renders a running remote session row and resolves its ancestry on the owning server', async () => { const now = Date.now() mocks.listSessionPage.mockResolvedValue({ items: [] }) diff --git a/frontend/src/hooks/useActiveWork.ts b/frontend/src/hooks/useActiveWork.ts index 0e4a8dcd..174278ec 100644 --- a/frontend/src/hooks/useActiveWork.ts +++ b/frontend/src/hooks/useActiveWork.ts @@ -1,13 +1,15 @@ import { useEffect, useMemo, useState } from 'react' import { useQueries, useQueryClient, type QueryClient } from '@tanstack/react-query' -import { LOCAL_OPENCODE_SERVER_ID, parseServerDirectoryKey } from '@opencode-manager/shared/schemas' +import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas' import type { SessionInfo } from '@opencode-manager/shared/opencode' +import { listSessionPage } from '@/api/opencode' import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode' import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups' import { usePendingInputSessionIDs, useRepoWorktreeList } from '@/contexts/RepoWorktreesContext' import { useSessionStatus } from '@/stores/sessionStatusStore' import { useOpenCodeServers } from '@/hooks/useOpenCodeServers' import { serverScopedKey } from '@/lib/serverScope' +import { activeWorkSessionsQueryKey } from '@/lib/queryInvalidation' import { useSettings } from '@/hooks/useSettings' import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@/api/types/settings' import { useRepoWorktrees } from '@/hooks/useRepoWorktrees' @@ -15,16 +17,20 @@ import { MS_PER_MINUTE, buildActiveWork, buildRepoActivityIndex, + buildServerActivityIndex, collectActiveRoots, needsWorktreeLookup, repoActivityFromIndex, rootSessionID, + serverActivityFromIndex, + sessionScopeOfDirectory, type ActiveWorkGroups, } from '@/lib/activeWork' import { combineQuerySessions, mergeExtraSessions } from '@/components/navigation/sidebar-session-tree' import type { Repo } from '@/api/types' const ACTIVE_WORK_SESSION_LIMIT = 50 +const ACTIVE_WORK_SESSIONS_STALE_MS = 10000 /** * The active-work time window in minutes, derived from the user's configured @@ -80,6 +86,28 @@ export function useRepoActivityState(repo: Repo): 'needs-input' | 'running' | nu ) } +/** + * Whether a linked server has any active session, returned as a primitive so rows only re-render + * when it changes. Reads only the session-status store and the pending queues, with no network. + */ +export function useServerActivityState(serverId: string): 'needs-input' | 'running' | null { + const pendingInputSessionIDs = usePendingInputSessionIDs() + + return useSessionStatus((state) => + serverActivityFromIndex( + serverId, + buildServerActivityIndex({ + statuses: state.statuses, + parents: state.parents, + runningShells: state.runningShells, + directories: state.directories, + sessionServers: state.sessionServers, + pendingInputSessionIDs, + }), + ), + ) +} + interface SessionScope { serverId: string directory: string | undefined @@ -94,13 +122,8 @@ function sessionScopeOf( directories: ReadonlyMap, sessionServers: ReadonlyMap, ): SessionScope { - const directoryKey = directories.get(sessionID) - const parsed = directoryKey ? parseServerDirectoryKey(directoryKey) : null - const serverId = - parsed && parsed.serverId !== LOCAL_OPENCODE_SERVER_ID - ? parsed.serverId - : sessionServers.get(sessionID) ?? LOCAL_OPENCODE_SERVER_ID - return { serverId, directory: parsed?.directory } + const scope = sessionScopeOfDirectory(directories.get(sessionID), sessionServers.get(sessionID)) + return { serverId: scope.serverId, directory: scope.directory ?? undefined } } /** @@ -140,6 +163,25 @@ const combineAncestorLinks = ( results: Array<{ data?: Array<[string, string | null]> }>, ): Array<[string, string | null]> => results.flatMap((result) => result.data ?? []) +interface ServerSessionPage { + serverId: string + sessions: SessionInfo[] +} + +/** + * Pairs each server's active-work page with its server id, dropping pages that are empty or failed + * so one unreachable server never removes the others from the list. + */ +function combineServerSessionPages( + results: Array<{ data?: SessionInfo[] }>, + serverIds: ReadonlyArray, +): ServerSessionPage[] { + return results.flatMap((result, index) => { + if (!result.data || result.data.length === 0) return [] + return [{ serverId: serverIds[index], sessions: result.data }] + }) +} + /** * The full active-work list. Performs network reads, so it must only be used by components that * are mounted while visible (the session picker fetches only while open). @@ -198,16 +240,70 @@ export function useActiveWork(windowMs: number): { const sessionServers = useSessionStatus((state) => state.sessionServers) const pendingInputSessionIDs = usePendingInputSessionIDs() + const { servers } = useOpenCodeServers() + const remoteServerIds = useMemo( + () => servers.filter((server) => server.enabled).map((server) => server.id), + [servers], + ) + + const serverSessionPages = useQueries({ + queries: remoteServerIds.map((serverId) => ({ + queryKey: activeWorkSessionsQueryKey(serverId), + queryFn: async (): Promise => { + const page = await listSessionPage( + { limit: ACTIVE_WORK_SESSION_LIMIT, order: 'desc', includeChildren: true }, + serverId, + ) + return page.items + }, + staleTime: ACTIVE_WORK_SESSIONS_STALE_MS, + refetchOnWindowFocus: true, + refetchOnReconnect: true, + retry: 1, + })), + combine: (results) => combineServerSessionPages(results, remoteServerIds), + }) + + const serverSessions = useMemo( + () => serverSessionPages.flatMap((page) => page.sessions), + [serverSessionPages], + ) + + const serverSessionServers = useMemo(() => { + const owners = new Map() + for (const page of serverSessionPages) { + for (const session of page.sessions) { + owners.set(session.id, page.serverId) + if (session.parentID) owners.set(session.parentID, page.serverId) + } + } + return owners + }, [serverSessionPages]) + + const allSessions = useMemo( + () => (serverSessions.length === 0 ? sessions : [...sessions, ...serverSessions]), + [sessions, serverSessions], + ) + + const sessionOwners = useMemo(() => { + if (serverSessionServers.size === 0) return sessionServers + const merged = new Map(sessionServers) + for (const [sessionID, serverId] of serverSessionServers) { + if (!merged.has(sessionID)) merged.set(sessionID, serverId) + } + return merged + }, [sessionServers, serverSessionServers]) + const parents = useMemo(() => { const merged = new Map() - for (const session of sessions) { + for (const session of allSessions) { merged.set(session.id, session.parentID ?? null) } for (const [sessionID, parentID] of storeParents) { if (!merged.has(sessionID)) merged.set(sessionID, parentID) } return merged - }, [sessions, storeParents]) + }, [allSessions, storeParents]) const roots = useMemo( () => collectActiveRoots({ statuses, parents, runningShells, pendingInputSessionIDs }), @@ -215,14 +311,14 @@ export function useActiveWork(windowMs: number): { ) const listedSessionIDs = useMemo( - () => new Set(sessions.map((session) => session.id)), - [sessions], + () => new Set(allSessions.map((session) => session.id)), + [allSessions], ) const missingRootIDs = useMemo(() => { const ids = new Set() const windowStart = now - windowMs - for (const session of sessions) { + for (const session of allSessions) { if (session.time.updated < windowStart) continue const rootID = rootSessionID(session.id, parents) if (!listedSessionIDs.has(rootID)) ids.add(rootID) @@ -234,14 +330,14 @@ export function useActiveWork(windowMs: number): { if (!listedSessionIDs.has(sessionID)) ids.add(sessionID) } return [...ids] - }, [sessions, parents, listedSessionIDs, roots, windowMs, now]) + }, [allSessions, parents, listedSessionIDs, roots, windowMs, now]) const ancestorLinks = useQueries({ queries: missingRootIDs.map((sessionID) => { - const { serverId } = sessionScopeOf(sessionID, sessionDirectories, sessionServers) + const { serverId } = sessionScopeOf(sessionID, sessionDirectories, sessionOwners) return { queryKey: serverScopedKey(['opencode', 'session-ancestry', sessionID], serverId), - queryFn: () => fetchAncestorLinks(queryClient, sessionID, sessionDirectories, sessionServers), + queryFn: () => fetchAncestorLinks(queryClient, sessionID, sessionDirectories, sessionOwners), staleTime: Infinity, } }), @@ -262,8 +358,8 @@ export function useActiveWork(windowMs: number): { ) const resolvedSessionServers = useMemo(() => { - const merged = new Map(sessionServers) - for (const [sessionID, serverId] of sessionServers) { + const merged = new Map(sessionOwners) + for (const [sessionID, serverId] of sessionOwners) { const visited = new Set() let currentID: string | null | undefined = sessionID while (currentID && !visited.has(currentID)) { @@ -273,7 +369,7 @@ export function useActiveWork(windowMs: number): { } } return merged - }, [sessionServers, resolvedParents]) + }, [sessionOwners, resolvedParents]) const hasRemoteRoots = useMemo( () => @@ -283,12 +379,12 @@ export function useActiveWork(windowMs: number): { [resolvedRoots, resolvedSessionServers], ) - const { servers } = useOpenCodeServers({ enabled: hasRemoteRoots }) + const hasServerSessions = hasRemoteRoots || serverSessionPages.length > 0 const serverNames = useMemo(() => { - if (!hasRemoteRoots || servers.length === 0) return undefined + if (!hasServerSessions || servers.length === 0) return undefined return new Map(servers.map((server) => [server.id, server.name])) - }, [hasRemoteRoots, servers]) + }, [hasServerSessions, servers]) const backfillRootIDs = useMemo(() => { const ids = new Set() @@ -308,8 +404,8 @@ export function useActiveWork(windowMs: number): { }) const mergedSessions = useMemo( - () => mergeExtraSessions(sessions, fetchedSessions), - [sessions, fetchedSessions], + () => mergeExtraSessions(allSessions, fetchedSessions), + [allSessions, fetchedSessions], ) const needsLookup = useMemo( diff --git a/frontend/src/hooks/useCommands.test.tsx b/frontend/src/hooks/useCommands.test.tsx index c7c2a907..84b88ef6 100644 --- a/frontend/src/hooks/useCommands.test.tsx +++ b/frontend/src/hooks/useCommands.test.tsx @@ -168,9 +168,9 @@ describe('useCommands', () => { const names = result.current.searchCommands('').map(({ item }) => item.name) - expect(names).not.toContain('sessions') - expect(names).not.toContain('resume') - expect(names).not.toContain('continue') + expect(names).toContain('sessions') + expect(names).toContain('resume') + expect(names).toContain('continue') expect(names).not.toContain('walkthrough') expect(names).toContain('mcp') expect(names).toContain('skills') diff --git a/frontend/src/hooks/useGlobalShortcutActions.test.tsx b/frontend/src/hooks/useGlobalShortcutActions.test.tsx index 75390fdf..4d3c7555 100644 --- a/frontend/src/hooks/useGlobalShortcutActions.test.tsx +++ b/frontend/src/hooks/useGlobalShortcutActions.test.tsx @@ -7,6 +7,7 @@ import { useGlobalShortcutActions } from './useGlobalShortcutActions' const mocks = vi.hoisted(() => ({ getRepo: vi.fn(), + getSession: vi.fn(), createSession: vi.fn(), useMobile: vi.fn(), })) @@ -27,6 +28,7 @@ vi.mock('@/api/repos', () => ({ vi.mock('@/api/opencode', () => ({ createSession: mocks.createSession, + getSession: mocks.getSession, })) function Harness() { @@ -60,6 +62,7 @@ describe('useGlobalShortcutActions', () => { queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) mocks.useMobile.mockReturnValue(false) mocks.getRepo.mockResolvedValue({ id: 5, fullPath: '/repo/five' }) + mocks.getSession.mockResolvedValue({ id: 'ses_1', location: { directory: '/srv/kitchen' } }) mocks.createSession.mockResolvedValue({ id: 'session-new' }) }) @@ -129,10 +132,20 @@ describe('useGlobalShortcutActions', () => { await waitFor(() => expect(location()).toBe('/repos/5/sessions/session-new')) }) - it('ignores the terminal and source-control shortcuts on a linked-server route', async () => { + it('toggles a linked-server route tool without falling back to a Manager host', async () => { const { location } = renderHarness('/servers/srv_kitchen/sessions/ses_1') pressLeaderFollowUp('t') + await waitFor(() => expect(location()).toBe('/servers/srv_kitchen/sessions/ses_1?panel=terminal')) + + pressLeaderFollowUp('t') + await waitFor(() => expect(location()).toBe('/servers/srv_kitchen/sessions/ses_1')) + expect(mocks.getRepo).not.toHaveBeenCalled() + }) + + it('does not fall back to a Manager host for a tool the linked-server route lacks', async () => { + const { location } = renderHarness('/servers/srv_kitchen/sessions/ses_1') + pressLeaderFollowUp('b') await act(async () => { @@ -143,6 +156,30 @@ describe('useGlobalShortcutActions', () => { expect(mocks.getRepo).not.toHaveBeenCalled() }) + it('toggles the terminal dialog on a linked-server route on mobile', async () => { + mocks.useMobile.mockReturnValue(true) + const { location } = renderHarness('/servers/srv_kitchen/sessions/ses_1') + + pressLeaderFollowUp('t') + + await waitFor(() => expect(location()).toBe('/servers/srv_kitchen/sessions/ses_1?dialog=terminal')) + }) + + it('creates a session in the linked server directory and navigates to the server session path', async () => { + const { location } = renderHarness('/servers/srv_kitchen/sessions/ses_1') + + await waitFor(() => expect(mocks.getSession).toHaveBeenCalledWith('ses_1', 'srv_kitchen')) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + pressKey({ key: 'o', ctrlKey: true }) + pressKey({ key: 'n' }) + + await waitFor(() => expect(mocks.createSession).toHaveBeenCalledWith({ directory: '/srv/kitchen' }, 'srv_kitchen')) + await waitFor(() => expect(location()).toBe('/servers/srv_kitchen/sessions/session-new')) + }) + it('does not swallow the follow-up key when the route has no new-session host', async () => { renderHarness('/') diff --git a/frontend/src/hooks/useGlobalShortcutActions.ts b/frontend/src/hooks/useGlobalShortcutActions.ts index 989d7ef9..a4c2ebb7 100644 --- a/frontend/src/hooks/useGlobalShortcutActions.ts +++ b/frontend/src/hooks/useGlobalShortcutActions.ts @@ -6,17 +6,25 @@ import { getRepo } from '@/api/repos' import { buildToolItems, toolKeyOf } from '@/components/navigation/moreDrawerItems' import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext' import { dialogSearch } from '@/hooks/useDialogParam' -import { useCreateSession } from '@/hooks/useOpenCode' +import { sessionQueryOptions, useCreateSession } from '@/hooks/useOpenCode' import { useMobile } from '@/hooks/useMobile' import { useSettingsDialog } from '@/hooks/useSettingsDialog' import { useUrlParams } from '@/hooks/useUrlParams' import { toggleToolDialogParams, toggleToolPanelParams, type PanelTool } from '@/hooks/useToolPanel' import { isLocalOpenCodeServer, useRouteOpenCodeServerId } from '@/contexts/OpenCodeServerContext' -import { getAssistantPath, getRepoPath, getSessionPath, isAssistantPath, parseRepoRoute } from '@/lib/navigation' +import { + getAssistantPath, + getRepoPath, + getServerSessionPath, + getSessionPath, + isAssistantPath, + parseRepoRoute, + parseServerSessionRoute, +} from '@/lib/navigation' /** - * Registers the app-wide shortcut actions: the settings dialog, the route tool panels, and repo-scoped session - * creation. Page layers can override any of these by registering the same action name. + * Registers the app-wide shortcut actions: the settings dialog, the route tool panels, and session creation on the + * route's OpenCode server. Page layers can override any of these by registering the same action name. */ export function useGlobalShortcutActions(): void { const { pathname } = useLocation() @@ -24,7 +32,8 @@ export function useGlobalShortcutActions(): void { const { updateParams } = useUrlParams() const { open: openSettings } = useSettingsDialog() const isMobile = useMobile() - const isRemoteRoute = !isLocalOpenCodeServer(useRouteOpenCodeServerId()) + const serverId = useRouteOpenCodeServerId() + const isRemoteRoute = !isLocalOpenCodeServer(serverId) const repoId = isAssistantPath(pathname) ? ASSISTANT_REPO_ID : parseRepoRoute(pathname).repoId @@ -34,16 +43,25 @@ export function useGlobalShortcutActions(): void { enabled: repoId !== null, }) - const createSession = useCreateSession(repo?.fullPath, (session) => { + const remoteSessionRoute = isRemoteRoute ? parseServerSessionRoute(pathname) : null + const { data: remoteSession } = useQuery( + sessionQueryOptions(remoteSessionRoute?.sessionId, undefined, serverId), + ) + const sessionDirectory = isRemoteRoute ? remoteSession?.location?.directory : repo?.fullPath + + const createSession = useCreateSession(sessionDirectory, (session) => { + if (isRemoteRoute) { + navigate(getServerSessionPath(serverId, session.id)) + return + } if (repoId === null) return navigate(getSessionPath(repoId, session.id)) - }) + }, serverId) const toolItems = useMemo(() => buildToolItems(pathname), [pathname]) const hasFilesTool = toolItems.some((item) => toolKeyOf(item) === 'files') const toggleRouteTool = useCallback((tool: PanelTool) => { - if (isRemoteRoute) return if (toolItems.some((item) => toolKeyOf(item) === tool)) { updateParams((params) => { if (isMobile) toggleToolDialogParams(params, tool) @@ -51,12 +69,12 @@ export function useGlobalShortcutActions(): void { }, 'push') return } - if (tool === 'files') return + if (isRemoteRoute || tool === 'files') return const host = repoId !== null ? getRepoPath(repoId) : getAssistantPath() navigate(`${host}${dialogSearch(tool)}`) }, [toolItems, isMobile, updateParams, navigate, repoId, isRemoteRoute]) - const newSession = repoId !== null && repo?.fullPath && !createSession.isPending + const newSession = sessionDirectory && !createSession.isPending ? () => createSession.mutate({}) : undefined diff --git a/frontend/src/hooks/useOpenCode.test.tsx b/frontend/src/hooks/useOpenCode.test.tsx index b9739e67..4a611dd6 100644 --- a/frontend/src/hooks/useOpenCode.test.tsx +++ b/frontend/src/hooks/useOpenCode.test.tsx @@ -466,6 +466,19 @@ describe('useCreateSession', () => { expect(mocks.createSession).toHaveBeenCalledWith({ directory: '/w/a', agent: undefined }, 'local') }) + + it('creates a session on an explicit server for a caller outside the server scope', async () => { + const queryClient = createQueryClient() + const { result } = renderHook(() => useCreateSession('/srv/kitchen', undefined, 'srv_kitchen'), { + wrapper: createWrapper(queryClient), + }) + + await act(async () => { + await result.current.mutateAsync({ agent: undefined }) + }) + + expect(mocks.createSession).toHaveBeenCalledWith({ directory: '/srv/kitchen', agent: undefined }, 'srv_kitchen') + }) }) describe('useChildSessionReconciliation', () => { diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index aa71cd2d..63a03aec 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -246,11 +246,17 @@ export const useChildSessionReconciliation = (sessionID: string | undefined) => }); }; +/** + * Creates a session in `directory` on the route's server, or on `serverIdOverride` for callers rendered + * outside the server scope that act on a linked server. + */ export const useCreateSession = ( directory?: string, onSuccess?: (session: { id: string }) => void, + serverIdOverride?: string, ) => { - const serverId = useOpenCodeServerId(); + const routeServerId = useOpenCodeServerId(); + const serverId = serverIdOverride ?? routeServerId; const queryClient = useQueryClient(); return useMutation({ diff --git a/frontend/src/lib/activeWork.test.ts b/frontend/src/lib/activeWork.test.ts index 179b692e..c3ca14d4 100644 --- a/frontend/src/lib/activeWork.test.ts +++ b/frontend/src/lib/activeWork.test.ts @@ -6,6 +6,7 @@ import type { RepoSibling, RepoWorktreeSource } from '@opencode-manager/shared/u import { buildActiveWork, buildRepoActivityIndex, + buildServerActivityIndex, buildWorktreeActivity, collectActiveRoots, formatActivityEmptyMessage, @@ -15,6 +16,7 @@ import { repoActivityFromIndex, resolveSessionBranch, rootSessionID, + serverActivityFromIndex, type ActiveWorktree, } from './activeWork' @@ -268,6 +270,127 @@ describe('buildRepoActivityIndex and repoActivityFromIndex', () => { }) }) +describe('buildServerActivityIndex and serverActivityFromIndex', () => { + const noShells = new Map() + + const stateFor = ( + serverId: string, + input: Parameters[0], + ): 'needs-input' | 'running' | null => + serverActivityFromIndex(serverId, buildServerActivityIndex(input)) + + it('ignores local sessions', () => { + const state = stateFor('srv_kitchen', { + statuses: statuses({ session: { type: 'busy' } }), + parents: new Map(), + runningShells: noShells, + directories: new Map([['session', '/home/me/app']]), + sessionServers: new Map(), + pendingInputSessionIDs: [], + }) + + expect(state).toBeNull() + }) + + it('marks the server named by a server-keyed directory', () => { + const state = stateFor('srv_kitchen', { + statuses: statuses({ session: { type: 'busy' } }), + parents: new Map(), + runningShells: noShells, + directories: new Map([['session', 'srv_kitchen|/home/me/app']]), + sessionServers: new Map(), + pendingInputSessionIDs: [], + }) + + expect(state).toBe('running') + }) + + it('marks the server named by the session-server index', () => { + const state = stateFor('srv_kitchen', { + statuses: statuses({ session: { type: 'busy' } }), + parents: new Map(), + runningShells: noShells, + directories: new Map([['session', '/home/me/app']]), + sessionServers: new Map([['session', 'srv_kitchen']]), + pendingInputSessionIDs: [], + }) + + expect(state).toBe('running') + }) + + it('rolls a remote needs-input child up to its root on that server', () => { + const input: Parameters[0] = { + statuses: statuses({}), + parents: new Map([['child', 'root'], ['root', null]]), + runningShells: noShells, + directories: new Map([['root', 'srv_kitchen|/home/me/app']]), + sessionServers: new Map(), + pendingInputSessionIDs: ['child'], + } + + expect(stateFor('srv_kitchen', input)).toBe('needs-input') + expect(stateFor('srv_office', input)).toBeNull() + }) + + it('keeps servers apart when the same directory is active on both', () => { + const runningInput: Parameters[0] = { + statuses: statuses({ kitchen: { type: 'busy' } }), + parents: new Map(), + runningShells: noShells, + directories: new Map([['kitchen', 'srv_kitchen|/home/me/app']]), + sessionServers: new Map(), + pendingInputSessionIDs: [], + } + + expect(stateFor('srv_kitchen', runningInput)).toBe('running') + expect(stateFor('srv_office', runningInput)).toBeNull() + }) + + it('prefers needs-input over running', () => { + const state = stateFor('srv_kitchen', { + statuses: statuses({ busy: { type: 'busy' }, waiting: { type: 'busy' } }), + parents: new Map(), + runningShells: noShells, + directories: new Map([ + ['busy', 'srv_kitchen|/home/me/app'], + ['waiting', 'srv_kitchen|/home/me/other'], + ]), + sessionServers: new Map(), + pendingInputSessionIDs: ['waiting'], + }) + + expect(state).toBe('needs-input') + }) + + it('marks a running shell on its server', () => { + const state = stateFor('srv_kitchen', { + statuses: statuses({}), + parents: new Map(), + runningShells: new Map([ + ['shell-1', { sessionID: 'orphan', directory: 'srv_kitchen|/home/me/app' }], + ]), + directories: new Map(), + sessionServers: new Map([['orphan', 'srv_kitchen']]), + pendingInputSessionIDs: [], + }) + + expect(state).toBe('running') + }) + + it('reuses the index for the same snapshot references', () => { + const input: Parameters[0] = { + statuses: statuses({ session: { type: 'busy' } }), + parents: new Map(), + runningShells: noShells, + directories: new Map([['session', 'srv_kitchen|/home/me/app']]), + sessionServers: new Map(), + pendingInputSessionIDs: [], + } + + expect(buildServerActivityIndex(input)).toBe(buildServerActivityIndex(input)) + }) +}) + describe('repoActivityFromIndex with worktrees', () => { const noShells = new Map() const main = createRepo({ id: 1, fullPath: '/repos/a' }) @@ -557,7 +680,7 @@ describe('buildActiveWork', () => { expect(groups.recent).toEqual([]) }) - it('never emits a recent row for a remote session', () => { + it('emits a recent remote root with its server label and server session path', () => { const sessions = [createSession('remote', NOW - 1000, '/home/me/app')] const groups = buildActiveWork({ @@ -569,9 +692,41 @@ describe('buildActiveWork', () => { roots: emptyRoots, outcomes: new Map(), sessionServers: new Map([['remote', 'srv_kitchen']]), + serverNames: new Map([['srv_kitchen', 'Kitchen']]), }) - expect(groups).toEqual({ needsInput: [], running: [], recent: [] }) + expect(groups.recent).toHaveLength(1) + expect(groups.recent[0].repo).toBeNull() + expect(groups.recent[0].serverId).toBe('srv_kitchen') + expect(groups.recent[0].serverName).toBe('Kitchen') + expect(groups.recent[0].state).toBe('recent') + expect(groups.recent[0].path).toBe('/servers/srv_kitchen/sessions/remote') + }) + + it('rolls a remote child up to its remote root and keeps only the root row', () => { + const parents = new Map([ + ['remote-root', null], + ['remote-child', 'remote-root'], + ]) + const sessions = [ + createSession('remote-root', NOW - 4000, '/home/me/app'), + createSession('remote-child', NOW - 1000, '/home/me/app', 'remote-root'), + ] + + const groups = buildActiveWork({ + now: NOW, + windowMs: WINDOW_MS, + repos: [repoA], + sessions, + parents, + roots: emptyRoots, + outcomes: new Map(), + sessionServers: new Map([['remote-root', 'srv_kitchen']]), + serverNames: new Map([['srv_kitchen', 'Kitchen']]), + }) + + expect(groups.recent.map((item) => item.session.id)).toEqual(['remote-root']) + expect(groups.recent[0].updatedAt).toBe(NOW - 1000) }) }) diff --git a/frontend/src/lib/activeWork.ts b/frontend/src/lib/activeWork.ts index fce74ea1..84d2c506 100644 --- a/frontend/src/lib/activeWork.ts +++ b/frontend/src/lib/activeWork.ts @@ -115,7 +115,7 @@ export function collectActiveRoots(input: { return { needsInput, running } } -interface RepoActivityIndexInput { +interface ActivityIndexInput { statuses: ReadonlyMap parents: ReadonlyMap runningShells: ReadonlyMap @@ -123,67 +123,171 @@ interface RepoActivityIndexInput { pendingInputSessionIDs: Iterable } -let cachedRepoActivityIndex: (RepoActivityIndexInput & { - index: Map -}) | null = null +interface ServerActivityIndexInput extends ActivityIndexInput { + sessionServers: ReadonlyMap +} -function computeRepoActivityIndex(input: RepoActivityIndexInput): Map { +type ActivityIndex = Map + +/** Caches one built value per input snapshot, matching the input fields the value depends on. */ +function cacheByInput( + compute: (input: I) => V, + sameInput: (left: I, right: I) => boolean, +): (input: I) => V { + let cached: { input: I; value: V } | null = null + + return (input) => { + if (cached && sameInput(cached.input, input)) return cached.value + const value = compute(input) + cached = { input, value } + return value + } +} + +function sameActivityInput(left: I, right: I): boolean { + return ( + left.statuses === right.statuses && + left.parents === right.parents && + left.runningShells === right.runningShells && + left.directories === right.directories && + left.pendingInputSessionIDs === right.pendingInputSessionIDs + ) +} + +function sameServerActivityInput( + left: ServerActivityIndexInput, + right: ServerActivityIndexInput, +): boolean { + return sameActivityInput(left, right) && left.sessionServers === right.sessionServers +} + +/** + * Rolls every active or pending session onto the index key its directory resolves to. Pending + * input marks its own and its root's key as needs-input; non-idle sessions and running shells mark + * running unless needs-input already claimed the key. + */ +function computeActivityIndex( + input: ActivityIndexInput, + keyOf: (sessionID: string, directory: string | null | undefined) => string | null, +): ActivityIndex { const { statuses, parents, runningShells, directories, pendingInputSessionIDs } = input - const index = new Map() + const index: ActivityIndex = new Map() - const markNeedsInput = (directory?: string | null): void => { - const normalized = normalizeDirectory(localDirectoryOf(directory)) - if (normalized) index.set(normalized, 'needs-input') + const mark = ( + state: 'needs-input' | 'running', + sessionID: string, + directory?: string | null, + ): void => { + const key = keyOf(sessionID, directory) + if (!key) return + if (state === 'running' && index.get(key) === 'needs-input') return + index.set(key, state) } - const markRunning = (directory?: string | null): void => { - const normalized = normalizeDirectory(localDirectoryOf(directory)) - if (!normalized || index.get(normalized) === 'needs-input') return - index.set(normalized, 'running') + const markSession = (state: 'needs-input' | 'running', sessionID: string): void => { + mark(state, sessionID, directories.get(sessionID)) + mark(state, sessionID, directories.get(rootSessionID(sessionID, parents))) } for (const sessionID of pendingInputSessionIDs) { - markNeedsInput(directories.get(sessionID)) - markNeedsInput(directories.get(rootSessionID(sessionID, parents))) + markSession('needs-input', sessionID) } for (const [sessionID, status] of statuses) { if (status.type === 'idle') continue - markRunning(directories.get(sessionID)) - markRunning(directories.get(rootSessionID(sessionID, parents))) + markSession('running', sessionID) } for (const shell of runningShells.values()) { - markRunning(shell.directory) - markRunning(directories.get(shell.sessionID)) - markRunning(directories.get(rootSessionID(shell.sessionID, parents))) + mark('running', shell.sessionID, shell.directory) + markSession('running', shell.sessionID) } return index } +function localActivityKey(_sessionID: string, directory?: string | null): string | null { + return normalizeDirectory(localDirectoryOf(directory)) +} + +const repoActivityIndex = cacheByInput( + (input) => computeActivityIndex(input, localActivityKey), + sameActivityInput, +) + /** * Indexes active sessions by normalized directory for repo badges. Pending input marks its own and * its root's directory as needs-input; non-idle sessions and running shells mark running unless * needs-input already claimed the directory. Shared across rows per store snapshot by reference. */ -export function buildRepoActivityIndex( - input: RepoActivityIndexInput, -): Map { - if ( - cachedRepoActivityIndex && - cachedRepoActivityIndex.statuses === input.statuses && - cachedRepoActivityIndex.parents === input.parents && - cachedRepoActivityIndex.runningShells === input.runningShells && - cachedRepoActivityIndex.directories === input.directories && - cachedRepoActivityIndex.pendingInputSessionIDs === input.pendingInputSessionIDs - ) { - return cachedRepoActivityIndex.index +export function buildRepoActivityIndex(input: ActivityIndexInput): ActivityIndex { + return repoActivityIndex(input) +} + +/** The server and plain directory named by a session-status directory value. */ +export interface SessionDirectoryScope { + serverId: string + directory: string | null +} + +/** + * Resolves a session-status directory value to its owning server and plain directory. A + * server-keyed value names its owner, otherwise the session-server entry does; everything else + * belongs to the local server. + */ +export function sessionScopeOfDirectory( + directory: string | null | undefined, + sessionServerId?: string, +): SessionDirectoryScope { + const parsed = directory ? parseServerDirectoryKey(directory) : null + const serverId = + parsed && parsed.serverId !== LOCAL_OPENCODE_SERVER_ID + ? parsed.serverId + : sessionServerId ?? LOCAL_OPENCODE_SERVER_ID + return { serverId, directory: parsed?.directory ?? null } +} + +function serverIndexKey(serverId: string, directory?: string | null): string { + return `${serverId}|${normalizeDirectory(directory) ?? ''}` +} + +const serverActivityIndex = cacheByInput( + (input) => + computeActivityIndex(input, (sessionID, directory) => { + const scope = sessionScopeOfDirectory(directory, input.sessionServers.get(sessionID)) + if (scope.serverId === LOCAL_OPENCODE_SERVER_ID) return null + return serverIndexKey(scope.serverId, scope.directory) + }), + sameServerActivityInput, +) + +/** + * Indexes active sessions by owning linked server and directory for server badges. A session + * belongs to the server named by its server-keyed directory, otherwise to its session-server entry; + * local sessions are never indexed. Keys are `|`, with an empty directory when + * the session's directory is unknown. + */ +export function buildServerActivityIndex(input: ServerActivityIndexInput): ActivityIndex { + return serverActivityIndex(input) +} + +/** + * A linked server's activity from a prebuilt server index. Needs-input outranks running. + */ +export function serverActivityFromIndex( + serverId: string, + index: ReadonlyMap, +): 'needs-input' | 'running' | null { + const prefix = `${serverId}|` + let running = false + + for (const [key, state] of index) { + if (!key.startsWith(prefix)) continue + if (state === 'needs-input') return 'needs-input' + if (state === 'running') running = true } - const index = computeRepoActivityIndex(input) - cachedRepoActivityIndex = { ...input, index } - return index + return running ? 'running' : null } /** @@ -322,11 +426,11 @@ export function needsWorktreeLookup(input: { /** * Groups the given sessions into needs-input, running, and recent roots. A session appears in * exactly one group (needs-input over running over recent) and only when it resolves to a local - * repo or to an owning linked server. A session owned by a linked server is only emitted while it - * needs input or is running, so remote work never fills the recent window. A recent session in a - * schedule worktree is omitted so schedules only surface while they need attention. The input may - * mix roots and children; children never become items, but their latest update time rolls up into - * the root's `updatedAt` and decides the recent window and ordering. + * repo or to an owning linked server. A session owned by a linked server keeps its own row in any + * state, opening on that server instead of a local repo. A recent session in a schedule worktree is + * omitted so schedules only surface while they need attention. The input may mix roots and children; + * children never become items, but their latest update time rolls up into the root's `updatedAt` and + * decides the recent window and ordering. */ export function buildActiveWork(input: { now: number @@ -380,7 +484,6 @@ export function buildActiveWork(input: { const serverId = sessionServers?.get(session.id) ?? null if (serverId) { - if (state === 'recent') continue seen.add(session.id) const item: ActiveWorkItem = { key: getSessionKey(session), @@ -395,7 +498,8 @@ export function buildActiveWork(input: { path: getServerSessionPath(serverId, session.id), } if (state === 'needs-input') needsInput.push(item) - else running.push(item) + else if (state === 'running') running.push(item) + else recent.push(item) continue } diff --git a/frontend/src/lib/builtinCommands.ts b/frontend/src/lib/builtinCommands.ts index 923172fb..4c25db67 100644 --- a/frontend/src/lib/builtinCommands.ts +++ b/frontend/src/lib/builtinCommands.ts @@ -69,13 +69,13 @@ export function isBuiltinCommand(command: CommandInfo): command is BuiltinComman } const MANAGER_ONLY_COMMAND_ACTIONS: ReadonlySet = new Set([ - 'showSessions', 'showWalkthrough', ]) /** * Built-in composer commands for a server scope. Commands backed by Manager-only features are omitted for - * linked OpenCode servers; MCP and skills stay because their views work against the linked server. + * linked OpenCode servers; MCP, skills, and the session picker stay because their views work against the + * linked server. */ export function getBuiltinCommands(isLocalServer: boolean): readonly BuiltinCommand[] { if (isLocalServer) return BUILTIN_COMMANDS diff --git a/frontend/src/lib/queryInvalidation.test.ts b/frontend/src/lib/queryInvalidation.test.ts index 672d500a..2ef7c355 100644 --- a/frontend/src/lib/queryInvalidation.test.ts +++ b/frontend/src/lib/queryInvalidation.test.ts @@ -1,6 +1,7 @@ import { QueryClient } from '@tanstack/react-query' import { afterEach, describe, expect, it, vi } from 'vitest' import { + activeWorkSessionsQueryKey, invalidateConfigCaches, invalidateProviderCaches, invalidateProviderCachesDebounced, @@ -206,6 +207,35 @@ describe('invalidateSessionListCachesDebounced', () => { expect(queryClient.getQueryState(sessionListKey('/a'))?.isInvalidated).toBe(true) expect(queryClient.getQueryState(sessionListKey('/b'))?.isInvalidated).toBe(true) }) + + it('keeps a remote event directory from invalidating the local list with the same path', () => { + vi.useFakeTimers() + const queryClient = new QueryClient() + const remoteListKey = ['opencode', 'sessions', '/repo', { allDirectories: true }, 'srv_a'] + queryClient.setQueryData(sessionListKey('/repo'), { pages: [], pageParams: [] }) + queryClient.setQueryData(remoteListKey, { pages: [], pageParams: [] }) + + invalidateSessionListCachesDebounced(queryClient, '/repo', 'srv_a') + vi.advanceTimersByTime(200) + + expect(queryClient.getQueryState(remoteListKey)?.isInvalidated).toBe(true) + expect(queryClient.getQueryState(sessionListKey('/repo'))?.isInvalidated).toBe(false) + }) + + it('invalidates the active-work list of the event server only', () => { + vi.useFakeTimers() + const queryClient = new QueryClient() + const localActiveWorkKey = activeWorkSessionsQueryKey('local') + const remoteActiveWorkKey = activeWorkSessionsQueryKey('srv_a') + queryClient.setQueryData(localActiveWorkKey, []) + queryClient.setQueryData(remoteActiveWorkKey, []) + + invalidateSessionListCachesDebounced(queryClient, '/repo', 'srv_a') + vi.advanceTimersByTime(200) + + expect(queryClient.getQueryState(remoteActiveWorkKey)?.isInvalidated).toBe(true) + expect(queryClient.getQueryState(localActiveWorkKey)?.isInvalidated).toBe(false) + }) }) describe('invalidateQueryKeysDebounced', () => { diff --git a/frontend/src/lib/queryInvalidation.ts b/frontend/src/lib/queryInvalidation.ts index b3bec075..501666c5 100644 --- a/frontend/src/lib/queryInvalidation.ts +++ b/frontend/src/lib/queryInvalidation.ts @@ -1,4 +1,5 @@ import type { QueryClient } from '@tanstack/react-query' +import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas' import type { GitStatusResponse } from '@/types/git' export function sessionTranscriptQueryKey(sessionID: string | null | undefined) { @@ -182,23 +183,49 @@ export function invalidateSessionCaches(queryClient: QueryClient) { }) } +const SESSION_LIST_QUERY_GROUPS = new Set(['sessions', 'active-work-sessions']) + +/** + * Query key of one server's active-work session list: flat, newest-first, across all directories. + * It is distinct from the paged session-list keys so the two data shapes never share a cache entry. + */ +export function activeWorkSessionsQueryKey(serverId: string): readonly unknown[] { + return ['opencode', 'active-work-sessions', serverId] +} + export function invalidateSessionListCaches(queryClient: QueryClient) { queryClient.invalidateQueries({ predicate: (query) => - query.queryKey[0] === 'opencode' && query.queryKey[1] === 'sessions', + query.queryKey[0] === 'opencode' && SESSION_LIST_QUERY_GROUPS.has(String(query.queryKey[1])), }) } +/** + * The server a session-list query key belongs to: an active-work key carries it third, a paged + * session-list key appends it after its options, and an unscoped key is a local-server key. + */ +function sessionListQueryServerId(queryKey: readonly unknown[]): string { + if (queryKey[1] === 'active-work-sessions') return String(queryKey[2]) + return typeof queryKey[4] === 'string' ? queryKey[4] : LOCAL_OPENCODE_SERVER_ID +} + interface SessionListInvalidationState { timer: ReturnType | null directories: Set invalidateAll: boolean } -const sessionListInvalidationStates = new WeakMap() +const sessionListInvalidationStates = new WeakMap>() -function sessionListQueryMatchesDirectories(queryKey: readonly unknown[], directories: Set) { - if (queryKey[0] !== 'opencode' || queryKey[1] !== 'sessions') return false +function sessionListQueryMatchesDirectories( + queryKey: readonly unknown[], + directories: Set, + serverId: string, +) { + if (queryKey[0] !== 'opencode') return false + if (!SESSION_LIST_QUERY_GROUPS.has(String(queryKey[1]))) return false + if (sessionListQueryServerId(queryKey) !== serverId) return false + if (queryKey[1] === 'active-work-sessions') return true const directoryKey = queryKey[2] if (typeof directoryKey !== 'string') return false return directoryKey.split('|').some((directory) => directories.has(directory)) @@ -207,22 +234,30 @@ function sessionListQueryMatchesDirectories(queryKey: readonly unknown[], direct function flushSessionListInvalidation( queryClient: QueryClient, state: SessionListInvalidationState, + serverId: string, ) { if (state.invalidateAll) { - invalidateSessionListCaches(queryClient) + queryClient.invalidateQueries({ + predicate: (query) => + query.queryKey[0] === 'opencode' && + SESSION_LIST_QUERY_GROUPS.has(String(query.queryKey[1])) && + sessionListQueryServerId(query.queryKey) === serverId, + }) return } queryClient.invalidateQueries({ - predicate: (query) => sessionListQueryMatchesDirectories(query.queryKey, state.directories), + predicate: (query) => sessionListQueryMatchesDirectories(query.queryKey, state.directories, serverId), }) } export function invalidateSessionListCachesDebounced( queryClient: QueryClient, directory?: string, + serverId: string = LOCAL_OPENCODE_SERVER_ID, delayMs = 200, ) { - const state = sessionListInvalidationStates.get(queryClient) ?? { + const states = sessionListInvalidationStates.get(queryClient) ?? new Map() + const state = states.get(serverId) ?? { timer: null, directories: new Set(), invalidateAll: false, @@ -233,10 +268,11 @@ export function invalidateSessionListCachesDebounced( } else { state.invalidateAll = true } - sessionListInvalidationStates.set(queryClient, state) + states.set(serverId, state) + sessionListInvalidationStates.set(queryClient, states) state.timer = setTimeout(() => { - sessionListInvalidationStates.delete(queryClient) - flushSessionListInvalidation(queryClient, state) + states.delete(serverId) + flushSessionListInvalidation(queryClient, state, serverId) }, delayMs) } diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 7582eb4a..c1cddc99 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -61,7 +61,7 @@ import { formatOpenCodeModelRef } from "@opencode-manager/shared/opencode"; import { FormPrompt } from "@/components/session/FormPrompt"; import { MinimizedFormIndicator } from "@/components/session/MinimizedFormIndicator"; import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"; -import { SourceControlPanel } from "@/components/source-control"; +import { SourceControlPanel, RemoteSourceControlPanel } from "@/components/source-control"; import { TerminalPanel } from "@/components/terminal/TerminalPanel"; import { PreviewPanel } from "@/components/preview/PreviewPanel"; import { SessionSendErrorBanner } from "@/components/session/SessionSendErrorBanner"; @@ -1060,15 +1060,24 @@ export function SessionDetail() { /> )} - {!isRemoteServer && ( - setSourceControlOpen(false)} - currentBranch={repo?.currentBranch || repo?.branch || "main"} - repoName={workspaceDisplayName} - /> - )} + {isRemoteServer + ? sessionDirectory && ( + setSourceControlOpen(false)} + /> + ) + : ( + setSourceControlOpen(false)} + currentBranch={repo?.currentBranch || repo?.branch || "main"} + repoName={workspaceDisplayName} + /> + )} ({ getRepo: vi.fn(), useSessionStatus: vi.fn(), SourceControlPanel: vi.fn(() => null), + RemoteSourceControlPanel: vi.fn(() => null), TerminalPanel: vi.fn(() => null), PreviewPanel: vi.fn(() => null), FileBrowserSheet: vi.fn(() => null), @@ -145,7 +146,10 @@ vi.mock('@/components/notifications/PendingActionsGroup', () => ({ vi.mock('@/components/navigation/SessionMoreButton', () => ({ SessionMoreButton: mocks.SessionMoreButton })) vi.mock('@/components/navigation/ToolSidePanel', () => ({ ToolSidePanel: mocks.ToolSidePanel })) vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: mocks.FileBrowserSheet })) -vi.mock('@/components/source-control', () => ({ SourceControlPanel: mocks.SourceControlPanel })) +vi.mock('@/components/source-control', () => ({ + SourceControlPanel: mocks.SourceControlPanel, + RemoteSourceControlPanel: mocks.RemoteSourceControlPanel, +})) vi.mock('@/components/terminal/TerminalPanel', () => ({ TerminalPanel: mocks.TerminalPanel })) vi.mock('@/components/preview/PreviewPanel', () => ({ PreviewPanel: mocks.PreviewPanel })) vi.mock('@/components/repo/ProjectActionsMenu', () => ({ ProjectActionsMenu: mocks.ProjectActionsMenu })) @@ -349,6 +353,23 @@ describe('SessionDetail remote server mode', () => { ) }) + it('opens the remote source control panel instead of the Manager one', async () => { + renderRemoteSession() + + await waitFor(() => { + expect(screen.getByTestId('message-thread')).toBeInTheDocument() + }) + + expect(mocks.SourceControlPanel).not.toHaveBeenCalled() + expect(mocks.RemoteSourceControlPanel.mock.calls.at(-1)?.[0]).toEqual( + expect.objectContaining({ + serverId: 'srv_kitchen', + directory: '/home/me/app', + isOpen: false, + }), + ) + }) + it('treats the stream as disconnected when the remote server status is disconnected', async () => { mocks.useOpenCodeServerStatuses.mockReturnValue({ statusById: {