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

+14 -3
View File
@@ -1,10 +1,21 @@
import { fetchWrapper } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { FuseMultiRunRequest, LaunchMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas'
import type {
FuseMultiRunRequest,
LaunchMultiRunRequest,
MultiRun,
MultiRunTarget,
} from '@opencode-manager/shared/schemas'
export async function listMultiRuns(repoId: number): Promise<MultiRun[]> {
function targetParams(target: MultiRunTarget): Record<string, string | number> {
return target.kind === 'repo'
? { repoId: target.repoId }
: { serverId: target.serverId, directory: target.directory }
}
export async function listMultiRuns(target: MultiRunTarget): Promise<MultiRun[]> {
const res = await fetchWrapper<{ runs: MultiRun[] }>(`${API_BASE_URL}/api/multi-runs`, {
params: { repoId },
params: targetParams(target),
})
return res.runs
}
+62
View File
@@ -24,6 +24,7 @@ export interface ScheduleJobWithRepo extends ScheduleJob {
repoName: string
repoPath: string
repoUrl: string
serverName: string | null
lastRun: ScheduleRunSummary | null
retainedWorktreeCount: number
}
@@ -32,6 +33,12 @@ export interface ScheduleRunWithContext extends ScheduleRun {
jobName: string
repoName: string
repoPath: string
serverName: string | null
}
export interface ScheduleServerTarget {
serverId: string
directory: string
}
export interface UnreadScheduleRun extends ScheduleRunWithContext {
@@ -100,6 +107,9 @@ export async function getScheduleCounts(): Promise<Map<number, ScheduleCount>> {
const counts = new Map<number, ScheduleCount>()
jobs.forEach((job) => {
if (job.repoId === null) {
return
}
const existing = counts.get(job.repoId)
if (existing) {
existing.total += 1
@@ -185,3 +195,55 @@ export async function deleteRepoScheduleRun(repoId: number, jobId: number, runId
method: 'DELETE',
})
}
function serverSchedulesPath(serverId: string): string {
return `${API_BASE_URL}/api/opencode-servers/${encodeURIComponent(serverId)}/schedules`
}
export async function getServerSchedule(serverId: string, jobId: number): Promise<{ job: ScheduleJob }> {
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}`)
}
export async function createServerSchedule(serverId: string, data: CreateScheduleJobRequest): Promise<{ job: ScheduleJob }> {
return fetchWrapper(serverSchedulesPath(serverId), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function updateServerSchedule(serverId: string, jobId: number, data: UpdateScheduleJobRequest): Promise<{ job: ScheduleJob }> {
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
}
export async function deleteServerSchedule(serverId: string, jobId: number): Promise<void> {
return fetchWrapperVoid(`${serverSchedulesPath(serverId)}/${jobId}`, { method: 'DELETE' })
}
export async function runServerSchedule(serverId: string, jobId: number): Promise<{ run: ScheduleRun }> {
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/run`, { method: 'POST' })
}
export async function listServerScheduleRuns(serverId: string, jobId: number, limit: number = 20): Promise<{ runs: ScheduleRun[] }> {
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs?limit=${limit}`)
}
export async function getServerScheduleRun(serverId: string, jobId: number, runId: number): Promise<{ run: ScheduleRun }> {
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs/${runId}`)
}
export async function cancelServerScheduleRun(serverId: string, jobId: number, runId: number): Promise<{ run: ScheduleRun }> {
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs/${runId}/cancel`, { method: 'POST' })
}
export async function clearServerScheduleRuns(serverId: string, jobId: number): Promise<{ cleared: number }> {
return fetchWrapper(`${serverSchedulesPath(serverId)}/${jobId}/runs`, { method: 'DELETE' })
}
export async function deleteServerScheduleRun(serverId: string, jobId: number, runId: number): Promise<void> {
return fetchWrapperVoid(`${serverSchedulesPath(serverId)}/${jobId}/runs/${runId}`, { method: 'DELETE' })
}
+10 -3
View File
@@ -1,10 +1,17 @@
import { fetchWrapper } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { SessionGoal, StartSessionGoalRequest } from '@opencode-manager/shared/schemas'
import {
LOCAL_OPENCODE_SERVER_ID,
type SessionGoal,
type StartSessionGoalRequest,
} from '@opencode-manager/shared/schemas'
export async function getLatestSessionGoal(sessionId: string): Promise<SessionGoal | null> {
export async function getLatestSessionGoal(
sessionId: string,
serverId: string = LOCAL_OPENCODE_SERVER_ID,
): Promise<SessionGoal | null> {
const res = await fetchWrapper<{ goal: SessionGoal | null }>(`${API_BASE_URL}/api/session-goals`, {
params: { sessionId },
params: { sessionId, serverId },
})
return res.goal
}
@@ -20,11 +20,23 @@ describe('sessionPermissionModes', () => {
const result = await getSessionPermissionMode('ses_1')
expect(result).toEqual(state)
expect(fetchMock.mock.calls[0][0]).toEqual(expect.stringContaining('/api/session-permission-modes/ses_1'))
const url = new URL(String(fetchMock.mock.calls[0][0]))
expect(url.pathname).toBe('/api/session-permission-modes/ses_1')
expect(url.searchParams.get('serverId')).toBe('local')
expect(fetchMock.mock.calls[0][1].method).toBeUndefined()
})
it('calls PUT /api/session-permission-modes/:id with the mode and directory', async () => {
it('sends the remote server id when reading a remote session mode', async () => {
const state = { sessionId: 'ses_1', rootSessionId: 'ses_1', mode: 'auto', lockedReason: null }
fetchMock.mockResolvedValue(new Response(JSON.stringify(state), { status: 200 }))
await getSessionPermissionMode('ses_1', 'srv_remote')
const url = new URL(String(fetchMock.mock.calls[0][0]))
expect(url.searchParams.get('serverId')).toBe('srv_remote')
})
it('calls PUT /api/session-permission-modes/:id with the mode, directory and server', async () => {
const input = { directory: '/repo', mode: 'auto' as const }
const state = { sessionId: 'ses_1', rootSessionId: 'ses_1', mode: 'auto' as const, lockedReason: null }
fetchMock.mockResolvedValue(new Response(JSON.stringify(state), { status: 200 }))
@@ -36,6 +48,16 @@ describe('sessionPermissionModes', () => {
const options = fetchMock.mock.calls[0][1]
expect(options.method).toBe('PUT')
expect(options.headers['Content-Type']).toBe('application/json')
expect(JSON.parse(options.body)).toEqual(input)
expect(JSON.parse(options.body)).toEqual({ ...input, serverId: 'local' })
})
it('sends the remote server id when writing a remote session mode', async () => {
const input = { directory: '/repo', mode: 'auto' as const }
const state = { sessionId: 'ses_1', rootSessionId: 'ses_1', mode: 'auto' as const, lockedReason: null }
fetchMock.mockResolvedValue(new Response(JSON.stringify(state), { status: 200 }))
await setSessionPermissionMode('ses_1', input, 'srv_remote')
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ ...input, serverId: 'srv_remote' })
})
})
+12 -3
View File
@@ -1,23 +1,32 @@
import { fetchWrapper } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { SessionPermissionModeState, SetSessionPermissionModeRequest } from '@opencode-manager/shared/schemas'
import {
LOCAL_OPENCODE_SERVER_ID,
type SessionPermissionModeState,
type SetSessionPermissionModeRequest,
} from '@opencode-manager/shared/schemas'
export async function getSessionPermissionMode(sessionId: string): Promise<SessionPermissionModeState> {
export async function getSessionPermissionMode(
sessionId: string,
serverId: string = LOCAL_OPENCODE_SERVER_ID,
): Promise<SessionPermissionModeState> {
return fetchWrapper<SessionPermissionModeState>(
`${API_BASE_URL}/api/session-permission-modes/${encodeURIComponent(sessionId)}`,
{ params: { serverId } },
)
}
export async function setSessionPermissionMode(
sessionId: string,
input: SetSessionPermissionModeRequest,
serverId: string = LOCAL_OPENCODE_SERVER_ID,
): Promise<SessionPermissionModeState> {
return fetchWrapper<SessionPermissionModeState>(
`${API_BASE_URL}/api/session-permission-modes/${encodeURIComponent(sessionId)}`,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
body: JSON.stringify({ ...input, serverId }),
},
)
}
+122
View File
@@ -0,0 +1,122 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { resizeTerminal, useCreateTerminal, useRemoveTerminal, useTerminals } from './terminals'
const fetchMock = vi.fn()
function jsonResponse(body: unknown): Response {
return new Response(JSON.stringify(body), { status: 200 })
}
function createWrapper(queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })) {
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
function lastRequestUrl(): string {
return String(fetchMock.mock.calls.at(-1)?.[0])
}
describe('terminal api targets', () => {
beforeEach(() => {
fetchMock.mockReset()
vi.stubGlobal('fetch', fetchMock)
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('lists repo terminals through the repo route', async () => {
fetchMock.mockResolvedValue(jsonResponse({ terminals: [] }))
const { result } = renderHook(
() => useTerminals({ kind: 'repo', repoId: 1 }, '/repo', { enabled: true }),
{ wrapper: createWrapper() },
)
await waitFor(() => expect(result.current.isSuccess).toBe(true))
const url = new URL(lastRequestUrl())
expect(url.pathname).toBe('/api/repos/1/terminals')
expect(url.searchParams.get('directory')).toBe('/repo')
})
it('lists linked server terminals through the server route', async () => {
fetchMock.mockResolvedValue(jsonResponse({ terminals: [] }))
const { result } = renderHook(
() => useTerminals({ kind: 'server', serverId: 'srv_kitchen' }, '/home/me/app', { enabled: true }),
{ wrapper: createWrapper() },
)
await waitFor(() => expect(result.current.isSuccess).toBe(true))
const url = new URL(lastRequestUrl())
expect(url.pathname).toBe('/api/opencode-servers/srv_kitchen/terminals')
expect(url.searchParams.get('directory')).toBe('/home/me/app')
})
it('scopes the query key to the linked server', async () => {
fetchMock.mockResolvedValue(jsonResponse({ terminals: [] }))
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const { result } = renderHook(
() => useTerminals({ kind: 'server', serverId: 'srv_kitchen' }, '/home/me/app', { enabled: true }),
{ wrapper: createWrapper(queryClient) },
)
await waitFor(() => expect(result.current.isSuccess).toBe(true))
expect(
queryClient.getQueryCache().findAll({ queryKey: ['terminals', 'srv_kitchen'] }),
).toHaveLength(1)
})
it('creates a linked server terminal through the server route', async () => {
fetchMock.mockResolvedValue(
jsonResponse({ id: 'pty-1', title: 'Terminal', kind: 'shell', cwd: '/home/me/app', status: 'running' }),
)
const { result } = renderHook(
() => useCreateTerminal({ kind: 'server', serverId: 'srv_kitchen' }),
{ wrapper: createWrapper() },
)
await act(() => result.current.mutateAsync({ directory: '/home/me/app' }))
const url = new URL(lastRequestUrl())
expect(url.pathname).toBe('/api/opencode-servers/srv_kitchen/terminals')
expect(fetchMock.mock.calls.at(-1)?.[1]?.method).toBe('POST')
})
it('removes a linked server terminal with the directory', async () => {
fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
const { result } = renderHook(
() => useRemoveTerminal({ kind: 'server', serverId: 'srv_kitchen' }),
{ wrapper: createWrapper() },
)
await act(() => result.current.mutateAsync({ ptyID: 'pty 1', directory: '/home/me/app' }))
const url = new URL(lastRequestUrl())
expect(url.pathname).toBe('/api/opencode-servers/srv_kitchen/terminals/pty%201')
expect(url.searchParams.get('directory')).toBe('/home/me/app')
expect(fetchMock.mock.calls.at(-1)?.[1]?.method).toBe('DELETE')
})
it('resizes a linked server terminal', async () => {
fetchMock.mockResolvedValue(jsonResponse({ success: true }))
await resizeTerminal({ kind: 'server', serverId: 'srv_kitchen' }, 'pty-1', {
directory: '/home/me/app',
cols: 80,
rows: 24,
})
const url = new URL(lastRequestUrl())
expect(url.pathname).toBe('/api/opencode-servers/srv_kitchen/terminals/pty-1')
expect(fetchMock.mock.calls.at(-1)?.[1]?.method).toBe('PATCH')
})
})
+26 -21
View File
@@ -1,42 +1,47 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { CreateTerminalRequest, ResizeTerminalRequest, TerminalInfo } from '@opencode-manager/shared/types'
import { API_BASE_URL } from '@/config'
import { terminalCollectionPath, terminalItemPath, terminalTargetScope, type TerminalTarget } from '@/lib/terminal-target'
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
function terminalsQueryKey(repoId: number, directory: string | undefined) {
return ['terminals', repoId, directory ?? null] as const
function terminalsQueryKey(target: TerminalTarget, directory: string | undefined) {
return ['terminals', terminalTargetScope(target), directory ?? null] as const
}
function terminalsRepoQueryKey(repoId: number) {
return ['terminals', repoId] as const
function terminalsScopeQueryKey(target: TerminalTarget) {
return ['terminals', terminalTargetScope(target)] as const
}
async function listTerminals(repoId: number, directory?: string): Promise<TerminalInfo[]> {
async function listTerminals(target: TerminalTarget, directory?: string): Promise<TerminalInfo[]> {
const data = await fetchWrapper<{ terminals: TerminalInfo[] }>(
`${API_BASE_URL}/api/repos/${repoId}/terminals`,
`${API_BASE_URL}${terminalCollectionPath(target)}`,
{ params: { directory } },
)
return data.terminals
}
async function createTerminal(repoId: number, body: CreateTerminalRequest): Promise<TerminalInfo> {
return fetchWrapper<TerminalInfo>(`${API_BASE_URL}/api/repos/${repoId}/terminals`, {
async function createTerminal(target: TerminalTarget, body: CreateTerminalRequest): Promise<TerminalInfo> {
return fetchWrapper<TerminalInfo>(`${API_BASE_URL}${terminalCollectionPath(target)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
export async function resizeTerminal(repoId: number, ptyID: string, body: ResizeTerminalRequest): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}`, {
export async function resizeTerminal(
target: TerminalTarget,
ptyID: string,
body: ResizeTerminalRequest,
): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}${terminalItemPath(target, ptyID)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
async function removeTerminal(repoId: number, ptyID: string, directory?: string): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}`, {
async function removeTerminal(target: TerminalTarget, ptyID: string, directory?: string): Promise<void> {
return fetchWrapperVoid(`${API_BASE_URL}${terminalItemPath(target, ptyID)}`, {
method: 'DELETE',
params: { directory },
})
@@ -47,21 +52,21 @@ interface UseTerminalsOptions {
refetchInterval?: number | false
}
export function useTerminals(repoId: number, directory: string | undefined, options: UseTerminalsOptions) {
export function useTerminals(target: TerminalTarget, directory: string | undefined, options: UseTerminalsOptions) {
return useQuery({
queryKey: terminalsQueryKey(repoId, directory),
queryFn: () => listTerminals(repoId, directory),
queryKey: terminalsQueryKey(target, directory),
queryFn: () => listTerminals(target, directory),
enabled: options.enabled,
refetchInterval: options.refetchInterval,
})
}
export function useCreateTerminal(repoId: number) {
export function useCreateTerminal(target: TerminalTarget) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (body: CreateTerminalRequest) => createTerminal(repoId, body),
mutationFn: (body: CreateTerminalRequest) => createTerminal(target, body),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: terminalsRepoQueryKey(repoId) })
queryClient.invalidateQueries({ queryKey: terminalsScopeQueryKey(target) })
},
})
}
@@ -71,12 +76,12 @@ interface RemoveTerminalVariables {
directory?: string
}
export function useRemoveTerminal(repoId: number) {
export function useRemoveTerminal(target: TerminalTarget) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ ptyID, directory }: RemoveTerminalVariables) => removeTerminal(repoId, ptyID, directory),
mutationFn: ({ ptyID, directory }: RemoveTerminalVariables) => removeTerminal(target, ptyID, directory),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: terminalsRepoQueryKey(repoId) })
queryClient.invalidateQueries({ queryKey: terminalsScopeQueryKey(target) })
},
})
}
@@ -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
+21 -18
View File
@@ -7,15 +7,18 @@ import type {
LaunchMultiRunRequest,
MultiRun,
MultiRunFusion,
MultiRunTarget,
} from '@opencode-manager/shared/schemas'
function multiRunQueryKey(repoId: number) {
return ['multi-runs', repoId] as const
function multiRunQueryKey(target: MultiRunTarget | undefined) {
return ['multi-runs', target] as const
}
function invalidateMultiRunCaches(queryClient: QueryClient, repoId: number) {
queryClient.invalidateQueries({ queryKey: multiRunQueryKey(repoId) })
queryClient.invalidateQueries({ queryKey: repoSiblingsQueryKey(repoId) })
function invalidateMultiRunCaches(queryClient: QueryClient, target: MultiRunTarget) {
queryClient.invalidateQueries({ queryKey: multiRunQueryKey(target) })
if (target.kind === 'repo') {
queryClient.invalidateQueries({ queryKey: repoSiblingsQueryKey(target.repoId) })
}
}
function buildStartingFusion(run: MultiRun, request: FuseMultiRunRequest): MultiRunFusion {
@@ -45,22 +48,22 @@ function countEntries(run: MultiRun, status: MultiRun['entries'][number]['status
return run.entries.filter((entry) => entry.status === status).length
}
export function useMultiRuns(repoId: number | undefined, enabled: boolean) {
export function useMultiRuns(target: MultiRunTarget | undefined, enabled: boolean) {
return useQuery({
queryKey: multiRunQueryKey(repoId ?? 0),
queryFn: () => listMultiRuns(repoId!),
enabled: enabled && !!repoId && repoId > 0,
queryKey: multiRunQueryKey(target),
queryFn: () => listMultiRuns(target!),
enabled: enabled && target !== undefined,
staleTime: 10_000,
})
}
export function useLaunchMultiRun(repoId: number) {
export function useLaunchMultiRun(target: MultiRunTarget) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (request: LaunchMultiRunRequest) => launchMultiRun(request),
onSuccess: (run) => {
invalidateMultiRunCaches(queryClient, repoId)
invalidateMultiRunCaches(queryClient, target)
const started = countEntries(run, 'started')
const failed = countEntries(run, 'failed')
if (failed === 0) {
@@ -77,14 +80,14 @@ export function useLaunchMultiRun(repoId: number) {
})
}
export function useFuseMultiRun(repoId: number) {
export function useFuseMultiRun(target: MultiRunTarget) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ runId, request }: { runId: number; request: FuseMultiRunRequest }) =>
fuseMultiRun(runId, request),
onMutate: async ({ runId, request }) => {
const queryKey = multiRunQueryKey(repoId)
const queryKey = multiRunQueryKey(target)
await queryClient.cancelQueries({ queryKey })
queryClient.setQueryData<MultiRun[]>(queryKey, (runs) =>
runs?.map((run) =>
@@ -95,10 +98,10 @@ export function useFuseMultiRun(repoId: number) {
)
},
onSuccess: (run, variables) => {
queryClient.setQueryData<MultiRun[]>(multiRunQueryKey(repoId), (runs) =>
queryClient.setQueryData<MultiRun[]>(multiRunQueryKey(target), (runs) =>
runs?.map((candidate) => (candidate.id === run.id ? run : candidate)),
)
invalidateMultiRunCaches(queryClient, repoId)
invalidateMultiRunCaches(queryClient, target)
const fusion = run.fusions.find((candidate) => candidate.requestId === variables.request.requestId)
if (fusion?.status === 'started') {
showToast.success('Fusion started')
@@ -107,19 +110,19 @@ export function useFuseMultiRun(repoId: number) {
}
},
onError: () => {
invalidateMultiRunCaches(queryClient, repoId)
invalidateMultiRunCaches(queryClient, target)
},
})
}
export function useDiscardMultiRunEntry(repoId: number) {
export function useDiscardMultiRunEntry(target: MultiRunTarget) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ runId, entryId }: { runId: number; entryId: number }) =>
discardMultiRunEntry(runId, entryId),
onSuccess: () => {
invalidateMultiRunCaches(queryClient, repoId)
invalidateMultiRunCaches(queryClient, target)
showToast.success('Run discarded')
},
onError: (error: unknown) => {
+3 -2
View File
@@ -608,8 +608,9 @@ export const useSendShell = (directory?: string) => {
});
};
export const useAgents = (directory?: string, options?: { enabled?: boolean }) => {
const serverId = useOpenCodeServerId();
export const useAgents = (directory?: string, options?: { enabled?: boolean; serverId?: string }) => {
const defaultServerId = useOpenCodeServerId()
const serverId = options?.serverId ?? defaultServerId;
return useQuery({
queryKey: serverScopedKey(["opencode", "agents", directory], serverId),
queryFn: () => listAgents(directory, serverId),
+3 -1
View File
@@ -5,10 +5,12 @@ import { serverScopedKey } from '@/lib/serverScope'
interface UseProvidersOptions {
enabled?: boolean
serverId?: string
}
export function useProviders(directory?: string, options: UseProvidersOptions = {}) {
const serverId = useOpenCodeServerId()
const defaultServerId = useOpenCodeServerId()
const serverId = options.serverId ?? defaultServerId
return useQuery({
queryKey: serverScopedKey(['opencode', 'providers', directory], serverId),
+5 -5
View File
@@ -208,7 +208,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
setError(null)
syncCurrentSession()
invalidateShellCaches(queryClient)
eventStreamSubscriptionRef.current?.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
eventStreamSubscriptionRef.current?.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current, serverId)
} else {
setError('Connection lost. Reconnecting...')
}
@@ -234,7 +234,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
}
const handleVisibilityChange = () => {
subscription.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current)
subscription.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current, serverId)
}
document.addEventListener('visibilitychange', handleVisibilityChange)
@@ -246,7 +246,7 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
document.removeEventListener('visibilitychange', handleVisibilityChange)
window.removeEventListener('focus', handleReconnect)
window.removeEventListener('online', handleReconnect)
subscription.reportVisibility(false, undefined)
subscription.reportVisibility(false, undefined, serverId)
subscription.dispose()
if (eventStreamSubscriptionRef.current === subscription) {
eventStreamSubscriptionRef.current = null
@@ -256,9 +256,9 @@ export const useSSE = (directory?: string | string[], currentSessionId?: string)
useEffect(() => {
if (isConnected && document.visibilityState === 'visible') {
eventStreamSubscriptionRef.current?.reportVisibility(true, currentSessionId)
eventStreamSubscriptionRef.current?.reportVisibility(true, currentSessionId, serverId)
}
}, [currentSessionId, isConnected])
}, [currentSessionId, isConnected, serverId])
return { isConnected, error, isReconnecting }
}
+2 -2
View File
@@ -1,8 +1,8 @@
import { useProviders } from '@/hooks/useProviders'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
export function useScheduleModels(enabled: boolean, directory?: string) {
const providersQuery = useProviders(directory, { enabled })
export function useScheduleModels(enabled: boolean, directory?: string, serverId?: string) {
const providersQuery = useProviders(directory, { enabled, serverId })
const availableModels: ModelInfo[] | null =
providersQuery.isSuccess && !providersQuery.isPlaceholderData
? providersQuery.data?.models ?? []
+262
View File
@@ -2,28 +2,51 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { CreateScheduleJobRequest, ScheduleRunWorktreesMode, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
import {
cancelRepoScheduleRun,
cancelServerScheduleRun,
clearRepoScheduleRuns,
clearServerScheduleRuns,
createRepoSchedule,
createServerSchedule,
deleteRepoSchedule,
deleteRepoScheduleRun,
deleteServerSchedule,
deleteServerScheduleRun,
getRepoSchedule,
getRepoScheduleRun,
getServerSchedule,
getServerScheduleRun,
listAllScheduleRuns,
listAllSchedules,
listRepoScheduleRuns,
listServerScheduleRuns,
listScheduleWorktrees,
listUnreadScheduleRuns,
markAllScheduleRunsViewed,
markScheduleRunViewed,
removeScheduleWorktrees,
runRepoSchedule,
runServerSchedule,
updateRepoSchedule,
updateServerSchedule,
} from '@/api/schedules'
import { showToast } from '@/lib/toast'
import type { ListAllRunsParams, ScheduleJobWithRepo, ScheduleRunWithContext } from '@/api/schedules'
export const UNREAD_SCHEDULE_RUNS_QUERY_KEY = ['schedule-runs-unread'] as const
export type ScheduleTargetRef =
| { kind: 'repo'; repoId: number }
| { kind: 'server'; serverId: string }
function invalidateScheduleQueries(queryClient: ReturnType<typeof useQueryClient>): void {
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule'] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs'] })
queryClient.invalidateQueries({ queryKey: ['server-schedule'] })
queryClient.invalidateQueries({ queryKey: ['server-schedule-runs'] })
}
export function useAllSchedules() {
return useQuery({
queryKey: ['all-schedules'],
@@ -289,3 +312,242 @@ export function useRemoveScheduleWorktrees() {
},
})
}
export function useServerSchedule(serverId: string | undefined, jobId: number | null) {
return useQuery({
queryKey: ['server-schedule', serverId, jobId],
queryFn: async () => (await getServerSchedule(serverId!, jobId!)).job,
enabled: Boolean(serverId) && jobId !== null,
refetchInterval: jobId !== null ? 5000 : false,
})
}
export function useServerScheduleRuns(serverId: string | undefined, jobId: number | null, limit: number = 20) {
return useQuery({
queryKey: ['server-schedule-runs', serverId, jobId, limit],
queryFn: async () => (await listServerScheduleRuns(serverId!, jobId!, limit)).runs,
enabled: Boolean(serverId) && jobId !== null,
refetchInterval: jobId !== null ? 5000 : false,
})
}
export function useServerScheduleRun(serverId: string | undefined, jobId: number | null, runId: number | null) {
return useQuery({
queryKey: ['server-schedule-run', serverId, jobId, runId],
queryFn: async () => (await getServerScheduleRun(serverId!, jobId!, runId!)).run,
enabled: Boolean(serverId) && jobId !== null && runId !== null,
refetchInterval: runId !== null ? 5000 : false,
})
}
export function useScheduleRunDetail(run: { repoId: number | null; serverId?: string; jobId: number; id: number } | null) {
const serverId = run && run.repoId === null ? run.serverId : undefined
return useQuery({
queryKey: ['schedule-run-detail', run?.repoId ?? null, serverId ?? null, run?.jobId ?? null, run?.id ?? null],
queryFn: async () => {
if (!run) return null
if (run.repoId === null) {
if (!run.serverId) return null
return (await getServerScheduleRun(run.serverId, run.jobId, run.id)).run
}
return (await getRepoScheduleRun(run.repoId, run.jobId, run.id)).run
},
enabled: run !== null && (run.repoId !== null || Boolean(run.serverId)),
refetchInterval: run !== null ? 5000 : false,
})
}
export function useCreateServerSchedule(serverId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (data: CreateScheduleJobRequest) => (await createServerSchedule(serverId, data)).job,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
showToast.success('Schedule created')
},
onError: (error: unknown) => {
showToast.error(`Failed to create schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useUpdateServerSchedule(serverId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ jobId, data }: { jobId: number; data: UpdateScheduleJobRequest }) =>
(await updateServerSchedule(serverId, jobId, data)).job,
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({ queryKey: ['server-schedule', serverId, variables.jobId] })
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
showToast.success('Schedule updated')
},
onError: (error: unknown) => {
showToast.error(`Failed to update schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useDeleteServerSchedule(serverId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (jobId: number) => deleteServerSchedule(serverId, jobId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
showToast.success('Schedule deleted')
},
onError: (error: unknown) => {
showToast.error(`Failed to delete schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useRunServerSchedule(serverId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (jobId: number) => (await runServerSchedule(serverId, jobId)).run,
onSuccess: (run) => {
queryClient.invalidateQueries({ queryKey: ['server-schedule-runs', serverId, run.jobId] })
queryClient.invalidateQueries({ queryKey: ['server-schedule', serverId, run.jobId] })
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
showToast.success(run.status === 'running' ? 'Schedule started' : 'Schedule run completed')
},
onError: (error: unknown) => {
showToast.error(`Failed to run schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useCancelServerScheduleRun(serverId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ jobId, runId }: { jobId: number; runId: number }) =>
(await cancelServerScheduleRun(serverId, jobId, runId)).run,
onSuccess: (run) => {
queryClient.invalidateQueries({ queryKey: ['server-schedule-runs', serverId, run.jobId] })
queryClient.invalidateQueries({ queryKey: ['server-schedule-run', serverId, run.jobId, run.id] })
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
showToast.success('Schedule run cancelled')
},
onError: (error: unknown) => {
showToast.error(`Failed to cancel schedule run: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useClearServerScheduleRuns(serverId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (jobId: number) => clearServerScheduleRuns(serverId, jobId),
onSuccess: (result, jobId) => {
queryClient.invalidateQueries({ queryKey: ['server-schedule-runs', serverId, jobId] })
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
showToast.success(result.cleared > 0 ? `Cleared ${result.cleared} run${result.cleared === 1 ? '' : 's'}` : 'No runs to clear')
},
onError: (error: unknown) => {
showToast.error(`Failed to clear run history: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useDeleteServerScheduleRun(serverId: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({ jobId, runId }: { jobId: number; runId: number }) => deleteServerScheduleRun(serverId, jobId, runId),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({ queryKey: ['server-schedule-runs', serverId, variables.jobId] })
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
showToast.success('Run deleted')
},
onError: (error: unknown) => {
showToast.error(`Failed to delete run: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useUpdateScheduleTarget() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ target, jobId, data }: { target: ScheduleTargetRef; jobId: number; data: UpdateScheduleJobRequest }) => {
const response = target.kind === 'repo'
? await updateRepoSchedule(target.repoId, jobId, data)
: await updateServerSchedule(target.serverId, jobId, data)
return response.job
},
onSuccess: () => {
invalidateScheduleQueries(queryClient)
showToast.success('Schedule updated')
},
onError: (error: unknown) => {
showToast.error(`Failed to update schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useDeleteScheduleTarget() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ target, jobId }: { target: ScheduleTargetRef; jobId: number }) => {
if (target.kind === 'repo') {
await deleteRepoSchedule(target.repoId, jobId)
return
}
await deleteServerSchedule(target.serverId, jobId)
},
onSuccess: () => {
invalidateScheduleQueries(queryClient)
showToast.success('Schedule deleted')
},
onError: (error: unknown) => {
showToast.error(`Failed to delete schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useRunScheduleTarget() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ target, jobId }: { target: ScheduleTargetRef; jobId: number }) => {
const response = target.kind === 'repo'
? await runRepoSchedule(target.repoId, jobId)
: await runServerSchedule(target.serverId, jobId)
return response.run
},
onSuccess: (run) => {
invalidateScheduleQueries(queryClient)
showToast.success(run.status === 'running' ? 'Schedule started' : 'Schedule run completed')
},
onError: (error: unknown) => {
showToast.error(`Failed to run schedule: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
export function useCancelScheduleTargetRun() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ target, jobId, runId }: { target: ScheduleTargetRef; jobId: number; runId: number }) => {
const response = target.kind === 'repo'
? await cancelRepoScheduleRun(target.repoId, jobId, runId)
: await cancelServerScheduleRun(target.serverId, jobId, runId)
return response.run
},
onSuccess: () => {
invalidateScheduleQueries(queryClient)
showToast.success('Schedule run cancelled')
},
onError: (error) => {
showToast.error(`Failed to cancel schedule run: ${error instanceof Error ? error.message : String(error)}`)
},
})
}
+16 -2
View File
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useSessionGoal } from './useSessionGoals'
import { getLatestSessionGoal } from '@/api/sessionGoals'
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
import type { SessionGoal, SessionGoalStatus } from '@opencode-manager/shared/schemas'
vi.mock('@/api/sessionGoals', () => ({
@@ -21,6 +22,7 @@ vi.mock('@/lib/toast', () => ({
const baseGoal: SessionGoal = {
id: 1,
sessionId: 'ses_1',
serverId: 'local',
directory: '/repo',
objective: 'Ship the feature',
status: 'active',
@@ -38,9 +40,11 @@ const baseGoal: SessionGoal = {
finishedAt: null,
}
function createWrapper(queryClient: QueryClient) {
function createWrapper(queryClient: QueryClient, serverId?: string) {
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
<QueryClientProvider client={queryClient}>
{serverId ? <OpenCodeServerProvider serverId={serverId}>{children}</OpenCodeServerProvider> : children}
</QueryClientProvider>
)
}
@@ -69,4 +73,14 @@ describe('useSessionGoal', () => {
expect(refetchInterval!({ state: { data: { status: 'stopped' } } })).toBe(false)
expect(refetchInterval!({ state: {} })).toBe(false)
})
it('reads the goal for the current server and scopes its cache key', async () => {
vi.mocked(getLatestSessionGoal).mockResolvedValue({ ...baseGoal, serverId: 'srv_remote' })
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
renderHook(() => useSessionGoal('ses_1'), { wrapper: createWrapper(queryClient, 'srv_remote') })
await waitFor(() => expect(getLatestSessionGoal).toHaveBeenCalledWith('ses_1', 'srv_remote'))
expect(queryClient.getQueryCache().find({ queryKey: ['session-goal', 'ses_1', 'srv_remote'] })).toBeDefined()
})
})
+13 -6
View File
@@ -6,17 +6,20 @@ import {
resumeSessionGoal,
startSessionGoal,
} from '@/api/sessionGoals'
import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
import { serverScopedKey } from '@/lib/serverScope'
import { showToast } from '@/lib/toast'
import { SESSION_GOAL_POLL_INTERVAL_MS, type SessionGoal, type StartSessionGoalRequest } from '@opencode-manager/shared/schemas'
function sessionGoalQueryKey(sessionId: string) {
return ['session-goal', sessionId] as const
function sessionGoalQueryKey(sessionId: string, serverId: string) {
return serverScopedKey(['session-goal', sessionId], serverId)
}
export function useSessionGoal(sessionId: string, options: { enabled?: boolean } = {}) {
const serverId = useOpenCodeServerId()
return useQuery({
queryKey: sessionGoalQueryKey(sessionId),
queryFn: () => getLatestSessionGoal(sessionId),
queryKey: sessionGoalQueryKey(sessionId, serverId),
queryFn: () => getLatestSessionGoal(sessionId, serverId),
enabled: options.enabled ?? true,
refetchInterval: (query) => (query.state.data?.status === 'active' ? SESSION_GOAL_POLL_INTERVAL_MS : false),
})
@@ -30,7 +33,7 @@ function useGoalMutation<TInput>(
return useMutation({
mutationFn,
onSuccess: (goal: SessionGoal) => {
queryClient.setQueryData(sessionGoalQueryKey(goal.sessionId), goal)
queryClient.setQueryData(sessionGoalQueryKey(goal.sessionId, goal.serverId), goal)
},
onError: (error: unknown) => {
showToast.error(error instanceof Error ? error.message : errorMessage)
@@ -39,7 +42,11 @@ function useGoalMutation<TInput>(
}
export function useStartSessionGoal() {
return useGoalMutation((input: StartSessionGoalRequest) => startSessionGoal(input), 'Failed to start goal')
const serverId = useOpenCodeServerId()
return useGoalMutation(
(input: StartSessionGoalRequest) => startSessionGoal({ ...input, serverId }),
'Failed to start goal',
)
}
export function usePauseSessionGoal() {
@@ -0,0 +1,63 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { useSessionPermissionMode, useSetSessionPermissionMode } from './useSessionPermissionMode'
import { getSessionPermissionMode, setSessionPermissionMode } from '@/api/sessionPermissionModes'
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
vi.mock('@/api/sessionPermissionModes', () => ({
getSessionPermissionMode: vi.fn(),
setSessionPermissionMode: vi.fn(),
}))
vi.mock('@/lib/toast', () => ({
showToast: { error: vi.fn() },
}))
function createWrapper(queryClient: QueryClient, serverId: string) {
return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>
<OpenCodeServerProvider serverId={serverId}>{children}</OpenCodeServerProvider>
</QueryClientProvider>
)
}
describe('useSessionPermissionMode', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('reads the mode for the current server and scopes its cache key', async () => {
const state = { sessionId: 'ses_1', rootSessionId: 'ses_1', mode: 'auto' as const, lockedReason: null }
vi.mocked(getSessionPermissionMode).mockResolvedValue(state)
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
renderHook(() => useSessionPermissionMode('ses_1'), { wrapper: createWrapper(queryClient, 'srv_remote') })
await waitFor(() => expect(getSessionPermissionMode).toHaveBeenCalledWith('ses_1', 'srv_remote'))
expect(queryClient.getQueryCache().find({ queryKey: ['session-permission-mode', 'ses_1', 'srv_remote'] })).toBeDefined()
})
it('writes the mode through the current server', async () => {
const state = { sessionId: 'ses_1', rootSessionId: 'ses_1', mode: 'auto' as const, lockedReason: null }
vi.mocked(setSessionPermissionMode).mockResolvedValue(state)
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const { result } = renderHook(() => useSetSessionPermissionMode('ses_1'), {
wrapper: createWrapper(queryClient, 'srv_remote'),
})
await act(async () => {
await result.current.mutateAsync({ directory: '/repo', mode: 'auto' })
})
expect(setSessionPermissionMode).toHaveBeenCalledWith(
'ses_1',
{ directory: '/repo', mode: 'auto' },
'srv_remote',
)
expect(
queryClient.getQueryData(['session-permission-mode', 'ses_1', 'srv_remote']),
).toEqual(state)
})
})
+11 -6
View File
@@ -1,16 +1,19 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getSessionPermissionMode, setSessionPermissionMode } from '@/api/sessionPermissionModes'
import { useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
import { serverScopedKey } from '@/lib/serverScope'
import { showToast } from '@/lib/toast'
import type { SessionPermissionModeState, SetSessionPermissionModeRequest } from '@opencode-manager/shared/schemas'
function sessionPermissionModeQueryKey(sessionId: string) {
return ['session-permission-mode', sessionId] as const
function sessionPermissionModeQueryKey(sessionId: string, serverId: string) {
return serverScopedKey(['session-permission-mode', sessionId], serverId)
}
export function useSessionPermissionMode(sessionId: string, options: { enabled?: boolean } = {}) {
const serverId = useOpenCodeServerId()
return useQuery({
queryKey: sessionPermissionModeQueryKey(sessionId),
queryFn: () => getSessionPermissionMode(sessionId),
queryKey: sessionPermissionModeQueryKey(sessionId, serverId),
queryFn: () => getSessionPermissionMode(sessionId, serverId),
enabled: options.enabled ?? true,
staleTime: 30000,
})
@@ -18,10 +21,12 @@ export function useSessionPermissionMode(sessionId: string, options: { enabled?:
export function useSetSessionPermissionMode(sessionId: string) {
const queryClient = useQueryClient()
const serverId = useOpenCodeServerId()
return useMutation({
mutationFn: (input: SetSessionPermissionModeRequest) => setSessionPermissionMode(sessionId, input),
mutationFn: (input: SetSessionPermissionModeRequest) =>
setSessionPermissionMode(sessionId, input, serverId),
onSuccess: (state: SessionPermissionModeState) => {
queryClient.setQueryData(sessionPermissionModeQueryKey(sessionId), state)
queryClient.setQueryData(sessionPermissionModeQueryKey(sessionId, serverId), state)
},
onError: () => {
showToast.error('Failed to update permission mode')
@@ -57,7 +57,7 @@ function metaFrame(cursor: number): ArrayBuffer {
function renderSocket(overrides: Partial<Parameters<typeof useTerminalSocket>[0]> = {}) {
return renderHook(() =>
useTerminalSocket({
repoId: 1,
target: { kind: 'repo', repoId: 1 },
directory: '/work/repo',
ptyID: 'pty-1',
onOutput: vi.fn(),
@@ -87,6 +87,13 @@ describe('useTerminalSocket', () => {
expect(url.searchParams.get('directory')).toBe('/work/repo')
})
it('builds the connection url for a linked server target', () => {
renderSocket({ target: { kind: 'server', serverId: 'srv_kitchen' } })
const url = new URL(FakeWebSocket.instances[0].url)
expect(url.pathname).toBe('/api/opencode-servers/srv_kitchen/terminals/pty-1/connect')
expect(url.searchParams.get('directory')).toBe('/work/repo')
})
it('accumulates the cursor and sends it when reconnecting after 1006', () => {
renderSocket()
const first = FakeWebSocket.instances[0]
+9 -9
View File
@@ -1,11 +1,12 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { terminalConnectPath, type TerminalTarget } from '@/lib/terminal-target'
import { TerminalFrameDecoder } from '@/lib/terminal-protocol'
import { toWebSocketUrl } from '@/lib/websocket-url'
export type TerminalSocketStatus = 'connecting' | 'open' | 'reconnecting' | 'closed'
export interface UseTerminalSocketOptions {
repoId: number
target: TerminalTarget
directory: string | undefined
ptyID: string
onOutput: (text: string) => void
@@ -17,8 +18,7 @@ const RECONNECT_DELAYS_MS = [1000, 2000, 5000, 5000, 5000]
const TERMINAL_CLOSE_CODES = new Set([1000, 4404])
function buildSocketUrl(
repoId: number,
ptyID: string,
connectPath: string,
directory: string | undefined,
cursor: number | undefined,
): string {
@@ -26,13 +26,11 @@ function buildSocketUrl(
if (directory !== undefined) params.set('directory', directory)
if (cursor !== undefined) params.set('cursor', String(cursor))
const query = params.toString()
return toWebSocketUrl(
`/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}/connect${query ? `?${query}` : ''}`,
)
return toWebSocketUrl(`${connectPath}${query ? `?${query}` : ''}`)
}
export function useTerminalSocket({
repoId,
target,
directory,
ptyID,
onOutput,
@@ -46,6 +44,8 @@ export function useTerminalSocket({
onOutputRef.current = onOutput
onExitRef.current = onExit
const connectPath = terminalConnectPath(target, ptyID)
const [status, setStatus] = useState<TerminalSocketStatus>(enabled ? 'connecting' : 'closed')
const send = useCallback((data: string) => {
@@ -71,7 +71,7 @@ export function useTerminalSocket({
if (disposed) return
setStatus(attempt === 0 ? 'connecting' : 'reconnecting')
const socket = new WebSocket(buildSocketUrl(repoId, ptyID, directory, cursorRef.current))
const socket = new WebSocket(buildSocketUrl(connectPath, directory, cursorRef.current))
socket.binaryType = 'arraybuffer'
socketRef.current = socket
@@ -129,7 +129,7 @@ export function useTerminalSocket({
socket.close()
}
}
}, [repoId, directory, ptyID, enabled])
}, [connectPath, directory, enabled])
return { send, status }
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { ASSISTANT_REPO_ID, buildSessionPath } from '@opencode-manager/shared/utils';
import { ASSISTANT_REPO_ID, buildServerSessionPath, buildSessionPath } from '@opencode-manager/shared/utils';
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas';
export function getAssistantPath(): string {
@@ -33,7 +33,7 @@ export function getServerPath(serverId: string): string {
}
export function getServerSessionPath(serverId: string, sessionId: string): string {
return `${getServerPath(serverId)}/sessions/${encodeURIComponent(sessionId)}`;
return buildServerSessionPath(serverId, sessionId);
}
export function parseServerSessionRoute(pathname: string): { serverId: string; sessionId: string } | null {
@@ -236,7 +236,23 @@ describe('OpenCodeEventStream', () => {
expect(transport.posts).toContainEqual({
path: '/api/sse/visibility',
body: { clientId: 'client-1', visible: true, activeSessionId: 'session-1' },
body: { clientId: 'client-1', visible: true, activeSessionId: 'session-1', activeServerId: 'local' },
})
})
it('reports the active server id for a remote server route', async () => {
const transport = new TestEventStreamTransport()
const stream = new OpenCodeEventStream({ transport })
const subscription = stream.subscribeGlobalMonitor({ directories: ['srv_a|/repo'], onEvent: vi.fn() })
transport.openConnection()
transport.connected('client-1')
subscription.reportVisibility(true, 'session-1', 'srv_a')
await Promise.resolve()
expect(transport.posts).toContainEqual({
path: '/api/sse/visibility',
body: { clientId: 'client-1', visible: true, activeSessionId: 'session-1', activeServerId: 'srv_a' },
})
})
@@ -1,4 +1,5 @@
import { DEFAULTS } from '@opencode-manager/shared/config'
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { createBrowserEventStreamTransport } from './browserTransport'
import type {
EventStreamHealthState,
@@ -75,7 +76,8 @@ export class OpenCodeEventStream {
return {
updateDirectories: (directories) => this.updateSubscriberDirectories(id, directories),
reconnect: () => this.reconnect(),
reportVisibility: (visible, activeSessionId) => this.reportVisibility(visible, activeSessionId),
reportVisibility: (visible, activeSessionId, activeServerId) =>
this.reportVisibility(visible, activeSessionId, activeServerId),
dispose: () => this.removeSubscriber(id),
}
}
@@ -477,13 +479,14 @@ export class OpenCodeEventStream {
void this.subscribeToRemoteDirectories(directories)
}
private reportVisibility(visible: boolean, activeSessionId?: string): void {
private reportVisibility(visible: boolean, activeSessionId?: string, activeServerId?: string): void {
if (!this.clientId || !this.connected) return
void this.transport.post('/api/sse/visibility', {
clientId: this.clientId,
visible,
activeSessionId: activeSessionId ?? null,
activeServerId: activeServerId ?? LOCAL_OPENCODE_SERVER_ID,
})
}
}
@@ -29,7 +29,7 @@ export interface EventStreamTransport {
export interface EventStreamSubscription {
dispose(): void
reconnect(): void
reportVisibility(visible: boolean, activeSessionId?: string): void
reportVisibility(visible: boolean, activeSessionId?: string, activeServerId?: string): void
}
export interface GlobalMonitorSubscription extends EventStreamSubscription {
+25
View File
@@ -0,0 +1,25 @@
export type TerminalTarget =
| { kind: 'repo'; repoId: number }
| { kind: 'server'; serverId: string }
export function terminalTargetScope(target: TerminalTarget): number | string {
return target.kind === 'repo' ? target.repoId : target.serverId
}
export function terminalTargetKey(target: TerminalTarget): string {
return target.kind === 'repo' ? `repo:${target.repoId}` : `server:${target.serverId}`
}
export function terminalCollectionPath(target: TerminalTarget): string {
return target.kind === 'repo'
? `/api/repos/${target.repoId}/terminals`
: `/api/opencode-servers/${encodeURIComponent(target.serverId)}/terminals`
}
export function terminalItemPath(target: TerminalTarget, ptyID: string): string {
return `${terminalCollectionPath(target)}/${encodeURIComponent(ptyID)}`
}
export function terminalConnectPath(target: TerminalTarget, ptyID: string): string {
return `${terminalItemPath(target, ptyID)}/connect`
}
+1 -1
View File
@@ -103,7 +103,7 @@ export function AssistantRedirect() {
/>
)}
<SourceControlPanel repoId={repoId} isOpen={!docked && sourceControlOpen} onClose={() => setSourceControlOpen(false)} currentBranch={repo?.currentBranch || repo?.branch || "main"} repoName="Assistant" />
<TerminalPanel repoId={0} directory={assistantDirectory} isOpen={!docked && terminalOpen} onClose={() => setTerminalOpen(false)} />
<TerminalPanel target={{ kind: 'repo', repoId: 0 }} directory={assistantDirectory} isOpen={!docked && terminalOpen} onClose={() => setTerminalOpen(false)} />
<PreviewPanel isOpen={!docked && previewOpen} onClose={() => setPreviewOpen(false)} directory={assistantDirectory} />
<ResetPermissionsDialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen} repoId={repoId} />
</>
+74 -31
View File
@@ -1,7 +1,16 @@
import { useState, useMemo, useEffect, useRef, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAllSchedules, useAllScheduleRuns, useCancelRepoScheduleRun, useUnreadScheduleRuns } from '@/hooks/useSchedules'
import { useDeleteRepoSchedule, useRunRepoSchedule, useUpdateRepoSchedule, useCreateRepoSchedule } from '@/hooks/useSchedules'
import {
useAllSchedules,
useAllScheduleRuns,
useCancelScheduleTargetRun,
useCreateRepoSchedule,
useDeleteScheduleTarget,
useRunScheduleTarget,
useUnreadScheduleRuns,
useUpdateScheduleTarget,
type ScheduleTargetRef,
} from '@/hooks/useSchedules'
import { ScheduleJobDialog, PromptsTab, ScheduleJobsTable, ScheduleListToolbar, ScheduleRunDrawer, ScheduleRunsTable, ScheduleRepoSwitcher } from '@/components/schedules'
import type { CreateScheduleJobRequest } from '@opencode-manager/shared/types'
import { DELETE_SCHEDULE_DESCRIPTION, matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
@@ -20,12 +29,26 @@ import { useDebouncedValue } from '@/hooks/useDebouncedValue'
import type { ScheduleJobWithRepo, ScheduleRunWithContext } from '@/api/schedules'
import { Combobox } from '@/components/ui/combobox'
import { getRepoPath } from '@/lib/navigation'
import { getRepoPath, getServerPath } from '@/lib/navigation'
type StatusFilter = 'all' | 'enabled' | 'disabled'
type ScheduleModeFilter = 'all' | 'cron' | 'interval'
type SortOption = 'nextRun' | 'name' | 'repo'
function jobBucket(job: ScheduleJobWithRepo): string {
return job.repoId === null ? `server:${job.serverId ?? ''}:${job.repoPath}` : job.repoPath
}
function targetForJob(job: ScheduleJobWithRepo): ScheduleTargetRef | null {
if (job.repoId !== null) return { kind: 'repo', repoId: job.repoId }
return job.serverId ? { kind: 'server', serverId: job.serverId } : null
}
function targetForRun(run: ScheduleRunWithContext): ScheduleTargetRef | null {
if (run.repoId !== null) return { kind: 'repo', repoId: run.repoId }
return run.serverId ? { kind: 'server', serverId: run.serverId } : null
}
export function GlobalSchedules() {
const navigate = useNavigate()
const [selectedRepoId, setSelectedRepoId] = useState<number | undefined>(undefined)
@@ -46,7 +69,7 @@ export function GlobalSchedules() {
const { scheduleTab, setScheduleTab, dialog, promptDialog, jobId, runId, templateId, openNewJob, openEditJob, openDeleteJob, openNewTemplate, openEditTemplate, openDeleteTemplate, openImportTemplate, closeDialog, closePromptDialog, selectRun } = useScheduleUrlState()
const cancelRunMutation = useCancelRepoScheduleRun()
const cancelRunMutation = useCancelScheduleTargetRun()
const cancelRunPending = cancelRunMutation.isPending
useEffect(() => {
@@ -100,9 +123,9 @@ export function GlobalSchedules() {
}, [nextUnreadRun, selectRun])
const createMutation = useCreateRepoSchedule()
const deleteMutation = useDeleteRepoSchedule()
const runMutation = useRunRepoSchedule()
const updateMutation = useUpdateRepoSchedule()
const deleteMutation = useDeleteScheduleTarget()
const runMutation = useRunScheduleTarget()
const updateMutation = useUpdateScheduleTarget()
useEffect(() => {
setRunOffset(0)
@@ -152,14 +175,15 @@ export function GlobalSchedules() {
}, [runsForDisplay, runSortOption])
const uniqueRepos = useMemo(() => {
const repoMap = new Map<string, { name: string; url: string }>()
const repoMap = new Map<string, { name: string; url: string; repoId: number | null }>()
jobs.forEach((job) => {
repoMap.set(job.repoPath, { name: job.repoName, url: job.repoUrl })
repoMap.set(jobBucket(job), { name: job.repoName, url: job.repoUrl, repoId: job.repoId })
})
return Array.from(repoMap.entries()).map(([path, info]) => ({
path,
return Array.from(repoMap.entries()).map(([bucket, info]) => ({
path: bucket,
name: info.name,
url: info.url,
repoId: info.repoId,
}))
}, [jobs])
@@ -179,7 +203,7 @@ export function GlobalSchedules() {
}
if (repoFilter !== 'all') {
filtered = filtered.filter((job) => job.repoPath === repoFilter)
filtered = filtered.filter((job) => jobBucket(job) === repoFilter)
}
filtered = filtered.filter((job) => matchesScheduleJobSearch(job, searchQuery))
@@ -207,7 +231,7 @@ export function GlobalSchedules() {
...uniqueRepos.map((repo) => ({
value: repo.path,
label: repo.name,
description: `${jobs.filter((j) => j.repoPath === repo.path).length} jobs`,
description: `${jobs.filter((j) => jobBucket(j) === repo.path).length} jobs`,
})),
], [jobs, uniqueRepos])
@@ -251,38 +275,43 @@ export function GlobalSchedules() {
const runRepoOptions = useMemo(() => [
{ value: 'all', label: 'All Repos', description: '' },
...uniqueRepos.map((repo) => ({
value: `${jobs.find((j) => j.repoPath === repo.path)?.repoId ?? 0}|${repo.path}`,
...uniqueRepos.filter((repo) => repo.repoId !== null).map((repo) => ({
value: `${repo.repoId}|${repo.path}`,
label: repo.name,
description: repo.path,
})),
], [uniqueRepos, jobs])
], [uniqueRepos])
const handleDelete = () => {
if (!deletingJob) {
const target = deletingJob ? targetForJob(deletingJob) : null
if (!deletingJob || !target) {
return
}
deleteMutation.mutate(
{ repoId: deletingJob.repoId, jobId: deletingJob.id },
{ target, jobId: deletingJob.id },
{ onSuccess: () => closeDialog() }
)
}
const handleCancelRun = (repoId: number, jobId: number, runId: number) => {
cancelRunMutation.mutate({ repoId, jobId, runId })
const handleCancelRun = (target: ScheduleTargetRef, jobId: number, runId: number) => {
cancelRunMutation.mutate({ target, jobId, runId })
}
const handleToggleEnabled = (job: ScheduleJobWithRepo) => {
const target = targetForJob(job)
if (!target) return
updateMutation.mutate({
repoId: job.repoId,
target,
jobId: job.id,
data: { enabled: !job.enabled },
})
}
const handleRunNow = (job: ScheduleJobWithRepo) => {
runMutation.mutate({ repoId: job.repoId, jobId: job.id })
const target = targetForJob(job)
if (!target) return
runMutation.mutate({ target, jobId: job.id })
}
const handleEdit = (job: ScheduleJobWithRepo) => {
@@ -303,10 +332,11 @@ export function GlobalSchedules() {
}
const handleUpdate = (data: CreateScheduleJobRequest) => {
if (!editingJob) return
const target = editingJob ? targetForJob(editingJob) : null
if (!editingJob || !target) return
updateMutation.mutate(
{
repoId: editingJob.repoId,
target,
jobId: editingJob.id,
data: toUpdateScheduleRequest(data),
},
@@ -319,12 +349,20 @@ export function GlobalSchedules() {
}
const handleNavigateToRepo = (repoPath: string) => {
const repoId = jobs.find((j) => j.repoPath === repoPath)?.repoId
if (repoId === undefined) return
navigate(getRepoPath(repoId))
const job = jobs.find((entry) => jobBucket(entry) === repoPath)
if (!job) return
if (job.repoId === null) {
if (job.serverId) navigate(getServerPath(job.serverId))
return
}
navigate(getRepoPath(job.repoId))
}
const handleOpenJobPage = (job: ScheduleJobWithRepo) => {
if (job.repoId === null) {
if (job.serverId) navigate(getServerPath(job.serverId))
return
}
navigate(`/repos/${job.repoId}/schedules`)
}
@@ -338,13 +376,15 @@ export function GlobalSchedules() {
}
const handleCancelJobRun = (job: ScheduleJobWithRepo) => {
if (!job.lastRun) return
handleCancelRun(job.repoId, job.id, job.lastRun.id)
const target = targetForJob(job)
if (!job.lastRun || !target) return
handleCancelRun(target, job.id, job.lastRun.id)
}
const handleCancelSelectedRun = () => {
if (!selectedRun) return
handleCancelRun(selectedRun.repoId, selectedRun.jobId, selectedRun.id)
const target = selectedRun ? targetForRun(selectedRun) : null
if (!selectedRun || !target) return
handleCancelRun(target, selectedRun.jobId, selectedRun.id)
}
const selectedRunIndex = runId !== null ? sortedRuns.findIndex((run) => run.id === runId) : -1
@@ -761,6 +801,9 @@ export function GlobalSchedules() {
showRepoSelector
repoId={selectedRepoId}
onRepoChange={setSelectedRepoId}
serverTarget={editingJob && editingJob.repoId === null && editingJob.serverId && editingJob.directory
? { serverId: editingJob.serverId, directory: editingJob.directory }
: undefined}
/>
<DeleteDialog
+4
View File
@@ -26,6 +26,8 @@ import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { RemoteSchedulesButton } from '@/components/schedules/RemoteSchedulesButton'
import { RemoteMultiRunButton } from '@/components/repo/RemoteMultiRunButton'
function ConnectionStatus({ status, isLoading }: { status?: OpenCodeServerStatus; isLoading: boolean }) {
if (isLoading) {
@@ -149,6 +151,8 @@ function ProjectRow({ project, serverId }: { project: OpenCodeProject; serverId:
{createSession.isPending ? <Loader2 className="mr-1 h-4 w-4 animate-spin" /> : <Plus className="mr-1 h-4 w-4" />}
New session
</Button>
<RemoteSchedulesButton serverId={serverId} directory={project.canonical} />
<RemoteMultiRunButton serverId={serverId} directory={project.canonical} />
</div>
{expanded ? <ProjectSessions serverId={serverId} directory={project.canonical} /> : null}
</Card>
+5 -3
View File
@@ -37,6 +37,7 @@ import { PendingActionsGroup } from "@/components/notifications/PendingActionsGr
import { getRepoDisplayName } from "@/lib/utils";
import { notifyWorktreeSetup } from "@/lib/worktreeSetup";
import { getRepoDirectoryNameError, isWorktreeSibling } from "@opencode-manager/shared/utils";
import type { MultiRunTarget } from "@opencode-manager/shared/schemas";
export function RepoDetail() {
const { id } = useParams<{ id: string }>();
@@ -117,7 +118,8 @@ export function RepoDetail() {
}, [baseDirectory, nonScheduleWorkspaceDirectories, activeScheduleDirectories]);
const showWorktrees = activeTab === 'workspaces';
const { data: multiRuns } = useMultiRuns(repoId, showWorktrees);
const multiRunTarget = useMemo<MultiRunTarget>(() => ({ kind: 'repo', repoId }), [repoId]);
const { data: multiRuns } = useMultiRuns(repoId > 0 ? multiRunTarget : undefined, showWorktrees);
const sessionListDirectories = useMemo(() => {
if (!showWorktrees) return baseDirectory ? [baseDirectory] : [];
return Array.from(new Set([...nonScheduleWorkspaceDirectories, ...activeScheduleDirectories]));
@@ -342,7 +344,7 @@ export function RepoDetail() {
/>
<TerminalPanel
repoId={repoId}
target={{ kind: 'repo', repoId }}
directory={terminalDirectory ?? baseDirectory}
isOpen={!docked && terminalOpen}
onClose={() => setTerminalOpen(false)}
@@ -361,7 +363,7 @@ export function RepoDetail() {
/>
<MultiRunSheet
repoId={repoId}
target={multiRunTarget}
directory={baseDirectory}
defaultBaseRef={currentBranch}
open={multiRunOpen}
+12 -11
View File
@@ -81,6 +81,7 @@ const OLDER_HISTORY_SCROLL_THRESHOLD_PX = 200
const PENDING_ACTION_SYNC_INTERVAL_MS = 30000
const PROMPT_OVERLAY_CLEARANCE_PX = 16
const REMOTE_SESSION_PANEL_TOOLS = ['terminal'] as const
function applyRevertBoundary(
messages: SessionMessageInfo[],
@@ -892,7 +893,7 @@ export function SessionDetail() {
/>
)}
<SessionSendErrorBanner sessionId={sessionId} isConnected={isConnected} isReconnecting={isReconnecting} />
{!isRemoteServer && <SessionGoalBar sessionID={sessionId} />}
<SessionGoalBar sessionID={sessionId} />
<BackgroundWorkBar
sessionID={sessionId}
directory={sessionDirectory}
@@ -915,16 +916,18 @@ export function SessionDetail() {
</div>
)}
</div>
{docked && !isRemoteServer && (
{docked && (
<ToolSidePanel
panel={sidePanel}
repoId={repoId}
repoId={isRemoteServer ? undefined : repoId}
sessionId={sessionId}
directory={sessionDirectory}
filesBasePath={workspaceBasePath}
currentBranch={repo?.currentBranch || repo?.branch || "main"}
selectedFilePath={selectedFilePath}
repoDirectory={repoDirectory}
terminalTarget={isRemoteServer ? { kind: 'server', serverId } : { kind: 'repo', repoId }}
allowedPanelTools={isRemoteServer ? REMOTE_SESSION_PANEL_TOOLS : undefined}
onSkillLoaded={handleSkillLoaded}
walkthroughSourceRequest={walkthroughSourceRequest}
walkthroughModel={modelRef}
@@ -1045,14 +1048,12 @@ export function SessionDetail() {
/>
)}
{!isRemoteServer && (
<TerminalPanel
repoId={repoId}
directory={sessionDirectory}
isOpen={!docked && terminalOpen}
onClose={() => setTerminalOpen(false)}
/>
)}
<TerminalPanel
target={isRemoteServer ? { kind: 'server', serverId } : { kind: 'repo', repoId }}
directory={sessionDirectory}
isOpen={!docked && terminalOpen}
onClose={() => setTerminalOpen(false)}
/>
{!isRemoteServer && (
<PreviewPanel
@@ -8,10 +8,10 @@ const mocks = vi.hoisted(() => ({
useAllSchedules: vi.fn(),
useAllScheduleRuns: vi.fn(),
useCreateRepoSchedule: vi.fn(),
useUpdateRepoSchedule: vi.fn(),
useDeleteRepoSchedule: vi.fn(),
useRunRepoSchedule: vi.fn(),
useCancelRepoScheduleRun: vi.fn(),
useUpdateScheduleTarget: vi.fn(),
useDeleteScheduleTarget: vi.fn(),
useRunScheduleTarget: vi.fn(),
useCancelScheduleTargetRun: vi.fn(),
useUnreadScheduleRuns: vi.fn(),
useScheduleUrlState: vi.fn(),
ScheduleJobsTable: vi.fn(() => null),
@@ -23,10 +23,10 @@ vi.mock('@/hooks/useSchedules', () => ({
useAllSchedules: mocks.useAllSchedules,
useAllScheduleRuns: mocks.useAllScheduleRuns,
useCreateRepoSchedule: mocks.useCreateRepoSchedule,
useUpdateRepoSchedule: mocks.useUpdateRepoSchedule,
useDeleteRepoSchedule: mocks.useDeleteRepoSchedule,
useRunRepoSchedule: mocks.useRunRepoSchedule,
useCancelRepoScheduleRun: mocks.useCancelRepoScheduleRun,
useUpdateScheduleTarget: mocks.useUpdateScheduleTarget,
useDeleteScheduleTarget: mocks.useDeleteScheduleTarget,
useRunScheduleTarget: mocks.useRunScheduleTarget,
useCancelScheduleTargetRun: mocks.useCancelScheduleTargetRun,
useUnreadScheduleRuns: mocks.useUnreadScheduleRuns,
}))
@@ -182,10 +182,10 @@ describe('GlobalSchedules run history', () => {
)
mocks.useAllSchedules.mockReturnValue({ data: [], isLoading: false, error: null })
mocks.useCreateRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useUpdateRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useDeleteRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useRunRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useCancelRepoScheduleRun.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useUpdateScheduleTarget.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useDeleteScheduleTarget.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useRunScheduleTarget.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useCancelScheduleTargetRun.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useUnreadScheduleRuns.mockReturnValue({ data: { runs: [], total: 0, failed: 0 } })
mocks.useScheduleUrlState.mockReturnValue(createMockScheduleUrlState())
})
@@ -274,7 +274,6 @@ describe('SessionDetail remote server mode', () => {
})
expect(mocks.SourceControlPanel).not.toHaveBeenCalled()
expect(mocks.TerminalPanel).not.toHaveBeenCalled()
expect(mocks.PreviewPanel).not.toHaveBeenCalled()
expect(mocks.FileBrowserSheet).not.toHaveBeenCalled()
expect(mocks.ProjectActionsMenu).not.toHaveBeenCalled()
@@ -283,8 +282,6 @@ describe('SessionDetail remote server mode', () => {
expect(mocks.RepoSkillsDialog).not.toHaveBeenCalled()
expect(mocks.RepoMcpDialog).not.toHaveBeenCalled()
expect(mocks.ChangesWalkthroughSheet).not.toHaveBeenCalled()
expect(mocks.ToolSidePanel).not.toHaveBeenCalled()
expect(mocks.SessionGoalBar).not.toHaveBeenCalled()
expect(mocks.SessionPickerDialog).not.toHaveBeenCalled()
expect(mocks.SessionMoreButton).not.toHaveBeenCalled()
expect(vi.mocked(PendingActionsGroup).mock.calls.at(-1)?.[0]).toEqual(
@@ -292,6 +289,43 @@ describe('SessionDetail remote server mode', () => {
)
})
it('shows the session goal bar for a remote session', async () => {
renderRemoteSession()
await waitFor(() => {
expect(screen.getByTestId('message-thread')).toBeInTheDocument()
})
expect(mocks.SessionGoalBar).toHaveBeenCalled()
expect(mocks.SessionGoalBar.mock.calls.at(-1)?.[0]).toEqual(
expect.objectContaining({ sessionID: 'ses_remote' }),
)
})
it('exposes terminals for the linked server', async () => {
renderRemoteSession()
await waitFor(() => {
expect(screen.getByTestId('message-thread')).toBeInTheDocument()
})
expect(mocks.TerminalPanel.mock.calls.at(-1)?.[0]).toEqual(
expect.objectContaining({
target: { kind: 'server', serverId: 'srv_kitchen' },
directory: '/home/me/app',
isOpen: false,
}),
)
expect(mocks.ToolSidePanel.mock.calls.at(-1)?.[0]).toEqual(
expect.objectContaining({
repoId: undefined,
terminalTarget: { kind: 'server', serverId: 'srv_kitchen' },
allowedPanelTools: ['terminal'],
directory: '/home/me/app',
}),
)
})
it('navigates child sessions within the linked server route', async () => {
const { capturedPathname } = renderRemoteSession()