chore(lint): replace ESLint with Oxlint and clear anti-slop findings

This commit is contained in:
Chris Scott committed 2026-11-13 01:13:34 -05:00
1 parent c6c13335e5
commit b625acfc0c
1083 files changed
+67089 -80136

No files matched your search

+90 -63
View File
@@ -1,22 +1,30 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import type { OcmState } from '../src/state.js'
import {
MockTokenStoreError,
mockStateModule,
mockTokenStoreModule,
unmockTokenStoreModules,
type TokenStoreMockOptions,
} from './helpers/token-store-mocks.js'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname } from 'node:path'
import { z } from 'zod'
import { createFileTokenStore } from '../src/token-store-file.js'
import { createCliHome, type CliHome } from './helpers/cli-home.js'
type CliOverrides = TokenStoreMockOptions & {
state?: OcmState | null
const MANAGER = 'https://manager.example.com'
interface LoadOptions {
state?: { managerUrl: string } | null
token?: string | null
envToken?: string | null
documentVersion?: number
}
async function loadCli(overrides: CliOverrides = {}) {
vi.resetModules()
const state = 'state' in overrides ? overrides.state : { managerUrl: 'https://manager.example.com' }
const { clearState } = mockStateModule(state ?? null)
const { getToken, setToken, deleteToken } = mockTokenStoreModule(overrides)
const homes: CliHome[] = []
async function loadCli(options: LoadOptions = {}) {
const home = createCliHome({
state: options.state === undefined ? { managerUrl: MANAGER } : options.state,
token: options.token ?? null,
envToken: options.envToken ?? null,
documentVersion: options.documentVersion,
account: MANAGER,
})
homes.push(home)
const written: string[] = []
const stderr: string[] = []
const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
@@ -27,15 +35,14 @@ async function loadCli(overrides: CliOverrides = {}) {
stderr.push(String(chunk))
return true
})
vi.resetModules()
const cli = await import('../bin/ocm')
return {
cli,
written,
stderr,
getToken,
setToken,
deleteToken,
clearState,
home,
storedToken: () => createFileTokenStore(home.credentialsPath).get(MANAGER),
restore: () => {
stdoutSpy.mockRestore()
stderrSpy.mockRestore()
@@ -43,6 +50,16 @@ async function loadCli(overrides: CliOverrides = {}) {
}
}
async function exitCodeOnFailure(run: () => Promise<void>): Promise<number | undefined> {
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
throw new Error('exit')
})
await expect(run()).rejects.toThrow('exit')
const code = z.number().safeParse(exitSpy.mock.calls[0]?.[0])
exitSpy.mockRestore()
return code.success ? code.data : undefined
}
describe('cli auth commands', () => {
let originalArgv: string[]
@@ -53,15 +70,15 @@ describe('cli auth commands', () => {
afterEach(() => {
process.argv = originalArgv
unmockTokenStoreModules()
for (const home of homes.splice(0)) home.restore()
})
it('ocm status reports the store kind and location', async () => {
const { cli, written, restore } = await loadCli({ token: 'tok', store: { kind: 'file', location: '/tmp/credentials.json' } })
const { cli, written, home, restore } = await loadCli({ token: 'tok' })
await cli.cmdStatus()
const out = written.join('')
expect(out).toContain('token store:')
expect(out).toContain('file (/tmp/credentials.json)')
expect(out).toContain(`file (${home.credentialsPath})`)
restore()
})
@@ -78,7 +95,7 @@ describe('cli auth commands', () => {
})
it('ocm status reports the env store', async () => {
const { cli, written, restore } = await loadCli({ env: 'tok_env' })
const { cli, written, restore } = await loadCli({ envToken: 'tok_env' })
await cli.cmdStatus()
const out = written.join('')
expect(out).toContain('env (OCM_TOKEN)')
@@ -86,17 +103,17 @@ describe('cli auth commands', () => {
})
it('ocm status reports the store in the no-state branch', async () => {
const { cli, written, restore } = await loadCli({ state: null, token: null })
const { cli, written, home, restore } = await loadCli({ state: null, token: null })
await cli.cmdStatus()
const out = written.join('')
expect(out).toContain('token store:')
expect(out).toContain('file (/tmp/credentials.json)')
expect(out).toContain(`file (${home.credentialsPath})`)
expect(out).toMatch(/^token:\s+no/m)
restore()
})
it('ocm status reports a token is present in the no-state branch when OCM_TOKEN is active', async () => {
const { cli, written, restore } = await loadCli({ state: null, env: 'tok_env' })
const { cli, written, restore } = await loadCli({ state: null, envToken: 'tok_env' })
await cli.cmdStatus()
const out = written.join('')
expect(out).toContain('token store:')
@@ -106,38 +123,33 @@ describe('cli auth commands', () => {
})
it('ocm status reports an unavailable token store instead of exiting', async () => {
const { cli, written, restore } = await loadCli({
getTokenImpl: () => Promise.reject(new MockTokenStoreError('keychain locked', 'keychain')),
})
const { cli, written, restore } = await loadCli({ documentVersion: 2 })
await cli.cmdStatus()
const out = written.join('')
expect(out).toMatch(/^token:\s+unavailable \(keychain locked\)/m)
expect(out).toMatch(/^token:\s+unavailable \(token file .*unsupported format version 2/m)
expect(out).toContain('manager url:')
restore()
})
it('ocm login stores the token verbatim', async () => {
const { cli, setToken, restore } = await loadCli()
it('ocm login stores the token for the normalized manager url', async () => {
const { cli, storedToken, restore } = await loadCli()
await cli.cmdLogin(['https://manager.example.com/', 'tok_xyz'])
expect(setToken).toHaveBeenCalledWith('https://manager.example.com', 'tok_xyz')
expect(await storedToken()).toBe('tok_xyz')
restore()
})
it('ocm login names the store on success', async () => {
const { cli, written, restore } = await loadCli({ store: { kind: 'file', location: '/tmp/credentials.json' } })
const { cli, written, home, restore } = await loadCli()
await cli.cmdLogin(['https://manager.example.com', 'tok_xyz'])
expect(written.join('')).toContain('Saved token for https://manager.example.com (file: /tmp/credentials.json).')
expect(written.join('')).toContain(`Saved token for ${MANAGER} (file: ${home.credentialsPath}).`)
restore()
})
it('ocm login reports the persisted store and warns that OCM_TOKEN wins', async () => {
const { cli, written, restore } = await loadCli({
env: 'tok_env',
writeTarget: { kind: 'file', location: '/tmp/credentials.json' },
})
const { cli, written, home, restore } = await loadCli({ envToken: 'tok_env' })
await cli.cmdLogin(['https://manager.example.com', 'tok_xyz'])
const out = written.join('')
expect(out).toContain('Saved token for https://manager.example.com (file: /tmp/credentials.json).')
expect(out).toContain(`Saved token for ${MANAGER} (file: ${home.credentialsPath}).`)
expect(out).toContain('note: OCM_TOKEN is set and takes precedence over the stored token')
restore()
})
@@ -150,25 +162,23 @@ describe('cli auth commands', () => {
})
it('ocm login surfaces a store failure', async () => {
const { cli, stderr, restore } = await loadCli({
setTokenImpl: () => Promise.reject(new MockTokenStoreError('disk full')),
})
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => { throw new Error('exit') })
await expect(cli.cmdLogin(['https://manager.example.com', 'tok_xyz'])).rejects.toThrow('exit')
expect(stderr.join('')).toContain('token store error: disk full')
expect(exitSpy).toHaveBeenCalledWith(1)
const { cli, stderr, restore } = await loadCli({ documentVersion: 2 })
const code = await exitCodeOnFailure(() => cli.cmdLogin(['https://manager.example.com', 'tok_xyz']))
expect(code).toBe(1)
expect(stderr.join('')).toContain('token store error: token file ')
expect(stderr.join('')).toContain('unsupported format version 2')
restore()
})
const expectLoginUsageError = async (args: string[]) => {
const { cli, stderr, setToken, restore } = await loadCli()
async function expectLoginUsageError(args: string[]): Promise<void> {
const { cli, stderr, storedToken, restore } = await loadCli()
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => {
throw new Error('exit')
})
await expect(cli.cmdLogin(args)).rejects.toThrow('exit')
expect(stderr.join('')).toContain('usage: ocm login <url> [token] [--name <name>]')
expect(exitSpy).toHaveBeenCalledWith(1)
expect(setToken).not.toHaveBeenCalled()
expect(await storedToken()).toBeNull()
restore()
}
@@ -191,46 +201,63 @@ describe('cli auth commands', () => {
it('ocm login accepts the token before or after --name', async () => {
const afterName = await loadCli()
await afterName.cli.cmdLogin(['https://manager.example.com', 'tok_xyz', '--name', 'prod'])
expect(afterName.setToken).toHaveBeenCalledWith('https://manager.example.com', 'tok_xyz')
expect(await afterName.storedToken()).toBe('tok_xyz')
afterName.restore()
const beforeName = await loadCli()
await beforeName.cli.cmdLogin(['https://manager.example.com', '--name', 'prod', 'tok_xyz'])
expect(beforeName.setToken).toHaveBeenCalledWith('https://manager.example.com', 'tok_xyz')
expect(await beforeName.storedToken()).toBe('tok_xyz')
beforeName.restore()
})
it('ocm logout reports removal', async () => {
const { cli, written, restore } = await loadCli({ deleteTokenImpl: () => Promise.resolve(true) })
const { cli, written, restore } = await loadCli({ token: 'tok' })
await cli.cmdLogout()
expect(written.join('')).toContain('Removed stored token for')
restore()
})
it('ocm logout reports nothing stored', async () => {
const { cli, written, restore } = await loadCli({ deleteTokenImpl: () => Promise.resolve(false) })
const { cli, written, restore } = await loadCli({ token: null })
await cli.cmdLogout()
expect(written.join('')).toContain('No stored token found.')
restore()
})
it('ocm logout clears state even when the store delete fails', async () => {
const { cli, written, stderr, clearState, restore } = await loadCli({
deleteTokenImpl: () => Promise.reject(new MockTokenStoreError('keychain locked', 'keychain')),
})
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => { throw new Error('exit') })
await expect(cli.cmdLogout()).rejects.toThrow('exit')
expect(clearState).toHaveBeenCalledOnce()
const { cli, written, stderr, home, restore } = await loadCli({ documentVersion: 2 })
const code = await exitCodeOnFailure(() => cli.cmdLogout())
expect(code).toBe(1)
expect(written.join('')).toContain('State cleared.')
expect(stderr.join('')).toContain('token store error: keychain locked')
expect(exitSpy).toHaveBeenCalledWith(1)
expect(stderr.join('')).toContain('token store error: token file ')
expect(stderr.join('')).toContain('unsupported format version 2')
vi.resetModules()
const { readState } = await import('../src/state.js')
expect(readState()).toBeNull()
expect(readFileSync(home.statePath, 'utf-8')).toBe('{}')
restore()
})
it('ocm logout warns that OCM_TOKEN still authenticates', async () => {
const { cli, written, restore } = await loadCli({ env: 'tok_env' })
const { cli, written, restore } = await loadCli({ token: 'tok', envToken: 'tok_env' })
await cli.cmdLogout()
expect(written.join('')).toContain('note: OCM_TOKEN is set and takes precedence over the stored token')
restore()
})
})
describe('cli home fixture', () => {
it('writes state and credentials under the temporary home', async () => {
const home = createCliHome({ state: { managerUrl: MANAGER, lastRepoId: 7 }, token: 'tok' })
homes.push(home)
mkdirSync(dirname(home.statePath), { recursive: true })
writeFileSync(home.credentialsPath, JSON.stringify({ version: 1, tokens: { [MANAGER]: 'tok_from_disk' } }))
vi.resetModules()
const { readState } = await import('../src/state.js')
expect(readState()?.lastRepoId).toBe(7)
expect(await createFileTokenStore(home.credentialsPath).get(MANAGER)).toBe('tok_from_disk')
})
})
+69
View File
@@ -0,0 +1,69 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { OcmState } from '../../src/state.js'
export interface CliHomeOptions {
state?: OcmState | null
account?: string
token?: string | null
documentVersion?: number
envToken?: string | null
}
export interface CliHome {
home: string
configDir: string
statePath: string
credentialsPath: string
account: string
writeState: (state: OcmState | null) => void
writeToken: (token: string | null) => void
restore: () => void
}
const DEFAULT_ACCOUNT = 'https://manager.example.com'
export function createCliHome(options: CliHomeOptions = {}): CliHome {
const savedHome = process.env.HOME
const savedToken = process.env.OCM_TOKEN
const home = mkdtempSync(join(tmpdir(), 'ocm-home-'))
process.env.HOME = home
if (options.envToken) process.env.OCM_TOKEN = options.envToken
else delete process.env.OCM_TOKEN
const configDir = join(home, '.config', 'opencode-manager')
mkdirSync(configDir, { recursive: true })
const statePath = join(configDir, 'state.json')
const credentialsPath = join(configDir, 'credentials.json')
const account = options.account ?? DEFAULT_ACCOUNT
function writeState(state: OcmState | null): void {
writeFileSync(statePath, state === null ? '{}' : JSON.stringify(state))
}
function writeToken(token: string | null): void {
const document = { version: options.documentVersion ?? 1, tokens: token === null ? {} : { [account]: token } }
writeFileSync(credentialsPath, JSON.stringify(document))
}
writeState(options.state === undefined ? { managerUrl: account } : options.state)
writeToken(options.token ?? null)
return {
home,
configDir,
statePath,
credentialsPath,
account,
writeState,
writeToken,
restore: () => {
if (savedHome === undefined) delete process.env.HOME
else process.env.HOME = savedHome
if (savedToken === undefined) delete process.env.OCM_TOKEN
else process.env.OCM_TOKEN = savedToken
rmSync(home, { recursive: true, force: true })
},
}
}
-69
View File
@@ -1,69 +0,0 @@
import { vi } from 'vitest'
import type { OcmState } from '../../src/state.js'
import type { TokenStoreDescription } from '../../src/token-store.js'
export class MockTokenStoreError extends Error {
constructor(message: string, public kind = 'file') {
super(message)
this.name = 'TokenStoreError'
}
}
const DEFAULT_STORE: TokenStoreDescription = { kind: 'file', location: '/tmp/credentials.json' }
export interface TokenStoreMockOptions {
token?: string | null
getTokenImpl?: (account: string) => Promise<string | null>
setTokenImpl?: (account: string, token: string) => Promise<void>
deleteTokenImpl?: (account: string) => Promise<boolean>
store?: TokenStoreDescription
writeTarget?: TokenStoreDescription
env?: string | null
}
export function mockStateModule(state: OcmState | null = { managerUrl: 'https://manager.example.com' }) {
const clearState = vi.fn()
vi.doMock('../../src/state.js', () => ({
readState: () => state,
writeState: () => {},
clearState,
getStatePath: () => '/tmp/state.json',
getConfigDir: () => '/tmp',
}))
return { clearState }
}
export function mockTokenStoreModule(options: TokenStoreMockOptions = {}) {
const envValue = options.env ?? null
const getToken = vi.fn<(account: string) => Promise<string | null>>(
options.getTokenImpl ?? (() => Promise.resolve(options.token ?? null)),
)
const setToken = vi.fn<(account: string, token: string) => Promise<void>>(
options.setTokenImpl ?? (() => Promise.resolve()),
)
const deleteToken = vi.fn<(account: string) => Promise<boolean>>(
options.deleteTokenImpl ?? (() => Promise.resolve(true)),
)
const store = options.store ?? DEFAULT_STORE
vi.doMock('../../src/internal-token-store.js', () => ({
TOKEN_ENV: 'OCM_TOKEN',
envToken: () => envValue,
getToken,
setToken,
deleteToken,
hasStoredToken: async (account: string | undefined) => {
if (envValue) return true
if (!account) return false
return (await getToken(account)) !== null
},
describeTokenStore: () => (envValue ? { kind: 'env', location: 'OCM_TOKEN' } : store),
describeTokenWriteTarget: () => options.writeTarget ?? store,
TokenStoreError: MockTokenStoreError,
}))
return { getToken, setToken, deleteToken }
}
export function unmockTokenStoreModules() {
vi.doUnmock('../../src/state.js')
vi.doUnmock('../../src/internal-token-store.js')
}
+45 -52
View File
@@ -13,13 +13,15 @@ import {
} from '../src/internal-token-store.js'
import type { TokenStore } from '../src/token-store.js'
const TOKEN_ENV_NAME = TOKEN_ENV
interface StoreCalls {
get: string[]
set: Array<{ account: string; token: string }>
delete: string[]
}
function makeInMemoryStore(seed: Record<string, string> = {}): TokenStore & {
calls: { get: string[]; set: Array<{ account: string; token: string }>; delete: string[] }
} {
function makeInMemoryStore(seed: Record<string, string> = {}): TokenStore & { calls: StoreCalls } {
const tokens = { ...seed }
const calls = { get: [] as string[], set: [] as Array<{ account: string; token: string }>, delete: [] as string[] }
const calls: StoreCalls = { get: [], set: [], delete: [] }
return {
describe: () => ({ kind: 'file', location: '<in-memory>' }),
async get(account: string) {
@@ -50,28 +52,24 @@ function makeFailingStore(err: TokenStoreError): TokenStore {
}
describe('internal token store facade', () => {
const savedToken = process.env[TOKEN_ENV_NAME]
const savedToken = process.env[TOKEN_ENV]
beforeEach(() => {
delete process.env[TOKEN_ENV_NAME]
delete process.env[TOKEN_ENV]
})
afterEach(() => {
if (savedToken === undefined) delete process.env[TOKEN_ENV_NAME]
else process.env[TOKEN_ENV_NAME] = savedToken
if (savedToken === undefined) delete process.env[TOKEN_ENV]
else process.env[TOKEN_ENV] = savedToken
})
describe('selectTokenStore', () => {
it('uses the keychain store on darwin', () => {
expect(selectTokenStore('darwin').describe().kind).toBe('keychain')
})
it('uses the file store on linux', () => {
expect(selectTokenStore('linux').describe().kind).toBe('file')
})
it('uses the file store on win32', () => {
expect(selectTokenStore('win32').describe().kind).toBe('file')
it.each([
['darwin', 'keychain'],
['linux', 'file'],
['win32', 'file'],
] as const)('selects the %s store as %s', (platform, kind) => {
expect(selectTokenStore(platform).describe().kind).toBe(kind)
})
})
@@ -81,42 +79,38 @@ describe('internal token store facade', () => {
expect(store.calls.get).toEqual(['https://m'])
})
it('OCM_TOKEN wins over the store', async () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
const store = makeInMemoryStore({ 'https://m': 'tok_stored' })
await expect(getToken('https://m', store)).resolves.toBe('tok_env')
expect(store.calls.get).toEqual([])
})
it('OCM_TOKEN wins over the store whether or not it holds a token', async () => {
process.env[TOKEN_ENV] = 'tok_env'
const populated = makeInMemoryStore({ 'https://m': 'tok_stored' })
await expect(getToken('https://m', populated)).resolves.toBe('tok_env')
expect(populated.calls.get).toEqual([])
it('OCM_TOKEN is used when the store is empty', async () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
const store = makeInMemoryStore()
await expect(getToken('https://m', store)).resolves.toBe('tok_env')
expect(store.calls.get).toEqual([])
const empty = makeInMemoryStore()
await expect(getToken('https://m', empty)).resolves.toBe('tok_env')
})
it('blank OCM_TOKEN falls through to the store', async () => {
process.env[TOKEN_ENV_NAME] = ' '
process.env[TOKEN_ENV] = ' '
const store = makeInMemoryStore({ 'https://m': 'tok_stored' })
await expect(getToken('https://m', store)).resolves.toBe('tok_stored')
expect(store.calls.get).toEqual(['https://m'])
})
it('envToken reports the trimmed override', () => {
process.env[TOKEN_ENV_NAME] = ' tok_env '
expect(envToken()).toBe('tok_env')
})
it('envToken reports null when the override is blank', () => {
process.env[TOKEN_ENV_NAME] = ' '
expect(envToken()).toBeNull()
it.each([
[' tok_env ', 'tok_env'],
[' ', null],
[undefined, null],
])('envToken reports %s as %s', (value, expected) => {
if (value === undefined) delete process.env[TOKEN_ENV]
else process.env[TOKEN_ENV] = value
expect(envToken()).toBe(expected)
})
it('setToken never writes the env', async () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
process.env[TOKEN_ENV] = 'tok_env'
const store = makeInMemoryStore()
await setToken('https://m', 'tok_new', store)
expect(process.env[TOKEN_ENV_NAME]).toBe('tok_env')
expect(process.env[TOKEN_ENV]).toBe('tok_env')
expect(store.calls.set).toEqual([{ account: 'https://m', token: 'tok_new' }])
})
@@ -146,7 +140,7 @@ describe('internal token store facade', () => {
})
it('hasStoredToken reports true from the env override without an account', async () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
process.env[TOKEN_ENV] = 'tok_env'
const store = makeInMemoryStore()
await expect(hasStoredToken(undefined, store)).resolves.toBe(true)
expect(store.calls.get).toEqual([])
@@ -164,15 +158,15 @@ describe('internal token store facade', () => {
})
it('hasStoredToken prefers the env override over a failing store', async () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
process.env[TOKEN_ENV] = 'tok_env'
const store = makeFailingStore(new TokenStoreError('keychain locked', 'keychain'))
await expect(hasStoredToken('https://m', store)).resolves.toBe(true)
})
it('describeTokenStore reports env when OCM_TOKEN is set', () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
process.env[TOKEN_ENV] = 'tok_env'
const store = makeInMemoryStore()
expect(describeTokenStore(store)).toEqual({ kind: 'env', location: TOKEN_ENV_NAME })
expect(describeTokenStore(store)).toEqual({ kind: 'env', location: TOKEN_ENV })
})
it('describeTokenStore reports the store when OCM_TOKEN is unset', () => {
@@ -180,13 +174,12 @@ describe('internal token store facade', () => {
expect(describeTokenStore(store)).toEqual({ kind: 'file', location: '<in-memory>' })
})
it('describeTokenWriteTarget reports the store even when OCM_TOKEN is set', () => {
process.env[TOKEN_ENV_NAME] = 'tok_env'
const store = makeInMemoryStore()
expect(describeTokenWriteTarget(store)).toEqual({ kind: 'file', location: '<in-memory>' })
})
it('describeTokenWriteTarget reports the store when OCM_TOKEN is unset', () => {
it.each([
['set', 'tok_env'],
['unset', undefined],
])('describeTokenWriteTarget reports the store when OCM_TOKEN is %s', (_label, envValue) => {
if (envValue === undefined) delete process.env[TOKEN_ENV]
else process.env[TOKEN_ENV] = envValue
const store = makeInMemoryStore()
expect(describeTokenWriteTarget(store)).toEqual({ kind: 'file', location: '<in-memory>' })
})
+51 -81
View File
@@ -2,7 +2,9 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
import { tmpdir, type NetworkInterfaceInfo } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, it, expect, vi } from 'vitest'
import { afterEach, describe, it, expect } from 'vitest'
import { z } from 'zod'
import { parseJsonText, type JsonObject, type JsonValue } from '@opencode-manager/shared/utils'
import {
buildOpenCodeBasicAuth,
createOpenCodePairingNonce,
@@ -21,6 +23,8 @@ import type { PairingServerOptions } from '../src/link'
import { buildOpenCodeServerLink, parseOpenCodeServerLink } from '@opencode-manager/shared/schemas'
const CODE = 'test-pairing-code-0123456789abcdef'
const PairingPayloadSchema = z.object({ iv: z.string(), ciphertext: z.string() })
const CREDENTIALS = { username: 'opencode', password: 'secret-password' }
const LAN_INTERFACES: NodeJS.Dict<NetworkInterfaceInfo[]> = {
@@ -70,34 +74,30 @@ function discover(paths: ServiceHome, interfaces: NodeJS.Dict<NetworkInterfaceIn
})
}
async function discoverOnPlatform(
function discoverOnPlatform(
platform: NodeJS.Platform,
paths: ServiceHome,
interfaces: NodeJS.Dict<NetworkInterfaceInfo[]> = LAN_INTERFACES,
) {
const originalPlatform = process.platform
Object.defineProperty(process, 'platform', { value: platform })
try {
vi.resetModules()
const { discoverOpenCodeService: discoverService } = await import('../src/link')
return discoverService({
env: { XDG_STATE_HOME: paths.state, XDG_CONFIG_HOME: paths.config },
home: paths.home,
interfaces,
})
} finally {
Object.defineProperty(process, 'platform', { value: originalPlatform })
}
return discoverOpenCodeService({
env: { XDG_STATE_HOME: paths.state, XDG_CONFIG_HOME: paths.config },
home: paths.home,
interfaces,
platform,
})
}
function writeRegistration(paths: ServiceHome, content: unknown): void {
const file = join(paths.state, 'opencode', 'service.json')
writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content))
function writeServiceFile(file: string, content: JsonValue): void {
const raw = z.string().safeParse(content)
writeFileSync(file, raw.success ? raw.data : JSON.stringify(content))
}
function writeServiceConfig(paths: ServiceHome, content: unknown): void {
const file = join(paths.config, 'opencode', 'service.json')
writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content))
function writeRegistration(paths: ServiceHome, content: JsonValue): void {
writeServiceFile(join(paths.state, 'opencode', 'service.json'), content)
}
function writeServiceConfig(paths: ServiceHome, content: JsonValue): void {
writeServiceFile(join(paths.config, 'opencode', 'service.json'), content)
}
function startPairing(overrides: Partial<PairingServerOptions> = {}) {
@@ -112,7 +112,7 @@ function startPairing(overrides: Partial<PairingServerOptions> = {}) {
})
}
function redeem(url: string, body: unknown, init: RequestInit = {}): Promise<Response> {
function redeem(url: string, body: JsonObject, init: RequestInit = {}): Promise<Response> {
return fetch(url, { method: 'POST', body: JSON.stringify(body), ...init })
}
@@ -139,7 +139,8 @@ async function startProbeServer(
server.listen(0, '127.0.0.1', resolve)
})
const address = server.address()
const port = typeof address === 'object' && address !== null ? address.port : 0
const bound = z.object({ port: z.number() }).safeParse(address)
const port = bound.success ? bound.data.port : 0
const handle: ProbeServer = {
baseUrl: `http://127.0.0.1:${port}`,
requests,
@@ -312,23 +313,19 @@ describe('discoverOpenCodeService', () => {
})
})
it('uses the platform default service port when the config omits one', async () => {
const cases: Array<{ platform: NodeJS.Platform; port: number }> = [
{ platform: 'linux', port: 49374 },
{ platform: 'win32', port: 45278 },
]
it.each([
['linux', 49374],
['win32', 45278],
] as const)('uses the %s default service port when the config omits one', (platform, port) => {
const paths = createServiceHome()
writeServiceConfig(paths, { password: 'config-secret' })
for (const { platform, port } of cases) {
const paths = createServiceHome()
writeServiceConfig(paths, { password: 'config-secret' })
expect(await discoverOnPlatform(platform, paths), platform).toEqual({
baseUrl: `http://127.0.0.1:${port}`,
password: 'config-secret',
source: 'config',
loopbackOnly: true,
})
}
expect(discoverOnPlatform(platform, paths)).toEqual({
baseUrl: `http://127.0.0.1:${port}`,
password: 'config-secret',
source: 'config',
loopbackOnly: true,
})
})
})
@@ -351,10 +348,14 @@ describe('probeOpenCodeServer', () => {
])
})
it('reports unauthorized when the server rejects the credentials', async () => {
it.each([
['a JSON error body', 'application/json', JSON.stringify({ _tag: 'UnauthorizedError', message: 'unauthorized' })],
['an empty body', 'text/plain', ''],
['a plain text body', 'text/plain', 'unauthorized'],
])('reports unauthorized when the server rejects the credentials with %s', async (_label, contentType, body) => {
const server = await startProbeServer((_request, response) => {
response.writeHead(401, { 'content-type': 'application/json' })
response.end(JSON.stringify({ _tag: 'UnauthorizedError', message: 'unauthorized' }))
response.writeHead(401, { 'content-type': contentType })
response.end(body)
})
await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
@@ -362,44 +363,13 @@ describe('probeOpenCodeServer', () => {
})
})
it('reports unauthorized when the server rejects the credentials with an empty body', async () => {
it.each([
['a JSON body', 'application/json', JSON.stringify({ error: 'boom' })],
['a plain text body', 'text/plain', 'boom'],
])('reports unreachable with the HTTP status for an unexpected %s', async (_label, contentType, body) => {
const server = await startProbeServer((_request, response) => {
response.writeHead(401, { 'content-type': 'text/plain' })
response.end()
})
await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
status: 'unauthorized',
})
})
it('reports unauthorized when the server rejects the credentials with a plain text body', async () => {
const server = await startProbeServer((_request, response) => {
response.writeHead(401, { 'content-type': 'text/plain' })
response.end('unauthorized')
})
await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
status: 'unauthorized',
})
})
it('reports unreachable with the HTTP status for an unexpected response', async () => {
const server = await startProbeServer((_request, response) => {
response.writeHead(500, { 'content-type': 'application/json' })
response.end(JSON.stringify({ error: 'boom' }))
})
await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
status: 'unreachable',
message: 'HTTP 500',
})
})
it('reports unreachable with the HTTP status for an unexpected plain text response', async () => {
const server = await startProbeServer((_request, response) => {
response.writeHead(500, { 'content-type': 'text/plain' })
response.end('boom')
response.writeHead(500, { 'content-type': contentType })
response.end(body)
})
await expect(probeOpenCodeServer(server.baseUrl, CREDENTIALS, 1000)).resolves.toEqual({
@@ -432,7 +402,7 @@ describe('startPairingServer', () => {
expect(raw).not.toContain(CREDENTIALS.password)
expect(raw).not.toContain(CODE)
const payload = JSON.parse(raw) as { iv: string; ciphertext: string }
const payload = PairingPayloadSchema.parse(parseJsonText(raw))
await expect(decryptOpenCodePairingCredentials({
code: CODE,
nonce: challenge.nonce,
@@ -523,7 +493,7 @@ describe('startPairingServer', () => {
const pairing = await startPairing()
const challenge = await createChallenge()
const payload = await redeem(pairing.url, challenge).then((response) => response.json()) as { iv: string; ciphertext: string }
const payload = PairingPayloadSchema.parse(await redeem(pairing.url, challenge).then((response) => response.json()))
await expect(decryptOpenCodePairingCredentials({
code: `${CODE}-other`,
+105 -73
View File
@@ -1,9 +1,12 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { JsonObjectSchema, type JsonValue } from '@opencode-manager/shared/utils'
import { ManagerApi, ManagerApiError, isManagerRouteMissing, MANAGER_FEATURE_MISSING } from '../src/manager-api.js'
import type { MultiRun } from '@opencode-manager/shared/schemas'
const BASE_URL = 'http://localhost:5003'
type FetchImplementation = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
const run: MultiRun = {
id: 3,
repoId: 1,
@@ -18,20 +21,35 @@ const run: MultiRun = {
fusions: [],
}
function okResponse(body: unknown) {
return { ok: true, status: 200, json: () => Promise.resolve(body), text: () => Promise.resolve('') }
function okResponse(body: JsonValue): Response {
return Response.json(body)
}
function errorResponse(status: number, text: string) {
return { ok: false, status, json: () => Promise.reject(new Error('no json')), text: () => Promise.resolve(text) }
function errorResponse(status: number, text: string): Response {
return new Response(text, { status })
}
function stubFetch(response: unknown) {
const fetchMock = vi.fn().mockResolvedValue(response)
function stubFetch(respond: FetchImplementation) {
const fetchMock = vi.fn<FetchImplementation>(respond)
vi.stubGlobal('fetch', fetchMock)
return fetchMock
}
function stubSingleResponse(response: Response) {
return stubFetch(async () => response)
}
async function expectApiError(request: Promise<unknown>): Promise<ManagerApiError> {
const failure = await request.then(() => null, (cause) => cause)
expect(failure).toBeInstanceOf(ManagerApiError)
if (!(failure instanceof ManagerApiError)) throw new Error('expected a ManagerApiError')
return failure
}
function errorBody(code: string | null, text: string): JsonValue {
return code === null ? { error: text } : { error: text, code }
}
afterEach(() => {
vi.unstubAllGlobals()
})
@@ -40,7 +58,7 @@ describe('ManagerApi multi-runs', () => {
const api = new ManagerApi(BASE_URL, 'tok')
it('lists runs for a repo', async () => {
const fetchMock = stubFetch(okResponse({ runs: [run] }))
const fetchMock = stubSingleResponse(okResponse({ runs: [run] }))
await expect(api.listMultiRuns(1)).resolves.toEqual([run])
expect(fetchMock).toHaveBeenCalledWith(`${BASE_URL}/api/internal/multi-runs?repoId=1`, {
@@ -49,7 +67,7 @@ describe('ManagerApi multi-runs', () => {
})
it('launches a run', async () => {
const fetchMock = stubFetch(okResponse({ run }))
const fetchMock = stubSingleResponse(okResponse({ run }))
const request = { repoId: 1, name: 'sweep', prompt: 'hello', models: ['a/b'], isolate: true }
await expect(api.launchMultiRun(request)).resolves.toEqual(run)
@@ -61,7 +79,7 @@ describe('ManagerApi multi-runs', () => {
})
it('fuses selected entries', async () => {
const fetchMock = stubFetch(okResponse({ run }))
const fetchMock = stubSingleResponse(okResponse({ run }))
const request = { requestId: '11111111-1111-4111-8111-111111111111', entryIds: [1, 2], model: 'a/b' }
await expect(api.fuseMultiRun(3, request)).resolves.toEqual(run)
@@ -73,7 +91,7 @@ describe('ManagerApi multi-runs', () => {
})
it('discards an entry', async () => {
const fetchMock = stubFetch(okResponse({ run }))
const fetchMock = stubSingleResponse(okResponse({ run }))
await expect(api.discardMultiRunEntry(3, 4)).resolves.toEqual(run)
expect(fetchMock).toHaveBeenCalledWith(`${BASE_URL}/api/internal/multi-runs/3/entries/4/discard`, {
@@ -85,44 +103,44 @@ describe('ManagerApi multi-runs', () => {
describe('ManagerApiError', () => {
const api = new ManagerApi(BASE_URL, 'tok')
const fusion = { requestId: '11111111-1111-4111-8111-111111111111', entryIds: [1, 2], model: 'a/b' }
it('reads the machine code from the JSON code field, not the human error text', async () => {
const details = { unavailableSources: [{ entryId: 1, model: 'a/b', reason: 'running', message: 'still running' }] }
stubFetch(errorResponse(409, JSON.stringify({ error: 'Fusion unavailable', code: 'FUSION_UNAVAILABLE', details })))
stubSingleResponse(errorResponse(409, JSON.stringify({ error: 'Fusion unavailable', code: 'FUSION_UNAVAILABLE', details })))
const error = await api.fuseMultiRun(3, { requestId: '11111111-1111-4111-8111-111111111111', entryIds: [1, 2], model: 'a/b' }).catch((err) => err)
const error = await expectApiError(api.fuseMultiRun(3, fusion))
expect(error).toBeInstanceOf(ManagerApiError)
expect((error as ManagerApiError).status).toBe(409)
expect((error as ManagerApiError).code).toBe('FUSION_UNAVAILABLE')
expect((error as ManagerApiError).message).toContain('Fusion unavailable')
expect((error as ManagerApiError).details).toEqual(details)
expect((error as ManagerApiError).jsonBody).toBe(true)
expect(error.status).toBe(409)
expect(error.code).toBe('FUSION_UNAVAILABLE')
expect(error.message).toContain('Fusion unavailable')
expect(error.details).toEqual(details)
expect(error.jsonBody).toBe(true)
})
it('leaves the code null when the body only carries human error text', async () => {
stubFetch(errorResponse(409, JSON.stringify({ error: 'Fusion unavailable' })))
stubSingleResponse(errorResponse(409, JSON.stringify(errorBody(null, 'Fusion unavailable'))))
const error = await api.fuseMultiRun(3, { requestId: '11111111-1111-4111-8111-111111111111', entryIds: [1, 2], model: 'a/b' }).catch((err) => err)
const error = await expectApiError(api.fuseMultiRun(3, fusion))
expect((error as ManagerApiError).code).toBeNull()
expect(error.code).toBeNull()
})
it('leaves details null when the error body has none', async () => {
stubFetch(errorResponse(400, JSON.stringify({ error: 'Invalid request' })))
stubSingleResponse(errorResponse(400, JSON.stringify(errorBody(null, 'Invalid request'))))
const error = await api.listMultiRuns(1).catch((err) => err)
const error = await expectApiError(api.listMultiRuns(1))
expect((error as ManagerApiError).details).toBeNull()
expect(error.details).toBeNull()
})
it('marks a plain-text error body as non-JSON', async () => {
stubFetch(errorResponse(500, 'boom'))
stubSingleResponse(errorResponse(500, 'boom'))
const error = await api.listMultiRuns(1).catch((err) => err)
const error = await expectApiError(api.listMultiRuns(1))
expect((error as ManagerApiError).jsonBody).toBe(false)
expect((error as ManagerApiError).code).toBeNull()
expect(error.jsonBody).toBe(false)
expect(error.code).toBeNull()
})
})
@@ -130,16 +148,16 @@ describe('ManagerApi feature support', () => {
const api = new ManagerApi(BASE_URL, 'tok')
it('maps a 401 to MANAGER_FEATURE_MISSING when the token probe succeeds', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(errorResponse(401, JSON.stringify({ error: 'Unauthorized' })))
.mockResolvedValueOnce(okResponse({ workspaces: [] }))
vi.stubGlobal('fetch', fetchMock)
const fetchMock = stubFetch(async (input) =>
String(input).endsWith('/api/internal/opencode-workspaces')
? okResponse({ workspaces: [] })
: errorResponse(401, JSON.stringify(errorBody(null, 'Unauthorized'))),
)
const error = await api.listMultiRuns(1).catch((err) => err)
const error = await expectApiError(api.listMultiRuns(1))
expect(error).toBeInstanceOf(ManagerApiError)
expect((error as ManagerApiError).status).toBe(401)
expect((error as ManagerApiError).code).toBe(MANAGER_FEATURE_MISSING)
expect(error.status).toBe(401)
expect(error.code).toBe(MANAGER_FEATURE_MISSING)
expect(isManagerRouteMissing(error)).toBe(true)
expect(fetchMock).toHaveBeenNthCalledWith(2, `${BASE_URL}/api/internal/opencode-workspaces`, {
headers: { Authorization: 'Bearer tok' },
@@ -147,31 +165,27 @@ describe('ManagerApi feature support', () => {
})
it('keeps the plain 401 when the token probe is also rejected', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(errorResponse(401, JSON.stringify({ error: 'Unauthorized' })))
.mockResolvedValueOnce(errorResponse(401, JSON.stringify({ error: 'Unauthorized' })))
vi.stubGlobal('fetch', fetchMock)
stubFetch(async () => errorResponse(401, JSON.stringify(errorBody(null, 'Unauthorized'))))
const error = await api.listMultiRuns(1).catch((err) => err)
const error = await expectApiError(api.listMultiRuns(1))
expect(error).toBeInstanceOf(ManagerApiError)
expect((error as ManagerApiError).status).toBe(401)
expect((error as ManagerApiError).code).toBeNull()
expect(error.status).toBe(401)
expect(error.code).toBeNull()
expect(isManagerRouteMissing(error)).toBe(false)
})
it('keeps the plain 401 when the token probe throws', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(errorResponse(401, JSON.stringify({ error: 'Unauthorized' })))
.mockRejectedValueOnce(new Error('network down'))
vi.stubGlobal('fetch', fetchMock)
const fetchMock = stubFetch(async (input) => {
if (String(input).endsWith('/api/internal/opencode-workspaces')) throw new Error('network down')
return errorResponse(401, JSON.stringify(errorBody(null, 'Unauthorized')))
})
const error = await api.listMultiRuns(1).catch((err) => err)
const error = await expectApiError(api.listMultiRuns(1))
expect(error).toBeInstanceOf(ManagerApiError)
expect((error as ManagerApiError).status).toBe(401)
expect((error as ManagerApiError).code).toBeNull()
expect(error.status).toBe(401)
expect(error.code).toBeNull()
expect(isManagerRouteMissing(error)).toBe(false)
expect(fetchMock).toHaveBeenCalledTimes(2)
})
})
@@ -179,16 +193,16 @@ describe('ManagerApi mirror routes', () => {
const api = new ManagerApi(BASE_URL, 'tok')
it('maps a 401 from mirrorCheckouts to MANAGER_FEATURE_MISSING with the move message', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(errorResponse(401, JSON.stringify({ error: 'Unauthorized' })))
.mockResolvedValueOnce(okResponse({ workspaces: [] }))
vi.stubGlobal('fetch', fetchMock)
const fetchMock = stubFetch(async (input) =>
String(input).endsWith('/api/internal/opencode-workspaces')
? okResponse({ workspaces: [] })
: errorResponse(401, JSON.stringify(errorBody(null, 'Unauthorized'))),
)
const error = await api.mirrorCheckouts(1, 'feature').catch((err) => err)
const error = await expectApiError(api.mirrorCheckouts(1, 'feature'))
expect(error).toBeInstanceOf(ManagerApiError)
expect((error as ManagerApiError).code).toBe(MANAGER_FEATURE_MISSING)
expect((error as ManagerApiError).message).toContain('too old for /ocm-move worktrees')
expect(error.code).toBe(MANAGER_FEATURE_MISSING)
expect(error.message).toContain('too old for /ocm-move worktrees')
expect(isManagerRouteMissing(error)).toBe(true)
expect(fetchMock).toHaveBeenNthCalledWith(2, `${BASE_URL}/api/internal/opencode-workspaces`, {
headers: { Authorization: 'Bearer tok' },
@@ -196,20 +210,22 @@ describe('ManagerApi mirror routes', () => {
})
it('keeps the multi-run feature message unchanged', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(errorResponse(401, JSON.stringify({ error: 'Unauthorized' })))
.mockResolvedValueOnce(okResponse({ workspaces: [] }))
vi.stubGlobal('fetch', fetchMock)
stubFetch(async (input) =>
String(input).endsWith('/api/internal/opencode-workspaces')
? okResponse({ workspaces: [] })
: errorResponse(401, JSON.stringify(errorBody(null, 'Unauthorized'))),
)
const error = await api.listMultiRuns(1).catch((err) => err)
const error = await expectApiError(api.listMultiRuns(1))
expect((error as ManagerApiError).code).toBe(MANAGER_FEATURE_MISSING)
expect((error as ManagerApiError).message).toContain('too old for ocm multi-runs')
expect(error.code).toBe(MANAGER_FEATURE_MISSING)
expect(error.message).toContain('too old for ocm multi-runs')
})
it('sends the directory query on mirrorHead and mirrorContains', async () => {
const fetchMock = vi.fn().mockResolvedValue(okResponse({}))
vi.stubGlobal('fetch', fetchMock)
const fetchMock = stubFetch(async () =>
okResponse({ repoId: 1, branch: null, head: null, dirty: false, contained: false }),
)
await api.mirrorHead(1, '/repos/work trees/repo')
await api.mirrorContains(1, 'abc1234', '/repos/work trees/repo')
@@ -217,23 +233,39 @@ describe('ManagerApi mirror routes', () => {
expect(new URL(String(fetchMock.mock.calls[0]![0])).searchParams.get('directory')).toBe('/repos/work trees/repo')
expect(new URL(String(fetchMock.mock.calls[1]![0])).searchParams.get('directory')).toBe('/repos/work trees/repo')
})
it('parses a checkouts response of typed checkout states', async () => {
const checkouts = {
main: { directory: '/repos/repo', branch: 'main', head: 'abc', dirty: false },
worktrees: [{ directory: '/repos/repo-feature', branch: 'feature', head: 'def', dirty: false }],
branchHead: 'def',
branchCheckedOut: true,
suffixedWorktreeBranch: 'feature-ocm',
}
stubSingleResponse(okResponse(checkouts))
const parsed = await api.mirrorCheckouts(1, 'feature')
expect(parsed).toEqual(checkouts)
expect(JsonObjectSchema.safeParse(checkouts).success).toBe(true)
})
})
describe('isManagerRouteMissing', () => {
const api = new ManagerApi(BASE_URL, 'tok')
it('is true for a 404 with a non-JSON body', async () => {
stubFetch(errorResponse(404, '404 Not Found'))
stubSingleResponse(errorResponse(404, '404 Not Found'))
const error = await api.listMultiRuns(1).catch((err) => err)
const error = await expectApiError(api.listMultiRuns(1))
expect(isManagerRouteMissing(error)).toBe(true)
})
it('is false for a 404 with a JSON error body', async () => {
stubFetch(errorResponse(404, JSON.stringify({ error: 'Multi-run not found' })))
stubSingleResponse(errorResponse(404, JSON.stringify(errorBody(null, 'Multi-run not found'))))
const error = await api.listMultiRuns(1).catch((err) => err)
const error = await expectApiError(api.listMultiRuns(1))
expect(isManagerRouteMissing(error)).toBe(false)
})
+55 -53
View File
@@ -1,97 +1,96 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { resolveManagerAuth, resolveManagerApi } from '../src/manager-auth.js'
import { describe, it, expect, vi } from 'vitest'
import { managerAuthDeps, resolveManagerAuth, resolveManagerApi } from '../src/manager-auth.js'
import type { ManagerAuthDeps } from '../src/manager-auth.js'
import { ManagerApi } from '../src/manager-api.js'
import { TokenStoreError } from '../src/token-store.js'
import type { TokenStoreDescription } from '../src/token-store.js'
const mocks = vi.hoisted(() => ({
readState: vi.fn(),
getToken: vi.fn(),
describeTokenStore: vi.fn(),
}))
const STORE: TokenStoreDescription = { kind: 'file', location: '/tmp/credentials.json' }
const STORE_LABEL = 'file: /tmp/credentials.json'
vi.mock('../src/state.js', () => ({ readState: mocks.readState }))
vi.mock('../src/internal-token-store.js', () => ({
getToken: mocks.getToken,
describeTokenStore: mocks.describeTokenStore,
}))
const STORE = { kind: 'file', location: '/tmp/credentials.json' }
beforeEach(() => {
vi.resetAllMocks()
mocks.describeTokenStore.mockReturnValue(STORE)
})
function authDeps(overrides: Partial<ManagerAuthDeps> = {}): ManagerAuthDeps {
return {
readState: () => ({ managerUrl: 'https://mgr.example' }),
getToken: async () => 'tok',
describeTokenStore: () => STORE,
...overrides,
}
}
describe('resolveManagerAuth', () => {
it('reports no manager when no state is stored', async () => {
mocks.readState.mockReturnValue(null)
const getToken = vi.fn<ManagerAuthDeps['getToken']>()
const deps = authDeps({ readState: () => null, getToken })
await expect(resolveManagerAuth()).resolves.toEqual({
await expect(resolveManagerAuth(undefined, deps)).resolves.toEqual({
ok: false,
reason: 'no-manager',
message: 'No manager configured. Run `ocm login <url>` first.',
})
expect(mocks.getToken).not.toHaveBeenCalled()
expect(getToken).not.toHaveBeenCalled()
})
it('does not read state when given an explicit manager URL', async () => {
mocks.readState.mockReturnValue(null)
mocks.getToken.mockResolvedValue('tok')
const deps = authDeps({
readState: () => {
throw new Error('state must not be read when a URL is given')
},
})
await expect(resolveManagerAuth('https://mgr.example')).resolves.toEqual({
await expect(resolveManagerAuth('https://mgr.example', deps)).resolves.toEqual({
ok: true,
managerUrl: 'https://mgr.example',
token: 'tok',
})
expect(mocks.readState).not.toHaveBeenCalled()
expect(mocks.getToken).toHaveBeenCalledWith('https://mgr.example')
})
it('looks up the token under the normalized manager URL', async () => {
mocks.getToken.mockResolvedValue('tok')
const getToken = vi.fn<ManagerAuthDeps['getToken']>(async () => 'tok')
await expect(resolveManagerAuth(' https://mgr.example// ')).resolves.toEqual({
await expect(resolveManagerAuth(' https://mgr.example// ', authDeps({ getToken }))).resolves.toEqual({
ok: true,
managerUrl: 'https://mgr.example',
token: 'tok',
})
expect(mocks.getToken).toHaveBeenCalledWith('https://mgr.example')
expect(getToken).toHaveBeenCalledWith('https://mgr.example')
})
it('reports a token store failure with the store kind and location', async () => {
mocks.readState.mockReturnValue({ managerUrl: 'https://mgr.example' })
mocks.getToken.mockRejectedValue(new TokenStoreError('keychain locked', 'keychain'))
const deps = authDeps({
getToken: async () => {
throw new TokenStoreError('keychain locked', 'keychain')
},
})
await expect(resolveManagerAuth()).resolves.toEqual({
await expect(resolveManagerAuth(undefined, deps)).resolves.toEqual({
ok: false,
reason: 'token-store',
message: 'token store error (file: /tmp/credentials.json): keychain locked. Run `ocm login https://mgr.example` after fixing the store.',
message: `token store error (${STORE_LABEL}): keychain locked. Run \`ocm login https://mgr.example\` after fixing the store.`,
})
})
it('rethrows a non token-store error', async () => {
mocks.readState.mockReturnValue({ managerUrl: 'https://mgr.example' })
mocks.getToken.mockRejectedValue(new Error('boom'))
const deps = authDeps({
getToken: async () => {
throw new Error('boom')
},
})
await expect(resolveManagerAuth()).rejects.toThrow('boom')
await expect(resolveManagerAuth(undefined, deps)).rejects.toThrow('boom')
})
it('reports a missing token with the store kind and location', async () => {
mocks.readState.mockReturnValue({ managerUrl: 'https://mgr.example' })
mocks.getToken.mockResolvedValue(null)
const deps = authDeps({ getToken: async () => null })
await expect(resolveManagerAuth()).resolves.toEqual({
await expect(resolveManagerAuth(undefined, deps)).resolves.toEqual({
ok: false,
reason: 'no-token',
message: 'no token stored for https://mgr.example (file: /tmp/credentials.json). Run `ocm login https://mgr.example`.',
message: `no token stored for https://mgr.example (${STORE_LABEL}). Run \`ocm login https://mgr.example\`.`,
})
})
it('resolves the manager URL and token', async () => {
mocks.readState.mockReturnValue({ managerUrl: 'https://mgr.example' })
mocks.getToken.mockResolvedValue('tok')
await expect(resolveManagerAuth()).resolves.toEqual({
it('resolves the manager URL from state and the token from the store', async () => {
await expect(resolveManagerAuth(undefined, authDeps())).resolves.toEqual({
ok: true,
managerUrl: 'https://mgr.example',
token: 'tok',
@@ -101,10 +100,7 @@ describe('resolveManagerAuth', () => {
describe('resolveManagerApi', () => {
it('builds an api from the resolved auth', async () => {
mocks.readState.mockReturnValue({ managerUrl: 'https://mgr.example' })
mocks.getToken.mockResolvedValue('tok')
const result = await resolveManagerApi()
const result = await resolveManagerApi(undefined, authDeps())
expect(result.ok).toBe(true)
if (!result.ok) return
@@ -113,11 +109,17 @@ describe('resolveManagerApi', () => {
})
it('reports the auth failure message without building an api', async () => {
mocks.readState.mockReturnValue(null)
await expect(resolveManagerApi()).resolves.toEqual({
await expect(resolveManagerApi(undefined, authDeps({ readState: () => null }))).resolves.toEqual({
ok: false,
message: 'No manager configured. Run `ocm login <url>` first.',
})
})
})
describe('managerAuthDeps', () => {
it('defaults to the real state and token store lookups', () => {
expect(managerAuthDeps.readState).toBeTypeOf('function')
expect(managerAuthDeps.getToken).toBeTypeOf('function')
expect(managerAuthDeps.describeTokenStore).toBeTypeOf('function')
})
})
File diff suppressed because it is too large. Load diff
+10 -25
View File
@@ -1,37 +1,26 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { compareSemver, parseSemver } from '@opencode-manager/shared/utils'
import { compareSemver, parseSemver, parseJsonText } from '@opencode-manager/shared/utils'
import { describe, expect, it } from 'vitest'
import { z } from 'zod'
interface PackageManifest {
version: string
devDependencies: Record<string, string>
peerDependencies: Record<string, string>
peerDependenciesMeta: Record<string, { optional?: boolean }>
}
const PackageManifestSchema = z.object({
version: z.string(),
devDependencies: z.record(z.string(), z.string()).default({}),
peerDependencies: z.record(z.string(), z.string()).default({}),
peerDependenciesMeta: z.record(z.string(), z.object({ optional: z.boolean().optional() })).default({}),
})
const PINNED_PACKAGES = ['@opentui/core', '@opentui/solid', '@opencode/theme'] as const
/**
* Reads and parses a package manifest from an absolute path.
*/
function readManifest(path: string): PackageManifest {
return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
function readManifest(path: string): z.infer<typeof PackageManifestSchema> {
return PackageManifestSchema.parse(parseJsonText(readFileSync(path, 'utf8')))
}
/**
* Reads the version of a dependency installed in ocm-cli's node_modules.
*/
function installedVersion(name: string): string {
return readManifest(join(__dirname, '..', 'node_modules', name, 'package.json')).version
}
/**
* Derives the minor-line peer range for an exact dependency version.
*
* A `0.x.y` version is constrained to its minor line; a version at major `1` or above
* is constrained to its major line.
*/
function deriveMinorLineRange(version: string): string {
const parsed = parseSemver(version)
if (!parsed || parsed.prerelease.length > 0) {
@@ -44,10 +33,6 @@ function deriveMinorLineRange(version: string): string {
return `>=${version} <${major + 1}.0.0`
}
/**
* Asserts that an installed version satisfies a plugin peer declaration: an exact
* pin, or space-separated `>=`, `<=` and `<` bounds such as `>=0.8.0 <0.9.0`.
*/
function expectVersionSatisfiesPeer(version: string, peer: string): void {
const comparators = peer.trim().split(/\s+/)
if (!comparators.every((comparator) => comparator.startsWith('>=') || comparator.startsWith('<'))) {
+14 -35
View File
@@ -3,34 +3,24 @@ import { formatBytes, createProgressReporter } from '../src/progress'
import type { ProgressSink } from '../src/progress'
describe('formatBytes', () => {
it('returns "0 B" for 0', () => {
expect(formatBytes(0)).toBe('0 B')
})
it('formats values below 1024 as whole bytes', () => {
expect(formatBytes(1)).toBe('1 B')
expect(formatBytes(500)).toBe('500 B')
expect(formatBytes(1023)).toBe('1023 B')
})
it('formats values at 1024 as KB with one decimal', () => {
expect(formatBytes(1024)).toBe('1.0 KB')
expect(formatBytes(1536)).toBe('1.5 KB')
})
it('formats values at 1 MB as MB with one decimal', () => {
expect(formatBytes(1_048_576)).toBe('1.0 MB')
expect(formatBytes(13_000_000)).toBe('12.4 MB')
})
it('formats values at 1 GB as GB with one decimal', () => {
expect(formatBytes(1_073_741_824)).toBe('1.0 GB')
expect(formatBytes(1_500_000_000)).toBe('1.4 GB')
it.each([
[0, '0 B'],
[1, '1 B'],
[500, '500 B'],
[1023, '1023 B'],
[1024, '1.0 KB'],
[1536, '1.5 KB'],
[1_048_576, '1.0 MB'],
[13_000_000, '12.4 MB'],
[1_073_741_824, '1.0 GB'],
[1_500_000_000, '1.4 GB'],
])('formats %d bytes as %s', (bytes, expected) => {
expect(formatBytes(bytes)).toBe(expected)
})
})
describe('createProgressReporter', () => {
function createSink(isTTY: boolean): { sink: ProgressSink; writes: string[] } {
function createSink(isTTY: boolean) {
const writes: string[] = []
const sink: ProgressSink = {
write(chunk: string) {
@@ -48,19 +38,15 @@ describe('createProgressReporter', () => {
const { sink, writes } = createSink(true)
const reporter = createProgressReporter('Test', sink, now)
// First tick at t=100000
reporter.tick(500)
expect(writes).toHaveLength(1)
expect(writes[0]).toMatch(/^\r\x1b\[K/)
// First frame is '⠋'
expect(writes[0]).toContain('⠋')
expect(writes[0]).toContain('500 B')
// Advance time past throttle window
fakeTime += 100
reporter.tick(1024)
expect(writes).toHaveLength(2)
// Second frame is '⠙'
expect(writes[1]).toContain('⠙')
expect(writes[1]).toContain('1.0 KB')
})
@@ -89,21 +75,16 @@ describe('createProgressReporter', () => {
const { sink, writes } = createSink(true)
const reporter = createProgressReporter('Test', sink, now)
// Render 12 ticks, each 100ms apart (past the 80ms throttle)
for (let i = 0; i < 12; i++) {
reporter.tick(i * 100)
fakeTime += 100
}
expect(writes).toHaveLength(12)
// No write should contain "undefined"
for (const w of writes) {
expect(w).not.toContain('undefined')
}
// After 10 frames, the 11th write cycles back to the first frame '⠋'
// writes[10] is the 11th rendered tick → frameIndex = (0 + 10) % 10 = 0 → '⠋'
expect(writes[10]).toContain('⠋')
// writes[11] is the 12th rendered tick → frameIndex = (0 + 11) % 10 = 1 → '⠙'
expect(writes[11]).toContain('⠙')
})
})
@@ -119,12 +100,10 @@ describe('createProgressReporter', () => {
expect(writes).toHaveLength(1)
expect(writes[0]).toBe('Test: 500 B\n')
// Too soon
fakeTime += 500
reporter.tick(1024)
expect(writes).toHaveLength(1)
// After 1000ms total
fakeTime += 500
reporter.tick(2048)
expect(writes).toHaveLength(2)
+35 -24
View File
@@ -1,4 +1,6 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { z } from 'zod'
import { JsonObjectSchema, parseJsonText, type JsonValue } from '@opencode-manager/shared/utils'
import { createManagerSessionTransfer } from '../src/remote-session.js'
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
@@ -6,19 +8,37 @@ afterEach(() => {
vi.unstubAllGlobals()
})
const transferData = {
info: { id: 'ses_a' },
messages: [{ id: 'msg_1' }],
} as unknown as SessionTransferData
const transferData: SessionTransferData = {
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: [{ id: 'msg_1', time: { created: 1 }, type: 'user', text: 'hello' }],
}
const ImportRequestBodySchema = z.object({
location: z.object({ directory: z.string() }),
info: JsonObjectSchema,
messages: z.array(JsonObjectSchema),
})
const ReminderRequestBodySchema = z.object({ text: z.string(), resume: z.boolean() })
function jsonResponse(status: number, body: JsonValue): Response {
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
}
async function requestedJson<Value>(init: RequestInit | undefined, schema: z.ZodType<Value>): Promise<Value> {
return schema.parse(parseJsonText(String(init?.body)))
}
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' },
}),
)
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { data: { id: 'ses_new' } }))
vi.stubGlobal('fetch', fetchMock)
const transfer = createManagerSessionTransfer('https://manager.example', 'tok_123')
@@ -28,22 +48,17 @@ describe('createManagerSessionTransfer', () => {
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(init?.method).toBe('POST')
const headers = new Headers(init?.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>
const body = await requestedJson(init, ImportRequestBodySchema)
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' },
}),
)
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { data: {} }))
vi.stubGlobal('fetch', fetchMock)
const transfer = createManagerSessionTransfer('https://manager.example', 'tok_123')
@@ -51,15 +66,11 @@ describe('createManagerSessionTransfer', () => {
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>
const body = await requestedJson(init, ReminderRequestBodySchema)
expect(body.text).toBe('hello')
expect(body.resume).toBe(false)
})
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
}
it('reports an existing Manager session', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { data: { id: 'ses_a' } }))
vi.stubGlobal('fetch', fetchMock)
+21 -13
View File
@@ -27,6 +27,13 @@ function fetchReturning(...responses: Array<Response | Error>) {
const noWait = vi.fn(async () => undefined)
async function expectProbeFailure(probe: Promise<unknown>): Promise<Error> {
const failure = await probe.then(() => null, (cause) => cause)
expect(failure).toBeInstanceOf(Error)
if (!(failure instanceof Error)) throw new Error('expected warmRepoProxy to fail with an Error')
return failure
}
describe('repoProxyUrl', () => {
it('builds the repo-scoped proxy url', () => {
expect(repoProxyUrl(managerUrl, 42)).toBe('https://manager.example.com/api/opencode-proxy/repos/42')
@@ -58,10 +65,10 @@ describe('warmRepoProxy', () => {
it('fails with an upgrade message when the Manager has no repo proxy route', async () => {
const fetchMock = fetchReturning(new Response('Not Found', { status: 404 }))
const error = await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait }).catch((err: unknown) => err)
const error = await expectProbeFailure(warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait }))
expect(error).toBeInstanceOf(ManagerTooOldError)
expect((error as Error).message).toBe(
expect(error.message).toBe(
`OpenCode Manager at ${managerUrl} is too old for ocm ${packageJson.version}; upgrade the Manager to >= ${MIN_MANAGER_VERSION}`,
)
expect(MIN_MANAGER_VERSION).toBe('0.19.0')
@@ -78,10 +85,10 @@ describe('warmRepoProxy', () => {
const fetchMock = fetchReturning(new Error('ECONNRESET'), new Response('', { status: 502 }), new Response('', { status: 503 }))
const wait = vi.fn(async () => undefined)
const error = await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait }).catch((err: unknown) => err)
const error = await expectProbeFailure(warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait }))
expect(error).toBeInstanceOf(RepoProxyResponseError)
expect((error as Error).message).toContain('HTTP 503')
expect(error.message).toContain('HTTP 503')
expect(fetchMock).toHaveBeenCalledTimes(3)
expect(wait.mock.calls).toEqual([[500], [1000]])
})
@@ -89,21 +96,21 @@ describe('warmRepoProxy', () => {
it('reports the status and body of a non-OK response', async () => {
const fetchMock = fetchReturning(new Response('proxy exploded', { status: 500 }))
const error = await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait, attempts: 1 }).catch((err: unknown) => err)
const error = await expectProbeFailure(warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait, attempts: 1 }))
expect(error).toBeInstanceOf(RepoProxyResponseError)
expect((error as Error).message).toContain('HTTP 500')
expect((error as Error).message).toContain('proxy exploded')
expect(error.message).toContain('HTTP 500')
expect(error.message).toContain('proxy exploded')
})
it('reports an invalid manager token on 401 without retrying', async () => {
const fetchMock = fetchReturning(new Response('Unauthorized', { status: 401 }))
const error = await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait }).catch((err: unknown) => err)
const error = await expectProbeFailure(warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait }))
expect(error).toBeInstanceOf(ManagerTokenInvalidError)
expect((error as Error).message).toContain('Settings -> Manager Internal Token')
expect((error as Error).message).toContain(`ocm login ${managerUrl}`)
expect(error.message).toContain('Settings -> Manager Internal Token')
expect(error.message).toContain(`ocm login ${managerUrl}`)
expect(fetchMock).toHaveBeenCalledTimes(1)
})
@@ -111,11 +118,12 @@ describe('warmRepoProxy', () => {
const cause = new Error('connect ECONNREFUSED')
const fetchMock = fetchReturning(cause, cause, cause)
const error = await warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait }).catch((err: unknown) => err)
const error = await expectProbeFailure(warmRepoProxy(managerUrl, 'tok', 42, { fetch: fetchMock, wait: noWait }))
expect(error).toBeInstanceOf(RepoProxyUnreachableError)
expect((error as Error).message).toContain('connect ECONNREFUSED')
expect((error as Error).cause).toBe(cause)
if (!(error instanceof RepoProxyUnreachableError)) throw new Error('expected a RepoProxyUnreachableError')
expect(error.message).toContain('connect ECONNREFUSED')
expect(error.cause).toBe(cause)
expect(fetchMock).toHaveBeenCalledTimes(3)
})
+44 -44
View File
@@ -15,7 +15,7 @@ function makeTransfer(messages: SessionMessageInfo[] = [], directory = '/Users/x
location: { directory },
},
messages,
} as unknown as SessionTransferData
}
}
function userWithFile(uri: string): SessionMessageInfo {
@@ -25,7 +25,7 @@ function userWithFile(uri: string): SessionMessageInfo {
type: 'user',
text: 'hi',
files: [{ data: '', mime: 'image/png', source: { type: 'uri', uri } }],
} as unknown as SessionMessageInfo
}
}
function assistantWithToolFile(uri: string): SessionMessageInfo {
@@ -44,7 +44,24 @@ function assistantWithToolFile(uri: string): SessionMessageInfo {
time: { created: 2 },
},
],
} as unknown as SessionMessageInfo
}
}
function userFileUri(transfer: SessionTransferData, index = 0): string | null {
const message = transfer.messages[index]
if (message?.type !== 'user') return null
const source = message.files?.[0]?.source
return source?.type === 'uri' ? source.uri : null
}
function assistantFileUri(transfer: SessionTransferData, index = 0): string | null {
const message = transfer.messages[index]
if (message?.type !== 'assistant') return null
const part = message.content[0]
if (part?.type !== 'tool') return null
if (part.state.status !== 'completed') return null
const file = part.state.content[0]
return file.type === 'file' ? file.uri : null
}
describe('rewriteTransferForRemote', () => {
@@ -63,59 +80,51 @@ describe('rewriteTransferForRemote', () => {
it('rewrites a user file attachment uri under the local root', () => {
const result = rewriteTransferForRemote(makeTransfer([userWithFile('/Users/x/repo/src/img.png')]), ctx)
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')
expect(userFileUri(result)).toBe('/workspace/repos/repo/src/img.png')
})
it('rewrites an assistant tool file uri under the local root', () => {
const result = rewriteTransferForRemote(makeTransfer([assistantWithToolFile('/Users/x/repo/out.png')]), ctx)
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')
expect(assistantFileUri(result)).toBe('/workspace/repos/repo/out.png')
})
it('leaves uris outside the local root untouched', () => {
const result = rewriteTransferForRemote(makeTransfer([userWithFile('/elsewhere/img.png')]), ctx)
const files = (result.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
expect(files[0]!.source.uri).toBe('/elsewhere/img.png')
expect(userFileUri(result)).toBe('/elsewhere/img.png')
})
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 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')
expect(userFileUri(result)).toBe('file:///workspace/repos/repo/a%20b.png')
})
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 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')
expect(assistantFileUri(result)).toBe('file:///workspace/repos/repo/out.png')
})
it('preserves file:// query and hash when relocating', () => {
const result = rewriteTransferForRemote(makeTransfer([userWithFile('file:///Users/x/repo/a.png?v=1#frag')]), ctx)
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')
expect(userFileUri(result)).toBe('file:///workspace/repos/repo/a.png?v=1#frag')
})
it('leaves a file:// uri outside the local root untouched', () => {
const uri = 'file:///elsewhere/img.png'
const result = rewriteTransferForRemote(makeTransfer([userWithFile(uri)]), ctx)
const files = (result.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
expect(files[0]!.source.uri).toBe(uri)
expect(userFileUri(result)).toBe(uri)
})
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 files = (result.messages[0] as unknown as { files: { source: { uri: string } }[] }).files
expect(files[0]!.source.uri).toBe(uri)
expect(userFileUri(result)).toBe(uri)
})
it('leaves data uris and external http urls untouched', () => {
@@ -123,23 +132,15 @@ describe('rewriteTransferForRemote', () => {
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)
expect(userFileUri(result, 0)).toBe(dataUri)
expect(userFileUri(result, 1)).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')])
it.each([
['file://', 'file:///Users/x/repo/a%20b.png'],
['path', '/Users/x/repo/src/img.png'],
])('does not mutate a %s input transfer', (_label, uri) => {
const input = makeTransfer([userWithFile(uri)])
const frozen = structuredClone(input)
rewriteTransferForRemote(input, ctx)
@@ -157,8 +158,8 @@ describe('transferSession', () => {
const progress: [number, number][] = []
const deps: TransferDeps = {
exportSession: vi.fn().mockResolvedValue(data),
importSession: vi.fn().mockImplementation(async (directory: string, transferred: SessionTransferData) => {
exportSession: vi.fn<TransferDeps['exportSession']>().mockResolvedValue(data),
importSession: vi.fn<TransferDeps['importSession']>().mockImplementation(async (directory, transferred) => {
importCalls.push({ directory, data: transferred })
return { sessionID: 'ses_a' }
}),
@@ -172,15 +173,14 @@ describe('transferSession', () => {
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(userFileUri(importCalls[0]!.data)).toBe('/workspace/repos/repo/src/img.png')
expect(progress).toEqual([[0, 1], [1, 1]])
})
it('returns the imported session id rather than the local one', async () => {
const deps: TransferDeps = {
exportSession: vi.fn().mockResolvedValue(makeTransfer()),
importSession: vi.fn().mockResolvedValue({ sessionID: 'ses_remote' }),
exportSession: vi.fn<TransferDeps['exportSession']>().mockResolvedValue(makeTransfer()),
importSession: vi.fn<TransferDeps['importSession']>().mockResolvedValue({ sessionID: 'ses_remote' }),
}
const result = await transferSession(input, deps)
@@ -190,8 +190,8 @@ describe('transferSession', () => {
it('reports an export failure without importing', async () => {
const deps: TransferDeps = {
exportSession: vi.fn().mockRejectedValue(new Error('export failed')),
importSession: vi.fn(),
exportSession: vi.fn<TransferDeps['exportSession']>().mockRejectedValue(new Error('export failed')),
importSession: vi.fn<TransferDeps['importSession']>(),
}
const result = await transferSession(input, deps)
@@ -202,8 +202,8 @@ describe('transferSession', () => {
it('reports an import failure', async () => {
const deps: TransferDeps = {
exportSession: vi.fn().mockResolvedValue(makeTransfer()),
importSession: vi.fn().mockRejectedValue(new Error('import diverged')),
exportSession: vi.fn<TransferDeps['exportSession']>().mockResolvedValue(makeTransfer()),
importSession: vi.fn<TransferDeps['importSession']>().mockRejectedValue(new Error('import diverged')),
}
const result = await transferSession(input, deps)
+29 -33
View File
@@ -2,6 +2,8 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { z } from 'zod'
import { JsonObjectSchema, parseJsonText } from '@opencode-manager/shared/utils'
import { createFileTokenStore } from '../src/token-store-file.js'
import { TokenStoreError } from '../src/token-store.js'
@@ -17,13 +19,17 @@ afterEach(() => {
rmSync(dir, { recursive: true, force: true })
})
async function expectFileStoreError(run: () => Promise<unknown>, messagePart?: string) {
const err = await run().then(() => null, (caught: unknown) => caught)
expect(err).toBeInstanceOf(TokenStoreError)
const storeError = err as TokenStoreError
expect(storeError.kind).toBe('file')
if (messagePart) expect(storeError.message).toContain(messagePart)
return storeError
async function expectFileStoreError(run: Promise<unknown>, messagePart?: string): Promise<TokenStoreError> {
const failure = await run.then(() => null, (cause) => cause)
expect(failure).toBeInstanceOf(TokenStoreError)
if (!(failure instanceof TokenStoreError)) throw new Error('expected a TokenStoreError from the file token store')
expect(failure.kind).toBe('file')
if (messagePart) expect(failure.message).toContain(messagePart)
return failure
}
function readWrittenDocument(): z.infer<typeof JsonObjectSchema> {
return JsonObjectSchema.parse(parseJsonText(readFileSync(file, 'utf-8')))
}
describe('file token store', () => {
@@ -175,7 +181,7 @@ describe('file token store', () => {
writeFileSync(file, JSON.stringify({ version: 2, tokens: { 'https://a': 'tok_a' } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expectFileStoreError(() => store.get('https://a'), 'unsupported format version 2')
await expectFileStoreError(store.get('https://a'), 'unsupported format version 2')
})
it('refuses to overwrite a document written by an unsupported future version', async () => {
@@ -183,7 +189,7 @@ describe('file token store', () => {
writeFileSync(file, future, { mode: 0o600 })
const store = createFileTokenStore(file)
await expectFileStoreError(() => store.set('https://b', 'tok_b'), 'unsupported format version 2')
await expectFileStoreError(store.set('https://b', 'tok_b'), 'unsupported format version 2')
expect(readFileSync(file, 'utf-8')).toBe(future)
})
@@ -191,7 +197,7 @@ describe('file token store', () => {
writeFileSync(file, JSON.stringify({ version: 2, tokens: { 'https://a': 'tok_a' } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expectFileStoreError(() => store.delete('https://a'), 'unsupported format version 2')
await expectFileStoreError(store.delete('https://a'), 'unsupported format version 2')
})
it('treats a versionless document as the current version', async () => {
@@ -207,7 +213,7 @@ describe('file token store', () => {
await store.set('https://a', 'tok_a')
const written = JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown>
const written = readWrittenDocument()
expect(written.futureField).toEqual({ keep: true })
expect(written.version).toBe(1)
})
@@ -215,13 +221,13 @@ describe('file token store', () => {
it('wraps read failures from set as a file TokenStoreError', async () => {
const store = createFileTokenStore(dir)
await expectFileStoreError(() => store.set('https://a', 'tok_a'))
await expectFileStoreError(store.set('https://a', 'tok_a'))
})
it('wraps read failures from delete as a file TokenStoreError', async () => {
const store = createFileTokenStore(dir)
await expectFileStoreError(() => store.delete('https://a'))
await expectFileStoreError(store.delete('https://a'))
})
it('throws a TokenStoreError naming the file and cause when the file is unreadable', async () => {
@@ -229,7 +235,7 @@ describe('file token store', () => {
writeFileSync(file, '{}', { mode: 0o000 })
const store = createFileTokenStore(file)
const err = await expectFileStoreError(() => store.get('https://a'), 'failed to read token file')
const err = await expectFileStoreError(store.get('https://a'), 'failed to read token file')
expect(err.message).toContain(file)
})
@@ -238,25 +244,15 @@ describe('file token store', () => {
writeFileSync(file, '{"version":1,"tokens":{"https://a":"tok_a"}}', { mode: 0o000 })
const store = createFileTokenStore(file)
await expectFileStoreError(() => store.get('https://a'))
await expectFileStoreError(store.get('https://a'))
})
it('treats an object-valued token as missing without throwing', async () => {
writeFileSync(file, JSON.stringify({ version: 1, tokens: { 'https://m': {} } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expect(store.get('https://m')).resolves.toBeNull()
})
it('treats a number-valued token as missing without throwing', async () => {
writeFileSync(file, JSON.stringify({ version: 1, tokens: { 'https://m': 42 } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expect(store.get('https://m')).resolves.toBeNull()
})
it('treats a boolean-valued token as missing without throwing', async () => {
writeFileSync(file, JSON.stringify({ version: 1, tokens: { 'https://m': true } }), { mode: 0o600 })
it.each([
['object', {}],
['number', 42],
['boolean', true],
])('treats a %s-valued token as missing without throwing', async (_label, value) => {
writeFileSync(file, JSON.stringify({ version: 1, tokens: { 'https://m': value } }), { mode: 0o600 })
const store = createFileTokenStore(file)
await expect(store.get('https://m')).resolves.toBeNull()
@@ -285,7 +281,7 @@ describe('file token store', () => {
await store.set('https://m', 'tok_real')
await expect(store.get('https://m')).resolves.toBe('tok_real')
const written = JSON.parse(readFileSync(file, 'utf-8')) as { tokens: Record<string, unknown> }
expect(typeof written.tokens['https://m']).toBe('string')
const written = z.object({ tokens: z.record(z.string(), z.string()) }).parse(parseJsonText(readFileSync(file, 'utf-8')))
expect(written.tokens['https://m']).toBe('tok_real')
})
})
+69 -77
View File
@@ -1,6 +1,7 @@
import { afterEach, describe, it, expect, vi } from 'vitest'
import { createKeychainTokenStore, formatSecurityCommand, KEYCHAIN_SERVICE } from '../src/token-store-keychain.js'
import type { SecurityResult } from '../src/token-store-keychain.js'
import { describe, it, expect, vi } from 'vitest'
import { createKeychainTokenStore, createSecurityRunner, formatSecurityCommand, KEYCHAIN_SERVICE } from '../src/token-store-keychain.js'
import type { SecurityExec, SecurityResult, SecurityRunner } from '../src/token-store-keychain.js'
import type { TokenStore } from '../src/token-store.js'
import { TokenStoreError } from '../src/token-store.js'
const ok = (stdout = ''): SecurityResult => ({ stdout, stderr: '', code: 0 })
@@ -11,38 +12,34 @@ const unavailable = () => Promise.reject(
const ACCOUNT = 'https://manager.example.com'
async function expectStoreError(run: () => Promise<unknown>, expected: { message: string | RegExp }) {
const err = await run().then(() => null, (caught: unknown) => caught)
expect(err).toBeInstanceOf(TokenStoreError)
const storeError = err as TokenStoreError
expect(storeError.kind).toBe('keychain')
if (typeof expected.message === 'string') expect(storeError.message).toContain(expected.message)
else expect(storeError.message).toMatch(expected.message)
return storeError
async function expectStoreError(run: Promise<unknown>, expected: { message: string | RegExp }): Promise<TokenStoreError> {
const failure = await run.then(() => null, (cause) => cause)
expect(failure).toBeInstanceOf(TokenStoreError)
if (!(failure instanceof TokenStoreError)) throw new Error('expected a TokenStoreError from the keychain store')
expect(failure.kind).toBe('keychain')
if (expected.message instanceof RegExp) expect(failure.message).toMatch(expected.message)
else expect(failure.message).toContain(expected.message)
return failure
}
function storeOf(run: SecurityRunner): TokenStore {
return createKeychainTokenStore(run)
}
describe('keychain token store', () => {
it('rejects with a diagnostic TokenStoreError when the security binary is missing on get', async () => {
const store = createKeychainTokenStore(unavailable)
it.each([
['get', (store: TokenStore) => store.get(ACCOUNT)],
['set', (store: TokenStore) => store.set(ACCOUNT, 'tok')],
['delete', (store: TokenStore) => store.delete(ACCOUNT)],
] as const)('rejects with a diagnostic TokenStoreError when the security binary is missing on %s', async (_label, action) => {
const store = storeOf(unavailable)
await expectStoreError(() => store.get(ACCOUNT), { message: /security/ })
})
it('rejects with a diagnostic TokenStoreError when the security binary is missing on set', async () => {
const store = createKeychainTokenStore(unavailable)
await expectStoreError(() => store.set(ACCOUNT, 'tok'), { message: /security/ })
})
it('rejects with a diagnostic TokenStoreError when the security binary is missing on delete', async () => {
const store = createKeychainTokenStore(unavailable)
await expectStoreError(() => store.delete(ACCOUNT), { message: /security/ })
await expectStoreError(action(store), { message: /security/ })
})
it('invokes security with the exact add-generic-password argv including -U upsert', async () => {
const run = vi.fn().mockResolvedValue(ok())
const store = createKeychainTokenStore(run)
const run = vi.fn<SecurityRunner>().mockResolvedValue(ok())
const store = storeOf(run)
await store.set('https://m', 'tok')
@@ -53,38 +50,30 @@ describe('keychain token store', () => {
})
it('rejects with a TokenStoreError containing stderr when set exits non-zero', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(1, 'boom')))
const store = storeOf(() => Promise.resolve(failed(1, 'boom')))
await expectStoreError(() => store.set(ACCOUNT, 'tok'), { message: 'boom' })
await expectStoreError(store.set(ACCOUNT, 'tok'), { message: 'boom' })
})
it('falls back to exit status in the set error when stderr is empty', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(1)))
it.each([
['set', (store: TokenStore) => store.set(ACCOUNT, 'tok'), 1],
['get', (store: TokenStore) => store.get(ACCOUNT), 36],
['delete', (store: TokenStore) => store.delete(ACCOUNT), 1],
] as const)('falls back to exit status in the %s error when stderr is empty', async (_label, action, code) => {
const store = storeOf(() => Promise.resolve(failed(code)))
await expectStoreError(() => store.set(ACCOUNT, 'tok'), { message: 'exit status 1' })
})
it('falls back to exit status in the get error when stderr is empty', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(36)))
await expectStoreError(() => store.get(ACCOUNT), { message: 'exit status 36' })
})
it('falls back to exit status in the delete error when stderr is empty', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(1)))
await expectStoreError(() => store.delete(ACCOUNT), { message: 'exit status 1' })
await expectStoreError(action(store), { message: `exit status ${code}` })
})
it('reports process termination when there is no stderr and no exit status', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(null)))
const store = storeOf(() => Promise.resolve(failed(null)))
await expectStoreError(() => store.set(ACCOUNT, 'tok'), { message: 'terminated' })
await expectStoreError(store.set(ACCOUNT, 'tok'), { message: 'terminated' })
})
it('invokes security with the exact find-generic-password -w argv on get', async () => {
const run = vi.fn().mockResolvedValue(ok('tok_abc\n'))
const store = createKeychainTokenStore(run)
const run = vi.fn<SecurityRunner>().mockResolvedValue(ok('tok_abc\n'))
const store = storeOf(run)
await store.get('https://m')
@@ -95,26 +84,26 @@ describe('keychain token store', () => {
})
it('trims a trailing newline from get stdout', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(ok('tok_abc\n')))
const store = storeOf(() => Promise.resolve(ok('tok_abc\n')))
await expect(store.get(ACCOUNT)).resolves.toBe('tok_abc')
})
it('returns null for an item-not-found exit without throwing', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(44, 'could not be found')))
const store = storeOf(() => Promise.resolve(failed(44, 'could not be found')))
await expect(store.get(ACCOUNT)).resolves.toBeNull()
})
it('returns null when get stdout is empty after trimming', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(ok('\n')))
const store = storeOf(() => Promise.resolve(ok('\n')))
await expect(store.get(ACCOUNT)).resolves.toBeNull()
})
it('invokes security with the exact delete-generic-password argv and returns true on status 0', async () => {
const run = vi.fn().mockResolvedValue(ok())
const store = createKeychainTokenStore(run)
const run = vi.fn<SecurityRunner>().mockResolvedValue(ok())
const store = storeOf(run)
await expect(store.delete('https://m')).resolves.toBe(true)
expect(run).toHaveBeenCalledWith(
@@ -123,21 +112,21 @@ describe('keychain token store', () => {
})
it('returns false when delete exits with the item-not-found code', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(44, 'could not be found')))
const store = storeOf(() => Promise.resolve(failed(44, 'could not be found')))
await expect(store.delete(ACCOUNT)).resolves.toBe(false)
})
it('rejects with a TokenStoreError on a non-44 get failure', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(36, 'user interaction is not allowed')))
const store = storeOf(() => Promise.resolve(failed(36, 'user interaction is not allowed')))
await expectStoreError(() => store.get(ACCOUNT), { message: 'user interaction is not allowed' })
await expectStoreError(store.get(ACCOUNT), { message: 'user interaction is not allowed' })
})
it('rejects with a TokenStoreError on a non-44 delete failure', async () => {
const store = createKeychainTokenStore(() => Promise.resolve(failed(1, 'keychain locked')))
const store = storeOf(() => Promise.resolve(failed(1, 'keychain locked')))
await expectStoreError(() => store.delete(ACCOUNT), { message: 'keychain locked' })
await expectStoreError(store.delete(ACCOUNT), { message: 'keychain locked' })
})
it('quotes every security argument and escapes backslashes and quotes', () => {
@@ -152,8 +141,8 @@ describe('keychain token store', () => {
})
it('describes itself as a keychain store with the service name', () => {
const run = vi.fn()
const store = createKeychainTokenStore(run)
const run = vi.fn<SecurityRunner>()
const store = storeOf(run)
expect(store.describe()).toEqual({
kind: 'keychain',
@@ -163,29 +152,32 @@ describe('keychain token store', () => {
})
})
describe('keychain token store process arguments', () => {
afterEach(() => {
vi.doUnmock('child_process')
vi.resetModules()
})
describe('keychain security process', () => {
it('sends the token on stdin and never puts it in the security argv', async () => {
const end = vi.fn()
const execFile = vi.fn((_bin: string, _args: string[], _opts: unknown, cb: (err: null, stdout: string, stderr: string) => void) => {
cb(null, '', '')
const end = vi.fn<(command: string) => void>()
const exec = vi.fn<SecurityExec>((_bin, _args, _options, callback) => {
callback(null, '', '')
return { stdin: { on: vi.fn(), end } }
})
vi.doMock('child_process', () => ({ execFile }))
vi.resetModules()
const { createKeychainTokenStore: create } = await import('../src/token-store-keychain.js')
const run = createSecurityRunner(exec)
await create().set('https://m', 'sup3r-secret')
await run(['add-generic-password', '-s', KEYCHAIN_SERVICE, '-a', 'https://m', '-w', 'sup3r-secret', '-U'])
expect(execFile).toHaveBeenCalledOnce()
expect(execFile.mock.calls[0]![0]).toBe('/usr/bin/security')
expect(execFile.mock.calls[0]![1]).toEqual(['-i'])
expect(exec).toHaveBeenCalledOnce()
expect(exec.mock.calls[0]![0]).toBe('/usr/bin/security')
expect(exec.mock.calls[0]![1]).toEqual(['-i'])
expect(end).toHaveBeenCalledWith(
`"add-generic-password" "-s" "${KEYCHAIN_SERVICE}" "-a" "https://m" "-w" "sup3r-secret" "-U"\n`,
)
})
it('reports a failure to start the security process as a TokenStoreError', async () => {
const exec = vi.fn<SecurityExec>((_bin, _args, _options, callback) => {
callback({ message: 'spawn /usr/bin/security ENOENT' }, '', '')
return { stdin: { on: vi.fn(), end: vi.fn() } }
})
const run = createSecurityRunner(exec)
await expectStoreError(run(['find-generic-password', '-w']), { message: /could not be found|security/ })
})
})
+16 -31
View File
@@ -1,13 +1,12 @@
import { describe, it, expect, vi } from 'vitest'
import type { Context } from '@opencode/plugin/tui/context'
import { confirmDialog, selectDialog, slashArgument } from '../src/tui-dialogs.js'
import type { DialogHost } from '../src/tui-dialogs.js'
function createFakeContext() {
const confirm = vi.fn()
const confirm = vi.fn<Context['ui']['dialog']['confirm']>()
const select = vi.fn()
const context = {
ui: { dialog: { confirm, select } },
} as unknown as Context
const context: DialogHost = { ui: { dialog: { confirm, select } } }
return { context, confirm, select }
}
@@ -20,16 +19,12 @@ describe('confirmDialog', () => {
expect(confirm).toHaveBeenCalledWith({ title: 'Confirm', message: 'Continue?' })
})
it('resolves false when the dialog is dismissed', async () => {
it.each([
['the dialog is dismissed', undefined],
['the dialog explicitly cancels', false],
])('resolves false when %s', async (_label, answer) => {
const { context, confirm } = createFakeContext()
confirm.mockResolvedValue(undefined)
expect(await confirmDialog(context, { title: 'Confirm', message: 'Continue?' })).toBe(false)
})
it('resolves false when the dialog explicitly cancels', async () => {
const { context, confirm } = createFakeContext()
confirm.mockResolvedValue(false)
confirm.mockResolvedValue(answer)
expect(await confirmDialog(context, { title: 'Confirm', message: 'Continue?' })).toBe(false)
})
@@ -57,23 +52,13 @@ describe('selectDialog', () => {
})
describe('slashArgument', () => {
it('resolves an empty string for undefined input', () => {
expect(slashArgument(undefined, 'goal')).toBe('')
})
it('strips a leading slash token and trims the rest', () => {
expect(slashArgument('/goal fix it ', 'goal')).toBe('fix it')
})
it('returns the trimmed argument when no slash token is present', () => {
expect(slashArgument(' fix it ', 'goal')).toBe('fix it')
})
it('only strips a whole-token match', () => {
expect(slashArgument('/goalie x', 'goal')).toBe('/goalie x')
})
it('resolves an empty string when only the slash token is present', () => {
expect(slashArgument('/goal', 'goal')).toBe('')
it.each([
[undefined, 'goal', ''],
['/goal fix it ', 'goal', 'fix it'],
[' fix it ', 'goal', 'fix it'],
['/goalie x', 'goal', '/goalie x'],
['/goal', 'goal', ''],
])('turns %s into %s', (input, name, expected) => {
expect(slashArgument(input, name)).toBe(expected)
})
})
+234 -160
View File
@@ -1,7 +1,11 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi, afterEach } from 'vitest'
import type { Context } from '@opencode/plugin/tui/context'
import type { ModelInfo } from '@opencode-manager/shared/opencode'
type CatalogList<Name extends 'model' | 'provider'> = NonNullable<ReturnType<Context['data']['location'][Name]['list']>>
type ModelInfo = CatalogList<'model'>[number]
type ProviderInfo = CatalogList<'provider'>[number]
import type { MultiRun, MultiRunEntry, MultiRunFusion } from '@opencode-manager/shared/schemas'
import { JsonObjectSchema, parseJsonText, type JsonObject } from '@opencode-manager/shared/utils'
import { z } from 'zod'
import {
describeMultiRunError,
filterModelOptions,
@@ -16,16 +20,17 @@ import {
MULTI_RUN_ATTACH_REQUIRED,
MULTI_RUN_ROUTE_MISSING,
} from '../src/tui-multi-run.js'
import type { LaunchFormInput, MultiRunActions } from '../src/tui-multi-run.js'
import type {
LaunchFormInput,
MultiRunActions,
MultiRunLaunchDialogProps,
MultiRunsDialogProps,
} from '../src/tui-multi-run.js'
import { ManagerApiError } from '../src/manager-api.js'
import type { ManagerApi } from '../src/manager-api.js'
import { resolveManagerApi } from '../src/manager-auth.js'
import type { ManagerAuthDeps } from '../src/manager-auth.js'
import type { OcmTuiContext } from '../src/tui-context.js'
import type { RemoteContext } from '../src/remote-context.js'
vi.mock('../src/manager-auth.js', () => ({
resolveManagerApi: vi.fn(),
}))
const remote: RemoteContext = {
managerUrl: 'https://manager.example',
managerHost: 'manager.example',
@@ -33,27 +38,35 @@ const remote: RemoteContext = {
repoId: 1,
}
type FakeProvider = { id: string; name: string; activation: 'auto' | 'enabled' | 'disabled' }
const STORE_LABEL = 'file: /tmp/credentials.json'
function provider(overrides: Partial<FakeProvider> = {}): FakeProvider {
return { id: 'openai', name: 'OpenAI', activation: 'enabled', ...overrides }
interface FakeProvider {
id: string
name: string
activation: 'auto' | 'enabled' | 'disabled'
}
function provider(overrides: Partial<ProviderInfo> = {}) {
const fake: FakeProvider = { id: 'openai', name: 'OpenAI', activation: 'enabled' }
const resolved: ProviderInfo = { package: '@ai-sdk/openai', ...fake, ...overrides }
return resolved
}
function model(overrides: Partial<ModelInfo> = {}): ModelInfo {
return {
const base: ModelInfo = {
id: 'gpt-5',
modelID: 'gpt-5',
providerID: 'openai',
name: 'GPT-5',
capabilities: {} as ModelInfo['capabilities'],
capabilities: { tools: false, input: [], output: [] },
variants: [],
time: { released: 0 },
cost: [],
status: 'active',
enabled: true,
limit: { context: 0, output: 0 },
...overrides,
} as ModelInfo
}
return { ...base, ...overrides }
}
function entry(overrides: Partial<MultiRunEntry> = {}): MultiRunEntry {
@@ -75,6 +88,8 @@ function multiRun(overrides: Partial<MultiRun> = {}): MultiRun {
return {
id: 3,
repoId: 1,
serverId: 'local',
directory: null,
name: 'sweep',
prompt: 'hello',
isolated: true,
@@ -105,56 +120,118 @@ function fusion(overrides: Partial<MultiRunFusion> = {}): MultiRunFusion {
}
}
interface RecordedRequest {
method: string
url: string
authorization: string | null
body: JsonObject | null
}
type RouteHandler = (request: RecordedRequest) => Response
interface MultiRunRoutes {
list?: RouteHandler
launch?: RouteHandler
fuse?: RouteHandler
discard?: RouteHandler
}
function requestBody(init: RequestInit | undefined): JsonObject | null {
const text = z.string().safeParse(init?.body)
return text.success ? JsonObjectSchema.parse(parseJsonText(text.data)) : null
}
function fusionRequestId(request: RecordedRequest): string {
return z.string().parse(request.body?.requestId)
}
function fuseResponding(overrides: Partial<MultiRunFusion> = {}): RouteHandler {
return (request) => Response.json({ run: multiRun({ fusions: [fusion({ requestId: fusionRequestId(request), ...overrides })] }) })
}
function createManager(routes: MultiRunRoutes = {}) {
const requests: RecordedRequest[] = []
const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>(async (input, init) => {
const url = new URL(String(input))
const request: RecordedRequest = {
method: init?.method ?? 'GET',
url: `${url.pathname}${url.search}`,
authorization: new Headers(init?.headers).get('authorization'),
body: requestBody(init),
}
requests.push(request)
if (url.pathname.endsWith('/fusions')) return (routes.fuse ?? fuseResponding())(request)
if (url.pathname.endsWith('/discard')) return (routes.discard ?? (() => Response.json({ run: multiRun() })))(request)
if (url.pathname === '/api/internal/multi-runs') {
if (request.method === 'POST') return (routes.launch ?? (() => Response.json({ run: multiRun() })))(request)
return (routes.list ?? (() => Response.json({ runs: [] })))(request)
}
return new Response(`unexpected route ${request.url}`, { status: 500 })
})
vi.stubGlobal('fetch', fetchMock)
return {
requests,
fetchMock,
requestsTo: (pathSuffix: string) => requests.filter((request) => request.url.includes(pathSuffix)),
}
}
function createFakeContext() {
const toast = vi.fn()
const prompt = vi.fn()
const toast = vi.fn<Context['ui']['toast']['show']>()
const prompt = vi.fn<Context['ui']['dialog']['prompt']>()
const select = vi.fn()
const confirm = vi.fn()
const open = vi.fn()
const focus = vi.fn()
const enabled = vi.fn(() => true)
const navigate = vi.fn()
const sync = vi.fn(async () => undefined)
const list = vi.fn(() => [] as ModelInfo[])
const providerSync = vi.fn(async () => undefined)
const providerList = vi.fn(() => [] as FakeProvider[])
const context = {
const confirm = vi.fn<Context['ui']['dialog']['confirm']>()
const open = vi.fn<Context['ui']['tabs']['open']>(() => true)
const focus = vi.fn<Context['ui']['tabs']['focus']>(() => true)
const enabled = vi.fn<Context['ui']['tabs']['enabled']>(() => true)
const navigate = vi.fn<Context['ui']['router']['navigate']>()
const current = vi.fn<Context['ui']['router']['current']>(() => ({ type: 'session', sessionID: 'ses_a' }))
const sync = vi.fn<() => Promise<void>>(async () => undefined)
const list = vi.fn<() => ModelInfo[] | undefined>(() => [])
const providerSync = vi.fn<() => Promise<void>>(async () => undefined)
const providerList = vi.fn<() => ProviderInfo[] | undefined>(() => [])
const context: OcmTuiContext = {
ui: {
toast: { show: toast },
dialog: { prompt, select, confirm },
tabs: { enabled, open, focus },
router: { navigate, current: () => ({ type: 'session', sessionID: 'ses_a' }) },
router: { navigate, current },
slot: vi.fn(),
},
data: { location: { model: { sync, list }, provider: { sync: providerSync, list: providerList } } },
} as unknown as Context
data: {
session: { get: () => undefined },
location: {
model: { sync, list },
provider: { sync: providerSync, list: providerList },
},
},
keymap: { layer: vi.fn(), dispatch: vi.fn() },
client: { session: { export: vi.fn() } },
}
return { context, toast, prompt, select, confirm, open, focus, enabled, navigate, sync, list, providerSync, providerList }
}
function makeApi() {
function authDeps(getToken: () => Promise<string | null> = async () => 'tok'): ManagerAuthDeps {
return {
launchMultiRun: vi.fn(async () => multiRun()),
listMultiRuns: vi.fn(async () => [] as MultiRun[]),
fuseMultiRun: vi.fn(async () => multiRun()),
discardMultiRunEntry: vi.fn(async () => multiRun()),
readState: () => ({ managerUrl: remote.managerUrl }),
getToken,
describeTokenStore: () => ({ kind: 'file', location: '/tmp/credentials.json' }),
}
}
function mockResolvedApi(api: ReturnType<typeof makeApi>): void {
vi.mocked(resolveManagerApi).mockResolvedValue({
ok: true,
auth: { ok: true, managerUrl: remote.managerUrl, token: 'tok' },
api: api as unknown as ManagerApi,
})
}
function depsFor() {
return { remote, showLaunchDialog: vi.fn(), showRunsDialog: vi.fn() }
return {
remote,
showLaunchDialog: vi.fn<(props: MultiRunLaunchDialogProps) => void>(),
showRunsDialog: vi.fn<(props: MultiRunsDialogProps) => void>(),
auth: authDeps(),
}
}
async function launchActions(fake: ReturnType<typeof createFakeContext>, api: ReturnType<typeof makeApi>): Promise<MultiRunActions> {
mockResolvedApi(api)
async function launchActions(fake: ReturnType<typeof createFakeContext>, manager = createManager()): Promise<MultiRunActions> {
const deps = depsFor()
await runMultiRunCommand(fake.context, deps, '/ocm-multirun hello')
expect(manager.requests.length).toBeGreaterThan(0)
return deps.showLaunchDialog.mock.calls[0]![0].actions
}
@@ -168,9 +245,8 @@ function fusionForm(overrides: Partial<{ entryIds: number[]; model: string; base
return { entryIds: [1, 2], model: 'anthropic/claude', baseRef: '', instructions: '', ...overrides }
}
beforeEach(() => {
vi.mocked(resolveManagerApi).mockReset()
mockResolvedApi(makeApi())
afterEach(() => {
vi.unstubAllGlobals()
})
describe('listModelOptions', () => {
@@ -231,10 +307,10 @@ describe('listModelOptions', () => {
const fake = createFakeContext()
fake.providerList.mockReturnValue([provider({ id: 'openai', name: 'OpenAI' })])
fake.list.mockReturnValue([
model({ providerID: 'openai', id: 'paid', name: 'Paid', cost: [{ input: 3 }], time: { released: 9 } }),
model({ providerID: 'openai', id: 'free-old', name: 'Free Old', cost: [{ input: 0 }], time: { released: 1 } }),
model({ providerID: 'openai', id: 'free-new', name: 'Free New', cost: [{ input: 0 }], time: { released: 5 } }),
model({ providerID: 'openai', id: 'paid-new', name: 'Paid New', cost: [{ input: 3 }], time: { released: 10 } }),
model({ providerID: 'openai', id: 'paid', name: 'Paid', cost: [{ input: 3, output: 0, cache: { read: 0, write: 0 } }], time: { released: 9 } }),
model({ providerID: 'openai', id: 'free-old', name: 'Free Old', cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }], time: { released: 1 } }),
model({ providerID: 'openai', id: 'free-new', name: 'Free New', cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }], time: { released: 5 } }),
model({ providerID: 'openai', id: 'paid-new', name: 'Paid New', cost: [{ input: 3, output: 0, cache: { read: 0, write: 0 } }], time: { released: 10 } }),
])
await expect(listModelOptions(fake.context)).resolves.toEqual([
@@ -245,17 +321,13 @@ describe('listModelOptions', () => {
])
})
it('tolerates a model list that is not loaded yet', async () => {
it.each([
{ label: 'model', models: undefined, providers: [provider()] },
{ label: 'provider', models: [model()], providers: undefined },
])('tolerates a $label list that is not loaded yet', async ({ models, providers }) => {
const fake = createFakeContext()
fake.list.mockReturnValue(undefined as unknown as ModelInfo[])
await expect(listModelOptions(fake.context)).resolves.toEqual([])
})
it('tolerates a provider list that is not loaded yet', async () => {
const fake = createFakeContext()
fake.providerList.mockReturnValue(undefined as unknown as FakeProvider[])
fake.list.mockReturnValue([model()])
fake.list.mockReturnValue(models)
fake.providerList.mockReturnValue(providers)
await expect(listModelOptions(fake.context)).resolves.toEqual([])
})
@@ -465,6 +537,7 @@ describe('describeMultiRunError', () => {
describe('runMultiRunCommand', () => {
it('refuses when not attached to a Manager repo', async () => {
const manager = createManager()
const fake = createFakeContext()
const withoutRemote = { ...depsFor(), remote: undefined }
const withoutRepo = { ...depsFor(), remote: { ...remote, repoId: undefined } }
@@ -476,62 +549,62 @@ describe('runMultiRunCommand', () => {
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: MULTI_RUN_ATTACH_REQUIRED })
expect(withoutRemote.showLaunchDialog).not.toHaveBeenCalled()
expect(withoutRepo.showRunsDialog).not.toHaveBeenCalled()
expect(resolveManagerApi).not.toHaveBeenCalled()
expect(manager.requests).toHaveLength(0)
})
it('reports an auth failure without opening a dialog', async () => {
vi.mocked(resolveManagerApi).mockResolvedValue({ ok: false, message: 'No token stored.' })
createManager()
const fake = createFakeContext()
const deps = depsFor()
const deps = { ...depsFor(), auth: authDeps(async () => null) }
await runMultiRunCommand(fake.context, deps)
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'No token stored.' })
expect(fake.toast).toHaveBeenCalledWith({
variant: 'error',
message: `no token stored for ${remote.managerUrl} (${STORE_LABEL}). Run \`ocm login ${remote.managerUrl}\`.`,
})
expect(deps.showRunsDialog).not.toHaveBeenCalled()
})
it('resolves the Manager api through resolveManagerApi and uses the returned api', async () => {
it('lists the attached repo through the authenticated manager api', async () => {
const manager = createManager({ list: () => Response.json({ runs: [multiRun()] }) })
const fake = createFakeContext()
const api = makeApi()
mockResolvedApi(api)
const deps = depsFor()
await runMultiRunCommand(fake.context, deps)
const actions = deps.showRunsDialog.mock.calls[0]![0].actions
await actions.list()
await expect(actions.list()).resolves.toEqual({ ok: true, value: [multiRun()] })
expect(resolveManagerApi).toHaveBeenCalledWith(remote.managerUrl)
expect(api.listMultiRuns).toHaveBeenCalledWith(1)
expect(manager.requestsTo('/api/internal/multi-runs?repoId=1')).toEqual([
{ method: 'GET', url: '/api/internal/multi-runs?repoId=1', authorization: 'Bearer tok', body: null },
])
})
it('opens the launch dialog prefilled with the slash argument after listing runs', async () => {
const manager = createManager()
const fake = createFakeContext()
const api = makeApi()
mockResolvedApi(api)
const deps = depsFor()
await runMultiRunCommand(fake.context, deps, '/ocm-multirun fix the flaky test ')
expect(api.listMultiRuns).toHaveBeenCalledWith(1)
expect(manager.requestsTo('/api/internal/multi-runs?repoId=1')).toHaveLength(1)
expect(deps.showLaunchDialog).toHaveBeenCalledWith({ actions: expect.any(Object), initialPrompt: 'fix the flaky test' })
expect(deps.showRunsDialog).not.toHaveBeenCalled()
})
it('does not open the launch dialog when the Manager cannot list multi-runs', async () => {
createManager({ list: () => new Response('not found', { status: 404 }) })
const fake = createFakeContext()
const api = makeApi()
api.listMultiRuns.mockRejectedValue(new ManagerApiError('not found', 404, null, 'list multi-runs'))
mockResolvedApi(api)
const deps = depsFor()
await runMultiRunCommand(fake.context, deps, '/ocm-multirun hello')
expect(api.listMultiRuns).toHaveBeenCalledWith(1)
expect(deps.showLaunchDialog).not.toHaveBeenCalled()
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: MULTI_RUN_ROUTE_MISSING })
})
it('opens the runs dialog without a prompt, whose new action opens an empty launch dialog', async () => {
createManager()
const fake = createFakeContext()
const deps = depsFor()
@@ -544,21 +617,25 @@ describe('runMultiRunCommand', () => {
describe('multi-run dialog actions', () => {
it('launches, toasts the result, and opens the started sessions', async () => {
const manager = createManager({
launch: () => Response.json({ run: multiRun({ name: 'fix the flaky test', entries: [entry({ id: 1, sessionId: 'ses_1' }), entry({ id: 2, sessionId: 'ses_2' })] }) }),
})
const fake = createFakeContext()
const api = makeApi()
api.launchMultiRun.mockResolvedValue(
multiRun({ name: 'fix the flaky test', entries: [entry({ id: 1, sessionId: 'ses_1' }), entry({ id: 2, sessionId: 'ses_2' })] }),
)
const actions = await launchActions(fake, api)
const actions = await launchActions(fake, manager)
await expect(actions.launch(launchForm())).resolves.toBeNull()
expect(api.launchMultiRun).toHaveBeenCalledWith({
repoId: 1,
name: 'fix the flaky test',
prompt: 'fix the flaky test',
models: ['openai/gpt-5'],
isolate: true,
expect(manager.requestsTo('/api/internal/multi-runs')).toContainEqual({
method: 'POST',
url: '/api/internal/multi-runs',
authorization: 'Bearer tok',
body: {
repoId: 1,
name: 'fix the flaky test',
prompt: 'fix the flaky test',
models: ['openai/gpt-5'],
isolate: true,
},
})
expect(fake.toast).toHaveBeenCalledWith({ variant: 'success', message: 'Launched fix the flaky test: 2/2 started' })
expect(fake.open).toHaveBeenCalledWith('ses_1')
@@ -566,12 +643,13 @@ describe('multi-run dialog actions', () => {
})
it('warns about failed entries after a launch', async () => {
const manager = createManager({
launch: () => Response.json({
run: multiRun({ entries: [entry(), entry({ id: 2, model: 'anthropic/claude', status: 'failed', sessionId: null, error: 'quota' })] }),
}),
})
const fake = createFakeContext()
const api = makeApi()
api.launchMultiRun.mockResolvedValue(
multiRun({ entries: [entry(), entry({ id: 2, model: 'anthropic/claude', status: 'failed', sessionId: null, error: 'quota' })] }),
)
const actions = await launchActions(fake, api)
const actions = await launchActions(fake, manager)
await actions.launch(launchForm())
@@ -579,17 +657,18 @@ describe('multi-run dialog actions', () => {
})
it('errors when no entry started', async () => {
const fake = createFakeContext()
const api = makeApi()
api.launchMultiRun.mockResolvedValue(
multiRun({
entries: [
entry({ id: 1, status: 'failed', sessionId: null, error: 'quota' }),
entry({ id: 2, model: 'anthropic/claude', status: 'failed', sessionId: null, error: 'quota' }),
],
const manager = createManager({
launch: () => Response.json({
run: multiRun({
entries: [
entry({ id: 1, status: 'failed', sessionId: null, error: 'quota' }),
entry({ id: 2, model: 'anthropic/claude', status: 'failed', sessionId: null, error: 'quota' }),
],
}),
}),
)
const actions = await launchActions(fake, api)
})
const fake = createFakeContext()
const actions = await launchActions(fake, manager)
await actions.launch(launchForm())
@@ -600,10 +679,9 @@ describe('multi-run dialog actions', () => {
})
it('returns validation and API errors from launch without toasting', async () => {
const manager = createManager({ launch: () => new Response('not found', { status: 404 }) })
const fake = createFakeContext()
const api = makeApi()
api.launchMultiRun.mockRejectedValue(new ManagerApiError('not found', 404, null, 'launch multi-run'))
const actions = await launchActions(fake, api)
const actions = await launchActions(fake, manager)
await expect(actions.launch(launchForm({ models: [] }))).resolves.toBe('Choose at least one model.')
await expect(actions.launch(launchForm())).resolves.toBe(MULTI_RUN_ROUTE_MISSING)
@@ -611,100 +689,96 @@ describe('multi-run dialog actions', () => {
})
it('lists runs for the attached repo', async () => {
const manager = createManager({ list: () => Response.json({ runs: [multiRun()] }) })
const fake = createFakeContext()
const api = makeApi()
api.listMultiRuns.mockResolvedValue([multiRun()])
const actions = await launchActions(fake, api)
const actions = await launchActions(fake, manager)
await expect(actions.list()).resolves.toEqual({ ok: true, value: [multiRun()] })
expect(api.listMultiRuns).toHaveBeenCalledWith(1)
expect(manager.requestsTo('/api/internal/multi-runs?repoId=1')).toHaveLength(2)
})
it('discards an entry and returns the updated run', async () => {
const fake = createFakeContext()
const api = makeApi()
const updated = multiRun({ entries: [entry({ status: 'discarded' })] })
api.discardMultiRunEntry.mockResolvedValue(updated)
const actions = await launchActions(fake, api)
const manager = createManager({ discard: () => Response.json({ run: updated }) })
const fake = createFakeContext()
const actions = await launchActions(fake, manager)
await expect(actions.discard(multiRun(), entry())).resolves.toEqual({ ok: true, value: updated })
expect(api.discardMultiRunEntry).toHaveBeenCalledWith(3, 1)
expect(manager.requestsTo('/multi-runs/3/entries/1/discard')).toEqual([
{ method: 'POST', url: '/api/internal/multi-runs/3/entries/1/discard', authorization: 'Bearer tok', body: null },
])
expect(fake.toast).toHaveBeenCalledWith({ variant: 'success', message: 'Discarded openai/gpt-5' })
})
it('fuses with a fresh request id and opens the fusion session', async () => {
const manager = createManager()
const fake = createFakeContext()
const api = makeApi()
api.fuseMultiRun.mockImplementation(async (_runId: number, request: { requestId: string }) =>
multiRun({ fusions: [fusion({ requestId: request.requestId, sessionId: 'ses_f' })] }),
)
const actions = await launchActions(fake, api)
const actions = await launchActions(fake, manager)
await expect(actions.fuse(multiRun(), fusionForm())).resolves.toBeNull()
const request = api.fuseMultiRun.mock.calls[0]![1] as Record<string, unknown>
expect(request).toEqual({ requestId: expect.stringMatching(/^[0-9a-f-]{36}$/), entryIds: [1, 2], model: 'anthropic/claude' })
expect(request).not.toHaveProperty('isolate')
const [fuseRequest] = manager.requestsTo('/fusions')
expect(fuseRequest?.body).toEqual({ requestId: expect.stringMatching(/^[0-9a-f-]{36}$/), entryIds: [1, 2], model: 'anthropic/claude' })
expect(fuseRequest?.body).not.toHaveProperty('isolate')
expect(fake.open).toHaveBeenCalledWith('ses_f')
})
it('reports a failed fusion', async () => {
const manager = createManager({ fuse: fuseResponding({ status: 'failed', sessionId: null, error: 'context limit' }) })
const fake = createFakeContext()
const api = makeApi()
api.fuseMultiRun.mockImplementation(async (_runId: number, request: { requestId: string }) =>
multiRun({ fusions: [fusion({ requestId: request.requestId, status: 'failed', sessionId: null, error: 'context limit' })] }),
)
const actions = await launchActions(fake, api)
const actions = await launchActions(fake, manager)
await expect(actions.fuse(multiRun(), fusionForm())).resolves.toBe('context limit')
expect(fake.open).not.toHaveBeenCalled()
})
it('reuses the fusion request id across reopened commands while a network error leaves the outcome unknown', async () => {
let fuses = 0
const manager = createManager({
fuse: (request) => {
fuses += 1
if (fuses <= 2) throw new Error('offline')
return fuseResponding()(request)
},
})
const fake = createFakeContext()
const api = makeApi()
api.fuseMultiRun.mockRejectedValueOnce(new Error('offline'))
api.fuseMultiRun.mockRejectedValueOnce(new Error('offline'))
api.fuseMultiRun.mockImplementationOnce(async (_runId: number, request: { requestId: string }) =>
multiRun({ fusions: [fusion({ requestId: request.requestId, sessionId: 'ses_f' })] }),
)
const actions = await launchActions(fake, api)
const actions = await launchActions(fake, manager)
await expect(actions.fuse(multiRun(), fusionForm())).resolves.toBe('offline')
await expect(actions.fuse(multiRun(), fusionForm())).resolves.toBe('offline')
const reopened = await launchActions(createFakeContext(), api)
const reopened = await launchActions(createFakeContext(), manager)
await expect(reopened.fuse(multiRun(), fusionForm())).resolves.toBeNull()
const [first, second, third] = api.fuseMultiRun.mock.calls.map((call) => (call[1] as { requestId: string }).requestId)
expect(second).toBe(first)
expect(third).toBe(first)
const requestIds = manager.requestsTo('/fusions').map((request) => z.string().parse(request.body?.requestId))
expect(requestIds).toHaveLength(3)
expect(requestIds[1]).toBe(requestIds[0])
expect(requestIds[2]).toBe(requestIds[0])
})
it('mints a fresh fusion request id once the Manager has answered', async () => {
let fuses = 0
const manager = createManager({
fuse: (request) => {
fuses += 1
if (fuses === 1) return new Response('boom', { status: 500 })
return fuseResponding()(request)
},
})
const fake = createFakeContext()
const api = makeApi()
api.fuseMultiRun.mockRejectedValueOnce(new ManagerApiError('boom', 500, null, 'fuse multi-run'))
api.fuseMultiRun.mockImplementationOnce(async (_runId: number, request: { requestId: string }) =>
multiRun({ fusions: [fusion({ requestId: request.requestId, sessionId: 'ses_f' })] }),
)
const actions = await launchActions(fake, api)
const actions = await launchActions(fake, manager)
await expect(actions.fuse(multiRun(), fusionForm())).resolves.toBe('boom')
await expect(actions.fuse(multiRun(), fusionForm())).resolves.toBe('fuse multi-run failed (500): boom')
await expect(actions.fuse(multiRun(), fusionForm())).resolves.toBeNull()
const [first, second] = api.fuseMultiRun.mock.calls.map((call) => (call[1] as { requestId: string }).requestId)
expect(second).not.toBe(first)
const requestIds = manager.requestsTo('/fusions').map((request) => z.string().parse(request.body?.requestId))
expect(requestIds[1]).not.toBe(requestIds[0])
})
it('opens the recovered fusion session instead of failing', async () => {
const manager = createManager({
fuse: () => new Response(JSON.stringify({ error: 'conflict', code: 'FUSION_ATTEMPT_RECOVERED', details: { fusions: [{ fusionId: 4, sessionId: 'ses_recovered' }] } }), { status: 409 }),
})
const fake = createFakeContext()
const api = makeApi()
api.fuseMultiRun.mockRejectedValue(
new ManagerApiError('conflict', 409, 'FUSION_ATTEMPT_RECOVERED', 'fuse multi-run', {
fusions: [{ fusionId: 4, sessionId: 'ses_recovered' }],
}),
)
const actions = await launchActions(fake, api)
const actions = await launchActions(fake, manager)
await expect(actions.fuse(multiRun(), fusionForm())).resolves.toBeNull()
expect(fake.open).toHaveBeenCalledWith('ses_recovered')
+107 -79
View File
@@ -1,25 +1,11 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { z } from 'zod'
import type { Context } from '@opencode/plugin/tui/context'
import { runOcmSwitch } from '../src/tui-ocm.js'
import type { OcmSwitchDeps, OcmSwitchRuntime } from '../src/tui-ocm.js'
import type { ManagerRepo } from '../src/manager-repos.js'
import type { RemoteContext } from '../src/remote-context.js'
const mocks = vi.hoisted(() => ({
resolveManagerAuth: vi.fn(),
fetchRepos: vi.fn(),
resolveOpenCodeProjectId: vi.fn(),
warmRepoProxy: vi.fn(),
readState: vi.fn(),
writeState: vi.fn(),
setPendingWarp: vi.fn(),
}))
vi.mock('../src/manager-auth.js', () => ({ resolveManagerAuth: mocks.resolveManagerAuth }))
vi.mock('../src/manager-repos.js', () => ({ fetchRepos: mocks.fetchRepos }))
vi.mock('@opencode-manager/shared/project-id', () => ({ resolveOpenCodeProjectId: mocks.resolveOpenCodeProjectId }))
vi.mock('../src/repo-proxy.js', () => ({ warmRepoProxy: mocks.warmRepoProxy }))
vi.mock('../src/state.js', () => ({ readState: mocks.readState, writeState: mocks.writeState }))
vi.mock('../src/warp.js', () => ({ setPendingWarp: mocks.setPendingWarp }))
import type { OcmTuiContext } from '../src/tui-context.js'
const MANAGER_URL = 'https://manager.example'
@@ -37,78 +23,117 @@ function repo(overrides: Partial<ManagerRepo> = {}): ManagerRepo {
}
}
const SelectRequestSchema = z.object({
title: z.string(),
options: z.array(z.object({
title: z.string(),
description: z.string().optional(),
category: z.string().optional(),
disabled: z.boolean().optional(),
}).loose()),
})
function createFakeContext(route: { type: string; sessionID?: string } = { type: 'home' }) {
const toast = vi.fn()
const confirm = vi.fn()
const toast = vi.fn<Context['ui']['toast']['show']>()
const confirm = vi.fn<Context['ui']['dialog']['confirm']>()
const select = vi.fn()
const dispatch = vi.fn()
const context = {
const dispatch = vi.fn<Context['keymap']['dispatch']>()
const context: OcmTuiContext = {
ui: {
toast: { show: toast },
dialog: { confirm, select },
router: { current: () => route },
dialog: { confirm, select, prompt: vi.fn() },
router: { current: () => (route.type === 'session' ? { type: 'session', sessionID: route.sessionID ?? 'ses_a' } : { type: 'home' }), navigate: vi.fn() },
tabs: { enabled: () => false, open: () => true, focus: () => true },
slot: vi.fn(() => () => undefined),
},
data: { session: { get: () => ({ location: { directory: '/work/session-dir' } }) } },
keymap: { dispatch },
} as unknown as Context
data: { session: { get: () => undefined }, location: { model: { list: () => [], sync: async () => undefined }, provider: { list: () => [], sync: async () => undefined } } },
keymap: { layer: vi.fn(), dispatch },
client: { session: { export: vi.fn() } },
}
return { context, toast, confirm, select, dispatch }
}
beforeEach(() => {
vi.resetAllMocks()
mocks.resolveManagerAuth.mockResolvedValue({ ok: true, managerUrl: MANAGER_URL, token: 'tok' })
mocks.readState.mockReturnValue({ managerUrl: MANAGER_URL })
mocks.resolveOpenCodeProjectId.mockResolvedValue('proj_a')
})
function offeredOptions(fake: ReturnType<typeof createFakeContext>) {
return SelectRequestSchema.parse(fake.select.mock.calls[0]?.[0]).options
}
function createRuntime(): OcmSwitchRuntime {
return {
resolveManagerAuth: vi.fn<OcmSwitchRuntime['resolveManagerAuth']>(async () => ({ ok: true, managerUrl: MANAGER_URL, token: 'tok' })),
fetchRepos: vi.fn<OcmSwitchRuntime['fetchRepos']>(async () => [repo()]),
resolveProjectId: vi.fn<OcmSwitchRuntime['resolveProjectId']>(async () => 'proj_a'),
warmRepoProxy: vi.fn<OcmSwitchRuntime['warmRepoProxy']>(async () => undefined),
readState: vi.fn<OcmSwitchRuntime['readState']>(() => ({ managerUrl: MANAGER_URL })),
writeState: vi.fn<OcmSwitchRuntime['writeState']>(),
setPendingWarp: vi.fn<OcmSwitchRuntime['setPendingWarp']>(),
}
}
function switchDeps(runtime: OcmSwitchRuntime, overrides: Omit<OcmSwitchDeps, 'runtime'> = { remote: undefined }): OcmSwitchDeps {
return { ...overrides, runtime }
}
describe('runOcmSwitch from a local TUI', () => {
let runtime: OcmSwitchRuntime
beforeEach(() => {
runtime = createRuntime()
})
it('confirms and attaches to the single Manager repo matching this directory', async () => {
const fake = createFakeContext()
const match = repo()
mocks.fetchRepos.mockResolvedValue([match, repo({ repoId: 2, name: 'other', projectId: 'proj_b' })])
vi.mocked(runtime.fetchRepos).mockResolvedValue([match, repo({ repoId: 2, name: 'other', projectId: 'proj_b' })])
fake.confirm.mockResolvedValue(true)
await runOcmSwitch(fake.context, { remote: undefined, cwd: '/work/oc-manager' })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote: undefined, cwd: '/work/oc-manager' }))
expect(mocks.resolveManagerAuth).toHaveBeenCalledWith(undefined)
expect(mocks.resolveOpenCodeProjectId).toHaveBeenCalledWith('/work/oc-manager')
expect(runtime.resolveManagerAuth).toHaveBeenCalledWith(undefined)
expect(runtime.resolveProjectId).toHaveBeenCalledWith('/work/oc-manager')
expect(fake.confirm).toHaveBeenCalledWith(
expect.objectContaining({ title: 'Switch to OpenCode Manager', message: expect.stringContaining('attach to oc-manager on manager.example') }),
)
expect(mocks.warmRepoProxy).toHaveBeenCalledWith(MANAGER_URL, 'tok', 1)
expect(mocks.writeState).toHaveBeenCalledWith({
expect(runtime.warmRepoProxy).toHaveBeenCalledWith(MANAGER_URL, 'tok', 1)
expect(runtime.writeState).toHaveBeenCalledWith({
managerUrl: MANAGER_URL,
lastRepoId: 1,
lastRepoName: 'oc-manager',
lastRepoDir: '/srv/repos/oc-manager',
lastRepoBranch: 'main',
})
expect(mocks.setPendingWarp).toHaveBeenCalledWith({
expect(runtime.setPendingWarp).toHaveBeenCalledWith({
kind: 'attach',
target: { managerUrl: MANAGER_URL, token: 'tok', repoId: 1, repoName: 'oc-manager' },
})
expect(fake.dispatch).toHaveBeenCalledWith('app.exit')
expect(mocks.warmRepoProxy.mock.invocationCallOrder[0]).toBeLessThan(fake.dispatch.mock.invocationCallOrder[0]!)
expect(vi.mocked(runtime.warmRepoProxy).mock.invocationCallOrder[0]).toBeLessThan(fake.dispatch.mock.invocationCallOrder[0]!)
})
it('stays put when the switch is declined', async () => {
const fake = createFakeContext()
mocks.fetchRepos.mockResolvedValue([repo()])
vi.mocked(runtime.fetchRepos).mockResolvedValue([repo()])
fake.confirm.mockResolvedValue(false)
await runOcmSwitch(fake.context, { remote: undefined, cwd: '/work/oc-manager' })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote: undefined, cwd: '/work/oc-manager' }))
expect(mocks.setPendingWarp).not.toHaveBeenCalled()
expect(runtime.setPendingWarp).not.toHaveBeenCalled()
expect(fake.dispatch).not.toHaveBeenCalled()
})
it('uses the current session directory to find the matching repo', async () => {
const fake = createFakeContext({ type: 'session', sessionID: 'ses_a' })
mocks.fetchRepos.mockResolvedValue([repo()])
fake.context.data.session.get = () => ({
id: 'ses_a',
projectID: 'proj_a',
cost: 0,
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
time: { created: 1, updated: 2 },
location: { directory: '/work/session-dir' },
})
await runOcmSwitch(fake.context, { remote: undefined })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote: undefined }))
expect(mocks.resolveOpenCodeProjectId).toHaveBeenCalledWith('/work/session-dir')
expect(runtime.resolveProjectId).toHaveBeenCalledWith('/work/session-dir')
})
it('offers a picker with matching repos first when several match, skipping repos that are not ready', async () => {
@@ -116,18 +141,17 @@ describe('runOcmSwitch from a local TUI', () => {
const main = repo()
const worktree = repo({ repoId: 3, name: 'oc-manager-feature', branch: 'feature', isWorktree: true })
const other = repo({ repoId: 2, name: 'other', projectId: 'proj_b', branch: null })
mocks.fetchRepos.mockResolvedValue([other, main, worktree, repo({ repoId: 4, name: 'cloning', cloneStatus: 'cloning' })])
vi.mocked(runtime.fetchRepos).mockResolvedValue([other, main, worktree, repo({ repoId: 4, name: 'cloning', cloneStatus: 'cloning' })])
fake.select.mockResolvedValue({ kind: 'repo', repo: worktree })
await runOcmSwitch(fake.context, { remote: undefined, cwd: '/work/oc-manager' })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote: undefined, cwd: '/work/oc-manager' }))
const options = fake.select.mock.calls[0]![0].options as { title: string; description?: string; category: string }[]
expect(options.map((option) => [option.title, option.category, option.description])).toEqual([
expect(offeredOptions(fake).map((option) => [option.title, option.category, option.description])).toEqual([
['oc-manager', 'Matches this directory', 'main'],
['oc-manager-feature', 'Matches this directory', 'worktree · feature'],
['other', 'Manager repos', undefined],
])
expect(mocks.setPendingWarp).toHaveBeenCalledWith({
expect(runtime.setPendingWarp).toHaveBeenCalledWith({
kind: 'attach',
target: { managerUrl: MANAGER_URL, token: 'tok', repoId: 3, repoName: 'oc-manager-feature' },
})
@@ -135,23 +159,22 @@ describe('runOcmSwitch from a local TUI', () => {
it('offers every ready repo when nothing matches, and does nothing when dismissed', async () => {
const fake = createFakeContext()
mocks.resolveOpenCodeProjectId.mockResolvedValue(null)
mocks.fetchRepos.mockResolvedValue([repo(), repo({ repoId: 2, name: 'other' })])
vi.mocked(runtime.resolveProjectId).mockResolvedValue(null)
vi.mocked(runtime.fetchRepos).mockResolvedValue([repo(), repo({ repoId: 2, name: 'other' })])
fake.select.mockResolvedValue(undefined)
await runOcmSwitch(fake.context, { remote: undefined, cwd: '/tmp' })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote: undefined, cwd: '/tmp' }))
const options = fake.select.mock.calls[0]![0].options as { category: string }[]
expect(options.map((option) => option.category)).toEqual(['Manager repos', 'Manager repos'])
expect(mocks.warmRepoProxy).not.toHaveBeenCalled()
expect(mocks.setPendingWarp).not.toHaveBeenCalled()
expect(offeredOptions(fake).map((option) => option.category)).toEqual(['Manager repos', 'Manager repos'])
expect(runtime.warmRepoProxy).not.toHaveBeenCalled()
expect(runtime.setPendingWarp).not.toHaveBeenCalled()
})
it('reports a Manager without ready repos', async () => {
const fake = createFakeContext()
mocks.fetchRepos.mockResolvedValue([repo({ cloneStatus: 'error' })])
vi.mocked(runtime.fetchRepos).mockResolvedValue([repo({ cloneStatus: 'error' })])
await runOcmSwitch(fake.context, { remote: undefined, cwd: '/work/oc-manager' })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote: undefined, cwd: '/work/oc-manager' }))
expect(fake.toast).toHaveBeenCalledWith({
variant: 'error',
@@ -165,35 +188,37 @@ describe('runOcmSwitch from an attached TUI', () => {
const remote: RemoteContext = { managerUrl: MANAGER_URL, managerHost: 'manager.example', repoName: 'oc-manager', repoId: 1 }
it('offers local opencode first and marks the current repo as unavailable', async () => {
const runtime = createRuntime()
const fake = createFakeContext()
mocks.fetchRepos.mockResolvedValue([repo(), repo({ repoId: 2, name: 'other' })])
vi.mocked(runtime.fetchRepos).mockResolvedValue([repo(), repo({ repoId: 2, name: 'other' })])
fake.select.mockResolvedValue({ kind: 'local' })
await runOcmSwitch(fake.context, { remote })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote }))
expect(mocks.resolveManagerAuth).toHaveBeenCalledWith(MANAGER_URL)
expect(mocks.resolveOpenCodeProjectId).not.toHaveBeenCalled()
const options = fake.select.mock.calls[0]![0].options as { title: string; disabled?: boolean; description?: string }[]
expect(runtime.resolveManagerAuth).toHaveBeenCalledWith(MANAGER_URL)
expect(runtime.resolveProjectId).not.toHaveBeenCalled()
const options = offeredOptions(fake)
expect(options.map((option) => [option.title, option.disabled ?? false])).toEqual([
['Local opencode', false],
['oc-manager', true],
['other', false],
])
expect(options[1]!.description).toBe('Current')
expect(mocks.setPendingWarp).toHaveBeenCalledWith({ kind: 'local' })
expect(mocks.warmRepoProxy).not.toHaveBeenCalled()
expect(runtime.setPendingWarp).toHaveBeenCalledWith({ kind: 'local' })
expect(runtime.warmRepoProxy).not.toHaveBeenCalled()
expect(fake.dispatch).toHaveBeenCalledWith('app.exit')
})
it('switches to another Manager repo', async () => {
const runtime = createRuntime()
const fake = createFakeContext()
const other = repo({ repoId: 2, name: 'other' })
mocks.fetchRepos.mockResolvedValue([repo(), other])
vi.mocked(runtime.fetchRepos).mockResolvedValue([repo(), other])
fake.select.mockResolvedValue({ kind: 'repo', repo: other })
await runOcmSwitch(fake.context, { remote })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote }))
expect(mocks.setPendingWarp).toHaveBeenCalledWith({
expect(runtime.setPendingWarp).toHaveBeenCalledWith({
kind: 'attach',
target: { managerUrl: MANAGER_URL, token: 'tok', repoId: 2, repoName: 'other' },
})
@@ -202,35 +227,38 @@ describe('runOcmSwitch from an attached TUI', () => {
describe('runOcmSwitch failures', () => {
it('reports an auth failure without contacting the Manager', async () => {
const runtime = createRuntime()
const fake = createFakeContext()
mocks.resolveManagerAuth.mockResolvedValue({ ok: false, message: 'No manager configured. Run `ocm login <url>` first.' })
vi.mocked(runtime.resolveManagerAuth).mockResolvedValue({ ok: false, reason: 'no-manager', message: 'No manager configured. Run `ocm login <url>` first.' })
await runOcmSwitch(fake.context, { remote: undefined })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote: undefined }))
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
expect(mocks.fetchRepos).not.toHaveBeenCalled()
expect(runtime.fetchRepos).not.toHaveBeenCalled()
})
it('reports a Manager request failure and does not exit', async () => {
const runtime = createRuntime()
const fake = createFakeContext()
mocks.fetchRepos.mockRejectedValue(new Error('manager responded 502 Bad Gateway'))
vi.mocked(runtime.fetchRepos).mockRejectedValue(new Error('manager responded 502 Bad Gateway'))
await runOcmSwitch(fake.context, { remote: undefined, cwd: '/work/oc-manager' })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote: undefined, cwd: '/work/oc-manager' }))
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'manager responded 502 Bad Gateway' })
expect(fake.dispatch).not.toHaveBeenCalled()
})
it('does not exit when the repo proxy cannot be warmed', async () => {
const runtime = createRuntime()
const fake = createFakeContext()
mocks.fetchRepos.mockResolvedValue([repo()])
vi.mocked(runtime.fetchRepos).mockResolvedValue([repo()])
fake.confirm.mockResolvedValue(true)
mocks.warmRepoProxy.mockRejectedValue(new Error('Manager is older than ocm requires'))
vi.mocked(runtime.warmRepoProxy).mockRejectedValue(new Error('Manager is older than ocm requires'))
await runOcmSwitch(fake.context, { remote: undefined, cwd: '/work/oc-manager' })
await runOcmSwitch(fake.context, switchDeps(runtime, { remote: undefined, cwd: '/work/oc-manager' }))
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'Manager is older than ocm requires' })
expect(mocks.setPendingWarp).not.toHaveBeenCalled()
expect(runtime.setPendingWarp).not.toHaveBeenCalled()
expect(fake.dispatch).not.toHaveBeenCalled()
})
})
+287 -339
View File
@@ -1,206 +1,208 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { describe, it, expect, vi } from 'vitest'
import type { Context } from '@opencode/plugin/tui/context'
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
import type { SessionInfo, SessionTransferData } from '@opencode-manager/shared/opencode'
import { setupOcm } from '../src/tui-plugin.js'
import type { OcmFeatures, OcmPluginDeps } from '../src/tui-plugin.js'
import { moveReminderText } from '../src/session-move.js'
import type { MoveDestination, RemoteRepoSummary } from '../src/mirror.js'
import type { ManagerSessionTransfer } from '../src/remote-session.js'
import type { ManagerRepo } from '../src/manager-repos.js'
import type { OcmTuiContext } from '../src/tui-context.js'
import type { PendingWarp } from '../src/warp.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(),
chooseMoveDestination: vi.fn(),
mirrorUpFast: vi.fn(),
pickMatchedRepo: vi.fn(),
getBranchName: vi.fn(),
createManagerSessionTransfer: vi.fn(),
setPendingWarp: vi.fn(),
runPendingWarp: vi.fn(),
mirrorCheckouts: vi.fn(),
warmRepoProxy: vi.fn(),
}))
const MANAGER_URL = 'https://manager.example'
vi.mock('../src/state.js', () => ({
readState: mocks.readState,
readInstallNotice: mocks.readInstallNotice,
}))
const matched: RemoteRepoSummary = { repoId: 1, name: 'repo', projectId: 'proj_1', branch: 'main' }
vi.mock('../src/internal-token-store.js', () => ({ getToken: mocks.getToken }))
const repo: ManagerRepo = {
repoId: 1,
name: 'repo',
branch: 'main',
cloneStatus: 'ready',
directory: '/workspace/repos/repo',
extra: { repoId: 1, localPath: 'repo', fullPath: '/workspace/repos/repo' },
}
vi.mock('../src/manager-repos.js', () => ({
fetchRepos: mocks.fetchRepos,
toRemoteRepoSummaries: mocks.toRemoteRepoSummaries,
}))
const noFeatures: OcmFeatures = { remote: undefined, dialogs: { multiRunLaunch: vi.fn(), multiRuns: vi.fn() } }
vi.mock('../src/mirror.js', () => ({
prepareMirror: mocks.prepareMirror,
chooseMoveDestination: mocks.chooseMoveDestination,
mirrorUpFast: mocks.mirrorUpFast,
pickMatchedRepo: mocks.pickMatchedRepo,
}))
vi.mock('../src/local-repo.js', () => ({ getBranchName: mocks.getBranchName }))
vi.mock('../src/remote-session.js', () => ({
createManagerSessionTransfer: mocks.createManagerSessionTransfer,
}))
vi.mock('../src/warp.js', () => ({
setPendingWarp: mocks.setPendingWarp,
runPendingWarp: mocks.runPendingWarp,
}))
vi.mock('../src/repo-proxy.js', () => ({ warmRepoProxy: mocks.warmRepoProxy }))
vi.mock('../src/manager-api.js', () => ({
ManagerApi: class {
constructor(
public readonly managerUrl: string,
public readonly token: string,
) {}
mirrorCheckouts = mocks.mirrorCheckouts
},
ManagerApiError: class ManagerApiError extends Error {
constructor(
message: string,
public readonly status: number,
) {
super(message)
}
},
isManagerRouteMissing: vi.fn(() => false),
}))
const noFeatures = { remote: undefined, dialogs: { multiRunLaunch: vi.fn(), multiRuns: vi.fn() } }
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 createSession(overrides: Partial<SessionInfo> = {}): SessionInfo {
const base: SessionInfo = {
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' },
}
return { ...base, ...overrides }
}
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' },
},
info: createSession(),
messages: [],
} as unknown as SessionTransferData
}
}
function createFakeContext(session: { location: { directory: string }; parentID?: string } = { location: { directory: '/Users/x/repo' } }) {
const exportMock = vi.fn()
const confirm = vi.fn()
const select = vi.fn()
const toast = vi.fn()
const layer = vi.fn()
const dispatch = vi.fn()
const slot = vi.fn(() => () => undefined)
const inPlace: MoveDestination = { kind: 'in-place', directory: '/workspace/repos/repo', branch: 'main', reasons: [] }
const context = {
const pushedInPlace = {
repoId: 1,
fullPath: '/workspace/repos/repo',
branch: 'main',
head: null,
created: false,
}
function createFakeContext(session: SessionInfo = createSession()) {
const exportSession = vi.fn<Context['client']['session']['export']>()
const confirm = vi.fn<Context['ui']['dialog']['confirm']>()
const select = vi.fn()
const prompt = vi.fn<Context['ui']['dialog']['prompt']>()
const toast = vi.fn<Context['ui']['toast']['show']>()
const layer = vi.fn<Context['keymap']['layer']>()
const dispatch = vi.fn<Context['keymap']['dispatch']>()
const slot = vi.fn<Context['ui']['slot']>(() => () => undefined)
const context: OcmTuiContext = {
ui: {
router: { current: () => ({ type: 'session', sessionID: 'ses_a' }) },
router: {
current: () => ({ type: 'session', sessionID: session.id }),
navigate: vi.fn(),
},
toast: { show: toast },
dialog: { confirm, select },
dialog: { confirm, select, prompt },
tabs: { enabled: () => false, open: () => true, focus: () => true },
slot,
},
data: {
session: { get: () => session },
location: {
model: { list: () => [], sync: async () => undefined },
provider: { list: () => [], sync: async () => undefined },
},
},
keymap: { layer, dispatch },
client: { session: { export: exportMock } },
} as unknown as Context
client: { session: { export: exportSession } },
}
return { context, exportMock, confirm, select, toast, layer, dispatch, slot }
return { context, exportSession, confirm, select, toast, layer, dispatch, slot }
}
function renderAppSlot(fake: ReturnType<typeof createFakeContext>) {
const claim = fake.slot.mock.calls.map((call) => (call as unknown[])[0] as { append?: string; render: () => unknown }).find((c) => c.append === 'app')!
claim.render()
interface FixtureOptions {
session?: SessionInfo
branch?: string | null
destination?: MoveDestination
pushed?: {
repoId: number
fullPath: string
branch: string | null
head: string | null
created: boolean
worktreeSetup?: { status: 'none' } | { status: 'failed'; error: string }
}
onManager?: string[]
existsError?: Error
importError?: Error
reminderError?: Error
exportError?: Error
proxyError?: Error
confirmAnswers?: boolean[]
deps?: Partial<OcmPluginDeps>
}
function stubTransfer(options: { importError?: Error; reminderError?: Error; onManager?: string[]; existsError?: Error } = {}) {
const sessionExists = vi.fn(async (sessionID: string) => {
if (options.existsError) throw options.existsError
return (options.onManager ?? []).includes(sessionID)
function createFixture(options: FixtureOptions = {}) {
const fake = createFakeContext(options.session)
const calls: string[] = []
const onManager = options.onManager ?? []
const transfer: ManagerSessionTransfer = {
sessionExists: vi.fn<ManagerSessionTransfer['sessionExists']>(async (sessionID) => {
if (options.existsError) throw options.existsError
return onManager.includes(sessionID)
}),
importSession: vi.fn<ManagerSessionTransfer['importSession']>(async () => {
calls.push('import')
if (options.importError) throw options.importError
return { sessionID: 'ses_a' }
}),
addReminder: vi.fn<ManagerSessionTransfer['addReminder']>(async (sessionID, text) => {
calls.push('synthetic')
if (options.reminderError) throw options.reminderError
return { id: 'msg_synthetic', sessionID, time: { created: 1 }, type: 'synthetic', payload: { text }, delivery: 'queue' }
}),
}
const managerApi = {
mirrorCheckouts: vi.fn(async () => ({
main: { directory: '/workspace/repos/repo', branch: 'main', head: null, dirty: false },
worktrees: [],
branchHead: null,
branchCheckedOut: false,
suffixedWorktreeBranch: 'main-ocm',
})),
mirrorCreateWorktree: vi.fn(),
mirrorUploadBundle: vi.fn(),
mirrorPatch: vi.fn(),
}
const deps: OcmPluginDeps = {
readInstallNotice: vi.fn(() => null),
resolveManagerAuth: vi.fn<OcmPluginDeps['resolveManagerAuth']>(async () => ({ ok: true, managerUrl: MANAGER_URL, token: 'tok' })),
fetchRepos: vi.fn(async () => [repo]),
toRemoteRepoSummaries: vi.fn(() => [matched]),
prepareMirror: vi.fn(async () => ({ repoRoot: '/Users/x/repo', localProjectId: 'proj_1', matched: [matched] })),
getBranchName: vi.fn(() => options.branch === undefined ? 'main' : options.branch),
pickMatchedRepo: vi.fn(() => matched),
warmRepoProxy: vi.fn(async () => {
if (options.proxyError) throw options.proxyError
}),
createManagerSessionTransfer: vi.fn(() => transfer),
createManagerApi: vi.fn(() => managerApi),
chooseMoveDestination: vi.fn(() => options.destination ?? inPlace),
mirrorUpFast: vi.fn(async () => options.pushed ?? pushedInPlace),
setPendingWarp: vi.fn<(warp: PendingWarp) => void>(),
runPendingWarp: vi.fn(),
...options.deps,
}
fake.exportSession.mockImplementation(async () => {
calls.push('export')
if (options.exportError) throw options.exportError
return makeTransfer()
})
const importSession = vi.fn(async () => {
mocks.calls.push('import')
if (options.importError) throw options.importError
return { sessionID: 'ses_a' }
})
const addReminder = vi.fn(async () => {
mocks.calls.push('synthetic')
if (options.reminderError) throw options.reminderError
})
mocks.createManagerSessionTransfer.mockReturnValue({ sessionExists, importSession, addReminder })
return { sessionExists, importSession, addReminder }
const answers = options.confirmAnswers ?? [true, false]
for (const answer of answers) fake.confirm.mockResolvedValueOnce(answer)
return { ...fake, deps, calls, transfer, managerApi }
}
function configureMove(fake: ReturnType<typeof createFakeContext>) {
mocks.readState.mockReturnValue({ managerUrl: 'https://manager.example' })
mocks.getToken.mockResolvedValue('tok')
mocks.warmRepoProxy.mockResolvedValue(undefined)
mocks.fetchRepos.mockResolvedValue(repos)
mocks.toRemoteRepoSummaries.mockImplementation((r: unknown) => r)
mocks.prepareMirror.mockResolvedValue({ repoRoot: '/Users/x/repo', localProjectId: 'proj_1', matched: [matched] })
mocks.getBranchName.mockReturnValue('main')
mocks.pickMatchedRepo.mockReturnValue(matched)
mocks.mirrorCheckouts.mockResolvedValue({
main: { directory: '/workspace/repos/repo', branch: 'main', head: null, dirty: false },
worktrees: [],
branchHead: null,
branchCheckedOut: false,
suffixedWorktreeBranch: 'main-ocm',
})
mocks.chooseMoveDestination.mockReturnValue({
kind: 'in-place',
directory: '/workspace/repos/repo',
branch: 'main',
reasons: [],
})
mocks.mirrorUpFast.mockResolvedValue({
repoId: 1,
fullPath: '/workspace/repos/repo',
branch: 'main',
head: null,
created: false,
})
fake.confirm.mockResolvedValueOnce(true).mockResolvedValueOnce(false)
type Fixture = ReturnType<typeof createFixture>
function renderAppSlot(fake: Fixture): void {
const claim = fake.slot.mock.calls[0]![0]
if (!('append' in claim) || claim.append !== 'app') throw new Error('expected an app slot claim')
claim.render({})
}
async function invokeMove(fake: ReturnType<typeof createFakeContext>) {
await setupOcm(fake.context, vi.fn(), noFeatures)
async function invokeMove(fake: Fixture): Promise<void> {
await setupOcm(fake.context, vi.fn(), noFeatures, fake.deps)
renderAppSlot(fake)
const factory = fake.layer.mock.calls[0]![0] as () => { commands: { id: string; run: () => Promise<void> }[] }
const command = factory().commands.find((entry) => entry.id === 'ocm.session.move')!
await command.run()
const factory = fake.layer.mock.calls[0]![0]
const command = factory().commands?.find((entry) => entry.id === 'ocm.session.move')
await command?.run()
}
beforeEach(() => {
vi.resetAllMocks()
mocks.calls.length = 0
})
function commandIds(fake: Fixture): (string | undefined)[] | undefined {
renderAppSlot(fake)
return fake.layer.mock.calls[0]![0]().commands?.map((entry) => entry.id)
}
describe('setupOcm', () => {
it('registers commands from the app slot so the host keymap provider is mounted', async () => {
const fake = createFakeContext()
const fake = createFixture()
await setupOcm(fake.context, vi.fn(), noFeatures)
await setupOcm(fake.context, vi.fn(), noFeatures, fake.deps)
expect(fake.layer).not.toHaveBeenCalled()
expect(fake.slot).toHaveBeenCalledWith(expect.objectContaining({ append: 'app' }))
@@ -208,249 +210,209 @@ describe('setupOcm', () => {
renderAppSlot(fake)
expect(fake.layer).toHaveBeenCalledTimes(1)
const factory = fake.layer.mock.calls[0]![0] as () => { mode?: string }
expect(factory().mode).toBe('global')
expect(fake.layer.mock.calls[0]![0]().mode).toBe('global')
})
it('registers no goal command', async () => {
const fake = createFakeContext()
it('registers the move, switch and multi-run commands but no goal command', async () => {
const fake = createFixture()
await setupOcm(fake.context, vi.fn(), noFeatures, fake.deps)
await setupOcm(fake.context, vi.fn(), noFeatures)
renderAppSlot(fake)
const factory = fake.layer.mock.calls[0]![0] as () => {
commands: { id: string }[]
}
expect(factory().commands.map((entry) => entry.id)).toEqual(['ocm.session.move', 'ocm.switch', 'ocm.multirun'])
expect(commandIds(fake)).toEqual(['ocm.session.move', 'ocm.switch', 'ocm.multirun'])
})
it('exposes the multi-run slash command', async () => {
const fake = createFakeContext()
await setupOcm(fake.context, vi.fn(), noFeatures)
it('exposes the multi-run and server switch slash commands', async () => {
const fake = createFixture()
await setupOcm(fake.context, vi.fn(), noFeatures, fake.deps)
renderAppSlot(fake)
const factory = fake.layer.mock.calls[0]![0] as () => {
commands: { id: string; slash?: { name: string; arguments?: true } }[]
}
const multiRun = factory().commands.find((entry) => entry.id === 'ocm.multirun')
expect(multiRun?.slash).toEqual({ name: 'ocm-multirun', arguments: true })
const commands = fake.layer.mock.calls[0]![0]().commands ?? []
expect(commands.find((entry) => entry.id === 'ocm.multirun')?.slash).toEqual({ name: 'ocm-multirun', arguments: true })
expect(commands.find((entry) => entry.id === 'ocm.switch')?.slash).toEqual({ name: 'ocm' })
})
it('exposes the server switch slash command', async () => {
const fake = createFakeContext()
it('shows the install notice once when one is pending', async () => {
const fake = createFixture({
deps: { readInstallNotice: vi.fn(() => ({ link: '/home/me/.local/bin/ocm', binDir: '/home/me/.local/bin', pathMissing: true })) },
})
await setupOcm(fake.context, vi.fn(), noFeatures)
renderAppSlot(fake)
await setupOcm(fake.context, vi.fn(), noFeatures, fake.deps)
const factory = fake.layer.mock.calls[0]![0] as () => {
commands: { id: string; slash?: { name: string; arguments?: true } }[]
}
const command = factory().commands.find((entry) => entry.id === 'ocm.switch')
expect(command?.slash).toEqual({ name: 'ocm' })
expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({
variant: 'success',
message: expect.stringContaining('/home/me/.local/bin/ocm'),
}))
})
it('runs the deferred warp when the returned cleanup is called', async () => {
const fake = createFixture()
const cleanup = await setupOcm(fake.context, vi.fn(), noFeatures, fake.deps)
cleanup()
expect(fake.deps.runPendingWarp).toHaveBeenCalledOnce()
})
})
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()
})
const fake = createFixture({ confirmAnswers: [true, false] })
await invokeMove(fake)
expect(mocks.calls).toEqual(['export', 'import', 'synthetic'])
expect(fake.exportMock).toHaveBeenCalledWith({ sessionID: 'ses_a' })
expect(importSession).toHaveBeenCalledWith(
expect(fake.calls).toEqual(['export', 'import', 'synthetic'])
expect(fake.exportSession).toHaveBeenCalledWith({ sessionID: 'ses_a' })
expect(fake.transfer.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.transfer.addReminder).toHaveBeenCalledWith('ses_a', moveReminderText('/workspace/repos/repo'))
expect(fake.deps.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'))
const fake = createFixture({ exportError: 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.calls).toEqual(['export'])
expect(fake.transfer.importSession).not.toHaveBeenCalled()
expect(fake.transfer.addReminder).not.toHaveBeenCalled()
expect(fake.deps.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()
})
const fake = createFixture({ importError: new Error('import diverged') })
await invokeMove(fake)
expect(mocks.calls).toEqual(['export', 'import'])
expect(addReminder).not.toHaveBeenCalled()
expect(mocks.setPendingWarp).not.toHaveBeenCalled()
expect(fake.calls).toEqual(['export', 'import'])
expect(fake.transfer.addReminder).not.toHaveBeenCalled()
expect(fake.deps.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()
})
const fake = createFixture({ reminderError: new Error('synthetic failed') })
await invokeMove(fake)
expect(addReminder).toHaveBeenCalledTimes(1)
expect(mocks.setPendingWarp).not.toHaveBeenCalled()
expect(fake.transfer.addReminder).toHaveBeenCalledTimes(1)
expect(fake.deps.setPendingWarp).not.toHaveBeenCalled()
expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'success' }))
})
function expectNothingPushed(fake: ReturnType<typeof createFakeContext>, importSession: ReturnType<typeof vi.fn>) {
expect(mocks.mirrorCheckouts).not.toHaveBeenCalled()
expect(fake.confirm).not.toHaveBeenCalled()
expect(mocks.mirrorUpFast).not.toHaveBeenCalled()
expect(fake.exportMock).not.toHaveBeenCalled()
expect(importSession).not.toHaveBeenCalled()
}
it('refuses to push when the session is already on the Manager', async () => {
const fake = createFakeContext()
configureMove(fake)
const { sessionExists, importSession } = stubTransfer({ onManager: ['ses_a'] })
it('attaches to the moved session when the user confirms the warp', async () => {
const fake = createFixture({ confirmAnswers: [true, true] })
await invokeMove(fake)
expect(sessionExists).toHaveBeenCalledWith('ses_a')
expectNothingPushed(fake, importSession)
expect(fake.deps.setPendingWarp).toHaveBeenCalledWith({
kind: 'attach',
target: expect.objectContaining({ repoId: 1, sessionID: 'ses_a', managerUrl: MANAGER_URL }),
})
expect(fake.dispatch).toHaveBeenCalledWith('app.exit')
})
function expectNothingPushed(fake: Fixture) {
expect(fake.managerApi.mirrorCheckouts).not.toHaveBeenCalled()
expect(fake.confirm).not.toHaveBeenCalled()
expect(fake.deps.mirrorUpFast).not.toHaveBeenCalled()
expect(fake.exportSession).not.toHaveBeenCalled()
expect(fake.transfer.importSession).not.toHaveBeenCalled()
}
it('refuses to push when the session is already on the Manager', async () => {
const fake = createFixture({ onManager: ['ses_a'] })
await invokeMove(fake)
expect(fake.transfer.sessionExists).toHaveBeenCalledWith('ses_a')
expectNothingPushed(fake)
expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'error', message: expect.stringContaining('already on the Manager') }))
})
it('refuses to push a subagent session whose parent is not on the Manager', async () => {
const fake = createFakeContext({ location: { directory: '/Users/x/repo' }, parentID: 'ses_parent' })
configureMove(fake)
const { sessionExists, importSession } = stubTransfer()
const fake = createFixture({ session: createSession({ parentID: 'ses_parent' }) })
await invokeMove(fake)
expect(sessionExists).toHaveBeenCalledWith('ses_parent')
expectNothingPushed(fake, importSession)
expect(fake.transfer.sessionExists).toHaveBeenCalledWith('ses_parent')
expectNothingPushed(fake)
expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'error', message: expect.stringContaining('Move the parent session first') }))
})
it('moves a subagent session once its parent is on the Manager', async () => {
const fake = createFakeContext({ location: { directory: '/Users/x/repo' }, parentID: 'ses_parent' })
configureMove(fake)
const { importSession } = stubTransfer({ onManager: ['ses_parent'] })
fake.exportMock.mockResolvedValue(makeTransfer())
const fake = createFixture({ session: createSession({ parentID: 'ses_parent' }), onManager: ['ses_parent'] })
await invokeMove(fake)
expect(mocks.mirrorUpFast).toHaveBeenCalledTimes(1)
expect(importSession).toHaveBeenCalledTimes(1)
expect(fake.deps.mirrorUpFast).toHaveBeenCalledTimes(1)
expect(fake.transfer.importSession).toHaveBeenCalledTimes(1)
})
it('refuses to push when the Manager session check fails', async () => {
const fake = createFakeContext()
configureMove(fake)
const { importSession } = stubTransfer({ existsError: new Error('proxy unreachable') })
const fake = createFixture({ existsError: new Error('proxy unreachable') })
await invokeMove(fake)
expectNothingPushed(fake, importSession)
expectNothingPushed(fake)
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'proxy unreachable' })
})
it('stops before pushing when the Manager lacks the repo proxy route', async () => {
const fake = createFakeContext()
configureMove(fake)
const { importSession } = stubTransfer()
const tooOld = 'OpenCode Manager at https://manager.example is too old for ocm 0.3.0; upgrade the Manager to >= 0.19.0'
mocks.warmRepoProxy.mockRejectedValue(new Error(tooOld))
const fake = createFixture({ proxyError: new Error(tooOld) })
await invokeMove(fake)
expect(mocks.warmRepoProxy).toHaveBeenCalledWith('https://manager.example', 'tok', 1)
expect(fake.deps.warmRepoProxy).toHaveBeenCalledWith(MANAGER_URL, 'tok', 1)
expect(fake.confirm).not.toHaveBeenCalled()
expect(mocks.mirrorUpFast).not.toHaveBeenCalled()
expect(fake.exportMock).not.toHaveBeenCalled()
expect(importSession).not.toHaveBeenCalled()
expect(fake.deps.mirrorUpFast).not.toHaveBeenCalled()
expect(fake.exportSession).not.toHaveBeenCalled()
expect(fake.transfer.importSession).not.toHaveBeenCalled()
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: tooOld })
})
it('refuses to move from a detached HEAD before pushing anything', async () => {
const fake = createFakeContext()
configureMove(fake)
const { importSession } = stubTransfer()
mocks.getBranchName.mockReturnValue(null)
const fake = createFixture({ branch: null })
await invokeMove(fake)
expect(mocks.mirrorCheckouts).not.toHaveBeenCalled()
expect(mocks.mirrorUpFast).not.toHaveBeenCalled()
expect(fake.exportMock).not.toHaveBeenCalled()
expect(importSession).not.toHaveBeenCalled()
expect(fake.managerApi.mirrorCheckouts).not.toHaveBeenCalled()
expect(fake.deps.mirrorUpFast).not.toHaveBeenCalled()
expect(fake.exportSession).not.toHaveBeenCalled()
expect(fake.transfer.importSession).not.toHaveBeenCalled()
expect(fake.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'error', message: expect.stringContaining('detached HEAD') }))
})
it('pushes in place with the strict current-branch guard when the main checkout is safe', async () => {
const fake = createFakeContext()
configureMove(fake)
const { importSession } = stubTransfer()
fake.exportMock.mockResolvedValue(makeTransfer())
const fake = createFixture()
await invokeMove(fake)
expect(mocks.mirrorCheckouts).toHaveBeenCalledWith(1, 'main')
expect(mocks.mirrorUpFast).toHaveBeenCalledWith(
expect(fake.managerApi.mirrorCheckouts).toHaveBeenCalledWith(1, 'main')
expect(fake.deps.mirrorUpFast).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ force: true, requireCurrentBranch: true }),
)
const pushOpts = mocks.mirrorUpFast.mock.calls[0]![1] as { directory?: string; targetBranch?: string }
const pushOpts = vi.mocked(fake.deps.mirrorUpFast).mock.calls[0]![1]
expect(pushOpts.directory).toBeUndefined()
expect(pushOpts.targetBranch).toBeUndefined()
expect(importSession).toHaveBeenCalledWith('/workspace/repos/repo', expect.anything())
expect(fake.transfer.importSession).toHaveBeenCalledWith('/workspace/repos/repo', expect.anything())
})
it('pushes into an existing suffixed worktree directory with the strict current-branch guard', async () => {
const fake = createFakeContext()
configureMove(fake)
const { importSession } = stubTransfer()
fake.exportMock.mockResolvedValue(makeTransfer())
mocks.chooseMoveDestination.mockReturnValue({
kind: 'existing-worktree',
directory: '/workspace/repos/repo-feature-ocm',
branch: 'feature-ocm',
reasons: [],
})
mocks.mirrorUpFast.mockResolvedValue({
repoId: 1,
fullPath: '/workspace/repos/repo-feature-ocm',
branch: 'feature-ocm',
head: null,
created: false,
const fake = createFixture({
destination: { kind: 'existing-worktree', directory: '/workspace/repos/repo-feature-ocm', branch: 'feature-ocm', reasons: [] },
pushed: { repoId: 1, fullPath: '/workspace/repos/repo-feature-ocm', branch: 'feature-ocm', head: null, created: false },
})
await invokeMove(fake)
expect(mocks.mirrorUpFast).toHaveBeenCalledWith(
expect(fake.deps.mirrorUpFast).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
force: true,
@@ -459,59 +421,45 @@ describe('ocm.session.move command', () => {
targetBranch: 'feature-ocm',
}),
)
expect(importSession).toHaveBeenCalledWith('/workspace/repos/repo-feature-ocm', expect.anything())
expect(fake.transfer.importSession).toHaveBeenCalledWith('/workspace/repos/repo-feature-ocm', expect.anything())
})
it('creates a new worktree through the fast push when no safe checkout exists', async () => {
const fake = createFakeContext()
configureMove(fake)
const { importSession } = stubTransfer()
fake.exportMock.mockResolvedValue(makeTransfer())
mocks.chooseMoveDestination.mockReturnValue({
kind: 'new-worktree',
directory: null,
branch: 'feature-ocm',
reasons: ['the server checkout is on main'],
})
mocks.mirrorUpFast.mockResolvedValue({
repoId: 1,
fullPath: '/workspace/repos/repo-feature-ocm',
branch: 'feature-ocm',
head: null,
created: true,
worktreeSetup: { status: 'none' },
const fake = createFixture({
destination: { kind: 'new-worktree', directory: null, branch: 'feature-ocm', reasons: ['the server checkout is on main'] },
pushed: {
repoId: 1,
fullPath: '/workspace/repos/repo-feature-ocm',
branch: 'feature-ocm',
head: null,
created: true,
worktreeSetup: { status: 'none' },
},
})
await invokeMove(fake)
expect(mocks.mirrorUpFast).toHaveBeenCalledWith(
expect(fake.deps.mirrorUpFast).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
force: true,
createWorktree: { targetBranch: 'feature-ocm' },
}),
)
expect(importSession).toHaveBeenCalledWith('/workspace/repos/repo-feature-ocm', expect.anything())
expect(fake.transfer.importSession).toHaveBeenCalledWith('/workspace/repos/repo-feature-ocm', expect.anything())
})
it('warns without aborting when worktree setup fails', async () => {
const fake = createFakeContext()
configureMove(fake)
const { importSession } = stubTransfer()
fake.exportMock.mockResolvedValue(makeTransfer())
mocks.chooseMoveDestination.mockReturnValue({
kind: 'new-worktree',
directory: null,
branch: 'feature-ocm',
reasons: [],
})
mocks.mirrorUpFast.mockResolvedValue({
repoId: 1,
fullPath: '/workspace/repos/repo-feature-ocm',
branch: 'feature-ocm',
head: null,
created: true,
worktreeSetup: { status: 'failed', error: 'setup script exploded' },
const fake = createFixture({
destination: { kind: 'new-worktree', directory: null, branch: 'feature-ocm', reasons: [] },
pushed: {
repoId: 1,
fullPath: '/workspace/repos/repo-feature-ocm',
branch: 'feature-ocm',
head: null,
created: true,
worktreeSetup: { status: 'failed', error: 'setup script exploded' },
},
})
await invokeMove(fake)
@@ -520,6 +468,6 @@ describe('ocm.session.move command', () => {
variant: 'warning',
message: expect.stringContaining('setup script exploded'),
}))
expect(importSession).toHaveBeenCalledWith('/workspace/repos/repo-feature-ocm', expect.anything())
expect(fake.transfer.importSession).toHaveBeenCalledWith('/workspace/repos/repo-feature-ocm', expect.anything())
})
})