feat(ocm-move): plan worktree mirror targets and stream move progress (#345)

* feat(ocm-move): plan worktree mirror targets and stream move progress

- Plan/ensure mirror targets per branch via new internal endpoints, creating a worktree repo when the target branch is not checked out in the source repo
- Skip branches checked out in other worktrees during bundle import and reset/clean before checkout on both server and CLI
- Rewrite workspace paths in message.updated events when replaying moved sessions
- Stream live move progress (bundle, upload, import, patch, replay) in the TUI
- Prefer branch-matched repos when moving sessions and share push-divergence descriptions

* chore(ocm-cli): bump version to 0.2.7

* fix(ocm): harden worktree mirror synchronization

* fix(ocm): protect active branch during branchless pull
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-01 22:14:48 -04:00
1 parent 4ed3460759
commit 68d586f183
23 files changed
+2026 -158

No files matched your search

+22 -5
View File
@@ -48,8 +48,8 @@ ocm
ocm status
ocm list
ocm use <repoId|name>
ocm push [--force] [--create] [--yes] [--full]
ocm pull [--force] [--full]
ocm push [repoId] [--force] [--create] [--yes] [--full]
ocm pull [repoId] [--force] [--full]
ocm logout
```
@@ -77,6 +77,14 @@ tarball mirror. If the fast path fails, `ocm` prompts before reverting to the
tarball mirror (and proceeds automatically when there is no TTY to prompt). It
refuses to overwrite uncommitted local changes unless `--force` is passed.
A base repo and one of its worktrees can both be registered as ready Manager
repos sharing the same OpenCode project id. When that happens, `ocm push` and
`ocm pull` accept an optional positional repo id to pick the target:
`ocm push [repoId]` / `ocm pull [repoId]`. The id must belong to one of the
repos matching the current project (the command fails clearly otherwise), and
any ambiguity message lists each match with its id, kind (repo or worktree),
branch, and path. The default attach reports the same details.
## OpenCode TUI plugin
The package exposes an OpenCode TUI plugin through its `./tui` package export.
@@ -84,9 +92,18 @@ Configure the package name and OpenCode resolves that TUI entrypoint
automatically. When attached to a Manager via `ocm`, the plugin shows a
`REMOTE <host> · <repo>` indicator at the bottom of the TUI; local launches
show nothing. It registers `/ocm-move`, which keeps the local session and
copies the active session to the Manager after pushing the current repo state.
When multiple Manager repos match, a picker dialog lets you choose the
destination. A confirmation dialog gates the move before any push. On success
copies the active session to the Manager after replacing the Manager repo's
working tree with your local one (commits, staged, unstaged, and untracked
files; gitignored files on the Manager are preserved). The Manager's current
checkout is never switched: if it is on your branch the repo is replaced in
place; otherwise your branch goes into a sibling worktree (`<repo>-<branch>`,
registered as its own Manager repo), created on demand if it does not exist
yet. When multiple Manager repos match, the one already on your branch is
chosen; otherwise a picker dialog lets you choose. A confirmation dialog gates
the move before any push, states where the state will land, and lists any
server-side work (uncommitted changes or commits not present locally) that will
be discarded there. While the move runs, a spinner with the current phase and a
progress bar is shown next to the prompt. On success
you can optionally warp — exit the local TUI and attach to the moved session
on the Manager immediately. Use it from inside an OpenCode session after
`ocm login` and after the repo already exists on the Manager
+28 -19
View File
@@ -3,12 +3,12 @@ import { basename } from 'path'
import { readState, writeState, clearState, getStatePath, type OcmState } from '../src/state.js'
import { getToken, setToken, deleteToken, hasStoredToken, describeTokenStore, describeTokenWriteTarget, envToken, TOKEN_ENV, TokenStoreError } from '../src/internal-token-store.js'
import { ManagerApi, ManagerApiError } from '../src/manager-api.js'
import { mirrorUp, mirrorDown, mirrorUpFast, mirrorDownFast, prepareMirror, MirrorAbort, checkPushDivergence, checkPullDivergence } from '../src/mirror.js'
import { mirrorUp, mirrorDown, mirrorUpFast, mirrorDownFast, prepareMirror, MirrorAbort, checkPushDivergence, checkPullDivergence, describePushDivergence } from '../src/mirror.js'
import type { RemoteRepoSummary, MirrorProgress, PushDivergence, PullDivergence } from '../src/mirror.js'
import { createProgressReporter } from '../src/progress.js'
import { getBranchName, getOriginUrl } from '../src/local-repo.js'
import { resolveOpenCodeProjectId } from '@opencode-manager/shared/project-id'
import { resolveTarget } from '../src/resolve-target.js'
import { resolveTarget, formatRepoIdentities, parseRepoIdPositional, restrictMatchesToRequestedRepo } from '../src/resolve-target.js'
import { buildRemoteAttachEnv } from '../src/remote-context.js'
import { type ManagerRepo, fetchRepos, toRemoteRepoSummaries } from '../src/manager-repos.js'
import packageJson from '../package.json' with { type: 'json' }
@@ -26,8 +26,10 @@ Usage:
ocm status Show current manager URL, repo, and whether token is set
ocm list List ready repos from the manager
ocm use <repoId|name> Attach to a specific repo and remember it as last
ocm push [--force] [--create] [--yes] [--full] Mirror $PWD to the matching Manager repo (fast patch sync by default)
ocm pull [--force] [--full] Mirror the matching Manager repo over $PWD (fast patch sync by default)
ocm push [repoId] [--force] [--create] [--yes] [--full]
Mirror $PWD to the matching Manager repo (fast patch sync by default)
ocm pull [repoId] [--force] [--full]
Mirror the matching Manager repo over $PWD (fast patch sync by default)
ocm --version Show the installed ocm version
ocm --help Show this help
`
@@ -72,17 +74,9 @@ function confirmOverwrite(headline: string, reasons: string[], question: string,
}
function guardDivergentPush(repoName: string, div: PushDivergence): boolean {
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')
}
if (div.serverDirty) reasons.push('the server has uncommitted changes')
return confirmOverwrite(
`pushing to ${repoName} will discard server-side work:`,
reasons,
describePushDivergence(div),
'Overwrite server-side work and push anyway?',
'This work is likely from OpenCode agent sessions on the manager.',
)
@@ -355,8 +349,7 @@ async function cmdDefault(): Promise<void> {
return
}
case 'cwd-ambiguous': {
const names = result.matches.map((r) => `${r.name} (id=${r.repoId})`).join(', ')
die(`multiple Manager repos match project ${result.localProjectId}: ${names}; disambiguate with \`ocm use <repoId>\``)
die(`multiple Manager repos match project ${result.localProjectId}: ${formatRepoIdentities(result.matches)}; disambiguate with \`ocm use <repoId>\``)
break
}
case 'local':
@@ -387,7 +380,17 @@ function toManagerRepo(repo: { repoId: number; name: string; branch: string | nu
}
}
const PUSH_FLAGS = ['--force', '--create', '--yes', '--full'] as const
const PULL_FLAGS = ['--force', '--full'] as const
function dieAmbiguousProjectMatch(command: 'push' | 'pull', localProjectId: string, repos: readonly ManagerRepo[], matches: readonly RemoteRepoSummary[]): never {
const matchedIds = new Set(matches.map((m) => m.repoId))
die(`multiple Manager repos match project ${localProjectId}: ${formatRepoIdentities(repos.filter((r) => matchedIds.has(r.repoId)))}; disambiguate with \`ocm ${command} <repoId>\``)
}
export async function cmdPush(args: string[]): Promise<void> {
const parsed = parseRepoIdPositional(args, PUSH_FLAGS)
if (parsed.error) die(parsed.error)
let force = false
let create = false
let yes = false
@@ -408,6 +411,9 @@ export async function cmdPush(args: string[]): Promise<void> {
const remotes: RemoteRepoSummary[] = toRemoteRepoSummaries(repos)
const plan = await prepareMirror(process.cwd(), remotes)
const restriction = restrictMatchesToRequestedRepo(plan.matched, parsed.repoId, plan.localProjectId)
if (restriction.error) die(restriction.error)
plan.matched = restriction.matches
if (plan.matched.length === 0) {
if (!create) {
@@ -464,12 +470,13 @@ export async function cmdPush(args: string[]): Promise<void> {
progress.done()
info(`pushed ${plan.repoRoot} -> ${plan.matched[0]!.name} (repoId=${result.repoId}, branch=${result.branch})`)
} else {
const names = plan.matched.map((r) => `${r.name} (id=${r.repoId})`).join(', ')
die(`multiple Manager repos match project ${plan.localProjectId}: ${names}; disambiguate with \`ocm push <repoId>\``)
dieAmbiguousProjectMatch('push', plan.localProjectId, repos, plan.matched)
}
}
async function cmdPull(args: string[]): Promise<void> {
const parsed = parseRepoIdPositional(args, PULL_FLAGS)
if (parsed.error) die(parsed.error)
let force = false
let full = false
@@ -486,14 +493,16 @@ async function cmdPull(args: string[]): Promise<void> {
const remotes: RemoteRepoSummary[] = toRemoteRepoSummaries(repos)
const plan = await prepareMirror(process.cwd(), remotes)
const restriction = restrictMatchesToRequestedRepo(plan.matched, parsed.repoId, plan.localProjectId)
if (restriction.error) die(restriction.error)
plan.matched = restriction.matches
if (plan.matched.length === 0) {
die(`no matching Manager repo for project ${plan.localProjectId}.`)
}
if (plan.matched.length > 1) {
const names = plan.matched.map((r) => `${r.name} (id=${r.repoId})`).join(', ')
die(`multiple Manager repos match project ${plan.localProjectId}: ${names}; disambiguate with \`ocm pull <repoId>\``)
dieAmbiguousProjectMatch('pull', plan.localProjectId, repos, plan.matched)
}
if (!force) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/ocm-cli",
"version": "0.2.6",
"version": "0.2.7",
"description": "OpenCode Manager CLI: attach a local OpenCode TUI to a Manager-hosted repo.",
"license": "MIT",
"repository": {
+28 -1
View File
@@ -1,5 +1,11 @@
import { createReadStream } from 'fs'
import { Readable } from 'stream'
import {
MirrorTargetEnsureResponseSchema,
MirrorTargetPlanResponseSchema,
type MirrorTargetEnsureResponse,
type MirrorTargetPlanResponse,
} from '@opencode-manager/shared/schemas'
export interface MirrorBeginOpts {
force?: boolean
@@ -175,11 +181,12 @@ export class ManagerApi {
async mirrorUploadBundle(
repoId: number,
bundlePath: string,
opts: { branch: string | null; force?: boolean; onProgress?: (bytesSent: number) => void },
opts: { branch: string | null; force?: boolean; requireCurrentBranch?: boolean; onProgress?: (bytesSent: number) => void },
): Promise<MirrorBundleResult> {
const query = opts.force === true ? '?force=1' : ''
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'
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}`, {
@@ -202,6 +209,26 @@ export class ManagerApi {
return (await res.json()) as MirrorHead
}
async mirrorTargetPlan(repoId: number, branch: string): Promise<MirrorTargetPlanResponse> {
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())
}
async mirrorEnsureTarget(repoId: number, branch: string): Promise<MirrorTargetEnsureResponse> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/target`, {
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())
}
async mirrorContains(repoId: number, sha: string): Promise<{ contained: boolean }> {
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/contains/${sha}`, {
headers: this.headers(),
+1
View File
@@ -7,6 +7,7 @@ export interface ManagerRepo {
cloneStatus: string
directory: string
projectId?: string | null
isWorktree?: boolean
extra: { repoId: number; localPath: string; fullPath: string }
}
+112 -27
View File
@@ -69,6 +69,12 @@ export async function prepareMirror(cwd: string, remotes: RemoteRepoSummary[]):
return { repoRoot, localProjectId, matched }
}
export function pickMatchedRepo(matched: RemoteRepoSummary[], localBranch: string | null): RemoteRepoSummary | null {
const onBranch = matched.filter((r) => localBranch !== null && r.branch === localBranch)
if (onBranch.length === 1) return onBranch[0]!
return matched.length === 1 ? matched[0]! : null
}
export interface PushDivergence {
serverHead: string | null
serverBranch: string | null
@@ -95,6 +101,17 @@ export async function checkPushDivergence(repoRoot: string, api: ManagerApi, rep
return { serverHead, serverBranch, serverDirty, diverged: true, lostCommits }
}
export function describePushDivergence(div: PushDivergence): 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')
}
if (div.serverDirty) reasons.push('the server has uncommitted changes')
return reasons
}
export interface PullDivergence {
diverged: boolean
lostCommits: number
@@ -393,30 +410,38 @@ async function createLocalBundle(repoRoot: string): Promise<string> {
return bundlePath
}
function importLocalBundle(repoRoot: string, bundlePath: string, branch: string | null): void {
runGit(repoRoot, ['fetch', bundlePath, '+refs/heads/*:refs/remotes/ocm-sync/*', '+refs/tags/*:refs/tags/*'])
const refs = runGit(repoRoot, ['for-each-ref', '--format=%(refname:strip=3) %(objectname)', 'refs/remotes/ocm-sync'])
const updates: string[] = []
for (const line of refs.split('\n')) {
const trimmed = line.trim()
if (!trimmed) continue
const firstSpace = trimmed.indexOf(' ')
if (firstSpace === -1) continue
const name = trimmed.slice(0, firstSpace)
if (name === 'HEAD') continue
const sha = trimmed.slice(firstSpace + 1)
updates.push(`update refs/heads/${name} ${sha}\n`)
}
if (updates.length > 0) {
runGit(repoRoot, ['update-ref', '--stdin'], updates.join(''))
function listWorktreeBranches(repoRoot: string): Map<string, string[]> {
const out = runGit(repoRoot, ['worktree', 'list', '--porcelain'])
const ownership = new Map<string, string[]>()
let currentPath: string | null = null
for (const line of out.split('\n')) {
if (line.startsWith('worktree ')) {
currentPath = line.slice('worktree '.length).trim()
} else if (line.startsWith('branch ')) {
if (!currentPath) continue
const branch = line.slice('branch '.length).trim().replace(/^refs\/heads\//, '')
const paths = ownership.get(branch) ?? []
paths.push(currentPath)
ownership.set(branch, paths)
}
}
return ownership
}
if (branch) {
runGit(repoRoot, ['checkout', branch])
const head = runGit(repoRoot, ['rev-parse', `refs/remotes/ocm-sync/${branch}`]).trim()
if (head) runGit(repoRoot, ['reset', '--hard', head])
}
function listLocalBranches(repoRoot: string): Set<string> {
const out = runGit(repoRoot, ['for-each-ref', '--format=%(refname:short)', 'refs/heads'])
return new Set(out.split('\n').map((l) => l.trim()).filter(Boolean))
}
function branchOwnedElsewhere(ownership: Map<string, string[]>, repoRoot: string): Set<string> {
const locked = new Set<string>()
for (const [branch, paths] of ownership) {
if (paths.some((path) => path !== repoRoot)) locked.add(branch)
}
return locked
}
function deleteSyncRefs(repoRoot: string): void {
try {
const syncRefsOut = runGit(repoRoot, ['for-each-ref', '--format=%(refname)', 'refs/remotes/ocm-sync'])
const deletes = syncRefsOut.split('\n').map((l) => l.trim()).filter(Boolean).map((ref) => `delete ${ref}\n`)
@@ -424,7 +449,62 @@ function importLocalBundle(repoRoot: string, bundlePath: string, branch: string
runGit(repoRoot, ['update-ref', '--stdin'], deletes.join(''))
}
} catch {
// cleanup of ocm-sync refs is best-effort
return
}
}
function importLocalBundle(repoRoot: string, bundlePath: string, branch: string | null, force: boolean): 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'])
const incoming = new Map<string, string>()
for (const line of refs.split('\n')) {
const trimmed = line.trim()
if (!trimmed) continue
const firstSpace = trimmed.indexOf(' ')
if (firstSpace === -1) continue
const name = trimmed.slice(0, firstSpace)
if (name === 'HEAD') continue
incoming.set(name, trimmed.slice(firstSpace + 1))
}
const lockedElsewhere = branchOwnedElsewhere(listWorktreeBranches(repoRoot), repoRoot)
const currentBranch = getBranchName(repoRoot)
if (branch) {
const incomingSha = incoming.get(branch)
if (!incomingSha) throw new MirrorAbort(`no incoming branch '${branch}' in the server bundle`)
if (lockedElsewhere.has(branch)) {
throw new MirrorAbort(`branch '${branch}' is checked out in another worktree; release it there before pulling`)
}
if (currentBranch !== branch) {
const checkoutArgs = force ? ['-f'] : []
if (listLocalBranches(repoRoot).has(branch)) {
runGit(repoRoot, ['checkout', ...checkoutArgs, branch])
} else {
runGit(repoRoot, ['checkout', ...checkoutArgs, '-b', branch, incomingSha])
}
}
}
const updates: string[] = []
for (const [name, sha] of incoming) {
if (branch === name) continue
if (lockedElsewhere.has(name)) continue
if (branch === null && name === currentBranch) continue
updates.push(`update refs/heads/${name} ${sha}\n`)
}
if (updates.length > 0) {
runGit(repoRoot, ['update-ref', '--stdin'], updates.join(''))
}
if (branch) {
const targetSha = incoming.get(branch)!
runGit(repoRoot, ['reset', '--hard', targetSha])
runGit(repoRoot, ['clean', '-fd'])
}
} finally {
deleteSyncRefs(repoRoot)
}
}
@@ -444,10 +524,15 @@ export type MirrorUpFastPhase =
| { kind: 'processing' }
| { kind: 'patching' }
type MirrorUpFastOpts = Pick<MirrorUpOpts, 'api' | 'force'> & {
requireCurrentBranch?: boolean
onPhase?: (phase: MirrorUpFastPhase) => void
}
export async function mirrorUpFast(
plan: MirrorPlan,
opts: Pick<MirrorUpOpts, 'api' | 'force'> & { onPhase?: (phase: MirrorUpFastPhase) => void },
): Promise<{ repoId: number; branch: string | null; head: string | null; created: false }> {
opts: MirrorUpFastOpts,
): Promise<{ repoId: number; fullPath: string; branch: string | null; head: string | null; created: false }> {
const repoId = plan.matched[0]!.repoId
const onPhase = opts.onPhase
onPhase?.({ kind: 'bundling' })
@@ -458,6 +543,7 @@ export async function mirrorUpFast(
await opts.api.mirrorUploadBundle(repoId, bundlePath, {
branch: getBranchName(plan.repoRoot),
force: opts.force,
requireCurrentBranch: opts.requireCurrentBranch,
onProgress: onPhase
? (bytesSent) => {
onPhase({ kind: 'uploading', bytesSent, totalBytes: size })
@@ -467,7 +553,7 @@ export async function mirrorUpFast(
})
onPhase?.({ kind: 'patching' })
const patchResult = await mirrorUpPatch(plan, opts)
return { repoId: patchResult.repoId, branch: patchResult.branch, head: patchResult.head, created: false }
return { repoId: patchResult.repoId, fullPath: patchResult.fullPath, branch: patchResult.branch, head: patchResult.head, created: false }
} finally {
await fsp.rm(bundlePath, { force: true }).catch(() => {})
}
@@ -486,11 +572,10 @@ export async function mirrorDownFast(
const snapshot = await api.mirrorPatchSnapshot(repoId)
const bundlePath = await writeBundleStream(repoId, api)
try {
importLocalBundle(repoRoot, bundlePath, snapshot.branch)
importLocalBundle(repoRoot, bundlePath, snapshot.branch, opts.force)
applyPatch(repoRoot, snapshot.patch)
} finally {
await fsp.rm(bundlePath, { force: true }).catch(() => {})
}
}
+41
View File
@@ -0,0 +1,41 @@
import type { MirrorUpFastPhase } from './mirror.js'
import { formatBytes, SPINNER_FRAMES } from './progress.js'
export interface MoveProgress {
label: string
fraction: number | null
}
const BAR_WIDTH = 12
export function renderProgressBar(fraction: number, width = BAR_WIDTH): string {
const clamped = Math.min(1, Math.max(0, fraction))
const filled = Math.round(clamped * width)
return `${'█'.repeat(filled)}${'░'.repeat(width - filled)} ${Math.round(clamped * 100)}%`
}
export function formatMoveProgress(progress: MoveProgress, frame: number): string {
const spinner = SPINNER_FRAMES[frame % SPINNER_FRAMES.length]
const bar = progress.fraction === null ? '' : ` ${renderProgressBar(progress.fraction)}`
return `${spinner} ocm-move: ${progress.label}${bar}`
}
export function pushPhaseProgress(phase: MirrorUpFastPhase): MoveProgress {
switch (phase.kind) {
case 'bundling':
return { label: 'creating git bundle', fraction: null }
case 'uploading':
return {
label: `uploading ${formatBytes(phase.bytesSent)} / ${formatBytes(phase.totalBytes)}`,
fraction: phase.totalBytes > 0 ? phase.bytesSent / phase.totalBytes : null,
}
case 'processing':
return { label: 'server importing bundle', fraction: null }
case 'patching':
return { label: 'applying local changes', fraction: null }
}
}
export function replayProgress(replayed: number, total: number): MoveProgress {
return { label: `replaying session ${replayed}/${total} events`, fraction: total > 0 ? replayed / total : null }
}
+3 -3
View File
@@ -1,4 +1,4 @@
const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
export const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
export function formatBytes(bytes: number): string {
if (bytes < 1024) {
@@ -42,8 +42,8 @@ export function createProgressReporter(
if (isTTY) {
if (t - lastRenderAt < 80) return
lastRenderAt = t
out.write(`\r\x1b[K${label}: ${FRAMES[frameIndex]} ${formatBytes(bytes)}`)
frameIndex = (frameIndex + 1) % FRAMES.length
out.write(`\r\x1b[K${label}: ${SPINNER_FRAMES[frameIndex]} ${formatBytes(bytes)}`)
frameIndex = (frameIndex + 1) % SPINNER_FRAMES.length
} else {
if (t - lastNonTtyTickAt < 1000) return
lastNonTtyTickAt = t
+64
View File
@@ -1,4 +1,5 @@
import { getRepoRoot } from './local-repo.js'
import type { RemoteRepoSummary } from './mirror.js'
export interface TargetRepo {
repoId: number
@@ -6,6 +7,69 @@ export interface TargetRepo {
branch: string | null
directory: string
projectId?: string | null
isWorktree?: boolean
}
export interface RepoIdentity {
repoId: number
name: string
branch: string | null
isWorktree?: boolean
directory?: string
}
export function formatRepoIdentity(repo: RepoIdentity): string {
const parts = [`id=${repo.repoId}`, repo.isWorktree ? 'worktree' : 'repo', `branch=${repo.branch ?? 'n/a'}`]
if (repo.directory) parts.push(`path=${repo.directory}`)
return `${repo.name} (${parts.join(', ')})`
}
export function formatRepoIdentities(repos: readonly RepoIdentity[]): string {
return repos.map(formatRepoIdentity).join(', ')
}
export interface RepoIdParseResult {
repoId: number | null
error?: string
}
export function parseRepoIdPositional(args: readonly string[], knownFlags: readonly string[]): RepoIdParseResult {
let repoId: number | null = null
for (const arg of args) {
if (knownFlags.includes(arg)) continue
if (arg.startsWith('-')) {
return { repoId: null, error: `unknown option: ${arg}` }
}
const id = Number(arg)
if (!/^\d+$/.test(arg) || !Number.isSafeInteger(id) || id <= 0) {
return { repoId: null, error: `invalid repo id: ${arg}; expected a positive integer` }
}
if (repoId !== null) {
return { repoId: null, error: `multiple repo ids given: ${repoId} and ${arg}` }
}
repoId = id
}
return { repoId }
}
export interface MatchRestriction {
matches: RemoteRepoSummary[]
error?: string
}
export function restrictMatchesToRequestedRepo(matches: readonly RemoteRepoSummary[], requestedRepoId: number | null, localProjectId: string): MatchRestriction {
if (requestedRepoId === null) return { matches: [...matches] }
const selected = matches.filter((m) => m.repoId === requestedRepoId)
if (selected.length === 0) {
const available = formatRepoIdentities(matches)
return {
matches: [],
error: available
? `repo ${requestedRepoId} does not match project ${localProjectId}; matching repos: ${available}`
: `repo ${requestedRepoId} does not match project ${localProjectId}; no Manager repo matches this project`,
}
}
return { matches: selected }
}
export type ResolveResult =
+34 -14
View File
@@ -53,6 +53,10 @@ export function rewriteEventsForRemote(events: ReplayEvent[], ctx: RewriteContex
stripWorkspaceID(data, 'location')
}
if (isMessageUpdated(event.type)) {
rewriteMessagePath(data, ctx)
}
coerceTimestamp(data)
return { ...event, data }
@@ -67,28 +71,44 @@ function isMovedEvent(type: string): boolean {
return type.startsWith('session.next.moved')
}
function isMessageUpdated(type: string): boolean {
return type.startsWith('message.updated')
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' ? (value as Record<string, unknown>) : null
}
function relocatePath(path: string, ctx: RewriteContext): string {
if (path === ctx.localRoot) return ctx.remoteRoot
if (path.startsWith(ctx.localRoot + '/')) return ctx.remoteRoot + path.slice(ctx.localRoot.length)
return path
}
function relocateField(obj: Record<string, unknown>, key: string, ctx: RewriteContext): void {
const value = obj[key]
if (typeof value === 'string') obj[key] = relocatePath(value, ctx)
}
function rewriteDirectory(
data: Record<string, unknown>,
key: 'info' | 'location',
ctx: RewriteContext,
): void {
const container = data[key]
if (!container || typeof container !== 'object') return
const obj = container as Record<string, unknown>
const dir = obj.directory
if (typeof dir !== 'string') return
if (dir === ctx.localRoot) {
obj.directory = ctx.remoteRoot
} else if (dir.startsWith(ctx.localRoot + '/')) {
obj.directory = ctx.remoteRoot + dir.slice(ctx.localRoot.length)
}
const container = asRecord(data[key])
if (container) relocateField(container, 'directory', ctx)
}
function rewriteMessagePath(data: Record<string, unknown>, ctx: RewriteContext): void {
const path = asRecord(asRecord(data.info)?.path)
if (!path) return
relocateField(path, 'cwd', ctx)
relocateField(path, 'root', ctx)
}
function stripWorkspaceID(data: Record<string, unknown>, key: 'info' | 'location'): void {
const container = data[key]
if (!container || typeof container !== 'object') return
const obj = container as Record<string, unknown>
delete obj.workspaceID
const container = asRecord(data[key])
if (container) delete container.workspaceID
}
/** Per commit 686c820d: coerce `data.timestamp` from ISO string to epoch ms. */
+69 -53
View File
@@ -4,16 +4,21 @@ import { getToken } from './internal-token-store.js'
import { TokenStoreError } from './token-store.js'
import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js'
import { ManagerApi, ManagerApiError } from './manager-api.js'
import { prepareMirror, checkPushDivergence, mirrorUpFast } from './mirror.js'
import type { MirrorPlan, MirrorUpFastPhase } from './mirror.js'
import { formatBytes } from './progress.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 { getBranchName } from './local-repo.js'
import { transferSession, moveReminderText } from './session-move.js'
import { createManagerReplay, createManagerPromptAsync } from './remote-replay.js'
import { readSessionEvents } from './local-history.js'
import { confirmDialog, selectDialog } from './tui-dialogs.js'
import { setPendingWarp, runPendingWarp } from './warp.js'
import { pushPhaseProgress, replayProgress } from './move-progress.js'
import type { MoveProgress } from './move-progress.js'
export async function setupOcm(api: TuiPluginApi): Promise<void> {
export type MoveProgressSetter = (progress: MoveProgress | null) => void
export async function setupOcm(api: TuiPluginApi, setMoveProgress: MoveProgressSetter): Promise<void> {
showInstallNotice(api)
api.keymap.registerLayer({
commands: [
@@ -24,7 +29,7 @@ export async function setupOcm(api: TuiPluginApi): Promise<void> {
category: 'OpenCode Manager',
namespace: 'palette',
slashName: 'ocm-move',
run: () => runSessionMove(api),
run: () => runSessionMove(api, setMoveProgress),
},
],
})
@@ -45,32 +50,40 @@ function showInstallNotice(api: TuiPluginApi): void {
})
}
function pushPhaseMessage(phase: MirrorUpFastPhase): string {
switch (phase.kind) {
case 'bundling':
return 'Pushing repo state: creating git bundle…'
case 'uploading':
return `Pushing repo state: uploading ${formatBytes(phase.bytesSent)} / ${formatBytes(phase.totalBytes)}…`
case 'processing':
return 'Pushing repo state: waiting for server to import bundle…'
case 'patching':
return 'Pushing repo state: applying local changes…'
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 createPushPhaseToaster(api: TuiPluginApi): (phase: MirrorUpFastPhase) => void {
let lastUploadToastAt = 0
return (phase) => {
if (phase.kind === 'uploading') {
const now = Date.now()
if (now - lastUploadToastAt < 1000) return
lastUploadToastAt = now
}
api.ui.toast({ message: pushPhaseMessage(phase) })
function describeMoveTarget(repoName: string, target: MirrorTargetPlanResponse): string {
switch (target.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?`
}
}
async function runSessionMove(api: TuiPluginApi): Promise<void> {
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(api: TuiPluginApi, setMoveProgress: MoveProgressSetter): Promise<void> {
try {
const current = api.route.current
if (current.name !== 'session' || !current.params) {
@@ -112,50 +125,51 @@ async function runSessionMove(api: TuiPluginApi): Promise<void> {
return
}
let matched = plan.matched[0]!
if (plan.matched.length > 1) {
const chosen = await selectDialog(api, 'Move session to Manager repo', plan.matched.map((r) => ({ title: r.name, description: `id=${r.repoId}`, value: r })))
if (!chosen) return
matched = chosen
}
const repoId = matched.repoId
const remoteRepo = repos.find((r) => r.repoId === repoId)
const remoteDirectory = remoteRepo!.directory
const proceed = await confirmDialog(api, { title: 'Move session to Manager', message: `Push repo state and move this session to ${matched.name} (${remoteDirectory})?` })
if (!proceed) return
const localBranch = getBranchName(plan.repoRoot)
const matched = pickMatchedRepo(plan.matched, localBranch)
?? await selectDialog(api, '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)!
const managerApi = new ManagerApi(state.managerUrl, token)
const target = await resolveMoveTarget(managerApi, matched, remoteRepo.directory, localBranch)
const discardReasons = target.repoId === null ? [] : await describeRemoteDiscard(plan.repoRoot, managerApi, target.repoId)
try {
const divergence = await checkPushDivergence(plan.repoRoot, managerApi, repoId)
if (divergence.diverged || divergence.serverDirty) {
api.ui.toast({ variant: 'error', title: 'Remote has diverged', message: 'Remote has diverged; resolve with `ocm push --force` first' })
return
}
} catch (error) {
if (!(error instanceof ManagerApiError && error.status === 404)) throw error
}
const selectedPlan: MirrorPlan = { ...plan, matched: [matched] }
await mirrorUpFast(selectedPlan, {
api: managerApi,
force: false,
onPhase: createPushPhaseToaster(api),
const proceed = await confirmDialog(api, {
title: 'Move session to Manager',
message: moveConfirmMessage(matched.name, target, discardReasons),
})
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
}
const selectedPlan: MirrorPlan = { ...plan, matched: [{ ...matched, repoId: targetRepoId }] }
const pushed = await mirrorUpFast(selectedPlan, {
api: managerApi,
force: true,
requireCurrentBranch: true,
onPhase: (phase) => setMoveProgress(pushPhaseProgress(phase)),
})
const remoteDirectory = pushed.fullPath
const result = await transferSession(
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
{
fetchLocalHistory: () => readSessionEvents(sessionID),
replayEvents: createManagerReplay(state.managerUrl, token),
onProgress: (replayed, total) => api.ui.toast({ message: `Moving session… ${replayed}/${total} events`, duration: 2000 }),
onProgress: (replayed, total) => setMoveProgress(replayProgress(replayed, total)),
},
)
switch (result.kind) {
case 'moved': {
setMoveProgress({ label: 'notifying moved session', fraction: null })
await createManagerPromptAsync(state.managerUrl, token)(remoteDirectory, result.sessionID, moveReminderText(remoteDirectory)).catch(() => undefined)
setMoveProgress(null)
const warp = await confirmDialog(api, { title: 'Attach to moved session?', message: 'Exit this TUI and attach to the moved session on the Manager now?' })
if (warp) {
await fetch(`${state.managerUrl}/api/opencode-proxy/session?directory=${encodeURIComponent(remoteDirectory)}`, { headers: { authorization: `Bearer ${token}` } }).catch(() => undefined)
@@ -178,6 +192,8 @@ async function runSessionMove(api: TuiPluginApi): Promise<void> {
}
} catch (err) {
api.ui.toast({ variant: 'error', message: err instanceof Error ? err.message : String(err) })
} finally {
setMoveProgress(null)
}
}
+30 -2
View File
@@ -1,9 +1,37 @@
/** @jsxImportSource @opentui/solid */
import { createSignal, createEffect, onCleanup, Show } from 'solid-js'
import { setupOcm, readRemoteContext } from './tui-plugin.js'
import { formatMoveProgress } from './move-progress.js'
import type { MoveProgress } from './move-progress.js'
import type { TuiPluginApi, TuiPluginModule, TuiSlotContext } from './tui-types.js'
const SPINNER_INTERVAL_MS = 80
const tui = async (api: TuiPluginApi): Promise<void> => {
await setupOcm(api)
const [moveProgress, setMoveProgress] = createSignal<MoveProgress | null>(null)
await setupOcm(api, setMoveProgress)
const moveIndicator = (ctx: TuiSlotContext) => {
const theme = ctx.theme.current
const [frame, setFrame] = createSignal(0)
createEffect(() => {
if (!moveProgress()) return
const timer = setInterval(() => setFrame((f) => f + 1), SPINNER_INTERVAL_MS)
onCleanup(() => clearInterval(timer))
})
return (
<box flexDirection="row" flexShrink={0}>
<Show when={moveProgress()}>
{(progress) => <text fg={theme.accent}>{formatMoveProgress(progress(), frame())}</text>}
</Show>
</box>
)
}
api.slots.register({
order: 290,
slots: { session_prompt_right: moveIndicator },
})
const remote = readRemoteContext(process.env)
if (!remote) return
@@ -29,4 +57,4 @@ const tui = async (api: TuiPluginApi): Promise<void> => {
})
}
export default { id: 'ocm', tui } satisfies TuiPluginModule
export default { id: 'ocm', tui } satisfies TuiPluginModule
+393 -1
View File
@@ -4,8 +4,9 @@ import { join } from 'path'
import { tmpdir } from 'os'
import { randomBytes } from 'crypto'
import { spawnSync, execSync } from 'child_process'
import { prepareMirror, MirrorAbort, mirrorDown, mirrorUp, mirrorUpPatch, mirrorUpFast, checkPushDivergence, checkPullDivergence, type MirrorUpFastPhase } from '../src/mirror'
import { prepareMirror, MirrorAbort, mirrorDown, mirrorDownFast, mirrorUp, mirrorUpPatch, mirrorUpFast, checkPushDivergence, checkPullDivergence, describePushDivergence, pickMatchedRepo, type MirrorUpFastPhase } from '../src/mirror'
import { getBranchName } from '../src/local-repo'
import { ManagerApi } from '../src/manager-api'
import { gitRemoteProjectId } from '@opencode-manager/shared/project-id'
import { mockStateModule, mockTokenStoreModule } from './helpers/token-store-mocks.js'
@@ -644,6 +645,46 @@ describe('checkPushDivergence', () => {
})
})
describe('pickMatchedRepo', () => {
const main = { repoId: 1, name: 'app', projectId: 'p', branch: 'main' }
const feature = { repoId: 2, name: 'app-feature', projectId: 'p', branch: 'feature' }
it('returns the single match regardless of branch', () => {
expect(pickMatchedRepo([main], 'feature')).toBe(main)
expect(pickMatchedRepo([main], null)).toBe(main)
})
it('prefers the repo already on the local branch when several match', () => {
expect(pickMatchedRepo([main, feature], 'feature')).toBe(feature)
})
it('returns null when several match and none is on the local branch', () => {
expect(pickMatchedRepo([main, feature], 'other')).toBeNull()
expect(pickMatchedRepo([main, feature], null)).toBeNull()
})
})
describe('describePushDivergence', () => {
const base = { serverHead: 'abc', serverBranch: 'main', lostCommits: 0 }
it('returns no reasons when the push is a clean fast-forward', () => {
expect(describePushDivergence({ ...base, serverDirty: false, diverged: false })).toEqual([])
})
it('describes a counted divergence and dirty server together', () => {
expect(describePushDivergence({ ...base, serverDirty: true, diverged: true, lostCommits: 2 })).toEqual([
'the server is 2 commit(s) ahead of your local branch',
'the server has uncommitted changes',
])
})
it('describes divergence with an unknown commit count', () => {
expect(describePushDivergence({ ...base, serverDirty: false, diverged: true, lostCommits: -1 })).toEqual([
'the server has commit(s) not present in your local branch',
])
})
})
describe('checkPullDivergence', () => {
let tmpDir: string
@@ -808,6 +849,58 @@ describe('mirrorUpFast targets the selected repo', () => {
expect(result.repoId).toBe(99)
})
it('forwards the strict current-branch option to the bundle upload', async () => {
const repoRoot = join(tmpDir, 'repo-strict-forward')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'tracked.txt'), 'content\n')
spawnSync('git', ['add', 'tracked.txt'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['commit', '-m', 'initial'], { cwd: repoRoot, stdio: 'ignore' })
const api = {
mirrorUploadBundle: vi.fn().mockResolvedValue(undefined),
mirrorPatch: vi.fn().mockResolvedValue({ repoId: 1, fullPath: '/tmp/x', branch: 'main', head: 'abc', created: false, applied: true }),
}
const plan = {
repoRoot,
localProjectId: 'proj',
matched: [{ repoId: 1, name: 'repo-A', projectId: 'proj', branch: 'main' }],
}
await mirrorUpFast(plan, { api: api as any, force: false, requireCurrentBranch: true })
expect(api.mirrorUploadBundle.mock.calls[0]![2].requireCurrentBranch).toBe(true)
})
it('omits the strict current-branch option by default', async () => {
const repoRoot = join(tmpDir, 'repo-strict-default')
mkdirSync(repoRoot)
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' })
writeFileSync(join(repoRoot, 'tracked.txt'), 'content\n')
spawnSync('git', ['add', 'tracked.txt'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['commit', '-m', 'initial'], { cwd: repoRoot, stdio: 'ignore' })
const api = {
mirrorUploadBundle: vi.fn().mockResolvedValue(undefined),
mirrorPatch: vi.fn().mockResolvedValue({ repoId: 1, fullPath: '/tmp/x', branch: 'main', head: 'abc', created: false, applied: true }),
}
const plan = {
repoRoot,
localProjectId: 'proj',
matched: [{ repoId: 1, name: 'repo-A', projectId: 'proj', branch: 'main' }],
}
await mirrorUpFast(plan, { api: api as any, force: false })
expect(api.mirrorUploadBundle.mock.calls[0]![2].requireCurrentBranch).toBeUndefined()
})
it('reports bundling, uploading, and patching phases in order', async () => {
const repoRoot = join(tmpDir, 'repo-phases')
mkdirSync(repoRoot)
@@ -915,3 +1008,302 @@ describe('mirrorUpFast targets the selected repo', () => {
})
})
describe('mirrorDownFast preflight', () => {
let tmpDir: string
beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'mirror-downfast-test-'))
})
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true })
})
function initRepo(name: string): string {
const repoRoot = join(tmpDir, name)
mkdirSync(repoRoot)
spawnSync('git', ['init', '-b', 'main'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' })
return repoRoot
}
function commitFile(repoRoot: string, file: string, content: string): string {
writeFileSync(join(repoRoot, file), content)
spawnSync('git', ['add', '.'], { cwd: repoRoot, stdio: 'ignore' })
spawnSync('git', ['commit', '-m', `update ${file}`], { cwd: repoRoot, stdio: 'ignore' })
return execSync('git rev-parse HEAD', { cwd: repoRoot, encoding: 'utf-8' }).trim()
}
function revRef(repoRoot: string, ref: string): string {
return execSync(`git rev-parse ${ref}`, { cwd: repoRoot, encoding: 'utf-8' }).trim()
}
function createBundle(repoRoot: string, name: string): Buffer {
const bundleFile = join(tmpDir, `${name}.bundle`)
execSync(`git bundle create "${bundleFile}" --all`, { cwd: repoRoot })
return readFileSync(bundleFile)
}
const streamOf = (buf: Buffer): ReadableStream<Uint8Array> =>
new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array(buf))
controller.close()
},
})
const fastApi = (branch: string | null, bundle: Buffer) => ({
mirrorPatchSnapshot: vi.fn().mockResolvedValue({ branch, patch: '' }),
mirrorDownloadBundle: vi.fn().mockResolvedValue(streamOf(bundle)),
})
const syncRefCount = (repoRoot: string): number =>
execSync('git for-each-ref refs/remotes/ocm-sync', { cwd: repoRoot, encoding: 'utf-8' }).trim().split('\n').filter(Boolean).length
it('updates the same branch target and leaves no ocm-sync refs behind', async () => {
const server = initRepo('server-same')
commitFile(server, 'tracked.txt', 'server-base\n')
execSync('git checkout -b feature', { cwd: server, stdio: 'ignore' })
commitFile(server, 'feature.txt', 'feature\n')
execSync('git checkout main', { cwd: server, stdio: 'ignore' })
commitFile(server, 'tracked.txt', 'server-head\n')
const serverMainSha = revRef(server, 'main')
const serverFeatureSha = revRef(server, 'feature')
const bundle = createBundle(server, 'server-same')
const local = initRepo('local-same')
commitFile(local, 'tracked.txt', 'local-head\n')
await mirrorDownFast(1, local, fastApi('main', bundle) as any, { force: false })
expect(getBranchName(local)).toBe('main')
expect(revRef(local, 'HEAD')).toBe(serverMainSha)
expect(readFileSync(join(local, 'tracked.txt'), 'utf-8')).toBe('server-head\n')
expect(revRef(local, 'feature')).toBe(serverFeatureSha)
expect(syncRefCount(local)).toBe(0)
})
it('switches branches when clean and selects the incoming target before resetting', async () => {
const server = initRepo('server-cross')
commitFile(server, 'main.txt', 'server-main\n')
execSync('git checkout -b topic', { cwd: server, stdio: 'ignore' })
const topicSha = commitFile(server, 'topic.txt', 'server-topic\n')
execSync('git checkout main', { cwd: server, stdio: 'ignore' })
commitFile(server, 'main.txt', 'server-main-2\n')
const serverMainSha = revRef(server, 'main')
const bundle = createBundle(server, 'server-cross')
const local = initRepo('local-cross')
commitFile(local, 'main.txt', 'local-main\n')
execSync('git branch topic', { cwd: local, stdio: 'ignore' })
await mirrorDownFast(1, local, fastApi('topic', bundle) as any, { force: false })
expect(getBranchName(local)).toBe('topic')
expect(revRef(local, 'HEAD')).toBe(topicSha)
expect(revRef(local, 'topic')).toBe(topicSha)
expect(revRef(local, 'main')).toBe(serverMainSha)
expect(readFileSync(join(local, 'topic.txt'), 'utf-8')).toBe('server-topic\n')
expect(syncRefCount(local)).toBe(0)
})
it('keeps the active branch untouched when the snapshot has no target branch', async () => {
const server = initRepo('server-null-target')
commitFile(server, 'a.txt', 'server-a\n')
execSync('git checkout -b feature', { cwd: server, stdio: 'ignore' })
const serverFeatureSha = commitFile(server, 'feature.txt', 'feature\n')
execSync('git checkout main', { cwd: server, stdio: 'ignore' })
commitFile(server, 'b.txt', 'server-b\n')
const bundle = createBundle(server, 'server-null-target')
const local = initRepo('local-null-target')
const localMainSha = commitFile(local, 'a.txt', 'local-a\n')
execSync('git checkout -b feature', { cwd: local, stdio: 'ignore' })
commitFile(local, 'local-feature.txt', 'local-feature\n')
execSync('git checkout main', { cwd: local, stdio: 'ignore' })
await mirrorDownFast(1, local, fastApi(null, bundle) as any, { force: false })
expect(getBranchName(local)).toBe('main')
expect(revRef(local, 'main')).toBe(localMainSha)
expect(revRef(local, 'HEAD')).toBe(localMainSha)
expect(readFileSync(join(local, 'a.txt'), 'utf-8')).toBe('local-a\n')
expect(execSync('git status --porcelain', { cwd: local, encoding: 'utf-8' })).toBe('')
expect(revRef(local, 'feature')).toBe(serverFeatureSha)
expect(syncRefCount(local)).toBe(0)
})
it('rejects a target checked out in another worktree and preserves the current worktree state', async () => {
const server = initRepo('server-wt')
commitFile(server, 'main.txt', 'server-main\n')
execSync('git checkout -b checked', { cwd: server, stdio: 'ignore' })
commitFile(server, 'checked.txt', 'server-checked\n')
execSync('git checkout main', { cwd: server, stdio: 'ignore' })
const bundle = createBundle(server, 'server-wt')
const local = initRepo('local-wt')
commitFile(local, 'main.txt', 'local-base\n')
execSync(`git worktree add "${join(tmpDir, 'checked-wt')}" -b checked`, { cwd: local, stdio: 'ignore' })
const localMainSha = revRef(local, 'main')
const localCheckedSha = revRef(local, 'checked')
writeFileSync(join(local, 'untracked.txt'), 'keep-me\n')
const thrown = await mirrorDownFast(1, local, fastApi('checked', bundle) as any, { force: true }).then(
() => null,
(err: unknown) => err,
)
expect(thrown).toBeInstanceOf(MirrorAbort)
expect((thrown as MirrorAbort).message).toContain('checked out in another worktree')
expect(getBranchName(local)).toBe('main')
expect(existsSync(join(local, 'untracked.txt'))).toBe(true)
expect(revRef(local, 'main')).toBe(localMainSha)
expect(revRef(local, 'checked')).toBe(localCheckedSha)
expect(existsSync(join(tmpDir, 'checked-wt', 'checked.txt'))).toBe(false)
expect(syncRefCount(local)).toBe(0)
})
it('rejects a missing target ref and preserves local refs and worktree state', async () => {
const server = initRepo('server-missing')
commitFile(server, 'main.txt', 'server-main\n')
const bundle = createBundle(server, 'server-missing')
const local = initRepo('local-missing')
const localMainSha = commitFile(local, 'main.txt', 'local-main\n')
writeFileSync(join(local, 'untracked.txt'), 'keep-me\n')
const thrown = await mirrorDownFast(1, local, fastApi('ghost', bundle) as any, { force: true }).then(
() => null,
(err: unknown) => err,
)
expect(thrown).toBeInstanceOf(MirrorAbort)
expect((thrown as MirrorAbort).message).toContain("no incoming branch 'ghost'")
expect(getBranchName(local)).toBe('main')
expect(revRef(local, 'main')).toBe(localMainSha)
expect(existsSync(join(local, 'untracked.txt'))).toBe(true)
expect(syncRefCount(local)).toBe(0)
})
})
describe('ManagerApi target response validation', () => {
afterEach(() => {
vi.unstubAllGlobals()
})
const api = new ManagerApi('http://localhost:5003', 'test-token')
it('parses a valid new-worktree target plan response', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ kind: 'new', repoId: null, fullPath: '/repos/repo-feature', localPath: 'repo-feature', branch: 'feature', currentBranch: 'main' }),
}))
const plan = await api.mirrorTargetPlan(1, 'feature')
expect(plan.kind).toBe('new')
expect(plan.repoId).toBeNull()
expect(plan.branch).toBe('feature')
})
it('parses a valid existing-worktree target plan response', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ kind: 'existing', repoId: 5, fullPath: '/repos/repo-feature', localPath: 'repo-feature', branch: 'feature', currentBranch: null }),
}))
const plan = await api.mirrorTargetPlan(1, 'feature')
expect(plan.kind).toBe('existing')
expect(plan.repoId).toBe(5)
})
it('rejects a target plan response whose repoId contradicts its kind', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ kind: 'new', repoId: 7, fullPath: '/repos/repo-feature', localPath: 'repo-feature', branch: 'feature', currentBranch: 'main' }),
}))
await expect(api.mirrorTargetPlan(1, 'feature')).rejects.toThrow()
})
it('rejects a target plan response with an unknown kind', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ kind: 'bogus', repoId: 1, fullPath: '/x', localPath: 'x', branch: 'main', currentBranch: null }),
}))
await expect(api.mirrorTargetPlan(1, 'main')).rejects.toThrow()
})
it('parses a valid ensure target response', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ repoId: 9, fullPath: '/repos/repo-feature', localPath: 'repo-feature', branch: 'feature', created: true }),
}))
const target = await api.mirrorEnsureTarget(1, 'feature')
expect(target.repoId).toBe(9)
expect(target.created).toBe(true)
})
it('rejects an ensure target response missing fields', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ repoId: 9, fullPath: '/repos/repo-feature' }),
}))
await expect(api.mirrorEnsureTarget(1, 'feature')).rejects.toThrow()
})
it('rejects an ensure target response with a non-positive repoId', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({ repoId: 0, fullPath: '/x', localPath: 'x', branch: 'main', created: false }),
}))
await expect(api.mirrorEnsureTarget(1, 'main')).rejects.toThrow()
})
})
describe('ManagerApi mirrorUploadBundle strict branch header', () => {
let tmpDir: string
beforeEach(() => {
tmpDir = mkdtempSync(join(tmpdir(), 'bundle-header-test-'))
})
afterEach(() => {
vi.unstubAllGlobals()
rmSync(tmpDir, { recursive: true, force: true })
})
const api = new ManagerApi('http://localhost:5003', 'test-token')
async function captureUpload(opts: { branch: string | null; requireCurrentBranch?: boolean }): Promise<Record<string, string>> {
const bundlePath = join(tmpDir, 'repo.bundle')
writeFileSync(bundlePath, 'bundle bytes')
let capturedHeaders: Record<string, string> | undefined
vi.stubGlobal('fetch', vi.fn().mockImplementation(async (_url: unknown, init?: RequestInit) => {
capturedHeaders = init!.headers as Record<string, string>
return { ok: true, json: () => Promise.resolve({ repoId: 1, fullPath: '/repos/x', branch: 'main', head: 'abc', created: false }) }
}))
await api.mirrorUploadBundle(1, bundlePath, opts)
expect(capturedHeaders).toBeDefined()
return capturedHeaders!
}
it('sends the require-current-branch header when requested', async () => {
const headers = await captureUpload({ branch: 'main', requireCurrentBranch: true })
expect(headers['X-OCM-Require-Current-Branch']).toBe('1')
expect(headers['X-OCM-Branch']).toBe('main')
})
it('omits the require-current-branch header for normal push', async () => {
const headers = await captureUpload({ branch: 'main' })
expect(headers['X-OCM-Require-Current-Branch']).toBeUndefined()
expect(headers['X-OCM-Branch']).toBe('main')
})
})
+48
View File
@@ -0,0 +1,48 @@
import { describe, it, expect } from 'vitest'
import { renderProgressBar, formatMoveProgress, pushPhaseProgress, replayProgress } from '../src/move-progress'
describe('renderProgressBar', () => {
it('fills proportionally and reports a percentage', () => {
expect(renderProgressBar(0, 10)).toBe('░░░░░░░░░░ 0%')
expect(renderProgressBar(0.5, 10)).toBe('█████░░░░░ 50%')
expect(renderProgressBar(1, 10)).toBe('██████████ 100%')
})
it('clamps out-of-range fractions', () => {
expect(renderProgressBar(-1, 4)).toBe('░░░░ 0%')
expect(renderProgressBar(7, 4)).toBe('████ 100%')
})
})
describe('formatMoveProgress', () => {
it('shows spinner frame and label without a bar for indeterminate phases', () => {
expect(formatMoveProgress({ label: 'creating git bundle', fraction: null }, 0)).toBe('⠋ ocm-move: creating git bundle')
})
it('appends a bar for determinate phases and cycles spinner frames', () => {
const text = formatMoveProgress({ label: 'uploading', fraction: 0.25 }, 11)
expect(text.startsWith('⠙ ocm-move: uploading ')).toBe(true)
expect(text.endsWith(' 25%')).toBe(true)
})
})
describe('phase mapping', () => {
it('maps upload bytes to a fraction', () => {
expect(pushPhaseProgress({ kind: 'uploading', bytesSent: 512, totalBytes: 2048 })).toEqual({ label: 'uploading 512 B / 2.0 KB', fraction: 0.25 })
})
it('treats a zero-byte upload as indeterminate', () => {
expect(pushPhaseProgress({ kind: 'uploading', bytesSent: 0, totalBytes: 0 }).fraction).toBeNull()
})
it('maps server phases to indeterminate labels', () => {
expect(pushPhaseProgress({ kind: 'bundling' })).toEqual({ label: 'creating git bundle', fraction: null })
expect(pushPhaseProgress({ kind: 'processing' })).toEqual({ label: 'server importing bundle', fraction: null })
expect(pushPhaseProgress({ kind: 'patching' })).toEqual({ label: 'applying local changes', fraction: null })
})
it('maps replay counts to a fraction', () => {
expect(replayProgress(3, 12)).toEqual({ label: 'replaying session 3/12 events', fraction: 0.25 })
expect(replayProgress(0, 0).fraction).toBeNull()
})
})
+111 -1
View File
@@ -3,7 +3,8 @@ import { mkdtempSync, mkdirSync, rmSync } from 'fs'
import { join } from 'path'
import { tmpdir } from 'os'
import { spawnSync } from 'child_process'
import { resolveTarget, type TargetRepo } from '../src/resolve-target'
import { resolveTarget, formatRepoIdentity, formatRepoIdentities, parseRepoIdPositional, restrictMatchesToRequestedRepo, type TargetRepo, type RepoIdentity } from '../src/resolve-target'
import type { RemoteRepoSummary } from '../src/mirror'
const LAST = {
repoId: 99,
@@ -141,3 +142,112 @@ describe('resolveTarget', () => {
}
})
})
describe('formatRepoIdentities', () => {
it('shows id, kind, branch, and path for a worktree and a base repo', () => {
const worktree = {
repoId: 3,
name: 'my-app-feat-x',
branch: 'feat/x',
isWorktree: true,
directory: '/repos/my-app-feat-x',
}
const base = {
repoId: 2,
name: 'my-app',
branch: null,
directory: '/repos/my-app',
}
expect(formatRepoIdentity(worktree)).toBe('my-app-feat-x (id=3, worktree, branch=feat/x, path=/repos/my-app-feat-x)')
expect(formatRepoIdentity(base)).toBe('my-app (id=2, repo, branch=n/a, path=/repos/my-app)')
expect(formatRepoIdentities([worktree, base])).toBe(
'my-app-feat-x (id=3, worktree, branch=feat/x, path=/repos/my-app-feat-x), my-app (id=2, repo, branch=n/a, path=/repos/my-app)',
)
})
it('accepts readonly identity arrays', () => {
const identities: readonly RepoIdentity[] = [
{ repoId: 1, name: 'a', branch: 'main', isWorktree: false, directory: '/repos/a' },
]
expect(formatRepoIdentities(identities)).toBe('a (id=1, repo, branch=main, path=/repos/a)')
})
it('formats cwd-ambiguous target matches with worktree metadata included', () => {
const ambiguous: readonly TargetRepo[] = [
{ repoId: 1, name: 'a', branch: 'main', directory: '/repos/a', isWorktree: false },
{ repoId: 2, name: 'b', branch: 'feat', directory: '/repos/b', isWorktree: true },
]
const formatted = formatRepoIdentities(ambiguous)
expect(formatted).toContain('a (id=1, repo, branch=main, path=/repos/a)')
expect(formatted).toContain('b (id=2, worktree, branch=feat, path=/repos/b)')
})
})
describe('parseRepoIdPositional', () => {
const flags = ['--force', '--create', '--yes', '--full']
it('returns null when no positional repo id is given and ignores known flags', () => {
expect(parseRepoIdPositional([], flags)).toEqual({ repoId: null })
expect(parseRepoIdPositional(['--force', '--full'], flags)).toEqual({ repoId: null })
})
it('parses a single positive integer repo id among flags', () => {
expect(parseRepoIdPositional(['--force', '7', '--full'], flags)).toEqual({ repoId: 7 })
expect(parseRepoIdPositional(['3'], flags)).toEqual({ repoId: 3 })
})
it('rejects non-positive-integer repo ids', () => {
expect(parseRepoIdPositional(['abc'], flags).error).toMatch(/invalid repo id: abc/)
expect(parseRepoIdPositional(['0'], flags).error).toMatch(/invalid repo id: 0/)
expect(parseRepoIdPositional(['1.5'], flags).error).toMatch(/invalid repo id/)
expect(parseRepoIdPositional(['1e3'], flags).error).toMatch(/invalid repo id/)
})
it('rejects oversized repo ids that are not safe integers', () => {
expect(parseRepoIdPositional(['9007199254740993'], flags).error).toMatch(/invalid repo id: 9007199254740993/)
expect(parseRepoIdPositional(['99999999999999999999'], flags).error).toMatch(/invalid repo id: 99999999999999999999/)
})
it('rejects unknown options', () => {
expect(parseRepoIdPositional(['--bogus'], flags).error).toBe('unknown option: --bogus')
expect(parseRepoIdPositional(['-x'], flags).error).toBe('unknown option: -x')
})
it('rejects duplicate positional repo ids', () => {
expect(parseRepoIdPositional(['3', '4'], flags).error).toMatch(/multiple repo ids given: 3 and 4/)
})
})
describe('restrictMatchesToRequestedRepo', () => {
const match = (id: number): RemoteRepoSummary => ({
repoId: id,
name: `repo-${id}`,
projectId: 'project-a',
branch: 'main',
})
it('passes matches through when no repo id is requested', () => {
const matches = [match(1), match(2)]
expect(restrictMatchesToRequestedRepo(matches, null, 'project-a')).toEqual({ matches })
})
it('restricts matches to the exact requested repo', () => {
const result = restrictMatchesToRequestedRepo([match(1), match(2)], 2, 'project-a')
expect(result.error).toBeUndefined()
expect(result.matches).toEqual([match(2)])
})
it('fails clearly when the requested repo is not one of the project matches', () => {
const result = restrictMatchesToRequestedRepo([match(1), match(2)], 7, 'project-a')
expect(result.error).toContain('repo 7 does not match project project-a')
expect(result.error).toContain('repo-1 (id=1, repo, branch=main')
expect(result.matches).toEqual([])
})
it('fails clearly when no repo matches the project', () => {
const result = restrictMatchesToRequestedRepo([], 7, 'project-a')
expect(result.error).toBe('repo 7 does not match project project-a; no Manager repo matches this project')
expect(result.matches).toEqual([])
})
})
+38
View File
@@ -118,6 +118,44 @@ describe('rewriteEventsForRemote', () => {
expect(result[0]!.data.location).toEqual({ directory: '/workspace/repos/repo/src' })
})
it('rewrites assistant message path cwd and root', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 3,
type: 'message.updated.1',
data: { info: { id: 'msg_1', role: 'assistant', path: { cwd: '/Users/x/repo/src', root: '/Users/x/repo' } } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.info).toEqual({
id: 'msg_1',
role: 'assistant',
path: { cwd: '/workspace/repos/repo/src', root: '/workspace/repos/repo' },
})
})
it('leaves message paths outside the local root untouched', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 3,
type: 'message.updated.1',
data: { info: { id: 'msg_1', role: 'assistant', path: { cwd: '/Users/x/repo-other', root: '/Users/x/repo-other' } } },
},
{
id: 'e2', aggregateID: 'ses_a', seq: 4,
type: 'message.updated.1',
data: { info: { id: 'msg_2', role: 'user' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.info).toEqual({ id: 'msg_1', role: 'assistant', path: { cwd: '/Users/x/repo-other', root: '/Users/x/repo-other' } })
expect(result[1]!.data.info).toEqual({ id: 'msg_2', role: 'user' })
})
it('strips workspaceID from info', () => {
const events: ReplayEvent[] = [
{