feat(schedules): require worktrees and choose commit or discard on removal

Drop the repo workspace mode so every scheduled run executes in a
worktree. Clearing run history or deleting a run now asks whether to
commit pending changes and keep the run branches, or force-remove the
worktrees and delete the branches.

Sibling repo listings carry the schedule name, and the repo detail
workspace view subscribes to schedule worktree sessions only while
expanded. Also unify schedule worktree path/branch helpers, refuse a run
branch already checked out elsewhere, and clean up terminals when a
worktree is removed.
This commit is contained in:
Chris Scott committed 2026-10-06 11:02:29 -04:00
1 parent 6ec3f3bd91
commit 26ff08d891
46 files changed
+1171 -375

No files matched your search

@@ -15,7 +15,6 @@ const makeWorktree = (overrides: Partial<RepoSibling> & Pick<RepoSibling, 'fullP
isWorktree: true,
currentBranch: overrides.currentBranch,
worktreeSource: overrides.worktreeSource,
worktreeStrategy: 'git',
...overrides,
})
@@ -29,14 +28,14 @@ const sharedScheduleWorktree = makeWorktree({
fullPath: '/s/job-14-shared',
currentBranch: 'schedule/14/shared',
worktreeSource: 'schedule',
schedule: { repoId: 1, jobId: 14, runId: null, inUse: true },
schedule: { repoId: 1, jobId: 14, runId: null, inUse: true, name: 'Nightly' },
})
const runScheduleWorktree = makeWorktree({
fullPath: '/s/job-14-run-340',
currentBranch: 'schedule/14/run-340',
worktreeSource: 'schedule',
schedule: { repoId: 1, jobId: 14, runId: 340, inUse: false },
schedule: { repoId: 1, jobId: 14, runId: 340, inUse: false, name: 'Nightly' },
})
const manualWorktree = makeWorktree({
@@ -74,6 +73,7 @@ function renderGroups(overrides: {
worktrees?: RepoSibling[]
sessions?: Session[]
searchQuery?: string
onExpandedScheduleDirectoriesChange?: (directories: string[]) => void
} = {}) {
return render(
<WorktreeSessionGroups
@@ -81,8 +81,8 @@ function renderGroups(overrides: {
worktrees={overrides.worktrees ?? allWorktrees}
sessions={overrides.sessions ?? [featureSession]}
searchQuery={overrides.searchQuery ?? ''}
scheduleNames={{ 14: 'Dependency audit' }}
renderSessionCard={(session) => <div key={session.id}>{session.title}</div>}
onExpandedScheduleDirectoriesChange={overrides.onExpandedScheduleDirectoriesChange}
onNewSession={onNewSession}
onOpenTerminal={onOpenTerminal}
onCreateWorktree={onCreateWorktree}
@@ -100,9 +100,9 @@ describe('WorktreeSessionGroups', () => {
expect(screen.getByText('Auth work')).toBeInTheDocument()
expect(screen.getByText('1 session')).toBeInTheDocument()
expect(screen.getByText('Dependency audit')).toBeInTheDocument()
expect(screen.getByText('Schedule · shared')).toBeInTheDocument()
expect(screen.getByText('Schedule · run #340')).toBeInTheDocument()
expect(screen.getByText('Nightly')).toBeInTheDocument()
expect(screen.getByText('Schedule · Shared worktree')).toBeInTheDocument()
expect(screen.getByText('Schedule · Run #340')).toBeInTheDocument()
expect(screen.getByText('in use')).toBeInTheDocument()
expect(screen.getByText('Git')).toBeInTheDocument()
@@ -157,7 +157,7 @@ describe('WorktreeSessionGroups', () => {
expect(screen.getByText('manual')).toBeInTheDocument()
expect(screen.queryByText('feature/auth')).not.toBeInTheDocument()
expect(screen.queryByText('Dependency audit')).not.toBeInTheDocument()
expect(screen.queryByText('Nightly')).not.toBeInTheDocument()
})
it('collapses a worktree and persists the collapsed state across remount', async () => {
@@ -172,12 +172,23 @@ describe('WorktreeSessionGroups', () => {
expect(screen.queryByText('Auth work')).not.toBeInTheDocument()
})
it('reports a schedule worktree directory only after its group is expanded', async () => {
const onExpandedScheduleDirectoriesChange = vi.fn()
renderGroups({ onExpandedScheduleDirectoriesChange })
expect(onExpandedScheduleDirectoriesChange).toHaveBeenLastCalledWith([])
await userEvent.click(screen.getByRole('button', { expanded: false, name: /schedule\/14\/shared/ }))
expect(onExpandedScheduleDirectoriesChange).toHaveBeenLastCalledWith(['/s/job-14-shared'])
})
it('hides empty worktrees while searching and renders the empty state when there are none', async () => {
const { unmount } = renderGroups({ searchQuery: 'auth' })
expect(screen.getByText('feature/auth')).toBeInTheDocument()
expect(screen.queryByText('manual')).not.toBeInTheDocument()
expect(screen.queryByText('Dependency audit')).not.toBeInTheDocument()
expect(screen.queryByText('Nightly')).not.toBeInTheDocument()
unmount()
renderGroups({ worktrees: [], sessions: [] })
@@ -13,8 +13,8 @@ interface WorktreeSessionGroupsProps {
worktrees: RepoSibling[]
sessions: Session[]
searchQuery: string
scheduleNames: Record<number, string>
renderSessionCard: (session: Session) => ReactNode
onExpandedScheduleDirectoriesChange?: (directories: string[]) => void
onNewSession: (directory: string) => void
onOpenTerminal: (directory: string) => void
onCreateWorktree: () => void
@@ -31,7 +31,7 @@ interface WorktreeGroup {
type GroupEntry =
| { kind: 'worktree'; key: string; group: WorktreeGroup; lastActive: number }
| { kind: 'schedule'; key: string; jobId: number; groups: WorktreeGroup[]; lastActive: number }
| { kind: 'schedule'; key: string; jobId: number; name: string; groups: WorktreeGroup[]; lastActive: number }
const OWNER_FILTERS: Array<{ value: OwnerFilter; label: string }> = [
{ value: 'all', label: 'All' },
@@ -57,8 +57,8 @@ export function WorktreeSessionGroups({
worktrees,
sessions,
searchQuery,
scheduleNames,
renderSessionCard,
onExpandedScheduleDirectoriesChange,
onNewSession,
onOpenTerminal,
onCreateWorktree,
@@ -67,9 +67,21 @@ export function WorktreeSessionGroups({
}: WorktreeSessionGroupsProps) {
const [ownerFilter, setOwnerFilter] = useState<OwnerFilter>('all')
const [collapsed, setCollapsed] = useCollapsedGroups(repoId)
const [expandedSchedule, setExpandedSchedule] = useState<Set<string>>(new Set())
const [pendingDelete, setPendingDelete] = useState<{ directories: string[]; label: string } | null>(null)
const isSearching = searchQuery.trim().length > 0
const scheduleWorktreeDirectories = useMemo(
() => worktrees.filter(isScheduleWorktree).map((worktree) => worktree.fullPath),
[worktrees],
)
useEffect(() => {
onExpandedScheduleDirectoriesChange?.(
scheduleWorktreeDirectories.filter((directory) => expandedSchedule.has(directory)),
)
}, [expandedSchedule, scheduleWorktreeDirectories, onExpandedScheduleDirectoriesChange])
const ownerCounts = useMemo(() => {
const counts: Record<OwnerFilter, number> = { all: worktrees.length, opencode: 0, schedule: 0, git: 0 }
worktrees.forEach((worktree) => {
@@ -92,10 +104,46 @@ export function WorktreeSessionGroups({
})
}
const allKeys = entries.flatMap((entry) => (
entry.kind === 'schedule' ? [entry.key, ...entry.groups.map((group) => groupKey(group.directory))] : [entry.key]
const isGroupOpen = (group: WorktreeGroup) => (
isScheduleWorktree(group.worktree)
? expandedSchedule.has(group.directory)
: !collapsed.has(groupKey(group.directory))
)
const toggleGroup = (group: WorktreeGroup) => {
if (isScheduleWorktree(group.worktree)) {
setExpandedSchedule((current) => {
const next = new Set(current)
if (next.has(group.directory)) next.delete(group.directory)
else next.add(group.directory)
return next
})
return
}
toggle(groupKey(group.directory))
}
const scheduleGroupDirectories = entries.flatMap((entry) => (
entry.kind === 'schedule' ? entry.groups.map((group) => group.directory) : []
))
const allCollapsed = allKeys.length > 0 && allKeys.every((key) => collapsed.has(key))
const allCollapsed = entries.length > 0 && entries.every((entry) => {
if (collapsed.has(entry.key)) return true
if (entry.kind === 'schedule') return entry.groups.every((group) => !expandedSchedule.has(group.directory))
return false
})
const toggleAll = () => {
if (allCollapsed) {
setCollapsed((current) => {
const next = new Set(current)
entries.forEach((entry) => next.delete(entry.key))
return next
})
setExpandedSchedule(new Set(scheduleGroupDirectories))
return
}
setCollapsed(new Set(entries.map((entry) => entry.key)))
setExpandedSchedule(new Set())
}
if (worktrees.length === 0) {
return (
@@ -112,7 +160,7 @@ export function WorktreeSessionGroups({
const renderWorktree = (group: WorktreeGroup, nested: boolean) => {
const key = groupKey(group.directory)
const isOpen = !collapsed.has(key)
const isOpen = isGroupOpen(group)
const label = workspaceLabel(group.worktree)
const source = group.worktree.worktreeSource
const sourceLabel = worktreeSourceLabel(group.worktree)
@@ -122,7 +170,7 @@ export function WorktreeSessionGroups({
<div className="flex items-center gap-1 px-2 py-1.5">
<button
type="button"
onClick={() => toggle(key)}
onClick={() => toggleGroup(group)}
aria-expanded={isOpen}
className="flex min-w-0 flex-1 items-center gap-2 rounded px-1 py-1 text-left hover:bg-accent/50"
>
@@ -210,7 +258,7 @@ export function WorktreeSessionGroups({
</button>
))}
<div className="ml-auto flex items-center gap-1">
<Button variant="ghost" size="sm" className="h-8 text-xs" onClick={() => setCollapsed(allCollapsed ? new Set() : new Set(allKeys))}>
<Button variant="ghost" size="sm" className="h-8 text-xs" onClick={toggleAll}>
{allCollapsed ? 'Expand all' : 'Collapse all'}
</Button>
<Button variant="outline" size="sm" className="h-8 text-xs" onClick={onCreateWorktree}>
@@ -227,7 +275,7 @@ export function WorktreeSessionGroups({
) : entries.map((entry) => {
if (entry.kind === 'worktree') return renderWorktree(entry.group, false)
const isOpen = !collapsed.has(entry.key)
const name = scheduleNames[entry.jobId] ?? `Schedule #${entry.jobId}`
const name = entry.name
const removable = worktrees
.filter((worktree) => worktree.schedule?.jobId === entry.jobId && !worktree.schedule.inUse)
.map((worktree) => worktree.fullPath)
@@ -285,6 +333,10 @@ function groupKey(directory: string): string {
return `worktree:${directory}`
}
function isScheduleWorktree(worktree: RepoSibling): boolean {
return worktree.worktreeSource === 'schedule'
}
function buildGroupEntries(
worktrees: RepoSibling[],
sessions: Session[],
@@ -314,19 +366,26 @@ function buildGroupEntries(
const scheduleEntries = new Map<number, Extract<GroupEntry, { kind: 'schedule' }>>()
const entries: GroupEntry[] = []
groups.forEach((group) => {
const jobId = group.worktree.schedule?.jobId
if (jobId === undefined) {
const schedule = group.worktree.schedule
if (!schedule) {
entries.push({ kind: 'worktree', key: groupKey(group.directory), group, lastActive: group.lastActive })
return
}
const existing = scheduleEntries.get(jobId)
const existing = scheduleEntries.get(schedule.jobId)
if (existing) {
existing.groups.push(group)
existing.lastActive = Math.max(existing.lastActive, group.lastActive)
return
}
const entry: Extract<GroupEntry, { kind: 'schedule' }> = { kind: 'schedule', key: `schedule:${jobId}`, jobId, groups: [group], lastActive: group.lastActive }
scheduleEntries.set(jobId, entry)
const entry: Extract<GroupEntry, { kind: 'schedule' }> = {
kind: 'schedule',
key: `schedule:${schedule.jobId}`,
jobId: schedule.jobId,
name: schedule.name,
groups: [group],
lastActive: group.lastActive,
}
scheduleEntries.set(schedule.jobId, entry)
entries.push(entry)
})
@@ -14,7 +14,6 @@ const makeWorkspaceSibling = (branch: string): RepoSibling => ({
isWorktree: true,
currentBranch: branch,
branch,
worktreeStrategy: 'git',
worktreeSource: 'opencode',
})
@@ -173,23 +173,21 @@ export function GeneralTab({
/>
</div>
)}
{workspaceMode !== 'repo' && (
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="schedule-branch">Base branch</Label>
<InfoHint text="New run worktrees branch off this base branch. A shared worktree only uses it when it is first created. Leave empty to use the repository's default branch." />
</div>
<BranchCombobox
id="schedule-branch"
repoId={branchRepoId}
value={branch}
onValueChange={onBranchChange}
placeholder="Defaults to default branch"
remotes="bare"
clearable
/>
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="schedule-branch">Base branch</Label>
<InfoHint text="Runs start from origin/<branch> when it exists, so local commits that are not pushed are not included. A shared worktree continues from its own branch after the first run. Leave empty to use the repository's default branch." />
</div>
)}
<BranchCombobox
id="schedule-branch"
repoId={branchRepoId}
value={branch}
onValueChange={onBranchChange}
placeholder="Defaults to default branch"
remotes="bare"
clearable
/>
</div>
</div>
<div className="space-y-2">
@@ -11,6 +11,7 @@ import {
} from '@/components/schedules/schedule-utils'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { useRemoveScheduleWorktrees, useScheduleWorktrees } from '@/hooks/useSchedules'
import { formatScheduleWorktreeLabel } from '@/lib/schedules/schedule-worktree'
import { Bot, CalendarClock, Clock3, GitBranch, History, Loader2, Pencil, Play, Sparkles, Trash2 } from 'lucide-react'
import { useScheduleModels } from '@/hooks/useScheduleModels'
import { resolveScheduleModel } from '@/lib/schedules/schedule-model'
@@ -139,7 +140,7 @@ export function JobDetailTab({
<div className="min-w-0">
<p className="truncate font-mono text-sm">{worktree.branch}</p>
<p className="truncate text-xs text-muted-foreground" title={worktree.worktreePath}>
{worktree.runId === null ? 'Shared worktree' : `Run #${worktree.runId}`}
{formatScheduleWorktreeLabel(worktree.runId)}
{worktree.inUse ? ' · in use' : ''} · {worktree.worktreePath}
</p>
</div>
@@ -0,0 +1,47 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ScheduleRunRemovalDialog } from './ScheduleRunRemovalDialog'
type DialogProps = Parameters<typeof ScheduleRunRemovalDialog>[0]
function renderDialog(overrides: Partial<DialogProps> = {}) {
const props: DialogProps = {
open: true,
onOpenChange: vi.fn(),
title: 'Delete run',
description: 'This permanently deletes this run.',
affectedWorktreeCount: 0,
isPending: false,
onCancel: vi.fn(),
onConfirm: vi.fn(),
...overrides,
}
render(<ScheduleRunRemovalDialog {...props} />)
return props
}
describe('ScheduleRunRemovalDialog', () => {
it('confirms without a worktrees mode when no kept worktree is affected', async () => {
const user = userEvent.setup()
const props = renderDialog()
await user.click(screen.getByRole('button', { name: 'Delete' }))
expect(props.onConfirm).toHaveBeenCalledWith()
})
it('offers commit and force delete when kept worktrees are affected', async () => {
const user = userEvent.setup()
const onConfirm = vi.fn()
renderDialog({ affectedWorktreeCount: 2, onConfirm })
expect(screen.getByText(/2 kept worktrees will be removed/)).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Commit and remove' }))
expect(onConfirm).toHaveBeenCalledWith('commit')
await user.click(screen.getByRole('button', { name: 'Force delete' }))
expect(onConfirm).toHaveBeenCalledWith('discard')
})
})
@@ -0,0 +1,100 @@
import type { ReactNode } from 'react'
import type { ScheduleRunWorktreesMode } from '@opencode-manager/shared/types'
import { Button } from '@/components/ui/button'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AlertTriangle, Loader2 } from 'lucide-react'
interface ScheduleRunRemovalDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
title: string
description: ReactNode
affectedWorktreeCount: number
isPending: boolean
onCancel: () => void
onConfirm: (worktrees?: ScheduleRunWorktreesMode) => void
}
export function ScheduleRunRemovalDialog({
open,
onOpenChange,
title,
description,
affectedWorktreeCount,
isPending,
onCancel,
onConfirm,
}: ScheduleRunRemovalDialogProps) {
if (affectedWorktreeCount === 0) {
return (
<DeleteDialog
open={open}
onOpenChange={onOpenChange}
onConfirm={() => onConfirm()}
onCancel={onCancel}
title={title}
description={description}
isDeleting={isPending}
/>
)
}
const worktreeLabel = `${affectedWorktreeCount} kept worktree${affectedWorktreeCount === 1 ? '' : 's'}`
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[90%] sm:max-w-md">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<Alert className="overflow-hidden">
<AlertTriangle className="h-4 w-4 flex-shrink-0" />
<AlertDescription className="break-words">
{worktreeLabel} will be removed. Choose how to handle {affectedWorktreeCount === 1 ? 'it' : 'them'}.
</AlertDescription>
</Alert>
<div className="space-y-2 text-sm">
<p>
<span className="font-medium">Commit and remove</span> — pending changes are committed to each run branch, then the worktree folders are removed. The branches are kept.
</p>
<p>
<span className="font-medium">Force delete</span> — the worktree folders are force-removed and their run branches deleted. Any uncommitted changes are lost.
</p>
</div>
<DialogFooter className="gap-2">
<Button
variant="outline"
onClick={onCancel}
disabled={isPending}
className="flex-1 sm:flex-none"
>
Cancel
</Button>
<Button
variant="destructive"
onClick={() => onConfirm('discard')}
disabled={isPending}
className="flex-1 sm:flex-none"
>
{isPending && <Loader2 className="h-4 w-4 animate-spin" />}
Force delete
</Button>
<Button
onClick={() => onConfirm('commit')}
disabled={isPending}
className="flex-1 sm:flex-none"
>
{isPending && <Loader2 className="h-4 w-4 animate-spin" />}
Commit and remove
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,6 +1,7 @@
export { ScheduleJobsTable } from './ScheduleJobsTable'
export { JobDetailTab } from './JobDetailTab'
export { RunHistoryTab } from './RunHistoryTab'
export { ScheduleRunRemovalDialog } from './ScheduleRunRemovalDialog'
export { ScheduleRunDrawer } from './ScheduleRunDrawer'
export { ScheduleRunsTable } from './ScheduleRunsTable'
export { RunDetailPanel } from './RunDetailPanel'
@@ -56,11 +56,6 @@ export const workspaceModeOptions: Array<RadioOption<ScheduleWorkspaceMode>> = [
label: 'Shared worktree',
description: 'Every run reuses one worktree and branch, so work builds up from run to run.',
},
{
value: 'repo',
label: 'Repository checkout',
description: 'Runs directly in the repository working directory. Nothing is isolated, committed, or cleaned up.',
},
]
export function formatWorkspaceMode(mode: ScheduleWorkspaceMode): string {
@@ -14,7 +14,6 @@ interface SessionCardProps {
isSelected: boolean;
isActive: boolean;
manageMode: boolean;
workspaceLabel?: string;
isPinned?: boolean;
onTogglePin?: () => void;
onSelect: (sessionID: string) => void;
@@ -27,7 +26,6 @@ export const SessionCard = ({
isSelected,
isActive,
manageMode,
workspaceLabel,
isPinned,
onTogglePin,
onSelect,
@@ -117,9 +115,6 @@ export const SessionCard = ({
addSuffix: true,
})}
</span>
{workspaceLabel ? (
<span className="text-primary truncate max-w-[140px]">{workspaceLabel}</span>
) : null}
</div>
</div>
</div>
@@ -139,9 +134,6 @@ export const SessionCard = ({
addSuffix: true,
})}
</span>
{workspaceLabel ? (
<span className="text-primary truncate max-w-[120px]">{workspaceLabel}</span>
) : null}
<SessionStatusIndicator sessionID={session.id} size="sm" />
</div>
</div>
@@ -16,7 +16,6 @@ interface SessionListProps {
directory?: string;
directories?: string[];
createDirectory?: string;
directoryLabels?: Record<string, string>;
activeSessionID?: string;
onSelectSession: (sessionID: string) => void;
renderSessions?: (args: SessionListRenderArgs) => ReactNode;
@@ -36,7 +35,6 @@ export const SessionList = ({
directory,
directories,
createDirectory,
directoryLabels,
activeSessionID,
onSelectSession,
renderSessions,
@@ -220,7 +218,6 @@ export const SessionList = ({
isSelected={selectedSessions.has(key)}
isActive={activeSessionID === session.id}
manageMode={manageMode}
workspaceLabel={directoryLabels?.[session.location.directory]}
isPinned={isPinned}
onSelect={onSelectSession}
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}