feat(ocm-cli): add session move with local history export and TUI plugin (#304)

* loop: ocm-session-move completed after 7 iterations

* feat(ocm-cli): add session move with local history export and TUI plugin

* docs(ocm-cli): update plugin config to tui-only entry and clarify session history source

* fix(ocm-cli): replace raw postinstall output with TUI toast notification
This commit is contained in:
Chris Scott authored and GitHub committed 2026-07-08 17:23:53 -04:00
1 parent 54323267f5
commit 61efcf9ad1
19 files changed
+906 -157

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
import { existsSync, readdirSync, statSync } from 'fs'
import { homedir } from 'os'
import { isAbsolute, join } from 'path'
import type { HistoryEventRow } from './session-move.js'
function opencodeDataDir(): string {
const xdg = process.env.XDG_DATA_HOME
return xdg ? join(xdg, 'opencode') : join(homedir(), '.local', 'share', 'opencode')
}
/**
* Resolves the opencode durable-event database path the same way
* `Database.path()` does in opencode core: an `OPENCODE_DB` override wins,
* then the default `opencode.db`, then the newest channel-suffixed variant
* (`opencode-<channel>.db`) for non-release channels.
*/
export function resolveOpencodeDbPath(): string | null {
const override = process.env.OPENCODE_DB
const dataDir = opencodeDataDir()
if (override) {
if (override === ':memory:' || isAbsolute(override)) return override
return join(dataDir, override)
}
const defaultPath = join(dataDir, 'opencode.db')
if (existsSync(defaultPath)) return defaultPath
if (!existsSync(dataDir)) return null
const variants = readdirSync(dataDir)
.filter((name) => name.startsWith('opencode-') && name.endsWith('.db'))
.map((name) => join(dataDir, name))
.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)
return variants[0] ?? null
}
export async function readSessionEvents(sessionID: string): Promise<HistoryEventRow[]> {
const dbPath = resolveOpencodeDbPath()
if (!dbPath) {
throw new Error('opencode database not found; is this machine running opencode with durable history?')
}
const { Database } = await import('bun:sqlite')
const db = new Database(dbPath, { readonly: true })
try {
const rows = db
.query<{ id: string; aggregate_id: string; seq: number; type: string; data: string }, [string]>(
'SELECT id, aggregate_id, seq, type, data FROM event WHERE aggregate_id = ? ORDER BY seq ASC',
)
.all(sessionID)
return rows.map((row) => ({
id: row.id,
aggregate_id: row.aggregate_id,
seq: row.seq,
type: row.type,
data: JSON.parse(row.data) as Record<string, unknown>,
}))
} finally {
db.close()
}
}
+1 -1
View File
@@ -165,7 +165,7 @@ export class ManagerApi {
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 ReadableStream<Uint8Array>
const body = Readable.toWeb(createReadStream(bundlePath)) as unknown as ReadableStream<Uint8Array>
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle${query}`, {
method: 'POST',
headers,
+31
View File
@@ -0,0 +1,31 @@
import type { RemoteRepoSummary } from './mirror.js'
export interface ManagerRepo {
repoId: number
name: string
branch: string | null
cloneStatus: string
directory: string
projectId?: string | null
extra: { repoId: number; localPath: string; fullPath: string }
}
export async function fetchRepos(managerUrl: string, token: string): Promise<ManagerRepo[]> {
const res = await fetch(`${managerUrl}/api/internal/opencode-workspaces`, {
headers: { Authorization: `Bearer ${token}` },
})
if (!res.ok) {
throw new Error(`manager responded ${res.status} ${res.statusText}`)
}
const data = (await res.json()) as { workspaces: ManagerRepo[] }
return data.workspaces
}
export function toRemoteRepoSummaries(repos: ManagerRepo[]): RemoteRepoSummary[] {
return repos.map((r) => ({
repoId: r.repoId,
name: r.name,
projectId: r.projectId ?? null,
branch: r.branch,
}))
}
-59
View File
@@ -1,59 +0,0 @@
import { mkdirSync, symlinkSync, lstatSync, readlinkSync, unlinkSync, existsSync, chmodSync } from 'node:fs'
import { homedir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const OCM_TARGET = join(PACKAGE_ROOT, 'dist', 'ocm.js')
const BIN_DIR = join(homedir(), '.local', 'bin')
const BIN_LINK = join(BIN_DIR, 'ocm')
function ensureSymlink(): { installed: boolean; message?: string } {
if (!existsSync(OCM_TARGET)) {
return { installed: false, message: `ocm-cli: missing ${OCM_TARGET}, skipping bin install` }
}
try {
chmodSync(OCM_TARGET, 0o755)
} catch {
// best effort
}
try {
mkdirSync(BIN_DIR, { recursive: true })
} catch (err) {
return { installed: false, message: `ocm-cli: cannot create ${BIN_DIR}: ${(err as Error).message}` }
}
try {
const stat = lstatSync(BIN_LINK)
if (stat.isSymbolicLink()) {
if (readlinkSync(BIN_LINK) === OCM_TARGET) {
return { installed: false }
}
unlinkSync(BIN_LINK)
} else {
return { installed: false, message: `ocm-cli: ${BIN_LINK} exists and is not a symlink; leaving alone` }
}
} catch {
// missing — fine
}
try {
symlinkSync(OCM_TARGET, BIN_LINK)
} catch (err) {
return { installed: false, message: `ocm-cli: failed to symlink ${BIN_LINK}: ${(err as Error).message}` }
}
const onPath = (process.env.PATH ?? '').split(':').includes(BIN_DIR)
const pathHint = onPath ? '' : ` (add "${BIN_DIR}" to your PATH to run \`ocm\`)`
return { installed: true, message: `ocm-cli: installed \`ocm\` at ${BIN_LINK}${pathHint}` }
}
const result = ensureSymlink()
if (result.message) {
process.stderr.write(`${result.message}\n`)
}
const plugin = async (): Promise<Record<string, never>> => ({})
export default plugin
+19
View File
@@ -0,0 +1,19 @@
import type { ReplayEvent } from './session-move.js'
export function createManagerReplay(managerUrl: string, token: string) {
return async (remoteDirectory: string, events: ReplayEvent[]): Promise<{ sessionID: string }> => {
const url = `${managerUrl}/api/opencode-proxy/sync/replay?directory=${encodeURIComponent(remoteDirectory)}`
const res = await fetch(url, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({ directory: remoteDirectory, events }),
})
if (!res.ok) {
const text = await res.text().catch(() => '')
throw new Error(`replay failed (${res.status}): ${text.slice(0, 200)}`)
}
return (await res.json()) as { sessionID: string }
}
}
+153
View File
@@ -0,0 +1,153 @@
export type HistoryEventRow = { id: string; aggregate_id: string; seq: number; type: string; data: Record<string, unknown> }
export type ReplayEvent = { id: string; aggregateID: string; seq: number; type: string; data: Record<string, unknown> }
export type CollectResult =
| { kind: 'ok'; events: ReplayEvent[] }
| { kind: 'empty' }
| { kind: 'gap'; missingSeq: number }
export type RewriteContext = { localRoot: string; remoteRoot: string }
export function collectSessionEvents(rows: HistoryEventRow[], sessionID: string): CollectResult {
const filtered = rows.filter((r) => r.aggregate_id === sessionID)
if (filtered.length === 0) return { kind: 'empty' }
const sorted = [...filtered].sort((a, b) => a.seq - b.seq)
if (sorted[0]!.seq !== 0) return { kind: 'gap', missingSeq: 0 }
for (let i = 1; i < sorted.length; i++) {
if (sorted[i]!.seq !== sorted[i - 1]!.seq + 1) {
return { kind: 'gap', missingSeq: sorted[i - 1]!.seq + 1 }
}
}
const events: ReplayEvent[] = sorted.map((r) => ({
id: r.id,
aggregateID: r.aggregate_id,
seq: r.seq,
type: r.type,
data: r.data,
}))
return { kind: 'ok', events }
}
/**
* Rewrites collected replay events for replay on a remote Manager server.
*
* Coercion rule for `data.timestamp` matches the prior implementation in
* commit 686c820d (`coerceReplayBodyTimestamps`): ISO 8601 string timestamps
* are converted to epoch milliseconds via `Date.parse`; already-numeric values
* are left untouched.
*/
export function rewriteEventsForRemote(events: ReplayEvent[], ctx: RewriteContext): ReplayEvent[] {
return events.map((event) => {
const data = deepClone(event.data)
if (shouldRewriteDirectory(event.type)) {
rewriteDirectory(data, 'info', ctx)
stripWorkspaceID(data, 'info')
}
if (isMovedEvent(event.type)) {
rewriteDirectory(data, 'location', ctx)
stripWorkspaceID(data, 'location')
}
coerceTimestamp(data)
return { ...event, data }
})
}
function shouldRewriteDirectory(type: string): boolean {
return type.startsWith('session.created') || type.startsWith('session.updated')
}
function isMovedEvent(type: string): boolean {
return type.startsWith('session.next.moved')
}
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)
}
}
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
}
/** Per commit 686c820d: coerce `data.timestamp` from ISO string to epoch ms. */
function coerceTimestamp(data: Record<string, unknown>): void {
const ts = data.timestamp
if (typeof ts !== 'string') return
const epoch = Date.parse(ts)
if (!Number.isFinite(epoch)) return
data.timestamp = epoch
}
export type TransferDeps = {
fetchLocalHistory: () => Promise<HistoryEventRow[]>
replayEvents: (remoteDirectory: string, events: ReplayEvent[]) => Promise<{ sessionID: string }>
}
export type TransferInput = { sessionID: string; localRoot: string; remoteDirectory: string }
export type TransferResult =
| { kind: 'moved'; sessionID: string; replayedEvents: number }
| { kind: 'not-found' }
| { kind: 'corrupt-history'; missingSeq: number }
| { kind: 'replay-failed'; message: string }
export function planReplayBatches(events: ReplayEvent[], batchSize = 10): ReplayEvent[][] {
const batches: ReplayEvent[][] = []
for (let i = 0; i < events.length; i += batchSize) {
batches.push(events.slice(i, i + batchSize))
}
return batches
}
export async function transferSession(input: TransferInput, deps: TransferDeps): Promise<TransferResult> {
const rows = await deps.fetchLocalHistory()
const collect = collectSessionEvents(rows, input.sessionID)
if (collect.kind === 'empty') return { kind: 'not-found' }
if (collect.kind === 'gap') return { kind: 'corrupt-history', missingSeq: collect.missingSeq }
const rewritten = rewriteEventsForRemote(collect.events, {
localRoot: input.localRoot,
remoteRoot: input.remoteDirectory,
})
const batches = planReplayBatches(rewritten)
let replayed = 0
for (const batch of batches) {
try {
await deps.replayEvents(input.remoteDirectory, batch)
replayed += batch.length
} catch (err) {
return { kind: 'replay-failed', message: err instanceof Error ? err.message : String(err) }
}
}
return { kind: 'moved', sessionID: input.sessionID, replayedEvents: replayed }
}
function deepClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj))
}
+30 -1
View File
@@ -1,4 +1,4 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'fs'
import { homedir } from 'os'
import { dirname, join } from 'path'
@@ -11,8 +11,15 @@ export interface OcmState {
updatedAt?: number
}
export interface InstallNotice {
link: string
binDir: string
pathMissing: boolean
}
const STATE_DIR = join(homedir(), '.config', 'opencode-manager')
const STATE_FILE = join(STATE_DIR, 'state.json')
const INSTALL_NOTICE_FILE = join(STATE_DIR, 'install-notice.json')
export function getStatePath(): string {
return STATE_FILE
@@ -41,3 +48,25 @@ export function clearState(): void {
writeFileSync(STATE_FILE, '{}', { mode: 0o600 })
}
}
export function readInstallNotice(): InstallNotice | null {
if (!existsSync(INSTALL_NOTICE_FILE)) return null
try {
const raw = readFileSync(INSTALL_NOTICE_FILE, 'utf-8')
const parsed = JSON.parse(raw) as InstallNotice
if (!parsed.link || !parsed.binDir) return null
return parsed
} catch {
return null
} finally {
deleteInstallNotice()
}
}
function deleteInstallNotice(): void {
try {
unlinkSync(INSTALL_NOTICE_FILE)
} catch {
return
}
}
+127
View File
@@ -0,0 +1,127 @@
import type { TuiPluginApi, TuiPluginModule } from './tui-types.js'
import { readInstallNotice, readState } from './state.js'
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 { readSessionEvents } from './local-history.js'
const tui = async (api: TuiPluginApi): Promise<void> => {
showInstallNotice(api)
api.keymap.registerLayer({
commands: [
{
name: 'ocm.session.move',
title: 'Move session to Manager',
desc: 'Push repo state and move this session to OpenCode Manager',
category: 'OpenCode Manager',
namespace: 'palette',
slashName: 'ocm-move',
run: () => runSessionMove(api),
},
],
})
}
function showInstallNotice(api: TuiPluginApi): void {
const notice = readInstallNotice()
if (!notice) return
api.ui.toast({
variant: 'success',
title: 'ocm installed',
message: notice.pathMissing
? `Linked at ${notice.link}. Add export PATH="$HOME/.local/bin:$PATH" to your shell rc if ocm is unavailable.`
: `Linked at ${notice.link}`,
duration: 10000,
})
}
async function runSessionMove(api: TuiPluginApi): Promise<void> {
try {
const current = api.route.current
if (current.name !== 'session' || !current.params) {
api.ui.toast({ variant: 'error', message: 'Not in a session' })
return
}
const sessionID = String(current.params.sessionID)
const session = api.state.session.get(sessionID)
if (!session?.directory) {
api.ui.toast({ variant: 'error', message: 'Session has no directory' })
return
}
const state = readState()
if (!state?.managerUrl) {
api.ui.toast({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
return
}
const token = getToken(state.managerUrl)
if (!token) {
api.ui.toast({ variant: 'error', message: `No token in Keychain. Run \`ocm login ${state.managerUrl}\`.` })
return
}
const repos = await fetchRepos(state.managerUrl, token)
const plan = await prepareMirror(session.directory, toRemoteRepoSummaries(repos))
if (plan.matched.length === 0) {
api.ui.toast({ variant: 'error', message: 'No matching Manager repo; run `ocm push --create` first' })
return
}
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 matched = plan.matched[0]!
const repoId = matched.repoId
const remoteRepo = repos.find((r) => r.repoId === repoId)
const remoteDirectory = remoteRepo!.directory
const managerApi = new ManagerApi(state.managerUrl, token)
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
}
api.ui.toast({ message: 'Pushing repo state…' })
await mirrorUpFast(plan, { api: managerApi, force: false })
const result = await transferSession(
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
{ fetchLocalHistory: () => readSessionEvents(sessionID), replayEvents: createManagerReplay(state.managerUrl, token) },
)
switch (result.kind) {
case 'moved':
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
case 'corrupt-history':
api.ui.toast({ variant: 'error', message: `Session history has a gap at sequence ${result.missingSeq}` })
break
case 'replay-failed':
api.ui.toast({ variant: 'error', message: `Replay failed: ${result.message}` })
break
}
} catch (err) {
api.ui.toast({ variant: 'error', message: err instanceof Error ? err.message : String(err) })
}
}
export default { id: 'ocm', tui } satisfies TuiPluginModule
+11
View File
@@ -0,0 +1,11 @@
export type TuiRouteCurrent = { name: 'session'; params: { sessionID: string } } | { name: string; params?: Record<string, unknown> }
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 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 }
}
export type TuiPluginModule = { id?: string; tui: (api: TuiPluginApi, options?: Record<string, unknown>) => Promise<void> }