diff --git a/frontend/src/api/opencode.test.ts b/frontend/src/api/opencode.test.ts index e8e7ed3c..7b0e91ce 100644 --- a/frontend/src/api/opencode.test.ts +++ b/frontend/src/api/opencode.test.ts @@ -12,6 +12,7 @@ import { createSessionWithPrompt, deleteSession, findFiles, + findRemoteProjectForDirectory, forkSession, getSession, interruptSession, @@ -799,4 +800,20 @@ describe('project helpers', () => { expect(remoteProjectName(project('p1', undefined, '/work/beta', { created: 1, updated: 2 }))).toBe('beta') expect(remoteProjectName(project('p1', ' ', '/work/gamma', { created: 1, updated: 2 }))).toBe('gamma') }) + + it('finds the project that owns a directory or one nested inside it', () => { + const projects = [ + project('p1', 'Alpha', '/work/alpha', { created: 1, updated: 2 }), + project('p2', 'Beta', '/work/beta', { created: 1, updated: 2 }), + ] + + expect(findRemoteProjectForDirectory(projects, '/work/beta')?.id).toBe('p2') + expect(findRemoteProjectForDirectory(projects, '/work/beta/packages/web')?.id).toBe('p2') + }) + + it('does not match a directory that only shares a prefix with a canonical directory', () => { + const projects = [project('p1', 'Alpha', '/work/alpha', { created: 1, updated: 2 })] + + expect(findRemoteProjectForDirectory(projects, '/work/alphabet')).toBeUndefined() + }) }) diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 9d4da65a..af21b06e 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -68,6 +68,23 @@ export function remoteProjectName(project: OpenCodeProject): string { return project.name?.trim() || getDirectoryName(project.canonical) } +/** + * Finds the project that owns a directory, matching its canonical directory and anything nested + * inside it. + * + * @param projects Projects of the server that owns the directory. + * @param directory Directory whose owning project is resolved. + * @returns The owning project, or undefined when the directory belongs to none of them. + */ +export function findRemoteProjectForDirectory( + projects: OpenCodeProject[], + directory: string, +): OpenCodeProject | undefined { + return projects.find( + (project) => directory === project.canonical || directory.startsWith(`${project.canonical}/`), + ) +} + export type VcsInfo = Awaited>['data'] export type VcsFileStatus = Awaited>['data'][number] diff --git a/frontend/src/components/message/ComposerModelPill.tsx b/frontend/src/components/message/ComposerModelPill.tsx index bd23a05b..89133d90 100644 --- a/frontend/src/components/message/ComposerModelPill.tsx +++ b/frontend/src/components/message/ComposerModelPill.tsx @@ -1,4 +1,4 @@ -import { memo } from 'react' +import { memo, useMemo } from 'react' import { ModelQuickSelect } from '@/components/model/ModelQuickSelect' import { ContextUsageMeter } from '@/components/session/ContextUsageMeter' import { useSession } from '@/hooks/useOpenCode' @@ -51,16 +51,8 @@ export const ComposerModelPill = memo(function ComposerModelPill({ contextUsage ? contextUsageAccessibleLabel(contextUsage) : null, ].filter((part): part is string => part !== null).join(', ') - return ( - + const trigger = useMemo( + () => ( + ), + [contextUsage, modelName, pillLabel, pillUsage, pillUsageTone, variant], + ) + + return ( + + {trigger} ) }) diff --git a/frontend/src/components/model/ModelQuickSelect.tsx b/frontend/src/components/model/ModelQuickSelect.tsx index d2099181..24e9dc94 100644 --- a/frontend/src/components/model/ModelQuickSelect.tsx +++ b/frontend/src/components/model/ModelQuickSelect.tsx @@ -1,4 +1,4 @@ -import { useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { memo, useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { Check, ChevronDown, ChevronLeft, ChevronRight, Search, Star, Trash2, X, type LucideIcon } from 'lucide-react' import { useModelSelection, type ModelSelectionSession } from '@/hooks/useModelSelection' import { useMobile } from '@/hooks/useMobile' @@ -220,7 +220,7 @@ function VirtualizedList({ ) } -export function ModelQuickSelect({ +export const ModelQuickSelect = memo(function ModelQuickSelect({ directory, disabled, children, @@ -801,4 +801,4 @@ export function ModelQuickSelect({ ) -} +}) diff --git a/frontend/src/components/navigation/DesktopSessionTree.tsx b/frontend/src/components/navigation/DesktopSessionTree.tsx index a31d6bf9..05ca0cf6 100644 --- a/frontend/src/components/navigation/DesktopSessionTree.tsx +++ b/frontend/src/components/navigation/DesktopSessionTree.tsx @@ -11,7 +11,7 @@ import { useSessionPins } from '@/hooks/useSessionPins' import { useSidebarServerSelection } from '@/hooks/useSidebarServerSelection' import { RemoteProjectNavList } from '@/components/navigation/RemoteProjectNav' import { - NewSessionButton, + LocalRepoNewSessionButton, RepoNavGroup, RepoSessionNavList, SearchClearButton, @@ -25,7 +25,7 @@ import { isCurrentSessionItem, isRepoReady, } from '@/components/navigation/sidebar-session-tree' -import { getRepoPath, getSessionPath } from '@/lib/navigation' +import { getRepoPath } from '@/lib/navigation' import { getRepoDisplayName } from '@/lib/utils' import { buildPinnedSessionKeys } from '@/lib/sessionKey' @@ -124,12 +124,7 @@ function SessionSearchResults({ onOpenRepo={() => navigate(getRepoPath(group.repo.id))} indicator={} actions={ - getSessionPath(group.repo.id, sessionId)} - onOpenSession={navigate} - /> + } > {group.items.map((item) => ( @@ -199,12 +194,7 @@ function LocalSessionTree() { onOpenRepo={(repoId) => navigate(getRepoPath(repoId))} onSelectSession={navigate} renderActions={(repo) => ( - getSessionPath(repo.id, sessionId)} - onOpenSession={navigate} - /> + )} /> )} diff --git a/frontend/src/components/navigation/RemoteProjectNav.tsx b/frontend/src/components/navigation/RemoteProjectNav.tsx index 9143b342..de19ff0a 100644 --- a/frontend/src/components/navigation/RemoteProjectNav.tsx +++ b/frontend/src/components/navigation/RemoteProjectNav.tsx @@ -363,7 +363,7 @@ export function RemoteProjectNavList({ const { servers, isLoading: isServersLoading } = useOpenCodeServers() const { statusById } = useOpenCodeServerStatuses() const server = servers.find((candidate) => candidate.id === serverId) - const activeDirectory = useActiveRemoteDirectory(serverId) + const { directory: activeDirectory } = useActiveRemoteDirectory(serverId) const { projects, isLoading: projectsLoading, isError: projectsError, hasData: hasProjects } = useRemoteProjects(serverId) diff --git a/frontend/src/components/navigation/RepoSessionNav.tsx b/frontend/src/components/navigation/RepoSessionNav.tsx index 261db78c..e3c2edd6 100644 --- a/frontend/src/components/navigation/RepoSessionNav.tsx +++ b/frontend/src/components/navigation/RepoSessionNav.tsx @@ -9,7 +9,7 @@ import { useRepoSiblings } from '@/hooks/useRepoSiblings' import { useSidebarRepoGroups } from '@/hooks/useSidebarRepoGroups' import { buildWorktreeActivity, type ActiveWorktree } from '@/lib/activeWork' import { cn, formatShortRelativeTime, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils' -import { getRepoPath } from '@/lib/navigation' +import { getRepoPath, getSessionPath } from '@/lib/navigation' import { isCurrentSessionItem, isRepoReady, @@ -348,3 +348,23 @@ export function NewSessionButton({ ) } + +interface LocalRepoNewSessionButtonProps { + repo: Repo + onOpenSession: (path: string) => void +} + +/** + * Creates a session in a local repository, deriving the session directory, accessible label, and + * session route from the repository so callers only choose what to render and where to navigate. + */ +export function LocalRepoNewSessionButton({ repo, onOpenSession }: LocalRepoNewSessionButtonProps) { + return ( + getSessionPath(repo.id, sessionId)} + onOpenSession={onOpenSession} + /> + ) +} diff --git a/frontend/src/components/session/ProjectPickerContent.tsx b/frontend/src/components/session/ProjectPickerContent.tsx index e05681d7..632c78a3 100644 --- a/frontend/src/components/session/ProjectPickerContent.tsx +++ b/frontend/src/components/session/ProjectPickerContent.tsx @@ -1,9 +1,8 @@ import { useEffect, useId, useMemo, useState } from 'react' import type { Repo } from '@/api/types' import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups' -import { NewSessionButton } from '@/components/navigation/RepoSessionNav' +import { LocalRepoNewSessionButton } from '@/components/navigation/RepoSessionNav' import { isRepoReady } from '@/components/navigation/sidebar-session-tree' -import { getSessionPath } from '@/lib/navigation' import { cn, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils' import { PickerSearchBar, @@ -158,12 +157,7 @@ export function ProjectPickerContent({ )} {isRepoReady(repo) ? ( - getSessionPath(repo.id, sessionId)} - onOpenSession={onNavigate} - /> + ) : ( Not ready )} diff --git a/frontend/src/components/session/SessionPickerDialog.tsx b/frontend/src/components/session/SessionPickerDialog.tsx index e7bb9266..78047515 100644 --- a/frontend/src/components/session/SessionPickerDialog.tsx +++ b/frontend/src/components/session/SessionPickerDialog.tsx @@ -20,7 +20,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog' import { ProjectPickerContent } from '@/components/session/ProjectPickerContent' import { AddRepoDialog } from '@/components/repo/AddRepoDialog' -import { NewSessionButton } from '@/components/navigation/RepoSessionNav' +import { LocalRepoNewSessionButton } from '@/components/navigation/RepoSessionNav' import { RemoteProjectNavList } from '@/components/navigation/RemoteProjectNav' import { PickerSearchBar, @@ -40,7 +40,6 @@ import { useSessionStatusForSession } from '@/stores/sessionStatusStore' import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext' import { useSettings } from '@/hooks/useSettings' import { buildPinnedSessionKeys, getSessionKey } from '@/lib/sessionKey' -import { getSessionPath } from '@/lib/navigation' import { formatShortcutLabel, resolveShortcutBindings } from '@/lib/keyboardShortcuts' import { cn, formatShortRelativeTime, getRepoDisplayName } from '@/lib/utils' import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery' @@ -72,21 +71,17 @@ function sessionsTabLabel(scopeEnabled: boolean, allProjects: boolean): string { export interface RemotePickerScope { serverId: string serverName?: string + /** Canonical project directory in view; omitted when the route scopes to the whole server. */ projectDirectory?: string + /** Whether the route's project directory is still resolving, which holds the all-sessions search. */ + isPending?: boolean } -interface SessionPickerDialogProps { - open: boolean +type SessionPickerDialogProps = Omit< + SessionPickerPanelProps, + 'searchTrailing' | 'onAddRepo' | 'renderTitle' +> & { onOpenChange: (open: boolean) => void - currentRepo: Repo | undefined - activeSessionID?: string - onSelectSession: (session: Session, repo: Repo) => void - onSelectRemoteSession?: (session: Session, serverId: string) => void - onDeleteActiveSession: () => void - onSelectRepo: (repo: Repo) => void - onNavigate: (path: string) => void - /** Set on a linked-server route to list that server's sessions instead of Manager repos. */ - remote?: RemotePickerScope } interface SessionPickerRow { @@ -988,6 +983,7 @@ interface RemoteSessionPickerContentProps { open: boolean serverName?: string projectDirectory?: string + isPending?: boolean activeSessionID?: string onSelectSession: (session: Session) => void switchHint: string @@ -999,6 +995,7 @@ function RemoteSessionPickerContent({ open, serverName, projectDirectory, + isPending = false, activeSessionID, onSelectSession, switchHint, @@ -1021,7 +1018,7 @@ function RemoteSessionPickerContent({ isFetchNextPageError, canFetchNextPage, } = useSessionSearch(projectDirectory ? [projectDirectory] : [], { - allDirectories: projectDirectory === undefined, + allDirectories: projectDirectory === undefined && !isPending, }) const sections = useMemo( @@ -1207,6 +1204,7 @@ export interface SessionPickerPanelProps { onDeleteActiveSession: () => void onSelectRepo: (repo: Repo) => void onNavigate: (path: string) => void + /** Set on a linked-server route to list that server's sessions instead of Manager repos. */ remote?: RemotePickerScope searchTrailing?: React.ReactNode onAddRepo?: () => void @@ -1312,12 +1310,7 @@ function SessionPickerPanelBody({ ) const newSessionButton = readyRepo ? ( - getSessionPath(readyRepo.id, sessionId)} - onOpenSession={onNavigate} - /> + ) : ( addRepoButton ) @@ -1411,6 +1404,7 @@ function SessionPickerPanelBody({ open={open} serverName={remote.serverName} projectDirectory={remote.projectDirectory} + isPending={remote.isPending} activeSessionID={activeSessionID} onSelectSession={(session) => onSelectRemoteSession?.(session, remote.serverId)} switchHint={switchHint} @@ -1477,7 +1471,6 @@ export function SessionPickerDialog({ onNavigate, remote, }: SessionPickerDialogProps) { - const searchInputRef = useRef(null) const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY) return ( @@ -1488,9 +1481,7 @@ export function SessionPickerDialog({ onEscapeKeyDown={() => onOpenChange(false)} onOpenAutoFocus={(event) => { event.preventDefault() - if (hasFinePointer) { - searchInputRef.current?.focus() - } else { + if (!hasFinePointer) { ;(event.currentTarget as HTMLElement).focus() } }} diff --git a/frontend/src/components/session/SessionPickerSheet.test.tsx b/frontend/src/components/session/SessionPickerSheet.test.tsx index a7822904..33ec181d 100644 --- a/frontend/src/components/session/SessionPickerSheet.test.tsx +++ b/frontend/src/components/session/SessionPickerSheet.test.tsx @@ -418,6 +418,52 @@ describe('SessionPickerSheet', () => { expect(mocks.lastAllDirectories).toBe(false) }) + it('scopes the sheet to the canonical project directory of a remote session subdirectory', async () => { + useSidebarServerStore.setState({ serverId: 'srv_kitchen' }) + mocks.getSession.mockResolvedValue(makeSession('ses_remote', 'Remote session', '/home/me/app/packages/web')) + mocks.listProjects.mockResolvedValue([ + { + id: 'p1', + name: 'App', + canonical: '/home/me/app', + time: { created: 1, updated: 2 }, + sandboxes: [], + }, + ]) + + renderSheet(['/servers/srv_kitchen/sessions/ses_remote?mobileTab=sessions']) + + await waitFor(() => expect(mocks.lastDirectories).toEqual(['/home/me/app'])) + expect(mocks.lastAllDirectories).toBe(false) + }) + + it('holds the all-directories search while the remote session directory resolves', async () => { + useSidebarServerStore.setState({ serverId: 'srv_kitchen' }) + mocks.getSession.mockReturnValue(new Promise(() => undefined)) + + renderSheet(['/servers/srv_kitchen/sessions/ses_remote?mobileTab=sessions']) + + await waitFor(() => expect(mocks.getSession).toHaveBeenCalled()) + expect(mocks.lastDirectories).toEqual([]) + expect(mocks.lastAllDirectories).toBe(false) + }) + + it('returns to the repo session list keeping its tab when the open session is deleted', async () => { + mocks.sessionsData = [makeSession('ses_active', 'Active session', '/w/a')] + mocks.deleteSessionMock.mockResolvedValue(undefined) + + const { location } = renderSheet(['/repos/1/sessions/ses_active?mobileTab=sessions&repoTab=changes']) + + const combobox = await screen.findByRole('combobox') + await screen.findByRole('option', { name: /Active session/ }) + fireEvent.keyDown(combobox, { key: 'd', ctrlKey: true }) + expect(screen.getByText('Press Ctrl+D again to confirm')).toBeInTheDocument() + fireEvent.keyDown(combobox, { key: 'd', ctrlKey: true }) + + await waitFor(() => expect(mocks.deleteSessionMock).toHaveBeenCalled()) + expect(location()).toBe('/repos/1?repoTab=changes REPLACE') + }) + it('does not resolve the remote session directory while the sheet is closed', async () => { useSidebarServerStore.setState({ serverId: 'srv_kitchen' }) diff --git a/frontend/src/components/ui/bottom-sheet.tsx b/frontend/src/components/ui/bottom-sheet.tsx index 59db125f..c37007fb 100644 --- a/frontend/src/components/ui/bottom-sheet.tsx +++ b/frontend/src/components/ui/bottom-sheet.tsx @@ -9,7 +9,7 @@ import { import { cn } from '@/lib/utils' import { MODAL_TRANSITION_MS } from '@/lib/utils' import { useSwipeDismiss } from '@/hooks/useMobile' -import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus' +import { useOverlayReturnFocus } from '@/hooks/useOverlayReturnFocus' export interface BottomSheetProps { isOpen: boolean @@ -31,10 +31,7 @@ export function BottomSheet({ dismissible = true, }: BottomSheetProps) { const [shouldRender, setShouldRender] = useState(false) - const [openState, setOpenState] = useState(() => ({ - open: isOpen, - returnFocus: isOpen ? getFocusedElement() : null, - })) + const { handleCloseAutoFocus } = useOverlayReturnFocus(isOpen) const panelRef = useRef(null) const [panelElement, setPanelElement] = useState(null) const setPanelRef = useCallback((node: HTMLDivElement | null) => { @@ -42,13 +39,6 @@ export function BottomSheet({ setPanelElement(node) }, []) - if (openState.open !== isOpen) { - setOpenState({ - open: isOpen, - returnFocus: isOpen ? getFocusedElement() : openState.returnFocus, - }) - } - const { bind, swipeStyles } = useSwipeDismiss(onClose, { enabled: isOpen && dismissible, threshold: 60, @@ -76,12 +66,6 @@ export function BottomSheet({ panelRef.current?.focus({ preventScroll: true }) } - const handleCloseAutoFocus = (event: Event) => { - if (restoreOverlayFocus(openState.returnFocus, event.currentTarget as Element | null)) { - event.preventDefault() - } - } - if (!isOpen && !shouldRender) return null const sheet = ( diff --git a/frontend/src/components/ui/dialog.tsx b/frontend/src/components/ui/dialog.tsx index 84171f7b..d9323131 100644 --- a/frontend/src/components/ui/dialog.tsx +++ b/frontend/src/components/ui/dialog.tsx @@ -5,25 +5,19 @@ import { X } from "lucide-react" import { cn } from "@/lib/utils" import { useSwipeBack } from '@/hooks/useMobile' import { useVisualViewport } from '@/hooks/useVisualViewport' -import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus' +import { useOverlayReturnFocus } from '@/hooks/useOverlayReturnFocus' const DialogOpenContext = React.createContext(true) -const DialogReturnFocusContext = React.createContext(null) +const DialogCloseAutoFocusContext = React.createContext<((event: Event) => void) | null>(null) function Dialog({ open, ...props }: React.ComponentProps) { - const [openState, setOpenState] = React.useState(() => ({ - open, - returnFocus: open ? getFocusedElement() : null, - })) - if (openState.open !== open) { - setOpenState({ open, returnFocus: open ? getFocusedElement() : openState.returnFocus }) - } + const { handleCloseAutoFocus } = useOverlayReturnFocus(open) return ( - + - + ) } @@ -68,13 +62,11 @@ const DialogContent = React.forwardRef< >(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, keyboardAware, canSwipeBack, onSwipeBack, overlayClassName, style, onCloseAutoFocus, onEscapeKeyDown, ...props }, ref) => { const isMobileFullscreenMode = fullscreen || mobileFullscreen const isDialogOpen = React.useContext(DialogOpenContext) - const returnFocus = React.useContext(DialogReturnFocusContext) + const restoreFocusOnClose = React.useContext(DialogCloseAutoFocusContext) const handleCloseAutoFocus = (event: Event) => { onCloseAutoFocus?.(event) if (event.defaultPrevented) return - if (restoreOverlayFocus(returnFocus, event.currentTarget as Element | null)) { - event.preventDefault() - } + restoreFocusOnClose?.(event) } const handleEscapeKeyDown = (event: KeyboardEvent) => { onEscapeKeyDown?.(event) diff --git a/frontend/src/contexts/EventContext.tsx b/frontend/src/contexts/EventContext.tsx index 1a3be477..e8aefc18 100644 --- a/frontend/src/contexts/EventContext.tsx +++ b/frontend/src/contexts/EventContext.tsx @@ -8,7 +8,6 @@ import { listActiveSessions, listPendingForms, listPendingPermissions, - listProjects, listShells, replyForm, replyPermission, @@ -19,6 +18,7 @@ import { buildServerDirectoryKey, LOCAL_OPENCODE_SERVER_ID, parseServerDirectory import { isLocalOpenCodeServer } from '@/contexts/OpenCodeServerContext' import { useAuth } from '@/hooks/useAuth' import { useOpenCodeServers } from '@/hooks/useOpenCodeServers' +import { remoteProjectsQueryOptions } from '@/hooks/useRemoteProjects' import type { FormAnswer, FormInfo, PermissionRequest, V2Event } from '@opencode-manager/shared/opencode' import type { PermissionResponse, SSHHostKeyRequest, Repo } from '@/api/types' import { showToast } from '@/lib/toast' @@ -399,10 +399,8 @@ export function EventProvider({ children }: { children: React.ReactNode }) { }, []) const remoteProjectQueries = useQueries({ queries: enabledRemoteServers.map((server) => ({ - queryKey: serverScopedKey(['opencode', 'projects'], server.id), - queryFn: () => listProjects(server.id), + ...remoteProjectsQueryOptions(server.id), enabled: isAuthenticated, - retry: false, })), }) const remoteProjectDirectoriesKey = useMemo(() => { diff --git a/frontend/src/hooks/useActiveRemoteDirectory.ts b/frontend/src/hooks/useActiveRemoteDirectory.ts index ab265f85..2beb70fd 100644 --- a/frontend/src/hooks/useActiveRemoteDirectory.ts +++ b/frontend/src/hooks/useActiveRemoteDirectory.ts @@ -1,29 +1,76 @@ +import { useMemo } from 'react' import { useLocation } from 'react-router-dom' -import { useQuery } from '@tanstack/react-query' +import { useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query' +import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas' +import type { SessionInfo } from '@opencode-manager/shared/opencode' +import { findRemoteProjectForDirectory } from '@/api/opencode' import { sessionQueryOptions } from '@/hooks/useOpenCode' -import { parseServerProjectRoute, parseServerSessionRoute } from '@/lib/navigation' +import { useRemoteProjects } from '@/hooks/useRemoteProjects' +import { parseActivePickerSession, parseServerProjectRoute } from '@/lib/navigation' + +export interface ActiveRemoteDirectory { + directory: string | null + isPending: boolean +} + +/** + * Reads the session cached on any directory variant of the shared session key for one server, so a + * page that already loaded the session does not make the picker wait for it again. + */ +function findCachedSession( + queryClient: QueryClient, + sessionID: string, + serverId: string, +): SessionInfo | undefined { + const scopedServerId = serverId === LOCAL_OPENCODE_SERVER_ID ? undefined : serverId + const entries = queryClient.getQueriesData({ + queryKey: ['opencode', 'session', sessionID], + }) + return entries.find(([key]) => key[4] === scopedServerId)?.[1] +} /** * Resolves the linked server directory currently in view: the project route's directory when one - * matches the server, otherwise the directory of the session route it belongs to. + * matches the server, otherwise the canonical project directory that owns the session route's + * directory, falling back to that directory when no project owns it. * * @param serverId Linked server whose active directory is resolved. - * @param options.enabled Whether the session lookup may run; omit for routes that always resolve it. - * @returns The active directory, or null when neither route identifies one. + * @param options.enabled Whether the lookups may run; omit for routes that always resolve them. + * @returns The active directory and whether a session route's directory is still resolving; the + * local server resolves neither. */ export function useActiveRemoteDirectory( serverId: string, { enabled = true }: { enabled?: boolean } = {}, -): string | null { +): ActiveRemoteDirectory { const { pathname, search } = useLocation() + const queryClient = useQueryClient() + const isRemote = serverId !== LOCAL_OPENCODE_SERVER_ID const projectRoute = parseServerProjectRoute(pathname, search) - const sessionRoute = parseServerSessionRoute(pathname) - const sessionID = sessionRoute?.serverId === serverId ? sessionRoute.sessionId : undefined - const { data: session } = useQuery({ + const activeSession = parseActivePickerSession(pathname) + const sessionID = isRemote && activeSession.serverId === serverId + ? activeSession.sessionId + : undefined + const cachedSession = useMemo( + () => (sessionID ? findCachedSession(queryClient, sessionID, serverId) : undefined), + [queryClient, sessionID, serverId], + ) + const sessionQuery = useQuery({ ...sessionQueryOptions(sessionID, undefined, serverId), enabled: Boolean(sessionID) && enabled, + initialData: cachedSession, }) + const { projects } = useRemoteProjects(serverId, { enabled: enabled && isRemote }) - if (projectRoute?.serverId === serverId) return projectRoute.directory - return session?.location.directory ?? null + if (projectRoute?.serverId === serverId) { + return { directory: projectRoute.directory, isPending: false } + } + + const sessionDirectory = sessionQuery.data?.location.directory + return { + directory: sessionDirectory + ? findRemoteProjectForDirectory(projects, sessionDirectory)?.canonical ?? sessionDirectory + : null, + isPending: Boolean(sessionID) && enabled && sessionQuery.isPending, + } } diff --git a/frontend/src/hooks/useContextUsage.test.tsx b/frontend/src/hooks/useContextUsage.test.tsx index c8747c51..2f3110bd 100644 --- a/frontend/src/hooks/useContextUsage.test.tsx +++ b/frontend/src/hooks/useContextUsage.test.tsx @@ -1,5 +1,5 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { renderHook } from '@testing-library/react' +import { act, renderHook } from '@testing-library/react' import type { ReactNode } from 'react' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { @@ -303,4 +303,101 @@ describe('useContextUsage', () => { expect(result.current).toBeNull() }) + + it('keeps the usage object identity across transcript updates that do not change the totals', () => { + const queryClient = createQueryClient() + seedTranscript(queryClient, [ + assistantMessage('assistant-1', { + input: 10, + output: 5, + reasoning: 0, + cache: { read: 1000, write: 500 }, + }), + ]) + + const { result, rerender } = renderHook(() => useContextUsage(SESSION_ID, DIRECTORY), { + wrapper: createWrapper(queryClient), + }) + const firstUsage = result.current + + act(() => { + seedTranscript(queryClient, [ + assistantMessage('assistant-1', { + input: 10, + output: 5, + reasoning: 0, + cache: { read: 1000, write: 500 }, + }), + assistantMessage('assistant-2', undefined), + ]) + }) + rerender() + + expect(result.current).toBe(firstUsage) + expect(result.current?.totalTokens).toBe(1515) + }) + + it('returns a new usage object when the token totals change', () => { + const queryClient = createQueryClient() + seedTranscript(queryClient, [ + assistantMessage('assistant-1', { + input: 10, + output: 5, + reasoning: 0, + cache: { read: 1000, write: 500 }, + }), + ]) + + const { result, rerender } = renderHook(() => useContextUsage(SESSION_ID, DIRECTORY), { + wrapper: createWrapper(queryClient), + }) + const firstUsage = result.current + + act(() => { + seedTranscript(queryClient, [ + assistantMessage('assistant-1', { + input: 10, + output: 5, + reasoning: 0, + cache: { read: 1000, write: 500 }, + }), + assistantMessage('assistant-2', { + input: 20, + output: 10, + reasoning: 0, + cache: { read: 100, write: 50 }, + }), + ]) + }) + rerender() + + expect(result.current).not.toBe(firstUsage) + expect(result.current?.totalTokens).toBe(180) + }) + + it('returns a new usage object when only the measurable context limit changes', () => { + const queryClient = createQueryClient() + seedTranscript(queryClient, [ + assistantMessage('assistant-1', { + input: 10, + output: 5, + reasoning: 0, + cache: { read: 1000, write: 500 }, + }), + ]) + + const { result, rerender } = renderHook(() => useContextUsage(SESSION_ID, DIRECTORY), { + wrapper: createWrapper(queryClient), + }) + const firstUsage = result.current + + mocks.useProviders.mockReturnValue({ + data: { models: [{ providerID: 'anthropic', id: 'claude-sonnet', limit: { context: 1000 } }] }, + }) + rerender() + + expect(result.current).not.toBe(firstUsage) + expect(result.current?.contextLimit).toBe(1000) + expect(result.current?.usagePercentage).toBe(152) + }) }) diff --git a/frontend/src/hooks/useContextUsage.ts b/frontend/src/hooks/useContextUsage.ts index bb7680e1..a63307ee 100644 --- a/frontend/src/hooks/useContextUsage.ts +++ b/frontend/src/hooks/useContextUsage.ts @@ -1,7 +1,7 @@ -import { useMemo } from 'react' +import { useMemo, useRef } from 'react' import { skipToken, useQuery } from '@tanstack/react-query' import { findModelInfo } from '@opencode-manager/shared/opencode' -import type { SessionMessageInfo } from '@opencode-manager/shared/opencode' +import type { ModelInfo, SessionMessageInfo } from '@opencode-manager/shared/opencode' import { useProviders } from '@/hooks/useProviders' import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext' import { sessionTranscriptQueryKey } from '@/lib/queryInvalidation' @@ -25,6 +25,56 @@ function lastAssistantWithUsageIndex(messages: SessionMessageInfo[], start: numb return -1 } +function computeContextUsage( + messages: SessionMessageInfo[], + models: ModelInfo[] | undefined, + revertMessageID: string | undefined, +): ContextUsage | null { + const boundaryIndex = revertMessageID + ? messages.findIndex((message) => message.id === revertMessageID) + : -1 + if (revertMessageID && boundaryIndex === -1) { + return null + } + + const end = boundaryIndex === -1 ? messages.length : boundaryIndex + const compactionIndex = lastCompletedCompactionIndex(messages, end) + const assistantIndex = lastAssistantWithUsageIndex(messages, compactionIndex, end) + const assistant = assistantIndex === -1 ? undefined : messages[assistantIndex] + if (assistant?.type !== 'assistant' || assistant.tokens === undefined) { + return null + } + + const { input, output, reasoning, cache } = assistant.tokens + const totalTokens = input + output + reasoning + cache.read + cache.write + if (totalTokens <= 0) { + return null + } + + const model = models + ? findModelInfo(models, { providerID: assistant.model.providerID, modelID: assistant.model.id }) + : undefined + const contextLimit = model?.limit.context ?? null + const usagePercentage = contextLimit ? Math.round((totalTokens / contextLimit) * 100) : null + + return { totalTokens, usagePercentage, contextLimit } +} + +function hasSameUsage(left: ContextUsage | null, right: ContextUsage | null): boolean { + if (left === null || right === null) return left === right + + return left.totalTokens === right.totalTokens + && left.usagePercentage === right.usagePercentage + && left.contextLimit === right.contextLimit +} + +/** + * Latest assistant context usage for a session. + * + * The transcript cache is rewritten on every streaming flush, so the returned object keeps its + * identity while the measured totals are unchanged. That lets consumers memoize on the reference + * instead of re-rendering for each frame of a reply. + */ export const useContextUsage = ( sessionID: string | undefined, directory?: string, @@ -40,36 +90,16 @@ export const useContextUsage = ( const { data: providersData } = useProviders(directory) const models = providersData?.models + const lastUsageRef = useRef(null) + return useMemo(() => { - const messages = transcriptData?.transcript.messages ?? [] - - const boundaryIndex = revertMessageID - ? messages.findIndex((message) => message.id === revertMessageID) - : -1 - if (revertMessageID && boundaryIndex === -1) { - return null - } - - const end = boundaryIndex === -1 ? messages.length : boundaryIndex - const compactionIndex = lastCompletedCompactionIndex(messages, end) - const assistantIndex = lastAssistantWithUsageIndex(messages, compactionIndex, end) - const assistant = assistantIndex === -1 ? undefined : messages[assistantIndex] - if (assistant?.type !== 'assistant' || assistant.tokens === undefined) { - return null - } - - const { input, output, reasoning, cache } = assistant.tokens - const totalTokens = input + output + reasoning + cache.read + cache.write - if (totalTokens <= 0) { - return null - } - - const model = models - ? findModelInfo(models, { providerID: assistant.model.providerID, modelID: assistant.model.id }) - : undefined - const contextLimit = model?.limit.context ?? null - const usagePercentage = contextLimit ? Math.round((totalTokens / contextLimit) * 100) : null - - return { totalTokens, usagePercentage, contextLimit } + const computed = computeContextUsage( + transcriptData?.transcript.messages ?? [], + models, + revertMessageID, + ) + const usage = hasSameUsage(lastUsageRef.current, computed) ? lastUsageRef.current : computed + lastUsageRef.current = usage + return usage }, [transcriptData, models, revertMessageID]) } diff --git a/frontend/src/hooks/useOverlayReturnFocus.test.tsx b/frontend/src/hooks/useOverlayReturnFocus.test.tsx new file mode 100644 index 00000000..b12b910e --- /dev/null +++ b/frontend/src/hooks/useOverlayReturnFocus.test.tsx @@ -0,0 +1,71 @@ +import { useRef, useState, type ReactNode } from 'react' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, describe, expect, it } from 'vitest' +import { stubMatchMedia } from '@/test/test-utils' +import { useOverlayReturnFocus } from './useOverlayReturnFocus' + +function OverlayHost({ children }: { children?: ReactNode }) { + const [open, setOpen] = useState(false) + const { handleCloseAutoFocus } = useOverlayReturnFocus(open) + const overlayRef = useRef(null) + + const close = () => { + const event = new Event('closeautofocus', { cancelable: true }) + Object.defineProperty(event, 'currentTarget', { value: overlayRef.current }) + handleCloseAutoFocus(event) + setOpen(false) + } + + return ( + <> + + {open && ( +
+ + {children} +
+ )} + + ) +} + +async function openOverlay() { + const opener = screen.getByRole('button', { name: 'open overlay' }) + opener.focus() + await userEvent.setup().click(opener) + return opener +} + +afterEach(() => { + Reflect.deleteProperty(window, 'matchMedia') +}) + +describe('useOverlayReturnFocus', () => { + it('restores focus to the opener when the overlay closes', async () => { + stubMatchMedia(true) + render() + + const opener = await openOverlay() + await userEvent.setup().click(screen.getByRole('button', { name: 'close overlay' })) + + expect(screen.queryByTestId('overlay')).not.toBeInTheDocument() + expect(opener).toHaveFocus() + }) + + it('captures the opener before a child with autoFocus claims focus', async () => { + stubMatchMedia(true) + render( + + + , + ) + + const opener = await openOverlay() + expect(screen.getByLabelText('overlay input')).toHaveFocus() + + await userEvent.setup().click(screen.getByRole('button', { name: 'close overlay' })) + + expect(opener).toHaveFocus() + }) +}) diff --git a/frontend/src/hooks/useOverlayReturnFocus.ts b/frontend/src/hooks/useOverlayReturnFocus.ts new file mode 100644 index 00000000..53d013ea --- /dev/null +++ b/frontend/src/hooks/useOverlayReturnFocus.ts @@ -0,0 +1,38 @@ +import { useCallback, useState } from 'react' +import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus' + +export interface OverlayReturnFocus { + handleCloseAutoFocus: (event: Event) => void +} + +/** + * Captures the element that owns focus when an overlay opens and restores focus to it when the + * overlay reports its close-autofocus event. + * + * The opener is captured during render on the closed-to-open transition, before children with + * `autoFocus` claim focus during commit, and the captured value survives re-renders while the + * overlay stays open. The returned handler prevents the close event's default focus handling only + * when focus was actually moved. + */ +export function useOverlayReturnFocus(open: boolean | undefined): OverlayReturnFocus { + const [openState, setOpenState] = useState(() => ({ + open, + returnFocus: open ? getFocusedElement() : null, + })) + + if (openState.open !== open) { + setOpenState({ open, returnFocus: open ? getFocusedElement() : openState.returnFocus }) + } + + const { returnFocus } = openState + const handleCloseAutoFocus = useCallback( + (event: Event) => { + if (restoreOverlayFocus(returnFocus, event.currentTarget as Element | null)) { + event.preventDefault() + } + }, + [returnFocus], + ) + + return { handleCloseAutoFocus } +} diff --git a/frontend/src/hooks/useRemoteProjects.ts b/frontend/src/hooks/useRemoteProjects.ts index a0f6551e..94929ffd 100644 --- a/frontend/src/hooks/useRemoteProjects.ts +++ b/frontend/src/hooks/useRemoteProjects.ts @@ -18,6 +18,21 @@ export interface UseRemoteProjectsResult { refetch: () => void } +/** + * Builds the query options for one linked server's project list so every reader shares the same + * cache entry and retry policy. + * + * @param serverId Linked server whose projects are listed. + * @returns The query options, without the caller's own enabled gate. + */ +export function remoteProjectsQueryOptions(serverId: string) { + return { + queryKey: serverScopedKey(['opencode', 'projects'], serverId), + queryFn: () => listProjects(serverId), + retry: false, + } +} + /** * Loads the projects of one linked server, most recently active first, while that server is enabled. * @@ -33,10 +48,8 @@ export function useRemoteProjects( const { servers } = useOpenCodeServers({ enabled }) const isServerEnabled = servers.find((server) => server.id === serverId)?.enabled === true const projectsQuery = useQuery({ - queryKey: serverScopedKey(['opencode', 'projects'], serverId), - queryFn: () => listProjects(serverId), + ...remoteProjectsQueryOptions(serverId), enabled: enabled && isServerEnabled, - retry: false, }) const projects = useMemo( diff --git a/frontend/src/hooks/useSessionPickerLocationPrefetch.test.tsx b/frontend/src/hooks/useSessionPickerLocationPrefetch.test.tsx new file mode 100644 index 00000000..f2661c01 --- /dev/null +++ b/frontend/src/hooks/useSessionPickerLocationPrefetch.test.tsx @@ -0,0 +1,130 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, renderHook, waitFor } from '@testing-library/react' +import type { ReactNode } from 'react' +import { MemoryRouter } from 'react-router-dom' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas' +import type { Repo } from '@/api/types' +import { openCodeLocationQueryOptions } from '@/lib/openCodeLocation' +import { useSessionPickerLocationPrefetch } from './useSessionPickerLocationPrefetch' + +const mocks = vi.hoisted(() => ({ + listRepos: vi.fn(), + getOpenCodeLocation: vi.fn(), +})) + +vi.mock('@/api/repos', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + listRepos: mocks.listRepos, + } +}) + +vi.mock('@/api/opencode', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + getOpenCodeLocation: mocks.getOpenCodeLocation, + } +}) + +const REPO_PATH = '/repo' +const LOCATION = { directory: REPO_PATH, projectID: 'proj_1', worktree: REPO_PATH } + +const repo: Repo = { + id: 1, + fullPath: REPO_PATH, + localPath: REPO_PATH, + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: 0, +} + +function createQueryClient() { + return new QueryClient({ defaultOptions: { queries: { retry: false } } }) +} + +function createWrapper(queryClient: QueryClient) { + return function Wrapper({ children }: { children: ReactNode }) { + return ( + + {children} + + ) + } +} + +describe('useSessionPickerLocationPrefetch', () => { + beforeEach(() => { + vi.clearAllMocks() + mocks.getOpenCodeLocation.mockResolvedValue(LOCATION) + }) + + afterEach(() => { + mocks.listRepos.mockReset() + }) + + it('prefetches the location once repos data arrives after mount', async () => { + let resolveRepos: (repos: Repo[]) => void = () => {} + mocks.listRepos.mockImplementation( + () => new Promise((resolve) => { + resolveRepos = resolve + }), + ) + const queryClient = createQueryClient() + + renderHook(() => useSessionPickerLocationPrefetch(), { + wrapper: createWrapper(queryClient), + }) + + expect(mocks.getOpenCodeLocation).not.toHaveBeenCalled() + + await act(async () => { + resolveRepos([repo]) + }) + + await waitFor(() => { + expect(mocks.getOpenCodeLocation).toHaveBeenCalledWith(REPO_PATH, LOCAL_OPENCODE_SERVER_ID) + }) + + const locationQuery = queryClient + .getQueryCache() + .find({ queryKey: openCodeLocationQueryOptions(REPO_PATH, LOCAL_OPENCODE_SERVER_ID).queryKey }) + expect(locationQuery?.observers.length).toBe(0) + }) + + it('prefetches the location when repos data is already cached', async () => { + mocks.listRepos.mockResolvedValue([repo]) + const queryClient = createQueryClient() + queryClient.setQueryData(['repos'], [repo]) + + renderHook(() => useSessionPickerLocationPrefetch(), { + wrapper: createWrapper(queryClient), + }) + + await waitFor(() => { + expect(mocks.getOpenCodeLocation).toHaveBeenCalledWith(REPO_PATH, LOCAL_OPENCODE_SERVER_ID) + }) + }) + + it('does not prefetch when the route has no repo', async () => { + mocks.listRepos.mockResolvedValue([repo]) + const queryClient = createQueryClient() + queryClient.setQueryData(['repos'], [repo]) + + renderHook(() => useSessionPickerLocationPrefetch(), { + wrapper: ({ children }: { children: ReactNode }) => ( + + {children} + + ), + }) + + await waitFor(() => { + expect(mocks.listRepos).toHaveBeenCalled() + }) + + expect(mocks.getOpenCodeLocation).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/src/hooks/useSessionPickerLocationPrefetch.ts b/frontend/src/hooks/useSessionPickerLocationPrefetch.ts index 550dc2ff..f3936704 100644 --- a/frontend/src/hooks/useSessionPickerLocationPrefetch.ts +++ b/frontend/src/hooks/useSessionPickerLocationPrefetch.ts @@ -2,28 +2,27 @@ import { useEffect } from 'react' import { useLocation } from 'react-router-dom' import { useQueryClient } from '@tanstack/react-query' import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas' -import type { Repo } from '@/api/types' import { openCodeLocationQueryOptions } from '@/lib/openCodeLocation' import { parseRepoRoute } from '@/lib/navigation' +import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups' /** * Warms the picker's project location on a local repo route so the first session picker open does - * not serialise the location lookup ahead of the session list. The repo path comes from the already - * cached repos query, and the prefetch never creates a query observer. + * not serialise the location lookup ahead of the session list. The repo path comes from the repos + * query the repo worktrees provider already observes, so a route restored before that query settles + * still prefetches once the repo data arrives. The prefetch never creates a query observer. */ export function useSessionPickerLocationPrefetch(): void { const { pathname } = useLocation() const queryClient = useQueryClient() + const { repos } = useNavigableRepos() const repoId = parseRepoRoute(pathname).repoId + const repoPath = repos.find((repo) => repo.id === repoId)?.fullPath useEffect(() => { - if (repoId === null) return - const repo = queryClient - .getQueryData(['repos']) - ?.find((candidate) => candidate.id === repoId) - if (!repo) return + if (repoPath === undefined) return void queryClient.prefetchQuery( - openCodeLocationQueryOptions(repo.fullPath, LOCAL_OPENCODE_SERVER_ID), + openCodeLocationQueryOptions(repoPath, LOCAL_OPENCODE_SERVER_ID), ) - }, [queryClient, repoId]) + }, [queryClient, repoPath]) } diff --git a/frontend/src/hooks/useSessionPickerNavigation.ts b/frontend/src/hooks/useSessionPickerNavigation.ts index 5e0bafe8..31a2ecb8 100644 --- a/frontend/src/hooks/useSessionPickerNavigation.ts +++ b/frontend/src/hooks/useSessionPickerNavigation.ts @@ -5,9 +5,10 @@ import type { Repo, Session } from '@/api/types' import { getRepoPath, getServerSessionPath, + getSessionListPath, getSessionPath, + parseActivePickerSession, parseRepoRoute, - parseServerSessionRoute, withQueryParam, } from '@/lib/navigation' @@ -18,7 +19,7 @@ export interface SessionPickerNavigationOptions { */ mode: 'push' | 'replace' onClose: () => void - /** Replaces the default delete behaviour of opening the current repo page. */ + /** Replaces the default delete behaviour of returning to the current repo's session list. */ onDeleteActiveSession?: () => void } @@ -46,12 +47,11 @@ export function useSessionPickerNavigation({ }: SessionPickerNavigationOptions): SessionPickerNavigation { const navigate = useNavigate() const { pathname, search } = useLocation() - const repoRoute = parseRepoRoute(pathname) - const serverSessionRoute = parseServerSessionRoute(pathname) - const currentRepoId = repoRoute.repoId - const activeSessionID = repoRoute.sessionId ?? serverSessionRoute?.sessionId ?? undefined - const activeServerId = repoRoute.sessionId ? LOCAL_OPENCODE_SERVER_ID : serverSessionRoute?.serverId - const isAssistantSession = new URLSearchParams(search).get('assistant') === '1' + const currentRepoId = parseRepoRoute(pathname).repoId + const { sessionId: activeSessionID, serverId: activeServerId } = parseActivePickerSession(pathname) + const searchParams = new URLSearchParams(search) + const isAssistantSession = searchParams.get('assistant') === '1' + const repoTab = searchParams.get('repoTab') ?? undefined const open = useCallback( (path: string) => { @@ -98,8 +98,8 @@ export function useSessionPickerNavigation({ onClose() return } - open(getRepoPath(currentRepoId)) - }, [currentRepoId, deleteActiveSessionOverride, onClose, open]) + open(getSessionListPath(currentRepoId, isAssistantSession, repoTab)) + }, [currentRepoId, deleteActiveSessionOverride, isAssistantSession, onClose, open, repoTab]) const onSelectRepo = useCallback( (repo: Repo) => { diff --git a/frontend/src/hooks/useSessionPickerRouteScope.test.tsx b/frontend/src/hooks/useSessionPickerRouteScope.test.tsx new file mode 100644 index 00000000..232535fe --- /dev/null +++ b/frontend/src/hooks/useSessionPickerRouteScope.test.tsx @@ -0,0 +1,126 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { ReactNode } from 'react' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { renderHook, waitFor } from '@testing-library/react' +import { MemoryRouter } from 'react-router-dom' +import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas' +import { useSidebarServerStore } from '@/stores/sidebarServerStore' +import { useSessionPickerRouteScope } from './useSessionPickerRouteScope' + +const mocks = vi.hoisted(() => ({ + getSession: vi.fn(), + listProjects: vi.fn(), +})) + +vi.mock('@/api/opencode', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, getSession: mocks.getSession, listProjects: mocks.listProjects } +}) + +vi.mock('@/hooks/useOpenCodeServers', () => ({ + useOpenCodeServers: () => ({ + servers: [{ id: 'srv_kitchen', name: 'Kitchen', enabled: true }], + isLoading: false, + }), +})) + +vi.mock('@/hooks/useSidebarRepoGroups', () => ({ + useNavigableRepos: () => ({ repos: [], isLoading: false, refetch: vi.fn() }), +})) + +function renderScope(entry: string, seed?: (queryClient: QueryClient) => void) { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + seed?.(queryClient) + const wrapper = ({ children }: { children: ReactNode }) => ( + + {children} + + ) + return renderHook(() => useSessionPickerRouteScope(true), { wrapper }) +} + +const kitchenProject = { + id: 'p1', + name: 'App', + canonical: '/home/me/app', + time: { created: 1, updated: 2 }, + sandboxes: [], +} + +describe('useSessionPickerRouteScope', () => { + beforeEach(() => { + vi.clearAllMocks() + useSidebarServerStore.setState({ serverId: 'srv_kitchen' }) + mocks.listProjects.mockResolvedValue([]) + }) + + it('resolves a session subdirectory to the canonical directory of its project', async () => { + mocks.getSession.mockResolvedValue({ + id: 'ses_remote', + location: { directory: '/home/me/app/packages/web' }, + }) + mocks.listProjects.mockResolvedValue([kitchenProject]) + + const { result } = renderScope('/servers/srv_kitchen/sessions/ses_remote') + + await waitFor(() => expect(result.current.remote?.projectDirectory).toBe('/home/me/app')) + expect(result.current.remote?.isPending).toBe(false) + expect(result.current.remote?.serverName).toBe('Kitchen') + expect(result.current.activeSessionID).toBe('ses_remote') + }) + + it('falls back to the session directory when no project owns it', async () => { + mocks.getSession.mockResolvedValue({ + id: 'ses_remote', + location: { directory: '/home/me/other' }, + }) + + const { result } = renderScope('/servers/srv_kitchen/sessions/ses_remote') + + await waitFor(() => expect(result.current.remote?.projectDirectory).toBe('/home/me/other')) + expect(result.current.remote?.isPending).toBe(false) + }) + + it('reports the scope as pending while the session directory resolves', async () => { + mocks.getSession.mockReturnValue(new Promise(() => undefined)) + + const { result } = renderScope('/servers/srv_kitchen/sessions/ses_remote') + + await waitFor(() => expect(result.current.remote?.isPending).toBe(true)) + expect(result.current.remote?.projectDirectory).toBeUndefined() + }) + + it('reuses the session the open page already loaded', async () => { + mocks.getSession.mockReturnValue(new Promise(() => undefined)) + mocks.listProjects.mockResolvedValue([kitchenProject]) + + const { result } = renderScope('/servers/srv_kitchen/sessions/ses_remote', (queryClient) => { + queryClient.setQueryData( + ['opencode', 'session', 'ses_remote', '/home/me/app/packages/web', 'srv_kitchen'], + { id: 'ses_remote', location: { directory: '/home/me/app/packages/web' } }, + ) + }) + + await waitFor(() => expect(result.current.remote?.projectDirectory).toBe('/home/me/app')) + expect(result.current.remote?.isPending).toBe(false) + expect(mocks.getSession).not.toHaveBeenCalled() + }) + + it('scopes to the whole server on a route without a session', () => { + const { result } = renderScope('/') + + expect(result.current.remote?.projectDirectory).toBeUndefined() + expect(result.current.remote?.isPending).toBe(false) + expect(result.current.activeSessionID).toBeUndefined() + }) + + it('resolves no linked-server scope for the local server', () => { + useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID }) + + const { result } = renderScope('/repos/5/sessions/ses_local') + + expect(result.current.remote).toBeUndefined() + expect(mocks.getSession).not.toHaveBeenCalled() + expect(mocks.listProjects).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/src/hooks/useSessionPickerRouteScope.ts b/frontend/src/hooks/useSessionPickerRouteScope.ts index 24dc2a66..81dc0726 100644 --- a/frontend/src/hooks/useSessionPickerRouteScope.ts +++ b/frontend/src/hooks/useSessionPickerRouteScope.ts @@ -2,7 +2,7 @@ import { useLocation } from 'react-router-dom' import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas' import type { Repo } from '@/api/types' import type { RemotePickerScope } from '@/components/session/SessionPickerDialog' -import { parseRepoRoute, parseServerSessionRoute } from '@/lib/navigation' +import { parseActivePickerSession, parseRepoRoute } from '@/lib/navigation' import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups' import { useOpenCodeServers } from '@/hooks/useOpenCodeServers' import { useSidebarServerSelection } from '@/hooks/useSidebarServerSelection' @@ -11,7 +11,6 @@ import { useActiveRemoteDirectory } from '@/hooks/useActiveRemoteDirectory' export interface SessionPickerRouteScope { currentRepo: Repo | undefined activeSessionID: string | undefined - activeServerId: string | undefined remote: RemotePickerScope | undefined } @@ -24,25 +23,23 @@ export function useSessionPickerRouteScope(enabled: boolean): SessionPickerRoute const isRemote = selectedServerId !== LOCAL_OPENCODE_SERVER_ID const repoRoute = parseRepoRoute(pathname) - const serverSessionRoute = parseServerSessionRoute(pathname) const currentRepo = isRemote || repoRoute.repoId === null ? undefined : repos.find((candidate) => candidate.id === repoRoute.repoId) - const activeSessionID = repoRoute.sessionId ?? serverSessionRoute?.sessionId ?? undefined - const activeServerId = repoRoute.sessionId ? LOCAL_OPENCODE_SERVER_ID : serverSessionRoute?.serverId + const activeSessionID = parseActivePickerSession(pathname).sessionId if (!isRemote) { - return { currentRepo, activeSessionID, activeServerId, remote: undefined } + return { currentRepo, activeSessionID, remote: undefined } } return { currentRepo, activeSessionID, - activeServerId, remote: { serverId: selectedServerId, serverName: servers.find((server) => server.id === selectedServerId)?.name, - projectDirectory: activeRemoteDirectory ?? undefined, + projectDirectory: activeRemoteDirectory.directory ?? undefined, + isPending: activeRemoteDirectory.isPending, }, } } diff --git a/frontend/src/lib/navigation.test.ts b/frontend/src/lib/navigation.test.ts index 1cb0940a..dc0d64c2 100644 --- a/frontend/src/lib/navigation.test.ts +++ b/frontend/src/lib/navigation.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerProjectPath, getServerSessionPath, getSessionPath, isSessionDetailRoute, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from './navigation'; +import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerProjectPath, getServerSessionPath, getSessionPath, isSessionDetailRoute, parseActivePickerSession, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from './navigation'; +import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'; describe('getAssistantPath', () => { it('returns /assistant', () => { @@ -191,6 +192,27 @@ describe('parseServerSessionRoute', () => { }); }); +describe('parseActivePickerSession', () => { + it('reads a local session route on the local server', () => { + expect(parseActivePickerSession('/repos/5/sessions/ses_1')).toEqual({ + sessionId: 'ses_1', + serverId: LOCAL_OPENCODE_SERVER_ID, + }); + }); + + it('reads a linked-server session route on its own server', () => { + expect(parseActivePickerSession('/servers/srv_kitchen/sessions/ses_1')).toEqual({ + sessionId: 'ses_1', + serverId: 'srv_kitchen', + }); + }); + + it('returns no session outside a session route', () => { + expect(parseActivePickerSession('/repos/5')).toEqual({}); + expect(parseActivePickerSession('/servers/srv_kitchen/projects')).toEqual({}); + }); +}); + describe('return target helpers', () => { it('adds encoded returnTo params for internal paths', () => { expect(getPathWithReturnTo('/repos/5/schedules', '/repos/5/sessions/abc?assistant=1')).toBe( diff --git a/frontend/src/lib/navigation.ts b/frontend/src/lib/navigation.ts index 20aeb54f..9226190c 100644 --- a/frontend/src/lib/navigation.ts +++ b/frontend/src/lib/navigation.ts @@ -65,6 +65,22 @@ export function parseServerSessionRoute(pathname: string): { serverId: string; s return { serverId, sessionId }; } +/** + * Reads the session route in view, whether it belongs to the local server or a linked one. + * + * @param pathname Pathname of the location to read. + * @returns The routed session and its server; both are omitted when the location is not a session route. + */ +export function parseActivePickerSession(pathname: string): { sessionId?: string; serverId?: string } { + const repoRoute = parseRepoRoute(pathname); + if (repoRoute.sessionId) { + return { sessionId: repoRoute.sessionId, serverId: LOCAL_OPENCODE_SERVER_ID }; + } + const serverSessionRoute = parseServerSessionRoute(pathname); + if (!serverSessionRoute) return {}; + return { sessionId: serverSessionRoute.sessionId, serverId: serverSessionRoute.serverId }; +} + export function isSessionDetailRoute(pathname: string): boolean { const normalizedPathname = pathname.replace(/\/+$/, ''); return /^\/repos\/[^/]+\/sessions\/[^/]+$/.test(normalizedPathname) || parseServerSessionRoute(normalizedPathname) !== null; diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 9c0ba24a..8ee72d4b 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -49,7 +49,7 @@ import { ProjectActionsMenu } from "@/components/repo/ProjectActionsMenu"; import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog"; import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"; import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog"; -import { compactSession, forkSession, listSessionMessages, remoteProjectName } from "@/api/opencode"; +import { compactSession, findRemoteProjectForDirectory, forkSession, listSessionMessages, remoteProjectName } from "@/api/opencode"; import { useOpenCodeServerId, isLocalOpenCodeServer } from "@/contexts/OpenCodeServerContext"; import { useRemoteProjects } from "@/hooks/useRemoteProjects"; import { useSwipeNavigation } from "@/contexts/SwipeNavigationContext"; @@ -221,9 +221,7 @@ export function SessionDetail() { const remoteProject = useMemo(() => { if (!isRemoteServer || !sessionDirectory) return undefined; - return remoteProjects.find( - (entry) => sessionDirectory === entry.canonical || sessionDirectory.startsWith(`${entry.canonical}/`), - ); + return findRemoteProjectForDirectory(remoteProjects, sessionDirectory); }, [isRemoteServer, remoteProjects, sessionDirectory]); const remoteProjectDirectory = isRemoteServer && sessionDirectory @@ -555,7 +553,7 @@ export function SessionDetail() { const pickerNavigation = useSessionPickerNavigation({ mode: 'push', onClose: () => setSessionsDialogOpen(false), - onDeleteActiveSession: handleCloseSession, + onDeleteActiveSession: isRemoteServer ? handleCloseSession : undefined, }) const handleOpenModelDialog = useCallback(() => { @@ -1051,7 +1049,12 @@ export function SessionDetail() { activeSessionID={sessionId || undefined} remote={ isRemoteServer - ? { serverId, serverName: linkedServer?.name, projectDirectory: remoteProjectDirectory } + ? { + serverId, + serverName: linkedServer?.name, + projectDirectory: remoteProjectDirectory, + isPending: sessionLoading, + } : undefined } {...pickerNavigation} diff --git a/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx b/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx index 053bfd6a..3079727d 100644 --- a/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx @@ -540,6 +540,7 @@ describe('SessionDetail remote server mode', () => { serverId: 'srv_kitchen', serverName: 'Kitchen', projectDirectory: '/home/me/app', + isPending: false, }, }), )