feat(servers): run Manager automation on linked servers

This commit is contained in:
Chris Scott committed 2026-10-19 00:06:34 +00:00
1 parent c591c15743
commit a9bdb8358f
131 files changed
+6568 -949

No files matched your search

@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ComposerToolsMenu } from './ComposerToolsMenu'
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
import { useSessionPermissionMode, useSetSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
import { useSessionSandbox, useSetSessionSandbox } from '@/hooks/useSessionSandbox'
import { FetchError } from '@/api/fetchWrapper'
@@ -72,6 +73,25 @@ function renderMenu(overrides: Partial<React.ComponentProps<typeof ComposerTools
return props
}
function renderRemoteMenu(overrides: Partial<React.ComponentProps<typeof ComposerToolsMenu>> = {}) {
const props = {
sessionID: 'ses_remote',
directory: '/remote/repo',
goalArmed: false,
goalDisabled: false,
goalLabel: 'Goal mode: the next message becomes the objective',
onToggleGoal: vi.fn(),
onAttachFile: vi.fn(),
...overrides,
}
render(
<OpenCodeServerProvider serverId="srv_remote">
<ComposerToolsMenu {...props} />
</OpenCodeServerProvider>,
)
return props
}
describe('ComposerToolsMenu', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -112,6 +132,18 @@ describe('ComposerToolsMenu', () => {
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'auto' })
})
it('offers permission and goal controls on a remote server without sandbox controls', async () => {
const user = userEvent.setup()
mockPermissionMode()
renderRemoteMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
expect(await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ })).toBeInTheDocument()
expect(screen.getByRole('menuitemcheckbox', { name: /Goal mode/ })).toBeInTheDocument()
expect(screen.queryByRole('menuitemcheckbox', { name: /Sandbox commands/ })).not.toBeInTheDocument()
})
it('shows why permissions cannot be changed', async () => {
const user = userEvent.setup()
mockPermissionMode({ lockedReason: 'child' })
@@ -9,6 +9,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { getIconToggleButtonClassName } from '@/components/ui/icon-toggle-button'
import { isLocalOpenCodeServer, useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
import { usePermissionModeToggle } from '@/hooks/usePermissionModeToggle'
import { useSandboxToggle } from '@/hooks/useSandboxToggle'
import { shouldShowSandboxResources } from '@/lib/sandboxResources'
@@ -25,7 +26,6 @@ interface ComposerToolsMenuProps {
onToggleGoal: () => void
onAttachFile: () => void
onDictate?: () => void
allowManagerTools?: boolean
}
export function ComposerToolsMenu({
@@ -37,10 +37,10 @@ export function ComposerToolsMenu({
onToggleGoal,
onAttachFile,
onDictate,
allowManagerTools = true,
}: ComposerToolsMenuProps) {
const permission = usePermissionModeToggle(sessionID, directory, { enabled: allowManagerTools })
const sandbox = useSandboxToggle(sessionID, { enabled: allowManagerTools })
const isLocalServer = isLocalOpenCodeServer(useOpenCodeServerId())
const permission = usePermissionModeToggle(sessionID, directory)
const sandbox = useSandboxToggle(sessionID, { enabled: isLocalServer })
const [resourcesOpen, setResourcesOpen] = useState(false)
return (
@@ -57,30 +57,28 @@ export function ComposerToolsMenu({
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="end" collisionPadding={8} className="w-64">
{allowManagerTools ? (
<>
<DropdownMenuCheckboxItem
checked={permission.isAuto}
disabled={permission.disabled}
onCheckedChange={permission.toggle}
>
<ToolMenuItemContent
icon={permission.isAuto ? <ShieldCheck className="h-4 w-4" /> : <Shield className="h-4 w-4" />}
title="Accept all permissions"
detail={permission.disabled ? permission.label : undefined}
/>
</DropdownMenuCheckboxItem>
<SandboxMenuItems sandbox={sandbox} onOpenResources={() => setResourcesOpen(true)} />
<DropdownMenuCheckboxItem checked={goalArmed} disabled={goalDisabled} onCheckedChange={onToggleGoal}>
<ToolMenuItemContent
icon={<Target className="h-4 w-4" />}
title="Goal mode"
detail={goalDisabled ? goalLabel : undefined}
/>
</DropdownMenuCheckboxItem>
<DropdownMenuSeparator />
</>
) : null}
<DropdownMenuCheckboxItem
checked={permission.isAuto}
disabled={permission.disabled}
onCheckedChange={permission.toggle}
>
<ToolMenuItemContent
icon={permission.isAuto ? <ShieldCheck className="h-4 w-4" /> : <Shield className="h-4 w-4" />}
title="Accept all permissions"
detail={permission.disabled ? permission.label : undefined}
/>
</DropdownMenuCheckboxItem>
{isLocalServer && (
<SandboxMenuItems sandbox={sandbox} onOpenResources={() => setResourcesOpen(true)} />
)}
<DropdownMenuCheckboxItem checked={goalArmed} disabled={goalDisabled} onCheckedChange={onToggleGoal}>
<ToolMenuItemContent
icon={<Target className="h-4 w-4" />}
title="Goal mode"
detail={goalDisabled ? goalLabel : undefined}
/>
</DropdownMenuCheckboxItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={onAttachFile} className="pl-8">
<ToolMenuItemContent icon={<Paperclip className="h-4 w-4" />} title="Attach image or PDF" />
</DropdownMenuItem>
@@ -252,7 +252,7 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const sessionAgent = useSessionAgent(sessionID, directory)
const hasBackgroundActivity = useHasBackgroundActivity(sessionID)
const allowManagerTools = isLocalOpenCodeServer(useOpenCodeServerId())
const isLocalServer = isLocalOpenCodeServer(useOpenCodeServerId())
const currentMode = localMode ?? sessionAgent.agent
const setStoredAgent = useSessionAgentStore((s) => s.setAgent)
const sendPrompt = useSendPrompt(directory)
@@ -260,8 +260,8 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
const startGoal = useStartSessionGoal()
const isPromptSubmitPending = sendPrompt.isPending || sendShell.isPending || startGoal.isPending
const interruptSession = useInterruptSession()
const { data: sessionGoal } = useSessionGoal(sessionID, { enabled: allowManagerTools })
const { data: permissionMode } = useSessionPermissionMode(sessionID, { enabled: allowManagerTools })
const { data: sessionGoal } = useSessionGoal(sessionID)
const { data: permissionMode } = useSessionPermissionMode(sessionID)
const { searchCommands, findCommand, recentNames } = useCommands({ directory })
const recordCommand = useRecentCommandsStore((state) => state.recordCommand)
const isExactCommandPrompt = (value: string) => {
@@ -1579,10 +1579,10 @@ return (
onAgentChange={handleAgentChange}
isBashMode={isBashMode}
/>
{directory && !isMobile && allowManagerTools ? (
{directory && !isMobile ? (
<>
<PermissionModeToggle sessionID={sessionID} directory={directory} />
<SessionSandboxMenu sessionID={sessionID} />
{isLocalServer && <SessionSandboxMenu sessionID={sessionID} />}
<IconToggleButton
active={isGoalArmed}
label={goalButtonLabel}
@@ -1664,7 +1664,6 @@ return (
goalLabel={goalButtonLabel}
onToggleGoal={toggleGoalArmed}
onAttachFile={openFilePicker}
allowManagerTools={allowManagerTools}
onDictate={canUseMobileVoice && hasPromptContent && !showVoiceFeedback ? () => void startVoiceRecording() : undefined}
/>
)}
@@ -81,18 +81,21 @@ export function DesktopSidebar() {
)}
{collapsed ? (
<div className="flex flex-col gap-1 p-2 pt-0">
{collapsedItems.map((item: MoreDrawerItem) => (
<SidebarItem
key={item.key}
icon={item.icon}
label={item.label}
collapsed={collapsed}
onClick={() => handleItemClick(item)}
danger={item.danger}
/>
))}
</div>
<>
<div className="flex flex-col gap-1 p-2 pt-0">
{collapsedItems.map((item: MoreDrawerItem) => (
<SidebarItem
key={item.key}
icon={item.icon}
label={item.label}
collapsed={collapsed}
onClick={() => handleItemClick(item)}
danger={item.danger}
/>
))}
</div>
<LinkedServersNav variant="rail" />
</>
) : (
<>
<LinkedServersNav />
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { render, screen, fireEvent } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { LinkedServersNav } from './LinkedServersNav'
@@ -34,6 +34,14 @@ function renderNav(pathname = '/') {
)
}
function renderRail(pathname = '/') {
return render(
<MemoryRouter initialEntries={[pathname]}>
<LinkedServersNav variant="rail" />
</MemoryRouter>,
)
}
describe('LinkedServersNav', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -75,4 +83,38 @@ describe('LinkedServersNav', () => {
expect(screen.getByRole('link', { name: /Kitchen/ })).toBeInTheDocument()
expect(screen.queryByRole('link', { name: /Office/ })).not.toBeInTheDocument()
})
it('renders enabled servers as icon links in the collapsed rail', () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
renderRail('/servers/srv_kitchen/sessions/abc')
expect(screen.getByRole('link', { name: 'Kitchen' })).toHaveAttribute(
'aria-current',
'page',
)
expect(screen.queryByText('Servers')).not.toBeInTheDocument()
})
it('renders nothing in the collapsed rail when no linked servers exist', () => {
const { container } = renderRail()
expect(container).toBeEmptyDOMElement()
})
it('hands navigation to the caller in the sheet variant', () => {
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
const onNavigate = vi.fn()
render(
<MemoryRouter>
<LinkedServersNav variant="sheet" onNavigate={onNavigate} />
</MemoryRouter>,
)
expect(screen.getByRole('heading', { name: 'Servers' })).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: /Kitchen/ }))
expect(onNavigate).toHaveBeenCalledWith('/servers/srv_kitchen')
})
})
@@ -5,7 +5,33 @@ import { SidebarSection } from '@/components/ui/sidebar'
import { getServerPath } from '@/lib/navigation'
import { cn } from '@/lib/utils'
export function LinkedServersNav() {
export type LinkedServersVariant = 'sidebar' | 'rail' | 'sheet'
interface LinkedServersNavProps {
/** `sidebar` renders the labelled section, `rail` the collapsed icon column, `sheet` the mobile sheet group. */
variant?: LinkedServersVariant
/** When provided, each row is a button that hands navigation to the caller instead of rendering a link. */
onNavigate?: (path: string) => void
}
function isActiveServerPath(pathname: string, path: string) {
return pathname === path || pathname.startsWith(`${path}/`)
}
function ServerConnectionDot({ connected }: { connected: boolean }) {
const label = connected ? 'Connected' : 'Disconnected'
return (
<span
role="img"
aria-label={label}
title={label}
className={cn('h-2 w-2 shrink-0 rounded-full', connected ? 'bg-success' : 'bg-muted-foreground/40')}
/>
)
}
export function LinkedServersNav({ variant = 'sidebar', onNavigate }: LinkedServersNavProps) {
const location = useLocation()
const { servers, isLoading } = useOpenCodeServers()
const { statusById } = useOpenCodeServerStatuses()
@@ -15,37 +41,87 @@ export function LinkedServersNav() {
return null
}
if (variant === 'rail') {
return (
<div className="flex flex-col gap-1 px-2">
{enabledServers.map((server) => {
const path = getServerPath(server.id)
const active = isActiveServerPath(location.pathname, path)
return (
<Link
key={server.id}
to={path}
title={server.name}
aria-current={active ? 'page' : undefined}
className={cn(
'flex items-center justify-center rounded-md p-2.5 transition-colors duration-150',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
active ? 'bg-accent text-accent-foreground' : 'text-foreground hover:bg-accent/50',
)}
>
<Server className="h-5 w-5 shrink-0" />
<span className="sr-only">{server.name}</span>
</Link>
)
})}
</div>
)
}
const rows = enabledServers.map((server) => {
const path = getServerPath(server.id)
const active = isActiveServerPath(location.pathname, path)
const connected = statusById[server.id]?.connected ?? false
const className = cn(
'flex items-center gap-3 rounded-md p-2.5 text-sm transition-colors duration-150',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
active ? 'bg-accent text-accent-foreground' : 'text-foreground hover:bg-accent/50',
variant === 'sheet' && 'mx-2 p-2 text-left',
)
const content = (
<>
<Server className="h-5 w-5 shrink-0" />
<span className="min-w-0 flex-1 truncate">{server.name}</span>
<ServerConnectionDot connected={connected} />
</>
)
if (onNavigate) {
return (
<button
key={server.id}
type="button"
onClick={() => onNavigate(path)}
aria-current={active ? 'page' : undefined}
className={className}
>
{content}
</button>
)
}
return (
<Link key={server.id} to={path} className={className}>
{content}
</Link>
)
})
if (variant === 'sheet') {
return (
<section aria-label="Servers" className="flex flex-col border-b border-border pb-1">
<h2 className="px-4 pt-2 pb-0.5 text-xs font-medium uppercase tracking-wider text-muted-foreground">
Servers
</h2>
{rows}
</section>
)
}
return (
<SidebarSection label="Servers" collapsed={false}>
{enabledServers.map((server) => {
const path = getServerPath(server.id)
const active = location.pathname === path || location.pathname.startsWith(`${path}/`)
const connected = statusById[server.id]?.connected ?? false
return (
<Link
key={server.id}
to={path}
className={cn(
'flex items-center gap-3 rounded-md p-2.5 text-sm transition-colors duration-150',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
active ? 'bg-accent text-accent-foreground' : 'text-foreground hover:bg-accent/50',
)}
>
<Server className="h-5 w-5 shrink-0" />
<span className="min-w-0 flex-1 truncate">{server.name}</span>
<span
role="img"
aria-label={connected ? 'Connected' : 'Disconnected'}
title={connected ? 'Connected' : 'Disconnected'}
className={cn(
'h-2 w-2 shrink-0 rounded-full',
connected ? 'bg-success' : 'bg-muted-foreground/40',
)}
/>
</Link>
)
})}
{rows}
</SidebarSection>
)
}
@@ -361,7 +361,7 @@ describe('MoreDrawer', () => {
expect(handleClose).not.toHaveBeenCalled()
})
it('offers only account items on a linked-server route', () => {
it('offers the terminal plus account items on a linked-server route', () => {
mockAuth()
mockServerHealth()
setActivityGroups({ recent: [createActiveWorkItem()] })
@@ -373,9 +373,9 @@ describe('MoreDrawer', () => {
expect(screen.getByText('Home')).toBeInTheDocument()
expect(screen.getByText('Settings')).toBeInTheDocument()
expect(screen.getByText('Logout')).toBeInTheDocument()
expect(screen.getByText('Terminal')).toBeInTheDocument()
expect(screen.queryByText('Files')).not.toBeInTheDocument()
expect(screen.queryByText('Source Control')).not.toBeInTheDocument()
expect(screen.queryByText('Terminal')).not.toBeInTheDocument()
expect(screen.queryByText('MCP')).not.toBeInTheDocument()
expect(screen.queryByText('Schedules')).not.toBeInTheDocument()
expect(screen.queryByText('Repos')).not.toBeInTheDocument()
@@ -38,6 +38,16 @@ const activityMocks = vi.hoisted(() => ({
useActivityWindowMinutes: vi.fn(),
}))
const serverMocks = vi.hoisted(() => ({
useOpenCodeServers: vi.fn(),
useOpenCodeServerStatuses: vi.fn(),
}))
vi.mock('@/hooks/useOpenCodeServers', () => ({
useOpenCodeServers: serverMocks.useOpenCodeServers,
useOpenCodeServerStatuses: serverMocks.useOpenCodeServerStatuses,
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: activityMocks.useActiveWork,
useActivityWindowMinutes: activityMocks.useActivityWindowMinutes,
@@ -132,6 +142,33 @@ function setActivityGroups(groups: {
})
}
function createLinkedServer(id: string, name: string, enabled = true) {
return {
id,
name,
baseUrl: `https://${id}.example.com`,
username: 'opencode',
enabled,
hasPassword: true,
createdAt: 1,
updatedAt: 2,
}
}
function setLinkedServers(servers: Array<ReturnType<typeof createLinkedServer>>) {
serverMocks.useOpenCodeServers.mockReturnValue({ servers, isLoading: false })
serverMocks.useOpenCodeServerStatuses.mockReturnValue({
statuses: [],
statusById: Object.fromEntries(
servers.map((server) => [
server.id,
{ serverId: server.id, connected: true, version: null, error: null },
]),
),
isLoading: false,
})
}
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: {
@@ -173,6 +210,7 @@ describe('RepoQuickSwitchSheet', () => {
permissionSessions.current.clear()
activityMocks.useActivityWindowMinutes.mockReturnValue(30)
setActivityGroups({})
setLinkedServers([])
})
it('renders with loading state', async () => {
@@ -927,4 +965,60 @@ describe('RepoQuickSwitchSheet', () => {
expect(pathname).toBe('/repos/2/sessions/new-session')
expect(handleClose).toHaveBeenCalled()
})
it('renders the Servers group with enabled linked servers', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
setLinkedServers([
createLinkedServer('srv_kitchen', 'Kitchen'),
createLinkedServer('srv_office', 'Office', false),
])
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
expect(await screen.findByRole('heading', { name: 'Servers' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Kitchen/ })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Office/ })).not.toBeInTheDocument()
expect(screen.getByRole('img', { name: 'Connected' })).toBeInTheDocument()
})
it('hides the Servers group when no linked servers exist', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
render(<RepoQuickSwitchSheet isOpen onClose={vi.fn()} />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByText('repo1')).toBeInTheDocument()
})
expect(screen.queryByRole('heading', { name: 'Servers' })).toBeNull()
})
it('navigates to a linked server and closes the sheet', async () => {
vi.mocked(listRepos).mockResolvedValue([createRepo(1, 'repo1', '/path/to/repo1')])
setLinkedServers([createLinkedServer('srv_kitchen', 'Kitchen')])
const handleClose = vi.fn()
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/repos/1']}>
<Routes>
<Route
path="*"
element={
<>
<RepoQuickSwitchSheet isOpen onClose={handleClose} />
<LocationSpy />
</>
}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
fireEvent.click(await screen.findByRole('button', { name: /Kitchen/ }))
expect(screen.getByTestId('location')).toHaveTextContent('/servers/srv_kitchen')
expect(handleClose).toHaveBeenCalled()
})
})
@@ -11,6 +11,7 @@ import { FolderGit2, Plus } from 'lucide-react'
import { useUrlParams } from '@/hooks/useUrlParams'
import { getAssistantPath, getRepoPath } from '@/lib/navigation'
import { NewSessionButton, RepoSessionNavList, SearchClearButton } from '@/components/navigation/RepoSessionNav'
import { LinkedServersNav } from '@/components/navigation/LinkedServersNav'
import { getActiveRepoId } from '@/components/navigation/sidebar-session-tree'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
@@ -96,6 +97,12 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
</div>
</BottomSheetHeader>
<BottomSheetContent className="flex flex-col px-0 pt-0 gap-0">
{isOpen && (
<LinkedServersNav
variant="sheet"
onNavigate={(path) => navigateAndClose(path, { replace: true })}
/>
)}
{isOpen && !searchQuery.trim() && (
<CompactActivityList onNavigate={(path) => navigateAndClose(path)} />
)}
@@ -26,6 +26,7 @@ import { useOpenNavItem } from '@/hooks/useOpenNavItem'
import { ActivityList } from '@/components/activity/ActivityList'
import { ActivityCountPill } from '@/components/activity/ActivityCountPill'
import { withQueryParam } from '@/lib/navigation'
import type { TerminalTarget } from '@/lib/terminal-target'
import { useActiveWorkCounts, useActivityWindowMinutes } from '@/hooks/useActiveWork'
import { formatActivityWindow } from '@/lib/activeWork'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
@@ -84,6 +85,8 @@ interface ToolSidePanelProps {
sessionId?: string
directory?: string
terminalDirectory?: string
terminalTarget?: TerminalTarget
allowedPanelTools?: readonly PanelTool[]
repoDirectory?: string
currentBranch?: string
selectedFilePath?: string
@@ -146,6 +149,8 @@ export function ToolSidePanel({
sessionId,
directory,
terminalDirectory,
terminalTarget,
allowedPanelTools,
repoDirectory,
currentBranch = 'main',
selectedFilePath,
@@ -172,10 +177,16 @@ export function ToolSidePanel({
const panelTools: Array<{ item: MoreDrawerItem; tool: PanelTool }> = []
const actionItems: MoreDrawerItem[] = []
const terminalWorkspaceTarget: TerminalTarget | undefined =
terminalTarget ?? (repoId === undefined ? undefined : { kind: 'repo', repoId })
for (const item of buildToolItems(location.pathname)) {
const tool = toolKeyOf(item)
if (isPanelTool(tool)) panelTools.push({ item, tool })
else actionItems.push(item)
if (isPanelTool(tool)) {
if (allowedPanelTools && !allowedPanelTools.includes(tool)) continue
panelTools.push({ item, tool })
} else {
actionItems.push(item)
}
}
const activeLabel = panelTools.find(({ tool }) => tool === activeTool)?.item.label
@@ -197,12 +208,15 @@ export function ToolSidePanel({
if (tool === 'mcp') return repoDirectory ? <RepoMcpContent open directory={repoDirectory} /> : null
if (tool === 'walkthrough') return sessionId ? <ChangesWalkthroughView /> : null
if (tool === 'activity') return <ActivityPanelBody />
if (tool === 'terminal') {
return terminalWorkspaceTarget
? <TerminalWorkspace target={terminalWorkspaceTarget} directory={terminalDirectory ?? directory} isOpen />
: null
}
if (repoId === undefined) return null
switch (tool) {
case 'sourceControl':
return <SourceControlContent repoId={repoId} isOpen currentBranch={currentBranch} compact />
case 'terminal':
return <TerminalWorkspace repoId={repoId} directory={terminalDirectory ?? directory} isOpen />
case 'actions':
return <RepoActionsContent repoId={repoId} directory={directory} open />
case 'skills':
@@ -164,6 +164,19 @@ describe('buildToolItems', () => {
])
})
it('returns the linked server session tools without Manager-only entries', () => {
expect(buildToolItems('/servers/srv_kitchen/sessions/ses_1').map((item) => item.key)).toEqual([
'activity',
'terminal',
])
expect(buildMoreItems('/servers/srv_kitchen/sessions/ses_1').map((item) => item.key)).toEqual([
'home',
'terminal',
'settings',
'logout',
])
})
it('returns the home route tools', () => {
expect(buildToolItems('/').map((item) => item.key)).toEqual(['activity', 'all-schedules', 'files'])
})
@@ -58,7 +58,6 @@ const NON_TOOL_ITEM_KEYS = new Set(['home', 'settings', 'logout'])
const MANAGER_ONLY_ITEM_KEYS: ReadonlySet<string> = new Set([
'files',
'source-control',
'terminal',
'preview',
'walkthrough',
'actions',
@@ -136,6 +135,17 @@ function buildRouteNavModel(pathname: string): NavModel {
}
}
const serverSessionMatch = /^\/servers\/[^/]+\/sessions\/[^/]+$/.exec(pathname)
if (serverSessionMatch) {
return {
primary: [],
items: [
{ key: 'terminal', label: 'Terminal', icon: SquareTerminal, dialog: 'terminal' },
...baseItems,
],
}
}
if (isAssistantPath(pathname)) {
const items: MoreDrawerItem[] = [
{ key: 'files', label: 'Files', icon: Folder, dialog: 'files' },
+24 -11
View File
@@ -1,6 +1,7 @@
import { useId, useState } from 'react'
import { ArrowRight, ArrowUpRight, Combine, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { ModelCombobox } from '@/components/model/ModelCombobox'
@@ -11,6 +12,7 @@ import {
FusionRecoveredDetailsSchema,
MULTI_RUN_FUSION_MIN_SOURCES,
type MultiRun,
type MultiRunTarget,
} from '@opencode-manager/shared/schemas'
export interface FusionComposerSubmission {
@@ -20,7 +22,7 @@ export interface FusionComposerSubmission {
}
interface FusionComposerProps {
repoId: number
target: MultiRunTarget
directory?: string
run: MultiRun
selectedEntryIds: number[]
@@ -38,7 +40,7 @@ function errorCode(error: unknown): string | undefined {
}
export function FusionComposer({
repoId,
target,
directory,
run,
selectedEntryIds,
@@ -85,15 +87,26 @@ export function FusionComposer({
Base ref
</Label>
<div className="min-w-0 flex-1">
<BranchCombobox
id="fusion-base-ref"
repoId={repoId}
value={baseRef}
onValueChange={setBaseRef}
placeholder="Current HEAD"
clearable
listClassName={UPWARD_LIST_CLASS}
/>
{target.kind === 'repo' ? (
<BranchCombobox
id="fusion-base-ref"
repoId={target.repoId}
value={baseRef}
onValueChange={setBaseRef}
placeholder="Current HEAD"
clearable
listClassName={UPWARD_LIST_CLASS}
/>
) : (
<Input
id="fusion-base-ref"
value={baseRef}
onChange={(event) => setBaseRef(event.target.value)}
placeholder="Current HEAD"
autoComplete="off"
className="font-mono text-sm"
/>
)}
</div>
</div>
@@ -42,7 +42,7 @@ interface MultiRunCardProps {
onExitSelection: () => void
onToggleEntry: (entryId: number, checked: boolean) => void
onOpenSession: (sessionId: string, isolated: boolean) => void
onWalkthrough: (sessionId: string) => void
onWalkthrough?: (sessionId: string) => void
onDiscard: (entry: MultiRunEntry) => void
}
@@ -278,7 +278,7 @@ interface EntryRowProps {
unavailableReason: string | null
onToggle: (checked: boolean) => void
onOpenSession: (sessionId: string, isolated: boolean) => void
onWalkthrough: (sessionId: string) => void
onWalkthrough?: (sessionId: string) => void
onDiscard: () => void
}
@@ -344,7 +344,7 @@ function EntryRow({
{sessionId ? (
<RowAction icon={ArrowUpRight} label="Open" onClick={() => onOpenSession(sessionId, entry.isolated)} />
) : null}
{sessionId ? (
{sessionId && onWalkthrough ? (
<RowAction icon={BookOpen} label="Walkthrough" onClick={() => onWalkthrough(sessionId)} />
) : null}
{canDiscard ? (
@@ -375,7 +375,7 @@ function EntryRow({
interface FusionRowProps {
fusion: MultiRunFusion
onOpenSession: (sessionId: string, isolated: boolean) => void
onWalkthrough: (sessionId: string) => void
onWalkthrough?: (sessionId: string) => void
}
function FusionRow({ fusion, onOpenSession, onWalkthrough }: FusionRowProps) {
@@ -403,7 +403,7 @@ function FusionRow({ fusion, onOpenSession, onWalkthrough }: FusionRowProps) {
{sessionId ? (
<div className="flex shrink-0 items-center gap-1">
<RowAction icon={ArrowUpRight} label="Open" onClick={() => onOpenSession(sessionId, fusion.isolated)} />
<RowAction icon={BookOpen} label="Walkthrough" onClick={() => onWalkthrough(sessionId)} />
{onWalkthrough ? <RowAction icon={BookOpen} label="Walkthrough" onClick={() => onWalkthrough(sessionId)} /> : null}
</div>
) : null}
</li>
@@ -119,6 +119,8 @@ function fusion(overrides: Partial<MultiRunFusion> = {}): MultiRunFusion {
const oneStartedRun: MultiRun = {
id: 3,
repoId: 7,
serverId: 'local',
directory: null,
name: 'Sweep',
prompt: 'go',
isolated: true,
@@ -162,7 +164,14 @@ function createWrapper() {
function renderSheet(overrides: Partial<React.ComponentProps<typeof MultiRunSheet>> = {}) {
const onOpenChange = vi.fn()
const view = render(
<MultiRunSheet repoId={7} directory="/repo" defaultBaseRef="main" open onOpenChange={onOpenChange} {...overrides} />,
<MultiRunSheet
target={{ kind: 'repo', repoId: 7 }}
directory="/repo"
defaultBaseRef="main"
open
onOpenChange={onOpenChange}
{...overrides}
/>,
{ wrapper: createWrapper() },
)
return { ...view, onOpenChange }
@@ -714,4 +723,93 @@ describe('MultiRunSheet', () => {
expect(mockNavigate).toHaveBeenCalledWith('/repos/7/sessions/ses_recovered')
})
})
describe('Linked server target', () => {
const serverTarget = { kind: 'server', serverId: 'srv_kitchen', directory: '/srv/app' } as const
const serverRun: MultiRun = {
...oneStartedRun,
repoId: null,
serverId: 'srv_kitchen',
directory: '/srv/app',
}
function renderServerSheet() {
return renderSheet({ target: serverTarget, directory: '/srv/app', defaultBaseRef: undefined })
}
it('lists the runs of the server directory', async () => {
mocks.listMultiRuns.mockResolvedValue([serverRun])
renderServerSheet()
expect(await screen.findByRole('region', { name: 'Sweep' })).toBeInTheDocument()
expect(mocks.listMultiRuns).toHaveBeenCalledWith(serverTarget)
})
it('launches with the server target instead of a repository', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(serverRun)
renderServerSheet()
await fillLaunchForm(user)
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith({
serverId: 'srv_kitchen',
directory: '/srv/app',
name: 'Sweep',
prompt: 'go',
models: ['openai/gpt-4o'],
isolate: true,
})
})
})
it('takes the base ref as text because server branches are not listed', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(serverRun)
renderServerSheet()
await openNewRun(user)
expect(screen.getByRole('textbox', { name: 'Start from' })).toBeInTheDocument()
expect(screen.queryByRole('combobox', { name: 'Start from' })).not.toBeInTheDocument()
await user.type(screen.getByLabelText('Start from'), 'release')
expect(mocks.listBranches).not.toHaveBeenCalled()
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith(expect.objectContaining({ baseRef: 'release' }))
})
})
it('opens sessions on the server route and hides the local-only walkthrough', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([serverRun])
const { onOpenChange } = renderServerSheet()
const card = await screen.findByRole('region', { name: 'Sweep' })
expect(within(card).queryByRole('button', { name: /walkthrough/i })).not.toBeInTheDocument()
await user.click(within(card).getByRole('button', { name: 'Open' }))
expect(onOpenChange).toHaveBeenCalledWith(false)
expect(mockNavigate).toHaveBeenCalledWith('/servers/srv_kitchen/sessions/ses_11')
})
it('opens a server fusion session on the server route', async () => {
const user = userEvent.setup()
mocks.listMultiRuns.mockResolvedValue([{ ...serverRun, fusions: [fusion()] }])
renderServerSheet()
const card = await screen.findByRole('region', { name: 'Sweep' })
const fusionRow = within(card).getByText('from 1 source (truncated)').closest('li') as HTMLElement
await user.click(within(fusionRow).getByRole('button', { name: 'Open' }))
expect(mockNavigate).toHaveBeenCalledWith('/servers/srv_kitchen/sessions/ses_fusion')
})
})
})
+44 -23
View File
@@ -17,18 +17,19 @@ import { ChangesWalkthroughSheet } from '@/components/session/ChangesWalkthrough
import { useModelSections } from '@/hooks/useModelSections'
import { useDiscardMultiRunEntry, useFuseMultiRun, useLaunchMultiRun, useMultiRuns } from '@/hooks/useMultiRuns'
import { filterModelSections } from '@/lib/modelSections'
import { getServerSessionPath, getSessionPath } from '@/lib/navigation'
import { randomId } from '@/lib/utils'
import { buildSessionPath } from '@opencode-manager/shared/utils'
import {
FusionUnavailableDetailsSchema,
MULTI_RUN_MAX_MODELS,
type FuseMultiRunRequest,
type LaunchMultiRunRequest,
type MultiRunEntry,
type MultiRunTarget,
} from '@opencode-manager/shared/schemas'
interface MultiRunSheetProps {
repoId: number
target: MultiRunTarget
directory?: string
defaultBaseRef?: string
open: boolean
@@ -55,7 +56,14 @@ function unavailableReasonsFromError(error: unknown): ReadonlyMap<number, string
return new Map(parsed.data.unavailableSources.map((source) => [source.entryId, source.message]))
}
export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenChange }: MultiRunSheetProps) {
function multiRunSessionPath(target: MultiRunTarget, sessionId: string, isolated: boolean): string {
if (target.kind === 'server') {
return getServerSessionPath(target.serverId, sessionId)
}
return getSessionPath(target.repoId, sessionId, isolated ? { repoTab: 'workspaces' } : undefined)
}
export function MultiRunSheet({ target, directory, defaultBaseRef, open, onOpenChange }: MultiRunSheetProps) {
const navigate = useNavigate()
const [activeTab, setActiveTab] = useState<SheetTab>('runs')
const [expandedRuns, setExpandedRuns] = useState<Record<number, boolean>>({})
@@ -64,9 +72,9 @@ export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenC
const [pendingDiscard, setPendingDiscard] = useState<PendingDiscard | null>(null)
const [walkthroughSessionId, setWalkthroughSessionId] = useState<string | null>(null)
const runsQuery = useMultiRuns(repoId, open)
const fuse = useFuseMultiRun(repoId)
const discard = useDiscardMultiRunEntry(repoId)
const runsQuery = useMultiRuns(target, open)
const fuse = useFuseMultiRun(target)
const discard = useDiscardMultiRunEntry(target)
const resetFuse = fuse.reset
useEffect(() => {
@@ -85,7 +93,7 @@ export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenC
const openSession = (sessionId: string, isolated: boolean) => {
onOpenChange(false)
navigate(buildSessionPath(repoId, sessionId, isolated ? { repoTab: 'workspaces' } : undefined))
navigate(multiRunSessionPath(target, sessionId, isolated))
}
const startSelection = (runId: number) => {
@@ -197,7 +205,7 @@ export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenC
onExitSelection={exitSelection}
onToggleEntry={toggleEntry}
onOpenSession={openSession}
onWalkthrough={setWalkthroughSessionId}
onWalkthrough={target.kind === 'repo' ? setWalkthroughSessionId : undefined}
onDiscard={(entry) => setPendingDiscard({ runId: run.id, entry })}
/>
))
@@ -207,7 +215,7 @@ export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenC
{selection && selectedRun ? (
<FusionComposer
key={selectedRun.id}
repoId={repoId}
target={target}
directory={directory}
run={selectedRun}
selectedEntryIds={selection.entryIds}
@@ -222,7 +230,7 @@ export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenC
<TabsContent forceMount value="new" className="mt-0 flex min-h-0 flex-1 flex-col px-0 data-[state=inactive]:hidden">
<NewRunForm
repoId={repoId}
target={target}
directory={directory}
defaultBaseRef={defaultBaseRef}
open={open}
@@ -258,7 +266,7 @@ export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenC
onOpenChange={(next) => {
if (!next) setWalkthroughSessionId(null)
}}
onOpenSession={(id) => navigate(buildSessionPath(repoId, id))}
onOpenSession={(id) => navigate(multiRunSessionPath(target, id, false))}
/>
) : null}
</>
@@ -266,14 +274,14 @@ export function MultiRunSheet({ repoId, directory, defaultBaseRef, open, onOpenC
}
interface NewRunFormProps {
repoId: number
target: MultiRunTarget
directory?: string
defaultBaseRef?: string
open: boolean
onLaunched: () => void
}
function NewRunForm({ repoId, directory, defaultBaseRef, open, onLaunched }: NewRunFormProps) {
function NewRunForm({ target, directory, defaultBaseRef, open, onLaunched }: NewRunFormProps) {
const [name, setName] = useState('')
const [prompt, setPrompt] = useState('')
const [selectedModels, setSelectedModels] = useState<string[]>([])
@@ -283,7 +291,7 @@ function NewRunForm({ repoId, directory, defaultBaseRef, open, onLaunched }: New
const deferredModelSearch = useDeferredValue(modelSearch)
const { sections: modelSections } = useModelSections(directory, { enabled: open })
const launch = useLaunchMultiRun(repoId)
const launch = useLaunchMultiRun(target)
const visibleModelSections = useMemo(
() => filterModelSections(modelSections, deferredModelSearch),
@@ -306,7 +314,9 @@ function NewRunForm({ repoId, directory, defaultBaseRef, open, onLaunched }: New
const handleLaunch = () => {
if (!canSubmit) return
const request: LaunchMultiRunRequest = {
repoId,
...(target.kind === 'repo'
? { repoId: target.repoId }
: { serverId: target.serverId, directory: target.directory }),
name: name.trim(),
prompt: prompt.trim(),
models: selectedModels,
@@ -378,14 +388,25 @@ function NewRunForm({ repoId, directory, defaultBaseRef, open, onLaunched }: New
{isolate ? (
<div className="space-y-1.5">
<Label htmlFor="multi-run-base-ref">Start from</Label>
<BranchCombobox
id="multi-run-base-ref"
repoId={repoId}
value={baseRef}
onValueChange={setBaseRef}
placeholder="Current HEAD"
clearable
/>
{target.kind === 'repo' ? (
<BranchCombobox
id="multi-run-base-ref"
repoId={target.repoId}
value={baseRef}
onValueChange={setBaseRef}
placeholder="Current HEAD"
clearable
/>
) : (
<Input
id="multi-run-base-ref"
value={baseRef}
onChange={(event) => setBaseRef(event.target.value)}
placeholder="Current HEAD"
autoComplete="off"
className="font-mono text-sm"
/>
)}
<p className="text-xs text-muted-foreground">Each isolated workspace starts from this branch.</p>
</div>
) : null}
@@ -61,12 +61,12 @@ export function ProjectActionsMenu({ repoId, directory }: ProjectActionsMenuProp
const openPreview = useOpenPreview()
const openTerminal = useOpenTerminal()
const configQuery = useProjectConfig(repoId, directory, menuOpen && !!directory)
const terminalsQuery = useTerminals(repoId, directory, {
const terminalsQuery = useTerminals({ kind: 'repo', repoId }, directory, {
enabled: menuOpen && !!directory,
refetchInterval: menuOpen ? 5000 : false,
})
const runAction = useRunProjectAction(repoId, directory)
const removeTerminal = useRemoveTerminal(repoId)
const removeTerminal = useRemoveTerminal({ kind: 'repo', repoId })
const trustConfig = useTrustRepoConfig(repoId)
const [pendingTrust, setPendingTrust] = useState<PendingTrust | null>(null)
const scopeRef = useRef({ repoId, directory })
@@ -0,0 +1,43 @@
import { describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { RemoteMultiRunButton } from './RemoteMultiRunButton'
vi.mock('@/components/repo/MultiRunSheet', () => ({
MultiRunSheet: ({
target,
directory,
open,
}: {
target: { kind: string; serverId?: string; directory?: string }
directory?: string
open: boolean
}) => (
<div
data-testid="multi-run-sheet"
data-open={String(open)}
data-kind={target.kind}
data-server={target.serverId}
data-target-directory={target.directory}
data-directory={directory}
/>
),
}))
describe('RemoteMultiRunButton', () => {
it('opens the multi-run sheet for the project directory on the linked server', async () => {
const user = userEvent.setup()
render(<RemoteMultiRunButton serverId="srv_kitchen" directory="/srv/app" />)
expect(screen.queryByTestId('multi-run-sheet')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Multi-run' }))
const sheet = screen.getByTestId('multi-run-sheet')
expect(sheet).toHaveAttribute('data-open', 'true')
expect(sheet).toHaveAttribute('data-kind', 'server')
expect(sheet).toHaveAttribute('data-server', 'srv_kitchen')
expect(sheet).toHaveAttribute('data-target-directory', '/srv/app')
expect(sheet).toHaveAttribute('data-directory', '/srv/app')
})
})
@@ -0,0 +1,36 @@
import { useState } from 'react'
import { Layers } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { MultiRunSheet } from '@/components/repo/MultiRunSheet'
interface RemoteMultiRunButtonProps {
serverId: string
directory: string
}
export function RemoteMultiRunButton({ serverId, directory }: RemoteMultiRunButtonProps) {
const [mounted, setMounted] = useState(false)
const [open, setOpen] = useState(false)
const handleOpen = () => {
setMounted(true)
setOpen(true)
}
return (
<>
<Button size="sm" variant="outline" onClick={handleOpen} className="shrink-0">
<Layers className="mr-1 h-4 w-4" />
Multi-run
</Button>
{mounted ? (
<MultiRunSheet
target={{ kind: 'server', serverId, directory }}
directory={directory}
open={open}
onOpenChange={setOpen}
/>
) : null}
</>
)
}
@@ -30,6 +30,7 @@ type GeneralTabProps = {
workspaceMode: ScheduleWorkspaceMode
onWorkspaceModeChange: (value: ScheduleWorkspaceMode) => void
showWorkspaceMode: boolean
showBranch?: boolean
showRepoSelector?: boolean
isEditing: boolean
repoId?: number
@@ -74,6 +75,7 @@ export function GeneralTab({
workspaceMode,
onWorkspaceModeChange,
showWorkspaceMode,
showBranch = true,
showRepoSelector,
isEditing,
repoId,
@@ -171,10 +173,11 @@ export function GeneralTab({
name="schedule-workspace-mode"
value={workspaceMode}
onChange={onWorkspaceModeChange}
options={workspaceModeOptions}
options={workspaceModeOptions.filter((option) => option.value !== 'in-place')}
/>
</div>
)}
{showBranch && (
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="schedule-branch">Base branch</Label>
@@ -190,6 +193,7 @@ export function GeneralTab({
clearable
/>
</div>
)}
</div>
<div className="space-y-2">
@@ -40,10 +40,13 @@ export function JobDetailTab({
runningRun,
isJobFetching,
}: JobDetailTabProps) {
const { scheduleTarget } = useScheduleTarget(selectedJob?.repoId)
const { availableModels } = useScheduleModels(Boolean(selectedJob), scheduleTarget?.fullPath)
const repoId = selectedJob?.repoId ?? undefined
const isRemote = selectedJob?.repoId === null
const { scheduleTarget } = useScheduleTarget(repoId)
const modelDirectory = isRemote ? (selectedJob?.directory ?? undefined) : scheduleTarget?.fullPath
const { availableModels } = useScheduleModels(Boolean(selectedJob), modelDirectory, isRemote ? selectedJob?.serverId : undefined)
const resolvedModel = resolveScheduleModel(selectedJob?.model, availableModels)
const { data: worktrees = [] } = useScheduleWorktrees(selectedJob?.repoId, selectedJob?.id ?? null)
const { data: worktrees = [] } = useScheduleWorktrees(repoId, selectedJob?.id ?? null)
const removeWorktrees = useRemoveScheduleWorktrees()
const idleWorktreeCount = worktrees.filter((worktree) => !worktree.inUse).length
@@ -119,7 +122,7 @@ export function JobDetailTab({
</section>
)}
{worktrees.length > 0 && (
{!isRemote && 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>
@@ -130,7 +133,7 @@ export function JobDetailTab({
variant="outline"
size="sm"
aria-label="Remove all worktrees"
onClick={() => removeWorktrees.mutate({ repoId: selectedJob.repoId, jobId: selectedJob.id })}
onClick={() => { if (repoId !== undefined) removeWorktrees.mutate({ 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" />}
@@ -152,7 +155,7 @@ export function JobDetailTab({
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 })}
onClick={() => { if (repoId !== undefined) removeWorktrees.mutate({ repoId, jobId: selectedJob.id, worktreePath: worktree.worktreePath }) }}
disabled={worktree.inUse || removeWorktrees.isPending}
>
<Trash2 className="h-4 w-4" />
@@ -184,7 +187,7 @@ 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 && (
{(isRemote || selectedJob.repoId !== ASSISTANT_REPO_ID) && (
<div>
<p className="text-muted-foreground">Workspace</p>
<p className="font-medium">{formatWorkspaceMode(selectedJob.workspaceMode)}</p>
@@ -0,0 +1,34 @@
import { useState } from 'react'
import { CalendarClock } from 'lucide-react'
import { Button } from '@/components/ui/button'
import type { ScheduleServerTarget } from '@/api/schedules'
import { ServerSchedulesDialog } from './ServerSchedulesDialog'
interface RemoteSchedulesButtonProps {
serverId: string
directory: string
}
/**
* Opens the schedule list for one project on a linked OpenCode server.
*/
export function RemoteSchedulesButton({ serverId, directory }: RemoteSchedulesButtonProps) {
const [open, setOpen] = useState(false)
const target: ScheduleServerTarget = { serverId, directory }
return (
<>
<Button
size="sm"
variant="outline"
onClick={() => setOpen(true)}
className="shrink-0"
aria-label={`Schedules for ${directory}`}
>
<CalendarClock className="mr-1 h-4 w-4" />
<span className="hidden sm:inline">Schedules</span>
</Button>
<ServerSchedulesDialog open={open} onOpenChange={setOpen} target={target} />
</>
)
}
@@ -9,7 +9,7 @@ import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
import { getRepo } from '@/api/repos'
import { createSessionWithContext } from '@/api/opencode'
import { getWorkspaceFilePath } from '@/lib/markdownLinks'
import { getSessionPath } from '@/lib/navigation'
import { getServerSessionPath, getSessionPath } from '@/lib/navigation'
import { getRepoDisplayName } from '@/lib/utils'
import { showToast } from '@/lib/toast'
import { useMarkScheduleRunViewed } from '@/hooks/useSchedules'
@@ -17,20 +17,22 @@ import { Loader2 } from 'lucide-react'
import type { ScheduleRun } from '@opencode-manager/shared/types'
interface RunDetailPanelProps {
repoId: number
repoId: number | null
serverId?: string
activeRun: ScheduleRun | null
selectedRunLoading: boolean
onCancelRun: () => void
cancelRunPending: boolean
}
export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancelRun, cancelRunPending }: RunDetailPanelProps) {
export function RunDetailPanel({ repoId, serverId, activeRun, selectedRunLoading, onCancelRun, cancelRunPending }: RunDetailPanelProps) {
const navigate = useNavigate()
const [selectedFilePath, setSelectedFilePath] = useState<string | null>(null)
const [openingSession, setOpeningSession] = useState(false)
const { data: repo, isPending: repoPending, isError: repoError, refetch: refetchRepo } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId),
queryFn: () => getRepo(repoId!),
enabled: repoId !== null,
})
const markRunViewed = useMarkScheduleRunViewed()
const viewedRunIdRef = useRef<number | null>(null)
@@ -74,6 +76,10 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
const opensNewRepoSession = Boolean(activeRun.runBranch) && !activeRun.worktreePath && activeRun.status !== 'running'
const handleOpenSession = async () => {
if (repoId === null) {
if (sessionId && serverId) navigate(getServerSessionPath(serverId, sessionId))
return
}
if (!opensNewRepoSession) {
if (sessionId) navigate(getSessionPath(repoId, sessionId))
return
@@ -130,10 +136,10 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
<div className="flex items-center justify-center p-4"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
) : activeRun.responseText ? (
<>
{repoPending && (
{repoId !== null && repoPending && (
<div role="status" className="px-3 pt-2 text-xs text-muted-foreground">Loading repository details for local links.</div>
)}
{repoError && (
{repoId !== null && repoError && (
<div role="alert" className="flex items-center gap-2 px-3 pt-2 text-xs text-destructive">
<span>Could not load repository details for local links.</span>
<Button variant="outline" size="sm" onClick={() => { void refetchRepo() }}>Retry</Button>
@@ -160,7 +166,7 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
onClose={() => setSelectedFilePath(null)}
basePath={repo?.localPath}
repoName={repo ? getRepoDisplayName(repo) : undefined}
repoId={repoId}
repoId={repoId ?? undefined}
initialSelectedFile={selectedFilePath ?? undefined}
/>
</>
@@ -0,0 +1,120 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ScheduleJob } from '@opencode-manager/shared/types'
import { ScheduleJobDialog } from './ScheduleJobDialog'
Element.prototype.scrollIntoView = vi.fn()
vi.mock('@/hooks/usePromptTemplates', () => ({
usePromptTemplates: () => ({ data: [], isLoading: false }),
useCreatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
useUpdatePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
useDeletePromptTemplate: () => ({ mutate: vi.fn(), isPending: false }),
}))
vi.mock('@/hooks/useScheduleTarget', () => ({
useScheduleTarget: () => ({ scheduleTarget: undefined, isLoading: false, isError: false }),
}))
vi.mock('@/hooks/useScheduleModels', () => ({
useScheduleModels: () => ({ availableModels: null, isLoading: false }),
}))
vi.mock('@/hooks/useOpenCode', () => ({
useAgents: () => ({ data: [], isSuccess: true }),
}))
vi.mock('@/api/settings', () => ({
settingsApi: {
listManagedSkills: () => Promise.resolve([]),
},
}))
vi.mock('@/api/mcp', () => ({
mcpApi: {
getStatus: () => Promise.resolve({}),
},
}))
vi.mock('@/api/repos', () => ({
listRepos: () => Promise.resolve([]),
}))
const remoteJob: ScheduleJob = {
id: 7,
repoId: null,
serverId: 'srv_kitchen',
directory: '/srv/projects/audit',
name: 'Nightly audit',
description: null,
enabled: true,
scheduleMode: 'interval',
intervalMinutes: 60,
cronExpression: null,
timezone: null,
agentSlug: null,
prompt: 'Audit the project.',
model: null,
skillMetadata: null,
permissionConfig: null,
mcpServers: [],
branch: null,
workspaceMode: 'in-place',
createdAt: 0,
updatedAt: 0,
lastRunAt: null,
nextRunAt: null,
}
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
describe('ScheduleJobDialog — server target', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('hides worktree workspace mode and submits an in-place target directory', async () => {
const onSubmit = vi.fn()
render(
<ScheduleJobDialog
open
onOpenChange={vi.fn()}
onSubmit={onSubmit}
isSaving={false}
job={remoteJob}
serverTarget={{ serverId: 'srv_kitchen', directory: '/srv/projects/audit' }}
/>,
{ wrapper: createWrapper() },
)
await waitFor(() => {
expect(screen.getByText('Edit schedule')).toBeInTheDocument()
})
expect(screen.queryByText('Workspace')).not.toBeInTheDocument()
expect(screen.queryByLabelText('Base branch')).not.toBeInTheDocument()
expect(screen.queryByText('Fresh worktree, cleaned up')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Save changes' }))
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({
workspaceMode: 'in-place',
directory: '/srv/projects/audit',
branch: null,
}))
})
})
})
@@ -9,6 +9,7 @@ import { settingsApi } from '@/api/settings'
import { mcpApi } from '@/api/mcp'
import { listRepos } from '@/api/repos'
import type { Repo } from '@/api/types'
import type { ScheduleServerTarget } from '@/api/schedules'
import { Button } from '@/components/ui/button'
import type { ComboboxOption } from '@/components/ui/combobox'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
@@ -45,9 +46,10 @@ type ScheduleJobDialogProps = {
repoId?: number
onRepoChange?: (repoId: number | undefined) => void
isEditing?: boolean
serverTarget?: ScheduleServerTarget
}
export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, showRepoSelector, repoId: selectedRepoId, onRepoChange }: ScheduleJobDialogProps) {
export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, showRepoSelector, repoId: selectedRepoId, onRepoChange, serverTarget }: ScheduleJobDialogProps) {
const [schedulePreset, setSchedulePreset] = useState<SchedulePreset>('interval')
const [name, setName] = useState('')
const [description, setDescription] = useState('')
@@ -81,17 +83,19 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
const { data: templates = EMPTY_TEMPLATES } = usePromptTemplates()
const deleteTemplateMutation = useDeletePromptTemplate()
const effectiveRepoId = selectedRepoId ?? job?.repoId
const { scheduleTarget } = useScheduleTarget(open ? effectiveRepoId : undefined)
const scheduleDirectory = scheduleTarget?.fullPath
const serverTargetId = serverTarget?.serverId
const serverTargetDirectory = serverTarget?.directory
const effectiveRepoId = selectedRepoId ?? job?.repoId ?? undefined
const { scheduleTarget } = useScheduleTarget(serverTargetId ? undefined : (open ? effectiveRepoId : undefined))
const scheduleDirectory = serverTargetDirectory ?? scheduleTarget?.fullPath
const { availableModels } = useScheduleModels(open, scheduleDirectory)
const { availableModels } = useScheduleModels(open, scheduleDirectory, serverTargetId)
const resolvedModel = useMemo(
() => (modelDirty ? (model.trim() || null) : resolveScheduleModel(model, availableModels)),
[model, modelDirty, availableModels],
)
const { data: agents = [], isSuccess: agentsLoaded } = useAgents(scheduleDirectory, { enabled: !!scheduleDirectory })
const { data: agents = [], isSuccess: agentsLoaded } = useAgents(scheduleDirectory, { enabled: !!scheduleDirectory, serverId: serverTargetId })
const { data: skills = [], isLoading: skillsLoading } = useQuery({
queryKey: ['managed-skills'],
@@ -101,8 +105,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
})
const { data: mcpStatuses = {}, isLoading: mcpStatusesLoading } = useQuery({
queryKey: ['mcp-status', scheduleDirectory],
queryFn: () => mcpApi.getStatus(scheduleDirectory),
queryKey: ['mcp-status', scheduleDirectory, serverTargetId],
queryFn: () => (serverTargetId
? mcpApi.getStatus(scheduleDirectory, serverTargetId)
: mcpApi.getStatus(scheduleDirectory)),
enabled: open && !!scheduleDirectory,
})
@@ -167,12 +173,12 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
initialSkillSlugsRef.current = initialSkillSlugs
initialSkillNotesRef.current = initialSkillNotes
setMcpServers(job?.mcpServers ?? [])
setBranch(job?.branch ?? '')
setWorkspaceMode(job?.workspaceMode ?? 'worktree')
setBranch(serverTargetDirectory ? '' : (job?.branch ?? ''))
setWorkspaceMode(serverTargetDirectory ? 'in-place' : (job?.workspaceMode ?? 'worktree'))
setAllowExternalDirectory(job?.permissionConfig?.allowExternalDirectory ?? false)
setAllowQuestions(job?.permissionConfig?.allowQuestions ?? false)
setBashDenyPatterns(job?.permissionConfig?.bashDenyPatterns ?? [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
}, [job, open])
}, [job, open, serverTargetDirectory])
useEffect(() => {
if (!open) {
@@ -216,8 +222,9 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
agentSlug: selectedAgentSlug.trim() || undefined,
model: resolvedModel ?? undefined,
prompt: prompt.trim(),
branch: branch.trim() || null,
workspaceMode,
branch: serverTargetDirectory ? null : (branch.trim() || null),
workspaceMode: serverTargetDirectory ? 'in-place' : workspaceMode,
...(serverTargetDirectory ? { directory: serverTargetDirectory } : {}),
mcpServers,
permissionConfig: {
allowExternalDirectory,
@@ -266,7 +273,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
<DialogHeader className="shrink-0 space-y-1 border-b border-border px-3 sm:px-6 py-4">
<DialogTitle>{job ? 'Edit schedule' : 'New schedule'}</DialogTitle>
<DialogDescription className="mt-0">
Create a reusable repo job with a visual schedule builder, manual runs, and optional advanced metadata.
{serverTarget ? 'Create a reusable job for this remote project' : 'Create a reusable repo job'} with a visual schedule builder, manual runs, and optional advanced metadata.
</DialogDescription>
</DialogHeader>
@@ -296,10 +303,11 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
onEnabledChange={setEnabled}
branch={branch}
onBranchChange={setBranch}
branchRepoId={open && effectiveRepoId !== ASSISTANT_REPO_ID ? effectiveRepoId : undefined}
branchRepoId={!serverTargetDirectory && open && effectiveRepoId !== undefined && effectiveRepoId !== ASSISTANT_REPO_ID ? effectiveRepoId : undefined}
workspaceMode={workspaceMode}
onWorkspaceModeChange={setWorkspaceMode}
showWorkspaceMode={effectiveRepoId !== ASSISTANT_REPO_ID}
showWorkspaceMode={!serverTargetDirectory && effectiveRepoId !== ASSISTANT_REPO_ID}
showBranch={!serverTargetDirectory}
showRepoSelector={showRepoSelector}
isEditing={!!job}
repoId={selectedRepoId}
@@ -8,13 +8,13 @@ import type { ScheduleRunWithContext } from '@/api/schedules'
import type { Repo } from '@/api/types'
const mocks = vi.hoisted(() => ({
useRepoScheduleRun: vi.fn(),
useScheduleRunDetail: vi.fn(),
useMarkScheduleRunViewed: vi.fn(),
getRepo: vi.fn(),
}))
vi.mock('@/hooks/useSchedules', () => ({
useRepoScheduleRun: mocks.useRepoScheduleRun,
useScheduleRunDetail: mocks.useScheduleRunDetail,
useMarkScheduleRunViewed: mocks.useMarkScheduleRunViewed,
}))
@@ -85,7 +85,7 @@ function renderDrawer(props: Partial<ComponentProps<typeof ScheduleRunDrawer>> =
describe('ScheduleRunDrawer', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
mocks.useScheduleRunDetail.mockReturnValue({ data: undefined, isLoading: false })
mocks.useMarkScheduleRunViewed.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.getRepo.mockResolvedValue(repo)
})
@@ -5,7 +5,7 @@ import { SideDrawer, SideDrawerContent, SideDrawerHeader } from '@/components/ui
import { RunDetailPanel } from './RunDetailPanel'
import { formatRunBranch, getRunRepoName, getRunStatusIcon, getRunStatusLabel, getRunTitle, type ScheduleRunRow } from './schedule-run-display'
import { formatRunDuration } from './schedule-utils'
import { useRepoScheduleRun } from '@/hooks/useSchedules'
import { useScheduleRunDetail } from '@/hooks/useSchedules'
interface ScheduleRunDrawerProps {
run: ScheduleRunRow | null
@@ -36,7 +36,7 @@ export function ScheduleRunDrawer({
onPrev,
onNext,
}: ScheduleRunDrawerProps) {
const { data: detail, isLoading } = useRepoScheduleRun(run?.repoId, run?.jobId ?? null, run?.id ?? null)
const { data: detail, isLoading } = useScheduleRunDetail(run)
const activeRun = detail ?? run
const title = run ? getRunTitle(run) : 'Run'
@@ -90,6 +90,7 @@ export function ScheduleRunDrawer({
{activeRun ? (
<RunDetailPanel
repoId={activeRun.repoId}
serverId={activeRun.serverId}
activeRun={activeRun}
selectedRunLoading={isLoading && !detail}
onCancelRun={onCancelRun}
@@ -0,0 +1,285 @@
import { useMemo, useState } from 'react'
import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types'
import type { ScheduleServerTarget } from '@/api/schedules'
import {
useAllSchedules,
useCancelServerScheduleRun,
useClearServerScheduleRuns,
useCreateServerSchedule,
useDeleteServerSchedule,
useDeleteServerScheduleRun,
useRunServerSchedule,
useServerSchedule,
useServerScheduleRuns,
useUpdateServerSchedule,
} from '@/hooks/useSchedules'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { CalendarClock, Loader2, Plus } from 'lucide-react'
import {
JobDetailTab,
RunHistoryTab,
ScheduleJobDialog,
ScheduleJobsTable,
ScheduleListToolbar,
ScheduleRunRemovalDialog,
ScheduleTabMenu,
} from '@/components/schedules'
import { DELETE_SCHEDULE_DESCRIPTION, matchesScheduleJobSearch, toUpdateScheduleRequest } from './schedule-utils'
type ServerScheduleTab = 'jobs' | 'detail' | 'runs'
type ServerScheduleDialog = 'new' | 'edit' | 'delete' | null
interface ServerSchedulesContentProps {
target: ScheduleServerTarget
}
/**
* Schedule jobs, job detail and run history for a project directory on a linked
* OpenCode server. Remote runs execute in place, so worktree controls are absent.
*/
export function ServerSchedulesContent({ target }: ServerSchedulesContentProps) {
const { serverId, directory } = target
const [tab, setTab] = useState<ServerScheduleTab>('jobs')
const [jobId, setJobId] = useState<number | null>(null)
const [runId, setRunId] = useState<number | null>(null)
const [dialog, setDialog] = useState<ServerScheduleDialog>(null)
const [search, setSearch] = useState('')
const [clearRunsOpen, setClearRunsOpen] = useState(false)
const [runToDelete, setRunToDelete] = useState<number | null>(null)
const { data: allSchedules, isLoading } = useAllSchedules()
const jobs = useMemo(
() => allSchedules?.filter((job) => job.serverId === serverId && job.directory === directory),
[allSchedules, directory, serverId],
)
const selectedJob = useMemo(
() => jobs?.find((job) => job.id === jobId),
[jobs, jobId],
)
const { data: fetchedJob, isFetching: isJobFetching } = useServerSchedule(serverId, jobId)
const { data: runs, isLoading: runsLoading } = useServerScheduleRuns(serverId, jobId, 30)
const createMutation = useCreateServerSchedule(serverId)
const updateMutation = useUpdateServerSchedule(serverId)
const deleteMutation = useDeleteServerSchedule(serverId)
const runMutation = useRunServerSchedule(serverId)
const cancelRunMutation = useCancelServerScheduleRun(serverId)
const clearRunsMutation = useClearServerScheduleRuns(serverId)
const deleteRunMutation = useDeleteServerScheduleRun(serverId)
const visibleJobs = useMemo(
() => (jobs ?? []).filter((job) => matchesScheduleJobSearch(job, search)),
[jobs, search],
)
const clearableRuns = useMemo(() => (runs ?? []).filter((run) => run.status !== 'running'), [runs])
const runningRun = useMemo(() => runs?.find((run) => run.status === 'running') ?? null, [runs])
const activeJob = selectedJob ?? fetchedJob
const editingJob = dialog === 'edit' ? selectedJob : undefined
const openJob = (job: ScheduleJob) => {
setJobId(job.id)
setTab('detail')
}
const handleCreate = (data: CreateScheduleJobRequest) => {
createMutation.mutate({ ...data, directory }, {
onSuccess: (job) => {
setDialog(null)
setJobId(job.id)
setTab('detail')
},
})
}
const handleUpdate = (data: CreateScheduleJobRequest) => {
if (dialog !== 'edit' || jobId === null) return
updateMutation.mutate({ jobId, data: toUpdateScheduleRequest(data) }, {
onSuccess: () => setDialog(null),
})
}
const handleDelete = () => {
if (dialog !== 'delete' || jobId === null) return
deleteMutation.mutate(jobId, {
onSuccess: () => {
setDialog(null)
setJobId(null)
setTab('jobs')
},
})
}
const handleToggleEnabled = (job: ScheduleJob) => {
updateMutation.mutate({ jobId: job.id, data: { enabled: !job.enabled } })
}
const handleRunNow = (job: ScheduleJob) => {
runMutation.mutate(job.id, {
onSuccess: (run) => {
setTab('runs')
setRunId(run.id)
},
})
}
const handleCancelRun = () => {
const run = runId !== null ? runs?.find((entry) => entry.id === runId) : null
if (!run || run.status !== 'running') return
cancelRunMutation.mutate({ jobId: run.jobId, runId: run.id })
}
const handleCancelJobRun = (job: ScheduleJob) => {
const lastRun = jobs?.find((entry) => entry.id === job.id)?.lastRun
if (!lastRun) return
cancelRunMutation.mutate({ jobId: job.id, runId: lastRun.id })
}
if (isLoading) {
return (
<div className="flex flex-1 items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)
}
const hasJobs = (jobs?.length ?? 0) > 0
return (
<>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
{!hasJobs ? (
<Card className="border-dashed border-border/70">
<CardContent className="flex flex-col items-start gap-4 p-6">
<div className="rounded-full border border-border bg-muted/40 p-3">
<CalendarClock className="h-6 w-6 text-muted-foreground" />
</div>
<div className="space-y-2">
<p className="text-xl font-semibold tracking-tight">No schedules yet</p>
<p className="text-sm text-muted-foreground">
Create a schedule for this remote project to automate recurring agent work in {directory}.
</p>
</div>
<Button onClick={() => setDialog('new')}>
<Plus className="mr-2 h-4 w-4" />
Create First Schedule
</Button>
</CardContent>
</Card>
) : (
<>
{tab === 'jobs' && (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
<ScheduleListToolbar search={search} onSearchChange={setSearch} searchPlaceholder="Search jobs">
<Button onClick={() => setDialog('new')} size="sm" className="h-9 shrink-0">
<Plus className="mr-1 h-4 w-4" />
New Schedule
</Button>
</ScheduleListToolbar>
<div className="min-h-0 flex-1 overflow-auto pt-2">
<div className="min-h-0 overflow-auto rounded-lg border border-border/70">
<ScheduleJobsTable
jobs={visibleJobs}
showRepo={false}
selectedJobId={jobId}
onOpen={openJob}
onRunNow={handleRunNow}
onToggleEnabled={handleToggleEnabled}
onEdit={(job) => { setJobId(job.id); setDialog('edit') }}
onDelete={(job) => { setJobId(job.id); setDialog('delete') }}
onCancelRun={handleCancelJobRun}
runPending={runMutation.isPending}
cancelPending={cancelRunMutation.isPending}
/>
</div>
</div>
</div>
)}
{tab === 'detail' && (
<JobDetailTab
selectedJob={activeJob}
onEdit={(job) => { setJobId(job.id); setDialog('edit') }}
onDelete={(id) => { setJobId(id); setDialog('delete') }}
onToggleEnabled={() => { if (activeJob) handleToggleEnabled(activeJob) }}
onRunNow={() => { if (activeJob) handleRunNow(activeJob) }}
updatePending={updateMutation.isPending}
runPending={runMutation.isPending}
runningRun={Boolean(runningRun)}
isJobFetching={isJobFetching}
/>
)}
{tab === 'runs' && (
<RunHistoryTab
selectedJob={activeJob}
runs={runs}
runsLoading={runsLoading}
runId={runId}
onSelectRun={setRunId}
onCancelRun={handleCancelRun}
cancelRunPending={cancelRunMutation.isPending}
onClearHistory={() => setClearRunsOpen(true)}
clearHistoryPending={clearRunsMutation.isPending}
onDeleteRun={setRunToDelete}
deleteRunPending={deleteRunMutation.isPending}
/>
)}
</>
)}
</div>
{hasJobs && (
<ScheduleTabMenu activeTab={tab} onTabChange={setTab} />
)}
<ScheduleJobDialog
open={dialog === 'new' || dialog === 'edit'}
onOpenChange={(open) => { if (!open) setDialog(null) }}
job={editingJob}
isSaving={createMutation.isPending || updateMutation.isPending}
onSubmit={dialog === 'edit' ? handleUpdate : handleCreate}
serverTarget={target}
/>
<DeleteDialog
open={dialog === 'delete'}
onOpenChange={(open) => { if (!open) setDialog(null) }}
onConfirm={handleDelete}
onCancel={() => setDialog(null)}
title="Delete Schedule"
description={DELETE_SCHEDULE_DESCRIPTION}
isDeleting={deleteMutation.isPending}
/>
<ScheduleRunRemovalDialog
open={clearRunsOpen}
onOpenChange={(open) => { if (!open) setClearRunsOpen(false) }}
title="Clear run history"
description={
<>This permanently deletes all <strong>{clearableRuns.length}</strong> finished run{clearableRuns.length === 1 ? '' : 's'} for this schedule. A run in progress is kept. This cannot be undone.</>
}
affectedWorktreeCount={0}
isPending={clearRunsMutation.isPending}
onCancel={() => setClearRunsOpen(false)}
onConfirm={() => {
if (jobId === null) return
clearRunsMutation.mutate(jobId, { onSuccess: () => setClearRunsOpen(false) })
}}
/>
<ScheduleRunRemovalDialog
open={runToDelete !== null}
onOpenChange={(open) => { if (!open) setRunToDelete(null) }}
title="Delete run"
description="This permanently deletes this run. This cannot be undone."
affectedWorktreeCount={0}
isPending={deleteRunMutation.isPending}
onCancel={() => setRunToDelete(null)}
onConfirm={() => {
if (jobId === null || runToDelete === null) return
deleteRunMutation.mutate({ jobId, runId: runToDelete }, { onSuccess: () => setRunToDelete(null) })
}}
/>
</>
)
}
@@ -0,0 +1,29 @@
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import type { ScheduleServerTarget } from '@/api/schedules'
import { ServerSchedulesContent } from './ServerSchedulesContent'
interface ServerSchedulesDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
target: ScheduleServerTarget | null
}
export function ServerSchedulesDialog({ open, onOpenChange, target }: ServerSchedulesDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex h-dvh max-h-dvh w-full max-w-5xl flex-col gap-0 overflow-hidden border-border bg-background p-0 shadow-lg sm:h-[min(88vh,860px)] sm:max-h-[88vh] sm:max-w-[92vw]">
<DialogHeader className="shrink-0 space-y-1 border-b border-border px-3 py-4 sm:px-6">
<DialogTitle>Schedules</DialogTitle>
<DialogDescription className="mt-0 truncate font-mono text-xs">
{target?.directory ?? ''}
</DialogDescription>
</DialogHeader>
{target ? (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden px-3 pb-3 pt-3 sm:px-6">
<ServerSchedulesContent target={target} />
</div>
) : null}
</DialogContent>
</Dialog>
)
}
@@ -56,6 +56,11 @@ export const workspaceModeOptions: Array<RadioOption<ScheduleWorkspaceMode>> = [
label: 'Shared worktree',
description: 'Every run reuses one worktree and branch, so work builds up from run to run.',
},
{
value: 'in-place',
label: 'In place',
description: 'Runs directly in the target project directory. Used for projects on a linked server.',
},
]
export function formatWorkspaceMode(mode: ScheduleWorkspaceMode): string {
@@ -15,6 +15,7 @@ vi.mock('@/hooks/useSessionGoals')
const baseGoal: SessionGoal = {
id: 1,
sessionId: 'ses_1',
serverId: 'local',
directory: '/repo',
objective: 'Ship the feature',
status: 'active',
@@ -80,7 +80,7 @@ function mockTerminalHooks(
function renderPanel(initialEntry = '/repos/1?dialog=terminal', onClose = vi.fn()) {
return render(
<MemoryRouter initialEntries={[initialEntry]}>
<TerminalPanel repoId={1} directory="/repo" isOpen onClose={onClose} />
<TerminalPanel target={{ kind: 'repo', repoId: 1 }} directory="/repo" isOpen onClose={onClose} />
</MemoryRouter>,
)
}
@@ -123,7 +123,7 @@ describe('TerminalPanel', () => {
mockTerminalHooks([], { isSuccess: true })
rerender(
<MemoryRouter initialEntries={['/repos/1?dialog=terminal']}>
<TerminalPanel repoId={1} directory="/repo" isOpen onClose={vi.fn()} />
<TerminalPanel target={{ kind: 'repo', repoId: 1 }} directory="/repo" isOpen onClose={vi.fn()} />
</MemoryRouter>,
)
@@ -147,7 +147,7 @@ describe('TerminalPanel', () => {
mockTerminalHooks([{ ...runningTerminal, status: 'exited', exitCode: 0 }])
rerender(
<MemoryRouter initialEntries={['/repos/1?dialog=terminal']}>
<TerminalPanel repoId={1} directory="/repo" isOpen onClose={vi.fn()} />
<TerminalPanel target={{ kind: 'repo', repoId: 1 }} directory="/repo" isOpen onClose={vi.fn()} />
</MemoryRouter>,
)
@@ -183,7 +183,7 @@ describe('TerminalPanel', () => {
const panel = (isOpen: boolean) => (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/repos/1?dialog=terminal&terminal=t2']}>
<TerminalPanel repoId={1} directory="/repo" isOpen={isOpen} onClose={vi.fn()} />
<TerminalPanel target={{ kind: 'repo', repoId: 1 }} directory="/repo" isOpen={isOpen} onClose={vi.fn()} />
</MemoryRouter>
</QueryClientProvider>
)
@@ -10,6 +10,7 @@ import { useOpenPreview } from '@/hooks/useOpenPreview'
import { useUrlParams } from '@/hooks/useUrlParams'
import { openUrlFromManager } from '@/lib/open-url'
import { cn } from '@/lib/utils'
import type { TerminalTarget } from '@/lib/terminal-target'
import { TerminalKeyBar } from './TerminalKeyBar'
import type { TerminalViewHandle } from './TerminalView'
@@ -18,28 +19,28 @@ const TerminalView = lazy(() =>
)
interface TerminalPanelProps {
repoId: number
target: TerminalTarget
directory: string | undefined
isOpen: boolean
onClose: () => void
}
interface TerminalWorkspaceProps {
repoId: number
target: TerminalTarget
directory: string | undefined
isOpen: boolean
}
export function TerminalWorkspace({ repoId, directory, isOpen }: TerminalWorkspaceProps) {
export function TerminalWorkspace({ target, directory, isOpen }: TerminalWorkspaceProps) {
const isMobile = useMobile()
const { searchParams, updateParams } = useUrlParams()
const openPreview = useOpenPreview()
const { data, isLoading, isSuccess, isFetching, refetch, error } = useTerminals(repoId, directory, {
const { data, isLoading, isSuccess, isFetching, refetch, error } = useTerminals(target, directory, {
enabled: isOpen && !!directory,
refetchInterval: isOpen ? 5000 : false,
})
const { mutate: createTerminal, isPending: isCreating } = useCreateTerminal(repoId)
const { mutate: removeTerminal, isPending: isRemoving } = useRemoveTerminal(repoId)
const { mutate: createTerminal, isPending: isCreating } = useCreateTerminal(target)
const { mutate: removeTerminal, isPending: isRemoving } = useRemoveTerminal(target)
const [ctrlArmed, setCtrlArmed] = useState(false)
const [pendingClose, setPendingClose] = useState<TerminalInfo | null>(null)
@@ -182,7 +183,7 @@ export function TerminalWorkspace({ repoId, directory, isOpen }: TerminalWorkspa
if (handle) viewHandlesRef.current.set(terminal.id, handle)
else viewHandlesRef.current.delete(terminal.id)
}}
repoId={repoId}
target={target}
directory={directory}
ptyID={terminal.id}
active={terminal.id === activeTerminalId}
@@ -218,7 +219,7 @@ export function TerminalWorkspace({ repoId, directory, isOpen }: TerminalWorkspa
)
}
export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPanelProps) {
export function TerminalPanel({ target, directory, isOpen, onClose }: TerminalPanelProps) {
const isMobile = useMobile()
return (
@@ -250,7 +251,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa
)}
</DialogHeader>
<TerminalWorkspace repoId={repoId} directory={directory} isOpen={isOpen} />
<TerminalWorkspace target={target} directory={directory} isOpen={isOpen} />
</DialogContent>
</Dialog>
)
@@ -59,7 +59,7 @@ function renderView(overrides: Partial<ComponentProps<typeof TerminalView>> = {}
const element = (
<TerminalView
ref={ref}
repoId={1}
target={{ kind: 'repo', repoId: 1 }}
directory="/repo"
ptyID="t1"
active
@@ -106,7 +106,7 @@ describe('TerminalView input handling', () => {
const ref = createRef<TerminalViewHandle>()
const onCtrlConsumed = vi.fn()
const props: ComponentProps<typeof TerminalView> = {
repoId: 1,
target: { kind: 'repo', repoId: 1 },
directory: '/repo',
ptyID: 't1',
active: true,
@@ -6,6 +6,7 @@ import '@xterm/xterm/css/xterm.css'
import { resizeTerminal } from '@/api/terminals'
import { applyCtrlModifier } from '@/lib/terminal-protocol'
import { resolveTerminalTheme } from '@/lib/terminal-theme'
import { terminalTargetKey, type TerminalTarget } from '@/lib/terminal-target'
import { useTerminalSocket } from '@/hooks/useTerminalSocket'
import { useMobile } from '@/hooks/useMobile'
import { cn } from '@/lib/utils'
@@ -19,7 +20,7 @@ export interface TerminalViewHandle {
}
interface TerminalViewProps {
repoId: number
target: TerminalTarget
directory: string | undefined
ptyID: string
active: boolean
@@ -30,7 +31,7 @@ interface TerminalViewProps {
}
export const TerminalView = forwardRef<TerminalViewHandle, TerminalViewProps>(function TerminalView({
repoId,
target,
directory,
ptyID,
active,
@@ -50,8 +51,12 @@ export const TerminalView = forwardRef<TerminalViewHandle, TerminalViewProps>(fu
const isMobile = useMobile()
const isMobileRef = useRef(isMobile)
const activeRef = useRef(active)
const targetRef = useRef(target)
const targetKey = terminalTargetKey(target)
const lastSizeRef = useRef<{ cols: number; rows: number } | null>(null)
targetRef.current = target
ctrlArmedRef.current = ctrlArmed
onCtrlConsumedRef.current = onCtrlConsumed
onOpenLinkRef.current = onOpenLink
@@ -78,7 +83,7 @@ export const TerminalView = forwardRef<TerminalViewHandle, TerminalViewProps>(fu
}, [])
const { send } = useTerminalSocket({
repoId,
target,
directory,
ptyID,
onOutput: handleOutput,
@@ -170,7 +175,7 @@ export const TerminalView = forwardRef<TerminalViewHandle, TerminalViewProps>(fu
const lastSize = lastSizeRef.current
if (lastSize && lastSize.cols === size.cols && lastSize.rows === size.rows) return
lastSizeRef.current = size
resizeTerminal(repoId, ptyID, { directory, cols: size.cols, rows: size.rows }).catch(() => {})
resizeTerminal(targetRef.current, ptyID, { directory, cols: size.cols, rows: size.rows }).catch(() => {})
}, RESIZE_DEBOUNCE_MS)
}
@@ -182,7 +187,7 @@ export const TerminalView = forwardRef<TerminalViewHandle, TerminalViewProps>(fu
observer.disconnect()
if (timer) clearTimeout(timer)
}
}, [repoId, directory, ptyID])
}, [targetKey, directory, ptyID])
useEffect(() => {
if (!active) return