feat(ocm): move sessions into OpenCode worktrees instead of replacing the Manager checkout

/ocm-move previously failed when the Manager checkout was dirty, behind, or on
another branch. Choose the destination instead: replace in place only when the
checkout is on the local branch, clean, and has nothing the local branch lacks;
otherwise reuse an existing OpenCode worktree on that branch when it is equally
safe; otherwise create a new OpenCode worktree through the same service the UI
and multi-runs use, so it appears in the repo's worktree lists. The new
worktree's branch is the local branch when free, else <branch>-ocm, -ocm-2 and
so on. Server work is never discarded, the confirmation states the destination
and why the main checkout was skipped, and a detached HEAD is refused.

The mirror push endpoints (bundle upload and patch) accept a worktree
directory, rejected unless it belongs to the repo, and a new endpoint creates
the worktree. The old <repo>-<branch> path that registered a plain git worktree
as a separate Manager repo is removed.
This commit is contained in:
Chris Scott committed 2026-10-08 20:47:02 -04:00
1 parent ae0dff6e84
commit bd7c3e3fef
13 files changed
+895 -585

No files matched your search

+31 -15
View File
@@ -1,14 +1,14 @@
import { createReadStream } from 'fs'
import { Readable } from 'stream'
import {
MirrorTargetEnsureResponseSchema,
MirrorTargetPlanResponseSchema,
MirrorMoveTargetResponseSchema,
MirrorWorktreeCreateResponseSchema,
MultiRunSchema,
SessionGoalSchema,
type FuseMultiRunRequest,
type LaunchMultiRunRequest,
type MirrorTargetEnsureResponse,
type MirrorTargetPlanResponse,
type MirrorMoveTargetResponse,
type MirrorWorktreeCreateResponse,
type MultiRun,
type SessionGoal,
type StartSessionGoalRequest,
@@ -244,11 +244,16 @@ export class ManagerApi {
return res.body!
}
async mirrorPatch(repoId: number, body: { baseHead: string | null; patch: string; force?: boolean }): Promise<MirrorPatchResult> {
async mirrorPatch(
repoId: number,
body: { baseHead: string | null; patch: string; force?: boolean; directory?: string },
): Promise<MirrorPatchResult> {
const payload: Record<string, unknown> = { baseHead: body.baseHead, patch: body.patch, force: body.force === true }
if (body.directory) payload.directory = body.directory
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/patch`, {
method: 'POST',
headers: { ...this.headers(), 'Content-Type': 'application/json' },
body: JSON.stringify({ baseHead: body.baseHead, patch: body.patch, force: body.force === true }),
body: JSON.stringify(payload),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror patch')
@@ -258,12 +263,23 @@ export class ManagerApi {
async mirrorUploadBundle(
repoId: number,
bundlePath: string,
opts: { branch: string | null; force?: boolean; requireCurrentBranch?: boolean; onProgress?: (bytesSent: number) => void },
opts: {
branch: string | null
force?: boolean
requireCurrentBranch?: boolean
directory?: string
targetBranch?: string
onProgress?: (bytesSent: number) => void
},
): Promise<MirrorBundleResult> {
const query = opts.force === true ? '?force=1' : ''
const params = new URLSearchParams()
if (opts.force === true) params.set('force', '1')
if (opts.directory) params.set('directory', opts.directory)
const query = params.size > 0 ? `?${params.toString()}` : ''
const headers: Record<string, string> = { ...this.headers(), 'Content-Type': 'application/octet-stream' }
if (opts.branch) headers['X-OCM-Branch'] = opts.branch
if (opts.requireCurrentBranch === true) headers['X-OCM-Require-Current-Branch'] = '1'
if (opts.targetBranch) headers['X-OCM-Target-Branch'] = opts.targetBranch
const fileStream = Readable.toWeb(createReadStream(bundlePath)) as unknown as ReadableStream<Uint8Array>
const body = opts.onProgress ? fileStream.pipeThrough(createByteCounter(opts.onProgress)) : fileStream
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle${query}`, {
@@ -286,24 +302,24 @@ export class ManagerApi {
return (await res.json()) as MirrorHead
}
async mirrorTargetPlan(repoId: number, branch: string): Promise<MirrorTargetPlanResponse> {
async mirrorMoveTarget(repoId: number, branch: string): Promise<MirrorMoveTargetResponse> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/target?branch=${encodeURIComponent(branch)}`, {
headers: this.headers(),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror target plan')
return MirrorTargetPlanResponseSchema.parse(await res.json())
if (!res.ok) throw await formatErrorResponse(res, 'mirror move target')
return MirrorMoveTargetResponseSchema.parse(await res.json())
}
async mirrorEnsureTarget(repoId: number, branch: string): Promise<MirrorTargetEnsureResponse> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/target`, {
async mirrorCreateWorktree(repoId: number, branch: string): Promise<MirrorWorktreeCreateResponse> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/worktree`, {
method: 'POST',
headers: { ...this.headers(), 'Content-Type': 'application/json' },
body: JSON.stringify({ branch }),
})
if (!res.ok) throw await formatErrorResponse(res, 'mirror target')
return MirrorTargetEnsureResponseSchema.parse(await res.json())
if (!res.ok) throw await formatErrorResponse(res, 'mirror create worktree')
return MirrorWorktreeCreateResponseSchema.parse(await res.json())
}
async mirrorContains(repoId: number, sha: string): Promise<{ contained: boolean }> {
+68 -3
View File
@@ -7,6 +7,7 @@ import { join, dirname } from 'path'
import { tmpdir } from 'os'
import { getRepoRoot, getDirtyPaths, getHeadSha, getBranchName, getMirrorPatch, runGit, hasCommit, isAncestor, countCommitsAhead } from './local-repo.js'
import { resolveOpenCodeProjectId } from '@opencode-manager/shared/project-id'
import type { MirrorCheckoutState, MirrorMoveTargetResponse } from '@opencode-manager/shared/schemas'
import type { ManagerApi } from './manager-api.js'
import { ManagerApiError } from './manager-api.js'
import { delay } from './delay.js'
@@ -86,7 +87,14 @@ export interface PushDivergence {
export async function checkPushDivergence(repoRoot: string, api: ManagerApi, repoId: number): Promise<PushDivergence> {
const info = await api.mirrorHead(repoId)
const { head: serverHead, branch: serverBranch, dirty: serverDirty } = info
return assessPushDivergence(repoRoot, info)
}
export function assessPushDivergence(
repoRoot: string,
state: { head: string | null; branch: string | null; dirty: boolean },
): PushDivergence {
const { head: serverHead, branch: serverBranch, dirty: serverDirty } = state
const localHead = getHeadSha(repoRoot)
if (!serverHead || serverHead === localHead) {
@@ -102,6 +110,59 @@ export async function checkPushDivergence(repoRoot: string, api: ManagerApi, rep
return { serverHead, serverBranch, serverDirty, diverged: true, lostCommits }
}
export type MoveDestinationKind = 'in-place' | 'existing-worktree' | 'new-worktree'
export interface MoveDestination {
kind: MoveDestinationKind
directory: string | null
branch: string
reasons: string[]
}
function isCheckoutSafe(repoRoot: string, state: MirrorCheckoutState): boolean {
return !state.dirty && !assessPushDivergence(repoRoot, state).diverged
}
function checkoutUnusableReasons(
repoRoot: string,
label: string,
state: MirrorCheckoutState,
localBranch: string,
): string[] {
if (state.branch !== localBranch) return [`${label} is on ${state.branch ?? 'a detached HEAD'}`]
const reasons: string[] = []
if (state.dirty) reasons.push(`${label} has uncommitted changes`)
if (assessPushDivergence(repoRoot, state).diverged) reasons.push(`${label} has commits not in your local branch`)
return reasons
}
export function chooseMoveDestination(
repoRoot: string,
localBranch: string,
target: MirrorMoveTargetResponse,
): MoveDestination {
if (target.main.branch === localBranch && isCheckoutSafe(repoRoot, target.main)) {
return { kind: 'in-place', directory: target.main.directory, branch: localBranch, reasons: [] }
}
if (target.branchWorktree && isCheckoutSafe(repoRoot, target.branchWorktree)) {
return { kind: 'existing-worktree', directory: target.branchWorktree.directory, branch: localBranch, reasons: [] }
}
const reasons = checkoutUnusableReasons(repoRoot, 'the server checkout', target.main, localBranch)
if (target.branchWorktree) {
reasons.push(
...checkoutUnusableReasons(
repoRoot,
`the worktree on ${target.branchWorktree.branch ?? 'another branch'}`,
target.branchWorktree,
localBranch,
),
)
}
return { kind: 'new-worktree', directory: null, branch: target.newWorktreeBranch, reasons }
}
export function describePushDivergence(div: PushDivergence): string[] {
const reasons: string[] = []
if (div.diverged) {
@@ -371,11 +432,11 @@ export async function mirrorDown(
export async function mirrorUpPatch(
plan: MirrorPlan,
opts: Pick<MirrorUpOpts, 'api' | 'force'>,
opts: Pick<MirrorUpOpts, 'api' | 'force'> & { directory?: string },
): Promise<{ repoId: number; fullPath: string; branch: string | null; head: string | null; created: false; applied: true }> {
const repoId = plan.matched[0]!.repoId
const patch = getMirrorPatch(plan.repoRoot)
return opts.api.mirrorPatch(repoId, { baseHead: getHeadSha(plan.repoRoot), patch, force: opts.force })
return opts.api.mirrorPatch(repoId, { baseHead: getHeadSha(plan.repoRoot), patch, force: opts.force, directory: opts.directory })
}
function applyPatch(repoRoot: string, patch: string): void {
@@ -532,6 +593,8 @@ export type MirrorUpFastPhase =
type MirrorUpFastOpts = Pick<MirrorUpOpts, 'api' | 'force'> & {
requireCurrentBranch?: boolean
directory?: string
targetBranch?: string
onPhase?: (phase: MirrorUpFastPhase) => void
}
@@ -550,6 +613,8 @@ export async function mirrorUpFast(
branch: getBranchName(plan.repoRoot),
force: opts.force,
requireCurrentBranch: opts.requireCurrentBranch,
directory: opts.directory,
targetBranch: opts.targetBranch,
onProgress: onPhase
? (bytesSent) => {
onPhase({ kind: 'uploading', bytesSent, totalBytes: size })
+40 -45
View File
@@ -2,10 +2,9 @@ import type { Context } from '@opencode/plugin/tui/context'
import { readInstallNotice } from './state.js'
import { resolveManagerAuth } from './manager-auth.js'
import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js'
import { ManagerApi, ManagerApiError } from './manager-api.js'
import type { MirrorTargetPlanResponse } from '@opencode-manager/shared/schemas'
import { prepareMirror, checkPushDivergence, describePushDivergence, mirrorUpFast, pickMatchedRepo } from './mirror.js'
import type { MirrorPlan, RemoteRepoSummary } from './mirror.js'
import { ManagerApi } from './manager-api.js'
import { prepareMirror, mirrorUpFast, pickMatchedRepo, chooseMoveDestination } from './mirror.js'
import type { MirrorPlan, MoveDestination } from './mirror.js'
import { getBranchName } from './local-repo.js'
import { transferSession, moveReminderText } from './session-move.js'
import { createManagerSessionTransfer } from './remote-session.js'
@@ -123,39 +122,24 @@ async function describeMoveBlocker(transfer: ManagerSessionTransfer, sessionID:
return null
}
async function describeRemoteDiscard(repoRoot: string, managerApi: ManagerApi, repoId: number): Promise<string[]> {
try {
return describePushDivergence(await checkPushDivergence(repoRoot, managerApi, repoId))
} catch (error) {
if (error instanceof ManagerApiError && error.status === 404) return []
throw error
}
}
function describeMoveTarget(repoName: string, target: MirrorTargetPlanResponse): string {
switch (target.kind) {
function moveConfirmMessage(repoName: string, destination: MoveDestination, localBranch: string): string {
switch (destination.kind) {
case 'in-place':
return `Replace the repo state of ${repoName} (${target.fullPath}) with your local working tree and move this session there?`
case 'existing':
return `${repoName} is checked out on ${target.currentBranch ?? 'another branch'}; branch ${target.branch} lives in worktree ${target.localPath} (${target.fullPath}).\n\nReplace that worktree with your local working tree and move this session there?`
case 'new':
return `${repoName} is checked out on ${target.currentBranch ?? 'another branch'}; it will not be touched.\n\nCreate worktree ${target.localPath} (${target.fullPath}) for branch ${target.branch}, push your local working tree there, and move this session?`
return `Replace the repo state of ${repoName} (${destination.directory}) with your local working tree and move this session there?`
case 'existing-worktree':
return `${repoName} is checked out on another branch; branch ${destination.branch} lives in worktree ${destination.directory}.\n\nReplace that worktree with your local working tree and move this session there?`
case 'new-worktree': {
const reasons = destination.reasons.length > 0
? `\n\nThe server checkout was not used because:\n${destination.reasons.map((r) => ` - ${r}`).join('\n')}`
: ''
const suffix = destination.branch !== localBranch
? `\n\n${localBranch} is checked out on the server, so ${destination.branch} is used instead.`
: ''
return `The ${repoName} server checkout will not be touched.${reasons}\n\nCreate a new OpenCode worktree for branch ${destination.branch}, push your local working tree there, and move this session?${suffix}`
}
}
}
function moveConfirmMessage(repoName: string, target: MirrorTargetPlanResponse, discardReasons: string[]): string {
const base = describeMoveTarget(repoName, target)
if (discardReasons.length === 0) return base
return `${base}\n\nThis discards server-side work:\n${discardReasons.map((r) => ` - ${r}`).join('\n')}`
}
async function resolveMoveTarget(managerApi: ManagerApi, matched: RemoteRepoSummary, remoteDirectory: string, localBranch: string | null): Promise<MirrorTargetPlanResponse> {
if (!localBranch) {
return { kind: 'in-place', repoId: matched.repoId, fullPath: remoteDirectory, localPath: remoteDirectory, branch: '', currentBranch: null }
}
return managerApi.mirrorTargetPlan(matched.repoId, localBranch)
}
async function runSessionMove(context: Context, setMoveProgress: MoveProgressSetter): Promise<void> {
try {
const sessionTarget = requireSessionTarget(context)
@@ -177,11 +161,14 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
}
const localBranch = getBranchName(plan.repoRoot)
if (!localBranch) {
context.ui.toast.show({ variant: 'error', message: 'Check out a branch before moving; a detached HEAD cannot be moved.' })
return
}
const matched = pickMatchedRepo(plan.matched, localBranch)
?? await selectDialog(context, 'Move session to Manager repo', plan.matched.map((r) => ({ title: r.name, description: `id=${r.repoId} branch=${r.branch ?? '-'}`, value: r })))
if (!matched) return
const matchedRepoId = matched.repoId
const remoteRepo = repos.find((r) => r.repoId === matchedRepoId)!
await warmRepoProxy(auth.managerUrl, auth.token, matchedRepoId)
@@ -193,25 +180,33 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
}
const managerApi = new ManagerApi(auth.managerUrl, auth.token)
const target = await resolveMoveTarget(managerApi, matched, remoteRepo.directory, localBranch)
const discardReasons = target.repoId === null ? [] : await describeRemoteDiscard(plan.repoRoot, managerApi, target.repoId)
const target = await managerApi.mirrorMoveTarget(matched.repoId, localBranch)
const destination = chooseMoveDestination(plan.repoRoot, localBranch, target)
const proceed = await confirmDialog(context, {
title: 'Move session to Manager',
message: moveConfirmMessage(matched.name, target, discardReasons),
message: moveConfirmMessage(matched.name, destination, localBranch),
})
if (!proceed) return
let targetRepoId = target.repoId
if (targetRepoId === null) {
setMoveProgress({ label: `creating worktree ${target.localPath}`, fraction: null })
targetRepoId = (await managerApi.mirrorEnsureTarget(matched.repoId, target.branch)).repoId
let pushDirectory: string | undefined
let pushTargetBranch: string | undefined
if (destination.kind === 'new-worktree') {
setMoveProgress({ label: `creating worktree ${destination.branch}`, fraction: null })
const worktree = await managerApi.mirrorCreateWorktree(matched.repoId, destination.branch)
pushDirectory = worktree.directory
pushTargetBranch = destination.branch
} else if (destination.kind === 'existing-worktree') {
pushDirectory = destination.directory ?? undefined
}
const selectedPlan: MirrorPlan = { ...plan, matched: [{ ...matched, repoId: targetRepoId }] }
const selectedPlan: MirrorPlan = { ...plan, matched: [matched] }
const pushed = await mirrorUpFast(selectedPlan, {
api: managerApi,
force: true,
requireCurrentBranch: true,
requireCurrentBranch: destination.kind !== 'new-worktree',
directory: pushDirectory,
targetBranch: pushTargetBranch,
onPhase: (phase) => setMoveProgress(pushPhaseProgress(phase)),
})
const remoteDirectory = pushed.fullPath
@@ -232,10 +227,10 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
setMoveProgress(null)
const warp = await confirmDialog(context, { title: 'Attach to moved session?', message: 'Exit this TUI and attach to the moved session on the Manager now?' })
if (warp) {
await warmRepoProxy(auth.managerUrl, auth.token, pushed.repoId)
await warmRepoProxy(auth.managerUrl, auth.token, matched.repoId)
setPendingWarp({
kind: 'attach',
target: { managerUrl: auth.managerUrl, token: auth.token, repoId: pushed.repoId, sessionID: result.sessionID, repoName: matched.name },
target: { managerUrl: auth.managerUrl, token: auth.token, repoId: matched.repoId, sessionID: result.sessionID, repoName: matched.name },
})
context.keymap.dispatch('app.exit')
return