mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
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:
1 parent
1d31286904
commit
bfbbbf08ef
23 files changed
+932
-81
No files matched your search
@@ -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
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user