feat(activity): surface active work across the session picker, tool rail and mobile

This commit is contained in:
Chris Scott committed 2026-10-16 00:54:06 -04:00
1 parent be874ee07c
commit d8f2fcf29c
46 files changed
+3120 -277

No files matched your search

+296
View File
@@ -0,0 +1,296 @@
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 { buildActiveWork, collectActiveRoots, activeRepoState, rootSessionID, formatActivityWindow } from './activeWork'
const NOW = 1_000_000_000_000
const WINDOW_MS = 60_000
function createSession(id: string, updated: number, directory: string): Session {
return {
id,
projectID: 'proj-1',
title: `Session ${id}`,
time: { created: updated - 10000, updated },
location: { directory },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
}
}
function createRepo(overrides: Partial<Repo> & { id: number; fullPath: string }): Repo {
return {
localPath: `repos/${overrides.id}`,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
...overrides,
}
}
function statuses(entries: Record<string, SessionStatusType>): Map<string, SessionStatusType> {
return new Map(Object.entries(entries))
}
const repoA = createRepo({ id: 1, fullPath: '/repos/a' })
const emptyRoots = { needsInput: new Set<string>(), running: new Set<string>() }
describe('formatActivityWindow', () => {
it('labels the known minute options', () => {
expect(formatActivityWindow(15)).toBe('15 minutes')
expect(formatActivityWindow(30)).toBe('30 minutes')
expect(formatActivityWindow(60)).toBe('1 hour')
expect(formatActivityWindow(120)).toBe('2 hours')
expect(formatActivityWindow(240)).toBe('4 hours')
expect(formatActivityWindow(480)).toBe('8 hours')
expect(formatActivityWindow(1440)).toBe('24 hours')
})
it('falls back to minutes for unknown values', () => {
expect(formatActivityWindow(45)).toBe('45 minutes')
expect(formatActivityWindow(90)).toBe('90 minutes')
})
it('falls back to hours for unknown values divisible by sixty', () => {
expect(formatActivityWindow(180)).toBe('3 hours')
})
})
describe('rootSessionID', () => {
it('climbs parents to the top-most root', () => {
const parents = new Map<string, string | null>([['child', 'parent'], ['parent', 'root'], ['root', null]])
expect(rootSessionID('child', parents)).toBe('root')
expect(rootSessionID('parent', parents)).toBe('root')
expect(rootSessionID('root', parents)).toBe('root')
})
it('terminates on a parent cycle', () => {
const parents = new Map<string, string | null>([['a', 'b'], ['b', 'a']])
expect(typeof rootSessionID('a', parents)).toBe('string')
})
})
describe('collectActiveRoots', () => {
it('rolls a busy child up to its root as running', () => {
const parents = new Map<string, string | null>([['child', 'root'], ['root', null]])
const roots = collectActiveRoots({
statuses: statuses({ child: { type: 'busy' } }),
parents,
runningShells: new Map(),
pendingInputSessionIDs: [],
})
expect(roots.running.has('root')).toBe(true)
expect(roots.running.has('child')).toBe(false)
expect(roots.needsInput.size).toBe(0)
})
it('rolls a running shell under a child up to the root', () => {
const parents = new Map<string, string | null>([['child', 'root'], ['root', null]])
const roots = collectActiveRoots({
statuses: statuses({}),
parents,
runningShells: new Map([['shell-1', { sessionID: 'child' }]]),
pendingInputSessionIDs: [],
})
expect(roots.running.has('root')).toBe(true)
})
it('rolls a pending permission up to the root as needs-input', () => {
const parents = new Map<string, string | null>([['child', 'root'], ['root', null]])
const roots = collectActiveRoots({
statuses: statuses({}),
parents,
runningShells: new Map(),
pendingInputSessionIDs: ['child'],
})
expect(roots.needsInput.has('root')).toBe(true)
})
it('terminates on a parent cycle', () => {
const parents = new Map<string, string | null>([['a', 'b'], ['b', 'a']])
const roots = collectActiveRoots({
statuses: statuses({ a: { type: 'busy' } }),
parents,
runningShells: new Map(),
pendingInputSessionIDs: [],
})
expect(roots.running.size).toBe(1)
})
})
describe('activeRepoState', () => {
const repo = repoA
const noShells = new Map<string, { sessionID: string; directory: string }>()
it('matches a busy session by its own directory', () => {
const state = activeRepoState({
repo,
statuses: statuses({ child: { type: 'busy' } }),
parents: new Map([['child', 'root'], ['root', null]]),
runningShells: noShells,
directories: new Map([['child', '/repos/a']]),
pendingInputSessionIDs: [],
})
expect(state).toBe('running')
})
it('matches a busy session by its root directory', () => {
const state = activeRepoState({
repo,
statuses: statuses({ child: { type: 'busy' } }),
parents: new Map([['child', 'root'], ['root', null]]),
runningShells: noShells,
directories: new Map([['root', '/repos/a']]),
pendingInputSessionIDs: [],
})
expect(state).toBe('running')
})
it('matches a running shell by its own directory', () => {
const state = activeRepoState({
repo,
statuses: statuses({}),
parents: new Map(),
runningShells: new Map([['shell-1', { sessionID: 'orphan', directory: '/repos/a' }]]),
directories: new Map(),
pendingInputSessionIDs: [],
})
expect(state).toBe('running')
})
it('matches a session directory against the repo local path', () => {
const localRepo = createRepo({ id: 7, fullPath: '/repos/full', localPath: '/local/path' })
const state = activeRepoState({
repo: localRepo,
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/local/path']]),
pendingInputSessionIDs: [],
})
expect(state).toBe('running')
})
it('prefers needs-input over running', () => {
const state = activeRepoState({
repo,
statuses: statuses({ session: { type: 'busy' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/repos/a']]),
pendingInputSessionIDs: ['session'],
})
expect(state).toBe('needs-input')
})
it('returns null when every matching session is idle', () => {
const state = activeRepoState({
repo,
statuses: statuses({ session: { type: 'idle' } }),
parents: new Map(),
runningShells: noShells,
directories: new Map([['session', '/repos/a']]),
pendingInputSessionIDs: [],
})
expect(state).toBeNull()
})
})
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>()
const roots = collectActiveRoots({
statuses: statuses({ root: { type: 'busy' } }),
parents,
runningShells: new Map(),
pendingInputSessionIDs: ['root'],
})
const sessions = [createSession('root', NOW - 1000, '/repos/a')]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots, outcomes: new Map() })
expect(groups.needsInput.map((item) => item.session.id)).toEqual(['root'])
expect(groups.running).toEqual([])
const all = [...groups.needsInput, ...groups.running, ...groups.recent]
expect(all.filter((item) => item.session.id === 'root')).toHaveLength(1)
})
it('includes a session updated exactly at the window boundary and excludes the one before it', () => {
const sessions = [
createSession('inside', NOW - WINDOW_MS, '/repos/a'),
createSession('outside', NOW - WINDOW_MS - 1, '/repos/a'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['inside'])
})
it('excludes archived sessions', () => {
const archived = createSession('archived', NOW - 1000, '/repos/a')
archived.time.archived = NOW - 500
const sessions = [createSession('active', NOW - 1000, '/repos/a'), archived]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['active'])
})
it('excludes sessions whose directory matches no repo', () => {
const sessions = [createSession('orphan', NOW - 1000, '/repos/other')]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent).toEqual([])
})
it('resolves a repo by local path and trims trailing slashes', () => {
const repo = createRepo({ id: 5, fullPath: '/repos/full', localPath: '/local/path' })
const sessions = [createSession('local', NOW - 1000, '/local/path/')]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repo], sessions, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent).toHaveLength(1)
expect(groups.recent[0].repo.id).toBe(5)
expect(groups.recent[0].key).toBe('/local/path/:local')
expect(groups.recent[0].path).toBe('/repos/5/sessions/local')
})
it('sorts each group by updated descending', () => {
const sessions = [
createSession('oldest', NOW - 3000, '/repos/a'),
createSession('newest', NOW - 1000, '/repos/a'),
createSession('middle', NOW - 2000, '/repos/a'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['newest', 'middle', 'oldest'])
})
it('carries the child outcome onto the item', () => {
const sessions = [createSession('root', NOW - 1000, '/repos/a')]
const outcomes = new Map<string, ChildOutcome>([['root', 'failed']])
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes })
expect(groups.recent[0].outcome).toBe('failed')
})
})
+191
View File
@@ -0,0 +1,191 @@
import type { Repo, Session } from '@/api/types'
import type { ChildOutcome } from '@/lib/backgroundWork'
import type { SessionStatusType } from '@/stores/sessionStatusStore'
import { getSessionKey } from '@/lib/sessionKey'
import { getSessionPath } from '@/lib/navigation'
import { findRepoForDirectory, repoMatchesDirectory } from '@/components/navigation/sidebar-session-tree'
const ACTIVITY_WINDOW_LABELS: Record<number, string> = {
15: '15 minutes',
30: '30 minutes',
60: '1 hour',
120: '2 hours',
240: '4 hours',
480: '8 hours',
1440: '24 hours',
}
/**
* Human-readable label for an activity window in minutes. Known options map to their labels;
* other values fall back to minutes, or to hours when the value divides evenly into hours.
*/
export function formatActivityWindow(minutes: number): string {
const known = ACTIVITY_WINDOW_LABELS[minutes]
if (known) return known
if (minutes % 60 === 0) {
const hours = minutes / 60
return `${hours} ${hours === 1 ? 'hour' : 'hours'}`
}
return `${minutes} minutes`
}
export type ActiveWorkState = 'needs-input' | 'running' | 'recent'
export interface ActiveWorkItem {
key: string
session: Session
repo: Repo
state: ActiveWorkState
outcome?: ChildOutcome
path: string
}
export interface ActiveWorkGroups {
needsInput: ActiveWorkItem[]
running: ActiveWorkItem[]
recent: ActiveWorkItem[]
}
export function rootSessionID(
sessionID: string,
parents: ReadonlyMap<string, string | null>,
): string {
const visited = new Set<string>()
let currentID = sessionID
while (!visited.has(currentID)) {
visited.add(currentID)
const parentID = parents.get(currentID)
if (parentID === undefined || parentID === null) break
currentID = parentID
}
return currentID
}
/**
* Rolls every active or pending session id up to its root. `needsInput` and `running` may both
* contain a root; callers apply the needs-input over running priority when grouping.
*/
export function collectActiveRoots(input: {
statuses: ReadonlyMap<string, SessionStatusType>
parents: ReadonlyMap<string, string | null>
runningShells: ReadonlyMap<string, { sessionID: string }>
pendingInputSessionIDs: Iterable<string>
}): { needsInput: Set<string>; running: Set<string> } {
const { statuses, parents, runningShells, pendingInputSessionIDs } = input
const needsInput = new Set<string>()
for (const sessionID of pendingInputSessionIDs) {
needsInput.add(rootSessionID(sessionID, parents))
}
const running = new Set<string>()
for (const [sessionID, status] of statuses) {
if (status.type === 'idle') continue
running.add(rootSessionID(sessionID, parents))
}
for (const shell of runningShells.values()) {
running.add(rootSessionID(shell.sessionID, parents))
}
return { needsInput, running }
}
/**
* Whether a repo has any active session. A session counts when its own directory or its root's
* directory matches the repo; running shells carry their own directory. Needs-input outranks running.
*/
export function activeRepoState(input: {
repo: Repo
statuses: ReadonlyMap<string, SessionStatusType>
parents: ReadonlyMap<string, string | null>
runningShells: ReadonlyMap<string, { sessionID: string; directory: string }>
directories: ReadonlyMap<string, string>
pendingInputSessionIDs: Iterable<string>
}): 'needs-input' | 'running' | null {
const { repo, statuses, parents, runningShells, directories, pendingInputSessionIDs } = input
const sessionMatches = (sessionID: string): boolean => {
if (repoMatchesDirectory(repo, directories.get(sessionID))) return true
const rootID = rootSessionID(sessionID, parents)
return rootID !== sessionID && repoMatchesDirectory(repo, directories.get(rootID))
}
for (const sessionID of pendingInputSessionIDs) {
if (sessionMatches(sessionID)) return 'needs-input'
}
for (const [sessionID, status] of statuses) {
if (status.type === 'idle') continue
if (sessionMatches(sessionID)) return 'running'
}
for (const shell of runningShells.values()) {
if (repoMatchesDirectory(repo, shell.directory) || sessionMatches(shell.sessionID)) return 'running'
}
return null
}
/**
* 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.
*/
export function buildActiveWork(input: {
now: number
windowMs: number
repos: Repo[]
sessions: Session[]
roots: { needsInput: Set<string>; running: Set<string> }
outcomes: ReadonlyMap<string, ChildOutcome>
}): ActiveWorkGroups {
const { now, windowMs, repos, sessions, roots, outcomes } = input
const windowStart = now - windowMs
const needsInput: ActiveWorkItem[] = []
const running: ActiveWorkItem[] = []
const recent: ActiveWorkItem[] = []
const seen = new Set<string>()
for (const session of sessions) {
if (seen.has(session.id)) continue
if (session.time.archived) continue
const state: ActiveWorkState | null = roots.needsInput.has(session.id)
? 'needs-input'
: roots.running.has(session.id)
? 'running'
: session.time.updated >= windowStart
? 'recent'
: null
if (!state) continue
const repo = findRepoForDirectory(repos, session.location.directory)
if (!repo) continue
seen.add(session.id)
const item: ActiveWorkItem = {
key: getSessionKey(session),
session,
repo,
state,
outcome: outcomes.get(session.id),
path: getSessionPath(repo.id, session.id),
}
if (state === 'needs-input') needsInput.push(item)
else if (state === 'running') running.push(item)
else recent.push(item)
}
const byUpdatedDesc = (a: ActiveWorkItem, b: ActiveWorkItem) =>
b.session.time.updated - a.session.time.updated
needsInput.sort(byUpdatedDesc)
running.sort(byUpdatedDesc)
recent.sort(byUpdatedDesc)
return { needsInput, running, recent }
}