feat(schedules): add workspace modes and worktree management

This commit is contained in:
Chris Scott committed 2026-10-06 10:16:34 -04:00
1 parent c06075651d
commit 6ec3f3bd91
90 files changed
+2084 -801

No files matched your search

@@ -1,250 +0,0 @@
import { useEffect, useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { GitBranch, Plus, Search, Trash2 } from 'lucide-react'
import { workspaceLabel, type RepoSibling } from '@/api/repos'
interface WorkspaceManagerProps {
open: boolean
onOpenChange: (open: boolean) => void
workspaces: RepoSibling[]
onDelete: (directories: string[]) => void
activeWorkspaceDirectory?: string
onActiveWorkspaceChange: (directory: string) => void
onCreateWorkspace: () => void
isDeleting?: boolean
}
export function WorkspaceManager({
open,
onOpenChange,
workspaces,
onDelete,
activeWorkspaceDirectory,
onActiveWorkspaceChange,
onCreateWorkspace,
isDeleting = false,
}: WorkspaceManagerProps) {
const [selected, setSelected] = useState<Set<string>>(new Set())
const [confirmOpen, setConfirmOpen] = useState(false)
const [manageMode, setManageMode] = useState(false)
const [searchQuery, setSearchQuery] = useState('')
useEffect(() => {
if (!open) {
setSearchQuery('')
}
}, [open])
const filteredWorkspaces = useMemo(() => {
const query = searchQuery.trim().toLowerCase()
if (!query) return workspaces
return workspaces.filter((workspace) => {
const haystack = [
workspaceLabel(workspace),
workspace.fullPath,
workspace.worktreeStrategy,
]
.filter(Boolean)
.join(' ')
.toLowerCase()
return haystack.includes(query)
})
}, [searchQuery, workspaces])
const selectableDirectories = useMemo(
() => filteredWorkspaces.map((workspace) => workspace.fullPath).filter((directory): directory is string => !!directory),
[filteredWorkspaces],
)
const allSelected = selectableDirectories.length > 0 && selectableDirectories.every((directory) => selected.has(directory))
const selectedCount = selected.size
const toggle = (directory: string, checked: boolean) => {
setSelected((prev) => {
const next = new Set(prev)
if (checked) {
next.add(directory)
} else {
next.delete(directory)
}
return next
})
}
const toggleAll = () => {
setSelected(allSelected ? new Set() : new Set(selectableDirectories))
}
const handleConfirm = () => {
onDelete(Array.from(selected))
setSelected(new Set())
setManageMode(false)
setConfirmOpen(false)
}
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen className="flex flex-col gap-0 overflow-hidden p-0 sm:max-h-[85vh] sm:max-w-[560px]">
<DialogHeader className="border-b border-border px-4 py-4">
<DialogTitle>Workspaces</DialogTitle>
<DialogDescription>Choose where new sessions should start.</DialogDescription>
</DialogHeader>
<div className="flex min-h-0 flex-1 flex-col gap-3 p-4">
<div className="flex items-center justify-between gap-3">
{manageMode ? (
<div className="flex items-center gap-2">
<Checkbox checked={allSelected} onCheckedChange={toggleAll} aria-label="Select all workspaces" />
<span className="text-xs text-muted-foreground">
{selectedCount > 0 ? `${selectedCount} selected` : 'Select all'}
</span>
</div>
) : (
<span className="text-xs text-muted-foreground">
{activeWorkspaceDirectory ? 'Selected workspace' : 'Select a workspace'}
</span>
)}
<div className="flex shrink-0 items-center gap-1">
<Button
type="button"
variant="ghost"
size="sm"
className="h-7"
onClick={() => {
onOpenChange(false)
onCreateWorkspace()
}}
>
<Plus className="h-3.5 w-3.5 mr-1" />
New
</Button>
{manageMode ? (
<>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 text-destructive hover:text-destructive"
disabled={selectedCount === 0 || isDeleting}
onClick={() => setConfirmOpen(true)}
>
<Trash2 className="h-3.5 w-3.5 mr-1" />
Delete
</Button>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7"
onClick={() => {
setSelected(new Set())
setManageMode(false)
}}
>
Done
</Button>
</>
) : (
<Button
type="button"
variant="ghost"
size="sm"
className="h-7"
onClick={() => setManageMode(true)}
>
Manage
</Button>
)}
</div>
</div>
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<input
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
placeholder="Search workspaces..."
className="h-10 w-full rounded-md border border-border bg-background pl-9 pr-3 text-sm outline-none placeholder:text-muted-foreground focus:border-primary"
/>
</div>
<div className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto pr-1">
{filteredWorkspaces.map((workspace) => {
if (!workspace.fullPath) return null
const directory = workspace.fullPath
const isChecked = selected.has(directory)
const isActive = directory === activeWorkspaceDirectory
const label = workspaceLabel(workspace)
const rowClassName = isActive
? 'border-primary/50 bg-primary/10 text-foreground'
: 'border-border bg-muted/30 hover:bg-muted/50'
if (!manageMode) {
return (
<button
key={directory}
type="button"
onClick={() => {
onActiveWorkspaceChange(directory)
onOpenChange(false)
}}
className={`flex min-h-11 items-center gap-2 rounded-md border px-3 py-2 text-sm text-left ${rowClassName}`}
aria-pressed={isActive}
>
<GitBranch className="h-3.5 w-3.5 text-primary flex-shrink-0" />
<span className={isActive ? 'truncate text-highlight' : 'truncate'}>{label}</span>
{isActive && <span className="text-xs text-highlight">Selected</span>}
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
{directory}
</span>
</button>
)
}
return (
<div
key={directory}
className="flex min-h-11 items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2 text-sm hover:bg-muted/50"
>
<Checkbox
checked={isChecked}
disabled={isDeleting}
onCheckedChange={(checked) => toggle(directory, checked === true)}
aria-label={`Select workspace ${directory}`}
/>
<GitBranch className="h-3.5 w-3.5 text-primary flex-shrink-0" />
<span className="truncate">{label}</span>
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
{directory}
</span>
</div>
)
})}
{filteredWorkspaces.length === 0 && (
<div className="rounded-md border border-dashed border-border px-3 py-6 text-center text-sm text-muted-foreground">
No workspaces found
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
<DeleteDialog
open={confirmOpen}
onOpenChange={setConfirmOpen}
onConfirm={handleConfirm}
onCancel={() => setConfirmOpen(false)}
title={selectedCount === 1 ? 'Delete Workspace' : 'Delete Workspaces'}
description={
selectedCount === 1
? 'Are you sure you want to delete this OpenCode workspace? This removes the workspace and its sessions in OpenCode.'
: `Are you sure you want to delete ${selectedCount} OpenCode workspaces? This removes the workspaces and their sessions in OpenCode.`
}
isDeleting={isDeleting}
/>
</>
)
}
@@ -0,0 +1,189 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { WorktreeSessionGroups } from './WorktreeSessionGroups'
import type { RepoSibling } from '@/api/repos'
import type { Session } from '@/api/types'
const makeWorktree = (overrides: Partial<RepoSibling> & Pick<RepoSibling, 'fullPath' | 'currentBranch' | 'worktreeSource'>): RepoSibling => ({
id: -1,
localPath: 'x',
fullPath: overrides.fullPath,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
isWorktree: true,
currentBranch: overrides.currentBranch,
worktreeSource: overrides.worktreeSource,
worktreeStrategy: 'git',
...overrides,
})
const featureWorktree = makeWorktree({
fullPath: '/w/feature',
currentBranch: 'feature/auth',
worktreeSource: 'opencode',
})
const sharedScheduleWorktree = makeWorktree({
fullPath: '/s/job-14-shared',
currentBranch: 'schedule/14/shared',
worktreeSource: 'schedule',
schedule: { repoId: 1, jobId: 14, runId: null, inUse: true },
})
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 },
})
const manualWorktree = makeWorktree({
fullPath: '/w/manual',
currentBranch: 'manual',
worktreeSource: 'git',
})
const allWorktrees = [featureWorktree, sharedScheduleWorktree, runScheduleWorktree, manualWorktree]
const makeSession = (id: string, title: string, directory: string): Session => ({
id,
title,
parentID: undefined,
location: { directory },
time: { created: 0, updated: 0 },
} as unknown as Session)
const featureSession = makeSession('ses_1', 'Auth work', '/w/feature')
const onNewSession = vi.fn()
const onOpenTerminal = vi.fn()
const onCreateWorktree = vi.fn()
const onDelete = vi.fn()
beforeEach(() => {
localStorage.clear()
onNewSession.mockReset()
onOpenTerminal.mockReset()
onCreateWorktree.mockReset()
onDelete.mockReset()
})
function renderGroups(overrides: {
worktrees?: RepoSibling[]
sessions?: Session[]
searchQuery?: string
} = {}) {
return render(
<WorktreeSessionGroups
repoId={1}
worktrees={overrides.worktrees ?? allWorktrees}
sessions={overrides.sessions ?? [featureSession]}
searchQuery={overrides.searchQuery ?? ''}
scheduleNames={{ 14: 'Dependency audit' }}
renderSessionCard={(session) => <div key={session.id}>{session.title}</div>}
onNewSession={onNewSession}
onOpenTerminal={onOpenTerminal}
onCreateWorktree={onCreateWorktree}
onDelete={onDelete}
/>,
)
}
describe('WorktreeSessionGroups', () => {
it('groups sessions under their worktree with owner badges, schedule header and in-use pill', async () => {
renderGroups()
expect(screen.getByText('feature/auth')).toBeInTheDocument()
expect(screen.getByText('OpenCode')).toBeInTheDocument()
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('in use')).toBeInTheDocument()
expect(screen.getByText('Git')).toBeInTheDocument()
expect(screen.getByText('No sessions in manual · Start one')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: /No sessions in manual/ }))
expect(onNewSession).toHaveBeenCalledWith('/w/manual')
await userEvent.click(screen.getByRole('button', { name: 'Open terminal in manual' }))
expect(onOpenTerminal).toHaveBeenCalledWith('/w/manual')
})
it('disables delete for the in-use worktree and deletes the run worktree after confirmation', async () => {
renderGroups()
expect(screen.getByRole('button', { name: 'Delete worktree schedule/14/shared' })).toBeDisabled()
const runDelete = screen.getByRole('button', { name: 'Delete worktree schedule/14/run-340' })
expect(runDelete).toBeEnabled()
await userEvent.click(runDelete)
const dialog = screen.getByRole('dialog', { name: 'Delete Worktree' })
await userEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))
expect(onDelete).toHaveBeenCalledWith(['/s/job-14-run-340'])
})
it('cleans up only the non-in-use worktrees of a schedule after confirmation', async () => {
renderGroups()
await userEvent.click(screen.getByRole('button', { name: 'Clean up' }))
const dialog = screen.getByRole('dialog', { name: 'Delete Worktree' })
await userEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))
expect(onDelete).toHaveBeenCalledWith(['/s/job-14-run-340'])
})
it('cleans up worktrees of a schedule that the search is hiding', async () => {
renderGroups({ sessions: [makeSession('ses_2', 'Audit run', '/s/job-14-shared')], searchQuery: 'audit' })
expect(screen.queryByText('schedule/14/run-340')).toBeNull()
await userEvent.click(screen.getByRole('button', { name: 'Clean up' }))
const dialog = screen.getByRole('dialog', { name: 'Delete Worktree' })
await userEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))
expect(onDelete).toHaveBeenCalledWith(['/s/job-14-run-340'])
})
it('filters to only the git worktree when the Git owner chip is selected', async () => {
renderGroups()
await userEvent.click(screen.getByRole('button', { name: 'Git 1' }))
expect(screen.getByText('manual')).toBeInTheDocument()
expect(screen.queryByText('feature/auth')).not.toBeInTheDocument()
expect(screen.queryByText('Dependency audit')).not.toBeInTheDocument()
})
it('collapses a worktree and persists the collapsed state across remount', async () => {
const { unmount } = renderGroups()
expect(screen.getByText('Auth work')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { expanded: true, name: /feature\/auth/ }))
expect(screen.queryByText('Auth work')).not.toBeInTheDocument()
unmount()
renderGroups()
expect(screen.queryByText('Auth work')).not.toBeInTheDocument()
})
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()
unmount()
renderGroups({ worktrees: [], sessions: [] })
expect(screen.getByText('No worktrees yet')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'New worktree' }))
expect(onCreateWorktree).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,359 @@
import { useEffect, useMemo, useState, type ReactNode } from 'react'
import { CalendarClock, ChevronRight, Layers, Plus, SquareTerminal, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { workspaceLabel, worktreeSourceLabel, type RepoSibling } from '@/api/repos'
import type { Session } from '@/api/types'
import type { RepoWorktreeSource } from '@opencode-manager/shared/utils'
type OwnerFilter = 'all' | RepoWorktreeSource
interface WorktreeSessionGroupsProps {
repoId: number
worktrees: RepoSibling[]
sessions: Session[]
searchQuery: string
scheduleNames: Record<number, string>
renderSessionCard: (session: Session) => ReactNode
onNewSession: (directory: string) => void
onOpenTerminal: (directory: string) => void
onCreateWorktree: () => void
onDelete: (directories: string[]) => void
isDeleting?: boolean
}
interface WorktreeGroup {
worktree: RepoSibling
directory: string
sessions: Session[]
lastActive: number
}
type GroupEntry =
| { kind: 'worktree'; key: string; group: WorktreeGroup; lastActive: number }
| { kind: 'schedule'; key: string; jobId: number; groups: WorktreeGroup[]; lastActive: number }
const OWNER_FILTERS: Array<{ value: OwnerFilter; label: string }> = [
{ value: 'all', label: 'All' },
{ value: 'opencode', label: 'OpenCode' },
{ value: 'schedule', label: 'Schedules' },
{ value: 'git', label: 'Git' },
]
const OWNER_BADGE_CLASS: Record<RepoWorktreeSource, string> = {
opencode: 'border-primary/40 bg-primary/15 text-primary',
schedule: 'border-highlight/40 bg-highlight/15 text-highlight',
git: 'border-border bg-muted text-muted-foreground',
}
const WORKTREE_REMOVAL_NOTE = 'OpenCode worktrees are removed with their sessions. Schedule worktrees have pending changes committed to their branch first. Other git worktrees are only removed when they have no uncommitted changes.'
/**
* The Worktrees tab body: every worktree of the repo as a collapsible section of its sessions,
* with a schedule's worktrees nested under that schedule so kept runs stay visible as they pile up.
*/
export function WorktreeSessionGroups({
repoId,
worktrees,
sessions,
searchQuery,
scheduleNames,
renderSessionCard,
onNewSession,
onOpenTerminal,
onCreateWorktree,
onDelete,
isDeleting = false,
}: WorktreeSessionGroupsProps) {
const [ownerFilter, setOwnerFilter] = useState<OwnerFilter>('all')
const [collapsed, setCollapsed] = useCollapsedGroups(repoId)
const [pendingDelete, setPendingDelete] = useState<{ directories: string[]; label: string } | null>(null)
const isSearching = searchQuery.trim().length > 0
const ownerCounts = useMemo(() => {
const counts: Record<OwnerFilter, number> = { all: worktrees.length, opencode: 0, schedule: 0, git: 0 }
worktrees.forEach((worktree) => {
if (worktree.worktreeSource) counts[worktree.worktreeSource] += 1
})
return counts
}, [worktrees])
const entries = useMemo(
() => buildGroupEntries(worktrees, sessions, ownerFilter, isSearching),
[worktrees, sessions, ownerFilter, isSearching],
)
const toggle = (key: string) => {
setCollapsed((current) => {
const next = new Set(current)
if (next.has(key)) next.delete(key)
else next.add(key)
return next
})
}
const allKeys = entries.flatMap((entry) => (
entry.kind === 'schedule' ? [entry.key, ...entry.groups.map((group) => groupKey(group.directory))] : [entry.key]
))
const allCollapsed = allKeys.length > 0 && allKeys.every((key) => collapsed.has(key))
if (worktrees.length === 0) {
return (
<div className="flex flex-col items-center gap-3 rounded-md border border-dashed border-border p-6 text-center">
<p className="font-medium">No worktrees yet</p>
<p className="text-sm text-muted-foreground">Create a worktree to work on a branch without touching the main checkout.</p>
<Button size="sm" onClick={onCreateWorktree}>
<Plus className="mr-1 h-4 w-4" />
New worktree
</Button>
</div>
)
}
const renderWorktree = (group: WorktreeGroup, nested: boolean) => {
const key = groupKey(group.directory)
const isOpen = !collapsed.has(key)
const label = workspaceLabel(group.worktree)
const source = group.worktree.worktreeSource
const sourceLabel = worktreeSourceLabel(group.worktree)
const isInUse = group.worktree.schedule?.inUse === true
return (
<div key={key} className={`rounded-md border border-border bg-card/40 ${nested ? 'ml-3' : ''}`}>
<div className="flex items-center gap-1 px-2 py-1.5">
<button
type="button"
onClick={() => toggle(key)}
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"
>
<ChevronRight className={`h-4 w-4 shrink-0 text-muted-foreground transition-transform ${isOpen ? 'rotate-90' : ''}`} />
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-center gap-2">
<span className="truncate text-sm font-medium">{label}</span>
{sourceLabel && source && (
<span className={`shrink-0 rounded border px-1.5 text-[10px] leading-4 ${OWNER_BADGE_CLASS[source]}`}>{sourceLabel}</span>
)}
{isInUse && (
<span className="inline-flex shrink-0 items-center gap-1 rounded-full border border-success/40 bg-success/15 px-1.5 text-[10px] leading-4 text-success">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-success" />
in use
</span>
)}
<span className="shrink-0 text-xs text-muted-foreground">
{group.sessions.length} {group.sessions.length === 1 ? 'session' : 'sessions'}
</span>
</div>
<div className="truncate font-mono text-[11px] text-muted-foreground" title={group.directory}>{group.directory}</div>
</div>
</button>
<Button
variant="ghost"
size="icon"
className="size-8 shrink-0"
aria-label={`New session in ${label}`}
onClick={() => onNewSession(group.directory)}
>
<Plus className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="size-8 shrink-0"
aria-label={`Open terminal in ${label}`}
onClick={() => onOpenTerminal(group.directory)}
>
<SquareTerminal className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="size-8 shrink-0 text-muted-foreground hover:text-destructive"
aria-label={`Delete worktree ${label}`}
title={isInUse ? 'In use by a running scheduled run' : undefined}
disabled={isInUse || isDeleting}
onClick={() => setPendingDelete({ directories: [group.directory], label })}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
{isOpen && (
<div className="flex flex-col gap-2 px-3 pb-3">
{group.sessions.length > 0 ? group.sessions.map(renderSessionCard) : (
<button
type="button"
onClick={() => onNewSession(group.directory)}
className="rounded-md border border-dashed border-border px-3 py-3 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground"
>
No sessions in {label} · Start one
</button>
)}
</div>
)}
</div>
)
}
return (
<>
<div className="flex flex-wrap items-center gap-1.5">
{OWNER_FILTERS.map((filter) => (
<button
key={filter.value}
type="button"
aria-pressed={ownerFilter === filter.value}
onClick={() => setOwnerFilter(filter.value)}
className={`rounded-full border px-2.5 py-0.5 text-xs ${ownerFilter === filter.value
? 'border-primary/50 bg-primary/15 text-foreground'
: 'border-border text-muted-foreground hover:text-foreground'}`}
>
{filter.label} {ownerCounts[filter.value]}
</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))}>
{allCollapsed ? 'Expand all' : 'Collapse all'}
</Button>
<Button variant="outline" size="sm" className="h-8 text-xs" onClick={onCreateWorktree}>
<Layers className="mr-1 h-3.5 w-3.5 text-primary" />
New worktree
</Button>
</div>
</div>
{entries.length === 0 ? (
<div className="py-4 text-center text-sm text-muted-foreground">
{isSearching ? 'No sessions found' : 'No worktrees match this filter'}
</div>
) : 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 removable = worktrees
.filter((worktree) => worktree.schedule?.jobId === entry.jobId && !worktree.schedule.inUse)
.map((worktree) => worktree.fullPath)
return (
<div key={entry.key} className="flex flex-col gap-2">
<div className="flex items-center gap-1">
<button
type="button"
onClick={() => toggle(entry.key)}
aria-expanded={isOpen}
className="flex min-w-0 flex-1 items-center gap-2 rounded px-1 py-1 text-left text-sm hover:bg-accent/50"
>
<ChevronRight className={`h-4 w-4 shrink-0 text-muted-foreground transition-transform ${isOpen ? 'rotate-90' : ''}`} />
<CalendarClock className="h-4 w-4 shrink-0 text-highlight" />
<span className="truncate font-medium">{name}</span>
<span className="shrink-0 text-xs text-muted-foreground">
· {entry.groups.length} {entry.groups.length === 1 ? 'worktree' : 'worktrees'}
</span>
</button>
<Button
variant="ghost"
size="sm"
className="h-8 shrink-0 text-xs text-muted-foreground hover:text-destructive"
disabled={removable.length === 0 || isDeleting}
onClick={() => setPendingDelete({ directories: removable, label: `${name} worktrees` })}
>
Clean up
</Button>
</div>
{isOpen && entry.groups.map((group) => renderWorktree(group, true))}
</div>
)
})}
<DeleteDialog
open={pendingDelete !== null}
onOpenChange={(open) => { if (!open) setPendingDelete(null) }}
onCancel={() => setPendingDelete(null)}
onConfirm={() => {
if (pendingDelete) onDelete(pendingDelete.directories)
setPendingDelete(null)
}}
title={pendingDelete && pendingDelete.directories.length > 1 ? 'Delete Worktrees' : 'Delete Worktree'}
description={pendingDelete && pendingDelete.directories.length > 1
? `Delete ${pendingDelete.directories.length} worktrees? ${WORKTREE_REMOVAL_NOTE}`
: `Delete this worktree? ${WORKTREE_REMOVAL_NOTE}`}
itemName={pendingDelete?.label}
isDeleting={isDeleting}
/>
</>
)
}
function groupKey(directory: string): string {
return `worktree:${directory}`
}
function buildGroupEntries(
worktrees: RepoSibling[],
sessions: Session[],
ownerFilter: OwnerFilter,
hideEmpty: boolean,
): GroupEntry[] {
const sessionsByDirectory = new Map<string, Session[]>()
sessions.forEach((session) => {
const list = sessionsByDirectory.get(session.location.directory) ?? []
list.push(session)
sessionsByDirectory.set(session.location.directory, list)
})
const groups = worktrees
.filter((worktree) => ownerFilter === 'all' || worktree.worktreeSource === ownerFilter)
.map((worktree): WorktreeGroup => {
const groupSessions = sessionsByDirectory.get(worktree.fullPath) ?? []
return {
worktree,
directory: worktree.fullPath,
sessions: groupSessions,
lastActive: groupSessions[0]?.time.updated ?? 0,
}
})
.filter((group) => !hideEmpty || group.sessions.length > 0)
const scheduleEntries = new Map<number, Extract<GroupEntry, { kind: 'schedule' }>>()
const entries: GroupEntry[] = []
groups.forEach((group) => {
const jobId = group.worktree.schedule?.jobId
if (jobId === undefined) {
entries.push({ kind: 'worktree', key: groupKey(group.directory), group, lastActive: group.lastActive })
return
}
const existing = scheduleEntries.get(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)
entries.push(entry)
})
scheduleEntries.forEach((entry) => entry.groups.sort((a, b) => b.lastActive - a.lastActive))
return entries.sort((a, b) => b.lastActive - a.lastActive)
}
function useCollapsedGroups(repoId: number) {
const storageKey = `oc:repo:${repoId}:worktree-groups:collapsed`
const [collapsed, setCollapsed] = useState<Set<string>>(() => readCollapsed(storageKey))
useEffect(() => {
try {
localStorage.setItem(storageKey, JSON.stringify(Array.from(collapsed)))
} catch {
return
}
}, [storageKey, collapsed])
return [collapsed, setCollapsed] as const
}
function readCollapsed(storageKey: string): Set<string> {
try {
const parsed: unknown = JSON.parse(localStorage.getItem(storageKey) ?? '[]')
return new Set(Array.isArray(parsed) ? parsed.filter((value): value is string => typeof value === 'string') : [])
} catch {
return new Set()
}
}
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { WorktreeTabs } from './WorktreeTabs'
import type { RepoSibling } from '@/api/repos'
@@ -15,6 +15,7 @@ const makeWorkspaceSibling = (branch: string): RepoSibling => ({
currentBranch: branch,
branch,
worktreeStrategy: 'git',
worktreeSource: 'opencode',
})
const onValueChange = vi.fn()
@@ -30,18 +31,18 @@ describe('WorktreeTabs', () => {
)
expect(screen.getAllByRole('tab')).toHaveLength(1)
expect(screen.getByText('main')).toBeInTheDocument()
expect(screen.getByText('Workspace')).toBeInTheDocument()
expect(screen.getByText('Worktree')).toBeInTheDocument()
})
it('renders Repo and Workspaces tabs when at least one workspace exists', () => {
it('renders Repo and Worktrees tabs when at least one workspace exists', () => {
const workspaces = [makeWorkspaceSibling('feature-a')]
render(<WorktreeTabs workspaces={workspaces} value="repo" onValueChange={onValueChange} baseLabel="main" />)
const tabs = screen.getAllByRole('tab')
expect(tabs).toHaveLength(2)
expect(screen.getByText('main')).toBeInTheDocument()
expect(screen.getByText('Workspaces')).toBeInTheDocument()
expect(screen.getByText('(1)')).toBeInTheDocument()
expect(screen.getByText('Worktrees')).toBeInTheDocument()
expect(within(tabs[1]).getByText('1')).toBeInTheDocument()
})
it('marks the active tab', () => {
@@ -69,6 +70,6 @@ describe('WorktreeTabs', () => {
]
render(<WorktreeTabs workspaces={workspaces} value="repo" onValueChange={onValueChange} baseLabel="main" />)
expect(screen.getByText('(3)')).toBeInTheDocument()
expect(within(screen.getAllByRole('tab')[1]).getByText('3')).toBeInTheDocument()
})
})
+12 -17
View File
@@ -8,9 +8,7 @@ interface WorktreeTabsProps {
value: WorktreeTabValue
onValueChange: (value: WorktreeTabValue) => void
baseLabel: string
activeWorkspaceLabel?: string
onCreateWorkspace?: () => void
onWorkspaceMenu?: () => void
}
export function WorktreeTabs({
@@ -18,40 +16,37 @@ export function WorktreeTabs({
value,
onValueChange,
baseLabel,
activeWorkspaceLabel,
onCreateWorkspace,
onWorkspaceMenu,
}: WorktreeTabsProps) {
const hasWorkspaces = workspaces.length > 0
const workspaceLabel = value === 'workspaces' && activeWorkspaceLabel ? activeWorkspaceLabel : 'Workspaces'
const tabClassName =
'group min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3 data-[state=active]:border data-[state=active]:border-primary/50 data-[state=active]:bg-primary/10 data-[state=inactive]:hover:bg-accent data-[state=inactive]:hover:text-foreground'
'group min-w-0 flex-1 gap-1.5 rounded-t-md rounded-b-none border border-transparent border-b-0 px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground data-[state=active]:-mb-px data-[state=active]:border-border data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none sm:flex-none'
const activeLabelClassName = 'group-data-[state=active]:text-highlight'
return (
<div className="px-4 pt-2 flex-shrink-0">
<div className="flex-shrink-0">
<Tabs value={value} onValueChange={(next) => onValueChange(next as WorktreeTabValue)} className="min-w-0">
<TabsList className="w-full justify-start gap-1 overflow-hidden">
<TabsList className="flex h-auto w-full items-end justify-start gap-1 rounded-none border-b border-border bg-transparent p-0 px-4 pt-2">
<TabsTrigger value="repo" className={tabClassName}>
<GitBranch className="h-3 w-3 shrink-0" />
<span className={`min-w-0 truncate ${activeLabelClassName}`}>{baseLabel}</span>
</TabsTrigger>
{hasWorkspaces ? (
<>
<TabsTrigger value="workspaces" className={tabClassName} onClick={onWorkspaceMenu}>
<Layers className="h-3 w-3 shrink-0 text-primary" />
<span className={`min-w-0 truncate ${activeLabelClassName}`}>{workspaceLabel}</span>
<span className={`shrink-0 text-xs text-muted-foreground ${activeLabelClassName}`}>({workspaces.length})</span>
</TabsTrigger>
</>
<TabsTrigger value="workspaces" className={tabClassName}>
<Layers className="h-3 w-3 shrink-0 text-primary" />
<span className={`min-w-0 truncate ${activeLabelClassName}`}>Worktrees</span>
<span className="shrink-0 rounded-full border border-border bg-card px-1.5 text-[11px] leading-4 text-muted-foreground">
{workspaces.length}
</span>
</TabsTrigger>
) : (
<button
type="button"
onClick={onCreateWorkspace}
className="inline-flex h-8 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground sm:flex-none sm:px-3"
className="inline-flex min-w-0 flex-1 items-center justify-center gap-1.5 rounded-t-md rounded-b-none border border-transparent border-b-0 px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground sm:flex-none"
>
<Layers className="h-3 w-3 shrink-0 text-primary" />
<span className="min-w-0 truncate">Workspace</span>
<span className="min-w-0 truncate">Worktree</span>
<Plus className="h-3.5 w-3.5 shrink-0" />
</button>
)}
@@ -5,6 +5,9 @@ import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import { TabsContent } from '@/components/ui/tabs'
import { RadioOptionGroup } from '@/components/ui/radio-option-group'
import { workspaceModeOptions } from '@/components/schedules/schedule-utils'
import type { ScheduleWorkspaceMode } from '@opencode-manager/shared/types'
import { Info } from 'lucide-react'
type GeneralTabProps = {
@@ -23,6 +26,9 @@ type GeneralTabProps = {
branch: string
onBranchChange: (value: string) => void
branchRepoId: number | undefined
workspaceMode: ScheduleWorkspaceMode
onWorkspaceModeChange: (value: ScheduleWorkspaceMode) => void
showWorkspaceMode: boolean
showRepoSelector?: boolean
isEditing: boolean
repoId?: number
@@ -64,6 +70,9 @@ export function GeneralTab({
branch,
onBranchChange,
branchRepoId,
workspaceMode,
onWorkspaceModeChange,
showWorkspaceMode,
showRepoSelector,
isEditing,
repoId,
@@ -152,22 +161,35 @@ export function GeneralTab({
</div>
</div>
<div className="rounded-lg border border-border bg-card p-4">
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="schedule-branch">Base branch</Label>
<InfoHint text="Scheduled runs execute in an isolated worktree branched off this base branch. Leave empty to use the repository's default branch." />
<div className="rounded-lg border border-border bg-card p-4 space-y-4">
{showWorkspaceMode && (
<div className="space-y-2">
<p className="text-sm font-medium">Workspace</p>
<RadioOptionGroup
name="schedule-workspace-mode"
value={workspaceMode}
onChange={onWorkspaceModeChange}
options={workspaceModeOptions}
/>
</div>
<BranchCombobox
id="schedule-branch"
repoId={branchRepoId}
value={branch}
onValueChange={onBranchChange}
placeholder="Defaults to default branch"
remotes="bare"
clearable
/>
</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>
)}
</div>
<div className="space-y-2">
@@ -6,9 +6,12 @@ import {
formatScheduleSummary,
formatTimestamp,
getJobStatusTone,
formatWorkspaceMode,
hasSkillMetadata,
} from '@/components/schedules/schedule-utils'
import { Bot, CalendarClock, Clock3, History, Loader2, Pencil, Play, Sparkles, Trash2 } from 'lucide-react'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { useRemoveScheduleWorktrees, useScheduleWorktrees } from '@/hooks/useSchedules'
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'
@@ -37,6 +40,9 @@ export function JobDetailTab({
}: JobDetailTabProps) {
const { availableModelKeys, configDefaultModel } = useScheduleModels(Boolean(selectedJob))
const resolvedModel = resolveScheduleModel(selectedJob?.model, availableModelKeys, configDefaultModel)
const { data: worktrees = [] } = useScheduleWorktrees(selectedJob?.repoId, selectedJob?.id ?? null)
const removeWorktrees = useRemoveScheduleWorktrees()
const idleWorktreeCount = worktrees.filter((worktree) => !worktree.inUse).length
if (!selectedJob) {
return (
@@ -109,6 +115,49 @@ export function JobDetailTab({
<pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6 text-foreground/90">{JSON.stringify(selectedJob.skillMetadata, null, 2)}</pre>
</section>
)}
{worktrees.length > 0 && (
<section className="rounded-lg border border-border/60 bg-background/40 p-3 sm:p-4">
<div className="mb-3 flex items-start justify-between gap-3">
<div>
<h3 className="text-base font-medium flex items-center gap-2"><GitBranch className="h-4 w-4" /> Worktrees ({worktrees.length})</h3>
<p className="text-sm text-muted-foreground">Worktrees this schedule has on disk. Removing one commits any pending changes to its branch first and keeps the branch.</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => removeWorktrees.mutate({ repoId: selectedJob.repoId, jobId: selectedJob.id })}
disabled={removeWorktrees.isPending || idleWorktreeCount === 0}
>
{removeWorktrees.isPending ? <Loader2 className="h-4 w-4 sm:mr-2 animate-spin" /> : <Trash2 className="h-4 w-4 sm:mr-2" />}
<span className="hidden sm:inline">Remove all</span>
</Button>
</div>
<ul className="divide-y divide-border/60">
{worktrees.map((worktree) => (
<li key={worktree.worktreePath} className="flex items-center justify-between gap-2 py-2">
<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}`}
{worktree.inUse ? ' · in use' : ''} · {worktree.worktreePath}
</p>
</div>
<Button
variant="ghost"
size="sm"
aria-label={`Remove worktree ${worktree.branch}`}
title={worktree.inUse ? 'In use by a running run' : 'Remove worktree'}
onClick={() => removeWorktrees.mutate({ repoId: selectedJob.repoId, jobId: selectedJob.id, worktreePath: worktree.worktreePath })}
disabled={worktree.inUse || removeWorktrees.isPending}
>
<Trash2 className="h-4 w-4" />
</Button>
</li>
))}
</ul>
</section>
)}
</div>
<Card className="border-border/60 bg-background/60 shadow-none">
@@ -131,6 +180,12 @@ export function JobDetailTab({
<p className="text-muted-foreground">Model</p>
<p className="font-medium break-all">{resolvedModel ?? 'Workspace default'}</p>
</div>
{selectedJob.repoId !== ASSISTANT_REPO_ID && (
<div>
<p className="text-muted-foreground">Workspace</p>
<p className="font-medium">{formatWorkspaceMode(selectedJob.workspaceMode)}</p>
</div>
)}
<div>
<p className="text-muted-foreground">Created</p>
<p className="font-medium">{formatTimestamp(selectedJob.createdAt)}</p>
@@ -267,6 +267,15 @@ describe('RunDetailPanel open session', () => {
expect(apiMocks.createSessionWithContext).not.toHaveBeenCalled()
})
it('opens the original session for a finished run whose worktree was kept', async () => {
renderPanel({ ...run, status: 'completed', sessionId: 'ses_run', worktreePath: '/abs/worktrees/job-1-run-1', runBranch: 'schedule/1/run-1' })
await clickOpenSession()
await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/ses_run'))
expect(apiMocks.createSessionWithContext).not.toHaveBeenCalled()
})
it('opens a new repo session seeded with the full output and branch for a finished worktree run', async () => {
apiMocks.createSessionWithContext.mockResolvedValue({ id: 'ses_new' })
renderPanel({
@@ -71,7 +71,7 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
const { sessionId } = activeRun
const opensNewRepoSession = Boolean(activeRun.runBranch) && activeRun.status !== 'running'
const opensNewRepoSession = Boolean(activeRun.runBranch) && !activeRun.worktreePath && activeRun.status !== 'running'
const handleOpenSession = async () => {
if (!opensNewRepoSession) {
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob, ScheduleMcpServer } from '@opencode-manager/shared/types'
import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob, ScheduleMcpServer, ScheduleWorkspaceMode } from '@opencode-manager/shared/types'
import { useScheduleModels } from '@/hooks/useScheduleModels'
import { providerModelRef } from '@/api/providers'
import { resolveScheduleModel } from '@/lib/schedules/schedule-model'
@@ -71,6 +71,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
const initialSkillNotesRef = useRef<string | undefined>(undefined)
const [mcpServers, setMcpServers] = useState<ScheduleMcpServer[]>([])
const [branch, setBranch] = useState('')
const [workspaceMode, setWorkspaceMode] = useState<ScheduleWorkspaceMode>('worktree')
const [allowExternalDirectory, setAllowExternalDirectory] = useState(false)
const [allowQuestions, setAllowQuestions] = useState(false)
const [bashDenyPatterns, setBashDenyPatterns] = useState<string[]>([...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
@@ -204,6 +205,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
initialSkillNotesRef.current = initialSkillNotes
setMcpServers(job?.mcpServers ?? [])
setBranch(job?.branch ?? '')
setWorkspaceMode(job?.workspaceMode ?? 'worktree')
setAllowExternalDirectory(job?.permissionConfig?.allowExternalDirectory ?? false)
setAllowQuestions(job?.permissionConfig?.allowQuestions ?? false)
setBashDenyPatterns(job?.permissionConfig?.bashDenyPatterns ?? [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
@@ -252,6 +254,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
model: resolvedModel ?? undefined,
prompt: prompt.trim(),
branch: branch.trim() || null,
workspaceMode,
mcpServers,
permissionConfig: {
allowExternalDirectory,
@@ -331,6 +334,9 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
branch={branch}
onBranchChange={setBranch}
branchRepoId={open && effectiveRepoId !== ASSISTANT_REPO_ID ? effectiveRepoId : undefined}
workspaceMode={workspaceMode}
onWorkspaceModeChange={setWorkspaceMode}
showWorkspaceMode={effectiveRepoId !== ASSISTANT_REPO_ID}
showRepoSelector={showRepoSelector}
isEditing={!!job}
repoId={selectedRepoId}
@@ -184,6 +184,14 @@ export function ScheduleJobsTable({
>
{job.name}
</button>
{job.retainedWorktreeCount > 0 && (
<span
title="Worktrees this schedule has left on disk. Manage them from the job details."
className="shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground"
>
{job.retainedWorktreeCount} worktree{job.retainedWorktreeCount === 1 ? '' : 's'}
</span>
)}
</span>
{job.description && <span className="truncate text-xs text-muted-foreground sm:max-w-[20rem]">{job.description}</span>}
<span className="truncate text-xs text-muted-foreground sm:hidden" title={scheduleTitle}>{mobileDetail}</span>
@@ -1,6 +1,7 @@
import cronstrue from 'cronstrue'
import { formatDistanceToNow } from 'date-fns'
import type { CreateScheduleJobRequest, ScheduleJob, ScheduleRun, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
import type { CreateScheduleJobRequest, ScheduleJob, ScheduleRun, ScheduleWorkspaceMode, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
import type { RadioOption } from '@/components/ui/radio-option-group'
export const intervalOptions = [
{ label: '15m', value: 15 },
@@ -39,6 +40,33 @@ export const weekdayOptions = [
export type SchedulePreset = typeof schedulePresetOptions[number]['value']
export const workspaceModeOptions: Array<RadioOption<ScheduleWorkspaceMode>> = [
{
value: 'worktree',
label: 'Fresh worktree, cleaned up',
description: 'Each run gets its own worktree. Changes are committed to a run branch and the worktree is removed when the run ends.',
},
{
value: 'kept-worktree',
label: 'Fresh worktree, kept',
description: 'Each run gets its own worktree, which stays on disk afterwards so you can continue in it. Kept worktrees are listed on the job details.',
},
{
value: 'shared-worktree',
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 {
return workspaceModeOptions.find((option) => option.value === mode)?.label ?? mode
}
export function getLocalTimeZone(): string {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
@@ -351,3 +379,5 @@ export function matchesScheduleJobSearch(job: ScheduleJob & { repoName?: string
if (!term) return true
return [job.name, job.description, job.repoName].some((field) => field?.toLowerCase().includes(term))
}
export const DELETE_SCHEDULE_DESCRIPTION = 'This removes the job definition and all recorded run history for it. Any kept or shared worktrees are removed after their pending changes are committed to their branches; the branches are kept.'
@@ -244,6 +244,23 @@ describe('SessionList', () => {
expect(screen.getByText('Click here to start a new session')).toBeTruthy()
})
it('hands an empty list to a custom session renderer instead of the create-session card', () => {
sessionsData.splice(0, sessionsData.length)
const renderSessions = vi.fn(() => <p>Custom layout</p>)
render(
<SessionList
directories={['/w/a']}
onSelectSession={vi.fn()}
renderSessions={renderSessions}
/>,
)
expect(screen.getByText('Custom layout')).toBeTruthy()
expect(screen.queryByText('No sessions yet')).toBeNull()
expect(renderSessions).toHaveBeenCalledWith(expect.objectContaining({ sessions: [], searchQuery: '' }))
})
it('shows loading state instead of create-session card when the first page is empty but more pages are pending', () => {
sessionsData.splice(0, sessionsData.length)
hasNextPageRef.current = true
@@ -1,4 +1,4 @@
import { useCallback, useState, useMemo, useEffect, useRef } from "react";
import { useCallback, useState, useMemo, useEffect, useRef, type ReactNode } from "react";
import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
import type { Session } from "@/api/types";
@@ -19,6 +19,17 @@ interface SessionListProps {
directoryLabels?: Record<string, string>;
activeSessionID?: string;
onSelectSession: (sessionID: string) => void;
renderSessions?: (args: SessionListRenderArgs) => ReactNode;
}
/**
* Lets a caller lay out the loaded root sessions itself, for example grouped by worktree.
* Search, paging, pinning, selection and delete stay owned by SessionList.
*/
export interface SessionListRenderArgs {
sessions: Session[];
searchQuery: string;
renderSessionCard: (session: Session) => ReactNode;
}
export const SessionList = ({
@@ -28,6 +39,7 @@ export const SessionList = ({
directoryLabels,
activeSessionID,
onSelectSession,
renderSessions,
}: SessionListProps) => {
const directoriesList = useMemo(() => {
const source = directories && directories.length > 0 ? directories : directory ? [directory] : [];
@@ -118,7 +130,7 @@ export const SessionList = ({
if (hasNextPage || isFetchingNextPage) {
return <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
}
if (!searchQuery.trim()) {
if (!searchQuery.trim() && !renderSessions) {
return (
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
<Card
@@ -285,7 +297,13 @@ export const SessionList = ({
onScroll={handleSessionsScroll}
>
<div className="flex flex-col gap-4">
{filteredSessions.length === 0 && !isFetchingNextPage ? (
{renderSessions ? (
renderSessions({
sessions: filteredSessions,
searchQuery,
renderSessionCard: (session) => renderSessionCard(session, pinnedKeys.has(getSessionSelectionKey(session))),
})
) : filteredSessions.length === 0 && !isFetchingNextPage ? (
<div className="text-sm text-muted-foreground text-center py-4">
No sessions found
</div>
@@ -28,7 +28,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa
const isMobile = useMobile()
const { searchParams, updateParams } = useUrlParams()
const openPreview = useOpenPreview()
const { data, isLoading, isSuccess, isFetching, refetch } = useTerminals(repoId, directory, {
const { data, isLoading, isSuccess, isFetching, refetch, error } = useTerminals(repoId, directory, {
enabled: isOpen && !!directory,
refetchInterval: isOpen ? 5000 : false,
})
@@ -186,7 +186,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa
<div className="relative flex-1 min-h-0 bg-background">
{terminals.length === 0 ? (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
{isLoading || isCreating ? 'Starting terminal...' : 'No terminals'}
{error && !isCreating ? `Could not load terminals: ${error.message}` : isLoading || isCreating ? 'Starting terminal...' : 'No terminals'}
</div>
) : (
<Suspense