mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
fix(ocm): make /ocm-move worktree moves safe and round-trippable
- Answer the old /mirror/target routes with a 410 upgrade message and serve the lookup at GET /mirror/checkouts; detect older Managers via the token probe (MANAGER_FEATURE_MISSING). - Create the move worktree and import the bundle in one call; worktree setup runs after the import and the worktree is removed on failure. - Never rewind a server branch: suffix the new worktree branch when the server branch has commits the local branch lacks, and skip both the source and target branch when updating refs. - Reuse clean <branch>-ocm[-N] worktrees and legacy worktree repo rows instead of creating new ones on every move. - Let ocm push/pull target the worktree on the local branch via a directory parameter on the mirror read routes; no tarball fallback for worktrees. - Share one sibling loader (listRepoSiblings), validate branch names, compare canonical paths in isDirectoryInUse, and cut redundant git work in the checkouts lookup and the CLI destination choice.
This commit is contained in:
1 parent
bd7c3e3fef
commit
67f70e9635
21 files changed
+1777
-517
No files matched your search
+51
-26
@@ -1,13 +1,13 @@
|
||||
import { createReadStream } from 'fs'
|
||||
import { Readable } from 'stream'
|
||||
import {
|
||||
MirrorMoveTargetResponseSchema,
|
||||
MirrorCheckoutsResponseSchema,
|
||||
MirrorWorktreeCreateResponseSchema,
|
||||
MultiRunSchema,
|
||||
SessionGoalSchema,
|
||||
type FuseMultiRunRequest,
|
||||
type LaunchMultiRunRequest,
|
||||
type MirrorMoveTargetResponse,
|
||||
type MirrorCheckoutsResponse,
|
||||
type MirrorWorktreeCreateResponse,
|
||||
type MultiRun,
|
||||
type SessionGoal,
|
||||
@@ -78,6 +78,13 @@ function createByteCounter(onProgress: (bytesSent: number) => void): TransformSt
|
||||
|
||||
export const MANAGER_FEATURE_MISSING = 'MANAGER_FEATURE_MISSING'
|
||||
|
||||
const DEFAULT_FEATURE_NAME = 'ocm goals and multi-runs'
|
||||
const MOVE_FEATURE_NAME = '/ocm-move worktrees'
|
||||
|
||||
function directoryQuery(directory: string | undefined): string {
|
||||
return directory ? `?${new URLSearchParams({ directory }).toString()}` : ''
|
||||
}
|
||||
|
||||
export class ManagerApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
@@ -141,9 +148,9 @@ export class ManagerApi {
|
||||
path: string,
|
||||
operation: string,
|
||||
parse: (body: unknown) => T,
|
||||
init?: RequestInit & { feature?: boolean },
|
||||
init?: RequestInit & { feature?: boolean; featureName?: string },
|
||||
): Promise<T> {
|
||||
const { feature, ...requestInit } = init ?? {}
|
||||
const { feature, featureName, ...requestInit } = init ?? {}
|
||||
const baseHeaders = this.headers(
|
||||
typeof requestInit.body === 'string' ? { 'Content-Type': 'application/json' } : {},
|
||||
)
|
||||
@@ -151,25 +158,29 @@ export class ManagerApi {
|
||||
...requestInit,
|
||||
headers: { ...baseHeaders, ...(requestInit.headers as Record<string, string> | undefined) },
|
||||
})
|
||||
if (!res.ok) throw await this.handleErrorResponse(res, operation, feature === true, requestInit.signal ?? undefined)
|
||||
if (!res.ok) {
|
||||
const featureLabel = feature === true ? (featureName ?? DEFAULT_FEATURE_NAME) : null
|
||||
throw await this.handleErrorResponse(res, operation, featureLabel, requestInit.signal ?? undefined)
|
||||
}
|
||||
return parse(await res.json())
|
||||
}
|
||||
|
||||
private async handleErrorResponse(
|
||||
res: Response,
|
||||
operation: string,
|
||||
feature: boolean,
|
||||
featureName: string | null,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ManagerApiError> {
|
||||
const error = await formatErrorResponse(res, operation)
|
||||
if (feature && error.status === 401) {
|
||||
return this.probeFeatureSupport(operation, error, signal)
|
||||
if (featureName !== null && error.status === 401) {
|
||||
return this.probeFeatureSupport(operation, featureName, error, signal)
|
||||
}
|
||||
return error
|
||||
}
|
||||
|
||||
private async probeFeatureSupport(
|
||||
operation: string,
|
||||
featureName: string,
|
||||
fallback: ManagerApiError,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ManagerApiError> {
|
||||
@@ -177,7 +188,7 @@ export class ManagerApi {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/opencode-workspaces`, { headers: this.headers(), signal })
|
||||
if (res.ok) {
|
||||
return new ManagerApiError(
|
||||
`${operation} failed: this OpenCode Manager is too old for ocm goals and multi-runs; upgrade the Manager.`,
|
||||
`${operation} failed: this OpenCode Manager is too old for ${featureName}; upgrade the Manager.`,
|
||||
401,
|
||||
MANAGER_FEATURE_MISSING,
|
||||
operation,
|
||||
@@ -293,8 +304,8 @@ export class ManagerApi {
|
||||
return (await res.json()) as MirrorBundleResult
|
||||
}
|
||||
|
||||
async mirrorHead(repoId: number): Promise<MirrorHead> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/head`, {
|
||||
async mirrorHead(repoId: number, directory?: string): Promise<MirrorHead> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/head${directoryQuery(directory)}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
@@ -302,28 +313,42 @@ export class ManagerApi {
|
||||
return (await res.json()) as MirrorHead
|
||||
}
|
||||
|
||||
async mirrorMoveTarget(repoId: number, branch: string): Promise<MirrorMoveTargetResponse> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/target?branch=${encodeURIComponent(branch)}`, {
|
||||
async mirrorCheckouts(repoId: number, branch: string): Promise<MirrorCheckoutsResponse> {
|
||||
const params = new URLSearchParams({ branch })
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/checkouts?${params.toString()}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror move target')
|
||||
return MirrorMoveTargetResponseSchema.parse(await res.json())
|
||||
if (!res.ok) throw await this.handleErrorResponse(res, 'mirror checkouts', MOVE_FEATURE_NAME)
|
||||
return MirrorCheckoutsResponseSchema.parse(await res.json())
|
||||
}
|
||||
|
||||
async mirrorCreateWorktree(repoId: number, branch: string): Promise<MirrorWorktreeCreateResponse> {
|
||||
async mirrorCreateWorktree(
|
||||
repoId: number,
|
||||
bundlePath: string,
|
||||
opts: { branch: string; targetBranch: string; onProgress?: (bytesSent: number) => void },
|
||||
): Promise<MirrorWorktreeCreateResponse> {
|
||||
const headers: Record<string, string> = {
|
||||
...this.headers(),
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'X-OCM-Branch': opts.branch,
|
||||
'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/worktree`, {
|
||||
method: 'POST',
|
||||
headers: { ...this.headers(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ branch }),
|
||||
})
|
||||
headers,
|
||||
body: body as BodyInit,
|
||||
duplex: 'half',
|
||||
} as RequestInit & { duplex: 'half' })
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror create worktree')
|
||||
if (!res.ok) throw await this.handleErrorResponse(res, 'mirror create worktree', MOVE_FEATURE_NAME)
|
||||
return MirrorWorktreeCreateResponseSchema.parse(await res.json())
|
||||
}
|
||||
|
||||
async mirrorContains(repoId: number, sha: string): Promise<{ contained: boolean }> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/contains/${sha}`, {
|
||||
async mirrorContains(repoId: number, sha: string, directory?: string): Promise<{ contained: boolean }> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/contains/${sha}${directoryQuery(directory)}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
@@ -331,8 +356,8 @@ export class ManagerApi {
|
||||
return (await res.json()) as { repoId: number; contained: boolean }
|
||||
}
|
||||
|
||||
async mirrorDownloadBundle(repoId: number): Promise<ReadableStream<Uint8Array>> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle`, {
|
||||
async mirrorDownloadBundle(repoId: number, directory?: string): Promise<ReadableStream<Uint8Array>> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle${directoryQuery(directory)}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
@@ -340,8 +365,8 @@ export class ManagerApi {
|
||||
return res.body!
|
||||
}
|
||||
|
||||
async mirrorPatchSnapshot(repoId: number): Promise<MirrorPatchSnapshot> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/patch`, {
|
||||
async mirrorPatchSnapshot(repoId: number, directory?: string): Promise<MirrorPatchSnapshot> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/patch${directoryQuery(directory)}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
|
||||
+152
-58
@@ -7,9 +7,9 @@ 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 { MirrorCheckoutState, MirrorCheckoutsResponse, WorktreeSetupResult } from '@opencode-manager/shared/schemas'
|
||||
import type { ManagerApi } from './manager-api.js'
|
||||
import { ManagerApiError } from './manager-api.js'
|
||||
import { ManagerApiError, isManagerRouteMissing } from './manager-api.js'
|
||||
import { delay } from './delay.js'
|
||||
|
||||
const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo', '.DS_Store', '._*']
|
||||
@@ -85,8 +85,13 @@ export interface PushDivergence {
|
||||
lostCommits: number
|
||||
}
|
||||
|
||||
export async function checkPushDivergence(repoRoot: string, api: ManagerApi, repoId: number): Promise<PushDivergence> {
|
||||
const info = await api.mirrorHead(repoId)
|
||||
export async function checkPushDivergence(
|
||||
repoRoot: string,
|
||||
api: ManagerApi,
|
||||
repoId: number,
|
||||
directory?: string,
|
||||
): Promise<PushDivergence> {
|
||||
const info = await api.mirrorHead(repoId, directory)
|
||||
return assessPushDivergence(repoRoot, info)
|
||||
}
|
||||
|
||||
@@ -110,19 +115,13 @@ export function assessPushDivergence(
|
||||
return { serverHead, serverBranch, serverDirty, diverged: true, lostCommits }
|
||||
}
|
||||
|
||||
export type MoveDestinationKind = 'in-place' | 'existing-worktree' | 'new-worktree'
|
||||
|
||||
export interface MoveDestination {
|
||||
kind: MoveDestinationKind
|
||||
kind: 'in-place' | 'existing-worktree' | 'new-worktree'
|
||||
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,
|
||||
@@ -130,47 +129,64 @@ function checkoutUnusableReasons(
|
||||
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
|
||||
return describePushDivergence(assessPushDivergence(repoRoot, state), label)
|
||||
}
|
||||
|
||||
function worktreeUnusableReasons(
|
||||
repoRoot: string,
|
||||
state: MirrorCheckoutState,
|
||||
): string[] {
|
||||
return describePushDivergence(assessPushDivergence(repoRoot, state), `the worktree on ${state.branch ?? 'another branch'}`)
|
||||
}
|
||||
|
||||
function localContainsCommit(repoRoot: string, sha: string): boolean {
|
||||
const localHead = getHeadSha(repoRoot)
|
||||
if (!localHead) return false
|
||||
return hasCommit(repoRoot, sha) && isAncestor(repoRoot, sha, localHead)
|
||||
}
|
||||
|
||||
export function chooseMoveDestination(
|
||||
repoRoot: string,
|
||||
localBranch: string,
|
||||
target: MirrorMoveTargetResponse,
|
||||
checkouts: MirrorCheckoutsResponse,
|
||||
): MoveDestination {
|
||||
if (target.main.branch === localBranch && isCheckoutSafe(repoRoot, target.main)) {
|
||||
return { kind: 'in-place', directory: target.main.directory, branch: localBranch, reasons: [] }
|
||||
const mainReasons = checkoutUnusableReasons(repoRoot, 'the server checkout', checkouts.main, localBranch)
|
||||
if (mainReasons.length === 0) {
|
||||
return { kind: 'in-place', directory: checkouts.main.directory, branch: localBranch, reasons: [] }
|
||||
}
|
||||
|
||||
if (target.branchWorktree && isCheckoutSafe(repoRoot, target.branchWorktree)) {
|
||||
return { kind: 'existing-worktree', directory: target.branchWorktree.directory, branch: localBranch, reasons: [] }
|
||||
const worktreeReasons: string[] = []
|
||||
for (const worktree of checkouts.worktrees) {
|
||||
const reasons = worktreeUnusableReasons(repoRoot, worktree)
|
||||
if (reasons.length === 0) {
|
||||
return { kind: 'existing-worktree', directory: worktree.directory, branch: worktree.branch ?? localBranch, reasons: [] }
|
||||
}
|
||||
worktreeReasons.push(...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,
|
||||
),
|
||||
)
|
||||
const branchHeadMissing = checkouts.branchHead !== null && !localContainsCommit(repoRoot, checkouts.branchHead)
|
||||
const useSuffix = checkouts.branchCheckedOut || branchHeadMissing
|
||||
const reasons = [
|
||||
...mainReasons,
|
||||
...worktreeReasons,
|
||||
...(branchHeadMissing ? [`the server branch ${localBranch} has commits not in your local branch`] : []),
|
||||
]
|
||||
return {
|
||||
kind: 'new-worktree',
|
||||
directory: null,
|
||||
branch: useSuffix ? checkouts.suffixedWorktreeBranch : localBranch,
|
||||
reasons,
|
||||
}
|
||||
return { kind: 'new-worktree', directory: null, branch: target.newWorktreeBranch, reasons }
|
||||
}
|
||||
|
||||
export function describePushDivergence(div: PushDivergence): string[] {
|
||||
export function describePushDivergence(div: PushDivergence, subject = 'the server'): string[] {
|
||||
const reasons: string[] = []
|
||||
if (div.diverged) {
|
||||
reasons.push(div.lostCommits >= 0
|
||||
? `the server is ${div.lostCommits} commit(s) ahead of your local branch`
|
||||
: 'the server has commit(s) not present in your local branch')
|
||||
? `${subject} is ${div.lostCommits} commit(s) ahead of your local branch`
|
||||
: `${subject} has commit(s) not present in your local branch`)
|
||||
}
|
||||
if (div.serverDirty) reasons.push('the server has uncommitted changes')
|
||||
if (div.serverDirty) reasons.push(`${subject} has uncommitted changes`)
|
||||
return reasons
|
||||
}
|
||||
|
||||
@@ -180,17 +196,22 @@ export interface PullDivergence {
|
||||
serverHead: string | null
|
||||
}
|
||||
|
||||
export async function checkPullDivergence(repoRoot: string, api: ManagerApi, repoId: number): Promise<PullDivergence> {
|
||||
export async function checkPullDivergence(
|
||||
repoRoot: string,
|
||||
api: ManagerApi,
|
||||
repoId: number,
|
||||
directory?: string,
|
||||
): Promise<PullDivergence> {
|
||||
const localHead = getHeadSha(repoRoot)
|
||||
if (!localHead) return { diverged: false, lostCommits: 0, serverHead: null }
|
||||
|
||||
const { contained } = await api.mirrorContains(repoId, localHead)
|
||||
const { contained } = await api.mirrorContains(repoId, localHead, directory)
|
||||
if (contained) return { diverged: false, lostCommits: 0, serverHead: null }
|
||||
|
||||
let serverHead: string | null = null
|
||||
let lostCommits = -1
|
||||
try {
|
||||
serverHead = (await api.mirrorHead(repoId)).head
|
||||
serverHead = (await api.mirrorHead(repoId, directory)).head
|
||||
if (serverHead) lostCommits = countCommitsAhead(repoRoot, serverHead, localHead)
|
||||
} catch {
|
||||
// best-effort: count is informational only
|
||||
@@ -198,6 +219,36 @@ export async function checkPullDivergence(repoRoot: string, api: ManagerApi, rep
|
||||
return { diverged: true, lostCommits, serverHead }
|
||||
}
|
||||
|
||||
export interface BranchCheckoutSelection {
|
||||
directory?: string
|
||||
targetBranch?: string
|
||||
}
|
||||
|
||||
export async function resolveBranchCheckout(
|
||||
api: ManagerApi,
|
||||
repoId: number,
|
||||
repoRoot: string,
|
||||
): Promise<BranchCheckoutSelection> {
|
||||
const localBranch = getBranchName(repoRoot)
|
||||
if (!localBranch) return {}
|
||||
|
||||
let checkouts: MirrorCheckoutsResponse
|
||||
try {
|
||||
checkouts = await api.mirrorCheckouts(repoId, localBranch)
|
||||
} catch (error) {
|
||||
if (isManagerRouteMissing(error) || (error instanceof ManagerApiError && error.status === 410)) return {}
|
||||
throw error
|
||||
}
|
||||
|
||||
if (checkouts.main.branch === localBranch) return {}
|
||||
const worktree = checkouts.worktrees[0]
|
||||
if (!worktree) return {}
|
||||
return {
|
||||
directory: worktree.directory,
|
||||
targetBranch: worktree.branch !== null && worktree.branch !== localBranch ? worktree.branch : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export interface MirrorProgress {
|
||||
bytesSent: number
|
||||
}
|
||||
@@ -520,7 +571,13 @@ function deleteSyncRefs(repoRoot: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function importLocalBundle(repoRoot: string, bundlePath: string, branch: string | null, force: boolean): void {
|
||||
function importLocalBundle(
|
||||
repoRoot: string,
|
||||
bundlePath: string,
|
||||
branch: string | null,
|
||||
force: boolean,
|
||||
sourceBranch?: string,
|
||||
): void {
|
||||
runGit(repoRoot, ['fetch', bundlePath, '+refs/heads/*:refs/remotes/ocm-sync/*', '+refs/tags/*:refs/tags/*'])
|
||||
try {
|
||||
const refs = runGit(repoRoot, ['for-each-ref', '--format=%(refname:strip=3) %(objectname)', 'refs/remotes/ocm-sync'])
|
||||
@@ -537,10 +594,11 @@ function importLocalBundle(repoRoot: string, bundlePath: string, branch: string
|
||||
|
||||
const lockedElsewhere = branchOwnedElsewhere(listWorktreeBranches(repoRoot), repoRoot)
|
||||
const currentBranch = getBranchName(repoRoot)
|
||||
const source = sourceBranch ?? branch
|
||||
|
||||
if (branch) {
|
||||
const incomingSha = incoming.get(branch)
|
||||
if (!incomingSha) throw new MirrorAbort(`no incoming branch '${branch}' in the server bundle`)
|
||||
if (branch && source) {
|
||||
const incomingSha = incoming.get(source)
|
||||
if (!incomingSha) throw new MirrorAbort(`no incoming branch '${source}' in the server bundle`)
|
||||
if (lockedElsewhere.has(branch)) {
|
||||
throw new MirrorAbort(`branch '${branch}' is checked out in another worktree; release it there before pulling`)
|
||||
}
|
||||
@@ -554,9 +612,13 @@ function importLocalBundle(repoRoot: string, bundlePath: string, branch: string
|
||||
}
|
||||
}
|
||||
|
||||
const skipRefs = new Set<string>()
|
||||
if (branch) skipRefs.add(branch)
|
||||
if (source) skipRefs.add(source)
|
||||
|
||||
const updates: string[] = []
|
||||
for (const [name, sha] of incoming) {
|
||||
if (branch === name) continue
|
||||
if (skipRefs.has(name)) continue
|
||||
if (lockedElsewhere.has(name)) continue
|
||||
if (branch === null && name === currentBranch) continue
|
||||
updates.push(`update refs/heads/${name} ${sha}\n`)
|
||||
@@ -565,8 +627,8 @@ function importLocalBundle(repoRoot: string, bundlePath: string, branch: string
|
||||
runGit(repoRoot, ['update-ref', '--stdin'], updates.join(''))
|
||||
}
|
||||
|
||||
if (branch) {
|
||||
const targetSha = incoming.get(branch)!
|
||||
if (branch && source) {
|
||||
const targetSha = incoming.get(source)!
|
||||
runGit(repoRoot, ['reset', '--hard', targetSha])
|
||||
runGit(repoRoot, ['clean', '-fd'])
|
||||
}
|
||||
@@ -575,9 +637,9 @@ function importLocalBundle(repoRoot: string, bundlePath: string, branch: string
|
||||
}
|
||||
}
|
||||
|
||||
async function writeBundleStream(repoId: number, api: ManagerApi): Promise<string> {
|
||||
async function writeBundleStream(repoId: number, api: ManagerApi, directory?: string): Promise<string> {
|
||||
const bundlePath = join(tmpdir(), `ocm-bundle-down-${Date.now()}-${Math.random().toString(36).slice(2)}.bundle`)
|
||||
const stream = await api.mirrorDownloadBundle(repoId)
|
||||
const stream = await api.mirrorDownloadBundle(repoId, directory)
|
||||
await pipeline(
|
||||
Readable.fromWeb(stream as unknown as Parameters<typeof Readable.fromWeb>[0]),
|
||||
createWriteStream(bundlePath),
|
||||
@@ -595,13 +657,23 @@ type MirrorUpFastOpts = Pick<MirrorUpOpts, 'api' | 'force'> & {
|
||||
requireCurrentBranch?: boolean
|
||||
directory?: string
|
||||
targetBranch?: string
|
||||
createWorktree?: { targetBranch: string }
|
||||
onPhase?: (phase: MirrorUpFastPhase) => void
|
||||
}
|
||||
|
||||
export interface MirrorUpFastResult {
|
||||
repoId: number
|
||||
fullPath: string
|
||||
branch: string | null
|
||||
head: string | null
|
||||
created: boolean
|
||||
worktreeSetup?: WorktreeSetupResult
|
||||
}
|
||||
|
||||
export async function mirrorUpFast(
|
||||
plan: MirrorPlan,
|
||||
opts: MirrorUpFastOpts,
|
||||
): Promise<{ repoId: number; fullPath: string; branch: string | null; head: string | null; created: false }> {
|
||||
): Promise<MirrorUpFastResult> {
|
||||
const repoId = plan.matched[0]!.repoId
|
||||
const onPhase = opts.onPhase
|
||||
onPhase?.({ kind: 'bundling' })
|
||||
@@ -609,18 +681,38 @@ export async function mirrorUpFast(
|
||||
try {
|
||||
const { size } = await fsp.stat(bundlePath)
|
||||
onPhase?.({ kind: 'uploading', bytesSent: 0, totalBytes: size })
|
||||
const onProgress = onPhase
|
||||
? (bytesSent: number) => {
|
||||
onPhase({ kind: 'uploading', bytesSent, totalBytes: size })
|
||||
if (bytesSent >= size) onPhase({ kind: 'processing' })
|
||||
}
|
||||
: undefined
|
||||
|
||||
if (opts.createWorktree) {
|
||||
const branch = getBranchName(plan.repoRoot)
|
||||
if (!branch) throw new MirrorAbort('cannot create a worktree from a detached HEAD')
|
||||
const created = await opts.api.mirrorCreateWorktree(repoId, bundlePath, {
|
||||
branch,
|
||||
targetBranch: opts.createWorktree.targetBranch,
|
||||
onProgress,
|
||||
})
|
||||
return {
|
||||
repoId: created.repoId,
|
||||
fullPath: created.fullPath,
|
||||
branch: created.branch,
|
||||
head: created.head,
|
||||
created: true,
|
||||
worktreeSetup: created.worktreeSetup,
|
||||
}
|
||||
}
|
||||
|
||||
await opts.api.mirrorUploadBundle(repoId, bundlePath, {
|
||||
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 })
|
||||
if (bytesSent >= size) onPhase({ kind: 'processing' })
|
||||
}
|
||||
: undefined,
|
||||
onProgress,
|
||||
})
|
||||
onPhase?.({ kind: 'patching' })
|
||||
const patchResult = await mirrorUpPatch(plan, opts)
|
||||
@@ -634,16 +726,18 @@ export async function mirrorDownFast(
|
||||
repoId: number,
|
||||
repoRoot: string,
|
||||
api: ManagerApi,
|
||||
opts: { force: boolean } = { force: false },
|
||||
opts: { force: boolean; directory?: string; sourceBranch?: string; targetBranch?: string } = { force: false },
|
||||
): Promise<void> {
|
||||
if (!opts.force && getDirtyPaths(repoRoot).size > 0) {
|
||||
throw new MirrorAbort('working tree has uncommitted changes; rerun with --force')
|
||||
}
|
||||
|
||||
const snapshot = await api.mirrorPatchSnapshot(repoId)
|
||||
const bundlePath = await writeBundleStream(repoId, api)
|
||||
const snapshot = await api.mirrorPatchSnapshot(repoId, opts.directory)
|
||||
const bundlePath = await writeBundleStream(repoId, api, opts.directory)
|
||||
try {
|
||||
importLocalBundle(repoRoot, bundlePath, snapshot.branch, opts.force)
|
||||
const branch = opts.targetBranch ?? snapshot.branch
|
||||
const sourceBranch = opts.sourceBranch ?? branch ?? undefined
|
||||
importLocalBundle(repoRoot, bundlePath, branch, opts.force, sourceBranch)
|
||||
applyPatch(repoRoot, snapshot.patch)
|
||||
} finally {
|
||||
await fsp.rm(bundlePath, { force: true }).catch(() => {})
|
||||
|
||||
+20
-18
@@ -127,13 +127,13 @@ function moveConfirmMessage(repoName: string, destination: MoveDestination, loca
|
||||
case 'in-place':
|
||||
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?`
|
||||
return `${repoName}'s main checkout is on another branch, but branch ${destination.branch} already 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.`
|
||||
? `\n\nYour local branch ${localBranch} cannot be pushed directly, so a new worktree on ${destination.branch} is created 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}`
|
||||
}
|
||||
@@ -180,8 +180,8 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
|
||||
}
|
||||
|
||||
const managerApi = new ManagerApi(auth.managerUrl, auth.token)
|
||||
const target = await managerApi.mirrorMoveTarget(matched.repoId, localBranch)
|
||||
const destination = chooseMoveDestination(plan.repoRoot, localBranch, target)
|
||||
const checkouts = await managerApi.mirrorCheckouts(matched.repoId, localBranch)
|
||||
const destination = chooseMoveDestination(plan.repoRoot, localBranch, checkouts)
|
||||
|
||||
const proceed = await confirmDialog(context, {
|
||||
title: 'Move session to Manager',
|
||||
@@ -189,28 +189,30 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
|
||||
})
|
||||
if (!proceed) return
|
||||
|
||||
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] }
|
||||
const pushed = await mirrorUpFast(selectedPlan, {
|
||||
api: managerApi,
|
||||
force: true,
|
||||
requireCurrentBranch: destination.kind !== 'new-worktree',
|
||||
directory: pushDirectory,
|
||||
targetBranch: pushTargetBranch,
|
||||
...(destination.kind === 'new-worktree'
|
||||
? { createWorktree: { targetBranch: destination.branch } }
|
||||
: destination.kind === 'existing-worktree'
|
||||
? {
|
||||
requireCurrentBranch: true,
|
||||
directory: destination.directory ?? undefined,
|
||||
targetBranch: destination.branch !== localBranch ? destination.branch : undefined,
|
||||
}
|
||||
: { requireCurrentBranch: true }),
|
||||
onPhase: (phase) => setMoveProgress(pushPhaseProgress(phase)),
|
||||
})
|
||||
const remoteDirectory = pushed.fullPath
|
||||
|
||||
if (pushed.worktreeSetup?.status === 'failed') {
|
||||
context.ui.toast.show({
|
||||
variant: 'warning',
|
||||
message: `Worktree setup failed: ${pushed.worktreeSetup.error}. The session was still moved.`,
|
||||
})
|
||||
}
|
||||
|
||||
const result = await transferSession(
|
||||
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user