mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
1 parent
53e3a0227e
commit
eff10d7829
22 files changed
+845
-64
No files matched your search
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user