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
refactor(model-hub): remove unused mock client (#1487)
Call Whitec42b2bfb3cfb
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex c69be9553..08388c578 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -2237,10 +2237,7 @@ def test_models_live_api_calls_only_registered_server_routes():source = Path("ui/src/components/settings/models/modelsApi.ts").read_text(encoding="utf-8")- live_api = source.split("const liveApi: ModelsApi = {", 1)[1].split(- "// ── Mock client",- 1,- )[0]+ live_api = source.split("export const modelsApi: ModelsApi = {", 1)[1]path_pattern = re.compile(r"'(?P<single>/api/models/[^']*)'|`(?P<template>/api/models/[^`]*)`")diff --git a/ui/src/components/settings/models/featureFlags.ts b/ui/src/components/settings/models/featureFlags.tsindex 057839cdd..0d2896ab3 100644--- a/ui/src/components/settings/models/featureFlags.ts+++ b/ui/src/components/settings/models/featureFlags.ts@@ -12,11 +12,3 @@ export const modelHubEnabledFromConfig = (config: unknown): boolean => {(modelHub as { enabled?: unknown }).enabled === true,);};--/**- * 'mock' serves typed fixtures from `mockData.ts`; 'live' calls the real- * `/api/models/*` endpoints (L2). Now 'live': all backend lanes are merged, so- * shipping the nav must serve real data — never fabricated mock sources. (Flip- * to 'mock' only for hermetic pixel/screenshot runs with no backend.)- */-export const MODELS_API_MODE: 'mock' | 'live' = 'live';diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.tsindex d68ca1cd0..3ad73dbd8 100644--- a/ui/src/components/settings/models/mockData.ts+++ b/ui/src/components/settings/models/mockData.ts@@ -1,22 +1,5 @@-// Typed fixtures for hermetic Model Hub visual tests.-// Mirrors the frozen-// v3 contract example payloads. Timestamps are computed relative to "now" at-// fetch time so the 最近切换 list always renders 今天 / 昨天 correctly.-//-// The two exported predicates at the bottom (`mockEligibility`,-// `mockRecommendedOrder`) implement spec §4.4 and §4.2. They belong to the FAKE-// SERVER, not to the UI: production reads `AgentSources.eligibility` /-// `.order` off the wire and never re-derives either. They live here so the-// fixture and the MockStore share one implementation.-import type {- AgentBackend,- AgentSupply,- MigrationScan,- ResolutionEvent,- RuntimeDependency,- Source,- SourceEligibility,-} from './types';+// Typed source fixtures retained only for the source schema contract test.+import type { Source } from './types';const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString();const MIN = 60_000;@@ -138,341 +121,3 @@ export function buildMockSources(): Source[] {},];}--// The V6 01 story: Claude Code and Codex are on the hub (「2 个 Agent 已接入中枢」),-// OpenCode still runs its native config (直连). Claude Code owns a 自定义 subset-// that leaves 智谱 out — which is what makes the drawer's 未启用 section non-empty-// in frame V6 02; Codex 跟随推荐, so its order IS §4.2's output.-export function buildMockAgents(sources: Source[] = buildMockSources()): AgentSupply[] {- const claudeOrder = ['src_claudepro1', 'src_anthkey01', 'src_relay9c1x'];- return [- {- backend: 'claude',- cli_present: true,- mode: 'hub',- menu_kind: 'fixed',- selected_by_agent: null,- selected_model_id: 'claude-opus-4-6',- // A stored request stands behind the id, which is what the server reports- // as explicit — the resolver-picked case only exists on the open menu.- selected_model_explicit: true,- sources: {- order: claudeOrder,- eligibility: mockEligibility(sources, 'claude'),- },- // Serving from the head of the chain for the CURRENT selection, and no- // member of that chain is blocked — relay.example is cooling, but it does- // not supply Opus at all, so it is not a member and cannot degrade it.- supply_status: 'ok',- // claude-haiku-4-5 is mapped onto glm-5.2, which only 智谱 supplies — and- // 智谱 is 未启用 here. Depth 0 is the honest answer, and AC-9's Case A: a- // menu-model gap that must NOT render any Agent as interrupted.- model_supply: [- { model_id: 'claude-opus-4-6', chain_length: 2, has_runnable_hop: true },- { model_id: 'claude-sonnet-4-6', chain_length: 2, has_runnable_hop: true },- { model_id: 'claude-haiku-4-5', chain_length: 0, has_runnable_hop: false },- ],- named_agents: [- { name: 'claude', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' },- { name: 'pm', effective_model_id: 'claude-opus-4-6', supply_status: 'ok' },- ],- routes: {- 'claude-opus-4-6': { hops: [{ source_id: 'src_claudepro1', model_id: 'claude-opus-4-6' }, { source_id: 'src_anthkey01', model_id: 'claude-opus-4-6' }] },- 'claude-sonnet-4-6': { hops: [{ source_id: 'src_claudepro1', model_id: 'claude-sonnet-4-6' }, { source_id: 'src_anthkey01', model_id: 'claude-sonnet-4-6' }] },- 'claude-haiku-4-5': { hops: [] },- },- menu: null,- // Fixed-menu backends carry the server-populated built-in catalog- // The server projects these ids; the route editor never hardcodes them.- builtin_models: ['claude-opus-4-6', 'claude-sonnet-4-6', 'claude-haiku-4-5'],- standard_vendors: null,- },- {- backend: 'codex',- cli_present: true,- mode: 'hub',- menu_kind: 'fixed',- selected_by_agent: 'codex',- selected_model_id: 'gpt-5.6',- selected_model_explicit: true,- sources: {- order: mockRecommendedOrder(sources, 'codex'),- eligibility: mockEligibility(sources, 'codex'),- },- supply_status: 'ok',- model_supply: [- { model_id: 'gpt-5.6', chain_length: 1, has_runnable_hop: true },- { model_id: 'gpt-5.6-mini', chain_length: 1, has_runnable_hop: true },- ],- named_agents: [{ name: 'codex', effective_model_id: 'gpt-5.6', supply_status: 'ok' }],- routes: {- 'gpt-5.6': { hops: [{ source_id: 'src_chatgptplus', model_id: 'gpt-5.6' }] },- 'gpt-5.6-mini': { hops: [{ source_id: 'src_chatgptplus', model_id: 'gpt-5.6-mini' }] },- },- menu: null,- builtin_models: ['gpt-5.6', 'gpt-5.6-mini'],- standard_vendors: null,- },- {- // 直连: the CLI runs its own native config. Every hub-side projection is- // null by contract — no order, no chain, no probe (AC-7's gate).- backend: 'opencode',- cli_present: true,- mode: 'direct',- menu_kind: 'open',- selected_by_agent: null,- selected_model_id: null,- selected_model_explicit: false,- sources: null,- supply_status: null,- model_supply: null,- named_agents: [{ name: 'opencode', effective_model_id: null, supply_status: null }],- // Prefixed identifiers (opencode-overlay.md): provider = the SOURCE's- // vendor (custom fallback). Retained across the mode switch — it is stored- // config, not live state, and applies again the moment OpenCode rejoins.- menu: {- view: 'featured',- checked: [- 'anthropic/claude-opus-4-6',- 'anthropic/claude-sonnet-4-6',- 'zhipuai/glm-5.2',- 'zhipuai/glm-5.2-air',- 'zhipuai/glm-5-flash',- ],- },- builtin_models: null,- // Server mirror of STANDARD_OPENCODE_VENDOR_IDS (agent-supply v1.2), so the- // menu / custom-model identifiers byte-match the backend's opencode_model_id.- standard_vendors: [- 'anthropic', 'deepseek', 'github-copilot', 'google', 'groq', 'kimi',- 'minimax', 'mistral', 'moonshot', 'openai', 'openrouter', 'together',- 'xai', 'zhipuai',- ],- },- ];-}--export function buildMockEvents(): ResolutionEvent[] {- // Stored in display order (adapter-owned feed order); the UI renders as-is.- return [- {- id: 'evt_a',- ts: iso(-2 * HOUR - 11 * MIN),- agent: 'claude',- kind: 'switch',- model_id: 'claude-opus-4-6',- from_source: 'src_claudepro1',- to_source: 'src_anthkey01',- reason: 'quota_exhausted',- billing_note: 'entered_metered',- severity: 'info',- human_zh: 'Claude Code:Claude Pro 本周期额度用完 → 已切到 Anthropic API Key(按量)',- human_en: 'Claude Code: Claude Pro cycle quota exhausted → switched to Anthropic API Key (metered)',- },- {- id: 'evt_b',- ts: iso(-38 * MIN),- agent: 'claude',- kind: 'recover',- model_id: 'claude-opus-4-6',- from_source: 'src_anthkey01',- to_source: 'src_claudepro1',- reason: 'recovery',- billing_note: 'left_metered',- severity: 'info',- human_zh: 'Claude Code:Claude Pro 额度恢复 → 已切回订阅',- human_en: 'Claude Code: Claude Pro quota recovered → switched back to the subscription',- },- {- id: 'evt_c',- ts: iso(-1 * DAY - 30 * MIN),- agent: 'system',- kind: 'cooldown',- model_id: 'glm-5.2-air',- from_source: 'src_relay9c1x',- to_source: null,- reason: 'network',- billing_note: null,- severity: 'info',- human_zh: 'relay.example 连续超时 → 暂停使用 1 小时,期间自动跳过',- human_en: 'relay.example timed out repeatedly → paused for 1 hour, skipped automatically',- },- // AC-18's render-time 「已删除」 case: a retained event whose endpoint no- // longer resolves. The recorded sentence still names the source, because it- // was composed when the source existed — that string IS the snapshot.- {- id: 'evt_d',- ts: iso(-2 * DAY - 4 * HOUR),- agent: 'codex',- kind: 'needs_action',- model_id: 'gpt-5.6',- from_source: 'src_oldkey0099',- to_source: null,- reason: 'credential_revoked',- billing_note: null,- severity: 'action_required',- human_zh: 'Codex:旧 OpenAI API Key 凭证已失效 → 已跳过,需要重新授权',- human_en: 'Codex: the old OpenAI API Key credential was revoked → skipped, re-authorization needed',- },- // A history tail, so 「查看全部」 crosses a page boundary in the mock. With- // four rows the cursor path was unreachable in dev — the very case the feed's- // pagination exists for could only be seen against a real server.- // Deep enough that the feed needs THREE pages at the page size 最近切换 asks- // for (20): expanding 查看全部 pulls the second page on its own, so anything- // shallower exhausts the cursor before 查看更多 is ever clickable — which is- // how the button shipped unexercised in the first place.- ...olderHistory(45),- ];-}--/** Filler older events, oldest last, ids stable so `before` cursors are stable. */-function olderHistory(count: number): ResolutionEvent[] {- return Array.from({ length: count }, (_, i) => {- const n = i + 1;- const cooling = n % 3 === 0;- return {- id: `evt_h${String(n).padStart(2, '0')}`,- ts: iso(-3 * DAY - i * (5 * HOUR + 20 * MIN)),- agent: 'claude',- kind: cooling ? 'cooldown' : 'switch',- model_id: 'claude-opus-4-6',- from_source: cooling ? 'src_relay9c1x' : 'src_claudepro1',- to_source: cooling ? null : 'src_anthkey01',- reason: cooling ? 'rate_limited' : 'quota_exhausted',- billing_note: cooling ? null : 'entered_metered',- severity: 'info',- human_zh: cooling- ? 'relay.example 触发限流 → 暂停使用 10 分钟,期间自动跳过'- : 'Claude Code:Claude Pro 本周期额度用完 → 已切到 Anthropic API Key(按量)',- human_en: cooling- ? 'relay.example hit a rate limit → paused for 10 minutes, skipped automatically'- : 'Claude Code: Claude Pro cycle quota exhausted → switched to Anthropic API Key (metered)',- } satisfies ResolutionEvent;- });-}--export function buildMockRuntime(): RuntimeDependency {- return {- contract_version: 5,- manifest: {- name: 'cliproxyapi',- resolution: 'resolved',- version: 'v7.2.95',- source_sha: 'f71ec0eb6776854457892452cf28c47f0d658251',- assets: [],- },- status: {- installed_version: 'v7.2.95',- verified: true,- listening: { host: '127.0.0.1', port: 15220 },- health: 'ok',- last_check: iso(-3 * MIN),- },- };-}--// Migration scan fixture (frame 03). Mirrors the frozen migration-scan schema-// example, adapted to the mock backends. Per spec v1.1 + the 2026-07-23 L6-// finding: API keys / base URLs → import; subscription OAuth (Claude account +-// Codex auth.json) → keep_native. controlled_import is reserved and not-// applicable in v3, so this fixture emits only import / keep_native.-export function buildMockMigration(): MigrationScan {- const oauthNote = 'settings.models.migration.notes.keepNativeSanctioned';- return {- items: [- {- id: 'mig_claude_key',- backend: 'claude',- kind: 'api_key',- masked_detail: 'Anthropic API Key · sk-…dd3c',- proposed_action: 'import',- selected: true,- notes_key: 'settings.models.migration.notes.customBaseUrl',- },- {- id: 'mig_claude_oauth',- backend: 'claude',- kind: 'oauth_native',- masked_detail: 'Claude 账号登录(OAuth)',- proposed_action: 'keep_native',- selected: false,- notes_key: oauthNote,- },- {- id: 'mig_codex_auth',- backend: 'codex',- kind: 'oauth_native',- masked_detail: 'ChatGPT 登录 · auth.json',- proposed_action: 'keep_native',- selected: false,- notes_key: oauthNote,- },- {- id: 'mig_opencode_zhipu',- backend: 'opencode',- kind: 'opencode_provider',- masked_detail: '智谱 API Key · glm-…c31b',- proposed_action: 'import',- selected: true,- notes_key: 'settings.models.migration.notes.fromOpencode',- },- ],- };-}--// Model count a vendor's key "discovers" in the test-and-add flow (frame 06r).-export function mockDiscoveredCount(vendor: string): number {- const table: Record<string, number> = { anthropic: 8, openai: 31, zhipuai: 12, kimi: 6, xai: 4, custom: 23 };- return table[vendor] ?? 23;-}--// ── Fake-server predicates (spec §4.4 + §4.2) ───────────────────────────-// The vendor→client binding an eligible subscription must satisfy. OpenCode has-// no subscription channel at all, so it has no own vendor.-const OWN_VENDOR: Record<AgentBackend, string | null> = {- claude: 'anthropic',- codex: 'openai',- opencode: null,-};--/** §4.4 — server-authoritative eligibility, one row per source. API-key Sources- * serve every backend; a native subscription is bound to its own client. */-export function mockEligibility(sources: Source[], backend: AgentBackend): SourceEligibility[] {- return sources.map((s): SourceEligibility => {- if (s.kind === 'api_key') return { source_id: s.id, eligible: true, reason_key: null };- if (s.vendor !== OWN_VENDOR[backend]) {- return { source_id: s.id, eligible: false, reason_key: 'models.eligibility.subscription_wrong_client' };- }- return { source_id: s.id, eligible: true, reason_key: null };- });-}--// An absent created_at sorts before every present one (types.ts: the stamp may-// be null on rows persisted before the field existed).-const createdKey = (s: Source) => s.created_at ?? '';--/** §4.2 — the deterministic recommendation, exhaustive over eligible sources:- * (1) the backend's own-vendor subscription, native_cli before a hub-held one;- * (2) every eligible api_key by created_at ascending; (3) id ascending as the- * tie-break anywhere. No health, latency, cost or usage input. */-export function mockRecommendedOrder(sources: Source[], backend: AgentBackend): string[] {- const eligible = new Set(- mockEligibility(sources, backend).filter((e) => e.eligible).map((e) => e.source_id),- );- const pool = sources.filter((s) => eligible.has(s.id));- const byId = (a: Source, b: Source) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);- const subs = pool- .filter((s) => s.kind === 'subscription')- .sort((a, b) => {- const rank = (s: Source) => (s.supply_channel === 'native_cli' ? 0 : 1);- return rank(a) - rank(b) || byId(a, b);- });- const keys = pool- .filter((s) => s.kind === 'api_key')- .sort((a, b) => {- const ca = createdKey(a);- const cb = createdKey(b);- return (ca < cb ? -1 : ca > cb ? 1 : 0) || byId(a, b);- });- return [...subs, ...keys].map((s) => s.id);-}diff --git a/ui/src/components/settings/models/mockDataImportBoundary.test.ts b/ui/src/components/settings/models/mockDataImportBoundary.test.tsnew file mode 100644index 000000000..dcd52e7cd--- /dev/null+++ b/ui/src/components/settings/models/mockDataImportBoundary.test.ts@@ -0,0 +1,31 @@+import { readdirSync, readFileSync } from 'node:fs';+import { join, relative } from 'node:path';++import { describe, expect, it } from 'vitest';++const SOURCE_ROOT = join(process.cwd(), 'src');+const SOURCE_MODULE = /\.[cm]?[jt]sx?$/;+const TEST_MODULE = /\.(?:test|spec)\.[cm]?[jt]sx?$/;+const MODULE_SPECIFIER = /(?:\bfrom\s*|\b(?:import|require)\s*\(\s*|\bimport\s*)['"]([^'"]+)['"]/g;++const sourceModules = (directory: string): string[] =>+ readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const path = join(directory, entry.name);+ if (entry.isDirectory()) return sourceModules(path);+ return SOURCE_MODULE.test(entry.name) ? [path] : [];+ });++const importsMockData = (path: string): boolean =>+ [...readFileSync(path, 'utf8').matchAll(MODULE_SPECIFIER)]+ .some((match) => /(?:^|\/)mockData(?:\.[^/]*)?$/.test(match[1]));++describe('Model Hub fixture import boundary', () => {+ it('keeps fabricated source fixtures out of product modules', () => {+ const productImporters = sourceModules(SOURCE_ROOT)+ .filter(importsMockData)+ .filter((path) => !TEST_MODULE.test(path))+ .map((path) => relative(SOURCE_ROOT, path));++ expect(productImporters).toEqual([]);+ });+});diff --git a/ui/src/components/settings/models/modelsApi.mock.test.ts b/ui/src/components/settings/models/modelsApi.mock.test.tsdeleted file mode 100644index e13b92450..000000000--- a/ui/src/components/settings/models/modelsApi.mock.test.ts+++ /dev/null@@ -1,133 +0,0 @@-import { describe, expect, it } from 'vitest';--import { ApiCallError, MockStore } from './modelsApi';-import type { RouteHopRef } from './types';--const referencesTo = (store: MockStore, sourceId: string): RouteHopRef[] =>- store.agents.flatMap((agent) =>- Object.entries(agent.routes ?? {}).flatMap(([menuModel, route]) =>- route.hops.flatMap((hop, index) => hop.source_id === sourceId- ? [{- backend: agent.backend,- menu_model: menuModel,- source_id: hop.source_id,- model_id: hop.model_id,- position: index + 1,- }]- : [])));--describe('Model Hub mock deletion contract', () => {- it('reports and removes every seeded route reference to a deleted source', async () => {- const seeded = new MockStore();- const routedSourceIds = new Set(- seeded.agents.flatMap((agent) =>- Object.values(agent.routes ?? {}).flatMap((route) =>- route.hops.map((hop) => hop.source_id))),- );- expect(routedSourceIds.size).toBeGreaterThan(0);-- for (const sourceId of routedSourceIds) {- const store = new MockStore();- const expected = referencesTo(store, sourceId);- let refusal: ApiCallError | null = null;- try {- store.deleteSource(sourceId);- } catch (error) {- if (error instanceof ApiCallError) refusal = error;- else throw error;- }-- expect(refusal, sourceId).not.toBeNull();- expect(refusal?.code, sourceId).toBe('source_in_route_chain');- expect(refusal?.wouldRemoveHops, sourceId).toEqual(expected);- const answer = await store.deleteSource(sourceId, {- force: true,- would_remove_hops: refusal?.wouldRemoveHops ?? [],- would_interrupt: refusal?.wouldInterrupt ?? [],- });-- expect(answer.removed_hops, sourceId).toEqual(expected);- expect(referencesTo(store, sourceId), sourceId).toEqual([]);- for (const agent of store.agents) {- expect(agent.sources?.order ?? [], `${sourceId}:${agent.backend}`).not.toContain(sourceId);- }- }- });-});--describe('Model Hub mock endpoint-edit contract', () => {- it('reports and removes every invalidated route reference for every seeded routed Hub key', async () => {- const seeded = new MockStore();- const routedSourceIds = new Set(- seeded.agents.flatMap((agent) =>- Object.values(agent.routes ?? {}).flatMap((route) =>- route.hops.map((hop) => hop.source_id))),- );- const editableRoutedSourceIds = seeded.sources- .filter((source) => routedSourceIds.has(source.id)- && source.kind === 'api_key'- && source.supply_channel === 'hub'- && source.credential_ref)- .map((source) => source.id);- expect(editableRoutedSourceIds.length).toBeGreaterThan(0);-- for (const sourceId of editableRoutedSourceIds) {- const store = new MockStore();- const beforeReferences = referencesTo(store, sourceId);- const beforeRoutes = new Map(store.agents.flatMap((agent) =>- Object.entries(agent.routes ?? {}).map(([menuModel, route]) => [- `${agent.backend}\u0000${menuModel}`,- route.hops.map((hop) => ({ ...hop })),- ])));- const beforeOrders = new Map(store.agents.map((agent) => [- agent.backend,- [...(agent.sources?.order ?? [])],- ]));- const base_url = `https://retarget-${sourceId}.example/v1`;- let refusal: ApiCallError | null = null;- let answer;- try {- answer = await store.patchSource(sourceId, { base_url });- } catch (error) {- if (error instanceof ApiCallError) refusal = error;- else throw error;- }- if (refusal) {- expect(refusal.code, sourceId).toBe(refusal.wouldRemoveHops.length > 0- ? 'source_model_in_route_chain'- : 'source_last_supplier');- answer = await store.patchSource(sourceId, {- base_url,- force: true,- would_remove_hops: refusal.wouldRemoveHops,- would_interrupt: refusal.wouldInterrupt,- });- }- expect(answer, sourceId).toBeDefined();- const result = answer!;- const candidateModelIds = new Set(result.source.models- .filter((model) => model.retired !== true)- .map((model) => model.id));- const expectedRemoved = beforeReferences.filter((hop) => !candidateModelIds.has(hop.model_id));- expect(result.removed_hops, sourceId).toEqual(expectedRemoved);- expect(refusal?.wouldRemoveHops ?? [], sourceId).toEqual(expectedRemoved);-- const removed = new Set(expectedRemoved.map((hop) =>- `${hop.backend}\u0000${hop.menu_model}\u0000${hop.source_id}\u0000${hop.model_id}`));- for (const agent of store.agents) {- expect(agent.sources?.order ?? [], `${sourceId}:${agent.backend}:order`)- .toEqual(beforeOrders.get(agent.backend));- for (const [menuModel, route] of Object.entries(agent.routes ?? {})) {- const before = beforeRoutes.get(`${agent.backend}\u0000${menuModel}`) ?? [];- expect(route.hops, `${sourceId}:${agent.backend}:${menuModel}:route`).toEqual(- before.filter((hop) =>- !removed.has(`${agent.backend}\u0000${menuModel}\u0000${hop.source_id}\u0000${hop.model_id}`)),- );- for (const hop of route.hops.filter((hop) => hop.source_id === sourceId)) {- expect(candidateModelIds.has(hop.model_id), `${sourceId}:${agent.backend}:${menuModel}:${hop.model_id}`).toBe(true);- }- }- }- }- });-});diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 6caea51b8..92e7b591b 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -1,32 +1,15 @@-// Model Hub API client. Presents ONE typed surface to the UI; internally it-// either serves in-memory fixtures for hermetic visual tests or calls the frozen-// `/api/models/*` REST endpoints (live mode). Components never-// branch on the mode — flip `MODELS_API_MODE` in featureFlags.ts to switch.+// Model Hub API client. Presents one typed surface over the frozen+// `/api/models/*` REST endpoints.//// Methods unwrap the frozen envelope ({ok:true, …} | {ok:false, error}) and// throw an Error carrying the machine code on failure, so callers work with// plain domain objects.import { apiFetch, isApiFetchDeadlineAbort, withApiDeadline } from '@/lib/apiFetch';-import { MODELS_API_MODE } from './featureFlags';-import {- buildMockAgents,- buildMockEvents,- buildMockMigration,- buildMockRuntime,- buildMockSources,- mockDiscoveredCount,- mockEligibility,- mockRecommendedOrder,-} from './mockData';-import { canReauth, canReplaceKey, wasBlocked } from './repair';-import { validateRouteDraft } from './routeChainDraft';-import { isUnhealthy } from './supply';import type {AdoptedBy,AddedTo,AgentBackend,AgentChain,- AgentChainLink,AgentChainMutation,AgentChainPut,AgentMenu,@@ -51,8 +34,6 @@ import type {SupplyChannel,SupplyGap,} from './types';-import { equalHopIdentity } from './hopIdentity';-import { AGENT_CHAIN_CONTRACT_VERSION, CONTRACT_VERSION, PROBE_RESULT_CONTRACT_VERSION } from './types';/** Add-time Route placement returned by both source-creation paths. */export type Adoption = { added_to: AddedTo[]; adopted_by: AdoptedBy[] };@@ -156,9 +137,6 @@ export type ModelsApi = {cancelOAuth(flowId: string): Promise<void>;};-const isLive = () => MODELS_API_MODE === 'live';--// ── Live client ─────────────────────────────────────────────────────────export class ApiCallError extends Error {code: string;detail?: string;@@ -196,9 +174,8 @@ export class ApiCallError extends Error {* entirely consistent with. Anything downstream that skips a corrective re-read* because 「the route said so」 has to ask this rather than 「is it one of ours?」.*- * `true` by default because every other throw in this module IS an outcome: the- * local mock raises the same codes the routes do. Only `call` invents any, and- * it says so at both sites.+ * `true` by default because a named route error IS an outcome. `call` marks+ * each client-invented transport summary as false at its construction site.*/serverNamed: boolean;/** HTTP status observed by this client. Absent when no response arrived. */@@ -432,7 +409,8 @@ export const oauthResult = (r: OAuthResultResponse): OAuthResult => {};};-const liveApi: ModelsApi = {+/** The single client instance. Stable across renders (safe in effect deps). */+export const modelsApi: ModelsApi = {listSources: () => call<{ sources: Source[] }>('/api/models/sources').then((r) => r.sources),observeApiKeySource: (draft, signal) =>call<{ observation: SourceObservation }>('/api/models/sources/observe', {@@ -491,1057 +469,3 @@ const liveApi: ModelsApi = {submitOAuth: (flowId, value) => call<OAuthResultResponse>('/api/models/oauth/submit', jsonInit('POST', { flow_id: flowId, value })).then(oauthResult),cancelOAuth: (flowId) => call('/api/models/oauth/cancel', jsonInit('POST', { flow_id: flowId })).then(() => undefined),};--// ── Mock client ─────────────────────────────────────────────────────────-// A single mutable store so reorder / add / mode-switch stick across calls-// within a session, giving a realistic demo without a backend.-/** `recovered` is captured when a reauth flow STARTS, like the server's own- * `recovered = source.state.status in {needs_action, error}` — read before the- * native irreversible step rewrites that very status. */-type MockFlow = {- flow: OAuthFlow;- polls: number;- submitted: boolean;- recovered?: boolean;- placement?: Adoption;-};--const rid = (prefix: string) => `${prefix}_${Math.random().toString(36).slice(2, 10)}`;-const delay = <T>(value: T, ms = 260, signal?: AbortSignal): Promise<T> =>- new Promise((resolve, reject) => {- const timer = globalThis.setTimeout(() => resolve(value), ms);- signal?.addEventListener('abort', () => {- globalThis.clearTimeout(timer);- reject(new DOMException('The operation was aborted.', 'AbortError'));- }, { once: true });- });-const listedModelIdsForPlacement = (agent: AgentSupply): string[] => {- const values = [- ...(agent.builtin_models ?? []),- ...(agent.menu?.checked ?? []),- ...Object.keys(agent.routes ?? {}),- ];- return [...new Set(values)];-};--/** Exported so tests can assert mock/live contract parity over the seeded store. */-export class MockStore {- sources = buildMockSources();- agents = buildMockAgents(this.sources);- events = buildMockEvents();- runtime = buildMockRuntime();- flows = new Map<string, MockFlow>();-- // ── Fake server-side recomputation ───────────────────────────────────- // Reads refresh server-authoritative eligibility while preserving the stored- // order. Matching and Route construction happen only at add time.- private syncAgents() {- for (const a of this.agents) {- if (a.mode === 'direct') {- a.sources = null;- } else {- const eligibility = mockEligibility(this.sources, a.backend);- const eligible = new Set(eligibility.filter((e) => e.eligible).map((e) => e.source_id));- const order = (a.sources?.order ?? []).filter((id) => eligible.has(id));- a.sources = { order, eligibility };- }- this.deriveSupply(a);- }- }-- /** §4.3 + §4.5 in miniature: capability (supplies the configured id) split from- * runnability (not blocked), then the rollup over the resulting chain. */- private deriveSupply(a: AgentSupply) {- if (a.mode === 'direct') {- a.selected_model_id = null;- a.selected_model_explicit = false;- a.selected_by_agent = null;- a.supply_status = null;- a.model_supply = null;- a.named_agents = (a.named_agents ?? []).map((n) => ({ ...n, effective_model_id: null, supply_status: null }));- return;- }- const routeFor = (model: string) => a.routes?.[model]?.hops ?? [];- const chainFor = (model: string) => this.chainFor(a, model).chain;- if (a.builtin_models) {- a.model_supply = a.builtin_models.map((m) => ({- model_id: m,- chain_length: routeFor(m).length,- has_runnable_hop: chainFor(m).some((link) => link.runnable),- }));- }- const selected = a.selected_model_id ?? null;- if (!selected) {- a.supply_status = null;- } else {- const chain = chainFor(selected);- const head = chain.find((link) => link.runnable) ?? null;- const blocked = chain.filter((link) => !link.runnable);- if (!head) {- a.supply_status =- chain.length > 0 && blocked.every((link) => link.health === 'cooldown' && link.reason === null) ? 'waiting' : 'interrupted';- } else {- a.supply_status = head === chain[0] && blocked.length === 0 ? 'ok' : 'degraded';- }- }- const rollup = a.supply_status ?? null;- a.named_agents = (a.named_agents ?? []).map((n) =>- n.effective_model_id ? { ...n, supply_status: rollup } : n,- );- }-- listSources() {- // api.md: the inventory is explicitly UNORDERED — order is per-backend.- return delay(structuredClone(this.sources));- }-- /** Materialize placement once, in the same transaction that creates a Source. */- private placeNewSource(source: Source): Adoption {- const added_to: AddedTo[] = [];- const adopted_by: AdoptedBy[] = [];- for (const agent of this.agents) {- if (agent.mode !== 'hub') continue;- const eligible = mockEligibility(this.sources, agent.backend).some(- (entry) => entry.source_id === source.id && entry.eligible,- );- if (!eligible) continue;- const order = agent.sources?.order ?? [];- if (!order.includes(source.id)) order.push(source.id);- agent.sources = { order, eligibility: agent.sources?.eligibility ?? null };- for (const menuModel of listedModelIdsForPlacement(agent)) {- const supplied = source.models.find((model) => model.id === menuModel);- if (!supplied) continue;- const hops = agent.routes?.[menuModel]?.hops ?? [];- if (hops.some((hop) => hop.source_id === source.id)) continue;- const next = [...hops, { source_id: source.id, model_id: supplied.id }];- agent.routes = { ...(agent.routes ?? {}), [menuModel]: { hops: next } };- added_to.push({- backend: agent.backend,- menu_model: menuModel,- source_id: source.id,- model_id: supplied.id,- position: next.length,- });- adopted_by.push({ backend: agent.backend, menu_model: menuModel });- }- }- this.syncAgents();- return { added_to, adopted_by };- }-- createApiKeySource(draft: ApiKeySourceCreate) {- const existing = draft.client_nonce- ? this.sources.find((source) => source.client_nonce === draft.client_nonce)- : undefined;- if (existing) {- return delay({- source: structuredClone(existing),- added_to: [],- adopted_by: structuredClone(existing.adopted_by ?? []),- });- }- const count = mockDiscoveredCount(draft.vendor);- const source: Source = {- id: rid('src'),- client_nonce: draft.client_nonce ?? null,- created_at: new Date().toISOString(),- last_discovered_at: new Date().toISOString(),- kind: 'api_key',- vendor: draft.vendor,- display_name: draft.display_name || (draft.vendor === 'custom' ? hostLabel(draft.base_url) : vendorLabel(draft.vendor)),- protocol: draft.protocol_order?.[0] ?? (draft.vendor === 'anthropic' ? 'anthropic' : 'openai_chat'),- base_url: draft.base_url ?? null,- supply_channel: 'hub',- billing: 'metered',- state: { status: 'standby', retry_at: null, detail_key: null },- usage: { cycle_used_pct: null, month_spend_cents: 0, currency: 'USD' },- account_label: null,- // Simulates L2 computing the display mask once at provisioning.- masked_credential: maskKey(draft.key),- models: Array.from({ length: count }, (_, i) => ({- id: `${draft.vendor}-model-${i + 1}`,- display_name: null,- origin: 'discovered' as const,- reasoning_efforts: [],- discovered_at: new Date().toISOString(),- })),- credential_ref: rid('cred'),- };- this.sources.push(source);- const placement = this.placeNewSource(source);- source.adopted_by = placement.adopted_by;- // simulate probe latency- return delay({ source: structuredClone(source), ...placement }, 900);- }-- observeApiKeySource(draft: ApiKeySourceObservation, signal?: AbortSignal) {- const marker = `${draft.base_url ?? ''} ${draft.key}`.toLowerCase();- const base = {- contract_version: CONTRACT_VERSION,- models: [] as string[],- };- let observation: SourceObservation;- if (marker.includes('timeout')) {- observation = { ...base, outcome: 'timeout', reachable: null, authenticated: 'unknown', protocol: null, discovery: 'not_attempted' };- } else if (marker.includes('auth')) {- observation = { ...base, outcome: 'authentication_failed', reachable: true, authenticated: 'rejected', protocol: null, discovery: 'not_attempted' };- } else if (marker.includes('ambiguous')) {- observation = { ...base, outcome: 'ambiguous', reachable: true, authenticated: 'authenticated', protocol: null, discovery: 'not_attempted' };- } else if (marker.includes('inventory')) {- observation = { ...base, outcome: 'observed', reachable: true, authenticated: 'authenticated', protocol: draft.protocol_order?.[0] ?? 'openai_chat', discovery: 'failed' };- } else if (marker.includes('adapter')) {- observation = { ...base, outcome: 'adapter_error', reachable: null, authenticated: 'unknown', protocol: null, discovery: 'not_attempted' };- } else if (marker.includes('unreachable')) {- observation = { ...base, outcome: 'unreachable', reachable: false, authenticated: 'unknown', protocol: null, discovery: 'not_attempted' };- } else {- observation = {- ...base,- outcome: 'observed',- reachable: true,- authenticated: 'authenticated',- protocol: draft.protocol_order?.[0] ?? 'openai_chat',- discovery: 'succeeded',- models: ['model-1', 'model-2', 'model-3'],- };- }- return delay(observation, 900, signal);- }-- /**- * The supply guard, evaluated the way the server evaluates it: against the- * CANDIDATE config the write would produce, not against a live binding.- *- * The old version asked 「is this source some agent's `current`?」, which is a- * different and weaker question: deleting the second source of a two-source- * chain strands nothing (the head still serves), while deleting the only- * supplier of a *cooling* head strands a model that has no `current` at all.- * Reporting per (backend, model) with the Agents that run it is also what makes- * the confirm copy nameable — 「删除后 pm 将没有可用来源」.- */- private wouldInterrupt(candidate: Source[], removedHops: RouteHopRef[] = []): SupplyGap[] {- const byId = new Map(candidate.map((s) => [s.id, s]));- const removed = new Set(removedHops.map((hop) =>- `${hop.backend}\u0000${hop.menu_model}\u0000${hop.source_id}\u0000${hop.model_id}`));- const gaps: SupplyGap[] = [];- for (const a of this.agents) {- if (a.mode !== 'hub') continue;- const model = a.selected_model_id;- if (!model) continue;- const hops = a.routes?.[model]?.hops ?? [];- const survives = hops.some((hop) => {- if (removed.has(`${a.backend}\u0000${model}\u0000${hop.source_id}\u0000${hop.model_id}`)) return false;- const source = byId.get(hop.source_id);- return source !== undefined- && source.models.some((entry) => entry.id === hop.model_id && entry.retired !== true)- && isRunnable(source);- });- if (survives) continue;- gaps.push({- backend: a.backend,- model_id: model,- agents: (a.named_agents ?? []).filter((n) => n.effective_model_id === model).map((n) => n.name),- });- }- return gaps;- }-- deleteSource(id: string, confirmation?: GuardConfirmation) {- this.syncAgents();- const removedHops: RouteHopRef[] = this.agents.flatMap((agent) =>- Object.entries(agent.routes ?? {}).flatMap(([menuModel, route]) =>- route.hops.flatMap((hop, index) => hop.source_id === id- ? [{- backend: agent.backend,- menu_model: menuModel,- source_id: hop.source_id,- model_id: hop.model_id,- position: index + 1,- }]- : [])));- const remaining = this.sources.filter((s) => s.id !== id);- const gaps = this.wouldInterrupt(remaining);- const confirmed = confirmation !== undefined- && JSON.stringify(confirmation.would_remove_hops) === JSON.stringify(removedHops)- && JSON.stringify(confirmation.would_interrupt) === JSON.stringify(gaps);- if ((removedHops.length > 0 || gaps.length > 0) && !confirmed) {- // Routed deletion wins over last-supplier: this mirrors delete_source's- // `_require_guard_plan(error=...)` choice, not the mode-switch route.- throw new ApiCallError(- removedHops.length > 0 ? 'source_in_route_chain' : 'source_last_supplier',- undefined,- true,- gaps,- [],- removedHops,- );- }- this.sources = remaining;- for (const agent of this.agents) {- if (agent.sources) {- agent.sources = {- ...agent.sources,- order: agent.sources.order.filter((sourceId) => sourceId !== id),- };- }- if (agent.routes) {- agent.routes = Object.fromEntries(- Object.entries(agent.routes).map(([menuModel, route]) => [- menuModel,- { hops: route.hops.filter((hop) => hop.source_id !== id) },- ]),- );- }- }- this.syncAgents();- return delay({ removed_hops: removedHops, interrupted: gaps });- }-- replaceCredential(id: string, body: CredentialReplace) {- this.syncAgents();- const source = this.sources.find((s) => s.id === id);- if (!source) throw new ApiCallError('source_not_found');- // The server's preconditions, restated rather than assumed: the menu offers- // this only where they hold, but a mock that failed open would hide a wiring- // mistake until it reached a real backend.- if (!canReplaceKey(source) || !body.key.trim()) throw new ApiCallError('discovery_failed');- const recovered = wasBlocked(source.state);- const previousMask = source.masked_credential;- const previousState = { ...source.state };- // Atomic commit, standby-clearing semantics shared with refreshSource: a- // replacement re-discovers and lands on standby, never straight to active.- source.masked_credential = maskKey(body.key);- source.credential_ref = rid('cred');- source.state = { status: 'standby', retry_at: null, detail_key: null };- const interrupted = this.wouldInterrupt(this.sources);- // A RECOVERING write is exempt from the guard and merely reports what is- // still stranded; only an elective one can be refused.- if (interrupted.length > 0 && !recovered && !body.force) {- source.masked_credential = previousMask;- source.state = previousState;- throw new ApiCallError('source_last_supplier', undefined, true, interrupted);- }- this.syncAgents();- return delay({ source: structuredClone(source), removed_hops: [], interrupted }, 700);- }-- reauthSource(id: string) {- const source = this.sources.find((s) => s.id === id);- if (!source) throw new ApiCallError('source_not_found');- if (!canReauth(source)) throw new ApiCallError('discovery_failed');- // Read BEFORE the irreversible step below, which sets needs_action itself and- // would otherwise make every native re-auth report a recovery.- const recovered = wasBlocked(source.state);- // Native re-auth is irreversible from the first step: the server clears the- // discovered models and drops the account label BEFORE any login happens, so- // the row goes to 需处理 even if the user abandons the browser tab. Mirrored- // here, because a mock that kept the old models would make the confirm dialog- // look like a formality.- if (source.supply_channel === 'native_cli') {- source.models = [];- source.account_label = null;- source.state = { status: 'needs_action', retry_at: null, detail_key: 'models.source.needs_action.oauth_expired' };- }- const isDevice = source.vendor === 'openai';- const flow: OAuthFlow = {- flow_id: rid('oaf'),- intent: 'reauth',- // A reauth flow binds to the EXISTING source, which is what makes its- // terminal response a repair rather than a creation.- source_id: source.id,- vendor: source.vendor,- channel: source.supply_channel,- state: 'awaiting_action',- presentation: isDevice- ? { auth_url: 'https://chatgpt.com/device', device_code: 'RFTQ-MPZK', expects: 'none', instructions_key: 'settings.models.oauth.deviceCode.hint' }- : { auth_url: 'https://claude.ai/oauth/authorize?code=true&client_id=avibe&scope=org%3Acreate_api_key', device_code: null, expects: 'paste_code', instructions_key: 'settings.models.oauth.pasteCode.hint' },- error_key: null,- expires_at: new Date(Date.now() + 15 * 60_000).toISOString(),- };- this.flows.set(flow.flow_id, { flow, polls: 0, submitted: false, recovered });- this.syncAgents();- return delay(structuredClone(flow), 400);- }-- listAgents() {- this.syncAgents();- return delay(structuredClone(this.agents));- }-- private agentOr404(backend: AgentBackend): AgentSupply {- const agent = this.agents.find((a) => a.backend === backend);- if (!agent) throw new ApiCallError('source_not_found');- return agent;- }-- getAgentSources(backend: AgentBackend) {- this.syncAgents();- return delay(structuredClone(this.agentOr404(backend)));- }-- putAgentSources(backend: AgentBackend, body: AgentSourcesPut) {- const agent = this.agentOr404(backend);- if (agent.mode === 'direct') throw new ApiCallError('direct_mode');- const eligible = new Set(- mockEligibility(this.sources, backend).filter((e) => e.eligible).map((e) => e.source_id),- );- const seen = new Set<string>();- for (const id of body.order) {- if (!eligible.has(id) || seen.has(id)) throw new ApiCallError('invalid_source_order', id);- seen.add(id);- }- agent.sources = { order: [...body.order], eligibility: null };- this.syncAgents();- return delay(structuredClone(agent), 380);- }-- /**- * The chain both hub-only routes answer from, shared the way the server shares- * it: `probe_agent` calls `_agent_chain` and takes its first runnable member.- * Deriving the head a second time is how the mock's probe and chain would- * disagree about the same supply — and `supply_state` is a rollup the v4 schema- * now pins to this very array, so it cannot be restated per route either.- */- private chainFor(agent: AgentSupply, model: string) {- const byId = new Map(this.sources.map((s) => [s.id, s]));- const hops = agent.routes?.[model]?.hops ?? [];- const chain: AgentChainLink[] = hops- .map((hop) => ({ hop, source: byId.get(hop.source_id) }))- .map(({ hop, source }) => {- const modelEntry = source?.models.find((entry) => entry.id === hop.model_id);- const callable = modelEntry !== undefined && modelEntry.retired !== true;- const reason = !source- ? 'source_missing' as const- : callable ? null : 'model_unsupported' as const;- return {- source_id: hop.source_id,- model_id: hop.model_id,- channel: source?.supply_channel ?? 'hub',- health: source && callable ? chainHealth(source) : 'error',- runnable: source !== undefined && callable && isRunnable(source),- // v4: process availability is a fact about the serving process — which- // native CLI it can launch under its own login — and a browser mock has- // no way to observe it. So it stands in for a runtime where every- // configured CLI is launchable, rather than inventing an outage. The- // unavailable branch is asserted in the unit tests, which can state the- // fact instead of guessing it.- reason,- retry_at: source && callable && source.state.status === 'cooldown' ? source.state.retry_at ?? null : null,- };- });- const supply_state: AgentChain['supply_state'] = chain.some((l) => l.runnable)- ? 'ok'- : chain.length > 0 && chain.every((l) => l.health === 'cooldown' && l.reason === null)- ? 'waiting'- : 'interrupted';- const current = chain.find((link) => link.runnable);- return { chain, current: current ? { source_id: current.source_id, model_id: current.model_id } : null, supply_state };- }-- getAgentChain(backend: AgentBackend, model: string) {- this.syncAgents();- const agent = this.agentOr404(backend);- // AC-7: direct mode has no src_* identity to report, so the route refuses- // rather than answering with an empty (falsely alarming) chain.- if (agent.mode === 'direct') throw new ApiCallError('direct_mode');- const { chain, current, supply_state } = this.chainFor(agent, model);- return delay({- contract_version: AGENT_CHAIN_CONTRACT_VERSION,- backend,- model_id: model,- current,- chain,- supply_state,- });- }-- putAgentChain(backend: AgentBackend, model: string, body: AgentChainPut) {- const agent = this.agentOr404(backend);- if (agent.mode === 'direct') throw new ApiCallError('direct_mode');- const byId = new Map(this.sources.map((source) => [source.id, source]));- const previous = agent.routes?.[model]?.hops ?? [];- if (!validateRouteDraft(agent, this.sources, previous, body.hops).valid) {- throw new ApiCallError('model_unsupported');- }- const removed_hops: RouteHopRef[] = previous.flatMap((hop, index) => body.hops.some((next) => equalHopIdentity(next, hop))- ? []- : [{ backend, menu_model: model, ...hop, position: index + 1 }]);- const impactedAgents = (agent.named_agents ?? [])- .filter((entry) => entry.effective_model_id === model)- .map((entry) => entry.name);- const hasRunnableHop = body.hops.some((hop) => {- const source = byId.get(hop.source_id);- return source?.models.some((entry) => entry.id === hop.model_id && entry.retired !== true) === true- && isRunnable(source);- });- const gaps: SupplyGap[] = impactedAgents.length > 0 && !hasRunnableHop- ? [{ backend, model_id: model, agents: impactedAgents }]- : [];- const confirmed = body.force === true- && JSON.stringify(body.would_interrupt ?? []) === JSON.stringify(gaps)- && JSON.stringify(body.would_remove_hops ?? []) === JSON.stringify(removed_hops);- if (gaps.length > 0 && !confirmed) throw new ApiCallError('source_last_supplier', undefined, true, gaps, [], removed_hops);- agent.routes = { ...(agent.routes ?? {}), [model]: { hops: body.hops.map((hop) => ({ ...hop })) } };- this.syncAgents();- const settled = this.chainFor(agent, model);- return delay({- chain: {- contract_version: AGENT_CHAIN_CONTRACT_VERSION,- backend,- model_id: model,- current: settled.current,- chain: settled.chain,- supply_state: settled.supply_state,- },- removed_hops,- interrupted: gaps,- });- }-- probeAgent(backend: AgentBackend, model?: string) {- this.syncAgents();- const agent = this.agentOr404(backend);- if (agent.mode === 'direct') throw new ApiCallError('direct_mode');- const modelId = model ?? agent.selected_model_id;- if (!modelId) throw new ApiCallError('model_unsupported');- const { chain, supply_state } = this.chainFor(agent, modelId);- const head = chain.find((l) => l.runnable);- // `probe_no_candidate` is the contract's code for this; `no_runnable_source`- // was invented here and is in no error vocabulary, so the L5 dry-run button- // would have been written against a code the server never sends. The server- // also names WHICH blocked family it is in the 409's detail, and the drawer- // renders that key — a detail-less throw would leave it unreachable here.- // `ok` cannot occur on this branch: it is the rollup's word for "some member- // is runnable", which is exactly what failing to find a head rules out.- if (!head) throw new ApiCallError('probe_no_candidate', `models.probe.no_candidate.${supply_state}`);- // The native_cli half is a readiness answer, not a request: nothing upstream- // is attempted, so there is no latency to report and a measured local number- // would impersonate completion evidence. Readiness itself follows `reason`- // above — every configured CLI is launchable in the mock.- const native = head.channel === 'native_cli';- const probe: ProbeResult = {- contract_version: PROBE_RESULT_CONTRACT_VERSION,- backend,- channel: head.channel,- reachable: true,- source_id: head.source_id,- model_id: head.model_id,- latency_ms: native ? null : 180 + Math.floor(Math.random() * 420),- error: null,- };- // A real upstream request takes a real moment; a local readiness check does not.- return delay(probe, native ? 400 : 1200);- }-- setAgentMode(backend: AgentBackend, mode: AgentMode) {- const agent = this.agentOr404(backend);- agent.mode = mode;- if (mode === 'hub') {- // Rejoining the gateway materializes one exact Route per matching menu model.- const order = mockRecommendedOrder(this.sources, backend);- agent.sources = { order, eligibility: null };- agent.routes = Object.fromEntries(- (agent.builtin_models ?? []).map((modelId) => [modelId, { hops: order- .map((sourceId) => this.sources.find((source) => source.id === sourceId))- .filter((source): source is Source => Boolean(source && source.models.some((model) => model.id === modelId)))- .map((source) => ({ source_id: source.id, model_id: modelId })) }]),- );- agent.selected_model_id = agent.builtin_models?.[0] ?? this.sources[0]?.models[0]?.id ?? null;- // The server's default comes from the STORED per-backend request, so a- // non-null id here is explicit; nothing selected is the false case.- agent.selected_model_explicit = agent.selected_model_id !== null;- agent.named_agents = (agent.named_agents ?? []).map((n) => ({- ...n,- effective_model_id: agent.selected_model_id ?? null,- }));- }- this.syncAgents();- return delay(structuredClone(agent));- }-- putMenu(menu: AgentMenu) {- const agent = this.agents.find((a) => a.backend === 'opencode');- if (!agent) throw new ApiCallError('source_not_found');- agent.menu = menu;- this.syncAgents();- return delay(structuredClone(agent));- }-- addCustomModel(sourceId: string, draft: CustomModelCreate) {- const source = this.sources.find((s) => s.id === sourceId);- if (!source) throw new ApiCallError('source_not_found');- const existing = source.models.find((m) => m.id === draft.model_id);- if (existing) {- existing.display_name = draft.display_name ?? existing.display_name;- existing.origin = 'manual';- existing.reasoning_efforts = [...draft.reasoning_efforts];- } else {- source.models.push({- id: draft.model_id,- display_name: draft.display_name ?? null,- origin: 'manual',- reasoning_efforts: [...draft.reasoning_efforts],- discovered_at: null,- });- }- return delay(structuredClone(source), 400);- }-- updateModelReasoningEfforts(sourceId: string, modelId: string, reasoningEfforts: string[]) {- const source = this.sources.find((s) => s.id === sourceId);- if (!source) throw new ApiCallError('source_not_found');- const model = source.models.find((item) => item.id === modelId);- if (!model) throw new ApiCallError('source_not_found');- model.reasoning_efforts = [...reasoningEfforts];- return delay(structuredClone(source));- }-- deleteCustomModel(sourceId: string, modelId: string, confirmation?: GuardConfirmation) {- const source = this.sources.find((s) => s.id === sourceId);- if (!source) throw new ApiCallError('source_not_found');- const references: RouteHopRef[] = [];- for (const agent of this.agents) {- for (const [menuModel, route] of Object.entries(agent.routes ?? {})) {- for (const [index, hop] of route.hops.entries()) {- if (equalHopIdentity(hop, { source_id: sourceId, model_id: modelId })) {- references.push({ backend: agent.backend, menu_model: menuModel, ...hop, position: index + 1 });- }- }- }- }- const confirmed = confirmation !== undefined- && JSON.stringify(confirmation.would_remove_hops) === JSON.stringify(references)- && JSON.stringify(confirmation.would_interrupt) === JSON.stringify([]);- if (references.length > 0 && !confirmed) {- throw new ApiCallError('source_model_in_route_chain', undefined, true, [], [], references);- }- source.models = source.models.filter((m) => !(m.id === modelId && m.origin === 'manual'));- if (confirmation) {- for (const agent of this.agents) {- agent.routes = Object.fromEntries(- Object.entries(agent.routes ?? {}).map(([menuModel, route]) => [- menuModel,- { hops: route.hops.filter((hop) => !equalHopIdentity(hop, { source_id: sourceId, model_id: modelId })) },- ]),- );- }- }- this.syncAgents();- return delay(structuredClone(source));- }-- scanMigration() {- // Read-only: recompute the fixture each call so re-scans stay idempotent.- return delay(buildMockMigration(), 500);- }-- applyMigration(itemIds: string[]) {- const scan = buildMockMigration();- // reauth needs the interactive OAuth flow, so it is never bulk-applied here.- const chosen = scan.items.filter((i) => itemIds.includes(i.id) && i.proposed_action !== 'reauth');- // Copy-only: each selected native config materializes a new source; the- // (simulated) originals are never touched. import lands on the hub channel;- // keep_native registers a sanctioned native_cli source. (controlled_import- // is deferred per the 2026-07-23 L6 finding, so it's never emitted here.)- for (const item of chosen) {- const isKey = item.kind === 'api_key' || item.kind === 'opencode_provider';- const channel: SupplyChannel = item.proposed_action === 'keep_native' ? 'native_cli' : 'hub';- this.sources.push({- id: rid('src'),- created_at: new Date().toISOString(),- last_discovered_at: new Date().toISOString(),- kind: isKey ? 'api_key' : 'subscription',- vendor: item.backend === 'opencode' ? 'zhipuai' : item.backend === 'codex' ? 'openai' : 'anthropic',- display_name: item.masked_detail.split(' · ')[0] || 'Imported',- protocol: item.backend === 'codex' ? 'openai_responses' : 'anthropic',- base_url: null,- supply_channel: channel,- billing: isKey ? 'metered' : 'monthly',- state: { status: 'standby', retry_at: null, detail_key: null },- usage: isKey ? { cycle_used_pct: null, month_spend_cents: 0, currency: 'USD' } : { cycle_used_pct: 0, month_spend_cents: null, currency: null },- account_label: channel === 'native_cli' ? '[email protected]' : null,- masked_credential: isKey ? 'sk-…dd3c' : null,- models: [{ id: item.backend === 'opencode' ? 'glm-5.2' : item.backend === 'codex' ? 'gpt-5.6' : 'claude-opus-4-6', display_name: null, origin: 'discovered', reasoning_efforts: [], discovered_at: new Date().toISOString() }],- credential_ref: channel === 'hub' ? rid('cred') : null,- });- }- // Enable hub on the backends that received a hub-channel import.- for (const backend of new Set(chosen.filter((i) => i.proposed_action !== 'keep_native').map((i) => i.backend))) {- const agent = this.agents.find((a) => a.backend === backend);- if (agent) agent.mode = 'hub';- }- this.syncAgents();- return delay({ applied: chosen.length, sources: structuredClone(this.sources) }, 700);- }-- listEvents(limit = 20, before?: string) {- const start = before ? this.events.findIndex((e) => e.id === before) + 1 : 0;- return delay(structuredClone(this.events.slice(start, start + limit)));- }-- getRuntimeStatus() {- return delay(structuredClone(this.runtime));- }-- installRuntime() {- this.runtime.status.health = 'installing';- this.runtime.status.error_key = null;- setTimeout(() => {- this.runtime.status.installed_version = this.runtime.manifest.resolution === 'unresolved'- ? null- : this.runtime.manifest.version;- this.runtime.status.verified = true;- this.runtime.status.health = 'not_started';- }, 1200);- return delay(structuredClone(this.runtime));- }-- startRuntime() {- this.runtime.status.health = 'ok';- this.runtime.status.listening = { host: '127.0.0.1', port: 15220 };- return delay(structuredClone(this.runtime));- }-- startOAuth(vendor: string, channel: SupplyChannel, clientNonce?: string) {- if (clientNonce) {- const existing = [...this.flows.values()].find((entry) =>- entry.flow.client_nonce === clientNonce- && entry.flow.vendor === vendor- && entry.flow.channel === channel,- );- if (existing) return delay(structuredClone(existing.flow), 500);- }- const isDevice = vendor === 'openai';- const flow: OAuthFlow = {- flow_id: rid('oaf'),- // Deterministic pending-source binding (schema: hub flows always set it),- // consumed when the flow completes — mirrors the server, where the- // materialized source takes source.id = flow.source_id.- source_id: rid('src'),- vendor,- channel,- client_nonce: clientNonce ?? null,- state: 'awaiting_action',- presentation: isDevice- ? {- auth_url: 'https://chatgpt.com/device',- device_code: 'KDWT-GBSF',- expects: 'none',- instructions_key: 'settings.models.oauth.deviceCode.hint',- }- : {- auth_url: 'https://claude.ai/oauth/authorize?code=true&client_id=avibe&scope=org%3Acreate_api_key',- device_code: null,- expects: 'paste_code',- instructions_key: 'settings.models.oauth.pasteCode.hint',- },- error_key: null,- expires_at: new Date(Date.now() + 15 * 60_000).toISOString(),- };- this.flows.set(flow.flow_id, { flow, polls: 0, submitted: false });- return delay(structuredClone(flow), 500);- }-- getOAuthStatus(flowId: string) {- const entry = this.flows.get(flowId);- if (!entry) throw new ApiCallError('flow_not_found');- entry.polls += 1;- const { flow } = entry;- if (flow.state === 'success' || flow.state === 'failed' || flow.state === 'cancelled') {- return delay(this.oauthResult(entry));- }- if (flow.presentation.expects === 'none') {- // Device flow self-completes after a few polls.- if (entry.polls >= 3) this.completeFlow(entry);- } else if (entry.submitted) {- // Paste flows: verifying → success on the next poll.- this.completeFlow(entry);- }- return delay(this.oauthResult(entry));- }-- submitOAuth(flowId: string, _value: string) {- const entry = this.flows.get(flowId);- if (!entry) throw new ApiCallError('flow_not_found');- entry.submitted = true;- entry.flow.state = 'verifying';- return delay(this.oauthResult(entry));- }-- cancelOAuth(flowId: string) {- const entry = this.flows.get(flowId);- if (entry) entry.flow.state = 'cancelled';- return delay(undefined);- }-- // Reaching `success` IS the creation, as on the server: status/submit- // materialize the Source inside the same call that first reports success, and- // consume the flow binding doing it. Splitting the two here is what let a- // client that finalized with a second POST look correct against the mock while- // failing `flow_not_found` against the real server.- private completeFlow(entry: MockFlow) {- entry.flow.state = 'success';- const flow = entry.flow;- const id = flow.source_id ?? rid('src');- flow.source_id = id;- const isOpenai = flow.vendor === 'openai';- if (flow.intent === 'reauth') {- // A reauth flow REPAIRS the source it bound to; it creates nothing. The- // login is what puts the credential back, so the blocker clears and the- // supply a native start had wiped comes back with it.- const source = this.sources.find((s) => s.id === id);- if (!source) return;- source.account_label = '[email protected]';- source.state = { status: 'standby', retry_at: null, detail_key: null };- source.last_discovered_at = new Date().toISOString();- if (source.models.length === 0) {- source.models = [- {- id: isOpenai ? 'gpt-5.6' : 'claude-opus-4-6',- display_name: isOpenai ? 'GPT-5.6' : 'Opus 4.6',- origin: 'discovered',- reasoning_efforts: [],- discovered_at: new Date().toISOString(),- },- ];- }- return;- }- // Idempotent, like `_create_oauth_source(idempotent=True)`: re-polling a- // completed flow re-echoes the same source instead of creating a second one.- if (this.sources.some((s) => s.id === id)) return;- const source: Source = {- id,- created_at: new Date().toISOString(),- last_discovered_at: new Date().toISOString(),- kind: 'subscription',- vendor: flow.vendor,- display_name: isOpenai ? 'ChatGPT 订阅' : 'Claude 订阅',- protocol: isOpenai ? 'openai_responses' : 'anthropic',- base_url: null,- supply_channel: flow.channel,- billing: 'monthly',- state: { status: 'standby', retry_at: null, detail_key: null },- usage: { cycle_used_pct: 0, month_spend_cents: null, currency: null },- // native_cli subscriptions surface the CLI account; gateway-held sources- // may stay null until a later adapter revision publishes an account label.- account_label: flow.channel === 'native_cli' ? '[email protected]' : null,- masked_credential: null,- models: isOpenai- ? [{ id: 'gpt-5.6', display_name: 'GPT-5.6', origin: 'discovered', reasoning_efforts: [], discovered_at: new Date().toISOString() }]- : [{ id: 'claude-opus-4-6', display_name: 'Opus 4.6', origin: 'discovered', reasoning_efforts: [], discovered_at: new Date().toISOString() }],- credential_ref: flow.channel === 'hub' ? rid('cred') : null,- };- this.sources.push(source);- entry.placement = this.placeNewSource(source);- }-- /**- * The terminal envelope every status/submit response carries (api.md, "OAuth- * completion"): the flow, plus the creation it performed once it succeeded.- * Looked up by `source_id` rather than remembered from the completing call, so- * a later poll on an already-finished flow answers the same thing the server's- * idempotent path does instead of pretending nothing was created.- */- private oauthResult(entry: MockFlow): OAuthResult {- const flow = structuredClone(entry.flow);- const source = flow.state === 'success' ? this.sources.find((s) => s.id === flow.source_id) : undefined;- if (!source) return { flow, created: null, repaired: null };- // One intent, one tail — the same discrimination the live unwrap makes, so a- // reauth never reports an adoption list and a create never reports recovery.- if (flow.intent === 'reauth') {- this.syncAgents();- return {- flow,- created: null,- repaired: {- source: structuredClone(source),- recovered: entry.recovered === true,- interrupted_pairs: this.wouldInterrupt(this.sources),- },- };- }- return {- flow,- created: {- source: structuredClone(source),- ...(entry.placement ?? { added_to: [], adopted_by: [] }),- },- repaired: null,- };- }-- patchSource(id: string, patch: SourcePatch) {- this.syncAgents();- const sourceIndex = this.sources.findIndex((s) => s.id === id);- const source = this.sources[sourceIndex];- if (!source) throw new ApiCallError('source_not_found');- const candidate = structuredClone(source);- if (typeof patch.display_name === 'string') candidate.display_name = patch.display_name;- const nextBaseUrl = patch.base_url ?? null;- const endpointChanged = 'base_url' in patch && (source.base_url ?? null) !== nextBaseUrl;- if (!endpointChanged) {- this.sources[sourceIndex] = candidate;- return delay({ source: structuredClone(candidate), removed_hops: [], interrupted: [] }, 300);- }- if (source.kind !== 'api_key' || source.supply_channel !== 'hub' || !source.credential_ref) {- throw new ApiCallError('discovery_failed');- }-- // A target from the visual fixture rediscovers that target's known inventory;- // any other endpoint gets the fake server's deterministic vendor inventory.- const seededInventory = buildMockSources().find((item) =>- item.kind === 'api_key'- && item.vendor === source.vendor- && item.protocol === source.protocol- && (item.base_url ?? null) === nextBaseUrl);- const discoveredIds = seededInventory- ? seededInventory.models.filter((model) => model.origin === 'discovered').map((model) => model.id)- : Array.from({ length: mockDiscoveredCount(source.vendor) }, (_, index) => `${source.vendor}-model-${index + 1}`);- const previousById = new Map(source.models.map((model) => [model.id, model]));- const manualModels = candidate.models.filter((model) => model.origin === 'manual');- const manualIds = new Set(manualModels.map((model) => model.id));- const discoveredAt = new Date().toISOString();- candidate.base_url = nextBaseUrl;- candidate.credential_ref = rid('cred');- candidate.models = [- ...discoveredIds.filter((modelId) => !manualIds.has(modelId)).map((modelId) => {- const previous = previousById.get(modelId);- return {- id: modelId,- display_name: previous?.display_name ?? null,- origin: 'discovered' as const,- reasoning_efforts: [...(previous?.reasoning_efforts ?? [])],- discovered_at: discoveredAt,- };- }),- ...manualModels,- ];- candidate.last_discovered_at = discoveredAt;- candidate.state = { status: 'standby', retry_at: null, detail_key: null };- const candidateModelIds = new Set(candidate.models.filter((model) => model.retired !== true).map((model) => model.id));- const removedHops: RouteHopRef[] = this.agents.flatMap((agent) =>- Object.entries(agent.routes ?? {}).flatMap(([menuModel, route]) =>- route.hops.flatMap((hop, index) => hop.source_id === id && !candidateModelIds.has(hop.model_id)- ? [{ backend: agent.backend, menu_model: menuModel, ...hop, position: index + 1 }]- : [])));- const candidateSources = this.sources.map((item, index) => index === sourceIndex ? candidate : item);- const gaps = this.wouldInterrupt(candidateSources, removedHops);- const confirmed = patch.force === true- && JSON.stringify(patch.would_remove_hops) === JSON.stringify(removedHops)- && JSON.stringify(patch.would_interrupt) === JSON.stringify(gaps);- if ((removedHops.length > 0 || gaps.length > 0) && !confirmed) {- throw new ApiCallError(- removedHops.length > 0 ? 'source_model_in_route_chain' : 'source_last_supplier',- undefined,- true,- gaps,- [],- removedHops,- );- }-- this.sources[sourceIndex] = candidate;- const removed = new Set(removedHops.map((hop) =>- `${hop.backend}\u0000${hop.menu_model}\u0000${hop.source_id}\u0000${hop.model_id}`));- for (const agent of this.agents) {- agent.routes = Object.fromEntries(- Object.entries(agent.routes ?? {}).map(([menuModel, route]) => [- menuModel,- {- hops: route.hops.filter((hop) =>- !removed.has(`${agent.backend}\u0000${menuModel}\u0000${hop.source_id}\u0000${hop.model_id}`)),- },- ]),- );- }- this.syncAgents();- return delay({ source: structuredClone(candidate), removed_hops: removedHops, interrupted: gaps }, 300);- }-- refreshSource(id: string, _confirmation?: GuardConfirmation) {- const source = this.sources.find((s) => s.id === id);- if (!source) throw new ApiCallError('source_not_found');- // Native-CLI subscriptions can't be re-discovered (server rejects them);- // the UI only offers this action for hub sources, but fail closed anyway.- if (source.supply_channel === 'native_cli') throw new ApiCallError('discovery_failed');- source.state = { status: 'standby', retry_at: null, detail_key: null };- source.last_discovered_at = new Date().toISOString();- return delay({ source: structuredClone(source), discovered: source.models.length }, 700);- }-}--// §4.3's runnability half: retry-ready, and never needs_action / error. A-// cooling source stays visible in the chain but is skipped by the turn. Derived-// from the page's own predicate rather than restated, so the fake server and the-// UI cannot drift into disagreeing about which statuses can serve a turn.-const isRunnable = (s: Source): boolean => !isUnhealthy(s.state);--// SourceStatus → the chain link's health vocabulary (the two healthy statuses-// collapse; the three blockers map one-to-one).-const chainHealth = (s: Source): AgentChainLink['health'] =>- s.state.status === 'cooldown' ? 'cooldown' : s.state.status === 'needs_action' ? 'needs_action' : s.state.status === 'error' ? 'error' : 'healthy';--function vendorLabel(vendor: string): string {- const table: Record<string, string> = {- anthropic: 'Anthropic API Key',- openai: 'OpenAI API Key',- zhipuai: '智谱 API Key',- kimi: 'Kimi API Key',- xai: 'xAI API Key',- };- return table[vendor] ?? `${vendor} API Key`;-}--// Non-reversible display mask (contract rule: ≤7-char prefix + "…" + last 4).-function maskKey(key: string): string {- const k = key.trim();- if (k.length <= 5) return `${k}…`;- const prefix = k.slice(0, Math.min(7, k.length - 4));- return `${prefix}…${k.slice(-4)}`;-}--function hostLabel(baseUrl: string | null | undefined): string {- if (!baseUrl) return 'API Key';- try {- return new URL(baseUrl).host;- } catch {- return 'API Key';- }-}--const mockStore = new MockStore();--const mockApi: ModelsApi = {- listSources: () => mockStore.listSources(),- observeApiKeySource: (draft, signal) => mockStore.observeApiKeySource(draft, signal),- createApiKeySource: (draft) => mockStore.createApiKeySource(draft),- patchSource: (id, patch) => mockStore.patchSource(id, patch),- refreshSource: (id, confirmation) => mockStore.refreshSource(id, confirmation),- deleteSource: (id, confirmation) => mockStore.deleteSource(id, confirmation),- replaceCredential: (id, body) => mockStore.replaceCredential(id, body),- reauthSource: (id) => mockStore.reauthSource(id),- listAgents: () => mockStore.listAgents(),- getAgentSources: (backend) => mockStore.getAgentSources(backend),- putAgentSources: (backend, body) => mockStore.putAgentSources(backend, body),- getAgentChain: (backend, model) => mockStore.getAgentChain(backend, model),- putAgentChain: (backend, model, body) => mockStore.putAgentChain(backend, model, body),- probeAgent: (backend, model) => mockStore.probeAgent(backend, model),- setAgentMode: (backend, mode) => mockStore.setAgentMode(backend, mode),- putMenu: (menu) => mockStore.putMenu(menu),- addCustomModel: (sourceId, draft) => mockStore.addCustomModel(sourceId, draft),- updateModelReasoningEfforts: (sourceId, modelId, reasoningEfforts) => mockStore.updateModelReasoningEfforts(sourceId, modelId, reasoningEfforts),- deleteCustomModel: (sourceId, modelId, confirmation) => mockStore.deleteCustomModel(sourceId, modelId, confirmation),- scanMigration: () => mockStore.scanMigration(),- applyMigration: (itemIds) => mockStore.applyMigration(itemIds),- listEvents: (limit, before) => mockStore.listEvents(limit, before),- getRuntimeStatus: () => mockStore.getRuntimeStatus(),- installRuntime: () => mockStore.installRuntime(),- startRuntime: () => mockStore.startRuntime(),- startOAuth: (vendor, channel, clientNonce) => mockStore.startOAuth(vendor, channel, clientNonce),- getOAuthStatus: (flowId) => mockStore.getOAuthStatus(flowId),- submitOAuth: (flowId, value) => mockStore.submitOAuth(flowId, value),- cancelOAuth: (flowId) => mockStore.cancelOAuth(flowId),-};--/** The single client instance. Stable across renders (safe in effect deps). */-export const modelsApi: ModelsApi = isLive() ? liveApi : mockApi;diff --git a/ui/src/components/settings/models/routeChainDraft.test.ts b/ui/src/components/settings/models/routeChainDraft.test.tsindex 38f987991..ebd4e2daa 100644--- a/ui/src/components/settings/models/routeChainDraft.test.ts+++ b/ui/src/components/settings/models/routeChainDraft.test.ts@@ -1,5 +1,3 @@-import { readFileSync } from "node:fs";-import { describe, expect, it } from "vitest";import {@@ -82,14 +80,6 @@ describe("routeChainDraft", () => {).toEqual({ invalidIndexes: [0, 1], valid: false });});- it("keeps the mock write path on the same persisted-pair validator", () => {- const api = readFileSync(new URL("./modelsApi.ts", import.meta.url), "utf8");-- expect(api).toMatch(- /validateRouteDraft\(agent, this\.sources, previous, body\.hops\)/,- );- });-it("sorts listed sources first and preserves stable order for ties", () => {const draft: RouteHop[] = [{ source_id: "missing", model_id: "stale-1" },