The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): defer a reasoning pick made while a reply streams
unsupportedpastels661853e86187
diff --git a/apps/desktop/src/app/shell/use-model-menu-controller.test.tsx b/apps/desktop/src/app/shell/use-model-menu-controller.test.tsxnew file mode 100644index 00000000000..5470412fa9e--- /dev/null+++ b/apps/desktop/src/app/shell/use-model-menu-controller.test.tsx@@ -0,0 +1,40 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { renderHook, waitFor } from '@testing-library/react'+import type { ReactNode } from 'react'+import { expect, it, vi } from 'vitest'++import { $notifications } from '@/store/notifications'+import { $activeSessionId, $currentModel, $currentProvider } from '@/store/session'++import { useModelMenuController } from './use-model-menu-controller'++it('a level picked while a reply streams applies from the next message instead of failing (MP-24)', async () => {+ $activeSessionId.set('runtime-1')+ $currentModel.set('gemini-3.1-pro')+ $currentProvider.set('google')+ $notifications.set([])++ const requestGateway = vi.fn(async (method: string) =>+ method === 'config.set' ? { ok: true, operation: 'reasoning', status: 'deferred', value: 'high' } : { providers: [] }+ )++ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })++ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ )++ const { result } = renderHook(+ () => useModelMenuController({ onSelectModel: vi.fn(), requestGateway: requestGateway as never }),+ { wrapper }+ )++ result.current.controller.setOptions({ effort: 'high' }, { isActive: true, model: 'gemini-3.1-pro', provider: 'google' })++ await waitFor(() =>+ expect($notifications.get()).toContainEqual(+ expect.objectContaining({ kind: 'info', message: 'high applies from your next message' })+ )+ )+ expect($notifications.get().some(n => n.kind === 'error')).toBe(false)+})diff --git a/apps/desktop/src/app/shell/use-model-menu-controller.ts b/apps/desktop/src/app/shell/use-model-menu-controller.tsindex f0657aa0594..371802fec0e 100644--- a/apps/desktop/src/app/shell/use-model-menu-controller.ts+++ b/apps/desktop/src/app/shell/use-model-menu-controller.ts@@ -18,6 +18,7 @@ import {modelPresetServiceTier,setModelPreset} from '@/store/model-presets'+import { notify } from '@/store/notifications'import { $defaultReasoningEffort, markComposerSelectionManual } from '@/store/session'import type { ModelMenuController } from './model-catalog-menu'@@ -124,7 +125,20 @@ export function useModelMenuController({failMessage,scope: hostScope,primary: touchesPrimary,- request: requestGateway,+ // A level picked while a reply streams is the owner's for the next turn, like a model pick.+ request: async <T>(method: string, params?: Record<string, unknown>) => {+ const result = await requestGateway<T>(method, params)++ if ((result as { status?: unknown } | undefined)?.status === 'deferred') {+ notify({+ id: `model-pick-deferred-${activeSessionId}`,+ kind: 'info',+ message: t.shell.modelMenu.pickDeferred(String(params?.value ?? ''))+ })+ }++ return result+ },sessionId: activeSessionId,isCurrent: dimension => {const stamp = stamps.get(dimension)!diff --git a/gateway/session_deferred_pick.py b/gateway/session_deferred_pick.pyindex 9b0e0488fae..f538e3e2981 100644--- a/gateway/session_deferred_pick.py+++ b/gateway/session_deferred_pick.py@@ -1,8 +1,10 @@-"""A model pick on a session with a running turn lands for the next turn (RT-12).+"""A model or reasoning pick on a session with a running turn lands for the next turn (RT-12, MP-24).The pick is authorized and validated when it arrives, kept durably in ``state_meta`` (latest pickwins, survives an owner restart), and committed through ``session.mutate``'s own writer by thedrain at the next claim boundary, when nothing is executing. The running turn keeps its route.+A level rides in the same slot beside the model pick and commits first, as ``apply_pending_reasoning``+runs before a model pick: a level picked with a later model pick wins, a later level replaces it."""import jsonimport logging@@ -14,19 +16,21 @@ logger = logging.getLogger(__name__)def defer_pick(authority, actor, ref, params):- """Record *params* (an authorized ``model`` mutation refused only because a turn is running).+ """Record *params* (an authorized ``model`` or ``reasoning`` mutation refused only because a turn+ is running).Blocking SQLite: callers run it off the event loop. Acceptance writes the request's durablemutation receipt in the same transaction, so an exact retry returns this result instead ofoverwriting a newer pick, and the stored pick carries a stable application id."""from hermes_state_mutations import validate_actionfrom hermes_state_runtime import _epoch, _json, mutation_receipt_key, replay_mutation_receipt- validate_action('model', params['payload'])- key, digest = mutation_receipt_key(actor.subject, ref.session_id, params['request_id'], operation='model',+ operation = params.get('operation', 'model')+ validate_action(operation, params['payload'])+ key, digest = mutation_receipt_key(actor.subject, ref.session_id, params['request_id'], operation=operation,payload=params['payload'], expected_revision=params.get('expected_revision'),expected_generation=params.get('expected_generation'))- value = _json({'principal_id': actor.subject, 'request_id': params['request_id'], 'payload': params['payload'],- 'application_id': 'deferred-pick:' + params['request_id']})+ pick = {'principal_id': actor.subject, 'request_id': params['request_id'], 'payload': params['payload'],+ 'application_id': 'deferred-pick:' + params['request_id']}def write(conn):_epoch(conn, authority.epoch)@@ -37,10 +41,18 @@ def defer_pick(authority, actor, ref, params):(ref.session_id,)).fetchone()if row is None:raise RuntimeStoreError('not_found')- result = {'session_id': ref.session_id, 'operation': 'model', 'status': 'deferred',- 'model': params['payload']['model'], 'revision': row[0], 'execution_generation': row[1]}+ stored = conn.execute('SELECT value FROM state_meta WHERE key=?', (_PREFIX + ref.session_id,)).fetchone()+ current = json.loads(stored[0]) if stored else {}+ if operation == 'reasoning':+ current.get('payload', {}).pop('reasoning', None) # this level is newer than the one picked with the model+ value, picked = {**current, 'reasoning': pick}, {'effort': params['payload']['effort']}+ else:+ value = {**pick, **({'reasoning': current['reasoning']} if 'reasoning' in current else {})}+ picked = {'model': params['payload']['model']}+ result = {'session_id': ref.session_id, 'operation': operation, 'status': 'deferred', **picked,+ 'revision': row[0], 'execution_generation': row[1]}conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',- (_PREFIX + ref.session_id, value))+ (_PREFIX + ref.session_id, _json(value)))conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, _json({'digest': digest, 'result': result})))return resultreturn authority.db._execute_write(write)@@ -60,12 +72,61 @@ async def reask_on_attach(authority, ref, live):authority._schedule(ref)+async def _commit(authority, ref, entry, operation):+ """Commit the deferred *entry* as an *operation* mutation. Returns None while a worker still holds+ the transcript (the pick waits for the next boundary), else the mutation's result."""+ import asyncio+ from gateway.session_mutations import write_mutation+ from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS+ from hermes_state_mutation_retirement import has_mutation_receipt+ if await asyncio.to_thread(has_mutation_receipt, authority.db, entry['principal_id'], ref.session_id,+ entry['application_id']):+ return {'status': 'replayed'} # committed before a restart, not yet removed: never apply it twice+ row = await asyncio.to_thread(authority.db.get_session, ref.session_id)+ params = {'session_id': ref.session_id, 'request_id': entry['application_id'],+ 'expected_revision': row['runtime_revision'], 'expected_generation': row['runtime_generation'],+ 'operation': operation, 'payload': entry['payload']}+ try:+ return await write_mutation(authority, ref, params, None, principal_id=entry['principal_id'])+ except MUTATION_GUARD_REFUSALS:+ return None+ except RuntimeStoreError as exc:+ if exc.reason == 'session_busy':+ return None+ return {'session_id': ref.session_id, 'operation': operation, 'status': 'refused', 'reason': exc.reason}+ except Exception:+ # Resolving the pick failed (provider auth, catalog, resolver crash). This runs before the+ # claim, so letting it escape would kill or wedge the drain on the same pick forever.+ logger.exception('Deferred %s pick on %s failed to resolve', operation, ref.session_id)+ return {'session_id': ref.session_id, 'operation': operation, 'status': 'refused',+ 'reason': operation + '_resolution_failed'}+++async def _commit_level(authority, ref, key, raw, pick):+ """Commit the level deferred in *pick* (stored as *raw*) and drop it from the slot. Returns the+ remaining slot value, or None when nothing is left or a worker still holds the transcript."""+ import asyncio+ from hermes_state_runtime import _json+ result = await _commit(authority, ref, pick.pop('reasoning'), 'reasoning')+ if result is None:+ return None+ if result.get('status') == 'refused':+ logger.warning('Deferred reasoning pick on %s not applied: %s', ref.session_id, result['reason'])+ rest = _json(pick) if 'application_id' in pick else None++ def settle(conn):+ if rest is None:+ conn.execute('DELETE FROM state_meta WHERE key=? AND value=?', (key, raw))+ else:+ conn.execute('UPDATE state_meta SET value=? WHERE key=? AND value=?', (rest, key, raw))+ await asyncio.to_thread(authority.db._execute_write, settle)+ return rest++async def apply_deferred_pick(authority, ref, live):"""Commit a deferred pick. The drain calls this under the claim gate and mutation lock, beforeclaiming, so no turn is running. A pick that no longer resolves is dropped and announced."""import asyncio- from gateway.session_mutations import write_mutation- from hermes_state_mutation_retirement import has_mutation_receiptkey = _PREFIX + ref.session_iddef read():@@ -74,7 +135,12 @@ async def apply_deferred_pick(authority, ref, live):stored = await asyncio.to_thread(read)if stored is None:return- pick = json.loads(stored[0])+ raw = stored[0]+ pick = json.loads(raw)+ if 'reasoning' in pick:+ raw = await _commit_level(authority, ref, key, raw, pick)+ if raw is None:+ returnif 'awaiting_confirm' in pick:if not live.reask_pick:return # asked; the user's confirmed (or a newer) selection supersedes it@@ -82,32 +148,9 @@ async def apply_deferred_pick(authority, ref, live):# that still applies mints a fresh token (the stored one is never replayed as consent).pick = {k: v for k, v in pick.items() if k != 'awaiting_confirm'}live.reask_pick = False- application_id = pick['application_id']- if await asyncio.to_thread(has_mutation_receipt, authority.db, pick['principal_id'], ref.session_id,- application_id):- # Committed before a restart, not yet removed: never apply it twice.- await asyncio.to_thread(authority.db._execute_write, lambda conn: conn.execute(- 'DELETE FROM state_meta WHERE key=? AND value=?', (key, stored[0])))+ result = await _commit(authority, ref, pick, 'model')+ if result is None:return- row = await asyncio.to_thread(authority.db.get_session, ref.session_id)- params = {'session_id': ref.session_id, 'request_id': application_id,- 'expected_revision': row['runtime_revision'], 'expected_generation': row['runtime_generation'],- 'operation': 'model', 'payload': pick['payload']}- from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS- try:- result = await write_mutation(authority, ref, params, None, principal_id=pick['principal_id'])- except MUTATION_GUARD_REFUSALS:- return # a worker still holds the transcript: the pick waits for the next boundary- except RuntimeStoreError as exc:- if exc.reason == 'session_busy':- return- result = {'session_id': ref.session_id, 'operation': 'model', 'status': 'refused', 'reason': exc.reason}- except Exception:- # Resolving the pick failed (provider auth, catalog, resolver crash). This runs before the- # claim, so letting it escape would kill or wedge the drain on the same pick forever.- logger.exception('Deferred model pick on %s failed to resolve', ref.session_id)- result = {'session_id': ref.session_id, 'operation': 'model', 'status': 'refused',- 'reason': 'model_resolution_failed'}if result.get('status') == 'confirmation_required':# A guarded target (cost / data policy / large context): nothing was written. The pick stays# pending, marked as asked, and the owner's confirmation exchange goes to every viewer; the@@ -115,7 +158,7 @@ async def apply_deferred_pick(authority, ref, live):from hermes_state_runtime import _jsonawait asyncio.to_thread(authority.db._execute_write, lambda conn: conn.execute('UPDATE state_meta SET value=? WHERE key=? AND value=?',- (_json({**pick, 'awaiting_confirm': result['confirm']}), key, stored[0])))+ (_json({**pick, 'awaiting_confirm': result['confirm']}), key, raw)))current = await asyncio.to_thread(authority.db.get_session, ref.session_id) or {}provider = json.loads(current.get('model_config') or '{}').get('provider')# The committed selection rides along, so a viewer that declines paints it back.@@ -124,7 +167,7 @@ async def apply_deferred_pick(authority, ref, live):**({'committed_provider': provider} if provider else {})}, event_type='session.updated')returnawait asyncio.to_thread(authority.db._execute_write, lambda conn: conn.execute(- 'DELETE FROM state_meta WHERE key=? AND value=?', (key, stored[0])))+ 'DELETE FROM state_meta WHERE key=? AND value=?', (key, raw)))if result.get('status') == 'refused':logger.warning('Deferred model pick on %s not applied: %s', ref.session_id, result.get('reason'))# Named for the viewers that showed "applies from your next message": the target that wasdiff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex 3b44ea48d30..50fa25bdb0c 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -129,7 +129,8 @@ async def _owned_mutation(authority, actor, ref, params):result = await _mutate_session(authority, actor, ref, params, owner=owner)except (RuntimeStoreError, *MUTATION_GUARD_REFUSALS) as exc:# A pick on a running session is for the next turn (the running turn keeps its route).- if params.get('operation') != 'model' or getattr(exc, 'reason', 'session_busy') != 'session_busy':+ if (params.get('operation') not in {'model', 'reasoning'}+ or getattr(exc, 'reason', 'session_busy') != 'session_busy'):raisefrom gateway.session_deferred_pick import defer_pick# Its own BEGIN IMMEDIATE: off the loop, like the receipt commit.diff --git a/tests/gateway/test_session_deferred_reasoning.py b/tests/gateway/test_session_deferred_reasoning.pynew file mode 100644index 00000000000..633ad97b286--- /dev/null+++ b/tests/gateway/test_session_deferred_reasoning.py@@ -0,0 +1,51 @@+"""A reasoning level picked while a reply streams lands for the next turn, like a model pick (MP-24)."""+import asyncio+import threading++import pytest++from tests.gateway.test_session_mutation_model_busy import _owner, _run_turn, _running_model+from tests.waiting import async_wait_until++[email protected]('picks, expected', [+ ([('reasoning', {'effort': 'low'}), ('model', {'model': 'picked'}), ('reasoning', {'effort': 'high'})],+ ('picked', 'high')),+ ([('model', {'model': 'picked', 'reasoning': 'low'}), ('reasoning', {'effort': 'high'})], ('picked', 'high')),+ ([('reasoning', {'effort': 'high'}), ('model', {'model': 'picked', 'reasoning': 'low'})], ('picked', 'low')),+], ids=['level-model-level', 'model-with-level-then-level', 'level-then-model-with-level'])+async def test_levels_picked_during_a_running_turn_apply_to_the_next_turn_in_pick_order(+ tmp_path, monkeypatch, picks, expected):+ 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 or {}).get('effort')+ seen.append((event.text, _running_model(state['authority'], state['ref']), 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')+ for n, (operation, payload) in enumerate(picks):+ snap = db.get_session(ref.session_id)+ reply = await owner.dispatch({'id': n, 'method': 'session.mutate', 'params': {+ 'session_id': ref.session_id, 'request_id': f'pick-{n}', 'expected_revision': snap['runtime_revision'],+ 'expected_generation': snap['runtime_generation'], 'operation': operation, 'payload': payload}})+ assert reply.get('result', {}).get('status') == 'deferred', reply+ release.set()+ await _run_turn(authority, owner, db, ref, 'NEXT')+ assert seen[-1] == ('NEXT', *expected), seen+ finally:+ release.set()+ await owner.close()+ store.close_all_db_handles()