The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): Delegation routing settings — mode picker, model routes, profile routes
Tekniumfdaffcb9fb04
diff --git a/apps/desktop/src/api/delegation.ts b/apps/desktop/src/api/delegation.tsnew file mode 100644index 00000000000..e5f931bfc0d--- /dev/null+++ b/apps/desktop/src/api/delegation.ts@@ -0,0 +1,98 @@+import { capabilityScoped, type ProfileScope } from './client'++/** `delegation.backend` values the Settings editors know how to edit (any other plugin backend is a plain string). */+export type DelegationMode = 'default' | 'model_map' | 'profile_routes'++/** One backend row from `GET /api/delegation/routing`: `default` plus every plugin-registered backend. */+export interface DelegationBackendInfo {+ name: string+ label: string+ description: string+ available: boolean+ reason: string+ builtin: boolean+}++/** One entry of `delegation.backends.model_map.options`. Unknown keys round-trip untouched. */+export interface DelegationModelRoute {+ name: string+ description: string+ provider?: string+ model: string+ base_url?: string+ reasoning_effort?: string+ service_tier?: string+ /** Display-only preview when set; sending it back keeps the stored key. */+ api_key?: string+ fallback_providers?: unknown[]+ [key: string]: unknown+}++export interface DelegationProfileRoute {+ name: string+ description?: string+}++export interface DelegationModelMap {+ options: DelegationModelRoute[]+ default: null | string+}++export interface DelegationProfileRoutes {+ profiles: DelegationProfileRoute[]+ default: null | string+}++/** Shape of `GET /api/delegation/routing`. */+export interface DelegationRouting {+ /** The saved `delegation.backend` (normalized; `default` when unset). */+ configured: string+ /** Why the saved backend cannot run here (plugin missing, off or unavailable); `null` when it runs.+ * Core fails closed: while this is set every subagent is refused, it never quietly runs Default. */+ blocked_reason: null | string+ backends: DelegationBackendInfo[]+ model_map: DelegationModelMap+ profile_routes: DelegationProfileRoutes+ /** Profiles of this backend host a profile route may name. */+ profiles: string[]+}++export function getDelegationRouting(scope?: ProfileScope): Promise<DelegationRouting> {+ return window.hermesDesktop.api<DelegationRouting>({ ...capabilityScoped(scope), path: '/api/delegation/routing' })+}++export function selectDelegationBackend(+ backend: string,+ scope?: ProfileScope+): Promise<{ ok: boolean; backend: string }> {+ return window.hermesDesktop.api<{ ok: boolean; backend: string }>({+ ...capabilityScoped(scope),+ path: '/api/delegation/backend',+ method: 'PUT',+ body: { backend }+ })+}++export function saveDelegationModelRoutes(+ routes: DelegationModelMap,+ scope?: ProfileScope+): Promise<{ ok: boolean; model_map: DelegationModelMap }> {+ return window.hermesDesktop.api<{ ok: boolean; model_map: DelegationModelMap }>({+ ...capabilityScoped(scope),+ path: '/api/delegation/backends/model_map',+ method: 'PUT',+ body: routes+ })+}++export function saveDelegationProfileRoutes(+ routes: DelegationProfileRoutes,+ scope?: ProfileScope+): Promise<{ ok: boolean; profile_routes: DelegationProfileRoutes }> {+ return window.hermesDesktop.api<{ ok: boolean; profile_routes: DelegationProfileRoutes }>({+ ...capabilityScoped(scope),+ path: '/api/delegation/backends/profile_routes',+ method: 'PUT',+ body: routes+ })+}diff --git a/apps/desktop/src/app/settings/config-settings.tsx b/apps/desktop/src/app/settings/config-settings.tsxindex 7b09731371a..b4cb584c4dd 100644--- a/apps/desktop/src/app/settings/config-settings.tsx+++ b/apps/desktop/src/app/settings/config-settings.tsx@@ -39,6 +39,8 @@ import { PanelEmpty } from '../overlays/panel'import { ConfigField } from './config-field'import { configSubpageForField } from './config-subpages'import { DELEGATION_ROUTE_COMPANION_KEY, DelegationRouteRow } from './delegation-route-row'+import { DelegationRoutingSlot } from './delegation/routing-section'+import { SubagentModelGate } from './delegation/subagent-model-gate'import {clearsEnabledToolsets,configFieldValue,@@ -502,6 +504,14 @@ function ConfigSettingsInner({{/* Shared metrics are two coupled opt-ins with a consent side effect, so theygo through their own RPC rather than the generic field autosave. */}{showSharedMetrics ? <SharedMetricsSettings /> : null}+ {/* Routing picks the strategy and owns its routes; the subagent model row below is the+ Default strategy's route and goes inert while another strategy decides. */}+ <DelegationRoutingSlot+ readScope={scopeProfile}+ sectionId={activeSectionId}+ subpage={subpage}+ writeScope={writeScope}+ />{activeSectionId === 'voice' ? (<ListRow description={c.voiceShortcutHintDesc} title={c.voiceShortcutHintTitle} />) : null}@@ -512,7 +522,9 @@ function ConfigSettingsInner({{visibleFields.map(([key, field]) => (<div className="scroll-mt-6 rounded-lg" id={`setting-field-${key}`} key={key}>{key === 'delegation.model' ? (- <DelegationRouteRow config={config} onConfigChange={updateConfig} scope={writeScope ?? scopeProfile} />+ <SubagentModelGate scope={writeScope ?? scopeProfile}>+ <DelegationRouteRow config={config} onConfigChange={updateConfig} scope={writeScope ?? scopeProfile} />+ </SubagentModelGate>) : (<ConfigFielddescriptionExtra={diff --git a/apps/desktop/src/app/settings/delegation-model-provider-field.tsx b/apps/desktop/src/app/settings/delegation-model-provider-field.tsxindex 0df161de1b5..894d59d1eb1 100644--- a/apps/desktop/src/app/settings/delegation-model-provider-field.tsx+++ b/apps/desktop/src/app/settings/delegation-model-provider-field.tsx@@ -49,7 +49,7 @@ export function DelegationModelProviderField(props: DelegationModelProviderField}/** Catalog rows for the owner being edited; custom ids enrich only providers returned for that owner. */-function useOwnerCatalog(scope: ProfileScope | undefined) {+export function useOwnerCatalog(scope: ProfileScope | undefined) {const query = useQuery({queryKey: ['model-options', 'delegation', profileScopeKey(scope)],queryFn: () => getGlobalModelOptions(undefined, scope),@@ -71,7 +71,7 @@ function useOwnerCatalog(scope: ProfileScope | undefined) {}/** A saved provider the catalog lacks (alias, display name, custom) stays visible as-is. */-function displayProviders(+export function displayProviders(providers: readonly ModelOptionProvider[],draftProvider: string): readonly ModelOptionProvider[] {diff --git a/apps/desktop/src/app/settings/delegation-settings-integration.test.tsx b/apps/desktop/src/app/settings/delegation-settings-integration.test.tsxindex 770e542b319..195119776c6 100644--- a/apps/desktop/src/app/settings/delegation-settings-integration.test.tsx+++ b/apps/desktop/src/app/settings/delegation-settings-integration.test.tsx@@ -116,6 +116,11 @@ beforeEach(() => {return structuredClone(config)}+ // This backend predates delegation routing: the Subagents page keeps its pre-routing shape.+ if (request.path.startsWith('/api/delegation/')) {+ throw new Error('404: Not Found')+ }+return { ok: true }})} as typeof window.hermesDesktopdiff --git a/apps/desktop/src/app/settings/delegation/model-route-dialog.tsx b/apps/desktop/src/app/settings/delegation/model-route-dialog.tsxnew file mode 100644index 00000000000..1e29437c6bd--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/model-route-dialog.tsx@@ -0,0 +1,225 @@+import { REASONING_EFFORTS } from '@hermes/shared'+import { type FormEvent, useState } from 'react'++import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle+} from '@/components/ui/dialog'+import { Field, FieldHint } from '@/components/ui/field'+import { Input } from '@/components/ui/input'+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'+import { Textarea } from '@/components/ui/textarea'+import type { DelegationModelRoute, ProfileScope } from '@/hermes'+import { useI18n } from '@/i18n'+import { findCatalogProvider } from '@/lib/model-options'++import { displayProviders, useOwnerCatalog } from '../delegation-model-provider-field'+import { ModelSelect } from '../model-select'++import {+ draftFromRoute,+ emptyRouteDraft,+ type ModelRouteDraft,+ type RouteField,+ routeFromDraft,+ SERVICE_TIERS,+ validateRouteDraft+} from './routes'++// Radix Select cannot hold an empty value; this item stands for "no override".+const INHERIT = '__inherit__'++interface ModelRouteDialogProps {+ /** The route being edited; null creates a new one. */+ route: DelegationModelRoute | null+ /** Names of the other routes (a new name must not collide with them). */+ taken: readonly string[]+ scope: ProfileScope+ onClose: () => void+ onSave: (route: DelegationModelRoute) => Promise<boolean>+}++export function ModelRouteDialog({ route, taken, scope, onClose, onSave }: ModelRouteDialogProps) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing+ const { providers } = useOwnerCatalog(scope)+ const [draft, setDraft] = useState<ModelRouteDraft>(() => (route ? draftFromRoute(route) : emptyRouteDraft()))+ const [submitted, setSubmitted] = useState(false)+ const [touched, setTouched] = useState<Partial<Record<RouteField, boolean>>>({})+ const [busy, setBusy] = useState(false)+ const errors = validateRouteDraft(draft, taken, Boolean(route?.base_url))+ const selected = findCatalogProvider(providers, draft.provider)++ const set = (field: RouteField, value: string) => setDraft(current => ({ ...current, [field]: value }))+ const touch = (field: RouteField) => setTouched(current => ({ ...current, [field]: true }))++ const errorFor = (field: RouteField) =>+ (submitted || touched[field]) && errors[field] ? r.errors[errors[field]] : null++ const chooseProvider = (slug: string) => {+ const models = findCatalogProvider(providers, slug)?.models ?? []++ // Never carry a model id over to a provider that does not list it.+ setDraft(current => ({ ...current, provider: slug, model: models.includes(current.model) ? current.model : '' }))+ touch('provider')+ }++ async function handleSubmit(event: FormEvent) {+ event.preventDefault()+ setSubmitted(true)++ if (Object.keys(errors).length > 0) {+ return+ }++ setBusy(true)+ const saved = await onSave(routeFromDraft(draft, route ?? undefined))+ setBusy(false)++ if (saved) {+ onClose()+ }+ }++ const tierOptions = [+ { id: INHERIT, label: r.tierNormal },+ { id: SERVICE_TIERS[0], label: r.tierFast },+ { id: SERVICE_TIERS[1], label: r.tierUltrafast }+ ]++ return (+ <Dialog onOpenChange={open => !open && !busy && onClose()} open>+ <DialogContent className="max-w-lg" data-slot="delegation-route-dialog">+ <DialogHeader>+ <DialogTitle>{route ? r.dialogEdit : r.dialogNew}</DialogTitle>+ <DialogDescription>{r.dialogDesc}</DialogDescription>+ </DialogHeader>++ <form className="grid gap-4" noValidate onSubmit={handleSubmit}>+ <Field htmlFor="delegation-route-name" label={r.nameLabel}>+ <Input+ aria-invalid={Boolean(errorFor('name'))}+ autoFocus={!route}+ className="font-mono sm:max-w-56"+ id="delegation-route-name"+ onBlur={() => touch('name')}+ onChange={event => set('name', event.target.value)}+ placeholder={r.namePlaceholder}+ value={draft.name}+ />+ <FieldHint error={Boolean(errorFor('name'))}>{errorFor('name') ?? r.nameHint}</FieldHint>+ </Field>+ <Field htmlFor="delegation-route-description" label={r.descriptionLabel}>+ <Textarea+ aria-invalid={Boolean(errorFor('description'))}+ className="min-h-14 resize-none"+ id="delegation-route-description"+ onBlur={() => touch('description')}+ onChange={event => set('description', event.target.value)}+ placeholder={r.descriptionPlaceholder}+ rows={2}+ value={draft.description}+ />+ <FieldHint error={Boolean(errorFor('description'))}>+ {errorFor('description') ?? r.descriptionHint}+ </FieldHint>+ </Field>++ <div className="grid items-start gap-4 sm:grid-cols-2">+ <Field htmlFor="delegation-route-provider" label={r.providerLabel}>+ <Select onValueChange={chooseProvider} value={draft.provider || undefined}>+ <SelectTrigger+ aria-invalid={Boolean(errorFor('provider'))}+ className="[&_[data-slot=select-value]]:truncate"+ id="delegation-route-provider"+ >+ <SelectValue placeholder={r.providerPlaceholder} />+ </SelectTrigger>+ <SelectContent>+ {displayProviders(providers, draft.provider).map(provider => (+ <SelectItem key={provider.slug} value={provider.slug}>+ {provider.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {errorFor('provider') && <FieldHint error>{errorFor('provider')}</FieldHint>}+ {route?.base_url && !draft.provider && <FieldHint>{r.baseUrlRoute(route.base_url)}</FieldHint>}+ </Field>+ <Field htmlFor="delegation-route-model" label={r.modelLabel}>+ <div className="min-w-0" id="delegation-route-model">+ <ModelSelect+ aria-invalid={Boolean(errorFor('model'))}+ aria-label={r.modelLabel}+ className="w-full [&_[data-slot=select-value]]:truncate"+ models={selected?.models ?? []}+ onValueChange={model => {+ set('model', model)+ touch('model')+ }}+ provider={selected}+ providerSlug={draft.provider}+ value={draft.model}+ />+ </div>+ {errorFor('model') && <FieldHint error>{errorFor('model')}</FieldHint>}+ </Field>+ </div>++ <div className="grid items-start gap-4 sm:grid-cols-2">+ <Field htmlFor="delegation-route-effort" label={r.effortLabel} optional optionalLabel={r.optional}>+ <Select+ onValueChange={value => set('reasoning_effort', value === INHERIT ? '' : value)}+ value={draft.reasoning_effort || INHERIT}+ >+ <SelectTrigger id="delegation-route-effort">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={INHERIT}>{r.effortInherit}</SelectItem>+ {['none', ...REASONING_EFFORTS].map(effort => (+ <SelectItem key={effort} value={effort}>+ {effort}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ <Field htmlFor="delegation-route-tier" label={r.tierLabel} optional optionalLabel={r.optional}>+ <Select+ onValueChange={value => set('service_tier', value === INHERIT ? '' : value)}+ value={draft.service_tier || INHERIT}+ >+ <SelectTrigger id="delegation-route-tier">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {tierOptions.map(option => (+ <SelectItem key={option.id} value={option.id}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldHint>{r.tierHint}</FieldHint>+ </Field>+ </div>++ <DialogFooter>+ <Button disabled={busy} onClick={onClose} type="button" variant="ghost">+ {t.common.cancel}+ </Button>+ <Button disabled={busy} type="submit">+ {route ? r.saveRoute : r.createRoute}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}diff --git a/apps/desktop/src/app/settings/delegation/model-routes.tsx b/apps/desktop/src/app/settings/delegation/model-routes.tsxnew file mode 100644index 00000000000..f4dcafc4131--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/model-routes.tsx@@ -0,0 +1,143 @@+import { useState } from 'react'++import { ActionsMenu, renderActionItem } from '@/components/ui/actions-menu'+import { Button } from '@/components/ui/button'+import type { DelegationModelMap, DelegationModelRoute, ProfileScope } from '@/hermes'+import { useI18n } from '@/i18n'+import { Box, MoreHorizontal, Plus } from '@/lib/icons'+import { confirm } from '@/store/confirm'++import { Pill, SectionHeading } from '../primitives'++import { ModelRouteDialog } from './model-route-dialog'+import { removeRoute, setDefaultRoute, upsertRoute } from './routes'+import { saveModelRoutes } from './routing-data'++interface ModelRoutesEditorProps {+ scope: ProfileScope+ routes: DelegationModelMap+ providerNames: ReadonlyMap<string, string>+}++/** `delegation.backends.model_map`: the named routes the agent picks between, with create / edit / delete. */+export function ModelRoutesEditor({ scope, routes, providerNames }: ModelRoutesEditorProps) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing+ // undefined = closed, null = creating, a route = editing it.+ const [editing, setEditing] = useState<DelegationModelRoute | null | undefined>(undefined)+ const save = (next: DelegationModelMap) => saveModelRoutes(scope, next, r.saveFailed)++ const askDelete = async (route: DelegationModelRoute) => {+ const next = removeRoute(routes, route.name)+ const movesDefault = routes.default === route.name && next.default++ const ok = await confirm({+ confirmLabel: r.deleteConfirmAction,+ description: movesDefault+ ? `${r.deleteConfirmBody} ${r.deleteConfirmNextDefault(next.default!)}`+ : r.deleteConfirmBody,+ destructive: true,+ title: r.deleteConfirmTitle(route.name)+ })++ if (ok) {+ await save(next)+ }+ }++ return (+ <section data-slot="delegation-model-routes">+ <SectionHeading+ aside={+ <Button onClick={() => setEditing(null)} size="sm" variant="secondary">+ <Plus />+ {r.addRoute}+ </Button>+ }+ icon={Box}+ title={r.modelRoutesTitle}+ />+ {routes.options.length === 0 ? (+ <p className="py-3 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">+ {r.modelRoutesEmpty}+ </p>+ ) : (+ <ul className="grid">+ {routes.options.map(route => (+ <RouteRow+ isDefault={routes.default === route.name}+ key={route.name}+ onDelete={() => void askDelete(route)}+ onEdit={() => setEditing(route)}+ onMakeDefault={() => void save(setDefaultRoute(routes, route.name))}+ providerName={providerNames.get(route.provider ?? '') ?? route.provider}+ route={route}+ />+ ))}+ </ul>+ )}+ {editing !== undefined && (+ <ModelRouteDialog+ onClose={() => setEditing(undefined)}+ onSave={route => save(upsertRoute(routes, editing?.name ?? null, route))}+ route={editing}+ scope={scope}+ taken={routes.options.map(o => o.name).filter(name => name !== editing?.name)}+ />+ )}+ </section>+ )+}++interface RouteRowProps {+ route: DelegationModelRoute+ isDefault: boolean+ providerName?: string+ onEdit: () => void+ onMakeDefault: () => void+ onDelete: () => void+}++function RouteRow({ route, isDefault, providerName, onEdit, onMakeDefault, onDelete }: RouteRowProps) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing++ const facts = [+ providerName || (route.base_url ? r.baseUrlRoute(route.base_url) : ''),+ route.model,+ route.reasoning_effort ? `${r.effortLabel.toLowerCase()} ${route.reasoning_effort}` : '',+ route.service_tier ?? ''+ ].filter(Boolean)++ return (+ <li className="group flex items-start gap-3 border-t border-(--ui-stroke-tertiary) py-3 first:border-t-0">+ <button className="grid min-w-0 flex-1 gap-1 text-left" onClick={onEdit} type="button">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate font-mono text-[length:var(--conversation-text-font-size)] font-medium text-foreground">+ {route.name}+ </span>+ {isDefault && <Pill tone="primary">{r.defaultBadge}</Pill>}+ </span>+ <span className="text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-secondary)">+ {route.description}+ </span>+ <span className="truncate font-mono text-[0.68rem] text-(--ui-text-tertiary)">{facts.join(' · ')}</span>+ </button>+ <ActionsMenu+ ariaLabel={r.routeActions(route.name)}+ items={kit => (+ <>+ {renderActionItem(kit, { icon: 'edit', label: r.editRoute, onSelect: onEdit })}+ {!isDefault && renderActionItem(kit, { icon: 'star-empty', label: r.makeDefault, onSelect: onMakeDefault })}+ <kit.Separator />+ {renderActionItem(kit, { icon: 'trash', label: r.deleteRoute, onSelect: onDelete, variant: 'destructive' })}+ </>+ )}+ >+ <Button aria-label={r.routeActions(route.name)} size="icon-sm" variant="ghost">+ <MoreHorizontal />+ </Button>+ </ActionsMenu>+ </li>+ )+}diff --git a/apps/desktop/src/app/settings/delegation/plugin-actions.ts b/apps/desktop/src/app/settings/delegation/plugin-actions.tsnew file mode 100644index 00000000000..6142d9d7abd--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/plugin-actions.ts@@ -0,0 +1,71 @@+import { useStore } from '@nanostores/react'+import { useEffect } from 'react'++import { lookupPluginCatalogEntry } from '@/lib/plugin-catalog'+import type { GatewayRequest } from '@/store/agent-plugins'+import {+ $agentPlugins,+ $agentPluginsProfile,+ $agentPluginsStatus,+ loadAgentPlugins,+ toggleAgentPlugin+} from '@/store/agent-plugins'+import { notify } from '@/store/notifications'+import { openCatalogPluginInstall } from '@/store/plugin-catalog-install'++import { ADVANCED_DELEGATION_PLUGIN } from './routing-data'++/** Where the route backends' plugin stands for the Settings owner: drives the hint under a plugin mode. */+export type PluginState = 'disabled' | 'loading' | 'missing' | 'not_loaded'++/** The Advanced Delegation plugin's state for `owner` (the Settings "Applies to" profile; null = launch profile). */+export function useAdvancedDelegationPlugin(request: GatewayRequest, owner: null | string) {+ const rows = useStore($agentPlugins)+ const loadedFor = useStore($agentPluginsProfile)+ const status = useStore($agentPluginsStatus)+ const owned = loadedFor === owner++ useEffect(() => {+ if (!owned) {+ void loadAgentPlugins(request, owner)+ }+ }, [owned, owner, request])++ const row = owned+ ? rows.find(r => r.name === ADVANCED_DELEGATION_PLUGIN || r.key === ADVANCED_DELEGATION_PLUGIN)+ : undefined++ const state: PluginState = !owned+ ? status === 'error'+ ? 'missing'+ : 'loading'+ : !row+ ? 'missing'+ : row.status === 'enabled'+ ? 'not_loaded'+ : 'disabled'++ return { row, state }+}++/** Open the reviewed catalog install dialog for the owner; a catalog without the entry says so. */+export async function installAdvancedDelegation(owner: null | string, unavailableMessage: string) {+ const result = await lookupPluginCatalogEntry(ADVANCED_DELEGATION_PLUGIN)++ if (!result.ok) {+ notify({ kind: 'error', message: unavailableMessage })++ return+ }++ openCatalogPluginInstall(result.entry, owner)+}++export function enableAdvancedDelegation(+ request: GatewayRequest,+ key: string,+ owner: null | string,+ failMessage: string+) {+ return toggleAgentPlugin(request, key, true, failMessage, owner)+}diff --git a/apps/desktop/src/app/settings/delegation/profile-routes.tsx b/apps/desktop/src/app/settings/delegation/profile-routes.tsxnew file mode 100644index 00000000000..a1c9990284f--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/profile-routes.tsx@@ -0,0 +1,135 @@+import { useEffect, useState } from 'react'++import { Button } from '@/components/ui/button'+import { Checkbox } from '@/components/ui/checkbox'+import { Input } from '@/components/ui/input'+import type { DelegationProfileRoutes, ProfileScope } from '@/hermes'+import { useI18n } from '@/i18n'+import { Users } from '@/lib/icons'+import { isSubmitEnter } from '@/lib/ime'++import { Pill, SectionHeading } from '../primitives'++import { describeProfileRoute, setDefaultProfileRoute, toggleProfileRoute } from './routes'+import { saveProfileRoutes } from './routing-data'++interface ProfileRoutesEditorProps {+ scope: ProfileScope+ routes: DelegationProfileRoutes+ /** Profiles that exist on this backend host. */+ profiles: readonly string[]+}++/** `delegation.backends.profile_routes`: check the profiles subagents may run as, describe them, pick a default. */+export function ProfileRoutesEditor({ scope, routes, profiles }: ProfileRoutesEditorProps) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing+ const save = (next: DelegationProfileRoutes) => void saveProfileRoutes(scope, next, r.saveFailed)+ // A listed profile that was deleted since stays visible (and uncheckable) instead of vanishing.+ const missing = routes.profiles.map(p => p.name).filter(name => !profiles.includes(name))++ return (+ <section data-slot="delegation-profile-routes">+ <SectionHeading icon={Users} title={r.profileRoutesTitle} />+ <p className="text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">+ {r.profileRoutesHint}+ </p>+ {profiles.length === 0 ? (+ <p className="py-3 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">+ {r.profileEmpty}+ </p>+ ) : (+ <ul className="mt-2 grid">+ {[...profiles, ...missing].map(name => {+ const entry = routes.profiles.find(p => p.name === name)++ return (+ <ProfileRow+ checked={Boolean(entry)}+ description={entry?.description ?? ''}+ isDefault={routes.default === name}+ key={name}+ label={missing.includes(name) ? r.profileMissing(name) : name}+ name={name}+ onDescribe={text => save(describeProfileRoute(routes, name, text))}+ onMakeDefault={() => save(setDefaultProfileRoute(routes, name))}+ onToggle={on => save(toggleProfileRoute(routes, name, on))}+ />+ )+ })}+ </ul>+ )}+ </section>+ )+}++interface ProfileRowProps {+ name: string+ label: string+ checked: boolean+ description: string+ isDefault: boolean+ onToggle: (on: boolean) => void+ onDescribe: (text: string) => void+ onMakeDefault: () => void+}++function ProfileRow({+ name,+ label,+ checked,+ description,+ isDefault,+ onToggle,+ onDescribe,+ onMakeDefault+}: ProfileRowProps) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing+ const [draft, setDraft] = useState(description)+ const id = `delegation-profile-${name}`++ useEffect(() => setDraft(description), [description])++ const commit = () => {+ if (draft.trim() !== description.trim()) {+ onDescribe(draft)+ }+ }++ return (+ <li className="grid min-h-12 grid-cols-[minmax(8rem,12rem)_minmax(0,1fr)_auto] items-center gap-3 border-t border-(--ui-stroke-tertiary) py-2 first:border-t-0">+ <label className="flex min-w-0 items-center gap-2.5" htmlFor={id}>+ <Checkbox checked={checked} id={id} onCheckedChange={value => onToggle(value === true)} />+ <span className="truncate text-[length:var(--conversation-text-font-size)] text-foreground">{label}</span>+ </label>+ {checked ? (+ <Input+ aria-label={`${name}: ${r.descriptionLabel}`}+ onBlur={commit}+ onChange={event => setDraft(event.target.value)}+ onKeyDown={event => {+ if (isSubmitEnter(event)) {+ event.currentTarget.blur()+ }+ }}+ placeholder={r.profileDescriptionPlaceholder}+ size="sm"+ value={draft}+ />+ ) : (+ <span />+ )}+ <span className="flex w-24 justify-end">+ {checked &&+ (isDefault ? (+ <Pill tone="primary">{r.profileDefault}</Pill>+ ) : (+ <Button onClick={onMakeDefault} size="xs" variant="outline">+ {r.makeDefault}+ </Button>+ ))}+ </span>+ </li>+ )+}diff --git a/apps/desktop/src/app/settings/delegation/routes.test.ts b/apps/desktop/src/app/settings/delegation/routes.test.tsnew file mode 100644index 00000000000..5150723146c--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/routes.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest'++import type { DelegationModelMap } from '@/hermes'++import { removeRoute, routeFromDraft, toggleProfileRoute, upsertRoute, validateRouteDraft } from './routes'++const route = (name: string, extra: Record<string, unknown> = {}) => ({+ name,+ description: `${name} route`,+ provider: 'openrouter',+ model: `m-${name}`,+ ...extra+})++describe('route editing keeps a default while routes exist', () => {+ it('names a default on the first route, follows a rename, and moves it off a deleted default', () => {+ let map: DelegationModelMap = { options: [], default: null }++ map = upsertRoute(map, null, route('fast'))+ map = upsertRoute(map, null, route('deep'))+ expect(map.default).toBe('fast')++ map = upsertRoute(map, 'fast', route('quick'))+ expect(map).toEqual({ options: [route('quick'), route('deep')], default: 'quick' })++ expect(removeRoute(map, 'quick')).toEqual({ options: [route('deep')], default: 'deep' })+ expect(removeRoute(removeRoute(map, 'quick'), 'deep')).toEqual({ options: [], default: null })++ let profiles = toggleProfileRoute({ profiles: [], default: null }, 'coder', true)+ profiles = toggleProfileRoute(profiles, 'researcher', true)+ expect(profiles.default).toBe('coder')+ expect(toggleProfileRoute(profiles, 'coder', false)).toEqual({+ profiles: [{ name: 'researcher' }],+ default: 'researcher'+ })+ })++ it('refuses incomplete or clashing drafts and keeps keys the dialog does not edit', () => {+ const draft = { name: 'deep', description: '', provider: '', model: '', reasoning_effort: '', service_tier: '' }++ expect(validateRouteDraft(draft, ['deep'])).toEqual({+ name: 'duplicate',+ description: 'required',+ provider: 'required',+ model: 'required'+ })+ expect(validateRouteDraft({ ...draft, name: 'a b' }, []).name).toBe('spaces')+ // A hand-written endpoint route has no provider and stays valid.+ expect(validateRouteDraft({ ...draft, description: 'd', model: 'm' }, [], true)).toEqual({})++ const stored = route('local', {+ base_url: 'http://127.0.0.1:8080/v1',+ api_key: '«redacted:sk-…1234»',+ service_tier: 'fast'+ })++ const saved = routeFromDraft({ ...draft, name: 'local', description: 'Private', model: 'qwen' }, stored)++ expect(saved).toEqual({+ name: 'local',+ description: 'Private',+ model: 'qwen',+ base_url: 'http://127.0.0.1:8080/v1',+ api_key: '«redacted:sk-…1234»'+ })+ })+})diff --git a/apps/desktop/src/app/settings/delegation/routes.ts b/apps/desktop/src/app/settings/delegation/routes.tsnew file mode 100644index 00000000000..b6c4bc8abe1--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/routes.ts@@ -0,0 +1,148 @@+import type { DelegationModelMap, DelegationModelRoute, DelegationProfileRoutes } from '@/hermes'++/** The fields the route dialog edits; every other key of a stored route round-trips untouched. */+export interface ModelRouteDraft {+ name: string+ description: string+ provider: string+ model: string+ reasoning_effort: string+ service_tier: string+}++export type RouteField = keyof ModelRouteDraft+export type RouteError = 'duplicate' | 'required' | 'spaces'++export const SERVICE_TIERS = ['fast', 'ultrafast'] as const++export const emptyRouteDraft = (): ModelRouteDraft => ({+ name: '',+ description: '',+ provider: '',+ model: '',+ reasoning_effort: '',+ service_tier: ''+})++export const draftFromRoute = (route: DelegationModelRoute): ModelRouteDraft => ({+ name: route.name ?? '',+ description: route.description ?? '',+ provider: route.provider ?? '',+ model: route.model ?? '',+ reasoning_effort: route.reasoning_effort ?? '',+ service_tier: route.service_tier ?? ''+})++/** Field → problem, empty when the draft can be saved. `taken` = names of the OTHER routes.+ * A stored route with only a base_url (hand-written YAML) keeps it and needs no provider. */+export function validateRouteDraft(+ draft: ModelRouteDraft,+ taken: readonly string[],+ hasBaseUrl = false+): Partial<Record<RouteField, RouteError>> {+ const errors: Partial<Record<RouteField, RouteError>> = {}+ const name = draft.name.trim()++ if (!name) {+ errors.name = 'required'+ } else if (/\s/.test(name)) {+ errors.name = 'spaces'+ } else if (taken.includes(name)) {+ errors.name = 'duplicate'+ }++ for (const field of ['description', 'model'] as const) {+ if (!draft[field].trim()) {+ errors[field] = 'required'+ }+ }++ if (!draft.provider.trim() && !hasBaseUrl) {+ errors.provider = 'required'+ }++ return errors+}++/** The stored route for `draft`: edited fields replace, blank optional fields drop, unknown keys stay. */+export function routeFromDraft(draft: ModelRouteDraft, previous?: DelegationModelRoute): DelegationModelRoute {+ const next: Record<string, unknown> = { ...previous }++ for (const field of Object.keys(draft) as RouteField[]) {+ const value = draft[field].trim()++ if (value) {+ next[field] = value+ } else {+ delete next[field]+ }+ }++ return next as DelegationModelRoute+}++/** A default route always exists while routes do, so the subagent model below is plainly unused. */+function withDefault(options: DelegationModelRoute[], preferred: null | string): DelegationModelMap {+ const names = options.map(option => option.name)++ return { options, default: preferred && names.includes(preferred) ? preferred : (names[0] ?? null) }+}++/** Insert (`original` null) or replace the route called `original`; a rename carries the default along. */+export function upsertRoute(map: DelegationModelMap, original: null | string, route: DelegationModelRoute) {+ const index = original === null ? -1 : map.options.findIndex(option => option.name === original)+ const options = index < 0 ? [...map.options, route] : map.options.map((o, i) => (i === index ? route : o))+ const preferred = original !== null && map.default === original ? route.name : map.default++ return withDefault(options, preferred)+}++export const removeRoute = (map: DelegationModelMap, name: string) =>+ withDefault(+ map.options.filter(option => option.name !== name),+ map.default === name ? null : map.default+ )++export const setDefaultRoute = (map: DelegationModelMap, name: string) => withDefault(map.options, name)++/** Check or uncheck a profile; the first checked profile becomes the default when none is. */+export function toggleProfileRoute(+ routes: DelegationProfileRoutes,+ name: string,+ on: boolean+): DelegationProfileRoutes {+ const profiles = on+ ? routes.profiles.some(p => p.name === name)+ ? routes.profiles+ : [...routes.profiles, { name }]+ : routes.profiles.filter(p => p.name !== name)++ const names = profiles.map(p => p.name)+ const preferred = routes.default && names.includes(routes.default) ? routes.default : null++ return { profiles, default: preferred ?? names[0] ?? null }+}++export function describeProfileRoute(+ routes: DelegationProfileRoutes,+ name: string,+ description: string+): DelegationProfileRoutes {+ return {+ ...routes,+ profiles: routes.profiles.map(p => {+ if (p.name !== name) {+ return p+ }++ const text = description.trim()++ return text ? { name, description: text } : { name }+ })+ }+}++export const setDefaultProfileRoute = (routes: DelegationProfileRoutes, name: string): DelegationProfileRoutes => ({+ ...routes,+ default: name+})diff --git a/apps/desktop/src/app/settings/delegation/routing-data.ts b/apps/desktop/src/app/settings/delegation/routing-data.tsnew file mode 100644index 00000000000..3082290ba4c--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/routing-data.ts@@ -0,0 +1,148 @@+import { useStore } from '@nanostores/react'+import { useQuery } from '@tanstack/react-query'++import { getApiRequestConnection, getApiRequestProfile, type ProfileScope, profileScopeKey } from '@/api/client'+import {+ type DelegationMode,+ type DelegationModelMap,+ type DelegationProfileRoutes,+ type DelegationRouting,+ getDelegationRouting,+ saveDelegationModelRoutes,+ saveDelegationProfileRoutes,+ selectDelegationBackend+} from '@/api/delegation'+import { queryClient } from '@/lib/query-client'+import { $activeConnectionId } from '@/store/connections'+import { notifyError } from '@/store/notifications'+import { $activeProfile } from '@/store/profile'++/** The official plugin that provides the two route backends (`delegation.backend` values below). */+export const ADVANCED_DELEGATION_PLUGIN = 'advanced-delegation'+export const PLUGIN_MODES = ['model_map', 'profile_routes'] as const satisfies readonly DelegationMode[]+export const MODES = ['default', ...PLUGIN_MODES] as const satisfies readonly DelegationMode[]++// An unpinned scope follows the app's active profile and connection, so both are part of the key.+export const routingQueryKey = (scope: ProfileScope) =>+ [+ 'delegation-routing',+ profileScopeKey(scope ?? getApiRequestProfile()),+ getApiRequestConnection() ?? 'local'+ ] as const++// A backend older than the routing endpoint answers 404: a missing capability, not a failure to retry.+const isMissingEndpoint = (error: unknown) => /\b404\b/.test(error instanceof Error ? error.message : String(error))++/** The owner's delegation routing (backend, route blocks, registered backends), shared by every row of the page.+ * `null` data = the backend has no routing endpoint, so the page keeps its pre-routing shape. */+export function useDelegationRouting(scope: ProfileScope) {+ useStore($activeProfile)+ useStore($activeConnectionId)++ return useQuery({+ queryKey: routingQueryKey(scope),+ queryFn: async (): Promise<DelegationRouting | null> => {+ try {+ return await getDelegationRouting(scope)+ } catch (error) {+ if (isMissingEndpoint(error)) {+ return null+ }++ throw error+ }+ },+ retry: false,+ // Plugin installs and toggles elsewhere (Plugins page, CLI) change which backends exist: re-read on mount.+ staleTime: 0+ })+}++export const isPluginMode = (name: string): name is (typeof PLUGIN_MODES)[number] =>+ (PLUGIN_MODES as readonly string[]).includes(name)++/** Every mode the picker lists: the three it edits, each other registered backend (a third-party plugin's), then+ * a saved backend nothing registers, so the saved choice is always on screen even when it cannot run. */+export function modeChoices(routing: DelegationRouting): string[] {+ const known = new Set<string>(MODES)+ const names = [...MODES, ...routing.backends.filter(b => !b.builtin && !known.has(b.name)).map(b => b.name)]++ return names.includes(routing.configured) ? names : [...names, routing.configured]+}++/** Whether a mode can be chosen for this owner: `default` always, a plugin mode once its backend can run. */+export function modeAvailable(routing: DelegationRouting, mode: string): boolean {+ return routing.backends.some(backend => backend.name === mode && backend.available)+}++/** Any mode but Default decides each subagent's model itself (a task with no route runs on the main agent's+ * model), so `delegation.model` / `delegation.provider` never apply then, routes or not. */+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. */+async function writeThrough(+ scope: ProfileScope,+ patch: (current: DelegationRouting) => DelegationRouting,+ write: () => Promise<Partial<DelegationRouting>>,+ failMessage: string+): Promise<boolean> {+ const key = routingQueryKey(scope)+ const before = queryClient.getQueryData<DelegationRouting>(key)++ if (!before) {+ return false+ }++ queryClient.setQueryData(key, patch(before))++ try {+ const saved = await write()++ queryClient.setQueryData<DelegationRouting>(key, current => (current ? { ...current, ...saved } : current))++ return true+ } catch (err) {+ queryClient.setQueryData(key, before)+ notifyError(err, failMessage)++ return false+ }+}++/** Only a mode that can run is offered, and the server refuses any other: a saved choice is never blocked. */+export function chooseDelegationMode(scope: ProfileScope, mode: string, failMessage: string) {+ return writeThrough(+ scope,+ current => ({ ...current, configured: mode, blocked_reason: null }),+ async () => {+ const { backend } = await selectDelegationBackend(mode, scope)++ return { configured: backend, blocked_reason: null }+ },+ failMessage+ )+}++export function saveModelRoutes(scope: ProfileScope, next: DelegationModelMap, failMessage: string) {+ return writeThrough(+ scope,+ current => ({ ...current, model_map: next }),+ async () => ({ model_map: (await saveDelegationModelRoutes(next, scope)).model_map }),+ failMessage+ )+}++export function saveProfileRoutes(scope: ProfileScope, next: DelegationProfileRoutes, failMessage: string) {+ return writeThrough(+ scope,+ current => ({ ...current, profile_routes: next }),+ async () => ({ profile_routes: (await saveDelegationProfileRoutes(next, scope)).profile_routes }),+ failMessage+ )+}++export function refreshDelegationRouting(scope: ProfileScope) {+ return queryClient.invalidateQueries({ queryKey: routingQueryKey(scope) })+}diff --git a/apps/desktop/src/app/settings/delegation/routing-section.test.tsx b/apps/desktop/src/app/settings/delegation/routing-section.test.tsxnew file mode 100644index 00000000000..fa2b1996b10--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/routing-section.test.tsx@@ -0,0 +1,164 @@+import { QueryClientProvider } from '@tanstack/react-query'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'++import type { DelegationRouting } from '@/api/delegation'+import type { HermesApiRequest } from '@/global'+import { queryClient } from '@/lib/query-client'++import { DelegationRoutingSection } from './routing-section'+import { SubagentModelGate } from './subagent-model-gate'++// A stateful stand-in for the backend's /api/delegation routes (same shapes, same refusal).+let routing: DelegationRouting+const writes: HermesApiRequest[] = []++function backend(names: string[]): DelegationRouting['backends'] {+ return names.map(name => ({+ name,+ label: name,+ description: '',+ available: true,+ reason: '',+ builtin: name === 'default'+ }))+}++beforeEach(() => {+ queryClient.clear()+ writes.length = 0+ routing = {+ configured: 'default',+ blocked_reason: null,+ backends: backend(['default']),+ model_map: { options: [], default: null },+ profile_routes: { profiles: [], default: null },+ profiles: ['default', 'work']+ }+ window.hermesDesktop = {+ ...window.hermesDesktop,+ api: async (request: HermesApiRequest) => {+ if (request.path === '/api/delegation/routing') {+ return structuredClone(routing)+ }++ if (request.path === '/api/delegation/backend') {+ writes.push(request)+ const name = (request.body as { backend: string }).backend++ if (!routing.backends.some(b => b.name === name)) {+ throw new Error(`400: Delegation backend '${name}' is not installed for this profile.`)+ }++ routing = { ...routing, configured: name, blocked_reason: null }++ return { ok: true, backend: name }+ }++ if (request.path.startsWith('/api/model/options')) {+ return { providers: [] }+ }++ throw new Error('404: Not Found')+ }+ } as typeof window.hermesDesktop+})++afterEach(cleanup)++function mount() {+ return render(+ <QueryClientProvider client={queryClient}>+ <DelegationRoutingSection scope="work" />+ <SubagentModelGate scope="work">+ <div data-testid="subagent-model-row">Subagent Model</div>+ </SubagentModelGate>+ </QueryClientProvider>+ )+}++const radio = (name: RegExp) => screen.getByRole('radio', { name }) as HTMLButtonElement++describe('Subagents routing', () => {+ it('shows plugin modes with an install hint, never as choosable, until their backend registers', async () => {+ mount()+ await screen.findByText('Model routes and Profile routes come from the Advanced Delegation plugin.')++ expect(radio(/^Default/).getAttribute('aria-checked')).toBe('true')+ expect(radio(/^Model routes/).disabled).toBe(true)+ expect(radio(/^Profile routes/).disabled).toBe(true)+ expect(screen.getByRole('button', { name: 'Install plugin' })).toBeTruthy()+ expect(writes).toHaveLength(0)+ })++ it('choosing model routes makes the subagent model visibly inactive, and Switch to Default restores it', async () => {+ routing = {+ ...routing,+ backends: backend(['default', 'model_map', 'profile_routes']),+ model_map: {+ options: [{ name: 'fast', description: 'Quick', provider: 'openrouter', model: 'm' }],+ default: 'fast'+ }+ }+ mount()+ await waitFor(() => expect(radio(/^Model routes/).disabled).toBe(false))+ expect(screen.queryByText('Not used in this mode')).toBeNull()++ fireEvent.click(radio(/^Model routes/))++ await screen.findByText('Not used in this mode')+ expect(writes.map(w => [w.profile, (w.body as { backend: string }).backend])).toEqual([['work', 'model_map']])+ expect(screen.getByText(/Subagents that pick no route use “fast”/)).toBeTruthy()+ expect(screen.getByTestId('subagent-model-row').closest('[inert]')).not.toBeNull()++ fireEvent.click(screen.getByRole('button', { name: 'Switch to Default' }))++ await waitFor(() => expect(screen.queryByText('Not used in this mode')).toBeNull())+ expect(screen.getByTestId('subagent-model-row').closest('[inert]')).toBeNull()+ expect(routing.configured).toBe('default')+ })++ it('keeps a saved mode that cannot run selected, says subagents will not start, and offers the fixes', async () => {+ routing = { ...routing, configured: 'model_map', blocked_reason: "Delegation backend 'model_map' is not installed" }+ mount()++ await screen.findByText('Subagents will not start until Advanced Delegation is installed.')+ expect(radio(/^Model routes/).getAttribute('aria-checked')).toBe('true')+ expect(radio(/^Default/).getAttribute('aria-checked')).toBe('false')+ expect(screen.getByText('Not running')).toBeTruthy()+ expect(screen.getAllByRole('button', { name: 'Install plugin' })).toHaveLength(1)+ // The subagent model does not apply in this mode either: it stays inert, never silently "back on".+ expect(screen.getByTestId('subagent-model-row').closest('[inert]')).not.toBeNull()++ fireEvent.click(screen.getAllByRole('button', { name: 'Switch to Default' })[0])++ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull())+ expect(radio(/^Default/).getAttribute('aria-checked')).toBe('true')+ expect(routing.configured).toBe('default')+ })++ it('gates the subagent model in a route mode with no routes: unrouted tasks run on the main agent model', async () => {+ routing = { ...routing, configured: 'model_map', backends: backend(['default', 'model_map', 'profile_routes']) }+ mount()++ await screen.findByText(/Subagents that pick no route use the main agent's model/)+ expect(screen.getByTestId('subagent-model-row').closest('[inert]')).not.toBeNull()+ expect(screen.queryByRole('alert')).toBeNull()+ })++ it("lists another plugin's backend by its own label and gates the subagent model while it is saved", async () => {+ routing = {+ ...routing,+ configured: 'swarm',+ backends: [+ ...backend(['default']),+ { name: 'swarm', label: 'Swarm', description: '', available: true, reason: '', builtin: false }+ ]+ }+ mount()++ await screen.findByText(/Swarm decides each subagent's model/)+ expect(radio(/^Swarm/).getAttribute('aria-checked')).toBe('true')+ expect(screen.getByText('From a plugin. Its settings live with that plugin.')).toBeTruthy()+ })+})diff --git a/apps/desktop/src/app/settings/delegation/routing-section.tsx b/apps/desktop/src/app/settings/delegation/routing-section.tsxnew file mode 100644index 00000000000..cbcff4c51da--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/routing-section.tsx@@ -0,0 +1,296 @@+import { useStore } from '@nanostores/react'+import type { ReactNode } from 'react'++import { useGatewayRequest } from '@/app/gateway/hooks/use-gateway-request'+import { Button } from '@/components/ui/button'+import { Skeleton } from '@/components/ui/skeleton'+import type { DelegationRouting, ProfileScope } from '@/hermes'+import { useI18n } from '@/i18n'+import type { DelegationRoutingTranslations } from '@/i18n/types_delegation_routing'+import { AlertTriangle, Check, GitFork, Plug, SlidersHorizontal } from '@/lib/icons'+import { cn } from '@/lib/utils'+import { $settingsRequestProfile } from '@/store/settings-scope'++import { useOwnerCatalog } from '../delegation-model-provider-field'+import { Pill, SectionHeading, SettingsSection } from '../primitives'++import { ModelRoutesEditor } from './model-routes'+import { enableAdvancedDelegation, installAdvancedDelegation, useAdvancedDelegationPlugin } from './plugin-actions'+import { ProfileRoutesEditor } from './profile-routes'+import {+ chooseDelegationMode,+ isPluginMode,+ modeAvailable,+ modeChoices,+ MODES,+ PLUGIN_MODES,+ refreshDelegationRouting,+ useDelegationRouting+} from './routing-data'++interface DelegationRoutingSlotProps {+ sectionId: string+ /** Undefined = the whole section is shown (embedded consumers). */+ subpage?: string+ /** The config page's owner: the read origin once the config loaded, else the Applies-to profile. */+ writeScope?: ProfileScope+ readScope?: string+}++/** The Routing section on the page that owns `delegation.*` (Model › Subagents); nothing elsewhere. */+export function DelegationRoutingSlot({ sectionId, subpage, writeScope, readScope }: DelegationRoutingSlotProps) {+ if (sectionId !== 'model' || (subpage !== undefined && subpage !== 'delegation')) {+ return null+ }++ return <DelegationRoutingSection scope={writeScope ?? readScope} />+}++/** Settings › Model › Subagents: how each subagent gets its model, and the routes of the chosen mode. */+export function DelegationRoutingSection({ scope }: { scope: ProfileScope }) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing+ const query = useDelegationRouting(scope)+ const routing = query.data++ if (routing === null) {+ return null+ }++ return (+ <>+ <SettingsSection icon={GitFork} title={r.title}>+ <p className="mb-3 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">{r.intro}</p>+ {routing ? (+ <RoutingBody routing={routing} scope={scope} />+ ) : query.isError ? (+ <div className="flex items-center gap-2" role="status">+ <p className="text-xs text-muted-foreground">{r.loadFailed}</p>+ <Button disabled={query.isFetching} onClick={() => void query.refetch()} size="xs" variant="secondary">+ {t.common.retry}+ </Button>+ </div>+ ) : (+ <div className="grid gap-1.5">+ {MODES.map(mode => (+ <Skeleton className="h-14 rounded-lg" key={mode} />+ ))}+ </div>+ )}+ </SettingsSection>+ <SectionHeading icon={SlidersHorizontal} title={r.settingsTitle} />+ </>+ )+}++function RoutingBody({ routing, scope }: { routing: DelegationRouting; scope: ProfileScope }) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing+ const mode = routing.configured+ const blocked = Boolean(routing.blocked_reason)+ const { providers } = useOwnerCatalog(scope)+ const providerNames = new Map(providers.map(p => [p.slug, p.name]))+ const pluginNeeded = (isPluginMode(mode) && blocked) || PLUGIN_MODES.some(option => !modeAvailable(routing, option))++ return (+ <>+ <div aria-label={r.title} className="grid gap-1.5" role="radiogroup">+ {modeChoices(routing).map(option => (+ <ModeOption+ available={modeAvailable(routing, option)}+ blocked={blocked && option === mode}+ key={option}+ mode={option}+ onChoose={() => void chooseDelegationMode(scope, option, r.modeFailed)}+ routing={routing}+ selected={option === mode}+ />+ ))}+ </div>+ {pluginNeeded ? <AdvancedDelegationStatus blocked={blocked && isPluginMode(mode)} scope={scope} /> : null}+ {blocked && !isPluginMode(mode) && <BlockedBanner message={thirdPartyBlockedMessage(routing, r)} scope={scope} />}+ {mode === 'model_map' && (+ <div className="mt-6">+ <ModelRoutesEditor providerNames={providerNames} routes={routing.model_map} scope={scope} />+ </div>+ )}+ {mode === 'profile_routes' && (+ <div className="mt-6">+ <ProfileRoutesEditor profiles={routing.profiles} routes={routing.profile_routes} scope={scope} />+ </div>+ )}+ </>+ )+}++/** A saved third-party backend that cannot run: registered but unavailable, or no plugin provides it at all. */+function thirdPartyBlockedMessage(routing: DelegationRouting, r: DelegationRoutingTranslations): string {+ const backend = routing.backends.find(b => b.name === routing.configured)++ return backend ? r.blockedUnavailable(backend.label || backend.name) : r.blockedUnregistered(routing.configured)+}++/** Label + description of a picker row: the copy of a mode the page edits, else the plugin backend's own. */+function modeCopy(routing: DelegationRouting, mode: string, r: DelegationRoutingTranslations) {+ if (mode === 'default' || isPluginMode(mode)) {+ return r.modes[mode]+ }++ const backend = routing.backends.find(b => b.name === mode)++ return { label: backend?.label || mode, description: backend?.description || r.thirdPartyDescription }+}++interface ModeOptionProps {+ routing: DelegationRouting+ mode: string+ selected: boolean+ blocked: boolean+ available: boolean+ onChoose: () => void+}++function ModeOption({ routing, mode, selected, blocked, available, onChoose }: ModeOptionProps) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing+ const copy = modeCopy(routing, mode, r)++ return (+ <div+ className={cn(+ 'rounded-lg border transition-colors hover:transition-none',+ selected+ ? blocked+ ? 'border-amber-500/50 bg-amber-500/5'+ : 'border-(--ui-stroke-secondary) bg-(--ui-bg-tertiary)'+ : 'border-(--ui-stroke-tertiary)',+ !selected && available && 'hover:bg-(--chrome-action-hover)'+ )}+ data-blocked={blocked || undefined}+ data-mode={mode}+ >+ <button+ aria-checked={selected}+ className="flex w-full items-start gap-3 px-3 py-2.5 text-left disabled:cursor-default"+ disabled={!available || selected}+ onClick={onChoose}+ role="radio"+ type="button"+ >+ <span+ aria-hidden+ className={cn(+ 'mt-0.5 grid size-4 shrink-0 place-items-center rounded-full border',+ selected+ ? 'border-primary bg-primary text-primary-foreground'+ : 'border-(--ui-stroke-primary) bg-background',+ !available && !selected && 'opacity-60'+ )}+ >+ {selected && <Check className="size-2.5" />}+ </span>+ <span className="grid min-w-0 gap-0.5">+ <span className="flex flex-wrap items-center gap-2">+ <span+ className={cn(+ 'text-[length:var(--conversation-text-font-size)] font-medium',+ available || selected ? 'text-foreground' : 'text-(--ui-text-secondary)'+ )}+ >+ {copy.label}+ </span>+ {selected && (blocked ? <Pill tone="warn">{r.blockedPill}</Pill> : <Pill tone="primary">{r.inUse}</Pill>)}+ {mode !== 'default' && (!available || !isPluginMode(mode)) && !blocked && (+ <Pill tone="muted">+ <Plug className="size-3" />+ {r.plugin}+ </Pill>+ )}+ </span>+ <span className="text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-tertiary)">+ {copy.description}+ </span>+ </span>+ </button>+ </div>+ )+}++/** The saved mode cannot run, so core refuses every subagent: say so, the fix, and the way back to Default. */+function BlockedBanner({ message, action, scope }: { message: string; action?: ReactNode; scope: ProfileScope }) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing++ return (+ <div+ className="mt-2 flex flex-wrap items-start gap-x-3 gap-y-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2.5"+ data-slot="delegation-blocked"+ role="alert"+ >+ <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-300" />+ <div className="grid min-w-0 flex-1 basis-64 gap-0.5">+ <span className="text-[length:var(--conversation-text-font-size)] font-medium text-foreground">{message}</span>+ <span className="text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-secondary)">+ {r.blockedDetail}+ </span>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {action}+ <Button onClick={() => void chooseDelegationMode(scope, 'default', r.modeFailed)} size="sm" variant="secondary">+ {r.useDefault}+ </Button>+ </div>+ </div>+ )+}++/** Where the Advanced Delegation plugin stands for the owner: a hint under the picker, or, when the saved mode+ * is one of its own, the blocked banner with the fix (Install / Turn on / restart). */+function AdvancedDelegationStatus({ blocked, scope }: { blocked: boolean; scope: ProfileScope }) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing+ const { requestGateway } = useGatewayRequest()+ const owner = useStore($settingsRequestProfile) ?? null+ const { row, state } = useAdvancedDelegationPlugin(requestGateway, owner)++ if (state === 'loading') {+ return blocked ? <BlockedBanner message={r.blockedMissing} scope={scope} /> : null+ }++ const action =+ state === 'missing' ? (+ <Button onClick={() => void installAdvancedDelegation(owner, r.installUnavailable)} size="sm" variant="outline">+ {r.installPlugin}+ </Button>+ ) : state === 'disabled' && row?.key ? (+ <Button+ onClick={() =>+ void enableAdvancedDelegation(requestGateway, row.key!, owner, r.enableFailed).then(ok => {+ if (ok) {+ void refreshDelegationRouting(scope)+ }+ })+ }+ size="sm"+ variant="outline"+ >+ {r.enablePlugin}+ </Button>+ ) : null++ if (blocked) {+ const message = { disabled: r.blockedDisabled, missing: r.blockedMissing, not_loaded: r.blockedNotLoaded }[state]++ return <BlockedBanner action={action} message={message} scope={scope} />+ }++ const message = { disabled: r.pluginDisabled, missing: r.pluginMissing, not_loaded: r.pluginNotLoaded }[state]++ return (+ <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1.5 px-1" data-slot="delegation-plugin-hint">+ <Plug className="size-3.5 shrink-0 text-(--ui-text-tertiary)" />+ <span className="text-xs text-(--ui-text-secondary)">{message}</span>+ {action}+ </div>+ )+}diff --git a/apps/desktop/src/app/settings/delegation/subagent-model-gate.tsx b/apps/desktop/src/app/settings/delegation/subagent-model-gate.tsxnew file mode 100644index 00000000000..139cb288028--- /dev/null+++ b/apps/desktop/src/app/settings/delegation/subagent-model-gate.tsx@@ -0,0 +1,67 @@+import type { ReactNode } from 'react'++import type { DelegationRouting } from '@/api/delegation'+import { Button } from '@/components/ui/button'+import type { ProfileScope } from '@/hermes'+import { useI18n } from '@/i18n'+import type { DelegationRoutingTranslations } from '@/i18n/types_delegation_routing'+import { Info } from '@/lib/icons'++import { chooseDelegationMode, routesOwnSubagentModel, useDelegationRouting } from './routing-data'++/** Why the subagent model does not apply in the saved mode, and what a task that picks no route runs on. */+function inactiveReason(routing: DelegationRouting, r: DelegationRoutingTranslations): string {+ const mode = routing.configured++ if (mode === 'model_map') {+ const route = routing.model_map.default++ return route ? r.inactiveModelMap(route) : r.inactiveModelMapNoDefault+ }++ if (mode === 'profile_routes') {+ const profile = routing.profile_routes.default++ return profile ? r.inactiveProfiles(profile) : r.inactiveProfilesNoDefault+ }++ return r.inactivePlugin(routing.backends.find(b => b.name === mode)?.label || mode)+}++/**+ * The subagent model/provider rows (`delegation.model` / `delegation.provider`) in any mode but Default:+ * shown, but visibly inert, with the one line that says why and the way back.+ */+export function SubagentModelGate({ scope, children }: { scope: ProfileScope; children: ReactNode }) {+ const { t } = useI18n()+ const r = t.settings.model.subagents.routing+ const { data: routing } = useDelegationRouting(scope)++ if (!routing || !routesOwnSubagentModel(routing)) {+ return children+ }++ const reason = inactiveReason(routing, r)++ return (+ <div data-slot="subagent-model-inactive">+ <div className="mt-2 flex items-start gap-2.5 rounded-md bg-(--ui-bg-quaternary) px-3 py-2.5" role="note">+ <Info className="mt-0.5 size-4 shrink-0 text-(--ui-text-tertiary)" />+ <div className="grid min-w-0 flex-1 gap-0.5">+ <span className="text-[length:var(--conversation-text-font-size)] font-medium text-foreground">+ {r.inactiveTitle}+ </span>+ <span className="text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-tertiary)">+ {reason}+ </span>+ </div>+ <Button onClick={() => void chooseDelegationMode(scope, 'default', r.modeFailed)} size="xs" variant="secondary">+ {r.useDefault}+ </Button>+ </div>+ <div aria-disabled className="pointer-events-none opacity-45 select-none" inert>+ {children}+ </div>+ </div>+ )+}diff --git a/apps/desktop/src/app/settings/model-select.tsx b/apps/desktop/src/app/settings/model-select.tsxindex 385fec618a4..3bb4c225f4e 100644--- a/apps/desktop/src/app/settings/model-select.tsx+++ b/apps/desktop/src/app/settings/model-select.tsx@@ -32,6 +32,7 @@ export const fromItemValue = (item: string): string | null =>interface ModelSelectProps {'aria-label'?: string+ 'aria-invalid'?: booleanclassName?: string/** The provider's catalog row when known: the typed id is remembered under* it and made visible in the pickers. Absent (provider not in the catalog)@@ -52,6 +53,7 @@ interface ModelSelectProps {*/export function ModelSelect({'aria-label': ariaLabel,+ 'aria-invalid': ariaInvalid,className,models,onValueChange,@@ -95,6 +97,7 @@ export function ModelSelect({if (typing) {return (<Input+ aria-invalid={ariaInvalid}aria-label={ariaLabel}className={cn(CONTROL_TEXT, 'font-mono')}containerClassName={className}@@ -140,7 +143,7 @@ export function ModelSelect({}}value={toItemValue(value)}>- <SelectTrigger aria-label={ariaLabel} className={cn(className, CONTROL_TEXT)}>+ <SelectTrigger aria-invalid={ariaInvalid} aria-label={ariaLabel} className={cn(className, CONTROL_TEXT)}><SelectValue placeholder={m.model} /></SelectTrigger><SelectContent>diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.tsindex 2eb0101ad24..4a1fd216cab 100644--- a/apps/desktop/src/hermes.ts+++ b/apps/desktop/src/hermes.ts@@ -19,6 +19,7 @@ export {export type { ProfileScope, ResolvedOwner } from './api/client'export * from './api/config'export * from './api/cron'+export * from './api/delegation'export * from './api/local-models'export * from './api/mcp'export * from './api/messaging'diff --git a/apps/desktop/src/i18n/ar_delegation_routing.ts b/apps/desktop/src/i18n/ar_delegation_routing.tsnew file mode 100644index 00000000000..762adb920d2--- /dev/null+++ b/apps/desktop/src/i18n/ar_delegation_routing.ts@@ -0,0 +1,93 @@+import type { DelegationRoutingTranslations } from './types_delegation_routing'++export const arDelegationRouting: DelegationRoutingTranslations = {+ title: 'التوجيه',+ settingsTitle: 'الإعدادات الافتراضية للوكلاء الفرعيين',+ intro: 'كيف يحصل كل وكيل فرعي على نموذجه.',+ modes: {+ default: { label: 'افتراضي', description: 'يعمل كل وكيل فرعي بنموذج الوكيل الفرعي أدناه.' },+ model_map: { label: 'مسارات النماذج', description: 'سمِّ بضعة نماذج، ويختار الوكيل واحدًا منها لكل وكيل فرعي.' },+ profile_routes: {+ label: 'مسارات الملفات الشخصية',+ description: 'يعمل الوكلاء الفرعيون بأحد ملفاتك الشخصية، بنموذجه ومهاراته ومفاتيحه الخاصة.'+ }+ },+ inUse: 'قيد الاستخدام',+ plugin: 'إضافة',+ pluginMissing: 'مسارات النماذج ومسارات الملفات الشخصية مصدرها الإضافة Advanced Delegation.',+ pluginDisabled: 'الإضافة Advanced Delegation مثبتة لكنها متوقفة لهذا الملف الشخصي.',+ pluginNotLoaded: 'الإضافة Advanced Delegation مفعّلة، لكن Hermes لم يحمّلها بعد. أعد تشغيل Hermes لإكمال ذلك.',+ installPlugin: 'تثبيت الإضافة',+ installUnavailable: 'الإضافة Advanced Delegation ليست في كتالوج الإضافات بعد. ثبّتها من المهارات ← الإضافات.',+ enablePlugin: 'تفعيل',+ enableFailed: 'تعذّر تفعيل Advanced Delegation',+ modeFailed: 'تعذّر تغيير توجيه الوكلاء الفرعيين',+ loadFailed: 'تعذّر تحميل توجيه الوكلاء الفرعيين',+ blockedPill: 'لا يعمل',+ blockedDetail: 'هذا الوضع محفوظ، لذا يرفض Hermes كل وكيل فرعي بدلًا من استخدام الوضع الافتراضي بصمت.',+ blockedMissing: 'لن يبدأ الوكلاء الفرعيون حتى تُثبَّت الإضافة Advanced Delegation.',+ blockedDisabled: 'لن يبدأ الوكلاء الفرعيون حتى تُفعَّل الإضافة Advanced Delegation لهذا الملف الشخصي.',+ blockedNotLoaded:+ 'لن يبدأ الوكلاء الفرعيون حتى يحمّل Hermes الإضافة Advanced Delegation. أعد تشغيل Hermes لإكمال ذلك.',+ blockedUnavailable: label => `لن يبدأ الوكلاء الفرعيون حتى يتمكن ${label} من العمل هنا. تفيد إضافته بأنه لا يستطيع.`,+ blockedUnregistered: name => `لن يبدأ الوكلاء الفرعيون حتى تُثبَّت وتُفعَّل إضافة توفّر «${name}».`,+ thirdPartyDescription: 'من إضافة. إعداداته موجودة في تلك الإضافة.',++ modelRoutesTitle: 'مسارات النماذج',+ modelRoutesEmpty: 'لا توجد مسارات بعد. إلى أن تضيف مسارًا، يستخدم الوكلاء الفرعيون نموذج الوكيل الرئيسي.',+ addRoute: 'إضافة مسار',+ editRoute: 'تعديل',+ makeDefault: 'تعيين كافتراضي',+ deleteRoute: 'حذف',+ defaultBadge: 'افتراضي',+ routeActions: name => `إجراءات ${name}`,+ deleteConfirmTitle: name => `حذف المسار «${name}»؟`,+ deleteConfirmBody: 'لن يتمكن الوكلاء الفرعيون من اختياره بعد الآن.',+ deleteConfirmNextDefault: name => `هذا هو المسار الافتراضي، لذا يصبح «${name}» هو الافتراضي.`,+ deleteConfirmAction: 'حذف المسار',+ saveFailed: 'تعذّر حفظ المسارات',+ baseUrlRoute: url => `نقطة النهاية ${url}`,++ dialogNew: 'مسار نموذج جديد',+ dialogEdit: 'تعديل مسار النموذج',+ dialogDesc: 'يقرأ الوكيل الاسم والوصف ليقرر أي مسار يسلكه الوكيل الفرعي.',+ nameLabel: 'الاسم',+ namePlaceholder: 'مثال: fast',+ nameHint: 'قصير، بلا مسافات. يختار الوكيل المسارات بهذا الاسم.',+ descriptionLabel: 'متى يُستخدم',+ descriptionPlaceholder: 'مثال: رخيص وسريع: عمليات البحث، والملخصات، والتعديلات البسيطة.',+ descriptionHint: 'سطر واحد يقرؤه الوكيل قبل الاختيار.',+ providerLabel: 'المزوّد',+ providerPlaceholder: 'اختر مزوّدًا',+ modelLabel: 'النموذج',+ effortLabel: 'مستوى الاستدلال',+ effortInherit: 'الافتراضي للوكيل الفرعي',+ tierLabel: 'السرعة',+ tierNormal: 'عادية (افتراضي)',+ tierFast: 'سريعة',+ tierUltrafast: 'فائقة السرعة',+ tierHint: 'فقط في النماذج التي توفرها.',+ optional: 'اختياري',+ errors: { required: 'مطلوب', spaces: 'بلا مسافات', duplicate: 'مسار آخر يستخدم هذا الاسم بالفعل' },+ saveRoute: 'حفظ المسار',+ createRoute: 'إضافة مسار',++ profileRoutesTitle: 'الملفات الشخصية التي يمكن للوكلاء الفرعيين العمل بها',+ profileRoutesHint: 'يجلب كل ملف شخصي محدد نموذجه ومهاراته وشخصيته ومفاتيحه الخاصة.',+ profileDescriptionPlaceholder: 'متى يُستخدم (اختياري)',+ profileDefault: 'افتراضي',+ profileEmpty: 'لا توجد ملفات شخصية أخرى بعد. أنشئ واحدًا من شريط الملفات الشخصية.',+ profileMissing: name => `${name} (لم يعد الملف الشخصي موجودًا)`,++ inactiveTitle: 'غير مستخدم في هذا الوضع',+ inactiveModelMap: route =>+ `تختار مسارات النماذج نموذج كل وكيل فرعي. الوكلاء الفرعيون الذين لا يختارون مسارًا يستخدمون «${route}».`,+ inactiveProfiles: profile =>+ `تختار مسارات الملفات الشخصية ملف كل وكيل فرعي. الوكلاء الفرعيون الذين لا يختارون ملفًا شخصيًا يعملون بـ «${profile}».`,+ inactiveModelMapNoDefault:+ 'تختار مسارات النماذج نموذج كل وكيل فرعي. الوكلاء الفرعيون الذين لا يختارون مسارًا يستخدمون نموذج الوكيل الرئيسي.',+ inactiveProfilesNoDefault:+ 'تختار مسارات الملفات الشخصية ملف كل وكيل فرعي. الوكلاء الفرعيون الذين لا يختارون ملفًا شخصيًا يستخدمون نموذج الوكيل الرئيسي.',+ inactivePlugin: label => `${label} يحدد نموذج كل وكيل فرعي، لذا لا ينطبق هذا الإعداد.`,+ useDefault: 'التبديل إلى الافتراضي'+}diff --git a/apps/desktop/src/i18n/ar_settings.ts b/apps/desktop/src/i18n/ar_settings.tsindex 959ca16f753..b4abecce802 100644--- a/apps/desktop/src/i18n/ar_settings.ts+++ b/apps/desktop/src/i18n/ar_settings.ts@@ -1,3 +1,4 @@+import { arDelegationRouting } from './ar_delegation_routing'import { arUpdateChannel } from './ar_update_channel'import type { TranslationOverrides } from './define-locale'@@ -854,7 +855,8 @@ export const arSettings = {'نقطة نهاية مباشرة مفعّلة ولها الأولوية على الموفّر المحفوظ. يُحتفظ بعنوانها وبيانات اعتمادها ما دام هذا الوضع محددًا.',directClear: 'تطبيق هذا المسار يمسح نقطة النهاية المباشرة ومفتاحها المحفوظ. تبقى إعدادات الطلب الأخرى كما هي.',catalogFailed: 'كتالوج النماذج غير متاح. أدخل الموفّر والنموذج يدويًا أو أعد المحاولة.',- draftHint: 'تبقى التغييرات محلية حتى تطبيقها.'+ draftHint: 'تبقى التغييرات محلية حتى تطبيقها.',+ routing: arDelegationRouting}},providers: {diff --git a/apps/desktop/src/i18n/de_delegation_routing.ts b/apps/desktop/src/i18n/de_delegation_routing.tsnew file mode 100644index 00000000000..97be847fc41--- /dev/null+++ b/apps/desktop/src/i18n/de_delegation_routing.ts@@ -0,0 +1,105 @@+import type { DelegationRoutingTranslations } from './types_delegation_routing'++export const deDelegationRouting: DelegationRoutingTranslations = {+ title: 'Routing',+ settingsTitle: 'Subagent-Standards',+ intro: 'Wie jeder Subagent sein Modell erhält.',+ modes: {+ default: { label: 'Standard', description: 'Jeder Subagent läuft mit dem Subagent-Modell unten.' },+ model_map: {+ label: 'Modellrouten',+ description: 'Benennen Sie einige Modelle. Der Agent wählt für jeden Subagenten eines aus.'+ },+ profile_routes: {+ label: 'Profilrouten',+ description: 'Subagenten laufen als eines Ihrer Profile, mit dessen eigenem Modell, Skills und Schlüsseln.'+ }+ },+ inUse: 'Aktiv',+ plugin: 'Plugin',+ pluginMissing: 'Modellrouten und Profilrouten stammen aus dem Plugin Advanced Delegation.',+ pluginDisabled: 'Advanced Delegation ist installiert, aber für dieses Profil ausgeschaltet.',+ pluginNotLoaded:+ 'Advanced Delegation ist eingeschaltet, wurde von Hermes aber noch nicht geladen. Starten Sie Hermes neu, um den Vorgang abzuschließen.',+ installPlugin: 'Plugin installieren',+ installUnavailable:+ 'Advanced Delegation ist noch nicht im Plugin-Katalog. Installieren Sie es über Fähigkeiten › Plugins.',+ enablePlugin: 'Einschalten',+ enableFailed: 'Advanced Delegation konnte nicht eingeschaltet werden',+ modeFailed: 'Subagent-Routing konnte nicht geändert werden',+ loadFailed: 'Subagent-Routing konnte nicht geladen werden',+ blockedPill: 'Läuft nicht',+ blockedDetail:+ 'Dieser Modus ist gespeichert, daher lehnt Hermes jeden Subagenten ab, statt stillschweigend Standard zu verwenden.',+ blockedMissing: 'Subagenten starten erst, wenn Advanced Delegation installiert ist.',+ blockedDisabled: 'Subagenten starten erst, wenn Advanced Delegation für dieses Profil eingeschaltet ist.',+ blockedNotLoaded:+ 'Subagenten starten erst, wenn Hermes Advanced Delegation geladen hat. Starten Sie Hermes neu, um den Vorgang abzuschließen.',+ blockedUnavailable: label =>+ `Subagenten starten erst, wenn ${label} hier laufen kann. Sein Plugin meldet, dass es das nicht kann.`,+ blockedUnregistered: name =>+ `Subagenten starten erst, wenn ein Plugin, das „${name}“ bereitstellt, installiert und eingeschaltet ist.`,+ thirdPartyDescription: 'Stammt aus einem Plugin. Seine Einstellungen liegen bei diesem Plugin.',++ modelRoutesTitle: 'Modellrouten',+ modelRoutesEmpty: 'Noch keine Routen. Bis Sie eine hinzufügen, verwenden Subagenten das Modell des Hauptagenten.',+ addRoute: 'Route hinzufügen',+ editRoute: 'Bearbeiten',+ makeDefault: 'Als Standard festlegen',+ deleteRoute: 'Löschen',+ defaultBadge: 'Standard',+ routeActions: name => `Aktionen für ${name}`,+ deleteConfirmTitle: name => `Route „${name}“ löschen?`,+ deleteConfirmBody: 'Subagenten können sie dann nicht mehr wählen.',+ deleteConfirmNextDefault: name => `Sie ist die Standardroute, daher wird „${name}“ zum Standard.`,+ deleteConfirmAction: 'Route löschen',+ saveFailed: 'Routen konnten nicht gespeichert werden',+ baseUrlRoute: url => `Endpunkt ${url}`,++ dialogNew: 'Neue Modellroute',+ dialogEdit: 'Modellroute bearbeiten',+ dialogDesc: 'Der Agent liest Name und Beschreibung, um zu entscheiden, welche Route ein Subagent nimmt.',+ nameLabel: 'Name',+ namePlaceholder: 'z. B. fast',+ nameHint: 'Kurz, ohne Leerzeichen. Der Agent wählt Routen anhand dieses Namens.',+ descriptionLabel: 'Wann sie genutzt wird',+ descriptionPlaceholder: 'z. B. Günstig und schnell: Nachschlagen, Zusammenfassungen, einfache Änderungen.',+ descriptionHint: 'Eine Zeile, die der Agent vor der Wahl liest.',+ providerLabel: 'Anbieter',+ providerPlaceholder: 'Anbieter wählen',+ modelLabel: 'Modell',+ effortLabel: 'Denkanstrengung',+ effortInherit: 'Subagent-Standard',+ tierLabel: 'Geschwindigkeit',+ tierNormal: 'Normal (Standard)',+ tierFast: 'Schnell',+ tierUltrafast: 'Ultraschnell',+ tierHint: 'Nur bei Modellen, die das anbieten.',+ optional: 'optional',+ errors: {+ required: 'Erforderlich',+ spaces: 'Keine Leerzeichen',+ duplicate: 'Eine andere Route verwendet diesen Namen bereits'+ },+ saveRoute: 'Route speichern',+ createRoute: 'Route hinzufügen',++ profileRoutesTitle: 'Profile, als die Subagenten laufen können',+ profileRoutesHint: 'Jedes ausgewählte Profil bringt sein eigenes Modell, Skills, Persona und Schlüssel mit.',+ profileDescriptionPlaceholder: 'Wann es genutzt wird (optional)',+ profileDefault: 'Standard',+ profileEmpty: 'Noch keine weiteren Profile. Erstellen Sie eines über die Profil-Leiste.',+ profileMissing: name => `${name} (Profil existiert nicht mehr)`,++ inactiveTitle: 'In diesem Modus nicht verwendet',+ inactiveModelMap: route =>+ `Modellrouten wählen das Modell jedes Subagenten. Subagenten ohne gewählte Route verwenden „${route}“.`,+ inactiveProfiles: profile =>+ `Profilrouten wählen das Profil jedes Subagenten. Subagenten ohne gewähltes Profil laufen als „${profile}“.`,+ inactiveModelMapNoDefault:+ 'Modellrouten wählen das Modell jedes Subagenten. Subagenten ohne Route verwenden das Modell des Hauptagenten.',+ inactiveProfilesNoDefault:+ 'Profilrouten wählen das Profil jedes Subagenten. Subagenten ohne Profil verwenden das Modell des Hauptagenten.',+ inactivePlugin: label => `${label} legt das Modell jedes Subagenten fest, daher gilt diese Einstellung nicht.`,+ useDefault: 'Zu Standard wechseln'+}diff --git a/apps/desktop/src/i18n/de_model_settings.ts b/apps/desktop/src/i18n/de_model_settings.tsindex 39574e22a16..b025d06d4df 100644--- a/apps/desktop/src/i18n/de_model_settings.ts+++ b/apps/desktop/src/i18n/de_model_settings.ts@@ -1,6 +1,7 @@import type { TranslationOverride } from '@hermes/shared/i18n'import { deAuxTasks } from './de_aux_tasks'+import { deDelegationRouting } from './de_delegation_routing'import type { ModelSettingsTranslations } from './types_model_settings'export const deModelSettings: TranslationOverride<ModelSettingsTranslations> = {@@ -80,6 +81,7 @@ export const deModelSettings: TranslationOverride<ModelSettingsTranslations> = {directClear:'Diese Route entfernt den direkten Endpunkt und seinen gespeicherten Schlüssel. Andere Anfrage-Einstellungen bleiben erhalten.',catalogFailed: 'Modellkatalog nicht verfügbar. Anbieter und Modell manuell eingeben oder erneut versuchen.',- draftHint: 'Änderungen bleiben lokal, bis sie übernommen werden.'+ draftHint: 'Änderungen bleiben lokal, bis sie übernommen werden.',+ routing: deDelegationRouting}}diff --git a/apps/desktop/src/i18n/en_delegation_routing.ts b/apps/desktop/src/i18n/en_delegation_routing.tsnew file mode 100644index 00000000000..6d390ccd8f2--- /dev/null+++ b/apps/desktop/src/i18n/en_delegation_routing.ts@@ -0,0 +1,92 @@+import type { DelegationRoutingTranslations } from './types_delegation_routing'++export const enDelegationRouting: DelegationRoutingTranslations = {+ title: 'Routing',+ settingsTitle: 'Subagent defaults',+ intro: 'How each subagent gets its model.',+ modes: {+ default: { label: 'Default', description: 'Every subagent runs on the subagent model below.' },+ model_map: { label: 'Model routes', description: 'Name a few models. The agent picks one for each subagent.' },+ profile_routes: {+ label: 'Profile routes',+ description: 'Subagents run as one of your profiles, with its own model, skills and keys.'+ }+ },+ inUse: 'In use',+ plugin: 'Plugin',+ pluginMissing: 'Model routes and Profile routes come from the Advanced Delegation plugin.',+ pluginDisabled: 'Advanced Delegation is installed but turned off for this profile.',+ pluginNotLoaded: 'Advanced Delegation is on, but Hermes has not loaded it yet. Restart Hermes to finish.',+ installPlugin: 'Install plugin',+ installUnavailable: 'Advanced Delegation is not in the plugin catalog yet. Install it from Capabilities › Plugins.',+ enablePlugin: 'Turn on',+ enableFailed: 'Could not turn on Advanced Delegation',+ modeFailed: 'Could not change subagent routing',+ loadFailed: 'Could not load subagent routing',+ blockedPill: 'Not running',+ blockedDetail: 'This mode is saved, so Hermes refuses every subagent instead of quietly using Default.',+ blockedMissing: 'Subagents will not start until Advanced Delegation is installed.',+ blockedDisabled: 'Subagents will not start until Advanced Delegation is turned on for this profile.',+ blockedNotLoaded: 'Subagents will not start until Hermes loads Advanced Delegation. Restart Hermes to finish.',+ blockedUnavailable: label => `Subagents will not start until ${label} can run here. Its plugin reports it cannot.`,+ blockedUnregistered: name =>+ `Subagents will not start until a plugin that provides “${name}” is installed and turned on.`,+ thirdPartyDescription: 'From a plugin. Its settings live with that plugin.',++ modelRoutesTitle: 'Model routes',+ modelRoutesEmpty: "No routes yet. Until you add one, subagents use the main agent's model.",+ addRoute: 'Add route',+ editRoute: 'Edit',+ makeDefault: 'Make default',+ deleteRoute: 'Delete',+ defaultBadge: 'Default',+ routeActions: name => `Actions for ${name}`,+ deleteConfirmTitle: name => `Delete route “${name}”?`,+ deleteConfirmBody: 'Subagents can no longer pick it.',+ deleteConfirmNextDefault: name => `It is the default route, so “${name}” becomes the default.`,+ deleteConfirmAction: 'Delete route',+ saveFailed: 'Could not save routes',+ baseUrlRoute: url => `endpoint ${url}`,++ dialogNew: 'New model route',+ dialogEdit: 'Edit model route',+ dialogDesc: 'The agent reads the name and description to decide which route a subagent takes.',+ nameLabel: 'Name',+ namePlaceholder: 'e.g. fast',+ nameHint: 'Short, no spaces. The agent picks routes by this name.',+ descriptionLabel: 'When to use it',+ descriptionPlaceholder: 'e.g. Cheap and quick: lookups, summaries, simple edits.',+ descriptionHint: 'One line the agent reads before choosing.',+ providerLabel: 'Provider',+ providerPlaceholder: 'Choose a provider',+ modelLabel: 'Model',+ effortLabel: 'Reasoning effort',+ effortInherit: 'Subagent default',+ tierLabel: 'Speed',+ tierNormal: 'Normal (default)',+ tierFast: 'Fast',+ tierUltrafast: 'Ultrafast',+ tierHint: 'Only on models that offer it.',+ optional: 'optional',+ errors: { required: 'Required', spaces: 'No spaces', duplicate: 'Another route already uses this name' },+ saveRoute: 'Save route',+ createRoute: 'Add route',++ profileRoutesTitle: 'Profiles subagents can run as',+ profileRoutesHint: 'Each checked profile brings its own model, skills, persona and keys.',+ profileDescriptionPlaceholder: 'When to use it (optional)',+ profileDefault: 'Default',+ profileEmpty: 'No other profiles yet. Create one from the profile rail.',+ profileMissing: name => `${name} (profile no longer exists)`,++ inactiveTitle: 'Not used in this mode',+ inactiveModelMap: route => `Model routes pick each subagent's model. Subagents that pick no route use “${route}”.`,+ inactiveProfiles: profile =>+ `Profile routes pick each subagent's profile. Subagents that pick no profile run as “${profile}”.`,+ inactiveModelMapNoDefault:+ "Model routes pick each subagent's model. Subagents that pick no route use the main agent's model.",+ inactiveProfilesNoDefault:+ "Profile routes pick each subagent's profile. Subagents that pick no profile use the main agent's model.",+ inactivePlugin: label => `${label} decides each subagent's model, so this setting does not apply.`,+ useDefault: 'Switch to Default'+}diff --git a/apps/desktop/src/i18n/en_model_settings.ts b/apps/desktop/src/i18n/en_model_settings.tsindex 174bb8dde80..e1da036c878 100644--- a/apps/desktop/src/i18n/en_model_settings.ts+++ b/apps/desktop/src/i18n/en_model_settings.ts@@ -1,4 +1,5 @@import { enAuxTasks } from './en_aux_tasks'+import { enDelegationRouting } from './en_delegation_routing'import type { ModelSettingsTranslations } from './types_model_settings'export const enModelSettings: ModelSettingsTranslations = {@@ -73,6 +74,7 @@ export const enModelSettings: ModelSettingsTranslations = {'A direct endpoint is active and takes precedence over the saved provider. Its endpoint and credentials are kept while this mode is selected.',directClear: 'Applying this route clears the direct endpoint and its stored key. Other request settings are kept.',catalogFailed: 'Model catalog unavailable. Enter a provider and model manually, or retry.',- draftHint: 'Changes stay local until applied.'+ draftHint: 'Changes stay local until applied.',+ routing: enDelegationRouting}}diff --git a/apps/desktop/src/i18n/es_delegation_routing.ts b/apps/desktop/src/i18n/es_delegation_routing.tsnew file mode 100644index 00000000000..ff6fc4d2c8c--- /dev/null+++ b/apps/desktop/src/i18n/es_delegation_routing.ts@@ -0,0 +1,104 @@+import type { DelegationRoutingTranslations } from './types_delegation_routing'++export const esDelegationRouting: DelegationRoutingTranslations = {+ title: 'Enrutamiento',+ settingsTitle: 'Valores predeterminados de subagentes',+ intro: 'Cómo obtiene su modelo cada subagente.',+ modes: {+ default: {+ label: 'Predeterminado',+ description: 'Todos los subagentes usan el modelo de subagente de abajo.'+ },+ model_map: {+ label: 'Rutas de modelo',+ description: 'Nombra algunos modelos. El agente elige uno para cada subagente.'+ },+ profile_routes: {+ label: 'Rutas de perfil',+ description: 'Los subagentes se ejecutan como uno de tus perfiles, con su propio modelo, habilidades y claves.'+ }+ },+ inUse: 'En uso',+ plugin: 'Plugin',+ pluginMissing: 'Rutas de modelo y Rutas de perfil provienen del plugin Advanced Delegation.',+ pluginDisabled: 'Advanced Delegation está instalado, pero desactivado para este perfil.',+ pluginNotLoaded:+ 'Advanced Delegation está activado, pero Hermes aún no lo ha cargado. Reinicia Hermes para terminar.',+ installPlugin: 'Instalar plugin',+ installUnavailable:+ 'Advanced Delegation aún no está en el catálogo de plugins. Instálalo desde Capacidades › Plugins.',+ enablePlugin: 'Activar',+ enableFailed: 'No se pudo activar Advanced Delegation',+ modeFailed: 'No se pudo cambiar el enrutamiento de subagentes',+ loadFailed: 'No se pudo cargar el enrutamiento de subagentes',+ blockedPill: 'No funciona',+ blockedDetail:+ 'Este modo está guardado, así que Hermes rechaza cada subagente en lugar de usar Predeterminado sin avisar.',+ blockedMissing: 'Los subagentes no se iniciarán hasta que Advanced Delegation esté instalado.',+ blockedDisabled: 'Los subagentes no se iniciarán hasta que Advanced Delegation esté activado para este perfil.',+ blockedNotLoaded:+ 'Los subagentes no se iniciarán hasta que Hermes cargue Advanced Delegation. Reinicia Hermes para terminar.',+ blockedUnavailable: label =>+ `Los subagentes no se iniciarán hasta que ${label} pueda funcionar aquí. Su plugin indica que no puede.`,+ blockedUnregistered: name =>+ `Los subagentes no se iniciarán hasta que se instale y active un plugin que proporcione «${name}».`,+ thirdPartyDescription: 'Proviene de un plugin. Sus ajustes están en ese plugin.',++ modelRoutesTitle: 'Rutas de modelo',+ modelRoutesEmpty: 'Aún no hay rutas. Hasta que añadas una, los subagentes usan el modelo del agente principal.',+ addRoute: 'Añadir ruta',+ editRoute: 'Editar',+ makeDefault: 'Hacer predeterminada',+ deleteRoute: 'Eliminar',+ defaultBadge: 'Predeterminada',+ routeActions: name => `Acciones para ${name}`,+ deleteConfirmTitle: name => `¿Eliminar la ruta “${name}”?`,+ deleteConfirmBody: 'Los subagentes ya no podrán elegirla.',+ deleteConfirmNextDefault: name => `Es la ruta predeterminada, así que “${name}” pasa a ser la predeterminada.`,+ deleteConfirmAction: 'Eliminar ruta',+ saveFailed: 'No se pudieron guardar las rutas',+ baseUrlRoute: url => `endpoint ${url}`,++ dialogNew: 'Nueva ruta de modelo',+ dialogEdit: 'Editar ruta de modelo',+ dialogDesc: 'El agente lee el nombre y la descripción para decidir qué ruta toma un subagente.',+ nameLabel: 'Nombre',+ namePlaceholder: 'p. ej. fast',+ nameHint: 'Corto, sin espacios. El agente elige las rutas por este nombre.',+ descriptionLabel: 'Cuándo usarla',+ descriptionPlaceholder: 'p. ej. Barato y rápido: búsquedas, resúmenes, ediciones sencillas.',+ descriptionHint: 'Una línea que el agente lee antes de elegir.',+ providerLabel: 'Proveedor',+ providerPlaceholder: 'Elige un proveedor',+ modelLabel: 'Modelo',+ effortLabel: 'Esfuerzo de razonamiento',+ effortInherit: 'Predeterminado del subagente',+ tierLabel: 'Velocidad',+ tierNormal: 'Normal (predeterminada)',+ tierFast: 'Rápida',+ tierUltrafast: 'Ultrarrápida',+ tierHint: 'Solo en modelos que la ofrecen.',+ optional: 'opcional',+ errors: { required: 'Obligatorio', spaces: 'Sin espacios', duplicate: 'Otra ruta ya usa este nombre' },+ saveRoute: 'Guardar ruta',+ createRoute: 'Añadir ruta',++ profileRoutesTitle: 'Perfiles como los que pueden ejecutarse los subagentes',+ profileRoutesHint: 'Cada perfil marcado aporta su propio modelo, habilidades, personalidad y claves.',+ profileDescriptionPlaceholder: 'Cuándo usarlo (opcional)',+ profileDefault: 'Predeterminado',+ profileEmpty: 'Aún no hay otros perfiles. Crea uno desde la barra de perfiles.',+ profileMissing: name => `${name} (el perfil ya no existe)`,++ inactiveTitle: 'No se usa en este modo',+ inactiveModelMap: route =>+ `Las rutas de modelo eligen el modelo de cada subagente. Los subagentes que no eligen ninguna ruta usan “${route}”.`,+ inactiveProfiles: profile =>+ `Las rutas de perfil eligen el perfil de cada subagente. Los subagentes que no eligen ningún perfil se ejecutan como “${profile}”.`,+ inactiveModelMapNoDefault:+ 'Las rutas de modelo eligen el modelo de cada subagente. Los subagentes que no eligen ruta usan el modelo del agente principal.',+ inactiveProfilesNoDefault:+ 'Las rutas de perfil eligen el perfil de cada subagente. Los subagentes que no eligen perfil usan el modelo del agente principal.',+ inactivePlugin: label => `${label} decide el modelo de cada subagente, así que este ajuste no se aplica.`,+ useDefault: 'Cambiar a Predeterminado'+}diff --git a/apps/desktop/src/i18n/es_model_settings.ts b/apps/desktop/src/i18n/es_model_settings.tsindex 2d37d642606..c402b882355 100644--- a/apps/desktop/src/i18n/es_model_settings.ts+++ b/apps/desktop/src/i18n/es_model_settings.ts@@ -1,6 +1,7 @@import type { TranslationOverride } from '@hermes/shared/i18n'import { esAuxTasks } from './es_aux_tasks'+import { esDelegationRouting } from './es_delegation_routing'import type { ModelSettingsTranslations } from './types_model_settings'export const esModelSettings: TranslationOverride<ModelSettingsTranslations> = {@@ -81,6 +82,7 @@ export const esModelSettings: TranslationOverride<ModelSettingsTranslations> = {directClear:'Aplicar esta ruta borra el endpoint directo y su clave guardada. El resto de ajustes de solicitud se conserva.',catalogFailed: 'Catálogo de modelos no disponible. Introduce un proveedor y un modelo manualmente, o reintenta.',- draftHint: 'Los cambios se quedan en local hasta que los apliques.'+ draftHint: 'Los cambios se quedan en local hasta que los apliques.',+ routing: esDelegationRouting}}diff --git a/apps/desktop/src/i18n/fr_delegation_routing.ts b/apps/desktop/src/i18n/fr_delegation_routing.tsnew file mode 100644index 00000000000..51b1003625e--- /dev/null+++ b/apps/desktop/src/i18n/fr_delegation_routing.ts@@ -0,0 +1,103 @@+import type { DelegationRoutingTranslations } from './types_delegation_routing'++export const frDelegationRouting: DelegationRoutingTranslations = {+ title: 'Routage',+ settingsTitle: 'Paramètres par défaut des sous-agents',+ intro: 'Comment chaque sous-agent obtient son modèle.',+ modes: {+ default: { label: 'Par défaut', description: 'Chaque sous-agent utilise le modèle sous-agent ci-dessous.' },+ model_map: {+ label: 'Routes de modèle',+ description: "Nommez quelques modèles. L'agent en choisit un pour chaque sous-agent."+ },+ profile_routes: {+ label: 'Routes de profil',+ description:+ "Les sous-agents s'exécutent sous l'un de vos profils, avec son propre modèle, ses skills et ses clés."+ }+ },+ inUse: 'Utilisé',+ plugin: 'Plugin',+ pluginMissing: 'Routes de modèle et Routes de profil proviennent du plugin Advanced Delegation.',+ pluginDisabled: 'Advanced Delegation est installé mais désactivé pour ce profil.',+ pluginNotLoaded:+ "Advanced Delegation est activé, mais Hermes ne l'a pas encore chargé. Redémarrez Hermes pour terminer.",+ installPlugin: 'Installer le plugin',+ installUnavailable:+ "Advanced Delegation n'est pas encore dans le catalogue de plugins. Installez-le depuis Capacités › Plugins.",+ enablePlugin: 'Activer',+ enableFailed: "Impossible d'activer Advanced Delegation",+ modeFailed: 'Impossible de modifier le routage des sous-agents',+ loadFailed: 'Impossible de charger le routage des sous-agents',+ blockedPill: 'Inactif',+ blockedDetail:+ 'Ce mode est enregistré : Hermes refuse donc chaque sous-agent au lieu de passer discrètement à Par défaut.',+ blockedMissing: 'Les sous-agents ne démarreront pas tant qu’Advanced Delegation n’est pas installé.',+ blockedDisabled: 'Les sous-agents ne démarreront pas tant qu’Advanced Delegation n’est pas activé pour ce profil.',+ blockedNotLoaded:+ 'Les sous-agents ne démarreront pas tant que Hermes n’a pas chargé Advanced Delegation. Redémarrez Hermes pour terminer.',+ blockedUnavailable: label =>+ `Les sous-agents ne démarreront pas tant que ${label} ne peut pas fonctionner ici. Son plugin indique qu’il ne le peut pas.`,+ blockedUnregistered: name =>+ `Les sous-agents ne démarreront pas tant qu’un plugin fournissant « ${name} » n’est pas installé et activé.`,+ thirdPartyDescription: 'Fourni par un plugin. Ses réglages se trouvent dans ce plugin.',++ modelRoutesTitle: 'Routes de modèle',+ modelRoutesEmpty:+ 'Aucune route pour l’instant. Tant que vous n’en ajoutez pas, les sous-agents utilisent le modèle de l’agent principal.',+ addRoute: 'Ajouter une route',+ editRoute: 'Modifier',+ makeDefault: 'Définir par défaut',+ deleteRoute: 'Supprimer',+ defaultBadge: 'Par défaut',+ routeActions: name => `Actions pour ${name}`,+ deleteConfirmTitle: name => `Supprimer la route « ${name} » ?`,+ deleteConfirmBody: 'Les sous-agents ne pourront plus la choisir.',+ deleteConfirmNextDefault: name => `C'est la route par défaut : « ${name} » devient donc la route par défaut.`,+ deleteConfirmAction: 'Supprimer la route',+ saveFailed: "Impossible d'enregistrer les routes",+ baseUrlRoute: url => `point de terminaison ${url}`,++ dialogNew: 'Nouvelle route de modèle',+ dialogEdit: 'Modifier la route de modèle',+ dialogDesc: "L'agent lit le nom et la description pour décider quelle route prend un sous-agent.",+ nameLabel: 'Nom',+ namePlaceholder: 'ex. fast',+ nameHint: "Court, sans espaces. L'agent choisit les routes par ce nom.",+ descriptionLabel: "Quand l'utiliser",+ descriptionPlaceholder: 'ex. Économique et rapide : recherches, résumés, modifications simples.',+ descriptionHint: "Une ligne que l'agent lit avant de choisir.",+ providerLabel: 'Fournisseur',+ providerPlaceholder: 'Choisir un fournisseur',+ modelLabel: 'Modèle',+ effortLabel: 'Intensité du raisonnement',+ effortInherit: 'Valeur par défaut des sous-agents',+ tierLabel: 'Vitesse',+ tierNormal: 'Normale (par défaut)',+ tierFast: 'Rapide',+ tierUltrafast: 'Ultra-rapide',+ tierHint: 'Uniquement sur les modèles qui la proposent.',+ optional: 'facultatif',+ errors: { required: 'Obligatoire', spaces: "Pas d'espaces", duplicate: 'Une autre route utilise déjà ce nom' },+ saveRoute: 'Enregistrer la route',+ createRoute: 'Ajouter une route',++ profileRoutesTitle: 'Profils sous lesquels les sous-agents peuvent tourner',+ profileRoutesHint: 'Chaque profil coché apporte son propre modèle, ses skills, sa persona et ses clés.',+ profileDescriptionPlaceholder: "Quand l'utiliser (facultatif)",+ profileDefault: 'Par défaut',+ profileEmpty: "Aucun autre profil pour l'instant. Créez-en un depuis la barre des profils.",+ profileMissing: name => `${name} (le profil n'existe plus)`,++ inactiveTitle: 'Inutilisé dans ce mode',+ inactiveModelMap: route =>+ `Les routes de modèle choisissent le modèle de chaque sous-agent. Les sous-agents qui ne choisissent aucune route utilisent « ${route} ».`,+ inactiveProfiles: profile =>+ `Les routes de profil choisissent le profil de chaque sous-agent. Les sous-agents qui ne choisissent aucun profil tournent sous « ${profile} ».`,+ inactiveModelMapNoDefault:+ 'Les routes de modèle choisissent le modèle de chaque sous-agent. Les sous-agents sans route utilisent le modèle de l’agent principal.',+ inactiveProfilesNoDefault:+ 'Les routes de profil choisissent le profil de chaque sous-agent. Les sous-agents sans profil utilisent le modèle de l’agent principal.',+ inactivePlugin: label => `${label} choisit le modèle de chaque sous-agent, ce réglage ne s’applique donc pas.`,+ useDefault: 'Passer à Par défaut'+}diff --git a/apps/desktop/src/i18n/fr_model_settings.ts b/apps/desktop/src/i18n/fr_model_settings.tsindex b3036dd3fef..38792fdeea8 100644--- a/apps/desktop/src/i18n/fr_model_settings.ts+++ b/apps/desktop/src/i18n/fr_model_settings.ts@@ -1,6 +1,7 @@import type { TranslationOverride } from '@hermes/shared/i18n'import { frAuxTasks } from './fr_aux_tasks'+import { frDelegationRouting } from './fr_delegation_routing'import type { ModelSettingsTranslations } from './types_model_settings'export const frModelSettings: TranslationOverride<ModelSettingsTranslations> = {@@ -83,6 +84,7 @@ export const frModelSettings: TranslationOverride<ModelSettingsTranslations> = {'Appliquer cette route efface le point de terminaison direct et sa clé enregistrée. Les autres réglages de requête sont conservés.',catalogFailed:'Catalogue de modèles indisponible. Saisissez un fournisseur et un modèle manuellement, ou réessayez.',- draftHint: "Les modifications restent locales jusqu'à leur application."+ draftHint: "Les modifications restent locales jusqu'à leur application.",+ routing: frDelegationRouting}}diff --git a/apps/desktop/src/i18n/ja_delegation_routing.ts b/apps/desktop/src/i18n/ja_delegation_routing.tsnew file mode 100644index 00000000000..570d8dee68d--- /dev/null+++ b/apps/desktop/src/i18n/ja_delegation_routing.ts@@ -0,0 +1,100 @@+import type { DelegationRoutingTranslations } from './types_delegation_routing'++export const jaDelegationRouting: DelegationRoutingTranslations = {+ title: 'ルーティング',+ settingsTitle: 'サブエージェントの既定値',+ intro: '各サブエージェントがどのモデルを使うかを決めます。',+ modes: {+ default: { label: '既定', description: 'すべてのサブエージェントが下のサブエージェントモデルで動作します。' },+ model_map: {+ label: 'モデルルート',+ description: 'いくつかのモデルに名前を付けます。エージェントがサブエージェントごとに 1 つを選びます。'+ },+ profile_routes: {+ label: 'プロファイルルート',+ description: 'サブエージェントがいずれかのプロファイルとして、そのモデル、スキル、キーで動作します。'+ }+ },+ inUse: '使用中',+ plugin: 'プラグイン',+ pluginMissing: 'モデルルートとプロファイルルートは Advanced Delegation プラグインが提供します。',+ pluginDisabled: 'Advanced Delegation はインストール済みですが、このプロファイルではオフです。',+ pluginNotLoaded:+ 'Advanced Delegation はオンですが、Hermes がまだ読み込んでいません。完了するには Hermes を再起動してください。',+ installPlugin: 'プラグインをインストール',+ installUnavailable:+ 'Advanced Delegation はまだプラグインカタログにありません。スキルとツール › プラグイン からインストールしてください。',+ enablePlugin: 'オンにする',+ enableFailed: 'Advanced Delegation をオンにできませんでした',+ modeFailed: 'サブエージェントのルーティングを変更できませんでした',+ loadFailed: 'サブエージェントのルーティングを読み込めませんでした',+ blockedPill: '動作していません',+ blockedDetail: 'このモードが保存されているため、Hermes は黙って既定を使わず、すべてのサブエージェントを拒否します。',+ blockedMissing: 'Advanced Delegation をインストールするまで、サブエージェントは起動しません。',+ blockedDisabled: 'このプロファイルで Advanced Delegation をオンにするまで、サブエージェントは起動しません。',+ blockedNotLoaded:+ 'Hermes が Advanced Delegation を読み込むまで、サブエージェントは起動しません。Hermes を再起動して完了してください。',+ blockedUnavailable: label =>+ `${label} がここで動作できるようになるまで、サブエージェントは起動しません。そのプラグインは動作できないと報告しています。`,+ blockedUnregistered: name =>+ `「${name}」を提供するプラグインをインストールしてオンにするまで、サブエージェントは起動しません。`,+ thirdPartyDescription: 'プラグインが提供します。設定はそのプラグイン側にあります。',++ modelRoutesTitle: 'モデルルート',+ modelRoutesEmpty: 'ルートはまだありません。追加するまで、サブエージェントはメインエージェントのモデルを使います。',+ addRoute: 'ルートを追加',+ editRoute: '編集',+ makeDefault: '既定にする',+ deleteRoute: '削除',+ defaultBadge: '既定',+ routeActions: name => `${name} の操作`,+ deleteConfirmTitle: name => `ルート「${name}」を削除しますか?`,+ deleteConfirmBody: 'サブエージェントはこのルートを選べなくなります。',+ deleteConfirmNextDefault: name => `既定のルートのため、「${name}」が新しい既定になります。`,+ deleteConfirmAction: 'ルートを削除',+ saveFailed: 'ルートを保存できませんでした',+ baseUrlRoute: url => `エンドポイント ${url}`,++ dialogNew: '新しいモデルルート',+ dialogEdit: 'モデルルートを編集',+ dialogDesc: 'エージェントは名前と説明を読んで、サブエージェントがどのルートを使うかを決めます。',+ nameLabel: '名前',+ namePlaceholder: '例: fast',+ nameHint: '短く、スペースなしで。エージェントはこの名前でルートを選びます。',+ descriptionLabel: '使う場面',+ descriptionPlaceholder: '例: 安くて速い: 調べもの、要約、簡単な編集。',+ descriptionHint: 'エージェントが選ぶ前に読む 1 行の説明です。',+ providerLabel: 'プロバイダー',+ providerPlaceholder: 'プロバイダーを選択',+ modelLabel: 'モデル',+ effortLabel: '推論強度',+ effortInherit: 'サブエージェントの既定',+ tierLabel: '速度',+ tierNormal: '標準(既定)',+ tierFast: '高速',+ tierUltrafast: '超高速',+ tierHint: '対応しているモデルのみ。',+ optional: '任意',+ errors: { required: '必須', spaces: 'スペースは使えません', duplicate: 'この名前は別のルートで使われています' },+ saveRoute: 'ルートを保存',+ createRoute: 'ルートを追加',++ profileRoutesTitle: 'サブエージェントが使えるプロファイル',+ profileRoutesHint: 'チェックした各プロファイルは、それぞれのモデル、スキル、ペルソナ、キーを持ち込みます。',+ profileDescriptionPlaceholder: '使う場面(任意)',+ profileDefault: '既定',+ profileEmpty: 'ほかのプロファイルはまだありません。プロファイルバーから作成してください。',+ profileMissing: name => `${name}(プロファイルは存在しません)`,++ inactiveTitle: 'このモードでは使われません',+ inactiveModelMap: route =>+ `モデルルートが各サブエージェントのモデルを選びます。ルートを選ばなかったサブエージェントは「${route}」を使います。`,+ inactiveProfiles: profile =>+ `プロファイルルートが各サブエージェントのプロファイルを選びます。プロファイルを選ばなかったサブエージェントは「${profile}」として動作します。`,+ inactiveModelMapNoDefault:+ 'モデルルートが各サブエージェントのモデルを選びます。ルートを選ばなかったサブエージェントはメインエージェントのモデルを使います。',+ inactiveProfilesNoDefault:+ 'プロファイルルートが各サブエージェントのプロファイルを選びます。プロファイルを選ばなかったサブエージェントはメインエージェントのモデルを使います。',+ inactivePlugin: label => `${label} が各サブエージェントのモデルを決めるため、この設定は適用されません。`,+ useDefault: '既定に切り替え'+}diff --git a/apps/desktop/src/i18n/ja_model_settings.ts b/apps/desktop/src/i18n/ja_model_settings.tsindex fdbfa360f2e..6d82202f1c6 100644--- a/apps/desktop/src/i18n/ja_model_settings.ts+++ b/apps/desktop/src/i18n/ja_model_settings.ts@@ -1,6 +1,7 @@import type { TranslationOverride } from '@hermes/shared/i18n'import { jaAuxTasks } from './ja_aux_tasks'+import { jaDelegationRouting } from './ja_delegation_routing'import type { ModelSettingsTranslations } from './types_model_settings'export const jaModelSettings: TranslationOverride<ModelSettingsTranslations> = {@@ -68,6 +69,7 @@ export const jaModelSettings: TranslationOverride<ModelSettingsTranslations> = {directClear:'このルートを適用すると、直接エンドポイントと保存済みのキーが削除されます。その他のリクエスト設定は保持されます。',catalogFailed: 'モデルカタログを取得できません。プロバイダーとモデルを手動で入力するか、再試行してください。',- draftHint: '適用するまで変更はローカルにのみ保持されます。'+ draftHint: '適用するまで変更はローカルにのみ保持されます。',+ routing: jaDelegationRouting}}diff --git a/apps/desktop/src/i18n/ru_delegation_routing.ts b/apps/desktop/src/i18n/ru_delegation_routing.tsnew file mode 100644index 00000000000..e6e4131f8ff--- /dev/null+++ b/apps/desktop/src/i18n/ru_delegation_routing.ts@@ -0,0 +1,100 @@+import type { DelegationRoutingTranslations } from './types_delegation_routing'++export const ruDelegationRouting: DelegationRoutingTranslations = {+ title: 'Маршрутизация',+ settingsTitle: 'Параметры субагентов по умолчанию',+ intro: 'Как каждый субагент получает свою модель.',+ modes: {+ default: { label: 'По умолчанию', description: 'Все субагенты работают на модели субагента ниже.' },+ model_map: {+ label: 'Маршруты моделей',+ description: 'Назовите несколько моделей. Агент выбирает одну для каждого субагента.'+ },+ profile_routes: {+ label: 'Маршруты профилей',+ description: 'Субагенты работают как один из ваших профилей — с его моделью, навыками и ключами.'+ }+ },+ inUse: 'Используется',+ plugin: 'Плагин',+ pluginMissing: 'Маршруты моделей и маршруты профилей предоставляет плагин Advanced Delegation.',+ pluginDisabled: 'Advanced Delegation установлен, но отключён для этого профиля.',+ pluginNotLoaded: 'Advanced Delegation включён, но Hermes ещё не загрузил его. Перезапустите Hermes, чтобы завершить.',+ installPlugin: 'Установить плагин',+ installUnavailable:+ 'Advanced Delegation пока нет в каталоге плагинов. Установите его в разделе Возможности › Плагины.',+ enablePlugin: 'Включить',+ enableFailed: 'Не удалось включить Advanced Delegation',+ modeFailed: 'Не удалось изменить маршрутизацию субагентов',+ loadFailed: 'Не удалось загрузить маршрутизацию субагентов',+ blockedPill: 'Не работает',+ blockedDetail:+ 'Этот режим сохранён, поэтому Hermes отклоняет каждого субагента, а не переходит молча на «По умолчанию».',+ blockedMissing: 'Субагенты не запустятся, пока не установлен Advanced Delegation.',+ blockedDisabled: 'Субагенты не запустятся, пока Advanced Delegation не включён для этого профиля.',+ blockedNotLoaded:+ 'Субагенты не запустятся, пока Hermes не загрузит Advanced Delegation. Перезапустите Hermes, чтобы завершить.',+ blockedUnavailable: label =>+ `Субагенты не запустятся, пока ${label} не сможет работать здесь. Его плагин сообщает, что не может.`,+ blockedUnregistered: name =>+ `Субагенты не запустятся, пока не установлен и не включён плагин, предоставляющий «${name}».`,+ thirdPartyDescription: 'Предоставлен плагином. Его настройки находятся в этом плагине.',++ modelRoutesTitle: 'Маршруты моделей',+ modelRoutesEmpty: 'Маршрутов пока нет. Пока вы не добавите маршрут, субагенты используют модель основного агента.',+ addRoute: 'Добавить маршрут',+ editRoute: 'Изменить',+ makeDefault: 'Сделать основным',+ deleteRoute: 'Удалить',+ defaultBadge: 'Основной',+ routeActions: name => `Действия для ${name}`,+ deleteConfirmTitle: name => `Удалить маршрут «${name}»?`,+ deleteConfirmBody: 'Субагенты больше не смогут его выбрать.',+ deleteConfirmNextDefault: name => `Это основной маршрут, поэтому основным станет «${name}».`,+ deleteConfirmAction: 'Удалить маршрут',+ saveFailed: 'Не удалось сохранить маршруты',+ baseUrlRoute: url => `эндпоинт ${url}`,++ dialogNew: 'Новый маршрут модели',+ dialogEdit: 'Изменить маршрут модели',+ dialogDesc: 'Агент читает название и описание, чтобы решить, какой маршрут выберет субагент.',+ nameLabel: 'Название',+ namePlaceholder: 'например, fast',+ nameHint: 'Коротко, без пробелов. Агент выбирает маршруты по этому названию.',+ descriptionLabel: 'Когда использовать',+ descriptionPlaceholder: 'например, Дёшево и быстро: поиск, сводки, простые правки.',+ descriptionHint: 'Одна строка, которую агент читает перед выбором.',+ providerLabel: 'Провайдер',+ providerPlaceholder: 'Выберите провайдера',+ modelLabel: 'Модель',+ effortLabel: 'Глубина рассуждений',+ effortInherit: 'Как у субагента по умолчанию',+ tierLabel: 'Скорость',+ tierNormal: 'Обычная (по умолчанию)',+ tierFast: 'Быстрая',+ tierUltrafast: 'Сверхбыстрая',+ tierHint: 'Только для моделей, которые это поддерживают.',+ optional: 'необязательно',+ errors: { required: 'Обязательно', spaces: 'Без пробелов', duplicate: 'Это название уже использует другой маршрут' },+ saveRoute: 'Сохранить маршрут',+ createRoute: 'Добавить маршрут',++ profileRoutesTitle: 'Профили, от имени которых могут работать субагенты',+ profileRoutesHint: 'Каждый отмеченный профиль приносит свою модель, навыки, персону и ключи.',+ profileDescriptionPlaceholder: 'Когда использовать (необязательно)',+ profileDefault: 'Основной',+ profileEmpty: 'Других профилей пока нет. Создайте профиль на панели профилей.',+ profileMissing: name => `${name} (профиль больше не существует)`,++ inactiveTitle: 'Не используется в этом режиме',+ inactiveModelMap: route =>+ `Маршруты моделей выбирают модель для каждого субагента. Субагенты, не выбравшие маршрут, используют «${route}».`,+ inactiveProfiles: profile =>+ `Маршруты профилей выбирают профиль для каждого субагента. Субагенты, не выбравшие профиль, работают как «${profile}».`,+ inactiveModelMapNoDefault:+ 'Маршруты моделей выбирают модель для каждого субагента. Субагенты, не выбравшие маршрут, используют модель основного агента.',+ inactiveProfilesNoDefault:+ 'Маршруты профилей выбирают профиль для каждого субагента. Субагенты, не выбравшие профиль, используют модель основного агента.',+ inactivePlugin: label => `${label} выбирает модель для каждого субагента, поэтому эта настройка не применяется.`,+ useDefault: 'Переключить на «По умолчанию»'+}diff --git a/apps/desktop/src/i18n/ru_model_settings.ts b/apps/desktop/src/i18n/ru_model_settings.tsindex cd9d6a7eab8..6e336fee163 100644--- a/apps/desktop/src/i18n/ru_model_settings.ts+++ b/apps/desktop/src/i18n/ru_model_settings.ts@@ -1,6 +1,7 @@import type { TranslationOverride } from '@hermes/shared/i18n'import { ruAuxTasks } from './ru_aux_tasks'+import { ruDelegationRouting } from './ru_delegation_routing'import type { ModelSettingsTranslations } from './types_model_settings'export const ruModelSettings: TranslationOverride<ModelSettingsTranslations> = {@@ -71,6 +72,7 @@ export const ruModelSettings: TranslationOverride<ModelSettingsTranslations> = {directClear:'Применение этого маршрута удалит прямой эндпоинт и его сохранённый ключ. Остальные настройки запросов сохранятся.',catalogFailed: 'Каталог моделей недоступен. Введите провайдера и модель вручную или повторите попытку.',- draftHint: 'Изменения остаются локальными, пока вы их не примените.'+ draftHint: 'Изменения остаются локальными, пока вы их не примените.',+ routing: ruDelegationRouting}}diff --git a/apps/desktop/src/i18n/types_delegation_routing.ts b/apps/desktop/src/i18n/types_delegation_routing.tsnew file mode 100644index 00000000000..0589121db62--- /dev/null+++ b/apps/desktop/src/i18n/types_delegation_routing.ts@@ -0,0 +1,81 @@+export interface DelegationRoutingTranslations {+ title: string+ settingsTitle: string+ intro: string+ modes: Record<'default' | 'model_map' | 'profile_routes', { label: string; description: string }>+ inUse: string+ plugin: string+ pluginMissing: string+ pluginDisabled: string+ pluginNotLoaded: string+ installPlugin: string+ installUnavailable: string+ enablePlugin: string+ enableFailed: string+ modeFailed: string+ loadFailed: string+ /** The saved mode cannot run, so core refuses every subagent ("Subagents will not start until …"). */+ blockedPill: string+ blockedDetail: string+ blockedMissing: string+ blockedDisabled: string+ blockedNotLoaded: string+ blockedUnavailable: (label: string) => string+ blockedUnregistered: (name: string) => string+ /** Picker row of another plugin's backend that ships no description of its own. */+ thirdPartyDescription: string++ modelRoutesTitle: string+ modelRoutesEmpty: string+ addRoute: string+ editRoute: string+ makeDefault: string+ deleteRoute: string+ defaultBadge: string+ routeActions: (name: string) => string+ deleteConfirmTitle: (name: string) => string+ deleteConfirmBody: string+ deleteConfirmNextDefault: (name: string) => string+ deleteConfirmAction: string+ saveFailed: string+ baseUrlRoute: (url: string) => string++ dialogNew: string+ dialogEdit: string+ dialogDesc: string+ nameLabel: string+ namePlaceholder: string+ nameHint: string+ descriptionLabel: string+ descriptionPlaceholder: string+ descriptionHint: string+ providerLabel: string+ providerPlaceholder: string+ modelLabel: string+ effortLabel: string+ effortInherit: string+ tierLabel: string+ tierNormal: string+ tierFast: string+ tierUltrafast: string+ tierHint: string+ optional: string+ errors: { required: string; spaces: string; duplicate: string }+ saveRoute: string+ createRoute: string++ profileRoutesTitle: string+ profileRoutesHint: string+ profileDescriptionPlaceholder: string+ profileDefault: string+ profileEmpty: string+ profileMissing: (name: string) => string++ inactiveTitle: string+ inactiveModelMap: (route: string) => string+ inactiveProfiles: (profile: string) => string+ inactiveModelMapNoDefault: string+ inactiveProfilesNoDefault: string+ inactivePlugin: (label: string) => string+ useDefault: string+}diff --git a/apps/desktop/src/i18n/types_model_settings.ts b/apps/desktop/src/i18n/types_model_settings.tsindex e9f22b4628f..f0d0763536e 100644--- a/apps/desktop/src/i18n/types_model_settings.ts+++ b/apps/desktop/src/i18n/types_model_settings.ts@@ -1,4 +1,5 @@import type { AuxTaskCopyMap } from './types_aux_tasks'+import type { DelegationRoutingTranslations } from './types_delegation_routing'// Settings → Model; `Translations.settings.model`.export interface ModelSettingsTranslations {@@ -71,5 +72,7 @@ export interface ModelSettingsTranslations {directClear: stringcatalogFailed: stringdraftHint: string+ /** The Routing section above the subagent model: modes, model routes, profile routes. */+ routing: DelegationRoutingTranslations}}diff --git a/apps/desktop/src/i18n/zh-hant_delegation_routing.ts b/apps/desktop/src/i18n/zh-hant_delegation_routing.tsnew file mode 100644index 00000000000..98db74009aa--- /dev/null+++ b/apps/desktop/src/i18n/zh-hant_delegation_routing.ts@@ -0,0 +1,88 @@+import type { DelegationRoutingTranslations } from './types_delegation_routing'++export const zhHantDelegationRouting: DelegationRoutingTranslations = {+ title: '路由',+ settingsTitle: '子代理預設值',+ intro: '決定每個子代理使用哪個模型。',+ modes: {+ default: { label: '預設', description: '所有子代理都使用下方的子代理模型。' },+ model_map: { label: '模型路由', description: '為幾個模型命名,代理會為每個子代理挑選一個。' },+ profile_routes: {+ label: '設定檔路由',+ description: '子代理以你的某個設定檔執行,使用該設定檔自己的模型、技能和金鑰。'+ }+ },+ inUse: '使用中',+ plugin: '外掛',+ pluginMissing: '模型路由和設定檔路由來自 Advanced Delegation 外掛。',+ pluginDisabled: 'Advanced Delegation 已安裝,但在此設定檔中為關閉狀態。',+ pluginNotLoaded: 'Advanced Delegation 已開啟,但 Hermes 尚未載入。請重新啟動 Hermes 以完成設定。',+ installPlugin: '安裝外掛',+ installUnavailable: 'Advanced Delegation 尚未加入外掛目錄。請在 技能與工具 › 外掛 中安裝。',+ enablePlugin: '開啟',+ enableFailed: '無法開啟 Advanced Delegation',+ modeFailed: '無法變更子代理路由',+ loadFailed: '無法載入子代理路由',+ blockedPill: '未執行',+ blockedDetail: '此模式已儲存,因此 Hermes 會拒絕每個子代理,而不是悄悄改用預設。',+ blockedMissing: '安裝 Advanced Delegation 之前,子代理不會啟動。',+ blockedDisabled: '為此設定檔開啟 Advanced Delegation 之前,子代理不會啟動。',+ blockedNotLoaded: 'Hermes 載入 Advanced Delegation 之前,子代理不會啟動。重新啟動 Hermes 以完成。',+ blockedUnavailable: label => `${label} 能在此處執行之前,子代理不會啟動。其外掛回報無法執行。`,+ blockedUnregistered: name => `安裝並開啟提供「${name}」的外掛之前,子代理不會啟動。`,+ thirdPartyDescription: '來自外掛。其設定位於該外掛中。',++ modelRoutesTitle: '模型路由',+ modelRoutesEmpty: '尚無路由。新增路由之前,子代理會使用主代理的模型。',+ addRoute: '新增路由',+ editRoute: '編輯',+ makeDefault: '設為預設',+ deleteRoute: '刪除',+ defaultBadge: '預設',+ routeActions: name => `${name} 的操作`,+ deleteConfirmTitle: name => `刪除路由「${name}」?`,+ deleteConfirmBody: '子代理將無法再選擇它。',+ deleteConfirmNextDefault: name => `它是預設路由,因此「${name}」將成為預設路由。`,+ deleteConfirmAction: '刪除路由',+ saveFailed: '無法儲存路由',+ baseUrlRoute: url => `端點 ${url}`,++ dialogNew: '新增模型路由',+ dialogEdit: '編輯模型路由',+ dialogDesc: '代理會讀取名稱和描述,決定子代理走哪條路由。',+ nameLabel: '名稱',+ namePlaceholder: '例如 fast',+ nameHint: '簡短,不含空格。代理依此名稱挑選路由。',+ descriptionLabel: '何時使用',+ descriptionPlaceholder: '例如:便宜又快:查詢、摘要、簡單編輯。',+ descriptionHint: '代理在選擇前讀取的一行說明。',+ providerLabel: '提供方',+ providerPlaceholder: '選擇提供方',+ modelLabel: '模型',+ effortLabel: '推理強度',+ effortInherit: '子代理預設值',+ tierLabel: '速度',+ tierNormal: '一般(預設)',+ tierFast: '快速',+ tierUltrafast: '極速',+ tierHint: '僅適用於提供此選項的模型。',+ optional: '選填',+ errors: { required: '必填', spaces: '不可包含空格', duplicate: '其他路由已使用此名稱' },+ saveRoute: '儲存路由',+ createRoute: '新增路由',++ profileRoutesTitle: '子代理可使用的設定檔',+ profileRoutesHint: '每個勾選的設定檔都會帶上自己的模型、技能、人設和金鑰。',+ profileDescriptionPlaceholder: '何時使用(選填)',+ profileDefault: '預設',+ profileEmpty: '尚無其他設定檔。可從設定檔列建立。',+ profileMissing: name => `${name}(設定檔已不存在)`,++ inactiveTitle: '此模式下不使用',+ inactiveModelMap: route => `模型路由會為每個子代理挑選模型。未選擇路由的子代理使用「${route}」。`,+ inactiveProfiles: profile => `設定檔路由會為每個子代理挑選設定檔。未選擇設定檔的子代理以「${profile}」執行。`,+ inactiveModelMapNoDefault: '模型路由會為每個子代理挑選模型。未選擇路由的子代理使用主代理的模型。',+ inactiveProfilesNoDefault: '設定檔路由會為每個子代理挑選設定檔。未選擇設定檔的子代理使用主代理的模型。',+ inactivePlugin: label => `${label} 決定每個子代理的模型,因此此設定不適用。`,+ useDefault: '切換為預設'+}diff --git a/apps/desktop/src/i18n/zh-hant_settings.ts b/apps/desktop/src/i18n/zh-hant_settings.tsindex 9896e89e543..467cca6dbbc 100644--- a/apps/desktop/src/i18n/zh-hant_settings.ts+++ b/apps/desktop/src/i18n/zh-hant_settings.ts@@ -1,6 +1,7 @@import { defineFieldCopy } from '@/app/settings/field-copy'import type { TranslationOverrides } from './define-locale'+import { zhHantDelegationRouting } from './zh-hant_delegation_routing'import { zhHantUpdateChannel } from './zh-hant_update_channel'export const zhHantSettings = {@@ -1096,7 +1097,8 @@ export const zhHantSettings = {directActive: '直接端點已啟用,優先於已儲存的提供方。選擇此模式時會保留其端點與憑證。',directClear: '套用此路由會清除直接端點及其儲存的金鑰。其他請求設定維持不變。',catalogFailed: '模型目錄無法使用。請手動輸入提供方與模型,或重試。',- draftHint: '套用前,變更只保留在本機。'+ draftHint: '套用前,變更只保留在本機。',+ routing: zhHantDelegationRouting}},localModels: {diff --git a/apps/desktop/src/i18n/zh_delegation_routing.ts b/apps/desktop/src/i18n/zh_delegation_routing.tsnew file mode 100644index 00000000000..0c3f1304816--- /dev/null+++ b/apps/desktop/src/i18n/zh_delegation_routing.ts@@ -0,0 +1,88 @@+import type { DelegationRoutingTranslations } from './types_delegation_routing'++export const zhDelegationRouting: DelegationRoutingTranslations = {+ title: '路由',+ settingsTitle: '子智能体默认设置',+ intro: '决定每个子智能体使用哪个模型。',+ modes: {+ default: { label: '默认', description: '所有子智能体都使用下方的子智能体模型。' },+ model_map: { label: '模型路由', description: '为几个模型命名,智能体会为每个子智能体挑选一个。' },+ profile_routes: {+ label: '配置档案路由',+ description: '子智能体以你的某个配置档案运行,使用该档案自己的模型、技能和密钥。'+ }+ },+ inUse: '使用中',+ plugin: '插件',+ pluginMissing: '模型路由和配置档案路由来自 Advanced Delegation 插件。',+ pluginDisabled: 'Advanced Delegation 已安装,但在此配置档案中处于关闭状态。',+ pluginNotLoaded: 'Advanced Delegation 已开启,但 Hermes 尚未加载它。请重启 Hermes 以完成设置。',+ installPlugin: '安装插件',+ installUnavailable: 'Advanced Delegation 尚未加入插件目录。请在 技能与工具 › 插件 中安装。',+ enablePlugin: '开启',+ enableFailed: '无法开启 Advanced Delegation',+ modeFailed: '无法更改子智能体路由',+ loadFailed: '无法加载子智能体路由',+ blockedPill: '未运行',+ blockedDetail: '此模式已保存,因此 Hermes 会拒绝每个子智能体,而不是悄悄改用默认。',+ blockedMissing: '安装 Advanced Delegation 之前,子智能体不会启动。',+ blockedDisabled: '为此配置档案开启 Advanced Delegation 之前,子智能体不会启动。',+ blockedNotLoaded: 'Hermes 加载 Advanced Delegation 之前,子智能体不会启动。重启 Hermes 以完成。',+ blockedUnavailable: label => `${label} 能在此处运行之前,子智能体不会启动。其插件报告无法运行。`,+ blockedUnregistered: name => `安装并开启提供“${name}”的插件之前,子智能体不会启动。`,+ thirdPartyDescription: '来自插件。其设置位于该插件中。',++ modelRoutesTitle: '模型路由',+ modelRoutesEmpty: '还没有路由。添加路由之前,子智能体使用主智能体的模型。',+ addRoute: '添加路由',+ editRoute: '编辑',+ makeDefault: '设为默认',+ deleteRoute: '删除',+ defaultBadge: '默认',+ routeActions: name => `${name} 的操作`,+ deleteConfirmTitle: name => `删除路由“${name}”?`,+ deleteConfirmBody: '子智能体将无法再选择它。',+ deleteConfirmNextDefault: name => `它是默认路由,因此“${name}”将成为默认路由。`,+ deleteConfirmAction: '删除路由',+ saveFailed: '无法保存路由',+ baseUrlRoute: url => `端点 ${url}`,++ dialogNew: '新建模型路由',+ dialogEdit: '编辑模型路由',+ dialogDesc: '智能体会读取名称和描述,决定子智能体走哪条路由。',+ nameLabel: '名称',+ namePlaceholder: '例如 fast',+ nameHint: '简短,不含空格。智能体按此名称挑选路由。',+ descriptionLabel: '何时使用',+ descriptionPlaceholder: '例如:便宜又快:查询、摘要、简单编辑。',+ descriptionHint: '智能体在选择前读取的一行说明。',+ providerLabel: '提供方',+ providerPlaceholder: '选择提供方',+ modelLabel: '模型',+ effortLabel: '推理强度',+ effortInherit: '子智能体默认值',+ tierLabel: '速度',+ tierNormal: '普通(默认)',+ tierFast: '快速',+ tierUltrafast: '极速',+ tierHint: '仅适用于提供该选项的模型。',+ optional: '可选',+ errors: { required: '必填', spaces: '不能包含空格', duplicate: '其他路由已使用此名称' },+ saveRoute: '保存路由',+ createRoute: '添加路由',++ profileRoutesTitle: '子智能体可使用的配置档案',+ profileRoutesHint: '每个勾选的配置档案都会带上自己的模型、技能、人设和密钥。',+ profileDescriptionPlaceholder: '何时使用(可选)',+ profileDefault: '默认',+ profileEmpty: '还没有其他配置档案。可在配置档案栏中创建。',+ profileMissing: name => `${name}(配置档案已不存在)`,++ inactiveTitle: '此模式下不使用',+ inactiveModelMap: route => `模型路由为每个子智能体挑选模型。未选择路由的子智能体使用“${route}”。`,+ inactiveProfiles: profile => `配置档案路由为每个子智能体挑选配置档案。未选择配置档案的子智能体以“${profile}”运行。`,+ inactiveModelMapNoDefault: '模型路由为每个子智能体挑选模型。未选择路由的子智能体使用主智能体的模型。',+ inactiveProfilesNoDefault: '配置档案路由为每个子智能体挑选配置档案。未选择配置档案的子智能体使用主智能体的模型。',+ inactivePlugin: label => `${label} 决定每个子智能体的模型,因此此设置不适用。`,+ useDefault: '切换为默认'+}diff --git a/apps/desktop/src/i18n/zh_model_settings.ts b/apps/desktop/src/i18n/zh_model_settings.tsindex ae1a6e3bb97..9e6817fde39 100644--- a/apps/desktop/src/i18n/zh_model_settings.ts+++ b/apps/desktop/src/i18n/zh_model_settings.ts@@ -2,6 +2,7 @@ import type { TranslationOverride } from '@hermes/shared/i18n'import type { ModelSettingsTranslations } from './types_model_settings'import { zhAuxTasks } from './zh_aux_tasks'+import { zhDelegationRouting } from './zh_delegation_routing'export const zhModelSettings: TranslationOverride<ModelSettingsTranslations> = {setupProviderFallback: '提供方',@@ -72,6 +73,7 @@ export const zhModelSettings: TranslationOverride<ModelSettingsTranslations> = {directActive: '直接端点已启用,优先于保存的提供商。选择此模式会保留其端点和凭证。',directClear: '应用此路由会清除直接端点及其保存的密钥。其他请求设置保持不变。',catalogFailed: '模型目录不可用。请手动输入提供商和模型,或重试。',- draftHint: '应用前,更改仅保留在本地。'+ draftHint: '应用前,更改仅保留在本地。',+ routing: zhDelegationRouting}}diff --git a/hermes_cli/web_models.py b/hermes_cli/web_models.pyindex 98e6887ab97..7134d8962c2 100644--- a/hermes_cli/web_models.py+++ b/hermes_cli/web_models.py@@ -527,6 +527,20 @@ class TerminalBackendSelect(BaseModel):backend: strprofile: Optional[str] = None+class DelegationBackendSelect(BaseModel):+ backend: str+ profile: Optional[str] = None++class DelegationModelMapUpdate(BaseModel):+ options: list[dict[str, Any]]+ default: Optional[str] = None+ profile: Optional[str] = None++class DelegationProfileRoutesUpdate(BaseModel):+ profiles: list[dict[str, Any]]+ default: Optional[str] = None+ profile: Optional[str] = None+class RawConfigUpdate(BaseModel):yaml_text: strprofile: Optional[str] = Nonediff --git a/hermes_cli/web_routers/delegation.py b/hermes_cli/web_routers/delegation.pynew file mode 100644index 00000000000..297596f1471--- /dev/null+++ b/hermes_cli/web_routers/delegation.py@@ -0,0 +1,241 @@+"""Delegation routing routes: which ``delegation.backend`` runs subagents, and each plugin backend's+routes under ``delegation.backends.<name>``.++The settings shapes are the ones the official advanced-delegation plugin reads (``model_map``:+named model routes; ``profile_routes``: Hermes profiles subagents may run as). Writes replace one+backend's block wholesale through the same profile scope + config lock every config route uses, so+deleting a route really deletes it (``PUT /api/config`` deep-merges and cannot drop a key).+"""++from __future__ import annotations++import asyncio+import logging+from typing import Any, Callable, Mapping, Optional++from fastapi import APIRouter, HTTPException++from hermes_cli.web_deps import late+from hermes_cli.web_models import DelegationBackendSelect, DelegationModelMapUpdate, DelegationProfileRoutesUpdate+from hermes_cli.web_routers._common import (+ _profile_scope, config_write_scope, is_redacted_credential_preview, redacted_credential_preview,+)++router = APIRouter()+_log = logging.getLogger(__name__)++load_config = late("load_config", "hermes_cli.config")+save_config = late("save_config", "hermes_cli.config")++DEFAULT_BACKEND = "default"+MODEL_MAP = "model_map"+PROFILE_ROUTES = "profile_routes"+_OPTION_TEXT_KEYS = ("name", "description", "provider", "model", "base_url", "api_mode")+++def _bad_request(detail: str) -> HTTPException:+ return HTTPException(status_code=400, detail=detail)+++def _mapping(parent: Any, key: str) -> dict:+ value = parent.get(key) if isinstance(parent, Mapping) else None+ return value if isinstance(value, dict) else {}+++def _section(config: dict, key: str) -> dict:+ value = config.get(key)+ if not isinstance(value, dict):+ value = {}+ config[key] = value+ return value+++def _registered_backends() -> list[dict[str, Any]]:+ """``default`` plus every plugin-registered backend of the active profile, with availability."""+ from agent.delegation_backends import list_backends+ from agent.delegation_registry import DEFAULT_BACKEND as builtin+ from hermes_cli.plugins import discover_plugins++ discover_plugins() # idempotent; a plugin enabled after boot loads on the next scan+ return [{"name": b.name, "label": b.label, "description": b.description, "available": b.available,+ "reason": b.reason, "builtin": b.name == builtin} for b in list_backends()]+++def _redacted_options(options: Any) -> list[dict[str, Any]]:+ """Model routes as stored, with an ``api_key`` reduced to a display-only preview."""+ if not isinstance(options, list):+ return []+ out = []+ for entry in options:+ if not isinstance(entry, dict):+ continue+ row = dict(entry)+ if row.get("api_key"):+ row["api_key"] = redacted_credential_preview(row["api_key"])+ out.append(row)+ return out+++def _profile_names() -> list[str]:+ from hermes_cli.profiles import list_profile_names+ return list_profile_names()++[email protected]("/api/delegation/routing")+async def get_delegation_routing(profile: Optional[str] = None):+ """The profile's delegation backend (``configured``) and, when it cannot run here, why+ (``blocked_reason``, ``None`` when it runs: core fails closed, so subagents are refused until it is fixed), the registered+ backends, both route blocks and the profiles a profile route may name."""+ def _read():+ from agent.delegation_registry import backend_status, configured_backend+ with _profile_scope(profile):+ delegation = _mapping(load_config(), "delegation")+ backends = _registered_backends()+ configured = configured_backend(delegation)+ blocks = _mapping(delegation, "backends")+ model_map, routes = _mapping(blocks, MODEL_MAP), _mapping(blocks, PROFILE_ROUTES)+ return {+ "configured": configured,+ "blocked_reason": backend_status(configured)[1] or None,+ "backends": backends,+ MODEL_MAP: {"options": _redacted_options(model_map.get("options")),+ "default": model_map.get("default") or None},+ PROFILE_ROUTES: {"profiles": [p for p in routes.get("profiles") or [] if isinstance(p, dict)],+ "default": routes.get("default") or None},+ "profiles": _profile_names(),+ }++ return await asyncio.to_thread(_read)++[email protected]("/api/delegation/backend")+async def select_delegation_backend(body: DelegationBackendSelect, profile: Optional[str] = None):+ """Persist ``delegation.backend`` through core's ``set_global_backend``: only ``default`` or a backend+ that can run for this profile (core fails closed on any other, refusing every subagent)."""+ name = (body.backend or "").strip().lower() or DEFAULT_BACKEND++ def _run():+ from agent.delegation_backends import set_global_backend+ from hermes_cli.plugins import discover_plugins+ with config_write_scope(body.profile or profile):+ discover_plugins()+ try:+ set_global_backend(name)+ except ValueError as exc:+ raise _bad_request(str(exc)) from exc++ await asyncio.to_thread(_run)+ return {"ok": True, "backend": name}+++def _text(entry: dict, key: str) -> str:+ value = entry.get(key)+ return value.strip() if isinstance(value, str) else ""+++def _check_default(default: Optional[str], names: list[str], what: str) -> Optional[str]:+ value = (default or "").strip()+ if value and value not in names:+ raise _bad_request(f"Default {what} {value!r} is not in the list.")+ return value or None+++def _clean_model_option(index: int, entry: dict, stored: dict[str, dict]) -> dict[str, Any]:+ from agent.fast_mode import STATIC_TIERS, parse_exact_service_tier+ from hermes_constants import VALID_REASONING_EFFORTS, parse_reasoning_effort++ row = {key: _text(entry, key) for key in _OPTION_TEXT_KEYS if _text(entry, key)}+ label = f"Route {index + 1}"+ if not row.get("name"):+ raise _bad_request(f"{label} needs a name.")+ label = f"Route {row['name']!r}"+ if not row.get("description"):+ raise _bad_request(f"{label} needs a description: it is what the agent reads to choose it.")+ if not row.get("model"):+ raise _bad_request(f"{label} needs a model.")+ if not (row.get("provider") or row.get("base_url")):+ raise _bad_request(f"{label} needs a provider.")+ effort = _text(entry, "reasoning_effort")+ if effort:+ if parse_reasoning_effort(effort) is None:+ raise _bad_request(f"{label}: unknown reasoning effort {effort!r}. "+ f"Use none or one of: {', '.join(VALID_REASONING_EFFORTS)}.")+ row["reasoning_effort"] = effort+ tier = _text(entry, "service_tier")+ if tier:+ try:+ parsed = parse_exact_service_tier(tier)+ except ValueError:+ parsed = None+ if parsed is None or (parsed and parsed not in STATIC_TIERS):+ raise _bad_request(f"{label}: unknown service tier {tier!r}. Use normal, fast or ultrafast.")+ row["service_tier"] = tier+ if isinstance(entry.get("fallback_providers"), list):+ row["fallback_providers"] = entry["fallback_providers"]+ 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")+ if isinstance(key, str) and key.strip():+ row["api_key"] = key.strip()+ return row+++def _write_backend_block(profile: Optional[str], backend: str, build: Callable[[dict], dict]) -> dict:+ with config_write_scope(profile):+ config = load_config()+ blocks = _section(_section(config, "delegation"), "backends")+ block = build(_mapping(blocks, backend))+ blocks[backend] = block+ save_config(config)+ return block++[email protected]("/api/delegation/backends/model_map")+async def save_model_routes(body: DelegationModelMapUpdate, profile: Optional[str] = None):+ """Replace ``delegation.backends.model_map`` (``options`` + ``default``) after validating every route."""+ def _build(current: dict) -> dict:+ stored = {_text(o, "name"): o for o in current.get("options") or [] if isinstance(o, dict)}+ options = [_clean_model_option(i, dict(o), stored) for i, o in enumerate(body.options)]+ names = [o["name"] for o in options]+ duplicate = next((n for n in names if names.count(n) > 1), None)+ if duplicate:+ raise _bad_request(f"Two routes are named {duplicate!r}; route names must be unique.")+ block: dict[str, Any] = {"options": options}+ default = _check_default(body.default, names, "route")+ if default:+ block["default"] = default+ return block++ block = await asyncio.to_thread(_write_backend_block, body.profile or profile, MODEL_MAP, _build)+ return {"ok": True, MODEL_MAP: {"options": _redacted_options(block["options"]),+ "default": block.get("default")}}++[email protected]("/api/delegation/backends/profile_routes")+async def save_profile_routes(body: DelegationProfileRoutesUpdate, profile: Optional[str] = None):+ """Replace ``delegation.backends.profile_routes`` (``profiles`` + ``default``); every name must be an+ existing profile."""+ def _build(_current: dict) -> dict:+ known = set(_profile_names())+ profiles: list[dict[str, str]] = []+ names: list[str] = []+ for entry in body.profiles:+ name = _text(entry, "name")+ if not name:+ raise _bad_request("A profile route needs a profile name.")+ if name not in known:+ raise _bad_request(f"Profile {name!r} does not exist.")+ if name in names:+ raise _bad_request(f"Profile {name!r} is listed twice.")+ names.append(name)+ description = _text(entry, "description")+ profiles.append({"name": name, **({"description": description} if description else {})})+ block: dict[str, Any] = {"profiles": profiles}+ default = _check_default(body.default, names, "profile")+ if default:+ block["default"] = default+ return block++ block = await asyncio.to_thread(_write_backend_block, body.profile or profile, PROFILE_ROUTES, _build)+ return {"ok": True, PROFILE_ROUTES: {"profiles": block["profiles"], "default": block.get("default")}}diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 9ff8bbedb0d..59700ba32c5 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -782,6 +782,7 @@ from hermes_cli.web_routers import (chat_workspaces as _chat_workspaces_routes,dashboard_ui as _dashboard_ui_routes,shared_metrics as _shared_metrics_routes,+ delegation as _delegation_routes,)app.include_router(_files_routes.router)@@ -815,6 +816,7 @@ app.include_router(_chat_ws_routes.router)app.include_router(_chat_workspaces_routes.router)app.include_router(_dashboard_ui_routes.router)app.include_router(_shared_metrics_routes.router)+app.include_router(_delegation_routes.router)# Plugin API routes and the dashboard auth routes (/login, /auth/*, /api/auth/*)# mount before the SPA catch-all so /{full_path:path} doesn't swallow them. Authdiff --git a/tests/hermes_cli/test_web_delegation_routing.py b/tests/hermes_cli/test_web_delegation_routing.pynew file mode 100644index 00000000000..39448b4d1c9--- /dev/null+++ b/tests/hermes_cli/test_web_delegation_routing.py@@ -0,0 +1,159 @@+"""Settings › Subagents routes: ``delegation.backend`` and ``delegation.backends.*`` are read, validated and+written in the TARGET profile (``?profile=``). Real plugin directory registering real delegation providers, the+real loader and real config files under a temp home.+"""++from __future__ import annotations++import hermes_yaml as yaml+import pytest++pytest.importorskip("fastapi")+from starlette.testclient import TestClient++ROUTES_PLUGIN = '''+from agent.delegation_provider import DelegationProvider+++class _Routes(DelegationProvider):+ def __init__(self, name):+ self._name = name++ @property+ def name(self):+ return self._name++ def route_task(self, task, config):+ return dict(config)+++def register(ctx):+ ctx.register_delegation_provider(_Routes("model_map"))+ ctx.register_delegation_provider(_Routes("profile_routes"))+'''++SECRET = "sk-route-secret-0123456789abcdef"+++def homes(tmp_path, monkeypatch):+ from hermes_cli import plugins as plugins_mod++ root = tmp_path / "hermes_home"+ work = root / "profiles" / "work"+ plugin_dir = work / "plugins" / "routes"+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "plugin.yaml").write_text(yaml.safe_dump({"name": "routes", "version": "1.0"}), encoding="utf-8")+ (plugin_dir / "__init__.py").write_text(ROUTES_PLUGIN, encoding="utf-8")+ (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": "deep", "description": "Careful", "provider": "anthropic", "model": "m-deep"},+ ], "default": "deep"}}},+ }), encoding="utf-8")+ # The launch profile saved a plugin backend it does not have: configured, but nothing can run it.+ (root / "config.yaml").write_text(yaml.safe_dump({"delegation": {"backend": "model_map"}}), encoding="utf-8")+ empty_bundled = tmp_path / "bundled"+ empty_bundled.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(root))+ monkeypatch.setattr(plugins_mod, "get_bundled_plugins_dir", lambda: empty_bundled)+ from agent import secret_scope+ from tui_gateway import launch_profile_policy as lpp+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", False)+ monkeypatch.setattr(lpp, "_snapshot", None)+ plugins_mod._reset_plugin_managers_for_tests()+ yield root, work+ plugins_mod._reset_plugin_managers_for_tests()+++def client(homes):+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app+ c = TestClient(app)+ c.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN+ return c+++def _delegation(home) -> dict:+ return (yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8")) or {}).get("delegation") or {}+++def test_routing_reads_the_target_profile_and_never_returns_a_route_key(client):+ work = client.get("/api/delegation/routing?profile=work").json()+ assert {b["name"] for b in work["backends"]} == {"default", "model_map", "profile_routes"}+ assert (work["configured"], work["blocked_reason"]) == ("model_map", None)+ assert [o["name"] for o in work["model_map"]["options"]] == ["fast", "deep"]+ assert work["model_map"]["default"] == "deep"+ assert SECRET not in str(work) and work["model_map"]["options"][0]["api_key"]+ assert {"default", "work"} <= set(work["profiles"])++ # Core fails closed on a saved backend no plugin provides: the page must say why, not show Default.+ launch = client.get("/api/delegation/routing").json()+ assert [b["name"] for b in launch["backends"]] == ["default"]+ assert launch["configured"] == "model_map" and "not installed" in launch["blocked_reason"]+++def test_a_backend_can_only_be_chosen_where_its_plugin_is_registered(client, homes):+ root, work = homes+ resp = client.put("/api/delegation/backend?profile=work", json={"backend": "profile_routes"})+ assert resp.status_code == 200, resp.text+ assert _delegation(work)["backend"] == "profile_routes"++ before = (root / "config.yaml").read_text(encoding="utf-8")+ resp = client.put("/api/delegation/backend", json={"backend": "profile_routes"})+ assert resp.status_code == 400+ assert "not installed" in resp.json()["detail"]+ assert (root / "config.yaml").read_text(encoding="utf-8") == before++[email protected](("options", "problem"), [+ ([{"name": "a", "description": "x", "provider": "p", "model": "m"},+ {"name": "a", "description": "y", "provider": "p", "model": "m"}], "unique"),+ ([{"name": "a", "provider": "p", "model": "m"}], "description"),+ ([{"name": "a", "description": "x", "model": "m"}], "provider"),+ ([{"name": "a", "description": "x", "provider": "p", "model": "m", "service_tier": "warp"}], "service tier"),+ ([{"name": "a", "description": "x", "provider": "p", "model": "m", "reasoning_effort": "huge"}], "reasoning"),+])+def test_invalid_model_routes_are_refused_before_anything_is_written(client, homes, options, problem):+ _root, work = homes+ before = (work / "config.yaml").read_text(encoding="utf-8")+ resp = client.put("/api/delegation/backends/model_map?profile=work", json={"options": options})+ assert resp.status_code == 400+ assert problem in resp.json()["detail"]+ assert (work / "config.yaml").read_text(encoding="utf-8") == before+++def test_saving_model_routes_replaces_the_block_and_keeps_the_stored_key(client, homes):+ root, work = homes+ shown = 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"},+ {"name": "local", "description": "Private", "base_url": "http://127.0.0.1:8080/v1",+ "model": "qwen", "service_tier": "fast"}],+ "default": "local"}+ resp = client.put("/api/delegation/backends/model_map?profile=work", json=body)+ assert resp.status_code == 200, resp.text+ assert SECRET not in resp.text++ 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 "backends" not in _delegation(root)+++def test_profile_routes_only_name_existing_profiles(client, homes):+ _root, work = homes+ before = (work / "config.yaml").read_text(encoding="utf-8")+ resp = client.put("/api/delegation/backends/profile_routes?profile=work",+ json={"profiles": [{"name": "ghost"}]})+ assert resp.status_code == 400 and "does not exist" in resp.json()["detail"]+ assert (work / "config.yaml").read_text(encoding="utf-8") == before++ resp = client.put("/api/delegation/backends/profile_routes?profile=work",+ json={"profiles": [{"name": "default", "description": " The main one "}], "default": "default"})+ assert resp.status_code == 200, resp.text+ assert _delegation(work)["backends"]["profile_routes"] == {+ "profiles": [{"name": "default", "description": "The main one"}], "default": "default"}