The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a live-session pick shows when it lands or why it was refused
Tekniumae0ccd9cfe0c
diff --git a/apps/desktop/src/api/canonical-live-pick.test.ts b/apps/desktop/src/api/canonical-live-pick.test.tsnew file mode 100644index 00000000000..78f5083ce51--- /dev/null+++ b/apps/desktop/src/api/canonical-live-pick.test.ts@@ -0,0 +1,57 @@+import { JsonRpcGatewayClient, JsonRpcGatewayError } from '@hermes/shared'+import { afterEach, expect, test, vi } from 'vitest'++import { HermesGateway } from './client'++afterEach(() => { vi.restoreAllMocks() })++async function attached(mutate: (params: Record<string, unknown>) => unknown) {+ vi.spyOn(JsonRpcGatewayClient.prototype, 'connect').mockResolvedValue()+ const calls: Array<{ method: string; params: Record<string, unknown> }> = []+ vi.spyOn(JsonRpcGatewayClient.prototype, 'request').mockImplementation(async (method, params) => {+ calls.push({ method, params: params as Record<string, unknown> })++ if (method === 'session.mutate') { return mutate(params as Record<string, unknown>) as never }++ return { session_id: 's', revision: 4, execution_generation: 2, messages: [], info: {} } as never+ })+ const client = new HermesGateway()+ await client.connect('ws://localhost/api/ws?native_dial=fixture&ticket=fixture')+ await client.request('session.resume', { session_id: 's' })+ calls.length = 0++ return { calls, client }+}++const pick = { session_id: 's', key: 'model', value: 'picked --provider custom' }++test('a composer pick is the session-scoped mutate; a busy session answers deferred for the next turn', async () => {+ const { calls, client } = await attached(params => ({+ session_id: 's', operation: 'model', status: 'deferred', model: (params.payload as { model: string }).model, revision: 4+ }))++ await expect(client.request('config.set', pick)).resolves.toMatchObject({ deferred: true, ok: true })+ expect(calls).toEqual([{ method: 'session.mutate', params: expect.objectContaining({+ operation: 'model', payload: { model: 'picked', provider: 'custom' }, expected_revision: 4, expected_generation: 2 }) }])+})++test('a fence refusal naming fresh fences is retried once at them, never looped', async () => {+ const stale = () => { throw new JsonRpcGatewayError('stale_generation', { code: 4001, data: { reason: 'stale_generation', revision: 6, execution_generation: 3 } }) }+ let attempts = 0++ const { calls, client } = await attached(params => {+ attempts += 1++ return attempts === 1 ? stale() : { session_id: 's', operation: 'model', model: 'picked', revision: (params.expected_revision as number) + 1 }+ })++ await expect(client.request('config.set', pick)).resolves.toMatchObject({ model: 'picked' })+ expect(calls.map(call => [call.params.expected_revision, call.params.expected_generation])).toEqual([[4, 2], [6, 3]])+ expect(calls[1].params.request_id).not.toBe(calls[0].params.request_id)++ attempts = 0+ calls.length = 0+ const { calls: looping, client: refused } = await attached(stale)+ await expect(refused.request('config.set', pick)).rejects.toThrow('stale_generation')+ expect(looping).toHaveLength(2)+})diff --git a/apps/desktop/src/api/canonical-protocol.ts b/apps/desktop/src/api/canonical-protocol.tsindex b7380778868..13410e9bb52 100644--- a/apps/desktop/src/api/canonical-protocol.ts+++ b/apps/desktop/src/api/canonical-protocol.ts@@ -226,6 +226,22 @@ export class CanonicalDesktopProtocol {// A confirmed fence refusal did not mutate. Ambiguous transport failures keep// the original revision/id so a retry cannot overwrite another user's edit.for (const [key, mutation] of this.mutations) { if (mutation.request_id === params.request_id) { this.mutations.delete(key) } }+ // The owner names its current fences on the refusal: adopt them so the next attempt presents them.+ const data = (error as { data?: { revision?: unknown; execution_generation?: unknown } })?.data+ const owner = canonicalSessionKey(params.session_id, params.profile)++ if (typeof data?.revision === 'number') { this.revisions.set(owner, data.revision) }++ if (typeof data?.execution_generation === 'number') { this.generations.set(owner, data.execution_generation) }+ }++ // A fence refusal of a value pick (model / reasoning) that named fresh fences is retried once at them:+ // re-applying the same value is harmless, unlike a CAS edit of shared metadata.+ retryableFence(params: Record<string, unknown>, error: unknown): boolean {+ const data = (error as { data?: { reason?: unknown; revision?: unknown } })?.data++ return ['model', 'reasoning'].includes(params.operation as string) && typeof data?.revision === 'number'+ && (data.reason === 'revision_conflict' || data.reason === 'stale_generation')}// Wire method for a prepared request: composer metadata, branch and the@@ -578,6 +594,9 @@ export class CanonicalDesktopProtocol {if (method === 'slash.exec') { return { ...value, type: 'exec', output: mutationSummary(params.operation as string, value) } }+ // A pick on a running session is recorded for the next turn (the legacy `deferred` answer).+ if (params.operation === 'model' && value.status === 'deferred') { return { ...value, ok: true, deferred: true } }+// The legacy config.set answer every reasoning caller reads (`result.value`).return params.operation === 'reasoning' ? { ...value, ok: true, value: value.effort } : { ...value, ok: true }}diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.tsindex 2fb2d35bc42..488b2c69760 100644--- a/apps/desktop/src/api/client.ts+++ b/apps/desktop/src/api/client.ts@@ -407,7 +407,19 @@ export class HermesGateway extends JsonRpcGatewayClient {const wireMethod = this.protocol.wire(method, prepared)try {- const result = await super.request<T>(wireMethod, prepared, remainingRequestBudget(deadline, signal), signal)+ let result: T++ try {+ result = await super.request<T>(wireMethod, prepared, remainingRequestBudget(deadline, signal), signal)+ } catch (error) {+ if (!this.protocol.retryableFence(prepared, error)) { throw error }+ // The refusal carried the owner's current fences: one retry at them, never a loop.+ this.protocol.failure(prepared, error)+ this.requireConnectionGeneration(generation)+ prepared = this.protocol.prepare(method, params)+ result = await super.request<T>(wireMethod, prepared, remainingRequestBudget(deadline, signal), signal)+ }+this.requireConnectionGeneration(generation)if (['session.resume', 'session.create', 'session.activate'].includes(method)) {diff --git a/apps/desktop/src/app/session/hooks/use-model-controls.test.tsx b/apps/desktop/src/app/session/hooks/use-model-controls.test.tsxindex 47b048fa8ad..3bfab1ecd3f 100644--- a/apps/desktop/src/app/session/hooks/use-model-controls.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-model-controls.test.tsx@@ -52,7 +52,8 @@ vi.mock('@/i18n', async importOriginal => ({t: {desktop: {modelSwitchFailed: 'Model switch failed'- }+ },+ shell: { modelMenu: { pickDeferred: (model: string) => `${model} applies from your next message` } }}})}))@@ -307,6 +308,22 @@ describe('useModelControls', () => {expect($currentProvider.get()).toBe('xai')expect(invalidate).not.toHaveBeenCalled()expect(notifyError).not.toHaveBeenCalled()+ expect(notify).toHaveBeenCalledWith(expect.objectContaining({ message: 'grok-4.5 applies from your next message' }))+ })++ it('names the owner refusal of a pick in the failure toast', async () => {+ $activeSessionId.set('session-1')+ setCurrentModel('old')+ setCurrentProvider('xai')+ const refusal = Object.assign(new Error('model_resolution_failed'), { data: { reason: 'model_resolution_failed' } })+ const requestGateway = vi.fn(async () => { throw refusal })+ let controls!: Controls++ render(<Harness onReady={value => (controls = value)} requestGateway={requestGateway} />)++ await expect(controls.selectModel({ model: 'nope', provider: 'xai' })).resolves.toBe(false)+ expect(notifyError).toHaveBeenCalledWith(refusal, 'Model switch failed')+ expect($currentModel.get()).toBe('old')})it('still refetches after a switch that applied immediately', async () => {diff --git a/apps/desktop/src/app/session/hooks/use-model-controls.ts b/apps/desktop/src/app/session/hooks/use-model-controls.tsindex c2143b410ab..3503753b2ee 100644--- a/apps/desktop/src/app/session/hooks/use-model-controls.ts+++ b/apps/desktop/src/app/session/hooks/use-model-controls.ts@@ -13,7 +13,7 @@ import {modelOptionsQueryKey,requestModelOptions} from '@/lib/model-options'-import { notifyError } from '@/store/notifications'+import { notify, notifyError } from '@/store/notifications'import { $activeGatewayProfile } from '@/store/profile'import {$activeSessionId,@@ -374,6 +374,12 @@ export function useModelControls({void queryClient.invalidateQueries({queryKey: modelOptionsQueryKey(liveGatewayProfile, liveSessionId, cacheOwnerConnectionId)})+ } else {+ notify({+ id: `model-pick-deferred-${liveSessionId}`,+ kind: 'info',+ message: t.shell.modelMenu.pickDeferred(selection.model)+ })}}@@ -475,7 +481,7 @@ export function useModelControls({return false}},- [cacheOwnerConnectionId, cacheProfile, copy.modelSwitchFailed, queryClient, requestGateway, updateModelOptionsCache]+ [cacheOwnerConnectionId, cacheProfile, copy, queryClient, requestGateway, t, updateModelOptionsCache])return { applySavedMainModel, followDefaultModel, refreshCurrentModel, selectModel }diff --git a/apps/desktop/src/i18n/ar_chrome.ts b/apps/desktop/src/i18n/ar_chrome.tsindex 64f4514aa25..0e28a140ee6 100644--- a/apps/desktop/src/i18n/ar_chrome.ts+++ b/apps/desktop/src/i18n/ar_chrome.ts@@ -349,6 +349,7 @@ export const arChrome = {paneControls: 'تحكم اللوحات',appControls: 'تحكم التطبيق',modelMenu: {+ pickDeferred: (model: string) => `سيُطبَّق ${model} بدءًا من رسالتك التالية`,search: 'البحث عن نموذج...',noModels: 'لا توجد نماذج',editModels: 'تحرير النماذج',diff --git a/apps/desktop/src/i18n/de_model_menu.ts b/apps/desktop/src/i18n/de_model_menu.tsindex 356a5368471..05b2d642d8f 100644--- a/apps/desktop/src/i18n/de_model_menu.ts+++ b/apps/desktop/src/i18n/de_model_menu.ts@@ -1,4 +1,5 @@export const deModelMenu = {+ pickDeferred: (model: string) => `${model} gilt ab deiner nächsten Nachricht`,search: 'Modelle durchsuchen',noModels: 'Keine Modelle gefunden',editModels: 'Modelle bearbeiten…',diff --git a/apps/desktop/src/i18n/en_model_menu.ts b/apps/desktop/src/i18n/en_model_menu.tsindex ccf38e44ca3..ef4fb28a250 100644--- a/apps/desktop/src/i18n/en_model_menu.ts+++ b/apps/desktop/src/i18n/en_model_menu.ts@@ -1,6 +1,7 @@import type { Translations } from './types'export const enModelMenu: Translations['shell']['modelMenu'] = {+ pickDeferred: (model: string) => `${model} applies from your next message`,search: 'Search models',noModels: 'No models found',editModels: 'Edit models…',diff --git a/apps/desktop/src/i18n/es_model_menu.ts b/apps/desktop/src/i18n/es_model_menu.tsindex 7acb7d5eaed..718544e0e36 100644--- a/apps/desktop/src/i18n/es_model_menu.ts+++ b/apps/desktop/src/i18n/es_model_menu.ts@@ -1,4 +1,5 @@export const esModelMenu = {+ pickDeferred: (model: string) => `${model} se aplica desde tu próximo mensaje`,search: 'Buscar modelos',noModels: 'No se encontraron modelos',editModels: 'Editar modelos…',diff --git a/apps/desktop/src/i18n/fr_model_menu.ts b/apps/desktop/src/i18n/fr_model_menu.tsindex c4869309815..f220c10a3e4 100644--- a/apps/desktop/src/i18n/fr_model_menu.ts+++ b/apps/desktop/src/i18n/fr_model_menu.ts@@ -1,4 +1,5 @@export const frModelMenu = {+ pickDeferred: (model: string) => `${model} s’applique à partir de votre prochain message`,search: 'Rechercher des modèles',noModels: 'Aucun modèle trouvé',editModels: 'Modifier les modèles…',diff --git a/apps/desktop/src/i18n/ja_model_menu.ts b/apps/desktop/src/i18n/ja_model_menu.tsindex e967ff35425..f9f0cdf0690 100644--- a/apps/desktop/src/i18n/ja_model_menu.ts+++ b/apps/desktop/src/i18n/ja_model_menu.ts@@ -1,4 +1,5 @@export const jaModelMenu = {+ pickDeferred: (model: string) => `${model} は次のメッセージから適用されます`,search: 'モデルを検索',noModels: 'モデルが見つかりません',editModels: 'モデルを編集…',diff --git a/apps/desktop/src/i18n/ru_model_menu.ts b/apps/desktop/src/i18n/ru_model_menu.tsindex 7589ee4c2bf..21f1e0b691a 100644--- a/apps/desktop/src/i18n/ru_model_menu.ts+++ b/apps/desktop/src/i18n/ru_model_menu.ts@@ -1,4 +1,5 @@export const ruModelMenu = {+ pickDeferred: (model: string) => `${model} применится со следующего сообщения`,search: 'Поиск моделей',noModels: 'Модели не найдены',editModels: 'Изменить модели…',diff --git a/apps/desktop/src/i18n/types_model_menu.ts b/apps/desktop/src/i18n/types_model_menu.tsindex 5caebbc1196..5e4fe5df741 100644--- a/apps/desktop/src/i18n/types_model_menu.ts+++ b/apps/desktop/src/i18n/types_model_menu.ts@@ -1,4 +1,6 @@export interface ModelMenuTranslations {+ /** A pick made while a turn runs: the owner records it for the next turn. */+ pickDeferred: (model: string) => stringsearch: stringnoModels: stringeditModels: stringdiff --git a/apps/desktop/src/i18n/zh-hant_chrome.ts b/apps/desktop/src/i18n/zh-hant_chrome.tsindex a10ae545554..682771d20b4 100644--- a/apps/desktop/src/i18n/zh-hant_chrome.ts+++ b/apps/desktop/src/i18n/zh-hant_chrome.ts@@ -249,6 +249,7 @@ export const zhHantChrome = {paneControls: '窗格控制項',appControls: '應用程式控制項',modelMenu: {+ pickDeferred: (model: string) => `${model} 將從你的下一則訊息開始生效`,search: '搜尋模型',noModels: '找不到模型',editModels: '編輯模型…',diff --git a/apps/desktop/src/i18n/zh_model_menu.ts b/apps/desktop/src/i18n/zh_model_menu.tsindex c69a51ffeee..1b9b2b59d9c 100644--- a/apps/desktop/src/i18n/zh_model_menu.ts+++ b/apps/desktop/src/i18n/zh_model_menu.ts@@ -1,4 +1,5 @@export const zhModelMenu = {+ pickDeferred: (model: string) => `${model} 将从你的下一条消息开始生效`,search: '搜索模型',noModels: '未找到模型',editModels: '编辑模型…',