From 26ff08d8919af1b0521c092ab3d36502e07b01a8 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:02:29 -0400 Subject: [PATCH] feat(schedules): require worktrees and choose commit or discard on removal Drop the repo workspace mode so every scheduled run executes in a worktree. Clearing run history or deleting a run now asks whether to commit pending changes and keep the run branches, or force-remove the worktrees and delete the branches. Sibling repo listings carry the schedule name, and the repo detail workspace view subscribes to schedule worktree sessions only while expanded. Also unify schedule worktree path/branch helpers, refuse a run branch already checked out elsewhere, and clean up terminals when a worktree is removed. --- backend/src/db/schedules.ts | 20 +- backend/src/index.ts | 7 + backend/src/routes/repos.test.ts | 64 ++++--- backend/src/routes/repos.ts | 2 +- backend/src/routes/schedules.ts | 16 +- backend/src/routes/settings.test.ts | 36 +--- backend/src/services/assistant-mode.ts | 2 +- .../services/opencode-manager-tool-plugin.ts | 1 + backend/src/services/repo-workspace.ts | 21 ++- backend/src/services/repo.ts | 56 ++---- .../src/services/schedule-worktree-paths.ts | 58 ++++-- backend/src/services/schedule-worktree.ts | 117 ++++++++---- backend/src/services/schedules.ts | 99 ++++++---- backend/test/db/schedules.test.ts | 18 +- backend/test/index.test.ts | 1 + backend/test/routes/repos.test.ts | 2 +- backend/test/routes/schedules.test.ts | 40 ++++ .../opencode-manager-tool-plugin.test.ts | 15 ++ backend/test/services/repo-git.test.ts | 43 ++++- backend/test/services/repo-workspace.test.ts | 20 +- backend/test/services/repo.test.ts | 7 +- .../test/services/schedule-worktree.test.ts | 82 ++++++++- backend/test/services/schedules.test.ts | 134 ++++++++++++-- frontend/src/api/repos.ts | 14 +- frontend/src/api/schedules.ts | 16 +- .../repo/WorktreeSessionGroups.test.tsx | 29 ++- .../components/repo/WorktreeSessionGroups.tsx | 89 +++++++-- .../src/components/repo/WorktreeTabs.test.tsx | 1 - .../src/components/schedules/GeneralTab.tsx | 30 ++- .../src/components/schedules/JobDetailTab.tsx | 3 +- .../ScheduleRunRemovalDialog.test.tsx | 47 +++++ .../schedules/ScheduleRunRemovalDialog.tsx | 100 ++++++++++ frontend/src/components/schedules/index.ts | 1 + .../components/schedules/schedule-utils.ts | 5 - .../src/components/session/SessionCard.tsx | 8 - .../src/components/session/SessionList.tsx | 3 - frontend/src/hooks/useSchedules.ts | 12 +- .../src/lib/schedules/schedule-worktree.ts | 3 + frontend/src/pages/RepoDetail.tsx | 57 ++++-- frontend/src/pages/Schedules.tsx | 60 +++--- .../RepoDetail.schedule-sessions.test.tsx | 171 ++++++++++++++++++ .../RepoDetail.worktree-setup.test.tsx | 1 - .../src/pages/__tests__/Schedules.test.tsx | 4 + shared/src/schemas/schedule.ts | 15 +- shared/src/types/index.ts | 1 + shared/src/utils/repo.ts | 15 +- 46 files changed, 1171 insertions(+), 375 deletions(-) create mode 100644 frontend/src/components/schedules/ScheduleRunRemovalDialog.test.tsx create mode 100644 frontend/src/components/schedules/ScheduleRunRemovalDialog.tsx create mode 100644 frontend/src/lib/schedules/schedule-worktree.ts create mode 100644 frontend/src/pages/__tests__/RepoDetail.schedule-sessions.test.tsx diff --git a/backend/src/db/schedules.ts b/backend/src/db/schedules.ts index d04968fb..db9f11f3 100644 --- a/backend/src/db/schedules.ts +++ b/backend/src/db/schedules.ts @@ -5,6 +5,7 @@ import { SchedulePermissionConfigSchema, ScheduleRunSchema, ScheduleSkillMetadataSchema, + ScheduleWorkspaceModeSchema, type ScheduleJob, type ScheduleMcpServer, type ScheduleMode, @@ -102,6 +103,11 @@ function parseMcpServers(raw: string | null): ScheduleMcpServer[] { } } +function normalizeWorkspaceMode(raw: string | null): ScheduleWorkspaceMode { + const result = ScheduleWorkspaceModeSchema.safeParse(raw) + return result.success ? result.data : 'worktree' +} + function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob { return ScheduleJobSchema.parse({ id: row.id, @@ -120,7 +126,7 @@ function rowToScheduleJob(row: ScheduleJobRow): ScheduleJob { permissionConfig: parsePermissionConfig(row.permission_config), mcpServers: parseMcpServers(row.mcp_servers), branch: row.branch, - workspaceMode: row.workspace_mode ?? 'worktree', + workspaceMode: normalizeWorkspaceMode(row.workspace_mode), createdAt: row.created_at, updatedAt: row.updated_at, lastRunAt: row.last_run_at, @@ -304,9 +310,15 @@ export function listScheduleRunArtifactsByJob(db: Database, repoId: number, jobI })) } -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 interface ScheduleJobWorktreeOwner { + id: number + repoId: number + name: string +} + +export function listScheduleJobWorktreeOwners(db: Database): ScheduleJobWorktreeOwner[] { + const rows = db.prepare('SELECT id, repo_id, name FROM schedule_jobs').all() as Array<{ id: number; repo_id: number; name: string }> + return rows.map((row) => ({ id: row.id, repoId: row.repo_id, name: row.name })) } export function clearScheduleRunWorktreePath(db: Database, repoId: number, jobId: number, worktreePath: string): number { diff --git a/backend/src/index.ts b/backend/src/index.ts index d771af97..4f0efb13 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -245,6 +245,13 @@ const terminalService = new TerminalService( const projectConfigService = new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService) const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db) const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager) +scheduleService.setWorktreeRemovedHandler(async (directory) => { + try { + await terminalService.removeAll(directory) + } catch (error) { + logger.warn(`Failed to remove terminals for schedule worktree ${directory}:`, error) + } +}) const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, gitAuthService, projectConfigService, terminalService, scheduleService) const scheduleRunnerInstance = new ScheduleRunner(scheduleService) diff --git a/backend/src/routes/repos.test.ts b/backend/src/routes/repos.test.ts index d85e8e4a..28b99619 100644 --- a/backend/src/routes/repos.test.ts +++ b/backend/src/routes/repos.test.ts @@ -18,6 +18,17 @@ import path from 'path' import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' +const tempDirs: string[] = [] + +function createTempDir(name?: string): string { + const root = mkdtempSync(path.join(tmpdir(), 'repos-test-')) + tempDirs.push(root) + if (!name) return root + const dir = path.join(root, name) + mkdirSync(dir, { recursive: true }) + return dir +} + beforeEach(() => { mock.module('../services/project-id-resolver', () => ({ resolveProjectId: (() => null) as any, @@ -27,6 +38,9 @@ beforeEach(() => { afterEach(() => { mock.restore() + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } }) const stubGitAuthService = { @@ -50,7 +64,7 @@ function createTestApp( listSchedules: () => [], updateSchedule: () => {}, deleteSchedule: () => {}, - prepareRepoDelete: () => {}, + prepareRepoDelete: async () => {}, } as any const projectConfigService = new ProjectConfigService(db, createGitService(stubGitAuthService), stubGitAuthService) const repoWorkspaces = new RepoWorkspaceService(db, openCodeClient, stubGitAuthService, projectConfigService, terminalService, scheduleService) @@ -111,22 +125,23 @@ describe('GET /api/repos/:id/siblings', () => { })) createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + const worktreeDir = createTempDir('plugin-workspace') const client = createStubOpenCodeClient() client.api.worktree.list = mock(async () => ([{ - directory: '/tmp/plugin-workspace', + directory: worktreeDir, strategy: 'plugin-strategy', }])) as any app = createTestApp(db, client) const res = await app.request('/repos/1/siblings') expect(res.status).toBe(200) - const data = await res.json() as Array<{ id: number; fullPath?: string; localPath?: string; worktreeStrategy?: string; currentBranch?: string }> + const data = await res.json() as Array<{ id: number; fullPath?: string; localPath?: string; worktreeSource?: string; currentBranch?: string }> expect(data).toHaveLength(2) expect(data[1]).toMatchObject({ id: -1, - fullPath: '/tmp/plugin-workspace', + fullPath: worktreeDir, localPath: 'plugin-workspace', - worktreeStrategy: 'plugin-strategy', + worktreeSource: 'opencode', }) expect(data[1]?.currentBranch).toBeUndefined() }) @@ -138,17 +153,18 @@ describe('GET /api/repos/:id/siblings', () => { })) createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + const worktreeDir = createTempDir('duplicate-workspace') const client = createStubOpenCodeClient() client.api.worktree.list = mock(async () => ([ - { directory: '/tmp/duplicate-workspace', strategy: 'git' }, - { directory: '/tmp/duplicate-workspace/', strategy: 'git' }, + { directory: worktreeDir, strategy: 'git' }, + { directory: `${worktreeDir}/`, strategy: 'git' }, ])) as any app = createTestApp(db, client) const res = await app.request('/repos/1/siblings') expect(res.status).toBe(200) - const data = await res.json() as Array<{ worktreeStrategy?: string }> - expect(data.filter((entry) => entry.worktreeStrategy !== undefined)).toHaveLength(1) + const data = await res.json() as Array<{ worktreeSource?: string }> + expect(data.filter((entry) => entry.worktreeSource !== undefined)).toHaveLength(1) }) it('excludes a worktree pointing at the repo directory so it cannot be deleted', async () => { @@ -168,31 +184,33 @@ describe('GET /api/repos/:id/siblings', () => { const res = await app.request('/repos/1/siblings') expect(res.status).toBe(200) - const data = await res.json() as Array<{ id: number; worktreeStrategy?: string }> + const data = await res.json() as Array<{ id: number; worktreeSource?: string }> expect(data).toHaveLength(1) - expect(data.some((d) => d.worktreeStrategy !== undefined)).toBe(false) + expect(data.some((d) => d.worktreeSource !== undefined)).toBe(false) }) it('excludes a worktree that is a git main checkout so the main repo cannot be deleted', async () => { + const mainRepoDir = createTempDir('main-repo') + const featureDir = createTempDir('worktrees/feature-x') mock.module('../services/project-id-resolver', () => ({ resolveProjectId: (() => Promise.resolve('commit-A')) as any, isGitMainCheckout: ((dir: string) => - Promise.resolve(dir === '/Users/dev/main-repo')) as any, + Promise.resolve(dir === mainRepoDir)) as any, })) createRepo(db, { localPath: 'repo-wt', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) const client = createStubOpenCodeClient() client.api.worktree.list = mock(async () => ([ - { directory: '/Users/dev/main-repo', strategy: 'git' }, - { directory: '/Users/dev/worktrees/feature-x', strategy: 'git' }, + { directory: mainRepoDir, strategy: 'git' }, + { directory: featureDir, strategy: 'git' }, ])) as any app = createTestApp(db, client) const res = await app.request('/repos/1/siblings') expect(res.status).toBe(200) - const data = await res.json() as Array<{ worktreeStrategy?: string; fullPath?: string }> - expect(data.some((d) => d.fullPath === '/Users/dev/main-repo')).toBe(false) - expect(data.some((d) => d.fullPath === '/Users/dev/worktrees/feature-x')).toBe(true) + const data = await res.json() as Array<{ worktreeSource?: string; fullPath?: string }> + expect(data.some((d) => d.fullPath === mainRepoDir)).toBe(false) + expect(data.some((d) => d.fullPath === featureDir)).toBe(true) }) it('excludes repos with non-matching projectID', async () => { @@ -283,21 +301,22 @@ describe('DELETE /api/repos/:id/workspaces', () => { })) createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + const worktreeDir = createTempDir('worktree-one') const remove = mock(async () => undefined) const client = createStubOpenCodeClient() - client.api.worktree.list = mock(async () => ([{ directory: '/tmp/worktree-one', strategy: 'git' }])) as any + client.api.worktree.list = mock(async () => ([{ directory: worktreeDir, strategy: 'git' }])) as any client.api.worktree.remove = remove as any const app = createTestApp(db, client) const res = await app.request('/repos/1/workspaces', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ directory: '/tmp/worktree-one' }), + body: JSON.stringify({ directory: worktreeDir }), }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ success: true }) - expect(remove).toHaveBeenCalledWith({ projectID: 'commit-A', directory: '/tmp/worktree-one', force: true }) + expect(remove).toHaveBeenCalledWith({ projectID: 'commit-A', directory: worktreeDir, force: true }) }) it('returns 400 for a non-numeric repo id', async () => { @@ -401,8 +420,9 @@ describe('DELETE /api/repos/:id/workspaces', () => { })) createRepo(db, { localPath: 'repo-a', defaultBranch: 'main', cloneStatus: 'ready', clonedAt: Date.now(), isLocal: true }) + const worktreeDir = createTempDir('worktree-one') const client = createStubOpenCodeClient() - client.api.worktree.list = mock(async () => ([{ directory: '/tmp/worktree-one', strategy: 'git' }])) as any + client.api.worktree.list = mock(async () => ([{ directory: worktreeDir, strategy: 'git' }])) as any client.api.worktree.remove = mock(async () => { throw Object.assign(new Error('cannot remove'), { name: 'WorktreeError', data: { message: 'cannot remove' } }) }) as any @@ -411,7 +431,7 @@ describe('DELETE /api/repos/:id/workspaces', () => { const res = await app.request('/repos/1/workspaces', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ directory: '/tmp/worktree-one' }), + body: JSON.stringify({ directory: worktreeDir }), }) expect(res.status).toBe(409) diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 929c7821..96f295a4 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -404,7 +404,7 @@ app.get('/', async (c) => { } const removeWorktree = async () => { - scheduleService.prepareRepoDelete(id) + await scheduleService.prepareRepoDelete(id) await repoWorkspaces.removeRepoTerminals(repo) await repoService.deleteRepoFiles(database, id) } diff --git a/backend/src/routes/schedules.ts b/backend/src/routes/schedules.ts index 8c8d347d..20f7bc7a 100644 --- a/backend/src/routes/schedules.ts +++ b/backend/src/routes/schedules.ts @@ -2,8 +2,10 @@ import { Hono } from 'hono' import { CreateScheduleJobRequestSchema, RemoveScheduleWorktreesRequestSchema, + ScheduleRunWorktreesModeSchema, UpdateScheduleJobRequestSchema, } from '@opencode-manager/shared/schemas' +import type { ScheduleRunWorktreesMode } from '@opencode-manager/shared/types' import { ScheduleService, ScheduleServiceError } from '../services/schedules' import { parseId, handleServiceError } from '../utils/route-helpers' @@ -37,6 +39,14 @@ function parseRunIdFilter(value: string | undefined): number | undefined { return parsed } +function parseWorktreesMode(value: string | undefined): ScheduleRunWorktreesMode { + const result = ScheduleRunWorktreesModeSchema.safeParse(value) + if (!result.success) { + throw new ScheduleServiceError('Invalid worktrees mode', 400) + } + return result.data +} + export function createScheduleRoutes(scheduleService: ScheduleService) { const app = new Hono() @@ -236,7 +246,8 @@ export function createScheduleRoutes(scheduleService: ScheduleService) { try { const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError) - const result = await scheduleService.clearRunHistory(repoId, jobId) + const worktrees = parseWorktreesMode(c.req.query('worktrees')) + const result = await scheduleService.clearRunHistory(repoId, jobId, worktrees) return c.json(result) } catch (error) { return handleServiceError(c, error, 'Failed to clear schedule run history', ScheduleServiceError) @@ -248,7 +259,8 @@ export function createScheduleRoutes(scheduleService: ScheduleService) { const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError) const runId = parseId(c.req.param('runId'), 'run id', ScheduleServiceError) - await scheduleService.deleteRun(repoId, jobId, runId) + const worktrees = parseWorktreesMode(c.req.query('worktrees')) + await scheduleService.deleteRun(repoId, jobId, runId, worktrees) return c.json({ success: true }) } catch (error) { return handleServiceError(c, error, 'Failed to delete schedule run', ScheduleServiceError) diff --git a/backend/src/routes/settings.test.ts b/backend/src/routes/settings.test.ts index 36113718..149feabb 100644 --- a/backend/src/routes/settings.test.ts +++ b/backend/src/routes/settings.test.ts @@ -19,36 +19,19 @@ interface TestUserPreferenceRow { updated_at: number } -interface TestMigrationRow { - version: number - name: string - applied_at: number -} - interface StatementResult { - get?: (..._params: unknown[]) => TestUserPreferenceRow | TestMigrationRow | { count: number } | { name: string } | { user_id: string; preferences: string } | undefined + get?: (..._params: unknown[]) => TestUserPreferenceRow | { count: number } | { name: string } | { user_id: string; preferences: string } | undefined run?: (..._params: unknown[]) => { changes: number } all?: () => Array } class InMemoryDatabase { private userPreferences = new Map() - private schemaMigrations = new Map() private normalizeSql(sql: string): string { return sql.trim().toLowerCase().replace(/\s+/g, ' ') } - private getMigrationRows(): TestMigrationRow[] { - return [...this.schemaMigrations.entries()] - .sort((a, b) => a[0] - b[0]) - .map(([version, value]) => ({ - version, - name: value.name, - applied_at: value.applied_at, - })) - } - private setUserPreference(userId: string, preferences: string, updatedAt: number): void { this.userPreferences.set(userId, { preferences, updated_at: updatedAt }) } @@ -56,22 +39,6 @@ class InMemoryDatabase { private createStatement(sql: string): StatementResult { const normalizedSql = this.normalizeSql(sql) - if (normalizedSql === 'select version from schema_migrations order by version') { - return { - all: () => this.getMigrationRows(), - } - } - - if (normalizedSql.startsWith('insert into schema_migrations')) { - return { - run: (...params: unknown[]) => { - const [version, name, appliedAt] = params as [number, string, number] - this.schemaMigrations.set(version, { name, applied_at: appliedAt }) - return { changes: 1 } - }, - } - } - if (normalizedSql === 'select preferences, updated_at from user_preferences where user_id = ?') { return { get: (...params: unknown[]) => { @@ -172,7 +139,6 @@ class InMemoryDatabase { close() { this.userPreferences.clear() - this.schemaMigrations.clear() } } diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index 4391a291..dfd0c08c 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -400,7 +400,7 @@ 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. +Optional \`workspaceMode\` sets where runs execute: \`worktree\` (default, a fresh worktree removed after each run), \`kept-worktree\` (a fresh worktree kept after each run), or \`shared-worktree\` (one worktree and branch reused by every run). Kept and shared worktrees are listed with \`GET /repos/:repoId/schedules/:jobId/worktrees\`. Removing schedule worktrees is done by the user in the Manager UI. \`\`\`json { diff --git a/backend/src/services/opencode-manager-tool-plugin.ts b/backend/src/services/opencode-manager-tool-plugin.ts index 786357de..cb9990ea 100644 --- a/backend/src/services/opencode-manager-tool-plugin.ts +++ b/backend/src/services/opencode-manager-tool-plugin.ts @@ -29,6 +29,7 @@ export const MANAGER_TOOL_ALLOWED_ROUTES = [ 'GET /repos/*/schedules/*', 'PATCH /repos/*/schedules/*', 'DELETE /repos/*/schedules/*', + 'GET /repos/*/schedules/*/worktrees', 'POST /repos/*/schedules/*/run', 'GET /repos/*/schedules/*/runs', 'DELETE /repos/*/schedules/*/runs', diff --git a/backend/src/services/repo-workspace.ts b/backend/src/services/repo-workspace.ts index b09ea17a..4a393b76 100644 --- a/backend/src/services/repo-workspace.ts +++ b/backend/src/services/repo-workspace.ts @@ -7,8 +7,7 @@ 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 { findSiblingByDirectory, getSiblingRepos, removeWorktree, RepoWorkspaceError, resolveRepoProjectId } from './repo' import { getErrorMessage } from '../utils/error-utils' /** Single owner of repo worktree lifecycle side effects: worktree setup on create, and terminal cleanup plus owner-specific removal on remove. */ @@ -35,26 +34,28 @@ export class RepoWorkspaceService { /** * 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. + * OpenCode, schedule worktrees through the schedule (which commits pending changes and + * removes their terminals first), and plain git worktrees with `git worktree remove`, + * which refuses uncommitted changes. */ async remove(repo: Repo, directory: string): Promise { 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 } + await this.removeTerminals(worktree.fullPath) + 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) - }) + try { + await removeWorktree(repo.fullPath, worktree.fullPath, this.gitAuthService.getGitEnvironment(true), { force: false }) + } catch (error) { + throw new RepoWorkspaceError(`Could not remove worktree: ${getErrorMessage(error)}`, 400) + } return } diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 6b209265..4b8ba817 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -6,8 +6,8 @@ import { createRepo, getRepoByLocalPath, getRepoBySourcePath, getRepoById, updat 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, type RepoWorktreeSchedule, type RepoWorktreeSource } from '@opencode-manager/shared/utils' +import { getReposPath } from '@opencode-manager/shared/config/env' +import { normalizeRepoDirectoryName, sanitizeRepoDirectoryName, sanitizeBranchForDirectory, getRepoBaseDirectoryName, normalizeRepoUrlForCompare, isSSHUrl, normalizeSSHUrl, SCP_STYLE_URL_PATTERN, ASSISTANT_REPO_ID, type RepoSibling, type RepoWorktreeSource } from '@opencode-manager/shared/utils' import type { GitAuthService } from './git-auth' import { isGitHubHttpsUrl } from '../utils/git-auth' import path from 'path' @@ -16,8 +16,7 @@ import { getErrorMessage } from '../utils/error-utils' import { sseAggregator } from './sse-aggregator' import { resolveProjectId, isGitMainCheckout } from './project-id-resolver' import { listRepos } from '../db/queries' -import { getScheduleJobRepoId, listRunningScheduleRuns } from '../db/schedules' -import { parseScheduleWorktreeName } from './schedule-worktree-paths' +import { createScheduleWorktreeDescriber } from './schedule-worktree-paths' import { SettingsService } from './settings' import { buildAssistantRepo } from './assistant-mode' import type { OpenCodeClient } from './opencode/client' @@ -1020,7 +1019,18 @@ export async function resolveDefaultBranch(repoPath: string, env: Record 'main') } -export async function removeWorktree(baseRepoPath: string, worktreePath: string, env?: Record): Promise { +export async function removeWorktree( + baseRepoPath: string, + worktreePath: string, + env?: Record, + options: { force?: boolean } = {}, +): Promise { + if (options.force === false) { + await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', worktreePath], env ? { env } : undefined) + await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'prune'], env ? { env } : undefined).catch(() => {}) + return + } + try { await executeCommand(['git', '-C', baseRepoPath, 'worktree', 'remove', '--force', worktreePath], env ? { env } : undefined) } catch { @@ -1229,13 +1239,6 @@ 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, @@ -1330,7 +1333,6 @@ export async function getSiblingRepos( isLocal: true, currentBranch: candidate.branch, worktreeSource, - worktreeStrategy: candidate.strategy, ...(schedule ? { schedule } : {}), } }) @@ -1371,34 +1373,6 @@ export async function listGitWorktrees(repoPath: string, env: Record 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)), - } - } -} - export class RepoWorkspaceError extends Error { readonly status: 400 diff --git a/backend/src/services/schedule-worktree-paths.ts b/backend/src/services/schedule-worktree-paths.ts index 2aeda228..7f149ce9 100644 --- a/backend/src/services/schedule-worktree-paths.ts +++ b/backend/src/services/schedule-worktree-paths.ts @@ -1,22 +1,18 @@ import path from 'path' +import type { Database } from 'bun:sqlite' import { getScheduleWorktreesPath } from '@opencode-manager/shared/config/env' +import type { RepoWorktreeSchedule } from '@opencode-manager/shared/utils' +import { listRunningScheduleRuns, listScheduleJobWorktreeOwners } from '../db/schedules' +import { canonicalPathSync } from '../utils/fs-safe' const SCHEDULE_WORKTREE_DIRECTORY = /^job-(\d+)-(?:run-(\d+)|shared)$/ -export function getSharedScheduleWorktreePath(jobId: number): string { - return path.join(getScheduleWorktreesPath(), `job-${jobId}-shared`) +export function getScheduleWorktreePath(jobId: number, runId: number | null): string { + return path.join(getScheduleWorktreesPath(), runId === null ? `job-${jobId}-shared` : `job-${jobId}-run-${runId}`) } -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}` +export function getScheduleWorktreeBranch(jobId: number, runId: number | null): string { + return runId === null ? `schedule/${jobId}/shared` : `schedule/${jobId}/run-${runId}` } /** @@ -28,3 +24,41 @@ export function parseScheduleWorktreeName(name: string): { jobId: number; runId: if (!match) return null return { jobId: Number(match[1]), runId: match[2] ? Number(match[2]) : null } } + +/** + * Whether a path names a schedule's shared worktree, as opposed to one of its run worktrees. + */ +export function isSharedScheduleWorktreePath(worktreePath: string): boolean { + return parseScheduleWorktreeName(path.basename(worktreePath))?.runId === null +} + +/** + * 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. + */ +export function createScheduleWorktreeDescriber(database: Database): (directory: string) => RepoWorktreeSchedule | undefined { + const scheduleRoot = canonicalPathSync(path.resolve(getScheduleWorktreesPath())) + const jobsById = new Map(listScheduleJobWorktreeOwners(database).map((job) => [job.id, job] as const)) + const runningRuns = listRunningScheduleRuns(database) + const runningByDirectory = new Map(runningRuns.flatMap((run) => ( + run.worktreePath ? [[canonicalPathSync(path.resolve(run.worktreePath)), run] as const] : [] + ))) + + return (directory) => { + const canonicalDirectory = canonicalPathSync(path.resolve(directory)) + const running = runningByDirectory.get(canonicalDirectory) + const parsed = path.dirname(canonicalDirectory) === scheduleRoot ? parseScheduleWorktreeName(path.basename(canonicalDirectory)) : null + const jobId = parsed?.jobId ?? running?.jobId + if (jobId === undefined) return undefined + const job = jobsById.get(jobId) + if (!job) return undefined + return { + repoId: job.repoId, + jobId, + runId: parsed ? parsed.runId : (running?.id ?? null), + inUse: running !== undefined || (parsed?.runId === null && runningRuns.some((run) => run.jobId === jobId)), + name: job.name, + } + } +} diff --git a/backend/src/services/schedule-worktree.ts b/backend/src/services/schedule-worktree.ts index aa56c624..118d50ad 100644 --- a/backend/src/services/schedule-worktree.ts +++ b/backend/src/services/schedule-worktree.ts @@ -3,19 +3,18 @@ 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 { ScheduleRunWorktreesMode, 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' import { executeCommand } from '../utils/process' -import { resolveDefaultBranch, createWorktreeSafely, removeWorktree } from './repo' +import { resolveDefaultBranch, createWorktreeSafely, listGitWorktrees, removeWorktree } from './repo' import { logger } from '../utils/logger' -import { mkdirSyncSafe } from '../utils/fs-safe' +import { canonicalPathSync, mkdirSyncSafe } from '../utils/fs-safe' import { - getRunScheduleBranch, - getRunScheduleWorktreePath, - getSharedScheduleBranch, - getSharedScheduleWorktreePath, + getScheduleWorktreeBranch, + getScheduleWorktreePath, + isSharedScheduleWorktreePath, parseScheduleWorktreeName, } from './schedule-worktree-paths' @@ -35,10 +34,6 @@ export interface ScheduleWorktreeEntry { 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. @@ -57,16 +52,17 @@ export class ScheduleWorktreeManager { ) {} /** - * 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. + * Prepares the directory a run works in. Returns null when there is no worktree to + * prepare (the assistant repo or a directory that is not a git checkout). A shared + * worktree that already exists and is clean 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; workspaceMode: ScheduleWorkspaceMode }, runId: number, ): Promise { - if (repo.id === ASSISTANT_REPO_ID || job.workspaceMode === 'repo') return null + if (repo.id === ASSISTANT_REPO_ID) return null try { await executeCommand(['git', '-C', repo.fullPath, 'rev-parse', '--is-inside-work-tree'], { silent: true }) @@ -75,8 +71,9 @@ export class ScheduleWorktreeManager { } 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) + const worktreeRunId = shared ? null : runId + const runBranch = getScheduleWorktreeBranch(job.id, worktreeRunId) + const worktreePath = getScheduleWorktreePath(job.id, worktreeRunId) let sshSetup = false if (repo.repoUrl && isSSHUrl(repo.repoUrl)) { @@ -88,6 +85,10 @@ export class ScheduleWorktreeManager { const env = await this.buildGitEnv(repo, sshSetup, true) if (shared && await this.isUsableWorktree(worktreePath, env)) { + const status = await executeCommand(['git', '-C', worktreePath, 'status', '--porcelain'], { env }).catch(() => '') + if (status.trim()) { + throw new Error(`Shared worktree ${worktreePath} has uncommitted changes made outside a scheduled run. Commit or discard them before the next run.`) + } return { directory: worktreePath, worktreePath, runBranch } } @@ -103,6 +104,8 @@ export class ScheduleWorktreeManager { await removeWorktree(repo.fullPath, worktreePath, env) } + await this.assertRunBranchAvailable(repo.fullPath, runBranch, worktreePath, env) + mkdirSyncSafe(path.dirname(worktreePath)) await createWorktreeSafely(repo.fullPath, worktreePath, runBranch, env, baseRef) @@ -132,7 +135,7 @@ export class ScheduleWorktreeManager { return { commitHash: null } } - const retain = isSharedWorktreePath(run.worktreePath) || job.workspaceMode === 'kept-worktree' + const retain = isSharedScheduleWorktreePath(run.worktreePath) || job.workspaceMode === 'kept-worktree' let sshSetup = false let env: Record | undefined let commitHash: string | null = null @@ -211,7 +214,7 @@ export class ScheduleWorktreeManager { jobId: parsed.jobId, runId: parsed.runId, worktreePath: path.join(getScheduleWorktreesPath(), name), - branch: parsed.runId === null ? getSharedScheduleBranch(parsed.jobId) : getRunScheduleBranch(parsed.jobId, parsed.runId), + branch: getScheduleWorktreeBranch(parsed.jobId, parsed.runId), }] }) } @@ -220,34 +223,62 @@ export class ScheduleWorktreeManager { * Removes leftover worktrees and deletes the run branches for a set of * 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. + * In `commit` mode a run worktree still on disk is released through + * `releaseWorktree`, so its pending changes are committed and its branch kept; + * branches whose worktree is already gone are deleted. In `discard` mode the + * worktrees are force-removed and every run branch deleted. 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, + job: { id: number; name: string }, artifacts: { runBranch: string | null; worktreePath: string | null }[], + mode: ScheduleRunWorktreesMode = 'commit', ): Promise { - 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 sharedPath = getScheduleWorktreePath(job.id, null) + const sharedBranch = getScheduleWorktreeBranch(job.id, null) + const runWorktrees = artifacts + .map((artifact) => artifact.worktreePath) + .filter((worktreePath): worktreePath is string => worktreePath !== null && worktreePath !== sharedPath) const branches = artifacts - .map((a) => a.runBranch) - .filter((b): b is string => b !== null && b.length > 0 && b !== sharedBranch) + .map((artifact) => artifact.runBranch) + .filter((branch): branch is string => branch !== null && branch.length > 0 && branch !== sharedBranch) - if (worktreePaths.length === 0 && branches.length === 0) return + if (runWorktrees.length === 0 && branches.length === 0) return const env = await this.buildGitEnv(repo, false, true) - await Promise.all( - worktreePaths.map((worktreePath) => removeWorktree(repo.fullPath, worktreePath, env).catch(() => undefined)), - ) - - if (branches.length > 0) { - await executeCommand(['git', '-C', repo.fullPath, 'branch', '-D', ...branches], { env }).catch(() => {}) + if (mode === 'discard') { + await Promise.all(runWorktrees.map((worktreePath) => removeWorktree(repo.fullPath, worktreePath, env).catch(() => undefined))) + await this.deleteBranches(repo.fullPath, branches, env) + return } + + const branchByWorktree = new Map(artifacts.flatMap((artifact) => ( + artifact.worktreePath !== null && artifact.runBranch !== null + ? [[artifact.worktreePath, artifact.runBranch] as const] + : [] + ))) + const retainedBranches = new Set() + + await Promise.all(runWorktrees.map(async (worktreePath) => { + if (!existsSync(worktreePath)) return + const branch = branchByWorktree.get(worktreePath) + if (branch) retainedBranches.add(branch) + try { + await this.releaseWorktree(repo, job, worktreePath) + } catch (error) { + logger.error(`Failed to release schedule worktree ${worktreePath}:`, error) + } + })) + + await this.deleteBranches(repo.fullPath, branches.filter((branch) => !retainedBranches.has(branch)), env) + } + + private async deleteBranches(repoPath: string, branches: string[], env: Record): Promise { + if (branches.length === 0) return + await executeCommand(['git', '-C', repoPath, 'branch', '-D', ...branches], { env }).catch(() => {}) } private async commitPendingChanges( @@ -274,6 +305,20 @@ export class ScheduleWorktreeManager { } } + /** + * Refuses to create a worktree on a branch another checkout already has, which git + * would otherwise reject with an opaque error. + */ + private async assertRunBranchAvailable(repoPath: string, runBranch: string, worktreePath: string, env: Record): Promise { + const targetPath = canonicalPathSync(path.resolve(worktreePath)) + const conflicting = (await listGitWorktrees(repoPath, env)).find((worktree) => + worktree.branch === runBranch && canonicalPathSync(path.resolve(worktree.path)) !== targetPath, + ) + if (conflicting) { + throw new Error(`Branch ${runBranch} is checked out in ${conflicting.path}. Switch that checkout to another branch so the schedule can run.`) + } + } + /** * Resolves a user-supplied base branch name to a verified git ref, preferring * the remote-tracking branch for freshness. Returns null when neither the diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index 9b35022e..82b41da9 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -7,6 +7,7 @@ import { type ScheduleJob, type ScheduleRun, type ScheduleRunTriggerSource, + type ScheduleRunWorktreesMode, type ScheduleWorktree, type UpdateScheduleJobRequest, } from '@opencode-manager/shared/types' @@ -59,6 +60,7 @@ import { getErrorMessage } from '../utils/error-utils' import { logger } from '../utils/logger' import { canonicalPathSync } from '../utils/fs-safe' import { buildAssistantRepo } from './assistant-mode' +import { createScheduleWorktreeDescriber } from './schedule-worktree-paths' import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' class ScheduleServiceError extends Error { @@ -72,6 +74,8 @@ class ScheduleServiceError extends Error { const SESSION_STOPPED_ERROR = 'The session stopped without producing an assistant response. This usually means OpenCode restarted mid-run or the session was interrupted. Open the linked session to inspect any partial output and rerun if needed.' +const DELETION_RESERVATION_RUN_ID = -1 + interface SessionSignal { errorText: string | null disposed: boolean @@ -227,6 +231,7 @@ export class ScheduleService { private static pendingCancels = new Map() private static activeTeardowns = new Set() private onJobChange: ((job: ScheduleJob | null, jobId: number) => void) | null = null + private onWorktreeRemoved: ((directory: string) => Promise) | null = null constructor( private readonly db: Database, @@ -238,6 +243,10 @@ export class ScheduleService { this.onJobChange = handler } + setWorktreeRemovedHandler(handler: ((directory: string) => Promise) | null): void { + this.onWorktreeRemoved = handler + } + private static abortActiveRun(jobId: number, runId: number): void { const active = ScheduleService.activeRuns.get(jobId) if (active?.runId === runId) { @@ -325,11 +334,13 @@ export class ScheduleService { } listAllJobsWithRepos(): Array { - const runningPaths = this.listRunningWorktreePaths() + const describeSchedule = createScheduleWorktreeDescriber(this.db) const counts = new Map() for (const entry of this.worktreeManager.listWorktrees()) { - if (runningPaths.has(entry.worktreePath)) continue - counts.set(entry.jobId, (counts.get(entry.jobId) ?? 0) + 1) + const described = describeSchedule(canonicalPathSync(path.resolve(entry.worktreePath))) + if (described?.inUse === false) { + counts.set(entry.jobId, (counts.get(entry.jobId) ?? 0) + 1) + } } return listAllScheduleJobsWithRepos(this.db).map((job) => ({ ...job, retainedWorktreeCount: counts.get(job.id) ?? 0 })) } @@ -340,16 +351,18 @@ export class ScheduleService { */ 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 + const describeSchedule = createScheduleWorktreeDescriber(this.db) 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), - })) + .map((entry) => { + const described = describeSchedule(canonicalPathSync(path.resolve(entry.worktreePath))) + return { + worktreePath: entry.worktreePath, + branch: entry.branch, + runId: entry.runId, + inUse: described?.inUse ?? false, + } + }) .sort((left, right) => (right.runId ?? Number.MAX_SAFE_INTEGER) - (left.runId ?? Number.MAX_SAFE_INTEGER)) } @@ -383,15 +396,14 @@ export class ScheduleService { throw new ScheduleServiceError(`Failed to remove worktree ${target.worktreePath}: ${getErrorMessage(error)}`, 500) } clearScheduleRunWorktreePath(this.db, repoId, jobId, target.worktreePath) + if (this.onWorktreeRemoved) { + await this.onWorktreeRemoved(target.worktreePath) + } } return { removed: targets.length } } - private listRunningWorktreePaths(): Set { - return new Set(listRunningScheduleRuns(this.db).flatMap((run) => (run.worktreePath ? [run.worktreePath] : []))) - } - listAllRuns(options: ListAllRunsOptions = {}): ScheduleRunWithContext[] { const limit = Math.min(Math.max(options.limit ?? 20, 1), 100) const offset = Math.max(options.offset ?? 0, 0) @@ -460,6 +472,14 @@ export class ScheduleService { if (input.agentSlug !== undefined) { await this.assertAgentAvailable(repo.fullPath, input.agentSlug?.trim() || null) } + + if (input.workspaceMode !== undefined && input.workspaceMode !== existing.workspaceMode) { + const running = ScheduleService.activeRuns.has(jobId) || getRunningScheduleRunByJob(this.db, repoId, jobId) !== null + if (running) { + throw new ScheduleServiceError('Cannot change where runs execute while a run is in progress.', 409) + } + } + let job: ScheduleJob | null try { @@ -477,7 +497,7 @@ export class ScheduleService { async deleteJob(repoId: number, jobId: number): Promise { this.assertRepo(repoId) - this.assertJob(repoId, jobId) + const job = this.assertJob(repoId, jobId) if (ScheduleService.activeRuns.has(jobId)) { throw new ScheduleServiceError('Cannot delete a schedule while it is running. Cancel the run first.', 409) @@ -488,17 +508,27 @@ 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) - } this.onJobChange?.(null, jobId) + ScheduleService.activeRuns.set(jobId, { runId: DELETION_RESERVATION_RUN_ID, abort: new AbortController() }) + + try { + await this.removeWorktrees(repoId, jobId) + + const deleted = deleteScheduleJob(this.db, repoId, jobId) + if (!deleted) { + throw new ScheduleServiceError('Schedule not found', 404) + } + } catch (error) { + this.onJobChange?.(job, jobId) + throw error + } finally { + ScheduleService.releaseActiveRun(jobId, DELETION_RESERVATION_RUN_ID) + } } - prepareRepoDelete(repoId: number): void { + async prepareRepoDelete(repoId: number): Promise { const jobIds = listScheduleJobIdsByRepo(this.db, repoId) + for (const jobId of jobIds) { if (ScheduleService.activeRuns.has(jobId)) { throw new ScheduleServiceError('Cannot delete a repo while a schedule run is in progress. Cancel the run first.', 409) @@ -508,8 +538,11 @@ export class ScheduleService { if (runningRun) { throw new ScheduleServiceError('Cannot delete a repo while a schedule run is in progress. Cancel the run first.', 409) } + } + for (const jobId of jobIds) { this.onJobChange?.(null, jobId) + await this.removeWorktrees(repoId, jobId) } } @@ -543,36 +576,40 @@ export class ScheduleService { /** * Clears a job's run history: deletes every finished run's row plus its git * run branch and any leftover worktree. A run currently in progress is left - * untouched (its row and live worktree are skipped). + * untouched (its row and live worktree are skipped). `worktrees` controls + * whether a worktree still on disk is committed and kept (`commit`) or + * discarded along with its branch (`discard`). */ - async clearRunHistory(repoId: number, jobId: number): Promise<{ cleared: number }> { + async clearRunHistory(repoId: number, jobId: number, worktrees: ScheduleRunWorktreesMode = 'commit'): Promise<{ cleared: number }> { const repo = this.assertRepo(repoId) - this.assertJob(repoId, jobId) + const job = this.assertJob(repoId, jobId) const removable = listScheduleRunArtifactsByJob(this.db, repoId, jobId).filter((run) => run.status !== 'running') if (removable.length === 0) { return { cleared: 0 } } - await this.worktreeManager.pruneRunArtifacts(repo, jobId, removable) + await this.worktreeManager.pruneRunArtifacts(repo, job, removable, worktrees) const cleared = deleteScheduleRunsByIds(this.db, repoId, jobId, removable.map((run) => run.id)) return { cleared } } /** * Deletes a single finished run plus its git run branch and any leftover - * worktree. A run in progress must be cancelled first. + * worktree. A run in progress must be cancelled first. `worktrees` controls + * whether a worktree still on disk is committed and kept (`commit`) or + * discarded along with its branch (`discard`). */ - async deleteRun(repoId: number, jobId: number, runId: number): Promise { + async deleteRun(repoId: number, jobId: number, runId: number, worktrees: ScheduleRunWorktreesMode = 'commit'): Promise { const repo = this.assertRepo(repoId) - this.assertJob(repoId, jobId) + const job = this.assertJob(repoId, jobId) const run = this.getRun(repoId, jobId, runId) if (run.status === 'running') { throw new ScheduleServiceError('Cannot delete a run while it is in progress. Cancel it first.', 409) } - await this.worktreeManager.pruneRunArtifacts(repo, jobId, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }]) + await this.worktreeManager.pruneRunArtifacts(repo, job, [{ runBranch: run.runBranch, worktreePath: run.worktreePath }], worktrees) const deleted = deleteScheduleRunById(this.db, repoId, jobId, runId) if (!deleted) { throw new ScheduleServiceError('Run not found', 404) diff --git a/backend/test/db/schedules.test.ts b/backend/test/db/schedules.test.ts index f56c3011..3a2ded49 100644 --- a/backend/test/db/schedules.test.ts +++ b/backend/test/db/schedules.test.ts @@ -432,6 +432,17 @@ describe('schedule database queries', () => { expect(job).toBeNull() }) + it('maps a legacy repo workspace mode to worktree', () => { + const stmt = { + get: vi.fn().mockReturnValue(makeJobRow({ workspace_mode: 'repo' })), + } + mockDb.prepare.mockReturnValue(stmt) + + const job = schedulesDb.getScheduleJobById(mockDb, 42, 7) + + expect(job?.workspaceMode).toBe('worktree') + }) + it('deletes a schedule job successfully', () => { const stmt = { run: vi.fn().mockReturnValue({ changes: 1 }), @@ -672,12 +683,11 @@ describe('schedule database queries', () => { ]) }) - it('getScheduleJobRepoId returns the owning repo or null for an unknown job', () => { - const stmt = { get: vi.fn().mockReturnValueOnce({ repo_id: 42 }).mockReturnValueOnce(undefined) } + it('listScheduleJobWorktreeOwners returns id, repoId and name for every job', () => { + const stmt = { all: vi.fn().mockReturnValue([{ id: 7, repo_id: 42, name: 'nightly' }]) } mockDb.prepare.mockReturnValue(stmt) - expect(schedulesDb.getScheduleJobRepoId(mockDb, 7)).toBe(42) - expect(schedulesDb.getScheduleJobRepoId(mockDb, 8)).toBeNull() + expect(schedulesDb.listScheduleJobWorktreeOwners(mockDb)).toEqual([{ id: 7, repoId: 42, name: 'nightly' }]) }) it('deleteScheduleRunById deletes a single run row', () => { diff --git a/backend/test/index.test.ts b/backend/test/index.test.ts index b2321dba..3a75379b 100644 --- a/backend/test/index.test.ts +++ b/backend/test/index.test.ts @@ -63,6 +63,7 @@ const scheduleRunnerMock = vi.hoisted(() => ({ vi.mock('../src/services/schedules', () => ({ ScheduleService: vi.fn().mockImplementation(() => ({ getActiveRunSessions: vi.fn().mockResolvedValue([]), + setWorktreeRemovedHandler: vi.fn(), })), ScheduleRunner: vi.fn().mockImplementation(() => scheduleRunnerMock), })) diff --git a/backend/test/routes/repos.test.ts b/backend/test/routes/repos.test.ts index bbb78045..a5c59243 100644 --- a/backend/test/routes/repos.test.ts +++ b/backend/test/routes/repos.test.ts @@ -913,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', worktreeSource: 'opencode' }, + { ...createMockRepo({ id: -1, fullPath: '/tmp/plugin-workspace' }), currentBranch: undefined, worktreeSource: 'opencode' }, ]) const app = createTestRoutes() diff --git a/backend/test/routes/schedules.test.ts b/backend/test/routes/schedules.test.ts index 24b94923..ae721437 100644 --- a/backend/test/routes/schedules.test.ts +++ b/backend/test/routes/schedules.test.ts @@ -12,6 +12,8 @@ const scheduleService = { listRuns: vi.fn(), getRun: vi.fn(), cancelRun: vi.fn(), + clearRunHistory: vi.fn(), + deleteRun: vi.fn(), listAllEnabledJobs: vi.fn(), listAllJobsWithRepos: vi.fn(), listAllRuns: vi.fn(), @@ -363,4 +365,42 @@ describe('Schedule Routes', () => { expect(body.error).toBe('Invalid run id') expect(scheduleService.markRunViewed).not.toHaveBeenCalled() }) + + it('clears run history with the default commit worktrees mode', async () => { + scheduleService.clearRunHistory.mockResolvedValue({ cleared: 2 }) + + const response = await app.request('/repos/42/schedules/7/runs', { method: 'DELETE' }) + const body = await response.json() as { cleared: number } + + expect(response.status).toBe(200) + expect(body.cleared).toBe(2) + expect(scheduleService.clearRunHistory).toHaveBeenCalledWith(42, 7, 'commit') + }) + + it('passes the discard worktrees mode to clearRunHistory', async () => { + scheduleService.clearRunHistory.mockResolvedValue({ cleared: 1 }) + + const response = await app.request('/repos/42/schedules/7/runs?worktrees=discard', { method: 'DELETE' }) + + expect(response.status).toBe(200) + expect(scheduleService.clearRunHistory).toHaveBeenCalledWith(42, 7, 'discard') + }) + + it('rejects an invalid worktrees mode when clearing run history', async () => { + const response = await app.request('/repos/42/schedules/7/runs?worktrees=nope', { method: 'DELETE' }) + const body = await response.json() as { error: string } + + expect(response.status).toBe(400) + expect(body.error).toBe('Invalid worktrees mode') + expect(scheduleService.clearRunHistory).not.toHaveBeenCalled() + }) + + it('deletes a run with the requested worktrees mode', async () => { + scheduleService.deleteRun.mockResolvedValue(undefined) + + const response = await app.request('/repos/42/schedules/7/runs/5?worktrees=discard', { method: 'DELETE' }) + + expect(response.status).toBe(200) + expect(scheduleService.deleteRun).toHaveBeenCalledWith(42, 7, 5, 'discard') + }) }) diff --git a/backend/test/services/opencode-manager-tool-plugin.test.ts b/backend/test/services/opencode-manager-tool-plugin.test.ts index c2bd023b..028fdbb2 100644 --- a/backend/test/services/opencode-manager-tool-plugin.test.ts +++ b/backend/test/services/opencode-manager-tool-plugin.test.ts @@ -301,6 +301,21 @@ describe('ocm-manager plugin', () => { } }) + it('allows listing schedule worktrees but rejects deleting them', async () => { + const tool = await loadTool(configHome) + + const fetchMock = jsonResponse({}) + vi.stubGlobal('fetch', fetchMock) + await runTool(tool, { action: 'request', params: { method: 'GET', path: '/repos/1/schedules/2/worktrees' } }) + expect(fetchMock).toHaveBeenCalledTimes(1) + + const deleteMock = jsonResponse({}) + vi.stubGlobal('fetch', deleteMock) + await expect(runTool(tool, { action: 'request', params: { method: 'DELETE', path: '/repos/1/schedules/2/worktrees' } })) + .rejects.toThrow(/is not an allowed OpenCode Manager route/) + expect(deleteMock).not.toHaveBeenCalled() + }) + it('normalizes path traversal and rejects the resolved route without calling the API', async () => { const fetchMock = jsonResponse({}) vi.stubGlobal('fetch', fetchMock) diff --git a/backend/test/services/repo-git.test.ts b/backend/test/services/repo-git.test.ts index 4e287a4e..d5c42331 100644 --- a/backend/test/services/repo-git.test.ts +++ b/backend/test/services/repo-git.test.ts @@ -1,5 +1,5 @@ import { execFileSync } from 'node:child_process' -import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { createServer } from 'node:https' import { tmpdir } from 'node:os' import path from 'node:path' @@ -998,7 +998,7 @@ describe('repo service real git', () => { 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(extraDir)).toMatchObject({ worktreeSource: 'opencode', 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' }) @@ -1006,6 +1006,45 @@ describe('repo service real git', () => { expect(findSibling(manualPath)).toMatchObject({ worktreeSource: 'git', currentBranch: 'manual-work' }) }) + it('describes schedule worktrees by canonical path and shared-worktree in-use state', async () => { + const { createScheduleWorktreeDescriber } = await import('../../src/services/schedule-worktree-paths') + const repoA = path.join(reposPath, uniqueName('schedule-describer-a')) + mkdirSync(repoA, { recursive: true }) + const a = createRepo(db, { + isLocal: true, + localPath: path.basename(repoA), + sourcePath: repoA, + branch: 'main', + defaultBranch: 'main', + cloneStatus: 'ready', + clonedAt: Date.now(), + }) + 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 root = getScheduleWorktreesPath() + mkdirSync(root, { recursive: true }) + const runDir = path.join(root, `job-${jobId}-run-1`) + const sharedDir = path.join(root, `job-${jobId}-shared`) + mkdirSync(runDir, { recursive: true }) + mkdirSync(sharedDir, { recursive: true }) + const linkRoot = path.join(workspaceRoot, uniqueName('schedule-describer-link')) + symlinkSync(root, linkRoot, 'dir') + + const describeWorktree = createScheduleWorktreeDescriber(db) + + const canonicalRun = describeWorktree(realpathSync(runDir)) + expect(canonicalRun).toMatchObject({ repoId: a.id, jobId, runId: 1, inUse: false, name: 'nightly' }) + expect(describeWorktree(path.join(linkRoot, `job-${jobId}-run-1`))).toEqual(canonicalRun) + + const sharedBefore = describeWorktree(realpathSync(sharedDir)) + expect(sharedBefore).toMatchObject({ repoId: a.id, jobId, runId: null, inUse: false, name: 'nightly' }) + + 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 describeAfterRun = createScheduleWorktreeDescriber(db) + expect(describeAfterRun(realpathSync(sharedDir))).toMatchObject({ jobId, runId: null, inUse: true, name: 'nightly' }) + expect(describeAfterRun(path.join(root, 'job-999999-run-1'))).toBeUndefined() + }) + it('returns repo siblings when the OpenCode client fails', async () => { const { getSiblingRepos } = await import('../../src/services/repo') const origin = path.join(workspaceRoot, uniqueName('sibling-err-origin.git')) diff --git a/backend/test/services/repo-workspace.test.ts b/backend/test/services/repo-workspace.test.ts index e445b9ec..d4c64088 100644 --- a/backend/test/services/repo-workspace.test.ts +++ b/backend/test/services/repo-workspace.test.ts @@ -131,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', worktreeSource: 'opencode' }]) + mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/other', worktreeSource: 'opencode' }]) const { service } = createService({ worktreeRemove, removeAll }) const error = await service.remove(REPO, '/worktrees/unknown').catch((caught: unknown) => caught) @@ -145,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', worktreeSource: 'opencode' }]) + mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeSource: 'opencode' }]) const { service } = createService({ worktreeRemove, removeAll }) await service.remove(REPO, '/worktrees/feature-x') @@ -164,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', worktreeSource: 'opencode' }]) + mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/worktrees/feature-x', worktreeSource: 'opencode' }]) const { service } = createService({ worktreeRemove, removeAll }) await expect(service.remove(REPO, '/worktrees/feature-x')).resolves.toBeUndefined() @@ -176,18 +176,20 @@ describe('RepoWorkspaceService', () => { force: true, }) }) - it('removes a schedule worktree through its schedule instead of OpenCode', async () => { + it('removes a schedule worktree through its schedule without touching terminals', async () => { const worktreeRemove = vi.fn(async () => undefined) + const removeAll = vi.fn(async () => undefined) mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/schedule-worktrees/job-7-shared', worktreeSource: 'schedule', - schedule: { repoId: 3, jobId: 7, runId: null, inUse: false }, + schedule: { repoId: 3, jobId: 7, runId: null, inUse: false, name: 'Shared job' }, }]) - const { service, removeScheduleWorktrees } = createService({ worktreeRemove }) + const { service, removeScheduleWorktrees } = createService({ worktreeRemove, removeAll }) await service.remove(REPO, '/schedule-worktrees/job-7-shared') expect(removeScheduleWorktrees).toHaveBeenCalledWith(3, 7, '/schedule-worktrees/job-7-shared') + expect(removeAll).not.toHaveBeenCalled() expect(worktreeRemove).not.toHaveBeenCalled() }) @@ -196,7 +198,7 @@ describe('RepoWorkspaceService', () => { mocks.getSiblingRepos.mockResolvedValue([{ fullPath: '/schedule-worktrees/job-7-run-2', worktreeSource: 'schedule', - schedule: { repoId: 1, jobId: 7, runId: 2, inUse: true }, + schedule: { repoId: 1, jobId: 7, runId: 2, inUse: true, name: 'Run job' }, }]) const { service, removeScheduleWorktrees } = createService({ removeAll }) @@ -222,8 +224,8 @@ describe('RepoWorkspaceService', () => { 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', worktreeSource: 'opencode' }, - { fullPath: '/worktrees/b', worktreeStrategy: 'git', worktreeSource: 'opencode' }, + { fullPath: '/worktrees/a', worktreeSource: 'opencode' }, + { fullPath: '/worktrees/b', worktreeSource: 'opencode' }, { fullPath: '/repos/manager-worktree', isWorktree: true }, ]) const { service } = createService({ removeAll }) diff --git a/backend/test/services/repo.test.ts b/backend/test/services/repo.test.ts index 879224b4..7e515972 100644 --- a/backend/test/services/repo.test.ts +++ b/backend/test/services/repo.test.ts @@ -5,7 +5,7 @@ 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 type { RepoSibling } from '@opencode-manager/shared/utils' import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' @@ -536,7 +536,7 @@ describe('getSiblingRepos worktree API', () => { id: -1, fullPath: '/worktrees/feature-x', localPath: 'feature-x', - worktreeStrategy: 'git', + worktreeSource: 'opencode', }) expect(siblings[1]?.branch).toBeUndefined() expect(siblings[1]?.currentBranch).toBeUndefined() @@ -565,6 +565,7 @@ describe('getSiblingRepos worktree API', () => { 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_jobs (repo_id, name, prompt, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').run(1, 'nightly', 'check', Date.now(), Date.now()) 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) const client = createClient([ { directory: activePath, strategy: 'git' }, @@ -574,7 +575,7 @@ describe('getSiblingRepos worktree API', () => { const siblings = await getSiblingRepos(db, 1, {}, client) as SiblingRepo[] expect(siblings).toHaveLength(3) - expect(siblings[1]).toMatchObject({ fullPath: activePath, worktreeSource: 'schedule', schedule: { repoId: 1, jobId: 1, runId: 1, inUse: true } }) + expect(siblings[1]).toMatchObject({ fullPath: activePath, worktreeSource: 'schedule', schedule: { repoId: 1, jobId: 1, runId: 1, inUse: true, name: 'nightly' } }) expect(siblings[2]).toMatchObject({ fullPath: '/worktrees/feature-x', worktreeSource: 'opencode' }) }) diff --git a/backend/test/services/schedule-worktree.test.ts b/backend/test/services/schedule-worktree.test.ts index e0fa55b8..b5727356 100644 --- a/backend/test/services/schedule-worktree.test.ts +++ b/backend/test/services/schedule-worktree.test.ts @@ -274,7 +274,7 @@ describe('ScheduleWorktreeManager', () => { await removeWorktree(baseRepoPath, ctx!.worktreePath) }) - it('pruneRunArtifacts removes the worktree directory and deletes the run branch', async () => { + it('pruneRunArtifacts removes the worktree directory and deletes the run branch in discard mode', async () => { const manager = await createManager() const repo = testRepo() const job = { id: 90, branch: null, workspaceMode: 'worktree' as const } @@ -287,7 +287,7 @@ describe('ScheduleWorktreeManager', () => { const runBranch = ctx!.runBranch expect(existsSync(worktreePath)).toBe(true) - await manager.pruneRunArtifacts(repo, 90, [{ runBranch, worktreePath }]) + await manager.pruneRunArtifacts(repo, { id: 90, name: 'Prune job' }, [{ runBranch, worktreePath }], 'discard') expect(existsSync(worktreePath)).toBe(false) const branchList = execSync(`git -C "${baseRepoPath}" branch --list "${runBranch}"`, { @@ -296,12 +296,61 @@ describe('ScheduleWorktreeManager', () => { expect(branchList).toBe('') }) - it('prepare returns null in repo mode so the run works in the checkout', async () => { + it('pruneRunArtifacts commits a kept worktree and keeps its branch in commit mode', async () => { const manager = await createManager() - const ctx = await manager.prepare(testRepo(), { id: 30, branch: null, workspaceMode: 'repo' }, 1) + const repo = testRepo() + const job = { id: 91, branch: null, name: 'Commit prune', workspaceMode: 'kept-worktree' as const } + const runId = 910 - expect(ctx).toBeNull() - expect(manager.listWorktrees(30)).toEqual([]) + const ctx = await manager.prepare(repo, job, runId) + expect(ctx).not.toBeNull() + writeFileSync(path.join(ctx!.worktreePath, 'pending.md'), 'pending work') + + await manager.pruneRunArtifacts(repo, { id: 91, name: 'Commit prune' }, [{ runBranch: ctx!.runBranch, worktreePath: ctx!.worktreePath }], 'commit') + + expect(existsSync(ctx!.worktreePath)).toBe(false) + const branchList = execSync(`git -C "${baseRepoPath}" branch --list "${ctx!.runBranch}"`, { + encoding: 'utf-8', + }).trim() + expect(branchList).not.toBe('') + const log = execSync(`git -C "${baseRepoPath}" log "${ctx!.runBranch}" --oneline`, { encoding: 'utf-8' }) + expect(log).toContain('Schedule worktree removed: Commit prune') + }) + + it('pruneRunArtifacts deletes the branch of a run whose worktree is already gone in commit mode', async () => { + const manager = await createManager() + const repo = testRepo() + const job = { id: 92, branch: null, workspaceMode: 'kept-worktree' as const } + const runId = 920 + + const ctx = await manager.prepare(repo, job, runId) + const { removeWorktree } = await import('../../src/services/repo') + await removeWorktree(baseRepoPath, ctx!.worktreePath) + expect(existsSync(ctx!.worktreePath)).toBe(false) + + await manager.pruneRunArtifacts(repo, { id: 92, name: 'Gone prune' }, [{ runBranch: ctx!.runBranch, worktreePath: ctx!.worktreePath }], 'commit') + + const branchList = execSync(`git -C "${baseRepoPath}" branch --list "${ctx!.runBranch}"`, { + encoding: 'utf-8', + }).trim() + expect(branchList).toBe('') + }) + + it('prepare refuses when the run branch is checked out in another worktree', async () => { + const manager = await createManager() + const repo = testRepo() + const otherPath = path.join(tmpDir, 'other-checkout') + const runBranch = 'schedule/40/run-1' + execSync(`git -C "${baseRepoPath}" worktree add -b "${runBranch}" "${otherPath}" main`, { env }) + + try { + const error = await manager.prepare(repo, { id: 40, branch: null, workspaceMode: 'worktree' }, 1).catch((caught: unknown) => caught) + expect((error as Error).message).toContain(`Branch ${runBranch} is checked out in`) + expect((error as Error).message).toContain('Switch that checkout to another branch so the schedule can run.') + } finally { + execSync(`git -C "${baseRepoPath}" worktree remove --force "${otherPath}"`, { env }) + execSync(`git -C "${baseRepoPath}" branch -D "${runBranch}"`, { env }) + } }) it('finalize commits but keeps the worktree on its branch in kept-worktree mode', async () => { @@ -336,22 +385,35 @@ describe('ScheduleWorktreeManager', () => { 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 }]) + await manager.pruneRunArtifacts(repo, { id: 32, name: 'Shared job' }, [{ 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) }) + + it('refuses to reuse a shared worktree with uncommitted changes made outside a run', async () => { + const manager = await createManager() + const repo = testRepo() + const job = { id: 33, branch: null, name: 'Dirty shared', prompt: '', workspaceMode: 'shared-worktree' as const } + const sharedPath = path.join(scheduleWorktreesRoot, 'job-33-shared') + + await manager.prepare(repo, job, 1) + writeFileSync(path.join(sharedPath, 'outside.md'), 'outside edit') + + await expect(manager.prepare(repo, job, 2)).rejects.toThrow( + `Shared worktree ${sharedPath} has uncommitted changes made outside a scheduled run.`, + ) + + await manager.releaseWorktree(repo, job, sharedPath) + }) }) diff --git a/backend/test/services/schedules.test.ts b/backend/test/services/schedules.test.ts index 039eba0d..6448b592 100644 --- a/backend/test/services/schedules.test.ts +++ b/backend/test/services/schedules.test.ts @@ -1,6 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import path from 'path' import type { ScheduleJob, ScheduleRun } from '@opencode-manager/shared/types' import type { OpenCodeApi } from '@opencode-manager/shared/opencode' +import { getScheduleWorktreesPath } from '@opencode-manager/shared/config/env' const mocks = vi.hoisted(() => ({ getRepoById: vi.fn(), @@ -16,6 +18,7 @@ const mocks = vi.hoisted(() => ({ getScheduleRunById: vi.fn(), listEnabledScheduleJobs: vi.fn(), listRunningScheduleRuns: vi.fn(), + listScheduleJobWorktreeOwners: vi.fn(), clearScheduleRunWorktreePath: vi.fn(), listScheduleJobIdsByRepo: vi.fn(), listScheduleJobsByRepo: vi.fn(), @@ -58,6 +61,7 @@ vi.mock('../../src/db/schedules', () => ({ getScheduleRunById: mocks.getScheduleRunById, listEnabledScheduleJobs: mocks.listEnabledScheduleJobs, listRunningScheduleRuns: mocks.listRunningScheduleRuns, + listScheduleJobWorktreeOwners: mocks.listScheduleJobWorktreeOwners, clearScheduleRunWorktreePath: mocks.clearScheduleRunWorktreePath, listScheduleJobIdsByRepo: mocks.listScheduleJobIdsByRepo, listScheduleJobsByRepo: mocks.listScheduleJobsByRepo, @@ -187,6 +191,7 @@ describe('ScheduleService', () => { mocks.getRepoById.mockReturnValue(repo) mocks.getScheduleJobById.mockReturnValue(job) mocks.getRunningScheduleRunByJob.mockReturnValue(null) + mocks.listScheduleJobWorktreeOwners.mockReturnValue([{ id: job.id, repoId: job.repoId, name: job.name }]) mocks.createScheduleRun.mockReturnValue(baseRun) mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', id: 'gpt-5-mini', model: 'openai/gpt-5-mini' }) mocks.onEvent.mockReturnValue(vi.fn()) @@ -915,6 +920,18 @@ describe('ScheduleService', () => { expect(stub.api.agent.list).toHaveBeenCalledTimes(1) }) + it('rejects changing the workspace mode while a run is in progress', async () => { + const stub = createStubScheduleApi() + const service = makeService(stub.api) + Reflect.get(ScheduleService, 'activeRuns').set(7, { runId: 5, abort: new AbortController() }) + + await expect(service.updateJob(42, 7, { workspaceMode: 'kept-worktree' })).rejects.toMatchObject({ + message: 'Cannot change where runs execute while a run is in progress.', + status: 409, + }) + expect(mocks.updateScheduleJob).not.toHaveBeenCalled() + }) + it('throws when deleting or loading missing records', async () => { const stub = createStubScheduleApi() const service = makeService(stub.api) @@ -942,7 +959,7 @@ describe('ScheduleService', () => { 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', () => { + it('blocks prepareRepoDelete when a running run exists in activeRuns', async () => { const stub = createStubScheduleApi() const service = makeService(stub.api) const onJobChange = vi.fn() @@ -950,11 +967,11 @@ describe('ScheduleService', () => { mocks.listScheduleJobIdsByRepo.mockReturnValue([7, 8]) Reflect.get(ScheduleService, 'activeRuns').set(7, { runId: 5, abort: new AbortController() }) - expect(() => service.prepareRepoDelete(42)).toThrow('Cannot delete a repo while a schedule run is in progress. Cancel the run first.') + await expect(service.prepareRepoDelete(42)).rejects.toThrow('Cannot delete a repo while a schedule run is in progress. Cancel the run first.') expect(onJobChange).not.toHaveBeenCalled() }) - it('blocks prepareRepoDelete when a database running run exists', () => { + it('blocks prepareRepoDelete when a database running run exists', async () => { const stub = createStubScheduleApi() const service = makeService(stub.api) const onJobChange = vi.fn() @@ -962,7 +979,7 @@ describe('ScheduleService', () => { mocks.listScheduleJobIdsByRepo.mockReturnValue([7, 8]) mocks.getRunningScheduleRunByJob.mockReturnValue({ ...baseRun, status: 'running' }) - expect(() => service.prepareRepoDelete(42)).toThrow('Cannot delete a repo while a schedule run is in progress. Cancel the run first.') + await expect(service.prepareRepoDelete(42)).rejects.toThrow('Cannot delete a repo while a schedule run is in progress. Cancel the run first.') expect(onJobChange).not.toHaveBeenCalled() }) @@ -979,19 +996,23 @@ describe('ScheduleService', () => { expect(onJobChange).toHaveBeenCalledWith(null, 7) }) - it('prepares repo deletion by unregistering repo jobs without deleting records', () => { + it('prepares repo deletion by unregistering repo jobs and removing their worktrees without deleting records', async () => { const stub = createStubScheduleApi() const service = makeService(stub.api) const onJobChange = vi.fn() service.setJobChangeHandler(onJobChange) + const removeWorktrees = vi.spyOn(service, 'removeWorktrees').mockResolvedValue({ removed: 0 }) mocks.listScheduleJobIdsByRepo.mockReturnValue([7, 8]) - service.prepareRepoDelete(42) + await service.prepareRepoDelete(42) expect(mocks.listScheduleJobIdsByRepo).toHaveBeenCalledWith(expect.anything(), 42) expect(onJobChange).toHaveBeenCalledWith(null, 7) expect(onJobChange).toHaveBeenCalledWith(null, 8) expect(onJobChange).toHaveBeenCalledTimes(2) + expect(removeWorktrees).toHaveBeenCalledWith(42, 7) + expect(removeWorktrees).toHaveBeenCalledWith(42, 8) + expect(mocks.deleteScheduleJob).not.toHaveBeenCalled() }) it('cancels by finalizing the run when the assistant already completed', async () => { @@ -1238,6 +1259,7 @@ describe('ScheduleService startup cancellation', () => { mocks.getRepoById.mockReturnValue(repo) mocks.getScheduleJobById.mockReturnValue(job) mocks.getRunningScheduleRunByJob.mockReturnValue(null) + mocks.listScheduleJobWorktreeOwners.mockReturnValue([{ id: job.id, repoId: job.repoId, name: job.name }]) mocks.createScheduleRun.mockReturnValue(baseRun) mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', id: 'gpt-5-mini', model: 'openai/gpt-5-mini' }) mocks.onEvent.mockReturnValue(vi.fn()) @@ -1499,6 +1521,7 @@ describe('ScheduleService monitor cancellation', () => { mocks.getRepoById.mockReturnValue(repo) mocks.getScheduleJobById.mockReturnValue(job) mocks.getRunningScheduleRunByJob.mockReturnValue(null) + mocks.listScheduleJobWorktreeOwners.mockReturnValue([{ id: job.id, repoId: job.repoId, name: job.name }]) mocks.createScheduleRun.mockReturnValue(baseRun) mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', id: 'gpt-5-mini', model: 'openai/gpt-5-mini' }) mocks.onEvent.mockReturnValue(vi.fn()) @@ -2335,6 +2358,7 @@ describe('ScheduleService run history cleanup', () => { vi.clearAllMocks() mocks.getRepoById.mockReturnValue(repo) mocks.getScheduleJobById.mockReturnValue(job) + mocks.listScheduleJobWorktreeOwners.mockReturnValue([{ id: job.id, repoId: job.repoId, name: job.name }]) mocks.stubWorktreeManager.pruneRunArtifacts.mockResolvedValue(undefined) }) @@ -2356,14 +2380,28 @@ describe('ScheduleService run history cleanup', () => { const result = await makeService().clearRunHistory(42, 7) - expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, 7, [ + expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, job, [ { id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null }, { id: 1, status: 'failed', runBranch: null, worktreePath: null }, - ]) + ], 'commit') expect(mocks.deleteScheduleRunsByIds).toHaveBeenCalledWith({}, 42, 7, [3, 1]) expect(result).toEqual({ cleared: 2 }) }) + it('clearRunHistory forwards the discard worktrees mode to pruneRunArtifacts', async () => { + mocks.listScheduleRunArtifactsByJob.mockReturnValue([ + { id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: '/wt/3' }, + ]) + mocks.deleteScheduleRunsByIds.mockReturnValue(1) + + const result = await makeService().clearRunHistory(42, 7, 'discard') + + expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, job, [ + { id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: '/wt/3' }, + ], 'discard') + expect(result).toEqual({ cleared: 1 }) + }) + it('clearRunHistory is a no-op when only a running run exists', async () => { mocks.listScheduleRunArtifactsByJob.mockReturnValue([ { id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2' }, @@ -2382,25 +2420,27 @@ describe('ScheduleService run history cleanup', () => { await makeService().deleteRun(42, 7, 5) - expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, 7, [ + expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, job, [ { runBranch: 'schedule/7/run-5', worktreePath: '/wt/5' }, - ]) + ], 'commit') 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' }) + const root = getScheduleWorktreesPath() + const sharedPath = path.join(root, 'job-7-shared') + const runningPath = path.join(root, 'job-7-run-9') + mocks.listRunningScheduleRuns.mockReturnValue([{ ...baseRun, status: 'running', worktreePath: runningPath }]) 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' }, + { jobId: 7, runId: 3, worktreePath: path.join(root, 'job-7-run-3'), branch: 'schedule/7/run-3' }, + { jobId: 7, runId: null, worktreePath: sharedPath, branch: 'schedule/7/shared' }, + { jobId: 7, runId: 9, worktreePath: runningPath, 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 }, + { worktreePath: sharedPath, branch: 'schedule/7/shared', runId: null, inUse: true }, + { worktreePath: runningPath, branch: 'schedule/7/run-9', runId: 9, inUse: true }, + { worktreePath: path.join(root, 'job-7-run-3'), branch: 'schedule/7/run-3', runId: 3, inUse: false }, ]) }) @@ -2428,4 +2468,62 @@ describe('ScheduleService run history cleanup', () => { expect(mocks.stubWorktreeManager.pruneRunArtifacts).not.toHaveBeenCalled() expect(mocks.deleteScheduleRunById).not.toHaveBeenCalled() }) + + it('deleteJob unregisters the job and reserves it before awaiting worktree removal', async () => { + const service = makeService() + const onJobChange = vi.fn() + service.setJobChangeHandler(onJobChange) + mocks.getRunningScheduleRunByJob.mockReturnValue(null) + mocks.listRunningScheduleRuns.mockReturnValue([]) + mocks.stubWorktreeManager.listWorktrees.mockReturnValue([ + { jobId: 7, runId: 3, worktreePath: '/wt/job-7-run-3', branch: 'schedule/7/run-3' }, + ]) + let resolveRelease!: () => void + mocks.stubWorktreeManager.releaseWorktree.mockReturnValueOnce(new Promise((resolve) => { resolveRelease = resolve })) + mocks.deleteScheduleJob.mockReturnValue(true) + + const deletePromise = service.deleteJob(42, 7) + await vi.waitFor(() => expect(mocks.stubWorktreeManager.releaseWorktree).toHaveBeenCalled()) + + expect(onJobChange).toHaveBeenCalledWith(null, 7) + expect(Reflect.get(ScheduleService, 'activeRuns').has(7)).toBe(true) + + resolveRelease() + await deletePromise + + expect(mocks.deleteScheduleJob).toHaveBeenCalledWith({}, 42, 7) + expect(Reflect.get(ScheduleService, 'activeRuns').has(7)).toBe(false) + }) + + it('deleteJob re-registers the job and releases the reservation when worktree removal fails', async () => { + const service = makeService() + const onJobChange = vi.fn() + service.setJobChangeHandler(onJobChange) + mocks.getRunningScheduleRunByJob.mockReturnValue(null) + mocks.listRunningScheduleRuns.mockReturnValue([]) + mocks.stubWorktreeManager.listWorktrees.mockReturnValue([ + { jobId: 7, runId: 3, worktreePath: '/wt/job-7-run-3', branch: 'schedule/7/run-3' }, + ]) + mocks.stubWorktreeManager.releaseWorktree.mockRejectedValueOnce(new Error('release failed')) + + await expect(service.deleteJob(42, 7)).rejects.toThrow('Failed to remove worktree') + + expect(onJobChange).toHaveBeenCalledWith(job, 7) + expect(mocks.deleteScheduleJob).not.toHaveBeenCalled() + expect(Reflect.get(ScheduleService, 'activeRuns').has(7)).toBe(false) + }) + + it('removeWorktrees removes the terminals of each released worktree', async () => { + const service = makeService() + const onWorktreeRemoved = vi.fn(async () => undefined) + service.setWorktreeRemovedHandler(onWorktreeRemoved) + mocks.listRunningScheduleRuns.mockReturnValue([]) + mocks.stubWorktreeManager.listWorktrees.mockReturnValue([ + { jobId: 7, runId: 3, worktreePath: '/wt/job-7-run-3', branch: 'schedule/7/run-3' }, + ]) + + await expect(service.removeWorktrees(42, 7)).resolves.toEqual({ removed: 1 }) + + expect(onWorktreeRemoved).toHaveBeenCalledWith('/wt/job-7-run-3') + }) }) diff --git a/frontend/src/api/repos.ts b/frontend/src/api/repos.ts index 66f97fe4..0c529f7c 100644 --- a/frontend/src/api/repos.ts +++ b/frontend/src/api/repos.ts @@ -3,7 +3,10 @@ import { FetchError, fetchWrapper, fetchWrapperVoid, fetchWrapperBlob } from './ import { API_BASE_URL } from '@/config' import { saveFile } from '@/lib/download' import type { CreateRepoWorkspaceRequest, DiscoverReposResponse, AssistantModeStatus, AssistantModeInitRequest, DeleteRepoRequest, DeleteRepoResult, RepoGitIdentity, WorktreeSetupResult } from '@opencode-manager/shared/types' -import type { RepoWorktreeSchedule, RepoWorktreeSource } from '@opencode-manager/shared/utils' +import type { RepoSibling } from '@opencode-manager/shared/utils' +import { formatScheduleWorktreeLabel } from '@/lib/schedules/schedule-worktree' + +export type { RepoSibling } from '@opencode-manager/shared/utils' export interface CreateRepoOptions { repoUrl?: string @@ -39,20 +42,13 @@ export async function getRepo(id: number): Promise { return fetchWrapper(`${API_BASE_URL}/api/repos/${id}`) } -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 || 'worktree' } export function worktreeSourceLabel(worktree: RepoSibling): string | null { if (worktree.schedule) { - return worktree.schedule.runId === null ? 'Schedule · shared' : `Schedule · run #${worktree.schedule.runId}` + return `Schedule · ${formatScheduleWorktreeLabel(worktree.schedule.runId)}` } if (worktree.worktreeSource === 'git') return 'Git' return worktree.worktreeSource === 'opencode' ? 'OpenCode' : null diff --git a/frontend/src/api/schedules.ts b/frontend/src/api/schedules.ts index f834cd98..715c8177 100644 --- a/frontend/src/api/schedules.ts +++ b/frontend/src/api/schedules.ts @@ -2,9 +2,11 @@ import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper' import { API_BASE_URL } from '@/config' import type { CreateScheduleJobRequest, + RemoveScheduleWorktreesRequest, ScheduleJob, ScheduleRun, ScheduleRunStatus, + ScheduleRunWorktreesMode, ScheduleWorktree, UpdateScheduleJobRequest, } from '@opencode-manager/shared/types' @@ -158,8 +160,9 @@ export async function cancelRepoScheduleRun(repoId: number, jobId: number, runId }) } -export async function clearRepoScheduleRuns(repoId: number, jobId: number): Promise<{ cleared: number }> { - return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs`, { +export async function clearRepoScheduleRuns(repoId: number, jobId: number, worktrees?: ScheduleRunWorktreesMode): Promise<{ cleared: number }> { + const qs = worktrees ? `?worktrees=${worktrees}` : '' + return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs${qs}`, { method: 'DELETE', }) } @@ -168,16 +171,17 @@ export async function listScheduleWorktrees(repoId: number, jobId: number): Prom return fetchWrapper(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/worktrees`) } -export async function removeScheduleWorktrees(repoId: number, jobId: number, worktreePath?: string): Promise<{ removed: number }> { +export async function removeScheduleWorktrees(repoId: number, jobId: number, request: RemoveScheduleWorktreesRequest = {}): 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 } : {}), + body: JSON.stringify(request), }) } -export async function deleteRepoScheduleRun(repoId: number, jobId: number, runId: number): Promise { - return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}`, { +export async function deleteRepoScheduleRun(repoId: number, jobId: number, runId: number, worktrees?: ScheduleRunWorktreesMode): Promise { + const qs = worktrees ? `?worktrees=${worktrees}` : '' + return fetchWrapperVoid(`${API_BASE_URL}/api/repos/${repoId}/schedules/${jobId}/runs/${runId}${qs}`, { method: 'DELETE', }) } diff --git a/frontend/src/components/repo/WorktreeSessionGroups.test.tsx b/frontend/src/components/repo/WorktreeSessionGroups.test.tsx index 0c5612c7..f152e457 100644 --- a/frontend/src/components/repo/WorktreeSessionGroups.test.tsx +++ b/frontend/src/components/repo/WorktreeSessionGroups.test.tsx @@ -15,7 +15,6 @@ const makeWorktree = (overrides: Partial & Pick void } = {}) { return render(
{session.title}
} + onExpandedScheduleDirectoriesChange={overrides.onExpandedScheduleDirectoriesChange} onNewSession={onNewSession} onOpenTerminal={onOpenTerminal} onCreateWorktree={onCreateWorktree} @@ -100,9 +100,9 @@ describe('WorktreeSessionGroups', () => { 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('Nightly')).toBeInTheDocument() + expect(screen.getByText('Schedule · Shared worktree')).toBeInTheDocument() + expect(screen.getByText('Schedule · Run #340')).toBeInTheDocument() expect(screen.getByText('in use')).toBeInTheDocument() expect(screen.getByText('Git')).toBeInTheDocument() @@ -157,7 +157,7 @@ describe('WorktreeSessionGroups', () => { expect(screen.getByText('manual')).toBeInTheDocument() expect(screen.queryByText('feature/auth')).not.toBeInTheDocument() - expect(screen.queryByText('Dependency audit')).not.toBeInTheDocument() + expect(screen.queryByText('Nightly')).not.toBeInTheDocument() }) it('collapses a worktree and persists the collapsed state across remount', async () => { @@ -172,12 +172,23 @@ describe('WorktreeSessionGroups', () => { expect(screen.queryByText('Auth work')).not.toBeInTheDocument() }) + it('reports a schedule worktree directory only after its group is expanded', async () => { + const onExpandedScheduleDirectoriesChange = vi.fn() + renderGroups({ onExpandedScheduleDirectoriesChange }) + + expect(onExpandedScheduleDirectoriesChange).toHaveBeenLastCalledWith([]) + + await userEvent.click(screen.getByRole('button', { expanded: false, name: /schedule\/14\/shared/ })) + + expect(onExpandedScheduleDirectoriesChange).toHaveBeenLastCalledWith(['/s/job-14-shared']) + }) + 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() + expect(screen.queryByText('Nightly')).not.toBeInTheDocument() unmount() renderGroups({ worktrees: [], sessions: [] }) diff --git a/frontend/src/components/repo/WorktreeSessionGroups.tsx b/frontend/src/components/repo/WorktreeSessionGroups.tsx index 14727ee6..caf97543 100644 --- a/frontend/src/components/repo/WorktreeSessionGroups.tsx +++ b/frontend/src/components/repo/WorktreeSessionGroups.tsx @@ -13,8 +13,8 @@ interface WorktreeSessionGroupsProps { worktrees: RepoSibling[] sessions: Session[] searchQuery: string - scheduleNames: Record renderSessionCard: (session: Session) => ReactNode + onExpandedScheduleDirectoriesChange?: (directories: string[]) => void onNewSession: (directory: string) => void onOpenTerminal: (directory: string) => void onCreateWorktree: () => void @@ -31,7 +31,7 @@ interface WorktreeGroup { type GroupEntry = | { kind: 'worktree'; key: string; group: WorktreeGroup; lastActive: number } - | { kind: 'schedule'; key: string; jobId: number; groups: WorktreeGroup[]; lastActive: number } + | { kind: 'schedule'; key: string; jobId: number; name: string; groups: WorktreeGroup[]; lastActive: number } const OWNER_FILTERS: Array<{ value: OwnerFilter; label: string }> = [ { value: 'all', label: 'All' }, @@ -57,8 +57,8 @@ export function WorktreeSessionGroups({ worktrees, sessions, searchQuery, - scheduleNames, renderSessionCard, + onExpandedScheduleDirectoriesChange, onNewSession, onOpenTerminal, onCreateWorktree, @@ -67,9 +67,21 @@ export function WorktreeSessionGroups({ }: WorktreeSessionGroupsProps) { const [ownerFilter, setOwnerFilter] = useState('all') const [collapsed, setCollapsed] = useCollapsedGroups(repoId) + const [expandedSchedule, setExpandedSchedule] = useState>(new Set()) const [pendingDelete, setPendingDelete] = useState<{ directories: string[]; label: string } | null>(null) const isSearching = searchQuery.trim().length > 0 + const scheduleWorktreeDirectories = useMemo( + () => worktrees.filter(isScheduleWorktree).map((worktree) => worktree.fullPath), + [worktrees], + ) + + useEffect(() => { + onExpandedScheduleDirectoriesChange?.( + scheduleWorktreeDirectories.filter((directory) => expandedSchedule.has(directory)), + ) + }, [expandedSchedule, scheduleWorktreeDirectories, onExpandedScheduleDirectoriesChange]) + const ownerCounts = useMemo(() => { const counts: Record = { all: worktrees.length, opencode: 0, schedule: 0, git: 0 } worktrees.forEach((worktree) => { @@ -92,10 +104,46 @@ export function WorktreeSessionGroups({ }) } - const allKeys = entries.flatMap((entry) => ( - entry.kind === 'schedule' ? [entry.key, ...entry.groups.map((group) => groupKey(group.directory))] : [entry.key] + const isGroupOpen = (group: WorktreeGroup) => ( + isScheduleWorktree(group.worktree) + ? expandedSchedule.has(group.directory) + : !collapsed.has(groupKey(group.directory)) + ) + + const toggleGroup = (group: WorktreeGroup) => { + if (isScheduleWorktree(group.worktree)) { + setExpandedSchedule((current) => { + const next = new Set(current) + if (next.has(group.directory)) next.delete(group.directory) + else next.add(group.directory) + return next + }) + return + } + toggle(groupKey(group.directory)) + } + + const scheduleGroupDirectories = entries.flatMap((entry) => ( + entry.kind === 'schedule' ? entry.groups.map((group) => group.directory) : [] )) - const allCollapsed = allKeys.length > 0 && allKeys.every((key) => collapsed.has(key)) + const allCollapsed = entries.length > 0 && entries.every((entry) => { + if (collapsed.has(entry.key)) return true + if (entry.kind === 'schedule') return entry.groups.every((group) => !expandedSchedule.has(group.directory)) + return false + }) + const toggleAll = () => { + if (allCollapsed) { + setCollapsed((current) => { + const next = new Set(current) + entries.forEach((entry) => next.delete(entry.key)) + return next + }) + setExpandedSchedule(new Set(scheduleGroupDirectories)) + return + } + setCollapsed(new Set(entries.map((entry) => entry.key))) + setExpandedSchedule(new Set()) + } if (worktrees.length === 0) { return ( @@ -112,7 +160,7 @@ export function WorktreeSessionGroups({ const renderWorktree = (group: WorktreeGroup, nested: boolean) => { const key = groupKey(group.directory) - const isOpen = !collapsed.has(key) + const isOpen = isGroupOpen(group) const label = workspaceLabel(group.worktree) const source = group.worktree.worktreeSource const sourceLabel = worktreeSourceLabel(group.worktree) @@ -122,7 +170,7 @@ export function WorktreeSessionGroups({
))}
-
)} - {workspaceMode !== 'repo' && ( -
-
- - -
- +
+
+ +
- )} + +
diff --git a/frontend/src/components/schedules/JobDetailTab.tsx b/frontend/src/components/schedules/JobDetailTab.tsx index f7d27e1f..1274cb59 100644 --- a/frontend/src/components/schedules/JobDetailTab.tsx +++ b/frontend/src/components/schedules/JobDetailTab.tsx @@ -11,6 +11,7 @@ import { } from '@/components/schedules/schedule-utils' import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils' import { useRemoveScheduleWorktrees, useScheduleWorktrees } from '@/hooks/useSchedules' +import { formatScheduleWorktreeLabel } from '@/lib/schedules/schedule-worktree' 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' @@ -139,7 +140,7 @@ export function JobDetailTab({

{worktree.branch}

- {worktree.runId === null ? 'Shared worktree' : `Run #${worktree.runId}`} + {formatScheduleWorktreeLabel(worktree.runId)} {worktree.inUse ? ' · in use' : ''} · {worktree.worktreePath}

diff --git a/frontend/src/components/schedules/ScheduleRunRemovalDialog.test.tsx b/frontend/src/components/schedules/ScheduleRunRemovalDialog.test.tsx new file mode 100644 index 00000000..6ef2a4c9 --- /dev/null +++ b/frontend/src/components/schedules/ScheduleRunRemovalDialog.test.tsx @@ -0,0 +1,47 @@ +import { describe, it, expect, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { ScheduleRunRemovalDialog } from './ScheduleRunRemovalDialog' + +type DialogProps = Parameters[0] + +function renderDialog(overrides: Partial = {}) { + const props: DialogProps = { + open: true, + onOpenChange: vi.fn(), + title: 'Delete run', + description: 'This permanently deletes this run.', + affectedWorktreeCount: 0, + isPending: false, + onCancel: vi.fn(), + onConfirm: vi.fn(), + ...overrides, + } + render() + return props +} + +describe('ScheduleRunRemovalDialog', () => { + it('confirms without a worktrees mode when no kept worktree is affected', async () => { + const user = userEvent.setup() + const props = renderDialog() + + await user.click(screen.getByRole('button', { name: 'Delete' })) + + expect(props.onConfirm).toHaveBeenCalledWith() + }) + + it('offers commit and force delete when kept worktrees are affected', async () => { + const user = userEvent.setup() + const onConfirm = vi.fn() + renderDialog({ affectedWorktreeCount: 2, onConfirm }) + + expect(screen.getByText(/2 kept worktrees will be removed/)).toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: 'Commit and remove' })) + expect(onConfirm).toHaveBeenCalledWith('commit') + + await user.click(screen.getByRole('button', { name: 'Force delete' })) + expect(onConfirm).toHaveBeenCalledWith('discard') + }) +}) diff --git a/frontend/src/components/schedules/ScheduleRunRemovalDialog.tsx b/frontend/src/components/schedules/ScheduleRunRemovalDialog.tsx new file mode 100644 index 00000000..eeb56473 --- /dev/null +++ b/frontend/src/components/schedules/ScheduleRunRemovalDialog.tsx @@ -0,0 +1,100 @@ +import type { ReactNode } from 'react' +import type { ScheduleRunWorktreesMode } from '@opencode-manager/shared/types' +import { Button } from '@/components/ui/button' +import { DeleteDialog } from '@/components/ui/delete-dialog' +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Alert, AlertDescription } from '@/components/ui/alert' +import { AlertTriangle, Loader2 } from 'lucide-react' + +interface ScheduleRunRemovalDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + title: string + description: ReactNode + affectedWorktreeCount: number + isPending: boolean + onCancel: () => void + onConfirm: (worktrees?: ScheduleRunWorktreesMode) => void +} + +export function ScheduleRunRemovalDialog({ + open, + onOpenChange, + title, + description, + affectedWorktreeCount, + isPending, + onCancel, + onConfirm, +}: ScheduleRunRemovalDialogProps) { + if (affectedWorktreeCount === 0) { + return ( + onConfirm()} + onCancel={onCancel} + title={title} + description={description} + isDeleting={isPending} + /> + ) + } + + const worktreeLabel = `${affectedWorktreeCount} kept worktree${affectedWorktreeCount === 1 ? '' : 's'}` + + return ( + + + + {title} + {description} + + + + + + {worktreeLabel} will be removed. Choose how to handle {affectedWorktreeCount === 1 ? 'it' : 'them'}. + + + +
+

+ Commit and remove — pending changes are committed to each run branch, then the worktree folders are removed. The branches are kept. +

+

+ Force delete — the worktree folders are force-removed and their run branches deleted. Any uncommitted changes are lost. +

+
+ + + + + + +
+
+ ) +} diff --git a/frontend/src/components/schedules/index.ts b/frontend/src/components/schedules/index.ts index c8c33362..b2e18d1f 100644 --- a/frontend/src/components/schedules/index.ts +++ b/frontend/src/components/schedules/index.ts @@ -1,6 +1,7 @@ export { ScheduleJobsTable } from './ScheduleJobsTable' export { JobDetailTab } from './JobDetailTab' export { RunHistoryTab } from './RunHistoryTab' +export { ScheduleRunRemovalDialog } from './ScheduleRunRemovalDialog' export { ScheduleRunDrawer } from './ScheduleRunDrawer' export { ScheduleRunsTable } from './ScheduleRunsTable' export { RunDetailPanel } from './RunDetailPanel' diff --git a/frontend/src/components/schedules/schedule-utils.ts b/frontend/src/components/schedules/schedule-utils.ts index 450eb319..a62f4bd1 100644 --- a/frontend/src/components/schedules/schedule-utils.ts +++ b/frontend/src/components/schedules/schedule-utils.ts @@ -56,11 +56,6 @@ export const workspaceModeOptions: Array> = [ 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 { diff --git a/frontend/src/components/session/SessionCard.tsx b/frontend/src/components/session/SessionCard.tsx index 8fe65643..16e5e5d1 100644 --- a/frontend/src/components/session/SessionCard.tsx +++ b/frontend/src/components/session/SessionCard.tsx @@ -14,7 +14,6 @@ interface SessionCardProps { isSelected: boolean; isActive: boolean; manageMode: boolean; - workspaceLabel?: string; isPinned?: boolean; onTogglePin?: () => void; onSelect: (sessionID: string) => void; @@ -27,7 +26,6 @@ export const SessionCard = ({ isSelected, isActive, manageMode, - workspaceLabel, isPinned, onTogglePin, onSelect, @@ -117,9 +115,6 @@ export const SessionCard = ({ addSuffix: true, })} - {workspaceLabel ? ( - {workspaceLabel} - ) : null}
@@ -139,9 +134,6 @@ export const SessionCard = ({ addSuffix: true, })} - {workspaceLabel ? ( - {workspaceLabel} - ) : null} diff --git a/frontend/src/components/session/SessionList.tsx b/frontend/src/components/session/SessionList.tsx index 07f04bfe..f8a140a2 100644 --- a/frontend/src/components/session/SessionList.tsx +++ b/frontend/src/components/session/SessionList.tsx @@ -16,7 +16,6 @@ interface SessionListProps { directory?: string; directories?: string[]; createDirectory?: string; - directoryLabels?: Record; activeSessionID?: string; onSelectSession: (sessionID: string) => void; renderSessions?: (args: SessionListRenderArgs) => ReactNode; @@ -36,7 +35,6 @@ export const SessionList = ({ directory, directories, createDirectory, - directoryLabels, activeSessionID, onSelectSession, renderSessions, @@ -220,7 +218,6 @@ export const SessionList = ({ isSelected={selectedSessions.has(key)} isActive={activeSessionID === session.id} manageMode={manageMode} - workspaceLabel={directoryLabels?.[session.location.directory]} isPinned={isPinned} onSelect={onSelectSession} onToggleSelection={(selected) => toggleSessionSelection(session, selected)} diff --git a/frontend/src/hooks/useSchedules.ts b/frontend/src/hooks/useSchedules.ts index 70957e40..a3dd7c24 100644 --- a/frontend/src/hooks/useSchedules.ts +++ b/frontend/src/hooks/useSchedules.ts @@ -1,5 +1,5 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import type { CreateScheduleJobRequest, UpdateScheduleJobRequest } from '@opencode-manager/shared/types' +import type { CreateScheduleJobRequest, ScheduleRunWorktreesMode, UpdateScheduleJobRequest } from '@opencode-manager/shared/types' import { cancelRepoScheduleRun, clearRepoScheduleRuns, @@ -224,8 +224,8 @@ export function useClearRepoScheduleRuns() { const queryClient = useQueryClient() return useMutation({ - mutationFn: async ({ repoId, jobId }: { repoId: number; jobId: number }) => { - return clearRepoScheduleRuns(repoId, jobId) + mutationFn: async ({ repoId, jobId, worktrees }: { repoId: number; jobId: number; worktrees?: ScheduleRunWorktreesMode }) => { + return clearRepoScheduleRuns(repoId, jobId, worktrees) }, onSuccess: (result, variables) => { queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', variables.repoId, variables.jobId] }) @@ -243,8 +243,8 @@ export function useDeleteRepoScheduleRun() { const queryClient = useQueryClient() return useMutation({ - mutationFn: ({ repoId, jobId, runId }: { repoId: number; jobId: number; runId: number }) => { - return deleteRepoScheduleRun(repoId, jobId, runId) + mutationFn: ({ repoId, jobId, runId, worktrees }: { repoId: number; jobId: number; runId: number; worktrees?: ScheduleRunWorktreesMode }) => { + return deleteRepoScheduleRun(repoId, jobId, runId, worktrees) }, onSuccess: (_data, variables) => { queryClient.invalidateQueries({ queryKey: ['repo-schedule-runs', variables.repoId, variables.jobId] }) @@ -275,7 +275,7 @@ export function useRemoveScheduleWorktrees() { return useMutation({ mutationFn: ({ repoId, jobId, worktreePath }: { repoId: number; jobId: number; worktreePath?: string }) => { - return removeScheduleWorktrees(repoId, jobId, worktreePath) + return removeScheduleWorktrees(repoId, jobId, worktreePath ? { worktreePath } : {}) }, onSuccess: (result, variables) => { queryClient.invalidateQueries({ queryKey: ['schedule-worktrees', variables.repoId, variables.jobId] }) diff --git a/frontend/src/lib/schedules/schedule-worktree.ts b/frontend/src/lib/schedules/schedule-worktree.ts new file mode 100644 index 00000000..2e6c5ccc --- /dev/null +++ b/frontend/src/lib/schedules/schedule-worktree.ts @@ -0,0 +1,3 @@ +export function formatScheduleWorktreeLabel(runId: number | null): string { + return runId === null ? 'Shared worktree' : `Run #${runId}` +} diff --git a/frontend/src/pages/RepoDetail.tsx b/frontend/src/pages/RepoDetail.tsx index 9ebd3be2..f4608f49 100644 --- a/frontend/src/pages/RepoDetail.tsx +++ b/frontend/src/pages/RepoDetail.tsx @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState, type FormEvent } from "react"; +import { useCallback, useEffect, useMemo, useState, type FormEvent } from "react"; import { useParams, useNavigate } from "react-router-dom"; import { useQuery } from "@tanstack/react-query"; import { getRepo } from "@/api/repos"; @@ -22,7 +22,6 @@ import { useOpenTerminal, useTerminalDialogParam, useTerminalDirectoryParam } fr import { useWorktreeTab } from "@/hooks/useWorktreeTab"; import { WorktreeTabs } from "@/components/repo/WorktreeTabs"; 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"; @@ -70,30 +69,56 @@ export function RepoDetail() { [siblings], ); - const workspaceDirectories = useMemo( - () => workspaceSiblings.map((sibling) => sibling.fullPath).filter(Boolean), + const scheduleDirectorySet = useMemo( + () => new Set( + workspaceSiblings + .filter((sibling) => sibling.worktreeSource === 'schedule') + .map((sibling) => sibling.fullPath), + ), [workspaceSiblings], ); - const { data: allSchedules } = useAllSchedules(); - const scheduleNames = useMemo(() => { - const names: Record = {}; - (allSchedules ?? []).forEach((job) => { - if (job.repoId === repoId) names[job.id] = job.name; - }); - return names; - }, [allSchedules, repoId]); + const nonScheduleWorkspaceDirectories = useMemo( + () => workspaceSiblings + .filter((sibling) => sibling.worktreeSource !== 'schedule') + .map((sibling) => sibling.fullPath) + .filter(Boolean), + [workspaceSiblings], + ); + + const [expandedScheduleDirectories, setExpandedScheduleDirectories] = useState([]); + + const activeScheduleDirectories = useMemo( + () => expandedScheduleDirectories.filter((directory) => scheduleDirectorySet.has(directory)), + [expandedScheduleDirectories, scheduleDirectorySet], + ); + + const handleExpandedScheduleDirectoriesChange = useCallback((directories: string[]) => { + setExpandedScheduleDirectories((current) => + current.length === directories.length && current.every((directory, index) => directory === directories[index]) + ? current + : directories, + ); + }, []); const baseDirectory = repo?.fullPath; const subscriptionDirectories = useMemo(() => { const set = new Set(); if (baseDirectory) set.add(baseDirectory); - workspaceDirectories.forEach((dir) => set.add(dir)); + nonScheduleWorkspaceDirectories.forEach((dir) => set.add(dir)); + activeScheduleDirectories.forEach((dir) => set.add(dir)); return Array.from(set); - }, [baseDirectory, workspaceDirectories]); + }, [baseDirectory, nonScheduleWorkspaceDirectories, activeScheduleDirectories]); const showWorktrees = activeTab === 'workspaces'; - const sessionListDirectories = showWorktrees ? workspaceDirectories : (baseDirectory ? [baseDirectory] : []); + const sessionListDirectories = useMemo(() => { + if (!showWorktrees) return baseDirectory ? [baseDirectory] : []; + return Array.from(new Set([...nonScheduleWorkspaceDirectories, ...activeScheduleDirectories])); + }, [showWorktrees, baseDirectory, nonScheduleWorkspaceDirectories, activeScheduleDirectories]); + + useEffect(() => { + if (!showWorktrees) setExpandedScheduleDirectories([]); + }, [showWorktrees]); useSSE(subscriptionDirectories); @@ -138,8 +163,8 @@ export function RepoDetail() { worktrees={workspaceSiblings} sessions={sessions} searchQuery={searchQuery} - scheduleNames={scheduleNames} renderSessionCard={renderSessionCard} + onExpandedScheduleDirectoriesChange={handleExpandedScheduleDirectoriesChange} onNewSession={handleCreateSession} onOpenTerminal={(directory) => openTerminal(null, { repoTab: "workspaces", terminalDirectory: directory })} onCreateWorktree={() => setCreateWorkspaceOpen(true)} diff --git a/frontend/src/pages/Schedules.tsx b/frontend/src/pages/Schedules.tsx index c1349d3d..27744681 100644 --- a/frontend/src/pages/Schedules.tsx +++ b/frontend/src/pages/Schedules.tsx @@ -1,6 +1,6 @@ import { useEffect, useMemo, useState } from 'react' import { useLocation, useParams } from 'react-router-dom' -import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types' +import type { CreateScheduleJobRequest, ScheduleJob, ScheduleRunWorktreesMode } from '@opencode-manager/shared/types' import { useAllSchedules, useCancelRepoScheduleRun, @@ -11,12 +11,13 @@ import { useRepoSchedule, useRepoScheduleRuns, useRunRepoSchedule, + useScheduleWorktrees, useUpdateRepoSchedule, } from '@/hooks/useSchedules' 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 { ScheduleJobDialog, ScheduleJobsTable, ScheduleListToolbar, JobDetailTab, RunHistoryTab, ScheduleRunRemovalDialog, ScheduleTabMenu } from '@/components/schedules' import { DELETE_SCHEDULE_DESCRIPTION, matchesScheduleJobSearch, toUpdateScheduleRequest } from '@/components/schedules/schedule-utils' import type { ScheduleJobWithRepo } from '@/api/schedules' import { Header } from '@/components/ui/header' @@ -60,6 +61,7 @@ export function Schedules() { ) const { data: selectedJob, isFetching: isJobFetching } = useRepoSchedule(repoId, jobId) const { data: runs, isLoading: runsLoading } = useRepoScheduleRuns(repoId, jobId, 30) + const { data: scheduleWorktrees = [] } = useScheduleWorktrees(repoId, jobId) const createMutation = useCreateRepoSchedule() const updateMutation = useUpdateRepoSchedule() @@ -74,8 +76,14 @@ export function Schedules() { const [runToDelete, setRunToDelete] = useState(null) const clearableRuns = useMemo(() => (runs ?? []).filter((run) => run.status !== 'running'), [runs]) - const clearableWorktrees = useMemo(() => clearableRuns.filter((run) => run.worktreePath).length, [clearableRuns]) - const clearableBranches = useMemo(() => clearableRuns.filter((run) => run.runBranch).length, [clearableRuns]) + const affectedClearWorktreeCount = useMemo( + () => scheduleWorktrees.filter((worktree) => worktree.runId !== null && !worktree.inUse).length, + [scheduleWorktrees], + ) + const runToDeleteWorktreeCount = useMemo( + () => (runToDelete !== null && scheduleWorktrees.some((worktree) => worktree.runId === runToDelete) ? 1 : 0), + [scheduleWorktrees, runToDelete], + ) useEffect(() => { if (scheduleTab === 'prompts') { @@ -224,22 +232,22 @@ export function Schedules() { }) } - const handleClearHistory = () => { + const handleClearHistory = (worktrees?: ScheduleRunWorktreesMode) => { if (jobId === null) { return } - clearRunsMutation.mutate({ repoId: repoId!, jobId }, { + clearRunsMutation.mutate({ repoId: repoId!, jobId, worktrees }, { onSuccess: () => setClearRunsOpen(false), }) } - const handleConfirmDeleteRun = () => { + const handleConfirmDeleteRun = (worktrees?: ScheduleRunWorktreesMode) => { if (jobId === null || runToDelete === null) { return } - deleteRunMutation.mutate({ repoId: repoId!, jobId, runId: runToDelete }, { + deleteRunMutation.mutate({ repoId: repoId!, jobId, runId: runToDelete, worktrees }, { onSuccess: () => setRunToDelete(null), }) } @@ -374,40 +382,28 @@ export function Schedules() { isDeleting={deleteMutation.isPending} /> - !open && setClearRunsOpen(false)} - onConfirm={handleClearHistory} - onCancel={() => setClearRunsOpen(false)} title="Clear run history" description={ - <> -

This permanently deletes all {clearableRuns.length} finished run{clearableRuns.length === 1 ? '' : 's'} for this schedule.

- {clearableBranches > 0 && ( -

Git artifacts that will be pruned:

- )} -
    - {clearableWorktrees > 0 && ( -
  • {clearableWorktrees} worktree{clearableWorktrees === 1 ? '' : 's'}
  • - )} - {clearableBranches > 0 && ( -
  • {clearableBranches} run branch{clearableBranches === 1 ? '' : 'es'}
  • - )} -
-

A run in progress is kept. This cannot be undone.

- +

This permanently deletes all {clearableRuns.length} finished run{clearableRuns.length === 1 ? '' : 's'} for this schedule. A run in progress is kept. This cannot be undone.

} - isDeleting={clearRunsMutation.isPending} + affectedWorktreeCount={affectedClearWorktreeCount} + isPending={clearRunsMutation.isPending} + onCancel={() => setClearRunsOpen(false)} + onConfirm={handleClearHistory} /> - !open && setRunToDelete(null)} - onConfirm={handleConfirmDeleteRun} - onCancel={() => setRunToDelete(null)} title="Delete run" - description="This permanently deletes this run along with its git run branch and worktree. This cannot be undone." - isDeleting={deleteRunMutation.isPending} + description="This permanently deletes this run. This cannot be undone." + affectedWorktreeCount={runToDeleteWorktreeCount} + isPending={deleteRunMutation.isPending} + onCancel={() => setRunToDelete(null)} + onConfirm={handleConfirmDeleteRun} /> ) diff --git a/frontend/src/pages/__tests__/RepoDetail.schedule-sessions.test.tsx b/frontend/src/pages/__tests__/RepoDetail.schedule-sessions.test.tsx new file mode 100644 index 00000000..d64c3fbf --- /dev/null +++ b/frontend/src/pages/__tests__/RepoDetail.schedule-sessions.test.tsx @@ -0,0 +1,171 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, Route, Routes } from 'react-router-dom' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import type { ReactNode } from 'react' +import type { Repo, Session } from '@/api/types' +import type { RepoSibling } from '@/api/repos' +import { RepoDetail } from '../RepoDetail' + +interface SessionListCapture { + directories?: string[] + renderSessions?: (args: { + sessions: Session[] + searchQuery: string + renderSessionCard: (session: Session) => ReactNode + }) => ReactNode +} + +const mocks = vi.hoisted(() => ({ + getRepo: vi.fn(), + useRepoSiblings: vi.fn(), + useCreateRepoWorkspace: vi.fn(), + useDeleteRepoWorkspaces: vi.fn(), + useRepoActivity: vi.fn(), + useSSE: vi.fn(), + useCreateSession: vi.fn(), + lastSessionListProps: { current: undefined as SessionListCapture | undefined }, +})) + +vi.mock('@/api/repos', () => ({ + getRepo: mocks.getRepo, + workspaceLabel: (workspace: { currentBranch?: string; branch?: string; localPath?: string }) => + workspace.currentBranch || workspace.branch || workspace.localPath || 'worktree', + worktreeSourceLabel: (worktree: { schedule?: { runId: number | null }; worktreeSource?: string }) => { + 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 + }, +})) + +vi.mock('@/lib/toast', () => ({ + showToast: { + success: vi.fn(), + info: vi.fn(), + warning: vi.fn(), + error: vi.fn(), + }, +})) + +vi.mock('@/hooks/useRepoSiblings', () => ({ + useRepoSiblings: mocks.useRepoSiblings, + useCreateRepoWorkspace: mocks.useCreateRepoWorkspace, + useDeleteRepoWorkspaces: mocks.useDeleteRepoWorkspaces, +})) + +vi.mock('@/hooks/useRepoActivity', () => ({ useRepoActivity: mocks.useRepoActivity })) +vi.mock('@/hooks/useSSE', () => ({ useSSE: mocks.useSSE })) +vi.mock('@/hooks/useOpenCode', () => ({ useCreateSession: mocks.useCreateSession })) + +vi.mock('@/components/session/SessionList', () => ({ + SessionList: (props: SessionListCapture) => { + mocks.lastSessionListProps.current = props + return ( +
+ {props.renderSessions?.({ + sessions: [], + searchQuery: '', + renderSessionCard: () => null, + })} +
+ ) + }, +})) + +vi.mock('@/components/repo/WorktreeTabs', () => ({ + WorktreeTabs: ({ onValueChange }: { onValueChange: (value: 'workspaces') => void }) => ( + + ), +})) + +vi.mock('@/components/terminal/TerminalPanel', () => ({ TerminalPanel: () => null })) +vi.mock('@/components/file-browser/FileBrowserSheet', () => ({ FileBrowserSheet: () => null })) +vi.mock('@/components/repo/RepoMcpDialog', () => ({ RepoMcpDialog: () => null })) +vi.mock('@/components/repo/ProjectActionsMenu', () => ({ ProjectActionsMenu: () => null })) +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/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: () => null })) +vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null })) + +const baseRepo: Repo = { + id: 1, + name: 'my-repo', + localPath: 'repos/my-repo', + fullPath: '/abs/repos/my-repo', + defaultBranch: 'main', + currentBranch: 'main', + branch: 'main', + cloneStatus: 'ready', + clonedAt: 1, + isWorktree: false, +} + +const opencodeWorktree: RepoSibling = { + ...baseRepo, + id: 2, + fullPath: '/abs/repos/my-repo-ws', + currentBranch: 'feature/x', + branch: 'feature/x', + isWorktree: true, + worktreeSource: 'opencode', +} + +const scheduleWorktree: RepoSibling = { + ...baseRepo, + id: 3, + fullPath: '/abs/repos/schedule-nightly', + currentBranch: 'schedule/5/run-7', + branch: 'schedule/5/run-7', + isWorktree: true, + worktreeSource: 'schedule', + schedule: { repoId: 1, jobId: 5, runId: 7, inUse: false, name: 'Nightly' }, +} + +function renderRepoDetail() { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return render( + + + + } /> + + + , + ) +} + +describe('RepoDetail schedule session fetching', () => { + beforeEach(() => { + vi.clearAllMocks() + mocks.lastSessionListProps.current = undefined + mocks.getRepo.mockResolvedValue(baseRepo) + mocks.useRepoSiblings.mockReturnValue({ data: [opencodeWorktree, scheduleWorktree] }) + mocks.useCreateRepoWorkspace.mockReturnValue({ mutate: vi.fn(), isPending: false }) + mocks.useDeleteRepoWorkspaces.mockReturnValue({ mutate: vi.fn(), isPending: false }) + mocks.useCreateSession.mockReturnValue({ mutate: vi.fn(), isPending: false }) + }) + + it('fetches a schedule worktree directory only after its group is expanded', async () => { + const user = userEvent.setup() + renderRepoDetail() + + await user.click(await screen.findByRole('button', { name: 'Worktrees tab' })) + + await waitFor(() => { + expect(mocks.lastSessionListProps.current?.directories).toEqual(['/abs/repos/my-repo-ws']) + }) + + await user.click(screen.getByRole('button', { expanded: false, name: /schedule\/5\/run-7/ })) + + await waitFor(() => { + expect(mocks.lastSessionListProps.current?.directories).toEqual([ + '/abs/repos/my-repo-ws', + '/abs/repos/schedule-nightly', + ]) + }) + }) +}) diff --git a/frontend/src/pages/__tests__/RepoDetail.worktree-setup.test.tsx b/frontend/src/pages/__tests__/RepoDetail.worktree-setup.test.tsx index 46c84bec..203b27e1 100644 --- a/frontend/src/pages/__tests__/RepoDetail.worktree-setup.test.tsx +++ b/frontend/src/pages/__tests__/RepoDetail.worktree-setup.test.tsx @@ -64,7 +64,6 @@ 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('@/hooks/useSchedules', () => ({ useAllSchedules: () => ({ data: [] }) })) vi.mock('@/components/repo/ResetPermissionsDialog', () => ({ ResetPermissionsDialog: () => null })) vi.mock('@/components/notifications/PendingActionsGroup', () => ({ PendingActionsGroup: () => null })) diff --git a/frontend/src/pages/__tests__/Schedules.test.tsx b/frontend/src/pages/__tests__/Schedules.test.tsx index 59478a1f..630dc0fb 100644 --- a/frontend/src/pages/__tests__/Schedules.test.tsx +++ b/frontend/src/pages/__tests__/Schedules.test.tsx @@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({ useCancelRepoScheduleRun: vi.fn(), useClearRepoScheduleRuns: vi.fn(), useDeleteRepoScheduleRun: vi.fn(), + useScheduleWorktrees: vi.fn(), useRepoActivity: vi.fn(), useScheduleUrlState: vi.fn(), })) @@ -41,6 +42,7 @@ vi.mock('@/hooks/useSchedules', () => ({ useCancelRepoScheduleRun: mocks.useCancelRepoScheduleRun, useClearRepoScheduleRuns: mocks.useClearRepoScheduleRuns, useDeleteRepoScheduleRun: mocks.useDeleteRepoScheduleRun, + useScheduleWorktrees: mocks.useScheduleWorktrees, })) vi.mock('@/hooks/useRepoActivity', () => ({ @@ -73,6 +75,7 @@ vi.mock('@/components/schedules', () => ({ )), RunHistoryTab: vi.fn(() =>
RunHistoryTab
), + ScheduleRunRemovalDialog: () => null, ScheduleTabMenu: vi.fn(() =>
ScheduleTabMenu
), })) @@ -135,6 +138,7 @@ describe('Schedules', () => { mocks.useCancelRepoScheduleRun.mockReturnValue({ mutate: vi.fn(), isPending: false }) mocks.useClearRepoScheduleRuns.mockReturnValue({ mutate: vi.fn(), isPending: false }) mocks.useDeleteRepoScheduleRun.mockReturnValue({ mutate: vi.fn(), isPending: false }) + mocks.useScheduleWorktrees.mockReturnValue({ data: [], isLoading: false }) }) describe('assistant schedule target (repoId=0)', () => { diff --git a/shared/src/schemas/schedule.ts b/shared/src/schemas/schedule.ts index d2a0878a..e9bb5d3e 100644 --- a/shared/src/schemas/schedule.ts +++ b/shared/src/schemas/schedule.ts @@ -11,13 +11,20 @@ export type ScheduleMode = z.infer /** * 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. + * removed when the run ends, `kept-worktree` keeps each run's worktree afterwards, and + * `shared-worktree` reuses one worktree and branch for every run of the schedule. */ -export const ScheduleWorkspaceModeSchema = z.enum(['worktree', 'kept-worktree', 'shared-worktree', 'repo']) +export const ScheduleWorkspaceModeSchema = z.enum(['worktree', 'kept-worktree', 'shared-worktree']) export type ScheduleWorkspaceMode = z.infer +/** + * What clearing run history does with the run worktrees that still exist on disk. + * `commit` commits their pending changes to their branches and keeps those branches; + * `discard` force-removes the worktrees and deletes their branches. + */ +export const ScheduleRunWorktreesModeSchema = z.enum(['commit', 'discard']).default('commit') +export type ScheduleRunWorktreesMode = z.infer + /** * 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. diff --git a/shared/src/types/index.ts b/shared/src/types/index.ts index 5375c0df..6a02e843 100644 --- a/shared/src/types/index.ts +++ b/shared/src/types/index.ts @@ -155,6 +155,7 @@ export type { export type { ScheduleMode, ScheduleWorkspaceMode, + ScheduleRunWorktreesMode, ScheduleWorktree, RemoveScheduleWorktreesRequest, SchedulePermissionConfig, diff --git a/shared/src/utils/repo.ts b/shared/src/utils/repo.ts index 662ed20b..a12efff0 100644 --- a/shared/src/utils/repo.ts +++ b/shared/src/utils/repo.ts @@ -1,3 +1,5 @@ +import type { Repo } from '../types' + export const ASSISTANT_REPO_ID = 0 export const ASSISTANT_REPO_NAME = 'Assistant' export const ASSISTANT_REPO_PATH = 'assistant' @@ -94,13 +96,24 @@ 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. + * `inUse` is true while a running run works in it, and `name` is the schedule's display name. */ export interface RepoWorktreeSchedule { repoId: number jobId: number runId: number | null inUse: boolean + name: string +} + +/** + * A repository visible from another repository in the same project: the repo itself, a plain + * git or OpenCode worktree, or a schedule worktree. + */ +export type RepoSibling = Repo & { + currentBranch?: string + worktreeSource?: RepoWorktreeSource + schedule?: RepoWorktreeSchedule } export function isWorktreeSibling(sibling: { worktreeSource?: RepoWorktreeSource }): boolean {