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

@@ -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)
}