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

+16 -3
View File
@@ -2,7 +2,8 @@ import type { Repo } from './types'
import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import { saveFile } from '@/lib/download'
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity, WorktreeSetupResult } from '@opencode-manager/shared/types'
import type { CreateRepoWorkspaceRequest, DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity, WorktreeSetupResult } from '@opencode-manager/shared/types'
import type { RepoWorktreeSchedule, RepoWorktreeSource } from '@opencode-manager/shared/utils'
export interface CreateRepoOptions {
repoUrl?: string
@@ -40,11 +41,21 @@ export async function getRepo(id: number): Promise<Repo> {
export type RepoSibling = Repo & {
currentBranch?: string
worktreeSource?: RepoWorktreeSource
worktreeStrategy?: string
schedule?: RepoWorktreeSchedule
}
export function workspaceLabel(workspace: RepoSibling): string {
return workspace.currentBranch || workspace.branch || workspace.localPath || 'workspace'
return workspace.currentBranch || workspace.branch || workspace.localPath || 'worktree'
}
export function worktreeSourceLabel(worktree: RepoSibling): string | null {
if (worktree.schedule) {
return worktree.schedule.runId === null ? 'Schedule · shared' : `Schedule · run #${worktree.schedule.runId}`
}
if (worktree.worktreeSource === 'git') return 'Git'
return worktree.worktreeSource === 'opencode' ? 'OpenCode' : null
}
export interface RepoWorktree {
@@ -63,9 +74,11 @@ export async function deleteRepoWorkspace(repoId: number, directory: string): Pr
})
}
export async function createRepoWorkspace(repoId: number): Promise<RepoWorktree & { worktreeSetup?: WorktreeSetupResult }> {
export async function createRepoWorkspace(repoId: number, request: CreateRepoWorkspaceRequest = {}): Promise<RepoWorktree & { worktreeSetup?: WorktreeSetupResult }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
}
+14
View File
@@ -5,6 +5,7 @@ import type {
ScheduleJob,
ScheduleRun,
ScheduleRunStatus,
ScheduleWorktree,
UpdateScheduleJobRequest,
} from '@opencode-manager/shared/types'
@@ -22,6 +23,7 @@ export interface ScheduleJobWithRepo extends ScheduleJob {
repoPath: string
repoUrl: string
lastRun: ScheduleRunSummary | null
retainedWorktreeCount: number
}
export interface ScheduleRunWithContext extends ScheduleRun {
@@ -162,6 +164,18 @@ export async function clearRepoScheduleRuns(repoId: number, jobId: number): Prom
})
}
export async function listScheduleWorktrees(repoId: number, jobId: number): Promise<{ worktrees: ScheduleWorktree[] }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/worktrees`)
}
export async function removeScheduleWorktrees(repoId: number, jobId: number, worktreePath?: string): Promise<{ removed: number }> {
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/worktrees`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(worktreePath ? { worktreePath } : {}),
})
}
export async function deleteRepoScheduleRun(repoId: number, jobId: number, runId: number): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}`, {
method: 'DELETE',
@@ -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
+4 -2
View File
@@ -180,11 +180,13 @@ export const useCreateSession = (
title?: string;
agent?: string;
model?: string;
directory?: string;
}) => {
if (!directory) {
const targetDirectory = data.directory ?? directory;
if (!targetDirectory) {
throw new Error('A directory is required to create a session');
}
return createSession({ directory, ...data });
return createSession({ ...data, directory: targetDirectory });
},
onSuccess: (session) => {
invalidateSessionListCaches(queryClient);
+12 -4
View File
@@ -3,21 +3,29 @@ import { openDialogParam, useDialogParam } from './useDialogParam'
import { useUrlParams } from './useUrlParams'
const TERMINAL_DIALOG = 'terminal'
const TERMINAL_DIALOG_PARAMS = ['terminal'] as const
const TERMINAL_DIALOG_PARAMS = ['terminal', 'terminalDirectory'] as const
export function useTerminalDialogParam(): [boolean, (open: boolean) => void] {
return useDialogParam(TERMINAL_DIALOG, TERMINAL_DIALOG_PARAMS)
}
/**
* The directory the terminal dialog was opened for, such as a repo worktree; null means the repo itself.
*/
export function useTerminalDirectoryParam(): string | null {
const { searchParams } = useUrlParams()
return searchParams.get('terminalDirectory')
}
export function useOpenTerminal(): (
terminalId: string,
terminalId: string | null,
extraParams?: Record<string, string>,
) => void {
const { updateParams } = useUrlParams()
return useCallback(
(terminalId: string, extraParams?: Record<string, string>) => {
openDialogParam(updateParams, TERMINAL_DIALOG, { terminal: terminalId, ...extraParams })
(terminalId: string | null, extraParams?: Record<string, string>) => {
openDialogParam(updateParams, TERMINAL_DIALOG, { ...(terminalId ? { terminal: terminalId } : {}), ...extraParams })
},
[updateParams],
)
+16 -12
View File
@@ -1,6 +1,7 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { createRepoWorkspace, deleteRepoWorkspace, getRepoSiblings, type RepoSibling } from '@/api/repos'
import { showToast } from '@/lib/toast'
import type { CreateRepoWorkspaceRequest } from '@opencode-manager/shared/types'
export function repoSiblingsQueryKey(repoId: number | undefined) {
return ['repo', 'siblings', repoId] as const
@@ -24,22 +25,25 @@ export function useDeleteRepoWorkspaces(repoId: number | undefined) {
const results = await Promise.allSettled(
directories.map((directory) => deleteRepoWorkspace(repoId, directory)),
)
const failed = results.filter((result) => result.status === 'rejected').length
return { total: directories.length, failed }
const failures = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []))
return { total: directories.length, failed: failures.length, firstError: failures[0] instanceof Error ? failures[0].message : null }
},
onSuccess: ({ total, failed }) => {
onSuccess: ({ total, failed, firstError }) => {
queryClient.invalidateQueries({ queryKey: repoSiblingsQueryKey(repoId) })
queryClient.invalidateQueries({ queryKey: ['schedule-worktrees'] })
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
const deleted = total - failed
const reason = firstError ? `: ${firstError}` : ''
if (failed === 0) {
showToast.success(deleted === 1 ? 'Workspace deleted' : `${deleted} workspaces deleted`)
showToast.success(deleted === 1 ? 'Worktree deleted' : `${deleted} worktrees deleted`)
} else if (deleted === 0) {
showToast.error('Failed to delete workspaces')
showToast.error(`Failed to delete worktrees${reason}`)
} else {
showToast.error(`Deleted ${deleted}, failed ${failed}`)
showToast.error(`Deleted ${deleted}, failed ${failed}${reason}`)
}
},
onError: () => {
showToast.error('Failed to delete workspaces')
showToast.error('Failed to delete worktrees')
},
})
}
@@ -48,16 +52,16 @@ export function useCreateRepoWorkspace(repoId: number | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async () => {
mutationFn: async (request: CreateRepoWorkspaceRequest = {}) => {
if (!repoId) throw new Error('Repo id is required')
return createRepoWorkspace(repoId)
return createRepoWorkspace(repoId, request)
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: repoSiblingsQueryKey(repoId) })
showToast.success('Workspace created')
showToast.success('Worktree created')
},
onError: () => {
showToast.error('Failed to create workspace')
onError: (error) => {
showToast.error(`Failed to create worktree: ${error.message}`)
},
})
}
+36
View File
@@ -11,9 +11,11 @@ import {
listAllScheduleRuns,
listAllSchedules,
listRepoScheduleRuns,
listScheduleWorktrees,
listUnreadScheduleRuns,
markAllScheduleRunsViewed,
markScheduleRunViewed,
removeScheduleWorktrees,
runRepoSchedule,
updateRepoSchedule,
} from '@/api/schedules'
@@ -228,6 +230,7 @@ export function useClearRepoScheduleRuns() {
onSuccess: (result, variables) => {
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', variables.repoId, variables.jobId] })
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
queryClient.invalidateQueries({ queryKey: ['schedule-worktrees', variables.repoId, variables.jobId] })
showToast.success(result.cleared > 0 ? `Cleared ${result.cleared} run${result.cleared === 1 ? '' : 's'}` : 'No runs to clear')
},
onError: (error: unknown) => {
@@ -246,6 +249,7 @@ export function useDeleteRepoScheduleRun() {
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', variables.repoId, variables.jobId] })
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
queryClient.invalidateQueries({ queryKey: ['schedule-worktrees', variables.repoId, variables.jobId] })
showToast.success('Run deleted')
},
onError: (error: unknown) => {
@@ -253,3 +257,35 @@ export function useDeleteRepoScheduleRun() {
},
})
}
export function useScheduleWorktrees(repoId: number | undefined, jobId: number | null) {
return useQuery({
queryKey: ['schedule-worktrees', repoId, jobId],
queryFn: async () => {
const response = await listScheduleWorktrees(repoId!, jobId!)
return response.worktrees
},
enabled: repoId !== undefined && jobId !== null,
refetchInterval: jobId !== null ? 10000 : false,
})
}
export function useRemoveScheduleWorktrees() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ repoId, jobId, worktreePath }: { repoId: number; jobId: number; worktreePath?: string }) => {
return removeScheduleWorktrees(repoId, jobId, worktreePath)
},
onSuccess: (result, variables) => {
queryClient.invalidateQueries({ queryKey: ['schedule-worktrees', variables.repoId, variables.jobId] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', variables.repoId, variables.jobId] })
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
queryClient.invalidateQueries({ queryKey: ['repo', 'siblings'] })
showToast.success(`Removed ${result.removed} worktree${result.removed === 1 ? '' : 's'}`)
},
onError: (error: unknown) => {
showToast.error(`Failed to remove worktree: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
+2 -2
View File
@@ -4,7 +4,7 @@ import { useAllSchedules, useAllScheduleRuns, useCancelRepoScheduleRun, useUnrea
import { useDeleteRepoSchedule, useRunRepoSchedule, useUpdateRepoSchedule, useCreateRepoSchedule } from '@/hooks/useSchedules'
import { ScheduleJobDialog, PromptsTab, ScheduleJobsTable, ScheduleListToolbar, ScheduleRunDrawer, ScheduleRunsTable } from '@/components/schedules'
import type { CreateScheduleJobRequest } from '@opencode-manager/shared/types'
import { matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
import { DELETE_SCHEDULE_DESCRIPTION, matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
import { ScheduleReportsBell } from '@/components/notifications/ScheduleReportsBell'
@@ -779,7 +779,7 @@ export function GlobalSchedules() {
onConfirm={handleDelete}
onCancel={closeDialog}
title="Delete Schedule"
description="This removes the job definition and all recorded run history for it."
description={DELETE_SCHEDULE_DESCRIPTION}
isDeleting={deleteMutation.isPending}
/>
</div>
+130 -129
View File
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useCallback, useMemo, useState, type FormEvent } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { getRepo, workspaceLabel } from "@/api/repos";
import { SessionList } from "@/components/session/SessionList";
import { getRepo } from "@/api/repos";
import { SessionList, type SessionListRenderArgs } from "@/components/session/SessionList";
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
import { Header } from "@/components/ui/header";
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
@@ -18,11 +18,14 @@ import { useRepoActivity } from "@/hooks/useRepoActivity";
import { useCreateRepoWorkspace, useDeleteRepoWorkspaces, useRepoSiblings } from "@/hooks/useRepoSiblings";
import { useSSE } from "@/hooks/useSSE";
import { useDialogParam } from "@/hooks/useDialogParam";
import { useOpenTerminal, useTerminalDialogParam } from "@/hooks/useOpenTerminal";
import { useOpenTerminal, useTerminalDialogParam, useTerminalDirectoryParam } from "@/hooks/useOpenTerminal";
import { useWorktreeTab } from "@/hooks/useWorktreeTab";
import { WorktreeTabs } from "@/components/repo/WorktreeTabs";
import { WorkspaceManager } from "@/components/repo/WorkspaceManager";
import { WorktreeSessionGroups } from "@/components/repo/WorktreeSessionGroups";
import { useAllSchedules } from "@/hooks/useSchedules";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { GitBranch, Plus, Loader2, Layers, Columns3 } from "lucide-react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
@@ -30,7 +33,7 @@ import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
import { getRepoDisplayName } from "@/lib/utils";
import { notifyWorktreeSetup } from "@/lib/worktreeSetup";
import { isWorktreeSibling } from "@opencode-manager/shared/utils";
import { getRepoDirectoryNameError, isWorktreeSibling } from "@opencode-manager/shared/utils";
export function RepoDetail() {
const { id } = useParams<{ id: string }>();
@@ -46,10 +49,9 @@ export function RepoDetail() {
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
const [multiRunOpen, setMultiRunOpen] = useDialogParam('multiRun');
const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false);
const [workspaceSelectorOpen, setWorkspaceSelectorOpen] = useState(false);
const [activeWorkspaceDirectory, setActiveWorkspaceDirectory] = useState<string | undefined>();
const { activeTab, setActiveTab } = useWorktreeTab();
const openTerminal = useOpenTerminal();
const terminalDirectory = useTerminalDirectoryParam();
const { data: repo, isLoading: repoLoading } = useQuery({
queryKey: ["repo", repoId],
@@ -73,6 +75,15 @@ export function RepoDetail() {
[workspaceSiblings],
);
const { data: allSchedules } = useAllSchedules();
const scheduleNames = useMemo(() => {
const names: Record<number, string> = {};
(allSchedules ?? []).forEach((job) => {
if (job.repoId === repoId) names[job.id] = job.name;
});
return names;
}, [allSchedules, repoId]);
const baseDirectory = repo?.fullPath;
const subscriptionDirectories = useMemo(() => {
const set = new Set<string>();
@@ -81,89 +92,62 @@ export function RepoDetail() {
return Array.from(set);
}, [baseDirectory, workspaceDirectories]);
useEffect(() => {
if (workspaceDirectories.length === 0) {
setActiveWorkspaceDirectory(undefined);
return;
}
setActiveWorkspaceDirectory((current) => (
current && workspaceDirectories.includes(current) ? current : workspaceDirectories[0]
));
}, [workspaceDirectories]);
const workspaceComposerDirectory = activeWorkspaceDirectory ?? workspaceDirectories[0];
const sessionListDirectories = activeTab === 'workspaces' ? workspaceDirectories : (baseDirectory ? [baseDirectory] : []);
const composerDirectory = activeTab === 'workspaces' ? workspaceComposerDirectory : baseDirectory;
const directoryLabels = useMemo(() => {
const labels: Record<string, string> = {};
workspaceSiblings.forEach((sibling) => {
if (sibling.fullPath) {
labels[sibling.fullPath] = workspaceLabel(sibling);
}
});
return labels;
}, [workspaceSiblings]);
const activeWorkspaceLabel = activeWorkspaceDirectory ? directoryLabels[activeWorkspaceDirectory] : undefined;
const showWorktrees = activeTab === 'workspaces';
const sessionListDirectories = showWorktrees ? workspaceDirectories : (baseDirectory ? [baseDirectory] : []);
useSSE(subscriptionDirectories);
const sessionUrl = useCallback(
(sessionId: string) => {
(sessionId: string, inWorktree: boolean) => {
const base = `/repos/${repoId}/sessions/${sessionId}`;
return activeTab === 'workspaces' ? `${base}?repoTab=workspaces` : base;
return inWorktree ? `${base}?repoTab=workspaces` : base;
},
[repoId, activeTab],
[repoId],
);
const createSessionMutation = useCreateSession(composerDirectory, (session) => {
navigate(sessionUrl(session.id));
});
const createSessionMutation = useCreateSession(baseDirectory);
const handleCreateSession = async (options?: {
agentSlug?: string;
promptSlug?: string;
}) => {
if (activeTab === 'workspaces' && !workspaceComposerDirectory) {
setCreateWorkspaceOpen(true);
return;
}
await createSessionMutation.mutateAsync({
agent: options?.agentSlug,
const handleCreateSession = (directory = baseDirectory) => {
createSessionMutation.mutate({ directory }, {
onSuccess: (session) => navigate(sessionUrl(session.id, directory !== baseDirectory)),
});
};
const handleCreateWorkspace = async () => {
const workspace = await createWorkspace.mutateAsync();
if (workspace.directory) {
setActiveWorkspaceDirectory(workspace.directory);
}
setCreateWorkspaceOpen(false);
notifyWorktreeSetup(workspace.worktreeSetup);
if (workspace.worktreeSetup?.status === 'started') {
const terminalId = workspace.worktreeSetup.terminal.id;
openTerminal(terminalId, { repoTab: 'workspaces' });
return;
}
setActiveTab('workspaces');
};
const handleOpenWorkspaceSelector = () => {
if (workspaceSiblings.length === 0) {
setCreateWorkspaceOpen(true);
return;
}
setActiveTab('workspaces');
setWorkspaceSelectorOpen(true);
const handleCreateWorkspace = (name: string) => {
createWorkspace.mutate(name ? { name } : {}, {
onSuccess: (workspace) => {
setCreateWorkspaceOpen(false);
notifyWorktreeSetup(workspace.worktreeSetup);
if (workspace.worktreeSetup?.status === 'started') {
const terminalId = workspace.worktreeSetup.terminal.id;
openTerminal(terminalId, { repoTab: 'workspaces', ...(workspace.directory ? { terminalDirectory: workspace.directory } : {}) });
return;
}
setActiveTab('workspaces');
},
});
};
const handleSelectSession = (sessionId: string) => {
navigate(sessionUrl(sessionId));
navigate(sessionUrl(sessionId, showWorktrees));
};
const renderWorktreeGroups = ({ sessions, searchQuery, renderSessionCard }: SessionListRenderArgs) => (
<WorktreeSessionGroups
repoId={repoId}
worktrees={workspaceSiblings}
sessions={sessions}
searchQuery={searchQuery}
scheduleNames={scheduleNames}
renderSessionCard={renderSessionCard}
onNewSession={handleCreateSession}
onOpenTerminal={(directory) => openTerminal(null, { repoTab: "workspaces", terminalDirectory: directory })}
onCreateWorktree={() => setCreateWorkspaceOpen(true)}
onDelete={(directories) => deleteWorkspaces.mutate(directories)}
isDeleting={deleteWorkspaces.isPending}
/>
);
if (repoLoading) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
@@ -218,7 +202,7 @@ export function RepoDetail() {
</div>
<Header.Actions>
<div className="flex items-center gap-1">
<ProjectActionsMenu repoId={repoId} directory={composerDirectory} />
<ProjectActionsMenu repoId={repoId} directory={baseDirectory} />
<PendingActionsGroup />
</div>
<Button
@@ -257,29 +241,21 @@ export function RepoDetail() {
value={activeTab}
onValueChange={setActiveTab}
baseLabel={currentBranch}
activeWorkspaceLabel={activeWorkspaceLabel}
onCreateWorkspace={() => setCreateWorkspaceOpen(true)}
onWorkspaceMenu={handleOpenWorkspaceSelector}
/>
<WorkspaceManager
open={workspaceSelectorOpen}
onOpenChange={setWorkspaceSelectorOpen}
workspaces={workspaceSiblings}
activeWorkspaceDirectory={activeWorkspaceDirectory}
onActiveWorkspaceChange={setActiveWorkspaceDirectory}
onCreateWorkspace={() => setCreateWorkspaceOpen(true)}
onDelete={(directories) => deleteWorkspaces.mutate(directories)}
isDeleting={deleteWorkspaces.isPending}
/>
<div className="flex-1 flex flex-col min-h-0">
{sessionListDirectories.length > 0 && (
{showWorktrees && workspaceSiblings.length === 0 ? (
<div className="px-4 pt-4">
{renderWorktreeGroups({ sessions: [], searchQuery: "", renderSessionCard: () => null })}
</div>
) : sessionListDirectories.length > 0 && (
<SessionList
key={showWorktrees ? "worktrees" : "repo"}
directories={sessionListDirectories}
directoryLabels={activeTab === 'workspaces' ? directoryLabels : undefined}
createDirectory={activeTab === 'workspaces' ? workspaceComposerDirectory : baseDirectory}
createDirectory={baseDirectory}
onSelectSession={handleSelectSession}
renderSessions={showWorktrees ? renderWorktreeGroups : undefined}
/>
)}
</div>
@@ -303,12 +279,12 @@ export function RepoDetail() {
<RepoMcpDialog
open={mcpDialogOpen}
onOpenChange={setMcpDialogOpen}
directory={composerDirectory}
directory={baseDirectory}
/>
<RepoActionsDialog
repoId={repoId}
directory={composerDirectory}
directory={baseDirectory}
open={actionsDialogOpen}
onOpenChange={setActionsDialogOpen}
/>
@@ -329,7 +305,7 @@ export function RepoDetail() {
<TerminalPanel
repoId={repoId}
directory={composerDirectory}
directory={terminalDirectory ?? baseDirectory}
isOpen={terminalOpen}
onClose={() => setTerminalOpen(false)}
/>
@@ -337,7 +313,7 @@ export function RepoDetail() {
<PreviewPanel
isOpen={previewOpen}
onClose={() => setPreviewOpen(false)}
directory={composerDirectory}
directory={baseDirectory}
/>
<ResetPermissionsDialog
@@ -360,47 +336,72 @@ export function RepoDetail() {
interface CreateWorkspaceDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onCreate: () => Promise<void>;
onCreate: (name: string) => void;
isCreating: boolean;
}
function CreateWorkspaceDialog({ open, onOpenChange, onCreate, isCreating }: CreateWorkspaceDialogProps) {
const [name, setName] = useState("");
const trimmedName = name.trim();
const nameError = trimmedName ? getRepoDirectoryNameError(trimmedName) : null;
const handleOpenChange = (next: boolean) => {
if (!next) setName("");
onOpenChange(next);
};
const handleSubmit = (event: FormEvent) => {
event.preventDefault();
if (nameError || isCreating) return;
onCreate(trimmedName);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[420px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Layers className="h-4 w-4 text-primary" />
Create Workspace
</DialogTitle>
<DialogDescription>
Create an OpenCode worktree workspace for this repository.
</DialogDescription>
</DialogHeader>
<div className="rounded-md border border-border bg-muted/30 p-3 text-sm">
<div className="flex items-center gap-2 font-medium">
<GitBranch className="h-4 w-4 text-primary" />
Worktree
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Layers className="h-4 w-4 text-primary" />
Create Worktree
</DialogTitle>
<DialogDescription>
OpenCode creates a git worktree of this repository from the current commit.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-1.5">
<Label htmlFor="worktree-name">Name</Label>
<Input
id="worktree-name"
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="Generated if empty"
autoComplete="off"
autoFocus
disabled={isCreating}
aria-invalid={nameError ? true : undefined}
aria-describedby="worktree-name-hint"
/>
<p id="worktree-name-hint" className={`text-xs ${nameError ? "text-destructive" : "text-muted-foreground"}`}>
{nameError ?? "Used as the folder name and its label under Worktrees. If the folder already exists, a number is added."}
</p>
</div>
<p className="mt-1 text-xs text-muted-foreground">
OpenCode will create and manage a git worktree workspace.
</p>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isCreating}>
Cancel
</Button>
<Button onClick={() => { void onCreate(); }} disabled={isCreating} className="bg-primary hover:bg-primary-hover text-primary-foreground">
{isCreating ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Creating...
</>
) : (
'Create Workspace'
)}
</Button>
</DialogFooter>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={isCreating}>
Cancel
</Button>
<Button type="submit" disabled={isCreating || Boolean(nameError)} className="bg-primary hover:bg-primary-hover text-primary-foreground">
{isCreating ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Creating...
</>
) : (
'Create Worktree'
)}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
+2 -2
View File
@@ -17,7 +17,7 @@ import { useRepoActivity } from '@/hooks/useRepoActivity'
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
import { useScheduleUrlState } from '@/hooks/useScheduleUrlState'
import { ScheduleJobDialog, ScheduleJobsTable, ScheduleListToolbar, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
import { matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
import { DELETE_SCHEDULE_DESCRIPTION, matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
import type { ScheduleJobWithRepo } from '@/api/schedules'
import { Header } from '@/components/ui/header'
import { Button } from '@/components/ui/button'
@@ -370,7 +370,7 @@ export function Schedules() {
onConfirm={handleDelete}
onCancel={() => closeDialog()}
title="Delete Schedule"
description="This removes the job definition and all recorded run history for it."
description={DELETE_SCHEDULE_DESCRIPTION}
isDeleting={deleteMutation.isPending}
/>
@@ -14,7 +14,8 @@ const mocks = vi.hoisted(() => ({
useRepoActivity: vi.fn(),
useSSE: vi.fn(),
useCreateSession: vi.fn(),
createWorkspaceMutateAsync: vi.fn(),
createWorkspaceMutate: vi.fn(),
createWorkspaceResult: vi.fn(),
showToastInfo: vi.fn(),
showToastWarning: vi.fn(),
}))
@@ -63,7 +64,7 @@ vi.mock('@/components/repo/ProjectActionsMenu', () => ({ ProjectActionsMenu: ()
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: () => null }))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: () => null }))
vi.mock('@/components/source-control', () => ({ SourceControlPanel: () => null }))
vi.mock('@/components/repo/WorkspaceManager', () => ({ WorkspaceManager: () => null }))
vi.mock('@/hooks/useSchedules', () => ({ useAllSchedules: () => ({ data: [] }) }))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: () => null }))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null }))
@@ -106,12 +107,15 @@ async function startWorkspaceCreation() {
const user = userEvent.setup()
renderRepoDetail()
await user.click(await screen.findByRole('button', { name: 'New workspace' }))
await user.click(await screen.findByRole('button', { name: 'Create Workspace' }))
await user.click(await screen.findByRole('button', { name: 'Create Worktree' }))
}
describe('RepoDetail worktree setup', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.createWorkspaceMutate.mockImplementation((_request: unknown, options: { onSuccess: (value: unknown) => void }) => {
options.onSuccess(mocks.createWorkspaceResult())
})
mocks.getRepo.mockResolvedValue(baseRepo)
mocks.useRepoSiblings.mockReturnValue({ data: siblingsData })
mocks.useDeleteRepoWorkspaces.mockReturnValue({ mutate: vi.fn(), isPending: false })
@@ -120,10 +124,10 @@ describe('RepoDetail worktree setup', () => {
it('switches to the new workspace terminal when setup starts from the repo tab', async () => {
mocks.useCreateRepoWorkspace.mockReturnValue({
mutateAsync: mocks.createWorkspaceMutateAsync,
mutate: mocks.createWorkspaceMutate,
isPending: false,
})
mocks.createWorkspaceMutateAsync.mockResolvedValue({
mocks.createWorkspaceResult.mockReturnValue({
directory: newWorkspaceDirectory,
worktreeSetup: {
status: 'started',
@@ -154,10 +158,10 @@ describe('RepoDetail worktree setup', () => {
it('stays on the workspace tab without a terminal when setup does not start', async () => {
mocks.useCreateRepoWorkspace.mockReturnValue({
mutateAsync: mocks.createWorkspaceMutateAsync,
mutate: mocks.createWorkspaceMutate,
isPending: false,
})
mocks.createWorkspaceMutateAsync.mockResolvedValue({
mocks.createWorkspaceResult.mockReturnValue({
directory: newWorkspaceDirectory,
worktreeSetup: { status: 'none' },
})
@@ -168,9 +172,25 @@ describe('RepoDetail worktree setup', () => {
expect(screen.getByTestId('location')).toHaveTextContent('repoTab=workspaces'),
)
expect(screen.getByTestId('location')).not.toHaveTextContent('dialog=terminal')
expect(screen.getByTestId('terminal-panel')).toHaveAttribute(
'data-directory',
newWorkspaceDirectory,
)
expect(screen.getByTestId('terminal-panel')).toHaveAttribute('data-open', 'false')
})
it('sends the typed worktree name and blocks names that are not a single folder', async () => {
mocks.useCreateRepoWorkspace.mockReturnValue({ mutate: mocks.createWorkspaceMutate, isPending: false })
mocks.createWorkspaceResult.mockReturnValue({ directory: newWorkspaceDirectory, worktreeSetup: { status: 'none' } })
const user = userEvent.setup()
renderRepoDetail()
await user.click(await screen.findByRole('button', { name: 'New workspace' }))
const nameInput = await screen.findByLabelText('Name')
await user.type(nameInput, '../escape')
expect(screen.getByRole('button', { name: 'Create Worktree' })).toBeDisabled()
expect(screen.getByText('Directory name cannot contain dot-dot path segments')).toBeInTheDocument()
await user.clear(nameInput)
await user.type(nameInput, 'feature-login')
await user.click(screen.getByRole('button', { name: 'Create Worktree' }))
expect(mocks.createWorkspaceMutate).toHaveBeenCalledWith({ name: 'feature-login' }, expect.anything())
})
})