mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(servers): run Manager automation on linked servers
This commit is contained in:
1 parent
c591c15743
commit
a9bdb8358f
131 files changed
+6568
-949
No files matched your search
@@ -0,0 +1,61 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const SERVER_ID_COLUMN = 'server_id'
|
||||
|
||||
function tableExists(db: Database, table: string): boolean {
|
||||
return Boolean(
|
||||
db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table),
|
||||
)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
function addServerIdColumn(db: Database, table: string): void {
|
||||
if (!tableExists(db, table) || hasColumn(db, table, SERVER_ID_COLUMN)) {
|
||||
return
|
||||
}
|
||||
db.run(`ALTER TABLE ${table} ADD COLUMN server_id TEXT NOT NULL DEFAULT '${LOCAL_OPENCODE_SERVER_ID}'`)
|
||||
}
|
||||
|
||||
function dropServerIdColumn(db: Database, table: string): void {
|
||||
if (!tableExists(db, table) || !hasColumn(db, table, SERVER_ID_COLUMN)) {
|
||||
return
|
||||
}
|
||||
db.run(`ALTER TABLE ${table} DROP COLUMN ${SERVER_ID_COLUMN}`)
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610181300-session-server-scope',
|
||||
|
||||
up(db) {
|
||||
addServerIdColumn(db, 'session_permission_modes')
|
||||
addServerIdColumn(db, 'session_goals')
|
||||
|
||||
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')
|
||||
`)
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run('DROP INDEX IF EXISTS idx_session_goals_open')
|
||||
if (tableExists(db, 'session_goals')) {
|
||||
db.run(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
|
||||
ON session_goals(session_id)
|
||||
WHERE status IN ('active','paused')
|
||||
`)
|
||||
}
|
||||
dropServerIdColumn(db, 'session_goals')
|
||||
dropServerIdColumn(db, 'session_permission_modes')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
}
|
||||
|
||||
const REBUILT_COLUMNS = `
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
directory TEXT,
|
||||
name TEXT NOT NULL,
|
||||
prompt TEXT NOT NULL,
|
||||
isolated INTEGER NOT NULL,
|
||||
base_ref TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
`
|
||||
|
||||
function needsRebuild(columns: ColumnInfo[]): boolean {
|
||||
if (columns.length === 0) return false
|
||||
|
||||
const byName = new Map(columns.map((column) => [column.name, column]))
|
||||
const repoId = byName.get('repo_id')
|
||||
if (!repoId || repoId.notnull === 1) return true
|
||||
return !byName.has('server_id') || !byName.has('directory')
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610181310-multi-run-targets',
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(multi_runs)').all() as ColumnInfo[]
|
||||
if (!needsRebuild(columns)) return
|
||||
|
||||
const names = new Set(columns.map((column) => column.name))
|
||||
const serverId = names.has('server_id') ? 'server_id' : "'local'"
|
||||
const directory = names.has('directory') ? 'directory' : 'NULL'
|
||||
|
||||
db.run('DROP TABLE IF EXISTS multi_runs_targets')
|
||||
db.run(`CREATE TABLE multi_runs_targets (${REBUILT_COLUMNS})`)
|
||||
db.run(`
|
||||
INSERT INTO multi_runs_targets (id, repo_id, server_id, directory, name, prompt, isolated, base_ref, created_at)
|
||||
SELECT id, repo_id, ${serverId}, ${directory}, name, prompt, isolated, base_ref, created_at
|
||||
FROM multi_runs
|
||||
`)
|
||||
db.run('DROP TABLE multi_runs')
|
||||
db.run('ALTER TABLE multi_runs_targets RENAME TO multi_runs')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_multi_runs_repo ON multi_runs(repo_id, created_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_multi_runs_server ON multi_runs(server_id, directory, created_at DESC)')
|
||||
},
|
||||
|
||||
down(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(multi_runs)').all() as ColumnInfo[]
|
||||
if (columns.length === 0) return
|
||||
|
||||
const names = new Set(columns.map((column) => column.name))
|
||||
if (!names.has('server_id') && !names.has('directory')) return
|
||||
|
||||
db.run('DROP TABLE IF EXISTS multi_runs_repo_only')
|
||||
db.run(`
|
||||
CREATE TABLE multi_runs_repo_only (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
prompt TEXT NOT NULL,
|
||||
isolated INTEGER NOT NULL,
|
||||
base_ref TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
db.run(`
|
||||
INSERT INTO multi_runs_repo_only (id, repo_id, name, prompt, isolated, base_ref, created_at)
|
||||
SELECT id, repo_id, name, prompt, isolated, base_ref, created_at
|
||||
FROM multi_runs
|
||||
WHERE repo_id IS NOT NULL
|
||||
`)
|
||||
db.run('DROP TABLE multi_runs')
|
||||
db.run('ALTER TABLE multi_runs_repo_only RENAME TO multi_runs')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_multi_runs_repo ON multi_runs(repo_id, created_at DESC)')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -0,0 +1,254 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
}
|
||||
|
||||
const LEGACY_SUFFIX = '_legacy_202610181320'
|
||||
|
||||
function createJobsTable(db: { run: (sql: string) => void }, table: string): void {
|
||||
db.run(`
|
||||
CREATE TABLE ${table} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER REFERENCES repos(id) ON DELETE CASCADE,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
directory TEXT,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
interval_minutes INTEGER,
|
||||
schedule_mode TEXT NOT NULL DEFAULT 'interval',
|
||||
cron_expression TEXT,
|
||||
timezone TEXT,
|
||||
agent_slug TEXT,
|
||||
prompt TEXT NOT NULL,
|
||||
model TEXT,
|
||||
skill_metadata TEXT,
|
||||
permission_config TEXT,
|
||||
mcp_servers TEXT,
|
||||
branch TEXT,
|
||||
workspace_mode TEXT NOT NULL DEFAULT 'worktree',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
last_run_at INTEGER,
|
||||
next_run_at INTEGER
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
function createRunsTable(db: { run: (sql: string) => void }, table: string): void {
|
||||
db.run(`
|
||||
CREATE TABLE ${table} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
job_id INTEGER NOT NULL REFERENCES schedule_jobs(id) ON DELETE CASCADE,
|
||||
repo_id INTEGER REFERENCES repos(id) ON DELETE CASCADE,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
trigger_source TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
started_at INTEGER NOT NULL,
|
||||
finished_at INTEGER,
|
||||
viewed_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
session_id TEXT,
|
||||
session_title TEXT,
|
||||
log_text TEXT,
|
||||
response_text TEXT,
|
||||
error_text TEXT,
|
||||
run_branch TEXT,
|
||||
commit_hash TEXT,
|
||||
worktree_path TEXT
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610181320-remote-schedule-targets',
|
||||
|
||||
up(db) {
|
||||
const jobColumns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
if (jobColumns.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const runColumns = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
const jobColumnNames = new Set(jobColumns.map((column) => column.name))
|
||||
const runColumnNames = new Set(runColumns.map((column) => column.name))
|
||||
const jobsNeedRebuild =
|
||||
!jobColumnNames.has('server_id') ||
|
||||
!jobColumnNames.has('directory') ||
|
||||
jobColumns.find((column) => column.name === 'repo_id')?.notnull !== 0
|
||||
const runsNeedRebuild =
|
||||
!runColumnNames.has('server_id') ||
|
||||
runColumns.find((column) => column.name === 'repo_id')?.notnull !== 0
|
||||
|
||||
if (!jobsNeedRebuild && !runsNeedRebuild) {
|
||||
return
|
||||
}
|
||||
|
||||
const jobsLegacy = `schedule_jobs${LEGACY_SUFFIX}`
|
||||
const runsLegacy = `schedule_runs${LEGACY_SUFFIX}`
|
||||
|
||||
db.run(`DROP TABLE IF EXISTS ${runsLegacy}`)
|
||||
db.run(`DROP TABLE IF EXISTS ${jobsLegacy}`)
|
||||
|
||||
db.run(`ALTER TABLE schedule_jobs RENAME TO ${jobsLegacy}`)
|
||||
db.run(`ALTER TABLE schedule_runs RENAME TO ${runsLegacy}`)
|
||||
|
||||
createJobsTable(db, 'schedule_jobs')
|
||||
createRunsTable(db, 'schedule_runs')
|
||||
|
||||
const jobServerColumn = jobColumnNames.has('server_id') ? 'server_id' : "'local'"
|
||||
const jobDirectoryColumn = jobColumnNames.has('directory') ? 'directory' : 'NULL'
|
||||
const jobOptionalColumns = ['permission_config', 'mcp_servers', 'branch', 'workspace_mode']
|
||||
.map((column) => (jobColumnNames.has(column) ? column : 'NULL'))
|
||||
|
||||
db.run(`
|
||||
INSERT INTO schedule_jobs (
|
||||
id, repo_id, server_id, directory, name, description, enabled, interval_minutes, schedule_mode,
|
||||
cron_expression, timezone, agent_slug, prompt, model, skill_metadata, permission_config, mcp_servers,
|
||||
branch, workspace_mode, created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
SELECT
|
||||
id, repo_id, ${jobServerColumn}, ${jobDirectoryColumn}, name, description, enabled, interval_minutes,
|
||||
COALESCE(schedule_mode, 'interval'), cron_expression, timezone, agent_slug, prompt, model, skill_metadata,
|
||||
${jobOptionalColumns[0]}, ${jobOptionalColumns[1]}, ${jobOptionalColumns[2]},
|
||||
COALESCE(${jobOptionalColumns[3]}, 'worktree'), created_at, updated_at, last_run_at, next_run_at
|
||||
FROM ${jobsLegacy}
|
||||
`)
|
||||
|
||||
const runServerColumn = runColumnNames.has('server_id') ? 'server_id' : "'local'"
|
||||
const runOptionalColumns = ['viewed_at', 'run_branch', 'commit_hash', 'worktree_path']
|
||||
.map((column) => (runColumnNames.has(column) ? column : 'NULL'))
|
||||
|
||||
db.run(`
|
||||
INSERT INTO schedule_runs (
|
||||
id, job_id, repo_id, server_id, trigger_source, status, started_at, finished_at, viewed_at,
|
||||
created_at, session_id, session_title, log_text, response_text, error_text, run_branch,
|
||||
commit_hash, worktree_path
|
||||
)
|
||||
SELECT
|
||||
id, job_id, repo_id, ${runServerColumn}, trigger_source, status, started_at, finished_at,
|
||||
${runOptionalColumns[0]}, created_at, session_id, session_title, log_text, response_text, error_text,
|
||||
${runOptionalColumns[1]}, ${runOptionalColumns[2]}, ${runOptionalColumns[3]}
|
||||
FROM ${runsLegacy}
|
||||
`)
|
||||
|
||||
db.run(`DROP TABLE ${runsLegacy}`)
|
||||
db.run(`DROP TABLE ${jobsLegacy}`)
|
||||
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_server ON schedule_jobs(server_id)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_job ON schedule_runs(job_id, started_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_repo ON schedule_runs(repo_id, started_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_session ON schedule_runs(session_id, started_at DESC)')
|
||||
db.run(`
|
||||
CREATE INDEX IF NOT EXISTS idx_schedule_runs_unread
|
||||
ON schedule_runs(finished_at DESC)
|
||||
WHERE viewed_at IS NULL
|
||||
`)
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run('DELETE FROM schedule_runs WHERE repo_id IS NULL')
|
||||
db.run('DELETE FROM schedule_jobs WHERE repo_id IS NULL')
|
||||
|
||||
const jobsLegacy = `schedule_jobs${LEGACY_SUFFIX}`
|
||||
const runsLegacy = `schedule_runs${LEGACY_SUFFIX}`
|
||||
|
||||
db.run(`DROP TABLE IF EXISTS ${runsLegacy}`)
|
||||
db.run(`DROP TABLE IF EXISTS ${jobsLegacy}`)
|
||||
|
||||
db.run(`ALTER TABLE schedule_jobs RENAME TO ${jobsLegacy}`)
|
||||
db.run(`ALTER TABLE schedule_runs RENAME TO ${runsLegacy}`)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE schedule_jobs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
interval_minutes INTEGER,
|
||||
schedule_mode TEXT NOT NULL DEFAULT 'interval',
|
||||
cron_expression TEXT,
|
||||
timezone TEXT,
|
||||
agent_slug TEXT,
|
||||
prompt TEXT NOT NULL,
|
||||
model TEXT,
|
||||
skill_metadata TEXT,
|
||||
permission_config TEXT,
|
||||
mcp_servers TEXT,
|
||||
branch TEXT,
|
||||
workspace_mode TEXT NOT NULL DEFAULT 'worktree',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
last_run_at INTEGER,
|
||||
next_run_at INTEGER
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE schedule_runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
job_id INTEGER NOT NULL REFERENCES schedule_jobs(id) ON DELETE CASCADE,
|
||||
repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
|
||||
trigger_source TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
started_at INTEGER NOT NULL,
|
||||
finished_at INTEGER,
|
||||
viewed_at INTEGER,
|
||||
created_at INTEGER NOT NULL,
|
||||
session_id TEXT,
|
||||
session_title TEXT,
|
||||
log_text TEXT,
|
||||
response_text TEXT,
|
||||
error_text TEXT,
|
||||
run_branch TEXT,
|
||||
commit_hash TEXT,
|
||||
worktree_path TEXT
|
||||
)
|
||||
`)
|
||||
|
||||
db.run(`
|
||||
INSERT INTO schedule_jobs (
|
||||
id, repo_id, name, description, enabled, interval_minutes, schedule_mode, cron_expression, timezone,
|
||||
agent_slug, prompt, model, skill_metadata, permission_config, mcp_servers, branch, workspace_mode,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
SELECT
|
||||
id, repo_id, name, description, enabled, interval_minutes, schedule_mode, cron_expression, timezone,
|
||||
agent_slug, prompt, model, skill_metadata, permission_config, mcp_servers, branch, workspace_mode,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
FROM ${jobsLegacy}
|
||||
`)
|
||||
|
||||
db.run(`
|
||||
INSERT INTO schedule_runs (
|
||||
id, job_id, repo_id, trigger_source, status, started_at, finished_at, viewed_at, created_at,
|
||||
session_id, session_title, log_text, response_text, error_text, run_branch, commit_hash, worktree_path
|
||||
)
|
||||
SELECT
|
||||
id, job_id, repo_id, trigger_source, status, started_at, finished_at, viewed_at, created_at,
|
||||
session_id, session_title, log_text, response_text, error_text, run_branch, commit_hash, worktree_path
|
||||
FROM ${runsLegacy}
|
||||
`)
|
||||
|
||||
db.run(`DROP TABLE ${runsLegacy}`)
|
||||
db.run(`DROP TABLE ${jobsLegacy}`)
|
||||
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_repo ON schedule_jobs(repo_id)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_jobs_next_run ON schedule_jobs(enabled, next_run_at)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_job ON schedule_runs(job_id, started_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_repo ON schedule_runs(repo_id, started_at DESC)')
|
||||
db.run('CREATE INDEX IF NOT EXISTS idx_schedule_runs_session ON schedule_runs(session_id, started_at DESC)')
|
||||
db.run(`
|
||||
CREATE INDEX IF NOT EXISTS idx_schedule_runs_unread
|
||||
ON schedule_runs(finished_at DESC)
|
||||
WHERE viewed_at IS NULL
|
||||
`)
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -34,6 +34,9 @@ import migration202610141200 from './202610141200-session-sandbox-modes'
|
||||
import migration202610151200 from './202610151200-change-walkthrough-sessions'
|
||||
import migration202610161200 from './202610161200-change-walkthrough-execution'
|
||||
import migration202610181200 from './202610181200-opencode-servers'
|
||||
import migration202610181300 from './202610181300-session-server-scope'
|
||||
import migration202610181310 from './202610181310-multi-run-targets'
|
||||
import migration202610181320 from './202610181320-remote-schedule-targets'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -71,4 +74,7 @@ export const allMigrations: Migration[] = [
|
||||
migration202610151200,
|
||||
migration202610161200,
|
||||
migration202610181200,
|
||||
migration202610181300,
|
||||
migration202610181310,
|
||||
migration202610181320,
|
||||
]
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type MultiRunEntryStatus,
|
||||
type MultiRunFusionSource,
|
||||
type MultiRunFusionStatus,
|
||||
type MultiRunTarget,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
export interface MultiRunEntryRecord {
|
||||
@@ -37,7 +38,9 @@ export interface MultiRunFusionRecord {
|
||||
|
||||
export interface MultiRunRecord {
|
||||
id: number
|
||||
repoId: number
|
||||
repoId: number | null
|
||||
serverId: string
|
||||
directory: string | null
|
||||
name: string
|
||||
prompt: string
|
||||
isolated: boolean
|
||||
@@ -48,7 +51,9 @@ export interface MultiRunRecord {
|
||||
}
|
||||
|
||||
export interface CreateMultiRunGroup {
|
||||
repoId: number
|
||||
repoId: number | null
|
||||
serverId: string
|
||||
directory: string | null
|
||||
name: string
|
||||
prompt: string
|
||||
isolated: boolean
|
||||
@@ -81,7 +86,9 @@ export interface MultiRunFusionPatch {
|
||||
|
||||
interface MultiRunRow {
|
||||
id: number
|
||||
repo_id: number
|
||||
repo_id: number | null
|
||||
server_id: string
|
||||
directory: string | null
|
||||
name: string
|
||||
prompt: string
|
||||
isolated: number
|
||||
@@ -118,7 +125,7 @@ interface MultiRunFusionRow {
|
||||
updated_at: number
|
||||
}
|
||||
|
||||
const MULTI_RUN_COLUMNS = 'id, repo_id, name, prompt, isolated, base_ref, created_at'
|
||||
const MULTI_RUN_COLUMNS = 'id, repo_id, server_id, directory, name, prompt, isolated, base_ref, created_at'
|
||||
|
||||
const MULTI_RUN_ENTRY_COLUMNS = 'id, multi_run_id, model, status, session_id, directory, error, created_at, updated_at'
|
||||
|
||||
@@ -129,7 +136,9 @@ export function ensureMultiRunTables(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS multi_runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER NOT NULL,
|
||||
repo_id INTEGER,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
directory TEXT,
|
||||
name TEXT NOT NULL,
|
||||
prompt TEXT NOT NULL,
|
||||
isolated INTEGER NOT NULL,
|
||||
@@ -158,6 +167,10 @@ export function ensureMultiRunTables(db: Database): void {
|
||||
CREATE INDEX IF NOT EXISTS idx_multi_runs_repo
|
||||
ON multi_runs(repo_id, created_at DESC)
|
||||
`)
|
||||
db.run(`
|
||||
CREATE INDEX IF NOT EXISTS idx_multi_runs_server
|
||||
ON multi_runs(server_id, directory, created_at DESC)
|
||||
`)
|
||||
}
|
||||
|
||||
export function ensureMultiRunFusionTable(db: Database): void {
|
||||
@@ -194,8 +207,20 @@ export function createMultiRunWithEntries(
|
||||
const now = Date.now()
|
||||
const create = db.transaction(() => {
|
||||
const result = db
|
||||
.prepare(`INSERT INTO multi_runs(repo_id, name, prompt, isolated, base_ref, created_at) VALUES(?,?,?,?,?,?)`)
|
||||
.run(group.repoId, group.name, group.prompt, group.isolated ? 1 : 0, group.baseRef, now)
|
||||
.prepare(
|
||||
`INSERT INTO multi_runs(repo_id, server_id, directory, name, prompt, isolated, base_ref, created_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)`,
|
||||
)
|
||||
.run(
|
||||
group.repoId,
|
||||
group.serverId,
|
||||
group.directory,
|
||||
group.name,
|
||||
group.prompt,
|
||||
group.isolated ? 1 : 0,
|
||||
group.baseRef,
|
||||
now,
|
||||
)
|
||||
const multiRunId = Number(result.lastInsertRowid)
|
||||
|
||||
const insertEntry = db.prepare(`
|
||||
@@ -226,15 +251,20 @@ export function getMultiRun(db: Database, id: number): MultiRunRecord | null {
|
||||
return toMultiRunRecord(row, loadEntries(db, row.id), loadFusions(db, row.id))
|
||||
}
|
||||
|
||||
export function listMultiRuns(db: Database, repoId: number, limit: number): MultiRunRecord[] {
|
||||
export function listMultiRuns(db: Database, target: MultiRunTarget, limit: number): MultiRunRecord[] {
|
||||
const [where, params] =
|
||||
target.kind === 'repo'
|
||||
? ['repo_id = ?', [target.repoId] as const]
|
||||
: ['server_id = ? AND directory = ?', [target.serverId, target.directory] as const]
|
||||
|
||||
const rows = db
|
||||
.prepare(`
|
||||
SELECT ${MULTI_RUN_COLUMNS} FROM multi_runs
|
||||
WHERE repo_id = ?
|
||||
WHERE ${where}
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT ?
|
||||
`)
|
||||
.all(repoId, limit) as MultiRunRow[]
|
||||
.all(...params, limit) as MultiRunRow[]
|
||||
if (rows.length === 0) {
|
||||
return []
|
||||
}
|
||||
@@ -445,6 +475,8 @@ function toMultiRunRecord(
|
||||
return {
|
||||
id: row.id,
|
||||
repoId: row.repo_id,
|
||||
serverId: row.server_id,
|
||||
directory: row.directory,
|
||||
name: row.name,
|
||||
prompt: row.prompt,
|
||||
isolated: row.isolated === 1,
|
||||
|
||||
+92
-52
@@ -1,5 +1,6 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import {
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
ScheduleJobSchema,
|
||||
ScheduleMcpServersSchema,
|
||||
SchedulePermissionConfigSchema,
|
||||
@@ -20,7 +21,9 @@ import type { ScheduleJobPersistenceInput } from '../services/schedule-config'
|
||||
|
||||
interface ScheduleJobRow {
|
||||
id: number
|
||||
repo_id: number
|
||||
repo_id: number | null
|
||||
server_id: string
|
||||
directory: string | null
|
||||
name: string
|
||||
description: string | null
|
||||
enabled: number
|
||||
@@ -45,7 +48,8 @@ interface ScheduleJobRow {
|
||||
interface ScheduleRunRow {
|
||||
id: number
|
||||
job_id: number
|
||||
repo_id: number
|
||||
repo_id: number | null
|
||||
server_id: string
|
||||
trigger_source: string
|
||||
status: string
|
||||
started_at: number
|
||||
@@ -112,6 +116,8 @@ function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob {
|
||||
return ScheduleJobSchema.parse({
|
||||
id: row.id,
|
||||
repoId: row.repo_id,
|
||||
serverId: row.server_id ?? 'local',
|
||||
directory: row.directory ?? null,
|
||||
name: row.name,
|
||||
description: row.description,
|
||||
enabled: Boolean(row.enabled),
|
||||
@@ -139,6 +145,7 @@ function rowToScheduleRun(row: ScheduleRunRow): ScheduleRun {
|
||||
id: row.id,
|
||||
jobId: row.job_id,
|
||||
repoId: row.repo_id,
|
||||
serverId: row.server_id ?? 'local',
|
||||
triggerSource: row.trigger_source,
|
||||
status: row.status,
|
||||
startedAt: row.started_at,
|
||||
@@ -177,13 +184,19 @@ function serializeMcpServers(mcpServers: ScheduleJobPersistenceInput['mcpServers
|
||||
}
|
||||
|
||||
export function listScheduleJobsByRepo(db: Database, repoId: number): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(repoId) as ScheduleJobRow[]
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function listScheduleJobsByServer(db: Database, serverId: string): ScheduleJob[] {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE server_id = ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(serverId) as ScheduleJobRow[]
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function listScheduleJobIdsByRepo(db: Database, repoId: number): number[] {
|
||||
const stmt = db.prepare('SELECT id FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||
const stmt = db.prepare('SELECT id FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC')
|
||||
const rows = stmt.all(repoId) as Array<{ id: number }>
|
||||
return rows.map((row) => row.id)
|
||||
}
|
||||
@@ -194,28 +207,35 @@ export function listEnabledScheduleJobs(db: Database): ScheduleJob[] {
|
||||
return rows.map(rowToScheduleJob)
|
||||
}
|
||||
|
||||
export function getScheduleJobById(db: Database, repoId: number, jobId: number): ScheduleJob | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
export function getScheduleJobById(db: Database, repoId: number | null, jobId: number): ScheduleJob | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_jobs WHERE repo_id IS ? AND id = ?')
|
||||
const row = stmt.get(repoId, jobId) as ScheduleJobRow | undefined
|
||||
return row ? rowToScheduleJob(row) : null
|
||||
}
|
||||
|
||||
export function createScheduleJob(db: Database, repoId: number, input: ScheduleJobPersistenceInput): ScheduleJob {
|
||||
export function createScheduleJob(
|
||||
db: Database,
|
||||
repoId: number | null,
|
||||
input: ScheduleJobPersistenceInput,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): ScheduleJob {
|
||||
const now = Date.now()
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO schedule_jobs (
|
||||
repo_id, name, description, enabled, schedule_mode, interval_minutes, cron_expression, timezone, agent_slug, prompt, model, skill_metadata,
|
||||
repo_id, server_id, directory, name, description, enabled, schedule_mode, interval_minutes, cron_expression, timezone, agent_slug, prompt, model, skill_metadata,
|
||||
permission_config,
|
||||
mcp_servers,
|
||||
branch,
|
||||
workspace_mode,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
const result = stmt.run(
|
||||
repoId,
|
||||
serverId,
|
||||
input.directory ?? null,
|
||||
input.name,
|
||||
input.description ?? null,
|
||||
input.enabled ? 1 : 0,
|
||||
@@ -244,7 +264,7 @@ export function createScheduleJob(db: Database, repoId: number, input: ScheduleJ
|
||||
return job
|
||||
}
|
||||
|
||||
export function updateScheduleJob(db: Database, repoId: number, jobId: number, input: ScheduleJobPersistenceInput): ScheduleJob | null {
|
||||
export function updateScheduleJob(db: Database, repoId: number | null, jobId: number, input: ScheduleJobPersistenceInput): ScheduleJob | null {
|
||||
const existing = getScheduleJobById(db, repoId, jobId)
|
||||
if (!existing) {
|
||||
return null
|
||||
@@ -255,8 +275,8 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_jobs
|
||||
SET name = ?, description = ?, enabled = ?, schedule_mode = ?, interval_minutes = ?, cron_expression = ?, timezone = ?,
|
||||
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, workspace_mode = ?, updated_at = ?, next_run_at = ?
|
||||
WHERE repo_id = ? AND id = ?
|
||||
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, workspace_mode = ?, directory = ?, updated_at = ?, next_run_at = ?
|
||||
WHERE repo_id IS ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
@@ -275,6 +295,7 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
|
||||
serializeMcpServers(input.mcpServers),
|
||||
input.branch,
|
||||
input.workspaceMode,
|
||||
input.directory ?? null,
|
||||
now,
|
||||
input.nextRunAt,
|
||||
repoId,
|
||||
@@ -284,9 +305,9 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
|
||||
return getScheduleJobById(db, repoId, jobId)
|
||||
}
|
||||
|
||||
export function deleteScheduleJob(db: Database, repoId: number, jobId: number): boolean {
|
||||
db.prepare('DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ?').run(repoId, jobId)
|
||||
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
export function deleteScheduleJob(db: Database, repoId: number | null, jobId: number): boolean {
|
||||
db.prepare('DELETE FROM schedule_runs WHERE repo_id IS ? AND job_id = ?').run(repoId, jobId)
|
||||
const stmt = db.prepare('DELETE FROM schedule_jobs WHERE repo_id IS ? AND id = ?')
|
||||
const result = stmt.run(repoId, jobId)
|
||||
return result.changes > 0
|
||||
}
|
||||
@@ -298,9 +319,9 @@ export interface ScheduleRunArtifact {
|
||||
worktreePath: string | null
|
||||
}
|
||||
|
||||
export function listScheduleRunArtifactsByJob(db: Database, repoId: number, jobId: number): ScheduleRunArtifact[] {
|
||||
export function listScheduleRunArtifactsByJob(db: Database, repoId: number | null, jobId: number): ScheduleRunArtifact[] {
|
||||
const rows = db
|
||||
.prepare('SELECT id, status, run_branch, worktree_path FROM schedule_runs WHERE repo_id = ? AND job_id = ? ORDER BY id DESC')
|
||||
.prepare('SELECT id, status, run_branch, worktree_path FROM schedule_runs WHERE repo_id IS ? AND job_id = ? ORDER BY id DESC')
|
||||
.all(repoId, jobId) as { id: number; status: string; run_branch: string | null; worktree_path: string | null }[]
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
@@ -317,28 +338,28 @@ export interface ScheduleJobWorktreeOwner {
|
||||
}
|
||||
|
||||
export function listScheduleJobWorktreeOwners(db: Database): ScheduleJobWorktreeOwner[] {
|
||||
const rows = db.prepare('SELECT id, repo_id, name FROM schedule_jobs').all() as Array<{ id: number; repo_id: number; name: string }>
|
||||
const rows = db.prepare('SELECT id, repo_id, name FROM schedule_jobs WHERE repo_id IS NOT NULL').all() as Array<{ id: number; repo_id: number; name: string }>
|
||||
return rows.map((row) => ({ id: row.id, repoId: row.repo_id, name: row.name }))
|
||||
}
|
||||
|
||||
export function clearScheduleRunWorktreePath(db: Database, repoId: number, jobId: number, worktreePath: string): number {
|
||||
export function clearScheduleRunWorktreePath(db: Database, repoId: number | null, jobId: number, worktreePath: string): number {
|
||||
return db
|
||||
.prepare('UPDATE schedule_runs SET worktree_path = NULL WHERE repo_id = ? AND job_id = ? AND worktree_path = ?')
|
||||
.prepare('UPDATE schedule_runs SET worktree_path = NULL WHERE repo_id IS ? AND job_id = ? AND worktree_path = ?')
|
||||
.run(repoId, jobId, worktreePath).changes
|
||||
}
|
||||
|
||||
export function deleteScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): boolean {
|
||||
export function deleteScheduleRunById(db: Database, repoId: number | null, jobId: number, runId: number): boolean {
|
||||
const result = db
|
||||
.prepare('DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||
.prepare('DELETE FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id = ?')
|
||||
.run(repoId, jobId, runId)
|
||||
return result.changes > 0
|
||||
}
|
||||
|
||||
export function deleteScheduleRunsByIds(db: Database, repoId: number, jobId: number, runIds: number[]): number {
|
||||
export function deleteScheduleRunsByIds(db: Database, repoId: number | null, jobId: number, runIds: number[]): number {
|
||||
if (runIds.length === 0) return 0
|
||||
const placeholders = runIds.map(() => '?').join(', ')
|
||||
const result = db
|
||||
.prepare(`DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id IN (${placeholders})`)
|
||||
.prepare(`DELETE FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id IN (${placeholders})`)
|
||||
.run(repoId, jobId, ...runIds)
|
||||
return result.changes
|
||||
}
|
||||
@@ -346,22 +367,22 @@ export function deleteScheduleRunsByIds(db: Database, repoId: number, jobId: num
|
||||
export function cleanupOrphanedSchedules(db: Database): { orphanedJobs: number; orphanedRuns: number } {
|
||||
const runStmt = db.prepare(`
|
||||
DELETE FROM schedule_runs
|
||||
WHERE (repo_id != ? AND repo_id NOT IN (SELECT id FROM repos))
|
||||
WHERE (repo_id IS NOT NULL AND repo_id != ? AND repo_id NOT IN (SELECT id FROM repos))
|
||||
OR job_id NOT IN (SELECT id FROM schedule_jobs)
|
||||
`)
|
||||
const orphanedRuns = runStmt.run(ASSISTANT_REPO_ID).changes
|
||||
|
||||
const jobStmt = db.prepare(`
|
||||
DELETE FROM schedule_jobs
|
||||
WHERE repo_id != ? AND repo_id NOT IN (SELECT id FROM repos)
|
||||
WHERE repo_id IS NOT NULL AND repo_id != ? AND repo_id NOT IN (SELECT id FROM repos)
|
||||
`)
|
||||
const orphanedJobs = jobStmt.run(ASSISTANT_REPO_ID).changes
|
||||
|
||||
return { orphanedJobs, orphanedRuns }
|
||||
}
|
||||
|
||||
export function updateScheduleJobRunState(db: Database, repoId: number, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
|
||||
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||
export function updateScheduleJobRunState(db: Database, repoId: number | null, jobId: number, values: { lastRunAt: number; nextRunAt?: number | null }): void {
|
||||
const stmt = db.prepare('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id IS ? AND id = ?')
|
||||
stmt.run(values.lastRunAt, values.nextRunAt ?? null, Date.now(), repoId, jobId)
|
||||
}
|
||||
|
||||
@@ -374,7 +395,8 @@ export function createScheduleRun(
|
||||
db: Database,
|
||||
input: {
|
||||
jobId: number
|
||||
repoId: number
|
||||
repoId: number | null
|
||||
serverId?: string
|
||||
triggerSource: ScheduleRunTriggerSource
|
||||
status: ScheduleRunStatus
|
||||
startedAt: number
|
||||
@@ -382,13 +404,14 @@ export function createScheduleRun(
|
||||
},
|
||||
): ScheduleRun {
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO schedule_runs (job_id, repo_id, server_id, trigger_source, status, started_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
const result = stmt.run(
|
||||
input.jobId,
|
||||
input.repoId,
|
||||
input.serverId ?? LOCAL_OPENCODE_SERVER_ID,
|
||||
input.triggerSource,
|
||||
input.status,
|
||||
input.startedAt,
|
||||
@@ -404,7 +427,7 @@ export function createScheduleRun(
|
||||
|
||||
export function updateScheduleRun(
|
||||
db: Database,
|
||||
repoId: number,
|
||||
repoId: number | null,
|
||||
jobId: number,
|
||||
runId: number,
|
||||
input: {
|
||||
@@ -420,7 +443,7 @@ export function updateScheduleRun(
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_runs
|
||||
SET status = ?, finished_at = ?, session_id = ?, session_title = ?, log_text = ?, response_text = ?, error_text = ?
|
||||
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||
WHERE repo_id IS ? AND job_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
@@ -441,7 +464,7 @@ export function updateScheduleRun(
|
||||
|
||||
export function updateScheduleRunMetadata(
|
||||
db: Database,
|
||||
repoId: number,
|
||||
repoId: number | null,
|
||||
jobId: number,
|
||||
runId: number,
|
||||
input: {
|
||||
@@ -460,7 +483,7 @@ export function updateScheduleRunMetadata(
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_runs
|
||||
SET session_id = ?, session_title = ?, log_text = ?, response_text = ?, error_text = ?
|
||||
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||
WHERE repo_id IS ? AND job_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
@@ -479,7 +502,7 @@ export function updateScheduleRunMetadata(
|
||||
|
||||
export function updateScheduleRunWorktree(
|
||||
db: Database,
|
||||
repoId: number,
|
||||
repoId: number | null,
|
||||
jobId: number,
|
||||
runId: number,
|
||||
input: { worktreePath?: string | null; runBranch?: string | null; commitHash?: string | null },
|
||||
@@ -492,7 +515,7 @@ export function updateScheduleRunWorktree(
|
||||
const stmt = db.prepare(`
|
||||
UPDATE schedule_runs
|
||||
SET worktree_path = ?, run_branch = ?, commit_hash = ?
|
||||
WHERE repo_id = ? AND job_id = ? AND id = ?
|
||||
WHERE repo_id IS ? AND job_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
stmt.run(
|
||||
@@ -507,8 +530,8 @@ export function updateScheduleRunWorktree(
|
||||
return getScheduleRunById(db, repoId, jobId, runId)
|
||||
}
|
||||
|
||||
export function getScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||
export function getScheduleRunById(db: Database, repoId: number | null, jobId: number, runId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare('SELECT * FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id = ?')
|
||||
const row = stmt.get(repoId, jobId, runId) as ScheduleRunRow | undefined
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
@@ -519,10 +542,10 @@ export function getScheduleRunBySessionId(db: Database, sessionId: string): Sche
|
||||
return row ? rowToScheduleRun(row) : null
|
||||
}
|
||||
|
||||
export function getRunningScheduleRunByJob(db: Database, repoId: number, jobId: number): ScheduleRun | null {
|
||||
export function getRunningScheduleRunByJob(db: Database, repoId: number | null, jobId: number): ScheduleRun | null {
|
||||
const stmt = db.prepare(`
|
||||
SELECT * FROM schedule_runs
|
||||
WHERE repo_id = ? AND job_id = ? AND status = 'running'
|
||||
WHERE repo_id IS ? AND job_id = ? AND status = 'running'
|
||||
ORDER BY started_at DESC
|
||||
LIMIT 1
|
||||
`)
|
||||
@@ -541,12 +564,13 @@ export function listRunningScheduleRuns(db: Database, limit: number = 100): Sche
|
||||
return rows.map(rowToScheduleRun)
|
||||
}
|
||||
|
||||
export function listScheduleRunsByJob(db: Database, repoId: number, jobId: number, limit: number = 20): ScheduleRun[] {
|
||||
export function listScheduleRunsByJob(db: Database, repoId: number | null, jobId: number, limit: number = 20): ScheduleRun[] {
|
||||
const stmt = db.prepare(`
|
||||
SELECT
|
||||
id,
|
||||
job_id,
|
||||
repo_id,
|
||||
server_id,
|
||||
trigger_source,
|
||||
status,
|
||||
started_at,
|
||||
@@ -562,7 +586,7 @@ export function listScheduleRunsByJob(db: Database, repoId: number, jobId: numbe
|
||||
commit_hash,
|
||||
worktree_path
|
||||
FROM schedule_runs
|
||||
WHERE repo_id = ? AND job_id = ?
|
||||
WHERE repo_id IS ? AND job_id = ?
|
||||
ORDER BY started_at DESC
|
||||
LIMIT ?
|
||||
`)
|
||||
@@ -583,6 +607,7 @@ export interface ScheduleJobWithRepo extends ScheduleJob {
|
||||
repoName: string
|
||||
repoPath: string
|
||||
repoUrl: string
|
||||
serverName: string | null
|
||||
lastRun: ScheduleRunSummary | null
|
||||
}
|
||||
|
||||
@@ -591,6 +616,7 @@ interface ScheduleJobWithRepoRow extends ScheduleJobRow {
|
||||
repo_path: string | null
|
||||
repo_name: string | null
|
||||
repo_source_path: string | null
|
||||
server_name: string | null
|
||||
last_run_id: number | null
|
||||
last_run_status: string | null
|
||||
last_run_started_at: number | null
|
||||
@@ -601,14 +627,19 @@ interface ScheduleJobWithRepoRow extends ScheduleJobRow {
|
||||
}
|
||||
|
||||
interface RepoDisplayRow {
|
||||
repo_id: number
|
||||
repo_id: number | null
|
||||
repo_path: string | null
|
||||
repo_name: string | null
|
||||
repo_url?: string | null
|
||||
repo_source_path?: string | null
|
||||
directory?: string | null
|
||||
server_name?: string | null
|
||||
}
|
||||
|
||||
function resolveRepoDisplay(row: RepoDisplayRow): { repoName: string; repoPath: string } {
|
||||
if (row.repo_id === null) {
|
||||
return { repoName: row.server_name ?? 'Linked server', repoPath: row.directory ?? '' }
|
||||
}
|
||||
if (row.repo_id === ASSISTANT_REPO_ID) {
|
||||
return { repoName: ASSISTANT_REPO_NAME, repoPath: ASSISTANT_REPO_PATH }
|
||||
}
|
||||
@@ -641,6 +672,7 @@ function rowToScheduleJobWithRepo(row: ScheduleJobWithRepoRow): ScheduleJobWithR
|
||||
...rowToScheduleJob(row),
|
||||
...resolveRepoDisplay(row),
|
||||
repoUrl: row.repo_url ?? '',
|
||||
serverName: row.server_name ?? null,
|
||||
lastRun: buildLastRunSummary(row),
|
||||
}
|
||||
}
|
||||
@@ -649,6 +681,7 @@ export function listAllScheduleJobsWithRepos(db: Database): ScheduleJobWithRepo[
|
||||
const stmt = db.prepare(`
|
||||
SELECT
|
||||
sj.*, r.repo_url, r.local_path as repo_path, r.name as repo_name, r.source_path as repo_source_path,
|
||||
os.name AS server_name,
|
||||
sr.id AS last_run_id,
|
||||
sr.status AS last_run_status,
|
||||
sr.started_at AS last_run_started_at,
|
||||
@@ -658,10 +691,11 @@ export function listAllScheduleJobsWithRepos(db: Database): ScheduleJobWithRepo[
|
||||
substr(sr.response_text, 1, 600) AS last_run_response_head
|
||||
FROM schedule_jobs sj
|
||||
LEFT JOIN repos r ON sj.repo_id = r.id
|
||||
LEFT JOIN opencode_servers os ON sj.server_id = os.id AND sj.server_id != 'local'
|
||||
LEFT JOIN schedule_runs sr ON sr.id = (
|
||||
SELECT id FROM schedule_runs WHERE job_id = sj.id ORDER BY started_at DESC LIMIT 1
|
||||
)
|
||||
ORDER BY COALESCE(r.local_path, ''), sj.name
|
||||
ORDER BY COALESCE(r.local_path, sj.directory, ''), sj.name
|
||||
`)
|
||||
const rows = stmt.all() as ScheduleJobWithRepoRow[]
|
||||
return rows.map(rowToScheduleJobWithRepo)
|
||||
@@ -671,6 +705,7 @@ export interface ScheduleRunWithContext extends ScheduleRun {
|
||||
jobName: string
|
||||
repoName: string
|
||||
repoPath: string
|
||||
serverName: string | null
|
||||
}
|
||||
|
||||
interface ScheduleRunWithContextRow extends ScheduleRunRow {
|
||||
@@ -679,12 +714,15 @@ interface ScheduleRunWithContextRow extends ScheduleRunRow {
|
||||
repo_name: string | null
|
||||
repo_url: string | null
|
||||
repo_source_path: string | null
|
||||
directory?: string | null
|
||||
server_name?: string | null
|
||||
}
|
||||
|
||||
function rowToScheduleRunWithContext(row: ScheduleRunWithContextRow): ScheduleRunWithContext {
|
||||
return {
|
||||
...rowToScheduleRun(row),
|
||||
jobName: row.job_name,
|
||||
serverName: row.server_name ?? null,
|
||||
...resolveRepoDisplay(row),
|
||||
}
|
||||
}
|
||||
@@ -732,7 +770,7 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
|
||||
const searchTerm = search?.trim()
|
||||
if (searchTerm) {
|
||||
const pattern = `%${escapeLikePattern(searchTerm)}%`
|
||||
const searchColumns = ['sj.name', 'sr.session_title', 'sr.error_text', 'sr.run_branch', 'r.name', 'r.local_path']
|
||||
const searchColumns = ['sj.name', 'sr.session_title', 'sr.error_text', 'sr.run_branch', 'r.name', 'r.local_path', 'sj.directory', 'os.name']
|
||||
conditions.push(`(${searchColumns.map((column) => `${column} LIKE ? ESCAPE '\\'`).join(' OR ')})`)
|
||||
params.push(...searchColumns.map(() => pattern))
|
||||
}
|
||||
@@ -741,17 +779,18 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
|
||||
|
||||
const stmt = db.prepare(`
|
||||
SELECT
|
||||
sr.id, sr.job_id, sr.repo_id, sr.trigger_source, sr.status,
|
||||
sr.id, sr.job_id, sr.repo_id, sr.server_id, sr.trigger_source, sr.status,
|
||||
sr.started_at, sr.finished_at, sr.created_at,
|
||||
sr.session_id, sr.session_title,
|
||||
NULL AS log_text, NULL AS response_text, sr.error_text,
|
||||
sr.viewed_at,
|
||||
sr.run_branch, sr.commit_hash, sr.worktree_path,
|
||||
sj.name AS job_name, r.local_path AS repo_path, r.name AS repo_name,
|
||||
r.repo_url AS repo_url, r.source_path AS repo_source_path
|
||||
sj.name AS job_name, sj.directory AS directory, r.local_path AS repo_path, r.name AS repo_name,
|
||||
r.repo_url AS repo_url, r.source_path AS repo_source_path, os.name AS server_name
|
||||
FROM schedule_runs sr
|
||||
JOIN schedule_jobs sj ON sr.job_id = sj.id
|
||||
LEFT JOIN repos r ON sr.repo_id = r.id
|
||||
LEFT JOIN opencode_servers os ON sj.server_id = os.id AND sj.server_id != 'local'
|
||||
${whereClause}
|
||||
ORDER BY sr.started_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
@@ -810,17 +849,18 @@ interface UnreadScheduleRunRow extends ScheduleRunWithContextRow {
|
||||
export function listUnreadScheduleRuns(db: Database, limit: number = 20): ScheduleRunWithUnreadPreview[] {
|
||||
const stmt = db.prepare(`
|
||||
SELECT
|
||||
sr.id, sr.job_id, sr.repo_id, sr.trigger_source, sr.status,
|
||||
sr.id, sr.job_id, sr.repo_id, sr.server_id, sr.trigger_source, sr.status,
|
||||
sr.started_at, sr.finished_at, sr.created_at,
|
||||
sr.session_id, sr.session_title, sr.viewed_at,
|
||||
NULL AS log_text, NULL AS response_text, sr.error_text,
|
||||
sr.run_branch, sr.commit_hash, sr.worktree_path,
|
||||
sj.name AS job_name, r.local_path AS repo_path, r.name AS repo_name,
|
||||
r.repo_url AS repo_url, r.source_path AS repo_source_path,
|
||||
sj.name AS job_name, sj.directory AS directory, r.local_path AS repo_path, r.name AS repo_name,
|
||||
r.repo_url AS repo_url, r.source_path AS repo_source_path, os.name AS server_name,
|
||||
substr(sr.response_text, 1, 600) AS response_head
|
||||
FROM schedule_runs sr
|
||||
JOIN schedule_jobs sj ON sr.job_id = sj.id
|
||||
LEFT JOIN repos r ON sr.repo_id = r.id
|
||||
LEFT JOIN opencode_servers os ON sj.server_id = os.id AND sj.server_id != 'local'
|
||||
WHERE sr.status IN ('completed', 'failed') AND sr.viewed_at IS NULL
|
||||
ORDER BY (sr.status = 'failed') DESC, sr.finished_at DESC
|
||||
LIMIT ?
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type {
|
||||
SessionGoalStatus,
|
||||
SessionGoalStopReason,
|
||||
SessionGoalTurnState,
|
||||
SessionGoalVerdict,
|
||||
import {
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type SessionGoalStatus,
|
||||
type SessionGoalStopReason,
|
||||
type SessionGoalTurnState,
|
||||
type SessionGoalVerdict,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
export interface SessionGoalRecord {
|
||||
id: number
|
||||
sessionId: string
|
||||
serverId: string
|
||||
directory: string
|
||||
objective: string
|
||||
status: SessionGoalStatus
|
||||
@@ -29,6 +31,7 @@ export interface SessionGoalRecord {
|
||||
|
||||
export interface InsertSessionGoalInput {
|
||||
sessionId: string
|
||||
serverId?: string
|
||||
directory: string
|
||||
objective: string
|
||||
maxContinuations: number
|
||||
@@ -51,6 +54,7 @@ export interface SessionGoalPatch {
|
||||
interface SessionGoalRow {
|
||||
id: number
|
||||
session_id: string
|
||||
server_id: string
|
||||
directory: string
|
||||
objective: string
|
||||
status: SessionGoalStatus
|
||||
@@ -70,7 +74,7 @@ interface SessionGoalRow {
|
||||
}
|
||||
|
||||
const SESSION_GOAL_COLUMNS = `
|
||||
id, session_id, directory, objective, status, stop_reason, turn_state,
|
||||
id, session_id, server_id, directory, objective, status, stop_reason, turn_state,
|
||||
continuation_count, max_continuations, token_budget, tokens_at_start, tokens_used,
|
||||
consecutive_blocked, last_verdict, last_reason, created_at, updated_at, finished_at
|
||||
`
|
||||
@@ -80,6 +84,7 @@ export function ensureSessionGoalsTable(db: Database): void {
|
||||
CREATE TABLE IF NOT EXISTS session_goals (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id TEXT NOT NULL,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
directory TEXT NOT NULL,
|
||||
objective TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('active','paused','completed','blocked','stopped')),
|
||||
@@ -100,7 +105,7 @@ export function ensureSessionGoalsTable(db: Database): void {
|
||||
`)
|
||||
db.run(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_session_goals_open
|
||||
ON session_goals(session_id)
|
||||
ON session_goals(server_id, session_id)
|
||||
WHERE status IN ('active','paused')
|
||||
`)
|
||||
db.run(`
|
||||
@@ -114,12 +119,13 @@ export function insertSessionGoal(db: Database, input: InsertSessionGoalInput):
|
||||
try {
|
||||
const result = db.prepare(`
|
||||
INSERT INTO session_goals(
|
||||
session_id, directory, objective, status, stop_reason, turn_state,
|
||||
session_id, server_id, directory, objective, status, stop_reason, turn_state,
|
||||
continuation_count, max_continuations, token_budget, tokens_at_start, tokens_used,
|
||||
consecutive_blocked, last_verdict, last_reason, created_at, updated_at, finished_at
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
`).run(
|
||||
input.sessionId,
|
||||
input.serverId ?? LOCAL_OPENCODE_SERVER_ID,
|
||||
input.directory,
|
||||
input.objective,
|
||||
'active',
|
||||
@@ -153,10 +159,19 @@ export function getSessionGoalById(db: Database, id: number): SessionGoalRecord
|
||||
return row ? mapSessionGoalRow(row) : null
|
||||
}
|
||||
|
||||
export function getLatestSessionGoal(db: Database, sessionId: string): SessionGoalRecord | null {
|
||||
export function getLatestSessionGoal(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): SessionGoalRecord | null {
|
||||
const row = db
|
||||
.prepare(`SELECT ${SESSION_GOAL_COLUMNS} FROM session_goals WHERE session_id = ? ORDER BY created_at DESC, id DESC LIMIT 1`)
|
||||
.get(sessionId) as SessionGoalRow | undefined
|
||||
.prepare(`
|
||||
SELECT ${SESSION_GOAL_COLUMNS} FROM session_goals
|
||||
WHERE server_id = ? AND session_id = ?
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1
|
||||
`)
|
||||
.get(serverId, sessionId) as SessionGoalRow | undefined
|
||||
return row ? mapSessionGoalRow(row) : null
|
||||
}
|
||||
|
||||
@@ -228,6 +243,7 @@ function mapSessionGoalRow(row: SessionGoalRow): SessionGoalRecord {
|
||||
return {
|
||||
id: row.id,
|
||||
sessionId: row.session_id,
|
||||
serverId: row.server_id,
|
||||
directory: row.directory,
|
||||
objective: row.objective,
|
||||
status: row.status,
|
||||
|
||||
@@ -1,38 +1,60 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { SessionPermissionMode } from '@opencode-manager/shared/schemas'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, type SessionPermissionMode } from '@opencode-manager/shared/schemas'
|
||||
|
||||
export function ensureSessionPermissionModesTable(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS session_permission_modes (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
server_id TEXT NOT NULL DEFAULT 'local',
|
||||
mode TEXT NOT NULL CHECK(mode IN ('ask','auto')),
|
||||
updated_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
export function getSessionPermissionMode(db: Database, sessionId: string): SessionPermissionMode | null {
|
||||
export function getSessionPermissionMode(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): SessionPermissionMode | null {
|
||||
const row = db
|
||||
.prepare('SELECT mode FROM session_permission_modes WHERE session_id = ?')
|
||||
.get(sessionId) as { mode: SessionPermissionMode } | undefined
|
||||
.prepare('SELECT mode FROM session_permission_modes WHERE server_id = ? AND session_id = ?')
|
||||
.get(serverId, sessionId) as { mode: SessionPermissionMode } | undefined
|
||||
return row ? row.mode : null
|
||||
}
|
||||
|
||||
export function setSessionPermissionMode(db: Database, sessionId: string, mode: SessionPermissionMode): void {
|
||||
export function setSessionPermissionMode(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
mode: SessionPermissionMode,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): void {
|
||||
db.prepare(`
|
||||
INSERT INTO session_permission_modes(session_id, mode, updated_at)
|
||||
VALUES(?,?,?)
|
||||
ON CONFLICT(session_id) DO UPDATE SET mode=excluded.mode, updated_at=excluded.updated_at
|
||||
`).run(sessionId, mode, Date.now())
|
||||
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,
|
||||
mode=excluded.mode,
|
||||
updated_at=excluded.updated_at
|
||||
`).run(serverId, sessionId, mode, Date.now())
|
||||
}
|
||||
|
||||
export function insertSessionPermissionModeIfAbsent(db: Database, sessionId: string, mode: SessionPermissionMode): void {
|
||||
export function insertSessionPermissionModeIfAbsent(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
mode: SessionPermissionMode,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): void {
|
||||
db.prepare(`
|
||||
INSERT OR IGNORE INTO session_permission_modes(session_id, mode, updated_at)
|
||||
VALUES(?,?,?)
|
||||
`).run(sessionId, mode, Date.now())
|
||||
INSERT OR IGNORE INTO session_permission_modes(server_id, session_id, mode, updated_at)
|
||||
VALUES(?,?,?,?)
|
||||
`).run(serverId, sessionId, mode, Date.now())
|
||||
}
|
||||
|
||||
export function deleteSessionPermissionMode(db: Database, sessionId: string): void {
|
||||
db.prepare('DELETE FROM session_permission_modes WHERE session_id = ?').run(sessionId)
|
||||
export function deleteSessionPermissionMode(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): void {
|
||||
db.prepare('DELETE FROM session_permission_modes WHERE server_id = ? AND session_id = ?').run(serverId, sessionId)
|
||||
}
|
||||
+48
-27
@@ -15,7 +15,7 @@ import { createTTSRoutes, cleanupExpiredCache } from './routes/tts';
|
||||
import { createSTTRoutes } from './routes/stt'
|
||||
import { createFileRoutes } from './routes/files'
|
||||
import { createFilesystemRoutes } from './routes/filesystem'
|
||||
import { createScheduleRoutes } from './routes/schedules'
|
||||
import { createScheduleRoutes, createServerScheduleRoutes } from './routes/schedules'
|
||||
|
||||
async function getAppVersion(): Promise<string> {
|
||||
try {
|
||||
@@ -53,6 +53,10 @@ import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
|
||||
import { createAuthenticatedOpenCodeProxyRoutes } from './routes/opencode-auth-proxy'
|
||||
import { createOpenCodeServerProxyRoutes } from './routes/opencode-server-proxy'
|
||||
import { createOpenCodeServerRoutes } from './routes/opencode-servers'
|
||||
import {
|
||||
createOpenCodeServerTerminalRoutes,
|
||||
createOpenCodeServerTerminalSocketRoutes,
|
||||
} from './routes/opencode-server-terminals'
|
||||
import { sseAggregator } from './services/sse-aggregator'
|
||||
import { RemoteServerEventHub } from './services/remote-server-events'
|
||||
import { ensureDirectoryExists, writeFileContent, fileExists } from './services/file-operations'
|
||||
@@ -93,7 +97,7 @@ import {
|
||||
getTrustedOrigins,
|
||||
ENV
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
import { NotificationEventType } from '@opencode-manager/shared/schemas'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, NotificationEventType } from '@opencode-manager/shared/schemas'
|
||||
|
||||
|
||||
const { PORT, HOST } = ENV.SERVER
|
||||
@@ -250,14 +254,25 @@ try {
|
||||
}
|
||||
|
||||
const terminalService = new TerminalService(
|
||||
openCodeClient,
|
||||
{
|
||||
client: openCodeClient,
|
||||
baseUrl: () => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
|
||||
includeLocalCredentials: true,
|
||||
},
|
||||
new CredentialProvider(db),
|
||||
() => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
|
||||
)
|
||||
const resolveServerTerminalService = (serverId: string): TerminalService => {
|
||||
const connection = opencodeServerRegistry.getConnection(serverId)
|
||||
return terminalService.forTarget({
|
||||
client: opencodeServerRegistry.getClient(serverId),
|
||||
baseUrl: () => connection.baseUrl,
|
||||
includeLocalCredentials: false,
|
||||
})
|
||||
}
|
||||
const gitService = createGitService(gitAuthService)
|
||||
const projectConfigService = new ProjectConfigService(db, gitService, gitAuthService)
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager, opencodeServerRegistry)
|
||||
scheduleService.setWorktreeRemovedHandler(async (directory) => {
|
||||
try {
|
||||
await terminalService.removeAll(directory)
|
||||
@@ -268,37 +283,31 @@ scheduleService.setWorktreeRemovedHandler(async (directory) => {
|
||||
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService, scheduleService)
|
||||
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
|
||||
|
||||
const notificationService = new NotificationService(db)
|
||||
const notificationService = new NotificationService(db, opencodeServerRegistry)
|
||||
const sessionSettingsService = new SettingsService(db)
|
||||
const sessionAncestry = new SessionAncestry(openCodeClient)
|
||||
const sessionPermissionModeService = new SessionPermissionModeService(db, openCodeClient, sessionSettingsService, sessionAncestry)
|
||||
const sessionAncestry = new SessionAncestry((serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const sessionPermissionModeService = new SessionPermissionModeService(db, opencodeServerRegistry, sessionSettingsService, sessionAncestry)
|
||||
const sessionSandboxService = new SessionSandboxService(db, sessionAncestry, sessionSettingsService, {
|
||||
removeSessionSandbox: (rootSessionId) => new SandboxRuntimeService(db).removeSessionSandbox(rootSessionId),
|
||||
})
|
||||
const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSettingsService, {
|
||||
const sessionGoalService = new SessionGoalService(db, opencodeServerRegistry, sessionSettingsService, {
|
||||
onOutcome: (goal) => {
|
||||
void notificationService.notifyGoalOutcome(goal).catch((error) => {
|
||||
logger.error('Goal outcome notification error:', error)
|
||||
})
|
||||
},
|
||||
resolveSessionLock: async (sessionId) =>
|
||||
(await sessionPermissionModeService.getEffectiveMode(sessionId)).lockedReason,
|
||||
resolveSessionLock: async (sessionId, serverId) =>
|
||||
(await sessionPermissionModeService.getEffectiveMode(sessionId, serverId)).lockedReason,
|
||||
})
|
||||
sessionGoalService.loadOpenGoals()
|
||||
|
||||
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService)
|
||||
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService, (serverId) => opencodeServerRegistry.getClient(serverId))
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService, gitService)
|
||||
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
sessionPermissionModeService.handleEvent(directory, event).catch((err) => {
|
||||
logger.error('Session permission mode event handling error:', err)
|
||||
})
|
||||
sessionSandboxService.handleEvent(directory, event).catch((err) => {
|
||||
logger.error('Session sandbox event handling error:', err)
|
||||
})
|
||||
sessionGoalService.handleEvent(directory, event).catch((err) => {
|
||||
logger.error('Session goal event handling error:', err)
|
||||
})
|
||||
try {
|
||||
changeWalkthroughService.handleEvent(event)
|
||||
} catch (err) {
|
||||
@@ -306,12 +315,21 @@ sseAggregator.onEvent((directory, event) => {
|
||||
}
|
||||
})
|
||||
|
||||
notificationService.addEventSuppressor(async (event, sessionId) => {
|
||||
if (event.type !== 'permission.asked' || !sessionId) return false
|
||||
return (await sessionPermissionModeService.getEffectiveMode(sessionId)).mode === 'auto'
|
||||
sseAggregator.onServerEvent((serverId, directory, event) => {
|
||||
sessionPermissionModeService.handleEvent(directory, event, serverId).catch((err) => {
|
||||
logger.error('Session permission mode event handling error:', err)
|
||||
})
|
||||
sessionGoalService.handleEvent(directory, event, serverId).catch((err) => {
|
||||
logger.error('Session goal event handling error:', err)
|
||||
})
|
||||
})
|
||||
|
||||
notificationService.addEventSuppressor(async (event, sessionId) => {
|
||||
notificationService.addEventSuppressor((event, sessionId, serverId) =>
|
||||
sessionPermissionModeService.suppressesPermissionNotification(event, sessionId, serverId),
|
||||
)
|
||||
|
||||
notificationService.addEventSuppressor(async (event, sessionId, serverId) => {
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) return false
|
||||
if (!sessionId) return false
|
||||
if (event.type !== NotificationEventType.SESSION_IDLE && event.type !== NotificationEventType.SESSION_FAILED) return false
|
||||
return getChangeWalkthroughByWalkthroughSession(db, sessionId) !== null
|
||||
@@ -329,8 +347,8 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
|
||||
privateKey: ENV.VAPID.PRIVATE_KEY,
|
||||
subject: ENV.VAPID.SUBJECT || 'mailto:push@localhost',
|
||||
})
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
notificationService.handleSSEEvent(directory, event).catch((err) => {
|
||||
sseAggregator.onServerEvent((serverId, directory, event) => {
|
||||
notificationService.handleSSEEvent(directory, event, serverId).catch((err) => {
|
||||
logger.error('Push notification dispatch error:', err)
|
||||
})
|
||||
})
|
||||
@@ -338,9 +356,9 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
|
||||
|
||||
sseAggregator.setPendingActionsFetcher(openCodeClient)
|
||||
sseAggregator.setPasswordResolver(() => new SettingsService(db).getOpenCodeServerPassword())
|
||||
sseAggregator.onUpstreamConnected(() => {
|
||||
void sessionPermissionModeService.acceptPendingRequestsForActiveSessions().catch((err) => {
|
||||
logger.error('Failed to accept pending permission requests for active sessions:', err)
|
||||
sseAggregator.onServerConnected((serverId) => {
|
||||
void sessionPermissionModeService.acceptPendingRequestsForActiveSessions(serverId).catch((err) => {
|
||||
logger.error(`Failed to accept pending permission requests for server ${serverId}:`, err)
|
||||
})
|
||||
})
|
||||
sseAggregator.start()
|
||||
@@ -387,6 +405,9 @@ protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
|
||||
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
|
||||
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
|
||||
protectedApi.route('/session-pins', createSessionPinRoutes(db))
|
||||
protectedApi.route('/opencode-servers/:serverId/schedules', createServerScheduleRoutes(scheduleService))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalSocketRoutes(resolveServerTerminalService, upgradeWebSocket))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerTerminalRoutes(resolveServerTerminalService))
|
||||
protectedApi.route('/opencode-servers', createOpenCodeServerRoutes(opencodeServerRegistry, () => remoteServerEvents.getStatuses()))
|
||||
protectedApi.route('/session-permission-modes', createSessionPermissionModeRoutes(sessionPermissionModeService))
|
||||
protectedApi.route('/session-sandbox', createSessionSandboxRoutes(sessionSandboxService))
|
||||
|
||||
@@ -47,7 +47,7 @@ export function createInternalRoutes(
|
||||
const app = new Hono()
|
||||
app.use('/*', createInternalTokenMiddleware(db))
|
||||
app.route('/schedules', createScheduleRoutes(scheduleService))
|
||||
app.route('/session-goals', createSessionGoalRoutes(sessionGoals))
|
||||
app.route('/session-goals', createSessionGoalRoutes(sessionGoals, { serverScoped: false }))
|
||||
app.route('/multi-runs', createMultiRunRoutes(multiRuns))
|
||||
app.route('/notifications', createInternalNotificationRoutes(notificationService))
|
||||
app.route('/settings', createInternalSettingsRoutes(settingsService))
|
||||
|
||||
@@ -131,7 +131,7 @@ export function createInternalSessionRoutes(
|
||||
permissionModes.pinAsk(launched.sessionId)
|
||||
|
||||
const url = buildSessionPath(
|
||||
launched.repoId,
|
||||
input.repoId,
|
||||
launched.sessionId,
|
||||
launched.workspaceDirectory ? { repoTab: 'workspaces' } : undefined,
|
||||
)
|
||||
|
||||
@@ -1,16 +1,31 @@
|
||||
import { Hono } from 'hono'
|
||||
import { FuseMultiRunRequestSchema, LaunchMultiRunRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
FuseMultiRunRequestSchema,
|
||||
LaunchMultiRunRequestSchema,
|
||||
type MultiRunTarget,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { MultiRunError, type MultiRunService } from '../services/multi-runs'
|
||||
import { handleServiceError, parseId, parseJsonBody } from '../utils/route-helpers'
|
||||
import { ServiceError } from '../utils/service-error'
|
||||
|
||||
function listTarget(repoId: string | undefined, serverId: string | undefined, directory: string | undefined): MultiRunTarget {
|
||||
if (serverId) {
|
||||
if (!directory) {
|
||||
throw new MultiRunError('Missing directory', 400)
|
||||
}
|
||||
return { kind: 'server', serverId, directory }
|
||||
}
|
||||
|
||||
return { kind: 'repo', repoId: parseId(repoId, 'repoId', MultiRunError) }
|
||||
}
|
||||
|
||||
export function createMultiRunRoutes(service: MultiRunService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
try {
|
||||
const repoId = parseId(c.req.query('repoId'), 'repoId', MultiRunError)
|
||||
return c.json({ runs: service.list(repoId) })
|
||||
const target = listTarget(c.req.query('repoId'), c.req.query('serverId'), c.req.query('directory'))
|
||||
return c.json({ runs: service.list(target) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to list multi-runs', ServiceError)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context, MiddlewareHandler } from 'hono'
|
||||
import type { UpgradeWebSocket } from 'hono/ws'
|
||||
import { getTrustedOrigins } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
CreateTerminalRequestSchema,
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
ResizeTerminalRequestSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { OpenCodeServerError } from '../services/opencode-server-registry'
|
||||
import { TerminalNotFoundError, type TerminalService } from '../services/terminal'
|
||||
import { parseTerminalCursor } from '../utils/terminal-cursor'
|
||||
import { createBridgedSocketEvents, isAllowedUpgradeOrigin } from '../utils/websocket-bridge'
|
||||
import { handleOpenCodeError, handleServiceError, parseJsonBody } from '../utils/route-helpers'
|
||||
|
||||
export type ServerTerminalServiceResolver = (serverId: string) => TerminalService
|
||||
|
||||
interface ServerTerminalSocketVariables {
|
||||
terminalService: TerminalService
|
||||
terminalDirectory: string
|
||||
terminalCursor: number | undefined
|
||||
}
|
||||
|
||||
function isAbsoluteDirectory(directory: string): boolean {
|
||||
return directory.startsWith('/') || /^[A-Za-z]:[\\/]/.test(directory)
|
||||
}
|
||||
|
||||
function readAbsoluteDirectory(raw: string | undefined): string | null {
|
||||
if (raw === undefined) return null
|
||||
const directory = raw.trim()
|
||||
return directory.length > 0 && isAbsoluteDirectory(directory) ? directory : null
|
||||
}
|
||||
|
||||
function rejectLocalServer(c: Context, serverId: string): Response | null {
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) return null
|
||||
return c.json({ error: 'Local terminals are served by the repo terminal routes' }, 400)
|
||||
}
|
||||
|
||||
function rejectDirectory(c: Context): Response {
|
||||
return c.json({ error: 'An absolute directory is required' }, 400)
|
||||
}
|
||||
|
||||
function handleTerminalError(c: Context, error: unknown) {
|
||||
if (error instanceof TerminalNotFoundError) {
|
||||
return c.json({ error: error.message }, 404)
|
||||
}
|
||||
if (error instanceof OpenCodeServerError) {
|
||||
return handleServiceError(c, error, 'Terminal request failed', OpenCodeServerError)
|
||||
}
|
||||
return handleOpenCodeError(c, error, 'Terminal request failed')
|
||||
}
|
||||
|
||||
export function createOpenCodeServerTerminalRoutes(resolveTerminalService: ServerTerminalServiceResolver) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/:serverId/terminals', async (c) => {
|
||||
const serverId = c.req.param('serverId')
|
||||
const local = rejectLocalServer(c, serverId)
|
||||
if (local) return local
|
||||
|
||||
const directory = readAbsoluteDirectory(c.req.query('directory'))
|
||||
if (directory === null) return rejectDirectory(c)
|
||||
|
||||
try {
|
||||
const terminals = await resolveTerminalService(serverId).list(directory)
|
||||
return c.json({ terminals })
|
||||
} catch (error: unknown) {
|
||||
return handleTerminalError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:serverId/terminals', async (c) => {
|
||||
const serverId = c.req.param('serverId')
|
||||
const local = rejectLocalServer(c, serverId)
|
||||
if (local) return local
|
||||
|
||||
const parsed = await parseJsonBody(c, CreateTerminalRequestSchema, { allowEmpty: true })
|
||||
if (!parsed.ok) return parsed.response
|
||||
|
||||
const directory = readAbsoluteDirectory(parsed.data.directory)
|
||||
if (directory === null) return rejectDirectory(c)
|
||||
|
||||
try {
|
||||
const terminal = await resolveTerminalService(serverId).create(directory, {
|
||||
kind: 'shell',
|
||||
name: parsed.data.title ?? 'Terminal',
|
||||
})
|
||||
return c.json(terminal)
|
||||
} catch (error: unknown) {
|
||||
return handleTerminalError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
app.patch('/:serverId/terminals/:ptyID', async (c) => {
|
||||
const serverId = c.req.param('serverId')
|
||||
const local = rejectLocalServer(c, serverId)
|
||||
if (local) return local
|
||||
|
||||
const parsed = await parseJsonBody(c, ResizeTerminalRequestSchema)
|
||||
if (!parsed.ok) return parsed.response
|
||||
|
||||
const directory = readAbsoluteDirectory(parsed.data.directory)
|
||||
if (directory === null) return rejectDirectory(c)
|
||||
|
||||
const ptyID = c.req.param('ptyID')
|
||||
|
||||
try {
|
||||
const terminalService = resolveTerminalService(serverId)
|
||||
await terminalService.requireTerminal(directory, ptyID)
|
||||
await terminalService.resize(directory, ptyID, { cols: parsed.data.cols, rows: parsed.data.rows })
|
||||
return c.json({ success: true })
|
||||
} catch (error: unknown) {
|
||||
return handleTerminalError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:serverId/terminals/:ptyID', async (c) => {
|
||||
const serverId = c.req.param('serverId')
|
||||
const local = rejectLocalServer(c, serverId)
|
||||
if (local) return local
|
||||
|
||||
const directory = readAbsoluteDirectory(c.req.query('directory'))
|
||||
if (directory === null) return rejectDirectory(c)
|
||||
|
||||
const ptyID = c.req.param('ptyID')
|
||||
|
||||
try {
|
||||
const terminalService = resolveTerminalService(serverId)
|
||||
await terminalService.requireTerminal(directory, ptyID)
|
||||
await terminalService.remove(directory, ptyID)
|
||||
return c.json({ success: true })
|
||||
} catch (error: unknown) {
|
||||
return handleTerminalError(c, error)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
export function createOpenCodeServerTerminalSocketRoutes(
|
||||
resolveTerminalService: ServerTerminalServiceResolver,
|
||||
upgradeWebSocket: UpgradeWebSocket,
|
||||
trustedOrigins: readonly string[] = getTrustedOrigins(),
|
||||
) {
|
||||
const app = new Hono<{ Variables: ServerTerminalSocketVariables }>()
|
||||
|
||||
const validate: MiddlewareHandler<{ Variables: ServerTerminalSocketVariables }> = async (c, next) => {
|
||||
if (!isAllowedUpgradeOrigin(c.req.header('origin'), trustedOrigins)) {
|
||||
return c.json({ error: 'Origin not allowed' }, 403)
|
||||
}
|
||||
|
||||
const serverId = c.req.param('serverId') ?? ''
|
||||
const local = rejectLocalServer(c, serverId)
|
||||
if (local) return local
|
||||
|
||||
const cursor = parseTerminalCursor(c.req.query('cursor'))
|
||||
if (cursor === null) {
|
||||
return c.json({ error: 'Invalid cursor' }, 400)
|
||||
}
|
||||
|
||||
const directory = readAbsoluteDirectory(c.req.query('directory'))
|
||||
if (directory === null) return rejectDirectory(c)
|
||||
|
||||
try {
|
||||
c.set('terminalService', resolveTerminalService(serverId))
|
||||
} catch (error: unknown) {
|
||||
return handleTerminalError(c, error)
|
||||
}
|
||||
|
||||
c.set('terminalDirectory', directory)
|
||||
c.set('terminalCursor', cursor)
|
||||
await next()
|
||||
}
|
||||
|
||||
app.get(
|
||||
'/:serverId/terminals/:ptyID/connect',
|
||||
validate,
|
||||
upgradeWebSocket((c) => {
|
||||
const terminalService = c.get('terminalService')
|
||||
const directory = c.get('terminalDirectory')
|
||||
const cursor = c.get('terminalCursor')
|
||||
const ptyID = c.req.param('ptyID')
|
||||
|
||||
return createBridgedSocketEvents((peer) => terminalService.connect(directory, ptyID, cursor, peer))
|
||||
}),
|
||||
)
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import type { GitAuthService } from '../services/git-auth'
|
||||
import type { OpenCodeClient } from '../services/opencode/client'
|
||||
import type { TerminalService } from '../services/terminal'
|
||||
import { createBridgedSocketEvents, isAllowedUpgradeOrigin } from '../utils/websocket-bridge'
|
||||
import { parseTerminalCursor } from '../utils/terminal-cursor'
|
||||
import { resolveRepoRequestDirectory } from './repo-directory'
|
||||
|
||||
interface RepoTerminalSocketVariables {
|
||||
@@ -14,14 +15,6 @@ interface RepoTerminalSocketVariables {
|
||||
terminalCursor: number | undefined
|
||||
}
|
||||
|
||||
function parseCursor(raw: string | undefined): number | undefined | null {
|
||||
if (raw === undefined) return undefined
|
||||
if (!/^-?\d+$/.test(raw)) return null
|
||||
const parsed = Number(raw)
|
||||
if (!Number.isSafeInteger(parsed) || parsed < -1) return null
|
||||
return parsed
|
||||
}
|
||||
|
||||
export function createRepoTerminalSocketRoutes(
|
||||
database: Database,
|
||||
gitAuthService: GitAuthService,
|
||||
@@ -38,7 +31,7 @@ export function createRepoTerminalSocketRoutes(
|
||||
return c.json({ error: 'Origin not allowed' }, 403)
|
||||
}
|
||||
|
||||
const cursor = parseCursor(c.req.query('cursor'))
|
||||
const cursor = parseTerminalCursor(c.req.query('cursor'))
|
||||
if (cursor === null) {
|
||||
return c.json({ error: 'Invalid cursor' }, 400)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,13 @@ import type { ScheduleRunWorktreesMode } from '@opencode-manager/shared/types'
|
||||
import { ScheduleService, ScheduleServiceError } from '../services/schedules'
|
||||
import { parseId, handleServiceError } from '../utils/route-helpers'
|
||||
|
||||
function parseServerId(value: string | undefined): string {
|
||||
if (!value) {
|
||||
throw new ScheduleServiceError('OpenCode server id is required', 400)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function parseRunListLimit(value: string | undefined): number {
|
||||
if (value === undefined) {
|
||||
return 20
|
||||
@@ -270,4 +277,133 @@ export function createScheduleRoutes(scheduleService: ScheduleService) {
|
||||
return app
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule routes for a project directory on a linked OpenCode server. They mirror the
|
||||
* repo routes without worktree endpoints, because remote runs execute in place.
|
||||
*/
|
||||
export function createServerScheduleRoutes(scheduleService: ScheduleService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
try {
|
||||
return c.json({ jobs: scheduleService.listServerJobs(parseServerId(c.req.param('serverId'))) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to list schedules', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/', async (c) => {
|
||||
try {
|
||||
const serverId = parseServerId(c.req.param('serverId'))
|
||||
const body = await c.req.json()
|
||||
const input = CreateScheduleJobRequestSchema.parse(body)
|
||||
if (!input.directory) {
|
||||
throw new ScheduleServiceError('A remote schedule requires an absolute target directory', 400)
|
||||
}
|
||||
const job = await scheduleService.createServerJob(serverId, input.directory, input)
|
||||
return c.json({ job }, 201)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to create schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:jobId', (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const job = scheduleService.getServerJob(parseServerId(c.req.param('serverId')), jobId)
|
||||
if (!job) {
|
||||
return c.json({ error: 'Schedule not found' }, 404)
|
||||
}
|
||||
return c.json({ job })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to get schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.patch('/:jobId', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const body = await c.req.json()
|
||||
const input = UpdateScheduleJobRequestSchema.parse(body)
|
||||
const job = await scheduleService.updateServerJob(parseServerId(c.req.param('serverId')), jobId, input)
|
||||
return c.json({ job })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to update schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:jobId', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
await scheduleService.deleteServerJob(parseServerId(c.req.param('serverId')), jobId)
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to delete schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:jobId/run', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const run = await scheduleService.runServerJob(parseServerId(c.req.param('serverId')), jobId, 'manual')
|
||||
return c.json({ run })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to run schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:jobId/runs', (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const limit = parseRunListLimit(c.req.query('limit'))
|
||||
return c.json({ runs: scheduleService.listServerRuns(parseServerId(c.req.param('serverId')), jobId, limit) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to list schedule runs', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:jobId/runs/:runId', (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const runId = parseId(c.req.param('runId'), 'run id', ScheduleServiceError)
|
||||
return c.json({ run: scheduleService.getServerRun(parseServerId(c.req.param('serverId')), jobId, runId) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to get schedule run', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:jobId/runs/:runId/cancel', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const runId = parseId(c.req.param('runId'), 'run id', ScheduleServiceError)
|
||||
const run = await scheduleService.cancelServerRun(parseServerId(c.req.param('serverId')), jobId, runId)
|
||||
return c.json({ run })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to cancel schedule run', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:jobId/runs', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
return c.json(await scheduleService.clearServerRunHistory(parseServerId(c.req.param('serverId')), jobId))
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to clear schedule run history', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:jobId/runs/:runId', async (c) => {
|
||||
try {
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const runId = parseId(c.req.param('runId'), 'run id', ScheduleServiceError)
|
||||
await scheduleService.deleteServerRun(parseServerId(c.req.param('serverId')), jobId, runId)
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to delete schedule run', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,15 @@ import { StartSessionGoalRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { SessionGoalError, type SessionGoalService } from '../services/session-goals'
|
||||
import { handleServiceError, parseId, parseJsonBody } from '../utils/route-helpers'
|
||||
|
||||
export function createSessionGoalRoutes(service: SessionGoalService) {
|
||||
export interface SessionGoalRouteOptions {
|
||||
serverScoped?: boolean
|
||||
}
|
||||
|
||||
export function createSessionGoalRoutes(
|
||||
service: SessionGoalService,
|
||||
options: SessionGoalRouteOptions = {},
|
||||
) {
|
||||
const serverScoped = options.serverScoped ?? true
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/', (c) => {
|
||||
@@ -12,7 +20,8 @@ export function createSessionGoalRoutes(service: SessionGoalService) {
|
||||
if (!sessionId) {
|
||||
return c.json({ error: 'Invalid request' }, 400)
|
||||
}
|
||||
return c.json({ goal: service.getLatest(sessionId) })
|
||||
const serverId = serverScoped ? c.req.query('serverId') : undefined
|
||||
return c.json({ goal: serverId ? service.getLatest(sessionId, serverId) : service.getLatest(sessionId) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to read session goal', SessionGoalError)
|
||||
}
|
||||
@@ -25,7 +34,7 @@ export function createSessionGoalRoutes(service: SessionGoalService) {
|
||||
}
|
||||
|
||||
try {
|
||||
const goal = await service.start(parsed.data)
|
||||
const goal = await service.start(serverScoped ? parsed.data : { ...parsed.data, serverId: undefined })
|
||||
return c.json({ goal }, 201)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to start session goal', SessionGoalError)
|
||||
|
||||
@@ -8,7 +8,10 @@ export function createSessionPermissionModeRoutes(service: SessionPermissionMode
|
||||
|
||||
app.get('/:sessionId', async (c) => {
|
||||
try {
|
||||
const state = await service.getEffectiveMode(c.req.param('sessionId'))
|
||||
const state = await service.getEffectiveMode(
|
||||
c.req.param('sessionId'),
|
||||
c.req.query('serverId') || undefined,
|
||||
)
|
||||
return c.json(state)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to read session permission mode', SessionPermissionModeError)
|
||||
@@ -22,7 +25,12 @@ export function createSessionPermissionModeRoutes(service: SessionPermissionMode
|
||||
}
|
||||
|
||||
try {
|
||||
const state = await service.setMode(c.req.param('sessionId'), parsed.data.mode, parsed.data.directory)
|
||||
const state = await service.setMode(
|
||||
c.req.param('sessionId'),
|
||||
parsed.data.mode,
|
||||
parsed.data.directory,
|
||||
parsed.data.serverId,
|
||||
)
|
||||
return c.json(state)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to set session permission mode', SessionPermissionModeError)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Hono } from 'hono'
|
||||
import { stream } from 'hono/streaming'
|
||||
import { sseAggregator } from '../services/sse-aggregator'
|
||||
import { SSESubscribeSchema, SSEVisibilitySchema } from '@opencode-manager/shared/schemas'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, SSESubscribeSchema, SSEVisibilitySchema } from '@opencode-manager/shared/schemas'
|
||||
import { logger } from '../utils/logger'
|
||||
import { DEFAULTS } from '@opencode-manager/shared/config'
|
||||
import { createQueuedSSEWriter } from './sse-writer'
|
||||
@@ -92,7 +92,12 @@ export function createSSERoutes() {
|
||||
if (!result.success) {
|
||||
return c.json({ success: false, error: 'Invalid request', details: result.error.issues }, 400)
|
||||
}
|
||||
const success = sseAggregator.setClientVisibility(result.data.clientId, result.data.visible, result.data.activeSessionId ?? null)
|
||||
const success = sseAggregator.setClientVisibility(
|
||||
result.data.clientId,
|
||||
result.data.visible,
|
||||
result.data.activeSessionId ?? null,
|
||||
result.data.activeServerId ?? LOCAL_OPENCODE_SERVER_ID,
|
||||
)
|
||||
if (!success) {
|
||||
return c.json({ success: false, error: 'Client not found' }, 404)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { existsSync } from 'node:fs'
|
||||
import type { FuseMultiRunRequest, LaunchMultiRunRequest, MultiRun } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type FuseMultiRunRequest,
|
||||
type LaunchMultiRunRequest,
|
||||
type MultiRun,
|
||||
type MultiRunTarget,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import {
|
||||
createMultiRunWithEntries,
|
||||
@@ -16,7 +22,6 @@ import {
|
||||
type MultiRunRecord,
|
||||
} from '../db/multi-runs'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import type { Repo } from '../types/repo'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { ServiceError } from '../utils/service-error'
|
||||
@@ -24,7 +29,15 @@ import { buildFusionPrompt, buildFusionSourcePermissionRuleset, collectFusionSou
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { RepoWorkspaceError } from './repo'
|
||||
import type { RepoWorkspaceService } from './repo-workspace'
|
||||
import { requireReadyRepo, SessionLauncher, SessionLaunchError, type LaunchedSession } from './session-launcher'
|
||||
import {
|
||||
resolveSessionTarget,
|
||||
SessionLauncher,
|
||||
SessionLaunchError,
|
||||
sessionTargetInput,
|
||||
sessionTargetOfRun,
|
||||
type LaunchedSession,
|
||||
type ResolvedSessionTarget,
|
||||
} from './session-launcher'
|
||||
import type { SessionPermissionModeService } from './session-permission-modes'
|
||||
|
||||
const MULTI_RUN_LIST_LIMIT = 20
|
||||
@@ -35,6 +48,8 @@ function toMultiRun(record: MultiRunRecord): MultiRun {
|
||||
return {
|
||||
id: record.id,
|
||||
repoId: record.repoId,
|
||||
serverId: record.serverId,
|
||||
directory: record.directory,
|
||||
name: record.name,
|
||||
prompt: record.prompt,
|
||||
isolated: record.isolated,
|
||||
@@ -69,6 +84,22 @@ function toMultiRun(record: MultiRunRecord): MultiRun {
|
||||
}
|
||||
}
|
||||
|
||||
function multiRunTargetFromRequest(
|
||||
request: Pick<LaunchMultiRunRequest, 'repoId' | 'serverId' | 'directory'>,
|
||||
): MultiRunTarget {
|
||||
if (request.serverId !== undefined) {
|
||||
if (request.directory === undefined) {
|
||||
throw new MultiRunError('A server multi-run needs a directory', 400)
|
||||
}
|
||||
return { kind: 'server', serverId: request.serverId, directory: request.directory }
|
||||
}
|
||||
|
||||
if (request.repoId === undefined) {
|
||||
throw new MultiRunError('A multi-run needs a repository or server target', 400)
|
||||
}
|
||||
return { kind: 'repo', repoId: request.repoId }
|
||||
}
|
||||
|
||||
export class MultiRunService {
|
||||
private readonly sessionLauncher: SessionLauncher
|
||||
private readonly discardingEntries = new Set<number>()
|
||||
@@ -78,22 +109,21 @@ export class MultiRunService {
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
private readonly repoWorkspaces: RepoWorkspaceService,
|
||||
private readonly permissionModes: SessionPermissionModeService,
|
||||
private readonly getServerClient?: (serverId: string) => OpenCodeClient,
|
||||
) {
|
||||
this.sessionLauncher = new SessionLauncher(db, openCodeClient, repoWorkspaces)
|
||||
this.sessionLauncher = new SessionLauncher(db, openCodeClient, repoWorkspaces, getServerClient)
|
||||
}
|
||||
|
||||
async launch(request: LaunchMultiRunRequest): Promise<MultiRun> {
|
||||
let repo: Repo
|
||||
try {
|
||||
repo = requireReadyRepo(this.db, request.repoId)
|
||||
} catch (error) {
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Repository unavailable', 404)
|
||||
}
|
||||
const target = multiRunTargetFromRequest(request)
|
||||
const resolved = await this.resolveTarget(target)
|
||||
|
||||
const record = createMultiRunWithEntries(
|
||||
this.db,
|
||||
{
|
||||
repoId: request.repoId,
|
||||
repoId: target.kind === 'repo' ? target.repoId : null,
|
||||
serverId: target.kind === 'server' ? target.serverId : LOCAL_OPENCODE_SERVER_ID,
|
||||
directory: target.kind === 'server' ? target.directory : null,
|
||||
name: request.name,
|
||||
prompt: request.prompt,
|
||||
isolated: request.isolate,
|
||||
@@ -105,7 +135,7 @@ export class MultiRunService {
|
||||
const validations = await Promise.all(
|
||||
record.entries.map(async (entry) => {
|
||||
try {
|
||||
await this.sessionLauncher.resolveModel(repo, entry.model)
|
||||
await resolved.resolveModel(entry.model)
|
||||
return { entry, ok: true as const }
|
||||
} catch (error) {
|
||||
return { entry, ok: false as const, error }
|
||||
@@ -127,7 +157,7 @@ export class MultiRunService {
|
||||
})
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
launchable.map(({ entry, index }) => this.launchEntry(entry, index, request)),
|
||||
launchable.map(({ entry, index }) => this.launchEntry(entry, index, request, target)),
|
||||
)
|
||||
|
||||
results.forEach((result, resultIndex) => {
|
||||
@@ -174,12 +204,11 @@ export class MultiRunService {
|
||||
})
|
||||
}
|
||||
|
||||
let repo: Repo
|
||||
try {
|
||||
repo = requireReadyRepo(this.db, record.repoId)
|
||||
} catch (error) {
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Repository unavailable', 404)
|
||||
const target = sessionTargetOfRun(record)
|
||||
if (!target) {
|
||||
throw new MultiRunError('Multi-run target is no longer available', 409)
|
||||
}
|
||||
const resolved = await this.resolveTarget(target)
|
||||
|
||||
const entriesById = new Map(record.entries.map((entry) => [entry.id, entry]))
|
||||
const selectedEntries = request.entryIds.map((entryId) => {
|
||||
@@ -197,7 +226,7 @@ export class MultiRunService {
|
||||
)
|
||||
|
||||
try {
|
||||
await this.sessionLauncher.resolveModel(repo, request.model)
|
||||
await resolved.resolveModel(request.model)
|
||||
} catch (error) {
|
||||
if (error instanceof SessionLaunchError) {
|
||||
throw new MultiRunError(error.message, error.status)
|
||||
@@ -205,9 +234,9 @@ export class MultiRunService {
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Failed to resolve model', 502)
|
||||
}
|
||||
|
||||
await this.reconcileUncertainFusions(record)
|
||||
await this.reconcileUncertainFusions(record, resolved.client)
|
||||
|
||||
const collection = await collectFusionSources(this.openCodeClient, selectedEntries)
|
||||
const collection = await collectFusionSources(resolved.client, selectedEntries)
|
||||
if (collection.unavailable.length > 0) {
|
||||
throw new MultiRunError('Some selected results are not ready to fuse', 409, {
|
||||
code: 'FUSION_SOURCES_UNAVAILABLE',
|
||||
@@ -239,7 +268,7 @@ export class MultiRunService {
|
||||
let launched: LaunchedSession | null = null
|
||||
try {
|
||||
launched = await this.sessionLauncher.launch({
|
||||
repoId: record.repoId,
|
||||
...sessionTargetInput(target),
|
||||
prompt: built.prompt,
|
||||
model: request.model,
|
||||
title: `${record.name} · fusion`,
|
||||
@@ -269,7 +298,11 @@ export class MultiRunService {
|
||||
|
||||
if (launched) {
|
||||
try {
|
||||
await this.permissionModes.applyDefaultMode(launched.sessionId, launched.directory)
|
||||
await this.permissionModes.applyDefaultMode(
|
||||
launched.sessionId,
|
||||
launched.directory,
|
||||
target.kind === 'server' ? target.serverId : LOCAL_OPENCODE_SERVER_ID,
|
||||
)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to apply the default permission mode to fusion session ${launched.sessionId}:`, error)
|
||||
}
|
||||
@@ -278,8 +311,8 @@ export class MultiRunService {
|
||||
return { run: this.reload(multiRunId), created: true }
|
||||
}
|
||||
|
||||
list(repoId: number): MultiRun[] {
|
||||
return listMultiRuns(this.db, repoId, MULTI_RUN_LIST_LIMIT).map(toMultiRun)
|
||||
list(target: MultiRunTarget): MultiRun[] {
|
||||
return listMultiRuns(this.db, target, MULTI_RUN_LIST_LIMIT).map(toMultiRun)
|
||||
}
|
||||
|
||||
async discard(multiRunId: number, entryId: number): Promise<MultiRun> {
|
||||
@@ -303,18 +336,8 @@ export class MultiRunService {
|
||||
this.discardingEntries.add(entryId)
|
||||
|
||||
try {
|
||||
if (entry.isolated && entry.directory && existsSync(entry.directory)) {
|
||||
const repo = getRepoById(this.db, record.repoId)
|
||||
if (!repo) {
|
||||
throw new MultiRunError('Repository not found', 404)
|
||||
}
|
||||
|
||||
try {
|
||||
await this.repoWorkspaces.remove(repo, entry.directory)
|
||||
} catch (error) {
|
||||
const status = error instanceof RepoWorkspaceError ? error.status : 502
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Failed to remove workspace', status)
|
||||
}
|
||||
if (entry.isolated && entry.directory) {
|
||||
await this.removeEntryWorkspace(record, entry.directory)
|
||||
}
|
||||
|
||||
const updated = updateMultiRunEntry(this.db, entryId, ['started', 'failed'], { status: 'discarded' })
|
||||
@@ -328,13 +351,69 @@ export class MultiRunService {
|
||||
}
|
||||
}
|
||||
|
||||
private async removeEntryWorkspace(record: MultiRunRecord, directory: string): Promise<void> {
|
||||
const target = sessionTargetOfRun(record)
|
||||
if (!target) {
|
||||
throw new MultiRunError('Multi-run target is no longer available', 409)
|
||||
}
|
||||
|
||||
if (target.kind === 'repo') {
|
||||
if (!existsSync(directory)) {
|
||||
return
|
||||
}
|
||||
|
||||
const repo = getRepoById(this.db, target.repoId)
|
||||
if (!repo) {
|
||||
throw new MultiRunError('Repository not found', 404)
|
||||
}
|
||||
|
||||
try {
|
||||
await this.repoWorkspaces.remove(repo, directory)
|
||||
} catch (error) {
|
||||
const status = error instanceof RepoWorkspaceError ? error.status : 502
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Failed to remove workspace', status)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const resolved = await this.resolveTarget(target)
|
||||
await resolved.removeWorkspace(directory)
|
||||
} catch (error) {
|
||||
if (error instanceof MultiRunError) {
|
||||
throw error
|
||||
}
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Failed to remove workspace', 502)
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveTarget(target: MultiRunTarget): Promise<ResolvedSessionTarget> {
|
||||
try {
|
||||
return await resolveSessionTarget(
|
||||
{
|
||||
db: this.db,
|
||||
openCodeClient: this.openCodeClient,
|
||||
repoWorkspaces: this.repoWorkspaces,
|
||||
...(this.getServerClient ? { getServerClient: this.getServerClient } : {}),
|
||||
},
|
||||
target,
|
||||
)
|
||||
} catch (error) {
|
||||
if (error instanceof SessionLaunchError || error instanceof ServiceError) {
|
||||
throw new MultiRunError(error.message, error.status)
|
||||
}
|
||||
throw new MultiRunError(getErrorMessage(error) || 'Multi-run target is unavailable', 502)
|
||||
}
|
||||
}
|
||||
|
||||
private async launchEntry(
|
||||
entry: MultiRunEntryRecord,
|
||||
index: number,
|
||||
request: LaunchMultiRunRequest,
|
||||
target: MultiRunTarget,
|
||||
): Promise<LaunchedSession> {
|
||||
return this.sessionLauncher.launch({
|
||||
repoId: request.repoId,
|
||||
...sessionTargetInput(target),
|
||||
prompt: request.prompt,
|
||||
model: entry.model,
|
||||
title: `${request.name} · ${entry.model}`,
|
||||
@@ -345,7 +424,7 @@ export class MultiRunService {
|
||||
})
|
||||
}
|
||||
|
||||
private async reconcileUncertainFusions(record: MultiRunRecord): Promise<void> {
|
||||
private async reconcileUncertainFusions(record: MultiRunRecord, client: OpenCodeClient): Promise<void> {
|
||||
const uncertain = record.fusions.filter(
|
||||
(fusion): fusion is MultiRunFusionRecord & { sessionId: string } =>
|
||||
fusion.status === 'failed' && fusion.sessionId !== null,
|
||||
@@ -358,7 +437,7 @@ export class MultiRunService {
|
||||
await Promise.all(
|
||||
uncertain.map(async (fusion) => {
|
||||
try {
|
||||
const response = await this.openCodeClient.api.message.list({
|
||||
const response = await client.api.message.list({
|
||||
sessionID: fusion.sessionId,
|
||||
type: 'user',
|
||||
order: 'asc',
|
||||
|
||||
@@ -9,6 +9,8 @@ import type {
|
||||
import {
|
||||
NotificationEventType,
|
||||
DEFAULT_NOTIFICATION_PREFERENCES,
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type OpenCodeServer,
|
||||
type SessionGoal,
|
||||
} from "@opencode-manager/shared/schemas";
|
||||
import {
|
||||
@@ -23,10 +25,14 @@ import { sseAggregator, type SSEEvent } from "./sse-aggregator";
|
||||
import { getRepoName } from "../db/queries";
|
||||
import { getScheduleRunBySessionId } from "../db/schedules";
|
||||
import type { Repo } from "../types/repo";
|
||||
import { buildSessionPath } from "@opencode-manager/shared/utils";
|
||||
import { buildServerSessionPath, buildSessionPath } from "@opencode-manager/shared/utils";
|
||||
import { sessionIDFromEvent } from "@opencode-manager/shared/opencode";
|
||||
import { resolveRepoForDirectory } from "./repo";
|
||||
|
||||
export interface NotificationServerRegistry {
|
||||
get(serverId: string): Pick<OpenCodeServer, "name" | "enabled"> | null;
|
||||
}
|
||||
|
||||
interface VapidConfig {
|
||||
publicKey: string;
|
||||
privateKey: string;
|
||||
@@ -123,6 +129,8 @@ export function buildEventNotificationPayload(
|
||||
context: {
|
||||
repoName?: string;
|
||||
repoId?: number;
|
||||
serverId?: string;
|
||||
serverName?: string;
|
||||
sessionId?: string;
|
||||
directory?: string;
|
||||
url: string;
|
||||
@@ -134,8 +142,9 @@ export function buildEventNotificationPayload(
|
||||
const title = config.titleFn(event.data);
|
||||
|
||||
const detail = config.bodyFn(event.data);
|
||||
const rawBody = context.repoName
|
||||
? `${context.repoName} · ${detail}`
|
||||
const displayName = context.repoName ?? context.serverName;
|
||||
const rawBody = displayName
|
||||
? `${displayName} · ${detail}`
|
||||
: detail;
|
||||
const body = truncateWithEllipsis(rawBody, MAX_BODY_LENGTH);
|
||||
|
||||
@@ -151,19 +160,28 @@ export function buildEventNotificationPayload(
|
||||
directory: context.directory,
|
||||
repoId: context.repoId,
|
||||
repoName: context.repoName,
|
||||
serverId: context.serverId,
|
||||
serverName: context.serverName,
|
||||
url: context.url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
type EventSuppressor = (event: SSEEvent, sessionId: string | undefined) => Promise<boolean>;
|
||||
type EventSuppressor = (
|
||||
event: SSEEvent,
|
||||
sessionId: string | undefined,
|
||||
serverId: string
|
||||
) => Promise<boolean>;
|
||||
|
||||
export class NotificationService {
|
||||
private vapidConfig: VapidConfig | null = null;
|
||||
private settingsService: SettingsService;
|
||||
private eventSuppressors: EventSuppressor[] = [];
|
||||
|
||||
constructor(private db: Database) {
|
||||
constructor(
|
||||
private db: Database,
|
||||
private serverRegistry: NotificationServerRegistry | null = null
|
||||
) {
|
||||
this.settingsService = new SettingsService(db);
|
||||
this.initializePushSubscriptionsTable();
|
||||
}
|
||||
@@ -335,17 +353,29 @@ export class NotificationService {
|
||||
|
||||
async handleSSEEvent(
|
||||
directory: string | null,
|
||||
event: SSEEvent
|
||||
event: SSEEvent,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID
|
||||
): Promise<void> {
|
||||
const config = EVENT_CONFIG[event.type];
|
||||
if (!config) return;
|
||||
|
||||
const sessionId = resolveEventSessionId(event);
|
||||
if (sessionId && sseAggregator.isSessionBeingViewed(sessionId)) return;
|
||||
if (sessionId && sseAggregator.isSubagentSession(sessionId)) return;
|
||||
if (sessionId && sseAggregator.isSessionBeingViewed(sessionId, serverId)) return;
|
||||
if (sessionId && sseAggregator.isSubagentSession(sessionId, serverId)) return;
|
||||
|
||||
for (const suppressor of this.eventSuppressors) {
|
||||
if (await suppressor(event, sessionId)) return;
|
||||
if (await suppressor(event, sessionId, serverId)) return;
|
||||
}
|
||||
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) {
|
||||
await this.deliverRemoteEvent(
|
||||
serverId,
|
||||
directory,
|
||||
event,
|
||||
sessionId,
|
||||
config.preferencesKey
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const repo = directory ? await resolveRepoForDirectory(this.db, directory) : null;
|
||||
@@ -371,19 +401,53 @@ export class NotificationService {
|
||||
);
|
||||
}
|
||||
|
||||
private async deliverRemoteEvent(
|
||||
serverId: string,
|
||||
directory: string | null,
|
||||
event: SSEEvent,
|
||||
sessionId: string | undefined,
|
||||
preferencesKey: keyof typeof DEFAULT_NOTIFICATION_PREFERENCES.events
|
||||
): Promise<void> {
|
||||
const server = this.serverRegistry?.get(serverId) ?? null;
|
||||
if (!server || !server.enabled) return;
|
||||
|
||||
const url = sessionId
|
||||
? buildServerSessionPath(serverId, sessionId)
|
||||
: `/servers/${encodeURIComponent(serverId)}`;
|
||||
|
||||
const payload = buildEventNotificationPayload(event, {
|
||||
serverId,
|
||||
serverName: server.name,
|
||||
sessionId,
|
||||
directory: directory ?? undefined,
|
||||
url,
|
||||
});
|
||||
if (!payload) return;
|
||||
|
||||
await this.deliverToSubscribers(
|
||||
payload,
|
||||
(preferences) =>
|
||||
preferences.enabled &&
|
||||
preferences.events[preferencesKey] === true
|
||||
);
|
||||
}
|
||||
|
||||
async notifyGoalOutcome(goal: SessionGoal): Promise<void> {
|
||||
if (goal.stopReason === "turn_error") return;
|
||||
if (goal.stopReason === "cancelled" || goal.stopReason === "user_paused") return;
|
||||
if (sseAggregator.isSessionBeingViewed(goal.sessionId)) return;
|
||||
if (sseAggregator.isSessionBeingViewed(goal.sessionId, goal.serverId)) return;
|
||||
|
||||
const repo = goal.directory
|
||||
const isRemote = goal.serverId !== LOCAL_OPENCODE_SERVER_ID;
|
||||
const repo = !isRemote && goal.directory
|
||||
? await resolveRepoForDirectory(this.db, goal.directory)
|
||||
: null;
|
||||
const server = isRemote ? this.serverRegistry?.get(goal.serverId) ?? null : null;
|
||||
const repoName = repo ? getRepoName(repo) : undefined;
|
||||
const displayName = repoName ?? server?.name;
|
||||
|
||||
const payload: PushNotificationPayload = {
|
||||
title: getGoalOutcomeTitle(goal.status),
|
||||
body: buildGoalOutcomeBody(goal, repoName),
|
||||
body: buildGoalOutcomeBody(goal, displayName),
|
||||
tag: `session-goal-${goal.id}`,
|
||||
timestamp: Date.now(),
|
||||
renotify: true,
|
||||
@@ -393,7 +457,11 @@ export class NotificationService {
|
||||
directory: goal.directory,
|
||||
repoId: repo?.id,
|
||||
repoName,
|
||||
url: buildNotificationUrl(repo, goal.sessionId),
|
||||
serverId: goal.serverId,
|
||||
serverName: server?.name,
|
||||
url: isRemote
|
||||
? buildServerSessionPath(goal.serverId, goal.sessionId)
|
||||
: buildNotificationUrl(repo, goal.sessionId),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -24,6 +24,9 @@ export interface RemoteEventAggregator {
|
||||
sendRemoteResync(serverId: string, data: string): void
|
||||
hasClientDirectory(clientId: string, key: string): boolean
|
||||
setRemoteReplayHandler(handler: RemoteReplayHandler | null): void
|
||||
notifyServerEvent(serverId: string, directory: string | null, event: V2Event): void
|
||||
notifyServerConnected(serverId: string): void
|
||||
setRemoteSubagentResolver(resolver: ((serverId: string, sessionId: string) => boolean) | null): void
|
||||
}
|
||||
|
||||
export interface RemoteEventSource {
|
||||
@@ -51,6 +54,7 @@ interface RemoteServerStream {
|
||||
version: string | null
|
||||
versionRequested: boolean
|
||||
sessionDirectories: Map<string, string>
|
||||
subagentSessions: Set<string>
|
||||
}
|
||||
|
||||
type RemoteReplayEventType = 'permission.asked' | 'form.created'
|
||||
@@ -94,6 +98,7 @@ export class RemoteServerEventHub {
|
||||
this.started = true
|
||||
this.aggregator.setRemoteReplayHandler((clientId, serverId, directory) =>
|
||||
this.replayPendingActions(clientId, serverId, directory))
|
||||
this.aggregator.setRemoteSubagentResolver((serverId, sessionId) => this.isSubagentSession(serverId, sessionId))
|
||||
this.unsubscribeRegistry = this.registry.onChange(change => this.handleRegistryChange(change))
|
||||
this.connectAll()
|
||||
}
|
||||
@@ -108,6 +113,11 @@ export class RemoteServerEventHub {
|
||||
this.forgetStream(serverId)
|
||||
}
|
||||
this.aggregator.setRemoteReplayHandler(null)
|
||||
this.aggregator.setRemoteSubagentResolver(null)
|
||||
}
|
||||
|
||||
isSubagentSession(serverId: string, sessionId: string): boolean {
|
||||
return this.streams.get(serverId)?.subagentSessions.has(sessionId) ?? false
|
||||
}
|
||||
|
||||
getStatuses(): OpenCodeServerStatus[] {
|
||||
@@ -254,6 +264,7 @@ export class RemoteServerEventHub {
|
||||
stream.error = null
|
||||
stream.reconnectDelay = this.reconnectDelayMs
|
||||
logger.info(`Remote event stream connected: ${serverId}`)
|
||||
this.aggregator.notifyServerConnected(serverId)
|
||||
this.aggregator.sendRemoteResync(serverId, JSON.stringify({ timestamp: Date.now() }))
|
||||
void this.refreshVersion(serverId)
|
||||
}
|
||||
@@ -308,10 +319,16 @@ export class RemoteServerEventHub {
|
||||
|
||||
if (sessionID && event.type === 'session.deleted') {
|
||||
stream.sessionDirectories.delete(sessionID)
|
||||
stream.subagentSessions.delete(sessionID)
|
||||
} else if (sessionID && rememberedDirectory) {
|
||||
stream.sessionDirectories.set(sessionID, rememberedDirectory)
|
||||
}
|
||||
|
||||
if (event.type === 'session.created' && event.data.parentID) {
|
||||
stream.subagentSessions.add(event.data.sessionID)
|
||||
}
|
||||
|
||||
this.aggregator.notifyServerEvent(serverId, resolvedDirectory ?? null, event)
|
||||
this.aggregator.deliverRemoteEnvelope(serverId, resolvedDirectory ?? null, payloadJson)
|
||||
} catch (error) {
|
||||
logger.error(`Remote event stream failed to handle ${event.type} for ${serverId}:`, error)
|
||||
@@ -374,6 +391,7 @@ export class RemoteServerEventHub {
|
||||
version: null,
|
||||
versionRequested: false,
|
||||
sessionDirectories: new Map(),
|
||||
subagentSessions: new Set(),
|
||||
}
|
||||
this.streams.set(serverId, stream)
|
||||
return stream
|
||||
|
||||
@@ -28,6 +28,7 @@ export interface ScheduleJobPersistenceInput {
|
||||
mcpServers: ScheduleMcpServer[]
|
||||
branch: string | null
|
||||
workspaceMode: ScheduleWorkspaceMode
|
||||
directory?: string | null
|
||||
nextRunAt: number | null
|
||||
}
|
||||
|
||||
@@ -104,6 +105,7 @@ export function buildCreateSchedulePersistenceInput(input: CreateScheduleJobRequ
|
||||
skillMetadata: input.skillMetadata,
|
||||
branch: input.branch?.trim() || null,
|
||||
workspaceMode: input.workspaceMode ?? 'worktree',
|
||||
...(input.directory !== undefined ? { directory: input.directory?.trim() || null } : {}),
|
||||
}
|
||||
|
||||
const scheduleConfig = input.scheduleMode === 'cron'
|
||||
@@ -166,6 +168,9 @@ export function buildUpdatedSchedulePersistenceInput(
|
||||
mcpServers: input.mcpServers ?? existing.mcpServers,
|
||||
branch: input.branch === undefined ? existing.branch : (input.branch?.trim() || null),
|
||||
workspaceMode: input.workspaceMode ?? existing.workspaceMode,
|
||||
...(input.directory !== undefined || existing.directory !== undefined
|
||||
? { directory: input.directory === undefined ? (existing.directory ?? null) : (input.directory?.trim() || null) }
|
||||
: {}),
|
||||
nextRunAt,
|
||||
}
|
||||
}
|
||||
+400
-119
File diff suppressed because it is too large.
Load diff
@@ -1,25 +1,42 @@
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
|
||||
const MAX_PARENT_HOPS = 10
|
||||
|
||||
export type SessionClientResolver = (serverId: string) => OpenCodeClient
|
||||
|
||||
function sessionKey(serverId: string, sessionId: string): string {
|
||||
return `${serverId}:${sessionId}`
|
||||
}
|
||||
|
||||
export class SessionAncestry {
|
||||
private readonly parentBySession = new Map<string, string | null>()
|
||||
private readonly resolveClient: SessionClientResolver
|
||||
|
||||
constructor(private readonly openCodeClient: OpenCodeClient) {}
|
||||
|
||||
rememberParent(sessionId: string, parentId: string | null | undefined): void {
|
||||
this.parentBySession.set(sessionId, parentId ?? null)
|
||||
constructor(clientOrResolver: OpenCodeClient | SessionClientResolver) {
|
||||
this.resolveClient = typeof clientOrResolver === 'function' ? clientOrResolver : () => clientOrResolver
|
||||
}
|
||||
|
||||
forget(sessionId: string): void {
|
||||
this.parentBySession.delete(sessionId)
|
||||
rememberParent(
|
||||
sessionId: string,
|
||||
parentId: string | null | undefined,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): void {
|
||||
this.parentBySession.set(sessionKey(serverId, sessionId), parentId ?? null)
|
||||
}
|
||||
|
||||
async resolveRootSessionId(sessionId: string): Promise<string> {
|
||||
forget(sessionId: string, serverId: string = LOCAL_OPENCODE_SERVER_ID): void {
|
||||
this.parentBySession.delete(sessionKey(serverId, sessionId))
|
||||
}
|
||||
|
||||
async resolveRootSessionId(
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<string> {
|
||||
let current = sessionId
|
||||
|
||||
for (let hops = 0; hops < MAX_PARENT_HOPS; hops += 1) {
|
||||
const parentId = await this.getParentId(current)
|
||||
const parentId = await this.getParentId(current, serverId)
|
||||
if (!parentId) {
|
||||
return current
|
||||
}
|
||||
@@ -29,14 +46,15 @@ export class SessionAncestry {
|
||||
return current
|
||||
}
|
||||
|
||||
private async getParentId(sessionId: string): Promise<string | null> {
|
||||
if (this.parentBySession.has(sessionId)) {
|
||||
return this.parentBySession.get(sessionId) ?? null
|
||||
private async getParentId(sessionId: string, serverId: string): Promise<string | null> {
|
||||
const key = sessionKey(serverId, sessionId)
|
||||
if (this.parentBySession.has(key)) {
|
||||
return this.parentBySession.get(key) ?? null
|
||||
}
|
||||
|
||||
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
|
||||
const session = await this.resolveClient(serverId).api.session.get({ sessionID: sessionId })
|
||||
const parentId = session.parentID ?? null
|
||||
this.parentBySession.set(sessionId, parentId)
|
||||
this.parentBySession.set(key, parentId)
|
||||
return parentId
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import {
|
||||
DEFAULT_SESSION_DEFAULTS,
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type SessionGoal,
|
||||
type SessionGoalStatus,
|
||||
type SessionGoalStopReason,
|
||||
@@ -43,10 +44,17 @@ const RECOVERY_RETRY_MS = 5000
|
||||
|
||||
type PrerequisiteResult<T> = { ok: true; value: T } | { ok: false }
|
||||
|
||||
export interface SessionServerRegistry {
|
||||
getClient(serverId: string): OpenCodeClient
|
||||
get(serverId: string): { enabled: boolean } | null
|
||||
}
|
||||
|
||||
export type SessionServerSource = OpenCodeClient | SessionServerRegistry
|
||||
|
||||
export interface SessionGoalServiceOptions {
|
||||
quietMs?: number
|
||||
onOutcome?: (goal: SessionGoal) => void
|
||||
resolveSessionLock?: (sessionId: string) => Promise<SessionLockReason | null>
|
||||
resolveSessionLock?: (sessionId: string, serverId: string) => Promise<SessionLockReason | null>
|
||||
}
|
||||
|
||||
export class SessionGoalError extends Error {
|
||||
@@ -62,10 +70,29 @@ export function sessionTokenTotal(tokens: { input: number; output: number; reaso
|
||||
return tokens.input + tokens.output + tokens.reasoning
|
||||
}
|
||||
|
||||
function goalKey(serverId: string, sessionId: string): string {
|
||||
return `${serverId}:${sessionId}`
|
||||
}
|
||||
|
||||
function isServerRegistry(source: SessionServerSource): source is SessionServerRegistry {
|
||||
return typeof (source as SessionServerRegistry).getClient === 'function'
|
||||
}
|
||||
|
||||
function toServerRegistry(source: SessionServerSource): SessionServerRegistry {
|
||||
if (isServerRegistry(source)) {
|
||||
return source
|
||||
}
|
||||
return {
|
||||
getClient: () => source,
|
||||
get: (serverId) => (serverId === LOCAL_OPENCODE_SERVER_ID ? { enabled: true } : null),
|
||||
}
|
||||
}
|
||||
|
||||
function toSessionGoal(record: SessionGoalRecord): SessionGoal {
|
||||
return {
|
||||
id: record.id,
|
||||
sessionId: record.sessionId,
|
||||
serverId: record.serverId,
|
||||
directory: record.directory,
|
||||
objective: record.objective,
|
||||
status: record.status,
|
||||
@@ -91,16 +118,18 @@ export class SessionGoalService {
|
||||
private readonly auditing = new Set<number>()
|
||||
private readonly auditRequested = new Set<number>()
|
||||
private readonly auditGeneration = new Map<string, number>()
|
||||
private readonly servers: SessionServerRegistry
|
||||
private readonly quietMs: number
|
||||
private readonly onOutcome: (goal: SessionGoal) => void
|
||||
private readonly resolveSessionLock: (sessionId: string) => Promise<SessionLockReason | null>
|
||||
private readonly resolveSessionLock: (sessionId: string, serverId: string) => Promise<SessionLockReason | null>
|
||||
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
servers: SessionServerSource,
|
||||
private readonly settingsService: SettingsService,
|
||||
options: SessionGoalServiceOptions = {},
|
||||
) {
|
||||
this.servers = toServerRegistry(servers)
|
||||
this.quietMs = options.quietMs ?? DEFAULT_QUIET_MS
|
||||
this.onOutcome = options.onOutcome ?? (() => {})
|
||||
this.resolveSessionLock = options.resolveSessionLock ?? (async () => null)
|
||||
@@ -109,7 +138,7 @@ export class SessionGoalService {
|
||||
loadOpenGoals(): void {
|
||||
this.goalBySession.clear()
|
||||
for (const record of listOpenSessionGoals(this.db)) {
|
||||
this.goalBySession.set(record.sessionId, record.id)
|
||||
this.goalBySession.set(goalKey(record.serverId, record.sessionId), record.id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +147,9 @@ export class SessionGoalService {
|
||||
if (record.status !== 'active' || record.turnState !== 'running') {
|
||||
continue
|
||||
}
|
||||
if (!this.isServerAvailable(record.serverId)) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await this.recoverRunningGoal(record)
|
||||
} catch (error) {
|
||||
@@ -127,73 +159,93 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
private async recoverRunningGoal(record: SessionGoalRecord): Promise<void> {
|
||||
const generation = this.currentAuditGeneration(record.sessionId)
|
||||
const key = goalKey(record.serverId, record.sessionId)
|
||||
const generation = this.currentAuditGeneration(key)
|
||||
const client = this.servers.getClient(record.serverId)
|
||||
try {
|
||||
await this.openCodeClient.api.session.get({ sessionID: record.sessionId })
|
||||
await client.api.session.get({ sessionID: record.sessionId })
|
||||
} catch (error) {
|
||||
if (isSessionNotFoundError(error)) {
|
||||
this.finishGoal(record.id, 'stopped', 'session_deleted')
|
||||
return
|
||||
}
|
||||
logger.error(`Session goal recovery could not read session ${record.sessionId}:`, error)
|
||||
this.scheduleRecoveryRetry(record.sessionId, record.id, generation)
|
||||
this.scheduleRecoveryRetry(key, record.id, generation)
|
||||
return
|
||||
}
|
||||
|
||||
const busy = await this.readPrerequisite(record.id, 'busy check', () =>
|
||||
isSessionBusy(this.openCodeClient, record.sessionId),
|
||||
isSessionBusy(client, record.sessionId),
|
||||
)
|
||||
if (!busy.ok) {
|
||||
this.scheduleRecoveryRetry(record.sessionId, record.id, generation)
|
||||
this.scheduleRecoveryRetry(key, record.id, generation)
|
||||
return
|
||||
}
|
||||
if (busy.value) {
|
||||
return
|
||||
}
|
||||
this.scheduleAudit(record.sessionId, record.id, 0)
|
||||
this.scheduleAudit(key, record.id, 0)
|
||||
}
|
||||
|
||||
private scheduleRecoveryRetry(sessionId: string, goalId: number, generation: number): void {
|
||||
this.clearRecoveryTimer(sessionId)
|
||||
private isServerAvailable(serverId: string): boolean {
|
||||
if (serverId === LOCAL_OPENCODE_SERVER_ID) {
|
||||
return true
|
||||
}
|
||||
try {
|
||||
const server = this.servers.get(serverId)
|
||||
return Boolean(server?.enabled)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to resolve OpenCode server ${serverId}:`, error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleRecoveryRetry(key: string, goalId: number, generation: number): void {
|
||||
this.clearRecoveryTimer(key)
|
||||
const timer = setTimeout(() => {
|
||||
this.recoveryTimers.delete(sessionId)
|
||||
void this.retryRecovery(sessionId, goalId, generation).catch((error) => {
|
||||
this.recoveryTimers.delete(key)
|
||||
void this.retryRecovery(key, goalId, generation).catch((error) => {
|
||||
logger.error(`Session goal recovery retry failed for goal ${goalId}:`, error)
|
||||
})
|
||||
}, RECOVERY_RETRY_MS)
|
||||
this.recoveryTimers.set(sessionId, timer)
|
||||
this.recoveryTimers.set(key, timer)
|
||||
}
|
||||
|
||||
private async retryRecovery(sessionId: string, goalId: number, generation: number): Promise<void> {
|
||||
private async retryRecovery(key: string, goalId: number, generation: number): Promise<void> {
|
||||
const record = getSessionGoalById(this.db, goalId)
|
||||
if (!record || record.status !== 'active' || record.turnState !== 'running') {
|
||||
return
|
||||
}
|
||||
if (this.currentAuditGeneration(sessionId) !== generation) {
|
||||
if (!this.isServerAvailable(record.serverId)) {
|
||||
return
|
||||
}
|
||||
if (this.currentAuditGeneration(key) !== generation) {
|
||||
return
|
||||
}
|
||||
await this.recoverRunningGoal(record)
|
||||
}
|
||||
|
||||
private clearRecoveryTimer(sessionId: string): void {
|
||||
const timer = this.recoveryTimers.get(sessionId)
|
||||
private clearRecoveryTimer(key: string): void {
|
||||
const timer = this.recoveryTimers.get(key)
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer)
|
||||
this.recoveryTimers.delete(sessionId)
|
||||
this.recoveryTimers.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
async start(input: StartSessionGoalRequest): Promise<SessionGoal> {
|
||||
await this.assertSessionCanStartGoal(input.sessionId)
|
||||
const serverId = input.serverId ?? LOCAL_OPENCODE_SERVER_ID
|
||||
await this.assertSessionCanStartGoal(input.sessionId, serverId)
|
||||
|
||||
const defaults = this.settingsService.getSettings().preferences.sessionDefaults
|
||||
const maxContinuations =
|
||||
input.maxContinuations ?? defaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations
|
||||
const tokenBudget = input.tokenBudget ?? defaults?.goalTokenBudget ?? null
|
||||
const tokensAtStart = await this.readSessionTokenTotalOrDefault(input.sessionId)
|
||||
const tokensAtStart = await this.readSessionTokenTotalOrDefault(input.sessionId, serverId)
|
||||
|
||||
const record = insertSessionGoal(this.db, {
|
||||
sessionId: input.sessionId,
|
||||
serverId,
|
||||
directory: input.directory,
|
||||
objective: input.objective,
|
||||
maxContinuations,
|
||||
@@ -205,19 +257,19 @@ export class SessionGoalService {
|
||||
throw new SessionGoalError('This session already has an open goal', 409)
|
||||
}
|
||||
|
||||
this.goalBySession.set(record.sessionId, record.id)
|
||||
this.goalBySession.set(goalKey(record.serverId, record.sessionId), record.id)
|
||||
return toSessionGoal(record)
|
||||
}
|
||||
|
||||
getLatest(sessionId: string): SessionGoal | null {
|
||||
const record = getLatestSessionGoal(this.db, sessionId)
|
||||
getLatest(sessionId: string, serverId: string = LOCAL_OPENCODE_SERVER_ID): SessionGoal | null {
|
||||
const record = getLatestSessionGoal(this.db, sessionId, serverId)
|
||||
return record ? toSessionGoal(record) : null
|
||||
}
|
||||
|
||||
private async assertSessionCanStartGoal(sessionId: string): Promise<void> {
|
||||
private async assertSessionCanStartGoal(sessionId: string, serverId: string): Promise<void> {
|
||||
let lock: SessionLockReason | null
|
||||
try {
|
||||
lock = await this.resolveSessionLock(sessionId)
|
||||
lock = await this.resolveSessionLock(sessionId, serverId)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to resolve session lock for ${sessionId}:`, error)
|
||||
return
|
||||
@@ -256,41 +308,46 @@ export class SessionGoalService {
|
||||
})
|
||||
}
|
||||
|
||||
async handleEvent(directory: string | null, event: SSEEvent): Promise<void> {
|
||||
async handleEvent(
|
||||
directory: string | null,
|
||||
event: SSEEvent,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<void> {
|
||||
const sessionId = sessionIDFromEvent(event)
|
||||
if (!sessionId) {
|
||||
return
|
||||
}
|
||||
|
||||
const goalId = this.goalBySession.get(sessionId)
|
||||
const key = goalKey(serverId, sessionId)
|
||||
const goalId = this.goalBySession.get(key)
|
||||
if (goalId === undefined) {
|
||||
return
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'session.execution.started':
|
||||
this.clearAuditTimer(sessionId)
|
||||
this.clearAuditTimer(key)
|
||||
this.applyTransition(goalId, ['active'], { turnState: 'running' })
|
||||
return
|
||||
case 'session.idle':
|
||||
case 'session.execution.succeeded':
|
||||
this.scheduleAuditFromEvent(sessionId, goalId)
|
||||
this.scheduleAuditFromEvent(key, goalId)
|
||||
return
|
||||
case 'session.status':
|
||||
if (event.data.status.type === 'idle') {
|
||||
this.scheduleAuditFromEvent(sessionId, goalId)
|
||||
this.scheduleAuditFromEvent(key, goalId)
|
||||
}
|
||||
return
|
||||
case 'session.execution.failed':
|
||||
this.clearAuditTimer(sessionId)
|
||||
this.clearAuditTimer(key)
|
||||
this.finishGoal(goalId, 'stopped', 'turn_error')
|
||||
return
|
||||
case 'session.execution.interrupted':
|
||||
this.clearAuditTimer(sessionId)
|
||||
this.clearAuditTimer(key)
|
||||
this.finishGoal(goalId, 'paused', 'interrupted')
|
||||
return
|
||||
case 'session.deleted':
|
||||
this.clearAuditTimer(sessionId)
|
||||
this.clearAuditTimer(key)
|
||||
this.finishGoal(goalId, 'stopped', 'session_deleted', ['active', 'paused'])
|
||||
return
|
||||
default:
|
||||
@@ -298,50 +355,51 @@ export class SessionGoalService {
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleAuditFromEvent(sessionId: string, goalId: number): void {
|
||||
private scheduleAuditFromEvent(key: string, goalId: number): void {
|
||||
const record = getSessionGoalById(this.db, goalId)
|
||||
if (!record || record.status !== 'active' || record.turnState !== 'running') {
|
||||
return
|
||||
}
|
||||
this.scheduleAudit(sessionId, goalId, this.quietMs)
|
||||
this.scheduleAudit(key, goalId, this.quietMs)
|
||||
}
|
||||
|
||||
private async scheduleAuditWhenIdle(goal: SessionGoal): Promise<void> {
|
||||
const generation = this.currentAuditGeneration(goal.sessionId)
|
||||
const key = goalKey(goal.serverId, goal.sessionId)
|
||||
const generation = this.currentAuditGeneration(key)
|
||||
const busy = await this.readPrerequisite(goal.id, 'busy check', () =>
|
||||
isSessionBusy(this.openCodeClient, goal.sessionId),
|
||||
isSessionBusy(this.servers.getClient(goal.serverId), goal.sessionId),
|
||||
)
|
||||
|
||||
if (!busy.ok) {
|
||||
this.failAudit(goal.id, goal.sessionId, generation)
|
||||
this.failAudit(goal.id, key, generation)
|
||||
return
|
||||
}
|
||||
if (!this.isAuditCurrent(goal.id, goal.sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goal.id, key, generation)) {
|
||||
return
|
||||
}
|
||||
if (busy.value) {
|
||||
return
|
||||
}
|
||||
this.scheduleAudit(goal.sessionId, goal.id, 0)
|
||||
this.scheduleAudit(key, goal.id, 0)
|
||||
}
|
||||
|
||||
private scheduleAudit(sessionId: string, goalId: number, delay: number): void {
|
||||
this.clearRecoveryTimer(sessionId)
|
||||
this.clearAuditTimer(sessionId)
|
||||
private scheduleAudit(key: string, goalId: number, delay: number): void {
|
||||
this.clearRecoveryTimer(key)
|
||||
this.clearAuditTimer(key)
|
||||
const timer = setTimeout(() => {
|
||||
this.auditTimers.delete(sessionId)
|
||||
this.auditTimers.delete(key)
|
||||
void this.runAudit(goalId).catch((error) => {
|
||||
logger.error(`Session goal audit failed for goal ${goalId}:`, error)
|
||||
})
|
||||
}, delay)
|
||||
this.auditTimers.set(sessionId, timer)
|
||||
this.auditTimers.set(key, timer)
|
||||
}
|
||||
|
||||
private clearAuditTimer(sessionId: string): void {
|
||||
const timer = this.auditTimers.get(sessionId)
|
||||
private clearAuditTimer(key: string): void {
|
||||
const timer = this.auditTimers.get(key)
|
||||
if (timer !== undefined) {
|
||||
clearTimeout(timer)
|
||||
this.auditTimers.delete(sessionId)
|
||||
this.auditTimers.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -371,27 +429,29 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
const sessionId = goal.sessionId
|
||||
const generation = this.currentAuditGeneration(sessionId)
|
||||
const key = goalKey(goal.serverId, sessionId)
|
||||
const generation = this.currentAuditGeneration(key)
|
||||
const client = this.servers.getClient(goal.serverId)
|
||||
|
||||
const busy = await this.readPrerequisite(goalId, 'busy check', () =>
|
||||
isSessionBusy(this.openCodeClient, sessionId),
|
||||
isSessionBusy(client, sessionId),
|
||||
)
|
||||
if (!busy.ok) {
|
||||
this.failAudit(goalId, sessionId, generation)
|
||||
this.failAudit(goalId, key, generation)
|
||||
return
|
||||
}
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation) || busy.value) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation) || busy.value) {
|
||||
return
|
||||
}
|
||||
|
||||
const total = await this.readPrerequisite(goalId, 'token read', () =>
|
||||
this.readSessionTokenTotal(sessionId),
|
||||
this.readSessionTokenTotal(sessionId, goal.serverId),
|
||||
)
|
||||
if (!total.ok) {
|
||||
this.failAudit(goalId, sessionId, generation)
|
||||
this.failAudit(goalId, key, generation)
|
||||
return
|
||||
}
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -407,13 +467,13 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
const reply = await this.readPrerequisite(goalId, 'reply read', () =>
|
||||
readLatestAssistantReply(this.openCodeClient, sessionId),
|
||||
readLatestAssistantReply(client, sessionId),
|
||||
)
|
||||
if (!reply.ok) {
|
||||
this.failAudit(goalId, sessionId, generation)
|
||||
this.failAudit(goalId, key, generation)
|
||||
return
|
||||
}
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -423,7 +483,7 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
const verdict = await this.evaluateAudit(updated, reply.value)
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
if (!verdict) {
|
||||
@@ -431,16 +491,17 @@ export class SessionGoalService {
|
||||
return
|
||||
}
|
||||
|
||||
await this.applyVerdict(goalId, sessionId, generation, updated, verdict)
|
||||
await this.applyVerdict(goalId, key, generation, updated, verdict)
|
||||
}
|
||||
|
||||
private async evaluateAudit(goal: SessionGoalRecord, reply: AssistantReplyState | null): Promise<GoalVerdict | null> {
|
||||
const prompt = buildGoalAuditPrompt({ objective: goal.objective, reply: reply?.responseText ?? null })
|
||||
const model = this.resolveAuditorModel()
|
||||
const localClient = this.servers.getClient(LOCAL_OPENCODE_SERVER_ID)
|
||||
|
||||
for (let attempt = 0; attempt < AUDITOR_ATTEMPTS; attempt += 1) {
|
||||
try {
|
||||
const result = await this.openCodeClient.api.generate.text(model ? { prompt, model } : { prompt })
|
||||
const result = await localClient.api.generate.text(model ? { prompt, model } : { prompt })
|
||||
return parseGoalVerdict(result.text) ?? { verdict: 'continue', reason: GOAL_AUDIT_UNPARSED_REASON }
|
||||
} catch (error) {
|
||||
logger.error(`Goal auditor call failed for goal ${goal.id} (attempt ${attempt + 1}):`, error)
|
||||
@@ -457,12 +518,12 @@ export class SessionGoalService {
|
||||
|
||||
private async applyVerdict(
|
||||
goalId: number,
|
||||
sessionId: string,
|
||||
key: string,
|
||||
generation: number,
|
||||
goal: SessionGoalRecord,
|
||||
verdict: GoalVerdict,
|
||||
): Promise<void> {
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -487,11 +548,11 @@ export class SessionGoalService {
|
||||
return
|
||||
}
|
||||
|
||||
await this.continueGoal(goalId, sessionId, generation, goal, verdict.reason, patch)
|
||||
await this.continueGoal(goalId, key, generation, goal, verdict.reason, patch)
|
||||
return
|
||||
}
|
||||
|
||||
await this.continueGoal(goalId, sessionId, generation, goal, verdict.reason, {
|
||||
await this.continueGoal(goalId, key, generation, goal, verdict.reason, {
|
||||
consecutiveBlocked: 0,
|
||||
lastVerdict: 'continue',
|
||||
lastReason: verdict.reason,
|
||||
@@ -500,13 +561,13 @@ export class SessionGoalService {
|
||||
|
||||
private async continueGoal(
|
||||
goalId: number,
|
||||
sessionId: string,
|
||||
key: string,
|
||||
generation: number,
|
||||
goal: SessionGoalRecord,
|
||||
reason: string,
|
||||
patch: SessionGoalPatch,
|
||||
): Promise<void> {
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -525,13 +586,13 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
try {
|
||||
await this.openCodeClient.api.session.prompt({
|
||||
await this.servers.getClient(record.serverId).api.session.prompt({
|
||||
sessionID: record.sessionId,
|
||||
text: buildGoalContinuationPrompt({ objective: record.objective, reason }),
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`Failed to send continuation for goal ${goalId}:`, error)
|
||||
if (this.isAuditCurrent(goalId, sessionId, generation, 'waiting')) {
|
||||
if (this.isAuditCurrent(goalId, key, generation, 'waiting')) {
|
||||
this.finishGoal(goalId, 'stopped', 'turn_error')
|
||||
}
|
||||
}
|
||||
@@ -555,8 +616,8 @@ export class SessionGoalService {
|
||||
}
|
||||
}
|
||||
|
||||
private failAudit(goalId: number, sessionId: string, generation: number): void {
|
||||
if (!this.isAuditCurrent(goalId, sessionId, generation)) {
|
||||
private failAudit(goalId: number, key: string, generation: number): void {
|
||||
if (!this.isAuditCurrent(goalId, key, generation)) {
|
||||
return
|
||||
}
|
||||
this.finishGoal(goalId, 'paused', 'audit_failed')
|
||||
@@ -579,19 +640,19 @@ export class SessionGoalService {
|
||||
|
||||
private isAuditCurrent(
|
||||
goalId: number,
|
||||
sessionId: string,
|
||||
key: string,
|
||||
generation: number,
|
||||
turnState: SessionGoalTurnState = 'running',
|
||||
): boolean {
|
||||
if (this.currentAuditGeneration(sessionId) !== generation) {
|
||||
if (this.currentAuditGeneration(key) !== generation) {
|
||||
return false
|
||||
}
|
||||
const record = getSessionGoalById(this.db, goalId)
|
||||
return Boolean(record && record.status === 'active' && record.turnState === turnState)
|
||||
}
|
||||
|
||||
private currentAuditGeneration(sessionId: string): number {
|
||||
return this.auditGeneration.get(sessionId) ?? 0
|
||||
private currentAuditGeneration(key: string): number {
|
||||
return this.auditGeneration.get(key) ?? 0
|
||||
}
|
||||
|
||||
private applyTransition(
|
||||
@@ -632,14 +693,15 @@ export class SessionGoalService {
|
||||
}
|
||||
|
||||
private syncGoalIndex(record: SessionGoalRecord): void {
|
||||
const key = goalKey(record.serverId, record.sessionId)
|
||||
if (record.status === 'active' || record.status === 'paused') {
|
||||
this.goalBySession.set(record.sessionId, record.id)
|
||||
this.goalBySession.set(key, record.id)
|
||||
} else {
|
||||
this.goalBySession.delete(record.sessionId)
|
||||
this.clearAuditTimer(record.sessionId)
|
||||
this.goalBySession.delete(key)
|
||||
this.clearAuditTimer(key)
|
||||
}
|
||||
if (record.status !== 'active') {
|
||||
this.clearRecoveryTimer(record.sessionId)
|
||||
this.clearRecoveryTimer(key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -647,18 +709,19 @@ export class SessionGoalService {
|
||||
if (patch.status === undefined && patch.turnState !== 'running') {
|
||||
return
|
||||
}
|
||||
this.auditGeneration.set(record.sessionId, this.currentAuditGeneration(record.sessionId) + 1)
|
||||
const key = goalKey(record.serverId, record.sessionId)
|
||||
this.auditGeneration.set(key, this.currentAuditGeneration(key) + 1)
|
||||
this.auditRequested.delete(record.id)
|
||||
}
|
||||
|
||||
private async readSessionTokenTotal(sessionId: string): Promise<number> {
|
||||
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
|
||||
private async readSessionTokenTotal(sessionId: string, serverId: string): Promise<number> {
|
||||
const session = await this.servers.getClient(serverId).api.session.get({ sessionID: sessionId })
|
||||
return sessionTokenTotal(session.tokens)
|
||||
}
|
||||
|
||||
private async readSessionTokenTotalOrDefault(sessionId: string): Promise<number> {
|
||||
private async readSessionTokenTotalOrDefault(sessionId: string, serverId: string): Promise<number> {
|
||||
try {
|
||||
return await this.readSessionTokenTotal(sessionId)
|
||||
return await this.readSessionTokenTotal(sessionId, serverId)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to read token usage for session ${sessionId}:`, error)
|
||||
return 0
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
|
||||
import { LOCAL_OPENCODE_SERVER_ID, type MultiRunTarget } from '@opencode-manager/shared/schemas'
|
||||
import { sanitizeRepoDirectoryName } from '@opencode-manager/shared/utils'
|
||||
import { getRepoById } from '../db/queries'
|
||||
import type { Repo } from '../types/repo'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { resolveOpenCodeModel, type ResolvedOpenCodeModel } from './opencode-models'
|
||||
import { resolveRepoProjectId } from './repo'
|
||||
import type { RepoWorkspaceService } from './repo-workspace'
|
||||
|
||||
type SessionCreateInput = NonNullable<Parameters<OpenCodeClient['api']['session']['create']>[0]>
|
||||
|
||||
interface LaunchSessionInput {
|
||||
repoId: number
|
||||
interface LaunchSessionCommon {
|
||||
prompt: string
|
||||
title?: string
|
||||
model?: string
|
||||
@@ -20,9 +21,12 @@ interface LaunchSessionInput {
|
||||
permissions?: SessionCreateInput['permissions']
|
||||
}
|
||||
|
||||
export type LaunchSessionInput = LaunchSessionCommon &
|
||||
({ repoId: number } | { serverId: string; directory: string })
|
||||
|
||||
export interface LaunchedSession {
|
||||
sessionId: string
|
||||
repoId: number
|
||||
repoId: number | null
|
||||
directory: string
|
||||
workspaceDirectory: string | null
|
||||
model: string
|
||||
@@ -48,11 +52,31 @@ export class SessionLaunchError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export interface SessionTargetDeps {
|
||||
db: Database
|
||||
openCodeClient: OpenCodeClient
|
||||
repoWorkspaces: RepoWorkspaceService
|
||||
getServerClient?: (serverId: string) => OpenCodeClient
|
||||
}
|
||||
|
||||
/**
|
||||
* A resolved place to run sessions: the local repository checkout or a directory on a linked
|
||||
* OpenCode server. Workspaces and models are resolved through the same client the sessions run on.
|
||||
*/
|
||||
export interface ResolvedSessionTarget {
|
||||
client: OpenCodeClient
|
||||
directory: string
|
||||
repo: Repo | null
|
||||
resolveModel(requestedModel?: string): Promise<ResolvedOpenCodeModel>
|
||||
createWorkspace(options?: { name?: string; ref?: string }): Promise<string>
|
||||
removeWorkspace(directory: string): Promise<void>
|
||||
}
|
||||
|
||||
function withWorkspace(message: string, workspaceDirectory: string | null): string {
|
||||
return workspaceDirectory ? `${message} (workspace: ${workspaceDirectory})` : message
|
||||
}
|
||||
|
||||
export function requireReadyRepo(db: Database, repoId: number): Repo {
|
||||
function requireReadyRepo(db: Database, repoId: number): Repo {
|
||||
const repo = getRepoById(db, repoId)
|
||||
if (!repo || repo.cloneStatus !== 'ready') {
|
||||
throw new SessionLaunchError('Repository not found or not ready', 404)
|
||||
@@ -60,48 +84,137 @@ export function requireReadyRepo(db: Database, repoId: number): Repo {
|
||||
return repo
|
||||
}
|
||||
|
||||
export function sessionTargetInput(
|
||||
target: MultiRunTarget,
|
||||
): { repoId: number } | { serverId: string; directory: string } {
|
||||
return target.kind === 'repo'
|
||||
? { repoId: target.repoId }
|
||||
: { serverId: target.serverId, directory: target.directory }
|
||||
}
|
||||
|
||||
export function sessionTargetOfRun(run: {
|
||||
repoId: number | null
|
||||
serverId: string
|
||||
directory: string | null
|
||||
}): MultiRunTarget | null {
|
||||
if (run.repoId !== null) {
|
||||
return { kind: 'repo', repoId: run.repoId }
|
||||
}
|
||||
if (run.serverId === LOCAL_OPENCODE_SERVER_ID || run.directory === null) {
|
||||
return null
|
||||
}
|
||||
return { kind: 'server', serverId: run.serverId, directory: run.directory }
|
||||
}
|
||||
|
||||
async function resolveModelIn(
|
||||
client: OpenCodeClient,
|
||||
directory: string,
|
||||
requestedModel?: string,
|
||||
): Promise<ResolvedOpenCodeModel> {
|
||||
let resolved: ResolvedOpenCodeModel
|
||||
try {
|
||||
resolved = await resolveOpenCodeModel(client, directory, { preferredModel: requestedModel })
|
||||
} catch (error) {
|
||||
throw new SessionLaunchError(getErrorMessage(error) || 'Failed to resolve OpenCode model', 502)
|
||||
}
|
||||
|
||||
if (requestedModel) {
|
||||
const requestedRef = parseOpenCodeModelRef(requestedModel)
|
||||
if (!requestedRef || resolved.providerID !== requestedRef.providerID || resolved.id !== requestedRef.id) {
|
||||
throw new SessionLaunchError(`Model ${requestedModel} is not available`, 400)
|
||||
}
|
||||
}
|
||||
|
||||
return resolved
|
||||
}
|
||||
|
||||
function repoSessionTarget(deps: SessionTargetDeps, repoId: number): ResolvedSessionTarget {
|
||||
const repo = requireReadyRepo(deps.db, repoId)
|
||||
const client = deps.openCodeClient
|
||||
|
||||
return {
|
||||
client,
|
||||
directory: repo.fullPath,
|
||||
repo,
|
||||
resolveModel: (requestedModel) => resolveModelIn(client, repo.fullPath, requestedModel),
|
||||
createWorkspace: async (options) => (await deps.repoWorkspaces.create(repo, options)).directory,
|
||||
removeWorkspace: (directory) => deps.repoWorkspaces.remove(repo, directory),
|
||||
}
|
||||
}
|
||||
|
||||
function serverSessionTarget(
|
||||
deps: SessionTargetDeps,
|
||||
serverId: string,
|
||||
directory: string,
|
||||
): ResolvedSessionTarget {
|
||||
if (!deps.getServerClient) {
|
||||
throw new SessionLaunchError('Remote OpenCode servers are not available', 400)
|
||||
}
|
||||
|
||||
const client = deps.getServerClient(serverId)
|
||||
|
||||
return {
|
||||
client,
|
||||
directory,
|
||||
repo: null,
|
||||
resolveModel: (requestedModel) => resolveModelIn(client, directory, requestedModel),
|
||||
createWorkspace: async (options) => {
|
||||
const projectID = await resolveRepoProjectId(client, directory)
|
||||
const worktree = await client.api.worktree.create({
|
||||
projectID,
|
||||
...(options?.name ? { name: options.name } : {}),
|
||||
...(options?.ref ? { branch: options.ref } : {}),
|
||||
})
|
||||
return worktree.directory
|
||||
},
|
||||
removeWorkspace: async (workspaceDirectory) => {
|
||||
const projectID = await resolveRepoProjectId(client, directory)
|
||||
await client.api.worktree.remove({ projectID, directory: workspaceDirectory, force: true })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveSessionTarget(
|
||||
deps: SessionTargetDeps,
|
||||
target: MultiRunTarget,
|
||||
): Promise<ResolvedSessionTarget> {
|
||||
return target.kind === 'repo'
|
||||
? repoSessionTarget(deps, target.repoId)
|
||||
: serverSessionTarget(deps, target.serverId, target.directory)
|
||||
}
|
||||
|
||||
export class SessionLauncher {
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
private readonly repoWorkspaces: RepoWorkspaceService,
|
||||
private readonly getServerClient?: (serverId: string) => OpenCodeClient,
|
||||
) {}
|
||||
|
||||
async resolveModel(repo: Repo, requestedModel?: string): Promise<ResolvedOpenCodeModel> {
|
||||
let resolved: ResolvedOpenCodeModel
|
||||
try {
|
||||
resolved = await resolveOpenCodeModel(this.openCodeClient, repo.fullPath, {
|
||||
preferredModel: requestedModel,
|
||||
})
|
||||
} catch (error) {
|
||||
throw new SessionLaunchError(getErrorMessage(error) || 'Failed to resolve OpenCode model', 502)
|
||||
}
|
||||
|
||||
if (requestedModel) {
|
||||
const requestedRef = parseOpenCodeModelRef(requestedModel)
|
||||
if (!requestedRef || resolved.providerID !== requestedRef.providerID || resolved.id !== requestedRef.id) {
|
||||
throw new SessionLaunchError(`Model ${requestedModel} is not available`, 400)
|
||||
}
|
||||
}
|
||||
|
||||
return resolved
|
||||
}
|
||||
|
||||
async launch(input: LaunchSessionInput): Promise<LaunchedSession> {
|
||||
const repo = requireReadyRepo(this.db, input.repoId)
|
||||
const model = await this.resolveModel(repo, input.model)
|
||||
const target = await resolveSessionTarget(
|
||||
{
|
||||
db: this.db,
|
||||
openCodeClient: this.openCodeClient,
|
||||
repoWorkspaces: this.repoWorkspaces,
|
||||
...(this.getServerClient ? { getServerClient: this.getServerClient } : {}),
|
||||
},
|
||||
'repoId' in input
|
||||
? { kind: 'repo', repoId: input.repoId }
|
||||
: { kind: 'server', serverId: input.serverId, directory: input.directory },
|
||||
)
|
||||
const model = await target.resolveModel(input.model)
|
||||
|
||||
let directory = repo.fullPath
|
||||
let directory = target.directory
|
||||
let workspaceDirectory: string | null = null
|
||||
|
||||
if (input.workspace) {
|
||||
try {
|
||||
const workspace = await this.repoWorkspaces.create(repo, {
|
||||
directory = await target.createWorkspace({
|
||||
name: sanitizeRepoDirectoryName(input.workspace.name ?? '', 'session'),
|
||||
...(input.workspace.ref ? { ref: input.workspace.ref } : {}),
|
||||
})
|
||||
directory = workspace.directory
|
||||
workspaceDirectory = workspace.directory
|
||||
workspaceDirectory = directory
|
||||
} catch (error) {
|
||||
throw new SessionLaunchError(getErrorMessage(error) || 'Failed to create workspace', 502)
|
||||
}
|
||||
@@ -109,7 +222,7 @@ export class SessionLauncher {
|
||||
|
||||
let session: { id: string; title?: string | null }
|
||||
try {
|
||||
session = await this.openCodeClient.api.session.create({
|
||||
session = await target.client.api.session.create({
|
||||
...(input.title ? { title: input.title } : {}),
|
||||
...(input.agent ? { agent: input.agent } : {}),
|
||||
...(input.permissions ? { permissions: input.permissions } : {}),
|
||||
@@ -129,7 +242,7 @@ export class SessionLauncher {
|
||||
}
|
||||
|
||||
try {
|
||||
await this.openCodeClient.api.session.prompt({ sessionID: session.id, text: input.prompt })
|
||||
await target.client.api.session.prompt({ sessionID: session.id, text: input.prompt })
|
||||
} catch (error) {
|
||||
throw new SessionLaunchError(
|
||||
withWorkspace(getErrorMessage(error) || 'Failed to create OpenCode session', workspaceDirectory),
|
||||
@@ -141,7 +254,7 @@ export class SessionLauncher {
|
||||
|
||||
return {
|
||||
sessionId: session.id,
|
||||
repoId: repo.id,
|
||||
repoId: target.repo?.id ?? null,
|
||||
directory,
|
||||
workspaceDirectory,
|
||||
model: model.model,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type {
|
||||
SessionLockReason,
|
||||
SessionPermissionMode,
|
||||
SessionPermissionModeState,
|
||||
import {
|
||||
LOCAL_OPENCODE_SERVER_ID,
|
||||
type SessionLockReason,
|
||||
type SessionPermissionMode,
|
||||
type SessionPermissionModeState,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { openCodeLocation, type PermissionRequest } from '@opencode-manager/shared/opencode'
|
||||
import { getScheduleRunBySessionId } from '../db/schedules'
|
||||
@@ -18,6 +19,16 @@ import type { SessionAncestry } from './session-ancestry'
|
||||
import type { SSEEvent } from './sse-aggregator'
|
||||
import type { SettingsService } from './settings'
|
||||
|
||||
export interface SessionClientProvider {
|
||||
getClient(serverId: string): OpenCodeClient
|
||||
}
|
||||
|
||||
export type SessionClientSource = OpenCodeClient | SessionClientProvider
|
||||
|
||||
function isClientProvider(source: SessionClientSource): source is SessionClientProvider {
|
||||
return typeof (source as SessionClientProvider).getClient === 'function'
|
||||
}
|
||||
|
||||
export class SessionPermissionModeError extends Error {
|
||||
status: number
|
||||
|
||||
@@ -28,55 +39,71 @@ export class SessionPermissionModeError extends Error {
|
||||
}
|
||||
|
||||
export class SessionPermissionModeService {
|
||||
private readonly clients: SessionClientProvider
|
||||
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
clients: SessionClientSource,
|
||||
private readonly settingsService: SettingsService,
|
||||
private readonly ancestry: SessionAncestry,
|
||||
) {}
|
||||
) {
|
||||
this.clients = isClientProvider(clients) ? clients : { getClient: () => clients }
|
||||
}
|
||||
|
||||
async handleEvent(directory: string | null, event: SSEEvent): Promise<void> {
|
||||
async handleEvent(
|
||||
directory: string | null,
|
||||
event: SSEEvent,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<void> {
|
||||
switch (event.type) {
|
||||
case 'session.created': {
|
||||
const { sessionID, parentID, permissions } = event.data
|
||||
this.ancestry.rememberParent(sessionID, parentID)
|
||||
this.ancestry.rememberParent(sessionID, parentID, serverId)
|
||||
const hasExplicitPermissions = Array.isArray(permissions) && permissions.length > 0
|
||||
if (!parentID && !hasExplicitPermissions && this.defaultMode() === 'auto') {
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto')
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto', serverId)
|
||||
}
|
||||
return
|
||||
}
|
||||
case 'session.forked': {
|
||||
const { sessionID, parentID } = event.data
|
||||
this.ancestry.rememberParent(sessionID, null)
|
||||
const sourceMode = await this.getEffectiveMode(parentID)
|
||||
this.ancestry.rememberParent(sessionID, null, serverId)
|
||||
const sourceMode = await this.getEffectiveMode(parentID, serverId)
|
||||
if (sourceMode.mode === 'auto') {
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto')
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionID, 'auto', serverId)
|
||||
}
|
||||
return
|
||||
}
|
||||
case 'permission.asked': {
|
||||
const { sessionID, id } = event.data
|
||||
await this.autoAcceptRequest(sessionID, id)
|
||||
await this.autoAcceptRequest(sessionID, id, serverId)
|
||||
return
|
||||
}
|
||||
case 'session.deleted': {
|
||||
const { sessionID } = event.data
|
||||
this.ancestry.forget(sessionID)
|
||||
deleteSessionPermissionMode(this.db, sessionID)
|
||||
this.ancestry.forget(sessionID, serverId)
|
||||
deleteSessionPermissionMode(this.db, sessionID, serverId)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getEffectiveMode(sessionId: string): Promise<SessionPermissionModeState> {
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionId)
|
||||
return this.effectiveModeForRoot(sessionId, rootSessionId)
|
||||
async getEffectiveMode(
|
||||
sessionId: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<SessionPermissionModeState> {
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionId, serverId)
|
||||
return this.effectiveModeForRoot(sessionId, rootSessionId, serverId)
|
||||
}
|
||||
|
||||
async setMode(sessionId: string, mode: SessionPermissionMode, directory: string): Promise<SessionPermissionModeState> {
|
||||
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId)
|
||||
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId)
|
||||
async setMode(
|
||||
sessionId: string,
|
||||
mode: SessionPermissionMode,
|
||||
directory: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<SessionPermissionModeState> {
|
||||
const rootSessionId = await this.ancestry.resolveRootSessionId(sessionId, serverId)
|
||||
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId, serverId)
|
||||
if (lockedReason === 'schedule') {
|
||||
throw new SessionPermissionModeError(
|
||||
'Scheduled runs use their own permission configuration',
|
||||
@@ -91,15 +118,15 @@ export class SessionPermissionModeService {
|
||||
)
|
||||
}
|
||||
|
||||
setSessionPermissionMode(this.db, sessionId, mode)
|
||||
setSessionPermissionMode(this.db, sessionId, mode, serverId)
|
||||
if (mode === 'auto') {
|
||||
await this.acceptPendingRequestsInDirectory(directory, sessionId)
|
||||
await this.acceptPendingRequestsInDirectory(directory, serverId, sessionId)
|
||||
}
|
||||
return { sessionId, rootSessionId, mode, lockedReason: null }
|
||||
}
|
||||
|
||||
pinAsk(sessionId: string): void {
|
||||
setSessionPermissionMode(this.db, sessionId, 'ask')
|
||||
pinAsk(sessionId: string, serverId: string = LOCAL_OPENCODE_SERVER_ID): void {
|
||||
setSessionPermissionMode(this.db, sessionId, 'ask', serverId)
|
||||
}
|
||||
|
||||
defaultMode(): SessionPermissionMode {
|
||||
@@ -112,66 +139,93 @@ export class SessionPermissionModeService {
|
||||
*
|
||||
* Does nothing when the default mode is `ask`, since that needs no stored row.
|
||||
*/
|
||||
async applyDefaultMode(sessionId: string, directory: string): Promise<void> {
|
||||
async applyDefaultMode(
|
||||
sessionId: string,
|
||||
directory: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<void> {
|
||||
if (this.defaultMode() !== 'auto') {
|
||||
return
|
||||
}
|
||||
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionId, 'auto')
|
||||
await this.acceptPendingRequestsInDirectory(directory, sessionId)
|
||||
insertSessionPermissionModeIfAbsent(this.db, sessionId, 'auto', serverId)
|
||||
await this.acceptPendingRequestsInDirectory(directory, serverId, sessionId)
|
||||
}
|
||||
|
||||
async acceptPendingRequestsForActiveSessions(): Promise<void> {
|
||||
async acceptPendingRequestsForActiveSessions(serverId: string = LOCAL_OPENCODE_SERVER_ID): Promise<void> {
|
||||
try {
|
||||
const active = await this.openCodeClient.api.session.active()
|
||||
const client = this.clients.getClient(serverId)
|
||||
const active = await client.api.session.active()
|
||||
const directories = new Set<string>()
|
||||
|
||||
for (const sessionId of Object.keys(active ?? {})) {
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionId)
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionId, serverId)
|
||||
if (!rootSessionId) continue
|
||||
if (this.effectiveModeForRoot(sessionId, rootSessionId).mode !== 'auto') continue
|
||||
const directory = await this.resolveSessionDirectory(sessionId)
|
||||
if (this.effectiveModeForRoot(sessionId, rootSessionId, serverId).mode !== 'auto') continue
|
||||
const directory = await this.resolveSessionDirectory(sessionId, serverId)
|
||||
if (directory) directories.add(directory)
|
||||
}
|
||||
|
||||
for (const directory of directories) {
|
||||
await this.acceptPendingRequestsInDirectory(directory)
|
||||
await this.acceptPendingRequestsInDirectory(directory, serverId)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to accept pending permission requests for active sessions:', error)
|
||||
logger.error(`Failed to accept pending permission requests for server ${serverId}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
async suppressesPermissionNotification(
|
||||
event: SSEEvent,
|
||||
sessionId: string | undefined,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<boolean> {
|
||||
if (event.type !== 'permission.asked' || !sessionId) {
|
||||
return false
|
||||
}
|
||||
return (await this.getEffectiveMode(sessionId, serverId)).mode === 'auto'
|
||||
}
|
||||
|
||||
private effectiveModeForRoot(
|
||||
sessionId: string,
|
||||
rootSessionId: string | null,
|
||||
serverId: string,
|
||||
): SessionPermissionModeState {
|
||||
if (!rootSessionId) {
|
||||
return { sessionId, rootSessionId: sessionId, mode: 'ask', lockedReason: null }
|
||||
}
|
||||
|
||||
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId)
|
||||
const lockedReason = this.lockReasonForRoot(sessionId, rootSessionId, serverId)
|
||||
|
||||
if (lockedReason === 'schedule') {
|
||||
return { sessionId, rootSessionId, mode: 'ask', lockedReason }
|
||||
}
|
||||
|
||||
const stored = getSessionPermissionMode(this.db, rootSessionId)
|
||||
const stored = getSessionPermissionMode(this.db, rootSessionId, serverId)
|
||||
return { sessionId, rootSessionId, mode: stored ?? 'ask', lockedReason }
|
||||
}
|
||||
|
||||
private lockReasonForRoot(sessionId: string, rootSessionId: string): SessionLockReason | null {
|
||||
if (getScheduleRunBySessionId(this.db, rootSessionId)) {
|
||||
private lockReasonForRoot(
|
||||
sessionId: string,
|
||||
rootSessionId: string,
|
||||
serverId: string,
|
||||
): SessionLockReason | null {
|
||||
if (serverId === LOCAL_OPENCODE_SERVER_ID && getScheduleRunBySessionId(this.db, rootSessionId)) {
|
||||
return 'schedule'
|
||||
}
|
||||
|
||||
return rootSessionId !== sessionId ? 'child' : null
|
||||
}
|
||||
|
||||
private async acceptPendingRequestsInDirectory(directory: string, expectedRootSessionId?: string): Promise<void> {
|
||||
private async acceptPendingRequestsInDirectory(
|
||||
directory: string,
|
||||
serverId: string,
|
||||
expectedRootSessionId?: string,
|
||||
): Promise<void> {
|
||||
let requests: PermissionRequest[]
|
||||
try {
|
||||
const result = await this.openCodeClient.api.permission.request.list(openCodeLocation(directory))
|
||||
const result = await this.clients
|
||||
.getClient(serverId)
|
||||
.api.permission.request.list(openCodeLocation(directory))
|
||||
requests = result.data
|
||||
} catch (error) {
|
||||
logger.error(`Failed to list pending permission requests for directory ${directory}:`, error)
|
||||
@@ -179,13 +233,13 @@ export class SessionPermissionModeService {
|
||||
}
|
||||
|
||||
for (const request of requests) {
|
||||
await this.autoAcceptRequest(request.sessionID, request.id, expectedRootSessionId)
|
||||
await this.autoAcceptRequest(request.sessionID, request.id, serverId, expectedRootSessionId)
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveSessionDirectory(sessionId: string): Promise<string | null> {
|
||||
private async resolveSessionDirectory(sessionId: string, serverId: string): Promise<string | null> {
|
||||
try {
|
||||
const session = await this.openCodeClient.api.session.get({ sessionID: sessionId })
|
||||
const session = await this.clients.getClient(serverId).api.session.get({ sessionID: sessionId })
|
||||
return session.location.directory
|
||||
} catch (error) {
|
||||
logger.error(`Failed to resolve directory for session ${sessionId}:`, error)
|
||||
@@ -196,9 +250,10 @@ export class SessionPermissionModeService {
|
||||
private async autoAcceptRequest(
|
||||
sessionID: string,
|
||||
requestID: string,
|
||||
serverId: string,
|
||||
expectedRootSessionId?: string,
|
||||
): Promise<void> {
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionID)
|
||||
const rootSessionId = await this.resolveRootSessionIdOrNull(sessionID, serverId)
|
||||
if (!rootSessionId) {
|
||||
return
|
||||
}
|
||||
@@ -207,25 +262,27 @@ export class SessionPermissionModeService {
|
||||
return
|
||||
}
|
||||
|
||||
if (this.effectiveModeForRoot(sessionID, rootSessionId).mode !== 'auto') {
|
||||
if (this.effectiveModeForRoot(sessionID, rootSessionId, serverId).mode !== 'auto') {
|
||||
return
|
||||
}
|
||||
|
||||
await this.replyOnce(sessionID, requestID)
|
||||
await this.replyOnce(sessionID, requestID, serverId)
|
||||
}
|
||||
|
||||
private async replyOnce(sessionID: string, requestID: string): Promise<void> {
|
||||
private async replyOnce(sessionID: string, requestID: string, serverId: string): Promise<void> {
|
||||
try {
|
||||
await this.openCodeClient.api.permission.reply({ sessionID, requestID, decision: 'once' })
|
||||
await this.clients
|
||||
.getClient(serverId)
|
||||
.api.permission.reply({ sessionID, requestID, decision: 'once' })
|
||||
logger.info(`Auto-accepted permission request ${requestID} for session ${sessionID}`)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to auto-accept permission request ${requestID} for session ${sessionID}:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
private async resolveRootSessionIdOrNull(sessionId: string): Promise<string | null> {
|
||||
private async resolveRootSessionIdOrNull(sessionId: string, serverId: string): Promise<string | null> {
|
||||
try {
|
||||
return await this.ancestry.resolveRootSessionId(sessionId)
|
||||
return await this.ancestry.resolveRootSessionId(sessionId, serverId)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type SessionMessageAssistant,
|
||||
type SessionMessageInfo,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { truncateText } from '../utils/text-truncate'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { sseAggregator, type SSEEvent } from './sse-aggregator'
|
||||
@@ -47,7 +48,12 @@ export function sessionSettleSignal(event: SSEEvent, sessionId: string): Session
|
||||
}
|
||||
}
|
||||
|
||||
export function waitForSessionSettled(client: OpenCodeClient, sessionId: string, timeoutMs: number): Promise<void> {
|
||||
export function waitForSessionSettled(
|
||||
client: OpenCodeClient,
|
||||
sessionId: string,
|
||||
timeoutMs: number,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
): Promise<void> {
|
||||
if (timeoutMs <= 0) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
@@ -69,7 +75,10 @@ export function waitForSessionSettled(client: OpenCodeClient, sessionId: string,
|
||||
resolve()
|
||||
}
|
||||
|
||||
unsubscribe = sseAggregator.onEvent((_directory, event) => {
|
||||
unsubscribe = sseAggregator.onServerEvent((eventServerId, _directory, event) => {
|
||||
if (eventServerId !== serverId) {
|
||||
return
|
||||
}
|
||||
if (sessionSettleSignal(event, sessionId)) {
|
||||
finish()
|
||||
}
|
||||
|
||||
@@ -10,6 +10,9 @@ import { encodeSSEFrame } from '../utils/sse-frame'
|
||||
type SSEClientCallback = (event: string, data: string) => void
|
||||
type SSEClientFrameWriter = (frame: Uint8Array) => void
|
||||
type SSEEventListener = (directory: string | null, event: SSEEvent) => void
|
||||
type ServerEventListener = (serverId: string, directory: string | null, event: SSEEvent) => void
|
||||
type ServerConnectedListener = (serverId: string) => void
|
||||
type RemoteSubagentResolver = (serverId: string, sessionId: string) => boolean
|
||||
|
||||
export type RemoteReplayHandler = (clientId: string, serverId: string, directory: string) => void | Promise<void>
|
||||
|
||||
@@ -20,6 +23,7 @@ interface SSEClient {
|
||||
directories: Set<string>
|
||||
visible: boolean
|
||||
activeSessionId: string | null
|
||||
activeServerId: string | null
|
||||
}
|
||||
|
||||
export type SSEEvent = V2Event
|
||||
@@ -54,7 +58,10 @@ class SSEAggregator {
|
||||
private activeSessions: Map<string, Set<string>> = new Map()
|
||||
private sessionDirectories: Map<string, string> = new Map()
|
||||
private eventListeners: Set<SSEEventListener> = new Set()
|
||||
private serverEventListeners: Set<ServerEventListener> = new Set()
|
||||
private upstreamConnectedListeners: Set<() => void> = new Set()
|
||||
private serverConnectedListeners: Set<ServerConnectedListener> = new Set()
|
||||
private remoteSubagentResolver: RemoteSubagentResolver | null = null
|
||||
private subagentSessions: Map<string, Set<string>> = new Map()
|
||||
private upstream: EventSource | null = null
|
||||
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
@@ -122,7 +129,8 @@ class SSEAggregator {
|
||||
writeFrame,
|
||||
directories: new Set(directories),
|
||||
visible: false,
|
||||
activeSessionId: null
|
||||
activeSessionId: null,
|
||||
activeServerId: null
|
||||
}
|
||||
this.clients.set(id, client)
|
||||
directories.forEach(dir => this.indexClientDirectory(id, dir))
|
||||
@@ -436,6 +444,7 @@ class SSEAggregator {
|
||||
this.upstreamConnectedListeners.forEach(listener => {
|
||||
try { listener() } catch { /* ignore listener errors */ }
|
||||
})
|
||||
this.notifyServerConnected(LOCAL_OPENCODE_SERVER_ID)
|
||||
}
|
||||
|
||||
private broadcastResync(): void {
|
||||
@@ -456,11 +465,37 @@ class SSEAggregator {
|
||||
return () => { this.eventListeners.delete(listener) }
|
||||
}
|
||||
|
||||
onServerEvent(listener: ServerEventListener): () => void {
|
||||
this.serverEventListeners.add(listener)
|
||||
return () => { this.serverEventListeners.delete(listener) }
|
||||
}
|
||||
|
||||
onUpstreamConnected(listener: () => void): () => void {
|
||||
this.upstreamConnectedListeners.add(listener)
|
||||
return () => { this.upstreamConnectedListeners.delete(listener) }
|
||||
}
|
||||
|
||||
onServerConnected(listener: ServerConnectedListener): () => void {
|
||||
this.serverConnectedListeners.add(listener)
|
||||
return () => { this.serverConnectedListeners.delete(listener) }
|
||||
}
|
||||
|
||||
notifyServerEvent(serverId: string, directory: string | null, event: SSEEvent): void {
|
||||
this.serverEventListeners.forEach(listener => {
|
||||
try { listener(serverId, directory, event) } catch { /* ignore listener errors */ }
|
||||
})
|
||||
}
|
||||
|
||||
notifyServerConnected(serverId: string): void {
|
||||
this.serverConnectedListeners.forEach(listener => {
|
||||
try { listener(serverId) } catch { /* ignore listener errors */ }
|
||||
})
|
||||
}
|
||||
|
||||
setRemoteSubagentResolver(resolver: RemoteSubagentResolver | null): void {
|
||||
this.remoteSubagentResolver = resolver
|
||||
}
|
||||
|
||||
private handleUpstreamMessage(data: string): void {
|
||||
let event: V2Event
|
||||
try {
|
||||
@@ -531,6 +566,7 @@ class SSEAggregator {
|
||||
this.eventListeners.forEach(listener => {
|
||||
try { listener(directory, event) } catch { /* ignore listener errors */ }
|
||||
})
|
||||
this.notifyServerEvent(LOCAL_OPENCODE_SERVER_ID, directory, event)
|
||||
}
|
||||
|
||||
private writeEnvelopeToClients(clientIds: Iterable<string>, directory: string | null, payloadJson: string): void {
|
||||
@@ -692,7 +728,12 @@ class SSEAggregator {
|
||||
return this.clients.size
|
||||
}
|
||||
|
||||
setClientVisibility(id: string, visible: boolean, activeSessionId: string | null = null): boolean {
|
||||
setClientVisibility(
|
||||
id: string,
|
||||
visible: boolean,
|
||||
activeSessionId: string | null = null,
|
||||
activeServerId: string | null = null
|
||||
): boolean {
|
||||
const client = this.clients.get(id)
|
||||
if (!client) {
|
||||
logger.warn(`setClientVisibility: client ${id} not found`)
|
||||
@@ -700,19 +741,23 @@ class SSEAggregator {
|
||||
}
|
||||
client.visible = visible
|
||||
client.activeSessionId = visible ? activeSessionId : null
|
||||
client.activeServerId = visible ? (activeServerId ?? LOCAL_OPENCODE_SERVER_ID) : null
|
||||
return true
|
||||
}
|
||||
|
||||
isSessionBeingViewed(sessionId: string): boolean {
|
||||
isSessionBeingViewed(sessionId: string, serverId: string = LOCAL_OPENCODE_SERVER_ID): boolean {
|
||||
for (const client of this.clients.values()) {
|
||||
if (client.visible && client.activeSessionId === sessionId) {
|
||||
if (client.visible && client.activeSessionId === sessionId && client.activeServerId === serverId) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
isSubagentSession(sessionId: string): boolean {
|
||||
isSubagentSession(sessionId: string, serverId: string = LOCAL_OPENCODE_SERVER_ID): boolean {
|
||||
if (serverId !== LOCAL_OPENCODE_SERVER_ID) {
|
||||
return this.remoteSubagentResolver?.(serverId, sessionId) ?? false
|
||||
}
|
||||
for (const sessions of this.subagentSessions.values()) {
|
||||
if (sessions.has(sessionId)) {
|
||||
return true
|
||||
@@ -760,7 +805,10 @@ class SSEAggregator {
|
||||
this.directoryClients.clear()
|
||||
this.clients.clear()
|
||||
this.eventListeners.clear()
|
||||
this.serverEventListeners.clear()
|
||||
this.upstreamConnectedListeners.clear()
|
||||
this.serverConnectedListeners.clear()
|
||||
this.remoteSubagentResolver = null
|
||||
this.remoteReplayHandler = null
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,12 @@ export interface TerminalSize {
|
||||
rows: number
|
||||
}
|
||||
|
||||
export interface TerminalTarget {
|
||||
client: OpenCodeClient
|
||||
baseUrl: () => string
|
||||
includeLocalCredentials: boolean
|
||||
}
|
||||
|
||||
export class TerminalNotFoundError extends Error {
|
||||
constructor(ptyID: string) {
|
||||
super(`Terminal not found: ${ptyID}`)
|
||||
@@ -32,24 +38,30 @@ export class TerminalNotFoundError extends Error {
|
||||
|
||||
export class TerminalService {
|
||||
constructor(
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
private readonly target: TerminalTarget,
|
||||
private readonly credentialProvider: CredentialProvider,
|
||||
private readonly upstreamBaseUrl: () => string,
|
||||
private readonly openSocket: (url: string) => WebSocket = (url) => new WebSocket(url),
|
||||
) {}
|
||||
|
||||
forTarget(target: TerminalTarget): TerminalService {
|
||||
return new TerminalService(target, this.credentialProvider, this.openSocket)
|
||||
}
|
||||
|
||||
async list(directory: string): Promise<TerminalInfo[]> {
|
||||
const result = await this.openCodeClient.api.pty.list({ location: { directory } })
|
||||
const result = await this.target.client.api.pty.list({ location: { directory } })
|
||||
return result.data.map((pty) => this.toTerminalInfo(pty))
|
||||
}
|
||||
|
||||
async create(directory: string, input: CreateTerminalInput): Promise<TerminalInfo> {
|
||||
const result = await this.openCodeClient.api.pty.create({
|
||||
const result = await this.target.client.api.pty.create({
|
||||
location: { directory },
|
||||
title: formatTerminalTitle({ kind: input.kind, name: input.name, actionId: input.actionId }),
|
||||
...(input.command !== undefined ? { command: input.command } : {}),
|
||||
...(input.args !== undefined ? { args: input.args } : {}),
|
||||
env: { ...this.credentialProvider.getGhCliEnv({ cwd: directory }), ...input.env },
|
||||
env: {
|
||||
...(this.target.includeLocalCredentials ? this.credentialProvider.getGhCliEnv({ cwd: directory }) : {}),
|
||||
...input.env,
|
||||
},
|
||||
})
|
||||
return this.toTerminalInfo(result.data)
|
||||
}
|
||||
@@ -64,11 +76,11 @@ export class TerminalService {
|
||||
}
|
||||
|
||||
async resize(directory: string, ptyID: string, size: TerminalSize): Promise<void> {
|
||||
await this.openCodeClient.api.pty.update({ ptyID, location: { directory }, size })
|
||||
await this.target.client.api.pty.update({ ptyID, location: { directory }, size })
|
||||
}
|
||||
|
||||
async remove(directory: string, ptyID: string): Promise<void> {
|
||||
await this.openCodeClient.api.pty.remove({ ptyID, location: { directory } })
|
||||
await this.target.client.api.pty.remove({ ptyID, location: { directory } })
|
||||
}
|
||||
|
||||
async removeAll(directory: string): Promise<void> {
|
||||
@@ -92,13 +104,13 @@ export class TerminalService {
|
||||
): Promise<WebSocketBridge> {
|
||||
await this.requireTerminal(directory, ptyID)
|
||||
|
||||
const result = await this.openCodeClient.api.pty.connect.token({
|
||||
const result = await this.target.client.api.pty.connect.token({
|
||||
ptyID,
|
||||
location: { directory },
|
||||
'x-opencode-ticket': '1',
|
||||
})
|
||||
|
||||
const base = new URL(this.upstreamBaseUrl())
|
||||
const base = new URL(this.target.baseUrl())
|
||||
if (!base.pathname.endsWith('/')) base.pathname += '/'
|
||||
const socketUrl = new URL(`api/pty/${encodeURIComponent(ptyID)}/connect`, base)
|
||||
socketUrl.searchParams.set('ticket', result.data.ticket)
|
||||
@@ -111,7 +123,7 @@ export class TerminalService {
|
||||
private async removePersistentTerminals(directory: string): Promise<void> {
|
||||
let cursor: string | undefined
|
||||
do {
|
||||
const page = await this.openCodeClient.api.session.list({ directory, cursor })
|
||||
const page = await this.target.client.api.session.list({ directory, cursor })
|
||||
for (const session of page.data) {
|
||||
await this.removeSessionPersistentTerminals(session.id)
|
||||
}
|
||||
@@ -122,7 +134,7 @@ export class TerminalService {
|
||||
private async removeSessionPersistentTerminals(sessionID: string): Promise<void> {
|
||||
let terminals: OpenCodePersistentPty[]
|
||||
try {
|
||||
terminals = await this.openCodeClient.api.experimental.persistentPty.list({ sessionID })
|
||||
terminals = await this.target.client.api.experimental.persistentPty.list({ sessionID })
|
||||
} catch (error: unknown) {
|
||||
if (openCodeErrorStatus(error) === 404) return
|
||||
throw error
|
||||
@@ -130,7 +142,7 @@ export class TerminalService {
|
||||
|
||||
for (const terminal of terminals) {
|
||||
try {
|
||||
await this.openCodeClient.api.experimental.persistentPty.remove({ ptyID: terminal.id })
|
||||
await this.target.client.api.experimental.persistentPty.remove({ ptyID: terminal.id })
|
||||
} catch (error: unknown) {
|
||||
if (openCodeErrorStatus(error) === 404) continue
|
||||
throw error
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export function parseTerminalCursor(raw: string | undefined): number | undefined | null {
|
||||
if (raw === undefined) return undefined
|
||||
if (!/^-?\d+$/.test(raw)) return null
|
||||
const parsed = Number(raw)
|
||||
if (!Number.isSafeInteger(parsed) || parsed < -1) return null
|
||||
return parsed
|
||||
}
|
||||
@@ -53,7 +53,7 @@ describe('multi-run fusions', () => {
|
||||
function createRun(models = ['openai/a', 'openai/b']): number {
|
||||
const run = createMultiRunWithEntries(
|
||||
db,
|
||||
{ repoId: REPO_ID, name: 'Sweep', prompt: 'go', isolated: true, baseRef: null },
|
||||
{ repoId: REPO_ID, serverId: 'local', directory: null, name: 'Sweep', prompt: 'go', isolated: true, baseRef: null },
|
||||
models,
|
||||
)
|
||||
return run.id
|
||||
@@ -167,7 +167,7 @@ describe('multi-run fusions', () => {
|
||||
truncated: false,
|
||||
})
|
||||
|
||||
const listed = listMultiRuns(db, REPO_ID, 20)
|
||||
const listed = listMultiRuns(db, { kind: 'repo', repoId: REPO_ID }, 20)
|
||||
expect(listed[0]?.fusions).toHaveLength(1)
|
||||
expect(listed[0]?.fusions[0]?.sources).toHaveLength(2)
|
||||
})
|
||||
@@ -175,7 +175,7 @@ describe('multi-run fusions', () => {
|
||||
it('returns an empty fusion list for runs without fusions', () => {
|
||||
const multiRunId = createRun()
|
||||
expect(getMultiRun(db, multiRunId)?.fusions).toEqual([])
|
||||
expect(listMultiRuns(db, REPO_ID, 20)[0]?.fusions).toEqual([])
|
||||
expect(listMultiRuns(db, { kind: 'repo', repoId: REPO_ID }, 20)[0]?.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('reads a fusion by its request id', () => {
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import migration from '../../src/db/migrations/202610181310-multi-run-targets'
|
||||
import { ensureMultiRunTables } from '../../src/db/multi-runs'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
dflt_value: string | null
|
||||
}
|
||||
|
||||
function createLegacyTable(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE multi_runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
repo_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
prompt TEXT NOT NULL,
|
||||
isolated INTEGER NOT NULL,
|
||||
base_ref TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
db.run('CREATE INDEX idx_multi_runs_repo ON multi_runs(repo_id, created_at DESC)')
|
||||
}
|
||||
|
||||
function columns(db: Database): ColumnInfo[] {
|
||||
return db.prepare('PRAGMA table_info(multi_runs)').all() as ColumnInfo[]
|
||||
}
|
||||
|
||||
describe('202610181310-multi-run-targets migration', () => {
|
||||
let db: Database
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('makes repo_id nullable and adds the server target columns', () => {
|
||||
db = new Database(':memory:')
|
||||
createLegacyTable(db)
|
||||
|
||||
migration.up(db)
|
||||
|
||||
const byName = new Map(columns(db).map((column) => [column.name, column]))
|
||||
expect(byName.get('repo_id')?.notnull).toBe(0)
|
||||
expect(byName.get('server_id')).toMatchObject({ notnull: 1, dflt_value: "'local'" })
|
||||
expect(byName.has('directory')).toBe(true)
|
||||
})
|
||||
|
||||
it('preserves existing rows and their ids', () => {
|
||||
db = new Database(':memory:')
|
||||
createLegacyTable(db)
|
||||
db.run(
|
||||
`INSERT INTO multi_runs(id, repo_id, name, prompt, isolated, base_ref, created_at)
|
||||
VALUES(7, 3, 'Sweep', 'go', 1, 'main', 1700000000000)`,
|
||||
)
|
||||
|
||||
migration.up(db)
|
||||
|
||||
expect(
|
||||
db.prepare('SELECT id, repo_id, server_id, directory, name, prompt, isolated, base_ref, created_at FROM multi_runs').get(),
|
||||
).toEqual({
|
||||
id: 7,
|
||||
repo_id: 3,
|
||||
server_id: 'local',
|
||||
directory: null,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
isolated: 1,
|
||||
base_ref: 'main',
|
||||
created_at: 1700000000000,
|
||||
})
|
||||
})
|
||||
|
||||
it('recreates the repo and server indexes', () => {
|
||||
db = new Database(':memory:')
|
||||
createLegacyTable(db)
|
||||
|
||||
migration.up(db)
|
||||
|
||||
const indexes = (
|
||||
db.prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'multi_runs'").all() as Array<{
|
||||
name: string
|
||||
}>
|
||||
).map((index) => index.name)
|
||||
expect(indexes).toEqual(expect.arrayContaining(['idx_multi_runs_repo', 'idx_multi_runs_server']))
|
||||
})
|
||||
|
||||
it('is idempotent', () => {
|
||||
db = new Database(':memory:')
|
||||
createLegacyTable(db)
|
||||
db.run(
|
||||
`INSERT INTO multi_runs(id, repo_id, name, prompt, isolated, base_ref, created_at)
|
||||
VALUES(1, 2, 'Sweep', 'go', 0, NULL, 1)`,
|
||||
)
|
||||
|
||||
migration.up(db)
|
||||
migration.up(db)
|
||||
|
||||
expect(db.prepare('SELECT COUNT(*) AS count FROM multi_runs').get()).toEqual({ count: 1 })
|
||||
expect(columns(db).filter((column) => column.name === 'server_id')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('skips a table that already has the new schema', () => {
|
||||
db = new Database(':memory:')
|
||||
ensureMultiRunTables(db)
|
||||
db.run(
|
||||
`INSERT INTO multi_runs(id, repo_id, server_id, directory, name, prompt, isolated, base_ref, created_at)
|
||||
VALUES(4, NULL, 'srv_kitchen', '/srv/app', 'Remote sweep', 'go', 1, NULL, 2)`,
|
||||
)
|
||||
|
||||
migration.up(db)
|
||||
|
||||
expect(db.prepare('SELECT id, repo_id, server_id, directory FROM multi_runs').get()).toEqual({
|
||||
id: 4,
|
||||
repo_id: null,
|
||||
server_id: 'srv_kitchen',
|
||||
directory: '/srv/app',
|
||||
})
|
||||
})
|
||||
|
||||
it('drops remote rows and restores the repo-only schema on down', () => {
|
||||
db = new Database(':memory:')
|
||||
ensureMultiRunTables(db)
|
||||
db.run(
|
||||
`INSERT INTO multi_runs(id, repo_id, server_id, directory, name, prompt, isolated, base_ref, created_at)
|
||||
VALUES(1, 5, 'local', NULL, 'Local', 'go', 0, NULL, 1),
|
||||
(2, NULL, 'srv_kitchen', '/srv/app', 'Remote', 'go', 0, NULL, 2)`,
|
||||
)
|
||||
|
||||
migration.down(db)
|
||||
|
||||
expect(db.prepare('SELECT id, repo_id FROM multi_runs').all()).toEqual([{ id: 1, repo_id: 5 }])
|
||||
expect(columns(db).map((column) => column.name)).toEqual([
|
||||
'id',
|
||||
'repo_id',
|
||||
'name',
|
||||
'prompt',
|
||||
'isolated',
|
||||
'base_ref',
|
||||
'created_at',
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import migration from '../../src/db/migrations/202610181320-remote-schedule-targets'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
notnull: number
|
||||
}
|
||||
|
||||
const MIGRATION_ID = '202610181320-remote-schedule-targets'
|
||||
|
||||
function columns(db: Database, table: string): ColumnInfo[] {
|
||||
return db.prepare(`PRAGMA table_info(${table})`).all() as ColumnInfo[]
|
||||
}
|
||||
|
||||
describe('remote schedule target migration', () => {
|
||||
it('preserves jobs and runs while making repo_id nullable', () => {
|
||||
const db = new Database(':memory:')
|
||||
db.exec('PRAGMA foreign_keys = ON')
|
||||
migrate(db, allMigrations.filter((entry) => entry.id !== MIGRATION_ID))
|
||||
|
||||
const now = Date.now()
|
||||
db.exec(
|
||||
`INSERT INTO repos (id, repo_url, local_path, branch, default_branch, clone_status, cloned_at)
|
||||
VALUES (1, 'https://github.com/test/my-repo', 'repos/my-repo', 'main', 'main', 'ready', ${now})`,
|
||||
)
|
||||
db.prepare(
|
||||
`INSERT INTO schedule_jobs (id, repo_id, name, enabled, schedule_mode, prompt, workspace_mode, created_at, updated_at)
|
||||
VALUES (7, 1, 'Local job', 1, 'interval', 'Run it', 'shared-worktree', ?, ?)`,
|
||||
).run(now, now)
|
||||
db.prepare(
|
||||
`INSERT INTO schedule_runs (id, job_id, repo_id, trigger_source, status, started_at, created_at, session_id)
|
||||
VALUES (5, 7, 1, 'manual', 'completed', ?, ?, 'ses_local')`,
|
||||
).run(now, now)
|
||||
|
||||
migration.up(db)
|
||||
|
||||
const jobColumns = columns(db, 'schedule_jobs')
|
||||
expect(jobColumns.find((column) => column.name === 'repo_id')?.notnull).toBe(0)
|
||||
expect(jobColumns.find((column) => column.name === 'server_id')?.notnull).toBe(1)
|
||||
expect(jobColumns.some((column) => column.name === 'directory')).toBe(true)
|
||||
|
||||
const runColumns = columns(db, 'schedule_runs')
|
||||
expect(runColumns.find((column) => column.name === 'repo_id')?.notnull).toBe(0)
|
||||
expect(runColumns.some((column) => column.name === 'server_id')).toBe(true)
|
||||
|
||||
const job = db.prepare('SELECT * FROM schedule_jobs WHERE id = 7').get() as Record<string, unknown>
|
||||
expect(job).toMatchObject({
|
||||
repo_id: 1,
|
||||
server_id: 'local',
|
||||
directory: null,
|
||||
name: 'Local job',
|
||||
workspace_mode: 'shared-worktree',
|
||||
})
|
||||
|
||||
const run = db.prepare('SELECT * FROM schedule_runs WHERE id = 5').get() as Record<string, unknown>
|
||||
expect(run).toMatchObject({ repo_id: 1, server_id: 'local', session_id: 'ses_local', status: 'completed' })
|
||||
|
||||
db.prepare(
|
||||
`INSERT INTO schedule_jobs (id, repo_id, server_id, directory, name, enabled, schedule_mode, prompt, created_at, updated_at)
|
||||
VALUES (8, NULL, 'srv_kitchen', '/srv/project', 'Remote job', 1, 'interval', 'Run remotely', ?, ?)`,
|
||||
).run(now, now)
|
||||
db.prepare(
|
||||
`INSERT INTO schedule_runs (id, job_id, repo_id, server_id, trigger_source, status, started_at, created_at)
|
||||
VALUES (6, 8, NULL, 'srv_kitchen', 'manual', 'running', ?, ?)`,
|
||||
).run(now, now)
|
||||
|
||||
expect(db.prepare('SELECT COUNT(*) AS count FROM schedule_runs').get()).toEqual({ count: 2 })
|
||||
expect(db.prepare('PRAGMA foreign_key_check').all()).toEqual([])
|
||||
})
|
||||
|
||||
it('is idempotent', () => {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
|
||||
const now = Date.now()
|
||||
db.prepare(
|
||||
`INSERT INTO schedule_jobs (id, repo_id, server_id, directory, name, enabled, schedule_mode, prompt, created_at, updated_at)
|
||||
VALUES (3, NULL, 'srv_kitchen', '/srv/project', 'Remote job', 1, 'interval', 'Run remotely', ?, ?)`,
|
||||
).run(now, now)
|
||||
|
||||
migration.up(db)
|
||||
|
||||
expect(db.prepare('SELECT COUNT(*) AS count FROM schedule_jobs').get()).toEqual({ count: 1 })
|
||||
expect(db.prepare('PRAGMA foreign_key_check').all()).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -66,7 +66,7 @@ describe('schedule database queries', () => {
|
||||
|
||||
const jobs = schedulesDb.listScheduleJobsByRepo(mockDb, 42)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC')
|
||||
expect(jobs[0]).toMatchObject({
|
||||
id: 7,
|
||||
repoId: 42,
|
||||
@@ -86,7 +86,7 @@ describe('schedule database queries', () => {
|
||||
|
||||
const jobIds = schedulesDb.listScheduleJobIdsByRepo(mockDb, 42)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT id FROM schedule_jobs WHERE repo_id = ? ORDER BY created_at DESC')
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT id FROM schedule_jobs WHERE repo_id IS ? ORDER BY created_at DESC')
|
||||
expect(stmt.all).toHaveBeenCalledWith(42)
|
||||
expect(jobIds).toEqual([7, 8])
|
||||
})
|
||||
@@ -122,6 +122,8 @@ describe('schedule database queries', () => {
|
||||
|
||||
expect(insertStmt.run).toHaveBeenCalledWith(
|
||||
42,
|
||||
'local',
|
||||
null,
|
||||
'Weekly engineering summary',
|
||||
'Summarize repo health and recent changes.',
|
||||
1,
|
||||
@@ -196,6 +198,7 @@ describe('schedule database queries', () => {
|
||||
null,
|
||||
null,
|
||||
'worktree',
|
||||
null,
|
||||
expect.any(Number),
|
||||
null,
|
||||
42,
|
||||
@@ -222,9 +225,9 @@ describe('schedule database queries', () => {
|
||||
|
||||
const deleted = schedulesDb.deleteScheduleJob(mockDb, 42, 7)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(1, 'DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(1, 'DELETE FROM schedule_runs WHERE repo_id IS ? AND job_id = ?')
|
||||
expect(deleteRunsStmt.run).toHaveBeenCalledWith(42, 7)
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenNthCalledWith(2, 'DELETE FROM schedule_jobs WHERE repo_id IS ? AND id = ?')
|
||||
expect(deleteJobStmt.run).toHaveBeenCalledWith(42, 7)
|
||||
expect(deleted).toBe(true)
|
||||
})
|
||||
@@ -341,7 +344,7 @@ describe('schedule database queries', () => {
|
||||
createdAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
})
|
||||
|
||||
expect(insertStmt.run).toHaveBeenCalledWith(7, 42, 'manual', 'running', expect.any(Number), expect.any(Number))
|
||||
expect(insertStmt.run).toHaveBeenCalledWith(7, 42, 'local', 'manual', 'running', expect.any(Number), expect.any(Number))
|
||||
expect(run.id).toBe(5)
|
||||
})
|
||||
|
||||
@@ -416,7 +419,7 @@ describe('schedule database queries', () => {
|
||||
|
||||
const job = schedulesDb.getScheduleJobById(mockDb, 42, 7)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_jobs WHERE repo_id IS ? AND id = ?')
|
||||
expect(stmt.get).toHaveBeenCalledWith(42, 7)
|
||||
expect(job).toMatchObject({ id: 7, repoId: 42, name: 'Weekly engineering summary', branch: null })
|
||||
})
|
||||
@@ -451,7 +454,7 @@ describe('schedule database queries', () => {
|
||||
|
||||
const result = schedulesDb.deleteScheduleJob(mockDb, 42, 7)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('DELETE FROM schedule_jobs WHERE repo_id = ? AND id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('DELETE FROM schedule_jobs WHERE repo_id IS ? AND id = ?')
|
||||
expect(stmt.run).toHaveBeenCalledWith(42, 7)
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
@@ -477,7 +480,7 @@ describe('schedule database queries', () => {
|
||||
|
||||
schedulesDb.updateScheduleJobRunState(mockDb, 42, 7, { lastRunAt, nextRunAt })
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id = ? AND id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('UPDATE schedule_jobs SET last_run_at = ?, next_run_at = ?, updated_at = ? WHERE repo_id IS ? AND id = ?')
|
||||
expect(stmt.run).toHaveBeenCalledWith(lastRunAt, nextRunAt, expect.any(Number), 42, 7)
|
||||
})
|
||||
|
||||
@@ -525,7 +528,7 @@ describe('schedule database queries', () => {
|
||||
|
||||
const run = schedulesDb.getScheduleRunById(mockDb, 42, 7, 5)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT * FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id = ?')
|
||||
expect(stmt.get).toHaveBeenCalledWith(42, 7, 5)
|
||||
expect(run).toMatchObject({ id: 5, jobId: 7, repoId: 42, status: 'running', runBranch: null, commitHash: null, worktreePath: null })
|
||||
})
|
||||
@@ -629,7 +632,7 @@ describe('schedule database queries', () => {
|
||||
expect(sql).toContain("sj.name LIKE ? ESCAPE '\\'")
|
||||
expect(sql).toContain("r.local_path LIKE ? ESCAPE '\\'")
|
||||
const pattern = '%50\\%\\_off%'
|
||||
expect(stmt.all).toHaveBeenCalledWith(pattern, pattern, pattern, pattern, pattern, pattern, 50, 0)
|
||||
expect(stmt.all).toHaveBeenCalledWith(pattern, pattern, pattern, pattern, pattern, pattern, pattern, pattern, 50, 0)
|
||||
})
|
||||
|
||||
it('ignores a blank search term', () => {
|
||||
@@ -696,7 +699,7 @@ describe('schedule database queries', () => {
|
||||
|
||||
const deleted = schedulesDb.deleteScheduleRunById(mockDb, 42, 7, 5)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id = ?')
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('DELETE FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id = ?')
|
||||
expect(stmt.run).toHaveBeenCalledWith(42, 7, 5)
|
||||
expect(deleted).toBe(true)
|
||||
})
|
||||
@@ -707,7 +710,7 @@ describe('schedule database queries', () => {
|
||||
|
||||
const cleared = schedulesDb.deleteScheduleRunsByIds(mockDb, 42, 7, [3, 1])
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('DELETE FROM schedule_runs WHERE repo_id = ? AND job_id = ? AND id IN (?, ?)')
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('DELETE FROM schedule_runs WHERE repo_id IS ? AND job_id = ? AND id IN (?, ?)')
|
||||
expect(stmt.run).toHaveBeenCalledWith(42, 7, 3, 1)
|
||||
expect(cleared).toBe(2)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
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'
|
||||
|
||||
function createTestDb(): Database {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
return db
|
||||
}
|
||||
|
||||
function createLegacyTables(db: Database): void {
|
||||
db.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
|
||||
)
|
||||
`)
|
||||
db.run(`
|
||||
CREATE TABLE session_goals (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id TEXT NOT NULL,
|
||||
directory TEXT NOT NULL,
|
||||
objective TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('active','paused','completed','blocked','stopped')),
|
||||
stop_reason TEXT,
|
||||
turn_state TEXT NOT NULL DEFAULT 'waiting',
|
||||
continuation_count INTEGER NOT NULL DEFAULT 0,
|
||||
max_continuations INTEGER NOT NULL,
|
||||
token_budget INTEGER,
|
||||
tokens_at_start INTEGER NOT NULL DEFAULT 0,
|
||||
tokens_used INTEGER NOT NULL DEFAULT 0,
|
||||
consecutive_blocked INTEGER NOT NULL DEFAULT 0,
|
||||
last_verdict TEXT,
|
||||
last_reason TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
finished_at INTEGER
|
||||
)
|
||||
`)
|
||||
db.run(`
|
||||
CREATE UNIQUE INDEX idx_session_goals_open
|
||||
ON session_goals(session_id)
|
||||
WHERE status IN ('active','paused')
|
||||
`)
|
||||
}
|
||||
|
||||
function tableColumns(db: Database, table: string): string[] {
|
||||
return (db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).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,
|
||||
)
|
||||
}
|
||||
|
||||
describe('202610181300 session server scope migration', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDb()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('adds server_id to both session tables on a fresh database', () => {
|
||||
expect(tableColumns(db, 'session_permission_modes')).toContain('server_id')
|
||||
expect(tableColumns(db, 'session_goals')).toContain('server_id')
|
||||
expect(openGoalIndexColumns(db)).toEqual(['server_id', 'session_id'])
|
||||
})
|
||||
|
||||
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' })
|
||||
|
||||
expect(local).not.toBeNull()
|
||||
expect(remote).not.toBeNull()
|
||||
expect(duplicateRemote).toBeNull()
|
||||
})
|
||||
|
||||
it('upgrades legacy tables, keeps existing rows local and tolerates a second run', () => {
|
||||
const legacyDb = new Database(':memory:')
|
||||
createLegacyTables(legacyDb)
|
||||
legacyDb
|
||||
.prepare('INSERT INTO session_permission_modes(session_id, mode, updated_at) VALUES(?,?,?)')
|
||||
.run('ses_root', 'auto', Date.now())
|
||||
legacyDb
|
||||
.prepare(`
|
||||
INSERT INTO session_goals(session_id, directory, objective, status, turn_state, max_continuations, created_at, updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?)
|
||||
`)
|
||||
.run('ses_root', '/repo', 'Ship it', 'active', 'waiting', 1, Date.now(), Date.now())
|
||||
const legacyGoalId = (legacyDb.prepare('SELECT id FROM session_goals LIMIT 1').get() as { id: number }).id
|
||||
|
||||
migration.up(legacyDb)
|
||||
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(getSessionPermissionMode(legacyDb, 'ses_root')).toBe('auto')
|
||||
expect(getSessionGoalById(legacyDb, legacyGoalId)).toMatchObject({ serverId: 'local' })
|
||||
|
||||
legacyDb.close()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { request as httpRequest } from 'node:http'
|
||||
|
||||
export interface RawHandshakeResult {
|
||||
upgraded: boolean
|
||||
status?: number
|
||||
}
|
||||
|
||||
export function rawWebSocketHandshake(options: {
|
||||
port: number
|
||||
path: string
|
||||
origin?: string
|
||||
cookie?: string
|
||||
}): Promise<RawHandshakeResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const headers: Record<string, string> = {
|
||||
Connection: 'Upgrade',
|
||||
Upgrade: 'websocket',
|
||||
'Sec-WebSocket-Key': randomBytes(16).toString('base64'),
|
||||
'Sec-WebSocket-Version': '13',
|
||||
}
|
||||
if (options.origin !== undefined) headers.Origin = options.origin
|
||||
if (options.cookie) headers.Cookie = options.cookie
|
||||
|
||||
const request = httpRequest({ host: '127.0.0.1', port: options.port, path: options.path, method: 'GET', headers })
|
||||
let settled = false
|
||||
request.on('upgrade', (_res, socket) => {
|
||||
settled = true
|
||||
socket.destroy()
|
||||
resolve({ upgraded: true })
|
||||
})
|
||||
request.on('response', (res) => {
|
||||
settled = true
|
||||
res.resume()
|
||||
resolve({ upgraded: false, status: res.statusCode })
|
||||
})
|
||||
request.on('error', (error) => {
|
||||
if (!settled) reject(error)
|
||||
})
|
||||
request.end()
|
||||
})
|
||||
}
|
||||
@@ -122,11 +122,16 @@ vi.mock('../src/services/skills', () => ({
|
||||
|
||||
const sseAggregatorMock = vi.hoisted(() => ({
|
||||
onEvent: vi.fn(),
|
||||
onServerEvent: vi.fn(),
|
||||
onUpstreamConnected: vi.fn(),
|
||||
onServerConnected: vi.fn(),
|
||||
setPendingActionsFetcher: vi.fn(),
|
||||
setPasswordResolver: vi.fn(),
|
||||
setScheduledSessionsResolver: vi.fn(),
|
||||
setRemoteReplayHandler: vi.fn(),
|
||||
setRemoteSubagentResolver: vi.fn(),
|
||||
notifyServerEvent: vi.fn(),
|
||||
notifyServerConnected: vi.fn(),
|
||||
start: vi.fn(),
|
||||
shutdown: vi.fn(),
|
||||
reconnect: vi.fn(),
|
||||
|
||||
@@ -20,6 +20,8 @@ function createRun(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 1,
|
||||
repoId: 1,
|
||||
serverId: 'local',
|
||||
directory: null,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
isolated: true,
|
||||
@@ -69,7 +71,7 @@ describe('internal-multi-runs routes', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({ runs: [] })
|
||||
expect(multiRuns.list).toHaveBeenCalledWith(1)
|
||||
expect(multiRuns.list).toHaveBeenCalledWith({ kind: 'repo', repoId: 1 })
|
||||
})
|
||||
|
||||
it('POST /api/internal/multi-runs/3/entries/4/discard discards the entry', async () => {
|
||||
|
||||
@@ -8,6 +8,8 @@ function createRun(overrides: Partial<MultiRun> = {}): MultiRun {
|
||||
return {
|
||||
id: 1,
|
||||
repoId: 1,
|
||||
serverId: 'local',
|
||||
directory: null,
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
isolated: true,
|
||||
@@ -61,7 +63,27 @@ describe('multi-run routes', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({ runs: [createRun()] })
|
||||
expect(service.list).toHaveBeenCalledWith(1)
|
||||
expect(service.list).toHaveBeenCalledWith({ kind: 'repo', repoId: 1 })
|
||||
})
|
||||
|
||||
it('GET returns the runs of a server directory', async () => {
|
||||
service.list.mockReturnValue([])
|
||||
|
||||
const res = await app.request('/multi-runs?serverId=srv_kitchen&directory=%2Fsrv%2Fapp')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(service.list).toHaveBeenCalledWith({
|
||||
kind: 'server',
|
||||
serverId: 'srv_kitchen',
|
||||
directory: '/srv/app',
|
||||
})
|
||||
})
|
||||
|
||||
it('GET rejects a server target without a directory with 400', async () => {
|
||||
const res = await app.request('/multi-runs?serverId=srv_kitchen')
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(service.list).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('GET rejects a missing repoId with 400', async () => {
|
||||
@@ -91,6 +113,61 @@ describe('multi-run routes', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('POST launches a run for a server directory', async () => {
|
||||
service.launch.mockResolvedValue(createRun({ repoId: null, serverId: 'srv_kitchen', directory: '/srv/app' }))
|
||||
|
||||
const res = await app.request('/multi-runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
serverId: 'srv_kitchen',
|
||||
directory: '/srv/app',
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a'],
|
||||
isolate: true,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(201)
|
||||
expect(service.launch).toHaveBeenCalledWith({
|
||||
serverId: 'srv_kitchen',
|
||||
directory: '/srv/app',
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a'],
|
||||
isolate: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('POST rejects a launch with both a repository and a server target', async () => {
|
||||
const res = await app.request('/multi-runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: launchBody({ serverId: 'srv_kitchen', directory: '/srv/app' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(service.launch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST rejects a server target without a directory', async () => {
|
||||
const res = await app.request('/multi-runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
serverId: 'srv_kitchen',
|
||||
name: 'Sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a'],
|
||||
isolate: true,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(service.launch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST rejects more than five models with 400', async () => {
|
||||
const res = await app.request('/multi-runs', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { createNodeWebSocket } from '@hono/node-ws'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
createOpenCodeServerTerminalSocketRoutes,
|
||||
type ServerTerminalServiceResolver,
|
||||
} from '../../src/routes/opencode-server-terminals'
|
||||
import { TerminalService } from '../../src/services/terminal'
|
||||
import { OpenCodeServerNotFoundError } from '../../src/services/opencode-server-registry'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { CredentialProvider } from '../../src/services/credential-provider'
|
||||
import { startWebSocketServer, type WebSocketTestServer } from '../helpers/websocket-server'
|
||||
import { rawWebSocketHandshake } from '../helpers/raw-websocket-handshake'
|
||||
|
||||
const TRUSTED_ORIGIN = 'http://localhost:5003'
|
||||
const SERVER_ID = 'srv_kitchen'
|
||||
const UNKNOWN_SERVER_ID = 'srv_missing'
|
||||
const DIRECTORY = '/home/me/app'
|
||||
|
||||
const ptyList = vi.fn(async ({ location }: { location: { directory: string } }) => ({
|
||||
location,
|
||||
data: [
|
||||
{ id: 'pty-1', title: 'Terminal', command: 'sh', args: [], cwd: DIRECTORY, status: 'running' as const, pid: 1 },
|
||||
],
|
||||
}))
|
||||
const connectToken = vi.fn(async () => ({
|
||||
location: { directory: DIRECTORY },
|
||||
data: { ticket: 'remote-ticket', expires_in: 60 },
|
||||
}))
|
||||
|
||||
const remoteClient = {
|
||||
api: { pty: { list: ptyList, connect: { token: connectToken } } },
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
const credentialProvider = { getGhCliEnv: vi.fn(() => ({})) } as unknown as CredentialProvider
|
||||
|
||||
let upstream: WebSocketTestServer
|
||||
let manager: WebSocketTestServer
|
||||
let managerPort = 0
|
||||
let capturedUrl: URL | undefined
|
||||
|
||||
const upstreamApp = new Hono()
|
||||
const upstreamWs = createNodeWebSocket({ app: upstreamApp })
|
||||
|
||||
upstreamApp.get(
|
||||
'/api/pty/:ptyID/connect',
|
||||
upstreamWs.upgradeWebSocket((c) => {
|
||||
capturedUrl = new URL(c.req.url)
|
||||
return {
|
||||
onMessage(event, ws) {
|
||||
if (typeof event.data === 'string') ws.send(event.data)
|
||||
},
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
const managerApp = new Hono()
|
||||
const managerWs = createNodeWebSocket({ app: managerApp })
|
||||
|
||||
const terminalService = new TerminalService(
|
||||
{ client: remoteClient, baseUrl: () => `http://127.0.0.1:${upstream.port}`, includeLocalCredentials: false },
|
||||
credentialProvider,
|
||||
)
|
||||
|
||||
const resolveTerminalService: ServerTerminalServiceResolver = (serverId) => {
|
||||
if (serverId === UNKNOWN_SERVER_ID) throw new OpenCodeServerNotFoundError(serverId)
|
||||
return terminalService
|
||||
}
|
||||
|
||||
managerApp.route(
|
||||
'/',
|
||||
createOpenCodeServerTerminalSocketRoutes(resolveTerminalService, managerWs.upgradeWebSocket, [TRUSTED_ORIGIN]),
|
||||
)
|
||||
|
||||
function clientUrl(ptyID: string, directory = DIRECTORY, cursor?: number): string {
|
||||
const url = new URL(`ws://127.0.0.1:${managerPort}/${SERVER_ID}/terminals/${ptyID}/connect`)
|
||||
url.searchParams.set('directory', directory)
|
||||
if (cursor !== undefined) url.searchParams.set('cursor', String(cursor))
|
||||
return url.toString()
|
||||
}
|
||||
|
||||
function openEvent(socket: WebSocket): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (socket.readyState === WebSocket.OPEN) {
|
||||
resolve()
|
||||
return
|
||||
}
|
||||
socket.addEventListener('open', () => resolve(), { once: true })
|
||||
socket.addEventListener('error', () => reject(new Error('WebSocket error before open')), { once: true })
|
||||
})
|
||||
}
|
||||
|
||||
async function waitFor(predicate: () => boolean, timeoutMs = 5000): Promise<void> {
|
||||
const start = Date.now()
|
||||
while (!predicate()) {
|
||||
if (Date.now() - start > timeoutMs) throw new Error('Timed out waiting for condition')
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
upstream = await startWebSocketServer({ app: upstreamApp, injectWebSocket: upstreamWs.injectWebSocket })
|
||||
manager = await startWebSocketServer({ app: managerApp, injectWebSocket: managerWs.injectWebSocket })
|
||||
managerPort = manager.port
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
upstreamWs.wss.close()
|
||||
managerWs.wss.close()
|
||||
await upstream.close()
|
||||
await manager.close()
|
||||
})
|
||||
|
||||
describe('OpenCode Server Terminal Socket Route', () => {
|
||||
it('bridges to the remote base URL with a ticket, directory and cursor', async () => {
|
||||
const socket = new WebSocket(clientUrl('pty-1', DIRECTORY, 3))
|
||||
socket.binaryType = 'arraybuffer'
|
||||
const messages: Array<string | ArrayBuffer> = []
|
||||
socket.addEventListener('message', (event) => {
|
||||
messages.push(event.data as string | ArrayBuffer)
|
||||
})
|
||||
|
||||
await openEvent(socket)
|
||||
socket.send('echo remote')
|
||||
await waitFor(() => messages.includes('echo remote'))
|
||||
|
||||
expect(ptyList).toHaveBeenCalledWith({ location: { directory: DIRECTORY } })
|
||||
expect(connectToken).toHaveBeenCalledWith({
|
||||
ptyID: 'pty-1',
|
||||
location: { directory: DIRECTORY },
|
||||
'x-opencode-ticket': '1',
|
||||
})
|
||||
expect(capturedUrl?.searchParams.get('ticket')).toBe('remote-ticket')
|
||||
expect(capturedUrl?.searchParams.get('location[directory]')).toBe(DIRECTORY)
|
||||
expect(capturedUrl?.searchParams.get('cursor')).toBe('3')
|
||||
|
||||
socket.close()
|
||||
})
|
||||
|
||||
it('rejects an untrusted origin before the upgrade', async () => {
|
||||
const outcome = await rawWebSocketHandshake({
|
||||
port: managerPort,
|
||||
path: `/${SERVER_ID}/terminals/pty-1/connect?directory=${encodeURIComponent(DIRECTORY)}`,
|
||||
origin: 'http://localhost:5004',
|
||||
})
|
||||
|
||||
expect(outcome).toEqual({ upgraded: false, status: 403 })
|
||||
})
|
||||
|
||||
it('rejects the local server before the upgrade', async () => {
|
||||
const outcome = await rawWebSocketHandshake({
|
||||
port: managerPort,
|
||||
path: `/${LOCAL_OPENCODE_SERVER_ID}/terminals/pty-1/connect?directory=${encodeURIComponent(DIRECTORY)}`,
|
||||
})
|
||||
|
||||
expect(outcome).toEqual({ upgraded: false, status: 400 })
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown server before the upgrade', async () => {
|
||||
const outcome = await rawWebSocketHandshake({
|
||||
port: managerPort,
|
||||
path: `/${UNKNOWN_SERVER_ID}/terminals/pty-1/connect?directory=${encodeURIComponent(DIRECTORY)}`,
|
||||
})
|
||||
|
||||
expect(outcome).toEqual({ upgraded: false, status: 404 })
|
||||
})
|
||||
|
||||
it('rejects a relative directory before the upgrade', async () => {
|
||||
const outcome = await rawWebSocketHandshake({
|
||||
port: managerPort,
|
||||
path: `/${SERVER_ID}/terminals/pty-1/connect?directory=relative/path`,
|
||||
})
|
||||
|
||||
expect(outcome).toEqual({ upgraded: false, status: 400 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,215 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
createOpenCodeServerTerminalRoutes,
|
||||
type ServerTerminalServiceResolver,
|
||||
} from '../../src/routes/opencode-server-terminals'
|
||||
import { TerminalService } from '../../src/services/terminal'
|
||||
import { OpenCodeServerNotFoundError } from '../../src/services/opencode-server-registry'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { CredentialProvider } from '../../src/services/credential-provider'
|
||||
|
||||
const DIRECTORY = '/home/me/app'
|
||||
const SERVER_ID = 'srv_kitchen'
|
||||
const UNKNOWN_SERVER_ID = 'srv_missing'
|
||||
const jsonHeaders = { 'Content-Type': 'application/json' }
|
||||
|
||||
function createPty(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'pty-1',
|
||||
title: 'Terminal',
|
||||
command: 'sh',
|
||||
args: [],
|
||||
cwd: DIRECTORY,
|
||||
status: 'running' as const,
|
||||
pid: 1,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function createRemoteClient(terminals: Array<Record<string, unknown>> = [createPty()]) {
|
||||
const list = vi.fn(async ({ location }: { location: { directory: string } }) => ({
|
||||
location,
|
||||
data: terminals,
|
||||
}))
|
||||
const create = vi.fn(async (input: { location: { directory: string }; title: string; env: Record<string, string> }) => ({
|
||||
location: input.location,
|
||||
data: createPty({ id: 'pty-new', title: input.title }),
|
||||
}))
|
||||
const update = vi.fn(async () => ({ location: { directory: DIRECTORY }, data: createPty() }))
|
||||
const remove = vi.fn(async () => undefined)
|
||||
const client = { api: { pty: { list, create, update, remove } } } as unknown as OpenCodeClient
|
||||
return { client, list, create, update, remove }
|
||||
}
|
||||
|
||||
function createService(includeLocalCredentials = false, terminals?: Array<Record<string, unknown>>) {
|
||||
const remote = createRemoteClient(terminals)
|
||||
const credentialProvider = {
|
||||
getGhCliEnv: vi.fn(() => ({ GH_TOKEN: 'local-token' })),
|
||||
} as unknown as CredentialProvider
|
||||
const service = new TerminalService(
|
||||
{ client: remote.client, baseUrl: () => 'https://remote.internal', includeLocalCredentials },
|
||||
credentialProvider,
|
||||
)
|
||||
return { service, credentialProvider, ...remote }
|
||||
}
|
||||
|
||||
function createResolver(service: TerminalService): ServerTerminalServiceResolver {
|
||||
return (serverId) => {
|
||||
if (serverId === UNKNOWN_SERVER_ID) throw new OpenCodeServerNotFoundError(serverId)
|
||||
return service
|
||||
}
|
||||
}
|
||||
|
||||
function createApp(service: TerminalService): Hono {
|
||||
const app = new Hono()
|
||||
app.route('/', createOpenCodeServerTerminalRoutes(createResolver(service)))
|
||||
return app
|
||||
}
|
||||
|
||||
describe('OpenCode Server Terminal Routes', () => {
|
||||
describe('GET /:serverId/terminals', () => {
|
||||
it('lists the terminals of the remote directory', async () => {
|
||||
const { service, list } = createService()
|
||||
const res = await createApp(service).request(
|
||||
`/${SERVER_ID}/terminals?directory=${encodeURIComponent(DIRECTORY)}`,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({
|
||||
terminals: [{ id: 'pty-1', title: 'Terminal', kind: 'shell', cwd: DIRECTORY, status: 'running' }],
|
||||
})
|
||||
expect(list).toHaveBeenCalledWith({ location: { directory: DIRECTORY } })
|
||||
})
|
||||
|
||||
it('rejects the local server', async () => {
|
||||
const { service } = createService()
|
||||
const res = await createApp(service).request(
|
||||
`/${LOCAL_OPENCODE_SERVER_ID}/terminals?directory=${encodeURIComponent(DIRECTORY)}`,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown server', async () => {
|
||||
const { service } = createService()
|
||||
const res = await createApp(service).request(
|
||||
`/${UNKNOWN_SERVER_ID}/terminals?directory=${encodeURIComponent(DIRECTORY)}`,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
expect(await res.json()).toEqual({ error: `OpenCode server not found: ${UNKNOWN_SERVER_ID}` })
|
||||
})
|
||||
|
||||
it('requires an absolute directory', async () => {
|
||||
const { service } = createService()
|
||||
const app = createApp(service)
|
||||
|
||||
for (const path of [`/${SERVER_ID}/terminals`, `/${SERVER_ID}/terminals?directory=relative/path`]) {
|
||||
const res = await app.request(path)
|
||||
expect(res.status).toBe(400)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /:serverId/terminals', () => {
|
||||
it('creates a shell without local credentials', async () => {
|
||||
const { service, create, credentialProvider } = createService()
|
||||
const res = await createApp(service).request(`/${SERVER_ID}/terminals`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ directory: DIRECTORY, title: 'Remote shell' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(credentialProvider.getGhCliEnv).not.toHaveBeenCalled()
|
||||
expect(create).toHaveBeenCalledWith({
|
||||
location: { directory: DIRECTORY },
|
||||
title: 'Remote shell',
|
||||
env: {},
|
||||
})
|
||||
expect(await res.json()).toEqual({
|
||||
id: 'pty-new',
|
||||
title: 'Remote shell',
|
||||
kind: 'shell',
|
||||
cwd: DIRECTORY,
|
||||
status: 'running',
|
||||
})
|
||||
})
|
||||
|
||||
it('defaults the title and rejects a missing directory', async () => {
|
||||
const { service, create } = createService()
|
||||
const app = createApp(service)
|
||||
|
||||
const created = await app.request(`/${SERVER_ID}/terminals`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ directory: DIRECTORY }),
|
||||
})
|
||||
expect(created.status).toBe(200)
|
||||
expect(create).toHaveBeenCalledWith(expect.objectContaining({ title: 'Terminal' }))
|
||||
|
||||
const missing = await app.request(`/${SERVER_ID}/terminals`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
expect(missing.status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /:serverId/terminals/:ptyID', () => {
|
||||
it('resizes a terminal of the remote server', async () => {
|
||||
const { service, update } = createService()
|
||||
const res = await createApp(service).request(`/${SERVER_ID}/terminals/pty-1`, {
|
||||
method: 'PATCH',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ directory: DIRECTORY, cols: 120, rows: 40 }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ success: true })
|
||||
expect(update).toHaveBeenCalledWith({
|
||||
ptyID: 'pty-1',
|
||||
location: { directory: DIRECTORY },
|
||||
size: { cols: 120, rows: 40 },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown PTY id', async () => {
|
||||
const { service } = createService(false, [])
|
||||
const res = await createApp(service).request(`/${SERVER_ID}/terminals/missing`, {
|
||||
method: 'PATCH',
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({ directory: DIRECTORY, cols: 80, rows: 24 }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /:serverId/terminals/:ptyID', () => {
|
||||
it('removes a terminal of the remote server', async () => {
|
||||
const { service, remove } = createService()
|
||||
const res = await createApp(service).request(
|
||||
`/${SERVER_ID}/terminals/pty-1?directory=${encodeURIComponent(DIRECTORY)}`,
|
||||
{ method: 'DELETE' },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ success: true })
|
||||
expect(remove).toHaveBeenCalledWith({ ptyID: 'pty-1', location: { directory: DIRECTORY } })
|
||||
})
|
||||
|
||||
it('returns 404 for an unknown PTY id', async () => {
|
||||
const { service } = createService(false, [])
|
||||
const res = await createApp(service).request(
|
||||
`/${SERVER_ID}/terminals/missing?directory=${encodeURIComponent(DIRECTORY)}`,
|
||||
{ method: 'DELETE' },
|
||||
)
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,4 @@
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { request as httpRequest } from 'node:http'
|
||||
import { Hono } from 'hono'
|
||||
import { cors } from 'hono/cors'
|
||||
import { createNodeWebSocket } from '@hono/node-ws'
|
||||
@@ -12,6 +10,7 @@ import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { CredentialProvider } from '../../src/services/credential-provider'
|
||||
import { startWebSocketServer, type WebSocketTestServer } from '../helpers/websocket-server'
|
||||
import { rawWebSocketHandshake } from '../helpers/raw-websocket-handshake'
|
||||
|
||||
vi.mock('../../src/services/repo', () => ({
|
||||
resolveRepoOrAssistant: vi.fn(),
|
||||
@@ -79,7 +78,10 @@ upstreamApp.get(
|
||||
}),
|
||||
)
|
||||
|
||||
const terminalService = new TerminalService(openCodeClient, credentialProvider, () => upstreamBase)
|
||||
const terminalService = new TerminalService(
|
||||
{ client: openCodeClient, baseUrl: () => upstreamBase, includeLocalCredentials: true },
|
||||
credentialProvider,
|
||||
)
|
||||
|
||||
const managerApp = new Hono()
|
||||
const managerWs = createNodeWebSocket({ app: managerApp })
|
||||
@@ -119,41 +121,6 @@ authenticatedApp.route(
|
||||
|
||||
let authenticatedPort = 0
|
||||
|
||||
interface RawHandshakeResult {
|
||||
upgraded: boolean
|
||||
status?: number
|
||||
}
|
||||
|
||||
function rawHandshake(options: { port: number; path: string; origin?: string; cookie?: string }): Promise<RawHandshakeResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const headers: Record<string, string> = {
|
||||
Connection: 'Upgrade',
|
||||
Upgrade: 'websocket',
|
||||
'Sec-WebSocket-Key': randomBytes(16).toString('base64'),
|
||||
'Sec-WebSocket-Version': '13',
|
||||
}
|
||||
if (options.origin !== undefined) headers.Origin = options.origin
|
||||
if (options.cookie) headers.Cookie = options.cookie
|
||||
|
||||
const request = httpRequest({ host: '127.0.0.1', port: options.port, path: options.path, method: 'GET', headers })
|
||||
let settled = false
|
||||
request.on('upgrade', (_res, socket) => {
|
||||
settled = true
|
||||
socket.destroy()
|
||||
resolve({ upgraded: true })
|
||||
})
|
||||
request.on('response', (res) => {
|
||||
settled = true
|
||||
res.resume()
|
||||
resolve({ upgraded: false, status: res.statusCode })
|
||||
})
|
||||
request.on('error', (error) => {
|
||||
if (!settled) reject(error)
|
||||
})
|
||||
request.end()
|
||||
})
|
||||
}
|
||||
|
||||
function clientUrl(ptyID: string, directory = '/tmp/repo'): string {
|
||||
const url = new URL(`ws://127.0.0.1:${managerPort}/1/terminals/${ptyID}/connect`)
|
||||
url.searchParams.set('directory', directory)
|
||||
@@ -267,7 +234,7 @@ describe('Repo Terminal Socket Origin validation', () => {
|
||||
const path = `/1/terminals/pty-1/connect?directory=${encodeURIComponent('/tmp/repo')}`
|
||||
|
||||
it('accepts a trusted Origin with a valid session cookie', async () => {
|
||||
const outcome = await rawHandshake({
|
||||
const outcome = await rawWebSocketHandshake({
|
||||
port: authenticatedPort,
|
||||
path,
|
||||
origin: TRUSTED_ORIGIN,
|
||||
@@ -278,13 +245,13 @@ describe('Repo Terminal Socket Origin validation', () => {
|
||||
})
|
||||
|
||||
it('allows a non-browser client without an Origin header', async () => {
|
||||
const outcome = await rawHandshake({ port: authenticatedPort, path, cookie: 'session=valid' })
|
||||
const outcome = await rawWebSocketHandshake({ port: authenticatedPort, path, cookie: 'session=valid' })
|
||||
|
||||
expect(outcome).toEqual({ upgraded: true })
|
||||
})
|
||||
|
||||
it('rejects an untrusted same-site Origin before the upgrade', async () => {
|
||||
const outcome = await rawHandshake({
|
||||
const outcome = await rawWebSocketHandshake({
|
||||
port: authenticatedPort,
|
||||
path,
|
||||
origin: 'http://localhost:5004',
|
||||
@@ -295,7 +262,7 @@ describe('Repo Terminal Socket Origin validation', () => {
|
||||
})
|
||||
|
||||
it('rejects a null Origin before the upgrade', async () => {
|
||||
const outcome = await rawHandshake({
|
||||
const outcome = await rawWebSocketHandshake({
|
||||
port: authenticatedPort,
|
||||
path,
|
||||
origin: 'null',
|
||||
@@ -306,7 +273,7 @@ describe('Repo Terminal Socket Origin validation', () => {
|
||||
})
|
||||
|
||||
it('rejects the upgrade without a session cookie', async () => {
|
||||
const outcome = await rawHandshake({ port: authenticatedPort, path, origin: TRUSTED_ORIGIN })
|
||||
const outcome = await rawWebSocketHandshake({ port: authenticatedPort, path, origin: TRUSTED_ORIGIN })
|
||||
|
||||
expect(outcome).toEqual({ upgraded: false, status: 401 })
|
||||
})
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { ScheduleServiceError } from '../../src/services/schedules'
|
||||
|
||||
const scheduleService = {
|
||||
listServerJobs: vi.fn(),
|
||||
createServerJob: vi.fn(),
|
||||
getServerJob: vi.fn(),
|
||||
updateServerJob: vi.fn(),
|
||||
deleteServerJob: vi.fn(),
|
||||
runServerJob: vi.fn(),
|
||||
listServerRuns: vi.fn(),
|
||||
getServerRun: vi.fn(),
|
||||
cancelServerRun: vi.fn(),
|
||||
clearServerRunHistory: vi.fn(),
|
||||
deleteServerRun: vi.fn(),
|
||||
}
|
||||
|
||||
vi.mock('../../src/services/schedules', async () => {
|
||||
const actual = await vi.importActual('../../src/services/schedules')
|
||||
return {
|
||||
...actual,
|
||||
ScheduleService: vi.fn().mockImplementation(() => scheduleService),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { createServerScheduleRoutes } from '../../src/routes/schedules'
|
||||
|
||||
describe('Server schedule routes', () => {
|
||||
let app: Hono
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
app = new Hono()
|
||||
app.route('/opencode-servers/:serverId/schedules', createServerScheduleRoutes(scheduleService as unknown as import('../../src/services/schedules').ScheduleService))
|
||||
})
|
||||
|
||||
it('lists jobs for a linked server', async () => {
|
||||
scheduleService.listServerJobs.mockReturnValue([{ id: 7 }])
|
||||
|
||||
const response = await app.request('/opencode-servers/srv_kitchen/schedules')
|
||||
const body = await response.json() as { jobs: Array<{ id: number }> }
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.jobs).toHaveLength(1)
|
||||
expect(scheduleService.listServerJobs).toHaveBeenCalledWith('srv_kitchen')
|
||||
})
|
||||
|
||||
it('creates a remote schedule with its target directory', async () => {
|
||||
scheduleService.createServerJob.mockResolvedValue({ id: 7, serverId: 'srv_kitchen' })
|
||||
|
||||
const response = await app.request('/opencode-servers/srv_kitchen/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Nightly audit',
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
prompt: 'Audit the project.',
|
||||
directory: '/srv/projects/audit',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(201)
|
||||
expect(scheduleService.createServerJob).toHaveBeenCalledWith(
|
||||
'srv_kitchen',
|
||||
'/srv/projects/audit',
|
||||
expect.objectContaining({ directory: '/srv/projects/audit' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a remote schedule without a directory', async () => {
|
||||
const response = await app.request('/opencode-servers/srv_kitchen/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Nightly audit',
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
prompt: 'Audit the project.',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(scheduleService.createServerJob).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('updates, runs, and cancels a remote schedule', async () => {
|
||||
scheduleService.updateServerJob.mockResolvedValue({ id: 7 })
|
||||
scheduleService.runServerJob.mockResolvedValue({ id: 11, status: 'running' })
|
||||
scheduleService.cancelServerRun.mockResolvedValue({ id: 11, status: 'cancelled' })
|
||||
|
||||
const updateResponse = await app.request('/opencode-servers/srv_kitchen/schedules/7', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Updated audit' }),
|
||||
})
|
||||
expect(updateResponse.status).toBe(200)
|
||||
expect(scheduleService.updateServerJob).toHaveBeenCalledWith('srv_kitchen', 7, { name: 'Updated audit' })
|
||||
|
||||
const runResponse = await app.request('/opencode-servers/srv_kitchen/schedules/7/run', { method: 'POST' })
|
||||
expect(runResponse.status).toBe(200)
|
||||
expect(scheduleService.runServerJob).toHaveBeenCalledWith('srv_kitchen', 7, 'manual')
|
||||
|
||||
const cancelResponse = await app.request('/opencode-servers/srv_kitchen/schedules/7/runs/11/cancel', { method: 'POST' })
|
||||
expect(cancelResponse.status).toBe(200)
|
||||
expect(scheduleService.cancelServerRun).toHaveBeenCalledWith('srv_kitchen', 7, 11)
|
||||
})
|
||||
|
||||
it('lists and deletes runs for a remote schedule', async () => {
|
||||
scheduleService.listServerRuns.mockReturnValue([{ id: 11 }])
|
||||
scheduleService.getServerRun.mockReturnValue({ id: 11 })
|
||||
scheduleService.clearServerRunHistory.mockResolvedValue({ cleared: 1 })
|
||||
scheduleService.deleteServerRun.mockResolvedValue(undefined)
|
||||
|
||||
const listResponse = await app.request('/opencode-servers/srv_kitchen/schedules/7/runs')
|
||||
expect(listResponse.status).toBe(200)
|
||||
expect(scheduleService.listServerRuns).toHaveBeenCalledWith('srv_kitchen', 7, 20)
|
||||
|
||||
const getResponse = await app.request('/opencode-servers/srv_kitchen/schedules/7/runs/11')
|
||||
expect(getResponse.status).toBe(200)
|
||||
expect(scheduleService.getServerRun).toHaveBeenCalledWith('srv_kitchen', 7, 11)
|
||||
|
||||
const clearResponse = await app.request('/opencode-servers/srv_kitchen/schedules/7/runs', { method: 'DELETE' })
|
||||
expect(clearResponse.status).toBe(200)
|
||||
expect(scheduleService.clearServerRunHistory).toHaveBeenCalledWith('srv_kitchen', 7)
|
||||
|
||||
const deleteResponse = await app.request('/opencode-servers/srv_kitchen/schedules/7/runs/11', { method: 'DELETE' })
|
||||
expect(deleteResponse.status).toBe(200)
|
||||
expect(scheduleService.deleteServerRun).toHaveBeenCalledWith('srv_kitchen', 7, 11)
|
||||
})
|
||||
|
||||
it('maps service errors to their status', async () => {
|
||||
scheduleService.runServerJob.mockRejectedValue(new ScheduleServiceError('OpenCode server "Kitchen" is disabled', 400))
|
||||
|
||||
const response = await app.request('/opencode-servers/srv_kitchen/schedules/7/run', { method: 'POST' })
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(await response.json()).toMatchObject({ error: 'OpenCode server "Kitchen" is disabled' })
|
||||
})
|
||||
})
|
||||
@@ -190,4 +190,23 @@ describe('session goal routes', () => {
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('scopes goals by serverId', async () => {
|
||||
const app = createTestApp(db)
|
||||
|
||||
const postRes = await app.request('/session-goals', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: startBody({ serverId: 'srv_remote' }),
|
||||
})
|
||||
expect(postRes.status).toBe(201)
|
||||
const created = await postRes.json() as { goal: { serverId: string } }
|
||||
expect(created.goal.serverId).toBe('srv_remote')
|
||||
|
||||
const remoteRes = await app.request('/session-goals?sessionId=ses_1&serverId=srv_remote')
|
||||
await expect(remoteRes.json()).resolves.toMatchObject({ goal: { serverId: 'srv_remote' } })
|
||||
|
||||
const localRes = await app.request('/session-goals?sessionId=ses_1')
|
||||
await expect(localRes.json()).resolves.toEqual({ goal: null })
|
||||
})
|
||||
})
|
||||
@@ -115,4 +115,21 @@ describe('session permission mode routes', () => {
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('scopes PUT and GET by serverId', async () => {
|
||||
const app = createTestApp(db, { ses_root: null })
|
||||
|
||||
const putRes = await app.request('/session-permission-modes/ses_root', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ directory: '/abs/repo', mode: 'auto', serverId: 'srv_remote' }),
|
||||
})
|
||||
expect(putRes.status).toBe(200)
|
||||
|
||||
const remoteRes = await app.request('/session-permission-modes/ses_root?serverId=srv_remote')
|
||||
await expect(remoteRes.json()).resolves.toMatchObject({ mode: 'auto' })
|
||||
|
||||
const localRes = await app.request('/session-permission-modes/ses_root')
|
||||
await expect(localRes.json()).resolves.toMatchObject({ mode: 'ask' })
|
||||
})
|
||||
})
|
||||
@@ -240,7 +240,7 @@ describe('SSE Routes', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({ success: true })
|
||||
expect(sseMocks.setClientVisibility).toHaveBeenCalledWith('client-1', true, 'session-9')
|
||||
expect(sseMocks.setClientVisibility).toHaveBeenCalledWith('client-1', true, 'session-9', 'local')
|
||||
})
|
||||
|
||||
it('defaults the active session id to null when omitted', async () => {
|
||||
@@ -254,7 +254,20 @@ describe('SSE Routes', () => {
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
await expect(res.json()).resolves.toEqual({ success: true })
|
||||
expect(sseMocks.setClientVisibility).toHaveBeenCalledWith('client-1', false, null)
|
||||
expect(sseMocks.setClientVisibility).toHaveBeenCalledWith('client-1', false, null, 'local')
|
||||
})
|
||||
|
||||
it('forwards an explicit active server id', async () => {
|
||||
sseMocks.setClientVisibility.mockReturnValue(true)
|
||||
|
||||
const res = await app.fetch(new Request('http://localhost/visibility', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ clientId: 'client-1', visible: true, activeSessionId: 'session-9', activeServerId: 'srv_a' }),
|
||||
}))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(sseMocks.setClientVisibility).toHaveBeenCalledWith('client-1', true, 'session-9', 'srv_a')
|
||||
})
|
||||
|
||||
it('returns 400 for an invalid visibility body', async () => {
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { getMultiRun } from '../../src/db/multi-runs'
|
||||
import { MultiRunService } from '../../src/services/multi-runs'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { RepoWorkspaceService } from '../../src/services/repo-workspace'
|
||||
import type { SessionPermissionModeService } from '../../src/services/session-permission-modes'
|
||||
import { assistantMessage } from '../helpers/stub-schedule-api'
|
||||
|
||||
const SERVER_ID = 'srv_kitchen'
|
||||
const REMOTE_DIR = '/srv/projects/app'
|
||||
const FUSE_REQUEST_ID = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
resolveOpenCodeModel: vi.fn(),
|
||||
existsSync: vi.fn(),
|
||||
executeCommand: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-models', () => ({
|
||||
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
|
||||
}))
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:fs')>()
|
||||
return { ...actual, existsSync: mocks.existsSync }
|
||||
})
|
||||
|
||||
vi.mock('../../src/utils/process', () => ({
|
||||
executeCommand: mocks.executeCommand,
|
||||
}))
|
||||
|
||||
interface FakeRemoteClient {
|
||||
client: OpenCodeClient
|
||||
sessionCreate: ReturnType<typeof vi.fn>
|
||||
sessionPrompt: ReturnType<typeof vi.fn>
|
||||
locationGet: ReturnType<typeof vi.fn>
|
||||
worktreeCreate: ReturnType<typeof vi.fn>
|
||||
worktreeRemove: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
function createRemoteClient(options: { worktreeDirectory?: string } = {}): FakeRemoteClient {
|
||||
let sessionCounter = 0
|
||||
let worktreeCounter = 0
|
||||
|
||||
const locationGet = vi.fn(async () => ({ project: { id: 'proj_remote' } }))
|
||||
const worktreeCreate = vi.fn(async () => {
|
||||
worktreeCounter += 1
|
||||
return { directory: options.worktreeDirectory ?? `/srv/worktrees/app-${worktreeCounter}` }
|
||||
})
|
||||
const worktreeRemove = vi.fn(async () => undefined)
|
||||
|
||||
const sessionCreate = vi.fn(async (input: { title?: string }) => {
|
||||
sessionCounter += 1
|
||||
return { id: `ses_remote_${sessionCounter}`, title: input?.title }
|
||||
})
|
||||
const sessionPrompt = vi.fn(async () => ({}))
|
||||
const sessionGet = vi.fn(async ({ sessionID }: { sessionID: string }) => ({
|
||||
id: sessionID,
|
||||
outcome: 'succeeded',
|
||||
}))
|
||||
const sessionActive = vi.fn(async () => ({}))
|
||||
const sessionDiff = vi.fn(async () => [])
|
||||
const messageList = vi.fn(async (input: { sessionID: string; type?: string }) => {
|
||||
if (input.type === 'user') {
|
||||
return { data: [{ id: `${input.sessionID}-user`, type: 'user', time: { created: 0 }, text: 'hi' }], cursor: {} }
|
||||
}
|
||||
return { data: [assistantMessage('remote reply', { completed: true })], cursor: {} }
|
||||
})
|
||||
|
||||
const client = {
|
||||
api: {
|
||||
location: { get: locationGet },
|
||||
worktree: { create: worktreeCreate, remove: worktreeRemove },
|
||||
session: {
|
||||
create: sessionCreate,
|
||||
prompt: sessionPrompt,
|
||||
get: sessionGet,
|
||||
active: sessionActive,
|
||||
diff: sessionDiff,
|
||||
},
|
||||
message: { list: messageList },
|
||||
},
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
return { client, sessionCreate, sessionPrompt, locationGet, worktreeCreate, worktreeRemove }
|
||||
}
|
||||
|
||||
describe('MultiRunService on a linked server', () => {
|
||||
let db: Database
|
||||
let localClient: OpenCodeClient
|
||||
let localSessionCreate: ReturnType<typeof vi.fn>
|
||||
let repoWorkspaces: { create: ReturnType<typeof vi.fn>; remove: ReturnType<typeof vi.fn> }
|
||||
let applyDefaultMode: ReturnType<typeof vi.fn>
|
||||
let remote: FakeRemoteClient
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
|
||||
localSessionCreate = vi.fn(async () => ({ id: 'ses_local' }))
|
||||
localClient = {
|
||||
api: {
|
||||
session: { create: localSessionCreate, prompt: vi.fn(), get: vi.fn(), active: vi.fn(), diff: vi.fn() },
|
||||
message: { list: vi.fn() },
|
||||
},
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
repoWorkspaces = { create: vi.fn(), remove: vi.fn() }
|
||||
applyDefaultMode = vi.fn(async () => undefined)
|
||||
remote = createRemoteClient()
|
||||
|
||||
mocks.resolveOpenCodeModel.mockImplementation(async (_client, directory, options) => {
|
||||
const preferred = options?.preferredModel
|
||||
if (!preferred) {
|
||||
return { providerID: 'openai', id: 'gpt-5', model: 'openai/gpt-5', directory }
|
||||
}
|
||||
if (preferred === 'openai/retired') {
|
||||
return { providerID: 'openai', id: 'retired-x', model: 'openai/retired-x' }
|
||||
}
|
||||
const [providerID, ...rest] = preferred.split('/')
|
||||
return { providerID, id: rest.join('/'), model: preferred }
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
function createService(): MultiRunService {
|
||||
const permissionModes = { applyDefaultMode } as unknown as SessionPermissionModeService
|
||||
|
||||
return new MultiRunService(
|
||||
db,
|
||||
localClient,
|
||||
repoWorkspaces as unknown as RepoWorkspaceService,
|
||||
permissionModes,
|
||||
() => remote.client,
|
||||
)
|
||||
}
|
||||
|
||||
function launchRemote(overrides: Record<string, unknown> = {}) {
|
||||
return createService().launch({
|
||||
serverId: SERVER_ID,
|
||||
directory: REMOTE_DIR,
|
||||
name: 'Remote sweep',
|
||||
prompt: 'go',
|
||||
models: ['openai/a'],
|
||||
isolate: true,
|
||||
...overrides,
|
||||
})
|
||||
}
|
||||
|
||||
it('launches every model through the remote client and remote worktrees', async () => {
|
||||
const run = await launchRemote({ models: ['openai/a', 'openai/b'], baseRef: 'develop' })
|
||||
|
||||
expect(run).toMatchObject({
|
||||
repoId: null,
|
||||
serverId: SERVER_ID,
|
||||
directory: REMOTE_DIR,
|
||||
name: 'Remote sweep',
|
||||
isolated: true,
|
||||
})
|
||||
expect(run.entries.map((entry) => entry.status)).toEqual(['started', 'started'])
|
||||
expect(run.entries.map((entry) => entry.directory)).toEqual([
|
||||
'/srv/worktrees/app-1',
|
||||
'/srv/worktrees/app-2',
|
||||
])
|
||||
|
||||
expect(remote.locationGet).toHaveBeenCalledWith({ location: { directory: REMOTE_DIR } })
|
||||
expect(remote.worktreeCreate).toHaveBeenCalledTimes(2)
|
||||
expect(remote.worktreeCreate).toHaveBeenCalledWith({
|
||||
projectID: 'proj_remote',
|
||||
name: 'Remote-sweep-1',
|
||||
branch: 'develop',
|
||||
})
|
||||
expect(remote.sessionCreate).toHaveBeenCalledTimes(2)
|
||||
expect(remote.sessionCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ location: { directory: '/srv/worktrees/app-1' } }),
|
||||
)
|
||||
expect(remote.sessionPrompt).toHaveBeenCalledWith({ sessionID: 'ses_remote_1', text: 'go' })
|
||||
|
||||
expect(localSessionCreate).not.toHaveBeenCalled()
|
||||
expect(repoWorkspaces.create).not.toHaveBeenCalled()
|
||||
expect(mocks.existsSync).not.toHaveBeenCalled()
|
||||
expect(mocks.executeCommand).not.toHaveBeenCalled()
|
||||
expect(mocks.resolveOpenCodeModel).toHaveBeenCalledWith(remote.client, REMOTE_DIR, { preferredModel: 'openai/a' })
|
||||
})
|
||||
|
||||
it('runs in the target directory without a worktree when isolation is off', async () => {
|
||||
const run = await launchRemote({ isolate: false })
|
||||
|
||||
expect(run.entries[0]!.directory).toBe(REMOTE_DIR)
|
||||
expect(remote.worktreeCreate).not.toHaveBeenCalled()
|
||||
expect(remote.sessionCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ location: { directory: REMOTE_DIR } }),
|
||||
)
|
||||
})
|
||||
|
||||
it('fails an entry whose model the remote catalog does not offer', async () => {
|
||||
const run = await launchRemote({ models: ['openai/a', 'openai/retired'] })
|
||||
|
||||
expect(run.entries.map((entry) => entry.status)).toEqual(['started', 'failed'])
|
||||
expect(run.entries[1]!.error).toBe('Model openai/retired is not available')
|
||||
expect(remote.worktreeCreate).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('lists remote runs by server and directory without mixing in repository runs', async () => {
|
||||
const service = createService()
|
||||
await launchRemote({ name: 'Remote one' })
|
||||
|
||||
expect(service.list({ kind: 'server', serverId: SERVER_ID, directory: REMOTE_DIR }).map((run) => run.name)).toEqual([
|
||||
'Remote one',
|
||||
])
|
||||
expect(service.list({ kind: 'server', serverId: SERVER_ID, directory: '/srv/other' })).toEqual([])
|
||||
expect(service.list({ kind: 'repo', repoId: 1 })).toEqual([])
|
||||
})
|
||||
|
||||
it('removes a remote worktree on discard without touching the local filesystem', async () => {
|
||||
const service = createService()
|
||||
const run = await launchRemote()
|
||||
const entry = run.entries[0]!
|
||||
|
||||
const discarded = await service.discard(run.id, entry.id)
|
||||
|
||||
expect(discarded.entries[0]!.status).toBe('discarded')
|
||||
expect(remote.worktreeRemove).toHaveBeenCalledWith({
|
||||
projectID: 'proj_remote',
|
||||
directory: '/srv/worktrees/app-1',
|
||||
force: true,
|
||||
})
|
||||
expect(mocks.existsSync).not.toHaveBeenCalled()
|
||||
expect(repoWorkspaces.remove).not.toHaveBeenCalled()
|
||||
expect(mocks.executeCommand).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps a remote entry retryable when worktree removal fails', async () => {
|
||||
const service = createService()
|
||||
const run = await launchRemote()
|
||||
remote.worktreeRemove.mockRejectedValueOnce(new Error('worktree busy'))
|
||||
|
||||
const error = await service.discard(run.id, run.entries[0]!.id).catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toMatchObject({ status: 502 })
|
||||
expect(service.list({ kind: 'server', serverId: SERVER_ID, directory: REMOTE_DIR })[0]!.entries[0]!.status).toBe(
|
||||
'started',
|
||||
)
|
||||
})
|
||||
|
||||
it('fuses remote results in a remote worktree and reads sources from the remote client', async () => {
|
||||
const service = createService()
|
||||
const run = await launchRemote({ models: ['openai/a', 'openai/b'] })
|
||||
const entryIds = run.entries.map((entry) => entry.id)
|
||||
remote.sessionCreate.mockClear()
|
||||
|
||||
const { run: fused, created } = await service.fuse(run.id, {
|
||||
requestId: FUSE_REQUEST_ID,
|
||||
entryIds,
|
||||
model: 'openai/c',
|
||||
baseRef: 'develop',
|
||||
})
|
||||
|
||||
expect(created).toBe(true)
|
||||
const fusion = fused.fusions[0]!
|
||||
expect(fusion.status).toBe('started')
|
||||
expect(fusion.directory).toBe('/srv/worktrees/app-3')
|
||||
expect(fusion.sources.map((source) => source.sessionId)).toEqual(['ses_remote_1', 'ses_remote_2'])
|
||||
|
||||
expect(remote.worktreeCreate).toHaveBeenLastCalledWith({
|
||||
projectID: 'proj_remote',
|
||||
name: 'Remote-sweep-fusion-1',
|
||||
branch: 'develop',
|
||||
})
|
||||
expect(remote.sessionCreate).toHaveBeenCalledTimes(1)
|
||||
expect(remote.sessionCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
location: { directory: '/srv/worktrees/app-3' },
|
||||
permissions: [
|
||||
...buildSchedulePermissionRuleset(null),
|
||||
{ action: 'external_directory', resource: '/srv/worktrees/app-1/*', effect: 'allow' },
|
||||
{ action: 'edit', resource: '/srv/worktrees/app-1/*', effect: 'deny' },
|
||||
{ action: 'external_directory', resource: '/srv/worktrees/app-2/*', effect: 'allow' },
|
||||
{ action: 'edit', resource: '/srv/worktrees/app-2/*', effect: 'deny' },
|
||||
],
|
||||
}),
|
||||
)
|
||||
expect(localSessionCreate).not.toHaveBeenCalled()
|
||||
expect(repoWorkspaces.create).not.toHaveBeenCalled()
|
||||
expect(applyDefaultMode).toHaveBeenCalledWith('ses_remote_3', '/srv/worktrees/app-3', 'srv_kitchen')
|
||||
})
|
||||
|
||||
it('records a failed remote fusion without a local fallback', async () => {
|
||||
const service = createService()
|
||||
const run = await launchRemote({ models: ['openai/a', 'openai/b'] })
|
||||
remote.sessionCreate.mockRejectedValueOnce(new Error('remote boom'))
|
||||
|
||||
const { run: fused } = await service.fuse(run.id, {
|
||||
requestId: FUSE_REQUEST_ID,
|
||||
entryIds: run.entries.map((entry) => entry.id),
|
||||
model: 'openai/c',
|
||||
})
|
||||
|
||||
expect(fused.fusions[0]!.status).toBe('failed')
|
||||
expect(fused.fusions[0]!.error).toContain('remote boom')
|
||||
expect(fused.fusions[0]!.directory).toBe('/srv/worktrees/app-3')
|
||||
expect(localSessionCreate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('persists the server target on the run row', async () => {
|
||||
const run = await launchRemote()
|
||||
|
||||
expect(getMultiRun(db, run.id)).toMatchObject({
|
||||
repoId: null,
|
||||
serverId: SERVER_ID,
|
||||
directory: REMOTE_DIR,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -473,7 +473,7 @@ describe('MultiRunService', () => {
|
||||
expect(error).toBeInstanceOf(MultiRunError)
|
||||
expect(error).toMatchObject({ status: 400 })
|
||||
expect(repoWorkspaces.remove).toHaveBeenCalledTimes(1)
|
||||
expect(service.list(repoId)[0]!.entries[0]!.status).toBe('started')
|
||||
expect(service.list({ kind: 'repo', repoId })[0]!.entries[0]!.status).toBe('started')
|
||||
})
|
||||
|
||||
it('records the workspace of a failed isolated launch when prompting fails and removes it on discard', async () => {
|
||||
@@ -585,7 +585,7 @@ describe('MultiRunService', () => {
|
||||
expect(error).toBeInstanceOf(MultiRunError)
|
||||
expect(error).toMatchObject({ status: 502 })
|
||||
|
||||
expect(service.list(repoId)[0]!.entries[0]!.status).toBe('started')
|
||||
expect(service.list({ kind: 'repo', repoId })[0]!.entries[0]!.status).toBe('started')
|
||||
|
||||
const discarded = await service.discard(run.id, entry.id)
|
||||
|
||||
@@ -602,7 +602,7 @@ describe('MultiRunService', () => {
|
||||
await service.launch({ repoId, name: 'First', prompt: 'go', models: ['openai/a'], isolate: false })
|
||||
await service.launch({ repoId, name: 'Second', prompt: 'go', models: ['openai/b'], isolate: false })
|
||||
|
||||
const runs = service.list(repoId)
|
||||
const runs = service.list({ kind: 'repo', repoId })
|
||||
|
||||
expect(runs.map((run) => run.name)).toEqual(['Second', 'First'])
|
||||
})
|
||||
@@ -846,7 +846,7 @@ describe('MultiRunService', () => {
|
||||
unavailableSources: [expect.objectContaining({ reason: 'running' })],
|
||||
})
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
expect(service.list(repoId)[0]!.fusions).toEqual([])
|
||||
expect(service.list({ kind: 'repo', repoId })[0]!.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects fusion when the prompt exceeds the context limit', async () => {
|
||||
@@ -872,7 +872,7 @@ describe('MultiRunService', () => {
|
||||
expect(error).toBeInstanceOf(FusionContextLimitError)
|
||||
expect(error).toMatchObject({ status: 413, code: 'FUSION_CONTEXT_LIMIT' })
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
expect(service.list(repoId)[0]!.fusions).toEqual([])
|
||||
expect(service.list({ kind: 'repo', repoId })[0]!.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects fusion with an unavailable synthesis model before creating a fusion', async () => {
|
||||
@@ -899,7 +899,7 @@ describe('MultiRunService', () => {
|
||||
expect(error).toMatchObject({ status: 400 })
|
||||
expect((error as Error).message).toContain('not available')
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
expect(service.list(repoId)[0]!.fusions).toEqual([])
|
||||
expect(service.list({ kind: 'repo', repoId })[0]!.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('records a failed fusion with the workspace directory when the launch fails', async () => {
|
||||
@@ -1006,7 +1006,7 @@ describe('MultiRunService', () => {
|
||||
})
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
|
||||
const recovered = service.list(repoId)[0]!.fusions[0]!
|
||||
const recovered = service.list({ kind: 'repo', repoId })[0]!.fusions[0]!
|
||||
expect(recovered.status).toBe('started')
|
||||
expect(recovered.error).toBeNull()
|
||||
})
|
||||
@@ -1053,7 +1053,7 @@ describe('MultiRunService', () => {
|
||||
const service = createService(client, repoWorkspaces.service)
|
||||
const record = createMultiRunWithEntries(
|
||||
db,
|
||||
{ repoId: ASSISTANT_REPO_ID, name: 'Sweep', prompt: 'go', isolated: false, baseRef: null },
|
||||
{ repoId: ASSISTANT_REPO_ID, serverId: 'local', directory: null, name: 'Sweep', prompt: 'go', isolated: false, baseRef: null },
|
||||
['openai/a', 'openai/b'],
|
||||
)
|
||||
|
||||
@@ -1096,7 +1096,7 @@ describe('MultiRunService', () => {
|
||||
expect(error).toMatchObject({ status: 400 })
|
||||
expect((error as Error).message).toBe('Unknown multi-run entry 9999')
|
||||
expect(sessionCreate).not.toHaveBeenCalled()
|
||||
expect(service.list(repoId)[0]!.fusions).toEqual([])
|
||||
expect(service.list({ kind: 'repo', repoId })[0]!.fusions).toEqual([])
|
||||
})
|
||||
|
||||
it('persists the group and its entries in one transaction', () => {
|
||||
@@ -1104,10 +1104,11 @@ describe('MultiRunService', () => {
|
||||
db.run(`CREATE TRIGGER fail_entry BEFORE INSERT ON multi_run_entries BEGIN SELECT RAISE(ABORT, 'nope'); END`)
|
||||
|
||||
expect(() =>
|
||||
createMultiRunWithEntries(db, { repoId, name: 'Sweep', prompt: 'go', isolated: false, baseRef: null }, [
|
||||
'openai/a',
|
||||
'openai/b',
|
||||
]),
|
||||
createMultiRunWithEntries(
|
||||
db,
|
||||
{ repoId, serverId: 'local', directory: null, name: 'Sweep', prompt: 'go', isolated: false, baseRef: null },
|
||||
['openai/a', 'openai/b'],
|
||||
),
|
||||
).toThrow()
|
||||
|
||||
const count = db.prepare('SELECT COUNT(*) AS count FROM multi_runs').get() as { count: number }
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { NotificationService } from '../../src/services/notification'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { sseAggregator, type SSEEvent } from '../../src/services/sse-aggregator'
|
||||
import * as repoService from '../../src/services/repo'
|
||||
import type { PushNotificationPayload } from '@opencode-manager/shared/types'
|
||||
|
||||
vi.mock('../../src/services/repo', () => ({
|
||||
resolveRepoForDirectory: vi.fn(async () => null),
|
||||
}))
|
||||
|
||||
const USER_ID = 'user-1'
|
||||
const SERVER_ID = 'srv_a'
|
||||
const DIRECTORY = '/remote/repo'
|
||||
|
||||
const sendResult = { delivered: 0, expired: 0, failed: 0, total: 0 }
|
||||
|
||||
function permissionAskedEvent(sessionID: string): SSEEvent {
|
||||
return {
|
||||
id: 'evt_perm_1',
|
||||
created: 1700000000000,
|
||||
type: 'permission.asked',
|
||||
location: { directory: DIRECTORY },
|
||||
data: {
|
||||
id: 'perm-1',
|
||||
sessionID,
|
||||
action: 'shell',
|
||||
resources: ['ls -la'],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function createService(server: { name: string; enabled: boolean } | null = { name: 'Studio', enabled: true }) {
|
||||
const db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
const registry = { get: vi.fn(() => server) }
|
||||
const service = new NotificationService(db, registry)
|
||||
vi.spyOn(service, 'isConfigured').mockReturnValue(true)
|
||||
service.saveSubscription(USER_ID, 'https://push.example.com/sub-1', 'p256dh-key', 'auth-key')
|
||||
new SettingsService(db).updateSettings(
|
||||
{
|
||||
notifications: {
|
||||
enabled: true,
|
||||
events: { permissionAsked: true, questionAsked: true, sessionError: true, sessionIdle: true },
|
||||
},
|
||||
},
|
||||
USER_ID,
|
||||
)
|
||||
return { service, registry }
|
||||
}
|
||||
|
||||
describe('NotificationService remote server events', () => {
|
||||
beforeEach(() => {
|
||||
sseAggregator.shutdown()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('builds a server session URL with the server name and skips repo resolution', async () => {
|
||||
const { service, registry } = createService()
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.handleSSEEvent(DIRECTORY, permissionAskedEvent('ses_remote'), SERVER_ID)
|
||||
|
||||
expect(repoService.resolveRepoForDirectory).not.toHaveBeenCalled()
|
||||
expect(registry.get).toHaveBeenCalledWith(SERVER_ID)
|
||||
expect(send).toHaveBeenCalledTimes(1)
|
||||
const payload = send.mock.calls[0]?.[1] as PushNotificationPayload
|
||||
expect(payload.title).toBe('Run Command')
|
||||
expect(payload.body).toBe('Studio · ls -la')
|
||||
expect(payload.data?.url).toBe('/servers/srv_a/sessions/ses_remote')
|
||||
expect(payload.data?.serverId).toBe(SERVER_ID)
|
||||
expect(payload.data?.serverName).toBe('Studio')
|
||||
expect(payload.data?.repoId).toBeUndefined()
|
||||
expect(payload.data?.repoName).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops events for a disabled server', async () => {
|
||||
const { service } = createService({ name: 'Studio', enabled: false })
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.handleSSEEvent(DIRECTORY, permissionAskedEvent('ses_remote'), SERVER_ID)
|
||||
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('drops events for a deleted server', async () => {
|
||||
const { service } = createService(null)
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.handleSSEEvent(DIRECTORY, permissionAskedEvent('ses_remote'), SERVER_ID)
|
||||
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('suppresses a remote subagent session using the server-scoped check', async () => {
|
||||
const { service } = createService()
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
const isSubagent = vi.spyOn(sseAggregator, 'isSubagentSession').mockReturnValue(true)
|
||||
|
||||
await service.handleSSEEvent(DIRECTORY, permissionAskedEvent('ses_sub'), SERVER_ID)
|
||||
|
||||
expect(isSubagent).toHaveBeenCalledWith('ses_sub', SERVER_ID)
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('suppresses a remote session the user is viewing on that server', async () => {
|
||||
const { service } = createService()
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
const viewed = vi.spyOn(sseAggregator, 'isSessionBeingViewed').mockReturnValue(true)
|
||||
|
||||
await service.handleSSEEvent(DIRECTORY, permissionAskedEvent('ses_remote'), SERVER_ID)
|
||||
|
||||
expect(viewed).toHaveBeenCalledWith('ses_remote', SERVER_ID)
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -4,7 +4,7 @@ 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 { NotificationService } from '../../src/services/notification'
|
||||
import { NotificationService, type NotificationServerRegistry } from '../../src/services/notification'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import { sseAggregator, type SSEEvent } from '../../src/services/sse-aggregator'
|
||||
import type { PushNotificationPayload } from '@opencode-manager/shared/types'
|
||||
@@ -47,7 +47,10 @@ function permissionAskedEvent(sessionID: string): SSEEvent {
|
||||
}
|
||||
}
|
||||
|
||||
function createService(db = new Database(':memory:')): NotificationService {
|
||||
function createService(
|
||||
db = new Database(':memory:'),
|
||||
registry: NotificationServerRegistry | null = null,
|
||||
): NotificationService {
|
||||
migrate(db, allMigrations)
|
||||
createRepo(db, {
|
||||
localPath: 'repo-one',
|
||||
@@ -58,7 +61,7 @@ function createService(db = new Database(':memory:')): NotificationService {
|
||||
isLocal: true,
|
||||
})
|
||||
|
||||
const service = new NotificationService(db)
|
||||
const service = new NotificationService(db, registry)
|
||||
vi.spyOn(service, 'isConfigured').mockReturnValue(true)
|
||||
service.saveSubscription(USER_ID, 'https://push.example.com/sub-1', 'p256dh-key', 'auth-key')
|
||||
new SettingsService(db).updateSettings(
|
||||
@@ -168,7 +171,7 @@ describe('NotificationService.handleSSEEvent session routing', () => {
|
||||
|
||||
await service.handleSSEEvent(DIRECTORY, permissionAskedEvent('ses_perm'))
|
||||
|
||||
expect(suppressor).toHaveBeenCalledWith(expect.objectContaining({ type: 'permission.asked' }), 'ses_perm')
|
||||
expect(suppressor).toHaveBeenCalledWith(expect.objectContaining({ type: 'permission.asked' }), 'ses_perm', 'local')
|
||||
expect(send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -195,6 +198,7 @@ describe('NotificationService goal outcomes', () => {
|
||||
const completedGoal: SessionGoal = {
|
||||
id: 1,
|
||||
sessionId: 'ses_goal',
|
||||
serverId: 'local',
|
||||
directory: DIRECTORY,
|
||||
objective: 'Ship the feature',
|
||||
status: 'completed',
|
||||
@@ -229,6 +233,27 @@ describe('NotificationService goal outcomes', () => {
|
||||
expect(payload.data?.url).toBe('/repos/1/sessions/ses_goal')
|
||||
})
|
||||
|
||||
it('notifies a remote goal outcome with its server in the payload', async () => {
|
||||
const service = createService(new Database(':memory:'), {
|
||||
get: (serverId) => (serverId === 'srv_kitchen' ? { name: 'Kitchen', enabled: true } : null),
|
||||
})
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
await service.notifyGoalOutcome({
|
||||
...completedGoal,
|
||||
sessionId: 'ses_remote',
|
||||
serverId: 'srv_kitchen',
|
||||
directory: '/home/me/app',
|
||||
})
|
||||
|
||||
expect(send).toHaveBeenCalledTimes(1)
|
||||
const payload = send.mock.calls[0]?.[1] as PushNotificationPayload
|
||||
expect(payload.body).toContain('Kitchen')
|
||||
expect(payload.data?.serverId).toBe('srv_kitchen')
|
||||
expect(payload.data?.serverName).toBe('Kitchen')
|
||||
expect(payload.data?.url).toBe('/servers/srv_kitchen/sessions/ses_remote')
|
||||
})
|
||||
|
||||
it('reports the stop reason instead of a stale verdict reason', async () => {
|
||||
const service = createService()
|
||||
const send = vi.spyOn(service, 'sendToUser').mockResolvedValue(sendResult)
|
||||
|
||||
@@ -371,6 +371,51 @@ describe('RemoteServerEventHub event delivery', () => {
|
||||
|
||||
expect(client.frames).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('notifies server event listeners with the remote server id and resolved directory', () => {
|
||||
const seen: Array<{ serverId: string; directory: string | null; type: string }> = []
|
||||
sseAggregator.onServerEvent((serverId, directory, event) => {
|
||||
seen.push({ serverId, directory, type: event.type })
|
||||
})
|
||||
|
||||
hub.start()
|
||||
const source = sources.sources[0]!
|
||||
source.message(remoteEvent('session.created', { sessionID: 'ses_1' }, '/repo'))
|
||||
source.message(remoteEvent('session.execution.succeeded', { sessionID: 'ses_1' }))
|
||||
|
||||
expect(seen).toEqual([
|
||||
{ serverId: 'srv_a', directory: '/repo', type: 'session.created' },
|
||||
{ serverId: 'srv_a', directory: '/repo', type: 'session.execution.succeeded' },
|
||||
])
|
||||
expect(sseAggregator.getActiveSessions()).toEqual({})
|
||||
})
|
||||
|
||||
it('tracks remote subagent sessions per server', () => {
|
||||
hub.start()
|
||||
const source = sources.sources[0]!
|
||||
|
||||
source.message(remoteEvent('session.created', { sessionID: 'ses_sub', parentID: 'ses_root' }, '/repo'))
|
||||
|
||||
expect(hub.isSubagentSession('srv_a', 'ses_sub')).toBe(true)
|
||||
expect(sseAggregator.isSubagentSession('ses_sub', 'srv_a')).toBe(true)
|
||||
expect(sseAggregator.isSubagentSession('ses_sub')).toBe(false)
|
||||
expect(sseAggregator.isSubagentSession('ses_sub', 'srv_b')).toBe(false)
|
||||
|
||||
source.message(remoteEvent('session.deleted', { sessionID: 'ses_sub' }))
|
||||
|
||||
expect(hub.isSubagentSession('srv_a', 'ses_sub')).toBe(false)
|
||||
expect(sseAggregator.isSubagentSession('ses_sub', 'srv_a')).toBe(false)
|
||||
})
|
||||
|
||||
it('notifies server connected listeners when a remote stream opens', () => {
|
||||
const seen: string[] = []
|
||||
sseAggregator.onServerConnected(serverId => { seen.push(serverId) })
|
||||
|
||||
hub.start()
|
||||
sources.sources[1]!.open()
|
||||
|
||||
expect(seen).toEqual(['srv_b'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('RemoteServerEventHub reconnection', () => {
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
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 type { OpenCodeApi } from '@opencode-manager/shared/opencode'
|
||||
import { ScheduleService } from '../../src/services/schedules'
|
||||
import { createStubOpenCodeClient, stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
|
||||
import { createStubScheduleApi } from '../helpers/stub-schedule-api'
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const REMOTE_SERVER = {
|
||||
id: 'srv_kitchen',
|
||||
name: 'Kitchen server',
|
||||
baseUrl: 'http://kitchen.local:5551',
|
||||
username: 'opencode',
|
||||
enabled: true,
|
||||
createdAt: 0,
|
||||
updatedAt: 0,
|
||||
}
|
||||
|
||||
function createDatabase(): Database {
|
||||
const db = new Database(':memory:')
|
||||
db.exec('PRAGMA foreign_keys = OFF')
|
||||
migrate(db, allMigrations)
|
||||
const now = Date.now()
|
||||
db.prepare(
|
||||
`INSERT INTO opencode_servers (id, name, base_url, username, enabled, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
).run(REMOTE_SERVER.id, REMOTE_SERVER.name, REMOTE_SERVER.baseUrl, REMOTE_SERVER.username, 1, now, now)
|
||||
return db
|
||||
}
|
||||
|
||||
function createClient() {
|
||||
const stub = createStubScheduleApi()
|
||||
const api = { ...stub.api, ...stubLoadedModelCatalog() } as unknown as OpenCodeApi
|
||||
return { client: createStubOpenCodeClient({ api }), api: stub.api }
|
||||
}
|
||||
|
||||
function createService(db: Database, localClient: ReturnType<typeof createStubOpenCodeClient>, remoteClient: ReturnType<typeof createStubOpenCodeClient>, enabled = true) {
|
||||
const worktreeManager = {
|
||||
prepare: vi.fn().mockResolvedValue(null),
|
||||
finalize: vi.fn().mockResolvedValue({ commitHash: null }),
|
||||
pruneRunArtifacts: vi.fn().mockResolvedValue(undefined),
|
||||
listWorktrees: vi.fn().mockReturnValue([]),
|
||||
releaseWorktree: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
const registry = {
|
||||
get: vi.fn(() => ({ ...REMOTE_SERVER, enabled })),
|
||||
getClient: vi.fn(() => remoteClient),
|
||||
}
|
||||
const service = new ScheduleService(db, localClient, worktreeManager as never, registry as never)
|
||||
return { service, worktreeManager, registry }
|
||||
}
|
||||
|
||||
const baseRequest = {
|
||||
name: 'Nightly audit',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval' as const,
|
||||
intervalMinutes: 60,
|
||||
prompt: 'Audit the project.',
|
||||
}
|
||||
|
||||
describe('remote schedule targets', () => {
|
||||
let db: Database
|
||||
|
||||
beforeEach(() => {
|
||||
db = createDatabase()
|
||||
const staticState = ScheduleService as unknown as { activeRuns: Map<number, unknown>; pendingCancels: Map<number, unknown> }
|
||||
staticState.activeRuns.clear()
|
||||
staticState.pendingCancels.clear()
|
||||
})
|
||||
|
||||
it('creates a remote job with an in-place workspace mode', 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)
|
||||
|
||||
expect(job.repoId).toBeNull()
|
||||
expect(job.serverId).toBe(REMOTE_SERVER.id)
|
||||
expect(job.directory).toBe('/srv/projects/audit')
|
||||
expect(job.workspaceMode).toBe('in-place')
|
||||
expect(localClient.api.session.create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects worktree workspace modes for a remote job', async () => {
|
||||
const localClient = createClient().client
|
||||
const { client } = createClient()
|
||||
const { service } = createService(db, localClient, client)
|
||||
|
||||
await expect(
|
||||
service.createServerJob(REMOTE_SERVER.id, '/srv/projects/audit', { ...baseRequest, workspaceMode: 'worktree' }),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
expect(getScheduleJobById(db, null, 1)).toBeNull()
|
||||
})
|
||||
|
||||
it('runs a remote job on the remote client without touching local git', async () => {
|
||||
const localClient = createClient().client
|
||||
const { client, api } = createClient()
|
||||
const { service, worktreeManager } = createService(db, localClient, client)
|
||||
const job = await service.createServerJob(REMOTE_SERVER.id, '/srv/projects/audit', baseRequest)
|
||||
|
||||
const run = await service.runServerJob(REMOTE_SERVER.id, job.id, 'manual')
|
||||
|
||||
expect(run.repoId).toBeNull()
|
||||
expect(run.serverId).toBe(REMOTE_SERVER.id)
|
||||
expect(run.status).toBe('running')
|
||||
expect(api.session.create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
location: { directory: '/srv/projects/audit' },
|
||||
}))
|
||||
expect(localClient.api.session.create).not.toHaveBeenCalled()
|
||||
expect(worktreeManager.prepare).not.toHaveBeenCalled()
|
||||
expect(worktreeManager.finalize).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('records a failed run when 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 disabled = createService(db, localClient, client, false)
|
||||
|
||||
await expect(disabled.service.runServerJob(REMOTE_SERVER.id, job.id, 'manual')).rejects.toMatchObject({ status: 400 })
|
||||
|
||||
const runs = listScheduleRunsByJob(db, null, job.id)
|
||||
expect(runs).toHaveLength(1)
|
||||
expect(runs[0]).toMatchObject({ status: 'failed', serverId: REMOTE_SERVER.id })
|
||||
expect(runs[0]?.errorText).toContain('disabled')
|
||||
})
|
||||
|
||||
it('lists remote jobs and runs with the linked server name', 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)
|
||||
await service.runServerJob(REMOTE_SERVER.id, job.id, 'manual')
|
||||
|
||||
const jobs = service.listAllJobsWithRepos()
|
||||
expect(jobs.find((entry) => entry.id === job.id)).toMatchObject({
|
||||
repoId: null,
|
||||
serverId: REMOTE_SERVER.id,
|
||||
directory: '/srv/projects/audit',
|
||||
serverName: REMOTE_SERVER.name,
|
||||
repoName: REMOTE_SERVER.name,
|
||||
})
|
||||
|
||||
const runs = service.listAllRuns()
|
||||
expect(runs[0]).toMatchObject({ serverId: REMOTE_SERVER.id, serverName: REMOTE_SERVER.name })
|
||||
})
|
||||
})
|
||||
@@ -1100,3 +1100,156 @@ describe('SessionGoalService recovery', () => {
|
||||
expect(fake.auditorCalls).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('SessionGoalService remote servers', () => {
|
||||
let db: Database
|
||||
|
||||
const REMOTE_SERVER_ID = 'srv_remote'
|
||||
|
||||
function createRemoteRegistry(
|
||||
local: FakeSessionGoalClient,
|
||||
remote: FakeSessionGoalClient,
|
||||
options: { missing?: boolean; disabled?: boolean } = {},
|
||||
) {
|
||||
return {
|
||||
getClient: (serverId: string) =>
|
||||
serverId === 'local' ? local.client : remote.client,
|
||||
get: (serverId: string) => {
|
||||
if (serverId === 'local') return { enabled: true }
|
||||
if (options.missing) return null
|
||||
return { enabled: !options.disabled }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
db = createTestDb()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('continues a remote goal through the remote client while the auditor stays local', async () => {
|
||||
const local = createFakeSessionGoalClient({ auditorReplies: ['{"verdict":"continue","reason":"keep going"}'] })
|
||||
const remote = createFakeSessionGoalClient({
|
||||
tokens: { ses_remote: { input: 10, output: 5, reasoning: 0 } },
|
||||
})
|
||||
const service = new SessionGoalService(db, createRemoteRegistry(local, remote), new SettingsService(db), {
|
||||
quietMs: 0,
|
||||
})
|
||||
|
||||
const goal = await service.start({
|
||||
sessionId: 'ses_remote',
|
||||
serverId: REMOTE_SERVER_ID,
|
||||
directory: DIRECTORY,
|
||||
objective: 'Remote work',
|
||||
})
|
||||
|
||||
expect(goal.serverId).toBe(REMOTE_SERVER_ID)
|
||||
|
||||
await service.handleEvent(DIRECTORY, executionStarted('ses_remote'), REMOTE_SERVER_ID)
|
||||
await service.handleEvent(DIRECTORY, sessionIdle('ses_remote'), REMOTE_SERVER_ID)
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(remote.promptCalls).toHaveLength(1)
|
||||
expect(remote.promptCalls[0]?.sessionID).toBe('ses_remote')
|
||||
expect(local.promptCalls).toHaveLength(0)
|
||||
expect(local.auditorCalls).toHaveLength(1)
|
||||
expect(remote.auditorCalls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('keeps goal state scoped to the server that owns the session', async () => {
|
||||
const local = createFakeSessionGoalClient()
|
||||
const remote = createFakeSessionGoalClient({
|
||||
tokens: { ses_shared: { input: 0, output: 0, reasoning: 0 } },
|
||||
})
|
||||
const service = new SessionGoalService(db, createRemoteRegistry(local, remote), new SettingsService(db))
|
||||
|
||||
await service.start({
|
||||
sessionId: 'ses_shared',
|
||||
serverId: REMOTE_SERVER_ID,
|
||||
directory: DIRECTORY,
|
||||
objective: 'Remote only',
|
||||
})
|
||||
|
||||
expect(service.getLatest('ses_shared')).toBeNull()
|
||||
expect(service.getLatest('ses_shared', REMOTE_SERVER_ID)?.objective).toBe('Remote only')
|
||||
})
|
||||
|
||||
it('recovers a remote goal using the remote client', async () => {
|
||||
const local = createFakeSessionGoalClient({ auditorReplies: ['{"verdict":"done","reason":"finished"}'] })
|
||||
const remote = createFakeSessionGoalClient()
|
||||
const starter = new SessionGoalService(db, createRemoteRegistry(local, remote), new SettingsService(db))
|
||||
const goal = await starter.start({
|
||||
sessionId: 'ses_remote',
|
||||
serverId: REMOTE_SERVER_ID,
|
||||
directory: DIRECTORY,
|
||||
objective: 'Remote recovery',
|
||||
})
|
||||
transitionSessionGoal(db, goal.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const restarted = new SessionGoalService(db, createRemoteRegistry(local, remote), new SettingsService(db), {
|
||||
quietMs: 0,
|
||||
})
|
||||
await restarted.recoverOpenGoals()
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(local.auditorCalls).toHaveLength(1)
|
||||
expect(remote.auditorCalls).toHaveLength(0)
|
||||
expect(restarted.getLatest('ses_remote', REMOTE_SERVER_ID)?.status).toBe('completed')
|
||||
})
|
||||
|
||||
it('leaves remote goals open when their server is missing', async () => {
|
||||
const local = createFakeSessionGoalClient()
|
||||
const remote = createFakeSessionGoalClient()
|
||||
const starter = new SessionGoalService(db, createRemoteRegistry(local, remote), new SettingsService(db))
|
||||
const goal = await starter.start({
|
||||
sessionId: 'ses_remote',
|
||||
serverId: REMOTE_SERVER_ID,
|
||||
directory: DIRECTORY,
|
||||
objective: 'Orphaned',
|
||||
})
|
||||
transitionSessionGoal(db, goal.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const restarted = new SessionGoalService(
|
||||
db,
|
||||
createRemoteRegistry(local, remote, { missing: true }),
|
||||
new SettingsService(db),
|
||||
{ quietMs: 0 },
|
||||
)
|
||||
await restarted.recoverOpenGoals()
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(restarted.getLatest('ses_remote', REMOTE_SERVER_ID)).toMatchObject({ status: 'active' })
|
||||
expect(local.auditorCalls).toHaveLength(0)
|
||||
expect(remote.auditorCalls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('leaves remote goals open when their server is disabled', async () => {
|
||||
const local = createFakeSessionGoalClient()
|
||||
const remote = createFakeSessionGoalClient()
|
||||
const starter = new SessionGoalService(db, createRemoteRegistry(local, remote), new SettingsService(db))
|
||||
const goal = await starter.start({
|
||||
sessionId: 'ses_remote',
|
||||
serverId: REMOTE_SERVER_ID,
|
||||
directory: DIRECTORY,
|
||||
objective: 'Disabled',
|
||||
})
|
||||
transitionSessionGoal(db, goal.id, ['active'], { turnState: 'running' })
|
||||
|
||||
const restarted = new SessionGoalService(
|
||||
db,
|
||||
createRemoteRegistry(local, remote, { disabled: true }),
|
||||
new SettingsService(db),
|
||||
{ quietMs: 0 },
|
||||
)
|
||||
await restarted.recoverOpenGoals()
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(restarted.getLatest('ses_remote', REMOTE_SERVER_ID)).toMatchObject({ status: 'active' })
|
||||
expect(remote.auditorCalls).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -42,6 +42,21 @@ function createPermissionModeService(
|
||||
return new SessionPermissionModeService(db, client, settingsService, new SessionAncestry(client))
|
||||
}
|
||||
|
||||
function createMultiServerService(
|
||||
db: Database,
|
||||
clients: { local: OpenCodeClient } & Record<string, OpenCodeClient>,
|
||||
settingsService: SettingsService,
|
||||
): SessionPermissionModeService {
|
||||
const local = clients.local
|
||||
const resolve = (serverId: string) => (serverId === 'local' ? local : clients[serverId] ?? local)
|
||||
return new SessionPermissionModeService(
|
||||
db,
|
||||
{ getClient: resolve },
|
||||
settingsService,
|
||||
new SessionAncestry(resolve),
|
||||
)
|
||||
}
|
||||
|
||||
function permissionAskedEvent(sessionID: string, id: string): SSEEvent {
|
||||
return {
|
||||
id: `evt_${id}`,
|
||||
@@ -555,4 +570,116 @@ describe('SessionPermissionModeService', () => {
|
||||
|
||||
expect(client.replyPermission).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
describe('remote servers', () => {
|
||||
it('scopes stored modes by server', async () => {
|
||||
setSessionPermissionMode(db, 'ses_remote', 'auto', 'srv_remote')
|
||||
const local = createFakeSessionPermissionClient({ parents: { ses_remote: null } })
|
||||
const remote = createFakeSessionPermissionClient({ parents: { ses_remote: null } })
|
||||
const service = createMultiServerService(db, { local, srv_remote: remote }, new SettingsService(db))
|
||||
|
||||
await expect(service.getEffectiveMode('ses_remote')).resolves.toMatchObject({ mode: 'ask' })
|
||||
await expect(service.getEffectiveMode('ses_remote', 'srv_remote')).resolves.toMatchObject({ mode: 'auto' })
|
||||
|
||||
await service.setMode('ses_remote', 'auto', DIRECTORY, 'srv_remote')
|
||||
|
||||
expect(getSessionPermissionMode(db, 'ses_remote')).toBeNull()
|
||||
expect(getSessionPermissionMode(db, 'ses_remote', 'srv_remote')).toBe('auto')
|
||||
expect(remote.replyPermission).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('auto-accepts a remote permission request through the remote client', async () => {
|
||||
setSessionPermissionMode(db, 'ses_root', 'auto', 'srv_remote')
|
||||
const local = createFakeSessionPermissionClient({ parents: { ses_root: null } })
|
||||
const remote = createFakeSessionPermissionClient({ parents: { ses_root: null } })
|
||||
const service = createMultiServerService(db, { local, srv_remote: remote }, new SettingsService(db))
|
||||
|
||||
await service.handleEvent(DIRECTORY, permissionAskedEvent('ses_root', 'perm-remote'), 'srv_remote')
|
||||
|
||||
expect(remote.replyPermission).toHaveBeenCalledTimes(1)
|
||||
expect(remote.replyPermission).toHaveBeenCalledWith({
|
||||
sessionID: 'ses_root',
|
||||
requestID: 'perm-remote',
|
||||
decision: 'once',
|
||||
})
|
||||
expect(local.replyPermission).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves remote session parents through the remote client', async () => {
|
||||
setSessionPermissionMode(db, 'ses_root', 'auto', 'srv_remote')
|
||||
const local = createFakeSessionPermissionClient()
|
||||
const remote = createFakeSessionPermissionClient({ parents: { ses_child: 'ses_root', ses_root: null } })
|
||||
const service = createMultiServerService(db, { local, srv_remote: remote }, new SettingsService(db))
|
||||
|
||||
await service.handleEvent(DIRECTORY, permissionAskedEvent('ses_child', 'perm-child'), 'srv_remote')
|
||||
|
||||
expect(remote.replyPermission).toHaveBeenCalledWith({
|
||||
sessionID: 'ses_child',
|
||||
requestID: 'perm-child',
|
||||
decision: 'once',
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts pending requests for active sessions on the remote server', async () => {
|
||||
setSessionPermissionMode(db, 'ses_remote', 'auto', 'srv_remote')
|
||||
const local = createFakeSessionPermissionClient()
|
||||
const remote = createFakeSessionPermissionClient({
|
||||
parents: { ses_remote: null },
|
||||
directories: { ses_remote: DIRECTORY },
|
||||
activeSessions: ['ses_remote'],
|
||||
pendingRequests: { [DIRECTORY]: [{ id: 'perm-remote', sessionID: 'ses_remote' }] },
|
||||
})
|
||||
const service = createMultiServerService(db, { local, srv_remote: remote }, new SettingsService(db))
|
||||
|
||||
await service.acceptPendingRequestsForActiveSessions('srv_remote')
|
||||
|
||||
expect(remote.replyPermission).toHaveBeenCalledWith({
|
||||
sessionID: 'ses_remote',
|
||||
requestID: 'perm-remote',
|
||||
decision: 'once',
|
||||
})
|
||||
expect(local.replyPermission).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports schedule locks only for the local server', async () => {
|
||||
createRepo(db, {
|
||||
localPath: 'repo-one',
|
||||
sourcePath: '/abs/repo',
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: Date.now(),
|
||||
isLocal: true,
|
||||
})
|
||||
const run = createScheduleRun(db, {
|
||||
jobId: 1,
|
||||
repoId: 1,
|
||||
triggerSource: 'schedule',
|
||||
status: 'running',
|
||||
startedAt: Date.now(),
|
||||
createdAt: Date.now(),
|
||||
})
|
||||
updateScheduleRunMetadata(db, 1, 1, run.id, { sessionId: 'ses_scheduled' })
|
||||
|
||||
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')).resolves.toMatchObject({ lockedReason: 'schedule' })
|
||||
await expect(service.getEffectiveMode('ses_scheduled', 'srv_remote')).resolves.toMatchObject({
|
||||
lockedReason: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('suppresses permission notifications for remote auto sessions', async () => {
|
||||
setSessionPermissionMode(db, 'ses_root', 'auto', 'srv_remote')
|
||||
const local = createFakeSessionPermissionClient()
|
||||
const remote = createFakeSessionPermissionClient({ parents: { ses_root: null } })
|
||||
const service = createMultiServerService(db, { local, srv_remote: remote }, new SettingsService(db))
|
||||
const event = permissionAskedEvent('ses_root', 'perm-remote')
|
||||
|
||||
await expect(service.suppressesPermissionNotification(event, 'ses_root', 'srv_remote')).resolves.toBe(true)
|
||||
await expect(service.suppressesPermissionNotification(event, 'ses_root')).resolves.toBe(false)
|
||||
await expect(service.suppressesPermissionNotification(event, undefined, 'srv_remote')).resolves.toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -14,13 +14,13 @@ import {
|
||||
} from '../../src/services/session-reply'
|
||||
import { assistantMessage } from '../helpers/stub-schedule-api'
|
||||
|
||||
const mockOnEvent = vi.fn()
|
||||
const mockOnServerEvent = vi.fn()
|
||||
vi.mock('../../src/services/sse-aggregator', () => ({
|
||||
sseAggregator: { onEvent: (...args: unknown[]) => mockOnEvent(...args) },
|
||||
sseAggregator: { onServerEvent: (...args: unknown[]) => mockOnServerEvent(...args) },
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnEvent.mockReset()
|
||||
mockOnServerEvent.mockReset()
|
||||
})
|
||||
|
||||
function createFakeClient(messages: SessionMessageInfo[], active: Record<string, unknown> = {}): OpenCodeClient {
|
||||
@@ -166,14 +166,14 @@ describe('sessionSettleSignal', () => {
|
||||
|
||||
describe('waitForSessionSettled', () => {
|
||||
function captureListener() {
|
||||
let listener: ((directory: string, event: unknown) => void) | undefined
|
||||
let listener: ((serverId: string, directory: string | null, event: unknown) => void) | undefined
|
||||
const unsubscribe = vi.fn()
|
||||
mockOnEvent.mockImplementation((callback: (directory: string, event: unknown) => void) => {
|
||||
mockOnServerEvent.mockImplementation((callback: (serverId: string, directory: string | null, event: unknown) => void) => {
|
||||
listener = callback
|
||||
return unsubscribe
|
||||
})
|
||||
return {
|
||||
emit: (event: unknown) => listener?.('', event),
|
||||
emit: (event: unknown, serverId = 'local') => listener?.(serverId, null, event),
|
||||
unsubscribe,
|
||||
}
|
||||
}
|
||||
@@ -182,7 +182,7 @@ describe('waitForSessionSettled', () => {
|
||||
const client = createFakeClient([], { 'ses-1': {} })
|
||||
|
||||
await expect(waitForSessionSettled(client, 'ses-1', 0)).resolves.toBeUndefined()
|
||||
expect(mockOnEvent).not.toHaveBeenCalled()
|
||||
expect(mockOnServerEvent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves once the session settles and unsubscribes', async () => {
|
||||
@@ -224,4 +224,17 @@ describe('waitForSessionSettled', () => {
|
||||
await expect(waitForSessionSettled(client, 'ses-1', 20)).resolves.toBeUndefined()
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('ignores settle events from other servers when a server id is provided', async () => {
|
||||
const client = createFakeClient([], { 'ses-1': {} })
|
||||
const { emit, unsubscribe } = captureListener()
|
||||
|
||||
const settled = waitForSessionSettled(client, 'ses-1', 1000, 'srv_a')
|
||||
emit({ type: 'session.idle', data: { sessionID: 'ses-1' } }, 'local')
|
||||
expect(unsubscribe).not.toHaveBeenCalled()
|
||||
|
||||
emit({ type: 'session.idle', data: { sessionID: 'ses-1' } }, 'srv_a')
|
||||
await expect(settled).resolves.toBeUndefined()
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -836,6 +836,96 @@ describe('SSEAggregator directory-less session event routing', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('SSEAggregator server-aware event feed', () => {
|
||||
beforeEach(() => {
|
||||
sseAggregator.shutdown()
|
||||
sseAggregator.setPendingActionsFetcher(null)
|
||||
sseAggregator.setScheduledSessionsResolver(() => [])
|
||||
})
|
||||
|
||||
it('notifies server listeners for local events with the local server id and resolved directory', () => {
|
||||
const seen: Array<{ serverId: string; directory: string | null; type: string }> = []
|
||||
sseAggregator.onServerEvent((serverId, directory, event) => {
|
||||
seen.push({ serverId, directory, type: event.type })
|
||||
})
|
||||
|
||||
emitRawEvent({ type: 'session.created', location: { directory: '/r' }, data: { sessionID: 'ses_1' } })
|
||||
emitRawEvent({ type: 'session.execution.succeeded', data: { sessionID: 'ses_1' } })
|
||||
|
||||
expect(seen).toEqual([
|
||||
{ serverId: 'local', directory: '/r', type: 'session.created' },
|
||||
{ serverId: 'local', directory: '/r', type: 'session.execution.succeeded' },
|
||||
])
|
||||
})
|
||||
|
||||
it('delivers remote events with the remote server id without touching local active or subagent state', () => {
|
||||
const seen: Array<{ serverId: string; directory: string | null; type: string }> = []
|
||||
sseAggregator.onServerEvent((serverId, directory, event) => {
|
||||
seen.push({ serverId, directory, type: event.type })
|
||||
})
|
||||
|
||||
sseAggregator.notifyServerEvent('srv_a', '/repo', {
|
||||
id: 'evt_remote',
|
||||
created: 1,
|
||||
type: 'session.created',
|
||||
location: { directory: '/repo' },
|
||||
data: { sessionID: 'ses_remote', parentID: 'ses_parent' },
|
||||
} as never)
|
||||
|
||||
expect(seen).toEqual([{ serverId: 'srv_a', directory: '/repo', type: 'session.created' }])
|
||||
expect(sseAggregator.getActiveSessions()).toEqual({})
|
||||
expect(sseAggregator.isSubagentSession('ses_remote')).toBe(false)
|
||||
expect(sseAggregator.isSubagentSession('ses_remote', 'srv_a')).toBe(false)
|
||||
})
|
||||
|
||||
it('isolates a throwing server event listener from the others', () => {
|
||||
const throwing = vi.fn(() => { throw new Error('boom') })
|
||||
const healthy = vi.fn()
|
||||
sseAggregator.onServerEvent(throwing)
|
||||
const unsubscribe = sseAggregator.onServerEvent(healthy)
|
||||
|
||||
sseAggregator.notifyServerEvent('srv_a', '/repo', { type: 'session.idle', data: { sessionID: 'ses_1' } } as never)
|
||||
|
||||
expect(throwing).toHaveBeenCalledTimes(1)
|
||||
expect(healthy).toHaveBeenCalledTimes(1)
|
||||
|
||||
unsubscribe()
|
||||
sseAggregator.notifyServerEvent('srv_a', '/repo', { type: 'session.idle', data: { sessionID: 'ses_1' } } as never)
|
||||
expect(healthy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('notifies server-connected listeners for the local upstream and for remote streams', () => {
|
||||
const seen: string[] = []
|
||||
sseAggregator.onServerConnected(serverId => { seen.push(serverId) })
|
||||
|
||||
;(sseAggregator as unknown as { handleUpstreamOpen(wasConnectedBefore: boolean): void }).handleUpstreamOpen(false)
|
||||
sseAggregator.notifyServerConnected('srv_a')
|
||||
|
||||
expect(seen).toEqual(['local', 'srv_a'])
|
||||
})
|
||||
|
||||
it('scopes session visibility to the active server id', () => {
|
||||
sseAggregator.addClient('viewed-local', () => {}, () => {}, ['/r'])
|
||||
sseAggregator.addClient('viewed-remote', () => {}, () => {}, ['srv_a|/r'])
|
||||
|
||||
sseAggregator.setClientVisibility('viewed-local', true, 'ses_1')
|
||||
sseAggregator.setClientVisibility('viewed-remote', true, 'ses_2', 'srv_a')
|
||||
|
||||
expect(sseAggregator.isSessionBeingViewed('ses_1')).toBe(true)
|
||||
expect(sseAggregator.isSessionBeingViewed('ses_1', 'srv_a')).toBe(false)
|
||||
expect(sseAggregator.isSessionBeingViewed('ses_2', 'srv_a')).toBe(true)
|
||||
expect(sseAggregator.isSessionBeingViewed('ses_2')).toBe(false)
|
||||
})
|
||||
|
||||
it('clears the active server id when a client reports it is hidden', () => {
|
||||
sseAggregator.addClient('viewed-hidden', () => {}, () => {}, ['srv_a|/r'])
|
||||
sseAggregator.setClientVisibility('viewed-hidden', true, 'ses_1', 'srv_a')
|
||||
sseAggregator.setClientVisibility('viewed-hidden', false)
|
||||
|
||||
expect(sseAggregator.isSessionBeingViewed('ses_1', 'srv_a')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('SSEAggregator location-scoped catalog event broadcast', () => {
|
||||
beforeEach(() => {
|
||||
sseAggregator.shutdown()
|
||||
|
||||
@@ -31,8 +31,13 @@ function createTerminalService(
|
||||
provider: CredentialProvider,
|
||||
openSocket?: (url: string) => WebSocket,
|
||||
baseUrl = 'http://127.0.0.1:5551',
|
||||
includeLocalCredentials = true,
|
||||
): TerminalService {
|
||||
return new TerminalService(client, provider, () => baseUrl, openSocket)
|
||||
return new TerminalService(
|
||||
{ client, baseUrl: () => baseUrl, includeLocalCredentials },
|
||||
provider,
|
||||
openSocket,
|
||||
)
|
||||
}
|
||||
|
||||
class FakeUpstreamSocket {
|
||||
@@ -167,6 +172,83 @@ describe('TerminalService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('remote target', () => {
|
||||
it('does not inject local GitHub credentials when creating a terminal', async () => {
|
||||
const create = vi.fn(async () => ({
|
||||
location: { directory: '/repo' },
|
||||
data: createPty({ id: 'pty-remote', title: 'Terminal' }),
|
||||
}))
|
||||
const credentialProvider = createCredentialProvider({ GH_TOKEN: 'gh' })
|
||||
const service = createTerminalService(
|
||||
createClient({ create }),
|
||||
credentialProvider,
|
||||
undefined,
|
||||
'https://remote.internal',
|
||||
false,
|
||||
)
|
||||
|
||||
await service.create('/repo', { kind: 'shell', name: 'Terminal', env: { FOO: 'bar' } })
|
||||
|
||||
expect(credentialProvider.getGhCliEnv).not.toHaveBeenCalled()
|
||||
expect(create).toHaveBeenCalledWith(expect.objectContaining({ env: { FOO: 'bar' } }))
|
||||
})
|
||||
|
||||
it('keeps a remote shell environment empty without input env', async () => {
|
||||
let captured: Record<string, unknown> | undefined
|
||||
const create = vi.fn(async (input: Record<string, unknown>) => {
|
||||
captured = input
|
||||
return { location: { directory: '/repo' }, data: createPty() }
|
||||
})
|
||||
const service = createTerminalService(
|
||||
createClient({ create }),
|
||||
createCredentialProvider({ GH_TOKEN: 'gh' }),
|
||||
undefined,
|
||||
'https://remote.internal',
|
||||
false,
|
||||
)
|
||||
|
||||
await service.create('/repo', { kind: 'shell', name: 'Terminal' })
|
||||
|
||||
expect(captured?.env).toEqual({})
|
||||
})
|
||||
|
||||
it('builds the connect URL from the target base URL', async () => {
|
||||
const list = vi.fn(async ({ location }: { location: { directory: string } }) => ({
|
||||
location,
|
||||
data: [createPty({ id: 'pty-1' })],
|
||||
}))
|
||||
const token = vi.fn(async () => ({
|
||||
location: { directory: '/repo' },
|
||||
data: { ticket: 'remote-ticket', expires_in: 60 },
|
||||
}))
|
||||
const remoteClient = createClient({ list, connect: { token } })
|
||||
let opened: FakeUpstreamSocket | undefined
|
||||
const service = createTerminalService(
|
||||
createClient({}),
|
||||
createCredentialProvider(),
|
||||
(url) => {
|
||||
opened = new FakeUpstreamSocket(url)
|
||||
return opened as unknown as WebSocket
|
||||
},
|
||||
'https://local.internal',
|
||||
)
|
||||
const remote = service.forTarget({
|
||||
client: remoteClient,
|
||||
baseUrl: () => 'https://remote.internal',
|
||||
includeLocalCredentials: false,
|
||||
})
|
||||
|
||||
await remote.connect('/repo', 'pty-1', undefined, createPeer())
|
||||
|
||||
expect(list).toHaveBeenCalledWith({ location: { directory: '/repo' } })
|
||||
const url = new URL(opened!.url)
|
||||
expect(url.protocol).toBe('wss:')
|
||||
expect(url.host).toBe('remote.internal')
|
||||
expect(url.pathname).toBe('/api/pty/pty-1/connect')
|
||||
expect(url.searchParams.get('ticket')).toBe('remote-ticket')
|
||||
})
|
||||
})
|
||||
|
||||
describe('requireTerminal', () => {
|
||||
it('returns the terminal when the id exists in the directory', async () => {
|
||||
const list = vi.fn(async () => ({
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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' })
|
||||
}
|
||||
@@ -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' })
|
||||
})
|
||||
})
|
||||
@@ -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 }),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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' },
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
|
||||
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user