Skip to content

The agent that grows with you

fix: scope Ink config hydration and prompt model mutations

Teknium798c3926662a
diff --git a/ui-tui/src/__tests__/orchestratorPromptSession.test.ts b/ui-tui/src/__tests__/orchestratorPromptSession.test.ts
index cff6ac86cf0..6e3f540d07b 100644
--- a/ui-tui/src/__tests__/orchestratorPromptSession.test.ts
+++ b/ui-tui/src/__tests__/orchestratorPromptSession.test.ts
@@ -6,7 +6,7 @@ import { startPromptLiveSession } from '../app/useMainApp.js'
describe('startPromptLiveSession', () => {
it('keeps the created target through a delayed model switch without publishing into the new focus', async () => {
patchUiState({ sid: 'created' })
- let finish!: (value: { value: string }) => void
+ let finish!: (value: { model: string }) => void
const dispatched: unknown[] = []
const notices: string[] = []
@@ -17,13 +17,18 @@ describe('startPromptLiveSession', () => {
newLiveSession: async () => 'created',
onModelSwitched: () => notices.push('model'),
prompt: 'private prompt',
- rpc: () => new Promise(resolve => { finish = resolve }),
+ rpc: async method =>
+ method === 'session.resume'
+ ? { revision: 8, execution_generation: 4 }
+ : new Promise(resolve => {
+ finish = resolve
+ }),
sys: text => notices.push(text)
})
- await Promise.resolve()
+ await new Promise(resolve => setImmediate(resolve))
patchUiState({ sid: 'other' })
- finish({ value: 'chosen' })
+ finish({ model: 'chosen' })
await pending
expect(dispatched).toEqual([{ text: 'private prompt', destination: expect.objectContaining({ sid: 'created' }) }])
expect(notices).toEqual([])
@@ -48,7 +53,9 @@ describe('startPromptLiveSession', () => {
rpc: async (method, params) => {
calls.push(['rpc', { method, params }])
- return { value: 'kimi-k2.6', warning: '' }
+ return method === 'session.resume'
+ ? { revision: 8, execution_generation: 4 }
+ : { model: 'kimi-k2.6', warning: '' }
},
sys: text => calls.push(['sys', text])
})
@@ -56,16 +63,24 @@ describe('startPromptLiveSession', () => {
expect(sid).toBe('abc123')
expect(calls).toEqual([
['new', { message: 'new live session started', title: undefined }],
+ ['rpc', { method: 'session.resume', params: { session_id: 'abc123' } }],
[
'rpc',
{
- method: 'config.set',
- params: { key: 'model', session_id: 'abc123', value: 'kimi-k2.6 --provider ollama-cloud --session' }
+ method: 'session.mutate',
+ params: {
+ session_id: 'abc123',
+ request_id: expect.any(String),
+ expected_revision: 8,
+ expected_generation: 4,
+ operation: 'model',
+ payload: { model: 'kimi-k2.6', provider: 'ollama-cloud' }
+ }
}
],
['sys', 'model → kimi-k2.6'],
- ['warn', { value: 'kimi-k2.6', warning: '' }],
- ['model-switched', { result: { value: 'kimi-k2.6', warning: '' }, value: 'kimi-k2.6' }],
+ ['warn', { model: 'kimi-k2.6', value: 'kimi-k2.6', warning: '' }],
+ ['model-switched', { result: { model: 'kimi-k2.6', value: 'kimi-k2.6', warning: '' }, value: 'kimi-k2.6' }],
['dispatch', 'Build the thing']
])
})
diff --git a/ui-tui/src/__tests__/useConfigSync.test.ts b/ui-tui/src/__tests__/useConfigSync.test.ts
index 569e10ea1fa..015fd8477bb 100644
--- a/ui-tui/src/__tests__/useConfigSync.test.ts
+++ b/ui-tui/src/__tests__/useConfigSync.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { $uiState, resetUiState } from '../app/uiStore.js'
+import { $uiState, patchUiState, resetUiState } from '../app/uiStore.js'
import {
applyDisplay,
hydrateFullConfig,
@@ -525,6 +525,43 @@ describe('syncMcpReload (revision-aware ack)', () => {
// + apply body is now shared as ``hydrateFullConfig()``, exercised
// directly from both the initial hydration and the poll-tick body.
describe('hydrateFullConfig', () => {
+ it('hydrates the session busy preference instead of profile defaults and preserves it on read failure', async () => {
+ patchUiState({ sid: 'owner', busyInputMode: 'queue' })
+ const request = vi.fn(async (_method: string, params: any) =>
+ params.key === 'busy' ? { value: 'steer' } : { config: { display: { busy_input_mode: 'interrupt' } } }
+ )
+ const gw = { isCanonical: true, request } as any
+ const scope = { sid: 'owner', isCurrent: () => true }
+ await hydrateFullConfig(gw, vi.fn(), undefined, undefined, scope)
+ expect(request).toHaveBeenCalledWith('config.get', { key: 'full', session_id: 'owner' })
+ expect(request).toHaveBeenCalledWith('config.get', { key: 'busy', session_id: 'owner' })
+ expect($uiState.get().busyInputMode).toBe('steer')
+ request.mockImplementation(async (_method, params) => {
+ if (params.key === 'busy') throw new Error('disconnected')
+ return { config: { display: { busy_input_mode: 'interrupt' } } }
+ })
+ await hydrateFullConfig(gw, vi.fn(), undefined, undefined, scope)
+ expect($uiState.get().busyInputMode).toBe('steer')
+ })
+
+ it('discards delayed full and busy hydration after focus changes', async () => {
+ patchUiState({ sid: 'old', busyInputMode: 'queue' })
+ let current = true
+ const replies: Array<(value: any) => void> = []
+ const gw = {
+ isCanonical: true,
+ request: vi.fn(() => new Promise(resolve => replies.push(resolve)))
+ } as any
+ const setBell = vi.fn()
+ const pending = hydrateFullConfig(gw, setBell, undefined, undefined, { sid: 'old', isCurrent: () => current })
+ current = false
+ patchUiState({ sid: 'new', busyInputMode: 'interrupt' })
+ for (const reply of replies) reply({ config: { display: { busy_input_mode: 'steer' } }, value: 'steer' })
+ await pending
+ expect(setBell).not.toHaveBeenCalled()
+ expect($uiState.get().busyInputMode).toBe('interrupt')
+ })
+
beforeEach(() => {
resetUiState()
})
diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.ts
index eb9353da387..6d8d38e6499 100644
--- a/ui-tui/src/app/slash/canonicalSessionControls.ts
+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts
@@ -2,15 +2,18 @@ import { randomUUID } from 'node:crypto'
import { introMsg, toTranscriptMessages } from '../../domain/messages.js'
import { TUI_SESSION_MODEL_FLAG } from '../../domain/slash.js'
-import type { GatewayClient } from '../../gatewayClient.js'
import { asRpcResult } from '../../lib/rpc.js'
import { getUiState, patchUiState } from '../uiStore.js'
import type { SlashRunCtx } from './types.js'
+interface MutationGateway {
+ request: (method: string, params?: Record<string, unknown>) => Promise<unknown>
+}
+
// Keep the original CAS tuple after a lost reply. Reissuing the same command
// must query that receipt, not silently authorize another write at a new revision.
-const pending = new WeakMap<GatewayClient, Map<string, Record<string, unknown>>>()
+const pending = new WeakMap<MutationGateway, Map<string, Record<string, unknown>>>()
function modelPayload(arg: string) {
const parts = arg.trim().split(/\s+/)
@@ -40,72 +43,88 @@ function modelPayload(arg: string) {
return payload
}
-export async function runCanonicalSessionControl(
+export async function mutateCanonicalSession(
+ gw: MutationGateway,
+ sid: string,
operation: 'model' | 'branch' | 'compress',
arg: string,
- ctx: SlashRunCtx
+ stale: () => boolean = () => false
) {
- const gw = ctx.gateway.gw
+ const payload =
+ operation === 'model' ? modelPayload(arg) : arg ? { [operation === 'branch' ? 'title' : 'focus']: arg } : {}
- try {
- if (!ctx.sid) {
- throw new Error('no active session')
- }
+ let requests = pending.get(gw)
+
+ if (!requests) {
+ requests = new Map()
+ pending.set(gw, requests)
+ }
- const payload =
- operation === 'model' ? modelPayload(arg) : arg ? { [operation === 'branch' ? 'title' : 'focus']: arg } : {}
+ const key = JSON.stringify([sid, operation, payload])
+ let params = requests.get(key)
- let requests = pending.get(gw)
+ if (!params) {
+ const snapshot = asRpcResult(await gw.request('session.resume', { session_id: sid }))
- if (!requests) {
- requests = new Map()
- pending.set(gw, requests)
+ if (stale()) {
+ return
}
- const key = JSON.stringify([ctx.sid, operation, payload])
- let params = requests.get(key)
+ if (!Number.isSafeInteger(snapshot?.revision) || !Number.isSafeInteger(snapshot?.execution_generation)) {
+ throw new Error('session execution identity unavailable; reconnect before editing')
+ }
- if (!params) {
- const snapshot = asRpcResult(await gw.request('session.resume', { session_id: ctx.sid }))
+ params = {
+ session_id: sid,
+ request_id: randomUUID(),
+ expected_revision: snapshot!.revision,
+ expected_generation: snapshot!.execution_generation,
+ operation,
+ payload
+ }
+ requests.set(key, params)
+ }
- if (ctx.stale()) {
- return
- }
+ let result
- if (!Number.isSafeInteger(snapshot?.revision) || !Number.isSafeInteger(snapshot?.execution_generation)) {
- throw new Error('session execution identity unavailable; reconnect before editing')
- }
+ try {
+ result = asRpcResult(await gw.request('session.mutate', params))
- params = {
- session_id: ctx.sid,
- request_id: randomUUID(),
- expected_revision: snapshot!.revision,
- expected_generation: snapshot!.execution_generation,
- operation,
- payload
- }
- requests.set(key, params)
+ if (!result) {
+ throw new Error('invalid response: session.mutate')
}
- let result
+ requests.delete(key)
+ } catch (error) {
+ // A structured authority refusal is definitive; transport errors are not.
+ if ((error as { data?: { reason?: string } })?.data?.reason) {
+ requests.delete(key)
+ }
- try {
- result = asRpcResult(await gw.request('session.mutate', params))
+ throw error
+ }
+ return { result, expectedGeneration: params.expected_generation as number }
+}
- if (!result) {
- throw new Error('invalid response: session.mutate')
- }
+export async function runCanonicalSessionControl(
+ operation: 'model' | 'branch' | 'compress',
+ arg: string,
+ ctx: SlashRunCtx
+) {
+ const gw = ctx.gateway.gw
- requests.delete(key)
- } catch (error) {
- // A structured authority refusal is definitive; transport errors are not.
- if ((error as { data?: { reason?: string } })?.data?.reason) {
- requests.delete(key)
- }
+ try {
+ if (!ctx.sid) {
+ throw new Error('no active session')
+ }
- throw error
+ const mutation = await mutateCanonicalSession(gw, ctx.sid, operation, arg, ctx.stale)
+
+ if (!mutation) {
+ return
}
+ const { result, expectedGeneration } = mutation
if (ctx.stale()) {
return
}
@@ -115,7 +134,7 @@ export async function runCanonicalSessionControl(
if (
operation !== 'branch' &&
(current?.execution_epoch !== ctx.ui.info?.execution_epoch ||
- (current?.execution_generation ?? 0) > (result.execution_generation ?? params.expected_generation))
+ (current?.execution_generation ?? 0) > (result.execution_generation ?? expectedGeneration))
) {
return
}
diff --git a/ui-tui/src/app/useConfigSync.ts b/ui-tui/src/app/useConfigSync.ts
index 2f3f31dca32..e17db659894 100644
--- a/ui-tui/src/app/useConfigSync.ts
+++ b/ui-tui/src/app/useConfigSync.ts
@@ -16,7 +16,7 @@ import {
type StatusBarMode
} from './interfaces.js'
import { turnController } from './turnController.js'
-import { patchUiState } from './uiStore.js'
+import { getUiState, patchUiState } from './uiStore.js'
const STATUSBAR_ALIAS: Record<string, StatusBarMode> = {
bottom: 'bottom',
@@ -254,10 +254,23 @@ export async function hydrateFullConfig(
gw: GatewayClient,
setBell: (v: boolean) => void,
setVoiceRecordKey?: (v: ParsedVoiceRecordKey) => void,
- setBellOnPrompt?: (v: boolean) => void
+ setBellOnPrompt?: (v: boolean) => void,
+ scope?: { sid: string; isCurrent: () => boolean }
): Promise<ConfigFullResponse | null> {
- const cfg = await quietRpc<ConfigFullResponse>(gw, 'config.get', { key: 'full' })
- applyDisplay(cfg, setBell, setVoiceRecordKey, setBellOnPrompt)
+ const params = scope ? { session_id: scope.sid } : {}
+ const [cfg, busy] = await Promise.all([
+ quietRpc<ConfigFullResponse>(gw, 'config.get', { key: 'full', ...params }),
+ gw.isCanonical && scope ? quietRpc(gw, 'config.get', { key: 'busy', ...params }) : null
+ ])
+
+ if (scope && !scope.isCurrent()) {
+ return null
+ }
+
+ applyDisplay(cfg, setBell, setVoiceRecordKey, setBellOnPrompt, !gw.isCanonical)
+ if (gw.isCanonical && BUSY_MODES.has(busy?.value)) {
+ patchUiState({ busyInputMode: busy!.value })
+ }
return cfg
}
@@ -266,7 +279,8 @@ export const applyDisplay = (
cfg: ConfigFullResponse | null,
setBell: (v: boolean) => void,
setVoiceRecordKey?: (v: ParsedVoiceRecordKey) => void,
- setBellOnPrompt?: (v: boolean) => void
+ setBellOnPrompt?: (v: boolean) => void,
+ applyBusy = true
) => {
const d = cfg?.config?.display ?? {}
const approvals = cfg?.config?.approvals
@@ -290,7 +304,7 @@ export const applyDisplay = (
patchUiState({
battery: !!d.battery,
- busyInputMode: normalizeBusyInputMode(d.busy_input_mode),
+ ...(applyBusy ? { busyInputMode: normalizeBusyInputMode(d.busy_input_mode) } : {}),
compact: !!d.tui_compact,
// Fail safe: only YAML boolean false disables the prompt. A transient
// config RPC failure (cfg=null) preserves the last known policy instead
@@ -331,12 +345,16 @@ export function useConfigSync({
return
}
+ let active = true
+ const scope = { sid, isCurrent: () => active && getUiState().sid === sid }
+
// Keep startup cheap: voice.toggle status probes optional audio/STT deps and
// can run long enough to delay prompt.submit on the single stdio RPC pipe.
// Environment flags are enough to initialize the UI bit; the heavier status
// check still runs when the user opens /voice.
setVoiceEnabled(process.env.HERMES_VOICE === '1')
- quietRpc<ConfigMtimeResponse>(gw, 'config.get', { key: 'mtime' }).then(r => {
+ quietRpc<ConfigMtimeResponse>(gw, 'config.get', { key: 'mtime', session_id: sid }).then(r => {
+ if (!scope.isCurrent()) return
mtimeRef.current = Number(r?.mtime ?? 0)
// Seed the MCP revision baseline too: after a normal boot mtime is
// already non-zero, so the poller's baseline branch never runs, and an
@@ -344,7 +362,10 @@ export function useConfigSync({
// mcp_rev) look like an MCP change and fire a needless reload.mcp.
mcpRevRef.current.accepted = String(r?.mcp_rev ?? '')
})
- void hydrateFullConfig(gw, setBellOnComplete, setVoiceRecordKey, setBellOnPrompt)
+ void hydrateFullConfig(gw, setBellOnComplete, setVoiceRecordKey, setBellOnPrompt, scope)
+ return () => {
+ active = false
+ }
}, [gw, setBellOnComplete, setBellOnPrompt, setVoiceEnabled, setVoiceRecordKey, sid])
useEffect(() => {
@@ -352,8 +373,11 @@ export function useConfigSync({
return
}
+ let active = true
+ const scope = { sid, isCurrent: () => active && getUiState().sid === sid }
const id = setInterval(() => {
- quietRpc<ConfigMtimeResponse>(gw, 'config.get', { key: 'mtime' }).then(r => {
+ quietRpc<ConfigMtimeResponse>(gw, 'config.get', { key: 'mtime', session_id: sid }).then(r => {
+ if (!scope.isCurrent()) return
const next = Number(r?.mtime ?? 0)
const nextMcpRev = String(r?.mcp_rev ?? '')
@@ -392,11 +416,14 @@ export function useConfigSync({
)
}
- void hydrateFullConfig(gw, setBellOnComplete, setVoiceRecordKey, setBellOnPrompt)
+ void hydrateFullConfig(gw, setBellOnComplete, setVoiceRecordKey, setBellOnPrompt, scope)
})
}, MTIME_POLL_MS)
- return () => clearInterval(id)
+ return () => {
+ active = false
+ clearInterval(id)
+ }
}, [gw, setBellOnComplete, setBellOnPrompt, setVoiceRecordKey, sid])
}
diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.ts
index a76bebd051c..ac570ff4bfa 100644
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@ -18,7 +18,6 @@ import { RESIZE_COALESCE_MS } from '../config/timing.js'
import { hasLeadGap, prevRenderedMsg } from '../domain/blockLayout.js'
import { SECTION_NAMES, sectionMode } from '../domain/details.js'
import { composeTabTitle, fmtProjectCwdBranch, shortCwd } from '../domain/paths.js'
-import { sessionScopedModelArg } from '../domain/slash.js'
import { type GatewayClient } from '../gatewayClient.js'
import type { SubagentListResponse } from '../gatewayTypes.js'
import type {
@@ -57,6 +56,7 @@ import { type GatewayRpc, type StateSetter, type TranscriptRow } from './interfa
import { $overlayState, capturePromptResponseGuard, patchOverlayState } from './overlayStore.js'
import { $goodVibesTick } from './petFlashStore.js'
import { scrollWithSelectionBy } from './scroll.js'
+import { mutateCanonicalSession } from './slash/canonicalSessionControls.js'
import { captureDestination, isCurrentDestination, type SubmissionDestination } from './submissionDestination.js'
import { turnController } from './turnController.js'
import { patchTurnState, useTurnSelector } from './turnStore.js'
@@ -129,10 +129,11 @@ export async function startPromptLiveSession({
}
const destination = Object.freeze({ ...captureDestination(), sid })
- const requestedModel = modelArg ? sessionScopedModelArg(modelArg) : ''
+ const requestedModel = modelArg?.trim() ?? ''
if (requestedModel) {
- const result = await rpc<ConfigSetResponse>('config.set', { key: 'model', session_id: sid, value: requestedModel })
+ const mutation = await mutateCanonicalSession({ request: rpc }, sid, 'model', requestedModel)
+ const result = mutation ? { ...mutation.result, value: mutation.result.model } : null
if (!result?.value) {
sys('error: invalid response: model switch')