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
@@ -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