fix(servers): address CodeRabbit review on linked-server automation

Scope session permission modes and schedule locks by server, keep remote schedule cleanup working when a server is disabled or removed, harden the session server-scope migration and rollback, reject local server multi-run targets, widen schedule query invalidation, and update CLI fixtures for server-scoped schemas.
This commit is contained in:
Chris Scott committed 2026-10-18 21:01:53 -04:00
1 parent 780d31087b
commit 9ec2ed5903
13 files changed
+426 -49

No files matched your search

@@ -3,6 +3,13 @@ import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import type { Migration } from '../migration-runner'
const SERVER_ID_COLUMN = 'server_id'
const PERMISSION_MODES_TABLE = 'session_permission_modes'
const PERMISSION_MODES_REBUILD_TABLE = 'session_permission_modes_rebuild'
interface ColumnInfo {
name: string
pk: number
}
function tableExists(db: Database, table: string): boolean {
return Boolean(
@@ -10,9 +17,19 @@ function tableExists(db: Database, table: string): boolean {
)
}
function tableColumns(db: Database, table: string): ColumnInfo[] {
return db.prepare(`PRAGMA table_info(${table})`).all() as ColumnInfo[]
}
function hasColumn(db: Database, table: string, column: string): boolean {
const columns = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>
return columns.some((entry) => entry.name === column)
return tableColumns(db, table).some((entry) => entry.name === column)
}
function primaryKeyColumns(db: Database, table: string): string[] {
return tableColumns(db, table)
.filter((column) => column.pk > 0)
.sort((left, right) => left.pk - right.pk)
.map((column) => column.name)
}
function addServerIdColumn(db: Database, table: string): void {
@@ -29,22 +46,88 @@ function dropServerIdColumn(db: Database, table: string): void {
db.run(`ALTER TABLE ${table} DROP COLUMN ${SERVER_ID_COLUMN}`)
}
function deleteRemoteRows(db: Database, table: string): void {
if (!tableExists(db, table) || !hasColumn(db, table, SERVER_ID_COLUMN)) {
return
}
db.run(`DELETE FROM ${table} WHERE ${SERVER_ID_COLUMN} <> '${LOCAL_OPENCODE_SERVER_ID}'`)
}
function rebuildPermissionModesForServers(db: Database): void {
if (!tableExists(db, PERMISSION_MODES_TABLE) || !hasColumn(db, PERMISSION_MODES_TABLE, SERVER_ID_COLUMN)) {
return
}
const primaryKey = primaryKeyColumns(db, PERMISSION_MODES_TABLE)
if (primaryKey.length === 2 && primaryKey[0] === SERVER_ID_COLUMN && primaryKey[1] === 'session_id') {
return
}
db.run(`DROP TABLE IF EXISTS ${PERMISSION_MODES_REBUILD_TABLE}`)
db.run(`
CREATE TABLE ${PERMISSION_MODES_REBUILD_TABLE} (
session_id TEXT NOT NULL,
server_id TEXT NOT NULL DEFAULT '${LOCAL_OPENCODE_SERVER_ID}',
mode TEXT NOT NULL CHECK(mode IN ('ask','auto')),
updated_at INTEGER NOT NULL,
PRIMARY KEY (server_id, session_id)
)
`)
db.run(`
INSERT INTO ${PERMISSION_MODES_REBUILD_TABLE}(session_id, server_id, mode, updated_at)
SELECT session_id, ${SERVER_ID_COLUMN}, mode, updated_at FROM ${PERMISSION_MODES_TABLE}
`)
db.run(`DROP TABLE ${PERMISSION_MODES_TABLE}`)
db.run(`ALTER TABLE ${PERMISSION_MODES_REBUILD_TABLE} RENAME TO ${PERMISSION_MODES_TABLE}`)
}
function rebuildPermissionModesForLocalSessions(db: Database): void {
if (!tableExists(db, PERMISSION_MODES_TABLE) || !hasColumn(db, PERMISSION_MODES_TABLE, SERVER_ID_COLUMN)) {
return
}
const primaryKey = primaryKeyColumns(db, PERMISSION_MODES_TABLE)
if (primaryKey.length === 1 && primaryKey[0] === 'session_id') {
return
}
db.run(`DROP TABLE IF EXISTS ${PERMISSION_MODES_REBUILD_TABLE}`)
db.run(`
CREATE TABLE ${PERMISSION_MODES_REBUILD_TABLE} (
session_id TEXT PRIMARY KEY,
mode TEXT NOT NULL CHECK(mode IN ('ask','auto')),
updated_at INTEGER NOT NULL
)
`)
db.run(`
INSERT INTO ${PERMISSION_MODES_REBUILD_TABLE}(session_id, mode, updated_at)
SELECT session_id, mode, updated_at FROM ${PERMISSION_MODES_TABLE}
WHERE ${SERVER_ID_COLUMN} = '${LOCAL_OPENCODE_SERVER_ID}'
`)
db.run(`DROP TABLE ${PERMISSION_MODES_TABLE}`)
db.run(`ALTER TABLE ${PERMISSION_MODES_REBUILD_TABLE} RENAME TO ${PERMISSION_MODES_TABLE}`)
}
const migration: Migration = {
id: '202610181300-session-server-scope',
up(db) {
addServerIdColumn(db, 'session_permission_modes')
addServerIdColumn(db, PERMISSION_MODES_TABLE)
addServerIdColumn(db, 'session_goals')
rebuildPermissionModesForServers(db)
db.run('DROP INDEX IF EXISTS idx_session_goals_open')
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
ON session_goals(server_id, session_id)
WHERE status IN ('active','paused')
`)
if (tableExists(db, 'session_goals')) {
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
ON session_goals(server_id, session_id)
WHERE status IN ('active','paused')
`)
}
},
down(db) {
deleteRemoteRows(db, 'session_goals')
deleteRemoteRows(db, PERMISSION_MODES_TABLE)
db.run('DROP INDEX IF EXISTS idx_session_goals_open')
if (tableExists(db, 'session_goals')) {
db.run(`
@@ -53,8 +136,8 @@ const migration: Migration = {
WHERE status IN ('active','paused')
`)
}
rebuildPermissionModesForLocalSessions(db)
dropServerIdColumn(db, 'session_goals')
dropServerIdColumn(db, 'session_permission_modes')
},
}
+7 -3
View File
@@ -536,9 +536,13 @@ export function getScheduleRunById(db: Database, repoId: number | null, jobId: n
return row ? rowToScheduleRun(row) : null
}
export function getScheduleRunBySessionId(db: Database, sessionId: string): ScheduleRun | null {
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE session_id = ? ORDER BY started_at DESC LIMIT 1')
const row = stmt.get(sessionId) as ScheduleRunRow | undefined
export function getScheduleRunBySessionId(
db: Database,
sessionId: string,
serverId: string = LOCAL_OPENCODE_SERVER_ID,
): ScheduleRun | null {
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE server_id = ? AND session_id = ? ORDER BY started_at DESC LIMIT 1')
const row = stmt.get(serverId, sessionId) as ScheduleRunRow | undefined
return row ? rowToScheduleRun(row) : null
}
+4 -4
View File
@@ -4,10 +4,11 @@ import { LOCAL_OPENCODE_SERVER_ID, type SessionPermissionMode } from '@opencode-
export function ensureSessionPermissionModesTable(db: Database): void {
db.run(`
CREATE TABLE IF NOT EXISTS session_permission_modes (
session_id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
server_id TEXT NOT NULL DEFAULT 'local',
mode TEXT NOT NULL CHECK(mode IN ('ask','auto')),
updated_at INTEGER NOT NULL
updated_at INTEGER NOT NULL,
PRIMARY KEY (server_id, session_id)
)
`)
}
@@ -32,8 +33,7 @@ export function setSessionPermissionMode(
db.prepare(`
INSERT INTO session_permission_modes(server_id, session_id, mode, updated_at)
VALUES(?,?,?,?)
ON CONFLICT(session_id) DO UPDATE SET
server_id=excluded.server_id,
ON CONFLICT(server_id, session_id) DO UPDATE SET
mode=excluded.mode,
updated_at=excluded.updated_at
`).run(serverId, sessionId, mode, Date.now())
+3
View File
@@ -88,6 +88,9 @@ function multiRunTargetFromRequest(
request: Pick<LaunchMultiRunRequest, 'repoId' | 'serverId' | 'directory'>,
): MultiRunTarget {
if (request.serverId !== undefined) {
if (request.serverId === LOCAL_OPENCODE_SERVER_ID) {
throw new MultiRunError('Local multi-runs must target a repository', 400)
}
if (request.directory === undefined) {
throw new MultiRunError('A server multi-run needs a directory', 400)
}
+20 -14
View File
@@ -415,6 +415,13 @@ export class ScheduleService {
}
}
private resolveTargetPersistence(target: ScheduleJobTarget): { repo: Repo | null; repoId: number | null } {
if (target.kind === 'repo') {
return { repo: this.assertRepo(target.repoId), repoId: target.repoId }
}
return { repo: null, repoId: null }
}
private targetForJob(job: ScheduleJob): ScheduleJobTarget {
if (job.repoId !== null) {
return { kind: 'repo', repoId: job.repoId }
@@ -570,7 +577,6 @@ export class ScheduleService {
}
listServerJobs(serverId: string): ScheduleJob[] {
this.assertServer(serverId)
return listScheduleJobsByServer(this.db, serverId)
}
@@ -672,13 +678,13 @@ export class ScheduleService {
private async deleteJobForTarget(target: ScheduleJobTarget, jobId: number): Promise<void> {
const job = this.loadJobForTarget(target, jobId)
const context = this.resolveTargetContext(target, job.directory)
const { repoId } = this.resolveTargetPersistence(target)
if (ScheduleService.activeRuns.has(jobId)) {
throw new ScheduleServiceError('Cannot delete a schedule while it is running. Cancel the run first.', 409)
}
const runningRun = getRunningScheduleRunByJob(this.db, context.repoId, jobId)
const runningRun = getRunningScheduleRunByJob(this.db, repoId, jobId)
if (runningRun) {
throw new ScheduleServiceError('Cannot delete a schedule while it is running. Cancel the run first.', 409)
}
@@ -691,7 +697,7 @@ export class ScheduleService {
await this.removeWorktrees(target.repoId, jobId)
}
const deleted = deleteScheduleJob(this.db, context.repoId, jobId)
const deleted = deleteScheduleJob(this.db, repoId, jobId)
if (!deleted) {
throw new ScheduleServiceError('Schedule not found', 404)
}
@@ -781,17 +787,17 @@ export class ScheduleService {
private async clearRunHistoryForTarget(target: ScheduleJobTarget, jobId: number, worktrees: ScheduleRunWorktreesMode = 'commit'): Promise<{ cleared: number }> {
const job = this.loadJobForTarget(target, jobId)
const context = this.resolveTargetContext(target, job.directory)
const { repo, repoId } = this.resolveTargetPersistence(target)
const removable = listScheduleRunArtifactsByJob(this.db, context.repoId, jobId).filter((run) => run.status !== 'running')
const removable = listScheduleRunArtifactsByJob(this.db, repoId, jobId).filter((run) => run.status !== 'running')
if (removable.length === 0) {
return { cleared: 0 }
}
if (context.repo) {
await this.worktreeManager.pruneRunArtifacts(context.repo, job, removable, worktrees)
if (repo) {
await this.worktreeManager.pruneRunArtifacts(repo, job, removable, worktrees)
}
const cleared = deleteScheduleRunsByIds(this.db, context.repoId, jobId, removable.map((run) => run.id))
const cleared = deleteScheduleRunsByIds(this.db, repoId, jobId, removable.map((run) => run.id))
return { cleared }
}
@@ -811,8 +817,8 @@ export class ScheduleService {
private async deleteRunForTarget(target: ScheduleJobTarget, jobId: number, runId: number, worktrees: ScheduleRunWorktreesMode = 'commit'): Promise<void> {
const job = this.loadJobForTarget(target, jobId)
const context = this.resolveTargetContext(target, job.directory)
const run = getScheduleRunById(this.db, context.repoId, jobId, runId)
const { repo, repoId } = this.resolveTargetPersistence(target)
const run = getScheduleRunById(this.db, repoId, jobId, runId)
if (!run) {
throw new ScheduleServiceError('Run not found', 404)
@@ -821,10 +827,10 @@ export class ScheduleService {
throw new ScheduleServiceError('Cannot delete a run while it is in progress. Cancel it first.', 409)
}
if (context.repo) {
await this.worktreeManager.pruneRunArtifacts(context.repo, job, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }], worktrees)
if (repo) {
await this.worktreeManager.pruneRunArtifacts(repo, job, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }], worktrees)
}
const deleted = deleteScheduleRunById(this.db, context.repoId, jobId, runId)
const deleted = deleteScheduleRunById(this.db, repoId, jobId, runId)
if (!deleted) {
throw new ScheduleServiceError('Run not found', 404)
}
@@ -209,7 +209,7 @@ export class SessionPermissionModeService {
rootSessionId: string,
serverId: string,
): SessionLockReason | null {
if (serverId === LOCAL_OPENCODE_SERVER_ID && getScheduleRunBySessionId(this.db, rootSessionId)) {
if (getScheduleRunBySessionId(this.db, rootSessionId, serverId)) {
return 'schedule'
}
+27
View File
@@ -544,6 +544,33 @@ describe('schedule database queries', () => {
expect(run).toBeNull()
})
it('scopes the run lookup by session id and server id', () => {
const stmt = {
get: vi.fn().mockReturnValue(makeRunRow({ server_id: 'srv_kitchen' })),
}
mockDb.prepare.mockReturnValue(stmt)
const run = schedulesDb.getScheduleRunBySessionId(mockDb, 'ses-1', 'srv_kitchen')
expect(mockDb.prepare).toHaveBeenCalledWith(
'SELECT * FROM schedule_runs WHERE server_id = ? AND session_id = ? ORDER BY started_at DESC LIMIT 1',
)
expect(stmt.get).toHaveBeenCalledWith('srv_kitchen', 'ses-1')
expect(run).toMatchObject({ id: 5, sessionId: 'ses-1' })
})
it('defaults the run lookup to the local server', () => {
const stmt = {
get: vi.fn().mockReturnValue(undefined),
}
mockDb.prepare.mockReturnValue(stmt)
const run = schedulesDb.getScheduleRunBySessionId(mockDb, 'ses-1')
expect(stmt.get).toHaveBeenCalledWith('local', 'ses-1')
expect(run).toBeNull()
})
it('lists all runs with context and no filters', () => {
const row = {
...makeRunRow(),
@@ -4,7 +4,7 @@ import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import migration from '../../src/db/migrations/202610181300-session-server-scope'
import { getSessionGoalById, insertSessionGoal } from '../../src/db/session-goals'
import { getSessionPermissionMode } from '../../src/db/session-permission-modes'
import { getSessionPermissionMode, setSessionPermissionMode } from '../../src/db/session-permission-modes'
function createTestDb(): Database {
const db = new Database(':memory:')
@@ -53,12 +53,32 @@ function tableColumns(db: Database, table: string): string[] {
return (db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).map((column) => column.name)
}
function primaryKeyColumns(db: Database, table: string): string[] {
return (db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string; pk: number }>)
.filter((column) => column.pk > 0)
.sort((left, right) => left.pk - right.pk)
.map((column) => column.name)
}
function openGoalIndexColumns(db: Database): string[] {
return (db.prepare("PRAGMA index_info('idx_session_goals_open')").all() as Array<{ name: string }>).map(
(column) => column.name,
)
}
function countRows(db: Database, table: string): number {
return (db.prepare(`SELECT COUNT(*) AS count FROM ${table}`).get() as { count: number }).count
}
const GOAL_INPUT = {
sessionId: 'ses_shared',
directory: '/repo',
objective: 'Ship it',
maxContinuations: 1,
tokenBudget: null,
tokensAtStart: 0,
}
describe('202610181300 session server scope migration', () => {
let db: Database
@@ -77,24 +97,70 @@ describe('202610181300 session server scope migration', () => {
})
it('scopes the open goal index by server', () => {
const input = {
sessionId: 'ses_shared',
directory: '/repo',
objective: 'Ship it',
maxContinuations: 1,
tokenBudget: null,
tokensAtStart: 0,
}
const local = insertSessionGoal(db, input)
const remote = insertSessionGoal(db, { ...input, serverId: 'srv_remote' })
const duplicateRemote = insertSessionGoal(db, { ...input, serverId: 'srv_remote' })
const local = insertSessionGoal(db, GOAL_INPUT)
const remote = insertSessionGoal(db, { ...GOAL_INPUT, serverId: 'srv_remote' })
const duplicateRemote = insertSessionGoal(db, { ...GOAL_INPUT, serverId: 'srv_remote' })
expect(local).not.toBeNull()
expect(remote).not.toBeNull()
expect(duplicateRemote).toBeNull()
})
it('keys permission modes by server and session', () => {
expect(primaryKeyColumns(db, 'session_permission_modes')).toEqual(['server_id', 'session_id'])
setSessionPermissionMode(db, 'ses_shared', 'auto')
setSessionPermissionMode(db, 'ses_shared', 'ask', 'srv_x')
expect(getSessionPermissionMode(db, 'ses_shared')).toBe('auto')
expect(getSessionPermissionMode(db, 'ses_shared', 'srv_x')).toBe('ask')
expect(countRows(db, 'session_permission_modes')).toBe(2)
})
it('updates only the mode of the matching server and session', () => {
setSessionPermissionMode(db, 'ses_shared', 'auto')
setSessionPermissionMode(db, 'ses_shared', 'ask', 'srv_x')
setSessionPermissionMode(db, 'ses_shared', 'ask')
expect(getSessionPermissionMode(db, 'ses_shared')).toBe('ask')
expect(getSessionPermissionMode(db, 'ses_shared', 'srv_x')).toBe('ask')
expect(countRows(db, 'session_permission_modes')).toBe(2)
})
it('applies without the session_goals table', () => {
const standaloneDb = new Database(':memory:')
standaloneDb.run(`
CREATE TABLE session_permission_modes (
session_id TEXT PRIMARY KEY,
mode TEXT NOT NULL CHECK(mode IN ('ask','auto')),
updated_at INTEGER NOT NULL
)
`)
expect(() => migration.up(standaloneDb)).not.toThrow()
expect(primaryKeyColumns(standaloneDb, 'session_permission_modes')).toEqual(['server_id', 'session_id'])
standaloneDb.close()
})
it('removes remote rows and restores session-scoped keys when rolled back', () => {
insertSessionGoal(db, GOAL_INPUT)
insertSessionGoal(db, { ...GOAL_INPUT, serverId: 'srv_x' })
setSessionPermissionMode(db, 'ses_shared', 'auto')
setSessionPermissionMode(db, 'ses_shared', 'ask', 'srv_x')
expect(() => migration.down(db)).not.toThrow()
expect(openGoalIndexColumns(db)).toEqual(['session_id'])
expect(tableColumns(db, 'session_goals')).not.toContain('server_id')
expect(primaryKeyColumns(db, 'session_permission_modes')).toEqual(['session_id'])
expect(countRows(db, 'session_goals')).toBe(1)
expect(countRows(db, 'session_permission_modes')).toBe(1)
expect(db.prepare('SELECT session_id, mode FROM session_permission_modes').all()).toEqual([
{ session_id: 'ses_shared', mode: 'auto' },
])
})
it('upgrades legacy tables, keeps existing rows local and tolerates a second run', () => {
const legacyDb = new Database(':memory:')
createLegacyTables(legacyDb)
@@ -110,12 +176,16 @@ describe('202610181300 session server scope migration', () => {
const legacyGoalId = (legacyDb.prepare('SELECT id FROM session_goals LIMIT 1').get() as { id: number }).id
migration.up(legacyDb)
setSessionPermissionMode(legacyDb, 'ses_root', 'ask', 'srv_x')
migration.up(legacyDb)
expect(tableColumns(legacyDb, 'session_permission_modes')).toContain('server_id')
expect(tableColumns(legacyDb, 'session_goals')).toContain('server_id')
expect(openGoalIndexColumns(legacyDb)).toEqual(['server_id', 'session_id'])
expect(primaryKeyColumns(legacyDb, 'session_permission_modes')).toEqual(['server_id', 'session_id'])
expect(getSessionPermissionMode(legacyDb, 'ses_root')).toBe('auto')
expect(getSessionPermissionMode(legacyDb, 'ses_root', 'srv_x')).toBe('ask')
expect(countRows(legacyDb, 'session_permission_modes')).toBe(2)
expect(getSessionGoalById(legacyDb, legacyGoalId)).toMatchObject({ serverId: 'local' })
legacyDb.close()
+25 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Database } from 'bun:sqlite'
import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
import { buildSchedulePermissionRuleset, LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
import { createRepo, deleteRepo } from '../../src/db/queries'
import { migrate } from '../../src/db/migration-runner'
@@ -332,6 +332,30 @@ describe('MultiRunService', () => {
expect(error).toMatchObject({ status: 404 })
})
it('rejects a local server target because it stores no repository', async () => {
const repoId = readyRepo()
const { client, sessionCreate } = createClient()
const repoWorkspaces = createRepoWorkspaces()
const service = createService(client, repoWorkspaces.service)
const error = await service
.launch({
serverId: LOCAL_OPENCODE_SERVER_ID,
directory: REPO_DIR,
name: 'Sweep',
prompt: 'go',
models: ['openai/a'],
isolate: false,
})
.catch((caught: unknown) => caught)
expect(error).toBeInstanceOf(MultiRunError)
expect(error).toMatchObject({ status: 400 })
expect(sessionCreate).not.toHaveBeenCalled()
expect(repoWorkspaces.create).not.toHaveBeenCalled()
expect(service.list({ kind: 'repo', repoId })).toHaveLength(0)
})
it('removes the workspace when discarding an isolated entry', async () => {
const repoId = readyRepo()
const { client } = createClient()
+105 -3
View File
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { getScheduleJobById, listScheduleRunsByJob } from '../../src/db/schedules'
import { getScheduleJobById, createScheduleRun, listScheduleRunsByJob } from '../../src/db/schedules'
import type { OpenCodeApi } from '@opencode-manager/shared/opencode'
import { ScheduleService } from '../../src/services/schedules'
import { createStubOpenCodeClient, stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
@@ -44,7 +44,7 @@ function createClient() {
return { client: createStubOpenCodeClient({ api }), api: stub.api }
}
function createService(db: Database, localClient: ReturnType<typeof createStubOpenCodeClient>, remoteClient: ReturnType<typeof createStubOpenCodeClient>, enabled = true) {
function createService(db: Database, localClient: ReturnType<typeof createStubOpenCodeClient>, remoteClient: ReturnType<typeof createStubOpenCodeClient>, enabled = true, registered = true) {
const worktreeManager = {
prepare: vi.fn().mockResolvedValue(null),
finalize: vi.fn().mockResolvedValue({ commitHash: null }),
@@ -53,7 +53,7 @@ function createService(db: Database, localClient: ReturnType<typeof createStubOp
releaseWorktree: vi.fn().mockResolvedValue(undefined),
}
const registry = {
get: vi.fn(() => ({ ...REMOTE_SERVER, enabled })),
get: vi.fn(() => (registered ? { ...REMOTE_SERVER, enabled } : undefined)),
getClient: vi.fn(() => remoteClient),
}
const service = new ScheduleService(db, localClient, worktreeManager as never, registry as never)
@@ -156,4 +156,106 @@ describe('remote schedule targets', () => {
const runs = service.listAllRuns()
expect(runs[0]).toMatchObject({ serverId: REMOTE_SERVER.id, serverName: REMOTE_SERVER.name })
})
it('lists remote jobs for a disabled server and for an unregistered server', async () => {
const localClient = createClient().client
const { client } = createClient()
const { service } = createService(db, localClient, client)
const job = await service.createServerJob(REMOTE_SERVER.id, '/srv/projects/audit', baseRequest)
const disabled = createService(db, localClient, client, false)
expect(disabled.service.listServerJobs(REMOTE_SERVER.id).map((entry) => entry.id)).toEqual([job.id])
const unregistered = createService(db, localClient, client, true, false)
expect(unregistered.service.listServerJobs(REMOTE_SERVER.id).map((entry) => entry.id)).toEqual([job.id])
})
it('deletes a remote job while the target server is disabled', async () => {
const localClient = createClient().client
const { client } = createClient()
const { service } = createService(db, localClient, client)
const job = await service.createServerJob(REMOTE_SERVER.id, '/srv/projects/audit', baseRequest)
seedCompletedRun(db, job.id)
await createService(db, localClient, client, false).service.deleteServerJob(REMOTE_SERVER.id, job.id)
expect(getScheduleJobById(db, null, job.id)).toBeNull()
expect(listScheduleRunsByJob(db, null, job.id)).toEqual([])
})
it('deletes a remote job when the target server is missing from the registry', async () => {
const localClient = createClient().client
const { client } = createClient()
const { service } = createService(db, localClient, client)
const job = await service.createServerJob(REMOTE_SERVER.id, '/srv/projects/audit', baseRequest)
seedCompletedRun(db, job.id)
await createService(db, localClient, client, true, false).service.deleteServerJob(REMOTE_SERVER.id, job.id)
expect(getScheduleJobById(db, null, job.id)).toBeNull()
expect(listScheduleRunsByJob(db, null, job.id)).toEqual([])
})
it('clears remote run history while the target server is disabled', async () => {
const localClient = createClient().client
const { client } = createClient()
const { service } = createService(db, localClient, client)
const job = await service.createServerJob(REMOTE_SERVER.id, '/srv/projects/audit', baseRequest)
seedCompletedRun(db, job.id)
seedCompletedRun(db, job.id)
await expect(createService(db, localClient, client, false).service.clearServerRunHistory(REMOTE_SERVER.id, job.id))
.resolves.toEqual({ cleared: 2 })
expect(listScheduleRunsByJob(db, null, job.id)).toEqual([])
})
it('clears remote run history when the target server is missing from the registry', async () => {
const localClient = createClient().client
const { client } = createClient()
const { service } = createService(db, localClient, client)
const job = await service.createServerJob(REMOTE_SERVER.id, '/srv/projects/audit', baseRequest)
seedCompletedRun(db, job.id)
await expect(createService(db, localClient, client, true, false).service.clearServerRunHistory(REMOTE_SERVER.id, job.id))
.resolves.toEqual({ cleared: 1 })
expect(listScheduleRunsByJob(db, null, job.id)).toEqual([])
})
it('deletes a remote run while the target server is disabled', async () => {
const localClient = createClient().client
const { client } = createClient()
const { service } = createService(db, localClient, client)
const job = await service.createServerJob(REMOTE_SERVER.id, '/srv/projects/audit', baseRequest)
const runId = seedCompletedRun(db, job.id)
await createService(db, localClient, client, false).service.deleteServerRun(REMOTE_SERVER.id, job.id, runId)
expect(listScheduleRunsByJob(db, null, job.id)).toEqual([])
})
it('deletes a remote run when the target server is missing from the registry', async () => {
const localClient = createClient().client
const { client } = createClient()
const { service } = createService(db, localClient, client)
const job = await service.createServerJob(REMOTE_SERVER.id, '/srv/projects/audit', baseRequest)
const runId = seedCompletedRun(db, job.id)
await createService(db, localClient, client, true, false).service.deleteServerRun(REMOTE_SERVER.id, job.id, runId)
expect(listScheduleRunsByJob(db, null, job.id)).toEqual([])
})
})
function seedCompletedRun(db: Database, jobId: number): number {
return createScheduleRun(db, {
jobId,
repoId: null,
serverId: REMOTE_SERVER.id,
triggerSource: 'schedule',
status: 'completed',
startedAt: Date.now(),
createdAt: Date.now(),
}).id
}
@@ -3,7 +3,7 @@ import { Database } from 'bun:sqlite'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { createRepo } from '../../src/db/queries'
import { createScheduleRun, updateScheduleRunMetadata } from '../../src/db/schedules'
import { createScheduleRun, getScheduleRunBySessionId, updateScheduleRunMetadata } from '../../src/db/schedules'
import { getSessionPermissionMode, setSessionPermissionMode } from '../../src/db/session-permission-modes'
import { SettingsService } from '../../src/services/settings'
import { SessionPermissionModeService } from '../../src/services/session-permission-modes'
@@ -670,6 +670,57 @@ describe('SessionPermissionModeService', () => {
})
})
it('reports the schedule lock for a remote scheduled session even with a stored auto mode', async () => {
const run = createScheduleRun(db, {
jobId: 1,
repoId: null,
serverId: 'srv_remote',
triggerSource: 'schedule',
status: 'running',
startedAt: Date.now(),
createdAt: Date.now(),
})
updateScheduleRunMetadata(db, null, 1, run.id, { sessionId: 'ses_scheduled' })
setSessionPermissionMode(db, 'ses_scheduled', 'auto', 'srv_remote')
const local = createFakeSessionPermissionClient({ parents: { ses_scheduled: null } })
const remote = createFakeSessionPermissionClient({ parents: { ses_scheduled: null } })
const service = createMultiServerService(db, { local, srv_remote: remote }, new SettingsService(db))
await expect(service.getEffectiveMode('ses_scheduled', 'srv_remote')).resolves.toEqual({
sessionId: 'ses_scheduled',
rootSessionId: 'ses_scheduled',
mode: 'ask',
lockedReason: 'schedule',
})
await expect(service.setMode('ses_scheduled', 'auto', DIRECTORY, 'srv_remote')).rejects.toMatchObject({ status: 409 })
})
it('does not lock a local session that matches only a remote schedule run', async () => {
const run = createScheduleRun(db, {
jobId: 1,
repoId: null,
serverId: 'srv_remote',
triggerSource: 'schedule',
status: 'running',
startedAt: Date.now(),
createdAt: Date.now(),
})
updateScheduleRunMetadata(db, null, 1, run.id, { sessionId: 'ses_scheduled' })
expect(getScheduleRunBySessionId(db, 'ses_scheduled')).toBeNull()
const local = createFakeSessionPermissionClient({ parents: { ses_scheduled: null } })
const service = createMultiServerService(db, { local, srv_remote: createFakeSessionPermissionClient() }, new SettingsService(db))
await expect(service.getEffectiveMode('ses_scheduled')).resolves.toEqual({
sessionId: 'ses_scheduled',
rootSessionId: 'ses_scheduled',
mode: 'ask',
lockedReason: null,
})
})
it('suppresses permission notifications for remote auto sessions', async () => {
setSessionPermissionMode(db, 'ses_root', 'auto', 'srv_remote')
const local = createFakeSessionPermissionClient()
+4
View File
@@ -41,10 +41,14 @@ export type ScheduleTargetRef =
function invalidateScheduleQueries(queryClient: ReturnType<typeof useQueryClient>): void {
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
queryClient.invalidateQueries({ queryKey: ['repo-schedules'] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule'] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs'] })
queryClient.invalidateQueries({ queryKey: ['repo-schedule-run'] })
queryClient.invalidateQueries({ queryKey: ['server-schedule'] })
queryClient.invalidateQueries({ queryKey: ['server-schedule-runs'] })
queryClient.invalidateQueries({ queryKey: ['server-schedule-run'] })
queryClient.invalidateQueries({ queryKey: ['schedule-run-detail'] })
}
export function useAllSchedules() {
+3
View File
@@ -7,6 +7,7 @@ const BASE_URL = 'http://localhost:5003'
const goal: SessionGoal = {
id: 7,
sessionId: 'ses_1',
serverId: 'local',
directory: '/repo',
objective: 'fix the flaky test',
status: 'active',
@@ -27,6 +28,8 @@ const goal: SessionGoal = {
const run: MultiRun = {
id: 3,
repoId: 1,
serverId: 'local',
directory: null,
name: 'sweep',
prompt: 'hello',
isolated: true,