feat(opencode): add ocm install, schedule agent fallback, and session move guards

This commit is contained in:
Chris Scott committed 2026-09-26 13:11:20 -04:00
1 parent 53e3a0227e
commit eff10d7829
22 files changed
+845 -64

No files matched your search

+10
View File
@@ -32,6 +32,15 @@ The package exposes the `ocm` binary and an OpenCode plugin entrypoint. Global
installs link the binary through the package manager. Local workspace installs
also create a best-effort `~/.local/bin/ocm` symlink.
The package is also self-contained for a vendored install with no package
manager. `ocm install` copies the package into
`~/.config/opencode/plugin/ocm-cli`, registers `./plugin/ocm-cli/dist` in
`cli.json`, and links `ocm` at `~/.local/bin/ocm`. Run it without an existing
`ocm` via `pnpm dlx @opencode-manager/ocm-cli install`, or from a local build
via `./scripts/install.sh`. The command is idempotent, so re-run it to upgrade.
Use the `dist` directory, not `dist/tui.js`: OpenCode 2 loads `tui.js` from
directory entries and skips file entries.
## Login
```bash
@@ -71,6 +80,7 @@ ocm list
ocm use <repoId|name>
ocm push [repoId] [--force] [--create] [--yes] [--full]
ocm pull [repoId] [--force] [--full]
ocm install [--dir <path>] [--force] [--no-link]
ocm logout
```
+54 -2
View File
@@ -1,6 +1,8 @@
import { spawn, spawnSync } from 'child_process'
import { basename } from 'path'
import { readState, writeState, clearState, getStatePath, type OcmState } from '../src/state.js'
import { basename, dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
import { readState, writeState, clearState, getStatePath, writeInstallNotice, type OcmState } from '../src/state.js'
import { installVendoredOcm, resolveOpenCodeConfigDir, InstallError, OCM_PLUGIN_SPEC } from '../src/vendor-install.js'
import { getToken, setToken, deleteToken, hasStoredToken, describeTokenStore, describeTokenWriteTarget, envToken, TOKEN_ENV, TokenStoreError } from '../src/internal-token-store.js'
import { ManagerApi, ManagerApiError } from '../src/manager-api.js'
import { mirrorUp, mirrorDown, mirrorUpFast, mirrorDownFast, prepareMirror, MirrorAbort, checkPushDivergence, checkPullDivergence, describePushDivergence } from '../src/mirror.js'
@@ -28,6 +30,8 @@ Usage:
Mirror $PWD to the matching Manager repo (fast patch sync by default)
ocm pull [repoId] [--force] [--full]
Mirror the matching Manager repo over $PWD (fast patch sync by default)
ocm install [--dir <path>] [--force] [--no-link]
Vendor the CLI + TUI plugin into the OpenCode config dir
ocm --version Show the installed ocm version
ocm --help Show this help
`
@@ -515,6 +519,51 @@ async function cmdPull(args: string[]): Promise<void> {
info(`pulled ${plan.matched[0]!.name} -> ${plan.repoRoot}`)
}
function getSourceDistDir(): string {
return resolve(dirname(fileURLToPath(import.meta.url)), '..', 'dist')
}
export async function cmdInstall(args: string[]): Promise<void> {
let configDir: string | undefined
let force = false
let link = true
for (let i = 0; i < args.length; i++) {
const arg = args[i]!
if (arg === '--force') force = true
else if (arg === '--no-link') link = false
else if (arg === '--dir') {
configDir = args[++i]
if (!configDir) die('usage: ocm install [--dir <path>] [--force] [--no-link]')
} else if (arg.startsWith('--dir=')) {
configDir = arg.slice('--dir='.length)
} else {
die(`unknown option: ${arg}. run \`ocm --help\``)
}
}
const resolvedConfigDir = configDir ?? resolveOpenCodeConfigDir()
let result
try {
result = installVendoredOcm({ sourceDistDir: getSourceDistDir(), configDir: resolvedConfigDir, force, link })
} catch (err) {
if (err instanceof InstallError) die(err.message)
throw err
}
info(`vendored ocm into ${result.pluginDir}`)
info(result.copied.length > 0 ? `copied: ${result.copied.join(', ')}` : 'package files already up to date')
info(result.configChanged ? `registered ${OCM_PLUGIN_SPEC} in ${result.configFile}` : `plugin already registered in ${result.configFile}`)
if (result.binLink === null) {
info('skipped the ocm symlink (--no-link)')
} else {
writeInstallNotice({ link: result.binLink, binDir: dirname(result.binLink), pathMissing: result.pathMissing })
info(result.binLinkChanged ? `linked ${result.binLink}` : `already linked at ${result.binLink}`)
if (result.pathMissing) info('note: add export PATH="$HOME/.local/bin:$PATH" to your shell rc')
}
}
async function main(): Promise<void> {
const [, , cmd, ...rest] = process.argv
@@ -556,6 +605,9 @@ async function main(): Promise<void> {
case 'pull':
await cmdPull(rest)
break
case 'install':
await cmdInstall(rest)
break
default:
die(`unknown command: ${cmd}. run \`ocm --help\``)
}
+2
View File
@@ -39,6 +39,7 @@
"files": [
"dist",
"README.md",
"scripts/install.sh",
"scripts/postinstall.mjs"
],
"scripts": {
@@ -60,6 +61,7 @@
"@types/bun": "^1.3.14",
"@types/node": "^22.0.0",
"eslint": "^9.39.1",
"jsonc-parser": "^3.3.1",
"solid-js": "1.9.12",
"typescript": "^5.5.0",
"typescript-eslint": "^8.45.0",
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cli="$root/dist/ocm.js"
if [ ! -f "$cli" ]; then
echo "ocm: $cli not found; build the package first (pnpm --filter @opencode-manager/ocm-cli build)" >&2
exit 1
fi
exec node "$cli" install "$@"
+1 -1
View File
@@ -10,7 +10,7 @@ function isPermissionError(err: unknown): boolean {
return code === 'EACCES' || code === 'EPERM'
}
function removeQuietly(filePath: string): void {
export function removeQuietly(filePath: string): void {
try {
unlinkSync(filePath)
} catch {
+13 -2
View File
@@ -1,7 +1,9 @@
import { createOpenCodeApi } from '@opencode-manager/shared/opencode'
import { createOpenCodeApi, isSessionNotFoundError } from '@opencode-manager/shared/opencode'
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
import { repoProxyBaseUrl } from './repo-proxy.js'
export type ManagerSessionTransfer = ReturnType<typeof createManagerSessionTransfer>
export function createManagerSessionTransfer(managerUrl: string, token: string) {
const api = createOpenCodeApi({
baseUrl: repoProxyBaseUrl(managerUrl),
@@ -9,6 +11,15 @@ export function createManagerSessionTransfer(managerUrl: string, token: string)
})
return {
sessionExists: async (sessionID: string): Promise<boolean> => {
try {
await api.session.get({ sessionID })
return true
} catch (err) {
if (isSessionNotFoundError(err)) return false
throw err
}
},
importSession: async (remoteDirectory: string, data: SessionTransferData): Promise<{ sessionID: string }> => {
const session = await api.session.import({
info: data.info,
@@ -17,6 +28,6 @@ export function createManagerSessionTransfer(managerUrl: string, token: string)
})
return { sessionID: session.id }
},
addReminder: (sessionID: string, text: string) => api.session.synthetic({ sessionID, text }),
addReminder: (sessionID: string, text: string) => api.session.synthetic({ sessionID, text, resume: false }),
}
}
+8
View File
@@ -45,6 +45,14 @@ export function clearState(): void {
}
}
export function writeInstallNotice(notice: InstallNotice): void {
try {
writeJsonFileAtomic(INSTALL_NOTICE_FILE, notice)
} catch {
return
}
}
export function readInstallNotice(): InstallNotice | null {
let parsed: InstallNotice | null
try {
+38 -14
View File
@@ -10,6 +10,7 @@ import type { MirrorPlan, RemoteRepoSummary } from './mirror.js'
import { getBranchName } from './local-repo.js'
import { transferSession, moveReminderText } from './session-move.js'
import { createManagerSessionTransfer } from './remote-session.js'
import type { ManagerSessionTransfer } from './remote-session.js'
import { confirmDialog, selectDialog } from './tui-dialogs.js'
import { setPendingWarp, runPendingWarp } from './warp.js'
import { pushPhaseProgress, importProgress } from './move-progress.js'
@@ -20,19 +21,26 @@ export type MoveProgressSetter = (progress: MoveProgress | null) => void
export async function setupOcm(context: Context, setMoveProgress: MoveProgressSetter): Promise<() => void> {
showInstallNotice(context)
context.keymap.layer(() => ({
commands: [
{
id: 'ocm.session.move',
title: 'Move session to Manager',
description: 'Push repo state and move this session to OpenCode Manager',
group: 'OpenCode Manager',
palette: true,
slash: { name: 'ocm-move' },
run: () => runSessionMove(context, setMoveProgress),
},
],
}))
context.ui.slot({
append: 'app',
render: () => {
context.keymap.layer(() => ({
mode: 'global',
commands: [
{
id: 'ocm.session.move',
title: 'Move session to Manager',
description: 'Push repo state and move this session to OpenCode Manager',
group: 'OpenCode Manager',
palette: true,
slash: { name: 'ocm-move' },
run: () => runSessionMove(context, setMoveProgress),
},
],
}))
return null
},
})
return () => runPendingWarp()
}
@@ -50,6 +58,16 @@ function showInstallNotice(context: Context): void {
})
}
async function describeMoveBlocker(transfer: ManagerSessionTransfer, sessionID: string, parentID: string | undefined): Promise<string | null> {
if (await transfer.sessionExists(sessionID)) {
return `Session ${sessionID} is already on the Manager, so it cannot be moved again. Nothing was pushed. Run \`ocm\` to attach to it.`
}
if (parentID && !(await transfer.sessionExists(parentID))) {
return `This is a subagent session and its parent ${parentID} is not on the Manager. Move the parent session first. Nothing was pushed.`
}
return null
}
async function describeRemoteDiscard(repoRoot: string, managerApi: ManagerApi, repoId: number): Promise<string[]> {
try {
return describePushDivergence(await checkPushDivergence(repoRoot, managerApi, repoId))
@@ -134,6 +152,13 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
await warmRepoProxy(state.managerUrl, token, matchedRepoId)
const transfer = createManagerSessionTransfer(state.managerUrl, token)
const blocker = await describeMoveBlocker(transfer, sessionID, session.parentID)
if (blocker) {
context.ui.toast.show({ variant: 'error', message: blocker })
return
}
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)
@@ -158,7 +183,6 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
})
const remoteDirectory = pushed.fullPath
const transfer = createManagerSessionTransfer(state.managerUrl, token)
const result = await transferSession(
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
{
+208
View File
@@ -0,0 +1,208 @@
import { chmodSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'fs'
import { randomBytes } from 'crypto'
import { homedir } from 'os'
import { dirname, join, resolve } from 'path'
import { applyEdits, modify, parse as parseJsonc, type ParseError } from 'jsonc-parser/lib/esm/main.js'
import { removeQuietly } from './json-store.js'
export const OCM_PLUGIN_NAME = 'ocm-cli'
export const OCM_PLUGIN_SPEC = './plugin/ocm-cli/dist'
const CLI_CONFIG_SCHEMA = 'https://opencode.ai/v2/cli.json'
const COPIED_ENTRIES = ['dist', 'package.json', 'README.md', 'LICENSE'] as const
export class InstallError extends Error {
constructor(message: string) {
super(message)
this.name = 'InstallError'
}
}
export interface VendorPaths {
pluginDir: string
pluginDistDir: string
cliConfigFile: string
binDir: string
binLink: string
}
export interface InstallOptions {
sourceDistDir: string
configDir: string
home?: string
force?: boolean
link?: boolean
}
export interface InstallResult {
pluginDir: string
copied: string[]
configFile: string
configChanged: boolean
binLink: string | null
binLinkChanged: boolean
pathMissing: boolean
}
export function resolveOpenCodeConfigDir(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
const override = env.OPENCODE_CONFIG_DIR?.trim()
if (override) return override
const base = env.XDG_CONFIG_HOME?.trim() || join(home, '.config')
return join(base, 'opencode')
}
export function resolveVendorPaths(configDir: string, home = homedir()): VendorPaths {
const pluginDir = join(configDir, 'plugin', OCM_PLUGIN_NAME)
const binDir = join(home, '.local', 'bin')
return {
pluginDir,
pluginDistDir: join(pluginDir, 'dist'),
cliConfigFile: join(configDir, 'cli.json'),
binDir,
binLink: join(binDir, 'ocm'),
}
}
function realPath(filePath: string): string {
try {
return realpathSync(filePath)
} catch {
return resolve(filePath)
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function pluginEntrySpec(entry: unknown): string | undefined {
if (typeof entry === 'string') return entry
if (Array.isArray(entry) && typeof entry[0] === 'string') return entry[0]
return undefined
}
export function addPluginToCliConfig(text: string | null, spec = OCM_PLUGIN_SPEC): { text: string; changed: boolean } {
if (!text || text.trim() === '') {
return { text: `${JSON.stringify({ $schema: CLI_CONFIG_SCHEMA, plugins: [spec] }, null, 2)}\n`, changed: true }
}
const errors: ParseError[] = []
const parsed = parseJsonc(text, errors, { allowTrailingComma: true, disallowComments: false })
if (errors.length > 0 || !isRecord(parsed)) {
throw new InstallError('cli.json is not valid JSONC; add the plugin entry manually')
}
const plugins = parsed.plugins
if (plugins !== undefined && !Array.isArray(plugins)) {
throw new InstallError('cli.json "plugins" is not an array; add the plugin entry manually')
}
if (Array.isArray(plugins) && plugins.some((entry) => pluginEntrySpec(entry) === spec)) {
return { text, changed: false }
}
const index = Array.isArray(plugins) ? plugins.length : 0
const edits = modify(text, ['plugins', index], spec, { formattingOptions: { tabSize: 2, insertSpaces: true } })
return { text: applyEdits(text, edits), changed: true }
}
function copyEntry(from: string, to: string): boolean {
if (!existsSync(from)) return false
if (realPath(from) === realPath(to)) return false
rmSync(to, { recursive: true, force: true })
cpSync(from, to, { recursive: true })
return true
}
function writeTextAtomic(filePath: string, text: string): void {
const tmp = `${filePath}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`
let mode: number | undefined
try {
mode = statSync(filePath).mode
} catch {
mode = undefined
}
try {
writeFileSync(tmp, text, { encoding: 'utf-8', ...(mode === undefined ? {} : { mode }) })
renameSync(tmp, filePath)
} catch (err) {
removeQuietly(tmp)
throw err
}
}
function linkBinary(paths: VendorPaths, force: boolean): { changed: boolean; pathMissing: boolean } {
const target = join(paths.pluginDistDir, 'ocm.js')
if (!existsSync(target)) {
throw new InstallError(`vendored ocm.js missing at ${target}; re-run the install`)
}
chmodSync(target, 0o755)
mkdirSync(paths.binDir, { recursive: true })
let changed = false
let existing: ReturnType<typeof lstatSync> | undefined
try {
existing = lstatSync(paths.binLink)
} catch {
existing = undefined
}
if (existing?.isSymbolicLink()) {
if (realPath(paths.binLink) !== realPath(target)) {
unlinkSync(paths.binLink)
symlinkSync(target, paths.binLink)
changed = true
}
} else if (existing) {
if (!force) {
throw new InstallError(`${paths.binLink} exists and is not a symlink; re-run with --force to replace it`)
}
rmSync(paths.binLink, { force: true })
symlinkSync(target, paths.binLink)
changed = true
} else {
symlinkSync(target, paths.binLink)
changed = true
}
const path = process.env.PATH ?? ''
return { changed, pathMissing: !path.split(':').includes(paths.binDir) }
}
export function installVendoredOcm(options: InstallOptions): InstallResult {
const home = options.home ?? homedir()
const force = options.force === true
const link = options.link !== false
const paths = resolveVendorPaths(options.configDir, home)
const sourceDistDir = resolve(options.sourceDistDir)
if (!existsSync(join(sourceDistDir, 'ocm.js')) || !existsSync(join(sourceDistDir, 'tui.js'))) {
throw new InstallError(`package build not found at ${sourceDistDir}; build or unpack the package first`)
}
const sourceRoot = dirname(sourceDistDir)
const copied: string[] = []
for (const entry of COPIED_ENTRIES) {
const from = entry === 'dist' ? sourceDistDir : join(sourceRoot, entry)
if (copyEntry(from, join(paths.pluginDir, entry))) copied.push(entry)
}
const cliConfigFile = paths.cliConfigFile
let current: string | null = null
if (existsSync(cliConfigFile)) {
current = readFileSync(cliConfigFile, 'utf-8')
}
const patched = addPluginToCliConfig(current)
if (patched.changed) writeTextAtomic(cliConfigFile, patched.text)
const bin = link ? linkBinary(paths, force) : { changed: false, pathMissing: false }
return {
pluginDir: paths.pluginDir,
copied,
configFile: cliConfigFile,
configChanged: patched.changed,
binLink: link ? paths.binLink : null,
binLinkChanged: bin.changed,
pathMissing: bin.pathMissing,
}
}
+31
View File
@@ -53,5 +53,36 @@ describe('createManagerSessionTransfer', () => {
expect(String(url)).toBe('https://manager.example/api/opencode-proxy/api/session/ses_new/synthetic')
const body = JSON.parse(init.body as string) as Record<string, unknown>
expect(body.text).toBe('hello')
expect(body.resume).toBe(false)
})
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
}
it('reports an existing Manager session', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { data: { id: 'ses_a' } }))
vi.stubGlobal('fetch', fetchMock)
const transfer = createManagerSessionTransfer('https://manager.example', 'tok_123')
await expect(transfer.sessionExists('ses_a')).resolves.toBe(true)
expect(String(fetchMock.mock.calls[0]![0])).toBe('https://manager.example/api/opencode-proxy/api/session/ses_a')
})
it('reports a missing Manager session only for SessionNotFoundError', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse(404, { _tag: 'SessionNotFoundError', sessionID: 'ses_a', message: 'Session not found' })))
const transfer = createManagerSessionTransfer('https://manager.example', 'tok_123')
await expect(transfer.sessionExists('ses_a')).resolves.toBe(false)
})
it('rethrows other failures instead of treating the session as missing', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('Not Found', { status: 404 })))
const transfer = createManagerSessionTransfer('https://manager.example', 'tok_123')
await expect(transfer.sessionExists('ses_a')).rejects.toBeDefined()
})
})
+8
View File
@@ -121,6 +121,14 @@ describe('cli state file', () => {
expect(readInstallNotice()).toBeNull()
})
it('writes an install notice for the next TUI launch', async () => {
const { readInstallNotice, writeInstallNotice } = await loadState()
writeInstallNotice({ link: '/home/me/.local/bin/ocm', binDir: '/home/me/.local/bin', pathMissing: false })
expect(readInstallNotice()).toEqual({ link: '/home/me/.local/bin/ocm', binDir: '/home/me/.local/bin', pathMissing: false })
})
it('keeps an unreadable install notice instead of consuming it', async () => {
if (process.platform === 'win32' || process.getuid?.() === 0) return
const { readInstallNotice } = await loadState()
+90 -6
View File
@@ -102,31 +102,42 @@ function makeTransfer(): SessionTransferData {
} as unknown as SessionTransferData
}
function createFakeContext() {
function createFakeContext(session: { location: { directory: string }; parentID?: string } = { location: { directory: '/Users/x/repo' } }) {
const exportMock = vi.fn()
const confirm = vi.fn()
const select = vi.fn()
const toast = vi.fn()
const layer = vi.fn()
const dispatch = vi.fn()
const slot = vi.fn(() => () => undefined)
const context = {
ui: {
router: { current: () => ({ type: 'session', sessionID: 'ses_a' }) },
toast: { show: toast },
dialog: { confirm, select },
slot,
},
data: {
session: { get: () => ({ location: { directory: '/Users/x/repo' } }) },
session: { get: () => session },
},
keymap: { layer, dispatch },
client: { session: { export: exportMock } },
} as unknown as Context
return { context, exportMock, confirm, select, toast, layer, dispatch }
return { context, exportMock, confirm, select, toast, layer, dispatch, slot }
}
function stubTransfer(options: { importError?: Error; reminderError?: Error } = {}) {
function renderAppSlot(fake: ReturnType<typeof createFakeContext>) {
const claim = fake.slot.mock.calls.map((call) => (call as unknown[])[0] as { append?: string; render: () => unknown }).find((c) => c.append === 'app')!
claim.render()
}
function stubTransfer(options: { importError?: Error; reminderError?: Error; onManager?: string[]; existsError?: Error } = {}) {
const sessionExists = vi.fn(async (sessionID: string) => {
if (options.existsError) throw options.existsError
return (options.onManager ?? []).includes(sessionID)
})
const importSession = vi.fn(async () => {
mocks.calls.push('import')
if (options.importError) throw options.importError
@@ -136,8 +147,8 @@ function stubTransfer(options: { importError?: Error; reminderError?: Error } =
mocks.calls.push('synthetic')
if (options.reminderError) throw options.reminderError
})
mocks.createManagerSessionTransfer.mockReturnValue({ importSession, addReminder })
return { importSession, addReminder }
mocks.createManagerSessionTransfer.mockReturnValue({ sessionExists, importSession, addReminder })
return { sessionExists, importSession, addReminder }
}
function configureMove(fake: ReturnType<typeof createFakeContext>) {
@@ -177,6 +188,7 @@ function configureMove(fake: ReturnType<typeof createFakeContext>) {
async function invokeMove(fake: ReturnType<typeof createFakeContext>) {
await setupOcm(fake.context, vi.fn())
renderAppSlot(fake)
const factory = fake.layer.mock.calls[0]![0] as () => { commands: { id: string; run: () => Promise<void> }[] }
const command = factory().commands.find((entry) => entry.id === 'ocm.session.move')!
await command.run()
@@ -187,6 +199,23 @@ beforeEach(() => {
mocks.calls.length = 0
})
describe('setupOcm', () => {
it('registers commands from the app slot so the host keymap provider is mounted', async () => {
const fake = createFakeContext()
await setupOcm(fake.context, vi.fn())
expect(fake.layer).not.toHaveBeenCalled()
expect(fake.slot).toHaveBeenCalledWith(expect.objectContaining({ append: 'app' }))
renderAppSlot(fake)
expect(fake.layer).toHaveBeenCalledTimes(1)
const factory = fake.layer.mock.calls[0]![0] as () => { mode?: string }
expect(factory().mode).toBe('global')
})
})
describe('ocm.session.move command', () => {
it('exports, imports the rewritten transfer, then sends the synthetic reminder', async () => {
const fake = createFakeContext()
@@ -259,6 +288,61 @@ describe('ocm.session.move command', () => {
expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'success' }))
})
function expectNothingPushed(fake: ReturnType<typeof createFakeContext>, importSession: ReturnType<typeof vi.fn>) {
expect(mocks.mirrorTargetPlan).not.toHaveBeenCalled()
expect(fake.confirm).not.toHaveBeenCalled()
expect(mocks.mirrorUpFast).not.toHaveBeenCalled()
expect(fake.exportMock).not.toHaveBeenCalled()
expect(importSession).not.toHaveBeenCalled()
}
it('refuses to push when the session is already on the Manager', async () => {
const fake = createFakeContext()
configureMove(fake)
const { sessionExists, importSession } = stubTransfer({ onManager: ['ses_a'] })
await invokeMove(fake)
expect(sessionExists).toHaveBeenCalledWith('ses_a')
expectNothingPushed(fake, importSession)
expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'error', message: expect.stringContaining('already on the Manager') }))
})
it('refuses to push a subagent session whose parent is not on the Manager', async () => {
const fake = createFakeContext({ location: { directory: '/Users/x/repo' }, parentID: 'ses_parent' })
configureMove(fake)
const { sessionExists, importSession } = stubTransfer()
await invokeMove(fake)
expect(sessionExists).toHaveBeenCalledWith('ses_parent')
expectNothingPushed(fake, importSession)
expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'error', message: expect.stringContaining('Move the parent session first') }))
})
it('moves a subagent session once its parent is on the Manager', async () => {
const fake = createFakeContext({ location: { directory: '/Users/x/repo' }, parentID: 'ses_parent' })
configureMove(fake)
const { importSession } = stubTransfer({ onManager: ['ses_parent'] })
fake.exportMock.mockResolvedValue(makeTransfer())
await invokeMove(fake)
expect(mocks.mirrorUpFast).toHaveBeenCalledTimes(1)
expect(importSession).toHaveBeenCalledTimes(1)
})
it('refuses to push when the Manager session check fails', async () => {
const fake = createFakeContext()
configureMove(fake)
const { importSession } = stubTransfer({ existsError: new Error('proxy unreachable') })
await invokeMove(fake)
expectNothingPushed(fake, importSession)
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'proxy unreachable' })
})
it('stops before pushing when the Manager lacks the repo proxy route', async () => {
const fake = createFakeContext()
configureMove(fake)
+172
View File
@@ -0,0 +1,172 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import {
addPluginToCliConfig,
InstallError,
installVendoredOcm,
OCM_PLUGIN_SPEC,
resolveOpenCodeConfigDir,
resolveVendorPaths,
} from '../src/vendor-install.js'
let root: string
let sourceDist: string
let configDir: string
let home: string
function makeSourceDist(): string {
const dir = join(root, 'source', 'dist')
mkdirSync(dir, { recursive: true })
writeFileSync(join(dir, 'ocm.js'), '#!/usr/bin/env node\n', { mode: 0o644 })
writeFileSync(join(dir, 'tui.js'), 'export const setup = () => {}\n')
writeFileSync(join(root, 'source', 'package.json'), '{"name":"@opencode-manager/ocm-cli"}')
writeFileSync(join(root, 'source', 'README.md'), '# ocm-cli')
return dir
}
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'ocm-vendor-'))
sourceDist = makeSourceDist()
configDir = join(root, 'config', 'opencode')
home = join(root, 'home')
})
afterEach(() => {
rmSync(root, { recursive: true, force: true })
})
describe('resolveOpenCodeConfigDir', () => {
it('defaults to ~/.config/opencode', () => {
expect(resolveOpenCodeConfigDir({}, '/Users/me')).toBe('/Users/me/.config/opencode')
})
it('honours XDG_CONFIG_HOME', () => {
expect(resolveOpenCodeConfigDir({ XDG_CONFIG_HOME: '/xdg' }, '/Users/me')).toBe('/xdg/opencode')
})
it('prefers OPENCODE_CONFIG_DIR', () => {
expect(resolveOpenCodeConfigDir({ OPENCODE_CONFIG_DIR: '/custom', XDG_CONFIG_HOME: '/xdg' }, '/Users/me')).toBe('/custom')
})
})
describe('addPluginToCliConfig', () => {
it('creates a config with the schema and plugin entry', () => {
const result = addPluginToCliConfig(null)
expect(result.changed).toBe(true)
expect(JSON.parse(result.text)).toEqual({
$schema: 'https://opencode.ai/v2/cli.json',
plugins: [OCM_PLUGIN_SPEC],
})
})
it('appends to an existing plugins array', () => {
const result = addPluginToCliConfig(JSON.stringify({ plugins: ['other'] }, null, 2))
expect(result.changed).toBe(true)
expect(JSON.parse(result.text).plugins).toEqual(['other', OCM_PLUGIN_SPEC])
})
it('adds a plugins array to a config without one', () => {
const result = addPluginToCliConfig(JSON.stringify({ theme: { name: 'tokyonight' } }, null, 2))
expect(result.changed).toBe(true)
expect(JSON.parse(result.text)).toEqual({ theme: { name: 'tokyonight' }, plugins: [OCM_PLUGIN_SPEC] })
})
it('is idempotent for string and tuple entries', () => {
expect(addPluginToCliConfig(JSON.stringify({ plugins: [OCM_PLUGIN_SPEC] })).changed).toBe(false)
expect(addPluginToCliConfig(JSON.stringify({ plugins: [[OCM_PLUGIN_SPEC, {}]] })).changed).toBe(false)
})
it('preserves comments and other settings', () => {
const text = `{\n // keep\n "theme": { "name": "tokyonight" },\n "plugins": ["other"]\n}\n`
const result = addPluginToCliConfig(text)
expect(result.text).toContain('// keep')
expect(result.text).toContain('"tokyonight"')
expect(result.text).toContain(OCM_PLUGIN_SPEC)
})
it('rejects invalid json and non-array plugins', () => {
expect(() => addPluginToCliConfig('{ not json')).toThrow(InstallError)
expect(() => addPluginToCliConfig(JSON.stringify({ plugins: 'nope' }))).toThrow(InstallError)
})
})
describe('installVendoredOcm', () => {
it('copies the package, registers the plugin, and links the binary', () => {
const result = installVendoredOcm({ sourceDistDir: sourceDist, configDir, home })
expect(result.copied).toEqual(['dist', 'package.json', 'README.md'])
expect(existsSync(join(result.pluginDir, 'dist', 'ocm.js'))).toBe(true)
expect(existsSync(join(result.pluginDir, 'dist', 'tui.js'))).toBe(true)
expect(existsSync(join(result.pluginDir, 'package.json'))).toBe(true)
expect(result.configChanged).toBe(true)
expect(JSON.parse(readFileSync(result.configFile, 'utf-8')).plugins).toEqual([OCM_PLUGIN_SPEC])
expect(result.binLinkChanged).toBe(true)
expect(lstatSync(result.binLink!).isSymbolicLink()).toBe(true)
expect(readlinkSync(result.binLink!)).toBe(join(result.pluginDir, 'dist', 'ocm.js'))
})
it('is idempotent on a second run', () => {
installVendoredOcm({ sourceDistDir: sourceDist, configDir, home })
const second = installVendoredOcm({ sourceDistDir: sourceDist, configDir, home })
expect(second.copied).toEqual(['dist', 'package.json', 'README.md'])
expect(second.configChanged).toBe(false)
expect(second.binLinkChanged).toBe(false)
expect(JSON.parse(readFileSync(second.configFile, 'utf-8')).plugins).toEqual([OCM_PLUGIN_SPEC])
})
it('keeps an existing cli.json plugin list and settings', () => {
mkdirSync(configDir, { recursive: true })
writeFileSync(join(configDir, 'cli.json'), JSON.stringify({ theme: { name: 'tokyonight' }, plugins: ['other'] }))
installVendoredOcm({ sourceDistDir: sourceDist, configDir, home })
const config = JSON.parse(readFileSync(join(configDir, 'cli.json'), 'utf-8'))
expect(config.theme).toEqual({ name: 'tokyonight' })
expect(config.plugins).toEqual(['other', OCM_PLUGIN_SPEC])
})
it('leaves the source untouched when the plugin dir is a symlink to it', () => {
mkdirSync(join(configDir, 'plugin'), { recursive: true })
symlinkSync(join(root, 'source'), join(configDir, 'plugin', 'ocm-cli'))
const result = installVendoredOcm({ sourceDistDir: sourceDist, configDir, home, link: false })
expect(result.copied).toEqual([])
expect(existsSync(join(sourceDist, 'ocm.js'))).toBe(true)
expect(existsSync(join(root, 'source', 'package.json'))).toBe(true)
})
it('rejects a missing package build', () => {
expect(() => installVendoredOcm({ sourceDistDir: join(root, 'nope'), configDir, home })).toThrow(InstallError)
})
it('refuses to overwrite a non-symlink binary without force', () => {
mkdirSync(join(home, '.local', 'bin'), { recursive: true })
writeFileSync(join(home, '.local', 'bin', 'ocm'), '#!/bin/sh\n')
expect(() => installVendoredOcm({ sourceDistDir: sourceDist, configDir, home })).toThrow(InstallError)
const forced = installVendoredOcm({ sourceDistDir: sourceDist, configDir, home, force: true })
expect(forced.binLinkChanged).toBe(true)
expect(lstatSync(forced.binLink!).isSymbolicLink()).toBe(true)
})
it('skips the binary link when disabled', () => {
const result = installVendoredOcm({ sourceDistDir: sourceDist, configDir, home, link: false })
expect(result.binLink).toBeNull()
expect(existsSync(join(home, '.local', 'bin', 'ocm'))).toBe(false)
})
it('does not delete the running vendored install when re-run from it', () => {
installVendoredOcm({ sourceDistDir: sourceDist, configDir, home })
const vendoredDist = join(resolveVendorPaths(configDir, home).pluginDistDir)
const result = installVendoredOcm({ sourceDistDir: vendoredDist, configDir, home, link: false })
expect(result.copied).toEqual([])
expect(existsSync(join(vendoredDist, 'ocm.js'))).toBe(true)
})
})