mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
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.
This commit is contained in:
1 parent
4519bcd2e9
commit
b268a1d356
13 files changed
+602
-17
No files matched your search
@@ -4,7 +4,7 @@ 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 } from '../src/mirror'
|
||||
import { getBranchName } from '../src/local-repo'
|
||||
import { gitRemoteProjectId } from '@opencode-manager/shared/project-id'
|
||||
|
||||
@@ -772,3 +772,89 @@ 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('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