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
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.
This commit is contained in:
1 parent
6c2ebd764b
commit
7351d5f002
313 files changed
+23848
-36801
No files matched your search
+7
-5
@@ -87,9 +87,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,7 +102,9 @@ 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
|
||||
@@ -124,7 +126,7 @@ global installs); the plugin surface is TUI-only.
|
||||
## Requirements
|
||||
|
||||
- macOS or Linux (Windows is unsupported)
|
||||
- `opencode` available on `PATH`
|
||||
- OpenCode 2.x available on `PATH`
|
||||
- `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`)
|
||||
|
||||
+11
-13
@@ -117,8 +117,8 @@ 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)}`
|
||||
async function warmUpInstance(managerUrl: string, token: string, repoId: number): Promise<void> {
|
||||
const url = `${managerUrl}/api/opencode-proxy/repos/${repoId}/api/session?limit=1`
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
try {
|
||||
const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } })
|
||||
@@ -133,19 +133,17 @@ async function warmUpInstance(managerUrl: string, token: string, directory: stri
|
||||
}
|
||||
}
|
||||
|
||||
async function attach(managerUrl: string, token: string, repo: ManagerRepo): Promise<never> {
|
||||
await warmUpInstance(managerUrl, token, repo.directory)
|
||||
const proxyUrl = `${managerUrl}/api/opencode-proxy`
|
||||
async function attach(managerUrl: string, token: string, repo: ManagerRepo, cwd: string): Promise<never> {
|
||||
await warmUpInstance(managerUrl, token, repo.repoId)
|
||||
const proxyUrl = `${managerUrl}/api/opencode-proxy/repos/${repo.repoId}`
|
||||
const args = [
|
||||
'attach',
|
||||
'--server',
|
||||
proxyUrl,
|
||||
'--dir', repo.directory,
|
||||
'--password', token,
|
||||
'--username', 'opencode',
|
||||
]
|
||||
const child = spawn('opencode', args, {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, ...buildRemoteAttachEnv(managerUrl, repo.name) },
|
||||
cwd,
|
||||
env: { ...process.env, OPENCODE_PASSWORD: token, ...buildRemoteAttachEnv(managerUrl, repo.name) },
|
||||
})
|
||||
child.on('close', (code) => process.exit(code ?? 0))
|
||||
child.on('error', (err) => die(`failed to spawn opencode: ${err.message}`))
|
||||
@@ -306,7 +304,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 +337,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': {
|
||||
|
||||
@@ -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": {
|
||||
@@ -53,13 +53,14 @@
|
||||
},
|
||||
"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",
|
||||
"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' },
|
||||
})
|
||||
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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,21 @@
|
||||
import { createOpenCodeApi } from '@opencode-manager/shared/opencode'
|
||||
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
|
||||
|
||||
export function createManagerSessionTransfer(managerUrl: string, token: string) {
|
||||
const api = createOpenCodeApi({
|
||||
baseUrl: `${managerUrl}/api/opencode-proxy`,
|
||||
password: token,
|
||||
})
|
||||
|
||||
return {
|
||||
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 }),
|
||||
}
|
||||
}
|
||||
+57
-140
@@ -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,43 @@ 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
|
||||
}
|
||||
|
||||
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: 'replay-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) }
|
||||
}
|
||||
try {
|
||||
await deps.importSession(input.remoteDirectory, rewritten)
|
||||
} catch (err) {
|
||||
return { kind: 'replay-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: input.sessionID, replayedEvents: 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))
|
||||
}
|
||||
@@ -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 })
|
||||
}
|
||||
+42
-50
@@ -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,8 +9,7 @@ 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 { confirmDialog, selectDialog } from './tui-dialogs.js'
|
||||
import { setPendingWarp, runPendingWarp } from './warp.js'
|
||||
import { pushPhaseProgress, replayProgress } from './move-progress.js'
|
||||
@@ -18,29 +17,29 @@ 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({
|
||||
export async function setupOcm(context: Context, setMoveProgress: MoveProgressSetter): Promise<() => void> {
|
||||
showInstallNotice(context)
|
||||
context.keymap.layer(() => ({
|
||||
commands: [
|
||||
{
|
||||
name: 'ocm.session.move',
|
||||
id: '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),
|
||||
description: 'Push repo state and move this session to OpenCode Manager',
|
||||
group: 'OpenCode Manager',
|
||||
palette: true,
|
||||
slash: { name: 'ocm-move' },
|
||||
run: () => runSessionMove(context, setMoveProgress),
|
||||
},
|
||||
],
|
||||
})
|
||||
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
|
||||
@@ -83,24 +82,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,25 +108,25 @@ 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)!
|
||||
@@ -136,7 +135,7 @@ async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSe
|
||||
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),
|
||||
})
|
||||
@@ -156,45 +155,38 @@ async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSe
|
||||
})
|
||||
const remoteDirectory = pushed.fullPath
|
||||
|
||||
const transfer = createManagerSessionTransfer(state.managerUrl, token)
|
||||
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(replayProgress(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 fetch(`${state.managerUrl}/api/opencode-proxy/repos/${pushed.repoId}/api/session?limit=1`, { headers: { authorization: `Bearer ${token}` } }).catch(() => undefined)
|
||||
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.replayedEvents} events). Local copy kept — run \`ocm\` to attach.` })
|
||||
break
|
||||
}
|
||||
case 'not-found':
|
||||
api.ui.toast({ variant: 'error', message: 'No durable history found for this session' })
|
||||
break
|
||||
case 'corrupt-history':
|
||||
api.ui.toast({ variant: 'error', message: `Session history has a gap at sequence ${result.missingSeq}` })
|
||||
break
|
||||
case 'replay-failed':
|
||||
api.ui.toast({ variant: 'error', message: `Replay failed: ${result.message}` })
|
||||
context.ui.toast.show({ variant: 'error', message: `Replay 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)
|
||||
},
|
||||
})
|
||||
+7
-9
@@ -4,7 +4,7 @@ import { buildRemoteAttachEnv } from './remote-context.js'
|
||||
export type WarpTarget = {
|
||||
managerUrl: string
|
||||
token: string
|
||||
directory: string
|
||||
repoId: number
|
||||
sessionID: string
|
||||
repoName: string
|
||||
}
|
||||
@@ -29,12 +29,10 @@ export function takePendingWarp(): WarpTarget | undefined {
|
||||
|
||||
export function buildAttachArgs(target: WarpTarget): string[] {
|
||||
return [
|
||||
'attach',
|
||||
`${target.managerUrl}/api/opencode-proxy`,
|
||||
'--dir', target.directory,
|
||||
'--session', target.sessionID,
|
||||
'--password', target.token,
|
||||
'--username', 'opencode',
|
||||
'--server',
|
||||
`${target.managerUrl}/api/opencode-proxy/repos/${target.repoId}`,
|
||||
'--session',
|
||||
target.sessionID,
|
||||
]
|
||||
}
|
||||
|
||||
@@ -44,9 +42,9 @@ export function runPendingWarp(spawn: WarpSpawn = spawnSync): void {
|
||||
try {
|
||||
spawn('opencode', buildAttachArgs(target), {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, ...buildRemoteAttachEnv(target.managerUrl, target.repoName) },
|
||||
env: { ...process.env, OPENCODE_PASSWORD: target.token, ...buildRemoteAttachEnv(target.managerUrl, target.repoName) },
|
||||
})
|
||||
} 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,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,57 @@
|
||||
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')
|
||||
})
|
||||
})
|
||||
+148
-318
@@ -1,373 +1,203 @@
|
||||
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', replayedEvents: 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('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: 'replay-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: 'replay-failed', message: 'import diverged' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -388,4 +218,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>`,
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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,257 @@
|
||||
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(),
|
||||
}))
|
||||
|
||||
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/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() {
|
||||
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 context = {
|
||||
ui: {
|
||||
router: { current: () => ({ type: 'session', sessionID: 'ses_a' }) },
|
||||
toast: { show: toast },
|
||||
dialog: { confirm, select },
|
||||
},
|
||||
data: {
|
||||
session: { get: () => ({ location: { directory: '/Users/x/repo' } }) },
|
||||
},
|
||||
keymap: { layer, dispatch },
|
||||
client: { session: { export: exportMock } },
|
||||
} as unknown as Context
|
||||
|
||||
return { context, exportMock, confirm, select, toast, layer, dispatch }
|
||||
}
|
||||
|
||||
function stubTransfer(options: { importError?: Error; reminderError?: Error } = {}) {
|
||||
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({ importSession, addReminder })
|
||||
return { importSession, addReminder }
|
||||
}
|
||||
|
||||
function configureMove(fake: ReturnType<typeof createFakeContext>) {
|
||||
mocks.readState.mockReturnValue({ managerUrl: 'https://manager.example' })
|
||||
mocks.getToken.mockResolvedValue('tok')
|
||||
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())
|
||||
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('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' }))
|
||||
})
|
||||
})
|
||||
@@ -6,7 +6,7 @@ import { REMOTE_MANAGER_URL_ENV, REMOTE_REPO_NAME_ENV } from '../src/remote-cont
|
||||
const sampleTarget: WarpTarget = {
|
||||
managerUrl: 'https://manager.example.com',
|
||||
token: 'tok_abc123',
|
||||
directory: '/workspace/my-repo',
|
||||
repoId: 42,
|
||||
sessionID: 'sess_42',
|
||||
repoName: 'my-repo',
|
||||
}
|
||||
@@ -16,12 +16,10 @@ describe('buildAttachArgs', () => {
|
||||
const args = buildAttachArgs(sampleTarget)
|
||||
|
||||
expect(args).toEqual([
|
||||
'attach',
|
||||
'https://manager.example.com/api/opencode-proxy',
|
||||
'--dir', '/workspace/my-repo',
|
||||
'--session', 'sess_42',
|
||||
'--password', 'tok_abc123',
|
||||
'--username', 'opencode',
|
||||
'--server',
|
||||
'https://manager.example.com/api/opencode-proxy/repos/42',
|
||||
'--session',
|
||||
'sess_42',
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -68,6 +66,7 @@ describe('runPendingWarp', () => {
|
||||
stdio: 'inherit',
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_PASSWORD: sampleTarget.token,
|
||||
[REMOTE_MANAGER_URL_ENV]: sampleTarget.managerUrl,
|
||||
[REMOTE_REPO_NAME_ENV]: sampleTarget.repoName,
|
||||
},
|
||||
@@ -92,4 +91,4 @@ describe('runPendingWarp', () => {
|
||||
expect(() => runPendingWarp(spawn)).not.toThrow()
|
||||
expect(spawn).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user