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.

fix(model-hub): reconcile OpenCode menu writes

cyh16b3e2718e3a
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.md
index f910090a0..a977c755e 100644
--- a/docs/plans/model-hub-ui-spec.md
+++ b/docs/plans/model-hub-ui-spec.md
@@ -1488,6 +1488,7 @@ unable to outlive its surface, which is the cheaper answer wherever it is availa
| `gateway.menu.search` `[derived]` | 搜索模型或供应商 | Search models or sources |
| `gateway.menu.selected` `[derived]` | 已选 {{selected}} / {{total}} | {{selected}} of {{total}} selected |
| `gateway.menu.empty` `[derived]` | 没有可供 OpenCode 选择的模型 | No eligible source models are available |
+| `gateway.menu.configured` `[derived]` | 已有配置模型 | Existing configured model |
| `gateway.menu.baselineUnavailable` `[derived]` | 模型菜单数据暂未更新,请等待刷新完成,或重试读取失败的区域后再编辑。 | Model menu data is not current. Wait for refresh, or retry the failed section before editing. |
| `gateway.menu.noMatch` `[derived]` | 没有匹配的模型 | No models match this search |
| `gateway.menu.save` `[derived]` | 保存选择 | Save selection |
@@ -1869,12 +1870,15 @@ OpenCode identifier. Saving performs `PUT /api/models/agents/opencode/menu`; a s
model with no Route then appears as an ordinary row whose current-text slot reads
`gateway.group.status.unconfigured`, and that row opens frame 02. The dialog preserves
the saved menu view, blocks dismissal while its write is outstanding, and retains the
-draft after a failed save. Both inputs to the whole-menu write must be authoritative ready
-reads before the dialog enables search, selection, or save: `AgentSupply` owns `menu`,
-`standard_vendors` and eligibility, while `Source[]` owns the candidate inventory. Either
-input being loading, unread or degraded preserves the stored `menu.checked` values, shows
-`gateway.menu.baselineUnavailable`, and cannot issue the menu `PUT`; stale or absent data
-is never interpreted as an empty selection.
+draft after a failed save. The dialog owns a dedicated `AgentSupply` + `Source[]` read pair
+rather than composing the page's independently settled regions. It detects source-membership
+holes and regroups the pair once before enabling search, selection, or save, then reads the
+pair again immediately before its total write and rebases only the user's explicit additions
+and removals. Existing checked identifiers remain visible and selected even when their Route
+maps to a differently named upstream model. A failed or undecodable `PUT` is reconciled with
+another dedicated pair before the dialog reports failure or enables another edit. An unread
+or non-convergent pair preserves the draft, shows `gateway.menu.baselineUnavailable`, and
+cannot issue the menu `PUT`; stale or absent data is never interpreted as an empty selection.
**Extreme data**
diff --git a/ui/src/components/settings/models/OpenCodeMenuDialog.test.tsx b/ui/src/components/settings/models/OpenCodeMenuDialog.test.tsx
index 11fe2298a..a154f09ce 100644
--- a/ui/src/components/settings/models/OpenCodeMenuDialog.test.tsx
+++ b/ui/src/components/settings/models/OpenCodeMenuDialog.test.tsx
@@ -5,10 +5,8 @@ import { I18nextProvider } from 'react-i18next';
import { afterEach, describe, expect, it, vi } from 'vitest';
import i18n from '@/i18n';
-import { openCodeMenuBaselineReady } from './menuBaseline';
-import { modelsApi } from './modelsApi';
+import { ApiCallError, modelsApi } from './modelsApi';
import { OpenCodeMenuDialog } from './OpenCodeMenuDialog';
-import { failRegionRead, readyRegion } from './regionRead';
import type { AgentSupply, Source } from './types';
const source = (overrides: Partial<Source> & Pick<Source, 'id' | 'vendor' | 'display_name'>): Source => ({
@@ -74,6 +72,7 @@ describe('OpenCodeMenuDialog', () => {
menu: { view: 'featured' as const, checked: ['openai/gpt-5.6-luna'] },
model_supply: [{ model_id: 'openai/gpt-5.6-luna', chain_length: 0, has_runnable_hop: false }],
};
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);
const putMenu = vi.spyOn(modelsApi, 'putMenu').mockResolvedValue(echoed);
const onSaved = vi.fn();
const onClose = vi.fn();
@@ -82,17 +81,16 @@ describe('OpenCodeMenuDialog', () => {
<I18nextProvider i18n={i18n}>
<OpenCodeMenuDialog
open
- agent={agent}
- sources={sources}
- baselineReady
+ sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}
onClose={onClose}
onSaved={onSaved}
+ onObserved={vi.fn()}
menuWrite={{ pending: false, track: async (work) => work() }}
/>
</I18nextProvider>,
);
- expect(screen.getByText('0 of 2 selected')).toBeTruthy();
+ expect(await screen.findByText('0 of 2 selected')).toBeTruthy();
expect(screen.queryByText('Blocked Source')).toBeNull();
expect(screen.queryByText(/gpt-retired/)).toBeNull();
@@ -110,79 +108,174 @@ describe('OpenCodeMenuDialog', () => {
it('filters by source name without changing the selected menu', async () => {
const user = userEvent.setup();
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue({
+ ...agent,
+ menu: { view: 'full', checked: ['openai/gpt-5.6-sol'] },
+ });
render(
<I18nextProvider i18n={i18n}>
<OpenCodeMenuDialog
open
- agent={{ ...agent, menu: { view: 'full', checked: ['openai/gpt-5.6-sol'] } }}
- sources={sources}
- baselineReady
+ sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}
onClose={vi.fn()}
onSaved={vi.fn()}
+ onObserved={vi.fn()}
menuWrite={{ pending: false, track: async (work) => work() }}
/>
</I18nextProvider>,
);
- await user.type(screen.getByRole('textbox', { name: 'Search models or sources' }), 'luna');
+ await user.type(await screen.findByRole('textbox', { name: 'Search models or sources' }), 'luna');
expect(screen.getByRole('checkbox', { name: /openai\/gpt-5\.6-luna/i })).toBeTruthy();
expect(screen.queryByRole('checkbox', { name: /openai\/gpt-5\.6-sol/i })).toBeNull();
expect(screen.getByText('1 of 2 selected')).toBeTruthy();
});
- it('persists removal of a checked identifier whose last eligible supplier disappeared', async () => {
+ it('renders a checked route alias and removes it only after an explicit uncheck', async () => {
const user = userEvent.setup();
+ const configured = {
+ ...agent,
+ menu: { view: 'featured' as const, checked: ['openai/menu-model'] },
+ routes: { 'openai/menu-model': { hops: [{ source_id: 'src_openai', model_id: 'gpt-5.6-luna' }] } },
+ };
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(configured);
const putMenu = vi.spyOn(modelsApi, 'putMenu').mockResolvedValue({ ...agent, menu: { view: 'featured', checked: [] } });
render(
<I18nextProvider i18n={i18n}>
<OpenCodeMenuDialog
open
- agent={{ ...agent, menu: { view: 'featured', checked: ['openai/missing-model'] } }}
- sources={sources}
- baselineReady
+ sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}
onClose={vi.fn()}
onSaved={vi.fn()}
+ onObserved={vi.fn()}
menuWrite={{ pending: false, track: async (work) => work() }}
/>
</I18nextProvider>,
);
- expect(screen.getByText('0 of 2 selected')).toBeTruthy();
+ const alias = await screen.findByRole('checkbox', { name: /openai\/menu-model/i });
+ expect(alias.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByText('1 of 3 selected')).toBeTruthy();
+ await user.click(alias);
await user.click(screen.getByRole('button', { name: 'Save selection' }));
await waitFor(() => expect(putMenu).toHaveBeenCalledWith({ view: 'featured', checked: [] }));
});
- it('keeps the saved menu immutable while source inventory is unread', async () => {
+ it('preserves a checked cross-model route while saving an unrelated addition', async () => {
const user = userEvent.setup();
+ const configured = {
+ ...agent,
+ menu: { view: 'featured' as const, checked: ['openai/menu-model'] },
+ routes: { 'openai/menu-model': { hops: [{ source_id: 'src_openai', model_id: 'gpt-5.6-sol' }] } },
+ };
+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(configured);
+ const putMenu = vi.spyOn(modelsApi, 'putMenu').mockResolvedValue({
+ ...configured,
+ menu: { view: 'featured', checked: ['openai/menu-model', 'openai/gpt-5.6-luna'] },
+ });
+ render(
+ <I18nextProvider i18n={i18n}>
+ <OpenCodeMenuDialog
+ open
+ sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}
+ onClose={vi.fn()}
+ onSaved={vi.fn()}
+ onObserved={vi.fn()}
+ menuWrite={{ pending: false, track: async (work) => work() }}
+ />
+ </I18nextProvider>,
+ );
+
+ await user.click(await screen.findByRole('checkbox', { name: /openai\/gpt-5\.6-luna/i }));
+ await user.click(screen.getByRole('button', { name: 'Save selection' }));
+ await waitFor(() => expect(putMenu).toHaveBeenCalledWith({
+ view: 'featured',
+ checked: ['openai/menu-model', 'openai/gpt-5.6-luna'],
+ }));
+ });
+
+ it('blocks editing when its dedicated baseline read fails', async () => {
+ vi.spyOn(modelsApi, 'getAgentSources').mockRejectedValue(new Error('unread'));
const putMenu = vi.spyOn(modelsApi, 'putMenu');
render(
<I18nextProvider i18n={i18n}>
<OpenCodeMenuDialog
open
- agent={{ ...agent, menu: { view: 'featured', checked: ['openai/gpt-5.6-luna'] } }}
- sources={[]}
- baselineReady={false}
+ sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}
onClose={vi.fn()}
onSaved={vi.fn()}
+ onObserved={vi.fn()}
menuWrite={{ pending: false, track: async (work) => work() }}
/>
</I18nextProvider>,
);
- expect(screen.getByText('1 selected')).toBeTruthy();
- expect(screen.getByText('Model menu data is not current. Wait for refresh, or retry the failed section before editing.')).toBeTruthy();
- const save = screen.getByRole('button', { name: 'Save selection' });
- expect(save.hasAttribute('disabled')).toBe(true);
- await user.click(save);
+ expect(await screen.findByText('Model menu data is not current. Wait for refresh, or retry the failed section before editing.')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Save selection' }).hasAttribute('disabled')).toBe(true);
expect(putMenu).not.toHaveBeenCalled();
});
- it('requires current AgentSupply and Source inventory for the menu baseline', () => {
- const supply = readyRegion([agent]);
- const inventory = readyRegion(sources);
+ it('accepts a committed menu after an inconclusive PUT by re-reading it', async () => {
+ const user = userEvent.setup();
+ const committed = {
+ ...agent,
+ menu: { view: 'featured' as const, checked: ['openai/gpt-5.6-luna'] },
+ };
+ vi.spyOn(modelsApi, 'getAgentSources')
+ .mockResolvedValueOnce(agent)
+ .mockResolvedValueOnce(agent)
+ .mockResolvedValueOnce(committed);
+ vi.spyOn(modelsApi, 'putMenu').mockRejectedValue(new ApiCallError('bad_response', undefined, false));
+ const onSaved = vi.fn();
+ const onClose = vi.fn();
+ render(
+ <I18nextProvider i18n={i18n}>
+ <OpenCodeMenuDialog
+ open
+ sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}
+ onClose={onClose}
+ onSaved={onSaved}
+ onObserved={vi.fn()}
+ menuWrite={{ pending: false, track: async (work) => work() }}
+ />
+ </I18nextProvider>,
+ );
+
+ await user.click(await screen.findByRole('checkbox', { name: /openai\/gpt-5\.6-luna/i }));
+ await user.click(screen.getByRole('button', { name: 'Save selection' }));
+ await waitFor(() => expect(onSaved).toHaveBeenCalledWith(committed));
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it('rebases a failed draft on the observed menu before enabling retry', async () => {
+ const user = userEvent.setup();
+ vi.spyOn(modelsApi, 'getAgentSources')
+ .mockResolvedValueOnce(agent)
+ .mockResolvedValueOnce(agent)
+ .mockResolvedValueOnce(agent);
+ vi.spyOn(modelsApi, 'putMenu').mockRejectedValue(new ApiCallError('bad_response', undefined, false));
+ const onObserved = vi.fn();
+ render(
+ <I18nextProvider i18n={i18n}>
+ <OpenCodeMenuDialog
+ open
+ sourceReads={{ readValue: vi.fn().mockResolvedValue(sources) }}
+ onClose={vi.fn()}
+ onSaved={vi.fn()}
+ onObserved={onObserved}
+ menuWrite={{ pending: false, track: async (work) => work() }}
+ />
+ </I18nextProvider>,
+ );
+
+ const luna = await screen.findByRole('checkbox', { name: /openai\/gpt-5\.6-luna/i });
+ await user.click(luna);
+ await user.click(screen.getByRole('button', { name: 'Save selection' }));
- expect(openCodeMenuBaselineReady(supply, inventory)).toBe(true);
- expect(openCodeMenuBaselineReady(failRegionRead(supply), inventory)).toBe(false);
- expect(openCodeMenuBaselineReady(supply, failRegionRead(inventory))).toBe(false);
+ expect(await screen.findByText('The model selection was not saved')).toBeTruthy();
+ expect(onObserved).toHaveBeenCalledWith(agent);
+ expect(luna.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByRole('button', { name: 'Save selection' }).hasAttribute('disabled')).toBe(false);
});
});
diff --git a/ui/src/components/settings/models/OpenCodeMenuDialog.tsx b/ui/src/components/settings/models/OpenCodeMenuDialog.tsx
index 626c19d75..be380967e 100644
--- a/ui/src/components/settings/models/OpenCodeMenuDialog.tsx
+++ b/ui/src/components/settings/models/OpenCodeMenuDialog.tsx
@@ -1,5 +1,5 @@
import * as React from 'react';
-import { LoaderCircle, Search } from 'lucide-react';
+import { LoaderCircle, RefreshCw, Search } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
@@ -7,11 +7,19 @@ import { Checkbox } from '@/components/ui/checkbox';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
-import { initialSeedState, savedMenuKey, seedStep, type PendingWrite } from './asyncLifetime';
+import type { PendingWrite } from './asyncLifetime';
+import type { CollectionReadAuthority } from './collectionReadAuthority';
import { eligibleSources } from './eligibility';
+import {
+ applyOpenCodeMenuIntent,
+ openCodeMenuIntent,
+ readOpenCodeMenuBaseline,
+ sameOpenCodeMenu,
+ type OpenCodeMenuBaseline,
+} from './menuBaseline';
import { buildIdentifier } from './menus/identifiers';
import { modelsApi } from './modelsApi';
-import type { AgentSupply, Source } from './types';
+import type { AgentMenu, AgentSupply, Source } from './types';
type MenuModel = {
id: string;
@@ -21,6 +29,7 @@ type MenuModel = {
const selectableModels = (agent: AgentSupply, sources: Source[]): MenuModel[] => {
const standardVendors = new Set(agent.standard_vendors ?? []);
const namesById = new Map<string, Set<string>>();
+ const sourceNames = new Map(sources.map((source) => [source.id, source.display_name]));
for (const source of eligibleSources(sources, agent)) {
for (const model of source.models) {
if (model.retired) continue;
@@ -30,6 +39,15 @@ const selectableModels = (agent: AgentSupply, sources: Source[]): MenuModel[] =>
namesById.set(id, names);
}
}
+ for (const id of agent.menu?.checked ?? []) {
+ if (namesById.has(id)) continue;
+ const names = new Set<string>();
+ for (const hop of agent.routes?.[id]?.hops ?? []) {
+ const name = sourceNames.get(hop.source_id);
+ if (name) names.add(name);
+ }
+ namesById.set(id, names);
+ }
return [...namesById.entries()]
.map(([id, names]) => ({ id, sourceNames: [...names].sort((left, right) => left.localeCompare(right)) }))
.sort((left, right) => left.id.localeCompare(right.id));
@@ -37,40 +55,64 @@ const selectableModels = (agent: AgentSupply, sources: Source[]): MenuModel[] =>
export const OpenCodeMenuDialog: React.FC<{
open: boolean;
- agent: AgentSupply;
- sources: Source[];
- baselineReady: boolean;
+ sourceReads: Pick<CollectionReadAuthority<Source[]>, 'readValue'>;
onClose: () => void;
onSaved: (echoed: AgentSupply) => void | Promise<void>;
+ onObserved: (observed: AgentSupply) => void | Promise<void>;
menuWrite: PendingWrite;
-}> = ({ open, agent, sources, baselineReady, onClose, onSaved, menuWrite }) => {
+}> = ({ open, sourceReads, onClose, onSaved, onObserved, menuWrite }) => {
const { t } = useTranslation();
- const models = React.useMemo(() => selectableModels(agent, sources), [agent, sources]);
- const availableIds = React.useMemo(() => new Set(models.map((model) => model.id)), [models]);
- const rawChecked = React.useMemo(() => agent.menu?.checked ?? [], [agent.menu?.checked]);
- const savedChecked = React.useMemo(
- () => baselineReady ? rawChecked.filter((id) => availableIds.has(id)) : rawChecked,
- [availableIds, baselineReady, rawChecked],
+ const [baseline, setBaseline] = React.useState<OpenCodeMenuBaseline | null>(null);
+ const baselineRef = React.useRef<OpenCodeMenuBaseline | null>(null);
+ const [readState, setReadState] = React.useState<'loading' | 'ready' | 'error'>('loading');
+ const [selected, setSelectedState] = React.useState<Set<string>>(new Set());
+ const selectedRef = React.useRef<Set<string>>(new Set());
+ const readAttempt = React.useRef(0);
+ const models = React.useMemo(
+ () => baseline ? selectableModels(baseline.agent, baseline.sources) : [],
+ [baseline],
);
- const [selected, setSelected] = React.useState<Set<string>>(() => new Set(savedChecked));
+ const rawChecked = React.useMemo(() => baseline?.agent.menu?.checked ?? [], [baseline]);
const [query, setQuery] = React.useState('');
const [saveFailed, setSaveFailed] = React.useState(false);
- const seed = React.useRef(initialSeedState);
- const inventoryKey = React.useMemo(() => JSON.stringify(models.map((model) => model.id)), [models]);
- const [lastReadyInventory, setLastReadyInventory] = React.useState<string | null>(() => baselineReady ? inventoryKey : null);
- const inventoryAuthority = baselineReady ? inventoryKey : lastReadyInventory ?? 'unread';
- const authoritative = JSON.stringify([savedMenuKey(agent.menu), inventoryAuthority]);
+ const applyBaseline = React.useCallback((next: OpenCodeMenuBaseline, checked: readonly string[]) => {
+ const nextSelected = new Set(checked);
+ baselineRef.current = next;
+ selectedRef.current = nextSelected;
+ setBaseline(next);
+ setSelectedState(nextSelected);
+ setReadState('ready');
+ }, []);
+
+ const loadBaseline = React.useCallback(async (preserveDraft: boolean) => {
+ const attempt = ++readAttempt.current;
+ const previous = baselineRef.current;
+ const intent = preserveDraft && previous
+ ? openCodeMenuIntent(previous.agent.menu?.checked ?? [], [...selectedRef.current])
+ : null;
+ setReadState('loading');
+ try {
+ const next = await readOpenCodeMenuBaseline(modelsApi, sourceReads);
+ if (attempt !== readAttempt.current) return;
+ const selectableIds = new Set(selectableModels(next.agent, next.sources).map((model) => model.id));
+ applyBaseline(
+ next,
+ intent
+ ? applyOpenCodeMenuIntent(next.agent.menu?.checked ?? [], intent, selectableIds)
+ : next.agent.menu?.checked ?? [],
+ );
+ setQuery('');
+ setSaveFailed(false);
+ } catch {
+ if (attempt === readAttempt.current) setReadState('error');
+ }
+ }, [applyBaseline, sourceReads]);
+
React.useEffect(() => {
- if (!open) return;
- if (baselineReady && lastReadyInventory !== inventoryKey) setLastReadyInventory(inventoryKey);
- const step = seedStep(seed.current, authoritative);
- seed.current = step.state;
- if (!step.reseed) return;
- setSelected(new Set(savedChecked));
- setQuery('');
- setSaveFailed(false);
- }, [open, authoritative, baselineReady, inventoryKey, lastReadyInventory, savedChecked]);
+ if (open) void loadBaseline(false);
+ else readAttempt.current += 1;
+ }, [loadBaseline, open]);
const normalizedQuery = query.trim().toLocaleLowerCase();
const visibleModels = normalizedQuery
@@ -78,31 +120,69 @@ export const OpenCodeMenuDialog: React.FC<{
: models;
const savedSet = new Set(rawChecked);
const dirty = selected.size !== savedSet.size || [...selected].some((id) => !savedSet.has(id));
+ const baselineReady = readState === 'ready' && baseline !== null;
const toggle = (id: string) => {
if (!baselineReady || menuWrite.pending) return;
setSaveFailed(false);
- setSelected((previous) => {
- const next = new Set(previous);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
+ const next = new Set(selectedRef.current);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ selectedRef.current = next;
+ setSelectedState(next);
};
const save = () => {
- if (!baselineReady || !dirty || menuWrite.pending) return;
+ const current = baselineRef.current;
+ if (!baselineReady || !current || !dirty || menuWrite.pending) return;
+ const intent = openCodeMenuIntent(
+ current.agent.menu?.checked ?? [],
+ [...selectedRef.current],
+ );
setSaveFailed(false);
void menuWrite.track(async () => {
+ let latest: OpenCodeMenuBaseline;
+ try {
+ latest = await readOpenCodeMenuBaseline(modelsApi, sourceReads);
+ } catch {
+ setReadState('error');
+ setSaveFailed(true);
+ return;
+ }
+
+ const latestSelectable = new Set(selectableModels(latest.agent, latest.sources).map((model) => model.id));
+ const attemptedMenu: AgentMenu = {
+ view: latest.agent.menu?.view ?? 'featured',
+ checked: applyOpenCodeMenuIntent(latest.agent.menu?.checked ?? [], intent, latestSelectable),
+ };
+ applyBaseline(latest, attemptedMenu.checked);
+ if (sameOpenCodeMenu(latest.agent.menu, attemptedMenu)) {
+ await Promise.resolve(onObserved(latest.agent)).catch(() => {});
+ onClose();
+ return;
+ }
+
let echoed: AgentSupply;
try {
- const existing = rawChecked.filter((id) => availableIds.has(id) && selected.has(id));
- const added = models.map((model) => model.id).filter((id) => selected.has(id) && !savedSet.has(id));
- echoed = await modelsApi.putMenu({
- view: agent.menu?.view ?? 'featured',
- checked: [...existing, ...added],
- });
+ echoed = await modelsApi.putMenu(attemptedMenu);
} catch {
+ try {
+ const observed = await readOpenCodeMenuBaseline(modelsApi, sourceReads);
+ if (sameOpenCodeMenu(observed.agent.menu, attemptedMenu)) {
+ applyBaseline(observed, observed.agent.menu?.checked ?? []);
+ await Promise.resolve(onSaved(observed.agent)).catch(() => {});
+ onClose();
+ return;
+ }
+ const observedSelectable = new Set(selectableModels(observed.agent, observed.sources).map((model) => model.id));
+ applyBaseline(
+ observed,
+ applyOpenCodeMenuIntent(observed.agent.menu?.checked ?? [], intent, observedSelectable),
+ );
+ await Promise.resolve(onObserved(observed.agent)).catch(() => {});
+ } catch {
+ setReadState('error');
+ }
setSaveFailed(true);
return;
}
@@ -147,7 +227,11 @@ export const OpenCodeMenuDialog: React.FC<{
<div className="min-h-0 flex-1 overflow-y-auto rounded-md border border-border bg-background p-1.5">
{!baselineReady ? (
- <p className="px-4 py-10 text-center text-[12.5px] text-muted">{t('settings.models.gateway.menu.baselineUnavailable')}</p>
+ <div className="flex flex-col items-center gap-3 px-4 py-10 text-center text-[12.5px] text-muted">
+ {readState === 'loading' && <LoaderCircle className="size-4 animate-spin" aria-hidden="true" />}
+ <p>{t('settings.models.gateway.menu.baselineUnavailable')}</p>
+ {readState === 'error' && <Button type="button" variant="outline" size="xs" onClick={() => void loadBaseline(true)}><RefreshCw aria-hidden="true" />{t('settings.models.gateway.retry')}</Button>}
+ </div>
) : models.length === 0 ? (
<p className="px-4 py-10 text-center text-[12.5px] text-muted">{t('settings.models.gateway.menu.empty')}</p>
) : visibleModels.length === 0 ? (
@@ -156,6 +240,9 @@ export const OpenCodeMenuDialog: React.FC<{
<div className="space-y-1">
{visibleModels.map((model) => {
const checked = selected.has(model.id);
+ const sourceLabel = model.sourceNames.length > 0
+ ? model.sourceNames.join(' · ')
+ : t('settings.models.gateway.menu.configured');
return (
<button
key={model.id}
@@ -172,7 +259,7 @@ export const OpenCodeMenuDialog: React.FC<{
<Checkbox checked={checked} presentational />
<span className="min-w-0 flex-1">
<span className="block truncate font-mono text-[12px] font-medium text-foreground" title={model.id}>{model.id}</span>
- <span className="mt-0.5 block truncate text-[10.5px] text-muted" title={model.sourceNames.join(', ')}>{model.sourceNames.join(' · ')}</span>
+ <span className="mt-0.5 block truncate text-[10.5px] text-muted" title={sourceLabel}>{sourceLabel}</span>
</span>
</button>
);
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index c48890374..f7ac978be 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -25,7 +25,6 @@ import { SourceOrderDrawer } from './SourceOrderDrawer';
import { SourcesCard } from './SourcesCard';
import { modelsSurfaceKindFromReads } from './modelHubSurfaceState';
import { focusModelHubProjection } from './modelHubFocus';
-import { openCodeMenuBaselineReady } from './menuBaseline';
import { buildSupplyRelations } from './supplyRelations';
import {
emptySuspendedRouteAttempts,
@@ -929,7 +928,6 @@ export const SettingsModelsPage: React.FC = () => {
const sourceDetailOpen = selectedSourceId !== null && subscriptionVendor === null;
const orderAgent = agents.find((agent) => agent.backend === orderBackend && agent.mode === 'hub') ?? null;
const menuAgent = agents.find((agent) => agent.backend === menuBackend && agent.backend === 'opencode' && agent.mode === 'hub') ?? null;
- const menuBaselineReady = openCodeMenuBaselineReady(supplyRead, sourcesRead);
const currentRouteAgent = routeTarget
? installedAgents.find((agent) => agent.backend === routeTarget.agent.backend) ?? null
: null;
@@ -1385,7 +1383,7 @@ export const SettingsModelsPage: React.FC = () => {
/>
)}
{orderAgent && <SourceOrderDrawer open agent={orderAgent} sources={sources} sourceReads={sourceCollectionReads} onClose={() => setOrderBackend(null)} onSaved={agentSaved} orderWrite={{ pending: agentWrites.has(orderAgent.backend), track: (work) => agentWriteRegistry.track(orderAgent.backend, work) }} />}
- {menuAgent && <OpenCodeMenuDialog open agent={menuAgent} sources={sources} baselineReady={menuBaselineReady} onClose={() => setMenuBackend(null)} onSaved={agentSaved} menuWrite={{ pending: agentWrites.has(menuAgent.backend), track: (work) => agentWriteRegistry.track(menuAgent.backend, work) }} />}
+ {menuAgent && <OpenCodeMenuDialog open sourceReads={sourceCollectionReads} onClose={() => setMenuBackend(null)} onSaved={agentSaved} onObserved={applyAgentEcho} menuWrite={{ pending: agentWrites.has(menuAgent.backend), track: (work) => agentWriteRegistry.track(menuAgent.backend, work) }} />}
<RouteChainDialog
selection={routeSelection}
sources={sources}
diff --git a/ui/src/components/settings/models/menuBaseline.test.ts b/ui/src/components/settings/models/menuBaseline.test.ts
new file mode 100644
index 000000000..df293e321
--- /dev/null
+++ b/ui/src/components/settings/models/menuBaseline.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ applyOpenCodeMenuIntent,
+ openCodeMenuIntent,
+ readOpenCodeMenuBaseline,
+ sameOpenCodeMenu,
+} from './menuBaseline';
+import type { AgentSupply, Source } from './types';
+
+const source = (id: string): Source => ({
+ id,
+ last_discovered_at: null,
+ kind: 'api_key',
+ vendor: 'openai',
+ display_name: id,
+ protocol: 'openai_responses',
+ supply_channel: 'hub',
+ billing: 'metered',
+ state: { status: 'active', retry_at: null, detail_key: null },
+ models: [],
+});
+
+const agent = (sourceIds: string[]): AgentSupply => ({
+ backend: 'opencode',
+ cli_present: true,
+ mode: 'hub',
+ menu_kind: 'open',
+ sources: {
+ order: sourceIds,
+ eligibility: sourceIds.map((sourceId) => ({ source_id: sourceId, eligible: true })),
+ },
+ menu: { view: 'featured', checked: [] },
+ routes: {},
+ standard_vendors: ['openai'],
+});
+
+describe('readOpenCodeMenuBaseline', () => {
+ it('regroups once when concurrent reads expose a source-membership hole', async () => {
+ const getAgentSources = vi.fn()
+ .mockResolvedValueOnce(agent(['src_a', 'src_new']))
+ .mockResolvedValueOnce(agent(['src_a', 'src_new']));
+ const readValue = vi.fn()
+ .mockResolvedValueOnce([source('src_a')])
+ .mockResolvedValueOnce([source('src_a'), source('src_new')]);
+
+ const baseline = await readOpenCodeMenuBaseline({ getAgentSources }, { readValue });
+
+ expect(baseline.sources.map(({ id }) => id)).toEqual(['src_a', 'src_new']);
+ expect(getAgentSources).toHaveBeenCalledTimes(2);
+ expect(readValue).toHaveBeenCalledTimes(2);
+ });
+
+ it('rejects a pair that still has a composition hole after regrouping', async () => {
+ const getAgentSources = vi.fn().mockResolvedValue(agent(['src_a', 'src_new']));
+ const readValue = vi.fn().mockResolvedValue([source('src_a')]);
+
+ await expect(readOpenCodeMenuBaseline({ getAgentSources }, { readValue })).rejects.toThrow(
+ 'did not converge',
+ );
+ });
+});
+
+describe('OpenCode menu intent', () => {
+ it('preserves unrelated current selections and ignores additions no longer selectable', () => {
+ const intent = openCodeMenuIntent(
+ ['openai/kept', 'openai/removed'],
+ ['openai/kept', 'openai/added', 'openai/gone'],
+ );
+
+ expect(applyOpenCodeMenuIntent(
+ ['openai/concurrent', 'openai/kept', 'openai/removed'],
+ intent,
+ new Set(['openai/added']),
+ )).toEqual(['openai/concurrent', 'openai/kept', 'openai/added']);
+ });
+
+ it('compares the server menu as an ordered total value', () => {
+ const expected = { view: 'featured' as const, checked: ['openai/a', 'openai/b'] };
+ expect(sameOpenCodeMenu(expected, expected)).toBe(true);
+ expect(sameOpenCodeMenu({ ...expected, checked: ['openai/b', 'openai/a'] }, expected)).toBe(false);
+ expect(sameOpenCodeMenu(null, expected)).toBe(false);
+ });
+});
diff --git a/ui/src/components/settings/models/menuBaseline.ts b/ui/src/components/settings/models/menuBaseline.ts
index 9dd8cba81..92bfd9082 100644
--- a/ui/src/components/settings/models/menuBaseline.ts
+++ b/ui/src/components/settings/models/menuBaseline.ts
@@ -1,8 +1,76 @@
-import type { RegionRead } from './regionRead';
-import type { AgentSupply, Source } from './types';
-
-/** A whole-menu write is safe only when both server-owned halves of its baseline are current. */
-export const openCodeMenuBaselineReady = (
- supply: RegionRead<AgentSupply[]>,
- sources: RegionRead<Source[]>,
-): boolean => supply.kind === 'ready' && sources.kind === 'ready';
+import type { CollectionReadAuthority } from './collectionReadAuthority';
+import type { ModelsApi } from './modelsApi';
+import { combineSourceOrderReads } from './sourceOrderComposition';
+import type { AgentMenu, AgentSupply, Source } from './types';
+
+export type OpenCodeMenuBaseline = {
+ agent: AgentSupply;
+ sources: Source[];
+};
+
+export type OpenCodeMenuIntent = {
+ added: string[];
+ removed: Set<string>;
+};
+
+const readPair = async (
+ api: Pick<ModelsApi, 'getAgentSources'>,
+ sourceReads: Pick<CollectionReadAuthority<Source[]>, 'readValue'>,
+): Promise<OpenCodeMenuBaseline> => {
+ const [agent, sources] = await Promise.all([
+ api.getAgentSources('opencode'),
+ sourceReads.readValue(),
+ ]);
+ if (agent.backend !== 'opencode' || agent.mode !== 'hub' || agent.menu_kind !== 'open') {
+ throw new Error('OpenCode Model Hub menu is unavailable');
+ }
+ return { agent, sources };
+};
+
+/** A total menu write owns a dedicated pair, never the page's independently settled reads. */
+export const readOpenCodeMenuBaseline = async (
+ api: Pick<ModelsApi, 'getAgentSources'>,
+ sourceReads: Pick<CollectionReadAuthority<Source[]>, 'readValue'>,
+): Promise<OpenCodeMenuBaseline> => {
+ const first = await readPair(api, sourceReads);
+ if (!combineSourceOrderReads(first.agent, first.sources).hasHole) return first;
+
+ const regrouped = await readPair(api, sourceReads);
+ if (combineSourceOrderReads(regrouped.agent, regrouped.sources).hasHole) {
+ throw new Error('OpenCode Model Hub menu reads did not converge');
+ }
+ return regrouped;
+};
+
+export const openCodeMenuIntent = (
+ baseline: readonly string[],
+ draft: readonly string[],
+): OpenCodeMenuIntent => {
+ const baselineSet = new Set(baseline);
+ const draftSet = new Set(draft);
+ return {
+ added: draft.filter((id) => !baselineSet.has(id)),
+ removed: new Set(baseline.filter((id) => !draftSet.has(id))),
+ };
+};
+
+/** Rebase only explicit user edits; unrelated changes in a newer menu survive. */
+export const applyOpenCodeMenuIntent = (
+ current: readonly string[],
+ intent: OpenCodeMenuIntent,
+ selectableIds: ReadonlySet<string>,
+): string[] => {
+ const rebased = current.filter((id) => !intent.removed.has(id));
+ const present = new Set(rebased);
+ for (const id of intent.added) {
+ if (!selectableIds.has(id) || present.has(id)) continue;
+ rebased.push(id);
+ present.add(id);
+ }
+ return rebased;
+};
+
+export const sameOpenCodeMenu = (left: AgentMenu | null | undefined, right: AgentMenu): boolean => {
+ if (!left || left.view !== right.view || left.checked.length !== right.checked.length) return false;
+ return left.checked.every((id, index) => id === right.checked[index]);
+};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 7edb653d3..1b5f6c101 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -946,6 +946,7 @@
"search": "Search models or sources",
"selected": "{{selected}} of {{total}} selected",
"empty": "No eligible source models are available",
+ "configured": "Existing configured model",
"baselineUnavailable": "Model menu data is not current. Wait for refresh, or retry the failed section before editing.",
"noMatch": "No models match this search",
"save": "Save selection",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 091239620..b0144392b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -946,6 +946,7 @@
"search": "搜索模型或供应商",
"selected": "已选 {{selected}} / {{total}}",
"empty": "没有可供 OpenCode 选择的模型",
+ "configured": "已有配置模型",
"baselineUnavailable": "模型菜单数据暂未更新,请等待刷新完成,或重试读取失败的区域后再编辑。",
"noMatch": "没有匹配的模型",
"save": "保存选择",