mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(ocm-cli): add session warp with progress reporting (#314)
* feat(ocm-cli): add session warp with progress reporting Add warp functionality for moving sessions between local and remote Managers. Includes TUI dialogs, remote replay, progress reporting during event transfer, and comprehensive test coverage. * feat(ocm-cli): add granular push progress with phase reporting and upload tracking * chore(ocm-cli): bump version to 0.2.5 * docs(ocm-cli): document push progress phases in README
This commit is contained in:
1 parent
4519bcd2e9
commit
adf6bd2921
16 files changed
+759
-30
No files matched your search
@@ -52,6 +52,17 @@ export interface MirrorBundleResult {
|
||||
created: false
|
||||
}
|
||||
|
||||
function createByteCounter(onProgress: (bytesSent: number) => void): TransformStream<Uint8Array, Uint8Array> {
|
||||
let bytesSent = 0
|
||||
return new TransformStream<Uint8Array, Uint8Array>({
|
||||
transform(chunk, controller) {
|
||||
bytesSent += chunk.byteLength
|
||||
onProgress(bytesSent)
|
||||
controller.enqueue(chunk)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export class ManagerApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
@@ -161,11 +172,16 @@ export class ManagerApi {
|
||||
return (await res.json()) as MirrorPatchResult
|
||||
}
|
||||
|
||||
async mirrorUploadBundle(repoId: number, bundlePath: string, opts: { branch: string | null; force?: boolean }): Promise<MirrorBundleResult> {
|
||||
async mirrorUploadBundle(
|
||||
repoId: number,
|
||||
bundlePath: string,
|
||||
opts: { branch: string | null; force?: 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
|
||||
const body = Readable.toWeb(createReadStream(bundlePath)) as unknown as ReadableStream<Uint8Array>
|
||||
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}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
|
||||
+33
-3
@@ -379,7 +379,17 @@ function applyPatch(repoRoot: string, patch: string): void {
|
||||
|
||||
async function createLocalBundle(repoRoot: string): Promise<string> {
|
||||
const bundlePath = join(tmpdir(), `ocm-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.bundle`)
|
||||
runGit(repoRoot, ['bundle', 'create', bundlePath, '--all'])
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const child = spawn('git', ['bundle', 'create', bundlePath, '--all'], { cwd: repoRoot })
|
||||
const stderrChunks: Buffer[] = []
|
||||
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk))
|
||||
child.on('error', reject)
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) return resolve()
|
||||
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
|
||||
reject(new Error(`git bundle create failed${stderr ? `: ${stderr}` : ''}`))
|
||||
})
|
||||
})
|
||||
return bundlePath
|
||||
}
|
||||
|
||||
@@ -428,14 +438,34 @@ async function writeBundleStream(repoId: number, api: ManagerApi): Promise<strin
|
||||
return bundlePath
|
||||
}
|
||||
|
||||
export type MirrorUpFastPhase =
|
||||
| { kind: 'bundling' }
|
||||
| { kind: 'uploading'; bytesSent: number; totalBytes: number }
|
||||
| { kind: 'processing' }
|
||||
| { kind: 'patching' }
|
||||
|
||||
export async function mirrorUpFast(
|
||||
plan: MirrorPlan,
|
||||
opts: Pick<MirrorUpOpts, 'api' | 'force'>,
|
||||
opts: Pick<MirrorUpOpts, 'api' | 'force'> & { onPhase?: (phase: MirrorUpFastPhase) => void },
|
||||
): Promise<{ repoId: number; branch: string | null; head: string | null; created: false }> {
|
||||
const repoId = plan.matched[0]!.repoId
|
||||
const onPhase = opts.onPhase
|
||||
onPhase?.({ kind: 'bundling' })
|
||||
const bundlePath = await createLocalBundle(plan.repoRoot)
|
||||
try {
|
||||
await opts.api.mirrorUploadBundle(repoId, bundlePath, { branch: getBranchName(plan.repoRoot), force: opts.force })
|
||||
const { size } = await fsp.stat(bundlePath)
|
||||
onPhase?.({ kind: 'uploading', bytesSent: 0, totalBytes: size })
|
||||
await opts.api.mirrorUploadBundle(repoId, bundlePath, {
|
||||
branch: getBranchName(plan.repoRoot),
|
||||
force: opts.force,
|
||||
onProgress: onPhase
|
||||
? (bytesSent) => {
|
||||
onPhase({ kind: 'uploading', bytesSent, totalBytes: size })
|
||||
if (bytesSent >= size) onPhase({ kind: 'processing' })
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
onPhase?.({ kind: 'patching' })
|
||||
const patchResult = await mirrorUpPatch(plan, opts)
|
||||
return { repoId: patchResult.repoId, branch: patchResult.branch, head: patchResult.head, created: false }
|
||||
} finally {
|
||||
|
||||
@@ -16,4 +16,19 @@ export function createManagerReplay(managerUrl: string, token: string) {
|
||||
|
||||
return (await res.json()) as { sessionID: string }
|
||||
}
|
||||
}
|
||||
|
||||
export function createManagerPromptAsync(managerUrl: string, token: string) {
|
||||
return async (remoteDirectory: string, sessionID: string, text: string): Promise<void> => {
|
||||
const url = `${managerUrl}/api/opencode-proxy/session/${encodeURIComponent(sessionID)}/prompt_async?directory=${encodeURIComponent(remoteDirectory)}`
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ noReply: true, parts: [{ type: 'text', text, synthetic: true }] }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '')
|
||||
throw new Error(`prompt_async failed (${res.status}): ${body.slice(0, 200)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,7 @@ function coerceTimestamp(data: Record<string, unknown>): void {
|
||||
export type TransferDeps = {
|
||||
fetchLocalHistory: () => Promise<HistoryEventRow[]>
|
||||
replayEvents: (remoteDirectory: string, events: ReplayEvent[]) => Promise<{ sessionID: string }>
|
||||
onProgress?: (replayed: number, total: number) => void
|
||||
}
|
||||
|
||||
export type TransferInput = { sessionID: string; localRoot: string; remoteDirectory: string }
|
||||
@@ -134,12 +135,15 @@ export async function transferSession(input: TransferInput, deps: TransferDeps):
|
||||
})
|
||||
|
||||
const batches = planReplayBatches(rewritten)
|
||||
const total = rewritten.length
|
||||
let replayed = 0
|
||||
deps.onProgress?.(replayed, total)
|
||||
|
||||
for (const batch of batches) {
|
||||
try {
|
||||
await deps.replayEvents(input.remoteDirectory, batch)
|
||||
replayed += batch.length
|
||||
deps.onProgress?.(replayed, total)
|
||||
} catch (err) {
|
||||
return { kind: 'replay-failed', message: err instanceof Error ? err.message : String(err) }
|
||||
}
|
||||
@@ -148,6 +152,10 @@ export async function transferSession(input: TransferInput, deps: TransferDeps):
|
||||
return { kind: 'moved', sessionID: input.sessionID, replayedEvents: replayed }
|
||||
}
|
||||
|
||||
export function moveReminderText(directory: string): string {
|
||||
return `<system-reminder>The user has changed the current working directory to "${directory}". This is still the same project but at a possibly new location; take this into account when working with any files from now on.</system-reminder>`
|
||||
}
|
||||
|
||||
function deepClone<T>(obj: T): T {
|
||||
return JSON.parse(JSON.stringify(obj))
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { TuiPluginApi } from './tui-types.js'
|
||||
|
||||
export function confirmDialog(api: TuiPluginApi, props: { title: string; message: string }): Promise<boolean> {
|
||||
return new Promise<boolean>((resolve) => {
|
||||
let settled = false
|
||||
const settle = (value: boolean, clearDialog = true) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
if (clearDialog) api.ui.dialog.clear()
|
||||
resolve(value)
|
||||
}
|
||||
api.ui.dialog.replace(
|
||||
() => api.ui.DialogConfirm({ ...props, onConfirm: () => settle(true), onCancel: () => settle(false) }),
|
||||
() => settle(false, false),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export function selectDialog<Value>(
|
||||
api: TuiPluginApi,
|
||||
title: string,
|
||||
options: { title: string; description?: string; value: Value }[],
|
||||
): Promise<Value | undefined> {
|
||||
return new Promise<Value | undefined>((resolve) => {
|
||||
let settled = false
|
||||
const settle = (value: Value | undefined, clearDialog = true) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
if (clearDialog) api.ui.dialog.clear()
|
||||
resolve(value)
|
||||
}
|
||||
const mapped = options.map((o) => ({ ...o, onSelect: () => settle(o.value) }))
|
||||
api.ui.dialog.replace(
|
||||
() => api.ui.DialogSelect({ title, options: mapped, onSelect: (o) => settle(o.value as Value) }),
|
||||
() => settle(undefined, false),
|
||||
)
|
||||
})
|
||||
}
|
||||
+60
-11
@@ -4,9 +4,13 @@ import { getToken } from './keychain.js'
|
||||
import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js'
|
||||
import { ManagerApi, ManagerApiError } from './manager-api.js'
|
||||
import { prepareMirror, checkPushDivergence, mirrorUpFast } from './mirror.js'
|
||||
import { transferSession } from './session-move.js'
|
||||
import { createManagerReplay } from './remote-replay.js'
|
||||
import type { MirrorPlan, MirrorUpFastPhase } from './mirror.js'
|
||||
import { formatBytes } from './progress.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'
|
||||
|
||||
export async function setupOcm(api: TuiPluginApi): Promise<void> {
|
||||
showInstallNotice(api)
|
||||
@@ -23,6 +27,7 @@ export async function setupOcm(api: TuiPluginApi): Promise<void> {
|
||||
},
|
||||
],
|
||||
})
|
||||
api.lifecycle.onDispose(() => runPendingWarp())
|
||||
}
|
||||
|
||||
function showInstallNotice(api: TuiPluginApi): void {
|
||||
@@ -39,6 +44,31 @@ 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…'
|
||||
}
|
||||
}
|
||||
|
||||
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) })
|
||||
}
|
||||
}
|
||||
|
||||
async function runSessionMove(api: TuiPluginApi): Promise<void> {
|
||||
try {
|
||||
const current = api.route.current
|
||||
@@ -74,17 +104,19 @@ async function runSessionMove(api: TuiPluginApi): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
let matched = plan.matched[0]!
|
||||
if (plan.matched.length > 1) {
|
||||
const names = plan.matched.map((r) => `${r.name} (id=${r.repoId})`).join(', ')
|
||||
api.ui.toast({ variant: 'error', message: `Multiple Manager repos match: ${names}` })
|
||||
return
|
||||
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 matched = plan.matched[0]!
|
||||
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 managerApi = new ManagerApi(state.managerUrl, token)
|
||||
|
||||
try {
|
||||
@@ -97,18 +129,35 @@ async function runSessionMove(api: TuiPluginApi): Promise<void> {
|
||||
if (!(error instanceof ManagerApiError && error.status === 404)) throw error
|
||||
}
|
||||
|
||||
api.ui.toast({ message: 'Pushing repo state…' })
|
||||
await mirrorUpFast(plan, { api: managerApi, force: false })
|
||||
const selectedPlan: MirrorPlan = { ...plan, matched: [matched] }
|
||||
await mirrorUpFast(selectedPlan, {
|
||||
api: managerApi,
|
||||
force: false,
|
||||
onPhase: createPushPhaseToaster(api),
|
||||
})
|
||||
|
||||
const result = await transferSession(
|
||||
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
|
||||
{ fetchLocalHistory: () => readSessionEvents(sessionID), replayEvents: createManagerReplay(state.managerUrl, token) },
|
||||
{
|
||||
fetchLocalHistory: () => readSessionEvents(sessionID),
|
||||
replayEvents: createManagerReplay(state.managerUrl, token),
|
||||
onProgress: (replayed, total) => api.ui.toast({ message: `Moving session… ${replayed}/${total} events`, duration: 2000 }),
|
||||
},
|
||||
)
|
||||
|
||||
switch (result.kind) {
|
||||
case 'moved':
|
||||
case 'moved': {
|
||||
await createManagerPromptAsync(state.managerUrl, token)(remoteDirectory, result.sessionID, moveReminderText(remoteDirectory)).catch(() => undefined)
|
||||
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)
|
||||
setPendingWarp({ managerUrl: state.managerUrl, token, directory: remoteDirectory, sessionID: result.sessionID, repoName: matched.name })
|
||||
api.keymap.dispatchCommand('app.exit')
|
||||
return
|
||||
}
|
||||
api.ui.toast({ variant: 'success', message: `Session moved to Manager (${result.replayedEvents} events). Local copy kept — run \`ocm\` to attach.` })
|
||||
break
|
||||
}
|
||||
case 'not-found':
|
||||
api.ui.toast({ variant: 'error', message: 'No durable history found for this session' })
|
||||
break
|
||||
|
||||
@@ -18,11 +18,17 @@ export type TuiRouteCurrent = { name: 'session'; params: { sessionID: string } }
|
||||
export type TuiSessionInfo = { id: string; directory: string; title?: string }
|
||||
export type TuiToast = { title?: string; message: string; variant?: 'info' | 'success' | 'error' | 'warning'; duration?: number }
|
||||
export type TuiCommandDef = { name: string; title: string; desc?: string; category?: string; namespace?: string; slashName?: string; run: () => void | Promise<void> }
|
||||
export type TuiDialogConfirmProps = { title: string; message: string; onConfirm?: () => void; onCancel?: () => void }
|
||||
export type TuiDialogSelectOption<Value = unknown> = { title: string; value?: Value; description?: string; disabled?: boolean; onSelect?: () => void }
|
||||
export type TuiDialogSelectProps<Value = unknown> = { title: string; placeholder?: string; options: TuiDialogSelectOption<Value>[]; onSelect?: (option: TuiDialogSelectOption<Value>) => void }
|
||||
export type TuiDialogStack = { replace: (render: () => unknown, onClose?: () => void) => void; clear: () => void }
|
||||
export type TuiLifecycle = { readonly signal: AbortSignal; onDispose: (fn: () => void | Promise<void>) => () => void }
|
||||
export type TuiPluginApi = {
|
||||
route: { readonly current: TuiRouteCurrent }
|
||||
state: { session: { get: (sessionID: string) => TuiSessionInfo | undefined } }
|
||||
ui: { toast: (input: TuiToast) => void }
|
||||
keymap: { registerLayer: (layer: { commands: TuiCommandDef[]; bindings?: Record<string, unknown> }) => unknown }
|
||||
ui: { toast: (input: TuiToast) => void; DialogConfirm: (props: TuiDialogConfirmProps) => unknown; DialogSelect: <Value = unknown>(props: TuiDialogSelectProps<Value>) => unknown; dialog: TuiDialogStack }
|
||||
keymap: { registerLayer: (layer: { commands: TuiCommandDef[]; bindings?: Record<string, unknown> }) => unknown; dispatchCommand: (name: string) => unknown }
|
||||
slots: { register: (registration: TuiSlotRegistration) => string }
|
||||
lifecycle: TuiLifecycle
|
||||
}
|
||||
export type TuiPluginModule = { id?: string; tui: (api: TuiPluginApi, options?: Record<string, unknown>) => Promise<void> }
|
||||
@@ -0,0 +1,52 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { buildRemoteAttachEnv } from './remote-context.js'
|
||||
|
||||
export type WarpTarget = {
|
||||
managerUrl: string
|
||||
token: string
|
||||
directory: string
|
||||
sessionID: string
|
||||
repoName: string
|
||||
}
|
||||
|
||||
export type WarpSpawn = (
|
||||
command: string,
|
||||
args: string[],
|
||||
options: { stdio: 'inherit'; env: NodeJS.ProcessEnv },
|
||||
) => unknown
|
||||
|
||||
let pending: WarpTarget | undefined
|
||||
|
||||
export function setPendingWarp(target: WarpTarget): void {
|
||||
pending = target
|
||||
}
|
||||
|
||||
export function takePendingWarp(): WarpTarget | undefined {
|
||||
const t = pending
|
||||
pending = undefined
|
||||
return t
|
||||
}
|
||||
|
||||
export function buildAttachArgs(target: WarpTarget): string[] {
|
||||
return [
|
||||
'attach',
|
||||
`${target.managerUrl}/api/opencode-proxy`,
|
||||
'--dir', target.directory,
|
||||
'--session', target.sessionID,
|
||||
'--password', target.token,
|
||||
'--username', 'opencode',
|
||||
]
|
||||
}
|
||||
|
||||
export function runPendingWarp(spawn: WarpSpawn = spawnSync): void {
|
||||
const target = takePendingWarp()
|
||||
if (!target) return
|
||||
try {
|
||||
spawn('opencode', buildAttachArgs(target), {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, ...buildRemoteAttachEnv(target.managerUrl, target.repoName) },
|
||||
})
|
||||
} catch {
|
||||
void 0
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user