fix(activity): roll subagent activity up to its root and accept only selectable windows

- List child sessions in the activity query and credit each child's latest update
  to its root, so Recent includes roots whose subagents were active inside the
  window; children never become rows, and only roots of in-window children are
  fetched
- Show and sort activity rows by that rolled-up time
- Restrict activityWindowMinutes to the selectable options on write, and coerce a
  stored unknown value to the default on read so it cannot reset every preference
This commit is contained in:
Chris Scott committed 2026-10-16 11:57:52 -04:00
1 parent 8b6251d83b
commit 84cdffa261
22 files changed
+343 -48

No files matched your search

+6
View File
@@ -11,6 +11,8 @@ import type {
import {
UserPreferencesSchema,
DEFAULT_USER_PREFERENCES,
DEFAULT_ACTIVITY_WINDOW_MINUTES,
isActivityWindowMinutes,
} from '../types/settings'
import { isColorThemeId, MANAGER_COLOR_THEME_ID } from '@opencode-manager/shared/themes'
@@ -69,6 +71,10 @@ export class SettingsService {
parsed.colorTheme = MANAGER_COLOR_THEME_ID
}
if (!isActivityWindowMinutes(parsed.activityWindowMinutes)) {
parsed.activityWindowMinutes = DEFAULT_ACTIVITY_WINDOW_MINUTES
}
const validated = UserPreferencesSchema.parse({
...DEFAULT_USER_PREFERENCES,
...parsed,
@@ -181,6 +181,39 @@ describe('internal/settings routes', () => {
expect(body.error).toBe('Invalid request body')
})
it('PATCH /api/internal/settings with { activityWindowMinutes: 45 } returns 400 (non-option reject)', async () => {
const res = await app.request('/api/internal/settings', {
method: 'PATCH',
body: JSON.stringify({ activityWindowMinutes: 45 }),
headers: {
'content-type': 'application/json',
authorization: `Bearer ${token}`,
},
})
expect(res.status).toBe(400)
const body = await res.json() as { error: string }
expect(body.error).toBe('Invalid request body')
})
it('PATCH /api/internal/settings with { activityWindowMinutes: 60 } persists an allowed option', async () => {
const patchRes = await app.request('/api/internal/settings', {
method: 'PATCH',
body: JSON.stringify({ activityWindowMinutes: 60 }),
headers: {
'content-type': 'application/json',
authorization: `Bearer ${token}`,
},
})
expect(patchRes.status).toBe(200)
const getRes = await app.request('/api/internal/settings', {
headers: { authorization: `Bearer ${token}` },
})
expect(getRes.status).toBe(200)
const body = await getRes.json() as { preferences: { activityWindowMinutes: number } }
expect(body.preferences.activityWindowMinutes).toBe(60)
})
it('PATCH /api/internal/settings with { tts: { voice: "x", speed: 1.5 } } merges and preserves apiKey/endpoint', async () => {
// Seed a full TTS config (including secrets) directly via settingsService
settingsService.updateSettings({
+35
View File
@@ -1519,6 +1519,41 @@ describe('Settings Routes - OpenCode Upgrade', () => {
})
})
describe('PATCH / - activity window validation', () => {
it.each([5, 45, 2000, 30.5])('rejects activityWindowMinutes %s with 400', async (minutes) => {
const res = await settingsApp.fetch(new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: { activityWindowMinutes: minutes } }),
}))
const json = await res.json() as { error: string }
expect(res.status).toBe(400)
expect(json.error).toBe('Invalid settings data')
expect(mockUpdateSettings).not.toHaveBeenCalled()
})
it('accepts an allowed activityWindowMinutes value', async () => {
mockGetSettings.mockReturnValue({
preferences: { activityWindowMinutes: 30 },
updatedAt: 1,
})
mockUpdateSettings.mockReturnValue({
preferences: { activityWindowMinutes: 60 },
updatedAt: 2,
})
const res = await settingsApp.fetch(new Request('http://localhost/', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ preferences: { activityWindowMinutes: 60 } }),
}))
expect(res.status).toBe(200)
expect(mockUpdateSettings).toHaveBeenCalledWith({ activityWindowMinutes: 60 }, 'default')
})
})
describe('PATCH / - sandbox enable guard', () => {
afterEach(() => {
forceProcessAttestation(null)
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, it, beforeEach } from 'vitest'
import { Database } from 'bun:sqlite'
import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@opencode-manager/shared/schemas'
import { SettingsService } from '../../src/services/settings'
import { allMigrations } from '../../src/db/migrations'
import { migrate } from '../../src/db/migration-runner'
describe('SettingsService', () => {
let db: Database
let settingsService: SettingsService
beforeEach(() => {
db = new Database(':memory:')
migrate(db, allMigrations)
settingsService = new SettingsService(db)
})
it('recovers from a stored activityWindowMinutes outside the allowed options without losing other preferences', () => {
db.prepare(
`INSERT INTO user_preferences (user_id, preferences, updated_at)
VALUES (?, ?, ?)`
).run('default', JSON.stringify({ activityWindowMinutes: 5, autoScroll: false }), Date.now())
const settings = settingsService.getSettings()
expect(settings.preferences.activityWindowMinutes).toBe(DEFAULT_ACTIVITY_WINDOW_MINUTES)
expect(settings.preferences.autoScroll).toBe(false)
})
})
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest'
import {
ACTIVITY_WINDOW_MINUTE_OPTIONS,
ActivityWindowMinutesSchema,
UserPreferencesSchema,
} from '@opencode-manager/shared/schemas'
describe('ActivityWindowMinutesSchema', () => {
it.each(ACTIVITY_WINDOW_MINUTE_OPTIONS)('accepts the configured option %s', (minutes) => {
expect(ActivityWindowMinutesSchema.safeParse(minutes).success).toBe(true)
})
it.each([5, 45, 2000, 30.5])('rejects %s', (minutes) => {
expect(ActivityWindowMinutesSchema.safeParse(minutes).success).toBe(false)
})
it('rejects a non-option value through UserPreferencesSchema', () => {
expect(UserPreferencesSchema.shape.activityWindowMinutes.safeParse(45).success).toBe(false)
expect(UserPreferencesSchema.shape.activityWindowMinutes.safeParse(60).success).toBe(true)
})
})
+13
View File
@@ -125,6 +125,19 @@ describe('OpenCode facade', () => {
expect(lastRequest().init.method).toBe('GET')
})
it('omits the parentID filter when including child sessions', async () => {
fetchMock.mockResolvedValue(
jsonResponse({ data: [sessionInfo('ses_child', '/repo')], cursor: {} }),
)
await listSessionPage({ directory: '/repo', limit: 25, order: 'desc', includeChildren: true })
expect(lastRequest().url).toBe(
'http://localhost/api/opencode/api/session?limit=25&order=desc&directory=%2Frepo',
)
expect(lastRequest().init.method).toBe('GET')
})
it('reads a single session from the V2 session route', async () => {
fetchMock.mockResolvedValue(jsonResponse({ data: sessionInfo('ses_1', '/repo') }))
+2 -1
View File
@@ -48,6 +48,7 @@ export interface SessionPageInput {
order?: 'asc' | 'desc'
search?: string
cursor?: string
includeChildren?: boolean
}
export interface CreateSessionInput {
@@ -102,7 +103,7 @@ export async function listSessionPage(input: SessionPageInput): Promise<SessionP
...(input.directory === undefined ? {} : { directory: input.directory }),
...(input.project === undefined ? {} : { project: input.project }),
...(input.subpath === undefined ? {} : { subpath: input.subpath }),
parentID: 'null',
...(input.includeChildren ? {} : { parentID: 'null' }),
limit: input.limit,
order: input.order,
search: input.search,
@@ -48,6 +48,7 @@ function createItem(
return {
key: `${overrides.repo.id}:${overrides.session.id}`,
path: `/repos/${overrides.repo.id}/sessions/${overrides.session.id}`,
updatedAt: overrides.session.time.updated,
...overrides,
}
}
@@ -85,7 +85,7 @@ function ActivityRow({ item, isCurrent, onSelect }: ActivityRowProps) {
<span className="block truncate text-xs text-muted-foreground">{repoLine}</span>
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{formatShortRelativeTime(new Date(item.session.time.updated))}
{formatShortRelativeTime(new Date(item.updatedAt))}
</span>
</button>
)
@@ -109,7 +109,7 @@ function CompactActivityRow({ item, isCurrent, onSelect }: ActivityRowProps) {
{getRepoDisplayName(item.repo)}
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{formatShortRelativeTime(new Date(item.session.time.updated))}
{formatShortRelativeTime(new Date(item.updatedAt))}
</span>
</button>
)
@@ -37,6 +37,7 @@ function createActiveWorkItem(): ActiveWorkItem {
return {
key: '1:s1',
state: 'recent',
updatedAt: now,
path: '/repos/1/sessions/s1',
session: {
id: 's1',
@@ -105,12 +105,14 @@ function createRepo(id: number, name: string, fullPath: string) {
}
function createActiveWorkItem(): ActiveWorkItem {
const session = createSession('s1', Date.now(), '/path/to/repo1')
return {
key: '1:s1',
state: 'recent',
path: '/repos/1/sessions/s1',
session: createSession('s1', Date.now(), '/path/to/repo1'),
session,
repo: createRepo(1, 'repo1', '/path/to/repo1'),
updatedAt: session.time.updated,
path: '/repos/1/sessions/s1',
}
}
@@ -127,6 +127,7 @@ function createActivityItem(id: string, title: string, repoId: number, repoName:
session,
repo,
state: 'recent',
updatedAt: session.time.updated,
path: `/repos/${repoId}/sessions/${id}`,
}
}
@@ -131,11 +131,13 @@ function activeWorkItem(
state: ActiveWorkState = 'recent',
): ActiveWorkItem {
const itemRepo = mocks.repos.find((candidate) => candidate.fullPath === directory) ?? mocks.repos[0]
const itemSession = session(id, title, directory)
return {
key: `${directory}:${id}`,
session: session(id, title, directory),
session: itemSession,
repo: itemRepo,
state,
updatedAt: itemSession.time.updated,
path: `/repos/${itemRepo.id}/sessions/${id}`,
}
}
@@ -72,6 +72,7 @@ interface SessionPickerRow {
key: string
session: Session
repo: Repo
updatedAt?: number
}
interface SessionPickerSection {
@@ -262,7 +263,7 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
>
{showRepo && <span className="max-w-32 truncate">{getRepoDisplayName(row.repo)}</span>}
{!showRepo && label && <span className="max-w-32 truncate">{label}</span>}
<span>{formatShortRelativeTime(new Date(row.session.time.updated))}</span>
<span>{formatShortRelativeTime(new Date(row.updatedAt ?? row.session.time.updated))}</span>
</span>
</div>
<div className="flex shrink-0 items-center pr-1">
@@ -811,7 +812,7 @@ function ActivePickerContent({
const rows: SessionPickerRow[] = []
for (const item of groups[definition.key]) {
if (needle && !(item.session.title ?? '').toLowerCase().includes(needle)) continue
rows.push({ key: item.key, session: item.session, repo: item.repo })
rows.push({ key: item.key, session: item.session, repo: item.repo, updatedAt: item.updatedAt })
}
return rows.length > 0 ? [{ id: definition.key, heading: definition.heading, rows }] : []
})
@@ -49,13 +49,6 @@ describe('ActivitySettings', () => {
expect(screen.getByRole('combobox', { name: 'Recent activity window' })).toHaveTextContent('2 hours')
})
it('shows a stored window that is not a preset option', () => {
mockUseSettings({ preferences: { ...basePreferences, activityWindowMinutes: 45 } })
render(<ActivitySettings />)
expect(screen.getByRole('combobox', { name: 'Recent activity window' })).toHaveTextContent('45 minutes')
})
it('saves the chosen window in minutes', async () => {
const user = userEvent.setup()
const updateSettings = vi.fn()
@@ -1,4 +1,3 @@
import { useMemo } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
@@ -9,15 +8,6 @@ export function ActivitySettings() {
const { preferences, updateSettings } = useSettings()
const activityWindowMinutes = preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES
const windowOptions = useMemo(() => {
const options: number[] = [...ACTIVITY_WINDOW_MINUTE_OPTIONS]
if (!options.includes(activityWindowMinutes)) {
options.push(activityWindowMinutes)
options.sort((a, b) => a - b)
}
return options
}, [activityWindowMinutes])
return (
<div className="space-y-6">
<h2 className="text-lg font-semibold text-foreground">Activity</h2>
@@ -31,13 +21,18 @@ export function ActivitySettings() {
</div>
<Select
value={String(activityWindowMinutes)}
onValueChange={(value) => updateSettings({ activityWindowMinutes: Number(value) })}
onValueChange={(value) => {
const minutes = ACTIVITY_WINDOW_MINUTE_OPTIONS.find((option) => String(option) === value)
if (minutes !== undefined) {
updateSettings({ activityWindowMinutes: minutes })
}
}}
>
<SelectTrigger id="activityWindowMinutes" className="w-full shrink-0 sm:w-40">
<SelectValue placeholder="Select a window" />
</SelectTrigger>
<SelectContent>
{windowOptions.map((minutes) => (
{ACTIVITY_WINDOW_MINUTE_OPTIONS.map((minutes) => (
<SelectItem key={minutes} value={String(minutes)}>
{formatActivityWindow(minutes)}
</SelectItem>
+23 -3
View File
@@ -11,6 +11,7 @@ import {
buildRepoActivityIndex,
collectActiveRoots,
repoActivityFromIndex,
rootSessionID,
type ActiveWorkGroups,
} from '@/lib/activeWork'
import {
@@ -103,15 +104,27 @@ export function useActiveWork(windowMs: number): {
} = useSessionsAcrossDirectories(repoDirectories, {
allDirectories: true,
limit: ACTIVE_WORK_SESSION_LIMIT,
includeChildren: true,
})
const statuses = useSessionStatus((state) => state.statuses)
const parents = useSessionStatus((state) => state.parents)
const storeParents = useSessionStatus((state) => state.parents)
const runningShells = useSessionStatus((state) => state.runningShells)
const outcomes = useSessionStatus((state) => state.outcomes)
const sessionDirectories = useSessionStatus((state) => state.directories)
const pendingInputSessionIDs = usePendingInputSessionIDs()
const parents = useMemo(() => {
const merged = new Map<string, string | null>()
for (const session of sessions) {
merged.set(session.id, session.parentID ?? null)
}
for (const [sessionID, parentID] of storeParents) {
if (!merged.has(sessionID)) merged.set(sessionID, parentID)
}
return merged
}, [sessions, storeParents])
const roots = useMemo(
() => collectActiveRoots({ statuses, parents, runningShells, pendingInputSessionIDs }),
[statuses, parents, runningShells, pendingInputSessionIDs],
@@ -124,6 +137,12 @@ export function useActiveWork(windowMs: number): {
const missingRootIDs = useMemo(() => {
const ids = new Set<string>()
const windowStart = Date.now() - windowMs
for (const session of sessions) {
if (session.time.updated < windowStart) continue
const rootID = rootSessionID(session.id, parents)
if (!listedSessionIDs.has(rootID)) ids.add(rootID)
}
for (const sessionID of roots.needsInput) {
if (!listedSessionIDs.has(sessionID)) ids.add(sessionID)
}
@@ -131,7 +150,7 @@ export function useActiveWork(windowMs: number): {
if (!listedSessionIDs.has(sessionID)) ids.add(sessionID)
}
return [...ids]
}, [roots, listedSessionIDs])
}, [sessions, parents, listedSessionIDs, roots, windowMs])
const fetchedSessions = useQueries({
queries: missingRootIDs.map((sessionID) =>
@@ -152,10 +171,11 @@ export function useActiveWork(windowMs: number): {
windowMs,
repos,
sessions: mergedSessions,
parents,
roots,
outcomes,
}),
[windowMs, repos, mergedSessions, roots, outcomes],
[windowMs, repos, mergedSessions, parents, roots, outcomes],
)
return {
+55
View File
@@ -174,6 +174,61 @@ describe('useSessionsAcrossDirectories', () => {
expect(result.current.data.map((session) => session.id)).toEqual(['ses_all1', 'ses_all2'])
})
it('requests child sessions and records includeChildren in the query key', async () => {
mocks.listSessionPage.mockResolvedValue({ items: [sessionInfo('ses_child', '/w/a')] })
const queryClient = createQueryClient()
const { result } = renderHook(
() => useSessionsAcrossDirectories(['/w/a'], { includeChildren: true }),
{ wrapper: createWrapper(queryClient) },
)
await waitFor(() => {
expect(result.current.isLoading).toBe(false)
})
expect(mocks.listSessionPage).toHaveBeenCalledWith({
directory: '/w/a',
limit: 25,
order: 'desc',
search: undefined,
includeChildren: true,
})
expect(queryClient.getQueryCache().getAll()[0]?.queryKey).toEqual([
'opencode',
'sessions',
'/w/a',
{
search: undefined,
limit: 25,
allDirectories: false,
project: undefined,
subpath: undefined,
includeChildren: true,
},
])
})
it('keeps root-only and include-children lists in distinct cache entries', async () => {
mocks.listSessionPage.mockResolvedValue({ items: [] })
const queryClient = createQueryClient()
const wrapper = createWrapper(queryClient)
renderHook(() => useSessionsAcrossDirectories(['/w/a']), { wrapper })
renderHook(() => useSessionsAcrossDirectories(['/w/a'], { includeChildren: true }), { wrapper })
await waitFor(() => {
expect(mocks.listSessionPage).toHaveBeenCalledTimes(2)
})
const optionObjects = queryClient
.getQueryCache()
.getAll()
.map((query) => query.queryKey[3] as { includeChildren?: boolean })
expect(optionObjects.some((options) => options.includeChildren === true)).toBe(true)
expect(optionObjects.some((options) => options.includeChildren === false)).toBe(true)
})
it('pages a project scope through one cursor query with project and subpath', async () => {
mocks.listSessionPage.mockImplementation(async ({ cursor }: { cursor?: string }) => {
if (cursor === 'cursor_project') {
+10 -3
View File
@@ -44,6 +44,7 @@ interface UseSessionsAcrossDirectoriesOptions {
keepPreviousResults?: boolean
allDirectories?: boolean
project?: { id: string; subpath: string }
includeChildren?: boolean
}
type SessionDirectoryCursors = Record<string, string>
@@ -73,7 +74,9 @@ export const useSessionsAcrossDirectories = (
const projectSubpath = options?.project?.subpath;
const projectScoped = !allDirectories && projectId !== undefined;
const singleCursor = allDirectories || projectScoped;
const includeChildren = options?.includeChildren ?? false;
const directoryKey = uniqueDirectories.join('|');
const childSessionsParam = includeChildren ? { includeChildren: true } : {};
const query = useInfiniteQuery<
SessionListPage,
@@ -86,7 +89,7 @@ export const useSessionsAcrossDirectories = (
'opencode',
'sessions',
directoryKey,
{ search: normalizedSearch, limit, allDirectories, project: projectId, subpath: projectSubpath },
{ search: normalizedSearch, limit, allDirectories, project: projectId, subpath: projectSubpath, includeChildren },
],
queryFn: async ({ pageParam }) => {
if (singleCursor) {
@@ -98,8 +101,9 @@ export const useSessionsAcrossDirectories = (
order: 'desc',
search: normalizedSearch,
...(projectScoped ? { project: projectId, subpath: projectSubpath } : {}),
...childSessionsParam,
}
: { cursor },
: { cursor, ...childSessionsParam },
);
return {
items: page.items,
@@ -115,6 +119,7 @@ export const useSessionsAcrossDirectories = (
limit,
order: 'desc',
search: normalizedSearch,
...childSessionsParam,
}),
),
);
@@ -134,7 +139,9 @@ export const useSessionsAcrossDirectories = (
const entries = Object.entries(pageParam.cursors);
const pages = await Promise.all(
entries.map(([directory, cursor]) => listSessionPage({ directory, cursor })),
entries.map(([directory, cursor]) =>
listSessionPage({ directory, cursor, ...childSessionsParam }),
),
);
const cursors: SessionDirectoryCursors = {};
const items: SessionInfo[] = [];
+63 -8
View File
@@ -15,7 +15,7 @@ import {
const NOW = 1_000_000_000_000
const WINDOW_MS = 60_000
function createSession(id: string, updated: number, directory: string): Session {
function createSession(id: string, updated: number, directory: string, parentID?: string): Session {
return {
id,
projectID: 'proj-1',
@@ -24,6 +24,7 @@ function createSession(id: string, updated: number, directory: string): Session
location: { directory },
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
...(parentID ? { parentID } : {}),
}
}
@@ -264,7 +265,7 @@ describe('buildActiveWork', () => {
})
const sessions = [createSession('root', NOW - 1000, '/repos/a')]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots, outcomes: new Map() })
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents: new Map(), roots, outcomes: new Map() })
expect(groups.needsInput.map((item) => item.session.id)).toEqual(['root'])
expect(groups.running).toEqual([])
@@ -278,7 +279,7 @@ describe('buildActiveWork', () => {
createSession('outside', NOW - WINDOW_MS - 1, '/repos/a'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes: new Map() })
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents: new Map(), roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['inside'])
})
@@ -288,7 +289,7 @@ describe('buildActiveWork', () => {
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() })
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents: new Map(), roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['active'])
})
@@ -296,7 +297,7 @@ describe('buildActiveWork', () => {
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() })
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents: new Map(), roots: emptyRoots, outcomes: new Map() })
expect(groups.recent).toEqual([])
})
@@ -305,7 +306,7 @@ describe('buildActiveWork', () => {
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() })
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repo], sessions, parents: new Map(), roots: emptyRoots, outcomes: new Map() })
expect(groups.recent).toHaveLength(1)
expect(groups.recent[0].repo.id).toBe(5)
@@ -320,7 +321,7 @@ describe('buildActiveWork', () => {
createSession('middle', NOW - 2000, '/repos/a'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, roots: emptyRoots, outcomes: new Map() })
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents: new Map(), roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['newest', 'middle', 'oldest'])
})
@@ -329,8 +330,62 @@ describe('buildActiveWork', () => {
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 })
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents: new Map(), roots: emptyRoots, outcomes })
expect(groups.recent[0].outcome).toBe('failed')
})
it('rolls a child updated inside the window up to its root for the recent test and updatedAt', () => {
const parents = new Map<string, string | null>([['child', 'root'], ['root', null]])
const sessions = [
createSession('root', NOW - WINDOW_MS - 1, '/repos/a'),
createSession('child', NOW - 1000, '/repos/a', 'root'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['root'])
expect(groups.recent[0].updatedAt).toBe(NOW - 1000)
})
it('sorts by the rolled-up time and never emits children or grandchildren', () => {
const parents = new Map<string, string | null>([
['child-of-a', 'root-a'],
['grandchild-of-a', 'child-of-a'],
['root-a', null],
['root-b', null],
])
const sessions = [
createSession('root-a', NOW - 5000, '/repos/a'),
createSession('child-of-a', NOW - 4000, '/repos/a', 'root-a'),
createSession('grandchild-of-a', NOW - 1000, '/repos/a', 'child-of-a'),
createSession('root-b', NOW - 2000, '/repos/a'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['root-a', 'root-b'])
expect(groups.recent[0].updatedAt).toBe(NOW - 1000)
})
it('does not emit a child whose root is absent from the input', () => {
const parents = new Map<string, string | null>([['child', 'root']])
const sessions = [createSession('child', NOW - 1000, '/repos/a', 'root')]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent).toEqual([])
})
it('emits the root once it is supplied alongside its child', () => {
const parents = new Map<string, string | null>([['child', 'root'], ['root', null]])
const sessions = [
createSession('child', NOW - 1000, '/repos/a', 'root'),
createSession('root', NOW - WINDOW_MS - 1, '/repos/a'),
]
const groups = buildActiveWork({ now: NOW, windowMs: WINDOW_MS, repos: [repoA], sessions, parents, roots: emptyRoots, outcomes: new Map() })
expect(groups.recent.map((item) => item.session.id)).toEqual(['root'])
})
})
+20 -4
View File
@@ -32,6 +32,7 @@ export interface ActiveWorkItem {
session: Session
repo: Repo
state: ActiveWorkState
updatedAt: number
outcome?: ChildOutcome
path: string
}
@@ -186,18 +187,31 @@ export function repoActivityFromIndex(
/**
* 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.
*/
export function buildActiveWork(input: {
now: number
windowMs: number
repos: Repo[]
sessions: Session[]
parents: ReadonlyMap<string, string | null>
roots: { needsInput: Set<string>; running: Set<string> }
outcomes: ReadonlyMap<string, ChildOutcome>
}): ActiveWorkGroups {
const { now, windowMs, repos, sessions, roots, outcomes } = input
const { now, windowMs, repos, sessions, parents, roots, outcomes } = input
const windowStart = now - windowMs
const activityByRoot = new Map<string, number>()
for (const session of sessions) {
if (session.time.archived) continue
const rootID = rootSessionID(session.id, parents)
const current = activityByRoot.get(rootID)
if (current === undefined || session.time.updated > current) {
activityByRoot.set(rootID, session.time.updated)
}
}
const needsInput: ActiveWorkItem[] = []
const running: ActiveWorkItem[] = []
const recent: ActiveWorkItem[] = []
@@ -206,12 +220,14 @@ export function buildActiveWork(input: {
for (const session of sessions) {
if (seen.has(session.id)) continue
if (session.time.archived) continue
if (rootSessionID(session.id, parents) !== session.id) continue
const updatedAt = activityByRoot.get(session.id) ?? session.time.updated
const state: ActiveWorkState | null = roots.needsInput.has(session.id)
? 'needs-input'
: roots.running.has(session.id)
? 'running'
: session.time.updated >= windowStart
: updatedAt >= windowStart
? 'recent'
: null
if (!state) continue
@@ -225,6 +241,7 @@ export function buildActiveWork(input: {
session,
repo,
state,
updatedAt,
outcome: outcomes.get(session.id),
path: getSessionPath(repo.id, session.id),
}
@@ -234,8 +251,7 @@ export function buildActiveWork(input: {
else recent.push(item)
}
const byUpdatedDesc = (a: ActiveWorkItem, b: ActiveWorkItem) =>
b.session.time.updated - a.session.time.updated
const byUpdatedDesc = (a: ActiveWorkItem, b: ActiveWorkItem) => b.updatedAt - a.updatedAt
needsInput.sort(byUpdatedDesc)
running.sort(byUpdatedDesc)
recent.sort(byUpdatedDesc)
+11 -3
View File
@@ -66,10 +66,18 @@ export type STTConfig = {
export const DEFAULT_LEADER_KEY = 'Ctrl+X';
export const DEFAULT_ACTIVITY_WINDOW_MINUTES = 30;
export const ACTIVITY_WINDOW_MINUTE_OPTIONS = [15, 30, 60, 120, 240, 480, 1440] as const;
export const ActivityWindowMinutesSchema = z.literal(ACTIVITY_WINDOW_MINUTE_OPTIONS);
export type ActivityWindowMinutes = z.infer<typeof ActivityWindowMinutesSchema>;
export const DEFAULT_ACTIVITY_WINDOW_MINUTES: ActivityWindowMinutes = 30;
export function isActivityWindowMinutes(value: unknown): value is ActivityWindowMinutes {
return ActivityWindowMinutesSchema.safeParse(value).success;
}
export const DEFAULT_KEYBOARD_SHORTCUTS = {
submit: 'Cmd+Enter',
abort: 'Escape',
@@ -196,7 +204,7 @@ export const UserPreferencesSchema = z.object({
mode: z.enum(["plan", "build"]),
defaultModel: z.string().optional(),
walkthroughModel: z.string().optional(),
activityWindowMinutes: z.number().int().min(5).max(1440).optional(),
activityWindowMinutes: ActivityWindowMinutesSchema.optional(),
defaultAgent: z.string().optional(),
autoScroll: z.boolean(),
expandDiffs: z.boolean(),