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

+17 -27
View File
@@ -23,6 +23,11 @@ Use ocm 0.2.x with OpenCode Manager < 0.19.0 and OpenCode 1.x, installed pinned
`@opencode-manager/ocm-cli@0.2`. ocm is published together with each OpenCode Manager
release.
From the release after 0.4.1, the TUI plugin is built against `@opencode/plugin`
2.2.x and OpenTUI 0.7, so it requires a local OpenCode >= 2.2.0: OpenCode 2.2.0
refuses plugins built for OpenTUI 0.6, and older OpenCode builds may refuse the
OpenTUI 0.7 peers.
Attachment works with OpenCode Manager >= 0.19.0. The sync worktree targeting of
`ocm push` / `ocm pull` and `/ocm-move` worktree moves need ocm 0.4.0+ and
OpenCode Manager 1.0.0+; an older CLI is told to upgrade, and an older Manager is
@@ -259,25 +264,9 @@ reattaches; switching to a repo also remembers it as the last repo. The current
session stays where it is (use `/ocm-move` to push your local state and bring a
local session along).
The plugin also registers two Manager-backed commands, both of which need an
attached Manager repo through `ocm`:
The plugin also registers one Manager-backed command, which needs an attached
Manager repo through `ocm`:
- `/ocm-goal [objective]` starts a Manager-driven goal on the current top-level
session and sends the objective as the next message (queued if the session
is busy). With no objective, a dialog asks for it, plus optional max turns
(1-200) and token budget (a positive whole number); blank uses the Manager
defaults. `tab` moves between fields and `ctrl+s` starts the goal. The
objective is sent as plain text with the session's current agent and model:
the plugin cannot read the composer's selection, so send a message first if
you switched agent or model, and `@file` mentions are not attached. If the
objective cannot be sent, the goal is cancelled. Scheduled runs and subagent
sessions are rejected by the Manager. While a goal is open, a one-line status
above the composer shows `<status> · Turn n/max`, token usage when the goal
has a token budget, and the first line of the objective. The TUI keeps
following the goal after you leave the session, and a toast reports the
outcome with an option to open the session. Running `/ocm-goal` while a goal
is open shows its live status with `p` to pause or resume and `x` (twice) to
cancel.
- `/ocm-multirun [prompt]` opens a launch dialog: prompt, name (defaults to the
prompt's first line), a filterable model checklist (up to 5, `enter`
toggles), isolated workspaces or the shared repo directory, and, for isolated
@@ -294,17 +283,18 @@ attached Manager repo through `ocm`:
optional instructions; `ctrl+s` fuses and `ctrl+b` goes back. A fusion always
runs in a new isolated workspace.
Both commands need an OpenCode Manager release that exposes
`/api/internal/session-goals` and `/api/internal/multi-runs`. An older Manager
rejects these routes with `401 Unauthorized` even for a valid token, or with a
non-JSON `404`; on a `401` the TUI checks the token against another Manager
route and then reports that the Manager must be upgraded instead of asking you
to log in again.
Session goals use OpenCode's built-in `/goal` command instead.
`/ocm-multirun` needs an OpenCode Manager release that exposes
`/api/internal/multi-runs`. An older Manager rejects this route with
`401 Unauthorized` even for a valid token, or with a non-JSON `404`; on a `401`
the TUI checks the token against another Manager route and then reports that the
Manager must be upgraded instead of asking you to log in again.
The attached `opencode` process carries `OCM_REMOTE_MANAGER_URL`,
`OCM_REMOTE_REPO_NAME`, and `OCM_REMOTE_REPO_ID`. They drive the indicator and
tell `/ocm`, `/ocm-goal`, and `/ocm-multirun` which Manager and repo they act
on; `/ocm-multirun` requires `OCM_REMOTE_REPO_ID`. These commands authenticate
tell `/ocm` and `/ocm-multirun` which Manager and repo they act on;
`/ocm-multirun` requires `OCM_REMOTE_REPO_ID`. These commands authenticate
with the stored token (or `OCM_TOKEN`) for that Manager URL, not with
`OPENCODE_PASSWORD`.
@@ -323,7 +313,7 @@ global installs); the plugin surface is TUI-only.
## Requirements
- macOS or Linux (Windows is unsupported)
- OpenCode >= 2.0.15 (same major, 2.x) available on `PATH`
- OpenCode >= 2.2.0 (same major, 2.x) available on `PATH` for the TUI plugin
- Node available on `PATH` (runs the `ocm` binary)
- OpenCode Manager >= 0.19.0
- `git` and `tar` (with gzip support, i.e. the `-z` flag) available on `PATH`
+10 -5
View File
@@ -18,11 +18,15 @@
}
},
"peerDependencies": {
"@opentui/core": ">=0.5.10",
"@opentui/solid": ">=0.5.10",
"@opencode/theme": ">=2.2.1 <3.0.0",
"@opentui/core": ">=0.7.0 <0.8.0",
"@opentui/solid": ">=0.7.0 <0.8.0",
"solid-js": ">=1.9.0"
},
"peerDependenciesMeta": {
"@opencode/theme": {
"optional": true
},
"@opentui/core": {
"optional": true
},
@@ -54,10 +58,11 @@
},
"devDependencies": {
"@eslint/js": "^9.36.0",
"@opencode/plugin": "2.1.2",
"@opencode/plugin": "2.2.1",
"@opencode/theme": "2.2.1",
"@opencode-manager/shared": "workspace:*",
"@opentui/core": "^0.5.12",
"@opentui/solid": "^0.5.12",
"@opentui/core": "0.7.0",
"@opentui/solid": "0.7.0",
"@types/bun": "^1.3.14",
"@types/node": "^22.0.0",
"eslint": "^9.39.1",
-171
View File
@@ -1,171 +0,0 @@
import {
SESSION_GOAL_POLL_INTERVAL_MS,
isOpenSessionGoal,
isTerminalSessionGoal,
type SessionGoal,
} from '@opencode-manager/shared/schemas'
const BACKGROUND_POLL_INTERVAL_MS = 15000
const MAX_ERROR_BACKOFF_MS = 30000
const REQUEST_TIMEOUT_MS = 10000
export type GoalStoreDeps = {
load: (sessionID: string, signal: AbortSignal) => 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
}
interface GoalEntry {
readonly sessionID: string
goal: SessionGoal | null
listeners: Set<(goal: SessionGoal | null) => void>
timer: ReturnType<typeof setTimeout> | null
abort: AbortController | null
loading: boolean
version: number
errorBackoffMs: number
outcomeGoalId: number | null
}
export function createGoalStore(deps: GoalStoreDeps): GoalStore {
const pollIntervalMs = deps.pollIntervalMs ?? SESSION_GOAL_POLL_INTERVAL_MS
const entries = new Map<string, GoalEntry>()
function entryFor(sessionID: string): GoalEntry {
const existing = entries.get(sessionID)
if (existing) return existing
const entry: GoalEntry = {
sessionID,
goal: null,
listeners: new Set(),
timer: null,
abort: null,
loading: false,
version: 0,
errorBackoffMs: 0,
outcomeGoalId: null,
}
entries.set(sessionID, entry)
return entry
}
function clearTimer(entry: GoalEntry): void {
if (entry.timer === null) return
clearTimeout(entry.timer)
entry.timer = null
}
function isCurrent(entry: GoalEntry): boolean {
return entries.get(entry.sessionID) === entry
}
function hasListeners(entry: GoalEntry): boolean {
return entry.listeners.size > 0
}
function baseDelay(entry: GoalEntry): number {
return hasListeners(entry) ? pollIntervalMs : BACKGROUND_POLL_INTERVAL_MS
}
function wantsFollowing(entry: GoalEntry): boolean {
return isCurrent(entry) && (hasListeners(entry) || isOpenSessionGoal(entry.goal))
}
function schedule(entry: GoalEntry): void {
clearTimer(entry)
if (!wantsFollowing(entry)) return
const delay = entry.errorBackoffMs > 0 ? Math.min(entry.errorBackoffMs, MAX_ERROR_BACKOFF_MS) : baseDelay(entry)
entry.timer = setTimeout(() => {
entry.timer = null
void loadInto(entry)
}, delay)
}
function drop(entry: GoalEntry): void {
clearTimer(entry)
entry.abort?.abort()
entry.abort = null
entries.delete(entry.sessionID)
}
function applyGoal(entry: GoalEntry, goal: SessionGoal | null): void {
const previous = entry.goal
entry.goal = goal
for (const listener of entry.listeners) listener(goal)
if (goal !== null && entry.outcomeGoalId !== goal.id && isOpenSessionGoal(previous) && isTerminalSessionGoal(goal)) {
entry.outcomeGoalId = goal.id
deps.onOutcome(goal)
}
if (isOpenSessionGoal(goal)) {
schedule(entry)
return
}
clearTimer(entry)
if (!hasListeners(entry)) drop(entry)
}
function fail(entry: GoalEntry): void {
const current = entry.errorBackoffMs === 0 ? baseDelay(entry) : entry.errorBackoffMs
entry.errorBackoffMs = Math.min(current * 2, MAX_ERROR_BACKOFF_MS)
schedule(entry)
}
async function loadInto(entry: GoalEntry): Promise<void> {
if (entry.loading || !wantsFollowing(entry)) return
entry.loading = true
const version = ++entry.version
const controller = new AbortController()
entry.abort = controller
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)])
let goal: SessionGoal | null
try {
goal = await deps.load(entry.sessionID, signal)
} catch {
entry.loading = false
entry.abort = null
if (!isCurrent(entry)) return
fail(entry)
return
}
entry.loading = false
entry.abort = null
if (!isCurrent(entry)) return
if (version !== entry.version) {
schedule(entry)
return
}
entry.errorBackoffMs = 0
applyGoal(entry, goal)
}
return {
watch(sessionID, listener) {
const entry = entryFor(sessionID)
entry.listeners.add(listener)
if (entry.goal) listener(entry.goal)
void loadInto(entry)
return () => {
if (!entry.listeners.delete(listener)) return
if (hasListeners(entry)) return
if (isOpenSessionGoal(entry.goal)) {
schedule(entry)
return
}
drop(entry)
}
},
set(goal) {
const entry = entries.get(goal.sessionId)
if (!entry) return
entry.version++
applyGoal(entry, goal)
},
}
}
+4 -48
View File
@@ -4,14 +4,11 @@ import {
MirrorCheckoutsResponseSchema,
MirrorWorktreeCreateResponseSchema,
MultiRunSchema,
SessionGoalSchema,
type FuseMultiRunRequest,
type LaunchMultiRunRequest,
type MirrorCheckoutsResponse,
type MirrorWorktreeCreateResponse,
type MultiRun,
type SessionGoal,
type StartSessionGoalRequest,
} from '@opencode-manager/shared/schemas'
export interface MirrorBeginOpts {
@@ -78,7 +75,7 @@ function createByteCounter(onProgress: (bytesSent: number) => void): TransformSt
export const MANAGER_FEATURE_MISSING = 'MANAGER_FEATURE_MISSING'
const DEFAULT_FEATURE_NAME = 'ocm goals and multi-runs'
const DEFAULT_FEATURE_NAME = 'ocm multi-runs'
const MOVE_FEATURE_NAME = '/ocm-move worktrees'
function directoryQuery(directory: string | undefined): string {
@@ -160,7 +157,7 @@ export class ManagerApi {
})
if (!res.ok) {
const featureLabel = feature === true ? (featureName ?? DEFAULT_FEATURE_NAME) : null
throw await this.handleErrorResponse(res, operation, featureLabel, requestInit.signal ?? undefined)
throw await this.handleErrorResponse(res, operation, featureLabel)
}
return parse(await res.json())
}
@@ -169,11 +166,10 @@ export class ManagerApi {
res: Response,
operation: string,
featureName: string | null,
signal?: AbortSignal,
): Promise<ManagerApiError> {
const error = await formatErrorResponse(res, operation)
if (featureName !== null && error.status === 401) {
return this.probeFeatureSupport(operation, featureName, error, signal)
return this.probeFeatureSupport(operation, featureName, error)
}
return error
}
@@ -182,10 +178,9 @@ export class ManagerApi {
operation: string,
featureName: string,
fallback: ManagerApiError,
signal?: AbortSignal,
): Promise<ManagerApiError> {
try {
const res = await fetch(`${this.baseUrl}/api/internal/opencode-workspaces`, { headers: this.headers(), signal })
const res = await fetch(`${this.baseUrl}/api/internal/opencode-workspaces`, { headers: this.headers() })
if (res.ok) {
return new ManagerApiError(
`${operation} failed: this OpenCode Manager is too old for ${featureName}; upgrade the Manager.`,
@@ -382,45 +377,6 @@ export class ManagerApi {
return (await res.json()) as MirrorPatchSnapshot
}
getLatestSessionGoal(sessionId: string, signal?: AbortSignal): Promise<SessionGoal | null> {
return this.requestJson(
`/api/internal/session-goals?sessionId=${encodeURIComponent(sessionId)}`,
'read session goal',
(body) => SessionGoalSchema.nullable().parse((body as { goal: unknown }).goal),
{ signal, feature: true },
)
}
startSessionGoal(input: StartSessionGoalRequest): Promise<SessionGoal> {
return this.requestJson(
'/api/internal/session-goals',
'start session goal',
(body) => SessionGoalSchema.parse((body as { goal: unknown }).goal),
{ method: 'POST', body: JSON.stringify(input), feature: true },
)
}
private runSessionGoalAction(id: number, action: 'pause' | 'resume' | 'cancel'): Promise<SessionGoal> {
return this.requestJson(
`/api/internal/session-goals/${encodeURIComponent(id)}/${action}`,
`${action} session goal`,
(body) => SessionGoalSchema.parse((body as { goal: unknown }).goal),
{ method: 'POST', feature: true },
)
}
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')
}
listMultiRuns(repoId: number): Promise<MultiRun[]> {
return this.requestJson(
`/api/internal/multi-runs?repoId=${encodeURIComponent(repoId)}`,
-188
View File
@@ -1,188 +0,0 @@
/** @jsxImportSource @opentui/solid */
import { TextAttributes } from '@opentui/core'
import { useKeyboard } from '@opentui/solid'
import { createEffect, createSignal, on, onCleanup, Show } from 'solid-js'
import type { Context } from '@opencode/plugin/tui/context'
import { isOpenSessionGoal, type SessionGoal } from '@opencode-manager/shared/schemas'
import { getGoalOutcomeReason, getGoalOutcomeTitle, getGoalTokenLabel, getGoalTurnLabel } from '@opencode-manager/shared/notifications'
import type { GoalDialogProps } from './tui-goal.js'
import { DialogShell, TextAreaField, TextField, isSubmitKey, useFieldFocus } from './tui-form.js'
import type { DialogTheme } from './tui-form.js'
const FORM_FIELDS = 3
export function showGoalDialog(context: Context, props: GoalDialogProps): void {
context.ui.dialog.show(() => <GoalDialog context={context} {...props} />)
context.ui.dialog.set({ size: 'large' })
}
function GoalDialog(props: GoalDialogProps & { context: Context }) {
const theme: DialogTheme = props.context.theme.surface('dialog')
const [goal, setGoal] = createSignal<SessionGoal | null>(props.initialGoal)
const [busy, setBusy] = createSignal<string | null>(null)
const [error, setError] = createSignal<string | null>(null)
const [confirmCancel, setConfirmCancel] = createSignal(false)
const [objective, setObjective] = createSignal(props.initialObjective)
const [maxTurns, setMaxTurns] = createSignal('')
const [tokenBudget, setTokenBudget] = createSignal('')
onCleanup(props.store.watch(props.sessionID, (next) => setGoal(next)))
createEffect(on([objective, maxTurns, tokenBudget], () => setError(null), { defer: true }))
const openGoal = () => {
const current = goal()
return isOpenSessionGoal(current) ? current : null
}
const [field, setField] = useFieldFocus(() => FORM_FIELDS, () => openGoal() === null)
const run = async (label: string, operation: () => Promise<string | null>): Promise<string | null | undefined> => {
if (busy()) return undefined
setBusy(label)
setError(null)
const failure = await operation()
setBusy(null)
setError(failure)
return failure
}
const start = async () => {
const failure = await run('Starting goal…', () =>
props.actions.start({ objective: objective(), maxTurns: maxTurns(), tokenBudget: tokenBudget() }),
)
if (failure === null) props.context.ui.dialog.clear()
}
useKeyboard((event) => {
const current = openGoal()
if (!current) {
if (!isSubmitKey(event)) return
event.preventDefault()
void start()
return
}
if (event.name === 'p') {
event.preventDefault()
setConfirmCancel(false)
void run(current.status === 'paused' ? 'Resuming goal…' : 'Pausing goal…', () =>
current.status === 'paused' ? props.actions.resume(current) : props.actions.pause(current),
)
return
}
if (event.name === 'x') {
event.preventDefault()
if (!confirmCancel()) {
setConfirmCancel(true)
return
}
setConfirmCancel(false)
void run('Cancelling goal…', () => props.actions.cancel(current))
}
})
return (
<Show
when={openGoal()}
fallback={
<DialogShell
theme={theme}
title="Start goal"
subtitle="Runs until the Manager's auditor says it is done"
busy={busy()}
error={error()}
hints={[
['tab', 'next field'],
['ctrl+s', 'start goal'],
]}
>
<text fg={theme.text.muted}>Sends with this session's current agent and model; send a message first to switch.</text>
<Show when={goal()}>{(last) => <LastGoal theme={theme} goal={last()} />}</Show>
<TextAreaField
theme={theme}
label="Objective"
initialValue={props.initialObjective}
placeholder="What should this session accomplish?"
height={4}
focused={field() === 0}
onInput={setObjective}
/>
<box flexDirection="row" gap={4}>
<box flexGrow={1}>
<TextField
theme={theme}
label="Max turns"
initialValue=""
placeholder="Manager default"
focused={field() === 1}
onInput={setMaxTurns}
onSubmit={() => setField(2)}
/>
</box>
<box flexGrow={1}>
<TextField
theme={theme}
label="Token budget"
initialValue=""
placeholder="Manager default"
focused={field() === 2}
onInput={setTokenBudget}
onSubmit={() => void start()}
/>
</box>
</box>
</DialogShell>
}
>
{(current) => (
<DialogShell
theme={theme}
title="Session goal"
busy={busy()}
error={error()}
hints={[
['p', current().status === 'paused' ? 'resume' : 'pause'],
['x', 'cancel goal'],
]}
>
<GoalStatus theme={theme} goal={current()} />
<Show when={confirmCancel()}>
<text fg={theme.text.feedback.warning.base}>Press x again to cancel the goal. This cannot be undone.</text>
</Show>
</DialogShell>
)}
</Show>
)
}
function GoalStatus(props: { theme: DialogTheme; goal: SessionGoal }) {
const tone = () => (props.goal.status === 'active' ? props.theme.text.feedback.info.base : props.theme.text.feedback.warning.base)
return (
<box gap={1}>
<box flexDirection="row" gap={2} flexWrap="wrap">
<text fg={tone()} attributes={TextAttributes.BOLD}>
{getGoalOutcomeTitle(props.goal.status)}
</text>
<text fg={props.theme.text.muted}>{getGoalTurnLabel(props.goal)}</text>
<Show when={getGoalTokenLabel(props.goal)}>{(tokens) => <text fg={props.theme.text.muted}>{tokens()}</text>}</Show>
<text fg={props.theme.text.muted}>{props.goal.turnState === 'running' ? 'working' : 'waiting'}</text>
</box>
<text fg={props.theme.text.base}>{props.goal.objective}</text>
<Show when={getGoalOutcomeReason(props.goal)}>
{(reason) => (
<text fg={props.theme.text.muted}>
{props.goal.lastVerdict ? `Last verdict: ${props.goal.lastVerdict} · ` : ''}
{reason()}
</text>
)}
</Show>
</box>
)
}
function LastGoal(props: { theme: DialogTheme; goal: SessionGoal }) {
return (
<text fg={props.theme.text.muted} wrapMode="none" truncate>
Last goal: {getGoalOutcomeTitle(props.goal.status)}
{getGoalOutcomeReason(props.goal) ? ` · ${getGoalOutcomeReason(props.goal)}` : ''} · {props.goal.objective}
</text>
)
}
-202
View File
@@ -1,202 +0,0 @@
import type { Context, ToastOptions } from '@opencode/plugin/tui/context'
import {
GOAL_MAX_CONTINUATIONS_MAX,
GOAL_MAX_CONTINUATIONS_MIN,
StartSessionGoalRequestSchema,
isOpenSessionGoal,
type SessionGoal,
type StartSessionGoalRequest,
} from '@opencode-manager/shared/schemas'
import {
getGoalOutcomeReason,
getGoalOutcomeTitle,
getGoalTokenLabel,
getGoalTurnLabel,
} from '@opencode-manager/shared/notifications'
import { isManagerRouteMissing } from './manager-api.js'
import type { ManagerApi } from './manager-api.js'
import { resolveManagerApi } from './manager-auth.js'
import { describeCause } from './token-store.js'
import { requireSessionTarget, slashArgument } from './tui-dialogs.js'
import type { GoalStore } from './goal-store.js'
import type { RemoteContext } from './remote-context.js'
export const GOAL_COMMAND = 'ocm-goal'
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 GoalFormInput = {
objective: string
maxTurns: string
tokenBudget: string
}
export type GoalFormResult = { ok: true; request: StartSessionGoalRequest } | { ok: false; error: string }
/** Goal operations the goal dialog calls. Each resolves to an error message, or null on success. */
export type GoalActions = {
start(form: GoalFormInput): Promise<string | null>
pause(goal: SessionGoal): Promise<string | null>
resume(goal: SessionGoal): Promise<string | null>
cancel(goal: SessionGoal): Promise<string | null>
}
export type GoalDialogProps = {
sessionID: string
store: GoalStore
initialGoal: SessionGoal | null
initialObjective: string
actions: GoalActions
}
export type GoalCommandDeps = {
remote: RemoteContext | undefined
store: GoalStore | undefined
showDialog: (props: GoalDialogProps) => void
}
const GOAL_OBJECTIVE_MAX_LENGTH = 60
/** The objective's first line, cut to a single-line summary with a trailing ellipsis when long. */
export function goalObjectiveSummary(objective: string): string {
const newline = objective.indexOf('\n')
const firstLine = (newline === -1 ? objective : objective.slice(0, newline)).trim()
return firstLine.length > GOAL_OBJECTIVE_MAX_LENGTH ? `${firstLine.slice(0, GOAL_OBJECTIVE_MAX_LENGTH)}…` : firstLine
}
export function formatGoalStatus(goal: SessionGoal): string {
return [getGoalOutcomeTitle(goal.status), getGoalTurnLabel(goal), getGoalTokenLabel(goal), goalObjectiveSummary(goal.objective)]
.filter((part): part is string => part !== null)
.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: getGoalOutcomeReason(goal) ?? goalObjectiveSummary(goal.objective),
}
}
/** Validates the goal dialog fields into a start request; blank limits fall back to the Manager defaults. */
export function parseGoalForm(form: GoalFormInput, sessionId: string, directory: string): GoalFormResult {
const objective = form.objective.trim()
if (!objective) return { ok: false, error: 'Describe what this session should accomplish.' }
const maxContinuations = parseOptionalInteger(form.maxTurns)
if (
maxContinuations === null ||
(maxContinuations !== undefined &&
(maxContinuations < GOAL_MAX_CONTINUATIONS_MIN || maxContinuations > GOAL_MAX_CONTINUATIONS_MAX))
) {
return { ok: false, error: `Max turns must be a whole number from ${GOAL_MAX_CONTINUATIONS_MIN} to ${GOAL_MAX_CONTINUATIONS_MAX}.` }
}
const tokenBudget = parseOptionalInteger(form.tokenBudget)
if (tokenBudget === null || (tokenBudget !== undefined && tokenBudget <= 0)) {
return { ok: false, error: 'Token budget must be a positive whole number.' }
}
const parsed = StartSessionGoalRequestSchema.safeParse({
sessionId,
directory,
objective,
...(maxContinuations !== undefined ? { maxContinuations } : {}),
...(tokenBudget !== undefined ? { tokenBudget } : {}),
})
if (!parsed.success) return { ok: false, error: parsed.error.issues[0]?.message ?? 'Invalid goal.' }
return { ok: true, request: parsed.data }
}
export function describeGoalError(error: unknown): string {
if (isManagerRouteMissing(error)) return GOALS_ROUTE_MISSING
return describeCause(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 target = requireSessionTarget(context)
if (!target) return
const { sessionID, directory } = target
const resolved = await resolveManagerApi(deps.remote.managerUrl)
if (!resolved.ok) {
context.ui.toast.show({ variant: 'error', message: resolved.message })
return
}
const api = resolved.api
const store = deps.store
const actions = createGoalActions(context, api, store, sessionID, directory)
const objective = slashArgument(input, GOAL_COMMAND)
const existing = await api.getLatestSessionGoal(sessionID)
if (objective && !isOpenSessionGoal(existing)) {
const error = await actions.start({ objective, maxTurns: '', tokenBudget: '' })
if (error) context.ui.toast.show({ variant: 'error', message: error })
return
}
deps.showDialog({ sessionID, store, initialGoal: existing, initialObjective: objective, actions })
} catch (error) {
context.ui.toast.show({ variant: 'error', message: describeGoalError(error) })
}
}
function createGoalActions(context: Context, api: ManagerApi, store: GoalStore, sessionID: string, directory: string): GoalActions {
const run = async (operation: () => Promise<SessionGoal>): Promise<string | null> => {
try {
store.set(await operation())
return null
} catch (error) {
return describeGoalError(error)
}
}
return {
async start(form) {
const parsed = parseGoalForm(form, sessionID, directory)
if (!parsed.ok) return parsed.error
return startGoal(context, api, store, parsed.request)
},
pause: (goal) => run(() => api.pauseSessionGoal(goal.id)),
resume: (goal) => run(() => api.resumeSessionGoal(goal.id)),
cancel: (goal) => run(() => api.cancelSessionGoal(goal.id)),
}
}
async function startGoal(context: Context, api: ManagerApi, store: GoalStore, request: StartSessionGoalRequest): Promise<string | null> {
let goal: SessionGoal
try {
goal = await api.startSessionGoal(request)
} catch (error) {
return describeGoalError(error)
}
store.set(goal)
try {
await context.client.session.prompt({
sessionID: request.sessionId,
text: request.objective,
delivery: context.data.session.status(request.sessionId) === 'running' ? 'queue' : undefined,
})
return null
} catch (error) {
const cancelled = await api.cancelSessionGoal(goal.id).catch(() => undefined)
if (cancelled) store.set(cancelled)
return `The goal was cancelled because the objective could not be sent: ${describeCause(error)}`
}
}
function parseOptionalInteger(value: string): number | undefined | null {
const trimmed = value.trim()
if (!trimmed) return undefined
return /^\d+$/.test(trimmed) ? Number(trimmed) : null
}
-15
View File
@@ -14,25 +14,20 @@ 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 { GOAL_COMMAND, runGoalCommand } from './tui-goal.js'
import type { GoalDialogProps } from './tui-goal.js'
import { MULTI_RUN_COMMAND, runMultiRunCommand } from './tui-multi-run.js'
import type { MultiRunLaunchDialogProps, MultiRunsDialogProps } from './tui-multi-run.js'
import { runOcmSwitch } from './tui-ocm.js'
import type { GoalStore } from './goal-store.js'
import type { RemoteContext } from './remote-context.js'
export type MoveProgressSetter = (progress: MoveProgress | null) => void
export type OcmDialogs = {
goal: (props: GoalDialogProps) => void
multiRunLaunch: (props: MultiRunLaunchDialogProps) => void
multiRuns: (props: MultiRunsDialogProps) => void
}
export type OcmFeatures = {
remote: RemoteContext | undefined
goals: GoalStore | undefined
dialogs: OcmDialogs
}
@@ -62,16 +57,6 @@ export async function setupOcm(context: Context, setMoveProgress: MoveProgressSe
slash: { name: 'ocm' },
run: () => runOcmSwitch(context, { remote: features.remote }),
},
{
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_COMMAND, arguments: true },
run: (input) =>
runGoalCommand(context, { remote: features.remote, store: features.goals, showDialog: features.dialogs.goal }, input),
},
{
id: 'ocm.multirun',
title: 'Multi-run',
+3 -52
View File
@@ -1,18 +1,13 @@
/** @jsxImportSource @opentui/solid */
import { createSignal, createEffect, onCleanup, Show } from 'solid-js'
import { Plugin } from '@opencode/plugin/tui'
import type { HueScale } from '@opencode/theme/tui'
import { setupOcm } from './tui-plugin.js'
import { showGoalDialog } from './tui-goal-dialog.js'
import { showMultiRunLaunchDialog, showMultiRunsDialog } from './tui-multi-run-dialogs.js'
import { formatMoveProgress } from './move-progress.js'
import type { MoveProgress } from './move-progress.js'
import { readRemoteContext, remoteDisplayName } from './remote-context.js'
import { readState } from './state.js'
import { createGoalStore } from './goal-store.js'
import type { GoalStore } from './goal-store.js'
import { formatGoalStatus, goalOutcomeToast } from './tui-goal.js'
import { resolveManagerApi } from './manager-auth.js'
import { isOpenSessionGoal, type SessionGoal } from '@opencode-manager/shared/schemas'
const SPINNER_INTERVAL_MS = 80
@@ -42,9 +37,10 @@ export default Plugin.define({
const remote = readRemoteContext(process.env)
if (remote) {
const managerLabel = remoteDisplayName(remote, readState())
const namedHues: Readonly<Record<string, HueScale | undefined>> = context.theme.hue
const indicator = () => (
<box flexDirection="row" flexShrink={0} gap={1}>
<text fg={context.theme.hue.orange?.[400] ?? context.theme.text.feedback.warning.base}>{managerLabel}</text>
<text fg={namedHues.orange?.[400] ?? context.theme.text.feedback.warning.base}>{managerLabel}</text>
{remote.repoName && <text fg={context.theme.text.muted}> · {remote.repoName}</text>}
</box>
)
@@ -53,54 +49,9 @@ export default Plugin.define({
context.ui.slot({ append: 'home.footer.status', render: indicator })
}
const goals = remote
? createGoalStore({
load: async (sessionID, signal) => {
const resolved = await resolveManagerApi(remote.managerUrl)
if (!resolved.ok) throw new Error(resolved.message)
return resolved.api.getLatestSessionGoal(sessionID, signal)
},
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 isOpenSessionGoal(current) ? current : null
}
return (
<Show when={openGoal()}>
{(current) => (
<box flexDirection="row" flexShrink={0}>
<text wrapMode="none" 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,
dialogs: {
goal: (props) => showGoalDialog(context, props),
multiRunLaunch: (props) => showMultiRunLaunchDialog(context, props),
multiRuns: (props) => showMultiRunsDialog(context, props),
},
-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 () => {