The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): a picked model and reasoning level commit as one canonical selection
Tekniumb9a86d07e74e
diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.pyindex 1d1c24ef339..be090e27441 100644--- a/gateway/session_mutation_model.py+++ b/gateway/session_mutation_model.py@@ -33,6 +33,10 @@ async def prepare_model(authority, live, payload, prepared):# and the endpoint-bound credential fields (inline key, key_env/api_key_env) drop on a route change.# Off-loop: the context-pin check can do cold-start disk I/O.frozen['model'] = await asyncio.to_thread(apply_model_selection, frozen.get('model'), result)+ if 'reasoning' in payload:+ # The level picked with the model lands in the same commit (as prepare_reasoning writes it).+ frozen.setdefault('agent', {})['reasoning_effort'] = payload['reasoning']+ frozen['agent'].pop('reasoning_overrides', None)if old.follows_profile:# A committed /model holds while the profile still targets what it targets now (main's# composer_override_profile); a later profile edit supersedes it.diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex ceb4c569f9d..eb9d3245244 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -258,7 +258,7 @@ def _project_committed(authority, ref, operation, result):# the old live one and paused; with both now equal, queued input must run, not wait for# the next submit or restart.authority._schedule(ref)- if operation == 'reasoning':+ if operation == 'reasoning' or (operation == 'model' and 'effort' in result):# The picked level is the policy's now; a typed /reasoning override must not shadow it.authority.runner._set_session_reasoning_override(authority.sessions[ref.session_id].route, None)if operation in {'model', 'reasoning', 'workspace'}:diff --git a/hermes_state_mutation_prepared.py b/hermes_state_mutation_prepared.pyindex 69eee70d53c..5b547938340 100644--- a/hermes_state_mutation_prepared.py+++ b/hermes_state_mutation_prepared.py@@ -55,7 +55,8 @@ def model_in_transaction(db, conn, session_id, payload, prepared):conn.execute('UPDATE sessions SET model=?,model_config=? WHERE id=?', (model, _json(model_config), target))# This selection is newer than any pick still waiting for a turn boundary: that pick is superseded.conn.execute('DELETE FROM state_meta WHERE key=?', (DEFERRED_PICK_PREFIX + session_id,))- return {session_id, target}, {'model': model, 'provider': config['provider'], 'execution_generation': generation}+ return {session_id, target}, {'model': model, 'provider': config['provider'], 'execution_generation': generation,+ **({'effort': payload['reasoning']} if 'reasoning' in payload else {})}def reasoning_in_transaction(db, conn, session_id, payload, prepared):diff --git a/hermes_state_mutations.py b/hermes_state_mutations.pyindex 73374396f92..4a186195518 100644--- a/hermes_state_mutations.py+++ b/hermes_state_mutations.py@@ -9,9 +9,12 @@ def validate_action(operation, payload):if not isinstance(payload, dict) or not isinstance(operation, str):raise RuntimeStoreError('invalid_params')# ``confirm``: the owner's selection-guard token for this exact resolved target (session_mutation_model).- if (operation == 'model' and 'model' in payload and not set(payload) - {'model', 'provider', 'confirm'}+ # ``reasoning``: a level picked with the model, committed in the same selection.+ if (operation == 'model' and 'model' in payload and not set(payload) - {'model', 'provider', 'confirm', 'reasoning'}and all(isinstance(v, str) and v.strip() for v in payload.values())):- return+ from hermes_constants import parse_reasoning_effort+ if 'reasoning' not in payload or parse_reasoning_effort(payload['reasoning']) is not None:+ returnif operation == 'branch' and _valid_branch_payload(payload):return# Session-scope ``/reasoning <level>`` and Desktop's Move to project: revision-fenced edits ofdiff --git a/tests/gateway/test_session_mutation_model_busy.py b/tests/gateway/test_session_mutation_model_busy.pyindex 97da18d16f8..13ac0ec1b1a 100644--- a/tests/gateway/test_session_mutation_model_busy.py+++ b/tests/gateway/test_session_mutation_model_busy.py@@ -377,3 +377,40 @@ async def test_a_deferred_pick_that_raises_is_refused_and_the_queue_keeps_drainirelease.set()await owner.close()store.close_all_db_handles()+++async def test_a_deferred_model_and_reasoning_pick_commits_both_together(tmp_path, monkeypatch):+ from gateway.session_contract import Submission+ from gateway.session_policy import policy_for_source+ started, release = threading.Event(), asyncio.Event()+ seen = []+ state = {}++ async def handle(event):+ live = state['authority'].sessions[state['ref'].session_id]+ effort = policy_for_source(state['authority'].runner, live.source).reasoning_config+ seen.append((event.text, _running_model(state['authority'], state['ref']), (effort or {}).get('effort')))+ if event.text == 'RUNNING':+ started.set()+ await release.wait()+ return 'ok'+ store, db, authority, owner, ref = _owner(tmp_path, monkeypatch, handle)+ state.update(authority=authority, ref=ref)+ authority.runner._set_session_reasoning_override = lambda *a: None+ try:+ await authority.submit(owner.actor, Submission('running', ref, {'text': 'RUNNING'}, 'queue'))+ await async_wait_until(started.is_set, timeout=10, what='the first turn is running')+ snap = db.get_session(ref.session_id)+ reply = await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {+ 'session_id': ref.session_id, 'request_id': 'pick', 'expected_revision': snap['runtime_revision'],+ 'expected_generation': snap['runtime_generation'], 'operation': 'model',+ 'payload': {'model': 'picked', 'reasoning': 'high'}}})+ assert reply.get('result', {}).get('status') == 'deferred', reply+ release.set()+ await _run_turn(authority, owner, db, ref, 'NEXT')+ assert seen[-1] == ('NEXT', 'picked', 'high'), seen+ finally:+ release.set()+ await owner.close()+ store.close_all_db_handles()diff --git a/ui-tui/src/__tests__/canonicalSessionControls.test.ts b/ui-tui/src/__tests__/canonicalSessionControls.test.tsindex 53a544022d9..fcbbeaf4623 100644--- a/ui-tui/src/__tests__/canonicalSessionControls.test.ts+++ b/ui-tui/src/__tests__/canonicalSessionControls.test.ts@@ -247,7 +247,7 @@ it('a pick deferred by a running turn says it applies from the next turn', asyncexpect(getUiState().info?.model).toBe('old')})-it('a picker-issued --reasoning rides after the canonical model switch as its own mutation', async () => {+it('a picker-issued --reasoning rides in the one canonical model selection, deferred or not', async () => {const { request, slash } = harness()slash('/model picked --provider custom --reasoning HIGH --tui-session')await flush()@@ -257,10 +257,8 @@ it('a picker-issued --reasoning rides after the canonical model switch as its ow.filter(([method]) => method === 'session.mutate').map(([, params]) => [params.operation, params.payload])- expect(sends).toEqual([- ['model', { model: 'picked', provider: 'custom' }],- ['reasoning', { effort: 'high' }]- ])+ // One request: a busy session defers it and commits model + level together at the boundary.+ expect(sends).toEqual([['model', { model: 'picked', provider: 'custom', reasoning: 'high' }]])expect(request.mock.calls.some(([method]) => method === 'config.set')).toBe(false)})@@ -295,9 +293,8 @@ it('a guarded switch re-asks with the effort riding the confirmed re-send', asynawait flush()const sends = request.mock.calls.filter(([method]) => method === 'session.mutate').map(([, params]) => params.payload)expect(sends).toEqual([- { model: 'pricey' },- { model: 'pricey', confirm: 'tok-1' },- { effort: 'max' }+ { model: 'pricey', reasoning: 'max' },+ { model: 'pricey', reasoning: 'max', confirm: 'tok-1' }])expect(getUiState().info?.model).toBe('pricey')})diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex 3aa772fded4..fb0252bf4b7 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -613,8 +613,9 @@ function applyDeferredPickOutcome(}if (update.status === 'confirmation_required' && typeof update.confirm === 'string') {- const pick = (update.payload ?? {}) as { model?: string; provider?: string }- const arg = `${pick.model ?? ''}${pick.provider ? ` --provider ${pick.provider}` : ''}`+ const pick = (update.payload ?? {}) as { model?: string; provider?: string; reasoning?: string }+ // The confirmed resend is the same selection: its level commits with the model.+ const arg = `${pick.model ?? ''}${pick.provider ? ` --provider ${pick.provider}` : ''}${pick.reasoning ? ` --reasoning ${pick.reasoning}` : ''}`patchOverlayState({confirm: {diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.tsindex d7886cc47cc..2b4d26c270d 100644--- a/ui-tui/src/app/slash/canonicalSessionControls.ts+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts@@ -39,40 +39,18 @@ function modelPayload(arg: string) {continue}- throw new Error(t('canonical.controls.unsupportedModelOption', flag))- }-- return payload-}--/** Split a picker-issued `--reasoning <level>` off a `/model` argument (#138856): the canonical- * model mutation has no effort field, so the level rides as the follow-up `reasoning` mutation the- * same value's `/reasoning` command issues. An unknown level is refused like any other flag the- * model mutation does not take (the backend writes the level into policy unvalidated). */-function splitModelEffort(arg: string) {- const parts = arg.trim().split(/\s+/)- const rest: string[] = []- let effort = ''-- while (parts.length) {- const part = parts.shift()!-- if (part !== '--reasoning') {- rest.push(part)+ // A picker-issued level (#138856) rides in the same selection: a busy session defers the pick+ // and commits model and level together. An unknown level is refused like any other flag.+ if (flag === '--reasoning' && CANONICAL_REASONING_EFFORTS.has(parts[0]?.toLowerCase() ?? '')) {+ payload.reasoning = parts.shift()!.toLowerCase()continue}- const level = parts.shift()-- if (!level || !CANONICAL_REASONING_EFFORTS.has(level.toLowerCase())) {- throw new Error(t('canonical.controls.unsupportedModelOption', part))- }-- effort = level.toLowerCase()+ throw new Error(t('canonical.controls.unsupportedModelOption', flag))}- return { arg: rest.join(' '), effort }+ return payload}export type CanonicalOperation = 'model' | 'branch' | 'compress' | 'delete' | 'rename' | 'rewind' | 'reasoning'@@ -207,13 +185,7 @@ const needsModelConfirmation = (result: CanonicalControlResult): result is Model* nothing. Ask with the same dialog the legacy `config.set` path used; only "switch anyway"* re-sends, once, with the owner's token. A confirmed send refused again (a turn or another* switch landed first) is reported, never re-asked in a loop. */-function askModelConfirmation(- refusal: ModelConfirmation,- arg: string,- ctx: SlashRunCtx,- confirmed: boolean,- effort = ''-) {+function askModelConfirmation(refusal: ModelConfirmation, arg: string, ctx: SlashRunCtx, confirmed: boolean) {if (confirmed) {throw new Error(`${refusal.confirm_message ?? ''}\n\n${t('slashCmd.session.model.confirmStale')}`.trim())}@@ -224,7 +196,7 @@ function askModelConfirmation(confirmLabel: t('slashCmd.session.model.switchAnyway'),danger: true,detail: refusal.confirm_message || t('slashCmd.session.model.expensiveDetail'),- onConfirm: () => void runCanonicalSessionControl('model', arg, ctx, refusal.confirm, effort),+ onConfirm: () => void runCanonicalSessionControl('model', arg, ctx, refusal.confirm),title: t('slashCmd.session.model.confirmTitle', refusal.target_model ?? arg.trim().split(/\s+/)[0] ?? '')}})@@ -292,19 +264,10 @@ function applyModelResult(result: CanonicalControlResult, ctx: SlashRunCtx) {}}))ctx.transcript.sys(t('session.main.modelSwitched', result.model))-}-/** The picker's effort step applies after the pick lands, as the same revision-fenced `reasoning`- * mutation `/reasoning <level>` issues; a failed level reports without unwinding the switch. */-async function applyModelEffort(gw: MutationGateway, ctx: SlashRunCtx, effort: string) {- if (!effort) {- return- }-- const mutation = await mutateCanonical(gw, ctx.sid!, 'reasoning', { effort }, ctx.stale)-- if (mutation?.result && !ctx.stale()) {- ctx.transcript.sys(t('slashCmd.session.reasoning.current', effort))+ if (typeof result.effort === 'string') {+ // The level committed in the same selection (a deferred result carries none yet).+ ctx.transcript.sys(t('slashCmd.session.reasoning.current', result.effort))}}@@ -351,21 +314,15 @@ export async function runCanonicalSessionControl(operation: 'model' | 'branch' | 'compress',arg: string,ctx: SlashRunCtx,- confirm?: string,- confirmEffort = ''+ confirm?: string) {const gw = ctx.gateway.gw- let effort = confirmEfforttry {if (!ctx.sid) {throw new Error(t('slashCmd.core.status.noActiveSession'))}- if (operation === 'model' && arg.includes('--reasoning')) {- ;({ arg, effort } = splitModelEffort(arg))- }-const mutation = await mutateCanonicalSession(gw, ctx.sid, operation, arg, ctx.stale, confirm)if (!mutation) {@@ -383,12 +340,11 @@ export async function runCanonicalSessionControl(}if (operation === 'model' && needsModelConfirmation(result)) {- askModelConfirmation(result, arg, ctx, Boolean(confirm), effort)+ askModelConfirmation(result, arg, ctx, Boolean(confirm))} else if (operation === 'branch') {await applyBranchResult(result, arg, ctx)} else if (operation === 'model') {applyModelResult(result, ctx)- await applyModelEffort(gw, ctx, effort)} else if (result.status === 'preview') {// `--preview` is a read-only report; nothing to re-hydrate.ctx.transcript.sys((result.lines as string[]).join('\n'))