mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(schedules): add workspace modes and worktree management
This commit is contained in:
1 parent
c06075651d
commit
6ec3f3bd91
90 files changed
+2084
-801
No files matched your search
@@ -1,65 +1,38 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
/**
|
||||
* A schema change applied once per database. Migrations run in the order they appear in
|
||||
* `allMigrations`, and each is recorded by its `id`, which must never change once released.
|
||||
*
|
||||
* New migrations use a UTC timestamp id, `YYYYMMDDHHmm-short-name` (for example
|
||||
* `202610061345-schedule-workspace-mode`), in a file of the same name, so migrations written on
|
||||
* different branches cannot claim the same identity. Make `up` safe to run on a database that
|
||||
* already has the change, because merged branches may apply migrations in a different order.
|
||||
*
|
||||
* `legacy` only exists on the numbered migrations written before ids; it lets databases that
|
||||
* recorded them by version number in `schema_migrations` recognise them as applied.
|
||||
*/
|
||||
export interface Migration {
|
||||
version: number
|
||||
name: string
|
||||
id: string
|
||||
legacy?: { version: number; name: string }
|
||||
up(db: Database): void
|
||||
down(db: Database): void
|
||||
}
|
||||
|
||||
interface MigrationRecord {
|
||||
interface LegacyMigrationRecord {
|
||||
version: number
|
||||
name: string
|
||||
applied_at: number
|
||||
}
|
||||
|
||||
function ensureMigrationsTable(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
applied_at INTEGER NOT NULL
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
function getAppliedMigrations(db: Database): Map<number, string> {
|
||||
const rows = db.prepare('SELECT version, name FROM schema_migrations ORDER BY version').all() as MigrationRecord[]
|
||||
return new Map(rows.map(r => [r.version, r.name]))
|
||||
}
|
||||
|
||||
/**
|
||||
* Surfaces version-number collisions where a recorded migration's name differs
|
||||
* from the code migration registered under the same version. The runner keys on
|
||||
* version number alone, so a reused version silently skips the real migration
|
||||
* (e.g. an ADD COLUMN), producing later runtime errors that are hard to trace.
|
||||
* This converts that silent skip into a loud, actionable warning.
|
||||
*/
|
||||
function warnOnVersionNameMismatch(applied: Map<number, string>, migrations: Migration[]): void {
|
||||
for (const migration of migrations) {
|
||||
const recordedName = applied.get(migration.version)
|
||||
if (recordedName !== undefined && recordedName !== migration.name) {
|
||||
logger.warn(
|
||||
`Migration version ${migration.version} is recorded as "${recordedName}" but the code defines "${migration.name}". ` +
|
||||
`This migration was skipped; its schema changes may be missing. Verify the database schema and apply the changes manually if needed.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function markApplied(db: Database, migration: Migration): void {
|
||||
db.prepare('INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)')
|
||||
.run(migration.version, migration.name, Date.now())
|
||||
}
|
||||
|
||||
export function migrate(db: Database, migrations: Migration[]): void {
|
||||
ensureMigrationsTable(db)
|
||||
assertUniqueIds(migrations)
|
||||
db.run('CREATE TABLE IF NOT EXISTS applied_migrations (id TEXT PRIMARY KEY, applied_at INTEGER NOT NULL)')
|
||||
adoptLegacyMigrations(db, migrations)
|
||||
|
||||
const applied = getAppliedMigrations(db)
|
||||
warnOnVersionNameMismatch(applied, migrations)
|
||||
const sorted = [...migrations].sort((a, b) => a.version - b.version)
|
||||
const pending = sorted.filter(m => !applied.has(m.version))
|
||||
const applied = new Set((db.prepare('SELECT id FROM applied_migrations').all() as Array<{ id: string }>).map((row) => row.id))
|
||||
const pending = migrations.filter((migration) => !applied.has(migration.id))
|
||||
|
||||
if (pending.length === 0) {
|
||||
logger.info('Database schema is up to date')
|
||||
@@ -69,16 +42,16 @@ export function migrate(db: Database, migrations: Migration[]): void {
|
||||
logger.info(`Running ${pending.length} pending migration(s)`)
|
||||
|
||||
for (const migration of pending) {
|
||||
logger.info(`Applying migration ${migration.version}: ${migration.name}`)
|
||||
logger.info(`Applying migration ${migration.id}`)
|
||||
db.run('BEGIN TRANSACTION')
|
||||
try {
|
||||
migration.up(db)
|
||||
markApplied(db, migration)
|
||||
db.prepare('INSERT INTO applied_migrations (id, applied_at) VALUES (?, ?)').run(migration.id, Date.now())
|
||||
db.run('COMMIT')
|
||||
logger.info(`Migration ${migration.version} applied successfully`)
|
||||
logger.info(`Migration ${migration.id} applied successfully`)
|
||||
} catch (error) {
|
||||
db.run('ROLLBACK')
|
||||
logger.error(`Migration ${migration.version} failed:`, error)
|
||||
logger.error(`Migration ${migration.id} failed:`, error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -86,4 +59,47 @@ export function migrate(db: Database, migrations: Migration[]): void {
|
||||
logger.info('All migrations applied successfully')
|
||||
}
|
||||
|
||||
function assertUniqueIds(migrations: Migration[]): void {
|
||||
const seen = new Set<string>()
|
||||
for (const migration of migrations) {
|
||||
if (seen.has(migration.id)) throw new Error(`Duplicate migration id "${migration.id}"`)
|
||||
seen.add(migration.id)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records numbered migrations that a database applied under the old version-keyed table.
|
||||
* A version recorded under a different name is still treated as applied, as before, but warned
|
||||
* about because its schema change may be missing.
|
||||
*/
|
||||
function adoptLegacyMigrations(db: Database, migrations: Migration[]): void {
|
||||
const hasLegacyTable = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'").get()
|
||||
if (!hasLegacyTable) return
|
||||
|
||||
const records = new Map(
|
||||
(db.prepare('SELECT version, name, applied_at FROM schema_migrations').all() as LegacyMigrationRecord[])
|
||||
.map((record) => [record.version, record] as const),
|
||||
)
|
||||
const adopted = migrations.flatMap((migration) => {
|
||||
const record = migration.legacy ? records.get(migration.legacy.version) : undefined
|
||||
if (!migration.legacy || !record) return []
|
||||
if (record.name !== migration.legacy.name) {
|
||||
logger.warn(
|
||||
`Migration version ${migration.legacy.version} is recorded as "${record.name}" but the code defines "${migration.legacy.name}". ` +
|
||||
`This migration was skipped; its schema changes may be missing. Verify the database schema and apply the changes manually if needed.`,
|
||||
)
|
||||
}
|
||||
return [{ id: migration.id, appliedAt: record.applied_at }]
|
||||
})
|
||||
if (adopted.length === 0) return
|
||||
|
||||
const insert = db.prepare('INSERT OR IGNORE INTO applied_migrations (id, applied_at) VALUES (?, ?)')
|
||||
db.run('BEGIN TRANSACTION')
|
||||
try {
|
||||
adopted.forEach((entry) => insert.run(entry.id, entry.appliedAt))
|
||||
db.run('COMMIT')
|
||||
} catch (error) {
|
||||
db.run('ROLLBACK')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 1,
|
||||
name: 'base-schema',
|
||||
id: '001-base-schema',
|
||||
legacy: { version: 1, name: 'base-schema' },
|
||||
|
||||
up(db) {
|
||||
db.run(`
|
||||
|
||||
@@ -6,8 +6,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 2,
|
||||
name: 'repos-nullable-url',
|
||||
id: '002-repos-nullable-url',
|
||||
legacy: { version: 2, name: 'repos-nullable-url' },
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
|
||||
@@ -16,8 +16,8 @@ const COLUMNS = [
|
||||
]
|
||||
|
||||
const migration: Migration = {
|
||||
version: 3,
|
||||
name: 'repos-add-columns',
|
||||
id: '003-repos-add-columns',
|
||||
legacy: { version: 3, name: 'repos-add-columns' },
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 4,
|
||||
name: 'repos-indexes',
|
||||
id: '004-repos-indexes',
|
||||
legacy: { version: 4, name: 'repos-indexes' },
|
||||
|
||||
up(db) {
|
||||
db.run(`
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 5,
|
||||
name: 'repos-local-path-prefix',
|
||||
id: '005-repos-local-path-prefix',
|
||||
legacy: { version: 5, name: 'repos-local-path-prefix' },
|
||||
|
||||
up(db) {
|
||||
const repos = db.prepare("SELECT id, local_path FROM repos WHERE local_path LIKE 'repos/%'").all() as Array<{
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 6,
|
||||
name: 'git-token-to-credentials',
|
||||
id: '006-git-token-to-credentials',
|
||||
legacy: { version: 6, name: 'git-token-to-credentials' },
|
||||
|
||||
up(db) {
|
||||
const rows = db.prepare('SELECT user_id, preferences FROM user_preferences').all() as Array<{
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 7,
|
||||
name: 'schedules',
|
||||
id: '007-schedules',
|
||||
legacy: { version: 7, name: 'schedules' },
|
||||
|
||||
up(db) {
|
||||
db.run(`
|
||||
|
||||
@@ -7,8 +7,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 8,
|
||||
name: 'schedule-cron-support',
|
||||
id: '008-schedule-cron-support',
|
||||
legacy: { version: 8, name: 'schedule-cron-support' },
|
||||
|
||||
up(db) {
|
||||
const tableExists = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='schedule_jobs'").get()
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 10,
|
||||
name: '010-prompt-templates',
|
||||
id: '009-prompt-templates',
|
||||
legacy: { version: 10, name: '010-prompt-templates' },
|
||||
|
||||
up(db) {
|
||||
db.run(`
|
||||
|
||||
@@ -5,8 +5,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 9,
|
||||
name: 'repo-source-path',
|
||||
id: '009-repo-source-path',
|
||||
legacy: { version: 9, name: 'repo-source-path' },
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
|
||||
@@ -5,8 +5,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 11,
|
||||
name: 'repo-last-accessed',
|
||||
id: '011-repo-last-accessed',
|
||||
legacy: { version: 11, name: 'repo-last-accessed' },
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 12,
|
||||
name: 'opencode-model-state',
|
||||
id: '012-opencode-model-state',
|
||||
legacy: { version: 12, name: 'opencode-model-state' },
|
||||
up(db) {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS opencode_model_state (
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 13,
|
||||
name: 'app-secrets',
|
||||
id: '013-app-secrets',
|
||||
legacy: { version: 13, name: 'app-secrets' },
|
||||
up(db) {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS app_secrets (
|
||||
|
||||
@@ -5,8 +5,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 14,
|
||||
name: 'repos-add-name',
|
||||
id: '014-repos-add-name',
|
||||
legacy: { version: 14, name: 'repos-add-name' },
|
||||
|
||||
up(db) {
|
||||
const tableInfo = db.prepare('PRAGMA table_info(repos)').all() as ColumnInfo[]
|
||||
|
||||
@@ -7,8 +7,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 15,
|
||||
name: 'schedule-worktree-isolation',
|
||||
id: '015-schedule-worktree-isolation',
|
||||
legacy: { version: 15, name: 'schedule-worktree-isolation' },
|
||||
|
||||
up(db) {
|
||||
const jobColumns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
|
||||
@@ -7,8 +7,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 16,
|
||||
name: 'schedule-permission-config',
|
||||
id: '016-schedule-permission-config',
|
||||
legacy: { version: 16, name: 'schedule-permission-config' },
|
||||
|
||||
up(db) {
|
||||
const cols = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
|
||||
@@ -7,8 +7,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 17,
|
||||
name: 'schedule-run-workspace-id',
|
||||
id: '017-schedule-run-workspace-id',
|
||||
legacy: { version: 17, name: 'schedule-run-workspace-id' },
|
||||
|
||||
up(db) {
|
||||
const cols = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
|
||||
import { ensureSessionPinsTable } from '../session-pins'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 18,
|
||||
name: 'session-pins',
|
||||
id: '018-session-pins',
|
||||
legacy: { version: 18, name: 'session-pins' },
|
||||
up(db) {
|
||||
ensureSessionPinsTable(db)
|
||||
},
|
||||
|
||||
@@ -45,8 +45,8 @@ function archiveConfigs(rows: Array<{ config_name: string; config_content: strin
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 19,
|
||||
name: 'drop-opencode-configs',
|
||||
id: '019-drop-opencode-configs',
|
||||
legacy: { version: 19, name: 'drop-opencode-configs' },
|
||||
|
||||
up(db) {
|
||||
const rows = db.prepare('SELECT config_name, config_content, is_default FROM opencode_configs').all() as Array<{ config_name: string; config_content: string; is_default: number | null }>
|
||||
|
||||
@@ -49,8 +49,8 @@ function restoreModelStateFile(row: ModelStateRow): void {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 20,
|
||||
name: 'drop-opencode-model-state',
|
||||
id: '020-drop-opencode-model-state',
|
||||
legacy: { version: 20, name: 'drop-opencode-model-state' },
|
||||
|
||||
up(db) {
|
||||
const row = readDefaultRow(db)
|
||||
|
||||
@@ -5,8 +5,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 21,
|
||||
name: 'drop-schedule-run-workspace-id',
|
||||
id: '021-drop-schedule-run-workspace-id',
|
||||
legacy: { version: 21, name: 'drop-schedule-run-workspace-id' },
|
||||
|
||||
up(db) {
|
||||
const cols = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 22,
|
||||
name: 'schedule-runs-session-index',
|
||||
id: '022-schedule-runs-session-index',
|
||||
legacy: { version: 22, name: 'schedule-runs-session-index' },
|
||||
|
||||
up(db) {
|
||||
db.run(`
|
||||
|
||||
@@ -5,8 +5,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 23,
|
||||
name: 'schedule-mcp-servers',
|
||||
id: '023-schedule-mcp-servers',
|
||||
legacy: { version: 23, name: 'schedule-mcp-servers' },
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
|
||||
@@ -5,8 +5,8 @@ interface ColumnInfo {
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
version: 24,
|
||||
name: 'schedule-runs-viewed-at',
|
||||
id: '024-schedule-runs-viewed-at',
|
||||
legacy: { version: 24, name: 'schedule-runs-viewed-at' },
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
|
||||
import { ensureSessionPermissionModesTable } from '../session-permission-modes'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 25,
|
||||
name: 'session-permission-modes',
|
||||
id: '025-session-permission-modes',
|
||||
legacy: { version: 25, name: 'session-permission-modes' },
|
||||
up(db) {
|
||||
ensureSessionPermissionModesTable(db)
|
||||
},
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
|
||||
import { ensureSessionGoalsTable } from '../session-goals'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 26,
|
||||
name: 'session-goals',
|
||||
id: '026-session-goals',
|
||||
legacy: { version: 26, name: 'session-goals' },
|
||||
up(db) {
|
||||
ensureSessionGoalsTable(db)
|
||||
},
|
||||
|
||||
@@ -2,8 +2,8 @@ import type { Migration } from '../migration-runner'
|
||||
import { ensureMultiRunTables } from '../multi-runs'
|
||||
|
||||
const migration: Migration = {
|
||||
version: 27,
|
||||
name: 'multi-runs',
|
||||
id: '027-multi-runs',
|
||||
legacy: { version: 27, name: 'multi-runs' },
|
||||
up(db) {
|
||||
ensureMultiRunTables(db)
|
||||
},
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
interface ColumnInfo {
|
||||
name: string
|
||||
}
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610061345-schedule-workspace-mode',
|
||||
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(schedule_jobs)').all() as ColumnInfo[]
|
||||
if (!columns.some((column) => column.name === 'workspace_mode')) {
|
||||
db.run("ALTER TABLE schedule_jobs ADD COLUMN workspace_mode TEXT NOT NULL DEFAULT 'worktree'")
|
||||
}
|
||||
},
|
||||
|
||||
down(db) {
|
||||
db.run('ALTER TABLE schedule_jobs DROP COLUMN workspace_mode')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -26,6 +26,7 @@ import migration024 from './024-schedule-runs-viewed-at'
|
||||
import migration025 from './025-session-permission-modes'
|
||||
import migration026 from './026-session-goals'
|
||||
import migration027 from './027-multi-runs'
|
||||
import migration202610061345 from './202610061345-schedule-workspace-mode'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -55,4 +56,5 @@ export const allMigrations: Migration[] = [
|
||||
migration025,
|
||||
migration026,
|
||||
migration027,
|
||||
migration202610061345,
|
||||
]
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
type ScheduleRun,
|
||||
type ScheduleRunStatus,
|
||||
type ScheduleRunTriggerSource,
|
||||
type ScheduleWorkspaceMode,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_NAME, ASSISTANT_REPO_PATH, getRepoDisplayName } from '@opencode-manager/shared/utils'
|
||||
import type { ScheduleJobPersistenceInput } from '../services/schedule-config'
|
||||
@@ -33,6 +34,7 @@ interface ScheduleJobRow {
|
||||
permission_config: string | null
|
||||
mcp_servers: string | null
|
||||
branch: string | null
|
||||
workspace_mode: ScheduleWorkspaceMode | null
|
||||
created_at: number
|
||||
updated_at: number
|
||||
last_run_at: number | null
|
||||
@@ -118,6 +120,7 @@ function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob {
|
||||
permissionConfig: parsePermissionConfig(row.permission_config),
|
||||
mcpServers: parseMcpServers(row.mcp_servers),
|
||||
branch: row.branch,
|
||||
workspaceMode: row.workspace_mode ?? 'worktree',
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
lastRunAt: row.last_run_at,
|
||||
@@ -199,9 +202,10 @@ export function createScheduleJob(db: Database, repoId: number, input: ScheduleJ
|
||||
permission_config,
|
||||
mcp_servers,
|
||||
branch,
|
||||
workspace_mode,
|
||||
created_at, updated_at, last_run_at, next_run_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`)
|
||||
|
||||
const result = stmt.run(
|
||||
@@ -220,6 +224,7 @@ export function createScheduleJob(db: Database, repoId: number, input: ScheduleJ
|
||||
serializePermissionConfig(input.permissionConfig),
|
||||
serializeMcpServers(input.mcpServers),
|
||||
input.branch,
|
||||
input.workspaceMode,
|
||||
now,
|
||||
now,
|
||||
null,
|
||||
@@ -244,7 +249,7 @@ 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 = ?, updated_at = ?, next_run_at = ?
|
||||
agent_slug = ?, prompt = ?, model = ?, skill_metadata = ?, permission_config = ?, mcp_servers = ?, branch = ?, workspace_mode = ?, updated_at = ?, next_run_at = ?
|
||||
WHERE repo_id = ? AND id = ?
|
||||
`)
|
||||
|
||||
@@ -263,6 +268,7 @@ export function updateScheduleJob(db: Database, repoId: number, jobId: number, i
|
||||
serializePermissionConfig(input.permissionConfig),
|
||||
serializeMcpServers(input.mcpServers),
|
||||
input.branch,
|
||||
input.workspaceMode,
|
||||
now,
|
||||
input.nextRunAt,
|
||||
repoId,
|
||||
@@ -298,11 +304,15 @@ export function listScheduleRunArtifactsByJob(db: Database, repoId: number, jobI
|
||||
}))
|
||||
}
|
||||
|
||||
export function listActiveScheduleRunWorktreePaths(db: Database): string[] {
|
||||
const rows = db
|
||||
.prepare('SELECT worktree_path FROM schedule_runs WHERE worktree_path IS NOT NULL')
|
||||
.all() as { worktree_path: string }[]
|
||||
return rows.map((row) => row.worktree_path)
|
||||
export function getScheduleJobRepoId(db: Database, jobId: number): number | null {
|
||||
const row = db.prepare('SELECT repo_id FROM schedule_jobs WHERE id = ?').get(jobId) as { repo_id: number } | undefined
|
||||
return row?.repo_id ?? null
|
||||
}
|
||||
|
||||
export function clearScheduleRunWorktreePath(db: Database, repoId: number, jobId: number, worktreePath: string): number {
|
||||
return db
|
||||
.prepare('UPDATE schedule_runs SET worktree_path = NULL WHERE repo_id = ? AND job_id = ? AND worktree_path = ?')
|
||||
.run(repoId, jobId, worktreePath).changes
|
||||
}
|
||||
|
||||
export function deleteScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): boolean {
|
||||
|
||||
@@ -243,9 +243,9 @@ const terminalService = new TerminalService(
|
||||
() => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
|
||||
)
|
||||
const projectConfigService = new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService)
|
||||
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService)
|
||||
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
|
||||
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager)
|
||||
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService, scheduleService)
|
||||
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
|
||||
|
||||
const notificationService = new NotificationService(db)
|
||||
|
||||
@@ -53,7 +53,7 @@ function createTestApp(
|
||||
prepareRepoDelete: () => {},
|
||||
} as any
|
||||
const projectConfigService = new ProjectConfigService(db, createGitService(stubGitAuthService), stubGitAuthService)
|
||||
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, stubGitAuthService, projectConfigService, terminalService)
|
||||
const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, stubGitAuthService, projectConfigService, terminalService, scheduleService)
|
||||
app.route('/repos', createRepoRoutes(db, stubGitAuthService, scheduleService, openCodeClient, terminalService, projectConfigService, repoWorkspaces))
|
||||
return app
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from 'zod'
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { DeleteRepoResult, Repo } from '@opencode-manager/shared/types'
|
||||
import { DiscoverReposRequestSchema, AssistantModeInitRequestSchema, UpdateRepoRequestSchema, DeleteRepoRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { DiscoverReposRequestSchema, AssistantModeInitRequestSchema, UpdateRepoRequestSchema, CreateRepoWorkspaceRequestSchema, DeleteRepoRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { listRepos, getRepoById, updateLastAccessed, getRepoGitCredentialId, setRepoGitCredentialId, updateRepoName } from '../db/queries'
|
||||
import * as repoService from '../services/repo'
|
||||
import * as archiveService from '../services/archive'
|
||||
@@ -358,8 +358,13 @@ app.get('/', async (c) => {
|
||||
const repo = getRepoById(database, id)
|
||||
if (!repo || repo.cloneStatus !== 'ready') return c.json({ error: 'Repo not found' }, 404)
|
||||
|
||||
const parsed = CreateRepoWorkspaceRequestSchema.safeParse(await c.req.json().catch(() => ({})))
|
||||
if (!parsed.success) {
|
||||
return c.json({ error: parsed.error.issues[0]?.message ?? 'Invalid request' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
return c.json(await repoWorkspaces.create(repo))
|
||||
return c.json(await repoWorkspaces.create(repo, { name: parsed.data.name || undefined }))
|
||||
} catch (error: unknown) {
|
||||
if (isWorktreeError(error)) {
|
||||
return c.json({ error: error.data.message }, 409)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Hono } from 'hono'
|
||||
import {
|
||||
CreateScheduleJobRequestSchema,
|
||||
RemoveScheduleWorktreesRequestSchema,
|
||||
UpdateScheduleJobRequestSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { ScheduleService, ScheduleServiceError } from '../services/schedules'
|
||||
@@ -152,17 +153,40 @@ export function createScheduleRoutes(scheduleService: ScheduleService) {
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:jobId', (c) => {
|
||||
app.delete('/:jobId', async (c) => {
|
||||
try {
|
||||
const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError)
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
scheduleService.deleteJob(repoId, jobId)
|
||||
await scheduleService.deleteJob(repoId, jobId)
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to delete schedule', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:jobId/worktrees', (c) => {
|
||||
try {
|
||||
const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError)
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
return c.json({ worktrees: scheduleService.listWorktrees(repoId, jobId) })
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to list schedule worktrees', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/:jobId/worktrees', async (c) => {
|
||||
try {
|
||||
const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError)
|
||||
const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError)
|
||||
const body = await c.req.json().catch(() => ({}))
|
||||
const input = RemoveScheduleWorktreesRequestSchema.parse(body)
|
||||
const result = await scheduleService.removeWorktrees(repoId, jobId, input.worktreePath)
|
||||
return c.json(result)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to remove schedule worktrees', ScheduleServiceError)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/:jobId/run', async (c) => {
|
||||
try {
|
||||
const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError)
|
||||
|
||||
@@ -400,6 +400,8 @@ Create a new schedule job.
|
||||
|
||||
Body matches \`CreateScheduleJobRequest\` schema (discriminated union with \`scheduleMode: 'interval' | 'cron'\`).
|
||||
|
||||
Optional \`workspaceMode\` sets where runs execute: \`worktree\` (default, a fresh worktree removed after each run), \`kept-worktree\` (a fresh worktree kept after each run), \`shared-worktree\` (one worktree and branch reused by every run), or \`repo\` (the repository checkout itself). Kept and shared worktrees are listed with \`GET /repos/:repoId/schedules/:jobId/worktrees\` and removed with \`DELETE /repos/:repoId/schedules/:jobId/worktrees\` (optional body \`{ "worktreePath": "..." }\`; omit it to remove every idle worktree). Pending changes are committed to the worktree's branch before removal.
|
||||
|
||||
\`\`\`json
|
||||
{
|
||||
"action": "request",
|
||||
|
||||
@@ -6,7 +6,7 @@ import { getRepoById, getRepoByDirectory, updateRepoBranch, listRepos } from '..
|
||||
import { updateScheduleJobsBranch } from '../../db/schedules'
|
||||
import { isSSHUrl, getBranchNameError } from '@opencode-manager/shared/utils'
|
||||
import { GitOperationError, isNoUpstreamError, parseGitError } from '../../utils/git-errors'
|
||||
import { resolveMainCheckoutPath } from '../repo'
|
||||
import { listGitWorktrees, resolveMainCheckoutPath } from '../repo'
|
||||
import { MAX_COMMIT_PROMPT_DIFF_CHARS, type CommitMessageContext } from './commit-message-prompt'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import type { DeleteBranchResult, GitOperationKind, GitOperationState, GitStashEntry, IntegrateBranchRequest, IntegrateBranchResult, StashPushRequest } from '@opencode-manager/shared'
|
||||
@@ -1058,30 +1058,8 @@ export class GitService {
|
||||
)
|
||||
}
|
||||
|
||||
private async listWorktreeCheckouts(repoPath: string, env: Record<string, string> | undefined): Promise<Array<{ path: string; branch: string | null }>> {
|
||||
try {
|
||||
const output = await executeCommand(['git', '-C', repoPath, 'worktree', 'list', '--porcelain'], { env, silent: true })
|
||||
const checkouts: Array<{ path: string; branch: string | null }> = []
|
||||
let current: { path: string; branch: string | null } | null = null
|
||||
|
||||
for (const line of output.split('\n')) {
|
||||
if (line.startsWith('worktree ')) {
|
||||
if (current) checkouts.push(current)
|
||||
current = { path: line.slice('worktree '.length).trim(), branch: null }
|
||||
} else if (line.startsWith('branch refs/heads/') && current) {
|
||||
current.branch = line.slice('branch refs/heads/'.length).trim()
|
||||
}
|
||||
}
|
||||
if (current) checkouts.push(current)
|
||||
|
||||
return checkouts
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private async findCheckoutPath(repoPath: string, branch: string, env: Record<string, string> | undefined): Promise<string | null> {
|
||||
const checkouts = await this.listWorktreeCheckouts(repoPath, env)
|
||||
const checkouts = await listGitWorktrees(repoPath, env)
|
||||
return checkouts.find((checkout) => checkout.branch === branch)?.path ?? null
|
||||
}
|
||||
|
||||
|
||||
@@ -6,9 +6,12 @@ import type { GitAuthService } from './git-auth'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import type { ProjectConfigService } from './project-config'
|
||||
import type { TerminalService } from './terminal'
|
||||
import type { ScheduleService } from './schedules'
|
||||
import { findSiblingByDirectory, getSiblingRepos, RepoWorkspaceError, resolveRepoProjectId } from './repo'
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
|
||||
/** Single owner of OpenCode workspace lifecycle side effects: worktree setup on create and terminal cleanup on remove. */
|
||||
/** Single owner of repo worktree lifecycle side effects: worktree setup on create, and terminal cleanup plus owner-specific removal on remove. */
|
||||
export class RepoWorkspaceService {
|
||||
constructor(
|
||||
private readonly database: Database,
|
||||
@@ -16,6 +19,7 @@ export class RepoWorkspaceService {
|
||||
private readonly gitAuthService: GitAuthService,
|
||||
private readonly projectConfigService: ProjectConfigService,
|
||||
private readonly terminalService: TerminalService,
|
||||
private readonly scheduleWorktrees: Pick<ScheduleService, 'removeWorktrees'>,
|
||||
) {}
|
||||
|
||||
async create(repo: Repo, options: { name?: string; ref?: string } = {}) {
|
||||
@@ -29,11 +33,31 @@ export class RepoWorkspaceService {
|
||||
return { ...worktree, worktreeSetup }
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a worktree of the repo the way its owner expects: OpenCode worktrees through
|
||||
* OpenCode, schedule worktrees through the schedule (committing pending changes first),
|
||||
* and plain git worktrees with `git worktree remove`, which refuses uncommitted changes.
|
||||
*/
|
||||
async remove(repo: Repo, directory: string): Promise<void> {
|
||||
const worktree = findSiblingByDirectory(await this.listWorktreeSiblings(repo.id), directory)
|
||||
if (!worktree) throw new RepoWorkspaceError('Not a deletable worktree of this repo', 400)
|
||||
if (worktree.schedule?.inUse) throw new RepoWorkspaceError('This worktree is in use by a running scheduled run. Cancel the run first.', 400)
|
||||
|
||||
await this.removeTerminals(worktree.fullPath)
|
||||
|
||||
if (worktree.schedule) {
|
||||
await this.scheduleWorktrees.removeWorktrees(worktree.schedule.repoId, worktree.schedule.jobId, worktree.fullPath)
|
||||
return
|
||||
}
|
||||
|
||||
if (worktree.worktreeSource === 'git') {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'worktree', 'remove', worktree.fullPath], { env: this.gitAuthService.getGitEnvironment(true) })
|
||||
.catch((error: unknown) => {
|
||||
throw new RepoWorkspaceError(`Could not remove worktree: ${getErrorMessage(error)}`, 400)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const projectID = await resolveRepoProjectId(this.openCodeClient, repo.fullPath)
|
||||
await this.openCodeClient.api.worktree.remove({ projectID, directory: worktree.fullPath, force: true })
|
||||
}
|
||||
|
||||
+126
-53
@@ -7,7 +7,7 @@ import type { Database } from 'bun:sqlite'
|
||||
import type { Repo, CreateRepoInput } from '../types/repo'
|
||||
import { logger } from '../utils/logger'
|
||||
import { getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN, ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN, ASSISTANT_REPO_ID, type RepoWorktreeSchedule, type RepoWorktreeSource } from '@opencode-manager/shared/utils'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
import { isGitHubHttpsUrl } from '../utils/git-auth'
|
||||
import path from 'path'
|
||||
@@ -16,7 +16,8 @@ import { getErrorMessage } from '../utils/error-utils'
|
||||
import { sseAggregator } from './sse-aggregator'
|
||||
import { resolveProjectId, isGitMainCheckout } from './project-id-resolver'
|
||||
import { listRepos } from '../db/queries'
|
||||
import { listActiveScheduleRunWorktreePaths } from '../db/schedules'
|
||||
import { getScheduleJobRepoId, listRunningScheduleRuns } from '../db/schedules'
|
||||
import { parseScheduleWorktreeName } from './schedule-worktree-paths'
|
||||
import { SettingsService } from './settings'
|
||||
import { buildAssistantRepo } from './assistant-mode'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
@@ -1228,13 +1229,20 @@ export async function resolveRepoWorkingDirectory(
|
||||
return findSiblingByDirectory(await loadSiblings(), directory)?.fullPath ?? null
|
||||
}
|
||||
|
||||
export type RepoSibling = Repo & {
|
||||
currentBranch: string | undefined
|
||||
worktreeSource?: RepoWorktreeSource
|
||||
worktreeStrategy?: string
|
||||
schedule?: RepoWorktreeSchedule
|
||||
}
|
||||
|
||||
export async function getSiblingRepos(
|
||||
database: Database,
|
||||
repoId: number,
|
||||
gitEnv: Record<string, string>,
|
||||
openCodeClient?: OpenCodeClient,
|
||||
options: { includeBranch?: boolean } = {},
|
||||
): Promise<Array<Repo & { currentBranch: string | undefined; worktreeStrategy?: string }>> {
|
||||
): Promise<RepoSibling[]> {
|
||||
const settingsService = new SettingsService(database)
|
||||
const settings = settingsService.getSettings()
|
||||
const allRepos = listRepos(database, settings.preferences.repoOrder)
|
||||
@@ -1265,64 +1273,129 @@ export async function getSiblingRepos(
|
||||
})),
|
||||
)
|
||||
|
||||
if (!openCodeClient) return repoSiblings
|
||||
const [openCodeWorktrees, gitWorktrees] = await Promise.all([
|
||||
listOpenCodeWorktrees(openCodeClient, target.fullPath),
|
||||
listGitWorktrees(target.fullPath, gitEnv),
|
||||
])
|
||||
|
||||
try {
|
||||
const projectID = await resolveRepoProjectId(openCodeClient, target.fullPath)
|
||||
const worktrees = await openCodeClient.api.worktree.list({ projectID })
|
||||
const excludedDirectories = new Set([
|
||||
...repoSiblings.map((repo) => canonicalPathSync(path.resolve(repo.fullPath))),
|
||||
canonicalPathSync(path.resolve(getReposPath())),
|
||||
])
|
||||
const candidates = new Map<string, { directory: string; strategy?: string; branch?: string; inGit: boolean }>()
|
||||
openCodeWorktrees.forEach((worktree) => {
|
||||
const key = canonicalPathSync(path.resolve(worktree.directory))
|
||||
if (!excludedDirectories.has(key) && !candidates.has(key) && existsSync(worktree.directory)) {
|
||||
candidates.set(key, { directory: worktree.directory, strategy: worktree.strategy, inGit: false })
|
||||
}
|
||||
})
|
||||
gitWorktrees.slice(1).forEach((worktree) => {
|
||||
const key = canonicalPathSync(path.resolve(worktree.path))
|
||||
if (excludedDirectories.has(key)) return
|
||||
const existing = candidates.get(key)
|
||||
if (existing) {
|
||||
existing.branch = worktree.branch ?? undefined
|
||||
existing.inGit = true
|
||||
return
|
||||
}
|
||||
if (existsSync(worktree.path)) {
|
||||
candidates.set(key, { directory: worktree.path, branch: worktree.branch ?? undefined, inGit: true })
|
||||
}
|
||||
})
|
||||
|
||||
const knownDirectories = new Set(repoSiblings.map((repo) => canonicalPathSync(path.resolve(repo.fullPath))))
|
||||
const targetDirectory = canonicalPathSync(path.resolve(target.fullPath))
|
||||
const reposRoot = canonicalPathSync(path.resolve(getReposPath()))
|
||||
const scheduleWorktreeRoot = canonicalPathSync(path.resolve(getScheduleWorktreesPath()))
|
||||
const activeRunDirectories = new Set(
|
||||
listActiveScheduleRunWorktreePaths(database).map((p) => canonicalPathSync(path.resolve(p))),
|
||||
)
|
||||
const entries = Array.from(candidates.entries())
|
||||
const mainChecks = await Promise.all(
|
||||
entries.map(([, candidate]) => isGitMainCheckout(candidate.directory).catch(() => false)),
|
||||
)
|
||||
const describeSchedule = createScheduleWorktreeDescriber(database)
|
||||
|
||||
const candidates = worktrees.filter((worktree) => {
|
||||
const directory = canonicalPathSync(path.resolve(worktree.directory))
|
||||
if (directory === targetDirectory) return false
|
||||
if (directory === reposRoot) return false
|
||||
if (directory.startsWith(`${scheduleWorktreeRoot}${path.sep}`)) return false
|
||||
if (activeRunDirectories.has(directory)) return false
|
||||
if (knownDirectories.has(directory)) return false
|
||||
return true
|
||||
const worktreeSiblings = entries
|
||||
.filter((_, index) => !mainChecks[index])
|
||||
.map(([key, candidate]) => {
|
||||
const schedule = describeSchedule(key)
|
||||
const worktreeSource: RepoWorktreeSource | undefined = schedule
|
||||
? 'schedule'
|
||||
: candidate.strategy ? 'opencode' : candidate.inGit ? 'git' : undefined
|
||||
return {
|
||||
id: -1,
|
||||
repoUrl: target.repoUrl,
|
||||
localPath: path.basename(candidate.directory),
|
||||
fullPath: candidate.directory,
|
||||
sourcePath: candidate.directory,
|
||||
branch: candidate.branch,
|
||||
defaultBranch: target.defaultBranch,
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
isWorktree: true,
|
||||
isLocal: true,
|
||||
currentBranch: candidate.branch,
|
||||
worktreeSource,
|
||||
worktreeStrategy: candidate.strategy,
|
||||
...(schedule ? { schedule } : {}),
|
||||
}
|
||||
})
|
||||
|
||||
const mainChecks = await Promise.all(
|
||||
candidates.map((worktree) => isGitMainCheckout(worktree.directory).catch(() => false)),
|
||||
)
|
||||
return [...repoSiblings, ...worktreeSiblings]
|
||||
}
|
||||
|
||||
const uniqueWorktrees = new Map<string, typeof candidates[number]>()
|
||||
candidates
|
||||
.filter((_, index) => !mainChecks[index])
|
||||
.forEach((worktree) => {
|
||||
const directory = canonicalPathSync(path.resolve(worktree.directory))
|
||||
if (!uniqueWorktrees.has(directory)) {
|
||||
uniqueWorktrees.set(directory, worktree)
|
||||
}
|
||||
})
|
||||
|
||||
const worktreeSiblings = Array.from(uniqueWorktrees.values()).map((worktree) => ({
|
||||
id: -1,
|
||||
repoUrl: target.repoUrl,
|
||||
localPath: path.basename(worktree.directory),
|
||||
fullPath: worktree.directory,
|
||||
sourcePath: worktree.directory,
|
||||
branch: undefined,
|
||||
defaultBranch: target.defaultBranch,
|
||||
cloneStatus: 'ready' as const,
|
||||
clonedAt: Date.now(),
|
||||
isWorktree: true,
|
||||
isLocal: true,
|
||||
currentBranch: undefined,
|
||||
worktreeStrategy: worktree.strategy,
|
||||
}))
|
||||
|
||||
return [...repoSiblings, ...worktreeSiblings]
|
||||
async function listOpenCodeWorktrees(openCodeClient: OpenCodeClient | undefined, directory: string) {
|
||||
if (!openCodeClient) return []
|
||||
try {
|
||||
const projectID = await resolveRepoProjectId(openCodeClient, directory)
|
||||
return await openCodeClient.api.worktree.list({ projectID })
|
||||
} catch (error) {
|
||||
logger.warn('Failed to list OpenCode worktrees:', error)
|
||||
return repoSiblings
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists a repository's git worktrees with their checked-out branch; the main worktree comes first.
|
||||
*/
|
||||
export async function listGitWorktrees(repoPath: string, env: Record<string, string> | undefined): Promise<Array<{ path: string; branch: string | null }>> {
|
||||
try {
|
||||
const output = await executeCommand(['git', '-C', repoPath, 'worktree', 'list', '--porcelain'], { env, silent: true })
|
||||
const checkouts: Array<{ path: string; branch: string | null }> = []
|
||||
let current: { path: string; branch: string | null } | null = null
|
||||
for (const line of output.split('\n')) {
|
||||
if (line.startsWith('worktree ')) {
|
||||
current = { path: line.slice('worktree '.length).trim(), branch: null }
|
||||
checkouts.push(current)
|
||||
} else if (line.startsWith('branch refs/heads/') && current) {
|
||||
current.branch = line.slice('branch refs/heads/'.length).trim()
|
||||
}
|
||||
}
|
||||
return checkouts
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a lookup that says which schedule, if any, owns a canonical worktree directory:
|
||||
* either a directory named for a schedule under the schedule worktree root, or the
|
||||
* worktree a running run works in. Directories of deleted schedules are not owned.
|
||||
*/
|
||||
function createScheduleWorktreeDescriber(database: Database): (directory: string) => RepoWorktreeSchedule | undefined {
|
||||
const scheduleRoot = canonicalPathSync(path.resolve(getScheduleWorktreesPath()))
|
||||
const runningRuns = listRunningScheduleRuns(database)
|
||||
const runningByDirectory = new Map(runningRuns.flatMap((run) => (
|
||||
run.worktreePath ? [[canonicalPathSync(path.resolve(run.worktreePath)), run] as const] : []
|
||||
)))
|
||||
|
||||
return (directory) => {
|
||||
const running = runningByDirectory.get(directory)
|
||||
const parsed = path.dirname(directory) === scheduleRoot ? parseScheduleWorktreeName(path.basename(directory)) : null
|
||||
const jobId = parsed?.jobId ?? running?.jobId
|
||||
if (jobId === undefined) return undefined
|
||||
const repoId = running?.repoId ?? getScheduleJobRepoId(database, jobId)
|
||||
if (repoId === null) return undefined
|
||||
return {
|
||||
repoId,
|
||||
jobId,
|
||||
runId: parsed ? parsed.runId : running?.id ?? null,
|
||||
inUse: running !== undefined || (parsed?.runId === null && runningRuns.some((run) => run.jobId === jobId)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
ScheduleMode,
|
||||
SchedulePermissionConfig,
|
||||
ScheduleSkillMetadata,
|
||||
ScheduleWorkspaceMode,
|
||||
UpdateScheduleJobRequest,
|
||||
} from '@opencode-manager/shared/types'
|
||||
|
||||
@@ -26,6 +27,7 @@ export interface ScheduleJobPersistenceInput {
|
||||
permissionConfig: SchedulePermissionConfig | null
|
||||
mcpServers: ScheduleMcpServer[]
|
||||
branch: string | null
|
||||
workspaceMode: ScheduleWorkspaceMode
|
||||
nextRunAt: number | null
|
||||
}
|
||||
|
||||
@@ -101,6 +103,7 @@ export function buildCreateSchedulePersistenceInput(input: CreateScheduleJobRequ
|
||||
model: input.model?.trim() || null,
|
||||
skillMetadata: input.skillMetadata,
|
||||
branch: input.branch?.trim() || null,
|
||||
workspaceMode: input.workspaceMode ?? 'worktree',
|
||||
}
|
||||
|
||||
const scheduleConfig = input.scheduleMode === 'cron'
|
||||
@@ -162,6 +165,7 @@ export function buildUpdatedSchedulePersistenceInput(
|
||||
permissionConfig: input.permissionConfig === undefined ? existing.permissionConfig : (input.permissionConfig ?? null),
|
||||
mcpServers: input.mcpServers ?? existing.mcpServers,
|
||||
branch: input.branch === undefined ? existing.branch : (input.branch?.trim() || null),
|
||||
workspaceMode: input.workspaceMode ?? existing.workspaceMode,
|
||||
nextRunAt,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import path from 'path'
|
||||
import { getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
|
||||
const SCHEDULE_WORKTREE_DIRECTORY = /^job-(\d+)-(?:run-(\d+)|shared)$/
|
||||
|
||||
export function getSharedScheduleWorktreePath(jobId: number): string {
|
||||
return path.join(getScheduleWorktreesPath(), `job-${jobId}-shared`)
|
||||
}
|
||||
|
||||
export function getRunScheduleWorktreePath(jobId: number, runId: number): string {
|
||||
return path.join(getScheduleWorktreesPath(), `job-${jobId}-run-${runId}`)
|
||||
}
|
||||
|
||||
export function getSharedScheduleBranch(jobId: number): string {
|
||||
return `schedule/${jobId}/shared`
|
||||
}
|
||||
|
||||
export function getRunScheduleBranch(jobId: number, runId: number): string {
|
||||
return `schedule/${jobId}/run-${runId}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the job and run a schedule worktree directory name belongs to. `runId` is null
|
||||
* for a schedule's shared worktree; non-schedule names return null.
|
||||
*/
|
||||
export function parseScheduleWorktreeName(name: string): { jobId: number; runId: number | null } | null {
|
||||
const match = SCHEDULE_WORKTREE_DIRECTORY.exec(name)
|
||||
if (!match) return null
|
||||
return { jobId: Number(match[1]), runId: match[2] ? Number(match[2]) : null }
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { existsSync, readdirSync } from 'node:fs'
|
||||
import path from 'path'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import type { ScheduleWorkspaceMode } from '@opencode-manager/shared/types'
|
||||
import type { Repo } from '../types/repo'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
import { isSSHUrl } from '@opencode-manager/shared/utils'
|
||||
@@ -10,6 +11,13 @@ import { executeCommand } from '../utils/process'
|
||||
import { resolveDefaultBranch, createWorktreeSafely, removeWorktree } from './repo'
|
||||
import { logger } from '../utils/logger'
|
||||
import { mkdirSyncSafe } from '../utils/fs-safe'
|
||||
import {
|
||||
getRunScheduleBranch,
|
||||
getRunScheduleWorktreePath,
|
||||
getSharedScheduleBranch,
|
||||
getSharedScheduleWorktreePath,
|
||||
parseScheduleWorktreeName,
|
||||
} from './schedule-worktree-paths'
|
||||
|
||||
export interface ScheduleWorktreeContext {
|
||||
directory: string
|
||||
@@ -17,6 +25,20 @@ export interface ScheduleWorktreeContext {
|
||||
runBranch: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A schedule worktree directory found on disk. `runId` is null for a schedule's shared worktree.
|
||||
*/
|
||||
export interface ScheduleWorktreeEntry {
|
||||
jobId: number
|
||||
runId: number | null
|
||||
worktreePath: string
|
||||
branch: string
|
||||
}
|
||||
|
||||
function isSharedWorktreePath(worktreePath: string): boolean {
|
||||
return path.basename(worktreePath).endsWith('-shared')
|
||||
}
|
||||
|
||||
/**
|
||||
* Build repo-context environment variables used by the GIT_ASKPASS handler
|
||||
* to resolve repo-specific credentials. Mirrors GitService.getEnvironmentForRepo.
|
||||
@@ -34,12 +56,17 @@ export class ScheduleWorktreeManager {
|
||||
private readonly db: Database,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Prepares the directory a run works in. Returns null when the run works in the
|
||||
* repository checkout itself. A shared worktree that already exists is reused as-is;
|
||||
* otherwise a worktree is created, continuing the shared branch when it already exists.
|
||||
*/
|
||||
async prepare(
|
||||
repo: Repo,
|
||||
job: { id: number; branch: string | null },
|
||||
job: { id: number; branch: string | null; workspaceMode: ScheduleWorkspaceMode },
|
||||
runId: number,
|
||||
): Promise<ScheduleWorktreeContext | null> {
|
||||
if (repo.id === ASSISTANT_REPO_ID) return null
|
||||
if (repo.id === ASSISTANT_REPO_ID || job.workspaceMode === 'repo') return null
|
||||
|
||||
try {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'rev-parse', '--is-inside-work-tree'], { silent: true })
|
||||
@@ -47,6 +74,10 @@ export class ScheduleWorktreeManager {
|
||||
return null
|
||||
}
|
||||
|
||||
const shared = job.workspaceMode === 'shared-worktree'
|
||||
const runBranch = shared ? getSharedScheduleBranch(job.id) : getRunScheduleBranch(job.id, runId)
|
||||
const worktreePath = shared ? getSharedScheduleWorktreePath(job.id) : getRunScheduleWorktreePath(job.id, runId)
|
||||
|
||||
let sshSetup = false
|
||||
if (repo.repoUrl && isSSHUrl(repo.repoUrl)) {
|
||||
await this.gitAuthService.setupSSHForRepoUrl(repo.repoUrl, this.db)
|
||||
@@ -56,6 +87,10 @@ export class ScheduleWorktreeManager {
|
||||
try {
|
||||
const env = await this.buildGitEnv(repo, sshSetup, true)
|
||||
|
||||
if (shared && await this.isUsableWorktree(worktreePath, env)) {
|
||||
return { directory: worktreePath, worktreePath, runBranch }
|
||||
}
|
||||
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'fetch', '--prune', 'origin'], { env }).catch(() => {})
|
||||
|
||||
const base = job.branch?.trim() || (await resolveDefaultBranch(repo.fullPath, env))
|
||||
@@ -64,9 +99,10 @@ export class ScheduleWorktreeManager {
|
||||
throw new Error(`Base branch "${base}" was not found in this repository. Choose an existing branch in the schedule settings.`)
|
||||
}
|
||||
|
||||
const runBranch = `schedule/${job.id}/run-${runId}`
|
||||
if (existsSync(worktreePath)) {
|
||||
await removeWorktree(repo.fullPath, worktreePath, env)
|
||||
}
|
||||
|
||||
const worktreePath = path.join(getScheduleWorktreesPath(), `job-${job.id}-run-${runId}`)
|
||||
mkdirSyncSafe(path.dirname(worktreePath))
|
||||
await createWorktreeSafely(repo.fullPath, worktreePath, runBranch, env, baseRef)
|
||||
|
||||
@@ -82,15 +118,21 @@ export class ScheduleWorktreeManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits a finished run's changes to its branch. A `worktree` run's worktree is then
|
||||
* removed, along with its branch when nothing was committed. Kept and shared worktrees
|
||||
* stay on disk on their branch so the work can be continued.
|
||||
*/
|
||||
async finalize(
|
||||
repo: Repo,
|
||||
job: { id: number; name: string; prompt: string },
|
||||
job: { id: number; name: string; prompt: string; workspaceMode: ScheduleWorkspaceMode },
|
||||
run: { id: number; worktreePath: string | null; runBranch: string | null; triggerSource: string },
|
||||
): Promise<{ commitHash: string | null }> {
|
||||
if (!run.worktreePath) {
|
||||
return { commitHash: null }
|
||||
}
|
||||
|
||||
const retain = isSharedWorktreePath(run.worktreePath) || job.workspaceMode === 'kept-worktree'
|
||||
let sshSetup = false
|
||||
let env: Record<string, string> | undefined
|
||||
let commitHash: string | null = null
|
||||
@@ -103,33 +145,31 @@ export class ScheduleWorktreeManager {
|
||||
|
||||
env = await this.buildGitEnv(repo, sshSetup, false)
|
||||
|
||||
const status = await executeCommand(['git', '-C', run.worktreePath, 'status', '--porcelain'], { env }).catch(() => '')
|
||||
const promptSummary = job.prompt.length > 200 ? `${job.prompt.slice(0, 200)}...` : job.prompt
|
||||
commitHash = await this.commitPendingChanges(
|
||||
run.worktreePath,
|
||||
env,
|
||||
`Scheduled run: ${job.name} (run #${run.id})`,
|
||||
`Trigger: ${run.triggerSource}\nPrompt: ${promptSummary}`,
|
||||
)
|
||||
|
||||
if (status.trim()) {
|
||||
await executeCommand(['git', '-C', run.worktreePath, 'add', '-A'], { env })
|
||||
|
||||
const title = `Scheduled run: ${job.name} (run #${run.id})`
|
||||
const promptSummary = job.prompt.length > 200 ? `${job.prompt.slice(0, 200)}...` : job.prompt
|
||||
const body = `Trigger: ${run.triggerSource}\nPrompt: ${promptSummary}`
|
||||
await executeCommand(['git', '-C', run.worktreePath, 'commit', '-m', title, '-m', body], { env })
|
||||
|
||||
commitHash = (await executeCommand(['git', '-C', run.worktreePath, 'rev-parse', 'HEAD'], { env })).trim()
|
||||
if (!retain) {
|
||||
await executeCommand(['git', '-C', run.worktreePath, 'checkout', '--detach'], { env }).catch(() => {})
|
||||
}
|
||||
|
||||
// Detach HEAD to protect the run branch from accidental pushes
|
||||
await executeCommand(['git', '-C', run.worktreePath, 'checkout', '--detach'], { env }).catch(() => {})
|
||||
|
||||
return { commitHash }
|
||||
} catch (error) {
|
||||
logger.error(`Failed to finalize schedule run ${run.id} in worktree ${run.worktreePath}:`, error)
|
||||
throw error
|
||||
} finally {
|
||||
await removeWorktree(repo.fullPath, run.worktreePath, env).catch((error) => {
|
||||
logger.error(`Failed to remove worktree ${run.worktreePath}:`, error)
|
||||
})
|
||||
if (!retain) {
|
||||
await removeWorktree(repo.fullPath, run.worktreePath, env).catch((error) => {
|
||||
logger.error(`Failed to remove worktree ${run.worktreePath}:`, error)
|
||||
})
|
||||
|
||||
if (run.runBranch && !commitHash) {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', run.runBranch], env ? { env } : undefined).catch(() => undefined)
|
||||
if (run.runBranch && !commitHash) {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', run.runBranch], env ? { env } : undefined).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
|
||||
if (sshSetup) {
|
||||
@@ -138,33 +178,102 @@ export class ScheduleWorktreeManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a kept or shared worktree. Uncommitted changes are committed to its branch
|
||||
* first and the branch is kept, so no work is lost; if that commit fails the worktree
|
||||
* is left in place.
|
||||
*/
|
||||
async releaseWorktree(repo: Repo, job: { name: string }, worktreePath: string): Promise<void> {
|
||||
const env = await this.buildGitEnv(repo, false, true)
|
||||
|
||||
if (existsSync(worktreePath)) {
|
||||
await this.commitPendingChanges(worktreePath, env, `Schedule worktree removed: ${job.name}`, 'Uncommitted changes saved before the worktree was removed.')
|
||||
}
|
||||
|
||||
await removeWorktree(repo.fullPath, worktreePath, env)
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the schedule worktree directories on disk, optionally for a single job.
|
||||
*/
|
||||
listWorktrees(jobId?: number): ScheduleWorktreeEntry[] {
|
||||
let names: string[]
|
||||
try {
|
||||
names = readdirSync(getScheduleWorktreesPath())
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
|
||||
return names.flatMap((name) => {
|
||||
const parsed = parseScheduleWorktreeName(name)
|
||||
if (!parsed || (jobId !== undefined && parsed.jobId !== jobId)) return []
|
||||
return [{
|
||||
jobId: parsed.jobId,
|
||||
runId: parsed.runId,
|
||||
worktreePath: path.join(getScheduleWorktreesPath(), name),
|
||||
branch: parsed.runId === null ? getSharedScheduleBranch(parsed.jobId) : getRunScheduleBranch(parsed.jobId, parsed.runId),
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes leftover worktrees and deletes the run branches for a set of
|
||||
* finished runs. Used when clearing run history. Branch and worktree removal
|
||||
* are local git operations, so no SSH setup is needed; failures are swallowed
|
||||
* per artifact so one bad entry does not block the rest.
|
||||
* finished runs. Used when clearing run history. The job's shared worktree and
|
||||
* branch are never touched, since they belong to the schedule rather than a run.
|
||||
* Branch and worktree removal are local git operations, so no SSH setup is needed;
|
||||
* failures are swallowed per artifact so one bad entry does not block the rest.
|
||||
*/
|
||||
async pruneRunArtifacts(
|
||||
repo: Repo,
|
||||
jobId: number,
|
||||
artifacts: { runBranch: string | null; worktreePath: string | null }[],
|
||||
): Promise<void> {
|
||||
if (artifacts.length === 0) return
|
||||
const sharedPath = getSharedScheduleWorktreePath(jobId)
|
||||
const sharedBranch = getSharedScheduleBranch(jobId)
|
||||
const worktreePaths = artifacts
|
||||
.map((a) => a.worktreePath)
|
||||
.filter((p): p is string => p !== null && p !== sharedPath)
|
||||
const branches = artifacts
|
||||
.map((a) => a.runBranch)
|
||||
.filter((b): b is string => b !== null && b.length > 0 && b !== sharedBranch)
|
||||
|
||||
if (worktreePaths.length === 0 && branches.length === 0) return
|
||||
|
||||
const env = await this.buildGitEnv(repo, false, true)
|
||||
|
||||
await Promise.all(
|
||||
artifacts.map(async (artifact) => {
|
||||
if (!artifact.worktreePath) return
|
||||
await removeWorktree(repo.fullPath, artifact.worktreePath, env).catch(() => undefined)
|
||||
}),
|
||||
worktreePaths.map((worktreePath) => removeWorktree(repo.fullPath, worktreePath, env).catch(() => undefined)),
|
||||
)
|
||||
|
||||
const branches = artifacts.map((a) => a.runBranch).filter((b): b is string => b !== null && b.length > 0)
|
||||
if (branches.length > 0) {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', ...branches], { env }).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
private async commitPendingChanges(
|
||||
worktreePath: string,
|
||||
env: Record<string, string>,
|
||||
title: string,
|
||||
body: string,
|
||||
): Promise<string | null> {
|
||||
const status = await executeCommand(['git', '-C', worktreePath, 'status', '--porcelain'], { env }).catch(() => '')
|
||||
if (!status.trim()) return null
|
||||
|
||||
await executeCommand(['git', '-C', worktreePath, 'add', '-A'], { env })
|
||||
await executeCommand(['git', '-C', worktreePath, 'commit', '-m', title, '-m', body], { env })
|
||||
return (await executeCommand(['git', '-C', worktreePath, 'rev-parse', 'HEAD'], { env })).trim()
|
||||
}
|
||||
|
||||
private async isUsableWorktree(worktreePath: string, env: Record<string, string>): Promise<boolean> {
|
||||
if (!existsSync(path.join(worktreePath, '.git'))) return false
|
||||
try {
|
||||
await executeCommand(['git', '-C', worktreePath, 'rev-parse', '--is-inside-work-tree'], { env, silent: true })
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a user-supplied base branch name to a verified git ref, preferring
|
||||
* the remote-tracking branch for freshness. Returns null when neither the
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import path from 'path'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { Cron } from 'croner'
|
||||
import {
|
||||
@@ -5,6 +7,7 @@ import {
|
||||
type ScheduleJob,
|
||||
type ScheduleRun,
|
||||
type ScheduleRunTriggerSource,
|
||||
type ScheduleWorktree,
|
||||
type UpdateScheduleJobRequest,
|
||||
} from '@opencode-manager/shared/types'
|
||||
import { mcpStatusByName, openCodeLocation } from '@opencode-manager/shared/opencode'
|
||||
@@ -13,6 +16,7 @@ import { getRepoById } from '../db/queries'
|
||||
import type { ScheduleJobWithRepo } from '../db/schedules'
|
||||
import {
|
||||
cleanupOrphanedSchedules,
|
||||
clearScheduleRunWorktreePath,
|
||||
createScheduleJob,
|
||||
createScheduleRun,
|
||||
deleteScheduleJob,
|
||||
@@ -53,6 +57,7 @@ import type { Repo } from '../types/repo'
|
||||
import { sseAggregator, type ScheduledSessionRef } from './sse-aggregator'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { logger } from '../utils/logger'
|
||||
import { canonicalPathSync } from '../utils/fs-safe'
|
||||
import { buildAssistantRepo } from './assistant-mode'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
|
||||
@@ -319,8 +324,72 @@ export class ScheduleService {
|
||||
return listEnabledScheduleJobs(this.db)
|
||||
}
|
||||
|
||||
listAllJobsWithRepos(): ScheduleJobWithRepo[] {
|
||||
return listAllScheduleJobsWithRepos(this.db)
|
||||
listAllJobsWithRepos(): Array<ScheduleJobWithRepo & { retainedWorktreeCount: number }> {
|
||||
const runningPaths = this.listRunningWorktreePaths()
|
||||
const counts = new Map<number, number>()
|
||||
for (const entry of this.worktreeManager.listWorktrees()) {
|
||||
if (runningPaths.has(entry.worktreePath)) continue
|
||||
counts.set(entry.jobId, (counts.get(entry.jobId) ?? 0) + 1)
|
||||
}
|
||||
return listAllScheduleJobsWithRepos(this.db).map((job) => ({ ...job, retainedWorktreeCount: counts.get(job.id) ?? 0 }))
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the worktrees of a schedule that still exist on disk: kept run worktrees,
|
||||
* the shared worktree, and the worktree of a run in progress.
|
||||
*/
|
||||
listWorktrees(repoId: number, jobId: number): ScheduleWorktree[] {
|
||||
this.assertJob(repoId, jobId)
|
||||
const runningPaths = this.listRunningWorktreePaths()
|
||||
const jobRunning = ScheduleService.activeRuns.has(jobId) || getRunningScheduleRunByJob(this.db, repoId, jobId) !== null
|
||||
|
||||
return this.worktreeManager.listWorktrees(jobId)
|
||||
.map((entry) => ({
|
||||
worktreePath: entry.worktreePath,
|
||||
branch: entry.branch,
|
||||
runId: entry.runId,
|
||||
inUse: runningPaths.has(entry.worktreePath) || (entry.runId === null && jobRunning),
|
||||
}))
|
||||
.sort((left, right) => (right.runId ?? Number.MAX_SAFE_INTEGER) - (left.runId ?? Number.MAX_SAFE_INTEGER))
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes one of a schedule's worktrees, or every worktree not in use when no path is
|
||||
* given. Pending changes are committed to each worktree's branch first and branches are
|
||||
* kept, so a shared schedule continues from its branch on the next run.
|
||||
*/
|
||||
async removeWorktrees(repoId: number, jobId: number, worktreePath?: string): Promise<{ removed: number }> {
|
||||
const repo = this.assertRepo(repoId)
|
||||
const job = this.assertJob(repoId, jobId)
|
||||
const worktrees = this.listWorktrees(repoId, jobId)
|
||||
|
||||
let targets = worktrees.filter((worktree) => !worktree.inUse)
|
||||
if (worktreePath !== undefined) {
|
||||
const requestedPath = canonicalPathSync(path.resolve(worktreePath))
|
||||
const target = worktrees.find((worktree) => canonicalPathSync(worktree.worktreePath) === requestedPath)
|
||||
if (!target) {
|
||||
throw new ScheduleServiceError('Worktree not found for this schedule', 404)
|
||||
}
|
||||
if (target.inUse) {
|
||||
throw new ScheduleServiceError('This worktree is in use by a running run. Cancel the run first.', 409)
|
||||
}
|
||||
targets = [target]
|
||||
}
|
||||
|
||||
for (const target of targets) {
|
||||
try {
|
||||
await this.worktreeManager.releaseWorktree(repo, job, target.worktreePath)
|
||||
} catch (error) {
|
||||
throw new ScheduleServiceError(`Failed to remove worktree ${target.worktreePath}: ${getErrorMessage(error)}`, 500)
|
||||
}
|
||||
clearScheduleRunWorktreePath(this.db, repoId, jobId, target.worktreePath)
|
||||
}
|
||||
|
||||
return { removed: targets.length }
|
||||
}
|
||||
|
||||
private listRunningWorktreePaths(): Set<string> {
|
||||
return new Set(listRunningScheduleRuns(this.db).flatMap((run) => (run.worktreePath ? [run.worktreePath] : [])))
|
||||
}
|
||||
|
||||
listAllRuns(options: ListAllRunsOptions = {}): ScheduleRunWithContext[] {
|
||||
@@ -406,7 +475,7 @@ export class ScheduleService {
|
||||
return job
|
||||
}
|
||||
|
||||
deleteJob(repoId: number, jobId: number): void {
|
||||
async deleteJob(repoId: number, jobId: number): Promise<void> {
|
||||
this.assertRepo(repoId)
|
||||
this.assertJob(repoId, jobId)
|
||||
|
||||
@@ -419,6 +488,8 @@ export class ScheduleService {
|
||||
throw new ScheduleServiceError('Cannot delete a schedule while it is running. Cancel the run first.', 409)
|
||||
}
|
||||
|
||||
await this.removeWorktrees(repoId, jobId)
|
||||
|
||||
const deleted = deleteScheduleJob(this.db, repoId, jobId)
|
||||
if (!deleted) {
|
||||
throw new ScheduleServiceError('Schedule not found', 404)
|
||||
@@ -483,7 +554,7 @@ export class ScheduleService {
|
||||
return { cleared: 0 }
|
||||
}
|
||||
|
||||
await this.worktreeManager.pruneRunArtifacts(repo, removable)
|
||||
await this.worktreeManager.pruneRunArtifacts(repo, jobId, removable)
|
||||
const cleared = deleteScheduleRunsByIds(this.db, repoId, jobId, removable.map((run) => run.id))
|
||||
return { cleared }
|
||||
}
|
||||
@@ -501,7 +572,7 @@ export class ScheduleService {
|
||||
throw new ScheduleServiceError('Cannot delete a run while it is in progress. Cancel it first.', 409)
|
||||
}
|
||||
|
||||
await this.worktreeManager.pruneRunArtifacts(repo, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }])
|
||||
await this.worktreeManager.pruneRunArtifacts(repo, jobId, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }])
|
||||
const deleted = deleteScheduleRunById(this.db, repoId, jobId, runId)
|
||||
if (!deleted) {
|
||||
throw new ScheduleServiceError('Run not found', 404)
|
||||
@@ -1109,17 +1180,19 @@ export class ScheduleService {
|
||||
try {
|
||||
const fresh = getScheduleRunById(this.db, repoId, jobId, runId)
|
||||
if (!fresh?.worktreePath) return
|
||||
const worktreePath = fresh.worktreePath
|
||||
const remainingWorktreePath = () => (existsSync(worktreePath) ? worktreePath : null)
|
||||
try {
|
||||
const { commitHash } = await this.worktreeManager.finalize(repo, job, {
|
||||
id: runId,
|
||||
worktreePath: fresh.worktreePath,
|
||||
worktreePath,
|
||||
runBranch: fresh.runBranch,
|
||||
triggerSource: fresh.triggerSource,
|
||||
})
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null, commitHash })
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: remainingWorktreePath(), commitHash })
|
||||
} catch (error) {
|
||||
logger.error(`Failed to finalize worktree for run ${runId}:`, error)
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: null })
|
||||
updateScheduleRunWorktree(this.db, repoId, jobId, runId, { worktreePath: remainingWorktreePath() })
|
||||
}
|
||||
} finally {
|
||||
ScheduleService.activeTeardowns.delete(key)
|
||||
|
||||
@@ -1,26 +1,82 @@
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { migrate, type Migration } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import { logger } from '../../src/utils/logger'
|
||||
|
||||
function makeMigration(version: number, name: string, up: () => void): Migration {
|
||||
return { version, name, up, down: () => {} }
|
||||
function makeMigration(id: string, up: () => void = vi.fn(), legacy?: Migration['legacy']): Migration {
|
||||
return { id, legacy, up, down: () => {} }
|
||||
}
|
||||
|
||||
describe('migrate - version/name mismatch guard', () => {
|
||||
function createLegacyTable(db: Database, rows: Array<[number, string]>): void {
|
||||
db.run('CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)')
|
||||
rows.forEach(([version, name]) => {
|
||||
db.prepare('INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, 0)').run(version, name)
|
||||
})
|
||||
}
|
||||
|
||||
function appliedIds(db: Database): string[] {
|
||||
return (db.prepare('SELECT id FROM applied_migrations ORDER BY id').all() as Array<{ id: string }>).map((row) => row.id)
|
||||
}
|
||||
|
||||
describe('migrate', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('warns and skips when an applied version was recorded under a different name', () => {
|
||||
it('applies pending migrations in list order and records them by id', () => {
|
||||
const db = new Database(':memory:')
|
||||
db.run('CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)')
|
||||
db.run("INSERT INTO schema_migrations (version, name, applied_at) VALUES (15, 'repos-add-name', 0)")
|
||||
const order: string[] = []
|
||||
|
||||
migrate(db, [
|
||||
makeMigration('202610061345-second', () => order.push('second')),
|
||||
makeMigration('202610051200-first', () => order.push('first')),
|
||||
])
|
||||
|
||||
expect(order).toEqual(['second', 'first'])
|
||||
expect(appliedIds(db)).toEqual(['202610051200-first', '202610061345-second'])
|
||||
})
|
||||
|
||||
it('does not run a migration twice', () => {
|
||||
const db = new Database(':memory:')
|
||||
const up = vi.fn()
|
||||
|
||||
migrate(db, [makeMigration('202610061345-once', up)])
|
||||
migrate(db, [makeMigration('202610061345-once', up)])
|
||||
|
||||
expect(up).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('runs a migration whose old version number another branch already used', () => {
|
||||
const db = new Database(':memory:')
|
||||
createLegacyTable(db, [[28, 'remote-devices']])
|
||||
const up = vi.fn()
|
||||
|
||||
migrate(db, [makeMigration('202610061345-schedule-workspace-mode', up)])
|
||||
|
||||
expect(up).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('adopts numbered migrations recorded in the old version-keyed table', () => {
|
||||
const db = new Database(':memory:')
|
||||
createLegacyTable(db, [[15, 'schedule-worktree-isolation']])
|
||||
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
|
||||
const up = vi.fn()
|
||||
|
||||
migrate(db, [makeMigration(15, 'schedule-worktree-isolation', up)])
|
||||
migrate(db, [makeMigration('015-schedule-worktree-isolation', up, { version: 15, name: 'schedule-worktree-isolation' })])
|
||||
|
||||
expect(up).not.toHaveBeenCalled()
|
||||
expect(appliedIds(db)).toEqual(['015-schedule-worktree-isolation'])
|
||||
expect(warnSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('warns and skips when a legacy version was recorded under a different name', () => {
|
||||
const db = new Database(':memory:')
|
||||
createLegacyTable(db, [[15, 'repos-add-name']])
|
||||
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
|
||||
const up = vi.fn()
|
||||
|
||||
migrate(db, [makeMigration('015-schedule-worktree-isolation', up, { version: 15, name: 'schedule-worktree-isolation' })])
|
||||
|
||||
expect(up).not.toHaveBeenCalled()
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
@@ -28,26 +84,40 @@ describe('migrate - version/name mismatch guard', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('does not warn when recorded names match', () => {
|
||||
const db = new Database(':memory:')
|
||||
db.run('CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL)')
|
||||
db.run("INSERT INTO schema_migrations (version, name, applied_at) VALUES (15, 'schedule-worktree-isolation', 0)")
|
||||
|
||||
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {})
|
||||
|
||||
migrate(db, [makeMigration(15, 'schedule-worktree-isolation', vi.fn())])
|
||||
|
||||
expect(warnSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('applies pending migrations and records them', () => {
|
||||
it('rejects duplicate ids before touching the database', () => {
|
||||
const db = new Database(':memory:')
|
||||
const up = vi.fn()
|
||||
|
||||
migrate(db, [makeMigration(1, 'base', up)])
|
||||
expect(() => migrate(db, [makeMigration('202610061345-a', up), makeMigration('202610061345-a', up)])).toThrow('Duplicate migration id')
|
||||
expect(up).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
expect(up).toHaveBeenCalledTimes(1)
|
||||
const row = db.prepare('SELECT version, name FROM schema_migrations WHERE version = 1').get() as { version: number; name: string }
|
||||
expect(row).toEqual({ version: 1, name: 'base' })
|
||||
it('rolls back and stops when a migration fails', () => {
|
||||
const db = new Database(':memory:')
|
||||
vi.spyOn(logger, 'error').mockImplementation(() => {})
|
||||
const later = vi.fn()
|
||||
|
||||
expect(() => migrate(db, [
|
||||
makeMigration('202610061345-broken', () => {
|
||||
db.run('CREATE TABLE partial (id INTEGER)')
|
||||
throw new Error('boom')
|
||||
}),
|
||||
makeMigration('202610061346-later', later),
|
||||
])).toThrow('boom')
|
||||
|
||||
expect(later).not.toHaveBeenCalled()
|
||||
expect(appliedIds(db)).toEqual([])
|
||||
expect(db.prepare("SELECT name FROM sqlite_master WHERE name = 'partial'").get()).toBeFalsy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('allMigrations', () => {
|
||||
it('uses timestamp ids for every migration added after the numbered ones', () => {
|
||||
const unnumbered = allMigrations.filter((migration) => !migration.legacy)
|
||||
|
||||
expect(unnumbered.length).toBeGreaterThan(0)
|
||||
unnumbered.forEach((migration) => {
|
||||
expect(migration.id).toMatch(/^\d{12}-[a-z0-9]+(?:-[a-z0-9]+)*$/)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -22,7 +22,7 @@ const originalHome = process.env.HOME
|
||||
const originalImportConfigPath = process.env.OPENCODE_IMPORT_CONFIG_PATH
|
||||
|
||||
function migrateToV18(db: Database): void {
|
||||
migrate(db, allMigrations.filter(migration => migration.version < 19))
|
||||
migrate(db, allMigrations.filter(migration => (migration.legacy?.version ?? Infinity) < 19))
|
||||
}
|
||||
|
||||
function insertConfig(db: Database, name: string, content: string, isDefault: boolean): void {
|
||||
|
||||
@@ -23,7 +23,7 @@ interface ModelStateRow {
|
||||
}
|
||||
|
||||
function migrateToV19(db: Database): void {
|
||||
migrate(db, allMigrations.filter(migration => migration.version < 20))
|
||||
migrate(db, allMigrations.filter(migration => (migration.legacy?.version ?? Infinity) < 20))
|
||||
}
|
||||
|
||||
function insertRow(db: Database, state: ModelStateRow, updatedAt: number): void {
|
||||
|
||||
@@ -35,6 +35,7 @@ describe('schedule permission config persistence', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.now() + 3600000,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
@@ -116,6 +116,7 @@ describe('schedule database queries', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
})
|
||||
|
||||
@@ -135,6 +136,7 @@ describe('schedule database queries', () => {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
'worktree',
|
||||
expect.any(Number),
|
||||
expect.any(Number),
|
||||
null,
|
||||
@@ -174,6 +176,7 @@ describe('schedule database queries', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: null,
|
||||
})
|
||||
|
||||
@@ -192,6 +195,7 @@ describe('schedule database queries', () => {
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
'worktree',
|
||||
expect.any(Number),
|
||||
null,
|
||||
42,
|
||||
@@ -668,19 +672,12 @@ describe('schedule database queries', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('listActiveScheduleRunWorktreePaths returns only non-null worktree paths', () => {
|
||||
const stmt = {
|
||||
all: vi.fn().mockReturnValue([
|
||||
{ worktree_path: '/wt/2' },
|
||||
{ worktree_path: '/wt/9' },
|
||||
]),
|
||||
}
|
||||
it('getScheduleJobRepoId returns the owning repo or null for an unknown job', () => {
|
||||
const stmt = { get: vi.fn().mockReturnValueOnce({ repo_id: 42 }).mockReturnValueOnce(undefined) }
|
||||
mockDb.prepare.mockReturnValue(stmt)
|
||||
|
||||
const paths = schedulesDb.listActiveScheduleRunWorktreePaths(mockDb)
|
||||
|
||||
expect(mockDb.prepare).toHaveBeenCalledWith('SELECT worktree_path FROM schedule_runs WHERE worktree_path IS NOT NULL')
|
||||
expect(paths).toEqual(['/wt/2', '/wt/9'])
|
||||
expect(schedulesDb.getScheduleJobRepoId(mockDb, 7)).toBe(42)
|
||||
expect(schedulesDb.getScheduleJobRepoId(mockDb, 8)).toBeNull()
|
||||
})
|
||||
|
||||
it('deleteScheduleRunById deletes a single run row', () => {
|
||||
|
||||
@@ -21,9 +21,9 @@ describe('initializeDatabase', () => {
|
||||
it('creates the database file, applies migrations, and seeds defaults', async () => {
|
||||
const db = initializeDatabase(dbPath)
|
||||
|
||||
const migrations = db.prepare('SELECT name FROM schema_migrations ORDER BY version ASC').all() as Array<{ name: string }>
|
||||
expect(migrations.map(migration => migration.name)).toContain('base-schema')
|
||||
expect(migrations.map(migration => migration.name)).toContain('drop-opencode-configs')
|
||||
const migrations = db.prepare('SELECT id AS name FROM applied_migrations').all() as Array<{ name: string }>
|
||||
expect(migrations.map(migration => migration.name)).toContain('001-base-schema')
|
||||
expect(migrations.map(migration => migration.name)).toContain('019-drop-opencode-configs')
|
||||
|
||||
const preferences = db.prepare('SELECT preferences FROM user_preferences WHERE user_id = ?').get('default') as { preferences: string }
|
||||
expect(preferences.preferences).toBe('{}')
|
||||
|
||||
@@ -26,7 +26,7 @@ describe('internal-schedules routes', () => {
|
||||
db = new Database(':memory:')
|
||||
migrate(db, allMigrations)
|
||||
const openCodeClient = createOpenCodeClient()
|
||||
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }) } as unknown as ScheduleWorktreeManager
|
||||
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }), listWorktrees: () => [] } as unknown as ScheduleWorktreeManager
|
||||
scheduleService = new ScheduleService(db, openCodeClient, stubWorktreeManager)
|
||||
notificationService = new NotificationService(db)
|
||||
settingsService = new SettingsService(db)
|
||||
|
||||
@@ -110,7 +110,7 @@ const mockTerminalService = {
|
||||
|
||||
function createTestRoutes(openCodeClient: ReturnType<typeof createStubOpenCodeClient> = createStubOpenCodeClient()): ReturnType<typeof createRepoRoutes> {
|
||||
const projectConfigService = new ProjectConfigService(mockDb, createGitService(mockGitAuthService), mockGitAuthService)
|
||||
const repoWorkspaces = new RepoWorkspaceService(mockDb, openCodeClient, mockGitAuthService, projectConfigService, mockTerminalService)
|
||||
const repoWorkspaces = new RepoWorkspaceService(mockDb, openCodeClient, mockGitAuthService, projectConfigService, mockTerminalService, mockScheduleService)
|
||||
return createRepoRoutes(mockDb, mockGitAuthService, mockScheduleService, openCodeClient, mockTerminalService, projectConfigService, repoWorkspaces)
|
||||
}
|
||||
|
||||
@@ -505,6 +505,39 @@ describe('Repo Routes', () => {
|
||||
expect(await res.json()).toEqual({ directory: '/tmp/wrk-test', worktreeSetup: { status: 'none' } })
|
||||
})
|
||||
|
||||
it('passes a requested worktree name to OpenCode', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
|
||||
const client = createStubOpenCodeClient()
|
||||
const create = vi.fn(async () => ({ directory: '/tmp/feature-login' }))
|
||||
client.api.worktree.create = create as never
|
||||
|
||||
const res = await createTestRoutes(client).request('/1/workspaces', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: ' feature-login ' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(create).toHaveBeenCalledWith(expect.objectContaining({ name: 'feature-login' }))
|
||||
})
|
||||
|
||||
it('rejects a worktree name that is not a single folder name', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
|
||||
const client = createStubOpenCodeClient()
|
||||
const create = vi.fn(async () => ({ directory: '/tmp/x' }))
|
||||
client.api.worktree.create = create as never
|
||||
|
||||
const res = await createTestRoutes(client).request('/1/workspaces', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: '../escape' }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(await res.json()).toEqual({ error: 'Directory name cannot contain dot-dot path segments' })
|
||||
expect(create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 200 with a failed worktree setup when the setup terminal cannot start', async () => {
|
||||
vi.mocked(db.getRepoById).mockReturnValue(createMockRepo({ id: 1, fullPath: '/tmp/repos/test-repo' }))
|
||||
vi.mocked(db.getRepoSetting).mockImplementation((_database, _repoId, key) =>
|
||||
@@ -880,7 +913,7 @@ describe('Repo Routes', () => {
|
||||
vi.mocked(repoService.deleteRepoFiles).mockResolvedValue(undefined)
|
||||
vi.mocked(repoService.getSiblingRepos).mockResolvedValue([
|
||||
{ ...createMockRepo({ id: 2, fullPath: '/tmp/repos/manager-worktree', isWorktree: true }), currentBranch: undefined },
|
||||
{ ...createMockRepo({ id: -1, fullPath: '/tmp/plugin-workspace' }), currentBranch: undefined, worktreeStrategy: 'git' },
|
||||
{ ...createMockRepo({ id: -1, fullPath: '/tmp/plugin-workspace' }), currentBranch: undefined, worktreeStrategy: 'git', worktreeSource: 'opencode' },
|
||||
])
|
||||
|
||||
const app = createTestRoutes()
|
||||
|
||||
@@ -683,7 +683,7 @@ describe('assistant-mode end-to-end', () => {
|
||||
|
||||
const token = getOrCreateInternalToken(db)
|
||||
|
||||
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }) } as unknown as ScheduleWorktreeManager
|
||||
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }), listWorktrees: () => [] } as unknown as ScheduleWorktreeManager
|
||||
const scheduleService = new ScheduleService(db, createOpenCodeClient(), stubWorktreeManager)
|
||||
const notificationService = new NotificationService(db)
|
||||
const settingsService = new SettingsService(db)
|
||||
|
||||
@@ -43,6 +43,7 @@ function scheduleJobInput(name: string, branch: string): ScheduleJobPersistenceI
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
workspaceMode: 'worktree',
|
||||
branch,
|
||||
nextRunAt: null,
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createServer } from 'node:https'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
@@ -16,7 +16,6 @@ import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { Repo } from '../../src/types/repo'
|
||||
|
||||
type SiblingRepo = Repo & { currentBranch: string | undefined; worktreeStrategy?: string }
|
||||
|
||||
const workspaceRoot = mkdtempSync(path.join(tmpdir(), 'repo-git-'))
|
||||
process.env.WORKSPACE_PATH = workspaceRoot
|
||||
@@ -923,7 +922,7 @@ describe('repo service real git', () => {
|
||||
expect(siblings.every((repo) => repo.currentBranch === 'main')).toBe(true)
|
||||
})
|
||||
|
||||
it('adds filtered workspace siblings from the OpenCode client', async () => {
|
||||
it('lists OpenCode, schedule, and plain git worktrees as worktree siblings', async () => {
|
||||
const { getSiblingRepos } = await import('../../src/services/repo')
|
||||
const origin = path.join(workspaceRoot, uniqueName('sibling-ws-origin.git'))
|
||||
const work = path.join(workspaceRoot, uniqueName('sibling-ws-work'))
|
||||
@@ -953,15 +952,27 @@ describe('repo service real git', () => {
|
||||
const projectId = (await resolveOpenCodeProjectId(repoA))!
|
||||
const extraDir = path.join(workspaceRoot, uniqueName('sibling-ws-extra'))
|
||||
const duplicateDir = path.join(workspaceRoot, uniqueName('sibling-ws-duplicate'))
|
||||
const activeWorktree = path.join(workspaceRoot, uniqueName('sibling-ws-active'))
|
||||
const activeWorkspace = path.join(workspaceRoot, uniqueName('sibling-ws-active-dir'))
|
||||
const unownedDir = path.join(workspaceRoot, uniqueName('sibling-ws-unowned'))
|
||||
mkdirSync(extraDir, { recursive: true })
|
||||
mkdirSync(duplicateDir, { recursive: true })
|
||||
mkdirSync(activeWorktree, { recursive: true })
|
||||
mkdirSync(activeWorkspace, { recursive: true })
|
||||
const scheduleDir = path.join(getScheduleWorktreesPath(), uniqueName('sibling-ws-schedule'))
|
||||
db.prepare('INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at, worktree_path) VALUES (?, ?, ?, ?, ?, ?, ?)').run(1, a.id, 'manual', 'running', Date.now(), Date.now(), activeWorktree)
|
||||
db.prepare('INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at, worktree_path) VALUES (?, ?, ?, ?, ?, ?, ?)').run(1, a.id, 'manual', 'running', Date.now(), Date.now(), activeWorkspace)
|
||||
mkdirSync(unownedDir, { recursive: true })
|
||||
|
||||
const jobId = Number(db.prepare('INSERT INTO schedule_jobs (repo_id, name, prompt, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').run(a.id, 'nightly', 'check', Date.now(), Date.now()).lastInsertRowid)
|
||||
const keptDir = path.join(getScheduleWorktreesPath(), `job-${jobId}-run-3`)
|
||||
const sharedDir = path.join(getScheduleWorktreesPath(), `job-${jobId}-shared`)
|
||||
const orphanDir = path.join(getScheduleWorktreesPath(), 'job-999999-run-1')
|
||||
const manualDir = path.join(workspaceRoot, uniqueName('sibling-ws-manual'))
|
||||
mkdirSync(getScheduleWorktreesPath(), { recursive: true })
|
||||
git(['worktree', 'add', '-b', `schedule/${jobId}/run-3`, keptDir], repoA)
|
||||
git(['worktree', 'add', '-b', `schedule/${jobId}/shared`, sharedDir], repoA)
|
||||
git(['worktree', 'add', '-b', 'schedule/999999/run-1', orphanDir], repoA)
|
||||
git(['worktree', 'add', '-b', 'manual-work', manualDir], repoA)
|
||||
db.prepare('INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at, worktree_path) VALUES (?, ?, ?, ?, ?, ?, ?)').run(jobId, a.id, 'manual', 'running', Date.now(), Date.now(), sharedDir)
|
||||
const keptPath = realpathSync(keptDir)
|
||||
const sharedPath = realpathSync(sharedDir)
|
||||
const orphanPath = realpathSync(orphanDir)
|
||||
const manualPath = realpathSync(manualDir)
|
||||
|
||||
const client = {
|
||||
api: {
|
||||
location: {
|
||||
@@ -974,22 +985,25 @@ describe('repo service real git', () => {
|
||||
{ directory: duplicateDir, strategy: 'git' },
|
||||
{ directory: repoA, strategy: 'git' },
|
||||
{ directory: getReposPath(), strategy: 'git' },
|
||||
{ directory: scheduleDir, strategy: 'git' },
|
||||
{ directory: activeWorktree, strategy: 'git' },
|
||||
{ directory: activeWorkspace, strategy: 'git' },
|
||||
{ directory: unownedDir },
|
||||
],
|
||||
},
|
||||
},
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
const siblings = await getSiblingRepos(db, a.id, {}, client) as SiblingRepo[]
|
||||
const siblings = await getSiblingRepos(db, a.id, {}, client)
|
||||
const worktreeSiblings = siblings.filter((repo) => isWorktreeSibling(repo))
|
||||
const findSibling = (directory: string) => worktreeSiblings.find((repo) => repo.fullPath === directory)
|
||||
|
||||
expect(worktreeSiblings.map((repo) => repo.fullPath)).toEqual([extraDir, duplicateDir])
|
||||
expect(worktreeSiblings.every((repo) => repo.id === -1)).toBe(true)
|
||||
expect(worktreeSiblings.every((repo) => repo.localPath === path.basename(repo.fullPath))).toBe(true)
|
||||
expect(worktreeSiblings.every((repo) => repo.worktreeStrategy === 'git')).toBe(true)
|
||||
expect(worktreeSiblings.every((repo) => repo.branch === undefined && repo.currentBranch === undefined)).toBe(true)
|
||||
expect(worktreeSiblings.map((repo) => repo.fullPath).sort()).toEqual([extraDir, duplicateDir, keptPath, sharedPath, orphanPath, manualPath].sort())
|
||||
expect(siblings.some((repo) => repo.fullPath === unownedDir && repo.worktreeSource === undefined)).toBe(true)
|
||||
expect(worktreeSiblings.every((repo) => repo.id === -1 && repo.localPath === path.basename(repo.fullPath))).toBe(true)
|
||||
expect(findSibling(extraDir)).toMatchObject({ worktreeSource: 'opencode', worktreeStrategy: 'git', branch: undefined })
|
||||
expect(findSibling(keptPath)).toMatchObject({ worktreeSource: 'schedule', branch: `schedule/${jobId}/run-3`, schedule: { repoId: a.id, jobId, runId: 3, inUse: false } })
|
||||
expect(findSibling(sharedPath)).toMatchObject({ worktreeSource: 'schedule', schedule: { repoId: a.id, jobId, runId: null, inUse: true } })
|
||||
expect(findSibling(orphanPath)).toMatchObject({ worktreeSource: 'git', branch: 'schedule/999999/run-1' })
|
||||
expect(findSibling(orphanPath)?.schedule).toBeUndefined()
|
||||
expect(findSibling(manualPath)).toMatchObject({ worktreeSource: 'git', currentBranch: 'manual-work' })
|
||||
})
|
||||
|
||||
it('returns repo siblings when the OpenCode client fails', async () => {
|
||||
@@ -1021,7 +1035,7 @@ describe('repo service real git', () => {
|
||||
},
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
const siblings = await getSiblingRepos(db, a.id, {}, client) as SiblingRepo[]
|
||||
const siblings = await getSiblingRepos(db, a.id, {}, client)
|
||||
|
||||
expect(siblings.some((repo) => repo.id === a.id)).toBe(true)
|
||||
expect(siblings.some((repo) => isWorktreeSibling(repo))).toBe(false)
|
||||
|
||||
@@ -145,7 +145,7 @@ describe('getSiblingRepos branch resolution', () => {
|
||||
|
||||
expect(siblings).toHaveLength(1)
|
||||
expect(siblings[0]?.currentBranch).toBeUndefined()
|
||||
expect(executeCommand).not.toHaveBeenCalled()
|
||||
expect(executeCommand.mock.calls.map(([args]) => args)).toEqual([['git', '-C', repo.fullPath, 'worktree', 'list', '--porcelain']])
|
||||
})
|
||||
|
||||
it('resolves the branch when includeBranch is true', async () => {
|
||||
|
||||
@@ -69,6 +69,7 @@ function createService(overrides: {
|
||||
} as unknown as OpenCodeClient
|
||||
const projectConfigService = { runWorktreeSetupForRepo } as unknown as ProjectConfigService
|
||||
const terminalService = { removeAll } as unknown as TerminalService
|
||||
const removeScheduleWorktrees = vi.fn(async () => ({ removed: 1 }))
|
||||
|
||||
return {
|
||||
service: new RepoWorkspaceService(
|
||||
@@ -77,7 +78,9 @@ function createService(overrides: {
|
||||
gitAuthService,
|
||||
projectConfigService,
|
||||
terminalService,
|
||||
{ removeWorktrees: removeScheduleWorktrees },
|
||||
),
|
||||
removeScheduleWorktrees,
|
||||
worktreeCreate,
|
||||
worktreeRemove,
|
||||
runWorktreeSetupForRepo,
|
||||
@@ -128,7 +131,7 @@ describe('RepoWorkspaceService', () => {
|
||||
it('throws a 400 when the directory is not a worktree sibling and touches nothing', async () => {
|
||||
const worktreeRemove = vi.fn(async () => undefined)
|
||||
const removeAll = vi.fn(async () => undefined)
|
||||
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/other', worktreeStrategy: 'git' }])
|
||||
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/other', worktreeStrategy: 'git', worktreeSource: 'opencode' }])
|
||||
const { service } = createService({ worktreeRemove, removeAll })
|
||||
|
||||
const error = await service.remove(REPO, '/worktrees/unknown').catch((caught: unknown) => caught)
|
||||
@@ -142,7 +145,7 @@ describe('RepoWorkspaceService', () => {
|
||||
it('removes terminals for the matched sibling before removing the worktree', async () => {
|
||||
const worktreeRemove = vi.fn(async () => undefined)
|
||||
const removeAll = vi.fn(async () => undefined)
|
||||
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeStrategy: 'git' }])
|
||||
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeStrategy: 'git', worktreeSource: 'opencode' }])
|
||||
const { service } = createService({ worktreeRemove, removeAll })
|
||||
|
||||
await service.remove(REPO, '/worktrees/feature-x')
|
||||
@@ -161,7 +164,7 @@ describe('RepoWorkspaceService', () => {
|
||||
const removeAll = vi.fn(async () => {
|
||||
throw new Error('pty cleanup failed')
|
||||
})
|
||||
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeStrategy: 'git' }])
|
||||
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeStrategy: 'git', worktreeSource: 'opencode' }])
|
||||
const { service } = createService({ worktreeRemove, removeAll })
|
||||
|
||||
await expect(service.remove(REPO, '/worktrees/feature-x')).resolves.toBeUndefined()
|
||||
@@ -173,14 +176,54 @@ describe('RepoWorkspaceService', () => {
|
||||
force: true,
|
||||
})
|
||||
})
|
||||
it('removes a schedule worktree through its schedule instead of OpenCode', async () => {
|
||||
const worktreeRemove = vi.fn(async () => undefined)
|
||||
mocks.getSiblingRepos.mockResolvedValue([{
|
||||
fullPath: '/schedule-worktrees/job-7-shared',
|
||||
worktreeSource: 'schedule',
|
||||
schedule: { repoId: 3, jobId: 7, runId: null, inUse: false },
|
||||
}])
|
||||
const { service, removeScheduleWorktrees } = createService({ worktreeRemove })
|
||||
|
||||
await service.remove(REPO, '/schedule-worktrees/job-7-shared')
|
||||
|
||||
expect(removeScheduleWorktrees).toHaveBeenCalledWith(3, 7, '/schedule-worktrees/job-7-shared')
|
||||
expect(worktreeRemove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses to remove a schedule worktree a running run is using', async () => {
|
||||
const removeAll = vi.fn(async () => undefined)
|
||||
mocks.getSiblingRepos.mockResolvedValue([{
|
||||
fullPath: '/schedule-worktrees/job-7-run-2',
|
||||
worktreeSource: 'schedule',
|
||||
schedule: { repoId: 1, jobId: 7, runId: 2, inUse: true },
|
||||
}])
|
||||
const { service, removeScheduleWorktrees } = createService({ removeAll })
|
||||
|
||||
await expect(service.remove(REPO, '/schedule-worktrees/job-7-run-2')).rejects.toThrow('in use by a running scheduled run')
|
||||
expect(removeAll).not.toHaveBeenCalled()
|
||||
expect(removeScheduleWorktrees).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports a plain git worktree that git refuses to remove', async () => {
|
||||
const worktreeRemove = vi.fn(async () => undefined)
|
||||
mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/manual', worktreeSource: 'git' }])
|
||||
const { service } = createService({ worktreeRemove })
|
||||
|
||||
const error = await service.remove(REPO, '/worktrees/manual').catch((caught: unknown) => caught)
|
||||
|
||||
expect(error).toBeInstanceOf(RepoWorkspaceError)
|
||||
expect((error as Error).message).toMatch(/^Could not remove worktree/)
|
||||
expect(worktreeRemove).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('removeRepoTerminals', () => {
|
||||
it('removes terminals for the repo directory and each worktree sibling', async () => {
|
||||
const removeAll = vi.fn(async () => undefined)
|
||||
mocks.getSiblingRepos.mockResolvedValue([
|
||||
{ fullPath: '/worktrees/a', worktreeStrategy: 'git' },
|
||||
{ fullPath: '/worktrees/b', worktreeStrategy: 'git' },
|
||||
{ fullPath: '/worktrees/a', worktreeStrategy: 'git', worktreeSource: 'opencode' },
|
||||
{ fullPath: '/worktrees/b', worktreeStrategy: 'git', worktreeSource: 'opencode' },
|
||||
{ fullPath: '/repos/manager-worktree', isWorktree: true },
|
||||
])
|
||||
const { service } = createService({ removeAll })
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import path from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import { getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
|
||||
import { getReposPath } from '@opencode-manager/shared/config/env'
|
||||
import type { GitAuthService } from '../../src/services/git-auth'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import type { Repo } from '../../src/types/repo'
|
||||
import type { RepoSibling } from '../../src/services/repo'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
|
||||
@@ -30,6 +31,18 @@ const symlink = vi.fn()
|
||||
const readlink = vi.fn()
|
||||
const mkdirSafe = vi.fn()
|
||||
|
||||
const missingDirectories = new Set<string>()
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:fs')>()
|
||||
return {
|
||||
...actual,
|
||||
existsSync: (target: string) => (
|
||||
target.startsWith('/worktrees/') ? !missingDirectories.has(target) : actual.existsSync(target)
|
||||
),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('fs/promises', () => ({
|
||||
default: {
|
||||
lstat,
|
||||
@@ -447,7 +460,7 @@ describe('repo service', () => {
|
||||
})
|
||||
|
||||
describe('getSiblingRepos worktree API', () => {
|
||||
type SiblingRepo = Repo & { currentBranch: string | undefined; worktreeStrategy?: string }
|
||||
type SiblingRepo = RepoSibling
|
||||
|
||||
let db: Database
|
||||
|
||||
@@ -496,6 +509,20 @@ describe('getSiblingRepos worktree API', () => {
|
||||
|
||||
afterEach(() => {
|
||||
db.close()
|
||||
missingDirectories.clear()
|
||||
})
|
||||
|
||||
it('skips worktrees OpenCode still records but that no longer exist on disk', async () => {
|
||||
const { getSiblingRepos } = await import('../../src/services/repo')
|
||||
missingDirectories.add('/worktrees/removed-run')
|
||||
const client = createClient([
|
||||
{ directory: '/worktrees/removed-run', strategy: 'git' },
|
||||
{ directory: '/worktrees/feature-x', strategy: 'git' },
|
||||
])
|
||||
|
||||
const siblings = await getSiblingRepos(db, 1, {}, client)
|
||||
|
||||
expect(siblings.filter((sibling) => sibling.id === -1).map((sibling) => sibling.fullPath)).toEqual(['/worktrees/feature-x'])
|
||||
})
|
||||
|
||||
it('maps worktree entries to worktree siblings', async () => {
|
||||
@@ -515,17 +542,15 @@ describe('getSiblingRepos worktree API', () => {
|
||||
expect(siblings[1]?.currentBranch).toBeUndefined()
|
||||
})
|
||||
|
||||
it('excludes the target repo, repos root, schedule root, known siblings, and main checkouts', async () => {
|
||||
it('excludes the target repo, repos root, known siblings, and main checkouts', async () => {
|
||||
const { getSiblingRepos } = await import('../../src/services/repo')
|
||||
const repoA = path.join(getReposPath(), 'repo-a')
|
||||
const repoB = path.join(getReposPath(), 'repo-b')
|
||||
const scheduleDir = path.join(getScheduleWorktreesPath(), 'run-1')
|
||||
listRepos.mockReturnValue([createRepoRow(1, 'repo-a'), createRepoRow(2, 'repo-b')])
|
||||
isGitMainCheckout.mockImplementation(async (directory: string) => directory === '/worktrees/main-checkout')
|
||||
const client = createClient([
|
||||
{ directory: repoA, strategy: 'git' },
|
||||
{ directory: getReposPath(), strategy: 'git' },
|
||||
{ directory: scheduleDir, strategy: 'git' },
|
||||
{ directory: repoB, strategy: 'git' },
|
||||
{ directory: '/worktrees/main-checkout', strategy: 'git' },
|
||||
{ directory: '/worktrees/feature-x', strategy: 'git' },
|
||||
@@ -537,7 +562,7 @@ describe('getSiblingRepos worktree API', () => {
|
||||
expect(siblings.filter((sibling) => sibling.id === -1).map((sibling) => sibling.fullPath)).toEqual(['/worktrees/feature-x'])
|
||||
})
|
||||
|
||||
it('excludes an active schedule run worktree path', async () => {
|
||||
it('marks an active schedule run worktree as an in-use schedule worktree', async () => {
|
||||
const { getSiblingRepos } = await import('../../src/services/repo')
|
||||
const activePath = '/worktrees/active-run'
|
||||
db.prepare('INSERT INTO schedule_runs (job_id, repo_id, trigger_source, status, started_at, created_at, worktree_path) VALUES (?, ?, ?, ?, ?, ?, ?)').run(1, 1, 'manual', 'running', Date.now(), Date.now(), activePath)
|
||||
@@ -548,8 +573,9 @@ describe('getSiblingRepos worktree API', () => {
|
||||
|
||||
const siblings = await getSiblingRepos(db, 1, {}, client) as SiblingRepo[]
|
||||
|
||||
expect(siblings).toHaveLength(2)
|
||||
expect(siblings[1]?.fullPath).toBe('/worktrees/feature-x')
|
||||
expect(siblings).toHaveLength(3)
|
||||
expect(siblings[1]).toMatchObject({ fullPath: activePath, worktreeSource: 'schedule', schedule: { repoId: 1, jobId: 1, runId: 1, inUse: true } })
|
||||
expect(siblings[2]).toMatchObject({ fullPath: '/worktrees/feature-x', worktreeSource: 'opencode' })
|
||||
})
|
||||
|
||||
it('returns only repo siblings when the location lookup rejects', async () => {
|
||||
|
||||
@@ -36,6 +36,7 @@ describe('schedule-config', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: currentDate + 60 * 60_000,
|
||||
})
|
||||
})
|
||||
@@ -76,6 +77,7 @@ describe('schedule-config', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -108,6 +110,7 @@ describe('schedule-config', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -143,6 +146,7 @@ describe('schedule-config', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: 'feature/foo',
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -174,6 +178,7 @@ describe('schedule-config', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -205,6 +210,7 @@ describe('schedule-config', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: 'feature/foo',
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -236,6 +242,7 @@ describe('schedule-config', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -280,6 +287,7 @@ describe('schedule-config', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
|
||||
@@ -118,7 +118,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
it('prepare creates a worktree with the correct branch name and returns context', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 10, branch: null }
|
||||
const job = { id: 10, branch: null, workspaceMode: 'worktree' as const }
|
||||
const runId = 1
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
@@ -144,7 +144,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
it('prepare returns null for a non-git directory', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo({ fullPath: nonGitDir })
|
||||
const job = { id: 12, branch: null }
|
||||
const job = { id: 12, branch: null, workspaceMode: 'worktree' as const }
|
||||
|
||||
const ctx = await manager.prepare(repo, job, 1)
|
||||
expect(ctx).toBeNull()
|
||||
@@ -153,7 +153,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
it('prepare returns null for the assistant repo', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo({ id: 0 })
|
||||
const job = { id: 13, branch: null }
|
||||
const job = { id: 13, branch: null, workspaceMode: 'worktree' as const }
|
||||
|
||||
const ctx = await manager.prepare(repo, job, 1)
|
||||
expect(ctx).toBeNull()
|
||||
@@ -162,7 +162,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
it('finalize returns null commit when no changes exist and removes the worktree', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 10, branch: null, name: 'No-change job' }
|
||||
const job = { id: 10, branch: null, name: 'No-change job', workspaceMode: 'worktree' as const }
|
||||
const runId = 100
|
||||
|
||||
// Prepare a worktree first
|
||||
@@ -174,7 +174,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
// Finalize without making any changes
|
||||
const result = await manager.finalize(
|
||||
repo,
|
||||
{ id: 10, name: 'No-change job', prompt: '' },
|
||||
{ id: 10, name: 'No-change job', prompt: '', workspaceMode: 'worktree' as const },
|
||||
{ id: runId, worktreePath, runBranch: ctx!.runBranch, triggerSource: 'manual' },
|
||||
)
|
||||
|
||||
@@ -186,7 +186,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
it('finalize commits changes and returns the commit hash, then removes the worktree', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 10, branch: null, name: 'Change job' }
|
||||
const job = { id: 10, branch: null, name: 'Change job', workspaceMode: 'worktree' as const }
|
||||
const runId = 200
|
||||
|
||||
// Prepare a worktree
|
||||
@@ -201,7 +201,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
// Finalize - should commit and clean up
|
||||
const result = await manager.finalize(
|
||||
repo,
|
||||
{ id: 10, name: 'Change job', prompt: 'Generate a changelog' },
|
||||
{ id: 10, name: 'Change job', prompt: 'Generate a changelog', workspaceMode: 'worktree' as const },
|
||||
{ id: runId, worktreePath, runBranch: ctx!.runBranch, triggerSource: 'schedule' },
|
||||
)
|
||||
|
||||
@@ -226,7 +226,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
|
||||
const result = await manager.finalize(
|
||||
repo,
|
||||
{ id: 10, name: 'Job', prompt: '' },
|
||||
{ id: 10, name: 'Job', prompt: '', workspaceMode: 'worktree' as const },
|
||||
{ id: 1, worktreePath: null, runBranch: null, triggerSource: 'manual' },
|
||||
)
|
||||
|
||||
@@ -238,7 +238,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
const repo = testRepo()
|
||||
// A clearly nonexistent ref (avoids case-insensitive filesystem false matches
|
||||
// that would let a typo like "Main" resolve to "main" locally).
|
||||
const job = { id: 21, branch: 'does-not-exist-branch' }
|
||||
const job = { id: 21, branch: 'does-not-exist-branch', workspaceMode: 'worktree' as const }
|
||||
|
||||
await expect(manager.prepare(repo, job, 1)).rejects.toThrow(
|
||||
/Base branch "does-not-exist-branch" was not found/,
|
||||
@@ -251,7 +251,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
it('prepare respects the branch override', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 20, branch: 'dev' }
|
||||
const job = { id: 20, branch: 'dev', workspaceMode: 'worktree' as const }
|
||||
const runId = 1
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
@@ -277,7 +277,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
it('pruneRunArtifacts removes the worktree directory and deletes the run branch', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 90, branch: null }
|
||||
const job = { id: 90, branch: null, workspaceMode: 'worktree' as const }
|
||||
const runId = 900
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
@@ -287,7 +287,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
const runBranch = ctx!.runBranch
|
||||
expect(existsSync(worktreePath)).toBe(true)
|
||||
|
||||
await manager.pruneRunArtifacts(repo, [{ runBranch, worktreePath }])
|
||||
await manager.pruneRunArtifacts(repo, 90, [{ runBranch, worktreePath }])
|
||||
|
||||
expect(existsSync(worktreePath)).toBe(false)
|
||||
const branchList = execSync(`git -C "${baseRepoPath}" branch --list "${runBranch}"`, {
|
||||
@@ -295,4 +295,63 @@ describe('ScheduleWorktreeManager', () => {
|
||||
}).trim()
|
||||
expect(branchList).toBe('')
|
||||
})
|
||||
|
||||
it('prepare returns null in repo mode so the run works in the checkout', async () => {
|
||||
const manager = await createManager()
|
||||
const ctx = await manager.prepare(testRepo(), { id: 30, branch: null, workspaceMode: 'repo' }, 1)
|
||||
|
||||
expect(ctx).toBeNull()
|
||||
expect(manager.listWorktrees(30)).toEqual([])
|
||||
})
|
||||
|
||||
it('finalize commits but keeps the worktree on its branch in kept-worktree mode', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 31, branch: null, name: 'Kept job', prompt: 'keep', workspaceMode: 'kept-worktree' as const }
|
||||
|
||||
const ctx = await manager.prepare(repo, job, 1)
|
||||
writeFileSync(path.join(ctx!.worktreePath, 'kept.md'), 'kept')
|
||||
|
||||
const result = await manager.finalize(repo, job, { id: 1, worktreePath: ctx!.worktreePath, runBranch: ctx!.runBranch, triggerSource: 'manual' })
|
||||
|
||||
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
expect(execSync(`git -C "${ctx!.worktreePath}" rev-parse --abbrev-ref HEAD`, { encoding: 'utf-8' }).trim()).toBe('schedule/31/run-1')
|
||||
expect(manager.listWorktrees(31)).toEqual([
|
||||
{ jobId: 31, runId: 1, worktreePath: ctx!.worktreePath, branch: 'schedule/31/run-1' },
|
||||
])
|
||||
|
||||
await manager.releaseWorktree(repo, job, ctx!.worktreePath)
|
||||
})
|
||||
|
||||
it('reuses one shared worktree across runs and continues its branch after release', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 32, branch: null, name: 'Shared job', prompt: 'share', workspaceMode: 'shared-worktree' as const }
|
||||
const sharedPath = path.join(scheduleWorktreesRoot, 'job-32-shared')
|
||||
|
||||
const first = await manager.prepare(repo, job, 1)
|
||||
expect(first).toEqual({ directory: sharedPath, worktreePath: sharedPath, runBranch: 'schedule/32/shared' })
|
||||
writeFileSync(path.join(sharedPath, 'first.md'), 'first')
|
||||
await manager.finalize(repo, job, { id: 1, worktreePath: sharedPath, runBranch: 'schedule/32/shared', triggerSource: 'manual' })
|
||||
expect(existsSync(sharedPath)).toBe(true)
|
||||
|
||||
writeFileSync(path.join(sharedPath, 'uncommitted.md'), 'pending')
|
||||
const second = await manager.prepare(repo, job, 2)
|
||||
expect(second!.worktreePath).toBe(sharedPath)
|
||||
expect(existsSync(path.join(sharedPath, 'uncommitted.md'))).toBe(true)
|
||||
|
||||
await manager.releaseWorktree(repo, job, sharedPath)
|
||||
expect(existsSync(sharedPath)).toBe(false)
|
||||
|
||||
const third = await manager.prepare(repo, job, 3)
|
||||
expect(existsSync(path.join(third!.worktreePath, 'first.md'))).toBe(true)
|
||||
expect(existsSync(path.join(third!.worktreePath, 'uncommitted.md'))).toBe(true)
|
||||
|
||||
await manager.pruneRunArtifacts(repo, 32, [{ runBranch: 'schedule/32/shared', worktreePath: sharedPath }])
|
||||
expect(existsSync(sharedPath)).toBe(true)
|
||||
expect(execSync(`git -C "${baseRepoPath}" branch --list schedule/32/shared`, { encoding: 'utf-8' }).trim()).not.toBe('')
|
||||
|
||||
await manager.releaseWorktree(repo, job, sharedPath)
|
||||
})
|
||||
})
|
||||
@@ -123,6 +123,7 @@ const baseJob: ScheduleJob = {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
|
||||
@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({
|
||||
getScheduleRunById: vi.fn(),
|
||||
listEnabledScheduleJobs: vi.fn(),
|
||||
listRunningScheduleRuns: vi.fn(),
|
||||
clearScheduleRunWorktreePath: vi.fn(),
|
||||
listScheduleJobIdsByRepo: vi.fn(),
|
||||
listScheduleJobsByRepo: vi.fn(),
|
||||
listScheduleRunsByJob: vi.fn(),
|
||||
@@ -35,6 +36,8 @@ const mocks = vi.hoisted(() => ({
|
||||
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),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -55,6 +58,7 @@ vi.mock('../../src/db/schedules', () => ({
|
||||
getScheduleRunById: mocks.getScheduleRunById,
|
||||
listEnabledScheduleJobs: mocks.listEnabledScheduleJobs,
|
||||
listRunningScheduleRuns: mocks.listRunningScheduleRuns,
|
||||
clearScheduleRunWorktreePath: mocks.clearScheduleRunWorktreePath,
|
||||
listScheduleJobIdsByRepo: mocks.listScheduleJobIdsByRepo,
|
||||
listScheduleJobsByRepo: mocks.listScheduleJobsByRepo,
|
||||
listScheduleRunsByJob: mocks.listScheduleRunsByJob,
|
||||
@@ -146,6 +150,7 @@ const job: ScheduleJob = {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
@@ -910,31 +915,31 @@ describe('ScheduleService', () => {
|
||||
expect(stub.api.agent.list).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('throws when deleting or loading missing records', () => {
|
||||
it('throws when deleting or loading missing records', async () => {
|
||||
const stub = createStubScheduleApi()
|
||||
const service = makeService(stub.api)
|
||||
|
||||
mocks.deleteScheduleJob.mockReturnValue(false)
|
||||
mocks.getScheduleRunById.mockReturnValue(null)
|
||||
|
||||
expect(() => service.deleteJob(42, 7)).toThrow('Schedule not found')
|
||||
await expect(service.deleteJob(42, 7)).rejects.toThrow('Schedule not found')
|
||||
expect(() => service.getRun(42, 7, 5)).toThrow('Run not found')
|
||||
})
|
||||
|
||||
it('blocks deleteJob when a running run exists in activeRuns', () => {
|
||||
it('blocks deleteJob when a running run exists in activeRuns', async () => {
|
||||
const stub = createStubScheduleApi()
|
||||
const service = makeService(stub.api)
|
||||
Reflect.get(ScheduleService, 'activeRuns').set(7, { runId: 5, abort: new AbortController() })
|
||||
|
||||
expect(() => service.deleteJob(42, 7)).toThrow('Cannot delete a schedule while it is running. Cancel the run first.')
|
||||
await expect(service.deleteJob(42, 7)).rejects.toThrow('Cannot delete a schedule while it is running. Cancel the run first.')
|
||||
})
|
||||
|
||||
it('blocks deleteJob when a running run exists in the database', () => {
|
||||
it('blocks deleteJob when a running run exists in the database', async () => {
|
||||
const stub = createStubScheduleApi()
|
||||
const service = makeService(stub.api)
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue({ ...baseRun, status: 'running' })
|
||||
|
||||
expect(() => service.deleteJob(42, 7)).toThrow('Cannot delete a schedule while it is running. Cancel the run first.')
|
||||
await expect(service.deleteJob(42, 7)).rejects.toThrow('Cannot delete a schedule while it is running. Cancel the run first.')
|
||||
})
|
||||
|
||||
it('blocks prepareRepoDelete when a running run exists in activeRuns', () => {
|
||||
@@ -961,14 +966,14 @@ describe('ScheduleService', () => {
|
||||
expect(onJobChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('deleteJob succeeds when no runs are active', () => {
|
||||
it('deleteJob succeeds when no runs are active', async () => {
|
||||
const stub = createStubScheduleApi()
|
||||
const service = makeService(stub.api)
|
||||
mocks.deleteScheduleJob.mockReturnValue(true)
|
||||
const onJobChange = vi.fn()
|
||||
service.setJobChangeHandler(onJobChange)
|
||||
|
||||
service.deleteJob(42, 7)
|
||||
await service.deleteJob(42, 7)
|
||||
|
||||
expect(mocks.deleteScheduleJob).toHaveBeenCalledWith(expect.anything(), 42, 7)
|
||||
expect(onJobChange).toHaveBeenCalledWith(null, 7)
|
||||
@@ -2153,6 +2158,7 @@ describe('ScheduleRunner', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
@@ -2191,6 +2197,7 @@ describe('ScheduleRunner', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
@@ -2227,6 +2234,7 @@ describe('ScheduleRunner', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
@@ -2262,6 +2270,7 @@ describe('ScheduleRunner', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
@@ -2297,6 +2306,7 @@ describe('ScheduleRunner', () => {
|
||||
permissionConfig: null,
|
||||
mcpServers: [],
|
||||
branch: null,
|
||||
workspaceMode: 'worktree',
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
createdAt: Date.now(),
|
||||
@@ -2346,7 +2356,7 @@ describe('ScheduleService run history cleanup', () => {
|
||||
|
||||
const result = await makeService().clearRunHistory(42, 7)
|
||||
|
||||
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, [
|
||||
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, 7, [
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null },
|
||||
{ id: 1, status: 'failed', runBranch: null, worktreePath: null },
|
||||
])
|
||||
@@ -2372,12 +2382,45 @@ describe('ScheduleService run history cleanup', () => {
|
||||
|
||||
await makeService().deleteRun(42, 7, 5)
|
||||
|
||||
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, [
|
||||
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, 7, [
|
||||
{ runBranch: 'schedule/7/run-5', worktreePath: '/wt/5' },
|
||||
])
|
||||
expect(mocks.deleteScheduleRunById).toHaveBeenCalledWith({}, 42, 7, 5)
|
||||
})
|
||||
|
||||
it('listWorktrees marks the shared worktree and running run worktrees as in use', () => {
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([{ ...baseRun, status: 'running', worktreePath: '/wt/job-7-run-9' }])
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue({ ...baseRun, status: 'running' })
|
||||
mocks.stubWorktreeManager.listWorktrees.mockReturnValue([
|
||||
{ jobId: 7, runId: 3, worktreePath: '/wt/job-7-run-3', branch: 'schedule/7/run-3' },
|
||||
{ jobId: 7, runId: null, worktreePath: '/wt/job-7-shared', branch: 'schedule/7/shared' },
|
||||
{ jobId: 7, runId: 9, worktreePath: '/wt/job-7-run-9', branch: 'schedule/7/run-9' },
|
||||
])
|
||||
|
||||
expect(makeService().listWorktrees(42, 7)).toEqual([
|
||||
{ worktreePath: '/wt/job-7-shared', branch: 'schedule/7/shared', runId: null, inUse: true },
|
||||
{ worktreePath: '/wt/job-7-run-9', branch: 'schedule/7/run-9', runId: 9, inUse: true },
|
||||
{ worktreePath: '/wt/job-7-run-3', branch: 'schedule/7/run-3', runId: 3, inUse: false },
|
||||
])
|
||||
})
|
||||
|
||||
it('removeWorktrees releases idle worktrees and clears run references', async () => {
|
||||
mocks.listRunningScheduleRuns.mockReturnValue([{ ...baseRun, status: 'running', worktreePath: '/wt/job-7-run-9' }])
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue(null)
|
||||
mocks.stubWorktreeManager.listWorktrees.mockReturnValue([
|
||||
{ jobId: 7, runId: 3, worktreePath: '/wt/job-7-run-3', branch: 'schedule/7/run-3' },
|
||||
{ jobId: 7, runId: 9, worktreePath: '/wt/job-7-run-9', branch: 'schedule/7/run-9' },
|
||||
])
|
||||
|
||||
await expect(makeService().removeWorktrees(42, 7)).resolves.toEqual({ removed: 1 })
|
||||
expect(mocks.stubWorktreeManager.releaseWorktree).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.stubWorktreeManager.releaseWorktree).toHaveBeenCalledWith(repo, job, '/wt/job-7-run-3')
|
||||
expect(mocks.clearScheduleRunWorktreePath).toHaveBeenCalledWith({}, 42, 7, '/wt/job-7-run-3')
|
||||
|
||||
await expect(makeService().removeWorktrees(42, 7, '/wt/job-7-run-9')).rejects.toThrow('in use by a running run')
|
||||
await expect(makeService().removeWorktrees(42, 7, '/etc')).rejects.toThrow('Worktree not found')
|
||||
})
|
||||
|
||||
it('deleteRun refuses to delete a run in progress', async () => {
|
||||
mocks.getScheduleRunById.mockReturnValue({ ...baseRun, id: 5, status: 'running' })
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@ import type { Repo } from './types'
|
||||
import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { saveFile } from '@/lib/download'
|
||||
import type { DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity, WorktreeSetupResult } from '@opencode-manager/shared/types'
|
||||
import type { CreateRepoWorkspaceRequest, DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity, WorktreeSetupResult } from '@opencode-manager/shared/types'
|
||||
import type { RepoWorktreeSchedule, RepoWorktreeSource } from '@opencode-manager/shared/utils'
|
||||
|
||||
export interface CreateRepoOptions {
|
||||
repoUrl?: string
|
||||
@@ -40,11 +41,21 @@ export async function getRepo(id: number): Promise<Repo> {
|
||||
|
||||
export type RepoSibling = Repo & {
|
||||
currentBranch?: string
|
||||
worktreeSource?: RepoWorktreeSource
|
||||
worktreeStrategy?: string
|
||||
schedule?: RepoWorktreeSchedule
|
||||
}
|
||||
|
||||
export function workspaceLabel(workspace: RepoSibling): string {
|
||||
return workspace.currentBranch || workspace.branch || workspace.localPath || 'workspace'
|
||||
return workspace.currentBranch || workspace.branch || workspace.localPath || 'worktree'
|
||||
}
|
||||
|
||||
export function worktreeSourceLabel(worktree: RepoSibling): string | null {
|
||||
if (worktree.schedule) {
|
||||
return worktree.schedule.runId === null ? 'Schedule · shared' : `Schedule · run #${worktree.schedule.runId}`
|
||||
}
|
||||
if (worktree.worktreeSource === 'git') return 'Git'
|
||||
return worktree.worktreeSource === 'opencode' ? 'OpenCode' : null
|
||||
}
|
||||
|
||||
export interface RepoWorktree {
|
||||
@@ -63,9 +74,11 @@ export async function deleteRepoWorkspace(repoId: number, directory: string): Pr
|
||||
})
|
||||
}
|
||||
|
||||
export async function createRepoWorkspace(repoId: number): Promise<RepoWorktree & { worktreeSetup?: WorktreeSetupResult }> {
|
||||
export async function createRepoWorkspace(repoId: number, request: CreateRepoWorkspaceRequest = {}): Promise<RepoWorktree & { worktreeSetup?: WorktreeSetupResult }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/workspaces`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
ScheduleJob,
|
||||
ScheduleRun,
|
||||
ScheduleRunStatus,
|
||||
ScheduleWorktree,
|
||||
UpdateScheduleJobRequest,
|
||||
} from '@opencode-manager/shared/types'
|
||||
|
||||
@@ -22,6 +23,7 @@ export interface ScheduleJobWithRepo extends ScheduleJob {
|
||||
repoPath: string
|
||||
repoUrl: string
|
||||
lastRun: ScheduleRunSummary | null
|
||||
retainedWorktreeCount: number
|
||||
}
|
||||
|
||||
export interface ScheduleRunWithContext extends ScheduleRun {
|
||||
@@ -162,6 +164,18 @@ export async function clearRepoScheduleRuns(repoId: number, jobId: number): Prom
|
||||
})
|
||||
}
|
||||
|
||||
export async function listScheduleWorktrees(repoId: number, jobId: number): Promise<{ worktrees: ScheduleWorktree[] }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/worktrees`)
|
||||
}
|
||||
|
||||
export async function removeScheduleWorktrees(repoId: number, jobId: number, worktreePath?: string): Promise<{ removed: number }> {
|
||||
return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/worktrees`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(worktreePath ? { worktreePath } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteRepoScheduleRun(repoId: number, jobId: number, runId: number): Promise<void> {
|
||||
return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}`, {
|
||||
method: 'DELETE',
|
||||
|
||||
@@ -1,250 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { GitBranch, Plus, Search, Trash2 } from 'lucide-react'
|
||||
import { workspaceLabel, type RepoSibling } from '@/api/repos'
|
||||
|
||||
interface WorkspaceManagerProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
workspaces: RepoSibling[]
|
||||
onDelete: (directories: string[]) => void
|
||||
activeWorkspaceDirectory?: string
|
||||
onActiveWorkspaceChange: (directory: string) => void
|
||||
onCreateWorkspace: () => void
|
||||
isDeleting?: boolean
|
||||
}
|
||||
|
||||
export function WorkspaceManager({
|
||||
open,
|
||||
onOpenChange,
|
||||
workspaces,
|
||||
onDelete,
|
||||
activeWorkspaceDirectory,
|
||||
onActiveWorkspaceChange,
|
||||
onCreateWorkspace,
|
||||
isDeleting = false,
|
||||
}: WorkspaceManagerProps) {
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [manageMode, setManageMode] = useState(false)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setSearchQuery('')
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const filteredWorkspaces = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
if (!query) return workspaces
|
||||
|
||||
return workspaces.filter((workspace) => {
|
||||
const haystack = [
|
||||
workspaceLabel(workspace),
|
||||
workspace.fullPath,
|
||||
workspace.worktreeStrategy,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
return haystack.includes(query)
|
||||
})
|
||||
}, [searchQuery, workspaces])
|
||||
|
||||
const selectableDirectories = useMemo(
|
||||
() => filteredWorkspaces.map((workspace) => workspace.fullPath).filter((directory): directory is string => !!directory),
|
||||
[filteredWorkspaces],
|
||||
)
|
||||
|
||||
const allSelected = selectableDirectories.length > 0 && selectableDirectories.every((directory) => selected.has(directory))
|
||||
const selectedCount = selected.size
|
||||
|
||||
const toggle = (directory: string, checked: boolean) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (checked) {
|
||||
next.add(directory)
|
||||
} else {
|
||||
next.delete(directory)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const toggleAll = () => {
|
||||
setSelected(allSelected ? new Set() : new Set(selectableDirectories))
|
||||
}
|
||||
|
||||
const handleConfirm = () => {
|
||||
onDelete(Array.from(selected))
|
||||
setSelected(new Set())
|
||||
setManageMode(false)
|
||||
setConfirmOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent mobileFullscreen className="flex flex-col gap-0 overflow-hidden p-0 sm:max-h-[85vh] sm:max-w-[560px]">
|
||||
<DialogHeader className="border-b border-border px-4 py-4">
|
||||
<DialogTitle>Workspaces</DialogTitle>
|
||||
<DialogDescription>Choose where new sessions should start.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3 p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
{manageMode ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox checked={allSelected} onCheckedChange={toggleAll} aria-label="Select all workspaces" />
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{selectedCount > 0 ? `${selectedCount} selected` : 'Select all'}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{activeWorkspaceDirectory ? 'Selected workspace' : 'Select a workspace'}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7"
|
||||
onClick={() => {
|
||||
onOpenChange(false)
|
||||
onCreateWorkspace()
|
||||
}}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5 mr-1" />
|
||||
New
|
||||
</Button>
|
||||
{manageMode ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 text-destructive hover:text-destructive"
|
||||
disabled={selectedCount === 0 || isDeleting}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 mr-1" />
|
||||
Delete
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7"
|
||||
onClick={() => {
|
||||
setSelected(new Set())
|
||||
setManageMode(false)
|
||||
}}
|
||||
>
|
||||
Done
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7"
|
||||
onClick={() => setManageMode(true)}
|
||||
>
|
||||
Manage
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<input
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
placeholder="Search workspaces..."
|
||||
className="h-10 w-full rounded-md border border-border bg-background pl-9 pr-3 text-sm outline-none placeholder:text-muted-foreground focus:border-primary"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto pr-1">
|
||||
{filteredWorkspaces.map((workspace) => {
|
||||
if (!workspace.fullPath) return null
|
||||
const directory = workspace.fullPath
|
||||
const isChecked = selected.has(directory)
|
||||
const isActive = directory === activeWorkspaceDirectory
|
||||
const label = workspaceLabel(workspace)
|
||||
const rowClassName = isActive
|
||||
? 'border-primary/50 bg-primary/10 text-foreground'
|
||||
: 'border-border bg-muted/30 hover:bg-muted/50'
|
||||
if (!manageMode) {
|
||||
return (
|
||||
<button
|
||||
key={directory}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onActiveWorkspaceChange(directory)
|
||||
onOpenChange(false)
|
||||
}}
|
||||
className={`flex min-h-11 items-center gap-2 rounded-md border px-3 py-2 text-sm text-left ${rowClassName}`}
|
||||
aria-pressed={isActive}
|
||||
>
|
||||
<GitBranch className="h-3.5 w-3.5 text-primary flex-shrink-0" />
|
||||
<span className={isActive ? 'truncate text-highlight' : 'truncate'}>{label}</span>
|
||||
{isActive && <span className="text-xs text-highlight">Selected</span>}
|
||||
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
|
||||
{directory}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div
|
||||
key={directory}
|
||||
className="flex min-h-11 items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2 text-sm hover:bg-muted/50"
|
||||
>
|
||||
<Checkbox
|
||||
checked={isChecked}
|
||||
disabled={isDeleting}
|
||||
onCheckedChange={(checked) => toggle(directory, checked === true)}
|
||||
aria-label={`Select workspace ${directory}`}
|
||||
/>
|
||||
<GitBranch className="h-3.5 w-3.5 text-primary flex-shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
|
||||
{directory}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{filteredWorkspaces.length === 0 && (
|
||||
<div className="rounded-md border border-dashed border-border px-3 py-6 text-center text-sm text-muted-foreground">
|
||||
No workspaces found
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<DeleteDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
onConfirm={handleConfirm}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
title={selectedCount === 1 ? 'Delete Workspace' : 'Delete Workspaces'}
|
||||
description={
|
||||
selectedCount === 1
|
||||
? 'Are you sure you want to delete this OpenCode workspace? This removes the workspace and its sessions in OpenCode.'
|
||||
: `Are you sure you want to delete ${selectedCount} OpenCode workspaces? This removes the workspaces and their sessions in OpenCode.`
|
||||
}
|
||||
isDeleting={isDeleting}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { WorktreeSessionGroups } from './WorktreeSessionGroups'
|
||||
import type { RepoSibling } from '@/api/repos'
|
||||
import type { Session } from '@/api/types'
|
||||
|
||||
const makeWorktree = (overrides: Partial<RepoSibling> & Pick<RepoSibling, 'fullPath' | 'currentBranch' | 'worktreeSource'>): RepoSibling => ({
|
||||
id: -1,
|
||||
localPath: 'x',
|
||||
fullPath: overrides.fullPath,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 0,
|
||||
isWorktree: true,
|
||||
currentBranch: overrides.currentBranch,
|
||||
worktreeSource: overrides.worktreeSource,
|
||||
worktreeStrategy: 'git',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const featureWorktree = makeWorktree({
|
||||
fullPath: '/w/feature',
|
||||
currentBranch: 'feature/auth',
|
||||
worktreeSource: 'opencode',
|
||||
})
|
||||
|
||||
const sharedScheduleWorktree = makeWorktree({
|
||||
fullPath: '/s/job-14-shared',
|
||||
currentBranch: 'schedule/14/shared',
|
||||
worktreeSource: 'schedule',
|
||||
schedule: { repoId: 1, jobId: 14, runId: null, inUse: true },
|
||||
})
|
||||
|
||||
const runScheduleWorktree = makeWorktree({
|
||||
fullPath: '/s/job-14-run-340',
|
||||
currentBranch: 'schedule/14/run-340',
|
||||
worktreeSource: 'schedule',
|
||||
schedule: { repoId: 1, jobId: 14, runId: 340, inUse: false },
|
||||
})
|
||||
|
||||
const manualWorktree = makeWorktree({
|
||||
fullPath: '/w/manual',
|
||||
currentBranch: 'manual',
|
||||
worktreeSource: 'git',
|
||||
})
|
||||
|
||||
const allWorktrees = [featureWorktree, sharedScheduleWorktree, runScheduleWorktree, manualWorktree]
|
||||
|
||||
const makeSession = (id: string, title: string, directory: string): Session => ({
|
||||
id,
|
||||
title,
|
||||
parentID: undefined,
|
||||
location: { directory },
|
||||
time: { created: 0, updated: 0 },
|
||||
} as unknown as Session)
|
||||
|
||||
const featureSession = makeSession('ses_1', 'Auth work', '/w/feature')
|
||||
|
||||
const onNewSession = vi.fn()
|
||||
const onOpenTerminal = vi.fn()
|
||||
const onCreateWorktree = vi.fn()
|
||||
const onDelete = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
onNewSession.mockReset()
|
||||
onOpenTerminal.mockReset()
|
||||
onCreateWorktree.mockReset()
|
||||
onDelete.mockReset()
|
||||
})
|
||||
|
||||
function renderGroups(overrides: {
|
||||
worktrees?: RepoSibling[]
|
||||
sessions?: Session[]
|
||||
searchQuery?: string
|
||||
} = {}) {
|
||||
return render(
|
||||
<WorktreeSessionGroups
|
||||
repoId={1}
|
||||
worktrees={overrides.worktrees ?? allWorktrees}
|
||||
sessions={overrides.sessions ?? [featureSession]}
|
||||
searchQuery={overrides.searchQuery ?? ''}
|
||||
scheduleNames={{ 14: 'Dependency audit' }}
|
||||
renderSessionCard={(session) => <div key={session.id}>{session.title}</div>}
|
||||
onNewSession={onNewSession}
|
||||
onOpenTerminal={onOpenTerminal}
|
||||
onCreateWorktree={onCreateWorktree}
|
||||
onDelete={onDelete}
|
||||
/>,
|
||||
)
|
||||
}
|
||||
|
||||
describe('WorktreeSessionGroups', () => {
|
||||
it('groups sessions under their worktree with owner badges, schedule header and in-use pill', async () => {
|
||||
renderGroups()
|
||||
|
||||
expect(screen.getByText('feature/auth')).toBeInTheDocument()
|
||||
expect(screen.getByText('OpenCode')).toBeInTheDocument()
|
||||
expect(screen.getByText('Auth work')).toBeInTheDocument()
|
||||
expect(screen.getByText('1 session')).toBeInTheDocument()
|
||||
|
||||
expect(screen.getByText('Dependency audit')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedule · shared')).toBeInTheDocument()
|
||||
expect(screen.getByText('Schedule · run #340')).toBeInTheDocument()
|
||||
expect(screen.getByText('in use')).toBeInTheDocument()
|
||||
|
||||
expect(screen.getByText('Git')).toBeInTheDocument()
|
||||
expect(screen.getByText('No sessions in manual · Start one')).toBeInTheDocument()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /No sessions in manual/ }))
|
||||
expect(onNewSession).toHaveBeenCalledWith('/w/manual')
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Open terminal in manual' }))
|
||||
expect(onOpenTerminal).toHaveBeenCalledWith('/w/manual')
|
||||
})
|
||||
|
||||
it('disables delete for the in-use worktree and deletes the run worktree after confirmation', async () => {
|
||||
renderGroups()
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Delete worktree schedule/14/shared' })).toBeDisabled()
|
||||
const runDelete = screen.getByRole('button', { name: 'Delete worktree schedule/14/run-340' })
|
||||
expect(runDelete).toBeEnabled()
|
||||
|
||||
await userEvent.click(runDelete)
|
||||
const dialog = screen.getByRole('dialog', { name: 'Delete Worktree' })
|
||||
await userEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))
|
||||
|
||||
expect(onDelete).toHaveBeenCalledWith(['/s/job-14-run-340'])
|
||||
})
|
||||
|
||||
it('cleans up only the non-in-use worktrees of a schedule after confirmation', async () => {
|
||||
renderGroups()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Clean up' }))
|
||||
const dialog = screen.getByRole('dialog', { name: 'Delete Worktree' })
|
||||
await userEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))
|
||||
|
||||
expect(onDelete).toHaveBeenCalledWith(['/s/job-14-run-340'])
|
||||
})
|
||||
|
||||
it('cleans up worktrees of a schedule that the search is hiding', async () => {
|
||||
renderGroups({ sessions: [makeSession('ses_2', 'Audit run', '/s/job-14-shared')], searchQuery: 'audit' })
|
||||
|
||||
expect(screen.queryByText('schedule/14/run-340')).toBeNull()
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Clean up' }))
|
||||
const dialog = screen.getByRole('dialog', { name: 'Delete Worktree' })
|
||||
await userEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))
|
||||
|
||||
expect(onDelete).toHaveBeenCalledWith(['/s/job-14-run-340'])
|
||||
})
|
||||
|
||||
it('filters to only the git worktree when the Git owner chip is selected', async () => {
|
||||
renderGroups()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Git 1' }))
|
||||
|
||||
expect(screen.getByText('manual')).toBeInTheDocument()
|
||||
expect(screen.queryByText('feature/auth')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Dependency audit')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('collapses a worktree and persists the collapsed state across remount', async () => {
|
||||
const { unmount } = renderGroups()
|
||||
expect(screen.getByText('Auth work')).toBeInTheDocument()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { expanded: true, name: /feature\/auth/ }))
|
||||
expect(screen.queryByText('Auth work')).not.toBeInTheDocument()
|
||||
|
||||
unmount()
|
||||
renderGroups()
|
||||
expect(screen.queryByText('Auth work')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides empty worktrees while searching and renders the empty state when there are none', async () => {
|
||||
const { unmount } = renderGroups({ searchQuery: 'auth' })
|
||||
|
||||
expect(screen.getByText('feature/auth')).toBeInTheDocument()
|
||||
expect(screen.queryByText('manual')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Dependency audit')).not.toBeInTheDocument()
|
||||
|
||||
unmount()
|
||||
renderGroups({ worktrees: [], sessions: [] })
|
||||
|
||||
expect(screen.getByText('No worktrees yet')).toBeInTheDocument()
|
||||
await userEvent.click(screen.getByRole('button', { name: 'New worktree' }))
|
||||
expect(onCreateWorktree).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,359 @@
|
||||
import { useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { CalendarClock, ChevronRight, Layers, Plus, SquareTerminal, Trash2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { workspaceLabel, worktreeSourceLabel, type RepoSibling } from '@/api/repos'
|
||||
import type { Session } from '@/api/types'
|
||||
import type { RepoWorktreeSource } from '@opencode-manager/shared/utils'
|
||||
|
||||
type OwnerFilter = 'all' | RepoWorktreeSource
|
||||
|
||||
interface WorktreeSessionGroupsProps {
|
||||
repoId: number
|
||||
worktrees: RepoSibling[]
|
||||
sessions: Session[]
|
||||
searchQuery: string
|
||||
scheduleNames: Record<number, string>
|
||||
renderSessionCard: (session: Session) => ReactNode
|
||||
onNewSession: (directory: string) => void
|
||||
onOpenTerminal: (directory: string) => void
|
||||
onCreateWorktree: () => void
|
||||
onDelete: (directories: string[]) => void
|
||||
isDeleting?: boolean
|
||||
}
|
||||
|
||||
interface WorktreeGroup {
|
||||
worktree: RepoSibling
|
||||
directory: string
|
||||
sessions: Session[]
|
||||
lastActive: number
|
||||
}
|
||||
|
||||
type GroupEntry =
|
||||
| { kind: 'worktree'; key: string; group: WorktreeGroup; lastActive: number }
|
||||
| { kind: 'schedule'; key: string; jobId: number; groups: WorktreeGroup[]; lastActive: number }
|
||||
|
||||
const OWNER_FILTERS: Array<{ value: OwnerFilter; label: string }> = [
|
||||
{ value: 'all', label: 'All' },
|
||||
{ value: 'opencode', label: 'OpenCode' },
|
||||
{ value: 'schedule', label: 'Schedules' },
|
||||
{ value: 'git', label: 'Git' },
|
||||
]
|
||||
|
||||
const OWNER_BADGE_CLASS: Record<RepoWorktreeSource, string> = {
|
||||
opencode: 'border-primary/40 bg-primary/15 text-primary',
|
||||
schedule: 'border-highlight/40 bg-highlight/15 text-highlight',
|
||||
git: 'border-border bg-muted text-muted-foreground',
|
||||
}
|
||||
|
||||
const WORKTREE_REMOVAL_NOTE = 'OpenCode worktrees are removed with their sessions. Schedule worktrees have pending changes committed to their branch first. Other git worktrees are only removed when they have no uncommitted changes.'
|
||||
|
||||
/**
|
||||
* The Worktrees tab body: every worktree of the repo as a collapsible section of its sessions,
|
||||
* with a schedule's worktrees nested under that schedule so kept runs stay visible as they pile up.
|
||||
*/
|
||||
export function WorktreeSessionGroups({
|
||||
repoId,
|
||||
worktrees,
|
||||
sessions,
|
||||
searchQuery,
|
||||
scheduleNames,
|
||||
renderSessionCard,
|
||||
onNewSession,
|
||||
onOpenTerminal,
|
||||
onCreateWorktree,
|
||||
onDelete,
|
||||
isDeleting = false,
|
||||
}: WorktreeSessionGroupsProps) {
|
||||
const [ownerFilter, setOwnerFilter] = useState<OwnerFilter>('all')
|
||||
const [collapsed, setCollapsed] = useCollapsedGroups(repoId)
|
||||
const [pendingDelete, setPendingDelete] = useState<{ directories: string[]; label: string } | null>(null)
|
||||
const isSearching = searchQuery.trim().length > 0
|
||||
|
||||
const ownerCounts = useMemo(() => {
|
||||
const counts: Record<OwnerFilter, number> = { all: worktrees.length, opencode: 0, schedule: 0, git: 0 }
|
||||
worktrees.forEach((worktree) => {
|
||||
if (worktree.worktreeSource) counts[worktree.worktreeSource] += 1
|
||||
})
|
||||
return counts
|
||||
}, [worktrees])
|
||||
|
||||
const entries = useMemo(
|
||||
() => buildGroupEntries(worktrees, sessions, ownerFilter, isSearching),
|
||||
[worktrees, sessions, ownerFilter, isSearching],
|
||||
)
|
||||
|
||||
const toggle = (key: string) => {
|
||||
setCollapsed((current) => {
|
||||
const next = new Set(current)
|
||||
if (next.has(key)) next.delete(key)
|
||||
else next.add(key)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const allKeys = entries.flatMap((entry) => (
|
||||
entry.kind === 'schedule' ? [entry.key, ...entry.groups.map((group) => groupKey(group.directory))] : [entry.key]
|
||||
))
|
||||
const allCollapsed = allKeys.length > 0 && allKeys.every((key) => collapsed.has(key))
|
||||
|
||||
if (worktrees.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-3 rounded-md border border-dashed border-border p-6 text-center">
|
||||
<p className="font-medium">No worktrees yet</p>
|
||||
<p className="text-sm text-muted-foreground">Create a worktree to work on a branch without touching the main checkout.</p>
|
||||
<Button size="sm" onClick={onCreateWorktree}>
|
||||
<Plus className="mr-1 h-4 w-4" />
|
||||
New worktree
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const renderWorktree = (group: WorktreeGroup, nested: boolean) => {
|
||||
const key = groupKey(group.directory)
|
||||
const isOpen = !collapsed.has(key)
|
||||
const label = workspaceLabel(group.worktree)
|
||||
const source = group.worktree.worktreeSource
|
||||
const sourceLabel = worktreeSourceLabel(group.worktree)
|
||||
const isInUse = group.worktree.schedule?.inUse === true
|
||||
return (
|
||||
<div key={key} className={`rounded-md border border-border bg-card/40 ${nested ? 'ml-3' : ''}`}>
|
||||
<div className="flex items-center gap-1 px-2 py-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggle(key)}
|
||||
aria-expanded={isOpen}
|
||||
className="flex min-w-0 flex-1 items-center gap-2 rounded px-1 py-1 text-left hover:bg-accent/50"
|
||||
>
|
||||
<ChevronRight className={`h-4 w-4 shrink-0 text-muted-foreground transition-transform ${isOpen ? 'rotate-90' : ''}`} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate text-sm font-medium">{label}</span>
|
||||
{sourceLabel && source && (
|
||||
<span className={`shrink-0 rounded border px-1.5 text-[10px] leading-4 ${OWNER_BADGE_CLASS[source]}`}>{sourceLabel}</span>
|
||||
)}
|
||||
{isInUse && (
|
||||
<span className="inline-flex shrink-0 items-center gap-1 rounded-full border border-success/40 bg-success/15 px-1.5 text-[10px] leading-4 text-success">
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-success" />
|
||||
in use
|
||||
</span>
|
||||
)}
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
{group.sessions.length} {group.sessions.length === 1 ? 'session' : 'sessions'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="truncate font-mono text-[11px] text-muted-foreground" title={group.directory}>{group.directory}</div>
|
||||
</div>
|
||||
</button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-8 shrink-0"
|
||||
aria-label={`New session in ${label}`}
|
||||
onClick={() => onNewSession(group.directory)}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-8 shrink-0"
|
||||
aria-label={`Open terminal in ${label}`}
|
||||
onClick={() => onOpenTerminal(group.directory)}
|
||||
>
|
||||
<SquareTerminal className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-8 shrink-0 text-muted-foreground hover:text-destructive"
|
||||
aria-label={`Delete worktree ${label}`}
|
||||
title={isInUse ? 'In use by a running scheduled run' : undefined}
|
||||
disabled={isInUse || isDeleting}
|
||||
onClick={() => setPendingDelete({ directories: [group.directory], label })}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
{isOpen && (
|
||||
<div className="flex flex-col gap-2 px-3 pb-3">
|
||||
{group.sessions.length > 0 ? group.sessions.map(renderSessionCard) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onNewSession(group.directory)}
|
||||
className="rounded-md border border-dashed border-border px-3 py-3 text-sm text-muted-foreground hover:bg-accent/50 hover:text-foreground"
|
||||
>
|
||||
No sessions in {label} · Start one
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{OWNER_FILTERS.map((filter) => (
|
||||
<button
|
||||
key={filter.value}
|
||||
type="button"
|
||||
aria-pressed={ownerFilter === filter.value}
|
||||
onClick={() => setOwnerFilter(filter.value)}
|
||||
className={`rounded-full border px-2.5 py-0.5 text-xs ${ownerFilter === filter.value
|
||||
? 'border-primary/50 bg-primary/15 text-foreground'
|
||||
: 'border-border text-muted-foreground hover:text-foreground'}`}
|
||||
>
|
||||
{filter.label} {ownerCounts[filter.value]}
|
||||
</button>
|
||||
))}
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<Button variant="ghost" size="sm" className="h-8 text-xs" onClick={() => setCollapsed(allCollapsed ? new Set() : new Set(allKeys))}>
|
||||
{allCollapsed ? 'Expand all' : 'Collapse all'}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="h-8 text-xs" onClick={onCreateWorktree}>
|
||||
<Layers className="mr-1 h-3.5 w-3.5 text-primary" />
|
||||
New worktree
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{entries.length === 0 ? (
|
||||
<div className="py-4 text-center text-sm text-muted-foreground">
|
||||
{isSearching ? 'No sessions found' : 'No worktrees match this filter'}
|
||||
</div>
|
||||
) : entries.map((entry) => {
|
||||
if (entry.kind === 'worktree') return renderWorktree(entry.group, false)
|
||||
const isOpen = !collapsed.has(entry.key)
|
||||
const name = scheduleNames[entry.jobId] ?? `Schedule #${entry.jobId}`
|
||||
const removable = worktrees
|
||||
.filter((worktree) => worktree.schedule?.jobId === entry.jobId && !worktree.schedule.inUse)
|
||||
.map((worktree) => worktree.fullPath)
|
||||
return (
|
||||
<div key={entry.key} className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggle(entry.key)}
|
||||
aria-expanded={isOpen}
|
||||
className="flex min-w-0 flex-1 items-center gap-2 rounded px-1 py-1 text-left text-sm hover:bg-accent/50"
|
||||
>
|
||||
<ChevronRight className={`h-4 w-4 shrink-0 text-muted-foreground transition-transform ${isOpen ? 'rotate-90' : ''}`} />
|
||||
<CalendarClock className="h-4 w-4 shrink-0 text-highlight" />
|
||||
<span className="truncate font-medium">{name}</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">
|
||||
· {entry.groups.length} {entry.groups.length === 1 ? 'worktree' : 'worktrees'}
|
||||
</span>
|
||||
</button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 shrink-0 text-xs text-muted-foreground hover:text-destructive"
|
||||
disabled={removable.length === 0 || isDeleting}
|
||||
onClick={() => setPendingDelete({ directories: removable, label: `${name} worktrees` })}
|
||||
>
|
||||
Clean up
|
||||
</Button>
|
||||
</div>
|
||||
{isOpen && entry.groups.map((group) => renderWorktree(group, true))}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
<DeleteDialog
|
||||
open={pendingDelete !== null}
|
||||
onOpenChange={(open) => { if (!open) setPendingDelete(null) }}
|
||||
onCancel={() => setPendingDelete(null)}
|
||||
onConfirm={() => {
|
||||
if (pendingDelete) onDelete(pendingDelete.directories)
|
||||
setPendingDelete(null)
|
||||
}}
|
||||
title={pendingDelete && pendingDelete.directories.length > 1 ? 'Delete Worktrees' : 'Delete Worktree'}
|
||||
description={pendingDelete && pendingDelete.directories.length > 1
|
||||
? `Delete ${pendingDelete.directories.length} worktrees? ${WORKTREE_REMOVAL_NOTE}`
|
||||
: `Delete this worktree? ${WORKTREE_REMOVAL_NOTE}`}
|
||||
itemName={pendingDelete?.label}
|
||||
isDeleting={isDeleting}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function groupKey(directory: string): string {
|
||||
return `worktree:${directory}`
|
||||
}
|
||||
|
||||
function buildGroupEntries(
|
||||
worktrees: RepoSibling[],
|
||||
sessions: Session[],
|
||||
ownerFilter: OwnerFilter,
|
||||
hideEmpty: boolean,
|
||||
): GroupEntry[] {
|
||||
const sessionsByDirectory = new Map<string, Session[]>()
|
||||
sessions.forEach((session) => {
|
||||
const list = sessionsByDirectory.get(session.location.directory) ?? []
|
||||
list.push(session)
|
||||
sessionsByDirectory.set(session.location.directory, list)
|
||||
})
|
||||
|
||||
const groups = worktrees
|
||||
.filter((worktree) => ownerFilter === 'all' || worktree.worktreeSource === ownerFilter)
|
||||
.map((worktree): WorktreeGroup => {
|
||||
const groupSessions = sessionsByDirectory.get(worktree.fullPath) ?? []
|
||||
return {
|
||||
worktree,
|
||||
directory: worktree.fullPath,
|
||||
sessions: groupSessions,
|
||||
lastActive: groupSessions[0]?.time.updated ?? 0,
|
||||
}
|
||||
})
|
||||
.filter((group) => !hideEmpty || group.sessions.length > 0)
|
||||
|
||||
const scheduleEntries = new Map<number, Extract<GroupEntry, { kind: 'schedule' }>>()
|
||||
const entries: GroupEntry[] = []
|
||||
groups.forEach((group) => {
|
||||
const jobId = group.worktree.schedule?.jobId
|
||||
if (jobId === undefined) {
|
||||
entries.push({ kind: 'worktree', key: groupKey(group.directory), group, lastActive: group.lastActive })
|
||||
return
|
||||
}
|
||||
const existing = scheduleEntries.get(jobId)
|
||||
if (existing) {
|
||||
existing.groups.push(group)
|
||||
existing.lastActive = Math.max(existing.lastActive, group.lastActive)
|
||||
return
|
||||
}
|
||||
const entry: Extract<GroupEntry, { kind: 'schedule' }> = { kind: 'schedule', key: `schedule:${jobId}`, jobId, groups: [group], lastActive: group.lastActive }
|
||||
scheduleEntries.set(jobId, entry)
|
||||
entries.push(entry)
|
||||
})
|
||||
|
||||
scheduleEntries.forEach((entry) => entry.groups.sort((a, b) => b.lastActive - a.lastActive))
|
||||
return entries.sort((a, b) => b.lastActive - a.lastActive)
|
||||
}
|
||||
|
||||
function useCollapsedGroups(repoId: number) {
|
||||
const storageKey = `oc:repo:${repoId}:worktree-groups:collapsed`
|
||||
const [collapsed, setCollapsed] = useState<Set<string>>(() => readCollapsed(storageKey))
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
localStorage.setItem(storageKey, JSON.stringify(Array.from(collapsed)))
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}, [storageKey, collapsed])
|
||||
|
||||
return [collapsed, setCollapsed] as const
|
||||
}
|
||||
|
||||
function readCollapsed(storageKey: string): Set<string> {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(localStorage.getItem(storageKey) ?? '[]')
|
||||
return new Set(Array.isArray(parsed) ? parsed.filter((value): value is string => typeof value === 'string') : [])
|
||||
} catch {
|
||||
return new Set()
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { WorktreeTabs } from './WorktreeTabs'
|
||||
import type { RepoSibling } from '@/api/repos'
|
||||
@@ -15,6 +15,7 @@ const makeWorkspaceSibling = (branch: string): RepoSibling => ({
|
||||
currentBranch: branch,
|
||||
branch,
|
||||
worktreeStrategy: 'git',
|
||||
worktreeSource: 'opencode',
|
||||
})
|
||||
|
||||
const onValueChange = vi.fn()
|
||||
@@ -30,18 +31,18 @@ describe('WorktreeTabs', () => {
|
||||
)
|
||||
expect(screen.getAllByRole('tab')).toHaveLength(1)
|
||||
expect(screen.getByText('main')).toBeInTheDocument()
|
||||
expect(screen.getByText('Workspace')).toBeInTheDocument()
|
||||
expect(screen.getByText('Worktree')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders Repo and Workspaces tabs when at least one workspace exists', () => {
|
||||
it('renders Repo and Worktrees tabs when at least one workspace exists', () => {
|
||||
const workspaces = [makeWorkspaceSibling('feature-a')]
|
||||
render(<WorktreeTabs workspaces={workspaces} value="repo" onValueChange={onValueChange} baseLabel="main" />)
|
||||
|
||||
const tabs = screen.getAllByRole('tab')
|
||||
expect(tabs).toHaveLength(2)
|
||||
expect(screen.getByText('main')).toBeInTheDocument()
|
||||
expect(screen.getByText('Workspaces')).toBeInTheDocument()
|
||||
expect(screen.getByText('(1)')).toBeInTheDocument()
|
||||
expect(screen.getByText('Worktrees')).toBeInTheDocument()
|
||||
expect(within(tabs[1]).getByText('1')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('marks the active tab', () => {
|
||||
@@ -69,6 +70,6 @@ describe('WorktreeTabs', () => {
|
||||
]
|
||||
render(<WorktreeTabs workspaces={workspaces} value="repo" onValueChange={onValueChange} baseLabel="main" />)
|
||||
|
||||
expect(screen.getByText('(3)')).toBeInTheDocument()
|
||||
expect(within(screen.getAllByRole('tab')[1]).getByText('3')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -8,9 +8,7 @@ interface WorktreeTabsProps {
|
||||
value: WorktreeTabValue
|
||||
onValueChange: (value: WorktreeTabValue) => void
|
||||
baseLabel: string
|
||||
activeWorkspaceLabel?: string
|
||||
onCreateWorkspace?: () => void
|
||||
onWorkspaceMenu?: () => void
|
||||
}
|
||||
|
||||
export function WorktreeTabs({
|
||||
@@ -18,40 +16,37 @@ export function WorktreeTabs({
|
||||
value,
|
||||
onValueChange,
|
||||
baseLabel,
|
||||
activeWorkspaceLabel,
|
||||
onCreateWorkspace,
|
||||
onWorkspaceMenu,
|
||||
}: WorktreeTabsProps) {
|
||||
const hasWorkspaces = workspaces.length > 0
|
||||
const workspaceLabel = value === 'workspaces' && activeWorkspaceLabel ? activeWorkspaceLabel : 'Workspaces'
|
||||
const tabClassName =
|
||||
'group min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3 data-[state=active]:border data-[state=active]:border-primary/50 data-[state=active]:bg-primary/10 data-[state=inactive]:hover:bg-accent data-[state=inactive]:hover:text-foreground'
|
||||
'group min-w-0 flex-1 gap-1.5 rounded-t-md rounded-b-none border border-transparent border-b-0 px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground data-[state=active]:-mb-px data-[state=active]:border-border data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-none sm:flex-none'
|
||||
const activeLabelClassName = 'group-data-[state=active]:text-highlight'
|
||||
|
||||
return (
|
||||
<div className="px-4 pt-2 flex-shrink-0">
|
||||
<div className="flex-shrink-0">
|
||||
<Tabs value={value} onValueChange={(next) => onValueChange(next as WorktreeTabValue)} className="min-w-0">
|
||||
<TabsList className="w-full justify-start gap-1 overflow-hidden">
|
||||
<TabsList className="flex h-auto w-full items-end justify-start gap-1 rounded-none border-b border-border bg-transparent p-0 px-4 pt-2">
|
||||
<TabsTrigger value="repo" className={tabClassName}>
|
||||
<GitBranch className="h-3 w-3 shrink-0" />
|
||||
<span className={`min-w-0 truncate ${activeLabelClassName}`}>{baseLabel}</span>
|
||||
</TabsTrigger>
|
||||
{hasWorkspaces ? (
|
||||
<>
|
||||
<TabsTrigger value="workspaces" className={tabClassName} onClick={onWorkspaceMenu}>
|
||||
<Layers className="h-3 w-3 shrink-0 text-primary" />
|
||||
<span className={`min-w-0 truncate ${activeLabelClassName}`}>{workspaceLabel}</span>
|
||||
<span className={`shrink-0 text-xs text-muted-foreground ${activeLabelClassName}`}>({workspaces.length})</span>
|
||||
</TabsTrigger>
|
||||
</>
|
||||
<TabsTrigger value="workspaces" className={tabClassName}>
|
||||
<Layers className="h-3 w-3 shrink-0 text-primary" />
|
||||
<span className={`min-w-0 truncate ${activeLabelClassName}`}>Worktrees</span>
|
||||
<span className="shrink-0 rounded-full border border-border bg-card px-1.5 text-[11px] leading-4 text-muted-foreground">
|
||||
{workspaces.length}
|
||||
</span>
|
||||
</TabsTrigger>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCreateWorkspace}
|
||||
className="inline-flex h-8 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground sm:flex-none sm:px-3"
|
||||
className="inline-flex min-w-0 flex-1 items-center justify-center gap-1.5 rounded-t-md rounded-b-none border border-transparent border-b-0 px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground sm:flex-none"
|
||||
>
|
||||
<Layers className="h-3 w-3 shrink-0 text-primary" />
|
||||
<span className="min-w-0 truncate">Workspace</span>
|
||||
<span className="min-w-0 truncate">Worktree</span>
|
||||
<Plus className="h-3.5 w-3.5 shrink-0" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
@@ -5,6 +5,9 @@ import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { TabsContent } from '@/components/ui/tabs'
|
||||
import { RadioOptionGroup } from '@/components/ui/radio-option-group'
|
||||
import { workspaceModeOptions } from '@/components/schedules/schedule-utils'
|
||||
import type { ScheduleWorkspaceMode } from '@opencode-manager/shared/types'
|
||||
import { Info } from 'lucide-react'
|
||||
|
||||
type GeneralTabProps = {
|
||||
@@ -23,6 +26,9 @@ type GeneralTabProps = {
|
||||
branch: string
|
||||
onBranchChange: (value: string) => void
|
||||
branchRepoId: number | undefined
|
||||
workspaceMode: ScheduleWorkspaceMode
|
||||
onWorkspaceModeChange: (value: ScheduleWorkspaceMode) => void
|
||||
showWorkspaceMode: boolean
|
||||
showRepoSelector?: boolean
|
||||
isEditing: boolean
|
||||
repoId?: number
|
||||
@@ -64,6 +70,9 @@ export function GeneralTab({
|
||||
branch,
|
||||
onBranchChange,
|
||||
branchRepoId,
|
||||
workspaceMode,
|
||||
onWorkspaceModeChange,
|
||||
showWorkspaceMode,
|
||||
showRepoSelector,
|
||||
isEditing,
|
||||
repoId,
|
||||
@@ -152,22 +161,35 @@ export function GeneralTab({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-border bg-card p-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="schedule-branch">Base branch</Label>
|
||||
<InfoHint text="Scheduled runs execute in an isolated worktree branched off this base branch. Leave empty to use the repository's default branch." />
|
||||
<div className="rounded-lg border border-border bg-card p-4 space-y-4">
|
||||
{showWorkspaceMode && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm font-medium">Workspace</p>
|
||||
<RadioOptionGroup
|
||||
name="schedule-workspace-mode"
|
||||
value={workspaceMode}
|
||||
onChange={onWorkspaceModeChange}
|
||||
options={workspaceModeOptions}
|
||||
/>
|
||||
</div>
|
||||
<BranchCombobox
|
||||
id="schedule-branch"
|
||||
repoId={branchRepoId}
|
||||
value={branch}
|
||||
onValueChange={onBranchChange}
|
||||
placeholder="Defaults to default branch"
|
||||
remotes="bare"
|
||||
clearable
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{workspaceMode !== 'repo' && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="schedule-branch">Base branch</Label>
|
||||
<InfoHint text="New run worktrees branch off this base branch. A shared worktree only uses it when it is first created. Leave empty to use the repository's default branch." />
|
||||
</div>
|
||||
<BranchCombobox
|
||||
id="schedule-branch"
|
||||
repoId={branchRepoId}
|
||||
value={branch}
|
||||
onValueChange={onBranchChange}
|
||||
placeholder="Defaults to default branch"
|
||||
remotes="bare"
|
||||
clearable
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
|
||||
@@ -6,9 +6,12 @@ import {
|
||||
formatScheduleSummary,
|
||||
formatTimestamp,
|
||||
getJobStatusTone,
|
||||
formatWorkspaceMode,
|
||||
hasSkillMetadata,
|
||||
} from '@/components/schedules/schedule-utils'
|
||||
import { Bot, CalendarClock, Clock3, History, Loader2, Pencil, Play, Sparkles, Trash2 } from 'lucide-react'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import { useRemoveScheduleWorktrees, useScheduleWorktrees } from '@/hooks/useSchedules'
|
||||
import { Bot, CalendarClock, Clock3, GitBranch, History, Loader2, Pencil, Play, Sparkles, Trash2 } from 'lucide-react'
|
||||
import { useScheduleModels } from '@/hooks/useScheduleModels'
|
||||
import { resolveScheduleModel } from '@/lib/schedules/schedule-model'
|
||||
|
||||
@@ -37,6 +40,9 @@ export function JobDetailTab({
|
||||
}: JobDetailTabProps) {
|
||||
const { availableModelKeys, configDefaultModel } = useScheduleModels(Boolean(selectedJob))
|
||||
const resolvedModel = resolveScheduleModel(selectedJob?.model, availableModelKeys, configDefaultModel)
|
||||
const { data: worktrees = [] } = useScheduleWorktrees(selectedJob?.repoId, selectedJob?.id ?? null)
|
||||
const removeWorktrees = useRemoveScheduleWorktrees()
|
||||
const idleWorktreeCount = worktrees.filter((worktree) => !worktree.inUse).length
|
||||
|
||||
if (!selectedJob) {
|
||||
return (
|
||||
@@ -109,6 +115,49 @@ export function JobDetailTab({
|
||||
<pre className="whitespace-pre-wrap break-words text-sm font-mono leading-6 text-foreground/90">{JSON.stringify(selectedJob.skillMetadata, null, 2)}</pre>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{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>
|
||||
<h3 className="text-base font-medium flex items-center gap-2"><GitBranch className="h-4 w-4" /> Worktrees ({worktrees.length})</h3>
|
||||
<p className="text-sm text-muted-foreground">Worktrees this schedule has on disk. Removing one commits any pending changes to its branch first and keeps the branch.</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => removeWorktrees.mutate({ repoId: selectedJob.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" />}
|
||||
<span className="hidden sm:inline">Remove all</span>
|
||||
</Button>
|
||||
</div>
|
||||
<ul className="divide-y divide-border/60">
|
||||
{worktrees.map((worktree) => (
|
||||
<li key={worktree.worktreePath} className="flex items-center justify-between gap-2 py-2">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-mono text-sm">{worktree.branch}</p>
|
||||
<p className="truncate text-xs text-muted-foreground" title={worktree.worktreePath}>
|
||||
{worktree.runId === null ? 'Shared worktree' : `Run #${worktree.runId}`}
|
||||
{worktree.inUse ? ' · in use' : ''} · {worktree.worktreePath}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
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 })}
|
||||
disabled={worktree.inUse || removeWorktrees.isPending}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Card className="border-border/60 bg-background/60 shadow-none">
|
||||
@@ -131,6 +180,12 @@ 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 && (
|
||||
<div>
|
||||
<p className="text-muted-foreground">Workspace</p>
|
||||
<p className="font-medium">{formatWorkspaceMode(selectedJob.workspaceMode)}</p>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-muted-foreground">Created</p>
|
||||
<p className="font-medium">{formatTimestamp(selectedJob.createdAt)}</p>
|
||||
|
||||
@@ -267,6 +267,15 @@ describe('RunDetailPanel open session', () => {
|
||||
expect(apiMocks.createSessionWithContext).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens the original session for a finished run whose worktree was kept', async () => {
|
||||
renderPanel({ ...run, status: 'completed', sessionId: 'ses_run', worktreePath: '/abs/worktrees/job-1-run-1', runBranch: 'schedule/1/run-1' })
|
||||
|
||||
await clickOpenSession()
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/repos/5/sessions/ses_run'))
|
||||
expect(apiMocks.createSessionWithContext).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens a new repo session seeded with the full output and branch for a finished worktree run', async () => {
|
||||
apiMocks.createSessionWithContext.mockResolvedValue({ id: 'ses_new' })
|
||||
renderPanel({
|
||||
|
||||
@@ -71,7 +71,7 @@ export function RunDetailPanel({ repoId, activeRun, selectedRunLoading, onCancel
|
||||
|
||||
const { sessionId } = activeRun
|
||||
|
||||
const opensNewRepoSession = Boolean(activeRun.runBranch) && activeRun.status !== 'running'
|
||||
const opensNewRepoSession = Boolean(activeRun.runBranch) && !activeRun.worktreePath && activeRun.status !== 'running'
|
||||
|
||||
const handleOpenSession = async () => {
|
||||
if (!opensNewRepoSession) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob, ScheduleMcpServer } from '@opencode-manager/shared/types'
|
||||
import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob, ScheduleMcpServer, ScheduleWorkspaceMode } from '@opencode-manager/shared/types'
|
||||
import { useScheduleModels } from '@/hooks/useScheduleModels'
|
||||
import { providerModelRef } from '@/api/providers'
|
||||
import { resolveScheduleModel } from '@/lib/schedules/schedule-model'
|
||||
@@ -71,6 +71,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
const initialSkillNotesRef = useRef<string | undefined>(undefined)
|
||||
const [mcpServers, setMcpServers] = useState<ScheduleMcpServer[]>([])
|
||||
const [branch, setBranch] = useState('')
|
||||
const [workspaceMode, setWorkspaceMode] = useState<ScheduleWorkspaceMode>('worktree')
|
||||
const [allowExternalDirectory, setAllowExternalDirectory] = useState(false)
|
||||
const [allowQuestions, setAllowQuestions] = useState(false)
|
||||
const [bashDenyPatterns, setBashDenyPatterns] = useState<string[]>([...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
|
||||
@@ -204,6 +205,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
initialSkillNotesRef.current = initialSkillNotes
|
||||
setMcpServers(job?.mcpServers ?? [])
|
||||
setBranch(job?.branch ?? '')
|
||||
setWorkspaceMode(job?.workspaceMode ?? 'worktree')
|
||||
setAllowExternalDirectory(job?.permissionConfig?.allowExternalDirectory ?? false)
|
||||
setAllowQuestions(job?.permissionConfig?.allowQuestions ?? false)
|
||||
setBashDenyPatterns(job?.permissionConfig?.bashDenyPatterns ?? [...DEFAULT_DESTRUCTIVE_BASH_PATTERNS])
|
||||
@@ -252,6 +254,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
model: resolvedModel ?? undefined,
|
||||
prompt: prompt.trim(),
|
||||
branch: branch.trim() || null,
|
||||
workspaceMode,
|
||||
mcpServers,
|
||||
permissionConfig: {
|
||||
allowExternalDirectory,
|
||||
@@ -331,6 +334,9 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
branch={branch}
|
||||
onBranchChange={setBranch}
|
||||
branchRepoId={open && effectiveRepoId !== ASSISTANT_REPO_ID ? effectiveRepoId : undefined}
|
||||
workspaceMode={workspaceMode}
|
||||
onWorkspaceModeChange={setWorkspaceMode}
|
||||
showWorkspaceMode={effectiveRepoId !== ASSISTANT_REPO_ID}
|
||||
showRepoSelector={showRepoSelector}
|
||||
isEditing={!!job}
|
||||
repoId={selectedRepoId}
|
||||
|
||||
@@ -184,6 +184,14 @@ export function ScheduleJobsTable({
|
||||
>
|
||||
{job.name}
|
||||
</button>
|
||||
{job.retainedWorktreeCount > 0 && (
|
||||
<span
|
||||
title="Worktrees this schedule has left on disk. Manage them from the job details."
|
||||
className="shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground"
|
||||
>
|
||||
{job.retainedWorktreeCount} worktree{job.retainedWorktreeCount === 1 ? '' : 's'}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{job.description && <span className="truncate text-xs text-muted-foreground sm:max-w-[20rem]">{job.description}</span>}
|
||||
<span className="truncate text-xs text-muted-foreground sm:hidden" title={scheduleTitle}>{mobileDetail}</span>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import cronstrue from 'cronstrue'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import type { CreateScheduleJobRequest, ScheduleJob, ScheduleRun, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
|
||||
import type { CreateScheduleJobRequest, ScheduleJob, ScheduleRun, ScheduleWorkspaceMode, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
|
||||
import type { RadioOption } from '@/components/ui/radio-option-group'
|
||||
|
||||
export const intervalOptions = [
|
||||
{ label: '15m', value: 15 },
|
||||
@@ -39,6 +40,33 @@ export const weekdayOptions = [
|
||||
|
||||
export type SchedulePreset = typeof schedulePresetOptions[number]['value']
|
||||
|
||||
export const workspaceModeOptions: Array<RadioOption<ScheduleWorkspaceMode>> = [
|
||||
{
|
||||
value: 'worktree',
|
||||
label: 'Fresh worktree, cleaned up',
|
||||
description: 'Each run gets its own worktree. Changes are committed to a run branch and the worktree is removed when the run ends.',
|
||||
},
|
||||
{
|
||||
value: 'kept-worktree',
|
||||
label: 'Fresh worktree, kept',
|
||||
description: 'Each run gets its own worktree, which stays on disk afterwards so you can continue in it. Kept worktrees are listed on the job details.',
|
||||
},
|
||||
{
|
||||
value: 'shared-worktree',
|
||||
label: 'Shared worktree',
|
||||
description: 'Every run reuses one worktree and branch, so work builds up from run to run.',
|
||||
},
|
||||
{
|
||||
value: 'repo',
|
||||
label: 'Repository checkout',
|
||||
description: 'Runs directly in the repository working directory. Nothing is isolated, committed, or cleaned up.',
|
||||
},
|
||||
]
|
||||
|
||||
export function formatWorkspaceMode(mode: ScheduleWorkspaceMode): string {
|
||||
return workspaceModeOptions.find((option) => option.value === mode)?.label ?? mode
|
||||
}
|
||||
|
||||
export function getLocalTimeZone(): string {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
|
||||
@@ -351,3 +379,5 @@ export function matchesScheduleJobSearch(job: ScheduleJob & { repoName?: string
|
||||
if (!term) return true
|
||||
return [job.name, job.description, job.repoName].some((field) => field?.toLowerCase().includes(term))
|
||||
}
|
||||
|
||||
export const DELETE_SCHEDULE_DESCRIPTION = 'This removes the job definition and all recorded run history for it. Any kept or shared worktrees are removed after their pending changes are committed to their branches; the branches are kept.'
|
||||
@@ -244,6 +244,23 @@ describe('SessionList', () => {
|
||||
expect(screen.getByText('Click here to start a new session')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('hands an empty list to a custom session renderer instead of the create-session card', () => {
|
||||
sessionsData.splice(0, sessionsData.length)
|
||||
const renderSessions = vi.fn(() => <p>Custom layout</p>)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
renderSessions={renderSessions}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Custom layout')).toBeTruthy()
|
||||
expect(screen.queryByText('No sessions yet')).toBeNull()
|
||||
expect(renderSessions).toHaveBeenCalledWith(expect.objectContaining({ sessions: [], searchQuery: '' }))
|
||||
})
|
||||
|
||||
it('shows loading state instead of create-session card when the first page is empty but more pages are pending', () => {
|
||||
sessionsData.splice(0, sessionsData.length)
|
||||
hasNextPageRef.current = true
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useState, useMemo, useEffect, useRef } from "react";
|
||||
import { useCallback, useState, useMemo, useEffect, useRef, type ReactNode } from "react";
|
||||
import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
|
||||
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
|
||||
import type { Session } from "@/api/types";
|
||||
@@ -19,6 +19,17 @@ interface SessionListProps {
|
||||
directoryLabels?: Record<string, string>;
|
||||
activeSessionID?: string;
|
||||
onSelectSession: (sessionID: string) => void;
|
||||
renderSessions?: (args: SessionListRenderArgs) => ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets a caller lay out the loaded root sessions itself, for example grouped by worktree.
|
||||
* Search, paging, pinning, selection and delete stay owned by SessionList.
|
||||
*/
|
||||
export interface SessionListRenderArgs {
|
||||
sessions: Session[];
|
||||
searchQuery: string;
|
||||
renderSessionCard: (session: Session) => ReactNode;
|
||||
}
|
||||
|
||||
export const SessionList = ({
|
||||
@@ -28,6 +39,7 @@ export const SessionList = ({
|
||||
directoryLabels,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
renderSessions,
|
||||
}: SessionListProps) => {
|
||||
const directoriesList = useMemo(() => {
|
||||
const source = directories && directories.length > 0 ? directories : directory ? [directory] : [];
|
||||
@@ -118,7 +130,7 @@ export const SessionList = ({
|
||||
if (hasNextPage || isFetchingNextPage) {
|
||||
return <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
|
||||
}
|
||||
if (!searchQuery.trim()) {
|
||||
if (!searchQuery.trim() && !renderSessions) {
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
<Card
|
||||
@@ -285,7 +297,13 @@ export const SessionList = ({
|
||||
onScroll={handleSessionsScroll}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{filteredSessions.length === 0 && !isFetchingNextPage ? (
|
||||
{renderSessions ? (
|
||||
renderSessions({
|
||||
sessions: filteredSessions,
|
||||
searchQuery,
|
||||
renderSessionCard: (session) => renderSessionCard(session, pinnedKeys.has(getSessionSelectionKey(session))),
|
||||
})
|
||||
) : filteredSessions.length === 0 && !isFetchingNextPage ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-4">
|
||||
No sessions found
|
||||
</div>
|
||||
|
||||
@@ -28,7 +28,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa
|
||||
const isMobile = useMobile()
|
||||
const { searchParams, updateParams } = useUrlParams()
|
||||
const openPreview = useOpenPreview()
|
||||
const { data, isLoading, isSuccess, isFetching, refetch } = useTerminals(repoId, directory, {
|
||||
const { data, isLoading, isSuccess, isFetching, refetch, error } = useTerminals(repoId, directory, {
|
||||
enabled: isOpen && !!directory,
|
||||
refetchInterval: isOpen ? 5000 : false,
|
||||
})
|
||||
@@ -186,7 +186,7 @@ export function TerminalPanel({ repoId, directory, isOpen, onClose }: TerminalPa
|
||||
<div className="relative flex-1 min-h-0 bg-background">
|
||||
{terminals.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
{isLoading || isCreating ? 'Starting terminal...' : 'No terminals'}
|
||||
{error && !isCreating ? `Could not load terminals: ${error.message}` : isLoading || isCreating ? 'Starting terminal...' : 'No terminals'}
|
||||
</div>
|
||||
) : (
|
||||
<Suspense
|
||||
|
||||
@@ -180,11 +180,13 @@ export const useCreateSession = (
|
||||
title?: string;
|
||||
agent?: string;
|
||||
model?: string;
|
||||
directory?: string;
|
||||
}) => {
|
||||
if (!directory) {
|
||||
const targetDirectory = data.directory ?? directory;
|
||||
if (!targetDirectory) {
|
||||
throw new Error('A directory is required to create a session');
|
||||
}
|
||||
return createSession({ directory, ...data });
|
||||
return createSession({ ...data, directory: targetDirectory });
|
||||
},
|
||||
onSuccess: (session) => {
|
||||
invalidateSessionListCaches(queryClient);
|
||||
|
||||
@@ -3,21 +3,29 @@ import { openDialogParam, useDialogParam } from './useDialogParam'
|
||||
import { useUrlParams } from './useUrlParams'
|
||||
|
||||
const TERMINAL_DIALOG = 'terminal'
|
||||
const TERMINAL_DIALOG_PARAMS = ['terminal'] as const
|
||||
const TERMINAL_DIALOG_PARAMS = ['terminal', 'terminalDirectory'] as const
|
||||
|
||||
export function useTerminalDialogParam(): [boolean, (open: boolean) => void] {
|
||||
return useDialogParam(TERMINAL_DIALOG, TERMINAL_DIALOG_PARAMS)
|
||||
}
|
||||
|
||||
/**
|
||||
* The directory the terminal dialog was opened for, such as a repo worktree; null means the repo itself.
|
||||
*/
|
||||
export function useTerminalDirectoryParam(): string | null {
|
||||
const { searchParams } = useUrlParams()
|
||||
return searchParams.get('terminalDirectory')
|
||||
}
|
||||
|
||||
export function useOpenTerminal(): (
|
||||
terminalId: string,
|
||||
terminalId: string | null,
|
||||
extraParams?: Record<string, string>,
|
||||
) => void {
|
||||
const { updateParams } = useUrlParams()
|
||||
|
||||
return useCallback(
|
||||
(terminalId: string, extraParams?: Record<string, string>) => {
|
||||
openDialogParam(updateParams, TERMINAL_DIALOG, { terminal: terminalId, ...extraParams })
|
||||
(terminalId: string | null, extraParams?: Record<string, string>) => {
|
||||
openDialogParam(updateParams, TERMINAL_DIALOG, { ...(terminalId ? { terminal: terminalId } : {}), ...extraParams })
|
||||
},
|
||||
[updateParams],
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { createRepoWorkspace, deleteRepoWorkspace, getRepoSiblings, type RepoSibling } from '@/api/repos'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import type { CreateRepoWorkspaceRequest } from '@opencode-manager/shared/types'
|
||||
|
||||
export function repoSiblingsQueryKey(repoId: number | undefined) {
|
||||
return ['repo', 'siblings', repoId] as const
|
||||
@@ -24,22 +25,25 @@ export function useDeleteRepoWorkspaces(repoId: number | undefined) {
|
||||
const results = await Promise.allSettled(
|
||||
directories.map((directory) => deleteRepoWorkspace(repoId, directory)),
|
||||
)
|
||||
const failed = results.filter((result) => result.status === 'rejected').length
|
||||
return { total: directories.length, failed }
|
||||
const failures = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []))
|
||||
return { total: directories.length, failed: failures.length, firstError: failures[0] instanceof Error ? failures[0].message : null }
|
||||
},
|
||||
onSuccess: ({ total, failed }) => {
|
||||
onSuccess: ({ total, failed, firstError }) => {
|
||||
queryClient.invalidateQueries({ queryKey: repoSiblingsQueryKey(repoId) })
|
||||
queryClient.invalidateQueries({ queryKey: ['schedule-worktrees'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
|
||||
const deleted = total - failed
|
||||
const reason = firstError ? `: ${firstError}` : ''
|
||||
if (failed === 0) {
|
||||
showToast.success(deleted === 1 ? 'Workspace deleted' : `${deleted} workspaces deleted`)
|
||||
showToast.success(deleted === 1 ? 'Worktree deleted' : `${deleted} worktrees deleted`)
|
||||
} else if (deleted === 0) {
|
||||
showToast.error('Failed to delete workspaces')
|
||||
showToast.error(`Failed to delete worktrees${reason}`)
|
||||
} else {
|
||||
showToast.error(`Deleted ${deleted}, failed ${failed}`)
|
||||
showToast.error(`Deleted ${deleted}, failed ${failed}${reason}`)
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to delete workspaces')
|
||||
showToast.error('Failed to delete worktrees')
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -48,16 +52,16 @@ export function useCreateRepoWorkspace(repoId: number | undefined) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
mutationFn: async (request: CreateRepoWorkspaceRequest = {}) => {
|
||||
if (!repoId) throw new Error('Repo id is required')
|
||||
return createRepoWorkspace(repoId)
|
||||
return createRepoWorkspace(repoId, request)
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: repoSiblingsQueryKey(repoId) })
|
||||
showToast.success('Workspace created')
|
||||
showToast.success('Worktree created')
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to create workspace')
|
||||
onError: (error) => {
|
||||
showToast.error(`Failed to create worktree: ${error.message}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -11,9 +11,11 @@ import {
|
||||
listAllScheduleRuns,
|
||||
listAllSchedules,
|
||||
listRepoScheduleRuns,
|
||||
listScheduleWorktrees,
|
||||
listUnreadScheduleRuns,
|
||||
markAllScheduleRunsViewed,
|
||||
markScheduleRunViewed,
|
||||
removeScheduleWorktrees,
|
||||
runRepoSchedule,
|
||||
updateRepoSchedule,
|
||||
} from '@/api/schedules'
|
||||
@@ -228,6 +230,7 @@ export function useClearRepoScheduleRuns() {
|
||||
onSuccess: (result, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', variables.repoId, variables.jobId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['schedule-worktrees', variables.repoId, variables.jobId] })
|
||||
showToast.success(result.cleared > 0 ? `Cleared ${result.cleared} run${result.cleared === 1 ? '' : 's'}` : 'No runs to clear')
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
@@ -246,6 +249,7 @@ export function useDeleteRepoScheduleRun() {
|
||||
onSuccess: (_data, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', variables.repoId, variables.jobId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['all-schedule-runs'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['schedule-worktrees', variables.repoId, variables.jobId] })
|
||||
showToast.success('Run deleted')
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
@@ -253,3 +257,35 @@ export function useDeleteRepoScheduleRun() {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function useScheduleWorktrees(repoId: number | undefined, jobId: number | null) {
|
||||
return useQuery({
|
||||
queryKey: ['schedule-worktrees', repoId, jobId],
|
||||
queryFn: async () => {
|
||||
const response = await listScheduleWorktrees(repoId!, jobId!)
|
||||
return response.worktrees
|
||||
},
|
||||
enabled: repoId !== undefined && jobId !== null,
|
||||
refetchInterval: jobId !== null ? 10000 : false,
|
||||
})
|
||||
}
|
||||
|
||||
export function useRemoveScheduleWorktrees() {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ repoId, jobId, worktreePath }: { repoId: number; jobId: number; worktreePath?: string }) => {
|
||||
return removeScheduleWorktrees(repoId, jobId, worktreePath)
|
||||
},
|
||||
onSuccess: (result, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['schedule-worktrees', variables.repoId, variables.jobId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', variables.repoId, variables.jobId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['all-schedules'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['repo', 'siblings'] })
|
||||
showToast.success(`Removed ${result.removed} worktree${result.removed === 1 ? '' : 's'}`)
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
showToast.error(`Failed to remove worktree: ${error instanceof Error ? error.message : String(error)}`)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { useAllSchedules, useAllScheduleRuns, useCancelRepoScheduleRun, useUnrea
|
||||
import { useDeleteRepoSchedule, useRunRepoSchedule, useUpdateRepoSchedule, useCreateRepoSchedule } from '@/hooks/useSchedules'
|
||||
import { ScheduleJobDialog, PromptsTab, ScheduleJobsTable, ScheduleListToolbar, ScheduleRunDrawer, ScheduleRunsTable } from '@/components/schedules'
|
||||
import type { CreateScheduleJobRequest } from '@opencode-manager/shared/types'
|
||||
import { matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
|
||||
import { DELETE_SCHEDULE_DESCRIPTION, matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
|
||||
import { Header } from '@/components/ui/header'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScheduleReportsBell } from '@/components/notifications/ScheduleReportsBell'
|
||||
@@ -779,7 +779,7 @@ export function GlobalSchedules() {
|
||||
onConfirm={handleDelete}
|
||||
onCancel={closeDialog}
|
||||
title="Delete Schedule"
|
||||
description="This removes the job definition and all recorded run history for it."
|
||||
description={DELETE_SCHEDULE_DESCRIPTION}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
|
||||
+130
-129
@@ -1,8 +1,8 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useMemo, useState, type FormEvent } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { getRepo, workspaceLabel } from "@/api/repos";
|
||||
import { SessionList } from "@/components/session/SessionList";
|
||||
import { getRepo } from "@/api/repos";
|
||||
import { SessionList, type SessionListRenderArgs } from "@/components/session/SessionList";
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
|
||||
@@ -18,11 +18,14 @@ import { useRepoActivity } from "@/hooks/useRepoActivity";
|
||||
import { useCreateRepoWorkspace, useDeleteRepoWorkspaces, useRepoSiblings } from "@/hooks/useRepoSiblings";
|
||||
import { useSSE } from "@/hooks/useSSE";
|
||||
import { useDialogParam } from "@/hooks/useDialogParam";
|
||||
import { useOpenTerminal, useTerminalDialogParam } from "@/hooks/useOpenTerminal";
|
||||
import { useOpenTerminal, useTerminalDialogParam, useTerminalDirectoryParam } from "@/hooks/useOpenTerminal";
|
||||
import { useWorktreeTab } from "@/hooks/useWorktreeTab";
|
||||
import { WorktreeTabs } from "@/components/repo/WorktreeTabs";
|
||||
import { WorkspaceManager } from "@/components/repo/WorkspaceManager";
|
||||
import { WorktreeSessionGroups } from "@/components/repo/WorktreeSessionGroups";
|
||||
import { useAllSchedules } from "@/hooks/useSchedules";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { GitBranch, Plus, Loader2, Layers, Columns3 } from "lucide-react";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
@@ -30,7 +33,7 @@ import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
import { getRepoDisplayName } from "@/lib/utils";
|
||||
import { notifyWorktreeSetup } from "@/lib/worktreeSetup";
|
||||
import { isWorktreeSibling } from "@opencode-manager/shared/utils";
|
||||
import { getRepoDirectoryNameError, isWorktreeSibling } from "@opencode-manager/shared/utils";
|
||||
|
||||
export function RepoDetail() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
@@ -46,10 +49,9 @@ export function RepoDetail() {
|
||||
const [resetPermissionsOpen, setResetPermissionsOpen] = useDialogParam('resetPermissions');
|
||||
const [multiRunOpen, setMultiRunOpen] = useDialogParam('multiRun');
|
||||
const [createWorkspaceOpen, setCreateWorkspaceOpen] = useState(false);
|
||||
const [workspaceSelectorOpen, setWorkspaceSelectorOpen] = useState(false);
|
||||
const [activeWorkspaceDirectory, setActiveWorkspaceDirectory] = useState<string | undefined>();
|
||||
const { activeTab, setActiveTab } = useWorktreeTab();
|
||||
const openTerminal = useOpenTerminal();
|
||||
const terminalDirectory = useTerminalDirectoryParam();
|
||||
|
||||
const { data: repo, isLoading: repoLoading } = useQuery({
|
||||
queryKey: ["repo", repoId],
|
||||
@@ -73,6 +75,15 @@ export function RepoDetail() {
|
||||
[workspaceSiblings],
|
||||
);
|
||||
|
||||
const { data: allSchedules } = useAllSchedules();
|
||||
const scheduleNames = useMemo(() => {
|
||||
const names: Record<number, string> = {};
|
||||
(allSchedules ?? []).forEach((job) => {
|
||||
if (job.repoId === repoId) names[job.id] = job.name;
|
||||
});
|
||||
return names;
|
||||
}, [allSchedules, repoId]);
|
||||
|
||||
const baseDirectory = repo?.fullPath;
|
||||
const subscriptionDirectories = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
@@ -81,89 +92,62 @@ export function RepoDetail() {
|
||||
return Array.from(set);
|
||||
}, [baseDirectory, workspaceDirectories]);
|
||||
|
||||
useEffect(() => {
|
||||
if (workspaceDirectories.length === 0) {
|
||||
setActiveWorkspaceDirectory(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
setActiveWorkspaceDirectory((current) => (
|
||||
current && workspaceDirectories.includes(current) ? current : workspaceDirectories[0]
|
||||
));
|
||||
}, [workspaceDirectories]);
|
||||
|
||||
const workspaceComposerDirectory = activeWorkspaceDirectory ?? workspaceDirectories[0];
|
||||
const sessionListDirectories = activeTab === 'workspaces' ? workspaceDirectories : (baseDirectory ? [baseDirectory] : []);
|
||||
const composerDirectory = activeTab === 'workspaces' ? workspaceComposerDirectory : baseDirectory;
|
||||
|
||||
const directoryLabels = useMemo(() => {
|
||||
const labels: Record<string, string> = {};
|
||||
workspaceSiblings.forEach((sibling) => {
|
||||
if (sibling.fullPath) {
|
||||
labels[sibling.fullPath] = workspaceLabel(sibling);
|
||||
}
|
||||
});
|
||||
return labels;
|
||||
}, [workspaceSiblings]);
|
||||
|
||||
const activeWorkspaceLabel = activeWorkspaceDirectory ? directoryLabels[activeWorkspaceDirectory] : undefined;
|
||||
const showWorktrees = activeTab === 'workspaces';
|
||||
const sessionListDirectories = showWorktrees ? workspaceDirectories : (baseDirectory ? [baseDirectory] : []);
|
||||
|
||||
useSSE(subscriptionDirectories);
|
||||
|
||||
const sessionUrl = useCallback(
|
||||
(sessionId: string) => {
|
||||
(sessionId: string, inWorktree: boolean) => {
|
||||
const base = `/repos/${repoId}/sessions/${sessionId}`;
|
||||
return activeTab === 'workspaces' ? `${base}?repoTab=workspaces` : base;
|
||||
return inWorktree ? `${base}?repoTab=workspaces` : base;
|
||||
},
|
||||
[repoId, activeTab],
|
||||
[repoId],
|
||||
);
|
||||
|
||||
const createSessionMutation = useCreateSession(composerDirectory, (session) => {
|
||||
navigate(sessionUrl(session.id));
|
||||
});
|
||||
const createSessionMutation = useCreateSession(baseDirectory);
|
||||
|
||||
const handleCreateSession = async (options?: {
|
||||
agentSlug?: string;
|
||||
promptSlug?: string;
|
||||
}) => {
|
||||
if (activeTab === 'workspaces' && !workspaceComposerDirectory) {
|
||||
setCreateWorkspaceOpen(true);
|
||||
return;
|
||||
}
|
||||
|
||||
await createSessionMutation.mutateAsync({
|
||||
agent: options?.agentSlug,
|
||||
const handleCreateSession = (directory = baseDirectory) => {
|
||||
createSessionMutation.mutate({ directory }, {
|
||||
onSuccess: (session) => navigate(sessionUrl(session.id, directory !== baseDirectory)),
|
||||
});
|
||||
};
|
||||
|
||||
const handleCreateWorkspace = async () => {
|
||||
const workspace = await createWorkspace.mutateAsync();
|
||||
if (workspace.directory) {
|
||||
setActiveWorkspaceDirectory(workspace.directory);
|
||||
}
|
||||
setCreateWorkspaceOpen(false);
|
||||
notifyWorktreeSetup(workspace.worktreeSetup);
|
||||
if (workspace.worktreeSetup?.status === 'started') {
|
||||
const terminalId = workspace.worktreeSetup.terminal.id;
|
||||
openTerminal(terminalId, { repoTab: 'workspaces' });
|
||||
return;
|
||||
}
|
||||
setActiveTab('workspaces');
|
||||
};
|
||||
|
||||
const handleOpenWorkspaceSelector = () => {
|
||||
if (workspaceSiblings.length === 0) {
|
||||
setCreateWorkspaceOpen(true);
|
||||
return;
|
||||
}
|
||||
setActiveTab('workspaces');
|
||||
setWorkspaceSelectorOpen(true);
|
||||
const handleCreateWorkspace = (name: string) => {
|
||||
createWorkspace.mutate(name ? { name } : {}, {
|
||||
onSuccess: (workspace) => {
|
||||
setCreateWorkspaceOpen(false);
|
||||
notifyWorktreeSetup(workspace.worktreeSetup);
|
||||
if (workspace.worktreeSetup?.status === 'started') {
|
||||
const terminalId = workspace.worktreeSetup.terminal.id;
|
||||
openTerminal(terminalId, { repoTab: 'workspaces', ...(workspace.directory ? { terminalDirectory: workspace.directory } : {}) });
|
||||
return;
|
||||
}
|
||||
setActiveTab('workspaces');
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleSelectSession = (sessionId: string) => {
|
||||
navigate(sessionUrl(sessionId));
|
||||
navigate(sessionUrl(sessionId, showWorktrees));
|
||||
};
|
||||
|
||||
const renderWorktreeGroups = ({ sessions, searchQuery, renderSessionCard }: SessionListRenderArgs) => (
|
||||
<WorktreeSessionGroups
|
||||
repoId={repoId}
|
||||
worktrees={workspaceSiblings}
|
||||
sessions={sessions}
|
||||
searchQuery={searchQuery}
|
||||
scheduleNames={scheduleNames}
|
||||
renderSessionCard={renderSessionCard}
|
||||
onNewSession={handleCreateSession}
|
||||
onOpenTerminal={(directory) => openTerminal(null, { repoTab: "workspaces", terminalDirectory: directory })}
|
||||
onCreateWorktree={() => setCreateWorkspaceOpen(true)}
|
||||
onDelete={(directories) => deleteWorkspaces.mutate(directories)}
|
||||
isDeleting={deleteWorkspaces.isPending}
|
||||
/>
|
||||
);
|
||||
|
||||
if (repoLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-background">
|
||||
@@ -218,7 +202,7 @@ export function RepoDetail() {
|
||||
</div>
|
||||
<Header.Actions>
|
||||
<div className="flex items-center gap-1">
|
||||
<ProjectActionsMenu repoId={repoId} directory={composerDirectory} />
|
||||
<ProjectActionsMenu repoId={repoId} directory={baseDirectory} />
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
<Button
|
||||
@@ -257,29 +241,21 @@ export function RepoDetail() {
|
||||
value={activeTab}
|
||||
onValueChange={setActiveTab}
|
||||
baseLabel={currentBranch}
|
||||
activeWorkspaceLabel={activeWorkspaceLabel}
|
||||
onCreateWorkspace={() => setCreateWorkspaceOpen(true)}
|
||||
onWorkspaceMenu={handleOpenWorkspaceSelector}
|
||||
/>
|
||||
|
||||
<WorkspaceManager
|
||||
open={workspaceSelectorOpen}
|
||||
onOpenChange={setWorkspaceSelectorOpen}
|
||||
workspaces={workspaceSiblings}
|
||||
activeWorkspaceDirectory={activeWorkspaceDirectory}
|
||||
onActiveWorkspaceChange={setActiveWorkspaceDirectory}
|
||||
onCreateWorkspace={() => setCreateWorkspaceOpen(true)}
|
||||
onDelete={(directories) => deleteWorkspaces.mutate(directories)}
|
||||
isDeleting={deleteWorkspaces.isPending}
|
||||
/>
|
||||
|
||||
<div className="flex-1 flex flex-col min-h-0">
|
||||
{sessionListDirectories.length > 0 && (
|
||||
{showWorktrees && workspaceSiblings.length === 0 ? (
|
||||
<div className="px-4 pt-4">
|
||||
{renderWorktreeGroups({ sessions: [], searchQuery: "", renderSessionCard: () => null })}
|
||||
</div>
|
||||
) : sessionListDirectories.length > 0 && (
|
||||
<SessionList
|
||||
key={showWorktrees ? "worktrees" : "repo"}
|
||||
directories={sessionListDirectories}
|
||||
directoryLabels={activeTab === 'workspaces' ? directoryLabels : undefined}
|
||||
createDirectory={activeTab === 'workspaces' ? workspaceComposerDirectory : baseDirectory}
|
||||
createDirectory={baseDirectory}
|
||||
onSelectSession={handleSelectSession}
|
||||
renderSessions={showWorktrees ? renderWorktreeGroups : undefined}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -303,12 +279,12 @@ export function RepoDetail() {
|
||||
<RepoMcpDialog
|
||||
open={mcpDialogOpen}
|
||||
onOpenChange={setMcpDialogOpen}
|
||||
directory={composerDirectory}
|
||||
directory={baseDirectory}
|
||||
/>
|
||||
|
||||
<RepoActionsDialog
|
||||
repoId={repoId}
|
||||
directory={composerDirectory}
|
||||
directory={baseDirectory}
|
||||
open={actionsDialogOpen}
|
||||
onOpenChange={setActionsDialogOpen}
|
||||
/>
|
||||
@@ -329,7 +305,7 @@ export function RepoDetail() {
|
||||
|
||||
<TerminalPanel
|
||||
repoId={repoId}
|
||||
directory={composerDirectory}
|
||||
directory={terminalDirectory ?? baseDirectory}
|
||||
isOpen={terminalOpen}
|
||||
onClose={() => setTerminalOpen(false)}
|
||||
/>
|
||||
@@ -337,7 +313,7 @@ export function RepoDetail() {
|
||||
<PreviewPanel
|
||||
isOpen={previewOpen}
|
||||
onClose={() => setPreviewOpen(false)}
|
||||
directory={composerDirectory}
|
||||
directory={baseDirectory}
|
||||
/>
|
||||
|
||||
<ResetPermissionsDialog
|
||||
@@ -360,47 +336,72 @@ export function RepoDetail() {
|
||||
interface CreateWorkspaceDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCreate: () => Promise<void>;
|
||||
onCreate: (name: string) => void;
|
||||
isCreating: boolean;
|
||||
}
|
||||
|
||||
function CreateWorkspaceDialog({ open, onOpenChange, onCreate, isCreating }: CreateWorkspaceDialogProps) {
|
||||
const [name, setName] = useState("");
|
||||
const trimmedName = name.trim();
|
||||
const nameError = trimmedName ? getRepoDirectoryNameError(trimmedName) : null;
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next) setName("");
|
||||
onOpenChange(next);
|
||||
};
|
||||
|
||||
const handleSubmit = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (nameError || isCreating) return;
|
||||
onCreate(trimmedName);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-[420px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Layers className="h-4 w-4 text-primary" />
|
||||
Create Workspace
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create an OpenCode worktree workspace for this repository.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="rounded-md border border-border bg-muted/30 p-3 text-sm">
|
||||
<div className="flex items-center gap-2 font-medium">
|
||||
<GitBranch className="h-4 w-4 text-primary" />
|
||||
Worktree
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Layers className="h-4 w-4 text-primary" />
|
||||
Create Worktree
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
OpenCode creates a git worktree of this repository from the current commit.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="worktree-name">Name</Label>
|
||||
<Input
|
||||
id="worktree-name"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
placeholder="Generated if empty"
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
disabled={isCreating}
|
||||
aria-invalid={nameError ? true : undefined}
|
||||
aria-describedby="worktree-name-hint"
|
||||
/>
|
||||
<p id="worktree-name-hint" className={`text-xs ${nameError ? "text-destructive" : "text-muted-foreground"}`}>
|
||||
{nameError ?? "Used as the folder name and its label under Worktrees. If the folder already exists, a number is added."}
|
||||
</p>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
OpenCode will create and manage a git worktree workspace.
|
||||
</p>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isCreating}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={() => { void onCreate(); }} disabled={isCreating} className="bg-primary hover:bg-primary-hover text-primary-foreground">
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
'Create Workspace'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={isCreating}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={isCreating || Boolean(nameError)} className="bg-primary hover:bg-primary-hover text-primary-foreground">
|
||||
{isCreating ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Creating...
|
||||
</>
|
||||
) : (
|
||||
'Create Worktree'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -17,7 +17,7 @@ import { useRepoActivity } from '@/hooks/useRepoActivity'
|
||||
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
|
||||
import { useScheduleUrlState } from '@/hooks/useScheduleUrlState'
|
||||
import { ScheduleJobDialog, ScheduleJobsTable, ScheduleListToolbar, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
|
||||
import { matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
|
||||
import { DELETE_SCHEDULE_DESCRIPTION, matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils'
|
||||
import type { ScheduleJobWithRepo } from '@/api/schedules'
|
||||
import { Header } from '@/components/ui/header'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -370,7 +370,7 @@ export function Schedules() {
|
||||
onConfirm={handleDelete}
|
||||
onCancel={() => closeDialog()}
|
||||
title="Delete Schedule"
|
||||
description="This removes the job definition and all recorded run history for it."
|
||||
description={DELETE_SCHEDULE_DESCRIPTION}
|
||||
isDeleting={deleteMutation.isPending}
|
||||
/>
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@ const mocks = vi.hoisted(() => ({
|
||||
useRepoActivity: vi.fn(),
|
||||
useSSE: vi.fn(),
|
||||
useCreateSession: vi.fn(),
|
||||
createWorkspaceMutateAsync: vi.fn(),
|
||||
createWorkspaceMutate: vi.fn(),
|
||||
createWorkspaceResult: vi.fn(),
|
||||
showToastInfo: vi.fn(),
|
||||
showToastWarning: vi.fn(),
|
||||
}))
|
||||
@@ -63,7 +64,7 @@ vi.mock('@/components/repo/ProjectActionsMenu', () => ({ ProjectActionsMenu: ()
|
||||
vi.mock('@/components/repo/RepoActionsDialog', () => ({ RepoActionsDialog: () => null }))
|
||||
vi.mock('@/components/repo/RepoSkillsDialog', () => ({ RepoSkillsDialog: () => null }))
|
||||
vi.mock('@/components/source-control', () => ({ SourceControlPanel: () => null }))
|
||||
vi.mock('@/components/repo/WorkspaceManager', () => ({ WorkspaceManager: () => null }))
|
||||
vi.mock('@/hooks/useSchedules', () => ({ useAllSchedules: () => ({ data: [] }) }))
|
||||
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: () => null }))
|
||||
vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null }))
|
||||
|
||||
@@ -106,12 +107,15 @@ async function startWorkspaceCreation() {
|
||||
const user = userEvent.setup()
|
||||
renderRepoDetail()
|
||||
await user.click(await screen.findByRole('button', { name: 'New workspace' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Create Workspace' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Create Worktree' }))
|
||||
}
|
||||
|
||||
describe('RepoDetail worktree setup', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.createWorkspaceMutate.mockImplementation((_request: unknown, options: { onSuccess: (value: unknown) => void }) => {
|
||||
options.onSuccess(mocks.createWorkspaceResult())
|
||||
})
|
||||
mocks.getRepo.mockResolvedValue(baseRepo)
|
||||
mocks.useRepoSiblings.mockReturnValue({ data: siblingsData })
|
||||
mocks.useDeleteRepoWorkspaces.mockReturnValue({ mutate: vi.fn(), isPending: false })
|
||||
@@ -120,10 +124,10 @@ describe('RepoDetail worktree setup', () => {
|
||||
|
||||
it('switches to the new workspace terminal when setup starts from the repo tab', async () => {
|
||||
mocks.useCreateRepoWorkspace.mockReturnValue({
|
||||
mutateAsync: mocks.createWorkspaceMutateAsync,
|
||||
mutate: mocks.createWorkspaceMutate,
|
||||
isPending: false,
|
||||
})
|
||||
mocks.createWorkspaceMutateAsync.mockResolvedValue({
|
||||
mocks.createWorkspaceResult.mockReturnValue({
|
||||
directory: newWorkspaceDirectory,
|
||||
worktreeSetup: {
|
||||
status: 'started',
|
||||
@@ -154,10 +158,10 @@ describe('RepoDetail worktree setup', () => {
|
||||
|
||||
it('stays on the workspace tab without a terminal when setup does not start', async () => {
|
||||
mocks.useCreateRepoWorkspace.mockReturnValue({
|
||||
mutateAsync: mocks.createWorkspaceMutateAsync,
|
||||
mutate: mocks.createWorkspaceMutate,
|
||||
isPending: false,
|
||||
})
|
||||
mocks.createWorkspaceMutateAsync.mockResolvedValue({
|
||||
mocks.createWorkspaceResult.mockReturnValue({
|
||||
directory: newWorkspaceDirectory,
|
||||
worktreeSetup: { status: 'none' },
|
||||
})
|
||||
@@ -168,9 +172,25 @@ describe('RepoDetail worktree setup', () => {
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('repoTab=workspaces'),
|
||||
)
|
||||
expect(screen.getByTestId('location')).not.toHaveTextContent('dialog=terminal')
|
||||
expect(screen.getByTestId('terminal-panel')).toHaveAttribute(
|
||||
'data-directory',
|
||||
newWorkspaceDirectory,
|
||||
)
|
||||
expect(screen.getByTestId('terminal-panel')).toHaveAttribute('data-open', 'false')
|
||||
})
|
||||
|
||||
it('sends the typed worktree name and blocks names that are not a single folder', async () => {
|
||||
mocks.useCreateRepoWorkspace.mockReturnValue({ mutate: mocks.createWorkspaceMutate, isPending: false })
|
||||
mocks.createWorkspaceResult.mockReturnValue({ directory: newWorkspaceDirectory, worktreeSetup: { status: 'none' } })
|
||||
const user = userEvent.setup()
|
||||
renderRepoDetail()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'New workspace' }))
|
||||
const nameInput = await screen.findByLabelText('Name')
|
||||
await user.type(nameInput, '../escape')
|
||||
expect(screen.getByRole('button', { name: 'Create Worktree' })).toBeDisabled()
|
||||
expect(screen.getByText('Directory name cannot contain dot-dot path segments')).toBeInTheDocument()
|
||||
|
||||
await user.clear(nameInput)
|
||||
await user.type(nameInput, 'feature-login')
|
||||
await user.click(screen.getByRole('button', { name: 'Create Worktree' }))
|
||||
|
||||
expect(mocks.createWorkspaceMutate).toHaveBeenCalledWith({ name: 'feature-login' }, expect.anything())
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from 'zod'
|
||||
import { getRepoDirectoryNameError } from '../utils/repo'
|
||||
|
||||
export const RepoStatusSchema = z.enum(['cloning', 'ready', 'error'])
|
||||
|
||||
@@ -54,6 +55,13 @@ export const UpdateRepoRequestSchema = z.object({
|
||||
name: z.string().trim().max(100).nullable(),
|
||||
})
|
||||
|
||||
export const CreateRepoWorkspaceRequestSchema = z.object({
|
||||
name: z.string().trim().optional().superRefine((name, ctx) => {
|
||||
const error = name ? getRepoDirectoryNameError(name) : null
|
||||
if (error) ctx.addIssue({ code: 'custom', message: error })
|
||||
}),
|
||||
})
|
||||
|
||||
export const DeleteRepoRequestSchema = z.object({
|
||||
deleteBranch: z.enum(['none', 'local', 'local-and-remote']).default('none'),
|
||||
})
|
||||
|
||||
@@ -9,6 +9,32 @@ export type ScheduleRunStatus = z.infer<typeof ScheduleRunStatusSchema>
|
||||
export const ScheduleModeSchema = z.enum(['interval', 'cron'])
|
||||
export type ScheduleMode = z.infer<typeof ScheduleModeSchema>
|
||||
|
||||
/**
|
||||
* Where a scheduled run executes. `worktree` gives every run a fresh worktree that is
|
||||
* removed when the run ends, `kept-worktree` keeps each run's worktree afterwards,
|
||||
* `shared-worktree` reuses one worktree and branch for every run of the schedule, and
|
||||
* `repo` runs directly in the repository checkout without isolation.
|
||||
*/
|
||||
export const ScheduleWorkspaceModeSchema = z.enum(['worktree', 'kept-worktree', 'shared-worktree', 'repo'])
|
||||
export type ScheduleWorkspaceMode = z.infer<typeof ScheduleWorkspaceModeSchema>
|
||||
|
||||
/**
|
||||
* A schedule worktree that still exists on disk. `runId` is null for the schedule's
|
||||
* shared worktree, and `inUse` is true while a running run is working in it.
|
||||
*/
|
||||
export const ScheduleWorktreeSchema = z.object({
|
||||
worktreePath: z.string(),
|
||||
branch: z.string(),
|
||||
runId: z.number().nullable(),
|
||||
inUse: z.boolean(),
|
||||
})
|
||||
export type ScheduleWorktree = z.infer<typeof ScheduleWorktreeSchema>
|
||||
|
||||
export const RemoveScheduleWorktreesRequestSchema = z.object({
|
||||
worktreePath: z.string().min(1).optional(),
|
||||
})
|
||||
export type RemoveScheduleWorktreesRequest = z.infer<typeof RemoveScheduleWorktreesRequestSchema>
|
||||
|
||||
export const ScheduleSkillMetadataSchema = z.object({
|
||||
skillSlugs: z.array(z.string().min(1).max(100)).default([]),
|
||||
notes: z.string().max(2000).optional(),
|
||||
@@ -153,6 +179,7 @@ export const ScheduleJobSchema = z.object({
|
||||
permissionConfig: SchedulePermissionConfigSchema.nullable(),
|
||||
mcpServers: ScheduleMcpServersSchema,
|
||||
branch: z.string().nullable(),
|
||||
workspaceMode: ScheduleWorkspaceModeSchema,
|
||||
createdAt: z.number(),
|
||||
updatedAt: z.number(),
|
||||
lastRunAt: z.number().nullable(),
|
||||
@@ -192,6 +219,7 @@ const ScheduleJobBaseRequestSchema = z.object({
|
||||
permissionConfig: SchedulePermissionConfigSchema.nullable().optional(),
|
||||
mcpServers: ScheduleMcpServersSchema.optional(),
|
||||
branch: z.string().min(1).max(200).nullable().optional(),
|
||||
workspaceMode: ScheduleWorkspaceModeSchema.optional(),
|
||||
})
|
||||
|
||||
export const CreateScheduleJobRequestSchema = z.discriminatedUnion('scheduleMode', [
|
||||
@@ -222,6 +250,7 @@ export const UpdateScheduleJobRequestSchema = z.object({
|
||||
permissionConfig: SchedulePermissionConfigSchema.nullable().optional(),
|
||||
mcpServers: ScheduleMcpServersSchema.optional(),
|
||||
branch: z.string().min(1).max(200).nullable().optional(),
|
||||
workspaceMode: ScheduleWorkspaceModeSchema.optional(),
|
||||
})
|
||||
export type UpdateScheduleJobRequest = z.infer<typeof UpdateScheduleJobRequestSchema>
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
DiscoverReposRequestSchema,
|
||||
DiscoverReposResponseSchema,
|
||||
UpdateRepoRequestSchema,
|
||||
CreateRepoWorkspaceRequestSchema,
|
||||
DeleteRepoRequestSchema,
|
||||
DeleteRepoResultSchema,
|
||||
RepoStatusSchema,
|
||||
@@ -89,6 +90,7 @@ export type DiscoverReposRequest = z.infer<typeof DiscoverReposRequestSchema>
|
||||
export type DiscoverReposResponse = z.infer<typeof DiscoverReposResponseSchema>
|
||||
export type RepoStatus = z.infer<typeof RepoStatusSchema>
|
||||
export type UpdateRepoRequest = z.infer<typeof UpdateRepoRequestSchema>
|
||||
export type CreateRepoWorkspaceRequest = z.infer<typeof CreateRepoWorkspaceRequestSchema>
|
||||
export type DeleteRepoRequest = z.infer<typeof DeleteRepoRequestSchema>
|
||||
export type DeleteRepoResult = z.infer<typeof DeleteRepoResultSchema>
|
||||
export type AssistantModeStatus = z.infer<typeof AssistantModeStatusSchema>
|
||||
@@ -152,6 +154,9 @@ export type {
|
||||
|
||||
export type {
|
||||
ScheduleMode,
|
||||
ScheduleWorkspaceMode,
|
||||
ScheduleWorktree,
|
||||
RemoveScheduleWorktreesRequest,
|
||||
SchedulePermissionConfig,
|
||||
ScheduleRunTriggerSource,
|
||||
ScheduleRunStatus,
|
||||
|
||||
@@ -87,8 +87,24 @@ export function getBranchNameError(name: string): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
export function isWorktreeSibling(sibling: { worktreeStrategy?: string }): boolean {
|
||||
return sibling.worktreeStrategy !== undefined
|
||||
/**
|
||||
* Who owns a repo worktree: OpenCode, a schedule, or nobody (a plain git worktree).
|
||||
*/
|
||||
export type RepoWorktreeSource = 'opencode' | 'schedule' | 'git'
|
||||
|
||||
/**
|
||||
* The schedule a worktree belongs to. `runId` is null for the schedule's shared worktree,
|
||||
* and `inUse` is true while a running run works in it.
|
||||
*/
|
||||
export interface RepoWorktreeSchedule {
|
||||
repoId: number
|
||||
jobId: number
|
||||
runId: number | null
|
||||
inUse: boolean
|
||||
}
|
||||
|
||||
export function isWorktreeSibling(sibling: { worktreeSource?: RepoWorktreeSource }): boolean {
|
||||
return sibling.worktreeSource !== undefined
|
||||
}
|
||||
|
||||
export function getRepoBaseDirectoryName(repo: { localPath: string; branch?: string; isWorktree?: boolean }): string {
|
||||
|
||||
Reference in new issue
Block a user