diff --git a/backend/src/routes/schedules.ts b/backend/src/routes/schedules.ts index 83dfb157..c1dad901 100644 --- a/backend/src/routes/schedules.ts +++ b/backend/src/routes/schedules.ts @@ -69,7 +69,7 @@ export function createScheduleRoutes(scheduleService: ScheduleService) { const repoId = parseId(c.req.param('id'), 'repo id', ScheduleServiceError) const body = await c.req.json() const input = CreateScheduleJobRequestSchema.parse(body) - const job = scheduleService.createJob(repoId, input) + const job = await scheduleService.createJob(repoId, input) return c.json({ job }, 201) } catch (error) { return handleServiceError(c, error, 'Failed to create schedule', ScheduleServiceError) @@ -96,7 +96,7 @@ export function createScheduleRoutes(scheduleService: ScheduleService) { const jobId = parseId(c.req.param('jobId'), 'schedule id', ScheduleServiceError) const body = await c.req.json() const input = UpdateScheduleJobRequestSchema.parse(body) - const job = scheduleService.updateJob(repoId, jobId, input) + const job = await scheduleService.updateJob(repoId, jobId, input) return c.json({ job }) } catch (error) { return handleServiceError(c, error, 'Failed to update schedule', ScheduleServiceError) diff --git a/backend/src/services/schedules.ts b/backend/src/services/schedules.ts index 4499a2af..8b96a489 100644 --- a/backend/src/services/schedules.ts +++ b/backend/src/services/schedules.ts @@ -326,8 +326,9 @@ export class ScheduleService { return getScheduleJobById(this.db, repoId, jobId) } - createJob(repoId: number, input: CreateScheduleJobRequest): ScheduleJob { - this.assertRepo(repoId) + async createJob(repoId: number, input: CreateScheduleJobRequest): Promise { + const repo = this.assertRepo(repoId) + await this.assertAgentAvailable(repo.fullPath, input.agentSlug?.trim() || null) try { const job = createScheduleJob(this.db, repoId, buildCreateSchedulePersistenceInput(input)) @@ -338,9 +339,12 @@ export class ScheduleService { } } - updateJob(repoId: number, jobId: number, input: UpdateScheduleJobRequest): ScheduleJob { - this.assertRepo(repoId) + async updateJob(repoId: number, jobId: number, input: UpdateScheduleJobRequest): Promise { + const repo = this.assertRepo(repoId) const existing = this.assertJob(repoId, jobId) + if (input.agentSlug !== undefined) { + await this.assertAgentAvailable(repo.fullPath, input.agentSlug?.trim() || null) + } let job: ScheduleJob | null try { @@ -494,7 +498,7 @@ export class ScheduleService { }) } - await this.assertAgentAvailable(runDirectory, job.agentSlug) + const runJob = { ...job, agentSlug: await this.resolveRunAgent(runDirectory, job.agentSlug) } const model = await resolveOpenCodeModel(this.openCodeClient, runDirectory, { preferredModel: job.model, }) @@ -503,7 +507,7 @@ export class ScheduleService { try { session = await this.openCodeClient.api.session.create({ title: sessionTitle, - agent: job.agentSlug ?? undefined, + agent: runJob.agentSlug ?? undefined, model: { providerID: model.providerID, id: model.id, variant: model.variant }, ...openCodeLocation(runDirectory), permissions: buildSchedulePermissionRuleset(job.permissionConfig), @@ -516,7 +520,7 @@ export class ScheduleService { sessionId: session.id, sessionTitle, logText: buildRunStartedLog({ - job, + job: runJob, triggerSource, sessionId: session.id, sessionTitle, @@ -531,7 +535,7 @@ export class ScheduleService { void this.submitPromptAndMonitor({ repoId, - job, + job: runJob, runId: run.id, sessionId: session.id, sessionTitle, @@ -1026,24 +1030,38 @@ export class ScheduleService { } } + private async listAgentIds(directory: string): Promise> { + try { + const response = await this.openCodeClient.api.agent.list(openCodeLocation(directory)) + return new Set(response.data.map((agent) => agent.id)) + } catch (error) { + throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to list agents', 502) + } + } + /** * OpenCode admits a prompt for a session whose agent does not exist at its location - * but never delivers it, so an unknown agent must fail the run before the session is created. + * but never delivers it, so a scheduled run falls back to the default agent when its agent is gone. */ + private async resolveRunAgent(directory: string, agentSlug: string | null): Promise { + if (!agentSlug) { + return null + } + + if ((await this.listAgentIds(directory)).has(agentSlug)) { + return agentSlug + } + + logger.warn(`Agent "${agentSlug}" is not available in ${directory}; running the schedule with the default agent`) + return null + } + private async assertAgentAvailable(directory: string, agentSlug: string | null): Promise { if (!agentSlug) { return } - let agentIds: Set - try { - const response = await this.openCodeClient.api.agent.list(openCodeLocation(directory)) - agentIds = new Set(response.data.map((agent) => agent.id)) - } catch (error) { - throw new ScheduleServiceError(getErrorMessage(error) || 'Failed to list agents', 502) - } - - if (!agentIds.has(agentSlug)) { + if (!(await this.listAgentIds(directory)).has(agentSlug)) { throw new ScheduleServiceError( `Agent "${agentSlug}" is not available in ${directory}. Choose an agent defined for this repo in the schedule settings, or clear the agent to use the default.`, 400, diff --git a/backend/test/services/schedules.permission.test.ts b/backend/test/services/schedules.permission.test.ts index 4edee99f..38603934 100644 --- a/backend/test/services/schedules.permission.test.ts +++ b/backend/test/services/schedules.permission.test.ts @@ -243,22 +243,27 @@ describe('ScheduleService permission ruleset in session creation', () => { }) }) - it('fails the run without creating a session when the agent is not available at the run location', async () => { + it('runs with the default agent when the agent is not available at the run location', async () => { mocks.getScheduleJobById.mockReturnValue({ ...baseJob, agentSlug: 'assistant' }) - mocks.updateScheduleRun.mockReturnValue({ ...baseRun, status: 'failed' }) + mocks.updateScheduleRunMetadata.mockReturnValue({ ...baseRun, sessionId: 'ses-perm-4' }) - const stub = createStubScheduleApi({ agents: ['build', 'plan'] }) + const stub = createStubScheduleApi({ + sessionID: 'ses-perm-4', + messages: [assistantMessage('', { completed: true })], + agents: ['build', 'plan'], + }) const service = new ScheduleService( {} as never, createStubOpenCodeClient({ api: stub.api }), mocks.stubWorktreeManager as never, ) - await expect(service.runJob(42, 7, 'manual')).rejects.toMatchObject({ - status: 400, - message: expect.stringContaining('Agent "assistant" is not available'), - }) - expect(stub.api.session.create).not.toHaveBeenCalled() - expect(mocks.updateScheduleRun).toHaveBeenCalledWith(expect.anything(), 42, 7, baseRun.id, expect.objectContaining({ status: 'failed' })) + await service.runJob(42, 7, 'manual') + + expect(stub.api.session.create).toHaveBeenCalledWith(expect.objectContaining({ agent: undefined })) + expect(mocks.updateScheduleRunMetadata).toHaveBeenCalledWith( + expect.anything(), 42, 7, baseRun.id, + expect.objectContaining({ logText: expect.stringContaining('Agent: default') }), + ) }) }) diff --git a/backend/test/services/schedules.test.ts b/backend/test/services/schedules.test.ts index b2b4ddf5..698f57b1 100644 --- a/backend/test/services/schedules.test.ts +++ b/backend/test/services/schedules.test.ts @@ -805,7 +805,7 @@ describe('ScheduleService', () => { expect(mocks.listScheduleRunsByJob).toHaveBeenCalledWith(expect.anything(), 42, 7, 10) }) - it('creates and updates jobs using normalized persistence input', () => { + it('creates and updates jobs using normalized persistence input', async () => { const stub = createStubScheduleApi() const service = makeService(stub.api) const createdJob = { ...job, id: 8, name: 'Daily release summary' } @@ -816,19 +816,49 @@ describe('ScheduleService', () => { mocks.buildUpdatedSchedulePersistenceInput.mockReturnValue({ name: 'Updated release summary' }) mocks.updateScheduleJob.mockReturnValue(updatedJob) - const createResult = service.createJob(42, { + const createResult = await service.createJob(42, { name: 'Daily release summary', enabled: true, scheduleMode: 'interval', intervalMinutes: 60, prompt: 'Summarize release readiness.', }) - const updateResult = service.updateJob(42, 7, { name: 'Updated release summary' }) + const updateResult = await service.updateJob(42, 7, { name: 'Updated release summary' }) expect(createResult).toEqual(createdJob) expect(updateResult).toEqual(updatedJob) expect(mocks.buildCreateSchedulePersistenceInput).toHaveBeenCalled() expect(mocks.buildUpdatedSchedulePersistenceInput).toHaveBeenCalledWith(job, { name: 'Updated release summary' }) + expect(stub.api.agent.list).not.toHaveBeenCalled() + }) + + it('rejects saving a job whose agent is not available in the repo', async () => { + const stub = createStubScheduleApi({ agents: ['build', 'plan'] }) + const service = makeService(stub.api) + + await expect(service.createJob(42, { + name: 'Daily release summary', + enabled: true, + scheduleMode: 'interval', + intervalMinutes: 60, + prompt: 'Summarize release readiness.', + agentSlug: 'assistant', + })).rejects.toMatchObject({ status: 400, message: expect.stringContaining('Agent "assistant" is not available') }) + await expect(service.updateJob(42, 7, { agentSlug: 'assistant' })).rejects.toMatchObject({ status: 400 }) + + expect(mocks.createScheduleJob).not.toHaveBeenCalled() + expect(mocks.updateScheduleJob).not.toHaveBeenCalled() + }) + + it('saves a job whose agent is available and allows clearing the agent', async () => { + const stub = createStubScheduleApi({ agents: ['build', 'plan'] }) + const service = makeService(stub.api) + mocks.buildUpdatedSchedulePersistenceInput.mockReturnValue({}) + mocks.updateScheduleJob.mockReturnValue(job) + + await expect(service.updateJob(42, 7, { agentSlug: 'plan' })).resolves.toEqual(job) + await expect(service.updateJob(42, 7, { agentSlug: null })).resolves.toEqual(job) + expect(stub.api.agent.list).toHaveBeenCalledTimes(1) }) it('throws when deleting or loading missing records', () => { diff --git a/docs/ocm-cli.md b/docs/ocm-cli.md index 8198d54e..e06b27ae 100644 --- a/docs/ocm-cli.md +++ b/docs/ocm-cli.md @@ -46,7 +46,7 @@ There is no per-repo OpenCode process. All sessions share one OpenCode server on ## 1. Install -The CLI is published as `@opencode-manager/ocm-cli`. There are two install paths. +The CLI is published as `@opencode-manager/ocm-cli`. There are four install paths. ### Option A — install via OpenCode's plugin loader (recommended) @@ -80,7 +80,36 @@ pnpm add -g @opencode-manager/ocm-cli This puts `ocm` on your PATH via the package manager's own bin shim. The `~/.local/bin` symlink is skipped for global installs. -### Option C — from this repository (dev) +### Option C — vendored, self-contained + +The package needs no install step: `dist/ocm.js` bundles everything, and `dist/tui.js` bundles everything except `@opencode/plugin/tui`, `@opentui/core`, `@opentui/solid`, and `solid-js`, which OpenCode provides at runtime. `ocm install` copies the package into your OpenCode config directory, registers the plugin in `cli.json`, and links the binary onto your PATH: + +```bash +pnpm dlx @opencode-manager/ocm-cli install +``` + +If `ocm` is already installed (Option A or B), run the same command directly: + +```bash +ocm install +``` + +The command is idempotent: re-run it to upgrade after a new release, or run the wrapper script below to vendor a local build. It writes the plugin as `./plugin/ocm-cli/dist`, a directory entry — OpenCode 2 loads `tui.js` from a directory entry and skips entries that name a file directly. + +| Flag | Effect | +|---|---| +| `--dir ` | Install into a different OpenCode config directory (default: `$OPENCODE_CONFIG_DIR`, else `$XDG_CONFIG_HOME/opencode`, else `~/.config/opencode`) | +| `--no-link` | Skip the `~/.local/bin/ocm` symlink | +| `--force` | Replace a non-symlink `ocm` already at the link path | + +From this repository, build the package and run the wrapper script instead: + +```bash +pnpm --filter @opencode-manager/ocm-cli build +./ocm-cli/scripts/install.sh +``` + +### Option D — from this repository (dev) ```bash pnpm install @@ -117,6 +146,7 @@ ocm list List ready repos from the manager ocm use Attach to a specific repo and remember it as last ocm push [--force] [--create] [--yes] [--full] Mirror $PWD to the matching Manager repo (fast bundle/patch sync by default) ocm pull [--force] [--full] Mirror the matching Manager repo over $PWD (fast bundle/patch sync by default) +ocm install [--dir ] [--force] [--no-link] Vendor the CLI + TUI plugin into the OpenCode config dir ocm --help Show this help ``` diff --git a/frontend/src/components/schedules/ScheduleJobDialog.assistant.test.tsx b/frontend/src/components/schedules/ScheduleJobDialog.assistant.test.tsx index 27b24a3e..778188b2 100644 --- a/frontend/src/components/schedules/ScheduleJobDialog.assistant.test.tsx +++ b/frontend/src/components/schedules/ScheduleJobDialog.assistant.test.tsx @@ -167,4 +167,54 @@ describe('ScheduleJobDialog — assistant create guard', () => { expect(mocks.useAgents).toHaveBeenLastCalledWith('/workspace/repos/assistant', { enabled: true }) }) }) + + it.each([ + { storedAgent: 'assistant', savedAgent: undefined }, + { storedAgent: 'build', savedAgent: 'build' }, + ])('saves agent $savedAgent when the stored agent is $storedAgent', async ({ storedAgent, savedAgent }) => { + mocks.useAgents.mockImplementation((...args: unknown[]) => ( + args[0] ? { data: [{ id: 'build', name: 'Build', mode: 'primary' }], isSuccess: true } : { data: [] } + ) as never) + const user = userEvent.setup() + const onSubmit = vi.fn() + + render( + , + { wrapper: createWrapper() }, + ) + + await waitFor(() => { + expect(mocks.useAgents).toHaveBeenLastCalledWith('/workspace/repos/assistant', { enabled: true }) + }) + await user.click(screen.getByRole('button', { name: 'Save changes' })) + + expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ agentSlug: savedAgent })) + }) }) diff --git a/frontend/src/components/schedules/ScheduleJobDialog.tsx b/frontend/src/components/schedules/ScheduleJobDialog.tsx index 23d6bd6c..9f11efa9 100644 --- a/frontend/src/components/schedules/ScheduleJobDialog.tsx +++ b/frontend/src/components/schedules/ScheduleJobDialog.tsx @@ -86,7 +86,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, const effectiveRepoId = selectedRepoId ?? job?.repoId const { scheduleTarget } = useScheduleTarget(open ? effectiveRepoId : undefined) const scheduleDirectory = scheduleTarget?.fullPath - const { data: agents = [] } = useAgents(scheduleDirectory, { enabled: !!scheduleDirectory }) + const { data: agents = [], isSuccess: agentsLoaded } = useAgents(scheduleDirectory, { enabled: !!scheduleDirectory }) const { data: skills = [], isLoading: skillsLoading } = useQuery({ queryKey: ['managed-skills'], @@ -186,6 +186,8 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, })) }, [agents]) + const selectedAgentSlug = agentsLoaded && !agentOptions.some((option) => option.value === agentSlug) ? '' : agentSlug + useEffect(() => { if (!open) { return @@ -258,7 +260,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, name: name.trim(), description: description.trim() || undefined, enabled, - agentSlug: agentSlug.trim() || undefined, + agentSlug: selectedAgentSlug.trim() || undefined, model: resolvedModel ?? undefined, prompt: prompt.trim(), branch: branch.trim() || null, @@ -328,7 +330,7 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit, onNameChange={setName} description={description} onDescriptionChange={setDescription} - agentSlug={agentSlug} + agentSlug={selectedAgentSlug} onAgentSlugChange={setAgentSlug} agentOptions={agentOptions} model={resolvedModel ?? ''} diff --git a/ocm-cli/README.md b/ocm-cli/README.md index 3bf6140e..ec0f60d0 100644 --- a/ocm-cli/README.md +++ b/ocm-cli/README.md @@ -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 ocm push [repoId] [--force] [--create] [--yes] [--full] ocm pull [repoId] [--force] [--full] +ocm install [--dir ] [--force] [--no-link] ocm logout ``` diff --git a/ocm-cli/bin/ocm.ts b/ocm-cli/bin/ocm.ts index 7b443a2d..140af689 100644 --- a/ocm-cli/bin/ocm.ts +++ b/ocm-cli/bin/ocm.ts @@ -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 ] [--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 { 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 { + 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 ] [--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 { const [, , cmd, ...rest] = process.argv @@ -556,6 +605,9 @@ async function main(): Promise { case 'pull': await cmdPull(rest) break + case 'install': + await cmdInstall(rest) + break default: die(`unknown command: ${cmd}. run \`ocm --help\``) } diff --git a/ocm-cli/package.json b/ocm-cli/package.json index 3f00ec92..a76aef13 100644 --- a/ocm-cli/package.json +++ b/ocm-cli/package.json @@ -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", diff --git a/ocm-cli/scripts/install.sh b/ocm-cli/scripts/install.sh new file mode 100755 index 00000000..699a5838 --- /dev/null +++ b/ocm-cli/scripts/install.sh @@ -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 "$@" diff --git a/ocm-cli/src/json-store.ts b/ocm-cli/src/json-store.ts index ca69b57d..34962c28 100644 --- a/ocm-cli/src/json-store.ts +++ b/ocm-cli/src/json-store.ts @@ -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 { diff --git a/ocm-cli/src/remote-session.ts b/ocm-cli/src/remote-session.ts index 6a874dfe..206b564a 100644 --- a/ocm-cli/src/remote-session.ts +++ b/ocm-cli/src/remote-session.ts @@ -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 + 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 => { + 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 }), } } diff --git a/ocm-cli/src/state.ts b/ocm-cli/src/state.ts index c435fc61..f47f7f0f 100644 --- a/ocm-cli/src/state.ts +++ b/ocm-cli/src/state.ts @@ -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 { diff --git a/ocm-cli/src/tui-plugin.ts b/ocm-cli/src/tui-plugin.ts index a9772f54..633e1b11 100644 --- a/ocm-cli/src/tui-plugin.ts +++ b/ocm-cli/src/tui-plugin.ts @@ -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 { + 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 { 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 }, { diff --git a/ocm-cli/src/vendor-install.ts b/ocm-cli/src/vendor-install.ts new file mode 100644 index 00000000..b2ffe4d5 --- /dev/null +++ b/ocm-cli/src/vendor-install.ts @@ -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 { + 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 | 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, + } +} diff --git a/ocm-cli/test/remote-session.test.ts b/ocm-cli/test/remote-session.test.ts index 667ce036..dc7885d2 100644 --- a/ocm-cli/test/remote-session.test.ts +++ b/ocm-cli/test/remote-session.test.ts @@ -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 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() }) }) diff --git a/ocm-cli/test/state.test.ts b/ocm-cli/test/state.test.ts index f437202b..1a3d67d0 100644 --- a/ocm-cli/test/state.test.ts +++ b/ocm-cli/test/state.test.ts @@ -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() diff --git a/ocm-cli/test/tui-plugin.test.ts b/ocm-cli/test/tui-plugin.test.ts index c1e27ad4..1af83f7a 100644 --- a/ocm-cli/test/tui-plugin.test.ts +++ b/ocm-cli/test/tui-plugin.test.ts @@ -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) { + 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) { @@ -177,6 +188,7 @@ function configureMove(fake: ReturnType) { async function invokeMove(fake: ReturnType) { await setupOcm(fake.context, vi.fn()) + renderAppSlot(fake) const factory = fake.layer.mock.calls[0]![0] as () => { commands: { id: string; run: () => Promise }[] } 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, importSession: ReturnType) { + 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) diff --git a/ocm-cli/test/vendor-install.test.ts b/ocm-cli/test/vendor-install.test.ts new file mode 100644 index 00000000..7a1b4cf7 --- /dev/null +++ b/ocm-cli/test/vendor-install.test.ts @@ -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) + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2d67208f..46af616d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -298,6 +298,9 @@ importers: eslint: specifier: ^9.39.1 version: 9.39.2(jiti@2.6.1) + jsonc-parser: + specifier: ^3.3.1 + version: 3.3.1 solid-js: specifier: 1.9.12 version: 1.9.12 @@ -1336,6 +1339,7 @@ packages: resolution: {integrity: sha512-VZ2sNMw1d/r1SLPjUbOP9LKscKz1CQjID8adTL6gG8Lrrq+mYcIUxutyB+P/eG0J/7oRZLPR6OMt7dUOap6RTg==} cpu: [arm64] os: [linux] + libc: [musl] '@opentui/core-linux-arm64@0.5.12': resolution: {integrity: sha512-XeKhuIaEtgipvuPHbl4qPOBj+Ut+2zObmsxMVM1jDcjz/FatG9PGeGQPx1G1SnvH2AgpT4K+eCu7DUF0+yIqoQ==} @@ -1346,6 +1350,7 @@ packages: resolution: {integrity: sha512-WWW0hVBoSYZ3D6AgZ4u2Y5/u/IyIq2pDb+4yI3WgJ70Wyt6ofHy+6kRGRgbXFn1p+rPInAHjCXD2v6C7iEKSrA==} cpu: [x64] os: [linux] + libc: [musl] '@opentui/core-linux-x64@0.5.12': resolution: {integrity: sha512-eZiCjEzwbb6qClPPfk32Nha9xmr9obt69Xj0+9SKsXxWLBKkjQEGOMRoh/R9ObaQF4aq8If1xV3VEY0sD9W9vg==} @@ -1934,56 +1939,67 @@ packages: resolution: {integrity: sha512-EHMUcDwhtdRGlXZsGSIuXSYwD5kOT9NVnx9sqzYiwAc91wfYOE1g1djOEDseZJKKqtHAHGwnGPQu3kytmfaXLQ==} cpu: [arm] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.54.0': resolution: {integrity: sha512-+pBrqEjaakN2ySv5RVrj/qLytYhPKEUwk+e3SFU5jTLHIcAtqh2rLrd/OkbNuHJpsBgxsD8ccJt5ga/SeG0JmA==} cpu: [arm] os: [linux] + libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.54.0': resolution: {integrity: sha512-NSqc7rE9wuUaRBsBp5ckQ5CVz5aIRKCwsoa6WMF7G01sX3/qHUw/z4pv+D+ahL1EIKy6Enpcnz1RY8pf7bjwng==} cpu: [arm64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.54.0': resolution: {integrity: sha512-gr5vDbg3Bakga5kbdpqx81m2n9IX8M6gIMlQQIXiLTNeQW6CucvuInJ91EuCJ/JYvc+rcLLsDFcfAD1K7fMofg==} cpu: [arm64] os: [linux] + libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.54.0': resolution: {integrity: sha512-gsrtB1NA3ZYj2vq0Rzkylo9ylCtW/PhpLEivlgWe0bpgtX5+9j9EZa0wtZiCjgu6zmSeZWyI/e2YRX1URozpIw==} cpu: [loong64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-ppc64-gnu@4.54.0': resolution: {integrity: sha512-y3qNOfTBStmFNq+t4s7Tmc9hW2ENtPg8FeUD/VShI7rKxNW7O4fFeaYbMsd3tpFlIg1Q8IapFgy7Q9i2BqeBvA==} cpu: [ppc64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-gnu@4.54.0': resolution: {integrity: sha512-89sepv7h2lIVPsFma8iwmccN7Yjjtgz0Rj/Ou6fEqg3HDhpCa+Et+YSufy27i6b0Wav69Qv4WBNl3Rs6pwhebQ==} cpu: [riscv64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.54.0': resolution: {integrity: sha512-ZcU77ieh0M2Q8Ur7D5X7KvK+UxbXeDHwiOt/CPSBTI1fBmeDMivW0dPkdqkT4rOgDjrDDBUed9x4EgraIKoR2A==} cpu: [riscv64] os: [linux] + libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.54.0': resolution: {integrity: sha512-2AdWy5RdDF5+4YfG/YesGDDtbyJlC9LHmL6rZw6FurBJ5n4vFGupsOBGfwMRjBYH7qRQowT8D/U4LoSvVwOhSQ==} cpu: [s390x] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.54.0': resolution: {integrity: sha512-WGt5J8Ij/rvyqpFexxk3ffKqqbLf9AqrTBbWDk7ApGUzaIs6V+s2s84kAxklFwmMF/vBNGrVdYgbblCOFFezMQ==} cpu: [x64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-musl@4.54.0': resolution: {integrity: sha512-JzQmb38ATzHjxlPHuTH6tE7ojnMKM2kYNzt44LO/jJi8BpceEC8QuXYA908n8r3CNuG/B3BV8VR3Hi1rYtmPiw==} cpu: [x64] os: [linux] + libc: [musl] '@rollup/rollup-openharmony-arm64@4.54.0': resolution: {integrity: sha512-huT3fd0iC7jigGh7n3q/+lfPcXxBi+om/Rs3yiFxjvSxbSB6aohDFXbWvlspaqjeOh+hx7DDHS+5Es5qRkWkZg==} @@ -2137,24 +2153,28 @@ packages: engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [glibc] '@tailwindcss/oxide-linux-arm64-musl@4.1.18': resolution: {integrity: sha512-1px92582HkPQlaaCkdRcio71p8bc8i/ap5807tPRDK/uw953cauQBT8c5tVGkOwrHMfc2Yh6UuxaH4vtTjGvHg==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [musl] '@tailwindcss/oxide-linux-x64-gnu@4.1.18': resolution: {integrity: sha512-v3gyT0ivkfBLoZGF9LyHmts0Isc8jHZyVcbzio6Wpzifg/+5ZJpDiRiUhDLkcr7f/r38SWNe7ucxmGW3j3Kb/g==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [glibc] '@tailwindcss/oxide-linux-x64-musl@4.1.18': resolution: {integrity: sha512-bhJ2y2OQNlcRwwgOAGMY0xTFStt4/wyU6pvI6LSuZpRgKQwxTec0/3Scu91O8ir7qCR3AuepQKLU/kX99FouqQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [musl] '@tailwindcss/oxide-wasm32-wasi@4.1.18': resolution: {integrity: sha512-LffYTvPjODiP6PT16oNeUQJzNVyJl1cjIebq/rWWBF+3eDst5JGEFSc5cWxyRCJ0Mxl+KyIkqRxk1XPEs9x8TA==} @@ -3900,24 +3920,28 @@ packages: engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [glibc] lightningcss-linux-arm64-musl@1.30.2: resolution: {integrity: sha512-5Vh9dGeblpTxWHpOx8iauV02popZDsCYMPIgiuw97OJ5uaDsL86cnqSFs5LZkG3ghHoX5isLgWzMs+eD1YzrnA==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [musl] lightningcss-linux-x64-gnu@1.30.2: resolution: {integrity: sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [glibc] lightningcss-linux-x64-musl@1.30.2: resolution: {integrity: sha512-XJaLUUFXb6/QG2lGIW6aIk6jKdtjtcffUT0NKvIqhSBY3hh9Ch+1LCeH80dR9q9LBjG3ewbDjnumefsLsP6aiA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [musl] lightningcss-win32-arm64-msvc@1.30.2: resolution: {integrity: sha512-FZn+vaj7zLv//D/192WFFVA0RgHawIcHqLX9xuWiQt7P0PtdFEVaxgF9rjM/IRYHQXNnk61/H/gb2Ei+kUQ4xQ==} @@ -7918,7 +7942,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: diff --git a/shared/src/opencode/index.ts b/shared/src/opencode/index.ts index 604485a1..2bdea9c0 100644 --- a/shared/src/opencode/index.ts +++ b/shared/src/opencode/index.ts @@ -44,7 +44,7 @@ export type { V2Event, } from '@opencode/client' -export { ClientError, isIntegrationNotFoundError, isMcpServerNotFoundError, isWorktreeError } from '@opencode/client' +export { ClientError, isIntegrationNotFoundError, isMcpServerNotFoundError, isSessionNotFoundError, isWorktreeError } from '@opencode/client' export { assistantText, sessionIDFromEvent, toolContentText } from './content'