mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(ocm-cli): add session warp with progress reporting (#314)
* feat(ocm-cli): add session warp with progress reporting Add warp functionality for moving sessions between local and remote Managers. Includes TUI dialogs, remote replay, progress reporting during event transfer, and comprehensive test coverage. * feat(ocm-cli): add granular push progress with phase reporting and upload tracking * chore(ocm-cli): bump version to 0.2.5 * docs(ocm-cli): document push progress phases in README
This commit is contained in:
1 parent
4519bcd2e9
commit
adf6bd2921
16 files changed
+759
-30
No files matched your search
+1
-1
@@ -131,7 +131,7 @@ When the TUI plugin is installed, these internal child-process variables add a `
|
||||
|
||||
### TUI `/ocm-move`
|
||||
|
||||
When the TUI plugin entry is installed, `/ocm-move` is available in local OpenCode sessions. It checks that the matching Manager repo has not diverged, pushes the local git state with the fast bundle + working-tree patch path, reads the active session history from the local OpenCode SQLite event database, rewrites local repo directories to the Manager repo directory, and replays the session through `/api/opencode-proxy/sync/replay`. The local session is retained.
|
||||
When the TUI plugin entry is installed, `/ocm-move` is available in local OpenCode sessions. It checks that the matching Manager repo has not diverged, pushes the local git state with the fast bundle + working-tree patch path, reads the active session history from the local OpenCode SQLite event database, rewrites local repo directories to the Manager repo directory, and replays the session through `/api/opencode-proxy/sync/replay`. The local session is retained. When multiple Manager repos match, a select dialog lets you pick the destination. A confirmation dialog gates the move before any push. On success, a synthetic `noReply` reminder prompt is sent to the remote session (best-effort, never fails the move). You can then choose to warp — exit the local TUI and attach to the moved session on the Manager immediately — or keep the local copy with the previous toast behavior.
|
||||
|
||||
- `--force` skips the dirty-working-tree check on `pull` and the safety bail on `push`.
|
||||
- `--create` (on `push`) creates a new Manager repo when no `origin` match is found.
|
||||
|
||||
+13
-7
@@ -49,11 +49,13 @@ it falls back to the last selected repo, then to local `opencode`.
|
||||
and attaches OpenCode to it.
|
||||
|
||||
`ocm push` syncs the current git repo to the matching Manager repo using a fast
|
||||
git bundle + working-tree patch by default. Pass `--full` to use the legacy
|
||||
tarball mirror. If the fast path fails, `ocm` prompts before reverting to the
|
||||
tarball mirror (and proceeds automatically when there is no TTY to prompt). Use
|
||||
`--create` to create a Manager repo when no project match exists, and `--yes` to
|
||||
confirm creation in non-interactive shells.
|
||||
git bundle + working-tree patch by default. The CLI reports granular progress
|
||||
phases during push: bundling, uploading (with byte counts), server processing,
|
||||
and patching. Pass `--full` to use the legacy tarball mirror. If the fast path
|
||||
fails, `ocm` prompts before reverting to the tarball mirror (and proceeds
|
||||
automatically when there is no TTY to prompt). Use `--create` to create a Manager
|
||||
repo when no project match exists, and `--yes` to confirm creation in
|
||||
non-interactive shells.
|
||||
|
||||
`ocm pull` syncs the matching Manager repo over the current working tree using a
|
||||
fast git bundle + working-tree patch by default. Pass `--full` to use the legacy
|
||||
@@ -69,8 +71,12 @@ 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 pushing the current repo state.
|
||||
Use it from inside an OpenCode session after `ocm login` and after the repo
|
||||
already exists on the Manager (`ocm push --create` if needed).
|
||||
When multiple Manager repos match, a picker dialog lets you choose the
|
||||
destination. A confirmation dialog gates the move before any push. 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`:
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-manager/ocm-cli",
|
||||
"version": "0.2.4",
|
||||
"version": "0.2.5",
|
||||
"description": "OpenCode Manager CLI: attach a local OpenCode TUI to a Manager-hosted repo.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -52,6 +52,17 @@ export interface MirrorBundleResult {
|
||||
created: false
|
||||
}
|
||||
|
||||
function createByteCounter(onProgress: (bytesSent: number) => void): TransformStream<Uint8Array, Uint8Array> {
|
||||
let bytesSent = 0
|
||||
return new TransformStream<Uint8Array, Uint8Array>({
|
||||
transform(chunk, controller) {
|
||||
bytesSent += chunk.byteLength
|
||||
onProgress(bytesSent)
|
||||
controller.enqueue(chunk)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export class ManagerApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
@@ -161,11 +172,16 @@ export class ManagerApi {
|
||||
return (await res.json()) as MirrorPatchResult
|
||||
}
|
||||
|
||||
async mirrorUploadBundle(repoId: number, bundlePath: string, opts: { branch: string | null; force?: boolean }): Promise<MirrorBundleResult> {
|
||||
async mirrorUploadBundle(
|
||||
repoId: number,
|
||||
bundlePath: string,
|
||||
opts: { branch: string | null; force?: boolean; onProgress?: (bytesSent: number) => void },
|
||||
): Promise<MirrorBundleResult> {
|
||||
const query = opts.force === true ? '?force=1' : ''
|
||||
const headers: Record<string, string> = { ...this.headers(), 'Content-Type': 'application/octet-stream' }
|
||||
if (opts.branch) headers['X-OCM-Branch'] = opts.branch
|
||||
const body = Readable.toWeb(createReadStream(bundlePath)) as unknown as ReadableStream<Uint8Array>
|
||||
const fileStream = Readable.toWeb(createReadStream(bundlePath)) as unknown as ReadableStream<Uint8Array>
|
||||
const body = opts.onProgress ? fileStream.pipeThrough(createByteCounter(opts.onProgress)) : fileStream
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle${query}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
|
||||
+33
-3
@@ -379,7 +379,17 @@ function applyPatch(repoRoot: string, patch: string): void {
|
||||
|
||||
async function createLocalBundle(repoRoot: string): Promise<string> {
|
||||
const bundlePath = join(tmpdir(), `ocm-bundle-${Date.now()}-${Math.random().toString(36).slice(2)}.bundle`)
|
||||
runGit(repoRoot, ['bundle', 'create', bundlePath, '--all'])
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const child = spawn('git', ['bundle', 'create', bundlePath, '--all'], { cwd: repoRoot })
|
||||
const stderrChunks: Buffer[] = []
|
||||
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk))
|
||||
child.on('error', reject)
|
||||
child.on('close', (code) => {
|
||||
if (code === 0) return resolve()
|
||||
const stderr = Buffer.concat(stderrChunks).toString('utf-8').trim()
|
||||
reject(new Error(`git bundle create failed${stderr ? `: ${stderr}` : ''}`))
|
||||
})
|
||||
})
|
||||
return bundlePath
|
||||
}
|
||||
|
||||
@@ -428,14 +438,34 @@ async function writeBundleStream(repoId: number, api: ManagerApi): Promise<strin
|
||||
return bundlePath
|
||||
}
|
||||
|
||||
export type MirrorUpFastPhase =
|
||||
| { kind: 'bundling' }
|
||||
| { kind: 'uploading'; bytesSent: number; totalBytes: number }
|
||||
| { kind: 'processing' }
|
||||
| { kind: 'patching' }
|
||||
|
||||
export async function mirrorUpFast(
|
||||
plan: MirrorPlan,
|
||||
opts: Pick<MirrorUpOpts, 'api' | 'force'>,
|
||||
opts: Pick<MirrorUpOpts, 'api' | 'force'> & { onPhase?: (phase: MirrorUpFastPhase) => void },
|
||||
): Promise<{ repoId: number; branch: string | null; head: string | null; created: false }> {
|
||||
const repoId = plan.matched[0]!.repoId
|
||||
const onPhase = opts.onPhase
|
||||
onPhase?.({ kind: 'bundling' })
|
||||
const bundlePath = await createLocalBundle(plan.repoRoot)
|
||||
try {
|
||||
await opts.api.mirrorUploadBundle(repoId, bundlePath, { branch: getBranchName(plan.repoRoot), force: opts.force })
|
||||
const { size } = await fsp.stat(bundlePath)
|
||||
onPhase?.({ kind: 'uploading', bytesSent: 0, totalBytes: size })
|
||||
await opts.api.mirrorUploadBundle(repoId, bundlePath, {
|
||||
branch: getBranchName(plan.repoRoot),
|
||||
force: opts.force,
|
||||
onProgress: onPhase
|
||||
? (bytesSent) => {
|
||||
onPhase({ kind: 'uploading', bytesSent, totalBytes: size })
|
||||
if (bytesSent >= size) onPhase({ kind: 'processing' })
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
onPhase?.({ kind: 'patching' })
|
||||
const patchResult = await mirrorUpPatch(plan, opts)
|
||||
return { repoId: patchResult.repoId, branch: patchResult.branch, head: patchResult.head, created: false }
|
||||
} finally {
|
||||
|
||||
@@ -16,4 +16,19 @@ export function createManagerReplay(managerUrl: string, token: string) {
|
||||
|
||||
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)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,7 @@ function coerceTimestamp(data: Record<string, unknown>): void {
|
||||
export type TransferDeps = {
|
||||
fetchLocalHistory: () => Promise<HistoryEventRow[]>
|
||||
replayEvents: (remoteDirectory: string, events: ReplayEvent[]) => Promise<{ sessionID: string }>
|
||||
onProgress?: (replayed: number, total: number) => void
|
||||
}
|
||||
|
||||
export type TransferInput = { sessionID: string; localRoot: string; remoteDirectory: string }
|
||||
@@ -134,12 +135,15 @@ export async function transferSession(input: TransferInput, deps: TransferDeps):
|
||||
})
|
||||
|
||||
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) }
|
||||
}
|
||||
@@ -148,6 +152,10 @@ export async function transferSession(input: TransferInput, deps: TransferDeps):
|
||||
return { kind: 'moved', sessionID: input.sessionID, replayedEvents: replayed }
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { TuiPluginApi } from './tui-types.js'
|
||||
|
||||
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 selectDialog<Value>(
|
||||
api: TuiPluginApi,
|
||||
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),
|
||||
)
|
||||
})
|
||||
}
|
||||
+60
-11
@@ -4,9 +4,13 @@ import { getToken } from './keychain.js'
|
||||
import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js'
|
||||
import { ManagerApi, ManagerApiError } from './manager-api.js'
|
||||
import { prepareMirror, checkPushDivergence, mirrorUpFast } from './mirror.js'
|
||||
import { transferSession } from './session-move.js'
|
||||
import { createManagerReplay } from './remote-replay.js'
|
||||
import type { MirrorPlan, MirrorUpFastPhase } from './mirror.js'
|
||||
import { formatBytes } from './progress.js'
|
||||
import { transferSession, moveReminderText } from './session-move.js'
|
||||
import { createManagerReplay, createManagerPromptAsync } from './remote-replay.js'
|
||||
import { readSessionEvents } from './local-history.js'
|
||||
import { confirmDialog, selectDialog } from './tui-dialogs.js'
|
||||
import { setPendingWarp, runPendingWarp } from './warp.js'
|
||||
|
||||
export async function setupOcm(api: TuiPluginApi): Promise<void> {
|
||||
showInstallNotice(api)
|
||||
@@ -23,6 +27,7 @@ export async function setupOcm(api: TuiPluginApi): Promise<void> {
|
||||
},
|
||||
],
|
||||
})
|
||||
api.lifecycle.onDispose(() => runPendingWarp())
|
||||
}
|
||||
|
||||
function showInstallNotice(api: TuiPluginApi): void {
|
||||
@@ -39,6 +44,31 @@ function showInstallNotice(api: TuiPluginApi): void {
|
||||
})
|
||||
}
|
||||
|
||||
function pushPhaseMessage(phase: MirrorUpFastPhase): string {
|
||||
switch (phase.kind) {
|
||||
case 'bundling':
|
||||
return 'Pushing repo state: creating git bundle…'
|
||||
case 'uploading':
|
||||
return `Pushing repo state: uploading ${formatBytes(phase.bytesSent)} / ${formatBytes(phase.totalBytes)}…`
|
||||
case 'processing':
|
||||
return 'Pushing repo state: waiting for server to import bundle…'
|
||||
case 'patching':
|
||||
return 'Pushing repo state: applying local changes…'
|
||||
}
|
||||
}
|
||||
|
||||
function createPushPhaseToaster(api: TuiPluginApi): (phase: MirrorUpFastPhase) => void {
|
||||
let lastUploadToastAt = 0
|
||||
return (phase) => {
|
||||
if (phase.kind === 'uploading') {
|
||||
const now = Date.now()
|
||||
if (now - lastUploadToastAt < 1000) return
|
||||
lastUploadToastAt = now
|
||||
}
|
||||
api.ui.toast({ message: pushPhaseMessage(phase) })
|
||||
}
|
||||
}
|
||||
|
||||
async function runSessionMove(api: TuiPluginApi): Promise<void> {
|
||||
try {
|
||||
const current = api.route.current
|
||||
@@ -74,17 +104,19 @@ async function runSessionMove(api: TuiPluginApi): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
let matched = plan.matched[0]!
|
||||
if (plan.matched.length > 1) {
|
||||
const names = plan.matched.map((r) => `${r.name} (id=${r.repoId})`).join(', ')
|
||||
api.ui.toast({ variant: 'error', message: `Multiple Manager repos match: ${names}` })
|
||||
return
|
||||
const chosen = await selectDialog(api, 'Move session to Manager repo', plan.matched.map((r) => ({ title: r.name, description: `id=${r.repoId}`, value: r })))
|
||||
if (!chosen) return
|
||||
matched = chosen
|
||||
}
|
||||
|
||||
const matched = plan.matched[0]!
|
||||
const repoId = matched.repoId
|
||||
const remoteRepo = repos.find((r) => r.repoId === repoId)
|
||||
const remoteDirectory = remoteRepo!.directory
|
||||
|
||||
const proceed = await confirmDialog(api, { title: 'Move session to Manager', message: `Push repo state and move this session to ${matched.name} (${remoteDirectory})?` })
|
||||
if (!proceed) return
|
||||
|
||||
const managerApi = new ManagerApi(state.managerUrl, token)
|
||||
|
||||
try {
|
||||
@@ -97,18 +129,35 @@ async function runSessionMove(api: TuiPluginApi): Promise<void> {
|
||||
if (!(error instanceof ManagerApiError && error.status === 404)) throw error
|
||||
}
|
||||
|
||||
api.ui.toast({ message: 'Pushing repo state…' })
|
||||
await mirrorUpFast(plan, { api: managerApi, force: false })
|
||||
const selectedPlan: MirrorPlan = { ...plan, matched: [matched] }
|
||||
await mirrorUpFast(selectedPlan, {
|
||||
api: managerApi,
|
||||
force: false,
|
||||
onPhase: createPushPhaseToaster(api),
|
||||
})
|
||||
|
||||
const result = await transferSession(
|
||||
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
|
||||
{ fetchLocalHistory: () => readSessionEvents(sessionID), replayEvents: createManagerReplay(state.managerUrl, token) },
|
||||
{
|
||||
fetchLocalHistory: () => readSessionEvents(sessionID),
|
||||
replayEvents: createManagerReplay(state.managerUrl, token),
|
||||
onProgress: (replayed, total) => api.ui.toast({ message: `Moving session… ${replayed}/${total} events`, duration: 2000 }),
|
||||
},
|
||||
)
|
||||
|
||||
switch (result.kind) {
|
||||
case 'moved':
|
||||
case 'moved': {
|
||||
await createManagerPromptAsync(state.managerUrl, token)(remoteDirectory, result.sessionID, moveReminderText(remoteDirectory)).catch(() => undefined)
|
||||
const warp = await confirmDialog(api, { 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')
|
||||
return
|
||||
}
|
||||
api.ui.toast({ 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
|
||||
|
||||
@@ -18,11 +18,17 @@ export type TuiRouteCurrent = { name: 'session'; params: { sessionID: string } }
|
||||
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 }
|
||||
keymap: { registerLayer: (layer: { commands: TuiCommandDef[]; bindings?: Record<string, unknown> }) => unknown }
|
||||
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> }
|
||||
@@ -0,0 +1,52 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { buildRemoteAttachEnv } from './remote-context.js'
|
||||
|
||||
export type WarpTarget = {
|
||||
managerUrl: string
|
||||
token: string
|
||||
directory: string
|
||||
sessionID: string
|
||||
repoName: string
|
||||
}
|
||||
|
||||
export type WarpSpawn = (
|
||||
command: string,
|
||||
args: string[],
|
||||
options: { stdio: 'inherit'; env: NodeJS.ProcessEnv },
|
||||
) => unknown
|
||||
|
||||
let pending: WarpTarget | undefined
|
||||
|
||||
export function setPendingWarp(target: WarpTarget): void {
|
||||
pending = target
|
||||
}
|
||||
|
||||
export function takePendingWarp(): WarpTarget | undefined {
|
||||
const t = pending
|
||||
pending = 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 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) },
|
||||
})
|
||||
} catch {
|
||||
void 0
|
||||
}
|
||||
}
|
||||
+155
-2
@@ -1,10 +1,10 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readdirSync, readFileSync } from 'fs'
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readdirSync, readFileSync, statSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { tmpdir } from 'os'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { spawnSync, execSync } from 'child_process'
|
||||
import { prepareMirror, MirrorAbort, mirrorDown, mirrorUp, mirrorUpPatch, checkPushDivergence, checkPullDivergence } from '../src/mirror'
|
||||
import { prepareMirror, MirrorAbort, mirrorDown, mirrorUp, mirrorUpPatch, mirrorUpFast, checkPushDivergence, checkPullDivergence, type MirrorUpFastPhase } from '../src/mirror'
|
||||
import { getBranchName } from '../src/local-repo'
|
||||
import { gitRemoteProjectId } from '@opencode-manager/shared/project-id'
|
||||
|
||||
@@ -772,3 +772,156 @@ describe('mirror patch helpers', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('mirrorUpFast targets the selected repo', () => {
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = mkdtempSync(join(tmpdir(), 'mirror-upfast-test-'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('uses the repoId from plan.matched[0] for bundle upload and patch', async () => {
|
||||
const repoRoot = join(tmpDir, 'repo-selected')
|
||||
mkdirSync(repoRoot)
|
||||
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
writeFileSync(join(repoRoot, 'tracked.txt'), 'content\n')
|
||||
spawnSync('git', ['add', 'tracked.txt'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['commit', '-m', 'initial'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
writeFileSync(join(repoRoot, 'tracked.txt'), 'updated\n')
|
||||
|
||||
const api = {
|
||||
mirrorUploadBundle: vi.fn().mockResolvedValue(undefined),
|
||||
mirrorPatch: vi.fn().mockResolvedValue({ repoId: 99, fullPath: '/tmp/x', branch: 'main', head: 'def', created: false, applied: true }),
|
||||
}
|
||||
|
||||
const plan = {
|
||||
repoRoot,
|
||||
localProjectId: 'proj',
|
||||
matched: [
|
||||
{ repoId: 10, name: 'first-repo', projectId: 'proj', branch: 'main' },
|
||||
{ repoId: 99, name: 'selected-repo', projectId: 'proj', branch: 'main' },
|
||||
],
|
||||
}
|
||||
|
||||
const selectedPlan = { ...plan, matched: [plan.matched[1]!] }
|
||||
const result = await mirrorUpFast(selectedPlan, { api: api as any, force: false })
|
||||
|
||||
expect(api.mirrorUploadBundle).toHaveBeenCalledTimes(1)
|
||||
expect(api.mirrorUploadBundle.mock.calls[0]![0]).toBe(99)
|
||||
expect(api.mirrorPatch).toHaveBeenCalledTimes(1)
|
||||
expect(api.mirrorPatch.mock.calls[0]![0]).toBe(99)
|
||||
expect(result.repoId).toBe(99)
|
||||
})
|
||||
|
||||
it('reports bundling, uploading, and patching phases in order', async () => {
|
||||
const repoRoot = join(tmpDir, 'repo-phases')
|
||||
mkdirSync(repoRoot)
|
||||
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
writeFileSync(join(repoRoot, 'a.txt'), 'a\n')
|
||||
spawnSync('git', ['add', '.'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['commit', '-m', 'init'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
|
||||
const api = {
|
||||
mirrorUploadBundle: vi.fn().mockResolvedValue(undefined),
|
||||
mirrorPatch: vi.fn().mockResolvedValue({ repoId: 1, fullPath: '/tmp/x', branch: 'main', head: 'abc', created: false, applied: true }),
|
||||
}
|
||||
|
||||
const plan = {
|
||||
repoRoot,
|
||||
localProjectId: 'proj',
|
||||
matched: [{ repoId: 1, name: 'repo-A', projectId: 'proj', branch: 'main' }],
|
||||
}
|
||||
|
||||
const phases: MirrorUpFastPhase[] = []
|
||||
await mirrorUpFast(plan, { api: api as any, force: false, onPhase: (p) => phases.push(p) })
|
||||
|
||||
expect(phases.map((p) => p.kind)).toEqual(['bundling', 'uploading', 'patching'])
|
||||
const uploading = phases[1] as Extract<MirrorUpFastPhase, { kind: 'uploading' }>
|
||||
expect(uploading.bytesSent).toBe(0)
|
||||
expect(uploading.totalBytes).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('emits cumulative upload progress and a processing phase when the api reports sent bytes', async () => {
|
||||
const repoRoot = join(tmpDir, 'repo-upload-progress')
|
||||
mkdirSync(repoRoot)
|
||||
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
writeFileSync(join(repoRoot, 'a.txt'), 'a\n')
|
||||
spawnSync('git', ['add', '.'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['commit', '-m', 'init'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
|
||||
const api = {
|
||||
mirrorUploadBundle: vi.fn().mockImplementation(
|
||||
async (_repoId: number, bundlePath: string, opts: { onProgress?: (bytesSent: number) => void }) => {
|
||||
const { size } = statSync(bundlePath)
|
||||
opts.onProgress?.(Math.floor(size / 2))
|
||||
opts.onProgress?.(size)
|
||||
},
|
||||
),
|
||||
mirrorPatch: vi.fn().mockResolvedValue({ repoId: 1, fullPath: '/tmp/x', branch: 'main', head: 'abc', created: false, applied: true }),
|
||||
}
|
||||
|
||||
const plan = {
|
||||
repoRoot,
|
||||
localProjectId: 'proj',
|
||||
matched: [{ repoId: 1, name: 'repo-A', projectId: 'proj', branch: 'main' }],
|
||||
}
|
||||
|
||||
const phases: MirrorUpFastPhase[] = []
|
||||
await mirrorUpFast(plan, { api: api as any, force: false, onPhase: (p) => phases.push(p) })
|
||||
|
||||
expect(phases.map((p) => p.kind)).toEqual(['bundling', 'uploading', 'uploading', 'uploading', 'processing', 'patching'])
|
||||
const sent = phases.filter((p): p is Extract<MirrorUpFastPhase, { kind: 'uploading' }> => p.kind === 'uploading').map((p) => p.bytesSent)
|
||||
expect(sent[0]).toBe(0)
|
||||
expect(sent[1]!).toBeGreaterThan(0)
|
||||
expect(sent[2]!).toBeGreaterThan(sent[1]!)
|
||||
})
|
||||
|
||||
it('narrows a multi-match plan so bundle goes to the chosen repo', async () => {
|
||||
const repoRoot = join(tmpDir, 'repo-narrow')
|
||||
mkdirSync(repoRoot)
|
||||
spawnSync('git', ['init'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['config', 'user.email', 'test@test.com'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['config', 'user.name', 'Test'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
writeFileSync(join(repoRoot, 'a.txt'), 'a\n')
|
||||
spawnSync('git', ['add', '.'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
spawnSync('git', ['commit', '-m', 'init'], { cwd: repoRoot, stdio: 'ignore' })
|
||||
writeFileSync(join(repoRoot, 'a.txt'), 'a-updated\n')
|
||||
|
||||
const uploadCalls: number[] = []
|
||||
const patchCalls: number[] = []
|
||||
|
||||
const api = {
|
||||
mirrorUploadBundle: vi.fn().mockImplementation(async (repoId: number) => { uploadCalls.push(repoId) }),
|
||||
mirrorPatch: vi.fn().mockImplementation(async (repoId: number) => {
|
||||
patchCalls.push(repoId)
|
||||
return { repoId, fullPath: '/tmp/x', branch: 'main', head: 'abc', created: false, applied: true }
|
||||
}),
|
||||
}
|
||||
|
||||
const multiPlan = {
|
||||
repoRoot,
|
||||
localProjectId: 'proj',
|
||||
matched: [
|
||||
{ repoId: 1, name: 'repo-A', projectId: 'proj', branch: 'main' },
|
||||
{ repoId: 2, name: 'repo-B', projectId: 'proj', branch: 'main' },
|
||||
{ repoId: 3, name: 'repo-C', projectId: 'proj', branch: 'main' },
|
||||
],
|
||||
}
|
||||
|
||||
const selectedPlan = { ...multiPlan, matched: [multiPlan.matched[2]!] }
|
||||
await mirrorUpFast(selectedPlan, { api: api as any, force: false })
|
||||
|
||||
expect(uploadCalls).toEqual([3])
|
||||
expect(patchCalls).toEqual([3])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
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): ')
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { collectSessionEvents, rewriteEventsForRemote, transferSession, planReplayBatches, type HistoryEventRow, type ReplayEvent, type TransferDeps } from '../src/session-move.js'
|
||||
import { collectSessionEvents, rewriteEventsForRemote, transferSession, planReplayBatches, moveReminderText, type HistoryEventRow, type ReplayEvent, type TransferDeps } from '../src/session-move.js'
|
||||
|
||||
describe('collectSessionEvents', () => {
|
||||
it('collects a session\'s events in seq order with remapped aggregateID', () => {
|
||||
@@ -269,6 +269,21 @@ describe('transferSession', () => {
|
||||
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)
|
||||
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([]),
|
||||
@@ -316,4 +331,23 @@ describe('transferSession', () => {
|
||||
expect(result).toEqual({ kind: 'replay-failed', message: 'Replay diverged' })
|
||||
expect(callCount).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('moveReminderText', () => {
|
||||
it('wraps the directory in a system-reminder block', () => {
|
||||
const result = moveReminderText('/workspace/repos/repo')
|
||||
expect(result).toContain('<system-reminder>')
|
||||
expect(result).toContain('</system-reminder>')
|
||||
expect(result).toContain('/workspace/repos/repo')
|
||||
})
|
||||
|
||||
it('matches the native opencode wording byte-for-byte apart from the directory', () => {
|
||||
const dir = '/some/path'
|
||||
const result = moveReminderText(dir)
|
||||
const prefix = '<system-reminder>The user has changed the current working directory to "'
|
||||
expect(result.startsWith(prefix)).toBe(true)
|
||||
expect(result).toBe(
|
||||
`<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>`,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import type { TuiPluginApi, TuiDialogConfirmProps, TuiDialogSelectProps } from '../src/tui-types.js'
|
||||
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 }
|
||||
}
|
||||
|
||||
describe('confirmDialog', () => {
|
||||
it('resolves true when onConfirm fires', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const p = confirmDialog(api, { title: 'Confirm', message: 'Continue?' })
|
||||
|
||||
const { render } = getCaptured()
|
||||
const props = render() as TuiDialogConfirmProps
|
||||
props.onConfirm!()
|
||||
|
||||
expect(await p).toBe(true)
|
||||
expect(api.ui.dialog.clear).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('resolves false when onCancel fires', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const p = confirmDialog(api, { title: 'Confirm', message: 'Continue?' })
|
||||
|
||||
const { render } = getCaptured()
|
||||
const props = render() as TuiDialogConfirmProps
|
||||
props.onCancel!()
|
||||
|
||||
expect(await p).toBe(false)
|
||||
expect(api.ui.dialog.clear).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('resolves false when onClose fires without calling clear', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const p = confirmDialog(api, { title: 'Confirm', message: 'Continue?' })
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
|
||||
describe('selectDialog', () => {
|
||||
it('resolves the chosen option value via onSelect', async () => {
|
||||
const { api, getCaptured } = createFakeApi()
|
||||
const options = [
|
||||
{ title: 'A', value: 'a' },
|
||||
{ title: 'B', value: 'b' },
|
||||
]
|
||||
const p = selectDialog(api, 'Pick one', options)
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
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)
|
||||
|
||||
const { onClose } = getCaptured()
|
||||
onClose!()
|
||||
|
||||
expect(await p).toBeUndefined()
|
||||
expect(api.ui.dialog.clear).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
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,95 @@
|
||||
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 { 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',
|
||||
sessionID: 'sess_42',
|
||||
repoName: 'my-repo',
|
||||
}
|
||||
|
||||
describe('buildAttachArgs', () => {
|
||||
it('produces the exact argv array for a sample target', () => {
|
||||
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',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('setPendingWarp / takePendingWarp', () => {
|
||||
beforeEach(() => {
|
||||
takePendingWarp()
|
||||
})
|
||||
|
||||
it('round-trips the target', () => {
|
||||
setPendingWarp(sampleTarget)
|
||||
expect(takePendingWarp()).toEqual(sampleTarget)
|
||||
})
|
||||
|
||||
it('returns undefined on second take', () => {
|
||||
setPendingWarp(sampleTarget)
|
||||
takePendingWarp()
|
||||
expect(takePendingWarp()).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('runPendingWarp', () => {
|
||||
beforeEach(() => {
|
||||
takePendingWarp()
|
||||
})
|
||||
|
||||
it('is a no-op when nothing is pending', () => {
|
||||
const spawn = vi.fn()
|
||||
runPendingWarp(spawn)
|
||||
expect(spawn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls spawn once with the correct args and env', () => {
|
||||
const spawn = vi.fn()
|
||||
setPendingWarp(sampleTarget)
|
||||
|
||||
runPendingWarp(spawn)
|
||||
|
||||
expect(spawn).toHaveBeenCalledOnce()
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'opencode',
|
||||
buildAttachArgs(sampleTarget),
|
||||
{
|
||||
stdio: 'inherit',
|
||||
env: {
|
||||
...process.env,
|
||||
[REMOTE_MANAGER_URL_ENV]: sampleTarget.managerUrl,
|
||||
[REMOTE_REPO_NAME_ENV]: sampleTarget.repoName,
|
||||
},
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
it('does not spawn again on a second invocation', () => {
|
||||
const spawn = vi.fn()
|
||||
setPendingWarp(sampleTarget)
|
||||
|
||||
runPendingWarp(spawn)
|
||||
runPendingWarp(spawn)
|
||||
|
||||
expect(spawn).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('swallows a throwing spawn without propagating', () => {
|
||||
const spawn = vi.fn(() => { throw new Error('spawn failed') })
|
||||
setPendingWarp(sampleTarget)
|
||||
|
||||
expect(() => runPendingWarp(spawn)).not.toThrow()
|
||||
expect(spawn).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user