section 5: Phase 5: Session goals in the TUI (/goal, composer status

This commit is contained in:
Chris Scott committed 2026-10-07 18:33:03 -04:00
1 parent 87e55372c0
commit e63f756c32
7 files changed
+1018 -4

No files matched your search

+113
View File
@@ -0,0 +1,113 @@
import type { SessionGoal } from '@opencode-manager/shared/schemas'
export const GOAL_POLL_INTERVAL_MS = 3000
export type GoalStoreDeps = {
load: (sessionID: string) => Promise<SessionGoal | null>
onOutcome: (goal: SessionGoal) => void
pollIntervalMs?: number
}
export type GoalStore = {
watch(sessionID: string, listener: (goal: SessionGoal | null) => void): () => void
set(goal: SessionGoal): void
refresh(sessionID: string): Promise<void>
}
interface GoalEntry {
readonly sessionID: string
goal: SessionGoal | null
listeners: Set<(goal: SessionGoal | null) => void>
timer: ReturnType<typeof setInterval> | null
}
export function isOpenGoal(goal: SessionGoal | null | undefined): goal is SessionGoal {
return !!goal && (goal.status === 'active' || goal.status === 'paused')
}
function isTerminalGoal(goal: SessionGoal): boolean {
return goal.status === 'completed' || goal.status === 'blocked' || goal.status === 'stopped'
}
export function createGoalStore(deps: GoalStoreDeps): GoalStore {
const pollIntervalMs = deps.pollIntervalMs ?? GOAL_POLL_INTERVAL_MS
const entries = new Map<string, GoalEntry>()
function entryFor(sessionID: string): GoalEntry {
let entry = entries.get(sessionID)
if (!entry) {
entry = { sessionID, goal: null, listeners: new Set(), timer: null }
entries.set(sessionID, entry)
}
return entry
}
function stopPolling(entry: GoalEntry): void {
if (entry.timer !== null) {
clearInterval(entry.timer)
entry.timer = null
}
}
function isLive(entry: GoalEntry): boolean {
return entry.listeners.size > 0 && entries.get(entry.sessionID) === entry
}
function startPolling(entry: GoalEntry): void {
stopPolling(entry)
entry.timer = setInterval(() => {
void loadInto(entry)
}, pollIntervalMs)
}
function applyGoal(entry: GoalEntry, goal: SessionGoal | null): void {
const previous = entry.goal
entry.goal = goal
for (const listener of entry.listeners) listener(goal)
if (entry.listeners.size > 0 && isOpenGoal(previous) && goal !== null && isTerminalGoal(goal)) {
deps.onOutcome(goal)
}
if (goal?.status === 'active' && isLive(entry)) startPolling(entry)
else stopPolling(entry)
}
async function loadInto(entry: GoalEntry): Promise<void> {
let goal: SessionGoal | null
try {
goal = await deps.load(entry.sessionID)
} catch {
if (entry.goal?.status !== 'active' || !isLive(entry)) stopPolling(entry)
return
}
if (entries.get(entry.sessionID) !== entry) {
stopPolling(entry)
return
}
applyGoal(entry, goal)
}
return {
watch(sessionID, listener) {
const entry = entryFor(sessionID)
entry.listeners.add(listener)
void loadInto(entry)
return () => {
entry.listeners.delete(listener)
if (entry.listeners.size === 0) {
stopPolling(entry)
entries.delete(sessionID)
}
}
},
set(goal) {
const entry = entries.get(goal.sessionId)
if (!entry) return
applyGoal(entry, goal)
},
refresh(sessionID) {
const entry = entries.get(sessionID)
if (!entry) return Promise.resolve()
return loadInto(entry)
},
}
}
+141
View File
@@ -0,0 +1,141 @@
import type { Context, ToastOptions } from '@opencode/plugin/tui/context'
import type { SessionGoal } from '@opencode-manager/shared/schemas'
import { getGoalOutcomeTitle, getGoalStopReasonLabel } from '@opencode-manager/shared/notifications'
import { ManagerApi, ManagerApiError, isManagerRouteMissing } from './manager-api.js'
import { resolveManagerAuth } from './manager-auth.js'
import type { ManagerAuth } from './manager-auth.js'
import { promptDialog, selectDialog, slashArgument } from './tui-dialogs.js'
import { isOpenGoal } from './goal-store.js'
import type { GoalStore } from './goal-store.js'
import type { RemoteContext } from './remote-context.js'
export const GOALS_ATTACH_REQUIRED =
'Goals run on OpenCode Manager. Attach with `ocm` (or move this session with /ocm-move) first.'
export const GOALS_ROUTE_MISSING = 'This OpenCode Manager does not expose goals to ocm; upgrade the Manager.'
export type ManagerAuthOk = Extract<ManagerAuth, { ok: true }>
export type GoalCommandDeps = {
remote: RemoteContext | undefined
store: GoalStore | undefined
createApi?: (auth: ManagerAuthOk) => ManagerApi
}
export function formatGoalStatus(goal: SessionGoal): string {
const parts = [getGoalOutcomeTitle(goal.status), `turn ${goal.continuationCount}/${goal.maxContinuations}`]
if (goal.tokenBudget !== null) {
parts.push(`${goal.tokensUsed}/${goal.tokenBudget} tokens`)
}
parts.push(goal.objective)
return parts.join(' · ')
}
export function goalOutcomeToast(goal: SessionGoal): ToastOptions {
const variant = goal.status === 'completed' ? 'success' : goal.status === 'blocked' ? 'error' : 'warning'
return {
variant,
title: getGoalOutcomeTitle(goal.status),
message: goal.stopReason ? getGoalStopReasonLabel(goal.stopReason) : goal.lastReason ?? goal.objective,
}
}
function showGoalError(context: Context, error: unknown): void {
if (isManagerRouteMissing(error)) {
context.ui.toast.show({ variant: 'error', message: GOALS_ROUTE_MISSING })
return
}
if (error instanceof ManagerApiError) {
context.ui.toast.show({ variant: 'error', message: error.message })
return
}
context.ui.toast.show({ variant: 'error', message: error instanceof Error ? error.message : String(error) })
}
async function runOpenGoalAction(context: Context, api: ManagerApi, goal: SessionGoal): Promise<SessionGoal | undefined> {
const action = await selectDialog(context, 'Session goal', [
goal.status === 'paused'
? { title: 'Resume goal', value: 'resume' as const }
: { title: 'Pause goal', value: 'pause' as const },
{ title: 'Cancel goal', value: 'cancel' as const },
])
if (!action) return undefined
switch (action) {
case 'pause':
return api.pauseSessionGoal(goal.id)
case 'resume':
return api.resumeSessionGoal(goal.id)
case 'cancel':
return api.cancelSessionGoal(goal.id)
}
}
async function startGoal(
context: Context,
store: GoalStore,
api: ManagerApi,
sessionID: string,
directory: string,
objective: string,
): Promise<void> {
const goal = await api.startSessionGoal({ sessionId: sessionID, directory, objective })
store.set(goal)
try {
await context.client.session.prompt({
sessionID,
text: objective,
delivery: context.data.session.status(sessionID) === 'running' ? 'queue' : undefined,
})
} catch (error) {
const cancelled = await api.cancelSessionGoal(goal.id).catch(() => undefined)
if (cancelled) store.set(cancelled)
context.ui.toast.show({ variant: 'error', message: error instanceof Error ? error.message : String(error) })
}
}
export async function runGoalCommand(context: Context, deps: GoalCommandDeps, input?: string): Promise<void> {
try {
if (!deps.remote || !deps.store) {
context.ui.toast.show({ variant: 'error', message: GOALS_ATTACH_REQUIRED })
return
}
const current = context.ui.router.current()
if (current.type !== 'session') {
context.ui.toast.show({ variant: 'error', message: 'Not in a session' })
return
}
const sessionID = current.sessionID
const session = context.data.session.get(sessionID)
if (!session?.location.directory) {
context.ui.toast.show({ variant: 'error', message: 'Session has no directory' })
return
}
const auth = await resolveManagerAuth(deps.remote.managerUrl)
if (!auth.ok) {
context.ui.toast.show({ variant: 'error', message: auth.message })
return
}
const api = deps.createApi ? deps.createApi(auth) : new ManagerApi(auth.managerUrl, auth.token)
const existing = await api.getLatestSessionGoal(sessionID)
if (isOpenGoal(existing)) {
const result = await runOpenGoalAction(context, api, existing)
if (result) deps.store.set(result)
return
}
const objective =
slashArgument(input, 'goal') ||
(await promptDialog(context, {
title: 'Start goal',
description: 'What should this session accomplish?',
placeholder: 'Describe the goal',
}))
if (!objective) return
await startGoal(context, deps.store, api, sessionID, session.location.directory, objective)
} catch (error) {
showGoalError(context, error)
}
}
+18 -1
View File
@@ -15,10 +15,18 @@ import { setPendingWarp, runPendingWarp } from './warp.js'
import { pushPhaseProgress, importProgress } from './move-progress.js'
import { warmRepoProxy } from './repo-proxy.js'
import type { MoveProgress } from './move-progress.js'
import { runGoalCommand } from './tui-goal.js'
import type { GoalStore } from './goal-store.js'
import type { RemoteContext } from './remote-context.js'
export type MoveProgressSetter = (progress: MoveProgress | null) => void
export async function setupOcm(context: Context, setMoveProgress: MoveProgressSetter): Promise<() => void> {
export type OcmFeatures = {
remote: RemoteContext | undefined
goals: GoalStore | undefined
}
export async function setupOcm(context: Context, setMoveProgress: MoveProgressSetter, features: OcmFeatures): Promise<() => void> {
showInstallNotice(context)
context.ui.slot({
append: 'app',
@@ -35,6 +43,15 @@ export async function setupOcm(context: Context, setMoveProgress: MoveProgressSe
slash: { name: 'ocm-move' },
run: () => runSessionMove(context, setMoveProgress),
},
{
id: 'ocm.goal',
title: 'Goal',
description: 'Start, pause, resume, or cancel a Manager goal for this session',
group: 'OpenCode Manager',
palette: true,
slash: { name: 'goal', arguments: true },
run: (input) => runGoalCommand(context, { remote: features.remote, store: features.goals }, input),
},
],
}))
return null
+50 -1
View File
@@ -5,6 +5,12 @@ import { setupOcm } from './tui-plugin.js'
import { formatMoveProgress } from './move-progress.js'
import type { MoveProgress } from './move-progress.js'
import { readRemoteContext } from './remote-context.js'
import { createGoalStore, isOpenGoal } from './goal-store.js'
import type { GoalStore } from './goal-store.js'
import { formatGoalStatus, goalOutcomeToast } from './tui-goal.js'
import { ManagerApi } from './manager-api.js'
import { resolveManagerAuth } from './manager-auth.js'
import type { SessionGoal } from '@opencode-manager/shared/schemas'
const SPINNER_INTERVAL_MS = 80
@@ -44,6 +50,49 @@ export default Plugin.define({
context.ui.slot({ append: 'home.footer.status', render: indicator })
}
return setupOcm(context, setMoveProgress)
const goals = remote
? createGoalStore({
load: async (sessionID) => {
const auth = await resolveManagerAuth(remote.managerUrl)
if (!auth.ok) throw new Error(auth.message)
return new ManagerApi(auth.managerUrl, auth.token).getLatestSessionGoal(sessionID)
},
onOutcome: (goal) => {
context.ui.toast.show({ ...goalOutcomeToast(goal), sessionID: goal.sessionId })
},
})
: undefined
const GoalLine = (props: { sessionID: string; store: GoalStore }) => {
const [goal, setGoal] = createSignal<SessionGoal | null>(null)
createEffect(() => {
const unsubscribe = props.store.watch(props.sessionID, (next) => setGoal(next))
onCleanup(unsubscribe)
})
const openGoal = () => {
const current = goal()
return current && isOpenGoal(current) ? current : null
}
return (
<Show when={openGoal()}>
{(current) => (
<box flexDirection="row" flexShrink={0}>
<text fg={current().status === 'active' ? context.theme.hue.accent[200] : context.theme.text.muted}>
{formatGoalStatus(current())}
</text>
</box>
)}
</Show>
)
}
if (goals) {
context.ui.slot({
append: 'session.composer.top',
render: (input) => <GoalLine sessionID={input.sessionID} store={goals} />,
})
}
return setupOcm(context, setMoveProgress, { remote, goals })
},
})
+318
View File
@@ -0,0 +1,318 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import type { SessionGoal } from '@opencode-manager/shared/schemas'
import { createGoalStore, isOpenGoal, GOAL_POLL_INTERVAL_MS } from '../src/goal-store.js'
function goal(overrides: Partial<SessionGoal> = {}): SessionGoal {
return {
id: 1,
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,
}
}
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
describe('isOpenGoal', () => {
it('accepts active and paused goals', () => {
expect(isOpenGoal(goal({ status: 'active' }))).toBe(true)
expect(isOpenGoal(goal({ status: 'paused' }))).toBe(true)
})
it('rejects terminal and missing goals', () => {
expect(isOpenGoal(goal({ status: 'completed' }))).toBe(false)
expect(isOpenGoal(goal({ status: 'blocked' }))).toBe(false)
expect(isOpenGoal(goal({ status: 'stopped' }))).toBe(false)
expect(isOpenGoal(null)).toBe(false)
expect(isOpenGoal(undefined)).toBe(false)
})
})
describe('createGoalStore', () => {
it('defaults the poll interval to the frontend refetch interval', () => {
expect(GOAL_POLL_INTERVAL_MS).toBe(3000)
})
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(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('stops polling when 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(1000)
expect(load).toHaveBeenCalledTimes(1)
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('reloads on demand through refresh', 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()
load.mockResolvedValue(next)
await store.refresh('ses_a')
expect(load).toHaveBeenCalledTimes(2)
expect(listener).toHaveBeenCalledWith(next)
unwatch()
})
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 store.refresh('ses_a')
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('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 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(100)
expect(load).toHaveBeenCalledTimes(3)
unwatch()
})
it('does not poll after an initial load failure', async () => {
const load = vi.fn().mockRejectedValue(new Error('offline'))
const store = createGoalStore({ load, onOutcome: vi.fn(), pollIntervalMs: 100 })
const listener = vi.fn()
const unwatch = store.watch('ses_a', listener)
await vi.advanceTimersByTimeAsync(0)
await vi.advanceTimersByTimeAsync(1000)
expect(load).toHaveBeenCalledTimes(1)
expect(listener).not.toHaveBeenCalled()
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()
})
})
+360
View File
@@ -0,0 +1,360 @@
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,
goalOutcomeToast,
GOALS_ATTACH_REQUIRED,
GOALS_ROUTE_MISSING,
} from '../src/tui-goal.js'
import { ManagerApiError } from '../src/manager-api.js'
import type { ManagerApi } from '../src/manager-api.js'
import { resolveManagerAuth } from '../src/manager-auth.js'
import type { GoalStore } from '../src/goal-store.js'
import type { RemoteContext } from '../src/remote-context.js'
vi.mock('../src/manager-auth.js', () => ({
resolveManagerAuth: vi.fn(),
}))
const remote: RemoteContext = {
managerUrl: 'https://manager.example',
managerHost: 'manager.example',
repoName: 'repo',
repoId: 1,
}
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,
}
}
function createFakeContext(route: { type: string; sessionID?: string } = { type: 'session', sessionID: 'ses_a' }) {
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: () => ({ location: { directory: '/repo' } }),
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,
refresh: vi.fn(async () => undefined),
}
return { store, set }
}
function depsFor(api: ReturnType<typeof makeApi>, store: GoalStore, createApi = vi.fn(() => api as unknown as ManagerApi)) {
return { remote, store, createApi }
}
beforeEach(() => {
vi.mocked(resolveManagerAuth).mockReset()
vi.mocked(resolveManagerAuth).mockResolvedValue({ ok: true, managerUrl: remote.managerUrl, token: 'tok' })
})
describe('formatGoalStatus', () => {
it('renders the outcome, turn counter, token budget and objective', () => {
expect(
formatGoalStatus(goal({ status: 'active', continuationCount: 2, maxContinuations: 5, tokenBudget: 1000, tokensUsed: 250 })),
).toBe('Goal active · turn 2/5 · 250/1000 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')
})
})
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',
})
})
})
describe('runGoalCommand', () => {
it('refuses when not attached to a Manager', async () => {
const fake = createFakeContext()
const { store } = makeStore()
const createApi = vi.fn()
await runGoalCommand(fake.context, { remote: undefined, store, createApi }, '/goal fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: GOALS_ATTACH_REQUIRED })
expect(createApi).not.toHaveBeenCalled()
})
it('refuses when no goal store is available', async () => {
const fake = createFakeContext()
await runGoalCommand(fake.context, { remote, store: undefined }, '/goal fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: GOALS_ATTACH_REQUIRED })
})
it('refuses outside a session', async () => {
const fake = createFakeContext({ type: 'home' })
const { store } = makeStore()
const createApi = vi.fn()
await runGoalCommand(fake.context, { remote, store, createApi }, '/goal fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'Not in a session' })
expect(createApi).not.toHaveBeenCalled()
})
it('reports an auth failure without calling the API', async () => {
const fake = createFakeContext()
const api = makeApi()
const { store } = makeStore()
vi.mocked(resolveManagerAuth).mockResolvedValue({ ok: false, message: 'No token stored. Run `ocm login https://manager.example`.' })
await runGoalCommand(fake.context, depsFor(api, store), '/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 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()
fake.sessionPrompt.mockResolvedValue(undefined)
await runGoalCommand(fake.context, depsFor(api, store), '/goal Fix the flaky test')
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])
})
it('queues the prompt 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), '/goal Fix it')
expect(fake.sessionPrompt).toHaveBeenCalledWith(expect.objectContaining({ delivery: 'queue' }))
})
it('prompts for the objective when the command has none', async () => {
const fake = createFakeContext()
const api = makeApi()
api.startSessionGoal.mockResolvedValue(goal())
const { store } = makeStore()
fake.dialogPrompt.mockResolvedValue('from dialog')
fake.sessionPrompt.mockResolvedValue(undefined)
await runGoalCommand(fake.context, depsFor(api, store), '/goal')
expect(fake.dialogPrompt).toHaveBeenCalledWith(expect.objectContaining({ title: 'Start goal' }))
expect(api.startSessionGoal).toHaveBeenCalledWith(expect.objectContaining({ objective: 'from dialog' }))
})
it('does nothing when the start prompt is dismissed', async () => {
const fake = createFakeContext()
const api = makeApi()
const { store } = makeStore()
fake.dialogPrompt.mockResolvedValue(undefined)
await runGoalCommand(fake.context, depsFor(api, store), '/goal')
expect(api.startSessionGoal).not.toHaveBeenCalled()
expect(fake.sessionPrompt).not.toHaveBeenCalled()
})
it('cancels the goal 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)
const { store, set } = makeStore()
fake.sessionPrompt.mockRejectedValue(new Error('send failed'))
await runGoalCommand(fake.context, depsFor(api, store), '/goal Fix it')
expect(api.cancelSessionGoal).toHaveBeenCalledWith(started.id)
expect(set).toHaveBeenLastCalledWith(cancelled)
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'send failed' })
})
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'))
const { store, set } = makeStore()
fake.sessionPrompt.mockRejectedValue(new Error('send failed'))
await runGoalCommand(fake.context, depsFor(api, store), '/goal Fix it')
expect(set).toHaveBeenCalledTimes(1)
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'send failed' })
})
it('offers pause and cancel for an active goal', async () => {
const fake = createFakeContext()
const api = makeApi()
const active = goal({ status: 'active' })
const paused = goal({ status: 'paused' })
api.getLatestSessionGoal.mockResolvedValue(active)
api.pauseSessionGoal.mockResolvedValue(paused)
const { store, set } = makeStore()
fake.select.mockResolvedValue('pause')
await runGoalCommand(fake.context, depsFor(api, store), '/goal')
const options = fake.select.mock.calls[0][0].options as { title: string }[]
expect(options.map((option) => option.title)).toEqual(['Pause goal', 'Cancel goal'])
expect(api.pauseSessionGoal).toHaveBeenCalledWith(active.id)
expect(set).toHaveBeenCalledWith(paused)
expect(api.startSessionGoal).not.toHaveBeenCalled()
})
it('offers resume and cancel for a paused goal', async () => {
const fake = createFakeContext()
const api = makeApi()
const paused = goal({ status: 'paused' })
const resumed = goal({ status: 'active' })
api.getLatestSessionGoal.mockResolvedValue(paused)
api.resumeSessionGoal.mockResolvedValue(resumed)
const { store, set } = makeStore()
fake.select.mockResolvedValue('resume')
await runGoalCommand(fake.context, depsFor(api, store), '/goal')
const options = fake.select.mock.calls[0][0].options as { title: string }[]
expect(options.map((option) => option.title)).toEqual(['Resume goal', 'Cancel goal'])
expect(api.resumeSessionGoal).toHaveBeenCalledWith(paused.id)
expect(set).toHaveBeenCalledWith(resumed)
})
it('cancels an open goal', async () => {
const fake = createFakeContext()
const api = makeApi()
const active = goal({ status: 'active' })
const stopped = goal({ status: 'stopped', stopReason: 'cancelled' })
api.getLatestSessionGoal.mockResolvedValue(active)
api.cancelSessionGoal.mockResolvedValue(stopped)
const { store, set } = makeStore()
fake.select.mockResolvedValue('cancel')
await runGoalCommand(fake.context, depsFor(api, store), '/goal')
expect(api.cancelSessionGoal).toHaveBeenCalledWith(active.id)
expect(set).toHaveBeenCalledWith(stopped)
})
it('does nothing when the goal action dialog is dismissed', async () => {
const fake = createFakeContext()
const api = makeApi()
api.getLatestSessionGoal.mockResolvedValue(goal({ status: 'active' }))
const { store, set } = makeStore()
fake.select.mockResolvedValue(undefined)
await runGoalCommand(fake.context, depsFor(api, store), '/goal')
expect(api.pauseSessionGoal).not.toHaveBeenCalled()
expect(set).not.toHaveBeenCalled()
})
it('reports a Manager API error message', async () => {
const fake = createFakeContext()
const api = makeApi()
api.getLatestSessionGoal.mockRejectedValue(new ManagerApiError('read failed', 500, 'boom', 'read session goal'))
const { store } = makeStore()
await runGoalCommand(fake.context, depsFor(api, store), '/goal fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: 'read failed' })
})
it('reports an outdated Manager when the goal route is missing', async () => {
const fake = createFakeContext()
const api = makeApi()
api.getLatestSessionGoal.mockRejectedValue(new ManagerApiError('not found', 404, null, 'read session goal'))
const { store } = makeStore()
await runGoalCommand(fake.context, depsFor(api, store), '/goal fix it')
expect(fake.toast).toHaveBeenCalledWith({ variant: 'error', message: GOALS_ROUTE_MISSING })
})
})
+18 -2
View File
@@ -74,8 +74,11 @@ vi.mock('../src/manager-api.js', () => ({
super(message)
}
},
isManagerRouteMissing: vi.fn(() => false),
}))
const noFeatures = { remote: undefined, goals: undefined }
const matched = { repoId: 1, name: 'repo', projectId: 'proj_1', branch: 'main' }
const repos = [
{
@@ -187,7 +190,7 @@ function configureMove(fake: ReturnType<typeof createFakeContext>) {
}
async function invokeMove(fake: ReturnType<typeof createFakeContext>) {
await setupOcm(fake.context, vi.fn())
await setupOcm(fake.context, vi.fn(), noFeatures)
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')!
@@ -203,7 +206,7 @@ describe('setupOcm', () => {
it('registers commands from the app slot so the host keymap provider is mounted', async () => {
const fake = createFakeContext()
await setupOcm(fake.context, vi.fn())
await setupOcm(fake.context, vi.fn(), noFeatures)
expect(fake.layer).not.toHaveBeenCalled()
expect(fake.slot).toHaveBeenCalledWith(expect.objectContaining({ append: 'app' }))
@@ -214,6 +217,19 @@ describe('setupOcm', () => {
const factory = fake.layer.mock.calls[0]![0] as () => { mode?: string }
expect(factory().mode).toBe('global')
})
it('exposes the goal slash 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 } }[]
}
const goal = factory().commands.find((entry) => entry.id === 'ocm.goal')
expect(goal?.slash).toEqual({ name: 'goal', arguments: true })
})
})
describe('ocm.session.move command', () => {