fix(activity): surface worktree sessions in active work, the sidebar and repo badges

- Resolve sessions in repo worktrees to the owning repo in the activity list; show the worktree branch and open the Workspaces tab
- Look up worktrees only for unmatched sessions in the window or under an active root, and hold the loading state until it settles
- Show schedule-worktree sessions only while running or needing input
- Light repo badges for worktree sessions through one app-wide worktree lookup
- List worktree sessions under the expanded repo in the sidebar
- Subscribe the event stream to active session directories so worktree permissions and forms arrive
- Keep the worktree tab when navigating from the desktop Activity panel
- Remove the braille spinner's always-dim bottom row
This commit is contained in:
Chris Scott committed 2026-10-16 20:36:56 +00:00
1 parent 1d31286904
commit bfbbbf08ef
23 files changed
+932 -81

No files matched your search

+22 -19
View File
@@ -26,6 +26,7 @@ import { ThemeProvider, useThemeMode } from './contexts/ThemeContext'
import { AuthProvider } from './contexts/AuthContext'
import { KeyboardShortcutsProvider } from './contexts/KeyboardShortcutsContext'
import { EventProvider, usePermissions, useEventContext } from '@/contexts/EventContext'
import { RepoWorktreesProvider } from '@/contexts/RepoWorktreesContext'
import { SwipeNavigationProvider, useSwipeNavigation } from '@/contexts/SwipeNavigationContext'
import { PermissionRequestDialog } from './components/session/PermissionRequestDialog'
import { SSHHostKeyDialog } from './components/ssh/SSHHostKeyDialog'
@@ -208,26 +209,28 @@ function AppShell() {
<ThemeProvider>
<AuthProvider>
<EventProvider>
<KeyboardShortcutsProvider>
<GlobalShortcuts />
<div className="flex h-dvh w-full min-w-0 flex-col">
<PwaUpdatePrompt />
<div ref={rootRef} className="flex flex-1 min-h-0 w-full min-w-0">
<DesktopSidebar />
<main className="flex-1 min-w-0 min-h-0 flex flex-col">
<Outlet />
</main>
<RepoWorktreesProvider>
<KeyboardShortcutsProvider>
<GlobalShortcuts />
<div className="flex h-dvh w-full min-w-0 flex-col">
<PwaUpdatePrompt />
<div ref={rootRef} className="flex flex-1 min-h-0 w-full min-w-0">
<DesktopSidebar />
<main className="flex-1 min-w-0 min-h-0 flex flex-col">
<Outlet />
</main>
</div>
</div>
</div>
<MobileTabBar />
<MobileSheetHost />
<PermissionDialogWrapper />
<SSHHostKeyDialogWrapper />
<SettingsDialog />
<HealthMonitor />
<VersionNotifier />
<ThemedToaster />
</KeyboardShortcutsProvider>
<MobileTabBar />
<MobileSheetHost />
<PermissionDialogWrapper />
<SSHHostKeyDialogWrapper />
<SettingsDialog />
<HealthMonitor />
<VersionNotifier />
<ThemedToaster />
</KeyboardShortcutsProvider>
</RepoWorktreesProvider>
</EventProvider>
</AuthProvider>
</ThemeProvider>
@@ -144,6 +144,23 @@ describe('ActivityList', () => {
expect(onNavigate).toHaveBeenCalledWith(item)
})
it('labels a worktree session with its worktree branch', () => {
setGroups({
recent: [
createItem({
state: 'recent',
session: createSession('c1', 'Worktree'),
repo: createRepo(3, 'Gamma'),
worktreeBranch: 'feature/wt',
}),
],
})
renderList()
expect(screen.getByRole('button', { name: /Worktree/ })).toHaveTextContent('Gamma · feature/wt')
})
it('marks the currently open session with aria-current', () => {
setGroups({
recent: [
@@ -63,7 +63,7 @@ interface ActivityRowProps {
}
function ActivityRow({ item, isCurrent, onSelect }: ActivityRowProps) {
const branch = getRepoBranchLabel(item.repo)
const branch = item.worktreeBranch ?? getRepoBranchLabel(item.repo)
const repoLine = branch
? `${getRepoDisplayName(item.repo)} · ${branch}`
: getRepoDisplayName(item.repo)
@@ -25,6 +25,7 @@ type SessionPinFixture = { sessionId: string; directory: string; pinnedAt: numbe
const {
listReposMock,
getRepoSiblingsMock,
sessionsData,
sessionsHookCalls,
createSessionCalls,
@@ -37,6 +38,7 @@ const {
searchError,
} = vi.hoisted(() => ({
listReposMock: vi.fn(),
getRepoSiblingsMock: vi.fn(),
sessionsData: [] as SessionFixture[],
sessionsHookCalls: [] as SessionsHookCall[],
createSessionCalls: [] as Array<{ directory?: string; vars?: unknown }>,
@@ -51,7 +53,7 @@ const {
vi.mock('@/api/repos', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/repos')>()
return { ...actual, listRepos: listReposMock }
return { ...actual, listRepos: listReposMock, getRepoSiblings: getRepoSiblingsMock }
})
vi.mock('@/api/opencode', async (importOriginal) => {
@@ -156,6 +158,8 @@ describe('DesktopSessionTree', () => {
beforeEach(() => {
listReposMock.mockReset()
listReposMock.mockResolvedValue([repoA, repoB, repoC])
getRepoSiblingsMock.mockReset()
getRepoSiblingsMock.mockResolvedValue([])
sessionsData.splice(
0,
sessionsData.length,
@@ -197,6 +201,18 @@ describe('DesktopSessionTree', () => {
expect(fetchedDirectories()).toEqual(new Set(['/repos/a']))
})
it('shows a worktree session under its repo with the worktree branch tag', async () => {
getRepoSiblingsMock.mockResolvedValue([
{ fullPath: '/repos/a/.worktrees/feat', currentBranch: 'feat/x', worktreeSource: 'git' },
])
sessionsData.push(createSession('w1', '/repos/a/.worktrees/feat', Date.now() - 1000))
render(<DesktopSessionTree />, { wrapper: createWrapper(['/repos/1']) })
const row = await screen.findByRole('button', { name: /^Session w1/ })
expect(row).toHaveTextContent('feat/x')
})
it('opens nothing outside a repo', async () => {
render(<DesktopSessionTree />, { wrapper: createWrapper(['/']) })
@@ -3,7 +3,7 @@ import { beforeEach, describe, it, expect, vi } from 'vitest'
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { RepoQuickSwitchSheet } from './RepoQuickSwitchSheet'
import { listRepos } from '@/api/repos'
import { getRepoSiblings, listRepos } from '@/api/repos'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import type { ActiveWorkItem } from '@/lib/activeWork'
@@ -167,6 +167,7 @@ function MobileSheetHarness() {
describe('RepoQuickSwitchSheet', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(getRepoSiblings).mockResolvedValue([])
sessionsData.splice(0, sessionsData.length)
sessionsHookCalls.splice(0, sessionsHookCalls.length)
permissionSessions.current.clear()
@@ -5,7 +5,9 @@ import { SessionStatusIndicator } from '@/components/ui/session-status-indicator
import { RepoActivityIndicator } from '@/components/activity/RepoActivityIndicator'
import { useForms, usePermissions } from '@/contexts/EventContext'
import { useCreateSession } from '@/hooks/useOpenCode'
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, getSessionPath } from '@/lib/navigation'
import {
@@ -118,13 +120,14 @@ interface SessionNavRowProps {
export function SessionNavRow({ item, isCurrent, onSelect, repoLabel }: SessionNavRowProps) {
const { hasForSession: hasPermission } = usePermissions()
const { hasForSession: hasForm } = useForms()
const branchLabel = item.worktreeBranch ?? item.branchLabel
return (
<button
type="button"
onClick={() => onSelect(item.path)}
aria-current={isCurrent ? 'page' : undefined}
title={item.branchLabel ? `${item.repoLabel} · ${item.branchLabel}` : item.repoLabel}
title={branchLabel ? `${item.repoLabel} · ${branchLabel}` : item.repoLabel}
className={cn(
'flex h-9 w-full items-center gap-2 pl-4 pr-3.5 text-left text-[13.5px] text-foreground hover:bg-accent/50',
isCurrent && 'bg-primary/25 font-semibold',
@@ -137,6 +140,11 @@ export function SessionNavRow({ item, isCurrent, onSelect, repoLabel }: SessionN
{repoLabel && (
<span className="max-w-24 shrink-0 truncate text-xs text-highlight">{repoLabel}</span>
)}
{item.worktreeBranch && (
<span className="max-w-24 shrink-0 truncate font-mono text-[11px] text-primary">
{item.worktreeBranch}
</span>
)}
<SessionStatusIndicator sessionID={item.session.id} size="sm" />
{hasPermission(item.session.id) && (
<Bell className="h-3 w-3 shrink-0 text-highlight" aria-label="Pending permission" />
@@ -186,9 +194,32 @@ interface RepoSessionListProps {
}
function RepoSessionList({ repo, onSelectSession }: RepoSessionListProps) {
const siblings = useRepoSiblings(repo.isWorktree ? undefined : repo.id)
const worktrees = useMemo(
() =>
repo.isWorktree
? undefined
: buildWorktreeActivity([repo], [{ data: siblings.data }]).filter(
(worktree) => !worktree.isSchedule,
),
[repo, siblings.data],
)
if (siblings.isLoading) return <SessionNavStatus>Loading sessions...</SessionNavStatus>
return <RepoSessionListItems repo={repo} worktrees={worktrees} onSelectSession={onSelectSession} />
}
interface RepoSessionListItemsProps {
repo: Repo
worktrees?: ActiveWorktree[]
onSelectSession: (path: string) => void
}
function RepoSessionListItems({ repo, worktrees, onSelectSession }: RepoSessionListItemsProps) {
const location = useLocation()
const repos = useMemo(() => [repo], [repo])
const { groups, isLoading, isError, hasMore } = useSidebarRepoGroups({ repos })
const { groups, isLoading, isError, hasMore } = useSidebarRepoGroups({ repos, worktrees })
const items = groups[0]?.items ?? []
if (isLoading) return <SessionNavStatus>Loading sessions...</SessionNavStatus>
@@ -355,6 +355,24 @@ describe('ToolSidePanel', () => {
expect(search().get('panel')).toBe('activity')
})
it('keeps a worktree session tab when navigating from the Activity panel', async () => {
const user = userEvent.setup()
setActivityGroups([
{
...createActivityItem('wt', 'Worktree Session', 2, 'Beta'),
path: '/repos/2/sessions/wt?repoTab=workspaces',
},
])
renderAt('')
await user.click(screen.getByRole('button', { name: 'Activity' }))
await user.click(await screen.findByRole('button', { name: /Worktree Session/ }))
await waitFor(() => expect(screen.getByTestId('pathname').textContent).toBe('/repos/2/sessions/wt'))
expect(search().get('repoTab')).toBe('workspaces')
expect(search().get('panel')).toBe('activity')
})
it('shows an Activity count pill and extends the accessible name', () => {
activityMocks.useActiveWorkCounts.mockReturnValue({ needsInput: 1, running: 2 })
renderAt('')
@@ -25,6 +25,7 @@ import { isPanelTool, type ToolPanelState, type PanelTool } from '@/hooks/useToo
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { ActivityList } from '@/components/activity/ActivityList'
import { ActivityCountPill } from '@/components/activity/ActivityCountPill'
import { withQueryParam } from '@/lib/navigation'
import { useActiveWorkCounts, useActivityWindowMinutes } from '@/hooks/useActiveWork'
import { formatActivityWindow } from '@/lib/activeWork'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
@@ -52,7 +53,7 @@ function ActivityPanelBody() {
<div className="min-h-0 flex-1 overflow-y-auto">
<ActivityList
minutes={minutes}
onNavigate={(item) => navigate({ pathname: item.path, search: '?panel=activity' })}
onNavigate={(item) => navigate(withQueryParam(item.path, 'panel', 'activity'))}
/>
</div>
)
@@ -191,6 +191,60 @@ describe('buildSidebarRepoGroups', () => {
expect(item.path).toBe('/repos/3/sessions/w1')
})
it('groups a session in a worktree of a repo under that repo with the worktree branch', () => {
const worktree = {
directory: '/repos/a/.worktrees/feat',
ownerRepo: repoA,
branch: 'feat/x',
isSchedule: false,
}
const sessions = [createSession('w1', atStartOfDay(2000), '/repos/a/.worktrees/feat')]
const groups = buildSidebarRepoGroups({
repos: [repoA],
sessions,
pinnedKeys: new Set(),
now: NOW,
worktrees: [worktree],
})
expect(groups).toHaveLength(1)
const item = groups[0].items[0]
expect(item.session.id).toBe('w1')
expect(item.repoId).toBe(1)
expect(item.worktreeBranch).toBe('feat/x')
expect(item.path).toBe('/repos/1/sessions/w1?repoTab=workspaces')
})
it('matches a worktree session directory with a trailing slash', () => {
const worktree = {
directory: '/repos/a/.worktrees/feat',
ownerRepo: repoA,
branch: 'feat/x',
isSchedule: false,
}
const sessions = [createSession('w1', atStartOfDay(2000), '/repos/a/.worktrees/feat/')]
const groups = buildSidebarRepoGroups({
repos: [repoA],
sessions,
pinnedKeys: new Set(),
now: NOW,
worktrees: [worktree],
})
expect(groups[0].items.map((item) => item.session.id)).toEqual(['w1'])
expect(groups[0].items[0].worktreeBranch).toBe('feat/x')
})
it('excludes a worktree session when no worktrees are provided', () => {
const sessions = [createSession('w1', atStartOfDay(2000), '/repos/a/.worktrees/feat')]
const groups = buildSidebarRepoGroups({ repos: [repoA], sessions, pinnedKeys: new Set(), now: NOW })
expect(groups[0].items).toEqual([])
})
it('labels assistant sessions and links them in assistant mode', () => {
const assistant = createRepo({ id: 0, fullPath: '/assistant', localPath: 'assistant' })
const sessions = [createSession('s1', atStartOfDay(1000), '/assistant')]
@@ -4,6 +4,7 @@ import { getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
import { getSessionKey } from '@/lib/sessionKey'
import { getSessionPath, isAssistantPath, parseRepoRoute } from '@/lib/navigation'
import { partitionSessions, selectRootSessions } from '@/components/session/session-partition'
import type { ActiveWorktree } from '@/lib/activeWork'
export const SIDEBAR_SESSIONS_PER_REPO = 10
@@ -30,6 +31,8 @@ export interface SidebarSessionItem {
repoId: number
repoLabel: string
branchLabel: string | null
/** Branch of the worktree the session runs in, when it runs in a worktree of the group's repo. */
worktreeBranch?: string | null
isWorktree: boolean
isPinned: boolean
path: string
@@ -88,16 +91,33 @@ export function buildSidebarRepoGroups(input: {
sessions: Session[]
pinnedKeys: ReadonlySet<string>
now: number
worktrees?: ReadonlyArray<ActiveWorktree>
}): SidebarRepoGroup[] {
const { repos, sessions, pinnedKeys, now } = input
const { repos, sessions, pinnedKeys, now, worktrees } = input
const keyFn = getSessionKey
const repoByDirectory = buildRepoByDirectory(repos)
const roots = selectRootSessions(sessions, {
directories: new Set(repos.map((repo) => repo.fullPath)),
keyFn,
}).flatMap((session) => {
const worktreeByDirectory = new Map<string, ActiveWorktree>()
for (const worktree of worktrees ?? []) {
worktreeByDirectory.set(worktree.directory, worktree)
}
const directories = new Set(repos.map((repo) => repo.fullPath))
for (const worktree of worktrees ?? []) {
directories.add(worktree.directory)
}
for (const session of sessions) {
const directory = normalizeDirectory(session.location.directory)
if (directory && worktreeByDirectory.has(directory)) {
directories.add(session.location.directory)
}
}
const roots = selectRootSessions(sessions, { directories, keyFn }).flatMap((session) => {
if (session.time.archived) return []
const directory = normalizeDirectory(session.location.directory)
const worktree = directory ? worktreeByDirectory.get(directory) : undefined
if (worktree) return [{ session, repo: worktree.ownerRepo }]
const repo = repoByDirectory.get(session.location.directory)
if (!repo) return []
return [{ session, repo }]
@@ -115,15 +135,20 @@ export function buildSidebarRepoGroups(input: {
const createItem = (session: Session, repo: Repo): SidebarSessionItem => {
const key = keyFn(session)
const directory = normalizeDirectory(session.location.directory)
const worktree = directory ? worktreeByDirectory.get(directory) : undefined
return {
key,
session,
repoId: repo.id,
repoLabel: getRepoDisplayName(repo),
branchLabel: getRepoBranchLabel(repo),
worktreeBranch: worktree ? worktree.branch : null,
isWorktree: Boolean(repo.isWorktree),
isPinned: pinnedKeys.has(key),
path: getSessionPath(repo.id, session.id),
path: worktree
? getSessionPath(repo.id, session.id, { repoTab: 'workspaces' })
: getSessionPath(repo.id, session.id),
}
}
@@ -16,11 +16,11 @@ const litIndexesFor = (frame: string) =>
describe('brailleDots', () => {
it('lights dots 1, 2 and 4 for the first frame', () => {
expect(brailleDots('⠋')).toEqual([true, true, false, true, false, false, false, false])
expect(brailleDots('⠋')).toEqual([true, true, false, true, false, false])
})
it('lights dots 1 through 4 for the last frame', () => {
expect(brailleDots('⠏')).toEqual([true, true, true, true, false, false, false, false])
expect(brailleDots('⠏')).toEqual([true, true, true, true, false, false])
})
})
@@ -30,10 +30,10 @@ describe('ActivitySpinner', () => {
vi.useRealTimers()
})
it('renders eight dots with the first frame lit and hidden from assistive technology', () => {
it('renders six dots with the first frame lit and hidden from assistive technology', () => {
const { container } = render(<ActivitySpinner />)
expect(circles(container)).toHaveLength(8)
expect(circles(container)).toHaveLength(6)
expect(litIndexes(container)).toEqual(litIndexesFor(SPINNER_FRAMES[0]))
expect(container.querySelector('svg')).toHaveAttribute('aria-hidden', 'true')
})
@@ -79,7 +79,7 @@ describe('ActivitySpinner', () => {
r: Number(circle.getAttribute('r')),
}))
expect(dots).toHaveLength(8)
expect(dots).toHaveLength(6)
for (const dot of dots) {
expect(dot.cx - dot.r).toBeGreaterThan(0)
@@ -13,19 +13,17 @@ const DOT_GRID: ReadonlyArray<readonly [number, number]> = [
[1, 0],
[1, 1],
[1, 2],
[0, 3],
[1, 3],
]
const COLUMN_X = [2.25, 6.75] as const
const ROW_Y = [2.25, 6, 9.75, 13.5] as const
const ROW_Y = [4.25, 8, 11.75] as const
const DOT_RADIUS = 1.6
const LIT_DOT_OPACITY = 1
const UNLIT_DOT_OPACITY = 0.25
/**
* Decodes one braille frame into its eight dot positions, ordered by braille dot numbering:
* Decodes one braille frame into its six dot positions, ordered by braille dot numbering:
* dot1, dot2 and dot3 are the left column top-to-bottom, dot4, dot5 and dot6 the right column
* top-to-bottom, and dot7 and dot8 the bottom-left and bottom-right cells.
* top-to-bottom.
*/
export function brailleDots(frame: string): boolean[] {
const bits = (frame.codePointAt(0) ?? BRAILLE_BASE) - BRAILLE_BASE
@@ -2550,4 +2550,43 @@ describe('EventProvider permissions and forms', () => {
expect(screen.getByTestId('permission-count').textContent).toBe('1')
expect(screen.getByTestId('count').textContent).toBe('1')
})
it('subscribes the directories of active sessions outside the repo directories', async () => {
mocks.listRepos.mockResolvedValue([{ id: 123, fullPath: '/repo' }])
const updateDirectories = vi.fn()
mocks.subscribeGlobalMonitor.mockReturnValue({
dispose: vi.fn(),
updateDirectories,
reconnect: vi.fn(),
reportVisibility: vi.fn(),
})
render(<Harness />, { wrapper: createWrapper() })
await waitFor(() => {
expect(updateDirectories).toHaveBeenCalledWith(['/repo'])
})
act(() => {
useSessionStatus.getState().setSessionDirectory('session-worktree', '/repo/.worktrees/feature')
useSessionStatus.getState().setStatus('session-worktree', { type: 'busy' })
})
await waitFor(() => {
expect(updateDirectories).toHaveBeenCalledWith(
expect.arrayContaining(['/repo', '/repo/.worktrees/feature']),
)
})
act(() => {
useSessionStatus.getState().setStatus('session-worktree', { type: 'idle' })
})
await waitFor(() => {
const calls = updateDirectories.mock.calls
const lastDirectories = calls[calls.length - 1][0] as string[]
expect(lastDirectories).toContain('/repo')
expect(lastDirectories).not.toContain('/repo/.worktrees/feature')
})
})
})
+27 -3
View File
@@ -236,6 +236,26 @@ async function settlePendingReply(
}
}
/**
* Primitive key of every directory that hosts an active session: the recorded directory of each
* session whose status is not `idle`, plus each running shell's directory, sorted and de-duplicated.
* A string keeps the zustand subscription stable across store updates that do not change the set.
*/
export function selectActiveSessionDirectoriesKey(
state: Pick<ReturnType<typeof useSessionStatus.getState>, 'statuses' | 'directories' | 'runningShells'>,
): string {
const directories = new Set<string>()
for (const [sessionID, status] of state.statuses.entries()) {
if (status.type === 'idle') continue
const directory = state.directories.get(sessionID)
if (directory) directories.add(directory)
}
for (const shell of state.runningShells.values()) {
if (shell.directory) directories.add(shell.directory)
}
return [...directories].sort().join('\n')
}
const EventContext = createContext<EventContextValue | null>(null)
export function EventProvider({ children }: { children: React.ReactNode }) {
@@ -243,6 +263,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
const navigate = useNavigate()
const location = useLocation()
const sessionParents = useSessionStatus((state) => state.parents)
const activeSessionDirectoriesKey = useSessionStatus(selectActiveSessionDirectoriesKey)
const [sshHostKeyRequest, setSSHHostKeyRequest] = useState<SSHHostKeyRequest | null>(null)
const [sseHealth, setSseHealth] = useState<SSEHealthState>(() => {
@@ -858,9 +879,12 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
reposRef.current = repos
const directories = [...new Set((repos ?? []).map(r => r.fullPath))]
subscriptionRef.current?.updateDirectories(directories)
}, [repos])
const directories = new Set((repos ?? []).map(r => r.fullPath))
for (const directory of activeSessionDirectoriesKey.split('\n')) {
if (directory) directories.add(directory)
}
subscriptionRef.current?.updateDirectories([...directories])
}, [repos, activeSessionDirectoriesKey])
useEffect(() => {
if (!repos || repos.length === 0) return
@@ -0,0 +1,119 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, render, screen, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { Repo } from '@/api/types'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { RepoWorktreesProvider, useRepoWorktreeList } from './RepoWorktreesContext'
const mocks = vi.hoisted(() => ({
getRepoSiblings: vi.fn(),
useNavigableRepos: vi.fn(),
}))
vi.mock('@/api/repos', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/repos')>()
return {
...actual,
getRepoSiblings: mocks.getRepoSiblings,
}
})
vi.mock('@/hooks/useSidebarRepoGroups', () => ({
useNavigableRepos: mocks.useNavigableRepos,
}))
vi.mock('@/contexts/EventContext', () => ({
usePermissions: () => ({ pendingSessionIDs: [] }),
useForms: () => ({ pendingSessionIDs: [] }),
}))
const REPO_PATH = '/repo'
const WORKTREE_PATH = '/repo/.worktrees/feature'
const repo: Repo = {
id: 1,
fullPath: REPO_PATH,
localPath: REPO_PATH,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
}
const worktreeSibling = {
...repo,
id: -1,
fullPath: WORKTREE_PATH,
localPath: 'feature',
sourcePath: WORKTREE_PATH,
currentBranch: 'feature',
worktreeSource: 'opencode' as const,
}
function WorktreeConsumer() {
const worktrees = useRepoWorktreeList()
return <div data-testid="worktrees">{worktrees.map((worktree) => worktree.directory).join(',')}</div>
}
const renderProvider = (queryClient: QueryClient) => {
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
return render(
<RepoWorktreesProvider>
<WorktreeConsumer />
</RepoWorktreesProvider>,
{ wrapper },
)
}
const setActiveSession = (directory: string) => {
useSessionStatus.setState({
statuses: new Map([['session', { type: 'busy' as const }]]),
directories: new Map([['session', directory]]),
})
}
describe('RepoWorktreesProvider', () => {
beforeEach(() => {
mocks.getRepoSiblings.mockReset()
mocks.getRepoSiblings.mockResolvedValue([worktreeSibling])
mocks.useNavigableRepos.mockReset()
mocks.useNavigableRepos.mockReturnValue({ repos: [repo], isLoading: false, refetch: vi.fn() })
useSessionStatus.setState({
statuses: new Map(),
statusCache: new Map(),
statusRevisions: new Map(),
knownSessions: new Set(),
outcomes: new Map(),
parents: new Map(),
directories: new Map(),
runningShells: new Map(),
shellRevisions: new Map(),
shellRevision: 0,
revision: 0,
})
})
it('never fetches siblings when every active directory belongs to a repo', async () => {
setActiveSession(REPO_PATH)
renderProvider(new QueryClient({ defaultOptions: { queries: { retry: false } } }))
await act(async () => {
await Promise.resolve()
})
expect(mocks.getRepoSiblings).not.toHaveBeenCalled()
expect(screen.getByTestId('worktrees')).toHaveTextContent('')
})
it('fetches siblings and exposes the worktree when a busy session directory is unmatched', async () => {
setActiveSession(WORKTREE_PATH)
renderProvider(new QueryClient({ defaultOptions: { queries: { retry: false } } }))
await waitFor(() => expect(screen.getByTestId('worktrees')).toHaveTextContent(WORKTREE_PATH))
expect(mocks.getRepoSiblings).toHaveBeenCalledWith(1)
})
})
@@ -0,0 +1,58 @@
/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useMemo, type ReactNode } from 'react'
import { useForms, usePermissions } from '@/contexts/EventContext'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { useRepoWorktrees } from '@/hooks/useRepoWorktrees'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import {
buildRepoActivityIndex,
hasUnmatchedActiveDirectory,
type ActiveWorktree,
} from '@/lib/activeWork'
const EMPTY_WORKTREES: ActiveWorktree[] = []
const RepoWorktreesContext = createContext<ActiveWorktree[]>(EMPTY_WORKTREES)
/** Pending permission and form session ids, merged once per snapshot into a referentially stable list. */
export function usePendingInputSessionIDs(): string[] {
const pendingPermissionSessionIDs = usePermissions().pendingSessionIDs
const pendingFormSessionIDs = useForms().pendingSessionIDs
return useMemo(
() => [...pendingPermissionSessionIDs, ...pendingFormSessionIDs],
[pendingPermissionSessionIDs, pendingFormSessionIDs],
)
}
/**
* Discovers the repos' worktrees once for the whole app and shares them, so per-row repo badges can
* resolve a session running in a worktree to its owning repo without each row fetching. The worktree
* lookup only runs while some active session sits in a directory that matches no repo.
*/
export function RepoWorktreesProvider({ children }: { children: ReactNode }) {
const { repos } = useNavigableRepos()
const pendingInputSessionIDs = usePendingInputSessionIDs()
const enabled = useSessionStatus((state) =>
hasUnmatchedActiveDirectory(
buildRepoActivityIndex({
statuses: state.statuses,
parents: state.parents,
runningShells: state.runningShells,
directories: state.directories,
pendingInputSessionIDs,
}),
repos,
),
)
const { worktrees } = useRepoWorktrees(repos, enabled)
return <RepoWorktreesContext.Provider value={worktrees}>{children}</RepoWorktreesContext.Provider>
}
/** The worktrees discovered for the app's repos, empty outside the provider. */
export function useRepoWorktreeList(): ActiveWorktree[] {
return useContext(RepoWorktreesContext)
}
+64 -2
View File
@@ -14,6 +14,7 @@ const WINDOW_MS = 60 * MS_PER_MINUTE
const mocks = vi.hoisted(() => ({
listSessionPage: vi.fn(),
getSession: vi.fn(),
getRepoSiblings: vi.fn(),
useNavigableRepos: vi.fn(),
pendingSessionIDs: [] as string[],
}))
@@ -27,6 +28,14 @@ vi.mock('@/api/opencode', async (importOriginal) => {
}
})
vi.mock('@/api/repos', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/repos')>()
return {
...actual,
getRepoSiblings: mocks.getRepoSiblings,
}
})
vi.mock('@/hooks/useSidebarRepoGroups', () => ({
useNavigableRepos: mocks.useNavigableRepos,
}))
@@ -48,12 +57,17 @@ vi.mock('@/lib/toast', () => ({
},
}))
const session = (id: string, updated: number, parentID?: string | null): SessionInfo => ({
const session = (
id: string,
updated: number,
parentID?: string | null,
directory = REPO_PATH,
): SessionInfo => ({
id,
projectID: 'proj_1',
title: `Session ${id}`,
time: { created: updated, updated },
location: { directory: REPO_PATH },
location: { directory },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
...(parentID === undefined ? {} : { parentID }),
@@ -83,6 +97,8 @@ describe('useActiveWork', () => {
beforeEach(() => {
mocks.listSessionPage.mockReset()
mocks.getSession.mockReset()
mocks.getRepoSiblings.mockReset()
mocks.getRepoSiblings.mockResolvedValue([])
mocks.useNavigableRepos.mockReset()
mocks.useNavigableRepos.mockReturnValue({ repos: [repo], isLoading: false, refetch: vi.fn() })
useSessionStatus.setState({
@@ -197,4 +213,50 @@ describe('useActiveWork', () => {
expect(recentIDs(result.current.groups)).not.toContain('root')
})
it('resolves a session in a worktree to its owning repo and opens the workspaces tab', async () => {
const now = Date.now()
mocks.listSessionPage.mockResolvedValue({
items: [session('wt', now - 500, undefined, '/repo/.worktrees/feature')],
})
mocks.getRepoSiblings.mockResolvedValue([
{
...repo,
id: -1,
fullPath: '/repo/.worktrees/feature',
localPath: 'feature',
sourcePath: '/repo/.worktrees/feature',
currentBranch: 'feature',
worktreeSource: 'opencode',
},
])
const { result } = renderHook(() => useActiveWork(WINDOW_MS), {
wrapper: createWrapper(createQueryClient()),
})
await waitFor(() => expect(recentIDs(result.current.groups)).toContain('wt'))
expect(result.current.groups.recent[0].repo.id).toBe(1)
expect(result.current.groups.recent[0].path).toBe('/repos/1/sessions/wt?repoTab=workspaces')
})
it('never fetches siblings for an orphan session updated outside the window', async () => {
const now = Date.now()
mocks.listSessionPage.mockResolvedValue({
items: [session('orphan', now - 2 * WINDOW_MS, undefined, '/outside/repo')],
})
const { result } = renderHook(() => useActiveWork(WINDOW_MS), {
wrapper: createWrapper(createQueryClient()),
})
await waitFor(() => expect(result.current.isLoading).toBe(false))
await act(async () => {
await Promise.resolve()
})
expect(mocks.getRepoSiblings).not.toHaveBeenCalled()
})
})
+24 -18
View File
@@ -3,23 +3,22 @@ import { useQueries, useQueryClient, type QueryClient } from '@tanstack/react-qu
import type { SessionInfo } from '@opencode-manager/shared/opencode'
import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { useForms, usePermissions } from '@/contexts/EventContext'
import { usePendingInputSessionIDs, useRepoWorktreeList } from '@/contexts/RepoWorktreesContext'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { useSettings } from '@/hooks/useSettings'
import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@/api/types/settings'
import { useRepoWorktrees } from '@/hooks/useRepoWorktrees'
import {
MS_PER_MINUTE,
buildActiveWork,
buildRepoActivityIndex,
collectActiveRoots,
needsWorktreeLookup,
repoActivityFromIndex,
rootSessionID,
type ActiveWorkGroups,
} from '@/lib/activeWork'
import {
combineQuerySessions,
mergeExtraSessions,
} from '@/components/navigation/sidebar-session-tree'
import { combineQuerySessions, mergeExtraSessions } from '@/components/navigation/sidebar-session-tree'
import type { Repo } from '@/api/types'
const ACTIVE_WORK_SESSION_LIMIT = 50
@@ -33,17 +32,6 @@ export function useActivityWindowMinutes(): number {
return preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES
}
/** Pending permission and form session ids, merged once per snapshot into a referentially stable list. */
function usePendingInputSessionIDs(): string[] {
const pendingPermissionSessionIDs = usePermissions().pendingSessionIDs
const pendingFormSessionIDs = useForms().pendingSessionIDs
return useMemo(
() => [...pendingPermissionSessionIDs, ...pendingFormSessionIDs],
[pendingPermissionSessionIDs, pendingFormSessionIDs],
)
}
/**
* Distinct active roots for a badge: needs-input roots and running roots that are not also
* pending input. Reads only the session-status store and the pending queues, with no network.
@@ -72,6 +60,7 @@ export function useActiveWorkCounts(): { needsInput: number; running: number } {
*/
export function useRepoActivityState(repo: Repo): 'needs-input' | 'running' | null {
const pendingInputSessionIDs = usePendingInputSessionIDs()
const worktrees = useRepoWorktreeList()
return useSessionStatus((state) =>
repoActivityFromIndex(
@@ -83,6 +72,7 @@ export function useRepoActivityState(repo: Repo): 'needs-input' | 'running' | nu
directories: state.directories,
pendingInputSessionIDs,
}),
worktrees,
),
)
}
@@ -256,6 +246,21 @@ export function useActiveWork(windowMs: number): {
[sessions, fetchedSessions],
)
const needsLookup = useMemo(
() =>
needsWorktreeLookup({
now,
windowMs,
repos,
sessions: mergedSessions,
parents: resolvedParents,
roots: resolvedRoots,
}),
[now, windowMs, repos, mergedSessions, resolvedParents, resolvedRoots],
)
const { worktrees, isLoading: isWorktreesLoading } = useRepoWorktrees(repos, needsLookup)
const groups = useMemo(
() =>
buildActiveWork({
@@ -266,13 +271,14 @@ export function useActiveWork(windowMs: number): {
parents: resolvedParents,
roots: resolvedRoots,
outcomes,
worktrees,
}),
[now, windowMs, repos, mergedSessions, resolvedParents, resolvedRoots, outcomes],
[now, windowMs, repos, mergedSessions, resolvedParents, resolvedRoots, outcomes, worktrees],
)
return {
groups,
isLoading: isReposLoading || isSessionsLoading,
isLoading: isReposLoading || isSessionsLoading || isWorktreesLoading,
isError: isSessionsError,
}
}
+28
View File
@@ -0,0 +1,28 @@
import { useQueries } from '@tanstack/react-query'
import { getRepoSiblings } from '@/api/repos'
import { repoSiblingsQueryKey } from '@/hooks/useRepoSiblings'
import { buildWorktreeActivity, type ActiveWorktree } from '@/lib/activeWork'
import type { Repo } from '@/api/types'
/**
* Discovers each repo's worktrees from its siblings while enabled, keyed by directory so a session
* running in a worktree resolves to the repo that owns it. Each query is skipped for repos without
* a positive id. `isLoading` is true while any enabled siblings query is still loading.
*/
export function useRepoWorktrees(
repos: Repo[],
enabled: boolean,
): { worktrees: ActiveWorktree[]; isLoading: boolean } {
return useQueries({
queries: repos.map((repo) => ({
queryKey: repoSiblingsQueryKey(repo.id),
queryFn: () => getRepoSiblings(repo.id),
enabled: enabled && repo.id > 0,
staleTime: 30_000,
})),
combine: (results) => ({
worktrees: buildWorktreeActivity(repos, results),
isLoading: results.some((result) => result.isLoading),
}),
})
}
+19 -4
View File
@@ -5,6 +5,7 @@ import { sessionQueryOptions, useSessionsAcrossDirectories } from '@/hooks/useOp
import { useSessionPins } from '@/hooks/useSessionPins'
import { buildPinnedSessionKeys, buildSessionKey, getSessionKey } from '@/lib/sessionKey'
import type { Repo } from '@/api/types'
import type { ActiveWorktree } from '@/lib/activeWork'
import {
SIDEBAR_SESSIONS_PER_REPO,
buildSidebarRepoGroups,
@@ -17,10 +18,17 @@ import {
export function useSidebarRepoGroups(input: {
repos: Repo[]
search?: string
worktrees?: ReadonlyArray<ActiveWorktree>
}): { groups: SidebarRepoGroup[]; isLoading: boolean; isError: boolean; hasMore: boolean } {
const { repos, search } = input
const { repos, search, worktrees } = input
const directories = useMemo(() => repos.map((repo) => repo.fullPath), [repos])
const directories = useMemo(
() => [
...repos.map((repo) => repo.fullPath),
...(worktrees ?? []).map((worktree) => worktree.directory),
],
[repos, worktrees],
)
const { data: sessions, isLoading, isError, hasNextPage } = useSessionsAcrossDirectories(directories, {
search,
@@ -52,8 +60,15 @@ export function useSidebarRepoGroups(input: {
)
const groups = useMemo(
() => buildSidebarRepoGroups({ repos, sessions: mergedSessions, pinnedKeys, now: Date.now() }),
[repos, mergedSessions, pinnedKeys],
() =>
buildSidebarRepoGroups({
repos,
sessions: mergedSessions,
pinnedKeys,
now: Date.now(),
worktrees,
}),
[repos, mergedSessions, pinnedKeys, worktrees],
)
return { groups, isLoading, isError, hasMore: Boolean(hasNextPage) }
+222
View File
@@ -2,14 +2,19 @@ import { describe, it, expect } from 'vitest'
import type { Repo, Session } from '@/api/types'
import type { ChildOutcome } from '@/lib/backgroundWork'
import type { SessionStatusType } from '@/stores/sessionStatusStore'
import type { RepoSibling, RepoWorktreeSource } from '@opencode-manager/shared/utils'
import {
buildActiveWork,
buildRepoActivityIndex,
buildWorktreeActivity,
collectActiveRoots,
formatActivityEmptyMessage,
formatActivityWindow,
hasUnmatchedActiveDirectory,
needsWorktreeLookup,
repoActivityFromIndex,
rootSessionID,
type ActiveWorktree,
} from './activeWork'
const NOW = 1_000_000_000_000
@@ -38,6 +43,14 @@ function createRepo(overrides: Partial<Repo> & { id: number; fullPath: string })
}
}
function createWorktreeSibling(id: number, fullPath: string, branch: string, source: RepoWorktreeSource): RepoSibling {
return {
...createRepo({ id, fullPath }),
currentBranch: branch,
worktreeSource: source,
}
}
function statuses(entries: Record<string, SessionStatusType>): Map<string, SessionStatusType> {
return new Map(Object.entries(entries))
}
@@ -254,6 +267,82 @@ describe('buildRepoActivityIndex and repoActivityFromIndex', () => {
})
})
describe('repoActivityFromIndex with worktrees', () => {
const noShells = new Map<string, { sessionID: string; directory: string }>()
const main = createRepo({ id: 1, fullPath: '/repos/a' })
const other = createRepo({ id: 2, fullPath: '/repos/b' })
const indexFor = (entries: Record<string, string>, pending: string[] = []) =>
buildRepoActivityIndex({
statuses: statuses(Object.fromEntries(Object.keys(entries).map((id) => [id, { type: 'busy' as const }]))),
parents: new Map(),
runningShells: noShells,
directories: new Map(Object.entries(entries)),
pendingInputSessionIDs: pending,
})
it('returns running for a repo whose owned worktree directory is running', () => {
const index = indexFor({ session: '/repos/a/.worktrees/feature' })
const worktrees: ActiveWorktree[] = [
{ directory: '/repos/a/.worktrees/feature', ownerRepo: main, branch: 'feature', isSchedule: false },
]
expect(repoActivityFromIndex(main, index, worktrees)).toBe('running')
})
it('ignores worktrees owned by another repo', () => {
const index = indexFor({ session: '/repos/b/.worktrees/feature' })
const worktrees: ActiveWorktree[] = [
{ directory: '/repos/b/.worktrees/feature', ownerRepo: other, branch: 'feature', isSchedule: false },
]
expect(repoActivityFromIndex(main, index, worktrees)).toBeNull()
})
it('prefers needs-input from a worktree over running on the repo path', () => {
const index = buildRepoActivityIndex({
statuses: statuses({ own: { type: 'busy' }, wt: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([
['own', '/repos/a'],
['wt', '/repos/a/.worktrees/feature'],
]),
pendingInputSessionIDs: ['wt'],
})
const worktrees: ActiveWorktree[] = [
{ directory: '/repos/a/.worktrees/feature', ownerRepo: main, branch: 'feature', isSchedule: false },
]
expect(repoActivityFromIndex(main, index, worktrees)).toBe('needs-input')
})
})
describe('hasUnmatchedActiveDirectory', () => {
const noShells = new Map<string, { sessionID: string; directory: string }>()
const indexFor = (directory: string) =>
buildRepoActivityIndex({
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', directory]]),
pendingInputSessionIDs: [],
})
it('is true when an index key matches no repo', () => {
expect(hasUnmatchedActiveDirectory(indexFor('/repos/other'), [repoA])).toBe(true)
})
it('is false when every indexed directory belongs to a repo', () => {
expect(hasUnmatchedActiveDirectory(indexFor('/repos/a'), [repoA])).toBe(false)
})
it('is false for an empty index', () => {
expect(hasUnmatchedActiveDirectory(new Map(), [repoA])).toBe(false)
})
})
describe('buildActiveWork', () => {
it('puts a root with both a pending permission and a busy status in needs-input only, once', () => {
const parents = new Map<string, string | null>()
@@ -388,4 +477,137 @@ describe('buildActiveWork', () => {
expect(groups.recent.map((item) => item.session.id)).toEqual(['root'])
})
it('resolves a session in a worktree to its owning repo and opens the workspaces tab', () => {
const main = createRepo({ id: 1, fullPath: '/repos/a' })
const sessions = [createSession('wt', NOW - 1000, '/repos/a/.worktrees/feature')]
const worktrees = [{ directory: '/repos/a/.worktrees/feature', ownerRepo: main, branch: 'feature', isSchedule: false }]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [main], sessions, parents: new Map(), roots: emptyRoots, outcomes: new Map(), worktrees })
expect(groups.recent).toHaveLength(1)
expect(groups.recent[0].repo.id).toBe(1)
expect(groups.recent[0].worktreeBranch).toBe('feature')
expect(groups.recent[0].path).toBe('/repos/1/sessions/wt?repoTab=workspaces')
})
it('drops a recent schedule worktree session but keeps it while its root is running', () => {
const main = createRepo({ id: 1, fullPath: '/repos/a' })
const worktrees = [
{ directory: '/repos/a/.worktrees/nightly', ownerRepo: main, branch: 'nightly', isSchedule: true },
]
const sessions = [createSession('sched', NOW - 1000, '/repos/a/.worktrees/nightly')]
const recentGroups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [main], sessions, parents: new Map(), roots: emptyRoots, outcomes: new Map(), worktrees })
expect(recentGroups.recent).toEqual([])
const runningGroups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [main], sessions, parents: new Map(), roots: { needsInput: new Set(), running: new Set(['sched']) }, outcomes: new Map(), worktrees })
expect(runningGroups.running.map((item) => item.session.id)).toEqual(['sched'])
})
})
describe('needsWorktreeLookup', () => {
const base = { now: NOW, windowMs: WINDOW_MS, repos: [repoA] }
it('returns true for an unmatched session updated inside the window', () => {
expect(
needsWorktreeLookup({
...base,
sessions: [createSession('orphan', NOW - 1000, '/repos/other')],
parents: new Map(),
roots: emptyRoots,
}),
).toBe(true)
})
it('returns false for an unmatched old idle session', () => {
expect(
needsWorktreeLookup({
...base,
sessions: [createSession('orphan', NOW - WINDOW_MS - 1, '/repos/other')],
parents: new Map(),
roots: emptyRoots,
}),
).toBe(false)
})
it('returns true for an unmatched old session whose root is running', () => {
const parents = new Map<string, string | null>([['orphan', 'root'], ['root', null]])
expect(
needsWorktreeLookup({
...base,
sessions: [createSession('orphan', NOW - WINDOW_MS - 1, '/repos/other', 'root')],
parents,
roots: { needsInput: new Set(), running: new Set(['root']) },
}),
).toBe(true)
})
it('returns false when every session matches a repo', () => {
expect(
needsWorktreeLookup({
...base,
sessions: [createSession('matched', NOW - 1000, '/repos/a')],
parents: new Map(),
roots: emptyRoots,
}),
).toBe(false)
})
it('returns false for an archived unmatched session', () => {
const archived = createSession('archived', NOW - 1000, '/repos/other')
archived.time.archived = NOW - 500
expect(
needsWorktreeLookup({
...base,
sessions: [archived],
parents: new Map(),
roots: emptyRoots,
}),
).toBe(false)
})
})
describe('buildWorktreeActivity', () => {
it('maps a worktree directory to its owning repo and branch', () => {
const main = createRepo({ id: 1, fullPath: '/repos/a' })
const worktree = createWorktreeSibling(-1, '/repos/a/.worktrees/feature', 'feature', 'opencode')
expect(buildWorktreeActivity([main], [{ data: [main, worktree] }])).toEqual([
{ directory: '/repos/a/.worktrees/feature', ownerRepo: main, branch: 'feature', isSchedule: false },
])
})
it('marks a schedule worktree as a schedule', () => {
const main = createRepo({ id: 1, fullPath: '/repos/a' })
const worktree = createWorktreeSibling(-1, '/repos/a/.worktrees/nightly', 'nightly', 'schedule')
expect(buildWorktreeActivity([main], [{ data: [worktree] }])).toEqual([
{ directory: '/repos/a/.worktrees/nightly', ownerRepo: main, branch: 'nightly', isSchedule: true },
])
})
it('prefers the non-worktree repo as owner and dedupes a worktree returned by several repos', () => {
const main = createRepo({ id: 1, fullPath: '/repos/a' })
const dbWorktree = createRepo({ id: 2, fullPath: '/repos/a-feature', isWorktree: true })
const worktree = createWorktreeSibling(-1, '/repos/a/.worktrees/feature', 'feature', 'git')
const entries = buildWorktreeActivity(
[dbWorktree, main],
[{ data: [worktree] }, { data: [worktree] }],
)
expect(entries).toHaveLength(1)
expect(entries[0].ownerRepo.id).toBe(1)
})
it('ignores siblings without a worktree source', () => {
const main = createRepo({ id: 1, fullPath: '/repos/a' })
expect(buildWorktreeActivity([main], [{ data: [main] }])).toEqual([])
})
})
+120 -10
View File
@@ -4,6 +4,7 @@ import type { SessionStatusType } from '@/stores/sessionStatusStore'
import { getSessionKey } from '@/lib/sessionKey'
import { getSessionPath } from '@/lib/navigation'
import { findRepoForDirectory, normalizeDirectory } from '@/components/navigation/sidebar-session-tree'
import { isWorktreeSibling, type RepoSibling } from '@opencode-manager/shared/utils'
export const MS_PER_MINUTE = 60_000
@@ -34,6 +35,8 @@ export interface ActiveWorkItem {
state: ActiveWorkState
updatedAt: number
outcome?: ChildOutcome
/** The worktree's branch when the session runs in a worktree of `repo`; null otherwise. */
worktreeBranch?: string | null
path: string
}
@@ -166,29 +169,126 @@ export function buildRepoActivityIndex(
return index
}
/** The repo's activity from a prebuilt index, checking each of its paths. Needs-input outranks running. */
/**
* The repo's activity from a prebuilt index, checking each of its own paths and the directories of
* the worktrees it owns. Needs-input outranks running.
*/
export function repoActivityFromIndex(
repo: Repo,
index: ReadonlyMap<string, 'needs-input' | 'running'>,
worktrees?: ReadonlyArray<ActiveWorktree>,
): 'needs-input' | 'running' | null {
let running = false
for (const path of [repo.fullPath, repo.localPath, repo.sourcePath]) {
const normalized = normalizeDirectory(path)
if (!normalized) continue
const check = (directory?: string | null): boolean => {
const normalized = normalizeDirectory(directory)
if (!normalized) return false
const state = index.get(normalized)
if (state === 'needs-input') return 'needs-input'
if (state === 'needs-input') return true
if (state === 'running') running = true
return false
}
for (const path of [repo.fullPath, repo.localPath, repo.sourcePath]) {
if (check(path)) return 'needs-input'
}
for (const worktree of worktrees ?? []) {
if (worktree.ownerRepo.id !== repo.id) continue
if (check(worktree.directory)) return 'needs-input'
}
return running ? 'running' : null
}
/**
* True when some indexed active directory matches no repo, so a session is active in a directory
* outside the repo list (such as a worktree) and the worktree lookup is worth running.
*/
export function hasUnmatchedActiveDirectory(
index: ReadonlyMap<string, 'needs-input' | 'running'>,
repos: Repo[],
): boolean {
for (const directory of index.keys()) {
if (!findRepoForDirectory(repos, directory)) return true
}
return false
}
/** A worktree directory and the repo that owns it, discovered from that repo's siblings. */
export interface ActiveWorktree {
directory: string
ownerRepo: Repo
branch: string | null
/** True when the worktree belongs to a schedule rather than an interactive session. */
isSchedule: boolean
}
/**
* Collects the worktrees discovered through each repo's siblings, keyed by directory so a session
* running in a worktree resolves to its owning repo. A repo's siblings include the worktrees of its
* whole OpenCode project, so the same worktree can come back from several repos: the non-worktree
* repo wins so a worktree session opens on the main repo, and duplicates are dropped.
*/
export function buildWorktreeActivity(
repos: Repo[],
siblingResults: ReadonlyArray<{ data?: RepoSibling[] }>,
): ActiveWorktree[] {
const ordered = repos
.map((repo, index) => ({ repo, siblings: siblingResults[index]?.data }))
.sort((a, b) => Number(Boolean(a.repo.isWorktree)) - Number(Boolean(b.repo.isWorktree)))
const worktrees: ActiveWorktree[] = []
const seen = new Set<string>()
for (const { repo, siblings } of ordered) {
for (const sibling of siblings ?? []) {
if (!isWorktreeSibling(sibling)) continue
const directory = normalizeDirectory(sibling.fullPath)
if (!directory || seen.has(directory)) continue
seen.add(directory)
worktrees.push({
directory,
ownerRepo: repo,
branch: sibling.currentBranch ?? sibling.branch ?? null,
isSchedule: sibling.worktreeSource === 'schedule',
})
}
}
return worktrees
}
/**
* Whether the worktree lookup is worth running: true when some non-archived session that matches no
* repo is either updated inside the window or has its root active (needs-input or running).
*/
export function needsWorktreeLookup(input: {
now: number
windowMs: number
repos: Repo[]
sessions: Session[]
parents: ReadonlyMap<string, string | null>
roots: { needsInput: Set<string>; running: Set<string> }
}): boolean {
const { now, windowMs, repos, sessions, parents, roots } = input
const windowStart = now - windowMs
return sessions.some((session) => {
if (session.time.archived) return false
if (findRepoForDirectory(repos, session.location.directory)) return false
if (session.time.updated >= windowStart) return true
const rootID = rootSessionID(session.id, parents)
return roots.needsInput.has(rootID) || roots.running.has(rootID)
})
}
/**
* 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 repo.
* 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.
* 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
@@ -198,10 +298,16 @@ export function buildActiveWork(input: {
parents: ReadonlyMap<string, string | null>
roots: { needsInput: Set<string>; running: Set<string> }
outcomes: ReadonlyMap<string, ChildOutcome>
worktrees?: ReadonlyArray<ActiveWorktree>
}): ActiveWorkGroups {
const { now, windowMs, repos, sessions, parents, roots, outcomes } = input
const { now, windowMs, repos, sessions, parents, roots, outcomes, worktrees } = input
const windowStart = now - windowMs
const worktreeByDirectory = new Map<string, ActiveWorktree>()
for (const worktree of worktrees ?? []) {
worktreeByDirectory.set(worktree.directory, worktree)
}
const activityByRoot = new Map<string, number>()
for (const session of sessions) {
if (session.time.archived) continue
@@ -232,8 +338,11 @@ export function buildActiveWork(input: {
: null
if (!state) continue
const repo = findRepoForDirectory(repos, session.location.directory)
const directory = normalizeDirectory(session.location.directory)
const worktree = directory ? worktreeByDirectory.get(directory) : undefined
const repo = worktree?.ownerRepo ?? findRepoForDirectory(repos, session.location.directory)
if (!repo) continue
if (worktree?.isSchedule && state === 'recent') continue
seen.add(session.id)
const item: ActiveWorkItem = {
@@ -243,7 +352,8 @@ export function buildActiveWork(input: {
state,
updatedAt,
outcome: outcomes.get(session.id),
path: getSessionPath(repo.id, session.id),
worktreeBranch: worktree ? worktree.branch : null,
path: getSessionPath(repo.id, session.id, worktree ? { repoTab: 'workspaces' } : undefined),
}
if (state === 'needs-input') needsInput.push(item)
+7 -3
View File
@@ -53,15 +53,19 @@ function isSafeInternalPath(path: string): boolean {
return path.startsWith('/') && !path.startsWith('//');
}
export function getPathWithReturnTo(path: string, returnTo: string): string {
if (!isSafeInternalPath(returnTo)) return path;
export function withQueryParam(path: string, key: string, value: string): string {
const [base, query = ''] = path.split('?');
const params = new URLSearchParams(query);
params.set('returnTo', returnTo);
params.set(key, value);
const search = params.toString();
return search ? `${base}?${search}` : base;
}
export function getPathWithReturnTo(path: string, returnTo: string): string {
if (!isSafeInternalPath(returnTo)) return path;
return withQueryParam(path, 'returnTo', returnTo);
}
export function getReturnToPath(search: string, fallback: string): string {
const returnTo = new URLSearchParams(search).get('returnTo');
return returnTo && isSafeInternalPath(returnTo) ? returnTo : fallback;