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): add source management actions (#1447)

Call White25bbe58d579c
diff --git a/tests/fixtures/model_hub_source_edit_validation.json b/tests/fixtures/model_hub_source_edit_validation.json
new file mode 100644
index 000000000..8f58b7616
--- /dev/null
+++ b/tests/fixtures/model_hub_source_edit_validation.json
@@ -0,0 +1,182 @@
+{
+ "display_names": [
+ {
+ "id": "ordinary",
+ "value": "Relay key",
+ "valid": true
+ },
+ {
+ "id": "empty",
+ "value": "",
+ "valid": false,
+ "reason": "displayNameRequired"
+ },
+ {
+ "id": "too_long",
+ "value": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "valid": false,
+ "reason": "displayNameTooLong"
+ },
+ {
+ "id": "credential_material",
+ "value": "sk-test-never-persist-this",
+ "valid": false,
+ "reason": "displayNameCredential"
+ }
+ ],
+ "base_urls": [
+ {
+ "id": "https_trailing_slash",
+ "value": "https://relay.example/v2/",
+ "valid": true,
+ "client_rejects": false,
+ "normalized": "https://relay.example/v2"
+ },
+ {
+ "id": "uppercase_scheme",
+ "value": "HTTPS://relay.example/v2/",
+ "valid": true,
+ "client_rejects": false,
+ "normalized": "https://relay.example/v2"
+ },
+ {
+ "id": "safe_query",
+ "value": "https://relay.example/v2?api-version=2026-08-15",
+ "valid": true,
+ "client_rejects": false,
+ "normalized": "https://relay.example/v2?api-version=2026-08-15"
+ },
+ {
+ "id": "explicit_default_port",
+ "value": "https://relay.example:443/v1",
+ "valid": true,
+ "client_rejects": false,
+ "normalized": "https://relay.example:443/v1"
+ },
+ {
+ "id": "uppercase_host",
+ "value": "https://Relay.Example/v1",
+ "valid": true,
+ "client_rejects": false,
+ "normalized": "https://Relay.Example/v1"
+ },
+ {
+ "id": "bad_scheme",
+ "value": "ftp://relay.example/v2",
+ "valid": false,
+ "client_rejects": false
+ },
+ {
+ "id": "userinfo",
+ "value": "https://user:[email protected]/v2",
+ "valid": false,
+ "client_rejects": false
+ },
+ {
+ "id": "fragment",
+ "value": "https://relay.example/v2#token",
+ "valid": false,
+ "client_rejects": false
+ },
+ {
+ "id": "missing_authority",
+ "value": "https:relay.example",
+ "valid": false,
+ "client_rejects": false
+ },
+ {
+ "id": "single_slash_authority",
+ "value": "https:/relay.example",
+ "valid": false,
+ "client_rejects": false
+ },
+ {
+ "id": "credential_query",
+ "value": "https://relay.example/v2?access_token=do-not-store",
+ "valid": false,
+ "client_rejects": true,
+ "reason": "baseUrlCredential"
+ },
+ {
+ "id": "credential_pattern",
+ "value": "https://relay.example/sk-test-never-persist-this",
+ "valid": false,
+ "client_rejects": true,
+ "reason": "baseUrlCredential"
+ }
+ ],
+ "empty_targets": [
+ {
+ "id": "anthropic_anthropic",
+ "vendor": "anthropic",
+ "protocol": "anthropic",
+ "server_valid": true
+ },
+ {
+ "id": "anthropic_openai_responses",
+ "vendor": "anthropic",
+ "protocol": "openai_responses",
+ "server_valid": false
+ },
+ {
+ "id": "anthropic_openai_chat",
+ "vendor": "anthropic",
+ "protocol": "openai_chat",
+ "server_valid": false
+ },
+ {
+ "id": "openai_anthropic",
+ "vendor": "openai",
+ "protocol": "anthropic",
+ "server_valid": false
+ },
+ {
+ "id": "openai_openai_responses",
+ "vendor": "openai",
+ "protocol": "openai_responses",
+ "server_valid": true
+ },
+ {
+ "id": "openai_openai_chat",
+ "vendor": "openai",
+ "protocol": "openai_chat",
+ "server_valid": true
+ },
+ {
+ "id": "codex_anthropic",
+ "vendor": "codex",
+ "protocol": "anthropic",
+ "server_valid": false
+ },
+ {
+ "id": "codex_openai_responses",
+ "vendor": "codex",
+ "protocol": "openai_responses",
+ "server_valid": true
+ },
+ {
+ "id": "codex_openai_chat",
+ "vendor": "codex",
+ "protocol": "openai_chat",
+ "server_valid": false
+ },
+ {
+ "id": "custom_anthropic",
+ "vendor": "custom",
+ "protocol": "anthropic",
+ "server_valid": false
+ },
+ {
+ "id": "custom_openai_responses",
+ "vendor": "custom",
+ "protocol": "openai_responses",
+ "server_valid": false
+ },
+ {
+ "id": "custom_openai_chat",
+ "vendor": "custom",
+ "protocol": "openai_chat",
+ "server_valid": false
+ }
+ ]
+}
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 7c36ff65b..608c1e324 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -49,9 +49,15 @@ from core.handlers.model_hub.service import (
from tests.ui_server_test_helpers import csrf_headers, remote_peer, save_config
from vibe import ui_server
from vibe.model_hub_client import ModelHubRemoteService, _decode
+from vibe.model_hub_runtime.state import EngineStateError, _validate_source_target
from vibe.ui_server import app
CONTRACTS = Path("docs/plans/model-hub-contracts")
+SOURCE_EDIT_VALIDATION_CASES = json.loads(
+ Path("tests/fixtures/model_hub_source_edit_validation.json").read_text(
+ encoding="utf-8"
+ )
+)
@pytest.fixture(autouse=True)
@@ -4519,6 +4525,61 @@ def test_source_patch_rejects_credential_bearing_base_url(tmp_path):
assert store.config.sources[0].base_url == "https://relay.example/v1?api-version=2026-07-23"
+ ("field", "case"),
+ [
+ (field, case)
+ for field in ("display_names", "base_urls")
+ for case in SOURCE_EDIT_VALIDATION_CASES[field]
+ ],
+ ids=lambda value: value.get("id", value) if isinstance(value, dict) else value,
+)
+def test_source_edit_validation_contract_fixture(tmp_path, field, case):
+ service, store, _ = _service(tmp_path)
+ source = asyncio.run(
+ _create_source(
+ service,
+ {
+ "kind": "api_key",
+ "vendor": "custom",
+ "display_name": "Original source",
+ "base_url": "https://relay.example/v1",
+ "key": "sk-test-transient-only",
+ },
+ )
+ )
+ payload_field = "display_name" if field == "display_names" else "base_url"
+
+ if not case["valid"]:
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.patch_source(source["id"], {payload_field: case["value"]})
+ )
+ assert exc_info.value.code == "discovery_failed"
+ return
+
+ updated = asyncio.run(
+ service.patch_source(source["id"], {payload_field: case["value"]})
+ )
+ expected = case.get("normalized", case["value"])
+ assert updated["source"][payload_field] == expected
+ assert getattr(store.config.sources[0], payload_field) == expected
+
+
+ "case",
+ SOURCE_EDIT_VALIDATION_CASES["empty_targets"],
+ ids=lambda case: case["id"],
+)
+def test_source_empty_target_contract_fixture(case):
+ if case["server_valid"]:
+ _validate_source_target(case["vendor"], case["protocol"], None)
+ return
+
+ with pytest.raises(EngineStateError):
+ _validate_source_target(case["vendor"], case["protocol"], None)
+
+
def test_source_display_names_reject_credential_material(tmp_path):
service, store, adapter = _service(tmp_path)
pasted_key = "sk-test-never-persist-this"
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
index 67cd13249..4ac96e9c3 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
@@ -79,9 +79,9 @@ const renderDialog = (onClose = vi.fn(), onAdded = vi.fn()) => {
const replacementSettlement = (
overrides: Partial<SourceMutationSettlement> = {},
): SourceMutationSettlement => ({
- source: vi.fn().mockResolvedValue(undefined),
- gone: vi.fn().mockResolvedValue(undefined),
- unread: vi.fn().mockResolvedValue(undefined),
+ source: vi.fn().mockResolvedValue('landed'),
+ gone: vi.fn().mockResolvedValue('landed'),
+ unread: vi.fn().mockResolvedValue('landed'),
release: vi.fn(),
readInventory: vi.fn().mockResolvedValue({ snapshot: 1, sources: [blockedSource] }),
...overrides,
@@ -91,9 +91,9 @@ const neverResolvingSettlement = (
overrides: Partial<SourceMutationSettlement> = {},
): SourceMutationSettlement => ({
...replacementSettlement(),
- source: vi.fn().mockReturnValue(new Promise<void>(() => undefined)),
- gone: vi.fn().mockReturnValue(new Promise<void>(() => undefined)),
- unread: vi.fn().mockReturnValue(new Promise<void>(() => undefined)),
+ source: vi.fn().mockReturnValue(new Promise<never>(() => undefined)),
+ gone: vi.fn().mockReturnValue(new Promise<never>(() => undefined)),
+ unread: vi.fn().mockReturnValue(new Promise<never>(() => undefined)),
...overrides,
});
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsx
index 57e67386a..79d7d1124 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx
@@ -33,6 +33,7 @@ import {
createContinuationSettlement,
createSourceCreatedDelivery,
type ContinuationTicket,
+ type SourceMutationLanding,
type SourceMutationSettlement,
type TrackSourceMutation,
} from './mutationSettlement';
@@ -252,7 +253,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
const publishReplacementFailure = React.useCallback((
seq: ContinuationTicket,
failureClass: ModelHubFailureClass,
- settle?: () => Promise<void>,
+ settle?: () => Promise<SourceMutationLanding>,
) => {
continuation.settle(seq, () => setReplacePhase({ kind: 'failure', failureClass }));
if (settle) void settle().catch(() => undefined);
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 26db279f2..d8fc5c931 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -36,7 +36,7 @@ import { emptyFeed, feedAfterHeadRead, feedAfterTailRead, feedTailCursor, type E
import { readFirstPaintRegions, type SurfaceLanding } from './firstPaintRegions';
import { modelsApi, type SourceCreated } from './modelsApi';
import { convergeMutation, createIntentAuthority } from './mutationConvergence';
-import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
+import type { SourceMutationLanding, SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
import { modelChainKey, modelChainRequests, type ModelChainIndex } from './modelRows';
import {
beginRegionRead,
@@ -519,7 +519,7 @@ export const SettingsModelsPage: React.FC = () => {
if (landing.supply.kind !== 'ready') setChainsRead(failRegionRead);
}));
- const refresh = React.useCallback(async () => {
+ const refresh = React.useCallback(async (): Promise<SourceMutationLanding> => {
void refreshEventHead();
const outcome: { landing: SurfaceLanding | null } = { landing: null };
const result = await refreshAuthority.run(async () => {
@@ -527,9 +527,16 @@ export const SettingsModelsPage: React.FC = () => {
outcome.landing = await readSurfaceLanding(sourceCollectionReads, agentCollectionReads);
return { landing: outcome.landing, sourceSnapshot };
});
- if (aliveRef.current && result === 'landed' && outcome.landing && surfaceLandingFailed(outcome.landing)) {
+ const failed = Boolean(aliveRef.current
+ && result === 'landed'
+ && outcome.landing
+ && surfaceLandingFailed(outcome.landing));
+ if (failed) {
showToast(t('settings.models.toast.refreshFailed') as string, 'error');
}
+ return aliveRef.current && result === 'landed' && outcome.landing && !failed
+ ? 'landed'
+ : 'degraded';
}, [agentCollectionReads, refreshAuthority, refreshEventHead, showToast, sourceCollectionReads, sourceEntityAuthority, t]);
const trackSourceMutation = React.useCallback((sourceId: string): TrackSourceMutation => async <T,>(work: (source: Source, settlement: SourceMutationSettlement) => Promise<T>): Promise<T> => {
@@ -539,11 +546,12 @@ export const SettingsModelsPage: React.FC = () => {
if (!current) throw new Error(`Source ${sourceId} is no longer available`);
const generation = sourceEntityAuthority.begin(sourceId);
let settled = false;
- const finish = async (apply: () => void, reconcile = true): Promise<void> => {
- if (settled) return;
- settled = true;
- apply();
- if (reconcile) await refresh();
+ const finish = async (apply: () => void, reconcile = true): Promise<SourceMutationLanding> => {
+ if (!settled) {
+ settled = true;
+ apply();
+ }
+ return reconcile ? refresh() : 'landed';
};
const settlement: SourceMutationSettlement = {
source: async (echoed) => finish(() => { sourceEntityAuthority.settle(generation, echoed); }),
diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
index 831e46dac..20a8c63c0 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
@@ -9,8 +9,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { ToastProvider } from '@/context/ToastProvider';
import i18n from '@/i18n';
-import { createPendingWrites } from './asyncLifetime';
-import { modelsApi } from './modelsApi';
+import { classifyModelHubFailure, createPendingWrites } from './asyncLifetime';
+import { MANAGE_DESTINATION, type ManageKind } from './manage';
+import { ApiCallError, modelsApi } from './modelsApi';
import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
import { GuardGapList } from './GuardGapList';
import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, repairAction, type RepairKind } from './repair';
@@ -38,6 +39,55 @@ const source: Source = {
models: [{ id: 'model-a', display_name: null, origin: 'manual', reasoning_efforts: ['high'] }],
};
+const heldHops = [{
+ backend: 'claude' as const,
+ menu_model: 'claude-opus-4-6',
+ position: 1,
+ source_id: source.id,
+ model_id: 'model-a',
+}];
+const heldGaps = [{
+ backend: 'claude' as const,
+ model_id: 'claude-opus-4-6',
+ agents: ['Release bot'],
+}];
+
+const guardRefusal = () => new ApiCallError(
+ 'source_last_supplier',
+ undefined,
+ true,
+ heldGaps,
+ [],
+ heldHops,
+ 409,
+);
+
+type UnknownWriteAction = 'edit' | 'delete';
+const UNKNOWN_WRITE_CASES = (['edit', 'delete'] as const).flatMap((action) =>
+ ([false, true] as const).flatMap((forced) =>
+ (['committed', 'absent', 'unread'] as const).map((outcome) => ({ action, forced, outcome }))));
+
+const submitManagementWrite = async (action: UnknownWriteAction, forced: boolean) => {
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ if (action === 'edit') {
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);
+ await userEvent.clear(name);
+ await userEvent.type(name, 'Unknown edit');
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ if (forced) {
+ await userEvent.click(await screen.findByRole('button', { name: /^Save anyway$|^仍要保存$/i }));
+ }
+ return;
+ }
+
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除来源$/i }));
+ await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除来源$/i }));
+ if (forced) {
+ await userEvent.click(await screen.findByRole('button', { name: /^Remove source$|^移除来源$/i }));
+ }
+};
+
const noReauth = () => {
throw new Error('this source has no re-login entry to reach');
};
@@ -63,9 +113,9 @@ const deferred = <T,>() => {
let sourceSnapshot = 0;
const beginSourceSnapshot = () => ++sourceSnapshot;
const settlement = (overrides: Partial<SourceMutationSettlement> = {}): SourceMutationSettlement => ({
- source: vi.fn().mockResolvedValue(undefined),
- gone: vi.fn().mockResolvedValue(undefined),
- unread: vi.fn().mockResolvedValue(undefined),
+ source: vi.fn().mockResolvedValue('landed'),
+ gone: vi.fn().mockResolvedValue('landed'),
+ unread: vi.fn().mockResolvedValue('landed'),
release: vi.fn(),
readInventory: async () => ({ snapshot: beginSourceSnapshot(), sources: await modelsApi.listSources() }),
...overrides,
@@ -97,9 +147,9 @@ const EchoPanel: React.FC<{ reconcile?: () => Promise<void> | void; scheduler?:
const latest = currentRef.current;
if (!latest) throw new Error('Source is gone');
return work(latest, settlement({
- source: async (echoed) => { currentRef.current = echoed; setCurrent(echoed); await reconcile(); },
- gone: async () => { currentRef.current = null; setCurrent(null); await reconcile(); },
- unread: async () => { await reconcile(); },
+ source: async (echoed) => { currentRef.current = echoed; setCurrent(echoed); await reconcile(); return 'landed'; },
+ gone: async () => { currentRef.current = null; setCurrent(null); await reconcile(); return 'landed'; },
+ unread: async () => { await reconcile(); return 'landed'; },
}));
});
return current
@@ -150,6 +200,601 @@ describe('SourceDetailPanel', () => {
expect(screen.getByText(/^In use$|^使用中$/i)).toBeTruthy();
});
+ // The capability set is discovered from its total destination Record. A new
+ // management kind therefore fails here until the rendered panel exposes a
+ // trigger carrying that exact destination.
+ it('gives every management capability a reachable declared destination', async () => {
+ const view = renderPanel();
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+
+ const declared = Object.keys(MANAGE_DESTINATION) as ManageKind[];
+ const triggers = [...view.container.ownerDocument.querySelectorAll<HTMLElement>('[data-manage-kind]')];
+ expect(new Set(triggers.map((trigger) => trigger.dataset.manageKind))).toEqual(new Set(declared));
+ for (const kind of declared) {
+ const trigger = triggers.find((candidate) => candidate.dataset.manageKind === kind);
+ expect(trigger?.dataset.manageDestination).toBe(MANAGE_DESTINATION[kind]);
+ }
+ });
+
+ it('edits the display name and endpoint through the source mutation queue', async () => {
+ const updated = { ...source, display_name: 'Relay key', base_url: 'https://relay.example/v2' };
+ const patch = vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({
+ source: updated,
+ removed_hops: [],
+ interrupted: [],
+ });
+ renderEchoPanel();
+
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);
+ const endpoint = screen.getByLabelText(/^Base URL$/i);
+ await userEvent.clear(name);
+ await userEvent.type(name, 'Relay key');
+ await userEvent.clear(endpoint);
+ await userEvent.type(endpoint, 'https://relay.example/v2/');
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+
+ await waitFor(() => expect(patch).toHaveBeenCalledWith(source.id, {
+ display_name: 'Relay key',
+ base_url: 'https://relay.example/v2/',
+ }));
+ expect(await screen.findByRole('heading', { name: 'Relay key' })).toBeTruthy();
+ });
+
+ it('explains client validation instead of leaving a mute disabled save', async () => {
+ renderEchoPanel();
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
+
+ const endpoint = screen.getByLabelText(/^Base URL$/i);
+ await userEvent.clear(endpoint);
+ await userEvent.type(endpoint, 'https://relay.example/v2?access_token=do-not-store');
+ expect(screen.getByText(/Remove credentials|移除凭据/i)).toBeTruthy();
+ expect((screen.getByRole('button', { name: /^Save$|^保存$/i }) as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ it('leaves URL acceptance to the server and renders its named failure in the editor', async () => {
+ const patch = vi.spyOn(modelsApi, 'patchSource')
+ .mockRejectedValueOnce(new ApiCallError('discovery_failed'));
+ renderEchoPanel();
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
+
+ const endpoint = screen.getByLabelText(/^Base URL$/i);
+ await userEvent.clear(endpoint);
+ await userEvent.type(endpoint, 'https:relay.example');
+ const save = screen.getByRole('button', { name: /^Save$|^保存$/i }) as HTMLButtonElement;
+ expect(save.disabled).toBe(false);
+ await userEvent.click(save);
+
+ await waitFor(() => expect(patch).toHaveBeenCalledWith(source.id, { base_url: 'https:relay.example' }));
+ expect(await screen.findByText(/source was not saved|来源没有保存上/i)).toBeTruthy();
+ expect(screen.getByDisplayValue('https:relay.example')).toBeTruthy();
+ });
+
+ it('renders the proved protocol through its product-facing locale key', async () => {
+ render(
+ <I18nextProvider i18n={i18n}>
+ <SourceDetailPanel
+ source={{ ...source, vendor: 'custom', protocol: 'openai_chat' }}
+ trackMutation={immediateTrack}
+ onReauth={noReauth}
+ />
+ </I18nextProvider>,
+ );
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
+
+ expect(screen.getByText(/OpenAI Chat Completions/i)).toBeTruthy();
+ expect(screen.queryByText('openai_chat')).toBeNull();
+ });
+
+ it('holds a committed edit impact envelope until the user completes the report', async () => {
+ const updated = { ...source, display_name: 'Impacted source' };
+ vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({
+ source: updated,
+ removed_hops: [{ backend: 'claude', menu_model: 'claude-opus-4-6', position: 1, source_id: source.id, model_id: 'model-a' }],
+ interrupted: [{ backend: 'claude', model_id: 'claude-opus-4-6', agents: ['Release bot'] }],
+ });
+ renderEchoPanel();
+
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);
+ await userEvent.clear(name);
+ await userEvent.type(name, updated.display_name);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+
+ const impactDialog = await screen.findByRole('dialog', { name: /source was updated|来源已更新/i });
+ expect(screen.queryByRole('heading', { name: updated.display_name })).toBeNull();
+ const done = within(impactDialog)
+ .getAllByRole('button', { name: /^Done$|^完成$/i })
+ .find((button) => button.classList.contains('model-hub-guard-action'));
+ expect(done).toBeTruthy();
+ await userEvent.click(done!);
+ expect(await screen.findByRole('heading', { name: updated.display_name })).toBeTruthy();
+ });
+
+ it('echoes a non-empty server plan exactly when deleting a source', async () => {
+ const hops = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 2, source_id: source.id, model_id: 'model-a' }];
+ const gaps = [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['Release bot'] }];
+ const requests: { url: string; init?: RequestInit }[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });
+ if (url.startsWith(`/api/models/sources/${source.id}`)) {
+ requests.push({ url, init });
+ if (requests.length === 1) {
+ return Response.json({ error: 'source_in_route_chain', would_remove_hops: hops, would_interrupt: gaps }, { status: 409 });
+ }
+ return Response.json({ removed_hops: hops, interrupted: gaps });
+ }
+ throw new Error(`unexpected request: ${url}`);
+ }));
+ renderEchoPanel();
+
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除来源$/i }));
+ await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除来源$/i }));
+ expect(await screen.findAllByText(/claude-opus-4-6/)).toHaveLength(2);
+ await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除来源$/i }));
+
+ await waitFor(() => expect(requests).toHaveLength(2));
+ expect(requests[0].url).not.toContain('force=true');
+ expect(requests[0].init?.body).toBeUndefined();
+ expect(requests[1].url).toContain('?force=true');
+ expect(JSON.parse(String(requests[1].init?.body))).toEqual({
+ would_remove_hops: hops,
+ would_interrupt: gaps,
+ });
+ expect(screen.queryByTestId('source-gone')).toBeNull();
+ const impactDialog = await screen.findByRole('dialog', { name: /source was removed|来源已移除/i });
+ const done = within(impactDialog)
+ .getAllByRole('button', { name: /^Done$|^完成$/i })
+ .find((button) => button.classList.contains('model-hub-guard-action'));
+ expect(done).toBeTruthy();
+ await userEvent.click(done!);
+ expect(await screen.findByTestId('source-gone')).toBeTruthy();
+ });
+
+ it('sends no force when deleting a source with an empty server plan', async () => {
+ const requests: { url: string; init?: RequestInit }[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });
+ if (url === `/api/models/sources/${source.id}`) {
+ requests.push({ url, init });
+ return Response.json({ removed_hops: [], interrupted: [] });
+ }
+ throw new Error(`unexpected request: ${url}`);
+ }));
+ renderEchoPanel();
+
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除来源$/i }));
+ await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除来源$/i }));
+
+ expect(await screen.findByTestId('source-gone')).toBeTruthy();
+ expect(requests).toHaveLength(1);
+ expect(requests[0].url).toBe(`/api/models/sources/${source.id}`);
+ expect(requests[0].init?.body).toBeUndefined();
+ });
+
+ it('keeps a refused deletion visible and offers a retry', async () => {
+ let requests = 0;
+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });
+ if (url === `/api/models/sources/${source.id}`) {
+ requests += 1;
+ return Response.json({ error: 'discovery_failed' }, { status: 503 });
+ }
+ throw new Error(`unexpected request: ${url}`);
+ }));
+ renderEchoPanel();
+
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除来源$/i }));
+ await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除来源$/i }));
+
+ expect(await screen.findByRole('heading', { name: source.display_name })).toBeTruthy();
+ const retry = await screen.findByRole('button', { name: /^Try again$|^重试$/i });
+ await userEvent.click(retry);
+ await waitFor(() => expect(requests).toBe(2));
+ expect(await screen.findByRole('button', { name: /^Try again$|^重试$/i })).toBeTruthy();
+ });
+
+ it('returns an edit guard cancellation to the held draft', async () => {
+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });
+ if (url === `/api/models/sources/${source.id}`) {
+ return Response.json({
+ error: 'source_last_supplier',
+ would_remove_hops: [{ backend: 'claude', menu_model: 'claude-opus-4-6', position: 1, source_id: source.id, model_id: 'model-a' }],
+ would_interrupt: [],
+ }, { status: 409 });
+ }
+ throw new Error(`unexpected request: ${url}`);
+ }));
+ renderEchoPanel();
+
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);
+ await userEvent.clear(name);
+ await userEvent.type(name, 'Held draft');
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ const guardDialog = await screen.findByRole('dialog', { name: /save changes|保存.*更改/i });
+ const cancel = within(guardDialog)
+ .getAllByRole('button', { name: /^Cancel$|^取消$/i })
+ .find((button) => button.classList.contains('model-hub-guard-action'));
+ expect(cancel).toBeTruthy();
+ await userEvent.click(cancel!);
+
+ expect(await screen.findByDisplayValue('Held draft')).toBeTruthy();
+ });
+
+ it('returns a failed forced edit to its held draft and visible error', async () => {
+ let attempts = 0;
+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });
+ if (url === `/api/models/sources/${source.id}`) {
+ attempts += 1;
+ if (attempts === 1) {
+ return Response.json({
+ error: 'source_last_supplier',
+ would_remove_hops: [{ backend: 'claude', menu_model: 'claude-opus-4-6', position: 1, source_id: source.id, model_id: 'model-a' }],
+ would_interrupt: [],
+ }, { status: 409 });
+ }
+ return Response.json({ error: 'discovery_failed' }, { status: 503 });
+ }
+ throw new Error(`unexpected request: ${url}`);
+ }));
+ renderEchoPanel();
+
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);
+ await userEvent.clear(name);
+ await userEvent.type(name, 'Held failure');
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+ await userEvent.click(await screen.findByRole('button', { name: /^Save anyway$|^仍要保存$/i }));
+
+ expect(await screen.findByDisplayValue('Held failure')).toBeTruthy();
+ expect(screen.getByText(/source was not saved|来源没有保存上/i)).toBeTruthy();
+ });
+
+ it('retries a failed forced delete with the exact held server plan', async () => {
+ const hops = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 1, source_id: source.id, model_id: 'model-a' }];
+ const gaps = [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['Release bot'] }];
+ const requests: { url: string; init?: RequestInit }[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });
+ if (url.startsWith(`/api/models/sources/${source.id}`)) {
+ requests.push({ url, init });
+ if (requests.length === 1) return Response.json({ error: 'source_in_route_chain', would_remove_hops: hops, would_interrupt: gaps }, { status: 409 });
+ if (requests.length === 2) return Response.json({ error: 'discovery_failed' }, { status: 503 });
+ return Response.json({ removed_hops: [], interrupted: [] });
+ }
+ throw new Error(`unexpected request: ${url}`);
+ }));
+ renderEchoPanel();
+
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Remove source$|^移除来源$/i }));
+ await userEvent.click(screen.getByRole('button', { name: /^Remove source$|^移除来源$/i }));
+ await userEvent.click(await screen.findByRole('button', { name: /^Remove source$|^移除来源$/i }));
+ await userEvent.click(await screen.findByRole('button', { name: /^Try again$|^重试$/i }));
+
+ await waitFor(() => expect(requests).toHaveLength(3));
+ for (const request of requests.slice(1)) {
+ expect(request.url).toContain('?force=true');
+ expect(JSON.parse(String(request.init?.body))).toEqual({
+ would_remove_hops: hops,
+ would_interrupt: gaps,
+ });
+ }
+ expect(await screen.findByTestId('source-gone')).toBeTruthy();
+ });
+
+ it.each(UNKNOWN_WRITE_CASES)(
+ 'reconciles an unknown $action write (forced=$forced, outcome=$outcome) from one authoritative read',
+ async ({ action, forced, outcome }) => {
+ const unknownFailure = action === 'edit'
+ ? new ApiCallError('http_502', undefined, false, heldGaps, [], heldHops, 502)
+ : new TypeError('response lost');
+ if (action === 'edit') {
+ const mutation = vi.spyOn(modelsApi, 'patchSource');
+ if (forced) mutation.mockRejectedValueOnce(guardRefusal());
+ mutation.mockRejectedValueOnce(unknownFailure);
+ } else {
+ const mutation = vi.spyOn(modelsApi, 'deleteSource');
+ if (forced) mutation.mockRejectedValueOnce(guardRefusal());
+ mutation.mockRejectedValueOnce(unknownFailure);
+ }
+
+ const updated = { ...source, display_name: 'Unknown edit' };
+ const inventory = vi.spyOn(modelsApi, 'listSources');
+ if (outcome === 'unread') inventory.mockRejectedValueOnce(new Error('inventory unavailable'));
+ else if (outcome === 'committed') inventory.mockResolvedValueOnce(action === 'edit' ? [updated] : []);
+ else inventory.mockResolvedValueOnce([source]);
+
+ renderEchoPanel();
+ await submitManagementWrite(action, forced);
+ await waitFor(() => expect(inventory).toHaveBeenCalledOnce());
+
+ if (outcome === 'committed' && forced) {
+ const impact = await screen.findByRole('dialog', {
+ name: action === 'edit' ? /source was updated|来源已更新/i : /source was removed|来源已移除/i,
+ });
+ expect(impact.textContent).toContain('claude-opus-4-6');
+ const done = within(impact)
+ .getAllByRole('button', { name: /^Done$|^完成$/i })
+ .find((button) => button.classList.contains('model-hub-guard-action'));
+ expect(done).toBeTruthy();
+ await userEvent.click(done!);
+ }
+
+ if (outcome === 'committed') {
+ if (action === 'edit') expect(await screen.findByRole('heading', { name: 'Unknown edit' })).toBeTruthy();
+ else expect(await screen.findByTestId('source-gone')).toBeTruthy();
+ return;
+ }
+
+ const failure = await waitFor(() => {
+ const node = document.querySelector<HTMLElement>(`[data-manage-failure="${action}"]`);
+ expect(node).toBeTruthy();
+ return node!;
+ });
+ expect(failure.dataset.manageRetryRead).toBe(String(outcome === 'unread'));
+ if (outcome === 'unread') expect(failure.textContent).toMatch(/Could not verify|无法确认/i);
+ else expect(failure.textContent).toMatch(/was not saved|was not removed|没有保存上|没有移除/i);
+ },
+ );
+
+ it.each([
+ { outcome: 'requested', rereadBaseUrl: 'https://requested.example/v2', committed: true },
+ { outcome: 'third-party', rereadBaseUrl: 'https://other.example/v3', committed: false },
+ { outcome: 'unchanged', rereadBaseUrl: source.base_url, committed: false },
+ ])(
+ 'confirms an endpoint write only when the reread value is $outcome',
+ async ({ rereadBaseUrl, committed }) => {
+ const requestedBaseUrl = 'https://requested.example/v2';
+ const patch = vi.spyOn(modelsApi, 'patchSource')
+ .mockRejectedValueOnce(new TypeError('response lost'));
+ const inventory = vi.spyOn(modelsApi, 'listSources')
+ .mockResolvedValueOnce([{ ...source, base_url: rereadBaseUrl }]);
+ renderEchoPanel();
+
+ await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
+ await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
+ const endpoint = screen.getByLabelText(/^Base URL$/i);
+ await userEvent.clear(endpoint);
+ await userEvent.type(endpoint, requestedBaseUrl);
+ await userEvent.click(screen.getByRole('button', { name: /^Save$|^保存$/i }));
+
+ await waitFor(() => expect(inventory).toHaveBeenCalledOnce());
+ expect(patch).toHaveBeenCalledWith(source.id, { base_url: requestedBaseUrl });
+ if (committed) {
+ expect(await screen.findByText(/requested\.example/)).toBeTruthy();
+ expect(document.querySelector('[data-manage-failure="edit"]')).toBeNull();
+ } else {
+ const failure = await waitFor(() => {
+ const node = document.querySelector<HTMLElement>('[data-manage-failure="edit"]');
+ expect(node).toBeTruthy();
+ return node!;
+ });
+ expect(failure.dataset.manageRetryRead).toBe('false');
+ expect(failure.textContent).toMatch(/was not saved|没有保存上/i);
+ }
+ },
+ );
+
+ it('rereads instead of issuing another PATCH while an unknown edit remains unresolved', async () => {
+ const patch = vi.spyOn(modelsApi, 'patchSource').mockRejectedValueOnce(new TypeError('response lost'));
+ const inventory = vi.spyOn(modelsApi, 'listSources')
+ .mockRejectedValueOnce(new Error('inventory unavailable'))
+ .mockResolvedValueOnce([source]);
+ renderEchoPanel();
+
+ await submitManagementWrite('edit', false);
+ await waitFor(() => expect(inventory).toHaveBeenCalledOnce());
+ const name = screen.getByLabelText(/^Display name$|^显示名称$/i);
+ await userEvent.type(name, ' still fenced');
+ await userEvent.keyboard('{Escape}');
+ expect(screen.getByDisplayValue('Unknown edit still fenced')).toBeTruthy();
+
+ await userEvent.click(screen.getByRole('button', { name: /^Try again$|^重试$/i }));
+ await waitFor(() => expect(inventory).toHaveBeenCalledTimes(2));
+ expect(patch).toHaveBeenCalledOnce();
+ });
+
+ it.each(['edit', 'delete'] as const)(
+ 'keeps the exact committed $action impact mounted until settlement lands',
+ async (action) => {
+ const reconcile = vi.fn()
+ .mockResolvedValueOnce('degraded')
+ .mockResolvedValueOnce('landed');
+ const hops = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 1, source_id: source.id, model_id: 'model-a' }];
+ const gaps = [{ backend: 'claude' as const, model_id: 'claude-opus-4-6', agents: ['Release bot'] }];
+ if (action === 'edit') {
+ vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({
+ source: { ...source, display_name: 'Unknown edit' },
+ removed_hops: hops,
+ interrupted: gaps,
+ });
+ } else {
+ vi.spyOn(modelsApi, 'deleteSource').mockResolvedValueOnce({
+ removed_hops: hops,
+ interrupted: gaps,
+ });
+ }
+ const trackMutation: TrackSourceMutation = (work) => work(source, settlement({
+ source: reconcile,
+ gone: reconcile,
+ }));
+ render(
+ <ToastProvider>
+ <I18nextProvider i18n={i18n}>
+ <SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />
+ </I18nextProvider>
+ </ToastProvider>,
+ );
+
+ await submitManagementWrite(action, false);
+ const impact = await screen.findByRole('dialog', {
+ name: action === 'edit' ? /source was updated|来源已更新/i : /source was removed|来源已移除/i,
+ });
+ const committedEvidence = () => Array.from(impact.querySelectorAll('.model-hub-guard-hop'))
+ .map((node) => node.textContent);
+ const evidenceBeforeRetry = committedEvidence();
+ expect(impact.textContent).toContain(hops[0].menu_model);
+ expect(impact.textContent).toContain(gaps[0].agents[0]);
+
+ const done = within(impact).getAllByRole('button', { name: /^Done$|^完成$/i })
+ .find((button) => button.classList.contains('model-hub-guard-action'));
+ expect(done).toBeTruthy();
+ await userEvent.click(done!);
+ expect(await within(impact).findByText(/could not be refreshed|暂时无法刷新/i)).toBeTruthy();
+ expect(committedEvidence()).toEqual(evidenceBeforeRetry);
+ expect(within(impact).getAllByRole('button', { name: /Dismiss unverified result|放弃未验证结果/i })
+ .some((button) => button.classList.contains('model-hub-guard-action'))).toBe(true);
+
+ await userEvent.click(within(impact).getByRole('button', { name: /^Try again$|^重试$/i }));
+ await waitFor(() => expect(screen.queryByRole('dialog', {
+ name: action === 'edit' ? /source was updated|来源已更新/i : /source was removed|来源已移除/i,
+ })).toBeNull());
+ expect(reconcile).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it('releases tracked work when degraded impact is explicitly dismissed', async () => {
+ const reconcile = vi.fn().mockResolvedValueOnce('degraded');
+ const hops = [{ backend: 'claude' as const, menu_model: 'claude-opus-4-6', position: 1, source_id: source.id, model_id: 'model-a' }];
+ vi.spyOn(modelsApi, 'patchSource').mockResolvedValueOnce({
+ source: { ...source, display_name: 'Dismissible impact' },
+ removed_hops: hops,
+ interrupted: [],
+ });
+ let tracked: Promise<unknown> | undefined;
+ let trackedSettled = false;
+ const trackMutation: TrackSourceMutation = (work) => {
+ const operation = work(source, settlement({ source: reconcile }));
+ tracked = operation;
+ void operation.then(
+ () => { trackedSettled = true; },
+ () => { trackedSettled = true; },
+ );
+ return operation;
+ };
+ render(
+ <ToastProvider>
+ <I18nextProvider i18n={i18n}>
+ <SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />
+ </I18nextProvider>
+ </ToastProvider>,
+ );
+
+ await submitManagementWrite('edit', false);
+ const impact = await screen.findByRole('dialog', { name: /source was updated|来源已更新/i });
+ const closeBeforeLanding = within(impact).getAllByRole('button', { name: /^Done$|^完成$/i })
+ .find((button) => button.classList.contains('model-hub-guard-close'));
+ expect(closeBeforeLanding).toBeTruthy();
+ expect((closeBeforeLanding as HTMLButtonElement).disabled).toBe(true);
+ const done = within(impact).getAllByRole('button', { name: /^Done$|^完成$/i })
+ .find((button) => button.classList.contains('model-hub-guard-action'));
+ await userEvent.click(done!);
+
+ const dismissButtons = await within(impact).findAllByRole('button', { name: /Dismiss unverified result|放弃未验证结果/i });
+ expect(dismissButtons.some((button) => button.classList.contains('model-hub-guard-action'))).toBe(true);
+ const dismissClose = dismissButtons.find((button) => button.classList.contains('model-hub-guard-close'));
+ expect(dismissClose).toBeTruthy();
+ expect((dismissClose as HTMLButtonElement).disabled).toBe(false);
+ expect(trackedSettled).toBe(false);
+ await userEvent.click(dismissClose!);
+ await waitFor(() => expect(screen.queryByRole('dialog', { name: /source was updated|来源已更新/i })).toBeNull());
+ expect(tracked).toBeDefined();
+ await tracked;
+ expect(trackedSettled).toBe(true);
+ });
+
+ it('releases tracked work when delete settlement unmounts the impact holder', async () => {
+ vi.spyOn(modelsApi, 'deleteSource').mockResolvedValueOnce({
+ removed_hops: heldHops,
+ interrupted: heldGaps,
+ });
+ let tracked: Promise<unknown> | undefined;
+ let trackedSettled = false;
+ let view: ReturnType<typeof render> | null = null;
+ const gone = vi.fn(async () => {
+ view?.unmount();
+ return 'degraded' as const;
+ });
+ const trackMutation: TrackSourceMutation = (work) => {
+ const operation = work(source, settlement({ gone }));
+ tracked = operation;
+ void operation.then(
+ () => { trackedSettled = true; },
+ () => { trackedSettled = true; },
+ );
+ return operation;
+ };
+ view = render(
+ <ToastProvider>
+ <I18nextProvider i18n={i18n}>
+ <SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} />
+ </I18nextProvider>
+ </ToastProvider>,
+ );
+
+ await submitManagementWrite('delete', false);
+ const impact = await screen.findByRole('dialog', { name: /source was removed|来源已移除/i });
+ const done = within(impact).getAllByRole('button', { name: /^Done$|^完成$/i })
+ .find((button) => button.classList.contains('model-hub-guard-action'));
+ expect(done).toBeTruthy();
+ expect(trackedSettled).toBe(false);
+ await userEvent.click(done!);
+
+ await waitFor(() => expect(gone).toHaveBeenCalledOnce());
+ expect(tracked).toBeDefined();
+ // Completeness comes from the total stage predicate, not from remembering
+ // each UI event that can stop holding the committed-impact stage.
+ await tracked;
+ expect(trackedSettled).toBe(true);
+ });
+
+ it.each((['edit', 'delete'] as const).flatMap((action) => [
+ { action, code: 'engine_down', serverNamed: true },
+ { action, code: 'bad_response', serverNamed: false },
+ { action, code: 'discovery_failed', serverNamed: true },
+ ]))(
+ 'rereads after $action exactly when the shared classifier marks $code inconclusive',
+ async ({ action, code, serverNamed }) => {
+ const failure = new ApiCallError(code, undefined, serverNamed);
+ if (action === 'edit') vi.spyOn(modelsApi, 'patchSource').mockRejectedValueOnce(failure);
+ else vi.spyOn(modelsApi, 'deleteSource').mockRejectedValueOnce(failure);
+ const inventory = vi.spyOn(modelsApi, 'listSources');
+ const inconclusive = classifyModelHubFailure(failure) === 'inconclusive';
+ if (inconclusive) inventory.mockResolvedValueOnce([source]);
+
+ renderEchoPanel();
+ await submitManagementWrite(action, false);
+
+ const failureSurface = await waitFor(() => {
+ const node = document.querySelector<HTMLElement>(`[data-manage-failure="${action}"]`);
+ expect(node).toBeTruthy();
+ return node!;
+ });
+ expect(failureSurface.dataset.manageRetryRead).toBe('false');
+ expect(inventory).toHaveBeenCalledTimes(inconclusive ? 1 : 0);
+ },
+ );
+
it('omits native refetch because that channel has no stored discovery credential', () => {
render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={{ ...source, kind: 'subscription', supply_channel: 'native_cli' }} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);
expect(screen.queryByRole('button', { name: /^Refetch$|^重新拉取$/i })).toBeNull();
@@ -237,8 +882,9 @@ describe('SourceDetailPanel', () => {
it('orders every full-Source mutation family through the same Source queue', async () => {
const writes = createPendingWrites(() => {});
const started: string[] = [];
- const gates = ['tier', 'refetch', 'add', 'remove'].map(() => deferred<void>());
- const runs = ['tier', 'refetch', 'add', 'remove'].map((name, index) => writes.track(source.id, async () => {
+ const families = ['tier', 'refetch', 'add', 'remove', 'edit', 'delete'];
+ const gates = families.map(() => deferred<void>());
+ const runs = families.map((name, index) => writes.track(source.id, async () => {
started.push(name);
await gates[index].promise;
}));
@@ -246,7 +892,7 @@ describe('SourceDetailPanel', () => {
await waitFor(() => expect(started).toEqual(['tier']));
for (let index = 0; index < gates.length; index += 1) {
gates[index].resolve();
- await waitFor(() => expect(started).toEqual(['tier', 'refetch', 'add', 'remove'].slice(0, index + 2)));
+ await waitFor(() => expect(started).toEqual(families.slice(0, index + 2)));
}
await Promise.all(runs);
});
@@ -256,9 +902,22 @@ describe('SourceDetailPanel', () => {
expect(detail).toMatch(/const refetch = \(confirmation\?: GuardConfirmation\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
expect(detail).toMatch(/const addManualModel = \(\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
expect(detail).toMatch(/const remove = \(model: SuppliedModel, confirmation\?: GuardConfirmation\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
+ expect(detail).toMatch(/const submitEdit = \(draft: SourceEditDraft, patch: SourcePatch, plan: ManageGuardPlan \| null\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
+ expect(detail).toMatch(/const submitDelete = \(plan: ManageGuardPlan \| null\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);
expect(detail).toMatch(/const commit = async[\s\S]*?setSaving\(true\)[\s\S]*?trackMutation\(async \(latest, settlement\)[\s\S]*?tierMutationPayload\(latest/);
});
+ it('routes every JSX management gesture through the stage authority', () => {
+ const detail = readFileSync(join(process.cwd(), 'src/components/settings/models/SourceDetailPanel.tsx'), 'utf8');
+ const jsx = detail.slice(detail.lastIndexOf('\n return ('));
+ expect(detail).toContain('React.useReducer(transitionManageStage');
+ expect(jsx).not.toMatch(/setManageStage|dispatchManageStage\(\{\s*type:\s*['"](?:begin|submit|guard|fail|commit|settled)/);
+ expect(jsx).toMatch(/editManageDraft/);
+ expect(jsx).toMatch(/cancelManage/);
+ expect(jsx).toMatch(/dismissUnresolvedManage/);
+ expect(jsx).toMatch(/completeManageImpact/);
+ });
+
it('keeps Source entities behind one generation authority without an adoption side cache', () => {
const page = readFileSync(join(process.cwd(), 'src/components/settings/models/SettingsModelsPage.tsx'), 'utf8');
const sourceRow = readFileSync(join(process.cwd(), 'src/components/settings/models/SourceRow.tsx'), 'utf8');
diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsx
index f13565da6..904d6fc27 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx
@@ -10,7 +10,26 @@ import { ResponsiveMenu } from '@/components/ui/responsive-menu';
import { cn } from '@/lib/utils';
import { formatRelativeTime } from '@/lib/relativeTime';
import { AddApiKeyDialog } from './AddApiKeyDialog';
+import { PROTOCOL_COPY_KEYS } from './addApiKeyState';
+import { classifyModelHubFailure } from './asyncLifetime';
+import { Field } from './dialogFields';
import { GuardImpact } from './GuardImpact';
+import {
+ assessSourceEdit,
+ canEditSourceEndpoint,
+ holdsCommittedImpact,
+ manageActions,
+ MANAGE_DESTINATION,
+ MANAGE_LABEL_KEY,
+ SOURCE_EDIT_REASON_KEY,
+ transitionManageStage,
+} from './manage';
+import type {
+ ManageGuardPlan,
+ ManageKind,
+ ManageStage,
+ SourceEditDraft,
+} from './manage';
import { apiFailure, modelsApi, type GuardConfirmation } from './modelsApi';
import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
import { handOffProviderTab } from './providerTab';
@@ -20,7 +39,7 @@ import { sourceStatePresentation } from './sourceStatePresentation';
import { tierMutationPayload, type TierMutationIntent } from './tierMutation';
import { useDeadlineClock } from './useDeadlineClock';
import { ACCENT_ICON, ACCENT_TILE, isCustomEndpoint, sourceVisual } from './vendorMeta';
-import type { RouteHopRef, Source, SuppliedModel, SupplyGap } from './types';
+import type { RouteHopRef, Source, SourcePatch, SuppliedModel, SupplyGap } from './types';
const ManualModelMenu: React.FC<{
model: SuppliedModel;
@@ -43,16 +62,66 @@ const ManualModelMenu: React.FC<{
);
};
+const SourceManageMenu: React.FC<{
+ source: Source;
+ busy: boolean;
+ onEdit: () => void;
+ onDelete: () => void;
+}> = ({ source, busy, onEdit, onDelete }) => {
+ const { t } = useTranslation();
+ const [open, setOpen] = React.useState(false);
+ const label = t('settings.models.sourceDetail.manage.label', { source: source.display_name }) as string;
+ const activate = (kind: ManageKind) => {
+ setOpen(false);
+ if (kind === 'edit_source') onEdit();
+ else onDelete();
+ };
+ return (
+ <ResponsiveMenu
+ open={open}
+ onOpenChange={setOpen}
+ sheetTitle={source.display_name}
+ className="w-44"
+ trigger={<button type="button" disabled={busy} aria-label={label} title={label} className="grid size-8 place-items-center rounded-md text-muted hover:bg-surface-2 hover:text-foreground"><MoreHorizontal className="size-4" /></button>}
+ >
+ {manageActions().map((kind) => (
+ <button
+ key={kind}
+ type="button"
+ role="menuitem"
+ data-manage-kind={kind}
+ data-manage-destination={MANAGE_DESTINATION[kind]}
+ className={cn(
+ 'flex w-full items-center rounded-md px-2.5 py-2 text-left text-[12px] font-semibold hover:bg-surface-2',
+ kind === 'delete_source' && 'text-destructive-ink hover:bg-destructive/[0.08]',
+ )}
+ onClick={() => activate(kind)}
+ >
+ {t(MANAGE_LABEL_KEY[kind])}
+ </button>
+ ))}
+ </ResponsiveMenu>
+ );
+};
+
type GuardedAction =
- | { kind: 'refetch'; hops: RouteHopRef[]; gaps: SupplyGap[] }
- | { kind: 'remove'; model: SuppliedModel; hops: RouteHopRef[]; gaps: SupplyGap[] };
+ | { kind: 'refetch'; plan: ManageGuardPlan }
+ | { kind: 'removeModel'; model: SuppliedModel; plan: ManageGuardPlan };
-const confirmGuardPlan = (guard: Pick<GuardedAction, 'hops' | 'gaps'>): GuardConfirmation => ({
+const confirmGuardPlan = (plan: ManageGuardPlan): GuardConfirmation => ({
force: true,
- would_remove_hops: guard.hops,
- would_interrupt: guard.gaps,
+ would_remove_hops: plan.hops,
+ would_interrupt: plan.gaps,
});
+const GUARD_COPY_KIND: Record<GuardedAction['kind'], 'refetch' | 'removeModel'> = {
+ refetch: 'refetch',
+ removeModel: 'removeModel',
+};
+
+const committedPlan = (hops: RouteHopRef[], gaps: SupplyGap[]): ManageGuardPlan | null =>
+ hops.length > 0 || gaps.length > 0 ? { hops, gaps } : null;
+
type SourceReconciliation =
| { kind: 'source'; source: Source }
| { kind: 'gone'; sources: Source[]; snapshot: number };
@@ -225,14 +294,40 @@ export const SourceDetailPanel: React.FC<{
const [busy, setBusy] = React.useState(false);
const [confirmingReauth, setConfirmingReauth] = React.useState(false);
const [replacingKey, setReplacingKey] = React.useState(false);
+ const [manageStage, dispatchManageStage] = React.useReducer(transitionManageStage, { kind: 'idle' });
+ const committedImpactReleaseRef = React.useRef<(() => void) | null>(null);
const [manualDraft, setManualDraft] = React.useState<{ modelId: string; tiers: string[]; failed: boolean; retryRead: boolean } | null>(null);
const [guard, setGuard] = React.useState<GuardedAction | null>(null);
const [result, setResult] = React.useState<{ added: string[]; removed: string[] } | null>(null);
const [refetchFailed, setRefetchFailed] = React.useState(false);
const [removeFailure, setRemoveFailure] = React.useState<{ modelId: string; retryRead: boolean } | null>(null);
const models = source.models;
+ const editDraft = 'draft' in manageStage ? manageStage.draft : null;
+ const editAssessment = editDraft
+ ? assessSourceEdit(source, editDraft)
+ : { valid: false as const, patch: null, reason: null };
+ const releaseCommittedImpact = React.useCallback(() => {
+ const release = committedImpactReleaseRef.current;
+ committedImpactReleaseRef.current = null;
+ release?.();
+ }, []);
+
+ React.useEffect(() => {
+ if (!holdsCommittedImpact(manageStage)) releaseCommittedImpact();
+ }, [manageStage, releaseCommittedImpact]);
+ React.useEffect(() => () => releaseCommittedImpact(), [releaseCommittedImpact]);
+
+ const beginEdit = () => {
+ dispatchManageStage({
+ type: 'begin_edit',
+ draft: { displayName: source.display_name, baseUrl: source.base_url ?? '' },
+ });
+ };
+ const beginDelete = () => {
+ dispatchManageStage({ type: 'begin_delete' });
+ };
- const guardedFailure = (error: unknown): { hops: RouteHopRef[]; gaps: SupplyGap[] } | null => {
+ const guardedFailure = (error: unknown): ManageGuardPlan | null => {
const failure = apiFailure(error);
if (!failure || (failure.wouldRemoveHops.length === 0 && failure.wouldInterrupt.length === 0)) return null;
return { hops: failure.wouldRemoveHops, gaps: failure.wouldInterrupt };
@@ -257,7 +352,7 @@ export const SourceDetailPanel: React.FC<{
else {
const refusal = guardedFailure(error);
if (refusal) {
- setGuard({ kind: 'refetch', ...refusal });
+ setGuard({ kind: 'refetch', plan: refusal });
settlement.release();
} else {
setRefetchFailed(true);
@@ -387,18 +482,265 @@ export const SourceDetailPanel: React.FC<{
else {
const refusal = guardedFailure(error);
if (refusal) {
- setGuard({ kind: 'remove', model, ...refusal });
+ setGuard({ kind: 'removeModel', model, plan: refusal });
settlement.release();
} else await reconcileRemoval(latest.id, model, settlement);
}
}
}).finally(() => setBusy(false));
};
+ const holdCommittedImpact = (
+ kind: 'edit' | 'delete',
+ plan: ManageGuardPlan,
+ settle: Extract<ManageStage, { kind: 'committed_edit_impact' }>['complete'],
+ ) => new Promise<void>((resolve) => {
+ setBusy(false);
+ committedImpactReleaseRef.current = resolve;
+ dispatchManageStage({ type: 'commit_impact', action: kind, plan, complete: settle });
+ });
+ const reconcileEditWrite = async (
+ before: Source,
+ draft: SourceEditDraft,
+ patch: SourcePatch,
+ plan: ManageGuardPlan | null,
+ settlement: SourceMutationSettlement,
+ ) => {
+ const reconciliation = await reconcileUnknownWrite(
+ settlement.readInventory,
+ ({ sources, snapshot }) => {
+ const current = sources.find((item) => item.id === before.id);
+ if (!current) return { kind: 'gone', sources, snapshot } satisfies SourceReconciliation;
+ const displayNameCommitted = patch.display_name === undefined
+ || current.display_name === patch.display_name;
+ const baseUrlCommitted = patch.base_url === undefined
+ || current.base_url === patch.base_url;
+ return displayNameCommitted && baseUrlCommitted
+ ? { kind: 'source', source: current } satisfies SourceReconciliation
+ : undefined;
+ },
+ );
+ if (reconciliation.kind === 'committed') {
+ const current = reconciliation.value.kind === 'source'
+ ? reconciliation.value.source
+ : null;
+ if (current && plan) {
+ await holdCommittedImpact(
+ 'edit',
+ plan,
+ () => settlement.source(current),
+ );
+ } else {
+ dispatchManageStage({ type: 'settled' });
+ await applyReconciliation(before.id, reconciliation.value, settlement);
+ }
+ return;
+ }
+ settlement.release();
+ dispatchManageStage({
+ type: 'fail_edit',
+ draft,
+ patch,
+ plan,
+ forced: plan !== null,
+ retryRead: reconciliation.kind === 'unread',
+ before,
+ });
+ };
+ const reconcileDeleteWrite = async (
+ before: Source,
+ plan: ManageGuardPlan | null,
+ settlement: SourceMutationSettlement,
+ ) => {
+ const reconciliation = await reconcileUnknownWrite(
+ settlement.readInventory,
+ ({ sources, snapshot }) => sources.some((item) => item.id === before.id)
+ ? undefined
+ : { sources, snapshot },
+ );
+ if (reconciliation.kind === 'committed') {
+ if (plan) {
+ await holdCommittedImpact(
+ 'delete',
+ plan,
+ () => settlement.gone(before.id, reconciliation.value),
+ );
+ } else {
+ dispatchManageStage({ type: 'settled' });
+ await settlement.gone(before.id, reconciliation.value);
+ }
+ return;
+ }
+ settlement.release();
+ dispatchManageStage({
+ type: 'fail_delete',
+ plan,
+ forced: plan !== null,
+ retryRead: reconciliation.kind === 'unread',
+ before,
+ });
+ };
+ const submitEdit = (draft: SourceEditDraft, patch: SourcePatch, plan: ManageGuardPlan | null) => {
+ if (busy) return Promise.resolve();
+ const forced = plan !== null;
+ dispatchManageStage({
+ type: 'submit_edit',
+ draft,
+ patch,
+ plan,
+ surface: forced ? 'guard' : 'edit',
+ });
+ setBusy(true);
+ return trackMutation(async (latest, settlement) => {
+ try {
+ const answer = await modelsApi.patchSource(
+ latest.id,
+ plan ? { ...patch, ...confirmGuardPlan(plan) } : patch,
+ );
+ const impact = committedPlan(answer.removed_hops, answer.interrupted);
+ if (impact) await holdCommittedImpact('edit', impact, () => settlement.source(answer.source));
+ else {
+ dispatchManageStage({ type: 'settled' });
+ await settlement.source(answer.source);
+ }
+ } catch (error) {
+ const failure = apiFailure(error);
+ if (failure?.code === 'source_not_found') {
+ dispatchManageStage({ type: 'settled' });
+ await settlement.gone(latest.id);
+ } else if (classifyModelHubFailure(failure) === 'inconclusive') {
+ await reconcileEditWrite(latest, draft, patch, plan, settlement);
+ } else {
+ const refusal = guardedFailure(error);
+ if (refusal) {
+ dispatchManageStage({ type: 'guard_edit', draft, patch, plan: refusal });
+ settlement.release();
+ } else {
+ dispatchManageStage({
+ type: 'fail_edit',
+ draft,
+ patch,
+ plan,
+ forced,
+ retryRead: false,
+ before: latest,
+ });
+ settlement.release();
+ }
+ }
+ }
+ }).finally(() => setBusy(false));
+ };
+ const submitDelete = (plan: ManageGuardPlan | null) => {
+ if (busy) return Promise.resolve();
+ const forced = plan !== null;
+ dispatchManageStage({ type: 'submit_delete', plan });
+ setBusy(true);
+ return trackMutation(async (latest, settlement) => {
+ try {
+ const answer = await modelsApi.deleteSource(
+ latest.id,
+ plan ? confirmGuardPlan(plan) : undefined,
+ );
+ const impact = committedPlan(answer.removed_hops, answer.interrupted);
+ if (impact) await holdCommittedImpact('delete', impact, () => settlement.gone(latest.id));
+ else {
+ dispatchManageStage({ type: 'settled' });
+ await settlement.gone(latest.id);
+ }
+ } catch (error) {
+ const failure = apiFailure(error);
+ if (failure?.code === 'source_not_found') {
+ dispatchManageStage({ type: 'settled' });
+ await settlement.gone(latest.id);
+ } else if (classifyModelHubFailure(failure) === 'inconclusive') {
+ await reconcileDeleteWrite(latest, plan, settlement);
+ } else {
+ const refusal = guardedFailure(error);
+ if (refusal) {
+ dispatchManageStage({ type: 'guard_delete', plan: refusal });
+ settlement.release();
+ } else {
+ dispatchManageStage({ type: 'fail_delete', plan, forced, retryRead: false, before: latest });
+ settlement.release();
+ }
+ }
+ }
+ }).finally(() => setBusy(false));
+ };
+ const retryEditRead = (failed: Extract<ManageStage, { kind: 'edit_failed' }>) => {
+ if (busy) return Promise.resolve();
+ dispatchManageStage({ type: 'retry' });
+ setBusy(true);
+ return trackMutation(async (_latest, settlement) => {
+ await reconcileEditWrite(
+ failed.before,
+ failed.draft,
+ failed.patch,
+ failed.plan,
+ settlement,
+ );
+ }).finally(() => setBusy(false));
+ };
+ const retryDeleteRead = (failed: Extract<ManageStage, { kind: 'delete_failed' }>) => {
+ if (busy) return Promise.resolve();
+ dispatchManageStage({ type: 'retry' });
+ setBusy(true);
+ return trackMutation(async (_latest, settlement) => {
+ await reconcileDeleteWrite(failed.before, failed.plan, settlement);
+ }).finally(() => setBusy(false));
+ };
+ const submitEditDialog = () => {
+ if (!editDraft || !editAssessment.valid || !editAssessment.patch) return;
+ if (manageStage.kind === 'edit_failed' && manageStage.retryRead) {
+ void retryEditRead(manageStage);
+ return;
+ }
+ const retryPlan = manageStage.kind === 'edit_failed' && manageStage.forced
+ ? manageStage.plan
+ : null;
+ void submitEdit(editDraft, editAssessment.patch, retryPlan);
+ };
+ const retryDelete = () => {
+ if (manageStage.kind !== 'delete_failed') return;
+ if (manageStage.retryRead) {
+ void retryDeleteRead(manageStage);
+ return;
+ }
+ void submitDelete(manageStage.forced ? manageStage.plan : null);
+ };
+ const cancelManage = () => {
+ if (busy) return;
+ dispatchManageStage({ type: 'cancel' });
+ };
+ const dismissUnresolvedManage = () => {
+ if (busy) return;
+ dispatchManageStage({ type: 'dismiss_unresolved' });
+ };
+ const completeManageImpact = () => {
+ if (busy || (
+ manageStage.kind !== 'committed_edit_impact'
+ && manageStage.kind !== 'committed_delete_impact'
+ )) return;
+ const complete = manageStage.complete;
+ setBusy(true);
+ void complete()
+ .then((verdict) => dispatchManageStage({ type: 'land', verdict }))
+ .catch(() => dispatchManageStage({ type: 'land', verdict: 'degraded' }))
+ .finally(() => setBusy(false));
+ };
+ const editManageDraft = (draft: SourceEditDraft) => {
+ dispatchManageStage({ type: 'edit_draft', draft });
+ };
+ const confirmManage = () => {
+ if (manageStage.kind === 'confirming_edit') {
+ void submitEdit(manageStage.draft, manageStage.patch, manageStage.plan);
+ }
+ if (manageStage.kind === 'confirming_delete') void submitDelete(manageStage.plan);
+ };
const confirmGuard = () => {
if (!guard) return;
- const confirmation = confirmGuardPlan(guard);
- if (guard.kind === 'refetch') void refetch(confirmation);
- else void remove(guard.model, confirmation);
+ if (guard.kind === 'refetch') void refetch(confirmGuardPlan(guard.plan));
+ if (guard.kind === 'removeModel') void remove(guard.model, confirmGuardPlan(guard.plan));
};
const adoptedBackends = [...new Set((source.adopted_by ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];
const state = sourceStatePresentation(source.state, 'detail', i18n.language, now, {
@@ -412,6 +754,23 @@ export const SourceDetailPanel: React.FC<{
// not a special case that can fall out of destination-completeness checks.
const repair = repairAction(source);
const repairDestination = repair ? REPAIR_DESTINATION[repair] : null;
+ const editDialogOpen = manageStage.kind === 'editing'
+ || manageStage.kind === 'edit_failed'
+ || (manageStage.kind === 'submitting_edit' && manageStage.surface === 'edit');
+ const manageGuardOpen = manageStage.kind === 'confirming_edit'
+ || manageStage.kind === 'confirming_delete'
+ || manageStage.kind === 'submitting_delete'
+ || (manageStage.kind === 'submitting_edit' && manageStage.surface === 'guard')
+ || manageStage.kind === 'committed_edit_impact'
+ || manageStage.kind === 'committed_delete_impact';
+ const manageImpact = manageStage.kind === 'committed_edit_impact'
+ || manageStage.kind === 'committed_delete_impact'
+ ? manageStage
+ : null;
+ const manageUnresolved = (manageStage.kind === 'edit_failed' || manageStage.kind === 'delete_failed')
+ && manageStage.retryRead;
+ const managePlan = 'plan' in manageStage ? manageStage.plan : null;
+ const manageCopyKind = manageStage.kind.includes('edit') ? 'editSource' : 'deleteSource';
return (
<div className="model-hub-source-detail">
@@ -430,11 +789,13 @@ export const SourceDetailPanel: React.FC<{
{repairDestination === 'replace_key_dialog' && <Button size="sm" className="model-hub-source-action" data-repair-kind={repair} data-repair-destination={repairDestination} disabled={busy} onClick={() => setReplacingKey(true)}>{t(REPAIR_LABEL_KEY.replace_key)}</Button>}
{source.supply_channel === 'hub' && <Button variant="outline" size="sm" className="model-hub-source-action" data-repair-kind={repairDestination === 'refetch_button' ? repair : undefined} data-repair-destination={repairDestination === 'refetch_button' ? repairDestination : undefined} disabled={busy} onClick={() => void refetch()}>{busy ? <Loader2 className="animate-spin" /> : <RefreshCw />}{t('settings.models.sourceDetail.action.refetch')}</Button>}
{source.kind === 'api_key' && <Button variant="secondary" size="sm" className="model-hub-source-action model-hub-ink-mint" disabled={busy || manualDraft !== null} onClick={() => setManualDraft({ modelId: '', tiers: [], failed: false, retryRead: false })}><Plus />{t('settings.models.sourceDetail.action.addModel')}</Button>}
+ <SourceManageMenu source={source} busy={busy || manageStage.kind !== 'idle'} onEdit={beginEdit} onDelete={beginDelete} />
</div>
</section>
{result && result.removed.length > 0 && <p className="model-hub-status-gold rounded-lg border px-3 py-2 text-[11.5px]">{t('settings.models.sourceDetail.refetch.removed', { count: result.removed.length, models: result.removed.join(', ') })}</p>}
{result && result.added.length === 0 && result.removed.length === 0 && <p className="model-hub-status-mint rounded-lg border px-3 py-2 text-[11.5px]">{t('settings.models.sourceDetail.refetch.unchangedOnly')}</p>}
{refetchFailed && <p className="rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2 text-[11.5px] text-destructive-ink">{t('settings.models.sourceDetail.fail.refetch')}</p>}
+ {manageStage.kind === 'delete_failed' && <p data-manage-failure="delete" data-manage-retry-read={String(manageStage.retryRead)} className="rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2 text-[11.5px] text-destructive-ink">{t(manageStage.retryRead ? 'settings.models.sourceDetail.fail.verifyDeleteSource' : 'settings.models.sourceDetail.fail.deleteSource')} <button type="button" disabled={busy} onClick={retryDelete} className="font-semibold underline underline-offset-2">{t('settings.models.sourceDetail.retry')}</button> <button type="button" disabled={busy} onClick={manageStage.retryRead ? dismissUnresolvedManage : cancelManage} className="font-semibold underline underline-offset-2">{t(manageStage.retryRead ? 'settings.models.sourceDetail.dismissUnverified' : 'common.cancel')}</button></p>}
<section className="model-hub-source-table overflow-hidden border border-border bg-surface">
<div className="model-hub-source-table-head hidden border-b border-border font-semibold md:grid">
<span>{t('settings.models.sourceDetail.col.id')}</span><span>{t('settings.models.sourceDetail.col.entry')}</span><span className="flex items-center gap-1">{t('settings.models.sourceDetail.col.tiers')}<Info className="size-3" /></span><span />
@@ -516,19 +877,83 @@ export const SourceDetailPanel: React.FC<{
trackMutation={trackMutation}
onClose={() => setReplacingKey(false)}
/>
- <DialogPrimitive.Root open={guard !== null} onOpenChange={(open) => !open && !busy && setGuard(null)}>
+ <DialogPrimitive.Root
+ open={editDialogOpen}
+ onOpenChange={(open) => { if (!open) cancelManage(); }}
+ >
+ <DialogPrimitive.Portal>
+ <DialogPrimitive.Overlay className="model-hub-guard-overlay fixed inset-0 z-50" />
+ <DialogPrimitive.Content
+ className="model-hub-guard-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-y-auto border border-border-strong bg-surface outline-none"
+ onEscapeKeyDown={(event) => { if (busy) event.preventDefault(); }}
+ onPointerDownOutside={(event) => { if (busy) event.preventDefault(); }}
+ >
+ <form className="contents" onSubmit={(event) => {
+ event.preventDefault();
+ submitEditDialog();
+ }}>
+ <header className="model-hub-guard-head">
+ <div className="flex items-center justify-between gap-3">
+ <DialogPrimitive.Title className="model-hub-guard-title text-foreground">{t('settings.models.sourceDetail.edit.title', { source: source.display_name })}</DialogPrimitive.Title>
+ <DialogPrimitive.Close asChild><Button type="button" variant="ghost" size="icon" className="model-hub-guard-close" disabled={busy || manageUnresolved} aria-label={t('settings.models.sourceDetail.edit.cancel')} title={t('settings.models.sourceDetail.edit.cancel')}><X aria-hidden /></Button></DialogPrimitive.Close>
+ </div>
+ <DialogPrimitive.Description className="model-hub-guard-subtitle">{t(`settings.models.sourceKind.${source.kind}`)} · {t(PROTOCOL_COPY_KEYS[source.protocol])}</DialogPrimitive.Description>
+ </header>
+ {editDraft && <div className="model-hub-guard-body">
+ <Field label={t('settings.models.sourceDetail.edit.name')}>
+ {(id) => <Input id={id} autoFocus value={editDraft.displayName} disabled={busy} aria-invalid={editAssessment.reason?.startsWith('displayName') || undefined} onChange={(event) => editManageDraft({ ...editDraft, displayName: event.target.value })} />}
+ </Field>
+ {canEditSourceEndpoint(source) && <Field label={t('settings.models.sourceDetail.edit.baseUrl')} mono>
+ {(id) => <Input id={id} type="text" inputMode="url" autoComplete="url" spellCheck={false} value={editDraft.baseUrl} disabled={busy} aria-invalid={editAssessment.reason?.startsWith('baseUrl') || undefined} className="font-mono" onChange={(event) => editManageDraft({ ...editDraft, baseUrl: event.target.value })} />}
+ </Field>}
+ <p className="model-hub-guard-hint"><Info aria-hidden />{t('settings.models.sourceDetail.edit.hint')}</p>
+ {editAssessment.reason && <p data-source-edit-validation className="text-[11.5px] text-destructive-ink">{t(SOURCE_EDIT_REASON_KEY[editAssessment.reason])}</p>}
+ {manageStage.kind === 'edit_failed' && <p data-manage-failure="edit" data-manage-retry-read={String(manageStage.retryRead)} className="text-[11.5px] text-destructive-ink">{t(manageStage.retryRead ? 'settings.models.sourceDetail.edit.verifyFail' : 'settings.models.sourceDetail.edit.fail')}</p>}
+ </div>}
+ <footer className="model-hub-guard-foot">
+ <Button type="button" variant="outline" className="model-hub-guard-action" onClick={manageUnresolved ? dismissUnresolvedManage : cancelManage} disabled={busy}>{t(manageUnresolved ? 'settings.models.sourceDetail.dismissUnverified' : 'settings.models.sourceDetail.edit.cancel')}</Button>
+ <Button type="submit" className="model-hub-guard-action" disabled={busy || !editAssessment.valid || !editAssessment.patch}>{busy && <Loader2 className="animate-spin" />}{t(busy ? 'settings.models.sourceDetail.edit.saving' : manageStage.kind === 'edit_failed' && manageStage.retryRead ? 'settings.models.sourceDetail.retry' : 'settings.models.sourceDetail.edit.save')}</Button>
+ </footer>
+ </form>
+ </DialogPrimitive.Content>
+ </DialogPrimitive.Portal>
+ </DialogPrimitive.Root>
+ <DialogPrimitive.Root open={guard !== null || manageGuardOpen} onOpenChange={(open) => {
+ if (!open && !busy) {
+ if (manageGuardOpen) cancelManage();
+ else setGuard(null);
+ }
+ }}>
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="model-hub-guard-overlay fixed inset-0 z-50" />
- <DialogPrimitive.Content className="model-hub-guard-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-y-auto border border-border-strong bg-surface outline-none">
+ <DialogPrimitive.Content
+ className="model-hub-guard-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col overflow-y-auto border border-border-strong bg-surface outline-none"
+ onEscapeKeyDown={(event) => { if (busy) event.preventDefault(); }}
+ onPointerDownOutside={(event) => { if (busy) event.preventDefault(); }}
+ >
<header className="model-hub-guard-head">
<div className="flex items-center justify-between gap-3">
- <DialogPrimitive.Title className="model-hub-guard-title text-foreground">{t(`settings.models.guard.title.${guard?.kind === 'remove' ? 'removeModel' : 'refetch'}`, { model: guard?.kind === 'remove' ? guard.model.id : undefined, source: source.display_name })}</DialogPrimitive.Title>
- <DialogPrimitive.Close asChild><Button type="button" variant="ghost" size="icon" className="model-hub-guard-close" disabled={busy} aria-label={t('settings.models.guard.cancel')} title={t('settings.models.guard.cancel')}><X aria-hidden /></Button></DialogPrimitive.Close>
+ <DialogPrimitive.Title className="model-hub-guard-title text-foreground">{manageImpact
+ ? t(`settings.models.sourceDetail.${manageImpact.kind === 'committed_edit_impact' ? 'edit' : 'remove'}.impact.title`)
+ : manageGuardOpen
+ ? t(`settings.models.guard.title.${manageCopyKind}`, { source: source.display_name })
+ : t(`settings.models.guard.title.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`, { model: guard?.kind === 'removeModel' ? guard.model.id : undefined, source: source.display_name })}</DialogPrimitive.Title>
+ <DialogPrimitive.Close asChild><Button type="button" variant="ghost" size="icon" className="model-hub-guard-close" disabled={busy || (manageImpact !== null && !manageImpact.landingFailed)} onClick={manageImpact?.landingFailed ? dismissUnresolvedManage : undefined} aria-label={t(manageImpact?.landingFailed ? 'settings.models.sourceDetail.dismissUnverified' : manageImpact ? `settings.models.sourceDetail.${manageImpact.kind === 'committed_edit_impact' ? 'edit' : 'remove'}.impact.done` : 'settings.models.guard.cancel')} title={t(manageImpact?.landingFailed ? 'settings.models.sourceDetail.dismissUnverified' : manageImpact ? `settings.models.sourceDetail.${manageImpact.kind === 'committed_edit_impact' ? 'edit' : 'remove'}.impact.done` : 'settings.models.guard.cancel')}><X aria-hidden /></Button></DialogPrimitive.Close>
</div>
- <DialogPrimitive.Description className="model-hub-guard-subtitle">{t(`settings.models.guard.subtitle.${guard?.kind === 'remove' ? 'removeModel' : 'refetch'}`)}</DialogPrimitive.Description>
+ <DialogPrimitive.Description className="model-hub-guard-subtitle">{manageImpact
+ ? t(`settings.models.sourceDetail.${manageImpact.kind === 'committed_edit_impact' ? 'edit' : 'remove'}.impact.detail`)
+ : manageGuardOpen
+ ? t(`settings.models.guard.subtitle.${manageCopyKind}`)
+ : t(`settings.models.guard.subtitle.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`)}</DialogPrimitive.Description>
</header>
- {guard && <div className="model-hub-guard-body"><GuardImpact hops={guard.hops} gaps={guard.gaps} /></div>}
- <footer className="model-hub-guard-foot"><Button variant="outline" className="model-hub-guard-action" onClick={() => setGuard(null)} disabled={busy}>{t('settings.models.guard.cancel')}</Button><Button variant="destructive" className="model-hub-guard-action" onClick={confirmGuard} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(`settings.models.guard.confirm.${guard?.kind === 'remove' ? 'removeModel' : 'refetch'}`)}</Button></footer>
+ {manageImpact && <div className="model-hub-guard-body"><GuardImpact hops={manageImpact.plan.hops} gaps={manageImpact.plan.gaps} committed />{manageImpact.landingFailed && <p data-manage-impact-failure className="text-[11.5px] text-destructive-ink">{t('settings.models.sourceDetail.impact.refreshFail')}</p>}</div>}
+ {!manageImpact && manageGuardOpen && managePlan && <div className="model-hub-guard-body"><GuardImpact hops={managePlan.hops} gaps={managePlan.gaps} /></div>}
+ {!manageGuardOpen && guard?.plan && <div className="model-hub-guard-body"><GuardImpact hops={guard.plan.hops} gaps={guard.plan.gaps} /></div>}
+ {manageImpact
+ ? <footer className="model-hub-guard-foot">{manageImpact.landingFailed && <Button type="button" variant="outline" className="model-hub-guard-action" onClick={dismissUnresolvedManage} disabled={busy}>{t('settings.models.sourceDetail.dismissUnverified')}</Button>}<Button className="model-hub-guard-action" onClick={completeManageImpact} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(manageImpact.landingFailed ? 'settings.models.sourceDetail.retry' : `settings.models.sourceDetail.${manageImpact.kind === 'committed_edit_impact' ? 'edit' : 'remove'}.impact.done`)}</Button></footer>
+ : manageGuardOpen
+ ? <footer className="model-hub-guard-foot"><Button variant="outline" className="model-hub-guard-action" onClick={cancelManage} disabled={busy}>{t('settings.models.guard.cancel')}</Button><Button variant="destructive" className="model-hub-guard-action" onClick={confirmManage} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(`settings.models.guard.confirm.${manageCopyKind}`)}</Button></footer>
+ : <footer className="model-hub-guard-foot"><Button variant="outline" className="model-hub-guard-action" onClick={() => setGuard(null)} disabled={busy}>{t('settings.models.guard.cancel')}</Button><Button variant="destructive" className="model-hub-guard-action" onClick={confirmGuard} disabled={busy}>{busy && <Loader2 className="animate-spin" />}{t(`settings.models.guard.confirm.${guard ? GUARD_COPY_KIND[guard.kind] : 'refetch'}`)}</Button></footer>}
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
diff --git a/ui/src/components/settings/models/manage.test.ts b/ui/src/components/settings/models/manage.test.ts
new file mode 100644
index 000000000..bbd07ac1e
--- /dev/null
+++ b/ui/src/components/settings/models/manage.test.ts
@@ -0,0 +1,269 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+import en from '../../../i18n/en.json';
+import zh from '../../../i18n/zh.json';
+import {
+ assessSourceEdit,
+ canEditSourceEndpoint,
+ holdsCommittedImpact,
+ manageActions,
+ MANAGE_DESTINATION,
+ MANAGE_LABEL_KEY,
+ MANAGE_STAGE_CANCEL,
+ MANAGE_STAGE_DISMISS_UNRESOLVED,
+ MANAGE_STAGE_EDIT_DRAFT,
+ MANAGE_STAGE_FAILURE_SURFACE,
+ MANAGE_STAGE_KINDS,
+ MANAGE_STAGE_LANDING,
+ MANAGE_STAGE_RETRY,
+ SOURCE_EDIT_REASON_KEY,
+ transitionManageStage,
+} from './manage';
+import type { ManageStage } from './manage';
+import { SOURCE_PROTOCOLS } from './types';
+import type { Source, SourceProtocol } from './types';
+
+type ValidationCase = {
+ id: string;
+ value: string;
+ valid: boolean;
+ normalized?: string;
+ reason?: string;
+};
+type BaseUrlValidationCase = ValidationCase & { client_rejects: boolean };
+type EmptyTargetCase = {
+ id: string;
+ vendor: string;
+ protocol: SourceProtocol;
+ server_valid: boolean;
+};
+
+const validationFixture = JSON.parse(readFileSync(join(
+ process.cwd(),
+ '../tests/fixtures/model_hub_source_edit_validation.json',
+), 'utf8')) as {
+ display_names: ValidationCase[];
+ base_urls: BaseUrlValidationCase[];
+ empty_targets: EmptyTargetCase[];
+};
+
+const source = (over: Partial<Source> = {}): Source => ({
+ id: 'src_manage',
+ kind: 'api_key',
+ vendor: 'anthropic',
+ display_name: 'Production key',
+ protocol: 'anthropic',
+ base_url: 'https://relay.example/v1',
+ supply_channel: 'hub',
+ billing: 'metered',
+ credential_ref: 'cred_manage',
+ state: { status: 'active' },
+ last_discovered_at: null,
+ models: [],
+ ...over,
+});
+
+const translated = (bundle: unknown, key: string): unknown =>
+ key.split('.').reduce<unknown>((node, part) => {
+ if (!node || typeof node !== 'object') return undefined;
+ return (node as Record<string, unknown>)[part];
+ }, bundle);
+
+describe('source management capabilities', () => {
+ it('keeps management available independently of repair state', () => {
+ expect(manageActions()).toEqual(Object.keys(MANAGE_DESTINATION));
+ });
+
+ it('limits endpoint ownership to Avibe-held API-key sources', () => {
+ expect(canEditSourceEndpoint(source())).toBe(true);
+ expect(canEditSourceEndpoint(source({ kind: 'subscription' }))).toBe(false);
+ expect(canEditSourceEndpoint(source({ supply_channel: 'native_cli' }))).toBe(false);
+ expect(canEditSourceEndpoint(source({ credential_ref: null }))).toBe(false);
+ });
+
+ it('defines every user event and visible-failure owner over every stage', () => {
+ for (const record of [
+ MANAGE_STAGE_CANCEL,
+ MANAGE_STAGE_RETRY,
+ MANAGE_STAGE_EDIT_DRAFT,
+ MANAGE_STAGE_DISMISS_UNRESOLVED,
+ MANAGE_STAGE_LANDING,
+ ]) {
+ expect(new Set(Object.keys(record))).toEqual(new Set(MANAGE_STAGE_KINDS));
+ for (const kind of MANAGE_STAGE_KINDS) expect(record[kind]).toEqual(expect.any(Function));
+ }
+ expect(new Set(Object.keys(MANAGE_STAGE_FAILURE_SURFACE))).toEqual(new Set(MANAGE_STAGE_KINDS));
+ for (const kind of MANAGE_STAGE_KINDS) expect(MANAGE_STAGE_FAILURE_SURFACE[kind]).toEqual(expect.any(String));
+ });
+
+ it('keeps unresolved evidence fenced under every incidental edit and dismissal event', () => {
+ type UnresolvedStage = Extract<ManageStage, { retryRead: boolean }>;
+ const before = source();
+ const plan = { hops: [], gaps: [] };
+ const unresolved = {
+ edit_failed: {
+ kind: 'edit_failed',
+ draft: { displayName: 'Pending edit', baseUrl: before.base_url ?? '' },
+ patch: { display_name: 'Pending edit' },
+ plan,
+ forced: true,
+ retryRead: true,
+ before,
+ },
+ delete_failed: {
+ kind: 'delete_failed',
+ plan,
+ forced: true,
+ retryRead: true,
+ before,
+ },
+ } satisfies { [Kind in UnresolvedStage['kind']]: Extract<UnresolvedStage, { kind: Kind }> };
+ const editedDraft = { displayName: 'Typing resolves nothing', baseUrl: 'https://other.example/v1' };
+
+ for (const stage of Object.values(unresolved)) {
+ for (const event of [{ type: 'cancel' }, { type: 'edit_draft', draft: editedDraft }] as const) {
+ const next = transitionManageStage(stage, event);
+ expect(next.kind, `${stage.kind}:${event.type}`).toBe(stage.kind);
+ expect('retryRead' in next && next.retryRead, `${stage.kind}:${event.type}`).toBe(true);
+ expect('before' in next && next.before, `${stage.kind}:${event.type}`).toBe(before);
+ expect('plan' in next && next.plan, `${stage.kind}:${event.type}`).toBe(plan);
+ expect('forced' in next && next.forced, `${stage.kind}:${event.type}`).toBe(true);
+ }
+ }
+ });
+
+ it('earns exit from every committed impact stage from landing evidence', () => {
+ const plan = { hops: [], gaps: [] };
+ const complete = async () => 'landed' as const;
+ const committed = {
+ committed_edit_impact: { kind: 'committed_edit_impact', plan, complete, landingFailed: false },
+ committed_delete_impact: { kind: 'committed_delete_impact', plan, complete, landingFailed: false },
+ } satisfies {
+ [Kind in Extract<ManageStage, { landingFailed: boolean }>['kind']]: Extract<ManageStage, { kind: Kind }>
+ };
+
+ for (const stage of Object.values(committed)) {
+ const degraded = transitionManageStage(stage, { type: 'land', verdict: 'degraded' });
+ expect(degraded.kind).toBe(stage.kind);
+ expect('plan' in degraded && degraded.plan).toBe(plan);
+ expect('landingFailed' in degraded && degraded.landingFailed).toBe(true);
+ expect(transitionManageStage(stage, { type: 'dismiss_unresolved' })).toBe(stage);
+ expect(transitionManageStage(degraded, { type: 'dismiss_unresolved' })).toEqual({ kind: 'idle' });
+ expect(transitionManageStage(degraded, { type: 'land', verdict: 'landed' })).toEqual({ kind: 'idle' });
+ }
+ });
+
+ it('keeps at least one enabled exit reachable from every active stage', () => {
+ const before = source();
+ const draft = { displayName: before.display_name, baseUrl: before.base_url ?? '' };
+ const patch = { display_name: before.display_name };
+ const plan = { hops: [], gaps: [] };
+ const complete = async () => 'landed' as const;
+ const stages = {
+ idle: { kind: 'idle' },
+ editing: { kind: 'editing', draft },
+ submitting_edit: { kind: 'submitting_edit', draft, patch, plan: null, forced: false, surface: 'edit' },
+ confirming_edit: { kind: 'confirming_edit', draft, patch, plan },
+ edit_failed: { kind: 'edit_failed', draft, patch, plan, forced: true, retryRead: true, before },
+ confirming_delete: { kind: 'confirming_delete', plan },
+ submitting_delete: { kind: 'submitting_delete', plan, forced: true },
+ delete_failed: { kind: 'delete_failed', plan, forced: true, retryRead: true, before },
+ committed_edit_impact: { kind: 'committed_edit_impact', plan, complete, landingFailed: true },
+ committed_delete_impact: { kind: 'committed_delete_impact', plan, complete, landingFailed: true },
+ } satisfies { [Kind in ManageStage['kind']]: Extract<ManageStage, { kind: Kind }> };
+ const exitEvents = [
+ { type: 'cancel' },
+ { type: 'dismiss_unresolved' },
+ { type: 'settled' },
+ { type: 'land', verdict: 'landed' },
+ ] as const;
+
+ expect(new Set(Object.keys(stages))).toEqual(new Set(MANAGE_STAGE_KINDS));
+ for (const stage of Object.values(stages)) {
+ expect(holdsCommittedImpact(stage), `${stage.kind}:holds committed impact`).toBe('complete' in stage);
+ if (stage.kind === 'idle') continue;
+ expect(
+ exitEvents.some((event) => transitionManageStage(stage, event).kind !== stage.kind),
+ stage.kind,
+ ).toBe(true);
+ }
+ });
+
+ it('trims metadata but leaves endpoint normalization to the server', () => {
+ expect(assessSourceEdit(source(), {
+ displayName: ' Relay key ',
+ baseUrl: 'HTTPS://relay.example/v2/',
+ })).toEqual({
+ valid: true,
+ patch: { display_name: 'Relay key', base_url: 'HTTPS://relay.example/v2/' },
+ reason: null,
+ });
+ });
+
+ it('holds the same display-name contract fixture as the server', () => {
+ for (const item of validationFixture.display_names) {
+ const assessment = assessSourceEdit(source(), {
+ displayName: item.value,
+ baseUrl: source().base_url ?? '',
+ });
+ expect(assessment.valid, item.id).toBe(item.valid);
+ expect(assessment.reason, item.id).toBe(item.reason ?? null);
+ }
+ });
+
+ it('rejects an endpoint if and only if the shared row carries credential material', () => {
+ for (const item of validationFixture.base_urls) {
+ const assessment = assessSourceEdit(source(), {
+ displayName: source().display_name,
+ baseUrl: item.value,
+ });
+ expect(assessment.valid, item.id).toBe(!item.client_rejects);
+ expect(assessment.reason, item.id).toBe(item.client_rejects ? 'baseUrlCredential' : null);
+ if (!item.client_rejects) expect(assessment.patch?.base_url, item.id).toBe(item.value.trim());
+ }
+ });
+
+ it('never adds an endpoint patch to a display-name-only edit', () => {
+ for (const item of validationFixture.base_urls.filter((candidate) => candidate.valid)) {
+ const stored = item.normalized ?? item.value.trim();
+ const assessment = assessSourceEdit(source({ base_url: stored }), {
+ displayName: 'Renamed source',
+ baseUrl: stored,
+ });
+ expect(assessment.valid, item.id).toBe(true);
+ expect(assessment.patch, item.id).toEqual({ display_name: 'Renamed source' });
+ expect(assessment.patch, item.id).not.toHaveProperty('base_url');
+ }
+ });
+
+ it('holds no vendor or protocol policy for an emptied endpoint', () => {
+ const vendors = new Set(validationFixture.empty_targets.map((item) => item.vendor));
+ const pairs = new Set(validationFixture.empty_targets.map((item) => `${item.vendor}:${item.protocol}`));
+ expect(pairs.size).toBe(vendors.size * SOURCE_PROTOCOLS.length);
+ for (const vendor of vendors) {
+ for (const protocol of SOURCE_PROTOCOLS) expect(pairs.has(`${vendor}:${protocol}`)).toBe(true);
+ }
+
+ for (const item of validationFixture.empty_targets) {
+ const assessment = assessSourceEdit(source({ vendor: item.vendor, protocol: item.protocol }), {
+ displayName: source().display_name,
+ baseUrl: '',
+ });
+ expect(assessment, item.id).toEqual({
+ valid: true,
+ patch: { base_url: null },
+ reason: null,
+ });
+ }
+ });
+
+ it.each(Object.entries(MANAGE_LABEL_KEY))('translates the %s action in both locales', (_kind, key) => {
+ for (const bundle of [en, zh]) expect(typeof translated(bundle, key)).toBe('string');
+ });
+
+ it.each(Object.entries(SOURCE_EDIT_REASON_KEY))('translates the %s validation reason in both locales', (_reason, key) => {
+ for (const bundle of [en, zh]) expect(typeof translated(bundle, key)).toBe('string');
+ });
+});
diff --git a/ui/src/components/settings/models/manage.ts b/ui/src/components/settings/models/manage.ts
new file mode 100644
index 000000000..9ee16cf68
--- /dev/null
+++ b/ui/src/components/settings/models/manage.ts
@@ -0,0 +1,376 @@
+import type { RouteHopRef, Source, SourcePatch, SupplyGap } from './types';
+import { SOURCE_DISPLAY_NAME_MAX_LENGTH } from './types';
+import type { SourceMutationLanding } from './mutationSettlement';
+import { optionalTrimmedTextWithin } from './validation';
+
+/** Management changes a valid Source; repair restores a blocked one. */
+export type ManageKind = 'edit_source' | 'delete_source';
+
+export type ManageDestination = 'edit_source_dialog' | 'delete_source_guard';
+
+export const MANAGE_DESTINATION: Record<ManageKind, ManageDestination> = {
+ edit_source: 'edit_source_dialog',
+ delete_source: 'delete_source_guard',
+};
+
+export const MANAGE_LABEL_KEY: Record<ManageKind, string> = {
+ edit_source: 'settings.models.sourceDetail.manage.edit',
+ delete_source: 'settings.models.sourceDetail.manage.remove',
+};
+
+/** Every persisted Source has the same two management actions. */
+export const manageActions = (): ManageKind[] => Object.keys(MANAGE_DESTINATION) as ManageKind[];
+
+/** Only Avibe-held API-key sources own an endpoint that this editor can change. */
+export const canEditSourceEndpoint = (source: Source): boolean =>
+ source.kind === 'api_key' && source.supply_channel === 'hub' && Boolean(source.credential_ref);
+
+export type SourceEditDraft = {
+ displayName: string;
+ baseUrl: string;
+};
+
+export type ManageGuardPlan = { hops: RouteHopRef[]; gaps: SupplyGap[] };
+
+export const MANAGE_STAGE_KINDS = [
+ 'idle',
+ 'editing',
+ 'submitting_edit',
+ 'confirming_edit',
+ 'edit_failed',
+ 'confirming_delete',
+ 'submitting_delete',
+ 'delete_failed',
+ 'committed_edit_impact',
+ 'committed_delete_impact',
+] as const;
+export type ManageStageKind = (typeof MANAGE_STAGE_KINDS)[number];
+
+export type ManageStage =
+ | { kind: 'idle' }
+ | { kind: 'editing'; draft: SourceEditDraft }
+ | { kind: 'submitting_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; forced: boolean; surface: 'edit' | 'guard' }
+ | { kind: 'confirming_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan }
+ | { kind: 'edit_failed'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
+ | { kind: 'confirming_delete'; plan: ManageGuardPlan | null }
+ | { kind: 'submitting_delete'; plan: ManageGuardPlan | null; forced: boolean }
+ | { kind: 'delete_failed'; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
+ | { kind: 'committed_edit_impact'; plan: ManageGuardPlan; complete: () => Promise<SourceMutationLanding>; landingFailed: boolean }
+ | { kind: 'committed_delete_impact'; plan: ManageGuardPlan; complete: () => Promise<SourceMutationLanding>; landingFailed: boolean };
+
+export const holdsCommittedImpact = (
+ stage: ManageStage,
+): stage is Extract<ManageStage, { landingFailed: boolean }> =>
+ stage.kind === 'committed_edit_impact' || stage.kind === 'committed_delete_impact';
+
+export type ManageFailureSurface = 'none' | 'edit_dialog' | 'guard_dialog' | 'delete_inline' | 'committed_dialog';
+
+type ManageStageTransition<Event> = {
+ [Kind in ManageStageKind]: (
+ stage: Extract<ManageStage, { kind: Kind }>,
+ event: Event,
+ ) => ManageStage;
+};
+
+type CancelManageStage = { type: 'cancel' };
+type RetryManageStage = { type: 'retry' };
+type EditManageDraft = { type: 'edit_draft'; draft: SourceEditDraft };
+type DismissUnresolvedManageStage = { type: 'dismiss_unresolved' };
+type LandManageStage = { type: 'land'; verdict: SourceMutationLanding };
+
+const keepManageStage = <Stage extends ManageStage>(stage: Stage): Stage => stage;
+const idleManageStage = (): ManageStage => ({ kind: 'idle' });
+
+/** Total event authority: a new stage cannot omit any user-driven transition. */
+export const MANAGE_STAGE_CANCEL = {
+ idle: keepManageStage,
+ editing: idleManageStage,
+ submitting_edit: keepManageStage,
+ confirming_edit: (stage) => ({ kind: 'editing', draft: stage.draft }),
+ edit_failed: (stage) => stage.retryRead ? stage : idleManageStage(),
+ confirming_delete: idleManageStage,
+ submitting_delete: keepManageStage,
+ delete_failed: (stage) => stage.retryRead ? stage : idleManageStage(),
+ committed_edit_impact: keepManageStage,
+ committed_delete_impact: keepManageStage,
+} satisfies ManageStageTransition<CancelManageStage>;
+
+export const MANAGE_STAGE_RETRY = {
+ idle: keepManageStage,
+ editing: keepManageStage,
+ submitting_edit: keepManageStage,
+ confirming_edit: (stage) => ({
+ kind: 'submitting_edit',
+ draft: stage.draft,
+ patch: stage.patch,
+ plan: stage.plan,
+ forced: true,
+ surface: 'guard',
+ }),
+ edit_failed: (stage) => ({
+ kind: 'submitting_edit',
+ draft: stage.draft,
+ patch: stage.patch,
+ plan: stage.plan,
+ forced: stage.forced,
+ surface: 'edit',
+ }),
+ confirming_delete: (stage) => ({
+ kind: 'submitting_delete',
+ plan: stage.plan,
+ forced: stage.plan !== null,
+ }),
+ submitting_delete: keepManageStage,
+ delete_failed: (stage) => ({
+ kind: 'submitting_delete',
+ plan: stage.plan,
+ forced: stage.forced,
+ }),
+ committed_edit_impact: keepManageStage,
+ committed_delete_impact: keepManageStage,
+} satisfies ManageStageTransition<RetryManageStage>;
+
+export const MANAGE_STAGE_EDIT_DRAFT = {
+ idle: keepManageStage,
+ editing: (stage, event) => ({ ...stage, draft: event.draft }),
+ submitting_edit: keepManageStage,
+ confirming_edit: keepManageStage,
+ edit_failed: (stage, event) => ({ ...stage, draft: event.draft }),
+ confirming_delete: keepManageStage,
+ submitting_delete: keepManageStage,
+ delete_failed: keepManageStage,
+ committed_edit_impact: keepManageStage,
+ committed_delete_impact: keepManageStage,
+} satisfies ManageStageTransition<EditManageDraft>;
+
+export const MANAGE_STAGE_DISMISS_UNRESOLVED = {
+ idle: keepManageStage,
+ editing: keepManageStage,
+ submitting_edit: keepManageStage,
+ confirming_edit: keepManageStage,
+ edit_failed: (stage) => stage.retryRead ? idleManageStage() : stage,
+ confirming_delete: keepManageStage,
+ submitting_delete: keepManageStage,
+ delete_failed: (stage) => stage.retryRead ? idleManageStage() : stage,
+ committed_edit_impact: (stage) => stage.landingFailed ? idleManageStage() : stage,
+ committed_delete_impact: (stage) => stage.landingFailed ? idleManageStage() : stage,
+} satisfies ManageStageTransition<DismissUnresolvedManageStage>;
+
+export const MANAGE_STAGE_LANDING = {
+ idle: keepManageStage,
+ editing: keepManageStage,
+ submitting_edit: keepManageStage,
+ confirming_edit: keepManageStage,
+ edit_failed: keepManageStage,
+ confirming_delete: keepManageStage,
+ submitting_delete: keepManageStage,
+ delete_failed: keepManageStage,
+ committed_edit_impact: (stage, event) => event.verdict === 'landed'
+ ? idleManageStage()
+ : { ...stage, landingFailed: true },
+ committed_delete_impact: (stage, event) => event.verdict === 'landed'
+ ? idleManageStage()
+ : { ...stage, landingFailed: true },
+} satisfies ManageStageTransition<LandManageStage>;
+
+export type ManageStageEvent =
+ | { type: 'begin_edit'; draft: SourceEditDraft }
+ | { type: 'begin_delete' }
+ | { type: 'submit_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; surface: 'edit' | 'guard' }
+ | { type: 'submit_delete'; plan: ManageGuardPlan | null }
+ | { type: 'guard_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan }
+ | { type: 'guard_delete'; plan: ManageGuardPlan }
+ | { type: 'fail_edit'; draft: SourceEditDraft; patch: SourcePatch; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
+ | { type: 'fail_delete'; plan: ManageGuardPlan | null; forced: boolean; retryRead: boolean; before: Source }
+ | { type: 'commit_impact'; action: 'edit' | 'delete'; plan: ManageGuardPlan; complete: () => Promise<SourceMutationLanding> }
+ | { type: 'settled' }
+ | CancelManageStage
+ | RetryManageStage
+ | EditManageDraft
+ | DismissUnresolvedManageStage
+ | LandManageStage;
+
+const applyManageStageTransition = <Event,>(
+ transitions: ManageStageTransition<Event>,
+ stage: ManageStage,
+ event: Event,
+): ManageStage => {
+ const transition = transitions[stage.kind] as (current: ManageStage, currentEvent: Event) => ManageStage;
+ return transition(stage, event);
+};
+
+export const transitionManageStage = (stage: ManageStage, event: ManageStageEvent): ManageStage => {
+ switch (event.type) {
+ case 'begin_edit': return { kind: 'editing', draft: event.draft };
+ case 'begin_delete': return { kind: 'confirming_delete', plan: null };
+ case 'submit_edit': return {
+ kind: 'submitting_edit',
+ draft: event.draft,
+ patch: event.patch,
+ plan: event.plan,
+ forced: event.plan !== null,
+ surface: event.surface,
+ };
+ case 'submit_delete': return {
+ kind: 'submitting_delete',
+ plan: event.plan,
+ forced: event.plan !== null,
+ };
+ case 'guard_edit': return {
+ kind: 'confirming_edit',
+ draft: event.draft,
+ patch: event.patch,
+ plan: event.plan,
+ };
+ case 'guard_delete': return { kind: 'confirming_delete', plan: event.plan };
+ case 'fail_edit': return {
+ kind: 'edit_failed',
+ draft: event.draft,
+ patch: event.patch,
+ plan: event.plan,
+ forced: event.forced,
+ retryRead: event.retryRead,
+ before: event.before,
+ };
+ case 'fail_delete': return {
+ kind: 'delete_failed',
+ plan: event.plan,
+ forced: event.forced,
+ retryRead: event.retryRead,
+ before: event.before,
+ };
+ case 'commit_impact': return event.action === 'edit'
+ ? { kind: 'committed_edit_impact', plan: event.plan, complete: event.complete, landingFailed: false }
+ : { kind: 'committed_delete_impact', plan: event.plan, complete: event.complete, landingFailed: false };
+ case 'settled': return idleManageStage();
+ case 'cancel': return applyManageStageTransition(MANAGE_STAGE_CANCEL, stage, event);
+ case 'retry': return applyManageStageTransition(MANAGE_STAGE_RETRY, stage, event);
+ case 'edit_draft': return applyManageStageTransition(MANAGE_STAGE_EDIT_DRAFT, stage, event);
+ case 'dismiss_unresolved': return applyManageStageTransition(MANAGE_STAGE_DISMISS_UNRESOLVED, stage, event);
+ case 'land': return applyManageStageTransition(MANAGE_STAGE_LANDING, stage, event);
+ }
+};
+
+export const MANAGE_STAGE_FAILURE_SURFACE: Record<ManageStageKind, ManageFailureSurface> = {
+ idle: 'none',
+ editing: 'edit_dialog',
+ submitting_edit: 'edit_dialog',
+ confirming_edit: 'guard_dialog',
+ edit_failed: 'edit_dialog',
+ confirming_delete: 'guard_dialog',
+ submitting_delete: 'delete_inline',
+ delete_failed: 'delete_inline',
+ committed_edit_impact: 'committed_dialog',
+ committed_delete_impact: 'committed_dialog',
+};
+
+export type SourceEditInvalidReason =
+ | 'displayNameRequired'
+ | 'displayNameTooLong'
+ | 'displayNameCredential'
+ | 'baseUrlCredential';
+
+export const SOURCE_EDIT_REASON_KEY: Record<SourceEditInvalidReason, string> = {
+ displayNameRequired: 'settings.models.sourceDetail.edit.validation.displayNameRequired',
+ displayNameTooLong: 'settings.models.sourceDetail.edit.validation.displayNameTooLong',
+ displayNameCredential: 'settings.models.sourceDetail.edit.validation.displayNameCredential',
+ baseUrlCredential: 'settings.models.sourceDetail.edit.validation.baseUrlCredential',
+};
+
+export type SourceEditAssessment =
+ | { valid: true; patch: SourcePatch | null; reason: null }
+ | { valid: false; patch: null; reason: SourceEditInvalidReason };
+
+// These two overlapping sets intentionally mirror config/v2_config.py. They
+// stay separate until the server contract changes with the shared fixture.
+const CREDENTIAL_QUERY_KEYS = new Set([
+ 'access_token',
+ 'api_key',
+ 'apikey',
+ 'auth',
+ 'authorization',
+ 'bearer',
+ 'credential',
+ 'key',
+ 'password',
+ 'passwd',
+ 'secret',
+ 'sig',
+ 'signature',
+ 'token',
+]);
+
+const CREDENTIAL_QUERY_MARKERS = [
+ 'api_key',
+ 'access_token',
+ 'auth_token',
+ 'token',
+ 'authorization',
+ 'signature',
+ 'secret',
+ 'password',
+ 'credential',
+];
+
+const CREDENTIAL_PATTERNS = [
+ /\b(?:sk|rk|pk|sess|token)[-_][a-z0-9_-]{8,}\b/i,
+ /\b(?:authorization|api[_ -]?key|access[_ -]?token)\s*[:=]\s*(?:sk[-_][a-z0-9_-]{8,}|[a-z0-9._~+/=-]{16,})/i,
+ /\bbearer\s+[a-z0-9._~+/=-]{8,}/i,
+];
+
+const containsCredentialMaterial = (value: string): boolean =>
+ CREDENTIAL_PATTERNS.some((pattern) => pattern.test(JSON.stringify(value)));
+
+type BaseUrlAssessment =
+ | { valid: true; value: string | null }
+ | { valid: false; reason: Extract<SourceEditInvalidReason, `baseUrl${string}`> };
+
+const assessedEditedBaseUrl = (value: string): BaseUrlAssessment => {
+ if (!value) return { valid: true, value: null };
+ if (containsCredentialMaterial(value)) return { valid: false, reason: 'baseUrlCredential' };
+
+ let parsed: URL;
+ try {
+ parsed = new URL(value);
+ } catch {
+ return { valid: true, value };
+ }
+
+ for (const key of parsed.searchParams.keys()) {
+ const normalized = key.trim().toLowerCase().replace(/[-.]/g, '_');
+ if (
+ CREDENTIAL_QUERY_KEYS.has(normalized)
+ || CREDENTIAL_QUERY_MARKERS.some((marker) => normalized.includes(marker))
+ ) return { valid: false, reason: 'baseUrlCredential' };
+ }
+
+ // The browser owns only the warning that prevents a user from persisting a
+ // secret. URL acceptance and normalization belong entirely to the server.
+ return { valid: true, value };
+};
+
+/** Pre-filter an actual edit and diff without claiming server target policy. */
+export const assessSourceEdit = (source: Source, draft: SourceEditDraft): SourceEditAssessment => {
+ const displayName = draft.displayName.trim();
+ if (!displayName) return { valid: false, patch: null, reason: 'displayNameRequired' };
+ if (!optionalTrimmedTextWithin(draft.displayName, SOURCE_DISPLAY_NAME_MAX_LENGTH)) {
+ return { valid: false, patch: null, reason: 'displayNameTooLong' };
+ }
+ if (containsCredentialMaterial(displayName)) {
+ return { valid: false, patch: null, reason: 'displayNameCredential' };
+ }
+
+ const patch: SourcePatch = {};
+ if (displayName !== source.display_name) patch.display_name = displayName;
+
+ if (canEditSourceEndpoint(source)) {
+ const baseUrl = draft.baseUrl.trim();
+ if (baseUrl !== (source.base_url ?? '')) {
+ const endpoint = assessedEditedBaseUrl(baseUrl);
+ if (!endpoint.valid) return { valid: false, patch: null, reason: endpoint.reason };
+ patch.base_url = endpoint.value;
+ }
+ }
+
+ return { valid: true, patch: Object.keys(patch).length > 0 ? patch : null, reason: null };
+};
diff --git a/ui/src/components/settings/models/modelsApi.mock.test.ts b/ui/src/components/settings/models/modelsApi.mock.test.ts
new file mode 100644
index 000000000..e13b92450
--- /dev/null
+++ b/ui/src/components/settings/models/modelsApi.mock.test.ts
@@ -0,0 +1,133 @@
+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.ts
index f189313c2..f4864fd14 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -63,6 +63,15 @@ export type CredentialReplacement = {
removed_hops: RouteHopRef[];
interrupted: SupplyGap[];
};
+export type SourcePatched = {
+ source: Source;
+ removed_hops: RouteHopRef[];
+ interrupted: SupplyGap[];
+};
+export type SourceDeleted = {
+ removed_hops: RouteHopRef[];
+ interrupted: SupplyGap[];
+};
export type GuardConfirmation = {
force: true;
would_remove_hops: RouteHopRef[];
@@ -100,14 +109,14 @@ export type ModelsApi = {
observeApiKeySource(draft: ApiKeySourceObservation, signal?: AbortSignal): Promise<SourceObservation>;
createApiKeySource(draft: ApiKeySourceCreate): Promise<SourceCreated>;
/** Rename / re-point a source (display_name, base_url). */
- patchSource(id: string, patch: SourcePatch): Promise<Source>;
+ patchSource(id: string, patch: SourcePatch): Promise<SourcePatched>;
/** Re-run discovery on a hub source; resolves with the updated source and count.
* Contractually ALSO the recovery test: run on a needs_action / error source
* it clears the blocker and returns the source to standby. v3 adds no second
* 「recover」 endpoint, so this is the whole retry affordance. */
refreshSource(id: string, confirmation?: GuardConfirmation): Promise<SourceRefresh>;
/** Delete a source. A destructive retry echoes the server's exact guard plan. */
- deleteSource(id: string, confirmation?: GuardConfirmation): Promise<void>;
+ deleteSource(id: string, confirmation?: GuardConfirmation): Promise<SourceDeleted>;
/** Replace the credential of a hub-channel api_key source. The normal guarded
* mutation tail reports every route hop removed and model interrupted. */
replaceCredential(id: string, body: CredentialReplace): Promise<CredentialReplacement>;
@@ -363,6 +372,28 @@ const credentialReplacement = (r: CredentialReplacementResponse): CredentialRepl
interrupted: supplyGaps(r.interrupted),
});
+type SourcePatchedResponse = {
+ source?: Source;
+ removed_hops?: RouteHopRef[];
+ interrupted?: SupplyGap[];
+} & Source;
+
+const sourcePatched = (r: SourcePatchedResponse): SourcePatched => ({
+ source: (r.source ?? r) as Source,
+ removed_hops: routeHopRefs(r.removed_hops),
+ interrupted: supplyGaps(r.interrupted),
+});
+
+type SourceDeletedResponse = {
+ removed_hops?: RouteHopRef[];
+ interrupted?: SupplyGap[];
+};
+
+const sourceDeleted = (r: SourceDeletedResponse): SourceDeleted => ({
+ removed_hops: routeHopRefs(r.removed_hops),
+ interrupted: supplyGaps(r.interrupted),
+});
+
/** The oauth terminal envelope, unwrapped without discarding either tail. */
export type OAuthResultResponse = { flow?: OAuthFlow } & OAuthFlow &
AdoptionTail & {
@@ -412,15 +443,15 @@ const liveApi: ModelsApi = {
// and no later read can put it back: `/agents` shows today's orders, not which
// of them this commit changed.
createApiKeySource: (draft) => call<SourceCreatedResponse>('/api/models/sources', jsonInit('POST', draft)).then(created),
- patchSource: (id, patch) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(id)}`, jsonInit('PATCH', patch)).then((r) => (r.source ?? r) as Source),
+ patchSource: (id, patch) => call<SourcePatchedResponse>(`/api/models/sources/${encodeURIComponent(id)}`, jsonInit('PATCH', patch)).then(sourcePatched),
refreshSource: (id, confirmation) => call<SourceRefresh>(`/api/models/sources/${encodeURIComponent(id)}/refresh`, jsonInit('POST', confirmation ?? {})),
- deleteSource: (id, confirmation) => call(
+ deleteSource: (id, confirmation) => call<SourceDeletedResponse>(
`/api/models/sources/${encodeURIComponent(id)}${confirmation ? '?force=true' : ''}`,
jsonInit('DELETE', confirmation ? {
would_remove_hops: confirmation.would_remove_hops,
would_interrupt: confirmation.would_interrupt,
} : undefined),
- ).then(() => undefined),
+ ).then(sourceDeleted),
// Both repair routes reject unknown body keys outright (`discovery_failed` /
// `reauth_confirmation_required`), so these bodies are exactly the contract's
// and carry no `contract_version` — the same closed-body rule as putAgentSources.
@@ -493,7 +524,8 @@ const listedModelIdsForPlacement = (agent: AgentSupply): string[] => {
return [...new Set(values)];
};
-class MockStore {
+/** Exported so tests can assert mock/live contract parity over the seeded store. */
+export class MockStore {
sources = buildMockSources();
agents = buildMockAgents(this.sources);
events = buildMockEvents();
@@ -686,17 +718,23 @@ class MockStore {
* Reporting per (backend, model) with the Agents that run it is also what makes
* the confirm copy nameable — 「删除后 pm 将没有可用来源」.
*/
- private wouldInterrupt(candidate: Source[]): SupplyGap[] {
+ 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
- .map((hop) => byId.get(hop.source_id))
- .some((s) => s !== undefined && isRunnable(s));
+ 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,
@@ -709,16 +747,53 @@ class MockStore {
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);
- // `source_last_supplier` — the code the contract actually sends here.
- // `mode_switch_blocked` belongs to the mode route, and a client written
- // against it retried nothing on a real refusal.
const gaps = this.wouldInterrupt(remaining);
- if (gaps.length > 0 && !confirmation)
- throw new ApiCallError('source_last_supplier', undefined, true, gaps);
+ 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;
- // Orders and the rollup are recomputed on the next read (syncAgents).
- return delay(undefined);
+ 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) {
@@ -1294,11 +1369,91 @@ class MockStore {
}
patchSource(id: string, patch: SourcePatch) {
- const source = this.sources.find((s) => s.id === id);
+ this.syncAgents();
+ const sourceIndex = this.sources.findIndex((s) => s.id === id);
+ const source = this.sources[sourceIndex];
if (!source) throw new ApiCallError('source_not_found');
- if (typeof patch.display_name === 'string') source.display_name = patch.display_name;
- if ('base_url' in patch && source.kind === 'api_key') source.base_url = patch.base_url ?? null;
- return delay(structuredClone(source), 300);
+ 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) {
diff --git a/ui/src/components/settings/models/mutationConvergence.ts b/ui/src/components/settings/models/mutationConvergence.ts
index e515cfa13..e11831bef 100644
--- a/ui/src/components/settings/models/mutationConvergence.ts
+++ b/ui/src/components/settings/models/mutationConvergence.ts
@@ -22,7 +22,7 @@ export type MutationConvergence<T> = {
entity?: T;
applyEntity: (entity: T) => void;
intent?: { authority: IntentAuthority; apply: () => void };
- reconcile: () => Promise<void>;
+ reconcile: () => Promise<unknown>;
};
/** Every mutation converges in the same order: the server-owned entity first,
diff --git a/ui/src/components/settings/models/mutationSettlement.test.ts b/ui/src/components/settings/models/mutationSettlement.test.ts
index a5aaf152b..17be7f125 100644
--- a/ui/src/components/settings/models/mutationSettlement.test.ts
+++ b/ui/src/components/settings/models/mutationSettlement.test.ts
@@ -43,4 +43,16 @@ describe('mutation settlement fences', () => {
expect(detail).toContain('settlement.source');
expect(detail).toContain('settlement.gone');
});
+
+ it('carries the surface landing verdict through every Source settlement', () => {
+ const here = dirname(fileURLToPath(import.meta.url));
+ const page = readFileSync(resolve(here, 'SettingsModelsPage.tsx'), 'utf8');
+ const refresh = page.slice(page.indexOf('const refresh = React.useCallback'), page.indexOf('\n\n const trackSourceMutation'));
+ const settlement = page.slice(page.indexOf('const trackSourceMutation'), page.indexOf('\n\n React.useEffect', page.indexOf('const trackSourceMutation')));
+
+ expect(refresh).toMatch(/Promise<SourceMutationLanding>/);
+ expect(refresh).toMatch(/\? 'landed'\s*:\s*'degraded'/);
+ expect(settlement).toMatch(/Promise<SourceMutationLanding>/);
+ expect(settlement).toMatch(/return reconcile \? refresh\(\) : 'landed'/);
+ });
});
diff --git a/ui/src/components/settings/models/mutationSettlement.ts b/ui/src/components/settings/models/mutationSettlement.ts
index d1a8fccc7..8e270d1cf 100644
--- a/ui/src/components/settings/models/mutationSettlement.ts
+++ b/ui/src/components/settings/models/mutationSettlement.ts
@@ -42,10 +42,12 @@ export const createSourceCreatedDelivery = () => {
export type SourceInventorySnapshot = { snapshot: number; sources: Source[] };
+export type SourceMutationLanding = 'landed' | 'degraded';
+
export type SourceMutationSettlement = {
- source: (source: Source) => Promise<void>;
- gone: (sourceId: string, inventory?: SourceInventorySnapshot) => Promise<void>;
- unread: () => Promise<void>;
+ source: (source: Source) => Promise<SourceMutationLanding>;
+ gone: (sourceId: string, inventory?: SourceInventorySnapshot) => Promise<SourceMutationLanding>;
+ unread: () => Promise<SourceMutationLanding>;
release: () => void;
readInventory: () => Promise<SourceInventorySnapshot>;
};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 0346ff90d..6cff12b0f 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1283,6 +1283,43 @@
"refetch": "Refetch",
"addModel": "Add model"
},
+ "manage": {
+ "label": "Manage {{source}}",
+ "edit": "Edit source",
+ "remove": "Remove source"
+ },
+ "edit": {
+ "title": "Edit {{source}}",
+ "name": "Display name",
+ "baseUrl": "Base URL",
+ "hint": "The protocol stays fixed. Changing the Base URL can change available models and routes; you will review any impact before it is applied.",
+ "cancel": "Cancel",
+ "save": "Save",
+ "saving": "Saving…",
+ "fail": "The source was not saved",
+ "verifyFail": "Could not verify whether the source was saved",
+ "validation": {
+ "displayNameRequired": "Enter a display name",
+ "displayNameTooLong": "Use 64 characters or fewer",
+ "displayNameCredential": "A display name cannot contain a credential",
+ "baseUrlCredential": "Remove credentials and credential-shaped query parameters from the Base URL"
+ },
+ "impact": {
+ "title": "The source was updated, and some supply was affected",
+ "detail": "These routes or models were removed or interrupted.",
+ "done": "Done"
+ }
+ },
+ "remove": {
+ "impact": {
+ "title": "The source was removed, and some supply was affected",
+ "detail": "These are the routes and models actually affected by this removal.",
+ "done": "Done"
+ }
+ },
+ "impact": {
+ "refreshFail": "The change committed, but the model surface could not be refreshed. Try the reconciliation again."
+ },
"refetch": {
"added": "New",
"removed_one": "This fetch removed {{count}} model: {{models}}",
@@ -1296,9 +1333,12 @@
"refetch": "The fetch did not come back. The list below is the last one this page actually read",
"tier": "The tier was not saved",
"addModel": "The model was not added",
- "removeModel": "The model was not removed"
+ "removeModel": "The model was not removed",
+ "deleteSource": "The source was not removed",
+ "verifyDeleteSource": "Could not verify whether the source was removed"
},
"retry": "Try again",
+ "dismissUnverified": "Dismiss unverified result",
"search": "Search model IDs",
"col": {
"id": "Model ID",
@@ -1352,19 +1392,25 @@
"refetch": "Refetch models from {{source}}",
"removeModel": "Remove {{model}} from {{source}}",
"saveRoute": "Save the route chain for {{menuModel}}",
- "replaceKey": "Replace key for {{source}}"
+ "replaceKey": "Replace key for {{source}}",
+ "editSource": "Save changes to {{source}}?",
+ "deleteSource": "Remove {{source}}?"
},
"subtitle": {
"refetch": "This refetch drops models from this source's inventory.",
"removeModel": "This model disappears from this source's inventory.",
"saveRoute": "This save leaves a configured model with no usable source",
- "replaceKey": "The replacement changes this source's model inventory."
+ "replaceKey": "The replacement changes this source's model inventory.",
+ "editSource": "Changing the endpoint can change this source's model inventory and routes.",
+ "deleteSource": "This removes the source from every Agent and route that uses it."
},
"confirm": {
"refetch": "Refetch anyway",
"removeModel": "Remove anyway",
"saveRoute": "Save anyway",
- "replaceKey": "Replace anyway"
+ "replaceKey": "Replace anyway",
+ "editSource": "Save anyway",
+ "deleteSource": "Remove source"
}
},
"repair": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 4de10897b..dc3a75eeb 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1283,6 +1283,43 @@
"refetch": "重新拉取",
"addModel": "添加模型"
},
+ "manage": {
+ "label": "管理 {{source}}",
+ "edit": "编辑来源",
+ "remove": "移除来源"
+ },
+ "edit": {
+ "title": "编辑 {{source}}",
+ "name": "显示名称",
+ "baseUrl": "Base URL",
+ "hint": "协议保持不变。更改 Base URL 可能改变可用型号和路由;应用前会先让你确认影响。",
+ "cancel": "取消",
+ "save": "保存",
+ "saving": "保存中…",
+ "fail": "来源没有保存上",
+ "verifyFail": "无法确认来源是否已保存",
+ "validation": {
+ "displayNameRequired": "请输入显示名称",
+ "displayNameTooLong": "最多输入 64 个字符",
+ "displayNameCredential": "显示名称不能包含凭据",
+ "baseUrlCredential": "请从 Base URL 中移除凭据和疑似凭据的查询参数"
+ },
+ "impact": {
+ "title": "来源已更新,部分供给受到影响",
+ "detail": "以下路由或型号已被移除或中断。",
+ "done": "完成"
+ }
+ },
+ "remove": {
+ "impact": {
+ "title": "来源已移除,部分供给受到影响",
+ "detail": "以下是这次移除实际影响的路由和型号。",
+ "done": "完成"
+ }
+ },
+ "impact": {
+ "refreshFail": "变更已经提交,但模型页面暂时无法刷新。请再次重试对账。"
+ },
"refetch": {
"added": "新增",
"removed_one": "本次拉取移除了 {{count}} 个型号:{{models}}",
@@ -1296,9 +1333,12 @@
"refetch": "拉取没有回来,下面是这一页最后一次真的读到的列表",
"tier": "档位没保存上",
"addModel": "这个型号没添加上",
- "removeModel": "这个型号没移除掉"
+ "removeModel": "这个型号没移除掉",
+ "deleteSource": "这个来源没有移除掉",
+ "verifyDeleteSource": "无法确认这个来源是否已移除"
},
"retry": "重试",
+ "dismissUnverified": "忽略未确认的结果",
"search": "搜索型号 ID",
"col": {
"id": "型号 ID",
@@ -1352,19 +1392,25 @@
"refetch": "重新拉取 {{source}} 的型号",
"removeModel": "从 {{source}} 移除 {{model}}",
"saveRoute": "保存 {{menuModel}} 的路由链",
- "replaceKey": "更换 {{source}} 的 Key"
+ "replaceKey": "更换 {{source}} 的 Key",
+ "editSource": "保存 {{source}} 的更改?",
+ "deleteSource": "移除 {{source}}?"
},
"subtitle": {
"refetch": "这次拉取会让部分型号从这个来源的清单里消失。",
"removeModel": "这个型号会从这个来源的清单里消失。",
"saveRoute": "这次保存会让已配置的型号没有可用来源",
- "replaceKey": "这次更换会改变这个来源的型号清单。"
+ "replaceKey": "这次更换会改变这个来源的型号清单。",
+ "editSource": "更改端点可能改变这个来源的型号清单和路由。",
+ "deleteSource": "这会从所有正在使用它的 Agent 和路由中移除该来源。"
},
"confirm": {
"refetch": "仍要拉取",
"removeModel": "仍要移除",
"saveRoute": "仍要保存",
- "replaceKey": "仍要更换"
+ "replaceKey": "仍要更换",
+ "editSource": "仍要保存",
+ "deleteSource": "移除来源"
}
},
"repair": {