Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(workbench): leave out efforts every hop refuses, name the Sources that refuse the rest, and keep a refused saved effort visible (#2594)

Call White4c3229d46fa2
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 157c7ee9e..c784871ef 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -55,6 +55,9 @@ capabilities:
- tests/test_model_hub_capability_evidence.py
- tests/test_provider_overlay.py
- tests/test_hosted_activity.py
+ - ui/src/lib/backendModels.test.ts
+ - ui/src/components/workbench/AgentRoutePicker.test.tsx
+ - ui/src/components/workbench/AgentsPage.test.tsx
- tests/agent_core/ai/test_hosted_requests.py
- tests/agent_core/ai/test_hosted_parsing.py
- tests/agent_core/ai/test_hosted_transform.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 9da724c14..79b7a0b25 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -13,6 +13,9 @@ capability:
- tests/test_provider_overlay.py
- tests/test_hosted_activity.py
- ui/src/components/workbench/HostedToolRow.test.tsx
+ - ui/src/lib/backendModels.test.ts
+ - ui/src/components/workbench/AgentRoutePicker.test.tsx
+ - ui/src/components/workbench/AgentsPage.test.tsx
- tests/agent_core/ai/test_hosted_requests.py
- tests/agent_core/ai/test_hosted_parsing.py
- tests/agent_core/ai/test_hosted_transform.py
@@ -264,6 +267,26 @@ scenarios:
- tests/test_hosted_activity.py::test_the_im_line_says_a_reason_avibe_worded_in_the_readers_language
- tests/test_hosted_activity.py::test_every_known_hosted_error_code_has_copy_on_every_surface
- ui/src/components/workbench/HostedToolRow.test.tsx::MH-HOSTED-UI-015
+ - id: MH-EFFORT-MENU-001
+ name: The model picker leaves out an effort every hop refuses and keeps, with its refusing Sources, one the other hops serve
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/lib/backendModels.test.ts::MH-EFFORT-MENU-001
+ - id: MH-EFFORT-MENU-002
+ name: The Chat route picker names the Sources that refuse an effort, or says some do when the viewer may not read Sources
+ status: covered
+ kind: observation
+ layer: unit
+ test: ui/src/components/workbench/AgentRoutePicker.test.tsx::MH-EFFORT-MENU-002
+ - id: MH-EFFORT-MENU-003
+ name: A saved effort routing now refuses on every hop stays visible as itself, marked, in the Chat route picker and on the Agents page, and is not offered as a choice
+ status: covered
+ kind: observation
+ layer: unit
+ test:
+ - ui/src/components/workbench/AgentRoutePicker.test.tsx::MH-EFFORT-MENU-003
+ - ui/src/components/workbench/AgentsPage.test.tsx::MH-EFFORT-MENU-003
- id: MH-HOSTED-VIBEY-001
name: Vibey declares a hop's native hosted tool verbatim with its include values and pins that request to the hop's Source; the probe builds the same request
status: covered
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 41b9f9f08..776f459f3 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -214,6 +214,21 @@ export type BackendModel = {
routeable: boolean;
};
+/**
+ * What routing would do with each of a model's efforts right now, in menu
+ * vocabulary (`model-hub-capability-model.md` §3.4). Response-only, on the model
+ * picker's catalog read: `omitted` efforts would end in `effort_unsupported` on
+ * every hop the route would try or wait for; `not_on` names, by Source id, the
+ * hops that refuse an effort the others still serve. Never written back.
+ */
+export type EffortMenu = { omitted: string[]; not_on: Record<string, string[]> };
+
+/** A catalog row as the model picker reads it. */
+export type PickerCatalogModel = BackendModel & { effort_menu?: EffortMenu };
+
+/** The model picker's read of one backend's catalog (`GET /api/models/agents/<backend>/models`). */
+export type PickerAgentCatalog = Pick<AgentSupply, 'backend' | 'mode'> & { catalog_models?: PickerCatalogModel[] | null };
+
/** `baseline` is the last full list this caller observed; `models` is its
* desired replacement. The server applies the difference to the latest saved
* list, so a concurrent editor's unrelated row survives.
diff --git a/ui/src/components/workbench/AgentRoutePicker.test.tsx b/ui/src/components/workbench/AgentRoutePicker.test.tsx
index 6da7fcce8..a4df39ae1 100644
--- a/ui/src/components/workbench/AgentRoutePicker.test.tsx
+++ b/ui/src/components/workbench/AgentRoutePicker.test.tsx
@@ -2,7 +2,7 @@
import { useState } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { act, cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, useLocation } from 'react-router-dom';
@@ -15,13 +15,22 @@ import { AgentRoutePicker } from './AgentRoutePicker';
import type { AgentRoutePatch, AgentRouteValue } from './AgentRoutePicker';
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ // The key, plus the Source names a hint interpolates, so a test can read both.
+ useTranslation: () => ({
+ t: (key: string, options?: { sources?: string }) => (options?.sources ? `${key}:${options.sources}` : key),
+ }),
}));
+// What the Sources read answers: names by id, or null when the role may not read them.
+let sourceNames: Record<string, string> | null = null;
+vi.mock('../../lib/useSourceNames', () => ({ useSourceNames: () => sourceNames }));
+
// One client for every render, as the real context provides: the picker's
// catalog read keys on it, so a fresh object per render would re-read on its own.
// The Hub read answers per test; `useAddModelPath` owns what it means.
let hubMode: 'hub' | 'direct' = 'direct';
+// Whether the next catalog read finds Model Hub unreadable (the native list, marked unread).
+let hubUnread = false;
const API = {
readModelHubAgentCatalogForModelPicker: (backend: string) => Promise.resolve({ backend, mode: hubMode }),
};
@@ -34,6 +43,7 @@ vi.mock('../../context/ApiContext', async (importOriginal) => ({
// model, so a test can say "this model has no efforts" the same way the server
// does — and an empty default keeps the backend fallback in play.
let catalogReasoning: Record<string, { value: string; label: string }[]> = {};
+let catalogMenus: Record<string, { omitted: string[]; not_on: Record<string, string[]> }> = {};
// How many catalog reads were made, and whether the next ones wait to be answered.
let catalogReads = 0;
let deferReads = false;
@@ -50,6 +60,8 @@ vi.mock('../../lib/backendModels', async (importOriginal) => ({
models: string[];
modelLabels: Record<string, string>;
reasoningOptions: Record<string, { value: string; label: string }[]>;
+ effortMenus?: Record<string, { omitted: string[]; not_on: Record<string, string[]> }>;
+ hubUnread?: true;
catalogRefreshPending: boolean;
}) => void,
) => {
@@ -58,6 +70,8 @@ vi.mock('../../lib/backendModels', async (importOriginal) => ({
models: ['sonnet', 'opus'],
modelLabels: {},
reasoningOptions: catalogReasoning,
+ // As the real loader answers: only a Hub catalog carries effort menus.
+ ...(hubUnread ? { hubUnread: true as const } : hubMode === 'hub' ? { effortMenus: catalogMenus } : {}),
catalogRefreshPending: false,
});
if (deferReads) pendingReads.push(answer);
@@ -66,6 +80,9 @@ vi.mock('../../lib/backendModels', async (importOriginal) => ({
},
}));
+/** The open menu's effort column: the trigger also names the current effort. */
+const effortColumn = () => within(screen.getByText('chat.picker.effort').parentElement as HTMLElement);
+
const agent = (over: Partial<VibeAgentBrief> = {}): VibeAgentBrief =>
({
id: 'agt-claude',
@@ -148,13 +165,14 @@ const HubPicker: React.FC<{
role: InstanceRole;
surfaceActive?: boolean;
onNavigateAway?: () => void;
-}> = ({ role, surfaceActive = true, onNavigateAway }) => (
+ onChange?: (value: AgentRouteValue) => void;
+}> = ({ role, surfaceActive = true, onNavigateAway, onChange = () => {} }) => (
<InstanceAuthorizationContext.Provider
value={{ remote: false, instanceKind: null, instanceRole: role, capabilities: capabilitiesFor(role) }}
>
<RouteSurfaceActiveContext.Provider value={surfaceActive}>
<MemoryRouter>
- <AgentRoutePicker value={CLAUDE_ROUTE} agents={AGENTS} onChange={() => {}} onNavigateAway={onNavigateAway} />
+ <AgentRoutePicker value={CLAUDE_ROUTE} agents={AGENTS} onChange={onChange} onNavigateAway={onNavigateAway} />
<LocationProbe />
</MemoryRouter>
</RouteSurfaceActiveContext.Provider>
@@ -165,7 +183,10 @@ describe('AgentRoutePicker', () => {
afterEach(() => {
cleanup();
catalogReasoning = {};
+ catalogMenus = {};
+ sourceNames = null;
hubMode = 'direct';
+ hubUnread = false;
catalogReads = 0;
deferReads = false;
pendingReads.length = 0;
@@ -231,6 +252,156 @@ describe('AgentRoutePicker', () => {
expect(screen.getByText('chat.picker.effort')).toBeTruthy();
});
+ it('MH-EFFORT-MENU-002: names the Sources that refuse an effort, and says some do when it cannot read them', async () => {
+ hubMode = 'hub';
+ catalogReasoning = { sonnet: [{ value: 'low', label: 'low' }, { value: 'high', label: 'high' }] };
+ catalogMenus = { sonnet: { omitted: [], not_on: { high: ['src_relaygpt1'] } } };
+ sourceNames = { src_relaygpt1: 'relay-gpt' };
+ const user = userEvent.setup();
+ render(<HubPicker role="owner" />);
+ await openMenu(user);
+
+ expect(effortColumn().getByRole('button', { name: /chat\.picker\.effortOptions\.high/ }).textContent)
+ .toContain('chat.picker.effortNotOn:relay-gpt');
+ // An effort every hop serves carries no hint.
+ expect(effortColumn().getByRole('button', { name: /chat\.picker\.effortOptions\.low/ }).textContent)
+ .toBe('chat.picker.effortOptions.low');
+ cleanup();
+
+ // A role that may not read Sources still learns that some refuse it.
+ sourceNames = null;
+ render(<HubPicker role="owner" />);
+ await openMenu(user);
+ expect(effortColumn().getByRole('button', { name: /chat\.picker\.effortOptions\.high/ }).textContent)
+ .toContain('chat.picker.effortNotOnSome');
+ });
+
+ it('MH-EFFORT-MENU-003: keeps a saved effort routing now refuses everywhere visible as itself, and says so', async () => {
+ // The route holds `low`; Model Hub now leaves it out because every hop refuses it.
+ hubMode = 'hub';
+ catalogReasoning = { sonnet: [{ value: 'high', label: 'high' }] };
+ catalogMenus = { sonnet: { omitted: ['low'], not_on: {} } };
+ const user = userEvent.setup();
+ render(<HubPicker role="owner" />);
+ await openMenu(user);
+
+ const saved = effortColumn().getByRole('button', { name: /chat\.picker\.effortOptions\.low/ });
+ expect(saved.textContent).toContain('chat.picker.effortRefused');
+ expect(saved.className).toContain('text-cyan-ink');
+ // What routing serves is still offered, without the mark.
+ expect(effortColumn().getByRole('button', { name: /chat\.picker\.effortOptions\.high/ }).textContent)
+ .toBe('chat.picker.effortOptions.high');
+ });
+
+ it('keeps the effort column in its own grid column when the refused saved effort is its only item', async () => {
+ hubMode = 'hub';
+ catalogReasoning = { sonnet: [] };
+ catalogMenus = { sonnet: { omitted: ['low'], not_on: {} } };
+ const user = userEvent.setup();
+ render(<HubPicker role="owner" />);
+ await openMenu(user);
+
+ const column = screen.getByText('chat.picker.effort').parentElement as HTMLElement;
+ expect((column.parentElement as HTMLElement).className).toContain('sm:grid-cols-[1fr_1.35fr_0.7fr]');
+ });
+
+ it('reads a refusal only from the effort\'s own entry, never one an effort name inherits', async () => {
+ // Efforts are free-form: one named like an Object property has no entry of its own.
+ hubMode = 'hub';
+ catalogReasoning = { sonnet: [{ value: 'constructor', label: 'constructor' }, { value: 'high', label: 'high' }] };
+ catalogMenus = { sonnet: { omitted: [], not_on: { high: ['src_relaygpt1'] } } };
+ sourceNames = { src_relaygpt1: 'relay-gpt' };
+ const user = userEvent.setup();
+ render(<HubPicker role="owner" />);
+ await openMenu(user);
+
+ expect(effortColumn().getByRole('button', { name: /chat\.picker\.effortOptions\.constructor/ }).textContent)
+ .toBe('chat.picker.effortOptions.constructor');
+ expect(effortColumn().getByRole('button', { name: /chat\.picker\.effortOptions\.high/ }).textContent)
+ .toContain('chat.picker.effortNotOn:relay-gpt');
+ });
+
+ it('reads a Hub catalog again on every open, since its effort menu follows evidence any turn can change', async () => {
+ hubMode = 'hub';
+ catalogReasoning = { sonnet: [{ value: 'low', label: 'low' }, { value: 'high', label: 'high' }] };
+ const user = userEvent.setup();
+ render(<HubPicker role="owner" />);
+ await openMenu(user);
+ expect(catalogReads).toBe(1);
+ await user.keyboard('{Escape}');
+
+ // A turn recorded that every hop refuses `high`.
+ catalogReasoning = { sonnet: [{ value: 'low', label: 'low' }] };
+ catalogMenus = { sonnet: { omitted: ['high'], not_on: {} } };
+ await openMenu(user);
+ expect(catalogReads).toBe(2);
+ expect(effortColumn().queryByRole('button', { name: /chat\.picker\.effortOptions\.high/ })).toBeNull();
+ });
+
+ it('keeps the last Hub answer, and reads Hub again, when one open falls back to the native list', async () => {
+ // Hub: every hop refuses the route's `low`.
+ hubMode = 'hub';
+ catalogReasoning = { sonnet: [{ value: 'high', label: 'high' }] };
+ catalogMenus = { sonnet: { omitted: ['low'], not_on: {} } };
+ const user = userEvent.setup();
+ render(<HubPicker role="owner" />);
+ await openMenu(user);
+ await user.keyboard('{Escape}');
+
+ // This open's Hub read failed over to the native ladder, which offers `low` and
+ // says nothing about Hub routing: the Hub answer stands.
+ hubUnread = true;
+ catalogReasoning = { sonnet: [{ value: 'low', label: 'low' }, { value: 'high', label: 'high' }] };
+ await openMenu(user);
+ expect(catalogReads).toBe(2);
+ expect(effortColumn().getByRole('button', { name: /chat\.picker\.effortOptions\.low/ }).textContent)
+ .toContain('chat.picker.effortRefused');
+ await user.keyboard('{Escape}');
+
+ // Hub answers again, and the next open still asks it.
+ hubUnread = false;
+ await openMenu(user);
+ expect(catalogReads).toBe(3);
+ });
+
+ it('takes a confirmed Direct answer over an earlier Hub one', async () => {
+ hubMode = 'hub';
+ catalogReasoning = { sonnet: [{ value: 'high', label: 'high' }] };
+ catalogMenus = { sonnet: { omitted: ['low'], not_on: {} } };
+ const user = userEvent.setup();
+ render(<HubPicker role="owner" />);
+ await openMenu(user);
+ await user.keyboard('{Escape}');
+
+ // Another tab switched the backend to Direct: its native list is the answer now.
+ hubMode = 'direct';
+ catalogReasoning = { sonnet: [{ value: 'low', label: 'low' }, { value: 'high', label: 'high' }] };
+ await openMenu(user);
+ expect(effortColumn().getByRole('button', { name: /chat\.picker\.effortOptions\.low/ }).textContent)
+ .toBe('chat.picker.effortOptions.low');
+ await user.keyboard('{Escape}');
+
+ // And it is cached like any Direct list again: reopening reads nothing (a native
+ // read may start a CLI).
+ const reads = catalogReads;
+ await openMenu(user);
+ expect(catalogReads).toBe(reads);
+ });
+
+ it('keeps a refused saved effort when the current model is chosen again', async () => {
+ hubMode = 'hub';
+ catalogReasoning = { sonnet: [{ value: 'high', label: 'high' }] };
+ catalogMenus = { sonnet: { omitted: ['low'], not_on: {} } };
+ const onChange = vi.fn();
+ const user = userEvent.setup();
+ render(<HubPicker role="owner" onChange={onChange} />);
+ await openMenu(user);
+
+ await user.click(screen.getByRole('button', { name: 'sonnet' }));
+ // Nothing changed, so nothing clears the effort the route holds.
+ expect(onChange.mock.calls.map(([value]) => value.reasoning_effort)).not.toContain(null);
+ });
+
it('reads the list again for a menu left open while Settings covered it', async () => {
const user = userEvent.setup();
const { rerender } = render(<HubPicker role="owner" />);
diff --git a/ui/src/components/workbench/AgentRoutePicker.tsx b/ui/src/components/workbench/AgentRoutePicker.tsx
index b2798ab24..35facb4a7 100644
--- a/ui/src/components/workbench/AgentRoutePicker.tsx
+++ b/ui/src/components/workbench/AgentRoutePicker.tsx
@@ -6,8 +6,11 @@ import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import type { VibeAgentBrief } from '../../context/ApiContext';
-import { loadBackendModelsWithRefresh, modelOptionLabel, useAddModelExit } from '../../lib/backendModels';
-import { isEffortSupported, resolveEffortOptions } from '../../lib/effortOptions';
+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
+import type { EffortMenu } from '../settings/models/types';
+import { loadBackendModelsWithRefresh, modelOptionLabel, supersedesHubAnswer, useAddModelExit } from '../../lib/backendModels';
+import { isEffortSupported, refusedSavedEffort, resolveEffortOptions } from '../../lib/effortOptions';
+import { useSourceNames } from '../../lib/useSourceNames';
import { useRouteSurfaceActive } from '../../lib/routeSurfaceActivity';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Button } from '../ui/button';
@@ -97,6 +100,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
}) => {
const { t } = useTranslation();
const api = useApi();
+ const authorization = useInstanceAuthorization();
const navigate = useNavigate();
const [open, setOpen] = useState(false);
const [modelsByBackend, setModelsByBackend] = useState<Record<string, string[]>>({});
@@ -104,7 +108,16 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
const [reasoningByBackend, setReasoningByBackend] = useState<
Record<string, Record<string, ReasoningOption[]>>
>({});
+ // Per backend, per model: what routing would do with its efforts now (Model
+ // Hub's `effort_menu`), for the column's "not on: <Source>" hints and a saved
+ // effort it refuses everywhere.
+ const [effortMenusByBackend, setEffortMenusByBackend] = useState<
+ Record<string, Record<string, EffortMenu>>
+ >({});
const loadedModelBackendsRef = useRef<Set<string>>(new Set());
+ // Backends whose catalog Model Hub answered: their effort menus are read on
+ // every open, even after one open fell back to the native list.
+ const hubBackendsRef = useRef<Set<string>>(new Set());
const surfaceActive = useRouteSurfaceActive();
const [loadingModels, setLoadingModels] = useState(false);
// Free-text filter for the model column — long backends (OpenCode) list dozens.
@@ -199,9 +212,11 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
useEffect(() => {
if (surfaceActive) return;
loadedModelBackendsRef.current.clear();
+ hubBackendsRef.current.clear();
setModelsByBackend({});
setModelLabelsByBackend({});
setReasoningByBackend({});
+ setEffortMenusByBackend({});
}, [surfaceActive]);
const grouped = useMemo(() => {
@@ -214,7 +229,10 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
// Fetch the active backend's model list the first time the menu opens for it;
// cached per backend so toggling agents doesn't refetch. A menu left open
- // under Settings reads again as it is uncovered.
+ // under Settings reads again as it is uncovered. A Hub catalog is read again on
+ // every open: its effort menu follows capability evidence, which any turn can
+ // change, and the read is the persisted catalog, which starts no CLI. The last
+ // answer shows until the new one lands.
useEffect(() => {
const loadedBackends = loadedModelBackendsRef.current;
if (!open || !surfaceActive || !backend || loadedBackends.has(backend)) return;
@@ -224,12 +242,21 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
const cancel = loadBackendModelsWithRefresh(
api,
backend,
- ({ models, modelLabels, reasoningOptions, catalogRefreshPending }) => {
- reloadOnNextOpen = Boolean(catalogRefreshPending);
+ (result) => {
+ const { models, modelLabels, reasoningOptions, effortMenus, catalogRefreshPending } = result;
+ const knownHub = hubBackendsRef.current.has(backend);
+ // A Hub answer marks the backend as Hub, a confirmed Direct one unmarks it
+ // (back to the per-mount Direct cache); an unread Hub changes neither.
+ if (effortMenus !== undefined) hubBackendsRef.current.add(backend);
+ else if (!result.hubUnread) hubBackendsRef.current.delete(backend);
+ reloadOnNextOpen = Boolean(catalogRefreshPending) || hubBackendsRef.current.has(backend);
+ setLoadingModels(false);
+ // A transient Hub failure answers with the native list: the last Hub answer stands.
+ if (!supersedesHubAnswer(result, knownHub)) return;
setReasoningByBackend((prev) => ({ ...prev, [backend]: reasoningOptions ?? {} }));
+ setEffortMenusByBackend((prev) => ({ ...prev, [backend]: effortMenus ?? {} }));
setModelsByBackend((prev) => ({ ...prev, [backend]: models }));
setModelLabelsByBackend((prev) => ({ ...prev, [backend]: modelLabels ?? {} }));
- setLoadingModels(false);
},
() => {
loadedBackends.delete(backend);
@@ -274,6 +301,28 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
() => (catalogAnswered ? resolveEffortOptions(backend, currentModel, backendReasoning) : []),
[catalogAnswered, backend, currentModel, backendReasoning],
);
+ const effortMenus = effortMenusByBackend[backend];
+ const effortNotOn = (currentModel && effortMenus?.[currentModel]?.not_on) || null;
+ // Routing now refuses the saved effort on every hop: it is out of the menu, but
+ // the route still sends it, so it shows as itself and says so.
+ const refusedEffort = catalogAnswered ? refusedSavedEffort(currentEffort, currentModel, effortMenus) : null;
+ // The layout and the column read one answer, so a refused-only column keeps its place.
+ const showEffortColumn = effortOptions.length > 0 || refusedEffort !== null;
+ // Names only when an effort needs one; a role that cannot read Sources gets the
+ // hint without them.
+ const sourceNames = useSourceNames(
+ open && effortNotOn !== null && Object.keys(effortNotOn).length > 0,
+ surfaceActive,
+ authorization.instanceRole ?? 'none',
+ );
+ const notOnLabel = (effort: string): string | null => {
+ // Efforts are free-form strings: only the map's own entry for this one counts,
+ // never one inherited from Object.prototype (an effort named "constructor").
+ const ids = effortNotOn && Object.prototype.hasOwnProperty.call(effortNotOn, effort) ? effortNotOn[effort] : null;
+ if (!Array.isArray(ids) || ids.length === 0) return null;
+ if (!sourceNames) return t('chat.picker.effortNotOnSome');
+ return t('chat.picker.effortNotOn', { sources: ids.map((id) => sourceNames[id] ?? id).join(', ') });
+ };
return (
<Popover open={open} onOpenChange={setOpen} modal={modal}>
@@ -343,7 +392,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
<div
className={clsx(
'grid grid-cols-1 divide-y divide-border sm:divide-x sm:divide-y-0',
- effortOptions.length > 0 ? 'sm:grid-cols-[1fr_1.35fr_0.7fr]' : 'sm:grid-cols-[1fr_1.35fr]',
+ showEffortColumn ? 'sm:grid-cols-[1fr_1.35fr_0.7fr]' : 'sm:grid-cols-[1fr_1.35fr]',
)}
>
{/* Column 1 — Agent */}
@@ -447,8 +496,9 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
const patch: AgentRoutePatch = { model };
// Switching to a model whose effort set no longer includes
// the current effort: clear it in the same patch so the displayed
- // route matches what dispatches.
- if (!isEffortSupported(backend, model, currentEffort, backendReasoning)) {
+ // route matches what dispatches. Choosing the current model
+ // again changes nothing, a refused saved effort included.
+ if (model !== currentModel && !isEffortSupported(backend, model, currentEffort, backendReasoning)) {
patch.reasoning_effort = null;
}
applyPatch(patch);
@@ -479,19 +529,31 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({
</RouteColumn>
{/* Column 3 — Effort (uses per-model catalog entries when available) */}
- {effortOptions.length > 0 && (
+ {showEffortColumn && (
<RouteColumn title={t('chat.picker.effort')}>
- {effortOptions.map((opt) => (
- <RouteItem
- key={opt}
- active={opt === currentEffort}
- onClick={() => applyPatch({ reasoning_effort: opt })}
- >
- <span className="flex-1 capitalize">
- {t(`chat.picker.effortOptions.${opt}`, { defaultValue: opt })}
+ {refusedEffort && (
+ <RouteItem active onClick={() => setOpen(false)}>
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="capitalize">{t(`chat.picker.effortOptions.${refusedEffort}`, { defaultValue: refusedEffort })}</span>
+ <span className="text-[10px] leading-snug text-gold-ink">{t('chat.picker.effortRefused')}</span>
</span>
</RouteItem>
- ))}
+ )}
+ {effortOptions.map((opt) => {
+ const notOn = notOnLabel(opt);
+ return (
+ <RouteItem
+ key={opt}
+ active={opt === currentEffort}
+ onClick={() => applyPatch({ reasoning_effort: opt })}
+ >
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="capitalize">{t(`chat.picker.effortOptions.${opt}`, { defaultValue: opt })}</span>
+ {notOn && <span className="text-[10px] leading-snug text-muted">{notOn}</span>}
+ </span>
+ </RouteItem>
+ );
+ })}
</RouteColumn>
)}
</div>
diff --git a/ui/src/components/workbench/AgentsPage.test.tsx b/ui/src/components/workbench/AgentsPage.test.tsx
index 6d90962f7..607125ea7 100644
--- a/ui/src/components/workbench/AgentsPage.test.tsx
+++ b/ui/src/components/workbench/AgentsPage.test.tsx
@@ -51,6 +51,8 @@ vi.mock('./CapabilityTabs', () => ({ CapabilityTabs: () => null }));
type FakeModelCatalog = {
models: string[];
reasoningOptions?: Record<string, { value: string; label: string }[]>;
+ effortMenus?: Record<string, { omitted: string[]; not_on: Record<string, string[]> }>;
+ hubUnread?: true;
};
let modelCatalog: FakeModelCatalog = { models: [] };
let modelCatalogReads = 0;
@@ -62,9 +64,12 @@ vi.mock('../../lib/backendModels', async (importOriginal) => ({
loadBackendModelsWithRefresh: (_api: unknown, _backend: string, onLoaded: (payload: FakeModelCatalog) => void) => {
modelCatalogReads += 1;
const catalog = modelCatalog;
- if (deferModelReads) pendingModelReads.push(() => onLoaded(catalog));
- else onLoaded(catalog);
- return () => {};
+ // As the real loader: a cancelled read never answers.
+ let cancelled = false;
+ const answer = () => { if (!cancelled) onLoaded(catalog); };
+ if (deferModelReads) pendingModelReads.push(answer);
+ else answer();
+ return () => { cancelled = true; };
},
}));
vi.mock('react-i18next', () => ({
@@ -1661,6 +1666,175 @@ describe('AgentsPage reconnect reconciliation', () => {
expect(screen.getByRole('button', { name: 'medium', exact: true }).className).not.toContain('bg-mint-soft');
});
+ it('MH-EFFORT-MENU-003: shows a saved effort routing now refuses on every hop as itself, and says so', async () => {
+ // Model Hub leaves the explicit Off (`none`) out of the menu, but this Agent still sends it.
+ modelCatalog = {
+ models: [],
+ reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }] },
+ effortMenus: { 'reasoning-model': { omitted: ['none'], not_on: {} } },
+ };
+ const initial = { ...brief('agent-a', 'description'), model: 'reasoning-model', reasoning_effort: 'none' };
+ const getVibeAgent = vi.fn().mockResolvedValue(fullAgent(initial, 'initial prompt'));
+ const api = makeApi(vi.fn().mockResolvedValue(listResult(initial)), getVibeAgent);
+ renderPage(api, { canManageAgents: true });
+
+ await waitFor(() => expect(screen.getByDisplayValue('description')).toBeTruthy());
+ // Named as the page names it anywhere else, not as the raw token.
+ expect(screen.getByText('chat.picker.effortOptions.none').getAttribute('title')).toBe('chat.picker.effortRefused');
+ expect(screen.queryByText('none', { exact: true })).toBeNull();
+ expect(screen.getByText('chat.picker.effortRefused')).toBeTruthy();
+ // It is not offered: only what routing still serves can be picked.
+ expect(screen.queryByRole('button', { name: 'chat.picker.effortOptions.none' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'medium', exact: true }).className).not.toContain('bg-mint-soft');
+ });
+
+ it('writes nothing, and keeps a refused saved effort, when the current model is chosen again', async () => {
+ modelCatalog = {
+ models: [],
+ reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }] },
+ effortMenus: { 'reasoning-model': { omitted: ['xhigh'], not_on: {} } },
+ };
+ const initial = { ...brief('agent-a', 'description'), model: 'reasoning-model', reasoning_effort: 'xhigh' };
+ const getVibeAgent = vi.fn().mockResolvedValue(fullAgent(initial, 'initial prompt'));
+ const updateVibeAgent = vi.fn().mockResolvedValue({ ok: true });
+ const api = makeApi(vi.fn().mockResolvedValue(listResult(initial)), getVibeAgent, undefined, undefined, updateVibeAgent);
+ renderPage(api, { canManageAgents: true });
+
+ await waitFor(() => expect(screen.getByDisplayValue('description')).toBeTruthy());
+ fireEvent.click(screen.getByRole('combobox'));
+ fireEvent.change(screen.getByPlaceholderText('Search...'), { target: { value: 'reasoning-model' } });
+ fireEvent.click(screen.getByText('Use "reasoning-model"'));
+
+ expect(updateVibeAgent).not.toHaveBeenCalled();
+ expect(screen.getByText('xhigh', { exact: true }).getAttribute('title')).toBe('chat.picker.effortRefused');
+ });
+
+ it('reads the effort menu again as the effort field is used, since any turn can change it', async () => {
+ modelCatalog = {
+ models: [],
+ reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }, { value: 'xhigh', label: 'xhigh' }] },
+ effortMenus: { 'reasoning-model': { omitted: [], not_on: {} } },
+ };
+ const initial = { ...brief('agent-a', 'description'), model: 'reasoning-model', reasoning_effort: 'medium' };
+ const getVibeAgent = vi.fn().mockResolvedValue(fullAgent(initial, 'initial prompt'));
+ const api = makeApi(vi.fn().mockResolvedValue(listResult(initial)), getVibeAgent);
+ renderPage(api, { canManageAgents: true });
+ await waitFor(() => expect(screen.getByRole('button', { name: 'xhigh', exact: true })).toBeTruthy());
+
+ // Another session's turn records that every hop refuses `xhigh`.
+ modelCatalog = {
+ models: [],
+ reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }] },
+ effortMenus: { 'reasoning-model': { omitted: ['xhigh'], not_on: {} } },
+ };
+ fireEvent.pointerEnter(document.querySelector('[data-effort-field]') as HTMLElement);
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'xhigh', exact: true })).toBeNull());
+ });
+
+ it('keeps the last Hub effort menu when a refresh falls back to the native list, and asks Hub again next time', async () => {
+ const hub = {
+ models: [],
+ reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }] },
+ effortMenus: { 'reasoning-model': { omitted: ['xhigh'], not_on: {} } },
+ };
+ modelCatalog = hub;
+ const initial = { ...brief('agent-a', 'description'), model: 'reasoning-model', reasoning_effort: 'medium' };
+ const api = makeApi(vi.fn().mockResolvedValue(listResult(initial)), vi.fn().mockResolvedValue(fullAgent(initial, 'prompt')));
+ renderPage(api, { canManageAgents: true });
+ await waitFor(() => expect(screen.getByRole('button', { name: 'medium', exact: true })).toBeTruthy());
+ const field = () => document.querySelector('[data-effort-field]') as HTMLElement;
+
+ // A refresh whose Hub read failed answers with the native ladder, which offers `xhigh`.
+ const native = { models: [], reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }, { value: 'xhigh', label: 'xhigh' }] } };
+ modelCatalog = { ...native, hubUnread: true };
+ fireEvent.pointerEnter(field());
+ expect(screen.queryByRole('button', { name: 'xhigh', exact: true })).toBeNull();
+
+ // Hub answers again, and the next use of the field still asks it.
+ modelCatalog = hub;
+ const reads = modelCatalogReads;
+ fireEvent.pointerEnter(field());
+ expect(modelCatalogReads).toBe(reads + 1);
+
+ // Another tab switched the backend to Direct: a confirmed answer replaces the Hub one.
+ modelCatalog = native;
+ fireEvent.pointerEnter(field());
+ expect(screen.getByRole('button', { name: 'xhigh', exact: true })).toBeTruthy();
+ // And the Hub-only re-reads end with it: a native read may start a CLI.
+ const directReads = modelCatalogReads;
+ fireEvent.pointerEnter(field());
+ expect(modelCatalogReads).toBe(directReads);
+ });
+
+ it('reads the effort menu once per approach to the field, not on every focus move inside it', async () => {
+ modelCatalog = {
+ models: [],
+ reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }, { value: 'high', label: 'High' }] },
+ effortMenus: { 'reasoning-model': { omitted: [], not_on: {} } },
+ };
+ const initial = { ...brief('agent-a', 'description'), model: 'reasoning-model', reasoning_effort: 'medium' };
+ const api = makeApi(vi.fn().mockResolvedValue(listResult(initial)), vi.fn().mockResolvedValue(fullAgent(initial, 'prompt')));
+ renderPage(api, { canManageAgents: true });
+ await waitFor(() => expect(screen.getByRole('button', { name: 'high', exact: true })).toBeTruthy());
+ const field = document.querySelector('[data-effort-field]') as HTMLElement;
+ const medium = screen.getByRole('button', { name: 'medium', exact: true });
+ const high = screen.getByRole('button', { name: 'high', exact: true });
+
+ deferModelReads = true;
+ const reads = modelCatalogReads;
+ // The pointer arrives and the click focuses a button: one approach, one read.
+ fireEvent.pointerEnter(field);
+ fireEvent.focusIn(medium);
+ expect(modelCatalogReads).toBe(reads + 1);
+ act(() => pendingModelReads.shift()!());
+
+ // Tabbing between the field's own buttons is not a new approach.
+ fireEvent.focusIn(high, { relatedTarget: medium });
+ expect(modelCatalogReads).toBe(reads + 1);
+ });
+
+ it('drops an effort-menu read still out when Settings covers the page', async () => {
+ modelCatalog = {
+ models: [],
+ reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }, { value: 'xhigh', label: 'xhigh' }] },
+ effortMenus: { 'reasoning-model': { omitted: [], not_on: {} } },
+ };
+ const initial = { ...brief('agent-a', 'description'), model: 'reasoning-model', reasoning_effort: 'medium' };
+ const api = makeApi(vi.fn().mockResolvedValue(listResult(initial)), vi.fn().mockResolvedValue(fullAgent(initial, 'prompt')));
+ apiRef.current = api;
+ const page = (surfaceActive: boolean) => (
+ <InstanceAuthorizationContext.Provider
+ value={{ remote: false, instanceKind: null, instanceRole: 'owner', capabilities: { ...OWNER_INSTANCE_CAPABILITIES, can_manage_agents: true } }}
+ >
+ <RouteSurfaceActiveContext.Provider value={surfaceActive}>
+ <MemoryRouter initialEntries={['/agents']}>
+ <AgentsPage />
+ </MemoryRouter>
+ </RouteSurfaceActiveContext.Provider>
+ </InstanceAuthorizationContext.Provider>
+ );
+ const view = render(page(true));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'xhigh', exact: true })).toBeTruthy());
+
+ // A refresh goes out with the old menu, then Settings covers the page while a
+ // turn elsewhere records that every hop refuses `xhigh`.
+ deferModelReads = true;
+ fireEvent.pointerEnter(document.querySelector('[data-effort-field]') as HTMLElement);
+ modelCatalog = {
+ models: [],
+ reasoningOptions: { 'reasoning-model': [{ value: 'medium', label: 'Medium' }] },
+ effortMenus: { 'reasoning-model': { omitted: ['xhigh'], not_on: {} } },
+ };
+ view.rerender(page(false));
+ view.rerender(page(true));
+ const [stale, fresh] = pendingModelReads;
+ act(() => fresh());
+ expect(screen.queryByRole('button', { name: 'xhigh', exact: true })).toBeNull();
+ // The read from before the visit lands last, and must not bring `xhigh` back.
+ act(() => stale());
+ expect(screen.queryByRole('button', { name: 'xhigh', exact: true })).toBeNull();
+ });
+
it('keeps a still-valid effort untouched when the model changes', async () => {
modelCatalog = {
models: [],
diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsx
index 2564c9d80..24970f41d 100644
--- a/ui/src/components/workbench/AgentsPage.tsx
+++ b/ui/src/components/workbench/AgentsPage.tsx
@@ -50,8 +50,8 @@ import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { onPageReactivated } from '../../lib/pageActivity';
import { useRouteSurfaceActive } from '../../lib/routeSurfaceActivity';
import { estimateTokens } from '../../lib/tokenEstimate';
-import { loadBackendModelsWithRefresh, modelOptionLabel, useAddModelExit } from '../../lib/backendModels';
-import { compatibleEffort, resolveEffortOptions } from '../../lib/effortOptions';
+import { loadBackendModelsWithRefresh, modelOptionLabel, supersedesHubAnswer, useAddModelExit, type BackendModels } from '../../lib/backendModels';
+import { compatibleEffort, refusedSavedEffort, resolveEffortOptions } from '../../lib/effortOptions';
import { WorkbenchPageHeader } from './WorkbenchPageHeader';
import { CapabilityTabs } from './CapabilityTabs';
// Backend order / labels / accent classes live in lib/backendAccent, shared
@@ -68,6 +68,7 @@ import { BackendAvatar } from '../visual';
import { isBuiltinAgent } from '../onboarding/setupTargets';
import { modelsApi } from '../settings/models/modelsApi';
import { agentsWithoutModel } from '../settings/models/supply';
+import type { EffortMenu } from '../settings/models/types';
import { errorMessage } from '@/lib/errorMessage';
// Tab set + its cross-visit memory live together so the remembered value can
// never name a tab this page no longer renders (see agentsViewMemory).
@@ -2018,6 +2019,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca
{
modelOptions: ComboboxOption[];
reasoningOptions: Record<string, { value: string; label: string }[]>;
+ effortMenus?: Record<string, EffortMenu>;
}
>
>({});
@@ -2104,20 +2106,32 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca
// backend doesn't know about yet (e.g. a freshly-released preview). Read
// again when Settings uncovers the page: the Model Hub there edits the list,
// so the rows read before the visit go when Settings covers it.
+ const applyModelCatalog = useCallback((backend: string, { models, modelLabels, reasoningOptions: opts, effortMenus }: BackendModels) => {
+ setModelCatalogs((current) => ({
+ ...current,
+ [backend]: {
+ modelOptions: models.map((m) => ({ value: m, label: modelOptionLabel(m, modelLabels) })),
+ reasoningOptions: opts ?? {},
+ effortMenus,
+ },
+ }));
+ }, []);
+ // Whether this backend answered from Model Hub in this activation; only another
+ // Hub answer replaces a Hub one (`supersedesHubAnswer`).
+ const hubKnownRef = useRef(false);
+ const takeModelCatalog = useCallback((backend: string, result: BackendModels) => {
+ if (!supersedesHubAnswer(result, hubKnownRef.current)) return;
+ // A confirmed Direct answer ends the Hub-only re-reads; an unread Hub got here only if none was known.
+ if (result.effortMenus !== undefined) hubKnownRef.current = true;
+ else if (!result.hubUnread) hubKnownRef.current = false;
+ applyModelCatalog(backend, result);
+ }, [applyModelCatalog]);
useEffect(() => {
if (!surfaceActive) return;
const cancel = loadBackendModelsWithRefresh(
api,
agent.backend,
- ({ models, modelLabels, reasoningOptions: opts }) => {
- setModelCatalogs((current) => ({
- ...current,
- [agent.backend]: {
- modelOptions: models.map((m) => ({ value: m, label: modelOptionLabel(m, modelLabels) })),
- reasoningOptions: opts ?? {},
- },
- }));
- },
+ (result) => takeModelCatalog(agent.backend, result),
() => {
setModelCatalogs((current) => ({
...current,
@@ -2133,6 +2147,39 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca
return next;
});
};
+ }, [agent.backend, api, surfaceActive, takeModelCatalog]);
+
+ // A Hub catalog's effort menu follows capability evidence, which a turn in any
+ // session can change while this panel stays open. Like the route picker, which
+ // reads it as its menu opens, read it again as the user turns to the effort
+ // field, the moment it is chosen from; the last answer shows until it lands.
+ const effortRefreshRef = useRef<(() => void) | null>(null);
+ // One read per approach: a read still out answers for this one too. Dropping a
+ // read does not stop its request, so restarting would only add requests.
+ const effortRefreshOutRef = useRef(false);
+ const refreshEffortMenus = useCallback(() => {
+ if (!surfaceActive || !hubKnownRef.current || effortRefreshOutRef.current) return;
+ effortRefreshOutRef.current = true;
+ const backend = agent.backend;
+ const settle = () => { effortRefreshOutRef.current = false; };
+ effortRefreshRef.current = loadBackendModelsWithRefresh(
+ api,
+ backend,
+ (result) => {
+ settle();
+ takeModelCatalog(backend, result);
+ },
+ settle,
+ );
+ }, [agent.backend, api, surfaceActive, takeModelCatalog]);
+ // A refresh still out when the page is covered or its backend changes answers
+ // for a catalog this page no longer shows, so it is dropped.
+ useEffect(() => () => {
+ effortRefreshRef.current?.();
+ effortRefreshRef.current = null;
+ effortRefreshOutRef.current = false;
+ // A new activation or backend starts without knowing which catalog serves it.
+ hubKnownRef.current = false;
}, [agent.backend, api, surfaceActive]);
const lockHint = system
@@ -2143,6 +2190,9 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca
const systemPromptTokens = estimateTokens(systemPrompt);
// Effort options follow the backend + selected model when the catalog provides them.
const effortOptions = resolveEffortOptions(agent.backend, model, reasoningOptions);
+ // Routing now refuses the saved effort on every hop: out of the options, but the
+ // Agent still sends it, so it shows as itself and says so.
+ const refusedEffort = refusedSavedEffort(effort, model, activeModelCatalog?.effortMenus);
// The efforts shown before the catalog answers are the backend's fallback
// ladder, which may hold one the model rejects; they stay visible but cannot
// be picked until the read (or its failure) lands.
@@ -2434,7 +2484,9 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca
value={model}
onValueChange={(next) => {
const value = next.trim();
- if (!value) return;
+ // Choosing the current model again is no edit: nothing to write, and a
+ // refused saved effort stays what it is.
+ if (!value || value === model) return;
markFieldEdit('model');
markFieldSubmitted('model');
setModel(value);
@@ -2465,12 +2517,26 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca
{/* Reasoning effort — design.pen LsjxT. A model whose catalog row states
no efforts has nothing to choose, so the field is absent rather than an
empty outline the user would read as a control that failed to load. */}
- {effortOptions.length > 0 && (
+ {(effortOptions.length > 0 || refusedEffort) && (
<Field label={t('agents.detail.effort')}>
<div
className="grid gap-0.5 rounded-lg border border-border-strong bg-surface-2 p-0.5"
style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(3.25rem, 1fr))' }}
+ data-effort-field
+ onPointerEnter={refreshEffortMenus}
+ // Focus coming into the field, not moving between its buttons.
+ onFocusCapture={(event) => {
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) refreshEffortMenus();
+ }}
>
+ {refusedEffort && (
+ <span
+ title={t('chat.picker.effortRefused')}
+ className="truncate rounded-md bg-gold/10 px-1 py-1.5 text-center text-[11px] font-bold capitalize text-gold-ink"
+ >
+ {refusedEffort === 'none' ? t('chat.picker.effortOptions.none') : refusedEffort}
+ </span>
+ )}
{effortOptions.map((opt) => {
const active = effort === opt;
return (
@@ -2496,6 +2562,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca
);
})}
</div>
+ {refusedEffort && <span className="text-[11px] text-gold-ink">{t('chat.picker.effortRefused')}</span>}
</Field>
)}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index e0b76f38b..61fc6bbd3 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1,7 +1,7 @@
import React, { createContext, useContext, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useToast } from './ToastContext';
-import type { AgentSupply } from '../components/settings/models/types';
+import type { PickerAgentCatalog } from '../components/settings/models/types';
import type { AgentBackendId, NativeCliBackend, WebOAuthBackend } from '../lib/agentBackends';
import { apiFetch, recoverRemoteAuthFromSessionProbe, withApiDeadline } from '../lib/apiFetch';
import { isAuthorizationSensitiveReadPath } from '../lib/authorizationCache';
@@ -697,7 +697,7 @@ export type ApiContextType = {
/** Picker-safe persisted catalog. Null tells pickers to use the native fallback. */
readModelHubAgentCatalogForModelPicker: (
backend: string,
- ) => Promise<Pick<AgentSupply, 'backend' | 'mode' | 'catalog_models'> | null>;
+ ) => Promise<PickerAgentCatalog | null>;
getLogs: (lines?: number, source?: string) => Promise<{ logs: LogEntry[]; total: number; source: string; sources: LogSource[] }>;
getVersion: () => Promise<VersionInfo>;
doUpgrade: () => Promise<UpgradeResult>;
@@ -3679,7 +3679,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
.then((payload) => {
const agent = payload?.ok === false ? null : payload?.agent;
return agent && typeof agent === 'object'
- ? (agent as Pick<AgentSupply, 'backend' | 'mode' | 'catalog_models'>)
+ ? (agent as PickerAgentCatalog)
: null;
})
.catch(() => null),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b12c81b46..7d560919d 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -4688,6 +4688,9 @@
"agent": "Agent",
"model": "Model",
"effort": "Effort",
+ "effortNotOn": "Not on {{sources}}",
+ "effortNotOnSome": "Not on some Sources",
+ "effortRefused": "No Source accepts it now",
"newAgent": "New agent",
"addModel": "Add model",
"noModels": "No models found",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 15469af21..6c311ed1a 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -4688,6 +4688,9 @@
"agent": "Agent",
"model": "模型",
"effort": "思考强度",
+ "effortNotOn": "{{sources}} 不支持",
+ "effortNotOnSome": "部分供应商不支持",
+ "effortRefused": "当前没有供应商支持",
"newAgent": "新建 Agent",
"addModel": "添加模型",
"noModels": "未找到模型",
diff --git a/ui/src/lib/backendModels.test.ts b/ui/src/lib/backendModels.test.ts
index 23c2ad965..8550ca6fc 100644
--- a/ui/src/lib/backendModels.test.ts
+++ b/ui/src/lib/backendModels.test.ts
@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { blankBackendModel, candidateBackendModel } from '../components/settings/models/backendCatalog';
import type { AgentSupply, BackendModel } from '../components/settings/models/types';
import { ApiError, type ApiContextType } from '../context/ApiContext';
-import { fetchBackendModels, loadBackendModelsWithRefresh, modelOptionLabel } from './backendModels';
+import { fetchBackendModels, loadBackendModelsWithRefresh, modelOptionLabel, supersedesHubAnswer } from './backendModels';
import { resolveEffortOptions } from './effortOptions';
/** No Model Hub record to read, which is what every pre-Hub server, unreadable
@@ -108,6 +108,7 @@ describe('fetchBackendModels for OpenCode', () => {
reasoningOptions: {
'moonshotai/kimi-k2': [{ value: 'high', label: 'High' }],
},
+ hubUnread: true,
});
});
@@ -119,7 +120,7 @@ describe('fetchBackendModels for OpenCode', () => {
.mockRejectedValue(new ApiError('forbidden', 403, 'instance_access_forbidden')),
} as unknown as ApiContextType;
- await expect(fetchBackendModels(api, 'opencode')).resolves.toEqual({ models: [] });
+ await expect(fetchBackendModels(api, 'opencode')).resolves.toEqual({ models: [], hubUnread: true });
});
it('still propagates a failure that is not the expected refusal', async () => {
@@ -145,11 +146,12 @@ describe('fetchBackendModels in gateway mode', () => {
const readOpencodeOptionsForModelPicker = vi.fn();
const api = { readModelHubAgentCatalogForModelPicker, claudeModels, codexModels, readOpencodeOptionsForModelPicker } as unknown as ApiContextType;
expect(await fetchBackendModels(api, 'vibey')).toEqual({
- models: ['local-model'], modelLabels: { 'local-model': 'Local model' }, reasoningOptions: { 'local-model': [] },
+ models: ['local-model'], modelLabels: { 'local-model': 'Local model' }, reasoningOptions: { 'local-model': [] }, effortMenus: {},
});
expect(readModelHubAgentCatalogForModelPicker).toHaveBeenCalledWith('vibey');
readModelHubAgentCatalogForModelPicker.mockResolvedValue(null);
- expect(await fetchBackendModels(api, 'vibey')).toEqual({ models: [] });
+ // No answer from Model Hub: the native list, marked as such.
+ expect(await fetchBackendModels(api, 'vibey')).toEqual({ models: [], hubUnread: true });
expect(claudeModels).not.toHaveBeenCalled();
expect(codexModels).not.toHaveBeenCalled();
expect(readOpencodeOptionsForModelPicker).not.toHaveBeenCalled();
@@ -192,9 +194,50 @@ describe('fetchBackendModels in gateway mode', () => {
// the catalog never wrote may fall back to the generic ladder.
beta: [],
},
+ // No row states an effort menu, so nothing is left out or marked.
+ effortMenus: {},
});
});
+ it('MH-EFFORT-MENU-001: leaves out an effort every hop refuses and names the Sources that refuse one the others serve', async () => {
+ const api = {
+ readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(
+ hubAgent('vibey', {
+ catalog_models: [
+ {
+ ...model('gpt-6-astra', { supports_reasoning: true, reasoning_efforts: ['low', 'high', 'xhigh', 'ultra'] }),
+ // Model Hub's answer for this model now: `ultra` would fail on every
+ // hop it routes to; `xhigh` fails only on one of them.
+ effort_menu: { omitted: ['ultra'], not_on: { xhigh: ['src_relaygpt1'] } },
+ },
+ model('grok-4.6', { supports_reasoning: true, reasoning_efforts: ['low', 'high'] }),
+ ],
+ }),
+ ),
+ } as unknown as ApiContextType;
+
+ const result = await fetchBackendModels(api, 'vibey');
+
+ expect(resolveEffortOptions('vibey', 'gpt-6-astra', result.reasoningOptions)).toEqual(['low', 'high', 'xhigh']);
+ expect(result.effortMenus).toEqual({ 'gpt-6-astra': { omitted: ['ultra'], not_on: { xhigh: ['src_relaygpt1'] } } });
+ // A model with no evidence is offered exactly what its row declares.
+ expect(resolveEffortOptions('vibey', 'grok-4.6', result.reasoningOptions)).toEqual(['low', 'high']);
+ });
+
+ it('tells an unread Model Hub from a confirmed Direct answer, so a Hub answer is replaced only by an answer', async () => {
+ const claudeModels = vi.fn().mockResolvedValue({ ok: true, models: ['sonnet'] });
+ const read = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce({ backend: 'claude', mode: 'direct' });
+ const api = { readModelHubAgentCatalogForModelPicker: read, claudeModels } as unknown as ApiContextType;
+
+ const unread = await fetchBackendModels(api, 'claude');
+ const direct = await fetchBackendModels(api, 'claude');
+ expect(unread.hubUnread).toBe(true);
+ expect(direct.hubUnread).toBeUndefined();
+ // A surface that had a Hub answer keeps it over an unread Hub, and takes a Direct one.
+ expect(supersedesHubAnswer(unread, true)).toBe(false);
+ expect(supersedesHubAnswer(direct, true)).toBe(true);
+ });
+
it('states "no efforts" for every routeable model the catalog says does not reason', async () => {
const api = {
readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(
@@ -318,6 +361,7 @@ describe('fetchBackendModels in gateway mode', () => {
models: [],
modelLabels: {},
reasoningOptions: {},
+ effortMenus: {},
});
expect(codexModels).not.toHaveBeenCalled();
});
diff --git a/ui/src/lib/backendModels.ts b/ui/src/lib/backendModels.ts
index 59ab5cdea..a6ec0b1b6 100644
--- a/ui/src/lib/backendModels.ts
+++ b/ui/src/lib/backendModels.ts
@@ -3,7 +3,7 @@ import { useLocation, useNavigate } from 'react-router-dom';
import { routeableCatalogModelIds } from '../components/settings/models/backendCatalog';
import { modelHubCatalogPath } from '../components/settings/models/modelHubRoutes';
-import type { AgentSupply } from '../components/settings/models/types';
+import type { EffortMenu, PickerAgentCatalog } from '../components/settings/models/types';
import { ApiError, useApi, type ApiContextType } from '../context/ApiContext';
import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
import { useRouteSurfaceActive } from './routeSurfaceActivity';
@@ -15,10 +15,18 @@ export interface BackendModels {
models: string[];
/** Optional display labels keyed by model identifier; values remain raw ids. */
modelLabels?: Record<string, string>;
- /** Per-model reasoning-effort option sets; undefined when a backend has none. */
+ /** Per-model reasoning-effort option sets; undefined when a backend has none.
+ * A Hub catalog leaves out every effort routing would refuse on every hop. */
reasoningOptions?: Record<string, { value: string; label: string }[]>;
+ /** Per model, what routing would do with its efforts now (Model Hub's
+ * `effort_menu`): the efforts left out above, and by Source id the hops that
+ * refuse one the others still serve. Hub catalogs only. */
+ effortMenus?: Record<string, EffortMenu>;
/** True while a background remote-catalog refresh may produce a newer snapshot. */
catalogRefreshPending?: boolean;
+ /** Model Hub gave no answer (the read failed, or the server predates the read),
+ * so these are the native list. A Direct-mode answer is an answer: absent. */
+ hubUnread?: true;
}
const CATALOG_REFRESH_RETRY_DELAY_MS = 3_500;
@@ -32,8 +40,6 @@ export function modelOptionLabel(model: string, labels?: Record<string, string>)
// In Hub mode the persisted catalog is authoritative. A missing catalog uses
// the native fallback; an explicitly empty catalog remains an empty menu.
-type PickerAgentCatalog = Pick<AgentSupply, 'backend' | 'mode' | 'catalog_models'>;
-
const isHubAgent = (agent: PickerAgentCatalog | null, backend: string): agent is PickerAgentCatalog =>
agent !== null && agent.backend === backend && agent.mode === 'hub';
@@ -48,20 +54,36 @@ const hubCatalogModels = (agent: PickerAgentCatalog | null, backend: string): Ba
// "constructor" and "__proto__" from colliding with Object properties.
const modelLabels = Object.create(null) as Record<string, string>;
const reasoningOptions = Object.create(null) as Record<string, { value: string; label: string }[]>;
+ const effortMenus = Object.create(null) as Record<string, EffortMenu>;
for (const id of models) {
const row = rows.get(id);
if (!row) continue;
if (row.display_name) modelLabels[id] = row.display_name;
+ // Model Hub states what routing would do with each effort now (`effort_menu`):
+ // one every hop refuses would only fail, so it is not offered.
+ const omitted = new Set(row.effort_menu?.omitted ?? []);
// Every routeable model gets a key, including an empty one: the catalog is
// authoritative here, so "this model does not reason" must be sayable and
// must not read as "nobody answered" and fall back to the generic ladder.
reasoningOptions[id] = row.supports_reasoning === false
? []
- : row.reasoning_efforts.map((effort) => ({ value: effort, label: effort }));
+ : row.reasoning_efforts.filter((effort) => !omitted.has(effort)).map((effort) => ({ value: effort, label: effort }));
+ if (row.effort_menu) effortMenus[id] = row.effort_menu;
}
- return { models, modelLabels, reasoningOptions };
+ return { models, modelLabels, reasoningOptions, effortMenus };
};
+/**
+ * Whether `result` may replace what a surface shows for a backend. Model Hub
+ * answers with effort menus; a Hub read that fails comes back as the native
+ * list (`hubUnread`), which says nothing about Hub routing and would offer
+ * efforts Hub refuses. So once a backend has answered from Hub in a surface's
+ * activation, an unread Hub does not replace it: the last answer stands, and the
+ * next read asks Hub again. A confirmed Direct answer does replace it.
+ */
+export const supersedesHubAnswer = (result: BackendModels, knownHub: boolean): boolean =>
+ !knownHub || result.effortMenus !== undefined || result.hubUnread !== true;
+
// Single source of truth for "list the selectable models for a backend",
// shared by ChatPage, the Agents detail panel, and the New Agent dialog so a
// new backend (or a fix like OpenCode's provider-prefixing) lands in one place.
@@ -79,8 +101,14 @@ export async function fetchBackendModels(
api: ApiContextType,
backend: string,
): Promise<BackendModels> {
- const hub = hubCatalogModels(await api.readModelHubAgentCatalogForModelPicker(backend), backend);
+ const agent = await api.readModelHubAgentCatalogForModelPicker(backend);
+ const hub = hubCatalogModels(agent, backend);
if (hub) return hub;
+ const native = await nativeBackendModels(api, backend);
+ return agent === null ? { ...native, hubUnread: true } : native;
+}
+
+async function nativeBackendModels(api: ApiContextType, backend: string): Promise<BackendModels> {
if (!getBackendUiMeta(backend).capabilities.supports_cli) return { models: [] };
if (backend === 'claude') {
const res = await api.claudeModels();
diff --git a/ui/src/lib/effortOptions.ts b/ui/src/lib/effortOptions.ts
index e1dc1c0b4..3e2b79d04 100644
--- a/ui/src/lib/effortOptions.ts
+++ b/ui/src/lib/effortOptions.ts
@@ -123,3 +123,18 @@ export function isEffortSupported(
): boolean {
return !effort || resolveEffortOptions(backend, model, reasoningOptions).includes(effort);
}
+
+/**
+ * The saved effort when routing now refuses it on every hop (`effort_menu.omitted`),
+ * else null. The menu leaves such an effort out, but a route that already holds
+ * it still sends it, so it stays visible as itself, marked, rather than the menu
+ * silently reading as some other effort than the one that dispatches.
+ */
+export function refusedSavedEffort(
+ saved: string | null | undefined,
+ model: string | null | undefined,
+ effortMenus: Record<string, { omitted: readonly string[] }> | undefined,
+): string | null {
+ if (!saved || !model || !effortMenus || !Object.prototype.hasOwnProperty.call(effortMenus, model)) return null;
+ return effortMenus[model].omitted.includes(saved) ? saved : null;
+}
diff --git a/ui/src/lib/useSourceNames.test.ts b/ui/src/lib/useSourceNames.test.ts
new file mode 100644
index 000000000..225749db1
--- /dev/null
+++ b/ui/src/lib/useSourceNames.test.ts
@@ -0,0 +1,79 @@
+/** @vitest-environment jsdom */
+// Source names for a hint must follow Settings: a Source renamed there while the
+// naming surface stays mounted is read again the next time the hint is needed.
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { modelsApi } from '../components/settings/models/modelsApi';
+import type { Source } from '../components/settings/models/types';
+import { useSourceNames } from './useSourceNames';
+
+const named = (display_name: string) => [{ id: 'src_relaygpt1', display_name } as Source];
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('useSourceNames', () => {
+ const mount = () => renderHook(
+ ({ wanted, active, viewer }) => useSourceNames(wanted, active, viewer),
+ { initialProps: { wanted: true, active: true, viewer: 'member' } },
+ );
+
+ it('reads the names once per activation, and again after Settings covered the surface', async () => {
+ const list = vi.spyOn(modelsApi, 'listSources')
+ .mockResolvedValueOnce(named('relay-gpt'))
+ .mockResolvedValueOnce(named('relay-gpt-eu'));
+ const { result, rerender } = mount();
+ await waitFor(() => expect(result.current).toEqual({ src_relaygpt1: 'relay-gpt' }));
+
+ // Reopening the menu within one activation reads nothing: the Sources read is heavy.
+ act(() => rerender({ wanted: false, active: true, viewer: 'member' }));
+ act(() => rerender({ wanted: true, active: true, viewer: 'member' }));
+ expect(list).toHaveBeenCalledTimes(1);
+
+ // Settings, where a Source is renamed, covers the surface and uncovers it.
+ act(() => rerender({ wanted: true, active: false, viewer: 'member' }));
+ act(() => rerender({ wanted: true, active: true, viewer: 'member' }));
+ await waitFor(() => expect(result.current).toEqual({ src_relaygpt1: 'relay-gpt-eu' }));
+ expect(list).toHaveBeenCalledTimes(2);
+ });
+
+ it('drops names an earlier read gave when a later one is refused', async () => {
+ // A Member read, then the role is lowered to Editor: the hint goes generic.
+ vi.spyOn(modelsApi, 'listSources')
+ .mockResolvedValueOnce(named('relay-gpt'))
+ .mockRejectedValueOnce(new Error('forbidden'));
+ const { result, rerender } = mount();
+ await waitFor(() => expect(result.current).toEqual({ src_relaygpt1: 'relay-gpt' }));
+
+ act(() => rerender({ wanted: true, active: false, viewer: 'member' }));
+ act(() => rerender({ wanted: true, active: true, viewer: 'member' }));
+ await waitFor(() => expect(result.current).toBeNull());
+ });
+
+ it('reads again when the viewer changes, so names a role may no longer read are dropped', async () => {
+ // A Member reads the names; the role is lowered to Editor while the surface stays open.
+ vi.spyOn(modelsApi, 'listSources')
+ .mockResolvedValueOnce(named('relay-gpt'))
+ .mockRejectedValueOnce(new Error('forbidden'));
+ const { result, rerender } = mount();
+ await waitFor(() => expect(result.current).toEqual({ src_relaygpt1: 'relay-gpt' }));
+
+ act(() => rerender({ wanted: true, active: true, viewer: 'editor' }));
+ await waitFor(() => expect(result.current).toBeNull());
+ });
+
+ it('hides names read for another viewer at once, before the new viewer\'s read answers', async () => {
+ let answer!: (sources: Source[]) => void;
+ vi.spyOn(modelsApi, 'listSources')
+ .mockResolvedValueOnce(named('relay-gpt'))
+ .mockImplementationOnce(() => new Promise<Source[]>((resolve) => { answer = resolve; }));
+ const { result, rerender } = mount();
+ await waitFor(() => expect(result.current).toEqual({ src_relaygpt1: 'relay-gpt' }));
+
+ act(() => rerender({ wanted: true, active: true, viewer: 'editor' }));
+ // The Editor's read is still out: nothing the Member read shows meanwhile.
+ expect(result.current).toBeNull();
+ await act(async () => { answer(named('relay-gpt')); });
+ expect(result.current).toEqual({ src_relaygpt1: 'relay-gpt' });
+ });
+});
diff --git a/ui/src/lib/useSourceNames.ts b/ui/src/lib/useSourceNames.ts
new file mode 100644
index 000000000..d79ca5c14
--- /dev/null
+++ b/ui/src/lib/useSourceNames.ts
@@ -0,0 +1,47 @@
+import { useEffect, useMemo, useState } from 'react';
+
+import { modelsApi } from '../components/settings/models/modelsApi';
+
+/**
+ * Model Hub Source display names by id, read once per activation of the surface
+ * that shows them and per viewer (`viewer` names the role reading them), when
+ * it first wants them.
+ *
+ * Sources are renamed, added and replaced in Settings, which covers the surface,
+ * so each uncovering reads them afresh; the last names show until the new answer
+ * lands. Within one activation the names are read once, not on every open: the
+ * Sources read carries each Source's whole model list. The read is a Member rule,
+ * and some surfaces that name a Source (the Chat route picker) are Editor
+ * surfaces, so a refused read is an expected answer: it yields null, and the
+ * caller says what it can without the names.
+ */
+export function useSourceNames(wanted: boolean, surfaceActive: boolean, viewer: string): Record<string, string> | null {
+ // The names and the viewer they were read for: they show to that viewer only,
+ // so a role change hides them at once, before its own read answers.
+ const [names, setNames] = useState<{ viewer: string; byId: Record<string, string> } | null>(null);
+ // One token per activation and viewer: each change of `surfaceActive` starts a
+ // new activation, and a change of who is looking (a role change) may change
+ // whether the names may be read at all. The last answer belongs to one token.
+ const activation = useMemo(() => ({ surfaceActive, viewer }), [surfaceActive, viewer]);
+ const [answeredFor, setAnsweredFor] = useState<object | null>(null);
+ useEffect(() => {
+ if (!wanted || !surfaceActive || answeredFor === activation) return undefined;
+ let current = true;
+ modelsApi.listSources().then(
+ (sources) => {
+ if (!current) return;
+ setNames({ viewer, byId: Object.fromEntries(sources.map((source) => [source.id, source.display_name])) });
+ setAnsweredFor(activation);
+ },
+ () => {
+ // Refused (a role that may not read Sources) or unreachable: the hint is
+ // generic, never names kept from an earlier read.
+ if (!current) return;
+ setNames(null);
+ setAnsweredFor(activation);
+ },
+ );
+ return () => { current = false; };
+ }, [wanted, surfaceActive, answeredFor, activation, viewer]);
+ return names !== null && names.viewer === viewer ? names.byId : null;
+}