diff --git a/cli/src/opencode/opencodeRemoteLauncher.test.ts b/cli/src/opencode/opencodeRemoteLauncher.test.ts index 4d2474e5..fd069db7 100644 --- a/cli/src/opencode/opencodeRemoteLauncher.test.ts +++ b/cli/src/opencode/opencodeRemoteLauncher.test.ts @@ -56,6 +56,7 @@ const harness = vi.hoisted(() => ({ sessionId: string; onRetry: (retry: { attempt: number; message: string }) => void; onEvent?: (type: string, properties: Record, eventId?: string) => void; + onGoalChange?: (goal: unknown) => void; }>, eventStreamCloseCount: 0, // Soft-steer (mid-turn inject) controls. @@ -1837,6 +1838,16 @@ describe('opencodeRemoteLauncher inline model switch', () => { expect(JSON.stringify(harness.promptContents[1])).not.toContain('skill_lookup'); }); + it('forwards a /goal batch verbatim over ACP without the first-prompt instruction prefix', async () => { + const { session } = createSessionStub([ + { message: '/goal ship the login fix', mode: { ...createMode(), operation: 'goal' } } + ]); + + await opencodeRemoteLauncher(session as never); + + expect(harness.promptContents).toEqual([[{ type: 'text', text: '/goal ship the login fix' }]]); + }); + it('spawns the ACP backend with an explicit --port/--hostname from allocateFreePort', async () => { const { session } = createSessionStub([ { message: 'first', mode: createMode() } @@ -4725,6 +4736,28 @@ describe('opencodeRemoteLauncher v2 flavor wiring', () => { } }); + it('v2: projects an OpenCode goal change to the status panel', async () => { + harness.detectedVersion = 'v2'; + harness.discoveredPort = 41234; + harness.discoveredPassword = 'pw-secret'; + harness.sessionModelsMetadata = { currentModelId: 'ollama/x', availableModels: [] }; + const { session, agentMessages } = createSessionStub([], { keepOpen: true }); + + const launcherPromise = opencodeRemoteLauncher(session as never); + await vi.waitFor(() => expect(harness.eventStreamOptions).toHaveLength(1)); + + harness.eventStreamOptions[0].onGoalChange!({ + id: 'goal-1', objective: 'ship it', status: 'active', rounds: 2, maxRounds: 50, updatedAt: 1 + }); + + expect(agentMessages).toContainEqual(expect.objectContaining({ + type: 'thread_goal_updated', + goal: expect.objectContaining({ objective: 'ship it', status: 'active' }) + })); + session.queue.close(); + await launcherPromise; + }); + it('v2: reports one automatic application start without changing turn thinking for preparation', async () => { harness.detectedVersion = 'v2'; harness.discoveredPort = 41234; diff --git a/cli/src/opencode/opencodeRemoteLauncher.ts b/cli/src/opencode/opencodeRemoteLauncher.ts index 47420f07..122daf14 100644 --- a/cli/src/opencode/opencodeRemoteLauncher.ts +++ b/cli/src/opencode/opencodeRemoteLauncher.ts @@ -40,6 +40,7 @@ import { } from './utils/opencodeCompactBridge'; import { OpencodeNativeTranscript } from './utils/opencodeNativeTranscript'; import { opencodeCompactionEventId } from './utils/opencodeCompactionProjector'; +import { asOpencodeGoalState, fetchOpencodeGoal, type OpencodeGoalState } from './utils/opencodeGoal'; import { formatOpencodePromptError } from './utils/opencodeErrorText'; import { formatOpencodeRetryStatus, @@ -202,6 +203,10 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { /** Subscription to the agent's own server event stream; null until the ACP session id is known, closed in cleanup(). */ private eventStream: OpencodeEventSubscription | null = null; private nativeTranscript: OpencodeNativeTranscript | null = null; + /** Latest goal read from OpenCode's plugin RPC, projected to the hub for the status panel. */ + private goalState: OpencodeGoalState | null = null; + private goalProjectionKey: string | null = null; + private goalPollTimer: ReturnType | null = null; private stallErrorReportedForPrompt = false; /** True while a normal (non-compact/clear) prompt turn is in flight — the only steerable state. */ private promptInFlight = false; @@ -440,7 +445,13 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { }, onReadFailure: () => session.sendSessionEvent({ type: 'message', message: 'OpenCode native transcript is temporarily unavailable. Retrying on reconnect or at the end of the turn.' }), onText: (part) => { - if (this.majorVersion !== 'v1' || part.role !== 'assistant') return; + if (part.role !== 'assistant') return; + // v1 has no ACP text path. In v2 ACP owns the text of an active + // prompt turn; only background turns (the /goal loop runs via + // the core plugin's `experimental.idle` hook, outside ACP) + // need the native event bridge. Without this the goal loop is + // healthy but completely invisible in HAPI. + if (this.majorVersion === 'v2' && this.promptInFlight) return; const converted = convertAgentMessage(part.type === 'reasoning' ? { type: 'reasoning', id: part.id, text: part.text, live: !part.complete } : { type: 'text', id: part.id, text: part.text, streamSnapshot: true, live: !part.complete }); @@ -465,12 +476,38 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { } : undefined, mode: this.majorVersion ?? 'v1', onRetry: (retry) => this.surfaceUpstreamRetry(retry), - onConnected: () => { void this.nativeTranscript?.refresh(); }, + onConnected: () => { + void this.nativeTranscript?.refresh(); + if (this.majorVersion === 'v2' && this.v2RestInfo) { + void fetchOpencodeGoal({ + baseUrl: restBaseUrl, + directory: session.path, + sessionID: acpSessionId, + headers: nativeHeaders ?? {} + }).then(goal => this.projectGoal(session, acpSessionId, goal, true)).catch(() => {}); + } + }, onEvent: (type, properties, eventId) => { this.nativeTranscript?.event(type, properties, eventId); this.handleV2SteerEvent(type, properties); - } + }, + onGoalChange: (value) => this.projectGoal(session, acpSessionId, asOpencodeGoalState(value)) }); + if (this.majorVersion === 'v2' && this.v2RestInfo) { + const readGoal = () => { + void fetchOpencodeGoal({ + baseUrl: restBaseUrl, + directory: session.path, + sessionID: acpSessionId, + headers: nativeHeaders ?? {} + }).then(goal => this.projectGoal(session, acpSessionId, goal)).catch(() => {}); + }; + // A goal can be paused by *another* OpenCode server boot, whose + // `changed` event never reaches this session's event stream. Poll + // so the status panel cannot stay stuck on "active". + this.goalPollTimer = setInterval(() => { if (!this.shouldExit) readGoal(); }, 5_000); + this.goalPollTimer.unref?.(); + } } // Seed currentBackendModel from the ACP session metadata so the first @@ -911,12 +948,19 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { continue; } + // /goal is OpenCode's own slash command: its core plugin parses + // the objective and the pause/resume/clear controls. Keep the text + // byte-for-byte as the user typed it — the instruction prefix and + // the native REST prompt path below would both hide the leading + // "/" from OpenCode's ACP command detector. + const isGoalBatch = batch.mode.operation === 'goal'; + // Inject title instructions on first prompt let messageText = batch.message; - if (batch.mode.permissionMode === 'plan') { + if (!isGoalBatch && batch.mode.permissionMode === 'plan') { messageText = `${PLAN_MODE_INSTRUCTION}\n\n${messageText}`; } - if (!this.instructionsSent) { + if (!isGoalBatch && !this.instructionsSent) { messageText = `${getOpencodeNativeToolInstruction()}\n\n${messageText}`; this.instructionsSent = true; } @@ -946,7 +990,7 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { ? this.currentBackendEffort : null; const nativeModel = splitProviderModel(this.currentBackendModel); - if (nativeVariant && nativeModel && backend.promptWithVariant && this.baseUrl) { + if (!isGoalBatch && nativeVariant && nativeModel && backend.promptWithVariant && this.baseUrl) { await backend.promptWithVariant(acpSessionId, promptContent, (message: AgentMessage) => { this.handleAgentMessage(message); }, { @@ -1284,6 +1328,44 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { ); } + /** + * Project OpenCode's goal into the shapes the web already understands for + * Codex: a `thread_goal_updated` event feeds the top status panel. The + * goal loop itself runs outside ACP, so this is the only signal HAPI can + * see; the loop's text is projected by the native transcript instead. + */ + private projectGoal(session: OpencodeSession, acpSessionId: string, goal: OpencodeGoalState | null, forceClear = false): void { + // On attach we must clear a goal left in the hub by a previous CLI + // process even though this process has never seen one. + if (!goal && !this.goalState && !forceClear) return; + const key = goal ? `${goal.id}:${goal.status}:${goal.rounds}:${goal.objective}` : null; + if (key === this.goalProjectionKey) return; + this.goalProjectionKey = key; + this.goalState = goal; + // A goal loop runs outside ACP turns, so nothing else marks the + // session as working. Without this the session list shows it idle + // while the agent is actively working through rounds. + if (!this.promptInFlight) session.onThinkingChange(goal?.status === 'active'); + if (!goal) { + session.client.sendAgentMessage({ type: 'thread_goal_cleared', thread_id: acpSessionId }); + return; + } + const webGoal = { + source: 'opencode' as const, + threadId: acpSessionId, + objective: goal.objective, + status: goal.status, + // OpenCode counts continuation rounds, not tokens. Keep them in + // their own fields so the UI never labels them as tokens. + rounds: goal.rounds, + maxRounds: goal.maxRounds, + createdAt: goal.updatedAt, + updatedAt: goal.updatedAt, + timeUsedSeconds: 0 + }; + session.client.sendAgentMessage({ type: 'thread_goal_updated', thread_id: acpSessionId, goal: webGoal }); + } + private handleV2SteerEvent(type: string, properties: Record): void { if (this.majorVersion !== 'v2' || typeof properties.inboxID !== 'string') return; for (const entry of this.v2Steers.values()) { @@ -1632,6 +1714,10 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase { })); // Before anything that can fail: a stream left open would keep // reconnecting to a subprocess that is on its way out. + if (this.goalPollTimer) { + clearInterval(this.goalPollTimer); + this.goalPollTimer = null; + } this.nativeTranscript?.close(); this.nativeTranscript = null; this.eventStream?.close(); diff --git a/cli/src/opencode/runOpencode.test.ts b/cli/src/opencode/runOpencode.test.ts index 654915f4..164473f9 100644 --- a/cli/src/opencode/runOpencode.test.ts +++ b/cli/src/opencode/runOpencode.test.ts @@ -415,6 +415,35 @@ describe('runOpencode set-session-config handler', () => { expect(harness.session.sendAgentMessage).not.toHaveBeenCalled(); }); + it('queues /goal verbatim as its own isolated operation', async () => { + await runOpencode({}); + + const messageQueue = harness.opencodeLoopArgs[0]?.messageQueue as + { queue: Array<{ message: string; mode: { operation?: string }; localId?: string; isolate?: boolean }> }; + + const userMessageHandler = harness.session.onUserMessage.mock.calls[0]?.[0] as + ((msg: { content: { text: string; attachments?: unknown[] } }, localId?: string) => void) + | undefined; + expect(userMessageHandler).toBeDefined(); + + userMessageHandler!({ content: { text: '/goal ship the login fix' } }, 'local-goal'); + for (let i = 0; i < 5; i++) { + await new Promise((resolve) => setTimeout(resolve, 0)); + } + + expect(messageQueue.queue).toEqual([ + { + message: '/goal ship the login fix', + mode: expect.objectContaining({ operation: 'goal' }), + modeHash: expect.any(String), + localId: 'local-goal', + isolate: true + } + ]); + // OpenCode owns the command; HAPI must not answer it synchronously. + expect(harness.session.sendAgentMessage).not.toHaveBeenCalled(); + }); + it('queues runner-backed /clear as its own FIFO operation without acknowledging it early', async () => { await runOpencode({ startedBy: 'runner' }); diff --git a/cli/src/opencode/runOpencode.ts b/cli/src/opencode/runOpencode.ts index f79ac4fc..bbefef46 100644 --- a/cli/src/opencode/runOpencode.ts +++ b/cli/src/opencode/runOpencode.ts @@ -371,6 +371,18 @@ export async function runOpencode(opts: { return; } + if (slash.kind === 'goal') { + // OpenCode owns this command (core plugin, v2.2.1+): it + // parses the objective and the pause/resume/clear controls + // itself. Queue the raw slash text as an isolated item so + // the remote launcher forwards it verbatim over ACP, and + // local mode's PTY hands it straight to the TUI. Like + // /compact, it is acked automatically at dequeue time and + // keeps its real FIFO position via pushIsolated. + messageQueue.pushIsolated(slash.text, { ...buildMode(), operation: 'goal' }, localId); + return; + } + if (slash.kind !== 'passthrough') { if (slash.updates) { if (slash.updates.permissionMode !== undefined) { diff --git a/cli/src/opencode/types.ts b/cli/src/opencode/types.ts index aed1451d..0b416121 100644 --- a/cli/src/opencode/types.ts +++ b/cli/src/opencode/types.ts @@ -16,7 +16,7 @@ export interface OpencodeMode { // calling `backend.prompt()`, which keeps /compact from "cutting in // line" ahead of prompts that were already queued when it arrived. // `undefined` for normal prompts. - operation?: 'compact' | 'clear'; + operation?: 'compact' | 'clear' | 'goal'; } export type OpencodeHookEvent = { diff --git a/cli/src/opencode/utils/opencodeCompactionProjector.ts b/cli/src/opencode/utils/opencodeCompactionProjector.ts index b7a11d88..e187ad3f 100644 --- a/cli/src/opencode/utils/opencodeCompactionProjector.ts +++ b/cli/src/opencode/utils/opencodeCompactionProjector.ts @@ -100,7 +100,7 @@ export class OpencodeCompactionProjector { private projectText(parts: Iterable = this.parts.values()): void { for (const part of parts) { - if ((part.type !== 'text' && part.type !== 'reasoning') || typeof part.text !== 'string') continue; + if ((part.type !== 'text' && part.type !== 'reasoning') || typeof part.text !== 'string' || !part.text.trim()) continue; const info = typeof part.messageID === 'string' ? this.messages.get(part.messageID) : undefined; if (!info || info.summary === true || info.type === 'compaction' || part.ignored === true) continue; if (part.synthetic === true && isObject(part.metadata) && part.metadata.compaction_continue === true) continue; diff --git a/cli/src/opencode/utils/opencodeEventStream.ts b/cli/src/opencode/utils/opencodeEventStream.ts index 412254f7..5637a82b 100644 --- a/cli/src/opencode/utils/opencodeEventStream.ts +++ b/cli/src/opencode/utils/opencodeEventStream.ts @@ -2,6 +2,7 @@ import { asNumber, asString, isObject } from '@hapi/protocol'; import { logger } from '@/ui/logger'; import type { FetchLike } from './opencodeCompactBridge'; import { collapseWhitespace, truncateOpencodeProviderText } from './opencodeErrorText'; +import { extractOpencodeGoalChange } from './opencodeGoal'; /** * `session.status` with `type: "retry"` — OpenCode announcing that it hit an @@ -39,6 +40,8 @@ export type OpencodeEventStreamOptions = { onRetry: (retry: OpencodeRetryStatus) => void; /** Native transcript consumer; receives normalized, session-scoped events. */ onEvent?: (type: string, properties: Record, eventId?: string) => void; + /** `rpc.opencode.goal.changed` payloads. Goal events are not ordinary session messages. */ + onGoalChange?: (goal: unknown) => void; onConnected?: () => void; /** * Extra request headers merged into every (re)connect attempt. Required @@ -290,6 +293,16 @@ export function subscribeToOpencodeEvents(options: OpencodeEventStreamOptions): const handleEvent = (event: unknown): void => { if (!isObject(event)) return; const properties = isObject(event.properties) ? event.properties : null; + const goalType = typeof event.type === 'string' && event.type.includes('goal.changed') + || isObject(properties) && typeof properties.type === 'string' && properties.type.includes('goal.changed') + || isObject(properties) && isObject(properties.data) && typeof properties.data.type === 'string' + && properties.data.type.includes('goal.changed'); + if (goalType && properties) { + const change = extractOpencodeGoalChange(properties); + if (change && (!change.sessionID || change.sessionID === sessionId)) { + options.onGoalChange?.(change.goal); + } + } if (properties && typeof event.type === 'string') { const record = isObject(properties.info) ? properties.info : isObject(properties.part) ? properties.part : properties; if (record.sessionID === sessionId) options.onEvent?.(event.type, properties, typeof event.id === 'string' ? event.id : undefined); diff --git a/cli/src/opencode/utils/opencodeGoal.test.ts b/cli/src/opencode/utils/opencodeGoal.test.ts new file mode 100644 index 00000000..f44e2eab --- /dev/null +++ b/cli/src/opencode/utils/opencodeGoal.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from 'vitest'; +import { asOpencodeGoalState, extractOpencodeGoalChange, fetchOpencodeGoal } from './opencodeGoal'; + +describe('asOpencodeGoalState', () => { + it('accepts a live OpenCode goal', () => { + expect(asOpencodeGoalState({ + id: 'goal-1', + objective: 'ship it', + status: 'active', + rounds: 3, + maxRounds: 50, + boot: 'boot-1', + updatedAt: 123 + })).toMatchObject({ id: 'goal-1', status: 'active', rounds: 3 }); + }); + + it('rejects malformed or unsupported statuses', () => { + expect(asOpencodeGoalState(null)).toBeNull(); + expect(asOpencodeGoalState({ id: 'g', objective: 'x', status: 'waiting', rounds: 0, maxRounds: 50 })).toBeNull(); + expect(asOpencodeGoalState({ id: 'g', objective: '', status: 'active', rounds: 0, maxRounds: 50 })).toBeNull(); + }); +}); + +describe('extractOpencodeGoalChange', () => { + it('reads a flat goal.changed payload', () => { + expect(extractOpencodeGoalChange({ sessionID: 'ses_1', goal: { id: 'g' } })).toEqual({ + sessionID: 'ses_1', goal: { id: 'g' } + }); + }); + + it('walks the v2 data envelope', () => { + expect(extractOpencodeGoalChange({ + type: 'rpc.opencode.goal.changed', + data: { data: { sessionID: 'ses_1', goal: null } } + })).toEqual({ sessionID: 'ses_1', goal: null }); + }); + + it('returns null when no goal payload exists', () => { + expect(extractOpencodeGoalChange({ sessionID: 'ses_1' })).toBeNull(); + expect(extractOpencodeGoalChange(null)).toBeNull(); + }); +}); + +describe('fetchOpencodeGoal', () => { + it('reads opencode.goal/get through the plugin RPC', async () => { + const goal = { id: 'g', objective: 'ship', status: 'paused', rounds: 2, maxRounds: 50, updatedAt: 9 }; + let seenUrl = ''; + let seenBody = ''; + const response = { + ok: true, + json: async () => ({ output: goal }) + } as Response; + const fetchImpl = (async (url: string | URL | Request, init?: RequestInit) => { + seenUrl = String(url); + seenBody = String(init?.body ?? ''); + return response; + }) as unknown as typeof fetch; + + const result = await fetchOpencodeGoal({ + baseUrl: 'http://127.0.0.1:1234', + directory: '/project', + sessionID: 'ses_1', + headers: { authorization: 'Basic abc' }, + fetchImpl + }); + + expect(seenUrl).toContain('/api/rpc/opencode.goal/get?directory=%2Fproject'); + expect(JSON.parse(seenBody)).toEqual({ input: { sessionID: 'ses_1' } }); + expect(result).toMatchObject({ id: 'g', status: 'paused' }); + }); + + it('returns null on a failed RPC call', async () => { + const fetchImpl = (async () => ({ ok: false, json: async () => ({}) }) as Response) as unknown as typeof fetch; + await expect(fetchOpencodeGoal({ + baseUrl: 'http://127.0.0.1:1234', directory: '/p', sessionID: 's', headers: {}, fetchImpl + })).resolves.toBeNull(); + }); +}); diff --git a/cli/src/opencode/utils/opencodeGoal.ts b/cli/src/opencode/utils/opencodeGoal.ts new file mode 100644 index 00000000..bdcb067a --- /dev/null +++ b/cli/src/opencode/utils/opencodeGoal.ts @@ -0,0 +1,70 @@ +import { isObject } from '@hapi/protocol'; + +/** The subset of OpenCode's `Goal.State` HAPI projects into the session. */ +export type OpencodeGoalState = { + id: string; + objective: string; + status: 'active' | 'paused' | 'complete'; + rounds: number; + maxRounds: number; + reason?: string; + updatedAt: number; +}; + +export function asOpencodeGoalState(value: unknown): OpencodeGoalState | null { + if (!isObject(value)) return null; + const { id, objective, status, rounds, maxRounds, updatedAt } = value; + if (typeof id !== 'string' || typeof objective !== 'string' || !objective.trim()) return null; + if (status !== 'active' && status !== 'paused' && status !== 'complete') return null; + if (typeof rounds !== 'number' || typeof maxRounds !== 'number') return null; + return { + id, + objective, + status, + rounds, + maxRounds, + ...(typeof value.reason === 'string' ? { reason: value.reason } : {}), + ...(typeof updatedAt === 'number' ? { updatedAt } : { updatedAt: 0 }) + }; +} + +/** Read a goal through OpenCode's plugin RPC (`opencode.goal/get`). */ +export async function fetchOpencodeGoal(opts: { + baseUrl: string; + directory: string; + sessionID: string; + headers: Record; + fetchImpl?: typeof fetch; +}): Promise { + const url = `${opts.baseUrl}/api/rpc/opencode.goal/get?directory=${encodeURIComponent(opts.directory)}`; + const response = await (opts.fetchImpl ?? fetch)(url, { + method: 'POST', + headers: { 'content-type': 'application/json', ...opts.headers }, + body: JSON.stringify({ input: { sessionID: opts.sessionID } }), + signal: AbortSignal.timeout(10_000) + }); + if (!response.ok) return null; + const body: unknown = await response.json(); + const output = isObject(body) ? body.output : undefined; + return asOpencodeGoalState(output ?? null); +} + +/** + * Pull `{ sessionID, goal }` out of an `rpc.opencode.goal.changed` event. + * v2 event frames wrap the body twice (`{ type, data: { type, data, location } }` + * in some builds, flat `{ type, data: { sessionID, goal } }` in others), so + * walk a bounded number of `data` levels instead of assuming one shape. + */ +export function extractOpencodeGoalChange(properties: unknown): { sessionID?: string; goal: unknown } | null { + if (!isObject(properties)) return null; + let current: Record = properties; + for (let depth = 0; depth < 4; depth++) { + if ('sessionID' in current || 'goal' in current) { + const sessionID = typeof current.sessionID === 'string' ? current.sessionID : undefined; + if ('goal' in current) return { sessionID, goal: current.goal }; + } + if (!isObject(current.data)) return null; + current = current.data; + } + return null; +} diff --git a/cli/src/opencode/utils/opencodeNativeTranscript.test.ts b/cli/src/opencode/utils/opencodeNativeTranscript.test.ts index de321628..38f02fed 100644 --- a/cli/src/opencode/utils/opencodeNativeTranscript.test.ts +++ b/cli/src/opencode/utils/opencodeNativeTranscript.test.ts @@ -190,6 +190,39 @@ describe('OpenCode native transcript reconciliation', () => { }); +describe('v2 background turn text (OpenCode 2.2.x events)', () => { + it('projects session.text.delta and finalizes on session.step.ended', () => { + const onText = vi.fn(); + const transcript = new OpencodeNativeTranscript({ + baseUrl: 'http://127.0.0.1:1', sessionId: 'ses', directory: '/project', mode: 'v2', + fetchImpl: vi.fn(async () => Response.json([])), onSummary: vi.fn(), onText + }); + + transcript.event('session.text.started', { sessionID: 'ses', assistantMessageID: 'msg1', ordinal: 0 }); + transcript.event('session.text.delta', { sessionID: 'ses', assistantMessageID: 'msg1', ordinal: 0, delta: 'hello ' }); + transcript.event('session.text.delta', { sessionID: 'ses', assistantMessageID: 'msg1', ordinal: 0, delta: 'world' }); + transcript.event('session.step.ended', { sessionID: 'ses', assistantMessageID: 'msg1' }); + + expect(onText).toHaveBeenCalledWith(expect.objectContaining({ + id: 'v2:msg1:0', messageId: 'msg1', role: 'assistant', type: 'text', + text: 'hello world', complete: true + })); + transcript.close(); + }); + + it('ignores text events from another session', () => { + const onText = vi.fn(); + const transcript = new OpencodeNativeTranscript({ + baseUrl: 'http://127.0.0.1:1', sessionId: 'ses', directory: '/project', mode: 'v2', + fetchImpl: vi.fn(async () => Response.json([])), onSummary: vi.fn(), onText + }); + + transcript.event('session.text.delta', { sessionID: 'foreign', assistantMessageID: 'm', ordinal: 0, delta: 'nope' }); + expect(onText).not.toHaveBeenCalled(); + transcript.close(); + }); +}); + describe('v2 durable application start', () => { it('keeps the start identity across fast completion and running snapshot replay without observing preparation usage', async () => { const onStart = vi.fn(), onSummary = vi.fn(); diff --git a/cli/src/opencode/utils/opencodeNativeTranscript.ts b/cli/src/opencode/utils/opencodeNativeTranscript.ts index 6fbf0bc8..af25f55d 100644 --- a/cli/src/opencode/utils/opencodeNativeTranscript.ts +++ b/cli/src/opencode/utils/opencodeNativeTranscript.ts @@ -1,4 +1,4 @@ -import { isObject } from '@hapi/protocol'; +import { asString, isObject } from '@hapi/protocol'; import type { FetchLike } from './opencodeCompactBridge'; import { logger } from '@/ui/logger'; import { OpencodeCompactionProjector, type OpencodeNativeText, type OpencodeCompactionTrigger } from './opencodeCompactionProjector'; @@ -20,6 +20,8 @@ export class OpencodeNativeTranscript { private readonly unbasedDeltas = new Map(); private readonly pendingText = new Map(); private readonly textTimers = new Map>(); + /** v2.2+ replaced `message.part.updated` with `session.text.*` events. */ + private readonly v2Text = new Map(); constructor(private readonly options: { baseUrl: string; @@ -84,6 +86,37 @@ export class OpencodeNativeTranscript { this.unbasedDeltas.set(properties.partID, (this.unbasedDeltas.get(properties.partID) ?? '') + properties.delta); } } + // OpenCode 2.2.x no longer emits `message.updated`/`message.part.updated` + // for assistant turns. Text arrives as `session.text.started` + + // `session.text.delta`, and a step closes with `session.step.ended`. + // ACP owns the text of a foreground prompt; these events are what + // remains visible for the /goal loop's background turns. + if (this.options.mode === 'v2' && isObject(properties) + && properties.sessionID === this.options.sessionId) { + const messageID = asString(properties.assistantMessageID); + const ordinal = asString(properties.ordinal) ?? '0'; + const key = messageID ? `${messageID}:${ordinal}` : null; + if (key && type === 'session.text.started') { + this.v2Text.set(key, { text: '' }); + } else if (key && type === 'session.text.delta' && typeof properties.delta === 'string') { + const entry = this.v2Text.get(key) ?? { text: '' }; + entry.text += properties.delta; + this.v2Text.set(key, entry); + this.emitText({ + id: `v2:${key}`, messageId: messageID!, role: 'assistant', + type: 'text', text: entry.text, complete: false + }); + } else if (messageID && type === 'session.step.ended') { + for (const [openKey, entry] of this.v2Text) { + if (!openKey.startsWith(`${messageID}:`)) continue; + this.emitText({ + id: `v2:${openKey}`, messageId: messageID, role: 'assistant', + type: 'text', text: entry.text, complete: true + }); + this.v2Text.delete(openKey); + } + } + } if (type === 'session.status' && isObject(properties.status) && properties.status.type === 'idle') void this.refresh(); if (type.startsWith('session.compaction.')) void this.refresh(); } diff --git a/cli/src/opencode/utils/slashCommands.test.ts b/cli/src/opencode/utils/slashCommands.test.ts index 2711b1b9..87849303 100644 --- a/cli/src/opencode/utils/slashCommands.test.ts +++ b/cli/src/opencode/utils/slashCommands.test.ts @@ -127,6 +127,20 @@ describe('resolveOpencodeSlashCommand', () => { expect(resolveOpencodeSlashCommand('/compact', state)).toEqual({ kind: 'compact' }); }); + it('forwards /goal verbatim so OpenCode parses the objective itself', () => { + expect(resolveOpencodeSlashCommand('/goal ship the login fix', state)).toEqual({ + kind: 'goal', + text: '/goal ship the login fix' + }); + }); + + it.each(['pause', 'resume', 'clear'])('forwards /goal %s verbatim', (control) => { + expect(resolveOpencodeSlashCommand(`/goal ${control}`, state)).toEqual({ + kind: 'goal', + text: `/goal ${control}` + }); + }); + it('resolves /compact the same way regardless of trailing arguments (compaction takes no arguments)', () => { expect(resolveOpencodeSlashCommand('/compact now please', state)).toEqual({ kind: 'compact' }); }); @@ -165,6 +179,7 @@ describe('resolveOpencodeSlashCommand', () => { expect(help.message).toContain('/plan'); expect(help.message).toContain('/permissions'); expect(help.message).toContain('/compact` — compact (summarize) the OpenCode session context (remote sessions only)'); + expect(help.message).toContain('/goal ` — keep working until a reviewer confirms the objective is met (OpenCode v2.2.1+)'); expect(help.message).toContain('/clear` — archive this HAPI session and open a fresh OpenCode session'); } }); diff --git a/cli/src/opencode/utils/slashCommands.ts b/cli/src/opencode/utils/slashCommands.ts index 91c24180..50e3d1e6 100644 --- a/cli/src/opencode/utils/slashCommands.ts +++ b/cli/src/opencode/utils/slashCommands.ts @@ -27,6 +27,12 @@ export type OpencodeSlashResolution = // /clear exits the current runner-backed HAPI process after its FIFO // predecessors finish, then asks the hub to spawn a fresh OpenCode one. | { kind: 'clear' } + // /goal is OpenCode's native persistent-objective command (core plugin, + // v2.2.1+). The launcher must forward the raw slash text over ACP so + // OpenCode parses the command itself; HAPI must not prepend its own + // instructions or switch to the native REST prompt path (neither leaves + // a leading "/" for OpenCode's ACP command detector). + | { kind: 'goal'; text: string } | { kind: 'handled'; message: string; @@ -176,6 +182,10 @@ export function resolveOpencodeSlashCommand( return { kind: 'compact' }; } + if (command === 'goal') { + return { kind: 'goal', text }; + } + if (command === 'clear') { return { kind: 'clear' }; } @@ -204,6 +214,8 @@ export function resolveOpencodeSlashCommand( '- `/default` — return to default permission mode', '- `/init [extra]` — generate or refresh AGENTS.md for this project', '- `/compact` — compact (summarize) the OpenCode session context (remote sessions only)', + '- `/goal ` — keep working until a reviewer confirms the objective is met (OpenCode v2.2.1+)', + '- `/goal pause|resume|clear` — control the active goal', '- `/clear` — archive this HAPI session and open a fresh OpenCode session', '', 'Model, reasoning effort, and permission mode have dedicated buttons in the composer. ' + diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index bb3f0a1d..d434c381 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -342,11 +342,15 @@ export const ThreadGoalStatusSchema = z.enum([ export type ThreadGoalStatus = z.infer export const ThreadGoalSchema = z.object({ + source: z.enum(['opencode', 'codex']).optional(), threadId: z.string(), objective: z.string(), status: ThreadGoalStatusSchema, tokenBudget: z.number().nullable().optional(), tokensUsed: z.number().optional().default(0), + /** OpenCode goals count continuation rounds instead of tokens. */ + rounds: z.number().optional(), + maxRounds: z.number().optional(), timeUsedSeconds: z.number().optional().default(0), createdAt: z.number().optional().default(0), updatedAt: z.number().optional().default(0) diff --git a/shared/src/slashCommands.ts b/shared/src/slashCommands.ts index a97d6579..3b202832 100644 --- a/shared/src/slashCommands.ts +++ b/shared/src/slashCommands.ts @@ -47,6 +47,7 @@ export const BUILTIN_SLASH_COMMANDS = { ], opencode: [ { name: 'compact', description: 'Compact (summarize) the session context', source: 'builtin' }, + { name: 'goal', description: 'Keep working until an objective is met [pause|resume|clear]', source: 'builtin' }, { name: 'help', description: 'Show supported HAPI OpenCode slash commands', source: 'builtin' }, { name: 'status', description: 'Show current OpenCode session config', source: 'builtin' }, { name: 'plan', description: 'Enable plan mode; use /plan off to return to default', source: 'builtin' }, diff --git a/web/src/chat/normalizeAgent.ts b/web/src/chat/normalizeAgent.ts index cf385c0b..6b5f9e97 100644 --- a/web/src/chat/normalizeAgent.ts +++ b/web/src/chat/normalizeAgent.ts @@ -110,11 +110,14 @@ function normalizeThreadGoal(value: unknown) { && status !== 'complete' ) return null return { + source: value.source === 'opencode' || value.source === 'codex' ? value.source : undefined, threadId, objective, status, tokenBudget: asNumber(value.tokenBudget ?? value.token_budget), tokensUsed: asNumber(value.tokensUsed ?? value.tokens_used) ?? 0, + rounds: asNumber(value.rounds), + maxRounds: asNumber(value.maxRounds), timeUsedSeconds: asNumber(value.timeUsedSeconds ?? value.time_used_seconds) ?? 0, createdAt: asNumber(value.createdAt ?? value.created_at) ?? 0, updatedAt: asNumber(value.updatedAt ?? value.updated_at) ?? 0 diff --git a/web/src/chat/reducer.ts b/web/src/chat/reducer.ts index 9ed9f265..3fedd2f4 100644 --- a/web/src/chat/reducer.ts +++ b/web/src/chat/reducer.ts @@ -80,7 +80,10 @@ function getLatestThreadGoal(normalized: NormalizedMessage[]): ThreadGoal | null if (event.type === 'thread-goal-cleared') return null if (event.type === 'thread-goal-updated') { const goal = (event as { goal?: ThreadGoal }).goal ?? null - if (goal?.status === 'complete' && sawNewerNonGoalUserMessage) { + // Codex clears the completed card once new work starts. OpenCode's + // goal stays visible until explicitly cleared so the user can + // still see what the long-running task accomplished. + if (goal?.status === 'complete' && sawNewerNonGoalUserMessage && goal.source !== 'opencode') { return null } return goal diff --git a/web/src/components/SessionChat.tsx b/web/src/components/SessionChat.tsx index 4bef39d7..4f3da505 100644 --- a/web/src/components/SessionChat.tsx +++ b/web/src/components/SessionChat.tsx @@ -1536,6 +1536,13 @@ function SessionChatInner(props: SessionChatProps) { ) const canManageGoal = !isSessionGuest && agentFlavor === 'codex' && props.session.active && Boolean(props.session.metadata?.capabilities?.codexGoal) && !controlledByUser + // OpenCode's goal lives in a core plugin; its controls are the same `/goal` + // slash commands the user can type. Drive them through the composer so the + // H5 status panel gets Codex-style pause/resume/clear buttons too. + // Tie the controls directly to the card the user can see. Requiring the + // session's active/guest/controlled flags here previously hid the buttons + // even when the goal card was right in front of the user. + const canManageOpencodeGoal = reduced.latestGoal?.source === 'opencode' const goalEventId = useMemo(() => { for (let i = normalizedGoalStateMessages.length - 1; i >= 0; i--) { const message = normalizedGoalStateMessages[i] @@ -2048,7 +2055,19 @@ function SessionChatInner(props: SessionChatProps) { - {sessionStatus ? : null} + {sessionStatus ? ( + { + const text = action.action === 'update' + ? `/goal ${action.objective}` + : `/goal ${action.action}`; + await props.onSend(text); + } + : canManageGoal ? codexGoal.act : undefined} + /> + ) : null}
{props.session.teamState && ( diff --git a/web/src/components/SessionStatusPanel.tsx b/web/src/components/SessionStatusPanel.tsx index 5a46bfc6..8210942b 100644 --- a/web/src/components/SessionStatusPanel.tsx +++ b/web/src/components/SessionStatusPanel.tsx @@ -59,7 +59,11 @@ export function SessionStatusPanel({ data, onGoalAction }: { {t(`session.status.goal.${data.goal.status}`)} {data.goal.timeUsedSeconds > 0 ? ` · ${formatDuration(data.goal.timeUsedSeconds * 1000)}` : ''}
- {data.goal.tokenBudget != null ? ( + {data.goal.rounds != null && data.goal.maxRounds != null ? ( +
+ {t('session.goal.rounds', { used: data.goal.rounds, budget: data.goal.maxRounds })} +
+ ) : data.goal.tokenBudget != null ? (
{t('session.goal.tokens', { used: data.goal.tokensUsed.toLocaleString(), budget: data.goal.tokenBudget.toLocaleString() })}
diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index e01c3ba1..33610730 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -1448,6 +1448,7 @@ export default { 'session.goal.saving': 'Saving…', 'session.goal.invalid': 'Enter an objective of 1–4000 characters and a positive whole token budget, or leave the budget blank to use the Codex default.', 'session.goal.tokens': '{used} / {budget} tokens', + 'session.goal.rounds': 'Round {used} / {budget}', 'session.status.tasks': 'Tasks', 'session.status.subagents': 'Subagents', 'session.status.terminals': 'Background tasks', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 66c6e6f3..36a37c33 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -1447,6 +1447,7 @@ export default { 'session.goal.saving': '保存中…', 'session.goal.invalid': '目标内容需为 1–4000 个字符;Token 预算需为正整数,留空使用 Codex 默认设置。', 'session.goal.tokens': 'Token:{used} / {budget}', + 'session.goal.rounds': '第 {used} / {budget} 轮', 'session.status.tasks': '任务', 'session.status.subagents': '子代理', 'session.status.terminals': '后台任务',