refactor(goals): replace the Manager session-goal API with OpenCode built-in /goal

This commit is contained in:
Chris Scott committed 2026-10-29 12:38:39 -04:00
1 parent c8647c1eec
commit cbe92c92ad
84 files changed
+2099 -6321

No files matched your search

-419
View File
@@ -1,419 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { SESSION_GOAL_POLL_INTERVAL_MS, type SessionGoal } from '@opencode-manager/shared/schemas'
import { createGoalStore } from '../src/goal-store.js'
import { goal } from './helpers/goal-fixture.js'
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
describe('createGoalStore', () => {
it('defaults the poll interval to the shared session goal interval', async () => {
expect(SESSION_GOAL_POLL_INTERVAL_MS).toBe(3000)
const load = vi.fn().mockResolvedValue(goal({ status: 'active' }))
const store = createGoalStore({ load, onOutcome: vi.fn() })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
expect(load).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(SESSION_GOAL_POLL_INTERVAL_MS)
expect(load).toHaveBeenCalledTimes(2)
unwatch()
})
it('loads once on watch and notifies the listener with the goal', async () => {
const active = goal()
const load = vi.fn().mockResolvedValue(active)
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const listener = vi.fn()
const unwatch = store.watch('ses_a', listener)
await vi.advanceTimersByTimeAsync(0)
expect(load).toHaveBeenCalledTimes(1)
expect(load).toHaveBeenCalledWith('ses_a', expect.any(AbortSignal))
expect(listener).toHaveBeenCalledWith(active)
unwatch()
})
it('notifies the listener with null when no goal exists', async () => {
const load = vi.fn().mockResolvedValue(null)
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const listener = vi.fn()
const unwatch = store.watch('ses_a', listener)
await vi.advanceTimersByTimeAsync(0)
expect(listener).toHaveBeenCalledWith(null)
unwatch()
})
it('polls while the goal is active', async () => {
const load = vi.fn().mockResolvedValue(goal({ status: 'active' }))
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
expect(load).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(3)
unwatch()
})
it('keeps polling while the goal is paused', async () => {
const load = vi.fn().mockResolvedValue(goal({ status: 'paused' }))
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(2)
unwatch()
})
it('stops polling when the goal is terminal', async () => {
const load = vi.fn().mockResolvedValue(goal({ status: 'completed' }))
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
await vi.advanceTimersByTimeAsync(1000)
expect(load).toHaveBeenCalledTimes(1)
unwatch()
})
it('updates watchers immediately on set', async () => {
const load = vi.fn().mockResolvedValue(null)
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const listener = vi.fn()
const unwatch = store.watch('ses_a', listener)
await vi.advanceTimersByTimeAsync(0)
listener.mockClear()
const next = goal({ status: 'active' })
store.set(next)
expect(listener).toHaveBeenCalledWith(next)
unwatch()
})
it('starts polling when set installs an active goal', async () => {
const load = vi.fn().mockResolvedValue(null)
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
expect(load).toHaveBeenCalledTimes(1)
store.set(goal({ status: 'active' }))
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(2)
unwatch()
})
it('does not start a second load while one is in flight', async () => {
let resolveLoad: (goal: SessionGoal | null) => void = () => {}
const load = vi.fn(
() =>
new Promise<SessionGoal | null>((resolve) => {
resolveLoad = resolve
}),
)
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
expect(load).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1000)
expect(load).toHaveBeenCalledTimes(1)
resolveLoad(goal({ status: 'active' }))
await vi.advanceTimersByTimeAsync(0)
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(2)
unwatch()
})
it('drops a stale load that resolves after set installs newer state', async () => {
let resolveLoad: (goal: SessionGoal | null) => void = () => {}
const load = vi.fn(
() =>
new Promise<SessionGoal | null>((resolve) => {
resolveLoad = resolve
}),
)
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const listener = vi.fn()
const unwatch = store.watch('ses_a', listener)
const installed = goal({ status: 'paused' })
store.set(installed)
expect(listener).toHaveBeenLastCalledWith(installed)
resolveLoad(goal({ status: 'active' }))
await vi.advanceTimersByTimeAsync(0)
expect(listener).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenLastCalledWith(installed)
unwatch()
})
it('backs off exponentially on load errors and resets on success', async () => {
const load = vi
.fn()
.mockRejectedValueOnce(new Error('offline'))
.mockRejectedValueOnce(new Error('offline'))
.mockResolvedValue(goal({ status: 'active' }))
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
expect(load).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(300)
expect(load).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(3)
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(4)
unwatch()
})
it('aborts the in-flight load when the last listener leaves without an open goal', async () => {
let captured: AbortSignal | undefined
const load = vi.fn((_sessionID: string, signal: AbortSignal) => {
captured = signal
return new Promise<SessionGoal | null>(() => {})
})
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
expect(captured?.aborted).toBe(false)
unwatch()
expect(captured?.aborted).toBe(true)
expect(load).toHaveBeenCalledTimes(1)
})
it('fires onOutcome once when a watched goal reaches a terminal status', async () => {
const active = goal({ status: 'active' })
const completed = goal({ status: 'completed' })
const load = vi.fn().mockResolvedValue(active)
const onOutcome = vi.fn()
const store = createGoalStore({ load, onOutcome, pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
load.mockResolvedValue(completed)
await vi.advanceTimersByTimeAsync(100)
expect(onOutcome).toHaveBeenCalledTimes(1)
expect(onOutcome).toHaveBeenCalledWith(completed)
await vi.advanceTimersByTimeAsync(1000)
expect(onOutcome).toHaveBeenCalledTimes(1)
unwatch()
})
it('fires onOutcome when a paused goal is cancelled through set', async () => {
const paused = goal({ status: 'paused' })
const stopped = goal({ status: 'stopped', stopReason: 'cancelled' })
const load = vi.fn().mockResolvedValue(paused)
const onOutcome = vi.fn()
const store = createGoalStore({ load, onOutcome, pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
store.set(stopped)
expect(onOutcome).toHaveBeenCalledTimes(1)
expect(onOutcome).toHaveBeenCalledWith(stopped)
unwatch()
})
it('fires onOutcome for each new goal id followed in the same entry', async () => {
const load = vi.fn().mockResolvedValue(goal({ status: 'completed' }))
const onOutcome = vi.fn()
const store = createGoalStore({ load, onOutcome, pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
const first = goal({ id: 7, status: 'active' })
const firstDone = goal({ id: 7, status: 'completed' })
store.set(first)
store.set(firstDone)
expect(onOutcome).toHaveBeenCalledTimes(1)
const second = goal({ id: 8, status: 'active' })
const secondDone = goal({ id: 8, status: 'completed' })
store.set(second)
store.set(secondDone)
expect(onOutcome).toHaveBeenCalledTimes(2)
expect(onOutcome).toHaveBeenLastCalledWith(secondDone)
unwatch()
})
it('does not fire onOutcome for a goal that is already terminal', async () => {
const load = vi.fn().mockResolvedValue(goal({ status: 'completed' }))
const onOutcome = vi.fn()
const store = createGoalStore({ load, onOutcome, pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
expect(onOutcome).not.toHaveBeenCalled()
unwatch()
})
it('keeps following an open goal in the background and fires onOutcome once after the last listener leaves', async () => {
const active = goal({ status: 'active' })
const completed = goal({ status: 'completed' })
const load = vi.fn().mockResolvedValueOnce(active).mockResolvedValue(completed)
const onOutcome = vi.fn()
const store = createGoalStore({ load, onOutcome, pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
expect(load).toHaveBeenCalledTimes(1)
unwatch()
await vi.advanceTimersByTimeAsync(14999)
expect(load).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(load).toHaveBeenCalledTimes(2)
expect(onOutcome).toHaveBeenCalledTimes(1)
expect(onOutcome).toHaveBeenCalledWith(completed)
await vi.advanceTimersByTimeAsync(60000)
expect(load).toHaveBeenCalledTimes(2)
expect(onOutcome).toHaveBeenCalledTimes(1)
})
it('returns to foreground polling when a listener re-subscribes', async () => {
const load = vi.fn().mockResolvedValue(goal({ status: 'active' }))
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
expect(load).toHaveBeenCalledTimes(1)
unwatch()
await vi.advanceTimersByTimeAsync(5000)
expect(load).toHaveBeenCalledTimes(1)
const unwatchAgain = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
expect(load).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(3)
unwatchAgain()
})
it('keeps the last goal and polling when a reload fails on an active goal', async () => {
const active = goal({ status: 'active' })
const load = vi.fn().mockResolvedValue(active)
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const listener = vi.fn()
const unwatch = store.watch('ses_a', listener)
await vi.advanceTimersByTimeAsync(0)
load.mockRejectedValue(new Error('offline'))
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(2)
expect(listener).toHaveBeenLastCalledWith(active)
await vi.advanceTimersByTimeAsync(200)
expect(load).toHaveBeenCalledTimes(3)
unwatch()
})
it('stops polling when the last listener unsubscribes', async () => {
const load = vi.fn().mockResolvedValue(goal({ status: 'active' }))
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const unwatch = store.watch('ses_a', vi.fn())
await vi.advanceTimersByTimeAsync(0)
expect(load).toHaveBeenCalledTimes(1)
unwatch()
await vi.advanceTimersByTimeAsync(1000)
expect(load).toHaveBeenCalledTimes(1)
})
it('does not resume polling when an in-flight load resolves after the last listener unsubscribes', async () => {
let resolveLoad: (goal: SessionGoal | null) => void = () => {}
const load = vi.fn(
() =>
new Promise<SessionGoal | null>((resolve) => {
resolveLoad = resolve
}),
)
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 20 })
const unwatch = store.watch('ses_a', vi.fn())
expect(load).toHaveBeenCalledTimes(1)
unwatch()
resolveLoad(goal({ status: 'active' }))
await vi.advanceTimersByTimeAsync(0)
await vi.advanceTimersByTimeAsync(200)
expect(load).toHaveBeenCalledTimes(1)
})
it('does not start polling when set targets an unwatched session', async () => {
const load = vi.fn().mockResolvedValue(goal({ status: 'active' }))
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 20 })
store.set(goal({ status: 'active' }))
await vi.advanceTimersByTimeAsync(200)
expect(load).not.toHaveBeenCalled()
})
it('keeps polling while another listener remains', async () => {
const load = vi.fn().mockResolvedValue(goal({ status: 'active' }))
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const second = vi.fn()
const unwatchFirst = store.watch('ses_a', vi.fn())
const unwatchSecond = store.watch('ses_a', second)
await vi.advanceTimersByTimeAsync(0)
unwatchFirst()
load.mockClear()
await vi.advanceTimersByTimeAsync(100)
expect(load).toHaveBeenCalledTimes(1)
expect(second).toHaveBeenCalled()
unwatchSecond()
})
})
-24
View File
@@ -1,24 +0,0 @@
import type { SessionGoal } from '@opencode-manager/shared/schemas'
export function goal(overrides: Partial<SessionGoal> = {}): SessionGoal {
return {
id: 7,
sessionId: 'ses_a',
directory: '/repo',
objective: 'fix it',
status: 'active',
stopReason: null,
turnState: 'waiting',
continuationCount: 0,
maxContinuations: 5,
tokenBudget: null,
tokensUsed: 0,
consecutiveBlocked: 0,
lastVerdict: null,
lastReason: null,
createdAt: 1,
updatedAt: 1,
finishedAt: null,
...overrides,
}
}
+3 -109
View File
@@ -1,30 +1,9 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { ManagerApi, ManagerApiError, isManagerRouteMissing, MANAGER_FEATURE_MISSING } from '../src/manager-api.js'
import type { MultiRun, SessionGoal } from '@opencode-manager/shared/schemas'
import type { MultiRun } from '@opencode-manager/shared/schemas'
const BASE_URL = 'http://localhost:5003'
const goal: SessionGoal = {
id: 7,
sessionId: 'ses_1',
serverId: 'local',
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,
@@ -57,76 +36,6 @@ 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('forwards the abort signal to fetch', async () => {
const fetchMock = stubFetch(okResponse({ goal }))
const controller = new AbortController()
await api.getLatestSessionGoal('ses_1', controller.signal)
expect(fetchMock).toHaveBeenCalledWith(`${BASE_URL}/api/internal/session-goals?sessionId=ses_1`, {
headers: { Authorization: 'Bearer tok' },
signal: controller.signal,
})
})
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')
@@ -264,21 +173,6 @@ describe('ManagerApi feature support', () => {
expect((error as ManagerApiError).code).toBeNull()
expect(isManagerRouteMissing(error)).toBe(false)
})
it('forwards the caller abort signal to the token probe', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(errorResponse(401, JSON.stringify({ error: 'Unauthorized' })))
.mockResolvedValueOnce(okResponse({ workspaces: [] }))
vi.stubGlobal('fetch', fetchMock)
const controller = new AbortController()
await api.getLatestSessionGoal('ses_1', controller.signal).catch(() => undefined)
expect(fetchMock).toHaveBeenNthCalledWith(2, `${BASE_URL}/api/internal/opencode-workspaces`, {
headers: { Authorization: 'Bearer tok' },
signal: controller.signal,
})
})
})
describe('ManagerApi mirror routes', () => {
@@ -301,7 +195,7 @@ describe('ManagerApi mirror routes', () => {
})
})
it('keeps the goal and multi-run feature message unchanged', async () => {
it('keeps the multi-run feature message unchanged', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(errorResponse(401, JSON.stringify({ error: 'Unauthorized' })))
.mockResolvedValueOnce(okResponse({ workspaces: [] }))
@@ -310,7 +204,7 @@ describe('ManagerApi mirror routes', () => {
const error = await api.listMultiRuns(1).catch((err) => err)
expect((error as ManagerApiError).code).toBe(MANAGER_FEATURE_MISSING)
expect((error as ManagerApiError).message).toContain('too old for ocm goals and multi-runs')
expect((error as ManagerApiError).message).toContain('too old for ocm multi-runs')
})
it('sends the directory query on mirrorHead and mirrorContains', async () => {
+58
View File
@@ -0,0 +1,58 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { parseSemver } from '@opencode-manager/shared/utils'
import { describe, expect, it } from 'vitest'
interface PackageManifest {
version: string
devDependencies: Record<string, string>
peerDependencies: Record<string, string>
peerDependenciesMeta: Record<string, { optional?: boolean }>
}
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
}
/**
* Derives the minor-line peer range for a plugin's exact dependency pin.
*
* A `0.x.y` pin is constrained to its minor line; a pin at major `1` or above
* is constrained to its major line.
*/
function deriveMinorLineRange(pin: string): string {
const parsed = parseSemver(pin)
if (!parsed || parsed.prerelease.length > 0) {
throw new Error(`Cannot derive a peer range from pin "${pin}"`)
}
const { major, minor } = parsed
if (major === 0) {
return `>=0.${minor}.0 <0.${minor + 1}.0`
}
return `>=${pin} <${major + 1}.0.0`
}
const ocmManifest = readManifest(join(__dirname, '..', 'package.json'))
const pluginManifest = readManifest(
join(__dirname, '..', 'node_modules', '@opencode', 'plugin', 'package.json'),
)
describe('ocm-cli package compatibility with the installed @opencode/plugin', () => {
for (const name of PINNED_PACKAGES) {
it(`${name} matches the plugin peer pin`, () => {
const pluginPin = pluginManifest.peerDependencies[name]
expect(ocmManifest.devDependencies[name]).toBe(pluginPin)
expect(ocmManifest.peerDependencies[name]).toBe(deriveMinorLineRange(pluginPin))
expect(ocmManifest.peerDependenciesMeta[name]?.optional).toBe(true)
})
}
it('@opencode/plugin devDependency matches the installed plugin version', () => {
expect(ocmManifest.devDependencies['@opencode/plugin']).toBe(pluginManifest.version)
})
})
-415
View File
@@ -1,415 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { Context } from '@opencode/plugin/tui/context'
import type { SessionGoal } from '@opencode-manager/shared/schemas'
import {
runGoalCommand,
formatGoalStatus,
goalObjectiveSummary,
goalOutcomeToast,
parseGoalForm,
GOALS_ATTACH_REQUIRED,
GOALS_ROUTE_MISSING,
} from '../src/tui-goal.js'
import type { GoalActions } from '../src/tui-goal.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 { GoalStore } from '../src/goal-store.js'
import type { RemoteContext } from '../src/remote-context.js'
import { goal } from './helpers/goal-fixture.js'
vi.mock('../src/manager-auth.js', () => ({
resolveManagerApi: vi.fn(),
}))
const remote: RemoteContext = {
managerUrl: 'https://manager.example',
managerHost: 'manager.example',
repoName: 'repo',
repoId: 1,
}
function createFakeContext(
route: { type: string; sessionID?: string } = { type: 'session', sessionID: 'ses_a' },
session: unknown = { location: { directory: '/repo' } },
) {
const toast = vi.fn()
const select = vi.fn()
const dialogPrompt = vi.fn()
const sessionPrompt = vi.fn()
const status = vi.fn(() => 'idle')
const context = {
ui: {
router: { current: () => route },
toast: { show: toast },
dialog: { prompt: dialogPrompt, select },
},
data: {
session: {
get: () => session,
status,
},
},
client: { session: { prompt: sessionPrompt } },
} as unknown as Context
return { context, toast, select, dialogPrompt, sessionPrompt, status }
}
function makeApi() {
return {
getLatestSessionGoal: vi.fn(async () => null as SessionGoal | null),
startSessionGoal: vi.fn(),
pauseSessionGoal: vi.fn(),
resumeSessionGoal: vi.fn(),
cancelSessionGoal: vi.fn(),
}
}
function makeStore() {
const set = vi.fn()
const store: GoalStore = {
watch: vi.fn(() => () => undefined),
set,
}
return { store, set }
}
function depsFor(api: ReturnType<typeof makeApi>, store: GoalStore) {
vi.mocked(resolveManagerApi).mockResolvedValue({
ok: true,
auth: { ok: true, managerUrl: remote.managerUrl, token: 'tok' },
api: api as unknown as ManagerApi,
})
return { remote, store, showDialog: vi.fn() }
}
async function dialogActions(fake: ReturnType<typeof createFakeContext>, api: ReturnType<typeof makeApi>, store: GoalStore): Promise<GoalActions> {
const deps = depsFor(api, store)
await runGoalCommand(fake.context, deps, '/ocm-goal')
return deps.showDialog.mock.calls[0]![0].actions
}
const blankLimits = { maxTurns: '', tokenBudget: '' }
beforeEach(() => {
vi.mocked(resolveManagerApi).mockReset()
})
describe('goalObjectiveSummary', () => {
it('keeps the first line of a multi-line objective', () => {
expect(goalObjectiveSummary('fix it\nand more')).toBe('fix it')
})
it('leaves a short single line unchanged', () => {
expect(goalObjectiveSummary('fix it')).toBe('fix it')
})
it('cuts a long first line and appends an ellipsis', () => {
expect(goalObjectiveSummary('x'.repeat(70))).toBe(`${'x'.repeat(60)}…`)
})
})
describe('formatGoalStatus', () => {
it('renders the outcome, shared turn and token labels, and objective', () => {
expect(
formatGoalStatus(goal({ status: 'active', continuationCount: 2, maxContinuations: 5, tokenBudget: 1000, tokensUsed: 250 })),
).toBe(`Goal active · Turn 2/5 · 250/${(1000).toLocaleString()} tokens · fix it`)
})
it('omits the token budget when there is none', () => {
expect(formatGoalStatus(goal({ status: 'paused', tokenBudget: null }))).toBe('Goal paused · Turn 0/5 · fix it')
})
it('renders one line using only the objective first line', () => {
expect(formatGoalStatus(goal({ status: 'active', objective: 'fix it\nsecond line' }))).toBe('Goal active · Turn 0/5 · fix it')
})
})
describe('goalOutcomeToast', () => {
it('maps completed to success with the last reason', () => {
expect(goalOutcomeToast(goal({ status: 'completed', lastReason: 'all green' }))).toEqual({
variant: 'success',
title: 'Goal completed',
message: 'all green',
})
})
it('maps blocked to error and falls back to the objective', () => {
expect(goalOutcomeToast(goal({ status: 'blocked', lastReason: null, objective: 'fix it' }))).toEqual({
variant: 'error',
title: 'Goal blocked',
message: 'fix it',
})
})
it('maps stopped to warning and prefers the stop reason label', () => {
expect(goalOutcomeToast(goal({ status: 'stopped', stopReason: 'cancelled' }))).toEqual({
variant: 'warning',
title: 'Goal stopped',
message: 'Cancelled',
})
})
it('summarizes a long objective fallback', () => {
expect(goalOutcomeToast(goal({ status: 'blocked', lastReason: null, objective: 'x'.repeat(70) })).message).toBe(`${'x'.repeat(60)}…`)
})
})
describe('parseGoalForm', () => {
it('trims the objective and leaves blank limits to the Manager defaults', () => {
expect(parseGoalForm({ objective: ' fix it ', ...blankLimits }, 'ses_a', '/repo')).toEqual({
ok: true,
request: { sessionId: 'ses_a', directory: '/repo', objective: 'fix it' },
})
})
it('passes explicit limits through', () => {
expect(parseGoalForm({ objective: 'fix it', maxTurns: ' 12 ', tokenBudget: '50000' }, 'ses_a', '/repo')).toEqual({
ok: true,
request: { sessionId: 'ses_a', directory: '/repo', objective: 'fix it', maxContinuations: 12, tokenBudget: 50000 },
})
})
it('rejects a blank objective and out-of-range or non-numeric limits', () => {
expect(parseGoalForm({ objective: ' ', ...blankLimits }, 'ses_a', '/repo')).toEqual({
ok: false,
error: 'Describe what this session should accomplish.',
})
for (const maxTurns of ['0', '201', 'ten', '1.5']) {
expect(parseGoalForm({ objective: 'x', maxTurns, tokenBudget: '' }, 'ses_a', '/repo')).toEqual({
ok: false,
error: 'Max turns must be a whole number from 1 to 200.',
})
}
for (const tokenBudget of ['0', '-5', 'lots']) {
expect(parseGoalForm({ objective: 'x', maxTurns: '', tokenBudget }, 'ses_a', '/repo')).toEqual({
ok: false,
error: 'Token budget must be a positive whole number.',
})
}
})
})
describe('runGoalCommand', () => {
it('refuses when not attached to a Manager or without a goal store', async () => {
const fake = createFakeContext()
const api = makeApi()
const { store } = makeStore()
const detached = { ...depsFor(api, store), remote: undefined }
const storeless = { ...depsFor(api, store), store: undefined }
await runGoalCommand(fake.context, detached, '/ocm-goal fix it')
await runGoalCommand(fake.context, storeless, '/ocm-goal fix it')
expect(fake.toast).toHaveBeenCalledTimes(2)
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: GOALS_ATTACH_REQUIRED })
expect(vi.mocked(resolveManagerApi)).not.toHaveBeenCalled()
})
it('refuses outside a session', async () => {
const fake = createFakeContext({ type: 'home' })
const { store } = makeStore()
const deps = depsFor(makeApi(), store)
await runGoalCommand(fake.context, deps, '/ocm-goal fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'Not in a session' })
expect(vi.mocked(resolveManagerApi)).not.toHaveBeenCalled()
})
it('refuses when the session has no directory', async () => {
const fake = createFakeContext({ type: 'session', sessionID: 'ses_a' }, { location: {} })
const { store } = makeStore()
const deps = depsFor(makeApi(), store)
await runGoalCommand(fake.context, deps, '/ocm-goal fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'Session has no directory' })
expect(vi.mocked(resolveManagerApi)).not.toHaveBeenCalled()
})
it('reports an auth failure without calling the API', async () => {
const fake = createFakeContext()
const api = makeApi()
const { store } = makeStore()
const deps = depsFor(api, store)
vi.mocked(resolveManagerApi).mockResolvedValue({ ok: false, message: 'No token stored. Run `ocm login https://manager.example`.' })
await runGoalCommand(fake.context, deps, '/ocm-goal fix it')
expect(fake.toast).toHaveBeenCalledWith({
variant: 'error',
message: 'No token stored. Run `ocm login https://manager.example`.',
})
expect(api.getLatestSessionGoal).not.toHaveBeenCalled()
})
it('starts a goal directly from the slash argument and sends the objective as the next message', async () => {
const fake = createFakeContext()
const api = makeApi()
const started = goal({ status: 'active' })
api.startSessionGoal.mockResolvedValue(started)
const { store, set } = makeStore()
const deps = depsFor(api, store)
fake.sessionPrompt.mockResolvedValue(undefined)
await runGoalCommand(fake.context, deps, '/ocm-goal Fix the flaky test')
expect(vi.mocked(resolveManagerApi)).toHaveBeenCalledWith(remote.managerUrl)
expect(api.startSessionGoal).toHaveBeenCalledWith({ sessionId: 'ses_a', directory: '/repo', objective: 'Fix the flaky test' })
expect(set).toHaveBeenCalledWith(started)
expect(fake.sessionPrompt).toHaveBeenCalledWith({ sessionID: 'ses_a', text: 'Fix the flaky test', delivery: undefined })
expect(api.startSessionGoal.mock.invocationCallOrder[0]).toBeLessThan(fake.sessionPrompt.mock.invocationCallOrder[0])
expect(deps.showDialog).not.toHaveBeenCalled()
})
it('queues the objective while the session is running', async () => {
const fake = createFakeContext()
const api = makeApi()
api.startSessionGoal.mockResolvedValue(goal())
const { store } = makeStore()
fake.status.mockReturnValue('running')
fake.sessionPrompt.mockResolvedValue(undefined)
await runGoalCommand(fake.context, depsFor(api, store), '/ocm-goal Fix it')
expect(fake.sessionPrompt).toHaveBeenCalledWith(expect.objectContaining({ delivery: 'queue' }))
})
it('opens the dialog with the latest goal when the command has no objective', async () => {
const fake = createFakeContext()
const api = makeApi()
const last = goal({ status: 'completed' })
api.getLatestSessionGoal.mockResolvedValue(last)
const { store } = makeStore()
const deps = depsFor(api, store)
await runGoalCommand(fake.context, deps, '/ocm-goal')
expect(deps.showDialog).toHaveBeenCalledWith({
sessionID: 'ses_a',
store,
initialGoal: last,
initialObjective: '',
actions: expect.any(Object),
})
expect(api.startSessionGoal).not.toHaveBeenCalled()
})
it('opens the dialog instead of starting when a goal is already open', async () => {
const fake = createFakeContext()
const api = makeApi()
const active = goal({ status: 'active' })
api.getLatestSessionGoal.mockResolvedValue(active)
const { store } = makeStore()
const deps = depsFor(api, store)
await runGoalCommand(fake.context, deps, '/ocm-goal something else')
expect(deps.showDialog).toHaveBeenCalledWith(expect.objectContaining({ initialGoal: active, initialObjective: 'something else' }))
expect(api.startSessionGoal).not.toHaveBeenCalled()
})
it('reports Manager errors, including an outdated Manager', async () => {
const fake = createFakeContext()
const api = makeApi()
const { store } = makeStore()
api.getLatestSessionGoal.mockRejectedValueOnce(new ManagerApiError('read failed', 500, 'boom', 'read session goal'))
api.getLatestSessionGoal.mockRejectedValueOnce(new ManagerApiError('not found', 404, null, 'read session goal'))
await runGoalCommand(fake.context, depsFor(api, store), '/ocm-goal fix it')
await runGoalCommand(fake.context, depsFor(api, store), '/ocm-goal fix it')
expect(fake.toast).toHaveBeenNthCalledWith(1, { variant: 'error', message: 'read failed' })
expect(fake.toast).toHaveBeenNthCalledWith(2, { variant: 'error', message: GOALS_ROUTE_MISSING })
})
})
describe('goal dialog actions', () => {
it('starts a goal with explicit limits', async () => {
const fake = createFakeContext()
const api = makeApi()
api.startSessionGoal.mockResolvedValue(goal())
fake.sessionPrompt.mockResolvedValue(undefined)
const { store } = makeStore()
const actions = await dialogActions(fake, api, store)
await expect(actions.start({ objective: 'fix it', maxTurns: '8', tokenBudget: '' })).resolves.toBeNull()
expect(api.startSessionGoal).toHaveBeenCalledWith({ sessionId: 'ses_a', directory: '/repo', objective: 'fix it', maxContinuations: 8 })
})
it('returns a validation error without calling the API', async () => {
const fake = createFakeContext()
const api = makeApi()
const { store } = makeStore()
const actions = await dialogActions(fake, api, store)
await expect(actions.start({ objective: 'fix it', maxTurns: '0', tokenBudget: '' })).resolves.toBe(
'Max turns must be a whole number from 1 to 200.',
)
expect(api.startSessionGoal).not.toHaveBeenCalled()
})
it('cancels the goal and explains why when sending the objective fails', async () => {
const fake = createFakeContext()
const api = makeApi()
const started = goal({ status: 'active' })
const cancelled = goal({ status: 'stopped', stopReason: 'cancelled' })
api.startSessionGoal.mockResolvedValue(started)
api.cancelSessionGoal.mockResolvedValue(cancelled)
fake.sessionPrompt.mockRejectedValue(new Error('send failed'))
const { store, set } = makeStore()
const actions = await dialogActions(fake, api, store)
await expect(actions.start({ objective: 'fix it', ...blankLimits })).resolves.toBe(
'The goal was cancelled because the objective could not be sent: send failed',
)
expect(api.cancelSessionGoal).toHaveBeenCalledWith(started.id)
expect(set).toHaveBeenLastCalledWith(cancelled)
})
it('still reports the send failure when cancelling fails', async () => {
const fake = createFakeContext()
const api = makeApi()
api.startSessionGoal.mockResolvedValue(goal())
api.cancelSessionGoal.mockRejectedValue(new Error('cancel failed'))
fake.sessionPrompt.mockRejectedValue(new Error('send failed'))
const { store, set } = makeStore()
const actions = await dialogActions(fake, api, store)
await expect(actions.start({ objective: 'fix it', ...blankLimits })).resolves.toMatch(/send failed$/)
expect(set).toHaveBeenCalledTimes(1)
})
it('pauses, resumes, and cancels through the Manager and updates the store', async () => {
const fake = createFakeContext()
const api = makeApi()
const paused = goal({ status: 'paused' })
const resumed = goal({ status: 'active' })
const stopped = goal({ status: 'stopped', stopReason: 'cancelled' })
api.pauseSessionGoal.mockResolvedValue(paused)
api.resumeSessionGoal.mockResolvedValue(resumed)
api.cancelSessionGoal.mockResolvedValue(stopped)
const { store, set } = makeStore()
const actions = await dialogActions(fake, api, store)
await expect(actions.pause(goal())).resolves.toBeNull()
await expect(actions.resume(paused)).resolves.toBeNull()
await expect(actions.cancel(resumed)).resolves.toBeNull()
expect(api.pauseSessionGoal).toHaveBeenCalledWith(7)
expect(set.mock.calls.map((call) => call[0])).toEqual([paused, resumed, stopped])
})
it('returns a goal action failure as a message', async () => {
const fake = createFakeContext()
const api = makeApi()
api.pauseSessionGoal.mockRejectedValue(new ManagerApiError('pause session goal failed (409): not active', 409, 'x', 'pause session goal'))
const { store, set } = makeStore()
const actions = await dialogActions(fake, api, store)
await expect(actions.pause(goal())).resolves.toBe('pause session goal failed (409): not active')
expect(set).not.toHaveBeenCalled()
})
})
+4 -5
View File
@@ -74,7 +74,7 @@ vi.mock('../src/manager-api.js', () => ({
isManagerRouteMissing: vi.fn(() => false),
}))
const noFeatures = { remote: undefined, goals: undefined, dialogs: { goal: vi.fn(), multiRunLaunch: vi.fn(), multiRuns: vi.fn() } }
const noFeatures = { remote: undefined, dialogs: { multiRunLaunch: vi.fn(), multiRuns: vi.fn() } }
const matched = { repoId: 1, name: 'repo', projectId: 'proj_1', branch: 'main' }
const repos = [
@@ -212,17 +212,16 @@ describe('setupOcm', () => {
expect(factory().mode).toBe('global')
})
it('exposes the goal slash command', async () => {
it('registers no goal command', async () => {
const fake = createFakeContext()
await setupOcm(fake.context, vi.fn(), noFeatures)
renderAppSlot(fake)
const factory = fake.layer.mock.calls[0]![0] as () => {
commands: { id: string; slash?: { name: string; arguments?: true } }[]
commands: { id: string }[]
}
const goal = factory().commands.find((entry) => entry.id === 'ocm.goal')
expect(goal?.slash).toEqual({ name: 'ocm-goal', arguments: true })
expect(factory().commands.map((entry) => entry.id)).toEqual(['ocm.session.move', 'ocm.switch', 'ocm.multirun'])
})
it('exposes the multi-run slash command', async () => {