mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
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:
1 parent
4ed3460759
commit
68d586f183
23 files changed
+2026
-158
No files matched your search
@@ -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(),
|
||||
|
||||
@@ -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
@@ -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(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
|
||||
Reference in new issue
Block a user