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

+9 -9
View File
@@ -29,29 +29,25 @@ The CLI is published as `@opencode-manager/ocm-cli`. There are two install paths
### Option A — install via OpenCode's plugin loader (recommended)
Add the package to your OpenCode config and OpenCode will fetch it on next start. The package's plugin entry self-installs a `~/.local/bin/ocm` symlink, so the `ocm` binary becomes available on your PATH automatically.
Add the TUI plugin entry to your OpenCode config and OpenCode will fetch the package on next start. The package `postinstall` script self-installs a `~/.local/bin/ocm` symlink for local plugin installs, so the `ocm` binary becomes available on your PATH automatically.
```jsonc
// ~/.config/opencode/opencode.json
{
"$schema": "https://opencode.ai/config.json",
"plugin": ["@opencode-manager/ocm-cli"]
"plugin": ["@opencode-manager/ocm-cli/tui"]
}
```
The next time OpenCode starts it will run `bun install` for the plugin and import it once. You'll see:
The next time OpenCode starts it will run `bun install` for the plugin. The installer stays quiet so it does not break the TUI layout; after the plugin loads, OpenCode shows a one-time toast confirming where `ocm` was linked.
```
ocm-cli: installed `ocm` at /Users/you/.local/bin/ocm
```
If `~/.local/bin` is not on your PATH, the message will tell you. Add this to your shell rc:
If `~/.local/bin` is not on your PATH, add this to your shell rc:
```bash
export PATH="$HOME/.local/bin:$PATH"
```
The plugin itself is a no-op — it does not register tools, commands, or hooks. Its only side effect is the bin symlink, so all real work happens through the `ocm` CLI.
The `./tui` entry registers `/ocm-move`, a TUI command that keeps the local session and copies the active session to the Manager after pushing the current repo state. Run it from inside a local OpenCode session after `ocm login` and after the repo exists on the Manager (`ocm push --create` if needed).
### Option B — global package manager install
@@ -129,6 +125,10 @@ The child takes over the terminal (`stdio: inherit`); closing the TUI exits `ocm
`ocm pull` uses a fast git bundle + working-tree patch by default to sync the matching Manager repo over `$PWD`. Pass `--full` to use the legacy 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).
### TUI `/ocm-move`
When the TUI plugin entry is installed, `/ocm-move` is available in local OpenCode sessions. It checks that the matching Manager repo has not diverged, pushes the local git state with the fast bundle + working-tree patch path, reads the active session history from the local OpenCode SQLite event database, rewrites local repo directories to the Manager repo directory, and replays the session through `/api/opencode-proxy/sync/replay`. The local session is retained.
- `--force` skips the dirty-working-tree check on `pull` and the safety bail on `push`.
- `--create` (on `push`) creates a new Manager repo when no `origin` match is found.
- `--yes` skips the interactive create confirmation.
+15 -7
View File
@@ -61,18 +61,26 @@ 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.
## OpenCode plugin
## OpenCode TUI plugin
The package default export is an OpenCode plugin entrypoint. Importing the
plugin performs a best-effort local `ocm` symlink install and then returns an
empty plugin object.
The package exposes an OpenCode TUI plugin at
`@opencode-manager/ocm-cli/tui`. It registers `/ocm-move`, which keeps the
local session and copies the active session to the Manager after pushing the
current repo state. Use it from inside an OpenCode session after `ocm login`
and after the repo already exists on the Manager (`ocm push --create` if
needed).
```ts
import ocm from '@opencode-manager/ocm-cli'
Enable it in `tui.json`:
export default [ocm]
```jsonc
{
"plugin": ["@opencode-manager/ocm-cli/tui"]
}
```
The `ocm` binary is installed via the package `postinstall` (or `bin` field on
global installs); the plugin surface is TUI-only.
## Requirements
- `opencode` available on `PATH`
+21 -34
View File
@@ -9,6 +9,7 @@ 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 { type ManagerRepo, fetchRepos, toRemoteRepoSummaries } from '../src/manager-repos.js'
import packageJson from '../package.json' with { type: 'json' }
const VERSION = packageJson.version
@@ -30,16 +31,6 @@ Usage:
ocm --help Show this help
`
interface ManagerRepo {
repoId: number
name: string
branch: string | null
cloneStatus: string
directory: string
projectId?: string | null
extra: { repoId: number; localPath: string; fullPath: string }
}
function die(msg: string, code = 1): never {
process.stderr.write(`ocm: ${msg}\n`)
process.exit(code)
@@ -124,18 +115,24 @@ function requireToken(state: OcmState): string {
return token
}
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}`)
async function warmUpInstance(managerUrl: string, token: string, directory: string): Promise<void> {
const url = `${managerUrl}/api/opencode-proxy/session?directory=${encodeURIComponent(directory)}`
for (let attempt = 1; attempt <= 3; attempt++) {
try {
const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } })
if (res.ok) {
await res.text()
return
}
} catch {
/* retry */
}
await new Promise((resolve) => setTimeout(resolve, attempt * 500))
}
const data = (await res.json()) as { workspaces: ManagerRepo[] }
return data.workspaces
}
function attach(managerUrl: string, token: string, repo: ManagerRepo): never {
async function attach(managerUrl: string, token: string, repo: ManagerRepo): Promise<never> {
await warmUpInstance(managerUrl, token, repo.directory)
const proxyUrl = `${managerUrl}/api/opencode-proxy`
const args = [
'attach',
@@ -271,7 +268,7 @@ async function cmdUse(args: string[]): Promise<void> {
lastRepoBranch: repo.branch,
})
attach(state.managerUrl, token, repo)
await attach(state.managerUrl, token, repo)
}
async function cmdDefault(): Promise<void> {
@@ -304,13 +301,13 @@ async function cmdDefault(): Promise<void> {
lastRepoDir: repo.directory,
lastRepoBranch: repo.branch,
})
attach(state.managerUrl, token, toManagerRepo(repo))
await attach(state.managerUrl, token, toManagerRepo(repo))
return
}
case 'last': {
const repo = result.repo
info(`attaching to ${repo.name} (last used)`)
attach(state.managerUrl, token, toManagerRepo(repo))
await attach(state.managerUrl, token, toManagerRepo(repo))
return
}
case 'cwd-ambiguous': {
@@ -364,12 +361,7 @@ export async function cmdPush(args: string[]): Promise<void> {
const api = new ManagerApi(state.managerUrl, token)
const repos = await fetchRepos(state.managerUrl, token)
const remotes: RemoteRepoSummary[] = repos.map((r) => ({
repoId: r.repoId,
name: r.name,
projectId: r.projectId ?? null,
branch: r.branch,
}))
const remotes: RemoteRepoSummary[] = toRemoteRepoSummaries(repos)
const plan = await prepareMirror(process.cwd(), remotes)
@@ -447,12 +439,7 @@ async function cmdPull(args: string[]): Promise<void> {
const api = new ManagerApi(state.managerUrl, token)
const repos = await fetchRepos(state.managerUrl, token)
const remotes: RemoteRepoSummary[] = repos.map((r) => ({
repoId: r.repoId,
name: r.name,
projectId: r.projectId ?? null,
branch: r.branch,
}))
const remotes: RemoteRepoSummary[] = toRemoteRepoSummaries(repos)
const plan = await prepareMirror(process.cwd(), remotes)
+7 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@opencode-manager/ocm-cli",
"version": "0.2.0",
"version": "0.2.1",
"description": "OpenCode Manager CLI: attach a local OpenCode TUI to a Manager-hosted repo.",
"license": "MIT",
"repository": {
@@ -9,10 +9,12 @@
"directory": "ocm-cli"
},
"type": "module",
"main": "./dist/plugin.js",
"oc-plugin": [
"tui"
],
"exports": {
".": {
"import": "./dist/plugin.js"
"./tui": {
"import": "./dist/tui.js"
}
},
"bin": {
@@ -32,10 +34,10 @@
"test:watch": "vitest",
"prepublishOnly": "bun scripts/build.ts"
},
"dependencies": {},
"devDependencies": {
"@eslint/js": "^9.36.0",
"@opencode-manager/shared": "workspace:*",
"@types/bun": "^1.3.14",
"@types/node": "^22.0.0",
"eslint": "^9.39.1",
"typescript": "^5.5.0",
+15 -25
View File
@@ -6,37 +6,27 @@ const dist = join(root, 'dist')
rmSync(dist, { recursive: true, force: true })
console.log('Bundling ocm CLI...')
const cliResult = await Bun.build({
entrypoints: [join(root, 'bin', 'ocm.ts')],
outdir: dist,
target: 'node',
format: 'esm',
naming: { entry: 'ocm.js' },
})
async function bundleEntry(label: string, entrypoint: string, outputName: string): Promise<void> {
console.log(`Bundling ${label}...`)
const result = await Bun.build({
entrypoints: [join(root, entrypoint)],
outdir: dist,
target: 'node',
format: 'esm',
external: ['bun:sqlite'],
naming: { entry: outputName },
})
if (!cliResult.success) {
for (const log of cliResult.logs) {
if (result.success) return
for (const log of result.logs) {
console.error(log)
}
process.exit(1)
}
console.log('Bundling opencode plugin entry...')
const pluginResult = await Bun.build({
entrypoints: [join(root, 'src', 'plugin.ts')],
outdir: dist,
target: 'node',
format: 'esm',
naming: { entry: 'plugin.js' },
})
if (!pluginResult.success) {
for (const log of pluginResult.logs) {
console.error(log)
}
process.exit(1)
}
await bundleEntry('ocm CLI', join('bin', 'ocm.ts'), 'ocm.js')
await bundleEntry('TUI plugin entry', join('src', 'tui-plugin.ts'), 'tui.js')
const ocmJsPath = join(dist, 'ocm.js')
const ocmJsContent = readFileSync(ocmJsPath, 'utf-8')
+15 -14
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env node
import { existsSync, mkdirSync, symlinkSync, unlinkSync, lstatSync, readlinkSync, chmodSync } from 'node:fs'
import { existsSync, mkdirSync, symlinkSync, unlinkSync, lstatSync, readlinkSync, chmodSync, writeFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join, resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -26,16 +26,24 @@ if (process.env.npm_config_global === 'true' || process.env.npm_config_global ==
}
const binDir = join(homedir(), '.local', 'bin')
const link = join(binDir, 'ocm')
const noticeDir = join(homedir(), '.config', 'opencode-manager')
const noticeFile = join(noticeDir, 'install-notice.json')
function writeInstallNotice(pathMissing) {
try {
mkdirSync(noticeDir, { recursive: true })
writeFileSync(noticeFile, JSON.stringify({ link, binDir, pathMissing }, null, 2), { mode: 0o600 })
} catch {
}
}
try {
mkdirSync(binDir, { recursive: true })
} catch (err) {
process.stderr.write(`ocm-cli: cannot create ${binDir}: ${err.message}\n`)
} catch {
process.exit(0)
}
const link = join(binDir, 'ocm')
try {
const stat = lstatSync(link)
if (stat.isSymbolicLink()) {
@@ -44,7 +52,6 @@ try {
}
unlinkSync(link)
} else {
process.stderr.write(`ocm-cli: ${link} exists and is not a symlink; leaving alone\n`)
process.exit(0)
}
} catch {
@@ -53,15 +60,9 @@ try {
try {
symlinkSync(target, link)
} catch (err) {
process.stderr.write(`ocm-cli: failed to symlink ${link}: ${err.message}\n`)
} catch {
process.exit(0)
}
process.stdout.write(`ocm installed at ${link}\n`)
const path = process.env.PATH ?? ''
if (!path.split(':').includes(binDir)) {
process.stdout.write(`note: ${binDir} is not on your PATH. Add to your shell rc:\n`)
process.stdout.write(` export PATH="${binDir}:$PATH"\n`)
}
writeInstallNotice(!path.split(':').includes(binDir))
+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> }
+52
View File
@@ -0,0 +1,52 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync, utimesSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { resolveOpencodeDbPath } from '../src/local-history.js'
describe('resolveOpencodeDbPath', () => {
let dataHome: string
let dataDir: string
const savedEnv = { XDG_DATA_HOME: process.env.XDG_DATA_HOME, OPENCODE_DB: process.env.OPENCODE_DB }
beforeEach(() => {
dataHome = mkdtempSync(join(tmpdir(), 'ocm-dbpath-'))
dataDir = join(dataHome, 'opencode')
mkdirSync(dataDir)
process.env.XDG_DATA_HOME = dataHome
delete process.env.OPENCODE_DB
})
afterEach(() => {
rmSync(dataHome, { recursive: true, force: true })
if (savedEnv.XDG_DATA_HOME === undefined) delete process.env.XDG_DATA_HOME
else process.env.XDG_DATA_HOME = savedEnv.XDG_DATA_HOME
if (savedEnv.OPENCODE_DB === undefined) delete process.env.OPENCODE_DB
else process.env.OPENCODE_DB = savedEnv.OPENCODE_DB
})
it('honours an absolute OPENCODE_DB override', () => {
process.env.OPENCODE_DB = '/tmp/custom.db'
expect(resolveOpencodeDbPath()).toBe('/tmp/custom.db')
})
it('resolves a relative OPENCODE_DB override against the data dir', () => {
process.env.OPENCODE_DB = 'custom.db'
expect(resolveOpencodeDbPath()).toBe(join(dataDir, 'custom.db'))
})
it('prefers the default opencode.db when present', () => {
writeFileSync(join(dataDir, 'opencode.db'), '', { flag: 'w' })
writeFileSync(join(dataDir, 'opencode-dev.db'), '')
expect(resolveOpencodeDbPath()).toBe(join(dataDir, 'opencode.db'))
})
it('falls back to the newest channel variant', () => {
const older = join(dataDir, 'opencode-old.db')
const newer = join(dataDir, 'opencode-dev.db')
writeFileSync(older, '')
writeFileSync(newer, '')
utimesSync(older, new Date('2024-01-01'), new Date('2024-01-01'))
expect(resolveOpencodeDbPath()).toBe(newer)
})
})
+319
View File
@@ -0,0 +1,319 @@
import { describe, it, expect, vi } from 'vitest'
import { collectSessionEvents, rewriteEventsForRemote, transferSession, planReplayBatches, type HistoryEventRow, type ReplayEvent, type TransferDeps } from '../src/session-move.js'
describe('collectSessionEvents', () => {
it('collects a session\'s events in seq order with remapped aggregateID', () => {
const rows: HistoryEventRow[] = [
{ id: 'e3', aggregate_id: 'ses_a', seq: 2, type: 'append', data: { text: 'c' } },
{ id: 'e1', aggregate_id: 'ses_a', seq: 0, type: 'append', data: { text: 'a' } },
{ id: 'e2', aggregate_id: 'ses_a', seq: 1, type: 'append', data: { text: 'b' } },
{ id: 'e4', aggregate_id: 'ses_b', seq: 0, type: 'append', data: { text: 'x' } },
]
const result = collectSessionEvents(rows, 'ses_a')
expect(result).toEqual({
kind: 'ok',
events: [
{ id: 'e1', aggregateID: 'ses_a', seq: 0, type: 'append', data: { text: 'a' } },
{ id: 'e2', aggregateID: 'ses_a', seq: 1, type: 'append', data: { text: 'b' } },
{ id: 'e3', aggregateID: 'ses_a', seq: 2, type: 'append', data: { text: 'c' } },
],
})
})
it('returns empty when the session has no events', () => {
const rows: HistoryEventRow[] = [
{ id: 'e1', aggregate_id: 'other', seq: 0, type: 'append', data: {} },
]
const result = collectSessionEvents(rows, 'unknown')
expect(result).toEqual({ kind: 'empty' })
})
it('detects a gap in the sequence', () => {
const rows: HistoryEventRow[] = [
{ id: 'e1', aggregate_id: 'ses_a', seq: 0, type: 'append', data: {} },
{ id: 'e2', aggregate_id: 'ses_a', seq: 1, type: 'append', data: {} },
{ id: 'e3', aggregate_id: 'ses_a', seq: 3, type: 'append', data: {} },
]
const result = collectSessionEvents(rows, 'ses_a')
expect(result).toEqual({ kind: 'gap', missingSeq: 2 })
})
it('detects a gap when sequence does not start at 0', () => {
const rows: HistoryEventRow[] = [
{ id: 'e1', aggregate_id: 'ses_a', seq: 1, type: 'append', data: {} },
{ id: 'e2', aggregate_id: 'ses_a', seq: 2, type: 'append', data: {} },
]
const result = collectSessionEvents(rows, 'ses_a')
expect(result).toEqual({ kind: 'gap', missingSeq: 0 })
})
})
describe('rewriteEventsForRemote', () => {
const ctx = {
localRoot: '/Users/x/repo',
remoteRoot: '/workspace/repos/repo',
}
it('rewrites session.created info directory to the remote root', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.created.1',
data: { info: { directory: '/Users/x/repo' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo' })
})
it('rewrites session.updated info directory to the remote root', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.updated.2',
data: { info: { directory: '/Users/x/repo' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo' })
})
it('preserves subdirectories under the repo root', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.created.1',
data: { info: { directory: '/Users/x/repo/packages/app' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo/packages/app' })
})
it('rewrites session.next.moved location directory', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.next.moved.1',
data: { location: { directory: '/Users/x/repo/src' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.location).toEqual({ directory: '/workspace/repos/repo/src' })
})
it('strips workspaceID from info', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.created.1',
data: { info: { directory: '/Users/x/repo', workspaceID: 'ws_abc' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo' })
expect('workspaceID' in result[0]!.data.info).toBe(false)
})
it('strips workspaceID from location on moved events', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.next.moved.1',
data: { location: { directory: '/Users/x/repo', workspaceID: 'ws_abc' } },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.location).toEqual({ directory: '/workspace/repos/repo' })
expect('workspaceID' in result[0]!.data.location).toBe(false)
})
it('coerces ISO time string in data.timestamp to epoch millis (per 686c820d)', () => {
const iso = '2026-07-01T10:00:00.000Z'
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.next.agent.switched.1',
data: { timestamp: iso, agent: 'code' },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.timestamp).toBe(Date.parse(iso))
expect(typeof result[0]!.data.timestamp).toBe('number')
})
it('leaves already-numeric timestamp untouched', () => {
const epoch = 1778974142967
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.next.model.switched.1',
data: { timestamp: epoch },
},
]
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data.timestamp).toBe(epoch)
})
it('leaves unrelated events untouched without mutating input', () => {
const events: ReplayEvent[] = [
{
id: 'e1', aggregateID: 'ses_a', seq: 0,
type: 'session.next.step.ended.2',
data: { sessionID: 'ses_a', step: { kind: 'code' } },
},
]
const frozen = JSON.parse(JSON.stringify(events))
const result = rewriteEventsForRemote(events, ctx)
expect(result[0]!.data).toEqual(frozen[0]!.data)
expect(events).toEqual(frozen)
})
})
describe('planReplayBatches', () => {
it('splits events into batches of batchSize (default 10)', () => {
const events = Array.from({ length: 25 }, (_, i) => ({
id: `e${i}`, aggregateID: 'ses_a', seq: i, type: 'append', data: {},
}))
const batches = planReplayBatches(events)
expect(batches).toHaveLength(3)
expect(batches[0]).toHaveLength(10)
expect(batches[1]).toHaveLength(10)
expect(batches[2]).toHaveLength(5)
expect(batches[0]![0]!.seq).toBe(0)
expect(batches[1]![0]!.seq).toBe(10)
expect(batches[2]![0]!.seq).toBe(20)
})
it('returns a single batch when events fit within batchSize', () => {
const events = Array.from({ length: 3 }, (_, i) => ({
id: `e${i}`, aggregateID: 'ses_a', seq: i, type: 'append', data: {},
}))
const batches = planReplayBatches(events, 10)
expect(batches).toHaveLength(1)
expect(batches[0]).toHaveLength(3)
})
it('returns empty array for empty events', () => {
expect(planReplayBatches([])).toEqual([])
})
})
function makeHistoryEvents(sessionID: string, count: number, opts: { root?: string; types?: string[] } = {}): HistoryEventRow[] {
const root = opts.root ?? '/Users/x/repo'
const types = opts.types ?? ['session.created.1']
return Array.from({ length: count }, (_, i) => ({
id: `e${i}`,
aggregate_id: sessionID,
seq: i,
type: types[Math.min(i, types.length - 1)]!,
data: { info: { directory: root }, timestamp: '2026-07-01T10:00:00.000Z' },
}))
}
describe('transferSession', () => {
const input = { sessionID: 'ses_a', localRoot: '/Users/x/repo', remoteDirectory: '/workspace/repos/repo' }
it('moves a session by replaying its full history in ordered batches', async () => {
const history = makeHistoryEvents('ses_a', 25)
const replayCalls: { dir: string; events: ReplayEvent[] }[] = []
const deps: TransferDeps = {
fetchLocalHistory: vi.fn().mockResolvedValue(history),
replayEvents: vi.fn().mockImplementation(async (dir: string, events: ReplayEvent[]) => {
replayCalls.push({ dir, events })
return { sessionID: 'ses_a' }
}),
}
const result = await transferSession(input, deps)
expect(result).toEqual({ kind: 'moved', sessionID: 'ses_a', replayedEvents: 25 })
expect(replayCalls).toHaveLength(3)
expect(replayCalls[0]!.dir).toBe('/workspace/repos/repo')
expect(replayCalls[0]!.events).toHaveLength(10)
expect(replayCalls[0]!.events[0]!.seq).toBe(0)
expect(replayCalls[1]!.events).toHaveLength(10)
expect(replayCalls[2]!.events).toHaveLength(5)
expect(replayCalls[0]!.events[0]!.data.info.directory).toBe('/workspace/repos/repo')
})
it('reports a missing session', async () => {
const deps: TransferDeps = {
fetchLocalHistory: vi.fn().mockResolvedValue([]),
replayEvents: vi.fn(),
}
const result = await transferSession(input, deps)
expect(result).toEqual({ kind: 'not-found' })
expect(deps.replayEvents).not.toHaveBeenCalled()
})
it('refuses to transfer corrupt history', async () => {
const rows: HistoryEventRow[] = [
{ id: 'e0', aggregate_id: 'ses_a', seq: 0, type: 'session.created.1', data: {} },
{ id: 'e2', aggregate_id: 'ses_a', seq: 2, type: 'session.updated.2', data: {} },
]
const deps: TransferDeps = {
fetchLocalHistory: vi.fn().mockResolvedValue(rows),
replayEvents: vi.fn(),
}
const result = await transferSession(input, deps)
expect(result).toEqual({ kind: 'corrupt-history', missingSeq: 1 })
expect(deps.replayEvents).not.toHaveBeenCalled()
})
it('surfaces replay failure and stops', async () => {
const history = makeHistoryEvents('ses_a', 25)
let callCount = 0
const deps: TransferDeps = {
fetchLocalHistory: vi.fn().mockResolvedValue(history),
replayEvents: vi.fn().mockImplementation(async () => {
callCount++
if (callCount === 2) throw new Error('Replay diverged')
return { sessionID: 'ses_a' }
}),
}
const result = await transferSession(input, deps)
expect(result).toEqual({ kind: 'replay-failed', message: 'Replay diverged' })
expect(callCount).toBe(2)
})
})
+1 -1
View File
@@ -4,7 +4,7 @@
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM"],
"types": ["node"],
"types": ["node", "bun"],
"strict": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
+18 -1
View File
@@ -281,6 +281,9 @@ importers:
'@opencode-manager/shared':
specifier: workspace:*
version: link:../shared
'@types/bun':
specifier: ^1.3.14
version: 1.3.14
'@types/node':
specifier: ^22.0.0
version: 22.19.19
@@ -1594,6 +1597,9 @@ packages:
'@types/bun@1.3.10':
resolution: {integrity: sha512-0+rlrUrOrTSskibryHbvQkDOWRJwJZqZlxrUs1u4oOoTln8+WIXBPmAuCF35SWB2z4Zl3E84Nl/D0P7803nigQ==}
'@types/bun@1.3.14':
resolution: {integrity: sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw==}
'@types/chai@5.2.3':
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
@@ -2098,6 +2104,9 @@ packages:
bun-types@1.3.10:
resolution: {integrity: sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg==}
bun-types@1.3.14:
resolution: {integrity: sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ==}
cac@6.7.14:
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
engines: {node: '>=8'}
@@ -5434,6 +5443,10 @@ snapshots:
dependencies:
bun-types: 1.3.10
'@types/bun@1.3.14':
dependencies:
bun-types: 1.3.14
'@types/chai@5.2.3':
dependencies:
'@types/deep-eql': 4.0.2
@@ -5794,7 +5807,7 @@ snapshots:
sirv: 3.0.2
tinyglobby: 0.2.15
tinyrainbow: 2.0.0
vitest: 3.2.4(@types/debug@4.1.12)(@types/node@24.10.4)(@vitest/ui@3.2.4)(jiti@2.6.1)(jsdom@27.4.0)(lightningcss@1.30.2)(terser@5.46.0)(yaml@2.9.0)
vitest: 3.2.4(@types/debug@4.1.12)(@types/node@22.19.19)(@vitest/ui@3.2.4)(jiti@2.6.1)(jsdom@27.4.0)(lightningcss@1.30.2)(terser@5.46.0)(yaml@2.9.0)
'@vitest/utils@3.2.4':
dependencies:
@@ -6009,6 +6022,10 @@ snapshots:
dependencies:
'@types/node': 24.10.4
bun-types@1.3.14:
dependencies:
'@types/node': 24.10.4
cac@6.7.14: {}
callsites@3.1.0: {}