Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

A model switch waits only for a turn; Models follows a harness still starting (#1244)

lingrd0d06ececccac
diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.ts
index 1f153e21f..3d0f27d9e 100644
--- a/cli/src/core/agents/retarget.spec.ts
+++ b/cli/src/core/agents/retarget.spec.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { applyOpencodeSessionModel, parseOpencodeModelId, opencodeMajorVersion } from '../../engines/launchControl.js'
+import { applyOpencodeSessionModel, parseOpencodeModelId, opencodeMajorVersion, opencodeV2TurnOpen } from '../../engines/launchControl.js'
import { isOpencodeV2 } from '../../engines/launchControl.js'
import { binaryOnPath } from '../../lib/binaryOnPath.js'
import { validateLaunchOverrides } from '../../lib/launchOverrides.js'
@@ -7,7 +7,6 @@ import type { RegisteredSession } from '../../lib/registry.js'
import { AgentRestartCoordinator, bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'
import { probeGatewayRuntime } from '../../lib/gatewayRuntime.js'
import { parseRuntimeProfile } from '../../lib/runtimeProfileWire.js'
-import { inspectRuntimePane } from '../../lib/runtimeProfileController.js'
import { clearPaneRemainOnExit } from '../../lib/tmux.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
@@ -19,6 +18,7 @@ vi.mock('../../engines/launchControl.js', async (real) => ({
...await real<object>(),
isOpencodeV2: vi.fn(() => false), opencodeMajorVersion: vi.fn(() => 1),
applyOpencodeSessionModel: vi.fn(async () => ({ ok: true })),
+ opencodeV2TurnOpen: vi.fn(async () => false),
parseOpencodeModelId: vi.fn((id: string) => ({ providerID: id.split('/')[0], modelID: id.split('/')[1] })),
}))
// Optional readers cannot gate a native launch decision.
@@ -36,7 +36,6 @@ vi.mock('../../lib/restartAgent.js', async (real) => ({
restartAgent: vi.fn(async () => ({ ok: true, resumed: true, processIdentity: { pid: 2, startMarker: 'new', executable: '/bin/claude' } })),
}))
vi.mock('../../lib/runtimeProfileWire.js', async (real) => ({ ...await real<object>(), parseRuntimeProfile: vi.fn(() => ({ engine: 'claude', model: 'opus' })) }))
-vi.mock('../../lib/runtimeProfileController.js', async (real) => ({ ...await real<object>(), inspectRuntimePane: vi.fn(() => ({ idle: true })) }))
vi.mock('../../lib/tmux.js', async (real) => ({
...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}),
processArgs: vi.fn(async () => 'codex -c model_providers.grid.base_url=http://grid.local/v1'),
@@ -52,7 +51,7 @@ const agent = (over: Partial<RegisteredSession> = {}): RegisteredSession => ({
function setup(row: RegisteredSession | null = agent(), over: Partial<RetargetDeps> = {}) {
const release = vi.fn(), releaseRoute = vi.fn()
const deps: RetargetDeps = {
- readScreen: async (session, capture) => ({ pane: inspectRuntimePane(session.engine, capture ?? ''), question: null, messageHold: null, teamHold: null, activity: null, busy: false, stoppedGoal: false }),
+ sessionTurnOpen: vi.fn(() => false),
purgeBusy: vi.fn(() => false),
tmuxBackend: { clearEnv: vi.fn(async () => ({ state: 'succeeded' })) } as unknown as RetargetDeps['tmuxBackend'],
registry: {
@@ -65,7 +64,6 @@ function setup(row: RegisteredSession | null = agent(), over: Partial<RetargetDe
} as unknown as RetargetDeps['registry'],
runtimeProfiles: { selectedModel: vi.fn(() => 'runtime-v1:claude:opus') } as never,
launchOverridesDeps: {} as never,
- captureTerminal: vi.fn(async () => 'idle pane'),
acquireTerminalControl: vi.fn(() => release),
relaunchOverrides: vi.fn(async () => ({ ok: true, overrides: { gridLaunchRecord: { override: grid, webSearch: 'off' } } })) as never,
downgradedPermission: vi.fn(async (_s, bypass: boolean) => ({ bypassPermission: bypass, permissionMode: null })) as never,
@@ -92,7 +90,7 @@ describe('retargeting an agent', () => {
const held = { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting for native evidence.' } as const
const run = setup(agent(), { launchOverridesDeps: { native: async () => held } as never })
expect(await run.retarget({ agentId: 'a1', grid })).toEqual(held)
- expect(run.deps.captureTerminal).not.toHaveBeenCalled()
+ expect(run.deps.sessionTurnOpen).not.toHaveBeenCalled()
expect(restartAgent).not.toHaveBeenCalled()
})
@@ -171,39 +169,22 @@ describe('retargeting an agent', () => {
})
describe('refusals before anything is touched', () => {
- it('keeps the admitted conversation in an asynchronous reader while a mutable row changes', async () => {
+ it('cannot follow a mutable row to a replacement conversation while validation waits', async () => {
const row = agent()
- let release!: () => void, entered = false, observed: string | undefined
- const ready = new Promise<void>(done => { release = done })
- const run = setup(row, { readScreen: async snapshot => {
- entered = true
- await ready
- observed = snapshot.sessionId
- return { pane: { idle: true } } as never
- } })
- const pending = run.retarget({ agentId: 'a1', grid })
- await vi.waitFor(() => expect(entered).toBe(true))
- row.sessionId = 'replacement'
- release()
- expect(await pending).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
- expect(observed).toBe('s1')
- expect(restartAgent).not.toHaveBeenCalled()
- })
-
- it('cannot follow a mutable row to a replacement conversation while capture waits', async () => {
- const row = agent()
- let finish!: (value: string) => void
- const run = setup(row, { captureTerminal: () => new Promise(done => { finish = done }) })
+ let finish!: () => void
+ vi.mocked(validateLaunchOverrides).mockImplementationOnce(() => new Promise(done => { finish = () => done({ ok: true } as never) }))
+ const run = setup(row)
const pending = run.retarget({ agentId: 'a1', grid })
await vi.waitFor(() => expect(finish).toBeTypeOf('function'))
row.sessionId = 'replacement'
row.processIdentity = { pid: 77, startMarker: 'replacement', executable: 'claude' }
- finish('idle pane')
+ finish()
expect(await pending).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(run.deps.sessionTurnOpen).not.toHaveBeenCalled()
expect(run.deps.relaunchOverrides).not.toHaveBeenCalled()
expect(restartAgent).not.toHaveBeenCalled()
})
- it.each(['validation', 'version', 'screen', 'preparation', 'native-write', 'environment', 'bypass', 'permission', 'replacement', 'gateway', 'pane-option'] as const)(
+ it.each(['validation', 'version', 'preparation', 'native-write', 'environment', 'bypass', 'permission', 'replacement', 'gateway', 'pane-option'] as const)(
'cannot publish or continue a retarget whose owner changes during %s', async phase => {
const row = agent({ engine: 'opencode', subscriptionModel: 'fixture/model' })
const run = setup(row, { relaunchOverrides: vi.fn(async () => ({ ok: true as const,
@@ -212,7 +193,6 @@ describe('retargeting an agent', () => {
switch (phase) {
case 'validation': vi.mocked(validateLaunchOverrides).mockImplementationOnce(async () => { replace(); return { ok: true } }); break
case 'version': vi.mocked(opencodeMajorVersion).mockImplementationOnce(async () => { replace(); return 2 }); break
- case 'screen': run.deps.readScreen = vi.fn(async () => { replace(); return { pane: { idle: true } } as never }); break
case 'preparation': vi.mocked(run.deps.relaunchOverrides).mockImplementationOnce(async () => { replace(); return { ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } } }); break
case 'native-write': vi.mocked(applyOpencodeSessionModel).mockImplementationOnce(async () => { replace(); return { ok: true } }); break
case 'environment': vi.mocked(run.deps.tmuxBackend!.clearEnv).mockImplementationOnce(async () => { replace(); return { state: 'succeeded', dispatch: 'executed' } }); break
@@ -254,7 +234,7 @@ describe('retargeting an agent', () => {
expect(vi.mocked(deps.restartJobs.cancel).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(deps.relaunchOverrides).mock.invocationCallOrder[0])
expect(release).toHaveBeenCalledOnce()
})
- it('rechecks a pane operation that began while the screen was being read', async () => {
+ it('rechecks a pane operation that began while the move was being checked', async () => {
const purgeBusy = vi.fn().mockReturnValueOnce(false).mockReturnValue(true)
const { retarget, deps } = setup(agent(), { purgeBusy })
expect(await retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })
@@ -278,10 +258,57 @@ describe('retargeting an agent', () => {
expect(await setup().retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'CWD_NOT_FOUND', detail: 'gone' })
})
- it('for a pane it cannot read, a turn in progress, a swap already running, or control it cannot take', async () => {
- expect(await setup(agent(), { captureTerminal: vi.fn(async () => null) }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'TMUX_FAILED' })
- vi.mocked(inspectRuntimePane).mockReturnValueOnce({ idle: false } as never)
- expect(await setup().retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })
+ it('for a turn in progress, said so, without reading the screen', async () => {
+ const turn = setup(agent(), { sessionTurnOpen: vi.fn(() => true) })
+ expect(await turn.retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY',
+ detail: 'This harness is in a turn. Stop it, then switch the model.' })
+ expect(turn.deps.sessionTurnOpen).toHaveBeenCalledWith('s1')
+ expect(turn.deps.acquireTerminalControl).not.toHaveBeenCalled()
+ expect(restartAgent).not.toHaveBeenCalled()
+ })
+
+ it('for an OpenCode 2 turn, read from its own store since the turn state does not see it', async () => {
+ const oc2 = agent({ engine: 'opencode' } as Partial<RegisteredSession>)
+ vi.mocked(isOpencodeV2).mockReturnValue(true)
+ try {
+ vi.mocked(opencodeV2TurnOpen).mockResolvedValueOnce(true)
+ const busy = setup(oc2)
+ expect(await busy.retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY',
+ detail: 'This harness is in a turn. Stop it, then switch the model.' })
+ expect(opencodeV2TurnOpen).toHaveBeenCalledWith('/db/opencode.db', 's1')
+ expect(busy.deps.acquireTerminalControl).not.toHaveBeenCalled()
+ // A native OpenCode's store is the one its own HOME holds.
+ const launch = { current: () => true, executable: '/fixture/native/opencode', environment: { HOME: '/fixture/home' }, opencodeMajor: 2 } as unknown as NativeLaunch
+ vi.mocked(opencodeV2TurnOpen).mockResolvedValueOnce(true)
+ expect(await setup(oc2, { launchOverridesDeps: { native: async () => ({ ok: true, launch }) } as never }).retarget({ agentId: 'a1', grid }))
+ .toMatchObject({ ok: false, error: 'AGENT_BUSY' })
+ expect(opencodeV2TurnOpen).toHaveBeenLastCalledWith('/fixture/home/.local/share/opencode/opencode.db', 's1')
+ // Between turns, or a store it cannot read: no turn known, so it moves.
+ vi.mocked(opencodeV2TurnOpen).mockResolvedValueOnce(false).mockResolvedValueOnce(null)
+ expect(await setup(oc2).retarget({ agentId: 'a1', grid })).toEqual({ ok: true })
+ expect(await setup(oc2).retarget({ agentId: 'a1', grid })).toEqual({ ok: true })
+ // A harness replaced while the store is read is not moved.
+ const row = agent({ engine: 'opencode' } as Partial<RegisteredSession>)
+ vi.mocked(opencodeV2TurnOpen).mockImplementationOnce(async () => { row.sessionId = 'replacement'; return false })
+ expect(await setup(row).retarget({ agentId: 'a1', grid })).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ } finally { vi.mocked(isOpencodeV2).mockReturnValue(false) }
+ // OpenCode 1 is read by the turn state itself.
+ vi.mocked(opencodeV2TurnOpen).mockClear()
+ await setup(oc2).retarget({ agentId: 'a1', grid })
+ expect(opencodeV2TurnOpen).not.toHaveBeenCalled()
+ })
+
+ it('moves an agent between turns whatever its prompt shows, and one with no conversation to ask about', async () => {
+ // OpenCode 2's placeholder once read as a draft and refused every switch until the first chat.
+ const idle = setup(agent({ engine: 'opencode' } as Partial<RegisteredSession>))
+ expect(await idle.retarget({ agentId: 'a1', grid })).toEqual({ ok: true })
+ expect(idle.deps.sessionTurnOpen).toHaveBeenCalledWith('s1')
+ const fresh = setup(agent({ sessionId: undefined } as Partial<RegisteredSession>), { sessionTurnOpen: vi.fn(() => true) })
+ expect(await fresh.retarget({ agentId: 'a1', grid })).toEqual({ ok: true })
+ expect(fresh.deps.sessionTurnOpen).not.toHaveBeenCalled()
+ })
+
+ it('for a swap already running, or control it cannot take', async () => {
expect(await setup(agent(), { restartJobs: { busy: () => true, revision: () => 0 } as never }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })
expect(await setup(agent(), { acquireTerminalControl: () => null }).retarget({ agentId: 'a1', grid })).toEqual({ ok: false, error: 'AGENT_BUSY' })
})
diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.ts
index 4077af975..3a1c25705 100644
--- a/cli/src/core/agents/retarget.ts
+++ b/cli/src/core/agents/retarget.ts
@@ -22,7 +22,6 @@ import type { registry, RegisteredSession } from '../../lib/registry.js'
import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'
import type { RuntimeProfileManager } from '../../lib/runtimeProfile.js'
import { parseRuntimeProfile } from '../../lib/runtimeProfileWire.js'
-import type { ScreenReader } from '../../lib/screenReader.js'
import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
import { terminalRouteKey } from '../../lib/terminalRuntime.js'
import type { TmuxRuntimeRef } from '../../lib/terminalTypes.js'
@@ -39,14 +38,14 @@ type LaunchHelpers = ReturnType<typeof createLaunchHelpers>
type RetargetAgent = NonNullable<BackendSocket['onRetargetAgent']>
export interface RetargetDeps {
- readScreen: ScreenReader
+ /** Whether the engine's turn state says this session is mid-turn (normalizers.sessionTurnOpen). */
+ sessionTurnOpen: (sessionId: string) => boolean
/** Whether a purge holds this agent (PurgeAgentService.busy). */
purgeBusy: (agentId: string) => boolean | undefined
tmuxBackend: TmuxBackend | null
registry: typeof registry
runtimeProfiles: Pick<RuntimeProfileManager, 'selectedModel'>
launchOverridesDeps: LaunchOverridesDeps
- captureTerminal: (target: string, historyLines?: number) => Promise<string | null>
acquireTerminalControl: (id: string, opts?: { forAnswer?: boolean }) => (() => void) | null
relaunchOverrides: LaunchHelpers['relaunchOverrides']
downgradedPermission: LaunchHelpers['downgradedPermission']
@@ -61,7 +60,7 @@ export interface RetargetDeps {
}
export function createAgentRetargeter({
- readScreen, purgeBusy, tmuxBackend, registry, runtimeProfiles, launchOverridesDeps, captureTerminal, acquireTerminalControl,
+ sessionTurnOpen, purgeBusy, tmuxBackend, registry, runtimeProfiles, launchOverridesDeps, acquireTerminalControl,
relaunchOverrides, downgradedPermission, agentReconciler, restartJobs, paneSwapDeps, liveBypassPermission,
announceSession, refreshGridAssignment, opencodeDb,
}: RetargetDeps) {
@@ -168,15 +167,19 @@ export function createAgentRetargeter({
const missing = workspaceMissing(session.cwd)
if (missing) return missing
// Mid-turn is the one state where restarting costs real work: the conversation comes back but
- // whatever the engine was doing does not. The app is told which agents these are so the user can
- // move them once they are done, rather than being asked to choose between losing a turn and losing
- // the grid.
- const capture = await captureTerminal(session.agentId, 100)
- if (!current()) return changed()
- if (!capture) return { ok: false, error: 'TMUX_FAILED' }
- const screen = await readScreen(session, capture)
- if (!current()) return changed()
- if (!screen?.pane.idle) return { ok: false, error: 'AGENT_BUSY' }
+ // whatever the engine was doing does not. The engine's own turn state (hooks, transcript) says
+ // so, for every engine; the screen is not read. It used to be, to keep an unsent draft, and an
+ // engine whose placeholder colour moved (OpenCode 2) then read as holding one and refused every
+ // switch until its first chat. A draft is lost to the respawn; that is the person's call.
+ const inTurn = { ok: false as const, error: 'AGENT_BUSY', detail: 'This harness is in a turn. Stop it, then switch the model.' }
+ if (session.sessionId && sessionTurnOpen(session.sessionId)) return inTurn
+ // OpenCode 2 keeps its turns where that state does not read (`opencodeV2TurnOpen`), so its own
+ // record is asked. A store it cannot read is no evidence of a turn, as for an engine with none.
+ if (session.sessionId && opencode?.isOpencodeV2(opencodeMajor)) {
+ const open = await opencode.opencodeV2TurnOpen(native ? nativeOpencodeStore(native.environment) : opencodeDb, session.sessionId)
+ if (!current()) return changed()
+ if (open) return inTurn
+ }
// Nothing may type into the pane while it is being replaced.
if (purgeBusy(session.agentId) || restartJobs.busy(session.agentId)) return { ok: false, error: 'AGENT_BUSY' }
const release = acquireTerminalControl(session.agentId)
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 6ea60337c..111412b80 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -2394,13 +2394,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Moving a running agent onto a grid, or back to its own login (core/agents/retarget.ts).
backend.onRetargetAgent = createAgentRetargeter({
- readScreen: screens.read,
+ sessionTurnOpen,
purgeBusy: (agentId) => restorePanes.busy(agentId) || backend.purgeAgentService?.busy(agentId),
tmuxBackend,
registry,
runtimeProfiles,
launchOverridesDeps,
- captureTerminal,
acquireTerminalControl,
relaunchOverrides,
downgradedPermission,
diff --git a/cli/src/engines/kit/pane.ts b/cli/src/engines/kit/pane.ts
index 360f447fb..92aaee900 100644
--- a/cli/src/engines/kit/pane.ts
+++ b/cli/src/engines/kit/pane.ts
@@ -131,9 +131,11 @@ function hasPlaceholderSgr(value: string): boolean {
* effect rather than treating "no change" as a change.
*
* Grey is judged by the colour itself: equal channels, and dark enough to read as secondary next to
- * the near-white a composer draws real text in. OpenCode's placeholder is `38;2;128;128;128` and its
- * own text `38;2;255;255;255`; the 256-colour ramp (232–255) and SGR 90 are the same intent spelled
- * differently.
+ * the near-white a composer draws real text in. OpenCode 1.18's placeholder is `38;2;128;128;128`,
+ * OpenCode 2's `38;2;180;180;180` (measured on 2.0.24: above the old 0xb0 bound, so a new harness read
+ * as holding a draft and every model switch was AGENT_BUSY), and its own text `38;2;255;255;255`;
+ * up to 0xc0 is still well short of that white. The 256-colour ramp (232–255) and SGR 90 are the
+ * same intent spelled differently.
*/
function sgrMutedForeground(params: readonly string[]): boolean | null {
for (let index = 0; index < params.length; index += 1) {
@@ -143,7 +145,7 @@ function sgrMutedForeground(params: readonly string[]): boolean | null {
if (kind === '2') {
const [r, g, b] = [params[index + 2], params[index + 3], params[index + 4]].map(Number)
if (![r, g, b].every(Number.isFinite)) return null
- return r === g && g === b && r >= 0x40 && r <= 0xb0
+ return r === g && g === b && r >= 0x40 && r <= 0xc0
}
if (kind === '5') {
const n = Number(params[index + 2])
diff --git a/cli/src/engines/launchControl.ts b/cli/src/engines/launchControl.ts
index c209e1dfe..a76c5f1de 100644
--- a/cli/src/engines/launchControl.ts
+++ b/cli/src/engines/launchControl.ts
@@ -1,10 +1,20 @@
/** Eager native launch control. Importing it neither probes a binary nor reads or writes a store. */
import { opencodeBinAsync } from '../lib/engineBin.js'
-import { OPENCODE_SESSION_MODEL, OPENCODE_VERSION } from './opencode/contract.js'
+import { sqliteReadAll } from '../lib/sqliteRead.js'
+import { OPENCODE_SESSION_MODEL, OPENCODE_V2_TURN, OPENCODE_VERSION } from './opencode/contract.js'
import { executableSnapshot, majorVersion, nativeVersionProbe, parseMajor, type NativeExecutableSnapshot, type VersionProbe } from './kit/nativeVersion.js'
import { createSessionModelControl, type NativeApiRun, type NativeModelResult, type NativeSessionModel, type NativeModelAuthority } from './kit/nativeSessionModel.js'
export { isOpencodeV2 } from './opencode/contract.js'
+/** Whether OpenCode 2 session [sessionId] is in a turn, read from [dbPath] (`OPENCODE_V2_TURN`). Null when
+ * the store cannot be read. */
+export async function opencodeV2TurnOpen(dbPath: string, sessionId: string): Promise<boolean | null> {
+ if (!OPENCODE_SESSION_MODEL.id.test(sessionId)) return null
+ const result = await sqliteReadAll(dbPath, OPENCODE_V2_TURN.sql, [sessionId])
+ if (!result.ok) return null
+ return result.rows[0]?.type === OPENCODE_V2_TURN.opens
+}
+
export type OpencodeVersionProbe = VersionProbe
const versionMemo = new Map<string, number | null>()
export const parseOpencodeMajor = (output: string): number | null => parseMajor(OPENCODE_VERSION, output)
diff --git a/cli/src/engines/opencode/contract.ts b/cli/src/engines/opencode/contract.ts
index 3c81648e3..ec2444ac2 100644
--- a/cli/src/engines/opencode/contract.ts
+++ b/cli/src/engines/opencode/contract.ts
@@ -15,6 +15,18 @@ export function isOpencodeV2(major: number | null | undefined): boolean {
export const OPENCODE_VERSION = { output: /(\d+)\.\d+\.\d+/, args: ['--version'], timeoutMs: 5_000 } as const
+/**
+ * Whether an OpenCode 2 session is in a turn, by its own record. v2 keeps its conversation in `session_message`
+ * (the `message` table the transcript reader polls stays empty, so the daemon's turn state never opens for it)
+ * and writes a `user` row as a turn starts and an `idle` row as it ends — `outcome` succeeded, interrupted or
+ * failed alike. Measured on 2.0.24's store: 550 `idle` rows since it began writing them (2026-09-28), and no
+ * session since left with a `user` after its last `idle`.
+ */
+export const OPENCODE_V2_TURN = {
+ sql: "SELECT type FROM session_message WHERE session_id = ? AND type IN ('user', 'idle') ORDER BY seq DESC LIMIT 1;",
+ opens: 'user',
+} as const
+
/** Native model changes: v1's picker transaction and v2's service protocol, measured before extraction. */
export const OPENCODE_SESSION_MODEL = {
label: 'opencode', serviceMajor: OPENCODE_V2_MAJOR, id: /^[A-Za-z0-9_]+$/,
diff --git a/cli/src/engines/opencode/reader.spec.ts b/cli/src/engines/opencode/reader.spec.ts
index e767f67fb..56719bf73 100644
--- a/cli/src/engines/opencode/reader.spec.ts
+++ b/cli/src/engines/opencode/reader.spec.ts
@@ -4,6 +4,7 @@ import { mkdtempSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { OpencodeReader, readOpencodeMessages } from './reader.js'
+import { opencodeV2TurnOpen } from '../launchControl.js'
import type { LiveEvent } from '../../lib/normalize.js'
const hasSqlite = (() => {
@@ -191,3 +192,33 @@ d('OpencodeReader (sqlite3 CLI)', () => {
expect(deltas).toContain('lo world')
})
})
+
+d('opencodeV2TurnOpen (OpenCode 2 session_message)', () => {
+ let dir = ''
+ let db = ''
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'oc-v2-turn-')); db = join(dir, 'opencode.db')
+ run(db, 'CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, type TEXT NOT NULL, seq INTEGER NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL);')
+ })
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }) })
+ const row = (seq: number, type: string, sid = SID): void =>
+ run(db, `INSERT INTO session_message VALUES ('m${seq}${sid}','${sid}','${type}',${seq},${seq},${seq},'{}');`)
+
+ // Rows as 2.0.24 writes them: system, user, assistant…, idle {outcome} — measured on a live store.
+ it('is open from the user row until its idle row, whatever the outcome', async () => {
+ expect(await opencodeV2TurnOpen(db, SID)).toBe(false)
+ row(1, 'system'); row(2, 'user'); row(3, 'assistant')
+ expect(await opencodeV2TurnOpen(db, SID)).toBe(true)
+ row(4, 'idle')
+ expect(await opencodeV2TurnOpen(db, SID)).toBe(false)
+ row(5, 'user'); row(6, 'model-switched')
+ expect(await opencodeV2TurnOpen(db, SID)).toBe(true)
+ row(7, 'user', 'ses_other'); row(8, 'idle', 'ses_other')
+ expect(await opencodeV2TurnOpen(db, SID)).toBe(true)
+ })
+
+ it('is unknown for a store it cannot read or an id it will not query', async () => {
+ expect(await opencodeV2TurnOpen(join(dir, 'missing.db'), SID)).toBeNull()
+ expect(await opencodeV2TurnOpen(db, "x' OR 1=1")).toBeNull()
+ })
+})
diff --git a/cli/src/engines/opencodeLaunch.golden.spec.ts b/cli/src/engines/opencodeLaunch.golden.spec.ts
index f05894c58..fbd71c0dd 100644
--- a/cli/src/engines/opencodeLaunch.golden.spec.ts
+++ b/cli/src/engines/opencodeLaunch.golden.spec.ts
@@ -138,7 +138,7 @@ it('records create, fork, relaunch and actual retarget dispatch before the extra
setActive: (...args: unknown[]) => event(['active', ...args]) },
runtimeProfiles: { selectedModel: () => null },
launchOverridesDeps: { machine: world.machine, tmuxSupportsSessionEnv: world.tmuxSupportsSessionEnv },
- captureTerminal: async () => 'fixture idle', readScreen: async () => ({ pane: { idle: true } }),
+ sessionTurnOpen: () => false,
acquireTerminalControl: () => () => event(['release']), relaunchOverrides: shapes.relaunch,
downgradedPermission: async () => ({ bypassPermission: false, permissionMode: null }),
agentReconciler: { holdRoute: () => { event(['holdRoute']); return () => event(['releaseRoute']) } },
diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.ts
index ad39131c7..6a6ebd902 100644
--- a/cli/src/lib/runtimeProfileController.spec.ts
+++ b/cli/src/lib/runtimeProfileController.spec.ts
@@ -238,6 +238,27 @@ describe('runtime pane parsing', () => {
.toMatchObject({ idle: false, draft: true })
})
+ it('reads OpenCode 2\'s lighter grey placeholder as a placeholder, not a draft', () => {
+ // Copied off a brand-new OpenCode 2.0.24 pane (2026-10-12): the placeholder is
+ // `38;2;180;180;180` over the box's `48;2;25;25;25`, one step lighter than 1.18's 128, and just
+ // above the grey this reader took for muted (≤ 0xb0). A new harness read as holding a draft, was
+ // never idle, and switching its model came back AGENT_BUSY until a first message cleared it.
+ const BOX = '\u001b[48;2;25;25;25m'
+ const WHITE = '\u001b[38;2;255;255;255m'
+ const HINT = '\u001b[38;2;180;180;180m'
+ const pane = (composer: string) => [
+ ` \u001b[38;2;178;148;187m┃${WHITE}${BOX} ${composer}${WHITE} \u001b[49m`,
+ ` \u001b[38;2;178;148;187m┃${WHITE}${BOX} \u001b[38;2;178;148;187mBuild${WHITE} ${HINT}·${WHITE} DeepSeek-V4-Flash-0731\u001b[49m`,
+ ' \u001b[38;2;178;148;187m╹\u001b[38;2;25;25;25m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀',
+ ].join('\n')
+
+ expect(inspectRuntimePane('opencode', pane(`${HINT}Ask anything… "Fix a TODO in the codebase"`)))
+ .toMatchObject({ idle: true, draft: false })
+ // ⚠️ Still the direction that must never be wrong: what the user types is the composer's white.
+ expect(inspectRuntimePane('opencode', pane(`${WHITE}switch me please`)))
+ .toMatchObject({ idle: false, draft: true })
+ })
+
it('reads copilot, whose composer carries no marker while its sent messages do', () => {
// Copied off a live pane. Copilot echoes every message the user has ALREADY SENT into the
// transcript as `❯ <text>` in full brightness, and draws its composer as a `┃` box that carries
diff --git a/tui/Cargo.lock b/tui/Cargo.lock
index 8c0632b83..728835d47 100644
--- a/tui/Cargo.lock
+++ b/tui/Cargo.lock
@@ -654,7 +654,7 @@ dependencies = [
[[package]]
name = "harness-tui"
-version = "0.1.23"
+version = "0.1.24"
dependencies = [
"alacritty_terminal",
"base64",
diff --git a/tui/Cargo.toml b/tui/Cargo.toml
index 44a1ff040..84fac545e 100644
--- a/tui/Cargo.toml
+++ b/tui/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "harness-tui"
-version = "0.1.23"
+version = "0.1.24"
edition = "2024"
[dependencies]
diff --git a/tui/src/models.rs b/tui/src/models.rs
index 3b714dd61..41e3fc618 100644
--- a/tui/src/models.rs
+++ b/tui/src/models.rs
@@ -395,6 +395,9 @@ pub struct Models {
/// The picker keeps the harness it opened for, even if another client changes focus.
pub selection: Option<crate::session_close::Identity>,
pub selection_fixed: bool,
+ /// The pane focused when it opened: a harness there still starting (its terminal, until the
+ /// daemon sees the engine) becomes the selection once it is one.
+ selection_pane: Option<u64>,
pub panel_generation: u64,
pub switch_generation: u64,
/// Each machine's local models, when they were last read, and a read out now.
@@ -508,7 +511,7 @@ pub fn target(app: &App) -> Option<Target> {
};
if app.models_view.selection_fixed {
let selected = app.models_view.selection.as_ref()?;
- if !selected.matches(app) { return None }
+ if !same_harness(app, selected) { return None }
return of(selected.machine.clone(), selected.agent.clone());
}
if let Some(t) = crate::input::focused_agent(app).and_then(|(m, a)| of(m, a)) { return Some(t) }
@@ -1129,8 +1132,16 @@ pub fn choose(app: &mut App, picker: &mut Picker, id: &str, stop: bool) {
run(app, picker, plan, &key);
}
+/// Whether [identity] is still the harness the view opened for. One that had no conversation yet and
+/// now has its first (a new harness is chatted with, or its engine reports its session late) is the
+/// same harness; any other change of conversation is not.
+fn same_harness(app: &App, identity: &crate::session_close::Identity) -> bool {
+ identity.matches(app) || identity.session.is_empty() && identity.connection_matches(app)
+ && app.fleet.agent(&identity.machine, &identity.agent).is_some_and(|a| a.created_at_wire == identity.created)
+}
+
fn current_identity(app: &App, identity: &crate::session_close::Identity) -> bool {
- identity.matches(app) && app.fleet.agent(&identity.machine, &identity.agent).is_some_and(|a| a.status != "stopped")
+ same_harness(app, identity) && app.fleet.agent(&identity.machine, &identity.agent).is_some_and(|a| a.status != "stopped")
}
fn selection_changed(app: &App) -> bool {
@@ -1888,9 +1899,8 @@ pub fn advance(app: &mut App) {
/// The view opened: read what it shows now (what was read in the last 20 s of the grids is kept).
pub fn open(app: &mut App) {
reconcile_reads(app);
- app.models_view.selection_fixed = false;
- app.models_view.selection = target(app).and_then(|t| app.fleet.agent(&t.machine, &t.agent)).map(|a| crate::session_close::Identity::capture(app, a));
- app.models_view.selection_fixed = true;
+ app.models_view.selection_pane = app.focused();
+ select(app);
app.models_view.panel_generation = app.models_view.panel_generation.wrapping_add(1);
let machine = app.fleet.local_id.clone();
if machine.is_empty() || app.link(&machine).is_none() { return }
@@ -1899,6 +1909,13 @@ pub fn open(app: &mut App) {
read_apis(app);
}
+/// Fix the harness the view acts on: the one [target] names now.
+fn select(app: &mut App) {
+ app.models_view.selection_fixed = false;
+ app.models_view.selection = target(app).and_then(|t| app.fleet.agent(&t.machine, &t.agent)).map(|a| crate::session_close::Identity::capture(app, a));
+ app.models_view.selection_fixed = true;
+}
+
/// Whether the view is still reading what it shows (its spinner turns).
pub fn loading(app: &App) -> bool { !app.models_view.reading.is_empty() || !app.models_view.grids_reading.is_empty() }
@@ -1907,7 +1924,14 @@ pub fn loading(app: &App) -> bool { !app.models_view.reading.is_empty() || !app.
pub fn tick(app: &mut App) {
reconcile_reads(app);
let open = matches!(&app.modal, Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Models, .. }));
- if !open { app.models_view.selection_fixed = false; app.models_view.selection = None; }
+ if !open { app.models_view.selection_fixed = false; app.models_view.selection = None; app.models_view.selection_pane = None; }
+ // Opened over a harness still starting: it is the one meant once its engine is seen, while that
+ // pane keeps the focus. (A selection already made is never replaced: "This session changed".)
+ if open && app.models_view.selection.is_none() && app.models_view.selection_pane.is_some() && app.focused() == app.models_view.selection_pane { select(app) }
+ // Its first conversation, once it has one, is the one it is held to from then on.
+ let first = app.models_view.selection.as_ref().filter(|s| s.session.is_empty() && same_harness(app, s))
+ .and_then(|s| app.fleet.agent(&s.machine, &s.agent)).map(|a| a.session_id.clone()).filter(|id| !id.is_empty());
+ if let (Some(session), Some(s)) = (first, app.models_view.selection.as_mut()) { s.session = session }
follow(app);
app.models_view.starts.retain(|_, at| at.elapsed() < START_CAP);
if app.models_view.switching.as_ref().is_some_and(|s| switched(app, s)) { app.models_view.switching = None }
@@ -2278,7 +2302,7 @@ mod tests {
/// The harness's frame, its `grid` as given (`{}`: on its own login).
fn frame(app: &mut App, grid: Value) {
let key = ("local".to_string(), "a1".to_string());
- let row = json!({ "id": "a1", "name": "fix-login", "engine": "claude", "selectedModel": "opus", "grid": grid });
+ let row = json!({ "id": "a1", "name": "fix-login", "engine": "claude", "sessionId": "s1", "selectedModel": "opus", "grid": grid });
let a = crate::fleet::agent_from("local", &row, app.fleet.agents.get(&key));
app.fleet.agents.insert(key, a);
}
@@ -2296,6 +2320,38 @@ mod tests {
assert_eq!(mine, vec!["mv:local:qwen-35b".to_string(), "mv:local:gemma-12b".into(), "mv:grid:own-grid\tstudio\tbox-model".into(), "mv:grid:own-grid\tlap\taway-model".into()]);
}
+ /// A harness just opened reads as its terminal until the daemon sees the engine in it (OpenCode:
+ /// ~7 s). Models opened in that window takes the engine once it is seen — the same pane, never
+ /// another — instead of saying "focus a harness" until it is closed and opened again.
+ #[test]
+ fn models_opened_while_a_harness_starts_takes_it_once_its_engine_is_seen() {
+ let mut app = app();
+ let key = ("local".to_string(), "t1".to_string());
+ app.fleet.agents.insert(key.clone(), crate::fleet::agent_from("local", &json!({ "id": "t1", "name": "new", "engine": "terminal" }), None));
+ app.panes.insert(2, crate::pane::Pane::new(2, "local", "t1", 75, 40));
+ app.rects = vec![(1, ratatui::layout::Rect::new(0, 0, 75, 40)), (2, ratatui::layout::Rect::new(75, 0, 75, 40))];
+ app.tabs[0].focus = Some(2);
+ app.modal = Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Models, picker: crate::picker::Picker::new("Models", "") });
+ open(&mut app);
+ assert!(target(&app).is_none(), "still a terminal");
+ app.fleet.agents.insert(key.clone(), crate::fleet::agent_from("local", &json!({ "id": "t1", "name": "new", "engine": "opencode" }), None));
+ tick(&mut app);
+ assert_eq!(target(&app).map(|t| t.agent).as_deref(), Some("t1"), "{}", no_target_why(&app));
+ // Its first conversation a moment later is the same harness; another one after it is not.
+ app.fleet.agents.insert(key.clone(), crate::fleet::agent_from("local", &json!({ "id": "t1", "name": "new", "engine": "opencode", "sessionId": "ses_1" }), None));
+ assert_eq!(target(&app).map(|t| t.agent).as_deref(), Some("t1"), "{}", no_target_why(&app));
+ tick(&mut app);
+ app.fleet.agents.insert(key.clone(), crate::fleet::agent_from("local", &json!({ "id": "t1", "name": "new", "engine": "opencode", "sessionId": "ses_2" }), None));
+ assert!(target(&app).is_none());
+ assert!(no_target_why(&app).contains("This session changed"), "{}", no_target_why(&app));
+ // Another pane focused meanwhile: not followed there.
+ app.fleet.agents.insert(key, crate::fleet::agent_from("local", &json!({ "id": "t1", "name": "new", "engine": "terminal" }), None));
+ open(&mut app);
+ app.tabs[0].focus = Some(1);
+ tick(&mut app);
+ assert!(target(&app).is_none());
+ }
+
/// Which harness Enter moves: the focused pane's. A focused terminal is the one meant — never
/// the harness beside it — and the panel says why there is none; with nothing focused, the one
/// harness on screen.