From 5041afb0524f945be4f985d738ee9f501fc9d3b6 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sun, 12 Apr 2026 00:10:52 -0700 Subject: [PATCH] fix: keep OpenCode activity and notifications in sync (#527) --- src/main/index.ts | 9 + src/main/ipc/pty.test.ts | 44 +++- src/main/ipc/pty.ts | 15 ++ src/main/opencode/hook-service.ts | 212 ++++++++++++++++++ src/preload/api-types.d.ts | 2 + src/preload/index.d.ts | 4 +- src/preload/index.ts | 13 +- .../terminal-pane/pty-transport.test.ts | 89 ++++++++ .../components/terminal-pane/pty-transport.ts | 68 +++++- src/shared/types.ts | 8 + 10 files changed, 452 insertions(+), 12 deletions(-) create mode 100644 src/main/opencode/hook-service.ts create mode 100644 src/renderer/src/components/terminal-pane/pty-transport.test.ts diff --git a/src/main/index.ts b/src/main/index.ts index 5bd19ac61..f9691e7ce 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -25,6 +25,7 @@ import { RateLimitService } from './rate-limits/service' import { attachMainWindowServices } from './window/attach-main-window-services' import { createMainWindow } from './window/createMainWindow' import { CodexAccountService } from './codex-accounts/service' +import { openCodeHookService } from './opencode/hook-service' let mainWindow: BrowserWindow | null = null /** Whether a manual app.quit() (Cmd+Q, etc.) is in progress. Shared with the @@ -127,6 +128,13 @@ app.whenReady().then(async () => { rateLimits.setCodexHomePathResolver(() => codexAccounts!.getSelectedManagedHomePath()) runtime = new OrcaRuntimeService(store, stats) nativeTheme.themeSource = store.getSettings().theme ?? 'system' + try { + await openCodeHookService.start() + } catch (error) { + // Why: OpenCode hooks only enrich status detection. Orca should still boot + // even if the local loopback server cannot bind on this launch. + console.error('[opencode] Failed to start local hook server:', error) + } registerAppMenu({ onCheckForUpdates: () => checkForUpdatesFromMenu(), @@ -193,6 +201,7 @@ app.on('will-quit', () => { // are still running. killAllPty() does not call runtime.onPtyExit(), // so without this ordering, running agents would produce orphaned // agent_start events with no matching stops. + openCodeHookService.stop() stats?.flush() killAllPty() void closeAllWatchers() diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index c5f84fa22..c56e5bd3d 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -1,3 +1,6 @@ +/* eslint-disable max-lines -- Why: PTY spawn env behavior is easiest to verify in +one focused file because the registration helper is stateful and each spawn-path +assertion reuses the same mocked IPC and node-pty harness. */ import { beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -8,7 +11,9 @@ const { existsSyncMock, statSyncMock, accessSyncMock, - spawnMock + spawnMock, + openCodeBuildPtyEnvMock, + openCodeClearPtyMock } = vi.hoisted(() => ({ handleMock: vi.fn(), onMock: vi.fn(), @@ -17,7 +22,9 @@ const { existsSyncMock: vi.fn(), statSyncMock: vi.fn(), accessSyncMock: vi.fn(), - spawnMock: vi.fn() + spawnMock: vi.fn(), + openCodeBuildPtyEnvMock: vi.fn(), + openCodeClearPtyMock: vi.fn() })) vi.mock('electron', () => ({ @@ -42,6 +49,13 @@ vi.mock('node-pty', () => ({ spawn: spawnMock })) +vi.mock('../opencode/hook-service', () => ({ + openCodeHookService: { + buildPtyEnv: openCodeBuildPtyEnvMock, + clearPty: openCodeClearPtyMock + } +})) + import { registerPtyHandlers } from './pty' describe('registerPtyHandlers', () => { @@ -64,6 +78,8 @@ describe('registerPtyHandlers', () => { statSyncMock.mockReset() accessSyncMock.mockReset() spawnMock.mockReset() + openCodeBuildPtyEnvMock.mockReset() + openCodeClearPtyMock.mockReset() mainWindow.webContents.on.mockReset() mainWindow.webContents.send.mockReset() @@ -72,6 +88,12 @@ describe('registerPtyHandlers', () => { }) existsSyncMock.mockReturnValue(true) statSyncMock.mockReturnValue({ isDirectory: () => true }) + openCodeBuildPtyEnvMock.mockReturnValue({ + ORCA_OPENCODE_HOOK_PORT: '4567', + ORCA_OPENCODE_HOOK_TOKEN: 'opencode-token', + ORCA_OPENCODE_PTY_ID: 'test-pty', + OPENCODE_CONFIG_DIR: '/tmp/orca-opencode-config' + }) spawnMock.mockReturnValue({ onData: vi.fn(), onExit: vi.fn(), @@ -150,6 +172,16 @@ describe('registerPtyHandlers', () => { expect(env.CODEX_HOME).toBe('/tmp/orca-codex-home') }) + it('injects the OpenCode hook env into Orca terminal PTYs', () => { + const env = spawnAndGetEnv() + expect(openCodeBuildPtyEnvMock).toHaveBeenCalledTimes(1) + expect(openCodeBuildPtyEnvMock.mock.calls[0]?.[0]).toEqual(expect.any(String)) + expect(env.ORCA_OPENCODE_HOOK_PORT).toBe('4567') + expect(env.ORCA_OPENCODE_HOOK_TOKEN).toBe('opencode-token') + expect(env.ORCA_OPENCODE_PTY_ID).toBe('test-pty') + expect(env.OPENCODE_CONFIG_DIR).toBe('/tmp/orca-opencode-config') + }) + it('leaves ambient CODEX_HOME untouched when system default is selected', () => { const env = spawnAndGetEnv(undefined, { CODEX_HOME: '/tmp/system-codex-home' }, () => null) expect(env.CODEX_HOME).toBe('/tmp/system-codex-home') @@ -201,7 +233,9 @@ describe('registerPtyHandlers', () => { const originalShell = process.env.SHELL const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - existsSyncMock.mockImplementation((targetPath: string) => targetPath !== '/opt/homebrew/bin/bash') + existsSyncMock.mockImplementation( + (targetPath: string) => targetPath !== '/opt/homebrew/bin/bash' + ) try { process.env.SHELL = '/opt/homebrew/bin/bash' @@ -276,7 +310,9 @@ describe('registerPtyHandlers', () => { const originalShell = process.env.SHELL const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - existsSyncMock.mockImplementation((targetPath: string) => targetPath !== '/opt/homebrew/bin/bash') + existsSyncMock.mockImplementation( + (targetPath: string) => targetPath !== '/opt/homebrew/bin/bash' + ) try { process.env.SHELL = '/bin/bash' diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index 2943433c9..a14a22b75 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -9,6 +9,7 @@ import { type BrowserWindow, ipcMain } from 'electron' import * as pty from 'node-pty' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { parseWslPath } from '../wsl' +import { openCodeHookService } from '../opencode/hook-service' let ptyCounter = 0 const ptyProcesses = new Map() @@ -112,6 +113,7 @@ export function registerPtyHandlers( ptyProcesses.delete(id) ptyShellName.delete(id) ptyLoadGeneration.delete(id) + openCodeHookService.clearPty(id) // Why: notify runtime so the agent detector can close out any live // agent sessions. Without this, killed PTYs would remain in the // detector's liveAgents map and accumulate inflated durations. @@ -144,6 +146,7 @@ export function registerPtyHandlers( ptyProcesses.delete(ptyId) ptyShellName.delete(ptyId) ptyLoadGeneration.delete(ptyId) + openCodeHookService.clearPty(ptyId) runtime?.onPtyExit(ptyId, -1) return true } @@ -224,6 +227,15 @@ export function registerPtyHandlers( FORCE_HYPERLINK: '1' } as Record + const openCodeHookEnv = openCodeHookService.buildPtyEnv(id) + if (spawnEnv.OPENCODE_CONFIG_DIR) { + // Why: OPENCODE_CONFIG_DIR is a singular extra config root. Replacing a + // user-provided directory would silently hide their custom OpenCode + // config, so preserve it and fall back to title-only detection there. + delete openCodeHookEnv.OPENCODE_CONFIG_DIR + } + Object.assign(spawnEnv, openCodeHookEnv) + // Why: the selected Codex account should affect Codex launched inside // Orca terminals too, not just Orca's background quota fetches. Inject // the managed CODEX_HOME only into this PTY environment so the override @@ -338,6 +350,7 @@ export function registerPtyHandlers( ptyProcesses.delete(id) ptyShellName.delete(id) ptyLoadGeneration.delete(id) + openCodeHookService.clearPty(id) runtime?.onPtyExit(id, exitCode) if (!mainWindow.isDestroyed()) { mainWindow.webContents.send('pty:exit', { id, code: exitCode }) @@ -373,6 +386,7 @@ export function registerPtyHandlers( ptyProcesses.delete(args.id) ptyShellName.delete(args.id) ptyLoadGeneration.delete(args.id) + openCodeHookService.clearPty(args.id) runtime?.onPtyExit(args.id, -1) } }) @@ -431,5 +445,6 @@ export function killAllPty(): void { ptyProcesses.delete(id) ptyShellName.delete(id) ptyLoadGeneration.delete(id) + openCodeHookService.clearPty(id) } } diff --git a/src/main/opencode/hook-service.ts b/src/main/opencode/hook-service.ts new file mode 100644 index 000000000..e3ee68e52 --- /dev/null +++ b/src/main/opencode/hook-service.ts @@ -0,0 +1,212 @@ +import { app, BrowserWindow } from 'electron' +import { randomUUID } from 'crypto' +import { createServer, type IncomingMessage, type ServerResponse } from 'http' +import { join } from 'path' +import { mkdirSync, writeFileSync } from 'fs' +import type { OpenCodeStatusEvent } from '../../shared/types' + +const ORCA_OPENCODE_PLUGIN_FILE = 'orca-opencode-status.js' + +type OpenCodeHookStatus = OpenCodeStatusEvent['status'] + +function readJsonBody(req: IncomingMessage): Promise { + return new Promise((resolve, reject) => { + let body = '' + req.on('data', (chunk: Buffer) => { + body += chunk.toString() + if (body.length > 1_000_000) { + reject(new Error('payload too large')) + req.destroy() + } + }) + req.on('end', () => { + try { + resolve(body ? JSON.parse(body) : {}) + } catch (error) { + reject(error) + } + }) + req.on('error', reject) + }) +} + +function normalizeStatus(value: unknown): OpenCodeHookStatus | null { + return value === 'working' || value === 'idle' || value === 'permission' ? value : null +} + +function getOpenCodePluginSource(): string { + return [ + 'const HOOK_PATH = "/hook";', + '', + 'function getHookUrl() {', + ' const port = process.env.ORCA_OPENCODE_HOOK_PORT;', + ' return port ? `http://127.0.0.1:${port}${HOOK_PATH}` : null;', + '}', + '', + 'function getStatusType(event) {', + ' return event?.properties?.status?.type ?? event?.status?.type ?? null;', + '}', + '', + 'async function postStatus(status) {', + ' const url = getHookUrl();', + ' const token = process.env.ORCA_OPENCODE_HOOK_TOKEN;', + ' const ptyId = process.env.ORCA_OPENCODE_PTY_ID;', + ' if (!url || !token || !ptyId) return;', + ' try {', + ' await fetch(url, {', + ' method: "POST",', + ' headers: {', + ' "Content-Type": "application/json",', + ' "X-Orca-Token": token,', + ' "X-Orca-OpenCode-Pty-Id": ptyId,', + ' },', + ' body: JSON.stringify({ status }),', + ' });', + ' } catch {', + ' // Why: OpenCode session hooks must never fail the agent run just', + ' // because Orca is unavailable or the local loopback request failed.', + ' }', + '}', + '', + 'export const OrcaOpenCodeStatusPlugin = async () => ({', + ' event: async ({ event }) => {', + ' if (!event?.type) return;', + '', + ' if (event.type === "permission.asked") {', + ' await postStatus("permission");', + ' return;', + ' }', + '', + ' if (event.type === "session.idle") {', + ' await postStatus("idle");', + ' return;', + ' }', + '', + ' if (event.type === "session.status") {', + ' const statusType = getStatusType(event);', + ' if (statusType === "busy" || statusType === "retry") {', + ' await postStatus("working");', + ' return;', + ' }', + ' if (statusType === "idle") {', + ' await postStatus("idle");', + ' }', + ' }', + ' },', + '});', + '' + ].join('\n') +} + +export class OpenCodeHookService { + private server: ReturnType | null = null + private port = 0 + private token = '' + private lastStatusByPtyId = new Map() + + async start(): Promise { + if (this.server) { + return + } + + this.token = randomUUID() + this.server = createServer(async (req: IncomingMessage, res: ServerResponse) => { + if (req.method !== 'POST' || req.url !== '/hook') { + res.writeHead(404) + res.end() + return + } + + if (req.headers['x-orca-token'] !== this.token) { + res.writeHead(403) + res.end() + return + } + + const ptyIdHeader = req.headers['x-orca-opencode-pty-id'] + const ptyId = Array.isArray(ptyIdHeader) ? ptyIdHeader[0] : ptyIdHeader + if (!ptyId) { + res.writeHead(400) + res.end() + return + } + + try { + const body = await readJsonBody(req) + const status = normalizeStatus((body as { status?: unknown }).status) + if (!status) { + res.writeHead(400) + res.end() + return + } + + if (this.lastStatusByPtyId.get(ptyId) !== status) { + this.lastStatusByPtyId.set(ptyId, status) + const payload: OpenCodeStatusEvent = { ptyId, status } + for (const window of BrowserWindow.getAllWindows()) { + if (!window.isDestroyed()) { + window.webContents.send('pty:opencode-status', payload) + } + } + } + + res.writeHead(204) + res.end() + } catch { + res.writeHead(400) + res.end() + } + }) + + await new Promise((resolve, reject) => { + this.server!.once('error', reject) + this.server!.listen(0, '127.0.0.1', () => { + const address = this.server!.address() + if (address && typeof address === 'object') { + this.port = address.port + } + resolve() + }) + }) + } + + stop(): void { + this.server?.close() + this.server = null + this.port = 0 + this.lastStatusByPtyId.clear() + } + + clearPty(ptyId: string): void { + this.lastStatusByPtyId.delete(ptyId) + } + + buildPtyEnv(ptyId: string): Record { + if (this.port <= 0 || !this.token) { + return {} + } + + const configDir = this.writePluginConfig(ptyId) + + // Why: OpenCode only reads the extra plugin directory at process startup. + // Inject these vars into every Orca PTY so manually launched `opencode` + // sessions inherit the hook path too, not just sessions started from a + // hardcoded Orca command template. + return { + ORCA_OPENCODE_HOOK_PORT: String(this.port), + ORCA_OPENCODE_HOOK_TOKEN: this.token, + ORCA_OPENCODE_PTY_ID: ptyId, + OPENCODE_CONFIG_DIR: configDir + } + } + + private writePluginConfig(ptyId: string): string { + const configDir = join(app.getPath('userData'), 'opencode-hooks', ptyId) + const pluginsDir = join(configDir, 'plugins') + mkdirSync(pluginsDir, { recursive: true }) + writeFileSync(join(pluginsDir, ORCA_OPENCODE_PLUGIN_FILE), getOpenCodePluginSource()) + return configDir + } +} + +export const openCodeHookService = new OpenCodeHookService() diff --git a/src/preload/api-types.d.ts b/src/preload/api-types.d.ts index 7ecc1c92a..31816cf95 100644 --- a/src/preload/api-types.d.ts +++ b/src/preload/api-types.d.ts @@ -14,6 +14,7 @@ import type { IssueInfo, NotificationDispatchRequest, NotificationDispatchResult, + OpenCodeStatusEvent, OrcaHooks, PersistedUIState, PRCheckDetail, @@ -194,6 +195,7 @@ export type PreloadApi = { getForegroundProcess: (id: string) => Promise onData: (callback: (data: { id: string; data: string }) => void) => () => void onExit: (callback: (data: { id: string; code: number }) => void) => () => void + onOpenCodeStatus: (callback: (event: OpenCodeStatusEvent) => void) => () => void } gh: { viewer: () => Promise diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index cd2b9ffa4..b38c87213 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -2,7 +2,8 @@ import type { ElectronAPI } from '@electron-toolkit/preload' import type { CreateWorktreeResult, GitHubViewer, - CreateWorktreeArgs + CreateWorktreeArgs, + OpenCodeStatusEvent } from '../../shared/types' import type { PreloadApi } from './api-types' @@ -50,6 +51,7 @@ type PtyApi = { hasChildProcesses: (id: string) => Promise onData: (callback: (data: { id: string; data: string }) => void) => () => void onExit: (callback: (data: { id: string; code: number }) => void) => () => void + onOpenCodeStatus: (callback: (event: OpenCodeStatusEvent) => void) => () => void } type GhApi = { diff --git a/src/preload/index.ts b/src/preload/index.ts index b1e95fad1..c48ed3293 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -4,7 +4,11 @@ review and type drift checks easier than scattering these bindings across module import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron' import { electronAPI } from '@electron-toolkit/preload' import type { CliInstallStatus } from '../shared/cli-install-types' -import type { FsChangedPayload, NotificationDispatchResult } from '../shared/types' +import type { + FsChangedPayload, + NotificationDispatchResult, + OpenCodeStatusEvent +} from '../shared/types' import type { RuntimeStatus, RuntimeSyncWindowGraph } from '../shared/runtime-types' import type { RateLimitState } from '../shared/rate-limit-types' import { @@ -214,6 +218,13 @@ const api = { callback(data) ipcRenderer.on('pty:exit', listener) return () => ipcRenderer.removeListener('pty:exit', listener) + }, + + onOpenCodeStatus: (callback: (event: OpenCodeStatusEvent) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, data: OpenCodeStatusEvent) => + callback(data) + ipcRenderer.on('pty:opencode-status', listener) + return () => ipcRenderer.removeListener('pty:opencode-status', listener) } }, diff --git a/src/renderer/src/components/terminal-pane/pty-transport.test.ts b/src/renderer/src/components/terminal-pane/pty-transport.test.ts new file mode 100644 index 000000000..96894cf0a --- /dev/null +++ b/src/renderer/src/components/terminal-pane/pty-transport.test.ts @@ -0,0 +1,89 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createIpcPtyTransport } from './pty-transport' + +describe('createIpcPtyTransport', () => { + const originalWindow = (globalThis as { window?: typeof window }).window + let onData: ((payload: { id: string; data: string }) => void) | null = null + let onExit: ((payload: { id: string; code: number }) => void) | null = null + let onOpenCodeStatus: + | ((payload: { ptyId: string; status: 'working' | 'idle' | 'permission' }) => void) + | null = null + + beforeEach(() => { + onData = null + onExit = null + onOpenCodeStatus = null + + ;(globalThis as { window: typeof window }).window = { + ...originalWindow, + api: { + ...originalWindow?.api, + pty: { + ...originalWindow?.api?.pty, + spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }), + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn(), + onData: vi.fn((callback: (payload: { id: string; data: string }) => void) => { + onData = callback + return () => {} + }), + onExit: vi.fn((callback: (payload: { id: string; code: number }) => void) => { + onExit = callback + return () => {} + }), + onOpenCodeStatus: vi.fn( + ( + callback: (payload: { + ptyId: string + status: 'working' | 'idle' | 'permission' + }) => void + ) => { + onOpenCodeStatus = callback + return () => {} + } + ) + } + } + } as unknown as typeof window + }) + + afterEach(() => { + if (originalWindow) { + ;(globalThis as { window: typeof window }).window = originalWindow + } else { + delete (globalThis as { window?: typeof window }).window + } + }) + + it('maps OpenCode status events into the existing working to idle agent lifecycle', async () => { + const onTitleChange = vi.fn() + const onAgentBecameWorking = vi.fn() + const onAgentBecameIdle = vi.fn() + + const transport = createIpcPtyTransport({ + onTitleChange, + onAgentBecameWorking, + onAgentBecameIdle + }) + + await transport.connect({ + url: '', + callbacks: {} + }) + + expect(onOpenCodeStatus).not.toBeNull() + + onOpenCodeStatus?.({ ptyId: 'pty-1', status: 'working' }) + onData?.({ id: 'pty-1', data: '\u001b]0;OpenCode\u0007' }) + onOpenCodeStatus?.({ ptyId: 'pty-1', status: 'idle' }) + + expect(onAgentBecameWorking).toHaveBeenCalledTimes(1) + expect(onAgentBecameIdle).toHaveBeenCalledWith('OpenCode') + expect(onTitleChange).toHaveBeenNthCalledWith(1, '⠋ OpenCode', '⠋ OpenCode') + expect(onTitleChange).toHaveBeenNthCalledWith(2, '⠋ OpenCode', '⠋ OpenCode') + expect(onTitleChange).toHaveBeenNthCalledWith(3, 'OpenCode', 'OpenCode') + expect(onData).not.toBeNull() + expect(onExit).not.toBeNull() + }) +}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport.ts b/src/renderer/src/components/terminal-pane/pty-transport.ts index e8575cb65..39d5dbe00 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport.ts @@ -6,6 +6,7 @@ import { normalizeTerminalTitle, extractLastOscTitle } from '../../../../shared/agent-detection' +import type { OpenCodeStatusEvent } from '../../../../shared/types' export type PtyTransport = { connect: (options: { @@ -53,6 +54,7 @@ export type PtyTransport = { // that triggers MaxListenersExceededWarning with many panes/tabs. const ptyDataHandlers = new Map void>() const ptyExitHandlers = new Map void>() +const openCodeStatusHandlers = new Map void>() let ptyDispatcherAttached = false export function ensurePtyDispatcher(): void { @@ -66,6 +68,9 @@ export function ensurePtyDispatcher(): void { window.api.pty.onExit((payload) => { ptyExitHandlers.get(payload.id)?.(payload.code) }) + window.api.pty.onOpenCodeStatus((payload) => { + openCodeStatusHandlers.get(payload.ptyId)?.(payload) + }) } // ─── Eager PTY buffer for reconnection on restart ─────────────────── @@ -173,6 +178,8 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra let inOsc = false let pendingOscEscape = false let lastEmittedTitle: string | null = null + let lastObservedTerminalTitle: string | null = null + let openCodeStatus: OpenCodeStatusEvent['status'] | null = null let staleTitleTimer: ReturnType | null = null const agentTracker = onAgentBecameIdle || onAgentBecameWorking || onAgentExited @@ -198,6 +205,54 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra function unregisterPtyHandlers(id: string): void { ptyDataHandlers.delete(id) ptyExitHandlers.delete(id) + openCodeStatusHandlers.delete(id) + } + + function getSyntheticOpenCodeTitle(status: OpenCodeStatusEvent['status']): string { + const baseTitle = + lastObservedTerminalTitle && lastObservedTerminalTitle !== 'OpenCode' + ? `OpenCode · ${lastObservedTerminalTitle}` + : 'OpenCode' + + if (status === 'working') { + return `⠋ ${baseTitle}` + } + if (status === 'permission') { + return `${baseTitle} permission needed` + } + return baseTitle + } + + function applyOpenCodeStatus(event: OpenCodeStatusEvent): void { + openCodeStatus = event.status + if (staleTitleTimer) { + clearTimeout(staleTitleTimer) + staleTitleTimer = null + } + + const rawTitle = getSyntheticOpenCodeTitle(event.status) + const title = normalizeTerminalTitle(rawTitle) + lastEmittedTitle = title + onTitleChange?.(title, rawTitle) + agentTracker?.handleTitle(rawTitle) + } + + function applyObservedTerminalTitle(title: string): void { + lastObservedTerminalTitle = title + + // Why: OpenCode can keep emitting plain titles like "OpenCode" while the + // session is still busy. If we let those raw titles overwrite the + // hook-derived state, the working spinner flashes briefly and disappears. + // While OpenCode has an explicit non-idle status, that status is the + // source of truth and the observed title is only used as context text. + if (openCodeStatus && openCodeStatus !== 'idle') { + applyOpenCodeStatus({ ptyId: ptyId ?? '', status: openCodeStatus }) + return + } + + lastEmittedTitle = normalizeTerminalTitle(title) + onTitleChange?.(lastEmittedTitle, title) + agentTracker?.handleTitle(title) } return { @@ -237,9 +292,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra clearTimeout(staleTitleTimer) staleTitleTimer = null } - lastEmittedTitle = normalizeTerminalTitle(title) - onTitleChange(lastEmittedTitle, title) - agentTracker?.handleTitle(title) + applyObservedTerminalTitle(title) } else if ( lastEmittedTitle && detectAgentStatusFromTitle(lastEmittedTitle) === 'working' @@ -274,6 +327,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra clearTimeout(staleTitleTimer) staleTitleTimer = null } + openCodeStatus = null connected = false ptyId = null unregisterPtyHandlers(spawnedId) @@ -281,6 +335,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra storedCallbacks.onDisconnect?.() onPtyExit?.(spawnedId) }) + openCodeStatusHandlers.set(spawnedId, applyOpenCodeStatus) storedCallbacks.onConnect?.() storedCallbacks.onStatus?.('shell') @@ -316,9 +371,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra clearTimeout(staleTitleTimer) staleTitleTimer = null } - lastEmittedTitle = normalizeTerminalTitle(title) - onTitleChange(lastEmittedTitle, title) - agentTracker?.handleTitle(title) + applyObservedTerminalTitle(title) } else if ( lastEmittedTitle && detectAgentStatusFromTitle(lastEmittedTitle) === 'working' @@ -347,6 +400,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra clearTimeout(staleTitleTimer) staleTitleTimer = null } + openCodeStatus = null connected = false ptyId = null unregisterPtyHandlers(id) @@ -354,6 +408,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra storedCallbacks.onDisconnect?.() onPtyExit?.(id) }) + openCodeStatusHandlers.set(id, applyOpenCodeStatus) // Replay any data buffered between eager spawn and now. Route through // the real data handler (not storedCallbacks.onData directly) so that @@ -383,6 +438,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra clearTimeout(staleTitleTimer) staleTitleTimer = null } + openCodeStatus = null if (ptyId) { const id = ptyId window.api.pty.kill(id) diff --git a/src/shared/types.ts b/src/shared/types.ts index ca7c87264..4d9597419 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -440,6 +440,14 @@ export type NotificationDispatchResult = { reason?: 'disabled' | 'source-disabled' | 'suppressed-focus' | 'cooldown' | 'not-supported' } +export type OpenCodeStatusEvent = { + ptyId: string + /** Compatibility shim for OpenCode: Orca's activity surfaces already depend + * on this normalized state machine, so hook payloads collapse into the same + * working/idle/permission categories instead of inventing a parallel model. */ + status: 'working' | 'idle' | 'permission' +} + export type WorktreeCardProperty = 'status' | 'unread' | 'ci' | 'issue' | 'pr' | 'comment' export type StatusBarItem = 'claude' | 'codex'