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
fix(model-hub): validate OpenCode menu snapshots
cyh345b31492fea
diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.pyindex 209ab285e..243c22b55 100644--- a/core/handlers/model_hub/resolver.py+++ b/core/handlers/model_hub/resolver.py@@ -100,6 +100,18 @@ def source_eligible_for_backend(source: ModelHubSourceConfig, backend: str) -> breturn ModelHubConfig.source_eligible_for_backend(source, backend)+def opencode_inventory_menu_ids(config: ModelHubConfig) -> frozenset[str]:+ """Return the OpenCode identities current eligible inventory can add."""++ return frozenset(+ opencode_model_id(source.vendor, model.id)+ for source in config.sources+ if source_eligible_for_backend(source, "opencode")+ for model in source.models+ if not model.retired+ )++def source_retry_ready(source: ModelHubSourceConfig, now: datetime | None) -> bool:if source.state.status != "cooldown" or now is None:return Falsediff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 086e9f494..91b564162 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -104,6 +104,7 @@ from .resolver import (allowed_origins,inspect_exact_hop,matching_v1_model_id as _matching_v1_model_id,+ opencode_inventory_menu_ids,resolve_model_hub_turn,source_after_cooldown_recovery,source_eligible_for_backend,@@ -3629,6 +3630,10 @@ class ModelHubService:)except (TypeError, ValueError) as exc:raise ModelHubError("mapping_target_unavailable") from exc+ existing_checked = set(agent.menu.checked if agent.menu else ())+ added = set(parsed_menu.checked) - existing_checked+ if not added.issubset(opencode_inventory_menu_ids(config)):+ raise ModelHubError("mapping_target_unavailable", status=409)agent.menu = parsed.menuagent.routes = parsed.routesawait self._commit_synced(previous, config)diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 93712ca51..81b83e689 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -40,7 +40,7 @@ compatibility path.| PUT `/api/models/agents/<backend>/sources` | `{order: string[]}` → `{agent: AgentSupply}` | Stores and re-echoes the complete canonical order; no policy state exists. This route never touches a Route chain and has no guarded `409` branch. || POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[]}` → `{agent: AgentSupply}` | With `order`, atomically stores the complete Source order and idempotently reorders every stored Route by it; with no body, applies the already stored order. In either form it adds, removes, remaps, matches, and guards nothing. The total order is defined below. || PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. A qualifying Direct → Gateway switch atomically adopts the recognized CLI login as the first native Source; other switches create nothing. |-| PUT `/api/models/agents/opencode/menu` | `{menu}` → `{agent: AgentSupply}` | Open-menu configuration. |+| PUT `/api/models/agents/opencode/menu` | `{menu}` → `{agent: AgentSupply}` | Open-menu configuration. A newly checked identifier must still be supplied by current OpenCode-eligible inventory at commit time; already checked route aliases may be preserved or removed without same-name inventory. || GET `/api/models/agents/<backend>/chains` | → `{chains: AgentChain[]}` | Hub only. Returns the complete Overview model set in menu order, followed by a selected model or configured Route not already present. All members share one config snapshot and observation time. Direct returns the documented `direct_mode` error. || GET `/api/models/agents/<backend>/chain?model=<id>` | → `{chain: AgentChain}` | Hub only. Direct returns the documented `direct_mode` error. || PUT `/api/models/agents/<backend>/chain?model=<id>` | `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | Replaces the exact Source/model pairs in submitted order after validating new or changed pairs; the handler never reads `sources.order`, and the submitted `hops` carry no Source-order semantics. It is the `mutation.route_replace` row of the authoritative mutation matrix. A visible noninterrupting hop removal is ordinary success; only a resulting protected-supply interruption enters the guard. |diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex d6b86c220..7ff0e61b5 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -1079,6 +1079,56 @@ def test_opencode_menu_validation_rejects_credential_material(tmp_path):assert store.load().agents["opencode"].menu.checked == []+def test_opencode_menu_rejects_a_new_model_absent_from_current_inventory(tmp_path):+ source = _source("src_opencode01", (), vendor="openai")+ service, store, _ = _service(tmp_path, _config([source]))++ with pytest.raises(ModelHubError) as exc:+ asyncio.run(+ service.set_opencode_menu(+ {"view": "featured", "checked": ["openai/removed-model"]}+ )+ )++ assert exc.value.code == "mapping_target_unavailable"+ assert exc.value.status == 409+ assert store.load().agents["opencode"].menu.checked == []+ assert "openai/removed-model" not in store.load().agents["opencode"].routes+++def test_opencode_menu_preserves_an_existing_route_alias_while_adding_inventory(tmp_path):+ source = _source(+ "src_opencode02",+ ("upstream-model", "new-model"),+ vendor="openai",+ )+ config = _config([source])+ opencode = config.agents["opencode"]+ opencode.menu = ModelHubMenuConfig(+ view="featured",+ checked=["openai/menu-model"],+ )+ opencode.routes["openai/menu-model"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),)+ )+ service, store, _ = _service(tmp_path, config)++ asyncio.run(+ service.set_opencode_menu(+ {+ "view": "featured",+ "checked": ["openai/menu-model", "openai/new-model"],+ }+ )+ )++ saved = store.load().agents["opencode"]+ assert saved.menu.checked == ["openai/menu-model", "openai/new-model"]+ assert saved.routes["openai/menu-model"].hops == (+ ModelHubRouteHopConfig(source.id, "upstream-model"),+ )++def test_explicit_opencode_selection_outside_menu_remains_visible(tmp_path):config = ModelHubConfig()config.agents["opencode"].mode = "hub"diff --git a/ui/src/components/settings/models/menuBaseline.test.ts b/ui/src/components/settings/models/menuBaseline.test.tsindex df293e321..070e1e104 100644--- a/ui/src/components/settings/models/menuBaseline.test.ts+++ b/ui/src/components/settings/models/menuBaseline.test.ts@@ -8,7 +8,7 @@ import {} from './menuBaseline';import type { AgentSupply, Source } from './types';-const source = (id: string): Source => ({+const source = (id: string, modelIds: string[] = []): Source => ({id,last_discovered_at: null,kind: 'api_key',@@ -18,7 +18,7 @@ const source = (id: string): Source => ({supply_channel: 'hub',billing: 'metered',state: { status: 'active', retry_at: null, detail_key: null },- models: [],+ models: modelIds.map((modelId) => ({ id: modelId, origin: 'manual', reasoning_efforts: [] })),});const agent = (sourceIds: string[]): AgentSupply => ({@@ -36,22 +36,30 @@ const agent = (sourceIds: string[]): AgentSupply => ({});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')]);+ it('accepts an Agent read bracketed by identical complete Source snapshots', async () => {+ const getAgentSources = vi.fn().mockResolvedValue(agent(['src_a']));+ const stable = [source('src_a', ['model-a'])];+ const readValue = vi.fn().mockResolvedValue(stable);const baseline = await readOpenCodeMenuBaseline({ getAgentSources }, { readValue });- expect(baseline.sources.map(({ id }) => id)).toEqual(['src_a', 'src_new']);- expect(getAgentSources).toHaveBeenCalledTimes(2);+ expect(baseline.sources).toEqual(stable);+ expect(getAgentSources).toHaveBeenCalledTimes(1);expect(readValue).toHaveBeenCalledTimes(2);});- it('rejects a pair that still has a composition hole after regrouping', async () => {+ it('rejects Source model content that changes across the Agent read', async () => {+ const getAgentSources = vi.fn().mockResolvedValue(agent(['src_a']));+ const readValue = vi.fn()+ .mockResolvedValueOnce([source('src_a', ['retired-model'])])+ .mockResolvedValueOnce([source('src_a')]);++ await expect(readOpenCodeMenuBaseline({ getAgentSources }, { readValue })).rejects.toThrow(+ 'did not converge',+ );+ });++ it('rejects stable Source snapshots with an Agent composition hole', async () => {const getAgentSources = vi.fn().mockResolvedValue(agent(['src_a', 'src_new']));const readValue = vi.fn().mockResolvedValue([source('src_a')]);diff --git a/ui/src/components/settings/models/menuBaseline.ts b/ui/src/components/settings/models/menuBaseline.tsindex 92bfd9082..f55b16439 100644--- a/ui/src/components/settings/models/menuBaseline.ts+++ b/ui/src/components/settings/models/menuBaseline.ts@@ -13,33 +13,25 @@ export type OpenCodeMenuIntent = {removed: Set<string>;};-const readPair = async (+const sameSourceSnapshot = (left: Source[], right: Source[]): boolean =>+ JSON.stringify(left) === JSON.stringify(right);++/** The Agent read is authoritative only when the complete Source projection is+ * unchanged on both sides of it. Source ids alone cannot detect model edits. */+export const readOpenCodeMenuBaseline = async (api: Pick<ModelsApi, 'getAgentSources'>,sourceReads: Pick<CollectionReadAuthority<Source[]>, 'readValue'>,): Promise<OpenCodeMenuBaseline> => {- const [agent, sources] = await Promise.all([- api.getAgentSources('opencode'),- sourceReads.readValue(),- ]);+ const before = await sourceReads.readValue();+ const agent = await api.getAgentSources('opencode');+ const after = await 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) {+ if (!sameSourceSnapshot(before, after) || combineSourceOrderReads(agent, after).hasHole) {throw new Error('OpenCode Model Hub menu reads did not converge');}- return regrouped;+ return { agent, sources: after };};export const openCodeMenuIntent = (