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 })
},
})