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) })
},
})
}