mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)
* feat(opencode): migrate OpenCode Manager to OpenCode 2 Port the backend lifecycle, generated plugins, event aggregation, schedules, worktrees, provider credentials, MCP, config handling, the frontend chat model, and the ocm CLI to OpenCode 2. Adopt @opencode/client 2.0.15 as the single typed V2 API contract, require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every V1-only code path. * refactor(opencode): reload config in place and drop v1 compatibility shims Route config/skill/AGENTS.md changes through the OpenCode location reload API instead of a full server restart, stop auto-resuming interrupted sessions, remove the restart coordinator and v1 MCP/version shims, and pin support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries, service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers. * refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows - extract shared semver and model-ref utilities, reuse across version checks - share the OpenCode release download script across Docker, entrypoint, dev setup - unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN - scope the repo proxy location rewrite and surface ocm proxy errors - rework frontend session projection, permission lookup, and cache invalidation * fix(schedules): reject unavailable agents before creating a session * feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
1 parent
6c2ebd764b
commit
dacde879d6
383 files changed
+29905
-46566
No files matched your search
+42
-8
@@ -6,6 +6,22 @@ OpenCode Manager CLI and plugin package.
|
||||
can also mirror a local git repo up to Manager or pull a Manager repo back down
|
||||
to the local working tree.
|
||||
|
||||
## Compatibility
|
||||
|
||||
| ocm | OpenCode Manager | Local OpenCode |
|
||||
|---|---|---|
|
||||
| 0.3.x | >= 0.19.0 | >= 2.0.15, < 3 |
|
||||
|
||||
ocm 0.3.0 attaches through the repo-scoped Manager proxy
|
||||
(`/api/opencode-proxy/repos/:repoId`), loads its plugin from the OpenCode 2
|
||||
`cli.json` `plugins` list, and moves sessions with OpenCode 2 session
|
||||
export/import. Older Managers lack that route; `ocm` then fails with
|
||||
`OpenCode Manager at <url> is too old for ocm 0.3.0; upgrade the Manager to >= 0.19.0`.
|
||||
Use ocm 0.2.x with OpenCode Manager < 0.19.0 and OpenCode 1.x, installed pinned
|
||||
(`pnpm add -g @opencode-manager/ocm-cli@0.2`) with the OpenCode 1.x plugin entry pinned to
|
||||
`@opencode-manager/ocm-cli@0.2`. ocm is published together with each OpenCode Manager
|
||||
release.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
@@ -16,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
|
||||
@@ -34,6 +59,11 @@ permissions. CLI state is stored at `~/.config/opencode-manager/state.json`.
|
||||
Windows is unsupported: the same file store is used, but the `0600` mode is not
|
||||
enforced there.
|
||||
|
||||
`ocm` passes the token to the local `opencode` client it launches as
|
||||
`OPENCODE_PASSWORD`. That variable belongs only to the local client process; never
|
||||
set `OPENCODE_PASSWORD` in the OpenCode Manager server environment (the Manager
|
||||
strips it because it would override the Manager-managed OpenCode password).
|
||||
|
||||
`OCM_TOKEN` overrides the token store for reads; `ocm login` always writes to
|
||||
the platform store and `ocm logout` cannot remove the override. Run `ocm status`
|
||||
to see the active store.
|
||||
@@ -50,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
|
||||
```
|
||||
|
||||
@@ -87,9 +118,9 @@ branch, and path. The default attach reports the same details.
|
||||
|
||||
## OpenCode TUI plugin
|
||||
|
||||
The package exposes an OpenCode TUI plugin through its `./tui` package export.
|
||||
Configure the package name and OpenCode resolves that TUI entrypoint
|
||||
automatically. When attached to a Manager via `ocm`, the plugin shows a
|
||||
The package exposes an OpenCode 2 TUI plugin (`{ id, setup }`) through its `./tui`
|
||||
package export. Configure the package name and OpenCode resolves that TUI
|
||||
entrypoint automatically. When attached to a Manager via `ocm`, the plugin shows a
|
||||
`REMOTE <host> · <repo>` indicator at the bottom of the TUI; local launches
|
||||
show nothing. It registers `/ocm-move`, which keeps the local session and
|
||||
copies the active session to the Manager after replacing the Manager repo's
|
||||
@@ -102,19 +133,21 @@ yet. When multiple Manager repos match, the one already on your branch is
|
||||
chosen; otherwise a picker dialog lets you choose. A confirmation dialog gates
|
||||
the move before any push, states where the state will land, and lists any
|
||||
server-side work (uncommitted changes or commits not present locally) that will
|
||||
be discarded there. While the move runs, a spinner with the current phase and a
|
||||
be discarded there. The session moves by exporting it from the local OpenCode 2
|
||||
server and importing it through the Manager proxy, followed by a synthetic
|
||||
reminder. While the move runs, a spinner with the current phase and a
|
||||
progress bar is shown next to the prompt. On success
|
||||
you can optionally warp — exit the local TUI and attach to the moved session
|
||||
on the Manager immediately. Use it from inside an OpenCode session after
|
||||
`ocm login` and after the repo already exists on the Manager
|
||||
(`ocm push --create` if needed).
|
||||
|
||||
Enable it in `tui.json`:
|
||||
Enable it in `~/.config/opencode/cli.json`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"$schema": "https://opencode.ai/tui.json",
|
||||
"plugin": ["@opencode-manager/ocm-cli"]
|
||||
"$schema": "https://opencode.ai/v2/cli.json",
|
||||
"plugins": ["@opencode-manager/ocm-cli"]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -124,7 +157,8 @@ global installs); the plugin surface is TUI-only.
|
||||
## Requirements
|
||||
|
||||
- macOS or Linux (Windows is unsupported)
|
||||
- `opencode` available on `PATH`
|
||||
- OpenCode >= 2.0.15 (same major, 2.x) available on `PATH`
|
||||
- OpenCode Manager >= 0.19.0
|
||||
- `git` and `tar` (with gzip support, i.e. the `-z` flag) available on `PATH`
|
||||
- `bash`, used for hidden token entry and interactive confirmations
|
||||
- macOS only: `/usr/bin/security`, used for Keychain-backed token storage (Linux uses a mode-`0600` file under the user config dir `~/.config/opencode-manager`)
|
||||
|
||||
+67
-36
@@ -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'
|
||||
@@ -9,11 +11,9 @@ import { createProgressReporter } from '../src/progress.js'
|
||||
import { getBranchName, getOriginUrl } from '../src/local-repo.js'
|
||||
import { resolveOpenCodeProjectId } from '@opencode-manager/shared/project-id'
|
||||
import { resolveTarget, formatRepoIdentities, parseRepoIdPositional, restrictMatchesToRequestedRepo } from '../src/resolve-target.js'
|
||||
import { buildRemoteAttachEnv } from '../src/remote-context.js'
|
||||
import { buildAttachInvocation } from '../src/warp.js'
|
||||
import { type ManagerRepo, fetchRepos, toRemoteRepoSummaries } from '../src/manager-repos.js'
|
||||
import packageJson from '../package.json' with { type: 'json' }
|
||||
|
||||
const VERSION = packageJson.version
|
||||
import { OCM_VERSION as VERSION, warmRepoProxy } from '../src/repo-proxy.js'
|
||||
|
||||
const USAGE = `ocm v${VERSION} - OpenCode Manager workspace launcher
|
||||
|
||||
@@ -30,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
|
||||
`
|
||||
@@ -117,39 +119,20 @@ async function requireToken(state: OcmState): Promise<string> {
|
||||
return token
|
||||
}
|
||||
|
||||
async function warmUpInstance(managerUrl: string, token: string, directory: string): Promise<void> {
|
||||
const url = `${managerUrl}/api/opencode-proxy/session?directory=${encodeURIComponent(directory)}`
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
try {
|
||||
const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } })
|
||||
if (res.ok) {
|
||||
await res.text()
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
/* retry */
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, attempt * 500))
|
||||
async function attach(managerUrl: string, token: string, repo: ManagerRepo, cwd: string): Promise<never> {
|
||||
try {
|
||||
await warmRepoProxy(managerUrl, token, repo.repoId)
|
||||
} catch (err) {
|
||||
die(err instanceof Error ? err.message : String(err))
|
||||
}
|
||||
}
|
||||
|
||||
async function attach(managerUrl: string, token: string, repo: ManagerRepo): Promise<never> {
|
||||
await warmUpInstance(managerUrl, token, repo.directory)
|
||||
const proxyUrl = `${managerUrl}/api/opencode-proxy`
|
||||
const args = [
|
||||
'attach',
|
||||
proxyUrl,
|
||||
'--dir', repo.directory,
|
||||
'--password', token,
|
||||
'--username', 'opencode',
|
||||
]
|
||||
const { args, env } = buildAttachInvocation({ managerUrl, token, repoId: repo.repoId, repoName: repo.name })
|
||||
const child = spawn('opencode', args, {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, ...buildRemoteAttachEnv(managerUrl, repo.name) },
|
||||
cwd,
|
||||
env,
|
||||
})
|
||||
child.on('close', (code) => process.exit(code ?? 0))
|
||||
child.on('error', (err) => die(`failed to spawn opencode: ${err.message}`))
|
||||
// hand control to child
|
||||
return undefined as never
|
||||
}
|
||||
|
||||
@@ -306,7 +289,7 @@ async function cmdUse(args: string[]): Promise<void> {
|
||||
lastRepoBranch: repo.branch,
|
||||
})
|
||||
|
||||
await attach(state.managerUrl, token, repo)
|
||||
await attach(state.managerUrl, token, repo, process.cwd())
|
||||
}
|
||||
|
||||
async function cmdDefault(): Promise<void> {
|
||||
@@ -339,13 +322,13 @@ async function cmdDefault(): Promise<void> {
|
||||
lastRepoDir: repo.directory,
|
||||
lastRepoBranch: repo.branch,
|
||||
})
|
||||
await attach(state.managerUrl, token, toManagerRepo(repo))
|
||||
await attach(state.managerUrl, token, toManagerRepo(repo), result.repoRoot)
|
||||
return
|
||||
}
|
||||
case 'last': {
|
||||
const repo = result.repo
|
||||
info(`attaching to ${repo.name} (last used)`)
|
||||
await attach(state.managerUrl, token, toManagerRepo(repo))
|
||||
await attach(state.managerUrl, token, toManagerRepo(repo), process.cwd())
|
||||
return
|
||||
}
|
||||
case 'cwd-ambiguous': {
|
||||
@@ -536,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
|
||||
|
||||
@@ -577,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\``)
|
||||
}
|
||||
|
||||
+10
-7
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-manager/ocm-cli",
|
||||
"version": "0.2.7",
|
||||
"version": "0.3.0",
|
||||
"description": "OpenCode Manager CLI: attach a local OpenCode TUI to a Manager-hosted repo.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
@@ -18,9 +18,9 @@
|
||||
}
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentui/core": ">=0.1.97",
|
||||
"@opentui/solid": ">=0.1.97",
|
||||
"solid-js": ">=1.9.11"
|
||||
"@opentui/core": ">=0.5.10",
|
||||
"@opentui/solid": ">=0.5.10",
|
||||
"solid-js": ">=1.9.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@opentui/core": {
|
||||
@@ -39,6 +39,7 @@
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md",
|
||||
"scripts/install.sh",
|
||||
"scripts/postinstall.mjs"
|
||||
],
|
||||
"scripts": {
|
||||
@@ -53,13 +54,15 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.36.0",
|
||||
"@opencode/plugin": "2.0.15",
|
||||
"@opencode-manager/shared": "workspace:*",
|
||||
"@opentui/core": "^0.1.97",
|
||||
"@opentui/solid": "^0.1.97",
|
||||
"@opentui/core": "^0.5.12",
|
||||
"@opentui/solid": "^0.5.12",
|
||||
"@types/bun": "^1.3.14",
|
||||
"@types/node": "^22.0.0",
|
||||
"eslint": "^9.39.1",
|
||||
"solid-js": "^1.9.11",
|
||||
"jsonc-parser": "^3.3.1",
|
||||
"solid-js": "1.9.12",
|
||||
"typescript": "^5.5.0",
|
||||
"typescript-eslint": "^8.45.0",
|
||||
"vitest": "^3.1.0"
|
||||
|
||||
@@ -14,7 +14,6 @@ async function bundleEntry(label: string, entrypoint: string, outputName: string
|
||||
outdir: dist,
|
||||
target: 'node',
|
||||
format: 'esm',
|
||||
external: ['bun:sqlite'],
|
||||
naming: { entry: outputName },
|
||||
})
|
||||
|
||||
@@ -35,7 +34,7 @@ const tuiResult = await Bun.build({
|
||||
target: 'node',
|
||||
format: 'esm',
|
||||
plugins: [solidPlugin],
|
||||
external: ['@opentui/solid', '@opentui/core', 'solid-js'],
|
||||
external: ['@opencode/plugin/tui', '@opentui/solid', '@opentui/core', 'solid-js'],
|
||||
naming: { entry: 'tui.js' },
|
||||
})
|
||||
|
||||
|
||||
Executable
+12
@@ -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 "$@"
|
||||
@@ -0,0 +1,3 @@
|
||||
export function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { existsSync, readdirSync, statSync } from 'fs'
|
||||
import { homedir } from 'os'
|
||||
import { isAbsolute, join } from 'path'
|
||||
import type { HistoryEventRow } from './session-move.js'
|
||||
|
||||
function opencodeDataDir(): string {
|
||||
const xdg = process.env.XDG_DATA_HOME
|
||||
return xdg ? join(xdg, 'opencode') : join(homedir(), '.local', 'share', 'opencode')
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the opencode durable-event database path the same way
|
||||
* `Database.path()` does in opencode core: an `OPENCODE_DB` override wins,
|
||||
* then the default `opencode.db`, then the newest channel-suffixed variant
|
||||
* (`opencode-<channel>.db`) for non-release channels.
|
||||
*/
|
||||
export function resolveOpencodeDbPath(): string | null {
|
||||
const override = process.env.OPENCODE_DB
|
||||
const dataDir = opencodeDataDir()
|
||||
if (override) {
|
||||
if (override === ':memory:' || isAbsolute(override)) return override
|
||||
return join(dataDir, override)
|
||||
}
|
||||
|
||||
const defaultPath = join(dataDir, 'opencode.db')
|
||||
if (existsSync(defaultPath)) return defaultPath
|
||||
if (!existsSync(dataDir)) return null
|
||||
|
||||
const variants = readdirSync(dataDir)
|
||||
.filter((name) => name.startsWith('opencode-') && name.endsWith('.db'))
|
||||
.map((name) => join(dataDir, name))
|
||||
.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)
|
||||
|
||||
return variants[0] ?? null
|
||||
}
|
||||
|
||||
export async function readSessionEvents(sessionID: string): Promise<HistoryEventRow[]> {
|
||||
const dbPath = resolveOpencodeDbPath()
|
||||
if (!dbPath) {
|
||||
throw new Error('opencode database not found; is this machine running opencode with durable history?')
|
||||
}
|
||||
|
||||
const { Database } = await import('bun:sqlite')
|
||||
const db = new Database(dbPath, { readonly: true })
|
||||
try {
|
||||
const rows = db
|
||||
.query<{ id: string; aggregate_id: string; seq: number; type: string; data: string }, [string]>(
|
||||
'SELECT id, aggregate_id, seq, type, data FROM event WHERE aggregate_id = ? ORDER BY seq ASC',
|
||||
)
|
||||
.all(sessionID)
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
aggregate_id: row.aggregate_id,
|
||||
seq: row.seq,
|
||||
type: row.type,
|
||||
data: JSON.parse(row.data) as Record<string, unknown>,
|
||||
}))
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { getRepoRoot, getDirtyPaths, getHeadSha, getBranchName, getMirrorPatch,
|
||||
import { resolveOpenCodeProjectId } from '@opencode-manager/shared/project-id'
|
||||
import type { ManagerApi } from './manager-api.js'
|
||||
import { ManagerApiError } from './manager-api.js'
|
||||
import { delay } from './delay.js'
|
||||
|
||||
const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo', '.DS_Store', '._*']
|
||||
const PART_RETRIES = 3
|
||||
@@ -147,10 +148,6 @@ export interface MirrorUpOpts {
|
||||
onProgress?: (p: MirrorProgress) => void
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
function isRetryablePartError(err: unknown): boolean {
|
||||
if (err instanceof ManagerApiError) {
|
||||
return err.status >= 500 || err.status === 408 || err.status === 429
|
||||
|
||||
@@ -36,6 +36,6 @@ export function pushPhaseProgress(phase: MirrorUpFastPhase): MoveProgress {
|
||||
}
|
||||
}
|
||||
|
||||
export function replayProgress(replayed: number, total: number): MoveProgress {
|
||||
return { label: `replaying session ${replayed}/${total} events`, fraction: total > 0 ? replayed / total : null }
|
||||
export function importProgress(imported: number, total: number): MoveProgress {
|
||||
return { label: `importing session ${imported}/${total} messages`, fraction: total > 0 ? imported / total : null }
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import type { ReplayEvent } from './session-move.js'
|
||||
|
||||
export function createManagerReplay(managerUrl: string, token: string) {
|
||||
return async (remoteDirectory: string, events: ReplayEvent[]): Promise<{ sessionID: string }> => {
|
||||
const url = `${managerUrl}/api/opencode-proxy/sync/replay?directory=${encodeURIComponent(remoteDirectory)}`
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ directory: remoteDirectory, events }),
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '')
|
||||
throw new Error(`replay failed (${res.status}): ${text.slice(0, 200)}`)
|
||||
}
|
||||
|
||||
return (await res.json()) as { sessionID: string }
|
||||
}
|
||||
}
|
||||
|
||||
export function createManagerPromptAsync(managerUrl: string, token: string) {
|
||||
return async (remoteDirectory: string, sessionID: string, text: string): Promise<void> => {
|
||||
const url = `${managerUrl}/api/opencode-proxy/session/${encodeURIComponent(sessionID)}/prompt_async?directory=${encodeURIComponent(remoteDirectory)}`
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ noReply: true, parts: [{ type: 'text', text, synthetic: true }] }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '')
|
||||
throw new Error(`prompt_async failed (${res.status}): ${body.slice(0, 200)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
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),
|
||||
password: token,
|
||||
})
|
||||
|
||||
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,
|
||||
messages: data.messages,
|
||||
location: { directory: remoteDirectory },
|
||||
})
|
||||
return { sessionID: session.id }
|
||||
},
|
||||
addReminder: (sessionID: string, text: string) => api.session.synthetic({ sessionID, text, resume: false }),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import packageJson from '../package.json' with { type: 'json' }
|
||||
import { delay } from './delay.js'
|
||||
import { describeCause } from './token-store.js'
|
||||
|
||||
export const OCM_VERSION = packageJson.version
|
||||
export const MIN_MANAGER_VERSION = '0.19.0'
|
||||
|
||||
export class ManagerTooOldError extends Error {
|
||||
constructor(managerUrl: string) {
|
||||
super(`OpenCode Manager at ${managerUrl} is too old for ocm ${OCM_VERSION}; upgrade the Manager to >= ${MIN_MANAGER_VERSION}`)
|
||||
this.name = 'ManagerTooOldError'
|
||||
}
|
||||
}
|
||||
|
||||
export class RepoProxyNotFoundError extends Error {
|
||||
constructor(managerUrl: string, repoId: number) {
|
||||
super(`repo ${repoId} is not available on OpenCode Manager at ${managerUrl} (missing or not ready)`)
|
||||
this.name = 'RepoProxyNotFoundError'
|
||||
}
|
||||
}
|
||||
|
||||
export class ManagerTokenInvalidError extends Error {
|
||||
constructor(managerUrl: string) {
|
||||
super(`OpenCode Manager rejected the token for ${managerUrl} (HTTP 401). The token may have been rotated: copy the current one from Settings -> Manager Internal Token, then run \`ocm login ${managerUrl}\` to store it again.`)
|
||||
this.name = 'ManagerTokenInvalidError'
|
||||
}
|
||||
}
|
||||
|
||||
export class RepoProxyResponseError extends Error {
|
||||
constructor(managerUrl: string, status: number, body: string) {
|
||||
const detail = body.trim()
|
||||
super(`OpenCode Manager at ${managerUrl} returned HTTP ${status} from the repo proxy${detail ? `: ${detail}` : ''}`)
|
||||
this.name = 'RepoProxyResponseError'
|
||||
}
|
||||
}
|
||||
|
||||
export class RepoProxyUnreachableError extends Error {
|
||||
constructor(managerUrl: string, cause: unknown) {
|
||||
super(`could not reach OpenCode Manager at ${managerUrl}: ${describeCause(cause)}`, { cause })
|
||||
this.name = 'RepoProxyUnreachableError'
|
||||
}
|
||||
}
|
||||
|
||||
export type WarmRepoProxyOptions = {
|
||||
attempts?: number
|
||||
fetch?: typeof fetch
|
||||
wait?: (ms: number) => Promise<void>
|
||||
}
|
||||
|
||||
export function repoProxyBaseUrl(managerUrl: string): string {
|
||||
return `${managerUrl}/api/opencode-proxy`
|
||||
}
|
||||
|
||||
export function repoProxyUrl(managerUrl: string, repoId: number): string {
|
||||
return `${repoProxyBaseUrl(managerUrl)}/repos/${repoId}`
|
||||
}
|
||||
|
||||
function isRepoNotFoundBody(body: string): boolean {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(body)
|
||||
return typeof parsed === 'object' && parsed !== null && (parsed as { error?: unknown }).error === 'Repo not found'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function warmRepoProxy(managerUrl: string, token: string, repoId: number, options: WarmRepoProxyOptions = {}): Promise<void> {
|
||||
const fetchImpl = options.fetch ?? fetch
|
||||
const attempts = Math.max(1, options.attempts ?? 3)
|
||||
const wait = options.wait ?? delay
|
||||
const url = `${repoProxyUrl(managerUrl, repoId)}/api/session?limit=1`
|
||||
|
||||
for (let attempt = 1; attempt <= attempts; attempt++) {
|
||||
let res: Response | null = null
|
||||
let networkError: unknown
|
||||
try {
|
||||
res = await fetchImpl(url, { headers: { Authorization: `Bearer ${token}` } })
|
||||
} catch (err) {
|
||||
networkError = err
|
||||
}
|
||||
|
||||
const isFinalAttempt = attempt === attempts
|
||||
|
||||
if (res) {
|
||||
const body = await res.text().catch(() => '')
|
||||
if (res.ok) return
|
||||
if (res.status === 404) {
|
||||
throw isRepoNotFoundBody(body) ? new RepoProxyNotFoundError(managerUrl, repoId) : new ManagerTooOldError(managerUrl)
|
||||
}
|
||||
if (res.status === 401) {
|
||||
throw new ManagerTokenInvalidError(managerUrl)
|
||||
}
|
||||
if (isFinalAttempt) {
|
||||
throw new RepoProxyResponseError(managerUrl, res.status, body)
|
||||
}
|
||||
} else if (isFinalAttempt) {
|
||||
throw new RepoProxyUnreachableError(managerUrl, networkError)
|
||||
}
|
||||
|
||||
await wait(attempt * 500)
|
||||
}
|
||||
}
|
||||
+60
-142
@@ -1,82 +1,53 @@
|
||||
export type HistoryEventRow = { id: string; aggregate_id: string; seq: number; type: string; data: Record<string, unknown> }
|
||||
export type ReplayEvent = { id: string; aggregateID: string; seq: number; type: string; data: Record<string, unknown> }
|
||||
export type CollectResult =
|
||||
| { kind: 'ok'; events: ReplayEvent[] }
|
||||
| { kind: 'empty' }
|
||||
| { kind: 'gap'; missingSeq: number }
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
|
||||
|
||||
export type RewriteContext = { localRoot: string; remoteRoot: string }
|
||||
|
||||
export function collectSessionEvents(rows: HistoryEventRow[], sessionID: string): CollectResult {
|
||||
const filtered = rows.filter((r) => r.aggregate_id === sessionID)
|
||||
if (filtered.length === 0) return { kind: 'empty' }
|
||||
export function rewriteTransferForRemote(data: SessionTransferData, ctx: RewriteContext): SessionTransferData {
|
||||
const cloned = structuredClone(data)
|
||||
cloned.info.location.directory = relocatePath(cloned.info.location.directory, ctx)
|
||||
relocateUris(cloned.messages, ctx)
|
||||
return cloned
|
||||
}
|
||||
|
||||
const sorted = [...filtered].sort((a, b) => a.seq - b.seq)
|
||||
|
||||
if (sorted[0]!.seq !== 0) return { kind: 'gap', missingSeq: 0 }
|
||||
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
if (sorted[i]!.seq !== sorted[i - 1]!.seq + 1) {
|
||||
return { kind: 'gap', missingSeq: sorted[i - 1]!.seq + 1 }
|
||||
}
|
||||
function relocateUris(value: unknown, ctx: RewriteContext): void {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) relocateUris(item, ctx)
|
||||
return
|
||||
}
|
||||
|
||||
const events: ReplayEvent[] = sorted.map((r) => ({
|
||||
id: r.id,
|
||||
aggregateID: r.aggregate_id,
|
||||
seq: r.seq,
|
||||
type: r.type,
|
||||
data: r.data,
|
||||
}))
|
||||
|
||||
return { kind: 'ok', events }
|
||||
if (!value || typeof value !== 'object') return
|
||||
const record = value as Record<string, unknown>
|
||||
if (typeof record.uri === 'string') record.uri = relocateUri(record.uri, ctx)
|
||||
for (const child of Object.values(record)) relocateUris(child, ctx)
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites collected replay events for replay on a remote Manager server.
|
||||
*
|
||||
* Coercion rule for `data.timestamp` matches the prior implementation in
|
||||
* commit 686c820d (`coerceReplayBodyTimestamps`): ISO 8601 string timestamps
|
||||
* are converted to epoch milliseconds via `Date.parse`; already-numeric values
|
||||
* are left untouched.
|
||||
*/
|
||||
export function rewriteEventsForRemote(events: ReplayEvent[], ctx: RewriteContext): ReplayEvent[] {
|
||||
return events.map((event) => {
|
||||
const data = deepClone(event.data)
|
||||
function relocateUri(uri: string, ctx: RewriteContext): string {
|
||||
const fileUrl = parseLocalFileUrl(uri)
|
||||
if (!fileUrl) return relocatePath(uri, ctx)
|
||||
|
||||
if (shouldRewriteDirectory(event.type)) {
|
||||
rewriteDirectory(data, 'info', ctx)
|
||||
stripWorkspaceID(data, 'info')
|
||||
}
|
||||
|
||||
if (isMovedEvent(event.type)) {
|
||||
rewriteDirectory(data, 'location', ctx)
|
||||
stripWorkspaceID(data, 'location')
|
||||
}
|
||||
|
||||
if (isMessageUpdated(event.type)) {
|
||||
rewriteMessagePath(data, ctx)
|
||||
}
|
||||
|
||||
coerceTimestamp(data)
|
||||
|
||||
return { ...event, data }
|
||||
})
|
||||
const relocated = relocatePath(fileUrl.path, ctx)
|
||||
if (relocated === fileUrl.path) return uri
|
||||
return `${pathToFileURL(relocated).href}${fileUrl.search}${fileUrl.hash}`
|
||||
}
|
||||
|
||||
function shouldRewriteDirectory(type: string): boolean {
|
||||
return type.startsWith('session.created') || type.startsWith('session.updated')
|
||||
}
|
||||
function parseLocalFileUrl(uri: string): { path: string; search: string; hash: string } | null {
|
||||
if (!uri.startsWith('file:')) return null
|
||||
|
||||
function isMovedEvent(type: string): boolean {
|
||||
return type.startsWith('session.next.moved')
|
||||
}
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(uri)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (url.protocol !== 'file:' || (url.host !== '' && url.host !== 'localhost')) return null
|
||||
|
||||
function isMessageUpdated(type: string): boolean {
|
||||
return type.startsWith('message.updated')
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === 'object' ? (value as Record<string, unknown>) : null
|
||||
let path: string
|
||||
try {
|
||||
path = fileURLToPath(url)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return { path, search: url.search, hash: url.hash }
|
||||
}
|
||||
|
||||
function relocatePath(path: string, ctx: RewriteContext): string {
|
||||
@@ -85,97 +56,44 @@ function relocatePath(path: string, ctx: RewriteContext): string {
|
||||
return path
|
||||
}
|
||||
|
||||
function relocateField(obj: Record<string, unknown>, key: string, ctx: RewriteContext): void {
|
||||
const value = obj[key]
|
||||
if (typeof value === 'string') obj[key] = relocatePath(value, ctx)
|
||||
}
|
||||
|
||||
function rewriteDirectory(
|
||||
data: Record<string, unknown>,
|
||||
key: 'info' | 'location',
|
||||
ctx: RewriteContext,
|
||||
): void {
|
||||
const container = asRecord(data[key])
|
||||
if (container) relocateField(container, 'directory', ctx)
|
||||
}
|
||||
|
||||
function rewriteMessagePath(data: Record<string, unknown>, ctx: RewriteContext): void {
|
||||
const path = asRecord(asRecord(data.info)?.path)
|
||||
if (!path) return
|
||||
relocateField(path, 'cwd', ctx)
|
||||
relocateField(path, 'root', ctx)
|
||||
}
|
||||
|
||||
function stripWorkspaceID(data: Record<string, unknown>, key: 'info' | 'location'): void {
|
||||
const container = asRecord(data[key])
|
||||
if (container) delete container.workspaceID
|
||||
}
|
||||
|
||||
/** Per commit 686c820d: coerce `data.timestamp` from ISO string to epoch ms. */
|
||||
function coerceTimestamp(data: Record<string, unknown>): void {
|
||||
const ts = data.timestamp
|
||||
if (typeof ts !== 'string') return
|
||||
const epoch = Date.parse(ts)
|
||||
if (!Number.isFinite(epoch)) return
|
||||
data.timestamp = epoch
|
||||
}
|
||||
|
||||
export type TransferDeps = {
|
||||
fetchLocalHistory: () => Promise<HistoryEventRow[]>
|
||||
replayEvents: (remoteDirectory: string, events: ReplayEvent[]) => Promise<{ sessionID: string }>
|
||||
onProgress?: (replayed: number, total: number) => void
|
||||
exportSession: (sessionID: string) => Promise<SessionTransferData>
|
||||
importSession: (remoteDirectory: string, data: SessionTransferData) => Promise<{ sessionID: string }>
|
||||
onProgress?: (transferred: number, total: number) => void
|
||||
}
|
||||
|
||||
export type TransferInput = { sessionID: string; localRoot: string; remoteDirectory: string }
|
||||
|
||||
export type TransferResult =
|
||||
| { kind: 'moved'; sessionID: string; replayedEvents: number }
|
||||
| { kind: 'not-found' }
|
||||
| { kind: 'corrupt-history'; missingSeq: number }
|
||||
| { kind: 'replay-failed'; message: string }
|
||||
|
||||
export function planReplayBatches(events: ReplayEvent[], batchSize = 10): ReplayEvent[][] {
|
||||
const batches: ReplayEvent[][] = []
|
||||
for (let i = 0; i < events.length; i += batchSize) {
|
||||
batches.push(events.slice(i, i + batchSize))
|
||||
}
|
||||
return batches
|
||||
}
|
||||
| { kind: 'moved'; sessionID: string; importedMessages: number }
|
||||
| { kind: 'import-failed'; message: string }
|
||||
|
||||
export async function transferSession(input: TransferInput, deps: TransferDeps): Promise<TransferResult> {
|
||||
const rows = await deps.fetchLocalHistory()
|
||||
const collect = collectSessionEvents(rows, input.sessionID)
|
||||
let data: SessionTransferData
|
||||
try {
|
||||
data = await deps.exportSession(input.sessionID)
|
||||
} catch (err) {
|
||||
return { kind: 'import-failed', message: err instanceof Error ? err.message : String(err) }
|
||||
}
|
||||
|
||||
if (collect.kind === 'empty') return { kind: 'not-found' }
|
||||
if (collect.kind === 'gap') return { kind: 'corrupt-history', missingSeq: collect.missingSeq }
|
||||
|
||||
const rewritten = rewriteEventsForRemote(collect.events, {
|
||||
const rewritten = rewriteTransferForRemote(data, {
|
||||
localRoot: input.localRoot,
|
||||
remoteRoot: input.remoteDirectory,
|
||||
})
|
||||
const total = rewritten.messages.length
|
||||
deps.onProgress?.(0, total)
|
||||
|
||||
const batches = planReplayBatches(rewritten)
|
||||
const total = rewritten.length
|
||||
let replayed = 0
|
||||
deps.onProgress?.(replayed, total)
|
||||
|
||||
for (const batch of batches) {
|
||||
try {
|
||||
await deps.replayEvents(input.remoteDirectory, batch)
|
||||
replayed += batch.length
|
||||
deps.onProgress?.(replayed, total)
|
||||
} catch (err) {
|
||||
return { kind: 'replay-failed', message: err instanceof Error ? err.message : String(err) }
|
||||
}
|
||||
let imported: { sessionID: string }
|
||||
try {
|
||||
imported = await deps.importSession(input.remoteDirectory, rewritten)
|
||||
} catch (err) {
|
||||
return { kind: 'import-failed', message: err instanceof Error ? err.message : String(err) }
|
||||
}
|
||||
|
||||
return { kind: 'moved', sessionID: input.sessionID, replayedEvents: replayed }
|
||||
deps.onProgress?.(total, total)
|
||||
return { kind: 'moved', sessionID: imported.sessionID, importedMessages: total }
|
||||
}
|
||||
|
||||
export function moveReminderText(directory: string): string {
|
||||
return `<system-reminder>The user has changed the current working directory to "${directory}". This is still the same project but at a possibly new location; take this into account when working with any files from now on.</system-reminder>`
|
||||
}
|
||||
|
||||
function deepClone<T>(obj: T): T {
|
||||
return JSON.parse(JSON.stringify(obj))
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,38 +1,13 @@
|
||||
import type { TuiPluginApi } from './tui-types.js'
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
|
||||
export function confirmDialog(api: TuiPluginApi, props: { title: string; message: string }): Promise<boolean> {
|
||||
return new Promise<boolean>((resolve) => {
|
||||
let settled = false
|
||||
const settle = (value: boolean, clearDialog = true) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
if (clearDialog) api.ui.dialog.clear()
|
||||
resolve(value)
|
||||
}
|
||||
api.ui.dialog.replace(
|
||||
() => api.ui.DialogConfirm({ ...props, onConfirm: () => settle(true), onCancel: () => settle(false) }),
|
||||
() => settle(false, false),
|
||||
)
|
||||
})
|
||||
export function confirmDialog(context: Context, props: { title: string; message: string }): Promise<boolean> {
|
||||
return context.ui.dialog.confirm(props).then((value) => value === true)
|
||||
}
|
||||
|
||||
export function selectDialog<Value>(
|
||||
api: TuiPluginApi,
|
||||
context: Context,
|
||||
title: string,
|
||||
options: { title: string; description?: string; value: Value }[],
|
||||
): Promise<Value | undefined> {
|
||||
return new Promise<Value | undefined>((resolve) => {
|
||||
let settled = false
|
||||
const settle = (value: Value | undefined, clearDialog = true) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
if (clearDialog) api.ui.dialog.clear()
|
||||
resolve(value)
|
||||
}
|
||||
const mapped = options.map((o) => ({ ...o, onSelect: () => settle(o.value) }))
|
||||
api.ui.dialog.replace(
|
||||
() => api.ui.DialogSelect({ title, options: mapped, onSelect: (o) => settle(o.value as Value) }),
|
||||
() => settle(undefined, false),
|
||||
)
|
||||
})
|
||||
}
|
||||
return context.ui.dialog.select({ title, options })
|
||||
}
|
||||
+75
-56
@@ -1,4 +1,4 @@
|
||||
import type { TuiPluginApi } from './tui-types.js'
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
import { readInstallNotice, readState } from './state.js'
|
||||
import { getToken } from './internal-token-store.js'
|
||||
import { TokenStoreError } from './token-store.js'
|
||||
@@ -9,38 +9,46 @@ import { prepareMirror, checkPushDivergence, describePushDivergence, mirrorUpFas
|
||||
import type { MirrorPlan, RemoteRepoSummary } from './mirror.js'
|
||||
import { getBranchName } from './local-repo.js'
|
||||
import { transferSession, moveReminderText } from './session-move.js'
|
||||
import { createManagerReplay, createManagerPromptAsync } from './remote-replay.js'
|
||||
import { readSessionEvents } from './local-history.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, replayProgress } from './move-progress.js'
|
||||
import { pushPhaseProgress, importProgress } from './move-progress.js'
|
||||
import { warmRepoProxy } from './repo-proxy.js'
|
||||
import type { MoveProgress } from './move-progress.js'
|
||||
|
||||
export type MoveProgressSetter = (progress: MoveProgress | null) => void
|
||||
|
||||
export async function setupOcm(api: TuiPluginApi, setMoveProgress: MoveProgressSetter): Promise<void> {
|
||||
showInstallNotice(api)
|
||||
api.keymap.registerLayer({
|
||||
commands: [
|
||||
{
|
||||
name: 'ocm.session.move',
|
||||
title: 'Move session to Manager',
|
||||
desc: 'Push repo state and move this session to OpenCode Manager',
|
||||
category: 'OpenCode Manager',
|
||||
namespace: 'palette',
|
||||
slashName: 'ocm-move',
|
||||
run: () => runSessionMove(api, setMoveProgress),
|
||||
},
|
||||
],
|
||||
export async function setupOcm(context: Context, setMoveProgress: MoveProgressSetter): Promise<() => void> {
|
||||
showInstallNotice(context)
|
||||
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
|
||||
},
|
||||
})
|
||||
api.lifecycle.onDispose(() => runPendingWarp())
|
||||
return () => runPendingWarp()
|
||||
}
|
||||
|
||||
function showInstallNotice(api: TuiPluginApi): void {
|
||||
function showInstallNotice(context: Context): void {
|
||||
const notice = readInstallNotice()
|
||||
if (!notice) return
|
||||
|
||||
api.ui.toast({
|
||||
context.ui.toast.show({
|
||||
variant: 'success',
|
||||
title: 'ocm installed',
|
||||
message: notice.pathMissing
|
||||
@@ -50,6 +58,16 @@ function showInstallNotice(api: TuiPluginApi): 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))
|
||||
@@ -83,24 +101,24 @@ async function resolveMoveTarget(managerApi: ManagerApi, matched: RemoteRepoSumm
|
||||
return managerApi.mirrorTargetPlan(matched.repoId, localBranch)
|
||||
}
|
||||
|
||||
async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSetter): Promise<void> {
|
||||
async function runSessionMove(context: Context, setMoveProgress: MoveProgressSetter): Promise<void> {
|
||||
try {
|
||||
const current = api.route.current
|
||||
if (current.name !== 'session' || !current.params) {
|
||||
api.ui.toast({ variant: 'error', message: 'Not in a session' })
|
||||
const current = context.ui.router.current()
|
||||
if (current.type !== 'session') {
|
||||
context.ui.toast.show({ variant: 'error', message: 'Not in a session' })
|
||||
return
|
||||
}
|
||||
const sessionID = String(current.params.sessionID)
|
||||
const sessionID = current.sessionID
|
||||
|
||||
const session = api.state.session.get(sessionID)
|
||||
if (!session?.directory) {
|
||||
api.ui.toast({ variant: 'error', message: 'Session has no directory' })
|
||||
const session = context.data.session.get(sessionID)
|
||||
if (!session?.location.directory) {
|
||||
context.ui.toast.show({ variant: 'error', message: 'Session has no directory' })
|
||||
return
|
||||
}
|
||||
|
||||
const state = readState()
|
||||
if (!state?.managerUrl) {
|
||||
api.ui.toast({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
|
||||
context.ui.toast.show({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -109,34 +127,43 @@ async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSe
|
||||
token = await getToken(state.managerUrl)
|
||||
} catch (err) {
|
||||
const reason = err instanceof TokenStoreError ? err.message : String(err)
|
||||
api.ui.toast({ variant: 'error', message: `Token store unavailable: ${reason}` })
|
||||
context.ui.toast.show({ variant: 'error', message: `Token store unavailable: ${reason}` })
|
||||
return
|
||||
}
|
||||
if (!token) {
|
||||
api.ui.toast({ variant: 'error', message: `No token stored. Run \`ocm login ${state.managerUrl}\`.` })
|
||||
context.ui.toast.show({ variant: 'error', message: `No token stored. Run \`ocm login ${state.managerUrl}\`.` })
|
||||
return
|
||||
}
|
||||
|
||||
const repos = await fetchRepos(state.managerUrl, token)
|
||||
const plan = await prepareMirror(session.directory, toRemoteRepoSummaries(repos))
|
||||
const plan = await prepareMirror(session.location.directory, toRemoteRepoSummaries(repos))
|
||||
|
||||
if (plan.matched.length === 0) {
|
||||
api.ui.toast({ variant: 'error', message: 'No matching Manager repo; run `ocm push --create` first' })
|
||||
context.ui.toast.show({ variant: 'error', message: 'No matching Manager repo; run `ocm push --create` first' })
|
||||
return
|
||||
}
|
||||
|
||||
const localBranch = getBranchName(plan.repoRoot)
|
||||
const matched = pickMatchedRepo(plan.matched, localBranch)
|
||||
?? await selectDialog(api, 'Move session to Manager repo', plan.matched.map((r) => ({ title: r.name, description: `id=${r.repoId} branch=${r.branch ?? '-'}`, value: r })))
|
||||
?? await selectDialog(context, 'Move session to Manager repo', plan.matched.map((r) => ({ title: r.name, description: `id=${r.repoId} branch=${r.branch ?? '-'}`, value: r })))
|
||||
if (!matched) return
|
||||
const matchedRepoId = matched.repoId
|
||||
const remoteRepo = repos.find((r) => r.repoId === matchedRepoId)!
|
||||
|
||||
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)
|
||||
|
||||
const proceed = await confirmDialog(api, {
|
||||
const proceed = await confirmDialog(context, {
|
||||
title: 'Move session to Manager',
|
||||
message: moveConfirmMessage(matched.name, target, discardReasons),
|
||||
})
|
||||
@@ -159,42 +186,34 @@ async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSe
|
||||
const result = await transferSession(
|
||||
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
|
||||
{
|
||||
fetchLocalHistory: () => readSessionEvents(sessionID),
|
||||
replayEvents: createManagerReplay(state.managerUrl, token),
|
||||
onProgress: (replayed, total) => setMoveProgress(replayProgress(replayed, total)),
|
||||
exportSession: (id) => context.client.session.export({ sessionID: id }),
|
||||
importSession: transfer.importSession,
|
||||
onProgress: (transferred, total) => setMoveProgress(importProgress(transferred, total)),
|
||||
},
|
||||
)
|
||||
|
||||
switch (result.kind) {
|
||||
case 'moved': {
|
||||
setMoveProgress({ label: 'notifying moved session', fraction: null })
|
||||
await createManagerPromptAsync(state.managerUrl, token)(remoteDirectory, result.sessionID, moveReminderText(remoteDirectory)).catch(() => undefined)
|
||||
await transfer.addReminder(result.sessionID, moveReminderText(remoteDirectory)).catch(() => undefined)
|
||||
setMoveProgress(null)
|
||||
const warp = await confirmDialog(api, { title: 'Attach to moved session?', message: 'Exit this TUI and attach to the moved session on the Manager now?' })
|
||||
const warp = await confirmDialog(context, { title: 'Attach to moved session?', message: 'Exit this TUI and attach to the moved session on the Manager now?' })
|
||||
if (warp) {
|
||||
await fetch(`${state.managerUrl}/api/opencode-proxy/session?directory=${encodeURIComponent(remoteDirectory)}`, { headers: { authorization: `Bearer ${token}` } }).catch(() => undefined)
|
||||
setPendingWarp({ managerUrl: state.managerUrl, token, directory: remoteDirectory, sessionID: result.sessionID, repoName: matched.name })
|
||||
api.keymap.dispatchCommand('app.exit')
|
||||
await warmRepoProxy(state.managerUrl, token, pushed.repoId)
|
||||
setPendingWarp({ managerUrl: state.managerUrl, token, repoId: pushed.repoId, sessionID: result.sessionID, repoName: matched.name })
|
||||
context.keymap.dispatch('app.exit')
|
||||
return
|
||||
}
|
||||
api.ui.toast({ variant: 'success', message: `Session moved to Manager (${result.replayedEvents} events). Local copy kept — run \`ocm\` to attach.` })
|
||||
context.ui.toast.show({ variant: 'success', message: `Session moved to Manager (${result.importedMessages} messages). Local copy kept — run \`ocm\` to attach.` })
|
||||
break
|
||||
}
|
||||
case 'not-found':
|
||||
api.ui.toast({ variant: 'error', message: 'No durable history found for this session' })
|
||||
break
|
||||
case 'corrupt-history':
|
||||
api.ui.toast({ variant: 'error', message: `Session history has a gap at sequence ${result.missingSeq}` })
|
||||
break
|
||||
case 'replay-failed':
|
||||
api.ui.toast({ variant: 'error', message: `Replay failed: ${result.message}` })
|
||||
case 'import-failed':
|
||||
context.ui.toast.show({ variant: 'error', message: `Session import failed: ${result.message}` })
|
||||
break
|
||||
}
|
||||
} catch (err) {
|
||||
api.ui.toast({ variant: 'error', message: err instanceof Error ? err.message : String(err) })
|
||||
context.ui.toast.show({ variant: 'error', message: err instanceof Error ? err.message : String(err) })
|
||||
} finally {
|
||||
setMoveProgress(null)
|
||||
}
|
||||
}
|
||||
|
||||
export { readRemoteContext } from './remote-context.js'
|
||||
@@ -1,34 +0,0 @@
|
||||
import type { RGBA } from '@opentui/core'
|
||||
|
||||
export type TuiThemeColors = {
|
||||
accent: RGBA
|
||||
text: RGBA
|
||||
textMuted: RGBA
|
||||
backgroundElement: RGBA
|
||||
}
|
||||
|
||||
export type TuiSlotContext = { theme: { readonly current: TuiThemeColors } }
|
||||
|
||||
export type TuiSlotRegistration = {
|
||||
order?: number
|
||||
slots: Record<string, (ctx: TuiSlotContext, props: Record<string, unknown>) => unknown>
|
||||
}
|
||||
|
||||
export type TuiRouteCurrent = { name: 'session'; params: { sessionID: string } } | { name: string; params?: Record<string, unknown> }
|
||||
export type TuiSessionInfo = { id: string; directory: string; title?: string }
|
||||
export type TuiToast = { title?: string; message: string; variant?: 'info' | 'success' | 'error' | 'warning'; duration?: number }
|
||||
export type TuiCommandDef = { name: string; title: string; desc?: string; category?: string; namespace?: string; slashName?: string; run: () => void | Promise<void> }
|
||||
export type TuiDialogConfirmProps = { title: string; message: string; onConfirm?: () => void; onCancel?: () => void }
|
||||
export type TuiDialogSelectOption<Value = unknown> = { title: string; value?: Value; description?: string; disabled?: boolean; onSelect?: () => void }
|
||||
export type TuiDialogSelectProps<Value = unknown> = { title: string; placeholder?: string; options: TuiDialogSelectOption<Value>[]; onSelect?: (option: TuiDialogSelectOption<Value>) => void }
|
||||
export type TuiDialogStack = { replace: (render: () => unknown, onClose?: () => void) => void; clear: () => void }
|
||||
export type TuiLifecycle = { readonly signal: AbortSignal; onDispose: (fn: () => void | Promise<void>) => () => void }
|
||||
export type TuiPluginApi = {
|
||||
route: { readonly current: TuiRouteCurrent }
|
||||
state: { session: { get: (sessionID: string) => TuiSessionInfo | undefined } }
|
||||
ui: { toast: (input: TuiToast) => void; DialogConfirm: (props: TuiDialogConfirmProps) => unknown; DialogSelect: <Value = unknown>(props: TuiDialogSelectProps<Value>) => unknown; dialog: TuiDialogStack }
|
||||
keymap: { registerLayer: (layer: { commands: TuiCommandDef[]; bindings?: Record<string, unknown> }) => unknown; dispatchCommand: (name: string) => unknown }
|
||||
slots: { register: (registration: TuiSlotRegistration) => string }
|
||||
lifecycle: TuiLifecycle
|
||||
}
|
||||
export type TuiPluginModule = { id?: string; tui: (api: TuiPluginApi, options?: Record<string, unknown>) => Promise<void> }
|
||||
+37
-48
@@ -1,60 +1,49 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { createSignal, createEffect, onCleanup, Show } from 'solid-js'
|
||||
import { setupOcm, readRemoteContext } from './tui-plugin.js'
|
||||
import { Plugin } from '@opencode/plugin/tui'
|
||||
import { setupOcm } from './tui-plugin.js'
|
||||
import { formatMoveProgress } from './move-progress.js'
|
||||
import type { MoveProgress } from './move-progress.js'
|
||||
import type { TuiPluginApi, TuiPluginModule, TuiSlotContext } from './tui-types.js'
|
||||
import { readRemoteContext } from './remote-context.js'
|
||||
|
||||
const SPINNER_INTERVAL_MS = 80
|
||||
|
||||
const tui = async (api: TuiPluginApi): Promise<void> => {
|
||||
const [moveProgress, setMoveProgress] = createSignal<MoveProgress | null>(null)
|
||||
await setupOcm(api, setMoveProgress)
|
||||
export default Plugin.define({
|
||||
id: 'ocm',
|
||||
async setup(context) {
|
||||
const [moveProgress, setMoveProgress] = createSignal<MoveProgress | null>(null)
|
||||
|
||||
const moveIndicator = (ctx: TuiSlotContext) => {
|
||||
const theme = ctx.theme.current
|
||||
const [frame, setFrame] = createSignal(0)
|
||||
createEffect(() => {
|
||||
if (!moveProgress()) return
|
||||
const timer = setInterval(() => setFrame((f) => f + 1), SPINNER_INTERVAL_MS)
|
||||
onCleanup(() => clearInterval(timer))
|
||||
})
|
||||
return (
|
||||
<box flexDirection="row" flexShrink={0}>
|
||||
<Show when={moveProgress()}>
|
||||
{(progress) => <text fg={theme.accent}>{formatMoveProgress(progress(), frame())}</text>}
|
||||
</Show>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
const moveIndicator = () => {
|
||||
const [frame, setFrame] = createSignal(0)
|
||||
createEffect(() => {
|
||||
if (!moveProgress()) return
|
||||
const timer = setInterval(() => setFrame((f) => f + 1), SPINNER_INTERVAL_MS)
|
||||
onCleanup(() => clearInterval(timer))
|
||||
})
|
||||
return (
|
||||
<box flexDirection="row" flexShrink={0}>
|
||||
<Show when={moveProgress()}>
|
||||
{(progress) => <text fg={context.theme.hue.accent[200]}>{formatMoveProgress(progress(), frame())}</text>}
|
||||
</Show>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
api.slots.register({
|
||||
order: 290,
|
||||
slots: { session_prompt_right: moveIndicator },
|
||||
})
|
||||
context.ui.slot({ append: 'prompt.footer.status', render: moveIndicator })
|
||||
|
||||
const remote = readRemoteContext(process.env)
|
||||
if (!remote) return
|
||||
const remote = readRemoteContext(process.env)
|
||||
if (remote) {
|
||||
const indicator = () => (
|
||||
<box flexDirection="row" flexShrink={0} gap={1}>
|
||||
<text fg={context.theme.hue.accent[200]}>{remote.managerHost}</text>
|
||||
{remote.repoName && <text fg={context.theme.text.muted}> · {remote.repoName}</text>}
|
||||
</box>
|
||||
)
|
||||
|
||||
const indicator = (ctx: TuiSlotContext) => {
|
||||
const theme = ctx.theme.current
|
||||
return (
|
||||
<box flexDirection="row" flexShrink={0} gap={1}>
|
||||
<text fg={theme.accent}>{remote.managerHost}</text>
|
||||
{remote.repoName && (
|
||||
<text fg={theme.textMuted}> · {remote.repoName}</text>
|
||||
)}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
context.ui.slot({ append: 'prompt.footer.status', render: indicator })
|
||||
context.ui.slot({ append: 'home.footer.status', render: indicator })
|
||||
}
|
||||
|
||||
api.slots.register({
|
||||
order: 300,
|
||||
slots: {
|
||||
session_prompt_right: indicator,
|
||||
home_prompt_right: indicator,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export default { id: 'ocm', tui } satisfies TuiPluginModule
|
||||
return setupOcm(context, setMoveProgress)
|
||||
},
|
||||
})
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
+23
-17
@@ -1,12 +1,22 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { buildRemoteAttachEnv } from './remote-context.js'
|
||||
import { repoProxyUrl } from './repo-proxy.js'
|
||||
|
||||
export type WarpTarget = {
|
||||
export type AttachTarget = {
|
||||
managerUrl: string
|
||||
token: string
|
||||
directory: string
|
||||
sessionID: string
|
||||
repoId: number
|
||||
repoName: string
|
||||
sessionID?: string
|
||||
}
|
||||
|
||||
export type WarpTarget = AttachTarget & {
|
||||
sessionID: string
|
||||
}
|
||||
|
||||
export type AttachInvocation = {
|
||||
args: string[]
|
||||
env: NodeJS.ProcessEnv
|
||||
}
|
||||
|
||||
export type WarpSpawn = (
|
||||
@@ -27,26 +37,22 @@ export function takePendingWarp(): WarpTarget | undefined {
|
||||
return t
|
||||
}
|
||||
|
||||
export function buildAttachArgs(target: WarpTarget): string[] {
|
||||
return [
|
||||
'attach',
|
||||
`${target.managerUrl}/api/opencode-proxy`,
|
||||
'--dir', target.directory,
|
||||
'--session', target.sessionID,
|
||||
'--password', target.token,
|
||||
'--username', 'opencode',
|
||||
]
|
||||
export function buildAttachInvocation(target: AttachTarget): AttachInvocation {
|
||||
const args = ['--server', repoProxyUrl(target.managerUrl, target.repoId)]
|
||||
if (target.sessionID) args.push('--session', target.sessionID)
|
||||
return {
|
||||
args,
|
||||
env: { ...process.env, OPENCODE_PASSWORD: target.token, ...buildRemoteAttachEnv(target.managerUrl, target.repoName) },
|
||||
}
|
||||
}
|
||||
|
||||
export function runPendingWarp(spawn: WarpSpawn = spawnSync): void {
|
||||
const target = takePendingWarp()
|
||||
if (!target) return
|
||||
try {
|
||||
spawn('opencode', buildAttachArgs(target), {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, ...buildRemoteAttachEnv(target.managerUrl, target.repoName) },
|
||||
})
|
||||
const { args, env } = buildAttachInvocation(target)
|
||||
spawn('opencode', args, { stdio: 'inherit', env })
|
||||
} catch {
|
||||
void 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync, utimesSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { resolveOpencodeDbPath } from '../src/local-history.js'
|
||||
|
||||
describe('resolveOpencodeDbPath', () => {
|
||||
let dataHome: string
|
||||
let dataDir: string
|
||||
const savedEnv = { XDG_DATA_HOME: process.env.XDG_DATA_HOME, OPENCODE_DB: process.env.OPENCODE_DB }
|
||||
|
||||
beforeEach(() => {
|
||||
dataHome = mkdtempSync(join(tmpdir(), 'ocm-dbpath-'))
|
||||
dataDir = join(dataHome, 'opencode')
|
||||
mkdirSync(dataDir)
|
||||
process.env.XDG_DATA_HOME = dataHome
|
||||
delete process.env.OPENCODE_DB
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(dataHome, { recursive: true, force: true })
|
||||
if (savedEnv.XDG_DATA_HOME === undefined) delete process.env.XDG_DATA_HOME
|
||||
else process.env.XDG_DATA_HOME = savedEnv.XDG_DATA_HOME
|
||||
if (savedEnv.OPENCODE_DB === undefined) delete process.env.OPENCODE_DB
|
||||
else process.env.OPENCODE_DB = savedEnv.OPENCODE_DB
|
||||
})
|
||||
|
||||
it('honours an absolute OPENCODE_DB override', () => {
|
||||
process.env.OPENCODE_DB = '/tmp/custom.db'
|
||||
expect(resolveOpencodeDbPath()).toBe('/tmp/custom.db')
|
||||
})
|
||||
|
||||
it('resolves a relative OPENCODE_DB override against the data dir', () => {
|
||||
process.env.OPENCODE_DB = 'custom.db'
|
||||
expect(resolveOpencodeDbPath()).toBe(join(dataDir, 'custom.db'))
|
||||
})
|
||||
|
||||
it('prefers the default opencode.db when present', () => {
|
||||
writeFileSync(join(dataDir, 'opencode.db'), '', { flag: 'w' })
|
||||
writeFileSync(join(dataDir, 'opencode-dev.db'), '')
|
||||
expect(resolveOpencodeDbPath()).toBe(join(dataDir, 'opencode.db'))
|
||||
})
|
||||
|
||||
it('falls back to the newest channel variant', () => {
|
||||
const older = join(dataDir, 'opencode-old.db')
|
||||
const newer = join(dataDir, 'opencode-dev.db')
|
||||
writeFileSync(older, '')
|
||||
writeFileSync(newer, '')
|
||||
utimesSync(older, new Date('2024-01-01'), new Date('2024-01-01'))
|
||||
expect(resolveOpencodeDbPath()).toBe(newer)
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { renderProgressBar, formatMoveProgress, pushPhaseProgress, replayProgress } from '../src/move-progress'
|
||||
import { renderProgressBar, formatMoveProgress, pushPhaseProgress, importProgress } from '../src/move-progress'
|
||||
|
||||
describe('renderProgressBar', () => {
|
||||
it('fills proportionally and reports a percentage', () => {
|
||||
@@ -41,8 +41,8 @@ describe('phase mapping', () => {
|
||||
expect(pushPhaseProgress({ kind: 'patching' })).toEqual({ label: 'applying local changes', fraction: null })
|
||||
})
|
||||
|
||||
it('maps replay counts to a fraction', () => {
|
||||
expect(replayProgress(3, 12)).toEqual({ label: 'replaying session 3/12 events', fraction: 0.25 })
|
||||
expect(replayProgress(0, 0).fraction).toBeNull()
|
||||
it('maps import counts to a fraction', () => {
|
||||
expect(importProgress(3, 12)).toEqual({ label: 'importing session 3/12 messages', fraction: 0.25 })
|
||||
expect(importProgress(0, 0).fraction).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,83 +0,0 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { createManagerReplay, createManagerPromptAsync } from '../src/remote-replay.js'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('createManagerReplay', () => {
|
||||
it('POSTs to the correct URL with bearer auth and body shape', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ sessionID: 'ses_new' }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const replay = createManagerReplay('https://manager.example', 'tok_123')
|
||||
const result = await replay('/workspace/repo', [
|
||||
{ id: 'e1', aggregateID: 'ses_a', seq: 0, type: 'session.created.1', data: { info: { directory: '/workspace/repo' } } },
|
||||
])
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledOnce()
|
||||
const [url, init] = fetchMock.mock.calls[0]!
|
||||
expect(url).toBe('https://manager.example/api/opencode-proxy/sync/replay?directory=%2Fworkspace%2Frepo')
|
||||
expect(init.method).toBe('POST')
|
||||
expect(init.headers.authorization).toBe('Bearer tok_123')
|
||||
expect(init.body).toBe(JSON.stringify({ directory: '/workspace/repo', events: [{ id: 'e1', aggregateID: 'ses_a', seq: 0, type: 'session.created.1', data: { info: { directory: '/workspace/repo' } } }] }))
|
||||
expect(result).toEqual({ sessionID: 'ses_new' })
|
||||
})
|
||||
|
||||
it('throws on non-ok response with status code', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: () => Promise.resolve('internal error'),
|
||||
}))
|
||||
|
||||
const replay = createManagerReplay('https://manager.example', 'tok_123')
|
||||
|
||||
await expect(replay('/workspace/repo', [])).rejects.toThrow('replay failed (500): internal error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('createManagerPromptAsync', () => {
|
||||
it('POSTs to the correct URL with sessionID, directory, and body', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const prompt = createManagerPromptAsync('https://manager.example', 'tok_abc')
|
||||
await prompt('/workspace/repo', 'ses/a=b&c', 'hello world')
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledOnce()
|
||||
const [url, init] = fetchMock.mock.calls[0]!
|
||||
expect(url).toBe('https://manager.example/api/opencode-proxy/session/ses%2Fa%3Db%26c/prompt_async?directory=%2Fworkspace%2Frepo')
|
||||
expect(init.method).toBe('POST')
|
||||
expect(init.headers.authorization).toBe('Bearer tok_abc')
|
||||
expect(init.headers['content-type']).toBe('application/json')
|
||||
expect(init.body).toBe(JSON.stringify({ noReply: true, parts: [{ type: 'text', text: 'hello world', synthetic: true }] }))
|
||||
})
|
||||
|
||||
it('throws on non-ok response including status code', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 404,
|
||||
text: () => Promise.resolve('not found'),
|
||||
}))
|
||||
|
||||
const prompt = createManagerPromptAsync('https://manager.example', 'tok_abc')
|
||||
|
||||
await expect(prompt('/workspace/repo', 'ses/a=b&c', 'text')).rejects.toThrow('prompt_async failed (404): not found')
|
||||
})
|
||||
|
||||
it('handles text() rejection gracefully', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 502,
|
||||
text: () => Promise.reject(new Error('body read fail')),
|
||||
}))
|
||||
|
||||
const prompt = createManagerPromptAsync('https://manager.example', 'tok_abc')
|
||||
|
||||
await expect(prompt('/workspace/repo', 'ses/a=b&c', 'text')).rejects.toThrow('prompt_async failed (502): ')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { createManagerSessionTransfer } from '../src/remote-session.js'
|
||||
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const transferData = {
|
||||
info: { id: 'ses_a' },
|
||||
messages: [{ id: 'msg_1' }],
|
||||
} as unknown as SessionTransferData
|
||||
|
||||
describe('createManagerSessionTransfer', () => {
|
||||
it('imports through the manager proxy with basic auth and the remote location', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ data: { id: 'ses_new' } }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const transfer = createManagerSessionTransfer('https://manager.example', 'tok_123')
|
||||
const result = await transfer.importSession('/workspace/repo', transferData)
|
||||
|
||||
expect(result).toEqual({ sessionID: 'ses_new' })
|
||||
expect(fetchMock).toHaveBeenCalledOnce()
|
||||
const [url, init] = fetchMock.mock.calls[0]!
|
||||
expect(String(url)).toBe('https://manager.example/api/opencode-proxy/api/experimental/session/import')
|
||||
expect(init.method).toBe('POST')
|
||||
const headers = init.headers as Headers
|
||||
expect(headers.get('authorization')).toBe(`Basic ${Buffer.from('opencode:tok_123').toString('base64')}`)
|
||||
const body = JSON.parse(init.body as string) as Record<string, unknown>
|
||||
expect(body.location).toEqual({ directory: '/workspace/repo' })
|
||||
expect(body.info).toEqual(transferData.info)
|
||||
expect(body.messages).toEqual(transferData.messages)
|
||||
})
|
||||
|
||||
it('sends a synthetic reminder through the manager proxy', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({ data: {} }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const transfer = createManagerSessionTransfer('https://manager.example', 'tok_123')
|
||||
await transfer.addReminder('ses_new', 'hello')
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0]!
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import packageJson from '../package.json' with { type: 'json' }
|
||||
import {
|
||||
ManagerTokenInvalidError,
|
||||
ManagerTooOldError,
|
||||
MIN_MANAGER_VERSION,
|
||||
OCM_VERSION,
|
||||
RepoProxyNotFoundError,
|
||||
RepoProxyResponseError,
|
||||
RepoProxyUnreachableError,
|
||||
repoProxyBaseUrl,
|
||||
repoProxyUrl,
|
||||
warmRepoProxy,
|
||||
} from '../src/repo-proxy.js'
|
||||
|
||||
const managerUrl = 'https://manager.example.com'
|
||||
|
||||
function fetchReturning(...responses: Array<Response | Error>) {
|
||||
const fetchMock = vi.fn(async () => {
|
||||
const next = responses.shift()
|
||||
if (!next) throw new Error('unexpected fetch')
|
||||
if (next instanceof Error) throw next
|
||||
return next
|
||||
})
|
||||
return fetchMock
|
||||
}
|
||||
|
||||
const noWait = vi.fn(async () => undefined)
|
||||
|
||||
describe('repoProxyUrl', () => {
|
||||
it('builds the repo-scoped proxy url', () => {
|
||||
expect(repoProxyUrl(managerUrl, 42)).toBe('https://manager.example.com/api/opencode-proxy/repos/42')
|
||||
})
|
||||
})
|
||||
|
||||
describe('repoProxyBaseUrl', () => {
|
||||
it('builds the manager proxy base url', () => {
|
||||
expect(repoProxyBaseUrl(managerUrl)).toBe('https://manager.example.com/api/opencode-proxy')
|
||||
})
|
||||
})
|
||||
|
||||
describe('warmRepoProxy', () => {
|
||||
it('reports the package version', () => {
|
||||
expect(OCM_VERSION).toBe(packageJson.version)
|
||||
})
|
||||
|
||||
it('resolves once the repo proxy route responds', async () => {
|
||||
const fetchMock = fetchReturning(new Response('[]', { status: 200 }))
|
||||
|
||||
await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://manager.example.com/api/opencode-proxy/repos/42/api/session?limit=1',
|
||||
{ headers: { Authorization: 'Bearer tok' } },
|
||||
)
|
||||
})
|
||||
|
||||
it('fails with an upgrade message when the Manager has no repo proxy route', async () => {
|
||||
const fetchMock = fetchReturning(new Response('Not Found', { status: 404 }))
|
||||
|
||||
const error = await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait }).catch((err: unknown) => err)
|
||||
|
||||
expect(error).toBeInstanceOf(ManagerTooOldError)
|
||||
expect((error as Error).message).toBe(
|
||||
`OpenCode Manager at ${managerUrl} is too old for ocm 0.3.0; upgrade the Manager to >= ${MIN_MANAGER_VERSION}`,
|
||||
)
|
||||
expect(MIN_MANAGER_VERSION).toBe('0.19.0')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('distinguishes a missing repo on a current Manager from an old Manager', async () => {
|
||||
const fetchMock = fetchReturning(Response.json({ error: 'Repo not found' }, { status: 404 }))
|
||||
|
||||
await expect(warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait })).rejects.toBeInstanceOf(RepoProxyNotFoundError)
|
||||
})
|
||||
|
||||
it('retries transient failures and reports the last response', async () => {
|
||||
const fetchMock = fetchReturning(new Error('ECONNRESET'), new Response('', { status: 502 }), new Response('', { status: 503 }))
|
||||
const wait = vi.fn(async () => undefined)
|
||||
|
||||
const error = await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait }).catch((err: unknown) => err)
|
||||
|
||||
expect(error).toBeInstanceOf(RepoProxyResponseError)
|
||||
expect((error as Error).message).toContain('HTTP 503')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
expect(wait.mock.calls).toEqual([[500], [1000]])
|
||||
})
|
||||
|
||||
it('reports the status and body of a non-OK response', async () => {
|
||||
const fetchMock = fetchReturning(new Response('proxy exploded', { status: 500 }))
|
||||
|
||||
const error = await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait, attempts: 1 }).catch((err: unknown) => err)
|
||||
|
||||
expect(error).toBeInstanceOf(RepoProxyResponseError)
|
||||
expect((error as Error).message).toContain('HTTP 500')
|
||||
expect((error as Error).message).toContain('proxy exploded')
|
||||
})
|
||||
|
||||
it('reports an invalid manager token on 401 without retrying', async () => {
|
||||
const fetchMock = fetchReturning(new Response('Unauthorized', { status: 401 }))
|
||||
|
||||
const error = await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait }).catch((err: unknown) => err)
|
||||
|
||||
expect(error).toBeInstanceOf(ManagerTokenInvalidError)
|
||||
expect((error as Error).message).toContain('Settings -> Manager Internal Token')
|
||||
expect((error as Error).message).toContain(`ocm login ${managerUrl}`)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reports the network cause when the manager is unreachable', async () => {
|
||||
const cause = new Error('connect ECONNREFUSED')
|
||||
const fetchMock = fetchReturning(cause, cause, cause)
|
||||
|
||||
const error = await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait }).catch((err: unknown) => err)
|
||||
|
||||
expect(error).toBeInstanceOf(RepoProxyUnreachableError)
|
||||
expect((error as Error).message).toContain('connect ECONNREFUSED')
|
||||
expect((error as Error).cause).toBe(cause)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('succeeds after a transient failure', async () => {
|
||||
const fetchMock = fetchReturning(new Response('', { status: 503 }), new Response('[]', { status: 200 }))
|
||||
|
||||
await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
+159
-318
@@ -1,373 +1,214 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { collectSessionEvents, rewriteEventsForRemote, transferSession, planReplayBatches, moveReminderText, type HistoryEventRow, type ReplayEvent, type TransferDeps } from '../src/session-move.js'
|
||||
import { rewriteTransferForRemote, transferSession, moveReminderText, type TransferDeps } from '../src/session-move.js'
|
||||
import type { SessionMessageInfo, SessionTransferData } from '@opencode-manager/shared/opencode'
|
||||
|
||||
describe('collectSessionEvents', () => {
|
||||
it('collects a session\'s events in seq order with remapped aggregateID', () => {
|
||||
const rows: HistoryEventRow[] = [
|
||||
{ id: 'e3', aggregate_id: 'ses_a', seq: 2, type: 'append', data: { text: 'c' } },
|
||||
{ id: 'e1', aggregate_id: 'ses_a', seq: 0, type: 'append', data: { text: 'a' } },
|
||||
{ id: 'e2', aggregate_id: 'ses_a', seq: 1, type: 'append', data: { text: 'b' } },
|
||||
{ id: 'e4', aggregate_id: 'ses_b', seq: 0, type: 'append', data: { text: 'x' } },
|
||||
]
|
||||
const ctx = { localRoot: '/Users/x/repo', remoteRoot: '/workspace/repos/repo' }
|
||||
|
||||
const result = collectSessionEvents(rows, 'ses_a')
|
||||
function makeTransfer(messages: SessionMessageInfo[] = [], directory = '/Users/x/repo'): SessionTransferData {
|
||||
return {
|
||||
info: {
|
||||
id: 'ses_a',
|
||||
projectID: 'proj_1',
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: 1, updated: 2 },
|
||||
location: { directory },
|
||||
},
|
||||
messages,
|
||||
} as unknown as SessionTransferData
|
||||
}
|
||||
|
||||
expect(result).toEqual({
|
||||
kind: 'ok',
|
||||
events: [
|
||||
{ id: 'e1', aggregateID: 'ses_a', seq: 0, type: 'append', data: { text: 'a' } },
|
||||
{ id: 'e2', aggregateID: 'ses_a', seq: 1, type: 'append', data: { text: 'b' } },
|
||||
{ id: 'e3', aggregateID: 'ses_a', seq: 2, type: 'append', data: { text: 'c' } },
|
||||
],
|
||||
})
|
||||
})
|
||||
function userWithFile(uri: string): SessionMessageInfo {
|
||||
return {
|
||||
id: 'msg_user',
|
||||
time: { created: 1 },
|
||||
type: 'user',
|
||||
text: 'hi',
|
||||
files: [{ data: '', mime: 'image/png', source: { type: 'uri', uri } }],
|
||||
} as unknown as SessionMessageInfo
|
||||
}
|
||||
|
||||
it('returns empty when the session has no events', () => {
|
||||
const rows: HistoryEventRow[] = [
|
||||
{ id: 'e1', aggregate_id: 'other', seq: 0, type: 'append', data: {} },
|
||||
]
|
||||
|
||||
const result = collectSessionEvents(rows, 'unknown')
|
||||
|
||||
expect(result).toEqual({ kind: 'empty' })
|
||||
})
|
||||
|
||||
it('detects a gap in the sequence', () => {
|
||||
const rows: HistoryEventRow[] = [
|
||||
{ id: 'e1', aggregate_id: 'ses_a', seq: 0, type: 'append', data: {} },
|
||||
{ id: 'e2', aggregate_id: 'ses_a', seq: 1, type: 'append', data: {} },
|
||||
{ id: 'e3', aggregate_id: 'ses_a', seq: 3, type: 'append', data: {} },
|
||||
]
|
||||
|
||||
const result = collectSessionEvents(rows, 'ses_a')
|
||||
|
||||
expect(result).toEqual({ kind: 'gap', missingSeq: 2 })
|
||||
})
|
||||
|
||||
it('detects a gap when sequence does not start at 0', () => {
|
||||
const rows: HistoryEventRow[] = [
|
||||
{ id: 'e1', aggregate_id: 'ses_a', seq: 1, type: 'append', data: {} },
|
||||
{ id: 'e2', aggregate_id: 'ses_a', seq: 2, type: 'append', data: {} },
|
||||
]
|
||||
|
||||
const result = collectSessionEvents(rows, 'ses_a')
|
||||
|
||||
expect(result).toEqual({ kind: 'gap', missingSeq: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('rewriteEventsForRemote', () => {
|
||||
const ctx = {
|
||||
localRoot: '/Users/x/repo',
|
||||
remoteRoot: '/workspace/repos/repo',
|
||||
}
|
||||
|
||||
it('rewrites session.created info directory to the remote root', () => {
|
||||
const events: ReplayEvent[] = [
|
||||
function assistantWithToolFile(uri: string): SessionMessageInfo {
|
||||
return {
|
||||
id: 'msg_assistant',
|
||||
time: { created: 2 },
|
||||
type: 'assistant',
|
||||
agent: 'code',
|
||||
model: { id: 'm', providerID: 'p' },
|
||||
content: [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 0,
|
||||
type: 'session.created.1',
|
||||
data: { info: { directory: '/Users/x/repo' } },
|
||||
type: 'tool',
|
||||
id: 'tool_1',
|
||||
name: 'read',
|
||||
state: { status: 'completed', input: {}, content: [{ type: 'file', uri, mime: 'image/png' }] },
|
||||
time: { created: 2 },
|
||||
},
|
||||
]
|
||||
],
|
||||
} as unknown as SessionMessageInfo
|
||||
}
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
describe('rewriteTransferForRemote', () => {
|
||||
it('rewrites info.location.directory to the remote root', () => {
|
||||
const result = rewriteTransferForRemote(makeTransfer(), ctx)
|
||||
|
||||
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo' })
|
||||
})
|
||||
|
||||
it('rewrites session.updated info directory to the remote root', () => {
|
||||
const events: ReplayEvent[] = [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 0,
|
||||
type: 'session.updated.2',
|
||||
data: { info: { directory: '/Users/x/repo' } },
|
||||
},
|
||||
]
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
|
||||
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo' })
|
||||
expect(result.info.location.directory).toBe('/workspace/repos/repo')
|
||||
})
|
||||
|
||||
it('preserves subdirectories under the repo root', () => {
|
||||
const events: ReplayEvent[] = [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 0,
|
||||
type: 'session.created.1',
|
||||
data: { info: { directory: '/Users/x/repo/packages/app' } },
|
||||
},
|
||||
]
|
||||
const result = rewriteTransferForRemote(makeTransfer([], '/Users/x/repo/packages/app'), ctx)
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
|
||||
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo/packages/app' })
|
||||
expect(result.info.location.directory).toBe('/workspace/repos/repo/packages/app')
|
||||
})
|
||||
|
||||
it('rewrites session.next.moved location directory', () => {
|
||||
const events: ReplayEvent[] = [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 0,
|
||||
type: 'session.next.moved.1',
|
||||
data: { location: { directory: '/Users/x/repo/src' } },
|
||||
},
|
||||
]
|
||||
it('rewrites a user file attachment uri under the local root', () => {
|
||||
const result = rewriteTransferForRemote(makeTransfer([userWithFile('/Users/x/repo/src/img.png')]), ctx)
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
|
||||
expect(result[0]!.data.location).toEqual({ directory: '/workspace/repos/repo/src' })
|
||||
const files = (result.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
|
||||
expect(files[0]!.source.uri).toBe('/workspace/repos/repo/src/img.png')
|
||||
})
|
||||
|
||||
it('rewrites assistant message path cwd and root', () => {
|
||||
const events: ReplayEvent[] = [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 3,
|
||||
type: 'message.updated.1',
|
||||
data: { info: { id: 'msg_1', role: 'assistant', path: { cwd: '/Users/x/repo/src', root: '/Users/x/repo' } } },
|
||||
},
|
||||
]
|
||||
it('rewrites an assistant tool file uri under the local root', () => {
|
||||
const result = rewriteTransferForRemote(makeTransfer([assistantWithToolFile('/Users/x/repo/out.png')]), ctx)
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
|
||||
expect(result[0]!.data.info).toEqual({
|
||||
id: 'msg_1',
|
||||
role: 'assistant',
|
||||
path: { cwd: '/workspace/repos/repo/src', root: '/workspace/repos/repo' },
|
||||
})
|
||||
const content = (result.messages[0] as unknown as { content: { state: { content: { uri: string }[] } }[] }).content
|
||||
expect(content[0]!.state.content[0]!.uri).toBe('/workspace/repos/repo/out.png')
|
||||
})
|
||||
|
||||
it('leaves message paths outside the local root untouched', () => {
|
||||
const events: ReplayEvent[] = [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 3,
|
||||
type: 'message.updated.1',
|
||||
data: { info: { id: 'msg_1', role: 'assistant', path: { cwd: '/Users/x/repo-other', root: '/Users/x/repo-other' } } },
|
||||
},
|
||||
{
|
||||
id: 'e2', aggregateID: 'ses_a', seq: 4,
|
||||
type: 'message.updated.1',
|
||||
data: { info: { id: 'msg_2', role: 'user' } },
|
||||
},
|
||||
]
|
||||
it('leaves uris outside the local root untouched', () => {
|
||||
const result = rewriteTransferForRemote(makeTransfer([userWithFile('/elsewhere/img.png')]), ctx)
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
|
||||
expect(result[0]!.data.info).toEqual({ id: 'msg_1', role: 'assistant', path: { cwd: '/Users/x/repo-other', root: '/Users/x/repo-other' } })
|
||||
expect(result[1]!.data.info).toEqual({ id: 'msg_2', role: 'user' })
|
||||
const files = (result.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
|
||||
expect(files[0]!.source.uri).toBe('/elsewhere/img.png')
|
||||
})
|
||||
|
||||
it('strips workspaceID from info', () => {
|
||||
const events: ReplayEvent[] = [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 0,
|
||||
type: 'session.created.1',
|
||||
data: { info: { directory: '/Users/x/repo', workspaceID: 'ws_abc' } },
|
||||
},
|
||||
]
|
||||
it('rewrites a file:// user attachment uri under the local root, preserving encoding', () => {
|
||||
const result = rewriteTransferForRemote(makeTransfer([userWithFile('file:///Users/x/repo/a%20b.png')]), ctx)
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
|
||||
expect(result[0]!.data.info).toEqual({ directory: '/workspace/repos/repo' })
|
||||
expect('workspaceID' in result[0]!.data.info).toBe(false)
|
||||
const files = (result.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
|
||||
expect(files[0]!.source.uri).toBe('file:///workspace/repos/repo/a%20b.png')
|
||||
})
|
||||
|
||||
it('strips workspaceID from location on moved events', () => {
|
||||
const events: ReplayEvent[] = [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 0,
|
||||
type: 'session.next.moved.1',
|
||||
data: { location: { directory: '/Users/x/repo', workspaceID: 'ws_abc' } },
|
||||
},
|
||||
]
|
||||
it('rewrites a file:// assistant tool file uri under the local root', () => {
|
||||
const result = rewriteTransferForRemote(makeTransfer([assistantWithToolFile('file:///Users/x/repo/out.png')]), ctx)
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
|
||||
expect(result[0]!.data.location).toEqual({ directory: '/workspace/repos/repo' })
|
||||
expect('workspaceID' in result[0]!.data.location).toBe(false)
|
||||
const content = (result.messages[0] as unknown as { content: { state: { content: { uri: string }[] } }[] }).content
|
||||
expect(content[0]!.state.content[0]!.uri).toBe('file:///workspace/repos/repo/out.png')
|
||||
})
|
||||
|
||||
it('coerces ISO time string in data.timestamp to epoch millis (per 686c820d)', () => {
|
||||
const iso = '2026-07-01T10:00:00.000Z'
|
||||
const events: ReplayEvent[] = [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 0,
|
||||
type: 'session.next.agent.switched.1',
|
||||
data: { timestamp: iso, agent: 'code' },
|
||||
},
|
||||
]
|
||||
it('preserves file:// query and hash when relocating', () => {
|
||||
const result = rewriteTransferForRemote(makeTransfer([userWithFile('file:///Users/x/repo/a.png?v=1#frag')]), ctx)
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
|
||||
expect(result[0]!.data.timestamp).toBe(Date.parse(iso))
|
||||
expect(typeof result[0]!.data.timestamp).toBe('number')
|
||||
const files = (result.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
|
||||
expect(files[0]!.source.uri).toBe('file:///workspace/repos/repo/a.png?v=1#frag')
|
||||
})
|
||||
|
||||
it('leaves already-numeric timestamp untouched', () => {
|
||||
const epoch = 1778974142967
|
||||
const events: ReplayEvent[] = [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 0,
|
||||
type: 'session.next.model.switched.1',
|
||||
data: { timestamp: epoch },
|
||||
},
|
||||
]
|
||||
it('leaves a file:// uri outside the local root untouched', () => {
|
||||
const uri = 'file:///elsewhere/img.png'
|
||||
const result = rewriteTransferForRemote(makeTransfer([userWithFile(uri)]), ctx)
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
|
||||
expect(result[0]!.data.timestamp).toBe(epoch)
|
||||
const files = (result.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
|
||||
expect(files[0]!.source.uri).toBe(uri)
|
||||
})
|
||||
|
||||
it('leaves unrelated events untouched without mutating input', () => {
|
||||
const events: ReplayEvent[] = [
|
||||
{
|
||||
id: 'e1', aggregateID: 'ses_a', seq: 0,
|
||||
type: 'session.next.step.ended.2',
|
||||
data: { sessionID: 'ses_a', step: { kind: 'code' } },
|
||||
},
|
||||
]
|
||||
const frozen = JSON.parse(JSON.stringify(events))
|
||||
it('does not relocate a file:// uri that only shares a prefix with the local root', () => {
|
||||
const uri = 'file:///Users/x/repo-other/img.png'
|
||||
const result = rewriteTransferForRemote(makeTransfer([userWithFile(uri)]), ctx)
|
||||
|
||||
const result = rewriteEventsForRemote(events, ctx)
|
||||
const files = (result.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
|
||||
expect(files[0]!.source.uri).toBe(uri)
|
||||
})
|
||||
|
||||
expect(result[0]!.data).toEqual(frozen[0]!.data)
|
||||
expect(events).toEqual(frozen)
|
||||
it('leaves data uris and external http urls untouched', () => {
|
||||
const dataUri = 'data:image/png;base64,AAAA'
|
||||
const httpUri = 'https://example.com/img.png'
|
||||
const result = rewriteTransferForRemote(makeTransfer([userWithFile(dataUri), userWithFile(httpUri)]), ctx)
|
||||
|
||||
const dataFiles = (result.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
|
||||
const httpFiles = (result.messages[1] as unknown as { files: { source: { uri: string } }[] }).files
|
||||
expect(dataFiles[0]!.source.uri).toBe(dataUri)
|
||||
expect(httpFiles[0]!.source.uri).toBe(httpUri)
|
||||
})
|
||||
|
||||
it('does not mutate a file:// input transfer', () => {
|
||||
const input = makeTransfer([userWithFile('file:///Users/x/repo/a%20b.png')])
|
||||
const frozen = structuredClone(input)
|
||||
|
||||
rewriteTransferForRemote(input, ctx)
|
||||
|
||||
expect(input).toEqual(frozen)
|
||||
})
|
||||
|
||||
it('does not mutate the input transfer', () => {
|
||||
const input = makeTransfer([userWithFile('/Users/x/repo/src/img.png')])
|
||||
const frozen = structuredClone(input)
|
||||
|
||||
rewriteTransferForRemote(input, ctx)
|
||||
|
||||
expect(input).toEqual(frozen)
|
||||
})
|
||||
})
|
||||
|
||||
describe('planReplayBatches', () => {
|
||||
it('splits events into batches of batchSize (default 10)', () => {
|
||||
const events = Array.from({ length: 25 }, (_, i) => ({
|
||||
id: `e${i}`, aggregateID: 'ses_a', seq: i, type: 'append', data: {},
|
||||
}))
|
||||
|
||||
const batches = planReplayBatches(events)
|
||||
|
||||
expect(batches).toHaveLength(3)
|
||||
expect(batches[0]).toHaveLength(10)
|
||||
expect(batches[1]).toHaveLength(10)
|
||||
expect(batches[2]).toHaveLength(5)
|
||||
expect(batches[0]![0]!.seq).toBe(0)
|
||||
expect(batches[1]![0]!.seq).toBe(10)
|
||||
expect(batches[2]![0]!.seq).toBe(20)
|
||||
})
|
||||
|
||||
it('returns a single batch when events fit within batchSize', () => {
|
||||
const events = Array.from({ length: 3 }, (_, i) => ({
|
||||
id: `e${i}`, aggregateID: 'ses_a', seq: i, type: 'append', data: {},
|
||||
}))
|
||||
|
||||
const batches = planReplayBatches(events, 10)
|
||||
|
||||
expect(batches).toHaveLength(1)
|
||||
expect(batches[0]).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('returns empty array for empty events', () => {
|
||||
expect(planReplayBatches([])).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
function makeHistoryEvents(sessionID: string, count: number, opts: { root?: string; types?: string[] } = {}): HistoryEventRow[] {
|
||||
const root = opts.root ?? '/Users/x/repo'
|
||||
const types = opts.types ?? ['session.created.1']
|
||||
return Array.from({ length: count }, (_, i) => ({
|
||||
id: `e${i}`,
|
||||
aggregate_id: sessionID,
|
||||
seq: i,
|
||||
type: types[Math.min(i, types.length - 1)]!,
|
||||
data: { info: { directory: root }, timestamp: '2026-07-01T10:00:00.000Z' },
|
||||
}))
|
||||
}
|
||||
|
||||
describe('transferSession', () => {
|
||||
const input = { sessionID: 'ses_a', localRoot: '/Users/x/repo', remoteDirectory: '/workspace/repos/repo' }
|
||||
|
||||
it('moves a session by replaying its full history in ordered batches', async () => {
|
||||
const history = makeHistoryEvents('ses_a', 25)
|
||||
const replayCalls: { dir: string; events: ReplayEvent[] }[] = []
|
||||
|
||||
const deps: TransferDeps = {
|
||||
fetchLocalHistory: vi.fn().mockResolvedValue(history),
|
||||
replayEvents: vi.fn().mockImplementation(async (dir: string, events: ReplayEvent[]) => {
|
||||
replayCalls.push({ dir, events })
|
||||
return { sessionID: 'ses_a' }
|
||||
}),
|
||||
}
|
||||
|
||||
const result = await transferSession(input, deps)
|
||||
|
||||
expect(result).toEqual({ kind: 'moved', sessionID: 'ses_a', replayedEvents: 25 })
|
||||
expect(replayCalls).toHaveLength(3)
|
||||
expect(replayCalls[0]!.dir).toBe('/workspace/repos/repo')
|
||||
expect(replayCalls[0]!.events).toHaveLength(10)
|
||||
expect(replayCalls[0]!.events[0]!.seq).toBe(0)
|
||||
expect(replayCalls[1]!.events).toHaveLength(10)
|
||||
expect(replayCalls[2]!.events).toHaveLength(5)
|
||||
|
||||
expect(replayCalls[0]!.events[0]!.data.info.directory).toBe('/workspace/repos/repo')
|
||||
})
|
||||
|
||||
it('reports replay progress after each batch', async () => {
|
||||
const history = makeHistoryEvents('ses_a', 25)
|
||||
it('exports, imports the rewritten transfer, and reports progress', async () => {
|
||||
const data = makeTransfer([userWithFile('/Users/x/repo/src/img.png')])
|
||||
const importCalls: { directory: string; data: SessionTransferData }[] = []
|
||||
const progress: [number, number][] = []
|
||||
|
||||
const deps: TransferDeps = {
|
||||
fetchLocalHistory: vi.fn().mockResolvedValue(history),
|
||||
replayEvents: vi.fn().mockResolvedValue({ sessionID: 'ses_a' }),
|
||||
onProgress: (replayed, total) => progress.push([replayed, total]),
|
||||
}
|
||||
|
||||
await transferSession(input, deps)
|
||||
|
||||
expect(progress).toEqual([[0, 25], [10, 25], [20, 25], [25, 25]])
|
||||
})
|
||||
|
||||
it('reports a missing session', async () => {
|
||||
const deps: TransferDeps = {
|
||||
fetchLocalHistory: vi.fn().mockResolvedValue([]),
|
||||
replayEvents: vi.fn(),
|
||||
}
|
||||
|
||||
const result = await transferSession(input, deps)
|
||||
|
||||
expect(result).toEqual({ kind: 'not-found' })
|
||||
expect(deps.replayEvents).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses to transfer corrupt history', async () => {
|
||||
const rows: HistoryEventRow[] = [
|
||||
{ id: 'e0', aggregate_id: 'ses_a', seq: 0, type: 'session.created.1', data: {} },
|
||||
{ id: 'e2', aggregate_id: 'ses_a', seq: 2, type: 'session.updated.2', data: {} },
|
||||
]
|
||||
|
||||
const deps: TransferDeps = {
|
||||
fetchLocalHistory: vi.fn().mockResolvedValue(rows),
|
||||
replayEvents: vi.fn(),
|
||||
}
|
||||
|
||||
const result = await transferSession(input, deps)
|
||||
|
||||
expect(result).toEqual({ kind: 'corrupt-history', missingSeq: 1 })
|
||||
expect(deps.replayEvents).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces replay failure and stops', async () => {
|
||||
const history = makeHistoryEvents('ses_a', 25)
|
||||
let callCount = 0
|
||||
|
||||
const deps: TransferDeps = {
|
||||
fetchLocalHistory: vi.fn().mockResolvedValue(history),
|
||||
replayEvents: vi.fn().mockImplementation(async () => {
|
||||
callCount++
|
||||
if (callCount === 2) throw new Error('Replay diverged')
|
||||
exportSession: vi.fn().mockResolvedValue(data),
|
||||
importSession: vi.fn().mockImplementation(async (directory: string, transferred: SessionTransferData) => {
|
||||
importCalls.push({ directory, data: transferred })
|
||||
return { sessionID: 'ses_a' }
|
||||
}),
|
||||
onProgress: (transferred, total) => progress.push([transferred, total]),
|
||||
}
|
||||
|
||||
const result = await transferSession(input, deps)
|
||||
|
||||
expect(result).toEqual({ kind: 'replay-failed', message: 'Replay diverged' })
|
||||
expect(callCount).toBe(2)
|
||||
expect(result).toEqual({ kind: 'moved', sessionID: 'ses_a', importedMessages: 1 })
|
||||
expect(deps.exportSession).toHaveBeenCalledWith('ses_a')
|
||||
expect(importCalls).toHaveLength(1)
|
||||
expect(importCalls[0]!.directory).toBe('/workspace/repos/repo')
|
||||
expect(importCalls[0]!.data.info.location.directory).toBe('/workspace/repos/repo')
|
||||
const files = (importCalls[0]!.data.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
|
||||
expect(files[0]!.source.uri).toBe('/workspace/repos/repo/src/img.png')
|
||||
expect(progress).toEqual([[0, 1], [1, 1]])
|
||||
})
|
||||
|
||||
it('returns the imported session id rather than the local one', async () => {
|
||||
const deps: TransferDeps = {
|
||||
exportSession: vi.fn().mockResolvedValue(makeTransfer()),
|
||||
importSession: vi.fn().mockResolvedValue({ sessionID: 'ses_remote' }),
|
||||
}
|
||||
|
||||
const result = await transferSession(input, deps)
|
||||
|
||||
expect(result).toEqual({ kind: 'moved', sessionID: 'ses_remote', importedMessages: 0 })
|
||||
})
|
||||
|
||||
it('reports an export failure without importing', async () => {
|
||||
const deps: TransferDeps = {
|
||||
exportSession: vi.fn().mockRejectedValue(new Error('export failed')),
|
||||
importSession: vi.fn(),
|
||||
}
|
||||
|
||||
const result = await transferSession(input, deps)
|
||||
|
||||
expect(result).toEqual({ kind: 'import-failed', message: 'export failed' })
|
||||
expect(deps.importSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports an import failure', async () => {
|
||||
const deps: TransferDeps = {
|
||||
exportSession: vi.fn().mockResolvedValue(makeTransfer()),
|
||||
importSession: vi.fn().mockRejectedValue(new Error('import diverged')),
|
||||
}
|
||||
|
||||
const result = await transferSession(input, deps)
|
||||
|
||||
expect(result).toEqual({ kind: 'import-failed', message: 'import diverged' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -388,4 +229,4 @@ describe('moveReminderText', () => {
|
||||
`<system-reminder>The user has changed the current working directory to "${dir}". This is still the same project but at a possibly new location; take this into account when working with any files from now on.</system-reminder>`,
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
|
||||
@@ -1,144 +1,57 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import type { TuiPluginApi, TuiDialogConfirmProps, TuiDialogSelectProps } from '../src/tui-types.js'
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
import { confirmDialog, selectDialog } from '../src/tui-dialogs.js'
|
||||
|
||||
function createFakeApi() {
|
||||
let capturedRender: (() => unknown) | undefined
|
||||
let capturedOnClose: (() => void) | undefined
|
||||
let clearCount = 0
|
||||
|
||||
const api = {
|
||||
route: { current: { name: 'session' as const, params: { sessionID: 's1' } } },
|
||||
state: { session: { get: () => undefined } },
|
||||
ui: {
|
||||
toast: vi.fn(),
|
||||
DialogConfirm: (props: TuiDialogConfirmProps) => props,
|
||||
DialogSelect: <Value,>(props: TuiDialogSelectProps<Value>) => props,
|
||||
dialog: {
|
||||
replace: vi.fn((render: () => unknown, onClose?: () => void) => {
|
||||
capturedRender = render
|
||||
capturedOnClose = onClose
|
||||
}),
|
||||
clear: vi.fn(() => { clearCount++ }),
|
||||
},
|
||||
},
|
||||
keymap: { registerLayer: vi.fn(), dispatchCommand: vi.fn() },
|
||||
slots: { register: vi.fn() },
|
||||
lifecycle: { signal: new AbortController().signal, onDispose: vi.fn() },
|
||||
} satisfies TuiPluginApi
|
||||
|
||||
const getCaptured = () => {
|
||||
const render = capturedRender!
|
||||
const onClose = capturedOnClose
|
||||
return { render, onClose }
|
||||
}
|
||||
|
||||
return { api, getCaptured, getClearCount: () => clearCount }
|
||||
function createFakeContext() {
|
||||
const confirm = vi.fn()
|
||||
const select = vi.fn()
|
||||
const context = {
|
||||
ui: { dialog: { confirm, select } },
|
||||
} as unknown as Context
|
||||
return { context, confirm, select }
|
||||
}
|
||||
|
||||
describe('confirmDialog', () => {
|
||||
it('resolves true when onConfirm fires', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const p = confirmDialog(api, { title: 'Confirm', message: 'Continue?' })
|
||||
it('resolves true when the dialog confirms', async () => {
|
||||
const { context, confirm } = createFakeContext()
|
||||
confirm.mockResolvedValue(true)
|
||||
|
||||
const { render } = getCaptured()
|
||||
const props = render() as TuiDialogConfirmProps
|
||||
props.onConfirm!()
|
||||
|
||||
expect(await p).toBe(true)
|
||||
expect(api.ui.dialog.clear).toHaveBeenCalledOnce()
|
||||
expect(await confirmDialog(context, { title: 'Confirm', message: 'Continue?' })).toBe(true)
|
||||
expect(confirm).toHaveBeenCalledWith({ title: 'Confirm', message: 'Continue?' })
|
||||
})
|
||||
|
||||
it('resolves false when onCancel fires', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const p = confirmDialog(api, { title: 'Confirm', message: 'Continue?' })
|
||||
it('resolves false when the dialog is dismissed', async () => {
|
||||
const { context, confirm } = createFakeContext()
|
||||
confirm.mockResolvedValue(undefined)
|
||||
|
||||
const { render } = getCaptured()
|
||||
const props = render() as TuiDialogConfirmProps
|
||||
props.onCancel!()
|
||||
|
||||
expect(await p).toBe(false)
|
||||
expect(api.ui.dialog.clear).toHaveBeenCalledOnce()
|
||||
expect(await confirmDialog(context, { title: 'Confirm', message: 'Continue?' })).toBe(false)
|
||||
})
|
||||
|
||||
it('resolves false when onClose fires without calling clear', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const p = confirmDialog(api, { title: 'Confirm', message: 'Continue?' })
|
||||
it('resolves false when the dialog explicitly cancels', async () => {
|
||||
const { context, confirm } = createFakeContext()
|
||||
confirm.mockResolvedValue(false)
|
||||
|
||||
const { onClose } = getCaptured()
|
||||
onClose!()
|
||||
|
||||
expect(await p).toBe(false)
|
||||
expect(api.ui.dialog.clear).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('resolves only once when onConfirm then onClose both fire', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const p = confirmDialog(api, { title: 'Confirm', message: 'Continue?' })
|
||||
|
||||
const { render, onClose } = getCaptured()
|
||||
const props = render() as TuiDialogConfirmProps
|
||||
props.onConfirm!()
|
||||
onClose!()
|
||||
|
||||
expect(await p).toBe(true)
|
||||
expect(api.ui.dialog.clear).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('resolves only once when onClose then onConfirm both fire', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const p = confirmDialog(api, { title: 'Confirm', message: 'Continue?' })
|
||||
|
||||
const { render, onClose } = getCaptured()
|
||||
onClose!()
|
||||
const props = render() as TuiDialogConfirmProps
|
||||
props.onConfirm!()
|
||||
|
||||
expect(await p).toBe(false)
|
||||
expect(api.ui.dialog.clear).not.toHaveBeenCalled()
|
||||
expect(await confirmDialog(context, { title: 'Confirm', message: 'Continue?' })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('selectDialog', () => {
|
||||
it('resolves the chosen option value via onSelect', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
it('resolves the chosen option value', async () => {
|
||||
const { context, select } = createFakeContext()
|
||||
const options = [
|
||||
{ title: 'A', value: 'a' },
|
||||
{ title: 'B', value: 'b' },
|
||||
]
|
||||
const p = selectDialog(api, 'Pick one', options)
|
||||
select.mockResolvedValue('b')
|
||||
|
||||
const { render } = getCaptured()
|
||||
const props = render() as TuiDialogSelectProps<string>
|
||||
props.onSelect!(props.options[1]!)
|
||||
|
||||
expect(await p).toBe('b')
|
||||
expect(api.ui.dialog.clear).toHaveBeenCalledOnce()
|
||||
expect(await selectDialog(context, 'Pick one', options)).toBe('b')
|
||||
expect(select).toHaveBeenCalledWith({ title: 'Pick one', options })
|
||||
})
|
||||
|
||||
it('resolves undefined when onClose fires without calling clear', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const options = [{ title: 'X', value: 42 }]
|
||||
const p = selectDialog(api, 'Pick', options)
|
||||
it('resolves undefined when the dialog is dismissed', async () => {
|
||||
const { context, select } = createFakeContext()
|
||||
select.mockResolvedValue(undefined)
|
||||
|
||||
const { onClose } = getCaptured()
|
||||
onClose!()
|
||||
|
||||
expect(await p).toBeUndefined()
|
||||
expect(api.ui.dialog.clear).not.toHaveBeenCalled()
|
||||
expect(await selectDialog(context, 'Pick', [{ title: 'X', value: 42 }])).toBeUndefined()
|
||||
})
|
||||
|
||||
it('resolves only once when onSelect then onClose both fire', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const options = [{ title: 'A', value: 'a' }]
|
||||
const p = selectDialog(api, 'Pick', options)
|
||||
|
||||
const { render, onClose } = getCaptured()
|
||||
const props = render() as TuiDialogSelectProps<string>
|
||||
props.onSelect!(props.options[0]!)
|
||||
onClose!()
|
||||
|
||||
expect(await p).toBe('a')
|
||||
expect(api.ui.dialog.clear).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,362 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
|
||||
import { setupOcm } from '../src/tui-plugin.js'
|
||||
import { moveReminderText } from '../src/session-move.js'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
calls: [] as string[],
|
||||
readState: vi.fn(),
|
||||
readInstallNotice: vi.fn(() => null),
|
||||
getToken: vi.fn(),
|
||||
fetchRepos: vi.fn(),
|
||||
toRemoteRepoSummaries: vi.fn((repos: unknown) => repos),
|
||||
prepareMirror: vi.fn(),
|
||||
checkPushDivergence: vi.fn(),
|
||||
describePushDivergence: vi.fn(() => []),
|
||||
mirrorUpFast: vi.fn(),
|
||||
pickMatchedRepo: vi.fn(),
|
||||
getBranchName: vi.fn(),
|
||||
createManagerSessionTransfer: vi.fn(),
|
||||
setPendingWarp: vi.fn(),
|
||||
runPendingWarp: vi.fn(),
|
||||
mirrorTargetPlan: vi.fn(),
|
||||
warmRepoProxy: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../src/state.js', () => ({
|
||||
readState: mocks.readState,
|
||||
readInstallNotice: mocks.readInstallNotice,
|
||||
}))
|
||||
|
||||
vi.mock('../src/internal-token-store.js', () => ({ getToken: mocks.getToken }))
|
||||
|
||||
vi.mock('../src/manager-repos.js', () => ({
|
||||
fetchRepos: mocks.fetchRepos,
|
||||
toRemoteRepoSummaries: mocks.toRemoteRepoSummaries,
|
||||
}))
|
||||
|
||||
vi.mock('../src/mirror.js', () => ({
|
||||
prepareMirror: mocks.prepareMirror,
|
||||
checkPushDivergence: mocks.checkPushDivergence,
|
||||
describePushDivergence: mocks.describePushDivergence,
|
||||
mirrorUpFast: mocks.mirrorUpFast,
|
||||
pickMatchedRepo: mocks.pickMatchedRepo,
|
||||
}))
|
||||
|
||||
vi.mock('../src/local-repo.js', () => ({ getBranchName: mocks.getBranchName }))
|
||||
|
||||
vi.mock('../src/remote-session.js', () => ({
|
||||
createManagerSessionTransfer: mocks.createManagerSessionTransfer,
|
||||
}))
|
||||
|
||||
vi.mock('../src/warp.js', () => ({
|
||||
setPendingWarp: mocks.setPendingWarp,
|
||||
runPendingWarp: mocks.runPendingWarp,
|
||||
}))
|
||||
|
||||
vi.mock('../src/repo-proxy.js', () => ({ warmRepoProxy: mocks.warmRepoProxy }))
|
||||
|
||||
vi.mock('../src/manager-api.js', () => ({
|
||||
ManagerApi: class {
|
||||
constructor(
|
||||
public readonly managerUrl: string,
|
||||
public readonly token: string,
|
||||
) {}
|
||||
mirrorTargetPlan = mocks.mirrorTargetPlan
|
||||
mirrorEnsureTarget = vi.fn()
|
||||
},
|
||||
ManagerApiError: class ManagerApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly status: number,
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
const matched = { repoId: 1, name: 'repo', projectId: 'proj_1', branch: 'main' }
|
||||
const repos = [
|
||||
{
|
||||
repoId: 1,
|
||||
name: 'repo',
|
||||
directory: '/workspace/repos/repo',
|
||||
branch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
extra: { repoId: 1, localPath: 'repo', fullPath: '/workspace/repos/repo' },
|
||||
},
|
||||
]
|
||||
|
||||
function makeTransfer(): SessionTransferData {
|
||||
return {
|
||||
info: {
|
||||
id: 'ses_a',
|
||||
projectID: 'proj_1',
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: 1, updated: 2 },
|
||||
location: { directory: '/Users/x/repo' },
|
||||
},
|
||||
messages: [],
|
||||
} as unknown as SessionTransferData
|
||||
}
|
||||
|
||||
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: () => session },
|
||||
},
|
||||
keymap: { layer, dispatch },
|
||||
client: { session: { export: exportMock } },
|
||||
} as unknown as Context
|
||||
|
||||
return { context, exportMock, confirm, select, toast, layer, dispatch, slot }
|
||||
}
|
||||
|
||||
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
|
||||
return { sessionID: 'ses_a' }
|
||||
})
|
||||
const addReminder = vi.fn(async () => {
|
||||
mocks.calls.push('synthetic')
|
||||
if (options.reminderError) throw options.reminderError
|
||||
})
|
||||
mocks.createManagerSessionTransfer.mockReturnValue({ sessionExists, importSession, addReminder })
|
||||
return { sessionExists, importSession, addReminder }
|
||||
}
|
||||
|
||||
function configureMove(fake: ReturnType<typeof createFakeContext>) {
|
||||
mocks.readState.mockReturnValue({ managerUrl: 'https://manager.example' })
|
||||
mocks.getToken.mockResolvedValue('tok')
|
||||
mocks.warmRepoProxy.mockResolvedValue(undefined)
|
||||
mocks.fetchRepos.mockResolvedValue(repos)
|
||||
mocks.toRemoteRepoSummaries.mockImplementation((r: unknown) => r)
|
||||
mocks.prepareMirror.mockResolvedValue({ repoRoot: '/Users/x/repo', localProjectId: 'proj_1', matched: [matched] })
|
||||
mocks.getBranchName.mockReturnValue('main')
|
||||
mocks.pickMatchedRepo.mockReturnValue(matched)
|
||||
mocks.mirrorTargetPlan.mockResolvedValue({
|
||||
kind: 'in-place',
|
||||
repoId: 1,
|
||||
fullPath: '/workspace/repos/repo',
|
||||
localPath: '/workspace/repos/repo',
|
||||
branch: 'main',
|
||||
currentBranch: null,
|
||||
})
|
||||
mocks.checkPushDivergence.mockResolvedValue({
|
||||
serverHead: null,
|
||||
serverBranch: 'main',
|
||||
serverDirty: false,
|
||||
diverged: false,
|
||||
lostCommits: 0,
|
||||
})
|
||||
mocks.describePushDivergence.mockReturnValue([])
|
||||
mocks.mirrorUpFast.mockResolvedValue({
|
||||
repoId: 1,
|
||||
fullPath: '/workspace/repos/repo',
|
||||
branch: 'main',
|
||||
head: null,
|
||||
created: false,
|
||||
})
|
||||
fake.confirm.mockResolvedValueOnce(true).mockResolvedValueOnce(false)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
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()
|
||||
configureMove(fake)
|
||||
const { importSession, addReminder } = stubTransfer()
|
||||
fake.exportMock.mockImplementation(async () => {
|
||||
mocks.calls.push('export')
|
||||
return makeTransfer()
|
||||
})
|
||||
|
||||
await invokeMove(fake)
|
||||
|
||||
expect(mocks.calls).toEqual(['export', 'import', 'synthetic'])
|
||||
expect(fake.exportMock).toHaveBeenCalledWith({ sessionID: 'ses_a' })
|
||||
expect(importSession).toHaveBeenCalledWith(
|
||||
'/workspace/repos/repo',
|
||||
expect.objectContaining({ info: expect.objectContaining({ location: { directory: '/workspace/repos/repo' } }) }),
|
||||
)
|
||||
expect(addReminder).toHaveBeenCalledWith('ses_a', moveReminderText('/workspace/repos/repo'))
|
||||
expect(mocks.setPendingWarp).not.toHaveBeenCalled()
|
||||
expect(fake.dispatch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not import or remind when export fails', async () => {
|
||||
const fake = createFakeContext()
|
||||
configureMove(fake)
|
||||
const { importSession, addReminder } = stubTransfer()
|
||||
fake.exportMock.mockRejectedValue(new Error('export failed'))
|
||||
|
||||
await invokeMove(fake)
|
||||
|
||||
expect(mocks.calls).toEqual([])
|
||||
expect(importSession).not.toHaveBeenCalled()
|
||||
expect(addReminder).not.toHaveBeenCalled()
|
||||
expect(mocks.setPendingWarp).not.toHaveBeenCalled()
|
||||
expect(fake.confirm).toHaveBeenCalledTimes(1)
|
||||
expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'error' }))
|
||||
})
|
||||
|
||||
it('does not remind when import fails', async () => {
|
||||
const fake = createFakeContext()
|
||||
configureMove(fake)
|
||||
const { addReminder } = stubTransfer({ importError: new Error('import diverged') })
|
||||
fake.exportMock.mockImplementation(async () => {
|
||||
mocks.calls.push('export')
|
||||
return makeTransfer()
|
||||
})
|
||||
|
||||
await invokeMove(fake)
|
||||
|
||||
expect(mocks.calls).toEqual(['export', 'import'])
|
||||
expect(addReminder).not.toHaveBeenCalled()
|
||||
expect(mocks.setPendingWarp).not.toHaveBeenCalled()
|
||||
expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'error' }))
|
||||
})
|
||||
|
||||
it('keeps the move successful when the synthetic reminder fails', async () => {
|
||||
const fake = createFakeContext()
|
||||
configureMove(fake)
|
||||
const { addReminder } = stubTransfer({ reminderError: new Error('synthetic failed') })
|
||||
fake.exportMock.mockImplementation(async () => {
|
||||
mocks.calls.push('export')
|
||||
return makeTransfer()
|
||||
})
|
||||
|
||||
await invokeMove(fake)
|
||||
|
||||
expect(addReminder).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.setPendingWarp).not.toHaveBeenCalled()
|
||||
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)
|
||||
const { importSession } = stubTransfer()
|
||||
const tooOld = 'OpenCode Manager at https://manager.example is too old for ocm 0.3.0; upgrade the Manager to >= 0.19.0'
|
||||
mocks.warmRepoProxy.mockRejectedValue(new Error(tooOld))
|
||||
|
||||
await invokeMove(fake)
|
||||
|
||||
expect(mocks.warmRepoProxy).toHaveBeenCalledWith('https://manager.example', 'tok', 1)
|
||||
expect(fake.confirm).not.toHaveBeenCalled()
|
||||
expect(mocks.mirrorUpFast).not.toHaveBeenCalled()
|
||||
expect(fake.exportMock).not.toHaveBeenCalled()
|
||||
expect(importSession).not.toHaveBeenCalled()
|
||||
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: tooOld })
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
+29
-19
@@ -1,27 +1,40 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { WarpTarget } from '../src/warp.js'
|
||||
import { setPendingWarp, takePendingWarp, buildAttachArgs, runPendingWarp } from '../src/warp.js'
|
||||
import { setPendingWarp, takePendingWarp, buildAttachInvocation, runPendingWarp } from '../src/warp.js'
|
||||
import { REMOTE_MANAGER_URL_ENV, REMOTE_REPO_NAME_ENV } from '../src/remote-context.js'
|
||||
|
||||
const sampleTarget: WarpTarget = {
|
||||
managerUrl: 'https://manager.example.com',
|
||||
token: 'tok_abc123',
|
||||
directory: '/workspace/my-repo',
|
||||
repoId: 42,
|
||||
sessionID: 'sess_42',
|
||||
repoName: 'my-repo',
|
||||
}
|
||||
|
||||
describe('buildAttachArgs', () => {
|
||||
it('produces the exact argv array for a sample target', () => {
|
||||
const args = buildAttachArgs(sampleTarget)
|
||||
describe('buildAttachInvocation', () => {
|
||||
it('produces the server args and attach env for a target without a session', () => {
|
||||
const invocation = buildAttachInvocation({ managerUrl: 'https://manager.example.com', token: 'tok_abc123', repoId: 42, repoName: 'my-repo' })
|
||||
|
||||
expect(args).toEqual([
|
||||
'attach',
|
||||
'https://manager.example.com/api/opencode-proxy',
|
||||
'--dir', '/workspace/my-repo',
|
||||
'--session', 'sess_42',
|
||||
'--password', 'tok_abc123',
|
||||
'--username', 'opencode',
|
||||
expect(invocation.args).toEqual([
|
||||
'--server',
|
||||
'https://manager.example.com/api/opencode-proxy/repos/42',
|
||||
])
|
||||
expect(invocation.env).toEqual({
|
||||
...process.env,
|
||||
OPENCODE_PASSWORD: 'tok_abc123',
|
||||
[REMOTE_MANAGER_URL_ENV]: 'https://manager.example.com',
|
||||
[REMOTE_REPO_NAME_ENV]: 'my-repo',
|
||||
})
|
||||
})
|
||||
|
||||
it('appends the session arg when the target has one', () => {
|
||||
const invocation = buildAttachInvocation(sampleTarget)
|
||||
|
||||
expect(invocation.args).toEqual([
|
||||
'--server',
|
||||
'https://manager.example.com/api/opencode-proxy/repos/42',
|
||||
'--session',
|
||||
'sess_42',
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -57,20 +70,17 @@ describe('runPendingWarp', () => {
|
||||
it('calls spawn once with the correct args and env', () => {
|
||||
const spawn = vi.fn()
|
||||
setPendingWarp(sampleTarget)
|
||||
const invocation = buildAttachInvocation(sampleTarget)
|
||||
|
||||
runPendingWarp(spawn)
|
||||
|
||||
expect(spawn).toHaveBeenCalledOnce()
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'opencode',
|
||||
buildAttachArgs(sampleTarget),
|
||||
invocation.args,
|
||||
{
|
||||
stdio: 'inherit',
|
||||
env: {
|
||||
...process.env,
|
||||
[REMOTE_MANAGER_URL_ENV]: sampleTarget.managerUrl,
|
||||
[REMOTE_REPO_NAME_ENV]: sampleTarget.repoName,
|
||||
},
|
||||
env: invocation.env,
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -92,4 +102,4 @@ describe('runPendingWarp', () => {
|
||||
expect(() => runPendingWarp(spawn)).not.toThrow()
|
||||
expect(spawn).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user