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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(ui): end Hub-supplied model lists with an Add model exit (#2317)
Call White5df655a8b355
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex b5a7c3195..76c1d8ad2 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -4,7 +4,7 @@ import { join } from 'node:path';import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { I18nextProvider } from 'react-i18next';-import { MemoryRouter } from 'react-router-dom';+import { MemoryRouter, useLocation } from 'react-router-dom';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { InstanceAuthorizationContext } from '@/context/InstanceAuthorizationContext';@@ -470,6 +470,40 @@ describe('SettingsModelsPage surface branches', () => {if (origin === 'passthrough') expect(view.container.querySelector('.model-hub-legend-swatch--passthrough')).not.toBeNull();});+ it.each([+ ['opens the catalog of a Hub backend a model picker sent the user to', 'codex', true],+ ['opens nothing for a backend that is not on the Hub', 'claude', false],+ ])('%s, and drops the request from the address', async (_case, backend, opens) => {+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([takeoverAgent, directAgent('claude')]);+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtime);+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(takeoverAgent);+ const LocationProbe = () => {+ const location = useLocation();+ return <output data-testid="location">{`${location.pathname}${location.search}`}</output>;+ };++ render(+ <ToastProvider>+ <I18nextProvider i18n={i18n}>+ <MemoryRouter initialEntries={[`/settings/models?manage=${backend}`]}>+ <SettingsModelsRoute />+ <LocationProbe />+ </MemoryRouter>+ </I18nextProvider>+ </ToastProvider>,+ );++ // A reload or Back must not open it again, so the request is consumed.+ await waitFor(() => expect(screen.getByTestId('location').textContent).toBe('/settings/models'));+ if (opens) {+ expect(await screen.findByRole('dialog', { name: /^Codex models$|^Codex 模型$/i })).toBeTruthy();+ } else {+ expect(screen.queryByRole('dialog')).toBeNull();+ }+ });+it('acknowledges a catalog save and reveals a new model beyond the collapsed limit', async () => {const ids = Array.from({ length: 6 }, (_, index) => `catalog-model-${index + 1}`);const addedId = 'catalog-model-added';diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex b0b595667..e9cdba388 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -1,7 +1,7 @@import * as React from 'react';import { ArrowDownToLine, Activity, Gauge, LoaderCircle, Power, RefreshCw, Route, ScrollText } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { useNavigate } from 'react-router-dom';+import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -26,6 +26,7 @@ import { SourceOrderDrawer } from './SourceOrderDrawer';import { SourcesCard } from './SourcesCard';import { modelsSurfaceKindFromReads } from './modelHubSurfaceState';import { focusDialogReturn, focusModelHubProjection } from './modelHubFocus';+import { MODEL_HUB_MANAGE_PARAM } from './modelHubRoutes';import { buildSupplyRelations } from './supplyRelations';import {emptySuspendedRouteAttempts,@@ -549,6 +550,26 @@ export const SettingsModelsPage: React.FC = () => {unread: () => [],degraded: (staleData) => staleData,});+ // `?manage=<backend>` is a model picker's 「Add model」 exit. Once the supply+ // read can say whether that backend is on the Hub, open its catalog (or+ // nothing, if it is not) and drop the parameter so a reload or Back does not+ // open it again. The replace keeps the Settings overlay's origin in state.+ const [searchParams, setSearchParams] = useSearchParams();+ const location = useLocation();+ const requestedCatalogBackend = searchParams.get(MODEL_HUB_MANAGE_PARAM);+ const supplyKnown = supplyRead.kind === 'ready' || supplyRead.kind === 'degraded';+ React.useEffect(() => {+ if (requestedCatalogBackend === null || !supplyKnown) return;+ const requested = agents.find((agent) => agent.backend === requestedCatalogBackend && agent.mode === 'hub');+ if (requested) {+ catalogOriginRef.current = null;+ setCatalogFocus(null);+ setMenuBackend(requested.backend);+ }+ const next = new URLSearchParams(searchParams);+ next.delete(MODEL_HUB_MANAGE_PARAM);+ setSearchParams(next, { replace: true, state: location.state });+ }, [agents, location.state, requestedCatalogBackend, searchParams, setSearchParams, supplyKnown]);const chains = foldRegionRead<ModelChainIndex, ModelChainIndex>(chainsRead, {loading: () => ({}),ready: (data) => data,diff --git a/ui/src/components/settings/models/modelHubRoutes.ts b/ui/src/components/settings/models/modelHubRoutes.tsindex 7d079d21f..d6d041552 100644--- a/ui/src/components/settings/models/modelHubRoutes.ts+++ b/ui/src/components/settings/models/modelHubRoutes.ts@@ -6,3 +6,10 @@ export const MODEL_HUB_DISABLED_REDIRECT = '/settings/backends';export const modelHubRouteTarget = (requestedPath: string, enabled: boolean): string =>enabled ? requestedPath : MODEL_HUB_DISABLED_REDIRECT;++// Opens the Model Hub with one backend's model catalog dialog in front, so a+// model picker can send the user straight to where its list is edited.+export const MODEL_HUB_MANAGE_PARAM = 'manage';++export const modelHubCatalogPath = (backend: string): string =>+ `${MODEL_HUB_SETTINGS_PATH}?${MODEL_HUB_MANAGE_PARAM}=${encodeURIComponent(backend)}`;diff --git a/ui/src/components/ui/combobox.test.tsx b/ui/src/components/ui/combobox.test.tsxindex 8f97deace..e0996295c 100644--- a/ui/src/components/ui/combobox.test.tsx+++ b/ui/src/components/ui/combobox.test.tsx@@ -120,6 +120,23 @@ describe('Combobox', () => {expect(screen.getByRole('combobox').getAttribute('aria-label')).toBeNull();});+ it('pins a footer action under the options, and leaves through it without choosing', async () => {+ // A model picker ends with 「Add model」, which goes where the list is edited;+ // it must stay reachable while a typed query hides every option, and taking+ // it must not write the query or a row as the field's value.+ const onSelect = vi.fn();+ const onValueChange = vi.fn();+ const { user } = await open(plain, { onValueChange, footerAction: { label: 'Add model', onSelect } });++ expect(screen.getAllByRole('option').map((row) => row.textContent).at(-1)).toBe('Add model');+ await user.keyboard('zzz');+ await user.click(screen.getByRole('option', { name: 'Add model' }));++ expect(onSelect).toHaveBeenCalledOnce();+ expect(onValueChange).not.toHaveBeenCalled();+ expect(screen.queryAllByRole('option')).toEqual([]);+ });+it('does not open while the field is disabled', async () => {await open(marked, { disabled: true });expect(screen.queryAllByRole('option')).toEqual([]);diff --git a/ui/src/components/ui/combobox.tsx b/ui/src/components/ui/combobox.tsxindex 437216500..8b716a4e9 100644--- a/ui/src/components/ui/combobox.tsx+++ b/ui/src/components/ui/combobox.tsx@@ -57,8 +57,15 @@ interface ComboboxProps {/** When set, the create affordance renders as a bordered input + this-labelled button* (design.pen `e3rPI`) instead of an inline command item. */createButtonLabel?: string+ /** A "+ label" row pinned under the options, visible however far the list+ * scrolls, that leads somewhere else rather than choosing a value; the menu+ * closes before `onSelect` runs. */+ footerAction?: { label: string; onSelect: () => void }}+// cmdk keys rows by value; a reserved one keeps the action apart from options.+const FOOTER_ACTION_VALUE = "__combobox_footer_action__"+export function Combobox({options,value,@@ -76,6 +83,7 @@ export function Combobox({createHeading,withFolderIcon = false,createButtonLabel,+ footerAction,}: ComboboxProps) {const [open, setOpen] = React.useState(false)const [inputValue, setInputValue] = React.useState("")@@ -254,6 +262,25 @@ export function Combobox({</CommandGroup>))}+ {/* Pinned to the bottom edge so a long list does not scroll it out of sight. */}+ {footerAction && (+ <div className="sticky bottom-0 border-t border-border bg-panel">+ <CommandGroup>+ <CommandItem+ value={FOOTER_ACTION_VALUE}+ onSelect={() => {+ setOpen(false)+ setInputValue("")+ footerAction.onSelect()+ }}+ className="text-mint-ink data-[selected=true]:text-mint-ink"+ >+ <Plus className="mr-2 h-4 w-4" />+ {footerAction.label}+ </CommandItem>+ </CommandGroup>+ </div>+ )}</CommandList></Command></PopoverContent>diff --git a/ui/src/components/workbench/AgentRoutePicker.test.tsx b/ui/src/components/workbench/AgentRoutePicker.test.tsxindex dd11f6e50..c946acac6 100644--- a/ui/src/components/workbench/AgentRoutePicker.test.tsx+++ b/ui/src/components/workbench/AgentRoutePicker.test.tsx@@ -2,11 +2,15 @@import { useState } from 'react';import { afterEach, describe, expect, it, vi } from 'vitest';-import { cleanup, render, screen } from '@testing-library/react';+import { act, cleanup, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { MemoryRouter } from 'react-router-dom';+import { MemoryRouter, useLocation } from 'react-router-dom';import type { VibeAgentBrief } from '../../context/ApiContext';+import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';+import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';+import { capabilitiesFor } from '../../lib/testing/instanceRoleCapabilities';+import type { InstanceRole } from '../../lib/sessionInfo';import { AgentRoutePicker } from './AgentRoutePicker';import type { AgentRoutePatch, AgentRouteValue } from './AgentRoutePicker';@@ -14,15 +18,26 @@ vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));+// 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';+const API = {+ readModelHubAgentCatalogForModelPicker: (backend: string) => Promise.resolve({ backend, mode: hubMode }),+};vi.mock('../../context/ApiContext', async (importOriginal) => ({...(await importOriginal<typeof import('../../context/ApiContext')>()),- useApi: () => ({}),+ useApi: () => API,}));// What the catalog answers for this render. A Hub catalog states one entry per// 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 }[]> = {};+// How many catalog reads were made, and whether the next ones wait to be answered.+let catalogReads = 0;+let deferReads = false;+const pendingReads: (() => void)[] = [];// The model column is fetched per backend; serve it synchronously so the test is// about the route state, not about the catalog request.@@ -38,12 +53,15 @@ vi.mock('../../lib/backendModels', async (importOriginal) => ({catalogRefreshPending: boolean;}) => void,) => {- onLoaded({+ catalogReads += 1;+ const answer = () => onLoaded({models: ['sonnet', 'opus'],modelLabels: {},reasoningOptions: catalogReasoning,catalogRefreshPending: false,});+ if (deferReads) pendingReads.push(answer);+ else answer();return () => {};},}));@@ -120,10 +138,111 @@ const openMenu = async (user: ReturnType<typeof userEvent.setup>) => {await screen.findByText('chat.picker.model');};+const LocationProbe = () => {+ const location = useLocation();+ return <output data-testid="location">{`${location.pathname}${location.search}`}</output>;+};++// A picker on a surface Settings can cover, seen by a viewer holding `role`.+const HubPicker: React.FC<{+ role: InstanceRole;+ surfaceActive?: boolean;+ onNavigateAway?: () => void;+}> = ({ role, surfaceActive = true, onNavigateAway }) => (+ <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} />+ <LocationProbe />+ </MemoryRouter>+ </RouteSurfaceActiveContext.Provider>+ </InstanceAuthorizationContext.Provider>+);+describe('AgentRoutePicker', () => {afterEach(() => {cleanup();catalogReasoning = {};+ hubMode = 'direct';+ catalogReads = 0;+ deferReads = false;+ pendingReads.length = 0;+ });++ it("ends a Hub backend's model list with an exit to that backend's catalog in the Model Hub", async () => {+ hubMode = 'hub';+ const user = userEvent.setup();+ const onNavigateAway = vi.fn();+ render(<HubPicker role="owner" onNavigateAway={onNavigateAway} />);+ await openMenu(user);++ const addModel = await screen.findByRole('button', { name: 'chat.picker.addModel' });+ const lastModel = screen.getByRole('button', { name: 'opus' });+ expect(lastModel.compareDocumentPosition(addModel) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();++ await user.click(addModel);++ expect(screen.getByTestId('location').textContent).toBe('/settings/models?manage=claude');+ expect(screen.queryByText('chat.picker.model')).toBeNull();+ // Settings opens over the host, which suspends under it with its draft+ // instead of being closed the way leaving for /agents closes it.+ expect(onNavigateAway).not.toHaveBeenCalled();+ });++ it('reads the model list again once Settings stops covering the surface', async () => {+ const user = userEvent.setup();+ const { rerender } = render(<HubPicker role="owner" />);+ await openMenu(user);+ await user.keyboard('{Escape}');+ await openMenu(user);+ await user.keyboard('{Escape}');+ // Reopening alone serves the list already read.+ expect(catalogReads).toBe(1);++ rerender(<HubPicker role="owner" surfaceActive={false} />);+ rerender(<HubPicker role="owner" />);+ await openMenu(user);++ // The Model Hub may have changed the list while it was covered.+ expect(catalogReads).toBe(2);+ });++ it('offers no row read before a Settings visit while the read after it is in flight', async () => {+ // The visit may have switched the backend to Direct, where a Hub-only row+ // is a route that cannot run.+ const user = userEvent.setup();+ const { rerender } = render(<HubPicker role="owner" />);+ await openMenu(user);+ expect(screen.getByRole('button', { name: 'opus' })).toBeTruthy();++ deferReads = true;+ rerender(<HubPicker role="owner" surfaceActive={false} />);+ rerender(<HubPicker role="owner" />);++ expect(screen.queryByRole('button', { name: 'opus' })).toBeNull();+ expect(screen.getByText('common.loading')).toBeTruthy();+ // Nor an effort: without the catalog the backend's fallback ladder could+ // offer one the current model rejects.+ expect(screen.queryByText('chat.picker.effort')).toBeNull();+ act(() => pendingReads.shift()!());+ expect(screen.getByRole('button', { name: 'opus' })).toBeTruthy();+ expect(screen.getByText('chat.picker.effort')).toBeTruthy();+ });++ 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" />);+ await openMenu(user);+ expect(catalogReads).toBe(1);++ // A Settings command opens over the surface without dismissing the menu.+ rerender(<HubPicker role="owner" surfaceActive={false} />);+ rerender(<HubPicker role="owner" />);++ expect(screen.getByText('chat.picker.model')).toBeTruthy();+ expect(catalogReads).toBe(2);});it('highlights the pick while the owner write is still in flight', async () => {diff --git a/ui/src/components/workbench/AgentRoutePicker.tsx b/ui/src/components/workbench/AgentRoutePicker.tsxindex c899a5f64..7c3054d4d 100644--- a/ui/src/components/workbench/AgentRoutePicker.tsx+++ b/ui/src/components/workbench/AgentRoutePicker.tsx@@ -6,8 +6,9 @@ import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import type { VibeAgentBrief } from '../../context/ApiContext';-import { loadBackendModelsWithRefresh, modelOptionLabel } from '../../lib/backendModels';+import { loadBackendModelsWithRefresh, modelOptionLabel, useAddModelExit } from '../../lib/backendModels';import { isEffortSupported, resolveEffortOptions } from '../../lib/effortOptions';+import { useRouteSurfaceActive } from '../../lib/routeSurfaceActivity';import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';import { Button } from '../ui/button';import { Input } from '../ui/input';@@ -59,7 +60,9 @@ interface AgentRoutePickerProps {* new-session sheet) so its content isn't aria-hidden/inert by the dialog. */modal?: boolean;/** Called before navigating to /agents — the create sheet uses it to close- * itself so the destination isn't left behind a focus-trapped modal. */+ * itself so the destination isn't left behind a focus-trapped modal. The+ * Model Hub exit does not call it: Settings opens over this surface, and a+ * host suspends under it with its draft intact, as it does for any visit. */onNavigateAway?: () => void;}@@ -100,6 +103,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({Record<string, Record<string, ReasoningOption[]>>>({});const loadedModelBackendsRef = 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.const [modelQuery, setModelQuery] = useState('');@@ -186,6 +190,18 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({};}, []);+ // Settings covers this surface while it is open, and the Model Hub there may+ // change any backend's list, even which catalog supplies it. Nothing read+ // before the visit survives it: the return shows loading until a new read+ // lands, never a row the backend may no longer offer.+ useEffect(() => {+ if (surfaceActive) return;+ loadedModelBackendsRef.current.clear();+ setModelsByBackend({});+ setModelLabelsByBackend({});+ setReasoningByBackend({});+ }, [surfaceActive]);+const grouped = useMemo(() => {const groups: Record<string, VibeAgentBrief[]> = {};for (const agent of visibleAgents) {@@ -195,10 +211,11 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({}, [visibleAgents]);// Fetch the active backend's model list the first time the menu opens for it;- // cached per backend so toggling agents doesn't refetch.+ // cached per backend so toggling agents doesn't refetch. A menu left open+ // under Settings reads again as it is uncovered.useEffect(() => {const loadedBackends = loadedModelBackendsRef.current;- if (!open || !backend || loadedBackends.has(backend)) return;+ if (!open || !surfaceActive || !backend || loadedBackends.has(backend)) return;loadedBackends.add(backend);let reloadOnNextOpen = true;setLoadingModels(true);@@ -215,6 +232,8 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({() => {loadedBackends.delete(backend);setModelsByBackend((prev) => ({ ...prev, [backend]: [] }));+ // No catalog to consult: the backend's own ladder, as for any unknown model.+ setReasoningByBackend((prev) => ({ ...prev, [backend]: prev[backend] ?? {} }));setLoadingModels(false);},);@@ -222,7 +241,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({cancel();if (reloadOnNextOpen) loadedBackends.delete(backend);};- }, [open, backend, api]);+ }, [open, surfaceActive, backend, api]);// Start each open (and every backend switch) from the full, unfiltered list.useEffect(() => {@@ -232,6 +251,7 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({const models = modelsByBackend[backend] ?? [];const modelLabels = modelLabelsByBackend[backend] ?? {};const backendReasoning = reasoningByBackend[backend] ?? EMPTY_REASONING_OPTIONS;+ const openAddModel = useAddModelExit(backend, open);// Show the search field only when the list is long enough to warrant it, so// claude/codex (a handful of models) stay uncluttered.const showModelSearch = models.length > 8;@@ -243,9 +263,14 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({modelOptionLabel(m, modelLabels).toLowerCase().includes(trimmedQuery),): models;+ // Efforts are a catalog answer too. Until this backend's read has answered+ // (first open, or the read after a Settings visit dropped the last one), the+ // fallback ladder could offer an effort the current model rejects, so the+ // column waits with the model column instead.+ const catalogAnswered = Object.prototype.hasOwnProperty.call(reasoningByBackend, backend);const effortOptions = useMemo(- () => resolveEffortOptions(backend, currentModel, backendReasoning),- [backend, currentModel, backendReasoning],+ () => (catalogAnswered ? resolveEffortOptions(backend, currentModel, backendReasoning) : []),+ [catalogAnswered, backend, currentModel, backendReasoning],);return (@@ -370,10 +395,8 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({))}</div>))}- <Button- type="button"- variant="ghost"- size="sm"+ <PickerExitButton+ label={t('chat.picker.newAgent')}onClick={() => {setOpen(false);onNavigateAway?.(); // close the create sheet before leaving, if any@@ -381,15 +404,14 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({// that tab explicitly instead of resuming the remembered one.navigate('/agents?tab=definitions');}}- className="mt-1 h-auto w-full justify-start gap-1.5 rounded px-2 py-1.5 text-[11px] font-medium text-cyan-ink hover:bg-cyan/[0.08] hover:text-cyan-ink"- >- <Plus className="size-3.5" />- {t('chat.picker.newAgent')}- </Button>+ /></RouteColumn>- {/* Column 2 — Model (lazy-loaded for the active backend) */}- <RouteColumn title={t('chat.picker.model')}>+ {/* Column 2 — Model (lazy-loaded for the active backend). Its own+ scroll box on phones too, where the columns stack: the sticky search+ and Add model rows pin to the nearest scroll box, and a column that+ never scrolls would leave them at the far ends of a long list. */}+ <RouteColumn title={t('chat.picker.model')} className="max-h-[45vh]">{showModelSearch && (<div className="sticky top-0 z-10 -mx-1.5 mb-1 bg-panel px-1.5 pb-1 pt-0.5"><div className="flex items-center gap-1.5 rounded-md border border-border bg-surface-2 px-2 focus-within:border-cyan/50">@@ -439,6 +461,19 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({</RouteItem>)))}+ {/* Pinned like the search above it: a long model list must not scroll+ the way to add one out of sight. */}+ {openAddModel && (+ <div className="sticky -bottom-1.5 z-10 -mx-1.5 -mb-1.5 border-t border-border bg-panel px-1.5 pb-1.5">+ <PickerExitButton+ label={t('chat.picker.addModel')}+ onClick={() => {+ setOpen(false);+ openAddModel();+ }}+ />+ </div>+ )}</RouteColumn>{/* Column 3 — Effort (uses per-model catalog entries when available) */}@@ -463,13 +498,28 @@ export const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({);};-const RouteColumn: React.FC<{ title: string; children: React.ReactNode }> = ({ title, children }) => (- <div className="flex min-w-0 flex-col overflow-y-auto p-1.5 sm:max-h-[320px]">+const RouteColumn: React.FC<{ title: string; className?: string; children: React.ReactNode }> = ({ title, className, children }) => (+ <div className={clsx('flex min-w-0 flex-col overflow-y-auto p-1.5 sm:max-h-[320px]', className)}><div className="px-2 pb-1 pt-0.5 text-[10px] font-bold uppercase tracking-[0.1em] text-muted">{title}</div>{children}</div>);+// The "+ …" row closing a column: it leaves the picker for the page where that+// column's list is edited.+const PickerExitButton: React.FC<{ label: string; onClick: () => void }> = ({ label, onClick }) => (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={onClick}+ className="mt-1 h-auto w-full justify-start gap-1.5 rounded px-2 py-1.5 text-[11px] font-medium text-cyan-ink hover:bg-cyan/[0.08] hover:text-cyan-ink"+ >+ <Plus className="size-3.5" />+ {label}+ </Button>+);+// A picker row on the shared Button primitive (variant + className overrides)// so it inherits the design system's focus/disabled behavior.const RouteItem: React.FC<{diff --git a/ui/src/components/workbench/AgentsPage.test.tsx b/ui/src/components/workbench/AgentsPage.test.tsxindex c45b5f6d0..777cd9594 100644--- a/ui/src/components/workbench/AgentsPage.test.tsx+++ b/ui/src/components/workbench/AgentsPage.test.tsx@@ -2,12 +2,13 @@import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';-import { MemoryRouter } from 'react-router-dom';+import { MemoryRouter, useLocation } from 'react-router-dom';import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';import type { VibeAgentBrief, WorkbenchEventHandlers, WorkbenchProject } from '../../context/ApiContext';import type { InstanceCapabilities, InstanceRole } from '../../lib/sessionInfo';import { OWNER_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';+import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';import { capabilitiesFor } from '../../lib/testing/instanceRoleCapabilities';import { AgentsPage } from './AgentsPage';@@ -22,6 +23,7 @@ type FakeApi = {listProjects: ReturnType<typeof vi.fn>;createSession: ReturnType<typeof vi.fn>;connectWorkbenchEvents: ReturnType<typeof vi.fn>;+ readModelHubAgentCatalogForModelPicker: ReturnType<typeof vi.fn>;};const apiRef = vi.hoisted(() => ({ current: null as FakeApi | null }));@@ -49,10 +51,17 @@ type FakeModelCatalog = {reasoningOptions?: Record<string, { value: string; label: string }[]>;};let modelCatalog: FakeModelCatalog = { models: [] };+let modelCatalogReads = 0;+let deferModelReads = false;+const pendingModelReads: (() => void)[] = [];-vi.mock('../../lib/backendModels', async () => ({+vi.mock('../../lib/backendModels', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../lib/backendModels')>()),loadBackendModelsWithRefresh: (_api: unknown, _backend: string, onLoaded: (payload: FakeModelCatalog) => void) => {- onLoaded(modelCatalog);+ modelCatalogReads += 1;+ const catalog = modelCatalog;+ if (deferModelReads) pendingModelReads.push(() => onLoaded(catalog));+ else onLoaded(catalog);return () => {};},}));@@ -128,6 +137,8 @@ function makeApi(handlers = next;return vi.fn();}),+ // No Model Hub record: the model field offers no Add model exit.+ readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue(null),};}@@ -182,6 +193,9 @@ afterEach(() => {handlers = null;showToast.mockReset();modelCatalog = { models: [] };+ modelCatalogReads = 0;+ deferModelReads = false;+ pendingModelReads.length = 0;});describe('AgentsPage load requests follow the rank that can serve them', () => {@@ -1485,6 +1499,52 @@ describe('AgentsPage reconnect reconciliation', () => {expect(screen.queryByText('agents.detail.effort')).toBeNull();});+ it("offers the Model Hub from a Hub backend's model list, and reads the list again on return", async () => {+ modelCatalog = { models: ['gpt-hub'] };+ const initial = brief('agent-a', 'description');+ const api = makeApi(vi.fn().mockResolvedValue(listResult(initial)), vi.fn().mockResolvedValue(fullAgent(initial, 'prompt')));+ api.readModelHubAgentCatalogForModelPicker.mockResolvedValue({ backend: 'codex', mode: 'hub' });+ apiRef.current = api;+ const LocationProbe = () => {+ const location = useLocation();+ return <output data-testid="location">{`${location.pathname}${location.search}`}</output>;+ };+ 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 />+ <LocationProbe />+ </MemoryRouter>+ </RouteSurfaceActiveContext.Provider>+ </InstanceAuthorizationContext.Provider>+ );+ const view = render(page(true));+ await waitFor(() => expect(screen.getByDisplayValue('description')).toBeTruthy());+ const reads = modelCatalogReads;++ // Settings covers the page and uncovers it: the Model Hub may have edited the+ // list, so the rows read before the visit are not offered meanwhile.+ deferModelReads = true;+ view.rerender(page(false));+ view.rerender(page(true));+ expect(modelCatalogReads).toBe(reads + 1);++ // cmdk scrolls its highlighted row into view; jsdom implements no scrolling.+ Element.prototype.scrollIntoView = vi.fn();+ // Neither a model nor an effort read before the visit can be picked meanwhile.+ expect((screen.getByRole('button', { name: 'medium', exact: true }) as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(screen.getByRole('combobox'));+ expect(screen.queryByRole('option', { name: 'gpt-hub' })).toBeNull();+ act(() => pendingModelReads.shift()!());+ expect(screen.getByRole('option', { name: 'gpt-hub' })).toBeTruthy();+ expect((screen.getByRole('button', { name: 'medium', exact: true, hidden: true }) as HTMLButtonElement).disabled).toBe(false);+ fireEvent.click(await screen.findByText('chat.picker.addModel'));+ expect(screen.getByTestId('location').textContent).toBe('/settings/models?manage=codex');+ });+it('keeps an unset server effort unset instead of lighting a default', async () => {// The reported inconsistency: the panel showed `medium` for an agent the// server held at null, so switching models sent only `model` and the recorddiff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex 907e00469..c5de29f60 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -48,8 +48,9 @@ import { Textarea } from '../ui/textarea';import { EditorDialog } from '../ui/editor-dialog';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 } from '../../lib/backendModels';+import { loadBackendModelsWithRefresh, modelOptionLabel, useAddModelExit } from '../../lib/backendModels';import { resolveEffortOptions } from '../../lib/effortOptions';import { WorkbenchPageHeader } from './WorkbenchPageHeader';import { CapabilityTabs } from './CapabilityTabs';@@ -2008,6 +2009,8 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, caconst activeModelCatalog = modelCatalogs[agent.backend];const modelOptions = activeModelCatalog?.modelOptions ?? [];const reasoningOptions = activeModelCatalog?.reasoningOptions ?? {};+ const openAddModel = useAddModelExit(agent.backend, canEdit);+ const surfaceActive = useRouteSurfaceActive();useEffect(() => {const previous = serverSnapshotRef.current;@@ -2065,9 +2068,12 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca// Load model catalog for the agent's backend so the Combobox can offer// suggestions. Keeps `allowCustomValue` so users can type a model the- // backend doesn't know about yet (e.g. a freshly-released preview).+ // 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.useEffect(() => {- return loadBackendModelsWithRefresh(+ if (!surfaceActive) return;+ const cancel = loadBackendModelsWithRefresh(api,agent.backend,({ models, modelLabels, reasoningOptions: opts }) => {@@ -2086,7 +2092,15 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca}));},);- }, [agent.backend, api]);+ return () => {+ cancel();+ setModelCatalogs((current) => {+ const next = { ...current };+ delete next[agent.backend];+ return next;+ });+ };+ }, [agent.backend, api, surfaceActive]);const lockHint = system? t('agents.detail.systemLocked')@@ -2096,6 +2110,10 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, caconst systemPromptTokens = estimateTokens(systemPrompt);// Effort options follow the backend + selected model when the catalog provides them.const effortOptions = resolveEffortOptions(agent.backend, model, reasoningOptions);+ // 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.+ const effortsAnswered = activeModelCatalog !== undefined;const markFieldEdit = (field: keyof typeof fieldRevisionRef.current) => {fieldRevisionRef.current[field] += 1;return fieldRevisionRef.current[field];@@ -2402,6 +2420,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, caplaceholder={t('agents.detail.modelPlaceholder')}emptyText={t('agents.detail.modelEmpty')}allowCustomValue+ footerAction={openAddModel ? { label: t('chat.picker.addModel'), onSelect: openAddModel } : undefined}/>)}</Field>@@ -2421,7 +2440,7 @@ const AgentDetailPanel: React.FC<DetailProps> = ({ agent, isDefault, canEdit, ca<buttonkey={opt}type="button"- disabled={!canEdit}+ disabled={!canEdit || !effortsAnswered}title={canEdit ? undefined : t('agents.remoteReadOnlyHint')}onClick={() => {markFieldEdit('effort');diff --git a/ui/src/components/workbench/NewAgentDialog.test.tsx b/ui/src/components/workbench/NewAgentDialog.test.tsxindex 4093f0ae8..e80926a73 100644--- a/ui/src/components/workbench/NewAgentDialog.test.tsx+++ b/ui/src/components/workbench/NewAgentDialog.test.tsx@@ -1,17 +1,28 @@/* @vitest-environment jsdom */import { afterEach, describe, expect, it, vi } from 'vitest';-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter, useLocation } from 'react-router-dom';+import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';+import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';+import { OWNER_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';import { NewAgentDialog } from './NewAgentDialog';-const apiRef = vi.hoisted(() => ({ current: null as { createVibeAgent: ReturnType<typeof vi.fn> } | null }));+const apiRef = vi.hoisted(() => ({+ current: null as {+ createVibeAgent: ReturnType<typeof vi.fn>;+ readModelHubAgentCatalogForModelPicker?: ReturnType<typeof vi.fn>;+ } | null,+}));vi.stubGlobal('ResizeObserver', class {observe() {}unobserve() {}disconnect() {}});+// cmdk scrolls its highlighted row into view; jsdom implements no scrolling.+Element.prototype.scrollIntoView = vi.fn();vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -31,11 +42,27 @@ type FakeModelCatalog = {reasoningOptions?: Record<string, { value: string; label: string }[]>;};let modelCatalog: FakeModelCatalog = { models: [] };+let modelCatalogReads = 0;+let deferReads = false;+let failReads = false;+const pendingReads: (() => void)[] = [];vi.mock('../../lib/backendModels', async (importOriginal) => ({...(await importOriginal<typeof import('../../lib/backendModels')>()),- loadBackendModelsWithRefresh: (_api: unknown, _backend: string, onLoaded: (payload: FakeModelCatalog) => void) => {- onLoaded(modelCatalog);+ loadBackendModelsWithRefresh: (+ _api: unknown,+ _backend: string,+ onLoaded: (payload: FakeModelCatalog) => void,+ onInitialError?: () => void,+ ) => {+ modelCatalogReads += 1;+ if (failReads) {+ onInitialError?.();+ return () => {};+ }+ const catalog = modelCatalog;+ if (deferReads) pendingReads.push(() => onLoaded(catalog));+ else onLoaded(catalog);return () => {};},}));@@ -43,7 +70,11 @@ vi.mock('../../lib/backendModels', async (importOriginal) => ({const renderDialog = () => {const createVibeAgent = vi.fn().mockResolvedValue({ ok: true, agent: { id: 'agt-new' } });apiRef.current = { createVibeAgent };- render(<NewAgentDialog open onClose={vi.fn()} onCreated={vi.fn()} />);+ render(+ <MemoryRouter>+ <NewAgentDialog open onClose={vi.fn()} onCreated={vi.fn()} />+ </MemoryRouter>,+ );return { createVibeAgent };};@@ -59,9 +90,121 @@ afterEach(() => {cleanup();apiRef.current = null;modelCatalog = { models: [] };+ modelCatalogReads = 0;+ deferReads = false;+ failReads = false;+ pendingReads.length = 0;});describe('NewAgentDialog', () => {+ it("keeps the form while the user adds a model in the Model Hub catalog", async () => {+ // Settings hides the page this dialog sits in; closing it would clear the+ // Agent the user was halfway through defining.+ modelCatalog = { models: ['opus'] };+ apiRef.current = {+ createVibeAgent: vi.fn(),+ readModelHubAgentCatalogForModelPicker: vi.fn().mockResolvedValue({ backend: 'claude', mode: 'hub' }),+ };+ const onClose = vi.fn();+ const LocationProbe = () => {+ const location = useLocation();+ return <output data-testid="location">{`${location.pathname}${location.search}`}</output>;+ };+ render(+ <InstanceAuthorizationContext.Provider+ value={{ remote: false, instanceKind: null, instanceRole: 'owner', capabilities: OWNER_INSTANCE_CAPABILITIES }}+ >+ <MemoryRouter>+ <NewAgentDialog open onClose={onClose} onCreated={vi.fn()} />+ <LocationProbe />+ </MemoryRouter>+ </InstanceAuthorizationContext.Provider>,+ );+ fireEvent.change(screen.getByPlaceholderText('agents.create.namePlaceholder'), { target: { value: 'router' } });++ fireEvent.click(screen.getByRole('combobox'));+ fireEvent.click(await screen.findByText('chat.picker.addModel'));++ expect(screen.getByTestId('location').textContent).toBe('/settings/models?manage=claude');+ expect(onClose).not.toHaveBeenCalled();+ expect(screen.getByDisplayValue('router')).toBeTruthy();+ });++ it('reads the model list again when Settings uncovers the open dialog', () => {+ // Closing and reopening would refresh it too, but only by clearing the form.+ apiRef.current = { createVibeAgent: vi.fn() };+ const dialog = (surfaceActive: boolean) => (+ <RouteSurfaceActiveContext.Provider value={surfaceActive}>+ <MemoryRouter>+ <NewAgentDialog open onClose={vi.fn()} onCreated={vi.fn()} />+ </MemoryRouter>+ </RouteSurfaceActiveContext.Provider>+ );+ const { rerender } = render(dialog(true));+ const reads = modelCatalogReads;++ rerender(dialog(false));+ rerender(dialog(true));++ expect(modelCatalogReads).toBe(reads + 1);+ });++ it('falls back to the backend ladder, not the efforts read before a Settings visit, when the read after it fails', () => {+ // The visit may have removed `max` from this model; a failed read cannot say+ // it did not, so the pre-visit efforts must not come back as choices.+ modelCatalog = { models: [], reasoningOptions: { 'only-max': [{ value: 'max', label: 'Max' }] } };+ apiRef.current = { createVibeAgent: vi.fn() };+ const dialog = (surfaceActive: boolean) => (+ <RouteSurfaceActiveContext.Provider value={surfaceActive}>+ <MemoryRouter>+ <NewAgentDialog open onClose={vi.fn()} onCreated={vi.fn()} />+ </MemoryRouter>+ </RouteSurfaceActiveContext.Provider>+ );+ const { rerender } = render(dialog(true));+ chooseModel('only-max');+ expect(screen.getByRole('button', { name: 'max', exact: true })).toBeTruthy();++ failReads = true;+ rerender(dialog(false));+ rerender(dialog(true));++ expect(screen.queryByRole('button', { name: 'max', exact: true })).toBeNull();+ expect(screen.getByRole('button', { name: 'medium', exact: true })).toBeTruthy();+ });++ it('offers no model read before a Settings visit while the read after it is in flight', () => {+ modelCatalog = { models: ['opus'] };+ apiRef.current = { createVibeAgent: vi.fn() };+ const dialog = (surfaceActive: boolean) => (+ <RouteSurfaceActiveContext.Provider value={surfaceActive}>+ <MemoryRouter>+ <NewAgentDialog open onClose={vi.fn()} onCreated={vi.fn()} />+ </MemoryRouter>+ </RouteSurfaceActiveContext.Provider>+ );+ const { rerender } = render(dialog(true));+ fireEvent.change(screen.getByPlaceholderText('agents.create.namePlaceholder'), { target: { value: 'router' } });+ const create = () => screen.getByRole('button', { name: /agents\.create\.submit/, hidden: true }) as HTMLButtonElement;+ const medium = () => screen.getByRole('button', { name: 'medium', exact: true, hidden: true }) as HTMLButtonElement;+ expect(create().disabled).toBe(false);+ deferReads = true;+ rerender(dialog(false));+ rerender(dialog(true));++ // The draft keeps its effort, but neither it nor Create can be chosen until+ // the new read can say whether the model still takes it.+ expect(screen.getByDisplayValue('router')).toBeTruthy();+ expect(medium().disabled).toBe(true);+ expect(create().disabled).toBe(true);+ fireEvent.click(screen.getByRole('combobox'));+ expect(screen.queryByText('opus')).toBeNull();+ act(() => pendingReads.shift()!());+ expect(screen.getByText('opus')).toBeTruthy();+ expect(medium().disabled).toBe(false);+ expect(create().disabled).toBe(false);+ });+it('creates with no effort when the catalog says the model has none', async () => {// `medium` is only a starting suggestion. Sending it for a model whose// catalog row states no efforts would create an Agent whose very firstdiff --git a/ui/src/components/workbench/NewAgentDialog.tsx b/ui/src/components/workbench/NewAgentDialog.tsxindex ba24c9bfe..0e02b36ec 100644--- a/ui/src/components/workbench/NewAgentDialog.tsx+++ b/ui/src/components/workbench/NewAgentDialog.tsx@@ -5,8 +5,9 @@ import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import type { VibeAgentFull } from '../../context/ApiContext';-import { loadBackendModelsWithRefresh, modelOptionLabel } from '../../lib/backendModels';+import { loadBackendModelsWithRefresh, modelOptionLabel, useAddModelExit } from '../../lib/backendModels';import { resolveEffortOptions } from '../../lib/effortOptions';+import { useRouteSurfaceActive } from '../../lib/routeSurfaceActivity';import { estimateTokens } from '../../lib/tokenEstimate';import { Combobox } from '../ui/combobox';import type { ComboboxOption } from '../ui/combobox';@@ -60,7 +61,13 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, oconst [error, setError] = useState<string | null>(null);const [modelOptions, setModelOptions] = useState<ComboboxOption[]>([]);const [reasoningOptions, setReasoningOptions] = useState<Record<string, { value: string; label: string }[]>>({});+ // Whether this backend's catalog has answered since it was last invalidated+ // (a backend switch, or a Settings visit). Until it has, nothing the dialog+ // offers is confirmed against it.+ const [catalogAnswered, setCatalogAnswered] = useState(false);const [editorOpen, setEditorOpen] = useState(false);+ const openAddModel = useAddModelExit(backend, open);+ const surfaceActive = useRouteSurfaceActive();useEffect(() => {if (!open) {@@ -78,19 +85,35 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, o// Reload the model catalog whenever the selected backend changes so// the Combobox suggests the right list. allowCustomValue stays on so- // freshly-released model IDs can still be typed in.+ // freshly-released model IDs can still be typed in. The dialog stays open+ // under Settings, so it reads again once Settings uncovers it, and offers no+ // row read before the visit meanwhile. The effort options stay so the draft's+ // chosen effort does not move, but neither an effort nor Create can be+ // chosen until the new read answers and the effort is checked against it.useEffect(() => {- if (!open) return;- return loadBackendModelsWithRefresh(+ if (!open || !surfaceActive) return;+ const cancel = loadBackendModelsWithRefresh(api,backend,({ models, modelLabels, reasoningOptions: opts }) => {setModelOptions(models.map((m) => ({ value: m, label: modelOptionLabel(m, modelLabels) })));setReasoningOptions(opts ?? {});+ setCatalogAnswered(true);+ },+ () => {+ // No catalog to check against: the backend's own ladder, as for any+ // unknown model, never the efforts read before the visit.+ setModelOptions([]);+ setReasoningOptions({});+ setCatalogAnswered(true);},- () => setModelOptions([]),);- }, [backend, open, api]);+ return () => {+ cancel();+ setModelOptions([]);+ setCatalogAnswered(false);+ };+ }, [backend, open, api, surfaceActive]);const modelComboboxOptions = useMemo(() => modelOptions, [modelOptions]);const effortOptions = useMemo(@@ -120,7 +143,7 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, oif (!open) return null;- const canSubmit = name.trim().length > 0 && !submitting;+ const canSubmit = name.trim().length > 0 && !submitting && catalogAnswered;const handleSubmit = async () => {if (!canSubmit) return;@@ -265,6 +288,9 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, oplaceholder={t('agents.detail.modelPlaceholder')}emptyText={t('agents.detail.modelEmpty')}allowCustomValue+ // The dialog stays open: Settings hides the page it sits in, and+ // the form is here again when the user comes back.+ footerAction={openAddModel ? { label: t('chat.picker.addModel'), onSelect: openAddModel } : undefined}/></div>{effortOptions.length > 0 && (@@ -281,8 +307,9 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, okey={opt}type="button"onClick={() => setEffort(opt)}+ disabled={!catalogAnswered}className={clsx(- 'truncate rounded px-0.5 py-1.5 text-[11px] capitalize transition',+ 'truncate rounded px-0.5 py-1.5 text-[11px] capitalize transition disabled:opacity-60',effort === opt ? 'bg-mint-soft font-bold text-mint-ink' : 'font-medium text-muted hover:text-foreground',)}>diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex afa722bfc..28f4eb7fe 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4575,6 +4575,7 @@"model": "Model","effort": "Effort","newAgent": "New agent",+ "addModel": "Add model","noModels": "No models found","searchModels": "Search models","noModelMatch": "No matching models",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 84ea2ebe1..747895018 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4575,6 +4575,7 @@"model": "模型","effort": "思考强度","newAgent": "新建 Agent",+ "addModel": "添加模型","noModels": "未找到模型","searchModels": "搜索模型","noModelMatch": "无匹配模型",diff --git a/ui/src/lib/backendModels.ts b/ui/src/lib/backendModels.tsindex 7e9920ea1..c15abd289 100644--- a/ui/src/lib/backendModels.ts+++ b/ui/src/lib/backendModels.ts@@ -1,6 +1,13 @@+import { useEffect, useState } from 'react';+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 { ApiError, type ApiContextType } from '../context/ApiContext';+import { ApiError, useApi, type ApiContextType } from '../context/ApiContext';+import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';+import { useRouteSurfaceActive } from './routeSurfaceActivity';+import { settingsOverlayContinuationState } from './settingsOverlay';export interface BackendModels {/** Selectable model identifiers for the backend. */@@ -26,8 +33,11 @@ export function modelOptionLabel(model: string, labels?: Record<string, string>)// 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';+const hubCatalogModels = (agent: PickerAgentCatalog | null, backend: string): BackendModels | null => {- if (!agent || agent.backend !== backend || agent.mode !== 'hub') return null;+ if (!isHubAgent(agent, backend)) return null;const catalog = agent.catalog_models ?? null;if (!catalog) return null;// A backend-owned selector such as Claude Code's Default is not routeable.@@ -139,6 +149,52 @@ export async function fetchBackendModels(return { models: [] };}+/**+ * A model picker's "Add model" exit: opens this backend's catalog in the Model+ * Hub, or is null when the picker shows none. Only a Model Hub backend has a+ * catalog to add to, and the Model Hub is an Instance Owner surface that sends+ * anyone else home.+ *+ * The one owner of that answer. It comes from a read made while the surface is+ * showing and is dropped the moment it may be stale — the surface is covered+ * (Settings may switch the backend to Direct), the backend changes, or `enabled`+ * turns off — so no exit outlives the read that justified it, and a failed read+ * shows none. `enabled` lets a picker read only while its menu is open.+ *+ * The exit is a detour to come back from, so it records where it starts, on a+ * phone too, where Settings otherwise keeps only the Workbench home mounted+ * behind it. From a picker already inside Settings it keeps the visit's origin.+ */+export function useAddModelExit(backend: string, enabled = true): (() => void) | null {+ const api = useApi();+ const navigate = useNavigate();+ const location = useLocation();+ const { capabilities } = useInstanceAuthorization();+ const surfaceActive = useRouteSurfaceActive();+ const readable = enabled && surfaceActive && Boolean(backend) && capabilities.can_manage_instance;+ const [hubBackend, setHubBackend] = useState<string | null>(null);+ useEffect(() => {+ if (!readable) return;+ let cancelled = false;+ void api.readModelHubAgentCatalogForModelPicker(backend).then((agent) => {+ if (!cancelled && isHubAgent(agent, backend)) setHubBackend(backend);+ });+ return () => {+ cancelled = true;+ setHubBackend(null);+ };+ }, [api, backend, readable]);+ if (!readable || hubBackend !== backend) return null;+ return () => navigate(modelHubCatalogPath(backend), { state: settingsOverlayContinuationState(location) });+}++/**+ * Read a backend's model list, then re-read while a remote-catalog refresh is+ * pending. A caller whose surface stays mounted under Settings treats a Settings+ * visit as invalidating what it read: it drops those rows when+ * `useRouteSurfaceActive()` turns false and reads again when it turns true, since+ * the Model Hub there edits the list and may change which catalog supplies it.+ */export function loadBackendModelsWithRefresh(api: ApiContextType,backend: string,diff --git a/ui/src/lib/settingsOverlay.ts b/ui/src/lib/settingsOverlay.tsindex ab124bc27..c48282c21 100644--- a/ui/src/lib/settingsOverlay.ts+++ b/ui/src/lib/settingsOverlay.ts@@ -140,6 +140,30 @@ export const settingsOverlayStateForOrigin = (*/const retainsOriginOnMobile = (pathname: string): boolean => pathname === '/' || pathname === '/setup';+/**+ * The origin a Settings-bound navigation from `source` carries: the one an+ * open Settings visit already holds, or else `source` itself when it may be+ * retained. A Settings route is never an origin, so a navigation inside+ * Settings keeps the visit's origin instead of replacing it.+ */+const sourceOrigin = (source: Location, retains: boolean, historyState: unknown): SettingsOverlayOrigin | null =>+ settingsOverlayOriginFromState(source.state)+ ?? (retains && !isSettingsEntryPath(source.pathname) ? originFromLocation(source, historyState) : null);++/**+ * State for a continuation into Settings that must come back to where it+ * started, such as a model picker's Add model exit, on every device. Mobile+ * otherwise retains only the routes above, and the page this leaves may hold+ * a draft.+ */+export const settingsOverlayContinuationState = (+ source: Location,+ historyState: unknown = currentHistoryState(),+): SettingsOverlayState | undefined => {+ const origin = sourceOrigin(source, true, historyState);+ return origin ? overlayStateForOrigin(origin) : undefined;+};+export const settingsOverlayNavigationState = ({destinationPathname,desktop,@@ -156,12 +180,7 @@ export const settingsOverlayNavigationState = ({if (!isSettingsEntryPath(destinationPathname)) return targetState;if (settingsOverlayOriginFromState(targetState)) return targetState;- const retainedOrigin = settingsOverlayOriginFromState(source.state);- const retains = desktop || retainsOriginOnMobile(source.pathname);- const origin = retainedOrigin- ?? (retains && !isSettingsEntryPath(source.pathname)- ? originFromLocation(source, historyState)- : null);+ const origin = sourceOrigin(source, desktop || retainsOriginOnMobile(source.pathname), historyState);if (!origin) return targetState;return settingsOverlayStateForOrigin(origin, targetState);};diff --git a/ui/src/lib/useAddModelExit.test.tsx b/ui/src/lib/useAddModelExit.test.tsxnew file mode 100644index 000000000..7c3243f56--- /dev/null+++ b/ui/src/lib/useAddModelExit.test.tsx@@ -0,0 +1,164 @@+/* @vitest-environment jsdom */+//+// Who sees a model picker's "Add model" exit, and for how long. The answer is+// only as good as the read behind it: Settings, which the exit opens, is also+// where a backend is switched to Direct, so an answer from before a visit may+// no longer hold and must not be shown while the next read is in flight.+import { act, renderHook } from '@testing-library/react';+import type { ReactNode } from 'react';+import { MemoryRouter, useLocation } from 'react-router-dom';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { AgentSupply } from '../components/settings/models/types';+import { InstanceAuthorizationContext } from '../context/InstanceAuthorizationContext';+import { useAddModelExit } from './backendModels';+import { RouteSurfaceActiveContext } from './routeSurfaceActivity';+import { settingsOverlayOpenState, settingsOverlayOriginFromState } from './settingsOverlay';+import { capabilitiesFor } from './testing/instanceRoleCapabilities';+import type { InstanceRole } from './sessionInfo';++type PickerAgent = Pick<AgentSupply, 'backend' | 'mode' | 'catalog_models'> | null;++// Each read waits for its own answer, so a test decides when a read lands.+const reads: { backend: string; answer: (agent: PickerAgent) => void }[] = [];+const API = {+ readModelHubAgentCatalogForModelPicker: vi.fn(+ (backend: string) => new Promise<PickerAgent>((answer) => reads.push({ backend, answer })),+ ),+};+vi.mock('../context/ApiContext', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../context/ApiContext')>()),+ useApi: () => API,+}));++const hub = (backend: AgentSupply['backend']): PickerAgent => ({ backend, mode: 'hub', catalog_models: [] });+const direct = (backend: AgentSupply['backend']): PickerAgent => ({ backend, mode: 'direct' });++const land = async (agent: PickerAgent) => {+ await act(async () => reads.at(-1)!.answer(agent));+};++type Entry = string | { pathname: string; state: unknown };++const setup = (initial: { backend: string; enabled?: boolean; surfaceActive?: boolean; role?: InstanceRole; entry?: Entry }) => {+ let surfaceActive = initial.surfaceActive ?? true;+ let role: InstanceRole = initial.role ?? 'owner';+ const wrapper = ({ children }: { children: ReactNode }) => (+ <InstanceAuthorizationContext.Provider+ value={{ remote: false, instanceKind: null, instanceRole: role, capabilities: capabilitiesFor(role) }}+ >+ <RouteSurfaceActiveContext.Provider value={surfaceActive}>+ <MemoryRouter initialEntries={[initial.entry ?? '/agents?tab=definitions']}>{children}</MemoryRouter>+ </RouteSurfaceActiveContext.Provider>+ </InstanceAuthorizationContext.Provider>+ );+ const view = renderHook(+ ({ backend, enabled }: { backend: string; enabled?: boolean }) => ({+ exit: useAddModelExit(backend, enabled),+ location: useLocation(),+ }),+ { wrapper, initialProps: { backend: initial.backend, enabled: initial.enabled } },+ );+ return {+ ...view,+ cover: (covered: boolean) => {+ surfaceActive = !covered;+ view.rerender({ backend: initial.backend, enabled: initial.enabled });+ },+ as: (next: InstanceRole) => {+ role = next;+ view.rerender({ backend: initial.backend, enabled: initial.enabled });+ },+ };+};++afterEach(() => {+ reads.length = 0;+ API.readModelHubAgentCatalogForModelPicker.mockClear();+});++describe('useAddModelExit', () => {+ it("opens the Hub backend's own catalog once the read confirms the Hub supplies it", async () => {+ const { result } = setup({ backend: 'codex' });+ expect(result.current.exit).toBeNull();++ await land(hub('codex'));+ act(() => result.current.exit!());++ const { pathname, search, state } = result.current.location;+ expect(`${pathname}${search}`).toBe('/settings/models?manage=codex');+ // A detour to come back from: the page it left, and any draft on it, stays+ // mounted behind Settings, which a phone does not do for an ordinary visit.+ expect(settingsOverlayOriginFromState(state)?.location).toMatchObject({+ pathname: '/agents',+ search: '?tab=definitions',+ });+ });++ it('keeps the Settings visit it starts in coming back to the same place', async () => {+ // The IM channel settings page is a Settings route over a session. A+ // Settings route is never an origin, so the exit must carry the visit's.+ const session = { pathname: '/chat/ses_1', search: '', hash: '', state: null, key: 'k1' };+ const { result } = setup({+ backend: 'codex',+ entry: { pathname: '/settings/platforms/groups', state: settingsOverlayOpenState(session, null) },+ });+ await land(hub('codex'));+ act(() => result.current.exit!());++ expect(result.current.location.pathname).toBe('/settings/models');+ expect(settingsOverlayOriginFromState(result.current.location.state)?.location.pathname).toBe('/chat/ses_1');+ });++ it.each([+ ['a Direct backend', direct('codex')],+ ['a failed read, which the API reports as no record', null],+ ['a record describing another backend', hub('claude')],+ ])('shows no exit for %s', async (_case, agent) => {+ const { result } = setup({ backend: 'codex' });+ await land(agent);+ expect(result.current.exit).toBeNull();+ });++ it('does not ask for a viewer the owner-only Model Hub would send home', () => {+ const { result } = setup({ backend: 'codex', role: 'editor' });+ expect(API.readModelHubAgentCatalogForModelPicker).not.toHaveBeenCalled();+ expect(result.current.exit).toBeNull();+ });++ it('reads nothing until the picker enables it', () => {+ setup({ backend: 'codex', enabled: false });+ expect(API.readModelHubAgentCatalogForModelPicker).not.toHaveBeenCalled();+ });++ it('drops the answer while Settings covers the surface and shows none until a new read lands', async () => {+ const view = setup({ backend: 'codex' });+ await land(hub('codex'));++ view.cover(true);+ expect(view.result.current.exit).toBeNull();++ view.cover(false);+ // The earlier answer is not lent to the read now in flight.+ expect(API.readModelHubAgentCatalogForModelPicker).toHaveBeenCalledTimes(2);+ expect(view.result.current.exit).toBeNull();++ // The visit switched the backend to Direct.+ await land(direct('codex'));+ expect(view.result.current.exit).toBeNull();+ });++ it("does not lend one backend's answer to the next", async () => {+ const view = setup({ backend: 'codex' });+ await land(hub('codex'));++ view.rerender({ backend: 'claude', enabled: undefined });+ expect(view.result.current.exit).toBeNull();++ // A late answer for the backend it has left changes nothing.+ await act(async () => reads[0].answer(hub('codex')));+ expect(view.result.current.exit).toBeNull();+ await land(hub('claude'));+ expect(view.result.current.exit).not.toBeNull();+ });+});