mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
section 3: Phase 3: Shared Manager auth helper and Manager API client f
This commit is contained in:
1 parent
b316cb960c
commit
a99e69f653
5 files changed
+427
-27
No files matched your search
+106
-2
@@ -3,8 +3,15 @@ import { Readable } from 'stream'
|
||||
import {
|
||||
MirrorTargetEnsureResponseSchema,
|
||||
MirrorTargetPlanResponseSchema,
|
||||
MultiRunSchema,
|
||||
SessionGoalSchema,
|
||||
type FuseMultiRunRequest,
|
||||
type LaunchMultiRunRequest,
|
||||
type MirrorTargetEnsureResponse,
|
||||
type MirrorTargetPlanResponse,
|
||||
type MultiRun,
|
||||
type SessionGoal,
|
||||
type StartSessionGoalRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
export interface MirrorBeginOpts {
|
||||
@@ -75,23 +82,30 @@ export class ManagerApiError extends Error {
|
||||
public readonly status: number,
|
||||
public readonly code: string | null,
|
||||
public readonly operation: string,
|
||||
public readonly details: unknown = null,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'ManagerApiError'
|
||||
}
|
||||
}
|
||||
|
||||
export function isManagerRouteMissing(error: unknown): boolean {
|
||||
return error instanceof ManagerApiError && error.status === 404 && error.code === null
|
||||
}
|
||||
|
||||
async function formatErrorResponse(res: Response, operation: string): Promise<ManagerApiError> {
|
||||
const text = await res.text().catch(() => '')
|
||||
let code: string | null = null
|
||||
let detail = text
|
||||
let details: unknown = null
|
||||
if (text) {
|
||||
try {
|
||||
const parsed = JSON.parse(text) as { error?: unknown; message?: unknown }
|
||||
const parsed = JSON.parse(text) as { error?: unknown; message?: unknown; details?: unknown }
|
||||
const errField = typeof parsed.error === 'string' ? parsed.error : null
|
||||
const msgField = typeof parsed.message === 'string' ? parsed.message : null
|
||||
code = errField
|
||||
detail = msgField ?? errField ?? text
|
||||
details = parsed.details ?? null
|
||||
} catch {
|
||||
/* not JSON, keep raw text */
|
||||
}
|
||||
@@ -99,7 +113,7 @@ async function formatErrorResponse(res: Response, operation: string): Promise<Ma
|
||||
const message = detail
|
||||
? `${operation} failed (${res.status}): ${detail}`
|
||||
: `${operation} failed (${res.status})`
|
||||
return new ManagerApiError(message, res.status, code, operation)
|
||||
return new ManagerApiError(message, res.status, code, operation, details)
|
||||
}
|
||||
|
||||
export class ManagerApi {
|
||||
@@ -255,4 +269,94 @@ export class ManagerApi {
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror patch snapshot')
|
||||
return (await res.json()) as MirrorPatchSnapshot
|
||||
}
|
||||
|
||||
async getLatestSessionGoal(sessionId: string): Promise<SessionGoal | null> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/session-goals?sessionId=${encodeURIComponent(sessionId)}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'read session goal')
|
||||
const body = (await res.json()) as { goal: unknown }
|
||||
return SessionGoalSchema.nullable().parse(body.goal)
|
||||
}
|
||||
|
||||
async startSessionGoal(input: StartSessionGoalRequest): Promise<SessionGoal> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/session-goals`, {
|
||||
method: 'POST',
|
||||
headers: { ...this.headers(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'start session goal')
|
||||
const body = (await res.json()) as { goal: unknown }
|
||||
return SessionGoalSchema.parse(body.goal)
|
||||
}
|
||||
|
||||
private async runSessionGoalAction(id: number, action: 'pause' | 'resume' | 'cancel'): Promise<SessionGoal> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/session-goals/${encodeURIComponent(id)}/${action}`, {
|
||||
method: 'POST',
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, `${action} session goal`)
|
||||
const body = (await res.json()) as { goal: unknown }
|
||||
return SessionGoalSchema.parse(body.goal)
|
||||
}
|
||||
|
||||
pauseSessionGoal(id: number): Promise<SessionGoal> {
|
||||
return this.runSessionGoalAction(id, 'pause')
|
||||
}
|
||||
|
||||
resumeSessionGoal(id: number): Promise<SessionGoal> {
|
||||
return this.runSessionGoalAction(id, 'resume')
|
||||
}
|
||||
|
||||
cancelSessionGoal(id: number): Promise<SessionGoal> {
|
||||
return this.runSessionGoalAction(id, 'cancel')
|
||||
}
|
||||
|
||||
async listMultiRuns(repoId: number): Promise<MultiRun[]> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/multi-runs?repoId=${encodeURIComponent(repoId)}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'list multi-runs')
|
||||
const body = (await res.json()) as { runs: unknown }
|
||||
return MultiRunSchema.array().parse(body.runs)
|
||||
}
|
||||
|
||||
async launchMultiRun(request: LaunchMultiRunRequest): Promise<MultiRun> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/multi-runs`, {
|
||||
method: 'POST',
|
||||
headers: { ...this.headers(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'launch multi-run')
|
||||
const body = (await res.json()) as { run: unknown }
|
||||
return MultiRunSchema.parse(body.run)
|
||||
}
|
||||
|
||||
async fuseMultiRun(runId: number, request: FuseMultiRunRequest): Promise<MultiRun> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/multi-runs/${encodeURIComponent(runId)}/fusions`, {
|
||||
method: 'POST',
|
||||
headers: { ...this.headers(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'fuse multi-run')
|
||||
const body = (await res.json()) as { run: unknown }
|
||||
return MultiRunSchema.parse(body.run)
|
||||
}
|
||||
|
||||
async discardMultiRunEntry(runId: number, entryId: number): Promise<MultiRun> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/multi-runs/${encodeURIComponent(runId)}/entries/${encodeURIComponent(entryId)}/discard`, {
|
||||
method: 'POST',
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'discard multi-run entry')
|
||||
const body = (await res.json()) as { run: unknown }
|
||||
return MultiRunSchema.parse(body.run)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { readState } from './state.js'
|
||||
import { getToken } from './internal-token-store.js'
|
||||
import { TokenStoreError } from './token-store.js'
|
||||
|
||||
export type ManagerAuth =
|
||||
| { ok: true; managerUrl: string; token: string }
|
||||
| { ok: false; message: string }
|
||||
|
||||
export async function resolveManagerAuth(
|
||||
managerUrl: string | undefined = readState()?.managerUrl,
|
||||
): Promise<ManagerAuth> {
|
||||
if (!managerUrl) {
|
||||
return { ok: false, message: 'No manager configured. Run `ocm login <url>` first.' }
|
||||
}
|
||||
|
||||
let token: string | null
|
||||
try {
|
||||
token = await getToken(managerUrl)
|
||||
} catch (err) {
|
||||
const reason = err instanceof TokenStoreError ? err.message : String(err)
|
||||
return { ok: false, message: `Token store unavailable: ${reason}` }
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
return { ok: false, message: `No token stored. Run \`ocm login ${managerUrl}\`.` }
|
||||
}
|
||||
|
||||
return { ok: true, managerUrl, token }
|
||||
}
|
||||
+11
-25
@@ -1,7 +1,6 @@
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
import { readInstallNotice, readState } from './state.js'
|
||||
import { getToken } from './internal-token-store.js'
|
||||
import { TokenStoreError } from './token-store.js'
|
||||
import { readInstallNotice } from './state.js'
|
||||
import { resolveManagerAuth } from './manager-auth.js'
|
||||
import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js'
|
||||
import { ManagerApi, ManagerApiError } from './manager-api.js'
|
||||
import type { MirrorTargetPlanResponse } from '@opencode-manager/shared/schemas'
|
||||
@@ -116,26 +115,13 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
|
||||
return
|
||||
}
|
||||
|
||||
const state = readState()
|
||||
if (!state?.managerUrl) {
|
||||
context.ui.toast.show({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
|
||||
const auth = await resolveManagerAuth()
|
||||
if (!auth.ok) {
|
||||
context.ui.toast.show({ variant: 'error', message: auth.message })
|
||||
return
|
||||
}
|
||||
|
||||
let token: string | null
|
||||
try {
|
||||
token = await getToken(state.managerUrl)
|
||||
} catch (err) {
|
||||
const reason = err instanceof TokenStoreError ? err.message : String(err)
|
||||
context.ui.toast.show({ variant: 'error', message: `Token store unavailable: ${reason}` })
|
||||
return
|
||||
}
|
||||
if (!token) {
|
||||
context.ui.toast.show({ variant: 'error', message: `No token stored. Run \`ocm login ${state.managerUrl}\`.` })
|
||||
return
|
||||
}
|
||||
|
||||
const repos = await fetchRepos(state.managerUrl, token)
|
||||
const repos = await fetchRepos(auth.managerUrl, auth.token)
|
||||
const plan = await prepareMirror(session.location.directory, toRemoteRepoSummaries(repos))
|
||||
|
||||
if (plan.matched.length === 0) {
|
||||
@@ -150,16 +136,16 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
|
||||
const matchedRepoId = matched.repoId
|
||||
const remoteRepo = repos.find((r) => r.repoId === matchedRepoId)!
|
||||
|
||||
await warmRepoProxy(state.managerUrl, token, matchedRepoId)
|
||||
await warmRepoProxy(auth.managerUrl, auth.token, matchedRepoId)
|
||||
|
||||
const transfer = createManagerSessionTransfer(state.managerUrl, token)
|
||||
const transfer = createManagerSessionTransfer(auth.managerUrl, auth.token)
|
||||
const blocker = await describeMoveBlocker(transfer, sessionID, session.parentID)
|
||||
if (blocker) {
|
||||
context.ui.toast.show({ variant: 'error', message: blocker })
|
||||
return
|
||||
}
|
||||
|
||||
const managerApi = new ManagerApi(state.managerUrl, token)
|
||||
const managerApi = new ManagerApi(auth.managerUrl, auth.token)
|
||||
const target = await resolveMoveTarget(managerApi, matched, remoteRepo.directory, localBranch)
|
||||
const discardReasons = target.repoId === null ? [] : await describeRemoteDiscard(plan.repoRoot, managerApi, target.repoId)
|
||||
|
||||
@@ -199,8 +185,8 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
|
||||
setMoveProgress(null)
|
||||
const warp = await confirmDialog(context, { title: 'Attach to moved session?', message: 'Exit this TUI and attach to the moved session on the Manager now?' })
|
||||
if (warp) {
|
||||
await warmRepoProxy(state.managerUrl, token, pushed.repoId)
|
||||
setPendingWarp({ managerUrl: state.managerUrl, token, repoId: pushed.repoId, sessionID: result.sessionID, repoName: matched.name })
|
||||
await warmRepoProxy(auth.managerUrl, auth.token, pushed.repoId)
|
||||
setPendingWarp({ managerUrl: auth.managerUrl, token: auth.token, repoId: pushed.repoId, sessionID: result.sessionID, repoName: matched.name })
|
||||
context.keymap.dispatch('app.exit')
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { ManagerApi, ManagerApiError, isManagerRouteMissing } from '../src/manager-api.js'
|
||||
import type { MultiRun, SessionGoal } from '@opencode-manager/shared/schemas'
|
||||
|
||||
const BASE_URL = 'http://localhost:5003'
|
||||
|
||||
const goal: SessionGoal = {
|
||||
id: 7,
|
||||
sessionId: 'ses_1',
|
||||
directory: '/repo',
|
||||
objective: 'fix the flaky test',
|
||||
status: 'active',
|
||||
stopReason: null,
|
||||
turnState: 'waiting',
|
||||
continuationCount: 0,
|
||||
maxContinuations: 10,
|
||||
tokenBudget: null,
|
||||
tokensUsed: 0,
|
||||
consecutiveBlocked: 0,
|
||||
lastVerdict: null,
|
||||
lastReason: null,
|
||||
createdAt: 1,
|
||||
updatedAt: 2,
|
||||
finishedAt: null,
|
||||
}
|
||||
|
||||
const run: MultiRun = {
|
||||
id: 3,
|
||||
repoId: 1,
|
||||
name: 'sweep',
|
||||
prompt: 'hello',
|
||||
isolated: true,
|
||||
baseRef: null,
|
||||
createdAt: 1,
|
||||
entries: [],
|
||||
fusions: [],
|
||||
}
|
||||
|
||||
function okResponse(body: unknown) {
|
||||
return { ok: true, status: 200, json: () => Promise.resolve(body), text: () => Promise.resolve('') }
|
||||
}
|
||||
|
||||
function errorResponse(status: number, text: string) {
|
||||
return { ok: false, status, json: () => Promise.reject(new Error('no json')), text: () => Promise.resolve(text) }
|
||||
}
|
||||
|
||||
function stubFetch(response: unknown) {
|
||||
const fetchMock = vi.fn().mockResolvedValue(response)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
return fetchMock
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('ManagerApi session goals', () => {
|
||||
const api = new ManagerApi(BASE_URL, 'tok')
|
||||
|
||||
it('reads the latest goal for a session', async () => {
|
||||
const fetchMock = stubFetch(okResponse({ goal }))
|
||||
|
||||
await expect(api.getLatestSessionGoal('ses_1')).resolves.toEqual(goal)
|
||||
expect(fetchMock).toHaveBeenCalledWith(`${BASE_URL}/api/internal/session-goals?sessionId=ses_1`, {
|
||||
headers: { Authorization: 'Bearer tok' },
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null when the session has no goal', async () => {
|
||||
stubFetch(okResponse({ goal: null }))
|
||||
|
||||
await expect(api.getLatestSessionGoal('ses_1')).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('starts a goal', async () => {
|
||||
const fetchMock = stubFetch(okResponse({ goal }))
|
||||
const input = { sessionId: 'ses_1', directory: '/repo', objective: 'fix it' }
|
||||
|
||||
await expect(api.startSessionGoal(input)).resolves.toEqual(goal)
|
||||
expect(fetchMock).toHaveBeenCalledWith(`${BASE_URL}/api/internal/session-goals`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer tok', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
})
|
||||
|
||||
it('pauses, resumes, and cancels a goal through the action route', async () => {
|
||||
const fetchMock = stubFetch(okResponse({ goal }))
|
||||
|
||||
await expect(api.pauseSessionGoal(7)).resolves.toEqual(goal)
|
||||
await expect(api.resumeSessionGoal(7)).resolves.toEqual(goal)
|
||||
await expect(api.cancelSessionGoal(7)).resolves.toEqual(goal)
|
||||
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, `${BASE_URL}/api/internal/session-goals/7/pause`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer tok' },
|
||||
})
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, `${BASE_URL}/api/internal/session-goals/7/resume`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer tok' },
|
||||
})
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, `${BASE_URL}/api/internal/session-goals/7/cancel`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer tok' },
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a goal response that fails schema validation', async () => {
|
||||
stubFetch(okResponse({ goal: { ...goal, status: 'bogus' } }))
|
||||
|
||||
await expect(api.getLatestSessionGoal('ses_1')).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ManagerApi multi-runs', () => {
|
||||
const api = new ManagerApi(BASE_URL, 'tok')
|
||||
|
||||
it('lists runs for a repo', async () => {
|
||||
const fetchMock = stubFetch(okResponse({ runs: [run] }))
|
||||
|
||||
await expect(api.listMultiRuns(1)).resolves.toEqual([run])
|
||||
expect(fetchMock).toHaveBeenCalledWith(`${BASE_URL}/api/internal/multi-runs?repoId=1`, {
|
||||
headers: { Authorization: 'Bearer tok' },
|
||||
})
|
||||
})
|
||||
|
||||
it('launches a run', async () => {
|
||||
const fetchMock = stubFetch(okResponse({ run }))
|
||||
const request = { repoId: 1, name: 'sweep', prompt: 'hello', models: ['a/b'], isolate: true }
|
||||
|
||||
await expect(api.launchMultiRun(request)).resolves.toEqual(run)
|
||||
expect(fetchMock).toHaveBeenCalledWith(`${BASE_URL}/api/internal/multi-runs`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer tok', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
})
|
||||
})
|
||||
|
||||
it('fuses selected entries', async () => {
|
||||
const fetchMock = stubFetch(okResponse({ run }))
|
||||
const request = { requestId: '11111111-1111-4111-8111-111111111111', entryIds: [1, 2], model: 'a/b', isolate: true }
|
||||
|
||||
await expect(api.fuseMultiRun(3, request)).resolves.toEqual(run)
|
||||
expect(fetchMock).toHaveBeenCalledWith(`${BASE_URL}/api/internal/multi-runs/3/fusions`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer tok', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
})
|
||||
})
|
||||
|
||||
it('discards an entry', async () => {
|
||||
const fetchMock = stubFetch(okResponse({ run }))
|
||||
|
||||
await expect(api.discardMultiRunEntry(3, 4)).resolves.toEqual(run)
|
||||
expect(fetchMock).toHaveBeenCalledWith(`${BASE_URL}/api/internal/multi-runs/3/entries/4/discard`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer tok' },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('ManagerApiError', () => {
|
||||
const api = new ManagerApi(BASE_URL, 'tok')
|
||||
|
||||
it('carries a JSON error code and details', async () => {
|
||||
const details = { unavailableSources: [{ entryId: 1, model: 'a/b', reason: 'running', message: 'still running' }] }
|
||||
stubFetch(errorResponse(409, JSON.stringify({ error: 'Fusion unavailable', details })))
|
||||
|
||||
const error = await api.fuseMultiRun(3, { requestId: '11111111-1111-4111-8111-111111111111', entryIds: [1, 2], model: 'a/b', isolate: true }).catch((err) => err)
|
||||
|
||||
expect(error).toBeInstanceOf(ManagerApiError)
|
||||
expect((error as ManagerApiError).status).toBe(409)
|
||||
expect((error as ManagerApiError).code).toBe('Fusion unavailable')
|
||||
expect((error as ManagerApiError).details).toEqual(details)
|
||||
})
|
||||
|
||||
it('leaves details null when the error body has none', async () => {
|
||||
stubFetch(errorResponse(400, JSON.stringify({ error: 'Invalid request' })))
|
||||
|
||||
const error = await api.listMultiRuns(1).catch((err) => err)
|
||||
|
||||
expect((error as ManagerApiError).details).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
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'))
|
||||
|
||||
const error = await api.listMultiRuns(1).catch((err) => err)
|
||||
|
||||
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' })))
|
||||
|
||||
const error = await api.listMultiRuns(1).catch((err) => err)
|
||||
|
||||
expect(isManagerRouteMissing(error)).toBe(false)
|
||||
})
|
||||
|
||||
it('is false for non-404 failures and unrelated errors', () => {
|
||||
expect(isManagerRouteMissing(new ManagerApiError('x', 500, null, 'op'))).toBe(false)
|
||||
expect(isManagerRouteMissing(new Error('nope'))).toBe(false)
|
||||
expect(isManagerRouteMissing(null)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { resolveManagerAuth } from '../src/manager-auth.js'
|
||||
import { TokenStoreError } from '../src/token-store.js'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
readState: vi.fn(),
|
||||
getToken: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../src/state.js', () => ({ readState: mocks.readState }))
|
||||
vi.mock('../src/internal-token-store.js', () => ({ getToken: mocks.getToken }))
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
})
|
||||
|
||||
describe('resolveManagerAuth', () => {
|
||||
it('reports no manager when no state is stored', async () => {
|
||||
mocks.readState.mockReturnValue(null)
|
||||
|
||||
await expect(resolveManagerAuth()).resolves.toEqual({
|
||||
ok: false,
|
||||
message: 'No manager configured. Run `ocm login <url>` first.',
|
||||
})
|
||||
expect(mocks.getToken).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not read state when given an explicit manager URL', async () => {
|
||||
mocks.readState.mockReturnValue(null)
|
||||
mocks.getToken.mockResolvedValue('tok')
|
||||
|
||||
await expect(resolveManagerAuth('https://mgr.example')).resolves.toEqual({
|
||||
ok: true,
|
||||
managerUrl: 'https://mgr.example',
|
||||
token: 'tok',
|
||||
})
|
||||
expect(mocks.readState).not.toHaveBeenCalled()
|
||||
expect(mocks.getToken).toHaveBeenCalledWith('https://mgr.example')
|
||||
})
|
||||
|
||||
it('reports a token store failure', async () => {
|
||||
mocks.readState.mockReturnValue({ managerUrl: 'https://mgr.example' })
|
||||
mocks.getToken.mockRejectedValue(new TokenStoreError('keychain locked', 'keychain'))
|
||||
|
||||
await expect(resolveManagerAuth()).resolves.toEqual({
|
||||
ok: false,
|
||||
message: 'Token store unavailable: keychain locked',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports a missing token', async () => {
|
||||
mocks.readState.mockReturnValue({ managerUrl: 'https://mgr.example' })
|
||||
mocks.getToken.mockResolvedValue(null)
|
||||
|
||||
await expect(resolveManagerAuth()).resolves.toEqual({
|
||||
ok: false,
|
||||
message: 'No token stored. 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({
|
||||
ok: true,
|
||||
managerUrl: 'https://mgr.example',
|
||||
token: 'tok',
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user