mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Merge branch 'main' into feat/docker-self-upgrade
Resolve conflicts against the restart-coordinator rewrite and renumber the manager-upgrade-jobs migration from 16 to 19 to avoid colliding with main's 016-018 migrations. Includes review fixes: background the docker pull, add a staleness guard for stuck recreating jobs, move manager-upgrade types to @opencode-manager/shared, wire the active-session pre-check dialog into the Upgrade Manager button, and surface upgrade errors via FetchError-aware messaging.
This commit is contained in:
commit
9effe53bdc
125 files changed
+3899
-975
No files matched your search
@@ -28,7 +28,6 @@ function createRunner(): { runner: DockerRunner; calls: { inspectSelf: SelfConta
|
||||
const runner: DockerRunner = {
|
||||
inspectSelf: vi.fn().mockImplementation(async () => {
|
||||
const info: SelfContainerInfo = {
|
||||
containerId: 'abc123',
|
||||
project: 'opencode',
|
||||
service: 'manager',
|
||||
workingDir: '/app',
|
||||
@@ -164,12 +163,16 @@ describe('ManagerUpgradeService', () => {
|
||||
|
||||
const job = await service.startUpgrade('0.15.0')
|
||||
|
||||
expect(job.status).toBe('recreating')
|
||||
// startUpgrade returns as soon as the job is created; the pull and
|
||||
// recreate continue in the background and are reflected via job status.
|
||||
expect(job.status).toBe('pulling')
|
||||
expect(job.toVersion).toBe('0.15.0')
|
||||
expect(job.targetImage).toBe('opencode-manager:0.15.0')
|
||||
expect(job.fromVersion).toBe('0.14.0')
|
||||
expect(job.error).toBeNull()
|
||||
|
||||
await tick()
|
||||
|
||||
// Pull was called with the resolved target image
|
||||
expect(calls.pulled).toEqual(['opencode-manager:0.15.0'])
|
||||
expect(calls.inspectSelf).toHaveLength(1)
|
||||
@@ -198,6 +201,7 @@ describe('ManagerUpgradeService', () => {
|
||||
})
|
||||
|
||||
await service.startUpgrade('0.15.0')
|
||||
await tick()
|
||||
expect(calls.pulled).toEqual(['my-registry/opencode-manager:0.15.0'])
|
||||
})
|
||||
|
||||
@@ -210,6 +214,7 @@ describe('ManagerUpgradeService', () => {
|
||||
})
|
||||
|
||||
await service.startUpgrade()
|
||||
await tick()
|
||||
expect(calls.pulled).toEqual(['opencode-manager:latest'])
|
||||
})
|
||||
})
|
||||
@@ -279,6 +284,8 @@ describe('ManagerUpgradeService', () => {
|
||||
message: 'An upgrade is already in progress',
|
||||
})
|
||||
|
||||
await tick()
|
||||
|
||||
// Only one pull and one spawn should have occurred
|
||||
expect(calls.pulled).toHaveLength(1)
|
||||
expect(calls.spawned).toHaveLength(1)
|
||||
@@ -286,8 +293,8 @@ describe('ManagerUpgradeService', () => {
|
||||
})
|
||||
|
||||
describe('startUpgrade - pull failure', () => {
|
||||
// Cycle 4: pull fails → job marked failed, 500 thrown
|
||||
it('marks job as failed and throws 500 when pull rejects', async () => {
|
||||
// Cycle 4: pull fails in the background → job marked failed with the error
|
||||
it('marks job as failed when the background pull rejects', async () => {
|
||||
const { runner, calls } = createRunner()
|
||||
runner.pull = vi.fn().mockRejectedValue(new Error('Network error'))
|
||||
|
||||
@@ -297,10 +304,10 @@ describe('ManagerUpgradeService', () => {
|
||||
capability: () => ({ inDocker: true, socket: true, enabled: true }),
|
||||
})
|
||||
|
||||
await expect(service.startUpgrade('0.15.0')).rejects.toMatchObject({
|
||||
status: 500,
|
||||
message: 'Network error',
|
||||
})
|
||||
const job = await service.startUpgrade('0.15.0')
|
||||
expect(job.status).toBe('pulling')
|
||||
|
||||
await tick()
|
||||
|
||||
// spawnRecreate should NOT have been called
|
||||
expect(calls.spawned).toHaveLength(0)
|
||||
@@ -314,6 +321,70 @@ describe('ManagerUpgradeService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('stale recreating jobs', () => {
|
||||
it('getStatus fails a recreating job older than the staleness bound', async () => {
|
||||
const { runner } = createRunner()
|
||||
insertUpgradeJob(db, {
|
||||
status: 'recreating',
|
||||
fromVersion: '0.14.0',
|
||||
toVersion: '0.15.0',
|
||||
startedAt: Date.now() - 11 * 60 * 1000,
|
||||
})
|
||||
|
||||
const service = new ManagerUpgradeService(db, {
|
||||
runner,
|
||||
// Same as fromVersion — the recreate helper never completed
|
||||
getCurrentVersion: vi.fn().mockResolvedValue('0.14.0'),
|
||||
capability: () => ({ inDocker: true, socket: true, enabled: true }),
|
||||
})
|
||||
|
||||
const status = await service.getStatus()
|
||||
expect(status.job).not.toBeNull()
|
||||
expect(status.job!.status).toBe('failed')
|
||||
expect(status.job!.error).toMatch(/did not complete/i)
|
||||
})
|
||||
|
||||
it('startUpgrade proceeds after expiring a stale recreating job', async () => {
|
||||
const { runner, calls } = createRunner()
|
||||
insertUpgradeJob(db, {
|
||||
status: 'recreating',
|
||||
fromVersion: '0.14.0',
|
||||
toVersion: '0.15.0',
|
||||
startedAt: Date.now() - 11 * 60 * 1000,
|
||||
})
|
||||
|
||||
const service = new ManagerUpgradeService(db, {
|
||||
runner,
|
||||
getCurrentVersion: vi.fn().mockResolvedValue('0.14.0'),
|
||||
capability: () => ({ inDocker: true, socket: true, enabled: true }),
|
||||
})
|
||||
|
||||
const job = await service.startUpgrade('0.16.0')
|
||||
expect(job.status).toBe('pulling')
|
||||
await tick()
|
||||
expect(calls.pulled).toEqual(['opencode-manager:0.16.0'])
|
||||
})
|
||||
|
||||
it('getStatus leaves a fresh recreating job untouched', async () => {
|
||||
const { runner } = createRunner()
|
||||
insertUpgradeJob(db, {
|
||||
status: 'recreating',
|
||||
fromVersion: '0.14.0',
|
||||
toVersion: '0.15.0',
|
||||
startedAt: Date.now(),
|
||||
})
|
||||
|
||||
const service = new ManagerUpgradeService(db, {
|
||||
runner,
|
||||
getCurrentVersion: vi.fn().mockResolvedValue('0.14.0'),
|
||||
capability: () => ({ inDocker: true, socket: true, enabled: true }),
|
||||
})
|
||||
|
||||
const status = await service.getStatus()
|
||||
expect(status.job!.status).toBe('recreating')
|
||||
})
|
||||
})
|
||||
|
||||
describe('reconcile', () => {
|
||||
// Cycle 5: recreating job + version matches toVersion → completed
|
||||
it('marks recreating job as completed when current version matches toVersion', async () => {
|
||||
@@ -492,6 +563,7 @@ describe('ManagerUpgradeService', () => {
|
||||
})
|
||||
|
||||
await service.startUpgrade('0.15.0')
|
||||
await tick()
|
||||
// Should NOT produce 'localhost:0.15.0'
|
||||
expect(calls.pulled).toEqual(['localhost:5000/opencode-manager:0.15.0'])
|
||||
expect(calls.spawned[0]!.targetImage).toBe('localhost:5000/opencode-manager:0.15.0')
|
||||
|
||||
@@ -33,6 +33,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Review the repository and summarize risks.',
|
||||
model: 'openai/gpt-5',
|
||||
skillMetadata: undefined,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: currentDate + 60 * 60_000,
|
||||
})
|
||||
@@ -71,6 +72,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Old prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
@@ -101,6 +103,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Old prompt',
|
||||
model: 'openai/gpt-5-mini',
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
@@ -134,6 +137,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: 'feature/foo',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
@@ -163,6 +167,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
@@ -192,6 +197,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: 'feature/foo',
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: null,
|
||||
@@ -221,6 +227,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Run a report',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
@@ -263,6 +270,7 @@ describe('schedule-config', () => {
|
||||
prompt: 'Prompt',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: null,
|
||||
lastRunAt: null,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { DEFAULT_DESTRUCTIVE_BASH_PATTERNS, buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
|
||||
|
||||
describe('buildSchedulePermissionRuleset', () => {
|
||||
it('returns the allow-all baseline with default deny rules when given null', () => {
|
||||
const result = buildSchedulePermissionRuleset(null)
|
||||
|
||||
expect(result['*']).toBe('allow')
|
||||
expect(result.external_directory).toBe('deny')
|
||||
for (const pattern of DEFAULT_DESTRUCTIVE_BASH_PATTERNS) {
|
||||
expect(result.bash?.[pattern]).toBe('deny')
|
||||
}
|
||||
})
|
||||
|
||||
it('returns only the allow-all baseline when all permissions are granted', () => {
|
||||
const result = buildSchedulePermissionRuleset({ allowExternalDirectory: true, bashDenyPatterns: [] })
|
||||
|
||||
expect(result).toEqual({ '*': 'allow' })
|
||||
})
|
||||
|
||||
it('includes a single custom bash deny pattern alongside external_directory deny', () => {
|
||||
const result = buildSchedulePermissionRuleset({ allowExternalDirectory: false, bashDenyPatterns: ['rm -rf *'] })
|
||||
|
||||
expect(result).toEqual({
|
||||
'*': 'allow',
|
||||
external_directory: 'deny',
|
||||
bash: { 'rm -rf *': 'deny' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -72,6 +72,19 @@ describe('ScheduleWorktreeManager', () => {
|
||||
}
|
||||
const mockDb = {} as any
|
||||
|
||||
// Default mock OpenCodeClient: postJson rejects (triggers fallback), forward
|
||||
// returns an ok response for teardown safety.
|
||||
const mockOpenCodeClient = {
|
||||
postJson: vi.fn().mockRejectedValue(new Error('API unavailable')),
|
||||
forward: vi.fn().mockResolvedValue(new Response(null, { status: 200 })),
|
||||
getJson: vi.fn(),
|
||||
forwardRaw: vi.fn(),
|
||||
setProviderAuth: vi.fn(),
|
||||
deleteProviderAuth: vi.fn(),
|
||||
startMcpAuth: vi.fn(),
|
||||
authenticateMcp: vi.fn(),
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
tmpDir = mkdtempSync(path.join(tmpdir(), 'schedule-worktree-test-'))
|
||||
tmpRoot = tmpDir
|
||||
@@ -113,6 +126,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
mockSettingsService as any,
|
||||
mockCredentialProvider as any,
|
||||
mockDb,
|
||||
mockOpenCodeClient as any,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -126,9 +140,9 @@ describe('ScheduleWorktreeManager', () => {
|
||||
} as any
|
||||
}
|
||||
|
||||
// ---- Tests ----
|
||||
// ---- Fallback (raw git) tests ----
|
||||
|
||||
it('prepare creates a worktree with the correct branch name and returns context', async () => {
|
||||
it('prepare creates a worktree with the correct branch name and returns context (raw git fallback)', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 10, branch: null }
|
||||
@@ -140,6 +154,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
expect(ctx!.directory).toBeDefined()
|
||||
expect(ctx!.worktreePath).toBe(ctx!.directory)
|
||||
expect(ctx!.runBranch).toBe(`schedule/10/run-1`)
|
||||
expect(ctx!.workspaceId).toBeNull()
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
|
||||
// The checked-out branch in the worktree must match the run branch
|
||||
@@ -260,7 +275,7 @@ describe('ScheduleWorktreeManager', () => {
|
||||
expect(existsSync(path.join(scheduleWorktreesRoot, 'job-21-run-1'))).toBe(false)
|
||||
})
|
||||
|
||||
it('prepare respects the branch override', async () => {
|
||||
it('prepare respects the branch override (raw git fallback)', async () => {
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 20, branch: 'dev' }
|
||||
@@ -285,4 +300,252 @@ describe('ScheduleWorktreeManager', () => {
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, ctx!.worktreePath)
|
||||
})
|
||||
|
||||
// ---- OpenCode API path tests ----
|
||||
|
||||
/**
|
||||
* Helper: creates a linked git worktree directory (rather than a clone) so
|
||||
* that refs and objects are shared with the base repo. The worktree is
|
||||
* created with a temp branch that prepare() will later overwrite via
|
||||
* `checkout -B`.
|
||||
*/
|
||||
async function createWorktreeWorkspace(dirName: string): Promise<{ directory: string; cleanup: () => Promise<void> }> {
|
||||
const directory = path.join(tmpDir, dirName)
|
||||
const tempBranch = `_temp_${dirName}`
|
||||
// Create a detached worktree on the current HEAD without creating a branch
|
||||
execSync(`git -C "${baseRepoPath}" worktree add --detach "${directory}" origin/main`, { env })
|
||||
execSync(`git -C "${directory}" config user.email test@test.com`, { env })
|
||||
execSync(`git -C "${directory}" config user.name Test`, { env })
|
||||
const cleanup = async () => {
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, directory)
|
||||
// Also remove any leftover branch the test might have created
|
||||
execSync(`git -C "${baseRepoPath}" branch -D "${tempBranch}" 2>/dev/null || true`, { env })
|
||||
}
|
||||
return { directory, cleanup }
|
||||
}
|
||||
|
||||
it('prepare calls POST /experimental/workspace and returns workspaceId on success', async () => {
|
||||
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-workspace')
|
||||
|
||||
const workspaceId = 'ws-test-123'
|
||||
const mockPost = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: workspaceDirectory,
|
||||
branch: null,
|
||||
})
|
||||
mockOpenCodeClient.postJson = mockPost
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 30, branch: null }
|
||||
const runId = 5
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBe(workspaceId)
|
||||
expect(ctx!.runBranch).toBe('schedule/30/run-5')
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
expect(ctx!.worktreePath).toBe(workspaceDirectory)
|
||||
|
||||
// Verify the API was called correctly
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
'/experimental/workspace',
|
||||
{ type: 'worktree', branch: null },
|
||||
{ directory: repo.fullPath },
|
||||
)
|
||||
|
||||
// Verify the branch was re-pointed
|
||||
const branch = execSync(`git -C "${workspaceDirectory}" rev-parse --abbrev-ref HEAD`, {
|
||||
encoding: 'utf-8',
|
||||
}).trim()
|
||||
expect(branch).toBe('schedule/30/run-5')
|
||||
|
||||
// Cleanup
|
||||
await cleanup()
|
||||
})
|
||||
|
||||
it('prepare falls back to raw git when postJson rejects', async () => {
|
||||
mockOpenCodeClient.postJson = vi.fn().mockRejectedValue(new Error('API unavailable'))
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 40, branch: null }
|
||||
const runId = 10
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBeNull()
|
||||
expect(ctx!.runBranch).toBe('schedule/40/run-10')
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
|
||||
// The worktree path should be under scheduleWorktreesRoot (raw git path)
|
||||
expect(ctx!.worktreePath).toContain(scheduleWorktreesRoot)
|
||||
|
||||
// Cleanup
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, ctx!.worktreePath)
|
||||
})
|
||||
|
||||
it('finalize deletes workspace via API when workspaceId is set', async () => {
|
||||
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-finalize-test')
|
||||
|
||||
const workspaceId = 'ws-finalize-456'
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: workspaceDirectory,
|
||||
branch: null,
|
||||
})
|
||||
|
||||
const deleteMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
|
||||
mockOpenCodeClient.forward = deleteMock
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 50, branch: null, name: 'Finalize API' }
|
||||
const runId = 300
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBe(workspaceId)
|
||||
|
||||
// Write a file so there are changes to commit
|
||||
writeFileSync(path.join(workspaceDirectory, 'output.md'), '# API Finalize Test')
|
||||
|
||||
const result = await manager.finalize(
|
||||
repo,
|
||||
{ id: 50, name: 'Finalize API', prompt: 'test' },
|
||||
{ id: runId, worktreePath: workspaceDirectory, runBranch: ctx!.runBranch, triggerSource: 'manual', workspaceId: ctx!.workspaceId },
|
||||
)
|
||||
|
||||
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
|
||||
|
||||
// Verify DELETE was called with the correct workspaceId
|
||||
expect(deleteMock).toHaveBeenCalledWith({
|
||||
method: 'DELETE',
|
||||
path: `/experimental/workspace/${encodeURIComponent(workspaceId)}`,
|
||||
directory: repo.fullPath,
|
||||
})
|
||||
|
||||
// The commit must still be reachable on the runBranch in the base repo
|
||||
const log = execSync(`git -C "${baseRepoPath}" log "${ctx!.runBranch}" --oneline`, {
|
||||
encoding: 'utf-8',
|
||||
}).trim()
|
||||
expect(log).toBeTruthy()
|
||||
|
||||
// Clean up in case the API mock didn't actually remove the worktree
|
||||
await cleanup()
|
||||
})
|
||||
|
||||
it('finalize falls back to raw removeWorktree when workspace DELETE fails', async () => {
|
||||
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-delete-fail')
|
||||
|
||||
const workspaceId = 'ws-delete-fail-789'
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: workspaceDirectory,
|
||||
branch: null,
|
||||
})
|
||||
// DELETE returns non-ok response → triggers fallback removeWorktree
|
||||
mockOpenCodeClient.forward = vi.fn().mockResolvedValue(new Response('Not Found', { status: 404 }))
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 60, branch: null, name: 'Delete Fail' }
|
||||
const runId = 400
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBe(workspaceId)
|
||||
|
||||
writeFileSync(path.join(workspaceDirectory, 'data.txt'), 'test data')
|
||||
|
||||
const result = await manager.finalize(
|
||||
repo,
|
||||
{ id: 60, name: 'Delete Fail', prompt: 'test' },
|
||||
{ id: runId, worktreePath: workspaceDirectory, runBranch: ctx!.runBranch, triggerSource: 'manual', workspaceId: ctx!.workspaceId },
|
||||
)
|
||||
|
||||
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
|
||||
// Directory should be cleaned up (via fallback removeWorktree)
|
||||
expect(existsSync(workspaceDirectory)).toBe(false)
|
||||
|
||||
// Clean up in case the directory somehow still exists
|
||||
await cleanup()
|
||||
})
|
||||
|
||||
it('finalize restores run branch if OpenCode delete removed it', async () => {
|
||||
const { directory: workspaceDirectory, cleanup } = await createWorktreeWorkspace('oc-branch-restore')
|
||||
|
||||
const workspaceId = 'ws-branch-restore-101'
|
||||
mockOpenCodeClient.postJson = vi.fn().mockResolvedValue({
|
||||
id: workspaceId,
|
||||
directory: workspaceDirectory,
|
||||
branch: null,
|
||||
})
|
||||
mockOpenCodeClient.forward = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 70, branch: null, name: 'Branch Restore' }
|
||||
const runId = 500
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBe(workspaceId)
|
||||
|
||||
writeFileSync(path.join(workspaceDirectory, 'important.md'), '# Branch Restore Test')
|
||||
|
||||
// Simulate: API delete removes the branch. First detach the worktree
|
||||
// HEAD so git allows the deletion (OpenCode's workspace DELETE handles
|
||||
// the worktree-level cleanup first, then the branch goes away).
|
||||
const runBranch = ctx!.runBranch!
|
||||
execSync(`git -C "${workspaceDirectory}" checkout --detach`, { env })
|
||||
execSync(`git -C "${baseRepoPath}" branch -D "${runBranch}"`, { env })
|
||||
|
||||
const result = await manager.finalize(
|
||||
repo,
|
||||
{ id: 70, name: 'Branch Restore', prompt: 'test' },
|
||||
{ id: runId, worktreePath: workspaceDirectory, runBranch, triggerSource: 'manual', workspaceId: ctx!.workspaceId },
|
||||
)
|
||||
|
||||
expect(result.commitHash).toMatch(/^[0-9a-f]{40}$/)
|
||||
|
||||
// Branch should have been restored by finalize
|
||||
const branchExists = execSync(`git -C "${baseRepoPath}" rev-parse --verify "refs/heads/${runBranch}"`, {
|
||||
encoding: 'utf-8',
|
||||
}).trim()
|
||||
expect(branchExists).toBeTruthy()
|
||||
|
||||
// And the commit hash should match
|
||||
const branchCommit = execSync(`git -C "${baseRepoPath}" rev-parse "${runBranch}"`, {
|
||||
encoding: 'utf-8',
|
||||
}).trim()
|
||||
expect(branchCommit).toBe(result.commitHash)
|
||||
|
||||
await cleanup()
|
||||
})
|
||||
|
||||
it('prepare returns workspaceId null on postJson failure (fallback path)', async () => {
|
||||
mockOpenCodeClient.postJson = vi.fn().mockRejectedValue(new Error('Network error'))
|
||||
|
||||
const manager = await createManager()
|
||||
const repo = testRepo()
|
||||
const job = { id: 80, branch: 'main' }
|
||||
const runId = 15
|
||||
|
||||
const ctx = await manager.prepare(repo, job, runId)
|
||||
|
||||
expect(ctx).not.toBeNull()
|
||||
expect(ctx!.workspaceId).toBeNull()
|
||||
expect(ctx!.runBranch).toBe('schedule/80/run-15')
|
||||
expect(existsSync(ctx!.worktreePath)).toBe(true)
|
||||
expect(ctx!.worktreePath).toContain(scheduleWorktreesRoot)
|
||||
|
||||
// Cleanup
|
||||
const { removeWorktree } = await import('../../src/services/repo')
|
||||
await removeWorktree(baseRepoPath, ctx!.worktreePath)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,314 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ScheduleJob, ScheduleRun } from '@opencode-manager/shared/types'
|
||||
import { buildSchedulePermissionRuleset } from '@opencode-manager/shared/schemas'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getRepoById: vi.fn(),
|
||||
createScheduleJob: vi.fn(),
|
||||
createScheduleRun: vi.fn(),
|
||||
deleteScheduleJob: vi.fn(),
|
||||
deleteScheduleRunById: vi.fn(),
|
||||
deleteScheduleRunsByIds: vi.fn(),
|
||||
listScheduleRunArtifactsByJob: vi.fn(),
|
||||
cleanupOrphanedSchedules: vi.fn(),
|
||||
getScheduleJobById: vi.fn(),
|
||||
getRunningScheduleRunByJob: vi.fn(),
|
||||
getScheduleRunById: vi.fn(),
|
||||
listEnabledScheduleJobs: vi.fn(),
|
||||
listRunningScheduleRuns: vi.fn(),
|
||||
listScheduleJobIdsByRepo: vi.fn(),
|
||||
listScheduleJobsByRepo: vi.fn(),
|
||||
listScheduleRunsByJob: vi.fn(),
|
||||
updateScheduleJob: vi.fn(),
|
||||
updateScheduleJobRunState: vi.fn(),
|
||||
updateScheduleRun: vi.fn(),
|
||||
updateScheduleRunMetadata: vi.fn(),
|
||||
buildCreateSchedulePersistenceInput: vi.fn(),
|
||||
buildUpdatedSchedulePersistenceInput: vi.fn(),
|
||||
computeNextRunAtForJob: vi.fn(),
|
||||
|
||||
resolveOpenCodeModel: vi.fn(),
|
||||
forward: vi.fn(),
|
||||
onEvent: vi.fn(),
|
||||
loggerError: vi.fn(),
|
||||
updateScheduleRunWorktree: vi.fn(),
|
||||
stubWorktreeManager: {
|
||||
prepare: vi.fn().mockResolvedValue(null),
|
||||
finalize: vi.fn().mockResolvedValue({ commitHash: null }),
|
||||
pruneRunArtifacts: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/queries', () => ({
|
||||
getRepoById: mocks.getRepoById,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/db/schedules', () => ({
|
||||
createScheduleJob: mocks.createScheduleJob,
|
||||
createScheduleRun: mocks.createScheduleRun,
|
||||
deleteScheduleJob: mocks.deleteScheduleJob,
|
||||
deleteScheduleRunById: mocks.deleteScheduleRunById,
|
||||
deleteScheduleRunsByIds: mocks.deleteScheduleRunsByIds,
|
||||
listScheduleRunArtifactsByJob: mocks.listScheduleRunArtifactsByJob,
|
||||
cleanupOrphanedSchedules: mocks.cleanupOrphanedSchedules,
|
||||
getScheduleJobById: mocks.getScheduleJobById,
|
||||
getRunningScheduleRunByJob: mocks.getRunningScheduleRunByJob,
|
||||
getScheduleRunById: mocks.getScheduleRunById,
|
||||
listEnabledScheduleJobs: mocks.listEnabledScheduleJobs,
|
||||
listRunningScheduleRuns: mocks.listRunningScheduleRuns,
|
||||
listScheduleJobIdsByRepo: mocks.listScheduleJobIdsByRepo,
|
||||
listScheduleJobsByRepo: mocks.listScheduleJobsByRepo,
|
||||
listScheduleRunsByJob: mocks.listScheduleRunsByJob,
|
||||
updateScheduleJob: mocks.updateScheduleJob,
|
||||
updateScheduleJobRunState: mocks.updateScheduleJobRunState,
|
||||
updateScheduleRun: mocks.updateScheduleRun,
|
||||
updateScheduleRunMetadata: mocks.updateScheduleRunMetadata,
|
||||
updateScheduleRunWorktree: mocks.updateScheduleRunWorktree,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/schedule-config', () => ({
|
||||
buildCreateSchedulePersistenceInput: mocks.buildCreateSchedulePersistenceInput,
|
||||
buildUpdatedSchedulePersistenceInput: mocks.buildUpdatedSchedulePersistenceInput,
|
||||
computeNextRunAtForJob: mocks.computeNextRunAtForJob,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-models', () => ({
|
||||
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/sse-aggregator', () => ({
|
||||
sseAggregator: {
|
||||
onEvent: mocks.onEvent,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
error: mocks.loggerError,
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockCronStop = vi.fn()
|
||||
|
||||
vi.mock('croner', () => ({
|
||||
Cron: vi.fn().mockImplementation(() => ({ stop: mockCronStop })),
|
||||
}))
|
||||
|
||||
import { ScheduleService } from '../../src/services/schedules'
|
||||
import type { ForwardRequest, OpenCodeClient } from '../../src/services/opencode/client'
|
||||
|
||||
function jsonResponse(body: unknown, status: number = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
function textResponse(body: string, status: number = 200): Response {
|
||||
return new Response(body, { status })
|
||||
}
|
||||
|
||||
function createOpenCodeClientStub(): OpenCodeClient {
|
||||
return {
|
||||
forward: mocks.forward,
|
||||
forwardRaw: vi.fn(async () => new Response('', { status: 200 })),
|
||||
getJson: vi.fn(async () => ({}) as unknown),
|
||||
postJson: vi.fn(async () => ({}) as unknown),
|
||||
setProviderAuth: vi.fn(async () => true),
|
||||
deleteProviderAuth: vi.fn(async () => true),
|
||||
startMcpAuth: vi.fn(async () => new Response('', { status: 200 })),
|
||||
authenticateMcp: vi.fn(async () => new Response('', { status: 200 })),
|
||||
} as OpenCodeClient
|
||||
}
|
||||
|
||||
function routeForward(handler: (req: ForwardRequest) => Promise<Response> | Response) {
|
||||
mocks.forward.mockImplementation((req: ForwardRequest) => Promise.resolve(handler(req)))
|
||||
}
|
||||
|
||||
const repo = {
|
||||
id: 42,
|
||||
fullPath: '/workspace/repos/sample-project',
|
||||
localPath: 'sample-project',
|
||||
repoUrl: 'https://github.com/example/sample-project',
|
||||
}
|
||||
|
||||
const baseJob: ScheduleJob = {
|
||||
id: 7,
|
||||
repoId: 42,
|
||||
name: 'Weekly engineering summary',
|
||||
description: 'Summarize repo health and recent changes.',
|
||||
enabled: true,
|
||||
scheduleMode: 'interval',
|
||||
intervalMinutes: 60,
|
||||
cronExpression: null,
|
||||
timezone: null,
|
||||
agentSlug: null,
|
||||
prompt: 'Review the repository and summarize the current state.',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
createdAt: Date.UTC(2026, 2, 8, 12, 0, 0),
|
||||
updatedAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
}
|
||||
|
||||
const baseRun: ScheduleRun = {
|
||||
id: 5,
|
||||
jobId: 7,
|
||||
repoId: 42,
|
||||
triggerSource: 'manual',
|
||||
status: 'running',
|
||||
startedAt: Date.UTC(2026, 2, 9, 12, 5, 0),
|
||||
finishedAt: null,
|
||||
createdAt: Date.UTC(2026, 2, 9, 12, 5, 0),
|
||||
sessionId: null,
|
||||
sessionTitle: null,
|
||||
logText: null,
|
||||
responseText: null,
|
||||
errorText: null,
|
||||
runBranch: null,
|
||||
commitHash: null,
|
||||
worktreePath: null,
|
||||
workspaceId: null,
|
||||
}
|
||||
|
||||
describe('ScheduleService permission ruleset in session creation', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
Reflect.get(ScheduleService, 'activeRuns').clear()
|
||||
Reflect.get(ScheduleService, 'activeTeardowns')?.clear()
|
||||
|
||||
mocks.getRepoById.mockReturnValue(repo)
|
||||
mocks.getRunningScheduleRunByJob.mockReturnValue(null)
|
||||
mocks.createScheduleRun.mockReturnValue(baseRun)
|
||||
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', modelID: 'gpt-5-mini' })
|
||||
mocks.onEvent.mockReturnValue(vi.fn())
|
||||
mocks.getScheduleRunById.mockReturnValue({
|
||||
...baseRun,
|
||||
sessionId: 'ses-perm-test',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started.',
|
||||
})
|
||||
})
|
||||
|
||||
it('sends default permission ruleset when job.permissionConfig is null', async () => {
|
||||
mocks.getScheduleJobById.mockReturnValue(baseJob)
|
||||
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-perm-1',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started.',
|
||||
}
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return jsonResponse({ id: 'ses-perm-1' })
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'POST') {
|
||||
return textResponse('')
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'GET') {
|
||||
return jsonResponse([{ info: { role: 'assistant', time: { completed: Date.now() } }, parts: [] }])
|
||||
}
|
||||
throw new Error(`Unexpected forward request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub(), mocks.stubWorktreeManager as never)
|
||||
await service.runJob(42, 7, 'manual')
|
||||
|
||||
const sessionCall = mocks.forward.mock.calls.find(
|
||||
([req]) => (req as ForwardRequest).path === '/session' && (req as ForwardRequest).method === 'POST',
|
||||
)
|
||||
expect(sessionCall).toBeDefined()
|
||||
const body = JSON.parse((sessionCall![0] as ForwardRequest).body!)
|
||||
expect(body.title).toBe('Scheduled: Weekly engineering summary')
|
||||
expect(body.agent).toBeUndefined()
|
||||
|
||||
const expectedRules = buildSchedulePermissionRuleset(null)
|
||||
expect(body.permission).toEqual(expectedRules)
|
||||
})
|
||||
|
||||
it('sends custom permission ruleset when job has custom permissionConfig', async () => {
|
||||
const customConfig = { allowExternalDirectory: true, bashDenyPatterns: [] }
|
||||
mocks.getScheduleJobById.mockReturnValue({ ...baseJob, permissionConfig: customConfig })
|
||||
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-perm-2',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started.',
|
||||
}
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return jsonResponse({ id: 'ses-perm-2' })
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'POST') {
|
||||
return textResponse('')
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'GET') {
|
||||
return jsonResponse([{ info: { role: 'assistant', time: { completed: Date.now() } }, parts: [] }])
|
||||
}
|
||||
throw new Error(`Unexpected forward request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub(), mocks.stubWorktreeManager as never)
|
||||
await service.runJob(42, 7, 'manual')
|
||||
|
||||
const sessionCall = mocks.forward.mock.calls.find(
|
||||
([req]) => (req as ForwardRequest).path === '/session' && (req as ForwardRequest).method === 'POST',
|
||||
)
|
||||
expect(sessionCall).toBeDefined()
|
||||
const body = JSON.parse((sessionCall![0] as ForwardRequest).body!)
|
||||
expect(body.title).toBe('Scheduled: Weekly engineering summary')
|
||||
expect(body.agent).toBeUndefined()
|
||||
|
||||
const expectedRules = buildSchedulePermissionRuleset(customConfig)
|
||||
expect(body.permission).toEqual(expectedRules)
|
||||
})
|
||||
|
||||
it('preserves existing fields (title, agent) when permission is added', async () => {
|
||||
mocks.getScheduleJobById.mockReturnValue({ ...baseJob, agentSlug: 'my-agent' })
|
||||
|
||||
const runWithSession: ScheduleRun = {
|
||||
...baseRun,
|
||||
sessionId: 'ses-perm-3',
|
||||
sessionTitle: 'Scheduled: Weekly engineering summary',
|
||||
logText: 'Run started.',
|
||||
}
|
||||
mocks.updateScheduleRunMetadata.mockReturnValue(runWithSession)
|
||||
|
||||
routeForward(({ path, method }) => {
|
||||
if (path === '/session' && method === 'POST') {
|
||||
return jsonResponse({ id: 'ses-perm-3' })
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'POST') {
|
||||
return textResponse('')
|
||||
}
|
||||
if (path.match(/^\/session\/[\w-]+\/message$/) && method === 'GET') {
|
||||
return jsonResponse([{ info: { role: 'assistant', time: { completed: Date.now() } }, parts: [] }])
|
||||
}
|
||||
throw new Error(`Unexpected forward request: ${method} ${path}`)
|
||||
})
|
||||
|
||||
const service = new ScheduleService({} as never, createOpenCodeClientStub(), mocks.stubWorktreeManager as never)
|
||||
await service.runJob(42, 7, 'manual')
|
||||
|
||||
const sessionCall = mocks.forward.mock.calls.find(
|
||||
([req]) => (req as ForwardRequest).path === '/session' && (req as ForwardRequest).method === 'POST',
|
||||
)
|
||||
expect(sessionCall).toBeDefined()
|
||||
const body = JSON.parse((sessionCall![0] as ForwardRequest).body!)
|
||||
expect(body.title).toBe('Scheduled: Weekly engineering summary')
|
||||
expect(body.agent).toBe('my-agent')
|
||||
expect(body.permission).toBeDefined()
|
||||
expect(body.permission['*']).toBe('allow')
|
||||
})
|
||||
})
|
||||
@@ -154,6 +154,7 @@ const job: ScheduleJob = {
|
||||
prompt: 'Review the repository and summarize the current state.',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.UTC(2026, 2, 9, 13, 0, 0),
|
||||
lastRunAt: Date.UTC(2026, 2, 9, 12, 0, 0),
|
||||
@@ -178,6 +179,7 @@ const baseRun: ScheduleRun = {
|
||||
runBranch: null,
|
||||
commitHash: null,
|
||||
worktreePath: null,
|
||||
workspaceId: null,
|
||||
}
|
||||
|
||||
describe('ScheduleService', () => {
|
||||
@@ -1412,6 +1414,7 @@ describe('ScheduleRunner', () => {
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
@@ -1447,6 +1450,7 @@ describe('ScheduleRunner', () => {
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
@@ -1480,6 +1484,7 @@ describe('ScheduleRunner', () => {
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
@@ -1512,6 +1517,7 @@ describe('ScheduleRunner', () => {
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
@@ -1544,6 +1550,7 @@ describe('ScheduleRunner', () => {
|
||||
prompt: 'Test',
|
||||
model: null,
|
||||
skillMetadata: null,
|
||||
permissionConfig: null,
|
||||
branch: null,
|
||||
nextRunAt: Date.now(),
|
||||
lastRunAt: null,
|
||||
@@ -1581,17 +1588,17 @@ describe('ScheduleService run history cleanup', () => {
|
||||
|
||||
it('clearRunHistory prunes finished runs and skips a running run', async () => {
|
||||
mocks.listScheduleRunArtifactsByJob.mockReturnValue([
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null },
|
||||
{ id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2' },
|
||||
{ id: 1, status: 'failed', runBranch: null, worktreePath: null },
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null, workspaceId: null },
|
||||
{ id: 2, status: 'running', runBranch: 'schedule/7/run-2', worktreePath: '/wt/2', workspaceId: null },
|
||||
{ id: 1, status: 'failed', runBranch: null, worktreePath: null, workspaceId: null },
|
||||
])
|
||||
mocks.deleteScheduleRunsByIds.mockReturnValue(2)
|
||||
|
||||
const result = await makeService().clearRunHistory(42, 7)
|
||||
|
||||
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, [
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null },
|
||||
{ id: 1, status: 'failed', runBranch: null, worktreePath: null },
|
||||
{ id: 3, status: 'completed', runBranch: 'schedule/7/run-3', worktreePath: null, workspaceId: null },
|
||||
{ id: 1, status: 'failed', runBranch: null, worktreePath: null, workspaceId: null },
|
||||
])
|
||||
expect(mocks.deleteScheduleRunsByIds).toHaveBeenCalledWith({}, 42, 7, [3, 1])
|
||||
expect(result).toEqual({ cleared: 2 })
|
||||
@@ -1616,7 +1623,7 @@ describe('ScheduleService run history cleanup', () => {
|
||||
await makeService().deleteRun(42, 7, 5)
|
||||
|
||||
expect(mocks.stubWorktreeManager.pruneRunArtifacts).toHaveBeenCalledWith(repo, [
|
||||
{ runBranch: 'schedule/7/run-5', worktreePath: '/wt/5' },
|
||||
{ runBranch: 'schedule/7/run-5', worktreePath: '/wt/5', workspaceId: null },
|
||||
])
|
||||
expect(mocks.deleteScheduleRunById).toHaveBeenCalledWith({}, 42, 7, 5)
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user