The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): route saves keep order, keys, request settings and an explicit Normal speed
Teknium46de0fd0febb
diff --git a/apps/desktop/src/app/settings/delegation/model-route-dialog.tsx b/apps/desktop/src/app/settings/delegation/model-route-dialog.tsxindex 1e29437c6bd..9ce37a10eea 100644--- a/apps/desktop/src/app/settings/delegation/model-route-dialog.tsx+++ b/apps/desktop/src/app/settings/delegation/model-route-dialog.tsx@@ -87,9 +87,10 @@ export function ModelRouteDialog({ route, taken, scope, onClose, onSave }: Model}const tierOptions = [- { id: INHERIT, label: r.tierNormal },- { id: SERVICE_TIERS[0], label: r.tierFast },- { id: SERVICE_TIERS[1], label: r.tierUltrafast }+ { id: INHERIT, label: r.effortInherit },+ { id: SERVICE_TIERS[0], label: r.tierNormal },+ { id: SERVICE_TIERS[1], label: r.tierFast },+ { id: SERVICE_TIERS[2], label: r.tierUltrafast }]return (diff --git a/apps/desktop/src/app/settings/delegation/routes.test.ts b/apps/desktop/src/app/settings/delegation/routes.test.tsindex 5150723146c..9e09958c4f6 100644--- a/apps/desktop/src/app/settings/delegation/routes.test.ts+++ b/apps/desktop/src/app/settings/delegation/routes.test.ts@@ -35,7 +35,7 @@ describe('route editing keeps a default while routes exist', () => {})})- it('refuses incomplete or clashing drafts and keeps keys the dialog does not edit', () => {+ it('refuses incomplete or clashing drafts; an edit keeps keys the dialog does not edit and names its source', () => {const draft = { name: 'deep', description: '', provider: '', model: '', reasoning_effort: '', service_tier: '' }expect(validateRouteDraft(draft, ['deep'])).toEqual({@@ -54,10 +54,12 @@ describe('route editing keeps a default while routes exist', () => {service_tier: 'fast'})- const saved = routeFromDraft({ ...draft, name: 'local', description: 'Private', model: 'qwen' }, stored)+ // A rename sends the preview key back with the old name, so the server keeps the stored key.+ const saved = routeFromDraft({ ...draft, name: 'lan', description: 'Private', model: 'qwen' }, stored)expect(saved).toEqual({- name: 'local',+ name: 'lan',+ original_name: 'local',description: 'Private',model: 'qwen',base_url: 'http://127.0.0.1:8080/v1',diff --git a/apps/desktop/src/app/settings/delegation/routes.ts b/apps/desktop/src/app/settings/delegation/routes.tsindex b6c4bc8abe1..2bc44ce5c8c 100644--- a/apps/desktop/src/app/settings/delegation/routes.ts+++ b/apps/desktop/src/app/settings/delegation/routes.ts@@ -13,7 +13,8 @@ export interface ModelRouteDraft {export type RouteField = keyof ModelRouteDraftexport type RouteError = 'duplicate' | 'required' | 'spaces'-export const SERVICE_TIERS = ['fast', 'ultrafast'] as const+/** Saved as written: an explicit `normal` turns a provider's own Fast setting off; no tier leaves it alone. */+export const SERVICE_TIERS = ['normal', 'fast', 'ultrafast'] as constexport const emptyRouteDraft = (): ModelRouteDraft => ({name: '',@@ -64,9 +65,10 @@ export function validateRouteDraft(return errors}-/** The stored route for `draft`: edited fields replace, blank optional fields drop, unknown keys stay. */+/** The stored route for `draft`: edited fields replace, blank optional fields drop, unknown keys stay. An edited+ * route names the route it came from (`original_name`), so the server keeps its stored key through a rename. */export function routeFromDraft(draft: ModelRouteDraft, previous?: DelegationModelRoute): DelegationModelRoute {- const next: Record<string, unknown> = { ...previous }+ const next: Record<string, unknown> = { ...previous, ...(previous ? { original_name: previous.name } : {}) }for (const field of Object.keys(draft) as RouteField[]) {const value = draft[field].trim()diff --git a/apps/desktop/src/app/settings/delegation/routing-data.test.ts b/apps/desktop/src/app/settings/delegation/routing-data.test.tsnew file mode 100644index 00000000000..18024305d10--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/routing-data.test.ts@@ -0,0 +1,91 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'++import type { DelegationModelMap, DelegationRouting } from '@/api/delegation'+import type { HermesApiRequest } from '@/global'+import { queryClient } from '@/lib/query-client'++import { routingQueryKey, saveModelRoutes } from './routing-data'++const route = (name: string) => ({ name, description: `${name} route`, provider: 'p', model: `m-${name}` })+const map = (...names: string[]): DelegationModelMap => ({ options: names.map(route), default: names[0] ?? null })++let server: DelegationModelMap+let pending: { body: DelegationModelMap; settle: (fail?: boolean) => void }[]++beforeEach(() => {+ queryClient.clear()+ server = map('a')+ pending = []+ queryClient.setQueryData<DelegationRouting>(routingQueryKey(undefined), {+ configured: 'model_map',+ blocked_reason: null,+ backends: [],+ model_map: server,+ profile_routes: { profiles: [], default: null },+ profiles: []+ })+ // Each PUT waits until the test settles it, so the test picks the order answers come back in.+ window.hermesDesktop = {+ ...window.hermesDesktop,+ api: (request: HermesApiRequest) => {+ if (request.path === '/api/delegation/routing') {+ return Promise.resolve({ ...queryClient.getQueryData(routingQueryKey(undefined)), model_map: server })+ }++ const body = request.body as DelegationModelMap++ return new Promise<unknown>((resolve, reject) =>+ pending.push({+ body,+ settle: fail => {+ if (fail) {+ reject(new Error('500: disk full'))+ } else {+ server = body+ resolve({ ok: true, model_map: body })+ }+ }+ })+ )+ }+ } as typeof window.hermesDesktop+})++afterEach(() => queryClient.clear())++const tick = () => new Promise(resolve => setTimeout(resolve, 0))+const shown = () => queryClient.getQueryData<DelegationRouting>(routingQueryKey(undefined))?.model_map++describe('route saves for one owner', () => {+ it('reach the server in order, and an older answer never undoes a newer edit on screen', async () => {+ const first = saveModelRoutes(undefined, map('a', 'b'), 'failed')+ const second = saveModelRoutes(undefined, map('a', 'b', 'c'), 'failed')++ // The second PUT is not sent until the first is answered: the server applies them in the user's order.+ await tick()+ expect(pending.map(p => p.body)).toEqual([map('a', 'b')])++ pending[0].settle()+ await first+ expect(shown()).toEqual(map('a', 'b', 'c'))++ await tick()+ pending[1].settle()+ await second+ expect([shown(), server]).toEqual([map('a', 'b', 'c'), map('a', 'b', 'c')])+ })++ it('a failed save does not stop the edits queued behind it', async () => {+ const failing = saveModelRoutes(undefined, map('a', 'b'), 'failed')+ const later = saveModelRoutes(undefined, map('a', 'b', 'c'), 'failed')++ await tick()+ pending[0].settle(true)+ await tick()+ pending[1].settle()++ expect(await failing).toBe(false)+ expect(await later).toBe(true)+ expect(shown()).toEqual(map('a', 'b', 'c'))+ })+})diff --git a/apps/desktop/src/app/settings/delegation/routing-data.ts b/apps/desktop/src/app/settings/delegation/routing-data.tsindex 3082290ba4c..9d562915f80 100644--- a/apps/desktop/src/app/settings/delegation/routing-data.ts+++ b/apps/desktop/src/app/settings/delegation/routing-data.ts@@ -81,7 +81,14 @@ export function routesOwnSubagentModel(routing: DelegationRouting): boolean {return routing.configured !== 'default'}-/** Paint `patch` now, persist with `write`, adopt the server's answer; a failed write rolls back and says so. */+// Writes for one owner run one at a time, in the order the user made them: each body is computed from the page+// as it stood after the previous edit, so the server must apply them in that order too.+const saveChains = new Map<string, Promise<unknown>>()+const latestWrite = new Map<string, number>()++/** Paint `patch` now, persist with `write` after this owner's earlier writes, and adopt the server's answer only+ * when no newer edit is queued behind it (an older answer would undo that edit on screen). A failed write+ * re-reads the owner's routing instead of restoring a snapshot, which would also undo edits saved since. */async function writeThrough(scope: ProfileScope,patch: (current: DelegationRouting) => DelegationRouting,@@ -89,23 +96,31 @@ async function writeThrough(failMessage: string): Promise<boolean> {const key = routingQueryKey(scope)- const before = queryClient.getQueryData<DelegationRouting>(key)+ const id = JSON.stringify(key)- if (!before) {+ if (!queryClient.getQueryData<DelegationRouting>(key)) {return false}- queryClient.setQueryData(key, patch(before))+ queryClient.setQueryData<DelegationRouting>(key, current => current && patch(current))++ const generation = (latestWrite.get(id) ?? 0) + 1+ latestWrite.set(id, generation)+ const run = (saveChains.get(id) ?? Promise.resolve()).catch(() => undefined).then(write)+ saveChains.set(id, run)try {- const saved = await write()+ const saved = await run- queryClient.setQueryData<DelegationRouting>(key, current => (current ? { ...current, ...saved } : current))+ if (latestWrite.get(id) === generation) {+ queryClient.setQueryData<DelegationRouting>(key, current => (current ? { ...current, ...saved } : current))+ }return true} catch (err) {- queryClient.setQueryData(key, before)notifyError(err, failMessage)+ await saveChains.get(id)?.catch(() => undefined)+ await queryClient.invalidateQueries({ queryKey: key })return false}diff --git a/apps/desktop/src/i18n/ar_delegation_routing.ts b/apps/desktop/src/i18n/ar_delegation_routing.tsindex 762adb920d2..a36942ed950 100644--- a/apps/desktop/src/i18n/ar_delegation_routing.ts+++ b/apps/desktop/src/i18n/ar_delegation_routing.ts@@ -63,7 +63,7 @@ export const arDelegationRouting: DelegationRoutingTranslations = {effortLabel: 'مستوى الاستدلال',effortInherit: 'الافتراضي للوكيل الفرعي',tierLabel: 'السرعة',- tierNormal: 'عادية (افتراضي)',+ tierNormal: 'عادية',tierFast: 'سريعة',tierUltrafast: 'فائقة السرعة',tierHint: 'فقط في النماذج التي توفرها.',diff --git a/apps/desktop/src/i18n/de_delegation_routing.ts b/apps/desktop/src/i18n/de_delegation_routing.tsindex 97be847fc41..b3b85892230 100644--- a/apps/desktop/src/i18n/de_delegation_routing.ts+++ b/apps/desktop/src/i18n/de_delegation_routing.ts@@ -71,7 +71,7 @@ export const deDelegationRouting: DelegationRoutingTranslations = {effortLabel: 'Denkanstrengung',effortInherit: 'Subagent-Standard',tierLabel: 'Geschwindigkeit',- tierNormal: 'Normal (Standard)',+ tierNormal: 'Normal',tierFast: 'Schnell',tierUltrafast: 'Ultraschnell',tierHint: 'Nur bei Modellen, die das anbieten.',diff --git a/apps/desktop/src/i18n/en_delegation_routing.ts b/apps/desktop/src/i18n/en_delegation_routing.tsindex 6d390ccd8f2..ddaaf69af92 100644--- a/apps/desktop/src/i18n/en_delegation_routing.ts+++ b/apps/desktop/src/i18n/en_delegation_routing.ts@@ -63,7 +63,7 @@ export const enDelegationRouting: DelegationRoutingTranslations = {effortLabel: 'Reasoning effort',effortInherit: 'Subagent default',tierLabel: 'Speed',- tierNormal: 'Normal (default)',+ tierNormal: 'Normal',tierFast: 'Fast',tierUltrafast: 'Ultrafast',tierHint: 'Only on models that offer it.',diff --git a/apps/desktop/src/i18n/es_delegation_routing.ts b/apps/desktop/src/i18n/es_delegation_routing.tsindex ff6fc4d2c8c..fcb33405c7b 100644--- a/apps/desktop/src/i18n/es_delegation_routing.ts+++ b/apps/desktop/src/i18n/es_delegation_routing.ts@@ -74,7 +74,7 @@ export const esDelegationRouting: DelegationRoutingTranslations = {effortLabel: 'Esfuerzo de razonamiento',effortInherit: 'Predeterminado del subagente',tierLabel: 'Velocidad',- tierNormal: 'Normal (predeterminada)',+ tierNormal: 'Normal',tierFast: 'Rápida',tierUltrafast: 'Ultrarrápida',tierHint: 'Solo en modelos que la ofrecen.',diff --git a/apps/desktop/src/i18n/fr_delegation_routing.ts b/apps/desktop/src/i18n/fr_delegation_routing.tsindex 51b1003625e..f9ce001b26c 100644--- a/apps/desktop/src/i18n/fr_delegation_routing.ts+++ b/apps/desktop/src/i18n/fr_delegation_routing.ts@@ -73,7 +73,7 @@ export const frDelegationRouting: DelegationRoutingTranslations = {effortLabel: 'Intensité du raisonnement',effortInherit: 'Valeur par défaut des sous-agents',tierLabel: 'Vitesse',- tierNormal: 'Normale (par défaut)',+ tierNormal: 'Normale',tierFast: 'Rapide',tierUltrafast: 'Ultra-rapide',tierHint: 'Uniquement sur les modèles qui la proposent.',diff --git a/apps/desktop/src/i18n/ja_delegation_routing.ts b/apps/desktop/src/i18n/ja_delegation_routing.tsindex 570d8dee68d..0fa0b708f29 100644--- a/apps/desktop/src/i18n/ja_delegation_routing.ts+++ b/apps/desktop/src/i18n/ja_delegation_routing.ts@@ -70,7 +70,7 @@ export const jaDelegationRouting: DelegationRoutingTranslations = {effortLabel: '推論強度',effortInherit: 'サブエージェントの既定',tierLabel: '速度',- tierNormal: '標準(既定)',+ tierNormal: '標準',tierFast: '高速',tierUltrafast: '超高速',tierHint: '対応しているモデルのみ。',diff --git a/apps/desktop/src/i18n/ru_delegation_routing.ts b/apps/desktop/src/i18n/ru_delegation_routing.tsindex e6e4131f8ff..02c3378823b 100644--- a/apps/desktop/src/i18n/ru_delegation_routing.ts+++ b/apps/desktop/src/i18n/ru_delegation_routing.ts@@ -70,7 +70,7 @@ export const ruDelegationRouting: DelegationRoutingTranslations = {effortLabel: 'Глубина рассуждений',effortInherit: 'Как у субагента по умолчанию',tierLabel: 'Скорость',- tierNormal: 'Обычная (по умолчанию)',+ tierNormal: 'Обычная',tierFast: 'Быстрая',tierUltrafast: 'Сверхбыстрая',tierHint: 'Только для моделей, которые это поддерживают.',diff --git a/apps/desktop/src/i18n/zh-hant_delegation_routing.ts b/apps/desktop/src/i18n/zh-hant_delegation_routing.tsindex 98db74009aa..9641bb57f11 100644--- a/apps/desktop/src/i18n/zh-hant_delegation_routing.ts+++ b/apps/desktop/src/i18n/zh-hant_delegation_routing.ts@@ -62,7 +62,7 @@ export const zhHantDelegationRouting: DelegationRoutingTranslations = {effortLabel: '推理強度',effortInherit: '子代理預設值',tierLabel: '速度',- tierNormal: '一般(預設)',+ tierNormal: '一般',tierFast: '快速',tierUltrafast: '極速',tierHint: '僅適用於提供此選項的模型。',diff --git a/apps/desktop/src/i18n/zh_delegation_routing.ts b/apps/desktop/src/i18n/zh_delegation_routing.tsindex 0c3f1304816..76956df2b73 100644--- a/apps/desktop/src/i18n/zh_delegation_routing.ts+++ b/apps/desktop/src/i18n/zh_delegation_routing.ts@@ -62,7 +62,7 @@ export const zhDelegationRouting: DelegationRoutingTranslations = {effortLabel: '推理强度',effortInherit: '子智能体默认值',tierLabel: '速度',- tierNormal: '普通(默认)',+ tierNormal: '普通',tierFast: '快速',tierUltrafast: '极速',tierHint: '仅适用于提供该选项的模型。',diff --git a/hermes_cli/web_routers/delegation.py b/hermes_cli/web_routers/delegation.pyindex 9c682c89653..0a4cba09b22 100644--- a/hermes_cli/web_routers/delegation.py+++ b/hermes_cli/web_routers/delegation.py@@ -151,6 +151,7 @@ def _check_default(default: Optional[str], names: list[str], what: str) -> Optiodef _clean_model_option(index: int, entry: dict, stored: dict[str, dict]) -> dict[str, Any]:+ from agent.delegation_provider import ROUTE_KEYSfrom agent.fast_mode import STATIC_TIERS, parse_exact_service_tierfrom hermes_constants import VALID_REASONING_EFFORTS, parse_reasoning_effort@@ -182,10 +183,17 @@ def _clean_model_option(index: int, entry: dict, stored: dict[str, dict]) -> dicrow["service_tier"] = tierif isinstance(entry.get("fallback_providers"), list):row["fallback_providers"] = entry["fallback_providers"]+ # Route fields the editor never touches (request_overrides, label, profile) round-trip as stored.+ validated = {*_OPTION_TEXT_KEYS, "api_key", "reasoning_effort", "service_tier", "fallback_providers"}+ for field in sorted(ROUTE_KEYS - validated):+ if entry.get(field) not in (None, "", [], {}):+ row[field] = entry[field]key = entry.get("api_key")if is_redacted_credential_preview(key):- # The renderer only ever saw a preview: keep the stored key of the route it came from.- key = stored.get(_text(entry, "original_name") or row["name"], {}).get("api_key")+ # The renderer only ever saw a preview: keep the stored key of the route it came from (a rename names+ # it in original_name; once that save landed, the route is stored under its new name).+ source = stored.get(_text(entry, "original_name")) or stored.get(row["name"]) or {}+ key = source.get("api_key")if isinstance(key, str) and key.strip():row["api_key"] = key.strip()return rowdiff --git a/tests/hermes_cli/test_web_delegation_routing.py b/tests/hermes_cli/test_web_delegation_routing.pyindex 31e29bb7f14..9eb1ced0939 100644--- a/tests/hermes_cli/test_web_delegation_routing.py+++ b/tests/hermes_cli/test_web_delegation_routing.py@@ -48,7 +48,8 @@ def homes(tmp_path, monkeypatch):(work / "config.yaml").write_text(yaml.safe_dump({"plugins": {"enabled": ["routes"]},"delegation": {"backend": "model_map", "backends": {"model_map": {"options": [- {"name": "fast", "description": "Quick", "provider": "openrouter", "model": "m-fast", "api_key": SECRET},+ {"name": "fast", "description": "Quick", "provider": "openrouter", "model": "m-fast", "api_key": SECRET,+ "request_overrides": {"extra_body": {"seed": 7}}},{"name": "deep", "description": "Careful", "provider": "anthropic", "model": "m-deep"},], "default": "deep"}}},}), encoding="utf-8")@@ -144,8 +145,10 @@ def test_invalid_model_routes_are_refused_before_anything_is_written(client, homdef test_saving_model_routes_replaces_the_block_and_keeps_the_stored_key(client, homes):root, work = homesshown = client.get("/api/delegation/routing?profile=work").json()["model_map"]["options"][0]- # Edit "fast" as the renderer would (preview key sent back), delete "deep", add "local".- body = {"options": [{**shown, "model": "m-faster", "reasoning_effort": "low"},+ # Rename and edit "fast" as the renderer would (preview key and untouched fields sent back, the old name in+ # original_name), delete "deep", add "local".+ body = {"options": [{**shown, "name": "speedy", "original_name": "fast", "model": "m-faster",+ "reasoning_effort": "low"},{"name": "local", "description": "Private", "base_url": "http://127.0.0.1:8080/v1","model": "qwen", "service_tier": "fast"}],"default": "local"}@@ -155,9 +158,10 @@ def test_saving_model_routes_replaces_the_block_and_keeps_the_stored_key(client,block = _delegation(work)["backends"]["model_map"]assert block["default"] == "local"- assert [o["name"] for o in block["options"]] == ["fast", "local"]- assert block["options"][0] == {"name": "fast", "description": "Quick", "provider": "openrouter",- "model": "m-faster", "reasoning_effort": "low", "api_key": SECRET}+ assert [o["name"] for o in block["options"]] == ["speedy", "local"]+ assert block["options"][0] == {"name": "speedy", "description": "Quick", "provider": "openrouter",+ "model": "m-faster", "reasoning_effort": "low", "api_key": SECRET,+ "request_overrides": {"extra_body": {"seed": 7}}}assert "backends" not in _delegation(root)