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 replace key repair flow (#1429)

Call Whiteb1d8996e90ad
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index 0ca7918ec..79b88ea1f 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -38,11 +38,18 @@ async def dispatch_model_hub_rpc(
payload.get("reauth"),
)
if operation == "delete_source":
- return await service.delete_source(payload.get("source_id"), force=payload.get("force") is True)
+ return await service.delete_source(
+ payload.get("source_id"),
+ force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
+ )
if operation == "refresh_source":
return await service.refresh_source(
payload.get("source_id"),
force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
)
if operation == "list_agents":
return await asyncio.to_thread(service.list_agents)
@@ -80,6 +87,8 @@ async def dispatch_model_hub_rpc(
payload.get("source_id"),
payload.get("model_id"),
force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
)
if operation == "list_events":
return service.list_events(limit=payload.get("limit", 20), before=payload.get("before"))
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 0897ca79d..c676928b9 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -1362,6 +1362,8 @@ class ModelHubService:
discovered: list[str],
*,
force: bool,
+ confirmed_remove_hops: object,
+ confirmed_interruptions: object,
) -> tuple[list[dict], list[dict]]:
"""Apply one successful inventory observation and commit it atomically."""
@@ -1378,6 +1380,8 @@ class ModelHubService:
updated,
source.id,
force=force,
+ confirmed_remove_hops=confirmed_remove_hops,
+ confirmed_interruptions=confirmed_interruptions,
)
await self._commit_synced(previous, updated)
return removed_hops, interrupted
@@ -2389,7 +2393,8 @@ class ModelHubService:
async def replace_credential(self, source_id: str, payload: object) -> dict:
if (
not isinstance(payload, dict)
- or set(payload) - {"key", "force"}
+ or set(payload)
+ - {"key", "force", "would_remove_hops", "would_interrupt"}
or set(payload) < {"key"}
or not isinstance(payload.get("key"), str)
or not str(payload["key"]).strip()
@@ -2437,6 +2442,8 @@ class ModelHubService:
source,
discovered,
force=force,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
)
committed = True
except asyncio.CancelledError:
@@ -2483,7 +2490,14 @@ class ModelHubService:
async def patch_source(self, source_id: str, payload: dict) -> dict:
if (
not isinstance(payload, dict)
- or set(payload) - {"display_name", "base_url", "force"}
+ or set(payload)
+ - {
+ "display_name",
+ "base_url",
+ "force",
+ "would_remove_hops",
+ "would_interrupt",
+ }
or ("force" in payload and not isinstance(payload["force"], bool))
):
raise ModelHubError("discovery_failed")
@@ -2542,6 +2556,8 @@ class ModelHubService:
source,
discovered,
force=force,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
)
committed = True
except asyncio.CancelledError:
@@ -2684,10 +2700,11 @@ class ModelHubService:
"menu_model": menu_model,
"source_id": source_id,
"model_id": hop.model_id,
+ "position": position,
}
for backend in MODEL_HUB_BACKENDS
for menu_model, route in config.agents[backend].routes.items()
- for hop in route.hops
+ for position, hop in enumerate(route.hops, start=1)
if hop.source_id == source_id
and inspect_exact_hop(
config,
@@ -2733,36 +2750,77 @@ class ModelHubService:
source_id: str,
*,
force: bool,
+ confirmed_remove_hops: object,
+ confirmed_interruptions: object,
) -> tuple[list[dict], list[dict]]:
would_remove_hops = self._invalidated_route_hops(updated, source_id)
would_interrupt = self._introduced_interruptions(previous, updated)
- if (would_remove_hops or would_interrupt) and not force:
- raise ModelHubError(
- (
- "source_model_in_route_chain"
- if would_remove_hops
- else "source_last_supplier"
- ),
- status=409,
- data={
- "would_remove_hops": would_remove_hops,
- "would_interrupt": would_interrupt,
- },
- )
+ self._require_guard_plan(
+ force=force,
+ confirmed_remove_hops=confirmed_remove_hops,
+ confirmed_interruptions=confirmed_interruptions,
+ would_remove_hops=would_remove_hops,
+ would_interrupt=would_interrupt,
+ error=(
+ "source_model_in_route_chain"
+ if would_remove_hops
+ else "source_last_supplier"
+ ),
+ )
if would_remove_hops:
self._prune_invalidated_route_hops(updated, would_remove_hops)
return would_remove_hops, would_interrupt
- async def delete_source(self, source_id: str, *, force: bool = False) -> dict:
+ @staticmethod
+ def _require_guard_plan(
+ *,
+ force: bool,
+ confirmed_remove_hops: object,
+ confirmed_interruptions: object,
+ would_remove_hops: list[dict],
+ would_interrupt: list[dict],
+ error: str,
+ ) -> None:
+ if not (would_remove_hops or would_interrupt):
+ return
+ if (
+ force
+ and _same_json_value(confirmed_remove_hops, would_remove_hops)
+ and _same_json_value(confirmed_interruptions, would_interrupt)
+ ):
+ return
+ raise ModelHubError(
+ error,
+ status=409,
+ data={
+ "would_remove_hops": would_remove_hops,
+ "would_interrupt": would_interrupt,
+ },
+ )
+
+ async def delete_source(
+ self,
+ source_id: str,
+ *,
+ force: bool = False,
+ confirmed_remove_hops: object = None,
+ confirmed_interruptions: object = None,
+ ) -> dict:
async with self._mutation_lock:
previous = self.store.load()
config = self._clone_config(previous)
source = self._source(config, source_id)
removed_hops = [
- {"backend": backend, "menu_model": model_id, "source_id": source_id, "model_id": hop.model_id}
+ {
+ "backend": backend,
+ "menu_model": model_id,
+ "source_id": source_id,
+ "model_id": hop.model_id,
+ "position": position,
+ }
for backend in MODEL_HUB_BACKENDS
for model_id, route in config.agents[backend].routes.items()
- for hop in route.hops
+ for position, hop in enumerate(route.hops, start=1)
if hop.source_id == source_id
]
config.sources = [item for item in config.sources if item.id != source_id]
@@ -2781,21 +2839,18 @@ class ModelHubService:
config,
newly_empty_routes=newly_empty_routes,
)
- if removed_hops and not force:
- raise ModelHubError(
- "source_in_route_chain",
- status=409,
- data={
- "would_remove_hops": removed_hops,
- "would_interrupt": would_interrupt,
- },
- )
- if would_interrupt and not force:
- raise ModelHubError(
- "source_last_supplier",
- status=409,
- data={"would_remove_hops": [], "would_interrupt": would_interrupt},
- )
+ self._require_guard_plan(
+ force=force,
+ confirmed_remove_hops=confirmed_remove_hops,
+ confirmed_interruptions=confirmed_interruptions,
+ would_remove_hops=removed_hops,
+ would_interrupt=would_interrupt,
+ error=(
+ "source_in_route_chain"
+ if removed_hops
+ else "source_last_supplier"
+ ),
+ )
self._prune_unavailable_agent_references(config)
if source.credential_ref:
self.revocations.add(source.id, source.credential_ref)
@@ -2827,7 +2882,14 @@ class ModelHubService:
self.revocations.remove(source.id, source.credential_ref)
return {"removed_hops": removed_hops, "interrupted": would_interrupt}
- async def refresh_source(self, source_id: str, *, force: bool = False) -> dict:
+ async def refresh_source(
+ self,
+ source_id: str,
+ *,
+ force: bool = False,
+ confirmed_remove_hops: object = None,
+ confirmed_interruptions: object = None,
+ ) -> dict:
async with self._mutation_lock:
previous = self.store.load()
config = self._clone_config(previous)
@@ -2842,6 +2904,8 @@ class ModelHubService:
source,
model_ids,
force=force,
+ confirmed_remove_hops=confirmed_remove_hops,
+ confirmed_interruptions=confirmed_interruptions,
)
except ModelHubError as exc:
if exc.code != "discovery_failed":
@@ -3292,6 +3356,8 @@ class ModelHubService:
model_id: object,
*,
force: bool = False,
+ confirmed_remove_hops: object = None,
+ confirmed_interruptions: object = None,
) -> dict:
if not isinstance(model_id, str) or not model_id:
raise ModelHubError("mapping_target_unavailable")
@@ -3310,10 +3376,11 @@ class ModelHubService:
"menu_model": menu_model,
"source_id": source.id,
"model_id": model_id,
+ "position": position,
}
for backend in MODEL_HUB_BACKENDS
for menu_model, route in config.agents[backend].routes.items()
- for hop in route.hops
+ for position, hop in enumerate(route.hops, start=1)
if hop.source_id == source.id and hop.model_id == model_id
]
source.models = [
@@ -3322,15 +3389,18 @@ class ModelHubService:
if item.id != model_id
]
would_interrupt = self._introduced_interruptions(previous, config)
- if (removed_hops or would_interrupt) and not force:
- raise ModelHubError(
- "source_model_in_route_chain" if removed_hops else "source_last_supplier",
- status=409,
- data={
- "would_remove_hops": removed_hops,
- "would_interrupt": would_interrupt,
- },
- )
+ self._require_guard_plan(
+ force=force,
+ confirmed_remove_hops=confirmed_remove_hops,
+ confirmed_interruptions=confirmed_interruptions,
+ would_remove_hops=removed_hops,
+ would_interrupt=would_interrupt,
+ error=(
+ "source_model_in_route_chain"
+ if removed_hops
+ else "source_last_supplier"
+ ),
+ )
if force and removed_hops:
for agent in config.agents.values():
for route in agent.routes.values():
diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
index aa60748e5..541941621 100644
--- a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
@@ -302,7 +302,14 @@ def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_ord
asyncio.run(service.delete_source(doomed.id))
assert refusal.value.code == "source_in_route_chain"
- result = asyncio.run(service.delete_source(doomed.id, force=True))
+ result = asyncio.run(
+ service.delete_source(
+ doomed.id,
+ force=True,
+ confirmed_remove_hops=refusal.value.data["would_remove_hops"],
+ confirmed_interruptions=refusal.value.data["would_interrupt"],
+ )
+ )
assert result["removed_hops"]
assert doomed.id not in {item.id for item in store.load().sources}
for backend, menu_model in (
@@ -340,13 +347,23 @@ def test_mh_supply_gap_001_empty_chain_remains_visible_after_inventory_loss(
)
service = service_for(tmp_path, store, adapter)
- result = asyncio.run(service.refresh_source(supplied.id, force=True))
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(service.refresh_source(supplied.id))
+ result = asyncio.run(
+ service.refresh_source(
+ supplied.id,
+ force=True,
+ confirmed_remove_hops=refusal.value.data["would_remove_hops"],
+ confirmed_interruptions=refusal.value.data["would_interrupt"],
+ )
+ )
assert result["removed_hops"] == [
{
"backend": "claude",
"menu_model": menu_model,
"source_id": supplied.id,
"model_id": menu_model,
+ "position": 1,
}
]
model_supply = next(
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index d196c2d95..7c36ff65b 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -849,7 +849,14 @@ def test_source_create_nonce_covers_in_flight_committed_and_deleted_states(tmp_p
if source.get("client_nonce") == payload["client_nonce"]
] == [payload["client_nonce"]]
- await service.delete_source(committed["source"]["id"], force=True)
+ with pytest.raises(ModelHubError) as delete_guard:
+ await service.delete_source(committed["source"]["id"])
+ await service.delete_source(
+ committed["source"]["id"],
+ force=True,
+ confirmed_remove_hops=delete_guard.value.data["would_remove_hops"],
+ confirmed_interruptions=delete_guard.value.data["would_interrupt"],
+ )
recreated = await service.create_source(payload)
assert recreated["source"]["id"] != committed["source"]["id"]
assert recreated["source"]["client_nonce"] == payload["client_nonce"]
@@ -3416,7 +3423,16 @@ def test_completed_hub_reauth_revokes_replacement_after_source_disappears(
store.config.sources.append(source)
_refresh_fixture_routes(store.config)
flow = asyncio.run(service.reauth_source(source.id, {"acknowledge_irreversible": True}))["flow"]
- asyncio.run(service.delete_source(source.id, force=True))
+ with pytest.raises(ModelHubError) as delete_refusal:
+ asyncio.run(service.delete_source(source.id))
+ asyncio.run(
+ service.delete_source(
+ source.id,
+ force=True,
+ confirmed_remove_hops=delete_refusal.value.data["would_remove_hops"],
+ confirmed_interruptions=delete_refusal.value.data["would_interrupt"],
+ )
+ )
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -3543,6 +3559,11 @@ def test_credential_route_carries_body_force_override_and_structured_guard(
assert refused.status_code == 409
refusal = refused.get_json()
+ route_hop_schema = _schema("guard-refusal.schema.json")["definitions"][
+ "RouteHopRef"
+ ]
+ for hop in refusal["would_remove_hops"]:
+ Draft7Validator(route_hop_schema).validate(hop)
assert refusal["error"] == "source_model_in_route_chain"
assert refusal["would_remove_hops"]
assert all(
@@ -3561,16 +3582,51 @@ def test_credential_route_carries_body_force_override_and_structured_guard(
"agents": [],
},
]
- committed = client.put(
+ unconfirmed = client.put(
f"/api/models/sources/{created['id']}/credential",
json={**request_body, "force": True},
headers=headers,
base_url=base_url,
+ )
+ assert unconfirmed.status_code == 409
+ assert unconfirmed.get_json()["would_remove_hops"] == refusal["would_remove_hops"]
+ assert unconfirmed.get_json()["would_interrupt"] == refusal["would_interrupt"]
+
+ stale_confirmation = client.put(
+ f"/api/models/sources/{created['id']}/credential",
+ json={
+ **request_body,
+ "force": True,
+ "would_remove_hops": refusal["would_remove_hops"],
+ "would_interrupt": refusal["would_interrupt"][:-1],
+ },
+ headers=headers,
+ base_url=base_url,
+ )
+ assert stale_confirmation.status_code == 409
+ assert stale_confirmation.get_json()["error"] == refusal["error"]
+ assert stale_confirmation.get_json()["would_remove_hops"] == refusal[
+ "would_remove_hops"
+ ]
+ assert stale_confirmation.get_json()["would_interrupt"] == refusal[
+ "would_interrupt"
+ ]
+
+ committed = client.put(
+ f"/api/models/sources/{created['id']}/credential",
+ json={
+ **request_body,
+ "force": True,
+ "would_remove_hops": refusal["would_remove_hops"],
+ "would_interrupt": refusal["would_interrupt"],
+ },
+ headers=headers,
+ base_url=base_url,
).get_json()
assert committed["removed_hops"] == refusal["would_remove_hops"]
assert committed["interrupted"] == refusal["would_interrupt"]
- assert committed["source"]["credential_ref"] == "cred_route_3"
+ assert committed["source"]["credential_ref"] == "cred_route_5"
removed_identities = {
(hop["backend"], hop["menu_model"], hop["source_id"], hop["model_id"])
for hop in committed["removed_hops"]
@@ -3581,7 +3637,13 @@ def test_credential_route_carries_body_force_override_and_structured_guard(
for menu_model, route in agent.routes.items()
for hop in route.hops
)
- assert adapter.revoked == ["cred_test001", "cred_route_2", "cred_route_1"]
+ assert adapter.revoked == [
+ "cred_test001",
+ "cred_route_2",
+ "cred_route_3",
+ "cred_route_4",
+ "cred_route_1",
+ ]
def test_failed_hub_oauth_source_creation_revokes_credential(tmp_path):
@@ -4680,7 +4742,12 @@ def test_base_url_change_guards_and_prunes_invalid_exact_hops(
committed = client.patch(
f"/api/models/sources/{source['id']}",
- json={"base_url": replacement_url, "force": True},
+ json={
+ "base_url": replacement_url,
+ "force": True,
+ "would_remove_hops": refusal["would_remove_hops"],
+ "would_interrupt": refusal["would_interrupt"],
+ },
headers=headers,
base_url=origin,
).get_json()
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 06c8babf3..ead548ece 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -3451,6 +3451,8 @@ def test_live_handle_settlement_survives_concurrent_source_deletion(
live_handles=[handle],
)
requested_model = _canonicalize_fixed_test_routes(service)["codex"]
+ with pytest.raises(ModelHubError) as delete_refusal:
+ await service.delete_source(source.id)
turn_id = f"turn_deleted_live_{kind.value}"
gateway = ModelHubTurnGateway(service)
base_url, token = await gateway.endpoint(
@@ -3475,7 +3477,16 @@ def test_live_handle_settlement_survives_concurrent_source_deletion(
)
)
await asyncio.wait_for(handle.started.wait(), timeout=1)
- await service.delete_source(source.id, force=True)
+ await service.delete_source(
+ source.id,
+ force=True,
+ confirmed_remove_hops=delete_refusal.value.data[
+ "would_remove_hops"
+ ],
+ confirmed_interruptions=delete_refusal.value.data[
+ "would_interrupt"
+ ],
+ )
handle.release()
response = await asyncio.wait_for(response_task, timeout=1)
payload = await response.read()
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 2172d859d..5f3319134 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -1963,7 +1963,7 @@ def test_manual_model_delete_ignores_preexisting_unrelated_gap(tmp_path):
]
-def test_manual_model_delete_rejects_a_new_gap(tmp_path):
+def test_manual_model_delete_requires_the_exact_guard_plan(tmp_path):
menu_model = "claude-opus-4-6"
source = _source("src_manual003")
source.models.append(ModelHubModelConfig(id="manual-model", provenance="manual"))
@@ -1978,6 +1978,26 @@ def test_manual_model_delete_rejects_a_new_gap(tmp_path):
assert exc.value.code == "source_model_in_route_chain"
assert store.load().to_payload() == config.to_payload()
+ with pytest.raises(ModelHubError) as unconfirmed:
+ asyncio.run(
+ service.delete_custom_model(
+ source.id,
+ "manual-model",
+ force=True,
+ )
+ )
+ assert unconfirmed.value.data == exc.value.data
+ result = asyncio.run(
+ service.delete_custom_model(
+ source.id,
+ "manual-model",
+ force=True,
+ confirmed_remove_hops=exc.value.data["would_remove_hops"],
+ confirmed_interruptions=exc.value.data["would_interrupt"],
+ )
+ )
+ assert result["removed_hops"] == exc.value.data["would_remove_hops"]
+ assert store.load().agents["claude"].routes[menu_model].hops == ()
def test_delete_unused_source_ignores_preexisting_unrelated_gap(tmp_path):
@@ -2041,7 +2061,18 @@ def test_delete_source_reports_and_then_prunes_exact_hops(tmp_path):
asyncio.run(service.delete_source(source.id))
assert exc.value.code == "source_in_route_chain"
assert exc.value.data["would_remove_hops"][0]["model_id"] == menu_model
- result = asyncio.run(service.delete_source(source.id, force=True))
+ with pytest.raises(ModelHubError) as unconfirmed:
+ asyncio.run(service.delete_source(source.id, force=True))
+ assert unconfirmed.value.code == exc.value.code
+ assert unconfirmed.value.data == exc.value.data
+ result = asyncio.run(
+ service.delete_source(
+ source.id,
+ force=True,
+ confirmed_remove_hops=exc.value.data["would_remove_hops"],
+ confirmed_interruptions=exc.value.data["would_interrupt"],
+ )
+ )
assert result["removed_hops"]
assert store.load().sources == []
assert store.load().agents["claude"].routes[menu_model].hops == ()
@@ -2056,7 +2087,14 @@ def test_refresh_source_uses_guarded_success_shape(tmp_path):
with pytest.raises(ModelHubError) as exc:
asyncio.run(service.refresh_source(source.id))
assert exc.value.code == "source_model_in_route_chain"
- result = asyncio.run(service.refresh_source(source.id, force=True))
+ result = asyncio.run(
+ service.refresh_source(
+ source.id,
+ force=True,
+ confirmed_remove_hops=exc.value.data["would_remove_hops"],
+ confirmed_interruptions=exc.value.data["would_interrupt"],
+ )
+ )
assert set(result) == {"source", "removed_hops", "interrupted"}
assert result["removed_hops"][0]["model_id"] == menu_model
assert store.load().agents["claude"].routes[menu_model].hops == ()
@@ -2094,30 +2132,51 @@ def test_inventory_mutations_share_the_successful_discovery_finalizer(
service, store, _ = _service(tmp_path, config, adapter)
before = store.load().to_payload()
- if operation == "refresh":
- mutation = service.refresh_source(source.id, force=True)
- elif operation == "base_url":
- mutation = service.patch_source(
- source.id,
- {
- "base_url": "https://new-relay.example/v1",
- "force": True,
- },
- )
- else:
- mutation = service.replace_credential(
+ def mutation(confirmation=None):
+ confirmation = confirmation or {}
+ if operation == "refresh":
+ return service.refresh_source(source.id, **confirmation)
+ if operation == "base_url":
+ return service.patch_source(
+ source.id,
+ {
+ "base_url": "https://new-relay.example/v1",
+ **confirmation,
+ },
+ )
+ return service.replace_credential(
source.id,
- {"key": "replacement-key", "force": True},
+ {"key": "replacement-key", **confirmation},
)
if inventory_case == "failure":
with pytest.raises(ModelHubError) as exc:
- asyncio.run(mutation)
+ asyncio.run(mutation())
assert exc.value.code == "discovery_failed"
assert store.load().to_payload() == before
return
- result = asyncio.run(mutation)
+ if inventory_case == "empty":
+ with pytest.raises(ModelHubError) as refusal:
+ asyncio.run(mutation())
+ confirmed = {
+ "force": True,
+ "would_remove_hops": refusal.value.data["would_remove_hops"],
+ "would_interrupt": refusal.value.data["would_interrupt"],
+ }
+ if operation == "refresh":
+ confirmed = {
+ "force": True,
+ "confirmed_remove_hops": refusal.value.data[
+ "would_remove_hops"
+ ],
+ "confirmed_interruptions": refusal.value.data[
+ "would_interrupt"
+ ],
+ }
+ result = asyncio.run(mutation(confirmed))
+ else:
+ result = asyncio.run(mutation())
persisted = store.load().sources[0]
assert result["source"] == persisted.to_payload()
assert persisted.state == ModelHubSourceStateConfig(status="standby")
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
index a9525aa68..67cd13249 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
@@ -8,7 +8,16 @@ import i18n from '@/i18n';
import { AddApiKeyDialog } from './AddApiKeyDialog';
import { createSourceCollectionReadAuthority } from './collectionReadAuthority';
import { ApiCallError, modelsApi } from './modelsApi';
-import { CONTRACT_VERSION, SOURCE_DISPLAY_NAME_MAX_LENGTH, SOURCE_PROTOCOLS, type Source, type SourceObservation } from './types';
+import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
+import {
+ CONTRACT_VERSION,
+ SOURCE_DISPLAY_NAME_MAX_LENGTH,
+ SOURCE_PROTOCOLS,
+ type RouteHopRef,
+ type Source,
+ type SourceObservation,
+ type SupplyGap,
+} from './types';
const observed = (patch: Partial<SourceObservation> = {}): SourceObservation => ({
contract_version: CONTRACT_VERSION,
@@ -35,6 +44,23 @@ const source: Source = {
models: [],
};
+const blockedSource: Source = {
+ ...source,
+ id: 'src_revoked',
+ display_name: 'Revoked key',
+ credential_ref: 'cred_revoked',
+ state: {
+ status: 'needs_action',
+ retry_at: null,
+ detail_key: 'models.source.needs_action.credential_revoked',
+ },
+};
+
+const successfulReplacementSource = (): Source => ({
+ ...blockedSource,
+ state: { status: 'standby', retry_at: null, detail_key: null },
+});
+
const deferred = <T,>() => {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => { resolve = done; });
@@ -50,6 +76,47 @@ const renderDialog = (onClose = vi.fn(), onAdded = vi.fn()) => {
return { onClose, onAdded };
};
+const replacementSettlement = (
+ overrides: Partial<SourceMutationSettlement> = {},
+): SourceMutationSettlement => ({
+ source: vi.fn().mockResolvedValue(undefined),
+ gone: vi.fn().mockResolvedValue(undefined),
+ unread: vi.fn().mockResolvedValue(undefined),
+ release: vi.fn(),
+ readInventory: vi.fn().mockResolvedValue({ snapshot: 1, sources: [blockedSource] }),
+ ...overrides,
+});
+
+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)),
+ ...overrides,
+});
+
+const renderReplacement = (
+ current: Source = blockedSource,
+ settlement: SourceMutationSettlement = replacementSettlement(),
+ onClose = vi.fn(),
+) => {
+ const trackMutation: TrackSourceMutation = (work) => work(current, settlement);
+ render(
+ <I18nextProvider i18n={i18n}>
+ <AddApiKeyDialog
+ mode="replace"
+ open
+ source={current}
+ trackMutation={trackMutation}
+ onClose={onClose}
+ />
+ </I18nextProvider>,
+ );
+ return { onClose, settlement };
+};
+
const fillCredentials = async () => {
const user = userEvent.setup();
await user.type(screen.getByRole('textbox', { name: /^Base URL$/i }), 'https://relay.example/v1');
@@ -398,4 +465,313 @@ describe('AddApiKeyDialog', () => {
expect(await screen.findByText(/cannot tell which interface|无法判断是哪种接口/i)).toBeTruthy();
expect(screen.queryByText(i18n.t('settings.models.addKey.fail.unclassified'))).toBeNull();
});
+
+ it('reaches the credential PUT with only the trimmed key', async () => {
+ const requests: Array<{ input: string; init?: RequestInit }> = [];
+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const path = String(input);
+ if (path === '/api/csrf-token') return Response.json({ csrf_token: 'csrf' });
+ requests.push({ input: path, init });
+ return Response.json({
+ source: successfulReplacementSource(),
+ removed_hops: [],
+ interrupted: [],
+ });
+ }));
+ const settled = replacementSettlement();
+ renderReplacement(blockedSource, settled);
+ const user = userEvent.setup();
+
+ await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), ' sk-replacement ');
+ await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
+
+ await waitFor(() => expect(requests).toHaveLength(1));
+ expect(requests[0].input).toBe(`/api/models/sources/${blockedSource.id}/credential`);
+ expect(requests[0].init?.method).toBe('PUT');
+ expect(JSON.parse(String(requests[0].init?.body))).toEqual({ key: 'sk-replacement' });
+ expect(settled.source).toHaveBeenCalledWith(expect.objectContaining({ state: {
+ status: 'standby',
+ retry_at: null,
+ detail_key: null,
+ } }));
+ });
+
+ it('uses the existing guard shape before force and reports the committed impact', async () => {
+ const hop: RouteHopRef = {
+ backend: 'claude',
+ menu_model: 'sonnet',
+ position: 1,
+ source_id: blockedSource.id,
+ model_id: 'claude-sonnet-4-5',
+ };
+ const gap: SupplyGap = { backend: 'claude', model_id: 'claude-sonnet-4-5', agents: ['pm-claude'] };
+ const replace = vi.spyOn(modelsApi, 'replaceCredential')
+ .mockRejectedValueOnce(new ApiCallError(
+ 'source_model_in_route_chain',
+ undefined,
+ true,
+ [gap],
+ [],
+ [hop],
+ ))
+ .mockResolvedValueOnce({
+ source: successfulReplacementSource(),
+ removed_hops: [hop],
+ interrupted: [gap],
+ });
+ renderReplacement();
+ const user = userEvent.setup();
+
+ await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-force');
+ await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
+
+ expect(await screen.findByRole('dialog', { name: /Replace key for|更换.*Key/i })).toBeTruthy();
+ expect(screen.getByText(/pm-claude/)).toBeTruthy();
+ await user.click(screen.getByRole('button', { name: /^Replace anyway$|^仍要更换$/i }));
+
+ await waitFor(() => expect(replace).toHaveBeenCalledTimes(2));
+ expect(replace.mock.calls).toEqual([
+ [blockedSource.id, { key: 'sk-force' }],
+ [blockedSource.id, {
+ key: 'sk-force',
+ force: true,
+ would_remove_hops: [hop],
+ would_interrupt: [gap],
+ }],
+ ]);
+ expect(await screen.findByText(/^Removed hops$|^已移除的跳$/i)).toBeTruthy();
+ expect(screen.getByText(/now have no usable source|现在没有可用来源/i)).toBeTruthy();
+ });
+
+ it('requires confirmation again when the server recomputes a different replacement plan', async () => {
+ const firstHop: RouteHopRef = {
+ backend: 'claude',
+ menu_model: 'sonnet',
+ position: 1,
+ source_id: blockedSource.id,
+ model_id: 'claude-sonnet-4-5',
+ };
+ const nextHop: RouteHopRef = {
+ backend: 'codex',
+ menu_model: 'gpt-5',
+ position: 2,
+ source_id: blockedSource.id,
+ model_id: 'gpt-5.4',
+ };
+ const replace = vi.spyOn(modelsApi, 'replaceCredential')
+ .mockRejectedValueOnce(new ApiCallError(
+ 'source_model_in_route_chain',
+ undefined,
+ true,
+ [],
+ [],
+ [firstHop],
+ ))
+ .mockRejectedValueOnce(new ApiCallError(
+ 'source_model_in_route_chain',
+ undefined,
+ true,
+ [],
+ [],
+ [nextHop],
+ ))
+ .mockResolvedValueOnce({
+ source: successfulReplacementSource(),
+ removed_hops: [nextHop],
+ interrupted: [],
+ });
+ renderReplacement();
+ const user = userEvent.setup();
+
+ await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-changing-plan');
+ await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
+ await user.click(await screen.findByRole('button', { name: /^Replace anyway$|^仍要更换$/i }));
+
+ expect(await screen.findByText(/^gpt-5\.4/)).toBeTruthy();
+ expect(replace.mock.calls[1][1]).toEqual({
+ key: 'sk-changing-plan',
+ force: true,
+ would_remove_hops: [firstHop],
+ would_interrupt: [],
+ });
+
+ await user.click(screen.getByRole('button', { name: /^Replace anyway$|^仍要更换$/i }));
+
+ await waitFor(() => expect(replace).toHaveBeenCalledTimes(3));
+ expect(replace.mock.calls[2][1]).toEqual({
+ key: 'sk-changing-plan',
+ force: true,
+ would_remove_hops: [nextHop],
+ would_interrupt: [],
+ });
+ });
+
+ it.each([
+ { path: 'response', outcome: 'repaired' },
+ { path: 'response', outcome: 'impact' },
+ { path: 'inventory', outcome: 'repaired' },
+ { path: 'inventory', outcome: 'impact' },
+ ] as const)(
+ 'publishes a $outcome outcome from $path evidence without waiting for reconciliation',
+ async ({ path, outcome }) => {
+ const current = successfulReplacementSource();
+ const hop: RouteHopRef = {
+ backend: 'claude',
+ menu_model: 'sonnet',
+ position: 1,
+ source_id: blockedSource.id,
+ model_id: 'claude-sonnet-4-5',
+ };
+ const gap: SupplyGap = {
+ backend: 'claude',
+ model_id: 'claude-sonnet-4-5',
+ agents: ['pm-claude'],
+ };
+ const replace = vi.spyOn(modelsApi, 'replaceCredential');
+ if (outcome === 'impact') {
+ replace.mockRejectedValueOnce(new ApiCallError(
+ 'source_model_in_route_chain',
+ undefined,
+ true,
+ [gap],
+ [],
+ [hop],
+ ));
+ }
+ if (path === 'response') {
+ replace.mockResolvedValueOnce({
+ source: current,
+ removed_hops: outcome === 'impact' ? [hop] : [],
+ interrupted: outcome === 'impact' ? [gap] : [],
+ });
+ } else {
+ replace.mockRejectedValueOnce(new ApiCallError('bad_response', undefined, false));
+ }
+ const settled = neverResolvingSettlement({
+ readInventory: vi.fn().mockResolvedValue({ snapshot: 2, sources: [current] }),
+ });
+ const closeTimer = vi.spyOn(window, 'setTimeout');
+ renderReplacement(blockedSource, settled);
+ const user = userEvent.setup();
+
+ await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-terminal');
+ await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
+ if (outcome === 'impact') {
+ await user.click(await screen.findByRole('button', { name: /^Replace anyway$|^仍要更换$/i }));
+ }
+
+ if (outcome === 'impact') {
+ expect(await screen.findByText(/^Removed hops$|^已移除的跳$/i)).toBeTruthy();
+ expect(screen.getByText(/pm-claude/)).toBeTruthy();
+ expect(replace.mock.calls.at(-1)?.[1]).toEqual({
+ key: 'sk-terminal',
+ force: true,
+ would_remove_hops: [hop],
+ would_interrupt: [gap],
+ });
+ } else {
+ expect(await screen.findByText(i18n.t('settings.models.repair.repaired'))).toBeTruthy();
+ }
+
+ const close = screen.getByRole('button', { name: /^Close$|^关闭$/i }) as HTMLButtonElement;
+ expect(close.disabled).toBe(false);
+ expect(screen.queryByRole('button', { name: /^Retry$|^重试$/i })).toBeNull();
+ expect(settled.source).toHaveBeenCalledWith(current);
+ expect(settled.unread).not.toHaveBeenCalled();
+ if (path === 'inventory') expect(settled.readInventory).toHaveBeenCalledOnce();
+ else expect(settled.readInventory).not.toHaveBeenCalled();
+ expect(closeTimer.mock.calls.filter(([, delay]) => delay === 1400)).toHaveLength(
+ outcome === 'repaired' ? 1 : 0,
+ );
+ },
+ );
+
+ it('keeps Retry when an ambiguous replacement still observes the blocked source', async () => {
+ vi.spyOn(modelsApi, 'replaceCredential').mockRejectedValueOnce(
+ new ApiCallError('bad_response', undefined, false),
+ );
+ const settled = neverResolvingSettlement({
+ readInventory: vi.fn().mockResolvedValue({ snapshot: 2, sources: [blockedSource] }),
+ });
+ const closeTimer = vi.spyOn(window, 'setTimeout');
+ renderReplacement(blockedSource, settled);
+ const user = userEvent.setup();
+
+ await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-uncommitted');
+ await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
+
+ expect(await screen.findByText(/Couldn't replace the key|更换失败/i)).toBeTruthy();
+ expect(screen.getByRole('button', { name: /^Retry$|^重试$/i })).toBeTruthy();
+ expect(screen.queryByText(i18n.t('settings.models.repair.repaired'))).toBeNull();
+ expect(screen.queryByText(/^Removed hops$|^已移除的跳$/i)).toBeNull();
+ expect(settled.readInventory).toHaveBeenCalledOnce();
+ expect(settled.source).not.toHaveBeenCalled();
+ expect(settled.unread).not.toHaveBeenCalled();
+ expect(closeTimer.mock.calls.filter(([, delay]) => delay === 1400)).toHaveLength(0);
+ });
+
+ it.each([
+ { path: 'response', failureClass: 'authoritative-terminal', retries: false },
+ { path: 'inventory-missing', failureClass: 'authoritative-terminal', retries: false },
+ { path: 'inventory-unread', failureClass: 'inconclusive', retries: true },
+ ] as const)(
+ 'publishes the $path terminal failure before any trailing settlement resolves',
+ async ({ path, failureClass, retries }) => {
+ vi.spyOn(modelsApi, 'replaceCredential').mockRejectedValueOnce(new ApiCallError(
+ path === 'response' ? 'source_not_found' : 'bad_response',
+ undefined,
+ path === 'response',
+ ));
+ const inventory = { snapshot: 3, sources: [] as Source[] };
+ const settled = neverResolvingSettlement({
+ readInventory: path === 'inventory-unread'
+ ? vi.fn().mockRejectedValue(new Error('inventory unavailable'))
+ : vi.fn().mockResolvedValue(inventory),
+ });
+ renderReplacement(blockedSource, settled);
+ const user = userEvent.setup();
+
+ await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-failure');
+ await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
+
+ const failure = await screen.findByText(/Couldn't replace the key|更换失败/i);
+ expect(failure.closest('[data-failure-class]')?.getAttribute('data-failure-class')).toBe(failureClass);
+ expect(screen.getAllByRole('button', { name: /^Cancel$|^取消$/i }))
+ .toSatisfy((buttons: HTMLButtonElement[]) => buttons.every((button) => !button.disabled));
+ expect(screen.queryByRole('button', { name: /^Retry$|^重试$/i }) !== null).toBe(retries);
+ expect(screen.queryByText(i18n.t('settings.models.repair.repaired'))).toBeNull();
+ expect(settled.source).not.toHaveBeenCalled();
+
+ if (path === 'response') {
+ expect(settled.readInventory).not.toHaveBeenCalled();
+ expect(settled.gone).toHaveBeenCalledWith(blockedSource.id);
+ } else if (path === 'inventory-missing') {
+ expect(settled.readInventory).toHaveBeenCalledOnce();
+ expect(settled.gone).toHaveBeenCalledWith(blockedSource.id, inventory);
+ } else {
+ expect(settled.readInventory).toHaveBeenCalledOnce();
+ expect(settled.unread).toHaveBeenCalledOnce();
+ }
+ },
+ );
+
+ it.each([
+ ['discovery_failed', 'retryable-provider', true],
+ ['engine_down', 'inconclusive', true],
+ ['source_not_found', 'authoritative-terminal', false],
+ ] as const)(
+ 'renders %s through the shared %s failure taxonomy',
+ async (code, failureClass, retries) => {
+ vi.spyOn(modelsApi, 'replaceCredential').mockRejectedValueOnce(new ApiCallError(code));
+ renderReplacement();
+ const user = userEvent.setup();
+
+ await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-failure');
+ await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));
+
+ const failure = await screen.findByText(/Couldn't replace the key|更换失败/i);
+ expect(failure.closest('[data-failure-class]')?.getAttribute('data-failure-class')).toBe(failureClass);
+ expect(screen.queryByRole('button', { name: /^Retry$|^重试$/i }) !== null).toBe(retries);
+ },
+ );
});
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsx
index 66e5a89ad..57e67386a 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx
@@ -16,6 +16,7 @@ import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
+import { classifyModelHubFailure, type ModelHubFailureClass } from './asyncLifetime';
import { Field } from './dialogFields';
import {
classifyObservation,
@@ -26,17 +27,27 @@ import {
type AddApiKeyOrigin,
} from './addApiKeyState';
import type { CollectionReadAuthority } from './collectionReadAuthority';
+import { GuardImpact } from './GuardImpact';
import { apiFailure, modelsApi, type SourceCreated } from './modelsApi';
-import { createContinuationSettlement, createSourceCreatedDelivery, type ContinuationTicket } from './mutationSettlement';
+import {
+ createContinuationSettlement,
+ createSourceCreatedDelivery,
+ type ContinuationTicket,
+ type SourceMutationSettlement,
+ type TrackSourceMutation,
+} from './mutationSettlement';
import { reconcileUnknownWrite } from './reconcileUnknownWrite';
+import { mayHaveWritten, REPAIR_LINE_KEY, wasBlocked } from './repair';
import { serverText } from './serverCopy';
import {
SOURCE_DISPLAY_NAME_MAX_LENGTH,
SOURCE_PROTOCOLS,
type ApiKeySourceCreate,
+ type RouteHopRef,
type Source,
type SourceObservation,
type SourceProtocol,
+ type SupplyGap,
} from './types';
import { optionalTrimmedTextWithin } from './validation';
@@ -51,6 +62,41 @@ type Phase =
const INITIAL_PHASE: Phase = { kind: 'form', report: null };
+type ReplaceOutcome =
+ | { kind: 'repaired' }
+ | { kind: 'impact'; hops: RouteHopRef[]; gaps: SupplyGap[] };
+
+const replacementOutcomeFromEvidence = (
+ hops: RouteHopRef[] = [],
+ gaps: SupplyGap[] = [],
+): ReplaceOutcome => {
+ if (hops.length > 0 || gaps.length > 0) return { kind: 'impact', hops, gaps };
+ return { kind: 'repaired' };
+};
+
+type ReplacePhase =
+ | { kind: 'edit' }
+ | { kind: 'submitting' }
+ | { kind: 'guard'; hops: RouteHopRef[]; gaps: SupplyGap[] }
+ | { kind: 'done'; outcome: ReplaceOutcome }
+ | { kind: 'failure'; failureClass: ModelHubFailureClass };
+
+type AddApiKeyDialogProps = {
+ open: boolean;
+ onClose: () => void;
+} & (
+ | {
+ mode?: 'add';
+ onAdded: (created: SourceCreated) => void;
+ sourceReads: CollectionReadAuthority<Source[]>;
+ }
+ | {
+ mode: 'replace';
+ source: Source;
+ trackMutation: TrackSourceMutation;
+ }
+);
+
const sourceClientNonce = (): string => {
const uuid = globalThis.crypto.randomUUID?.();
if (uuid) return `scn_${uuid.replaceAll('-', '').toLowerCase()}`;
@@ -85,30 +131,90 @@ const failureMessageKey = (failure: ReturnType<typeof apiFailure>): string | nul
return failure.code || null;
};
-export const AddApiKeyDialog: React.FC<{
- open: boolean;
- onClose: () => void;
- onAdded: (created: SourceCreated) => void;
- sourceReads: CollectionReadAuthority<Source[]>;
-}> = ({ open, onClose, onAdded, sourceReads }) => {
+const REPLACE_FAILURE_KEY: Record<ModelHubFailureClass, string> = {
+ 'authoritative-terminal': 'settings.models.repair.replaceFailed',
+ inconclusive: 'settings.models.repair.replaceFailed',
+ 'retryable-provider': 'settings.models.repair.replaceFailed',
+};
+
+const ApiKeyField: React.FC<{
+ value: string;
+ revealed: boolean;
+ disabled: boolean;
+ label: React.ReactNode;
+ autoFocus?: boolean;
+ onChange: (value: string) => void;
+ onToggleReveal: () => void;
+ onEnter?: () => void;
+}> = ({ value, revealed, disabled, label, autoFocus, onChange, onToggleReveal, onEnter }) => {
+ const { t } = useTranslation();
+ return (
+ <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={label}>
+ {(id) => (
+ <span className="model-hub-add-key-secret relative flex items-center">
+ <Input
+ id={id}
+ value={value}
+ type={revealed ? 'text' : 'password'}
+ disabled={disabled}
+ autoFocus={autoFocus}
+ autoComplete="off"
+ spellCheck={false}
+ onChange={(event) => onChange(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' || disabled || !onEnter) return;
+ event.preventDefault();
+ onEnter();
+ }}
+ className="model-hub-add-key-input w-full pr-10 font-mono"
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="model-hub-ink-59 absolute right-1 size-7"
+ aria-label={t(`settings.models.addKey.field.apiKey.${revealed ? 'conceal' : 'reveal'}`)}
+ disabled={disabled}
+ onClick={onToggleReveal}
+ >
+ {revealed ? <EyeOff className="size-3.5" /> : <Eye className="size-3.5" />}
+ </Button>
+ </span>
+ )}
+ </Field>
+ );
+};
+
+export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
+ const { open, onClose } = props;
+ const replaceMode = props.mode === 'replace';
+ const addSourceReads = replaceMode ? null : props.sourceReads;
+ const addOnAdded = replaceMode ? null : props.onAdded;
+ const replaceSourceId = replaceMode ? props.source.id : null;
const { t } = useTranslation();
const [displayName, setDisplayName] = React.useState('');
const [baseUrl, setBaseUrl] = React.useState('');
const [apiKey, setApiKey] = React.useState('');
const [revealed, setRevealed] = React.useState(false);
const [phase, setPhase] = React.useState<Phase>(INITIAL_PHASE);
+ const [replacePhase, setReplacePhase] = React.useState<ReplacePhase>({ kind: 'edit' });
const [continuation] = React.useState(createContinuationSettlement);
const [createdDelivery] = React.useState(createSourceCreatedDelivery);
const clientNonce = React.useRef(sourceClientNonce());
const observationAbort = React.useRef<AbortController | null>(null);
+ const replaceCloseTimer = React.useRef<number | null>(null);
React.useEffect(() => {
- createdDelivery.update(onAdded, onClose);
- }, [createdDelivery, onAdded, onClose]);
+ if (addOnAdded) createdDelivery.update(addOnAdded, onClose);
+ }, [addOnAdded, createdDelivery, onClose]);
React.useEffect(() => {
continuation.invalidate();
observationAbort.current?.abort();
observationAbort.current = null;
+ if (replaceCloseTimer.current !== null) {
+ window.clearTimeout(replaceCloseTimer.current);
+ replaceCloseTimer.current = null;
+ }
if (open) {
clientNonce.current = sourceClientNonce();
setDisplayName('');
@@ -116,8 +222,41 @@ export const AddApiKeyDialog: React.FC<{
setApiKey('');
setRevealed(false);
setPhase(INITIAL_PHASE);
+ setReplacePhase({ kind: 'edit' });
}
- }, [continuation, open]);
+ return () => {
+ if (replaceCloseTimer.current !== null) {
+ window.clearTimeout(replaceCloseTimer.current);
+ replaceCloseTimer.current = null;
+ }
+ };
+ }, [continuation, open, replaceSourceId]);
+
+ const publishReplacementEvidence = React.useCallback((
+ seq: ContinuationTicket,
+ settlement: SourceMutationSettlement,
+ source: Source,
+ hops?: RouteHopRef[],
+ gaps?: SupplyGap[],
+ ) => {
+ const outcome = replacementOutcomeFromEvidence(hops, gaps);
+ const landed = continuation.settle(seq, () => setReplacePhase({ kind: 'done', outcome }));
+ if (landed === 'landed' && outcome.kind === 'repaired') {
+ replaceCloseTimer.current = window.setTimeout(onClose, 1400);
+ }
+ // Entity settlement applies synchronously; collection reconciliation is
+ // trailing work and cannot gate an outcome already established by evidence.
+ void settlement.source(source).catch(() => undefined);
+ }, [continuation, onClose]);
+
+ const publishReplacementFailure = React.useCallback((
+ seq: ContinuationTicket,
+ failureClass: ModelHubFailureClass,
+ settle?: () => Promise<void>,
+ ) => {
+ continuation.settle(seq, () => setReplacePhase({ kind: 'failure', failureClass }));
+ if (settle) void settle().catch(() => undefined);
+ }, [continuation]);
const draft = React.useCallback((protocolOrder?: SourceProtocol[]): ApiKeySourceCreate => ({
kind: 'api_key',
@@ -205,7 +344,94 @@ export const AddApiKeyDialog: React.FC<{
}
}, [apiKey, baseUrl, continuation, persist]);
+ const submitReplacement = React.useCallback(async (force: boolean) => {
+ if (props.mode !== 'replace' || !apiKey.trim() || replacePhase.kind === 'submitting') return;
+ const confirmation = force && replacePhase.kind === 'guard'
+ ? {
+ force: true as const,
+ would_remove_hops: replacePhase.hops,
+ would_interrupt: replacePhase.gaps,
+ }
+ : null;
+ if (force && !confirmation) return;
+ const key = apiKey.trim();
+ const seq = continuation.begin();
+ setReplacePhase({ kind: 'submitting' });
+ await props.trackMutation(async (latest, settlement) => {
+ try {
+ const answer = await modelsApi.replaceCredential(
+ latest.id,
+ confirmation ? { key, ...confirmation } : { key },
+ );
+ publishReplacementEvidence(
+ seq,
+ settlement,
+ answer.source,
+ answer.removed_hops,
+ answer.interrupted,
+ );
+ } catch (error) {
+ const failure = apiFailure(error);
+ if (failure && (failure.wouldRemoveHops.length > 0 || failure.wouldInterrupt.length > 0)) {
+ settlement.release();
+ continuation.settle(seq, () => setReplacePhase({
+ kind: 'guard',
+ hops: failure.wouldRemoveHops,
+ gaps: failure.wouldInterrupt,
+ }));
+ return;
+ }
+ let failureClass = classifyModelHubFailure(failure);
+ if (failure?.code === 'source_not_found') {
+ publishReplacementFailure(
+ seq,
+ failureClass,
+ () => settlement.gone(latest.id),
+ );
+ return;
+ } else if (mayHaveWritten(failure)) {
+ try {
+ const inventory = await settlement.readInventory();
+ const current = inventory.sources.find((source) => source.id === latest.id);
+ if (!current) {
+ failureClass = 'authoritative-terminal';
+ publishReplacementFailure(
+ seq,
+ failureClass,
+ () => settlement.gone(latest.id, inventory),
+ );
+ return;
+ } else if (!wasBlocked(current.state)) {
+ publishReplacementEvidence(
+ seq,
+ settlement,
+ current,
+ confirmation?.would_remove_hops,
+ confirmation?.would_interrupt,
+ );
+ return;
+ }
+ } catch {
+ publishReplacementFailure(seq, failureClass, settlement.unread);
+ return;
+ }
+ } else settlement.release();
+ publishReplacementFailure(seq, failureClass);
+ }
+ });
+ }, [apiKey, continuation, props, publishReplacementEvidence, publishReplacementFailure, replacePhase]);
+
const cancel = React.useCallback(() => {
+ if (replaceMode) {
+ if (replacePhase.kind === 'submitting') return;
+ if (replacePhase.kind === 'guard') {
+ setReplacePhase({ kind: 'edit' });
+ return;
+ }
+ continuation.invalidate();
+ onClose();
+ return;
+ }
if (phase.kind === 'working' && phase.stage === 'persist') return;
continuation.invalidate();
observationAbort.current?.abort();
@@ -215,7 +441,7 @@ export const AddApiKeyDialog: React.FC<{
return;
}
createdDelivery.close();
- }, [continuation, createdDelivery, phase]);
+ }, [continuation, createdDelivery, onClose, phase, replaceMode, replacePhase.kind]);
const retry = async () => {
if (phase.kind === 'undetermined') {
@@ -233,9 +459,10 @@ export const AddApiKeyDialog: React.FC<{
return;
}
if (phase.kind === 'save_unconfirmed') {
+ if (!addSourceReads) return;
const seq = continuation.begin();
const reconciliation = await reconcileUnknownWrite(
- () => sourceReads.readValue(),
+ () => addSourceReads.readValue(),
(sources) => sources.find((source) => source.client_nonce === clientNonce.current),
);
if (reconciliation.kind === 'committed') {
@@ -270,6 +497,7 @@ export const AddApiKeyDialog: React.FC<{
};
const editKey = (value: string) => {
setApiKey(value);
+ if (replaceMode && replacePhase.kind === 'failure') setReplacePhase({ kind: 'edit' });
if (phase.kind === 'form' && phase.report) setPhase(INITIAL_PHASE);
};
const editDisplayName = (value: string) => {
@@ -279,11 +507,18 @@ export const AddApiKeyDialog: React.FC<{
const isWorking = phase.kind === 'working';
const formLocked = isWorking || phase.kind === 'save_unconfirmed';
- const canCancel = !(phase.kind === 'working' && phase.stage === 'persist');
+ const canCancel = replaceMode
+ ? replacePhase.kind !== 'submitting'
+ : !(phase.kind === 'working' && phase.stage === 'persist');
const displayNameValid = optionalTrimmedTextWithin(displayName, SOURCE_DISPLAY_NAME_MAX_LENGTH);
const canObserve = Boolean(baseUrl.trim() && apiKey.trim()) && !formLocked;
const canSubmit = canObserve && displayNameValid;
const showForm = phase.kind !== 'undetermined' && phase.kind !== 'inventory';
+ const replaceTerminalFailure = replacePhase.kind === 'failure'
+ && replacePhase.failureClass === 'authoritative-terminal';
+ const replaceFieldLocked = replacePhase.kind === 'submitting'
+ || replacePhase.kind === 'done'
+ || replaceTerminalFailure;
return (
<DialogPrimitive.Root open={open} onOpenChange={(next) => !next && canCancel && cancel()}>
<DialogPrimitive.Portal>
@@ -296,14 +531,18 @@ export const AddApiKeyDialog: React.FC<{
<header className="model-hub-add-key-head flex flex-col border-b border-border px-5 py-4">
<div className="flex items-center justify-between gap-3">
<DialogPrimitive.Title className="model-hub-add-key-title font-bold text-foreground">
- {t('settings.models.addKey.title')}
+ {replaceMode
+ ? replacePhase.kind === 'guard'
+ ? t('settings.models.guard.title.replaceKey', { source: props.source.display_name })
+ : t('settings.models.repair.replaceTitle', { name: props.source.display_name })
+ : t('settings.models.addKey.title')}
</DialogPrimitive.Title>
<Button
type="button"
variant="ghost"
size="icon"
className="model-hub-ink-59 size-[27px]"
- aria-label={t('settings.models.addKey.cancel')}
+ aria-label={t(replacePhase.kind === 'guard' ? 'settings.models.guard.cancel' : 'settings.models.addKey.cancel')}
disabled={!canCancel}
onClick={cancel}
>
@@ -311,11 +550,71 @@ export const AddApiKeyDialog: React.FC<{
</Button>
</div>
<DialogPrimitive.Description className="model-hub-add-key-subtitle model-hub-ink-muted-b3 font-mono">
- {t('settings.models.addKey.subtitle')}
+ {replaceMode
+ ? replacePhase.kind === 'guard'
+ ? t('settings.models.guard.subtitle.replaceKey')
+ : t('settings.models.repair.replaceBody')
+ : t('settings.models.addKey.subtitle')}
</DialogPrimitive.Description>
</header>
- {showForm && (
+ {replaceMode && replacePhase.kind === 'guard' && (
+ <div className="model-hub-guard-body">
+ <GuardImpact hops={replacePhase.hops} gaps={replacePhase.gaps} />
+ </div>
+ )}
+
+ {replaceMode && replacePhase.kind !== 'guard' && (
+ <div className="model-hub-add-key-body flex flex-col">
+ <ApiKeyField
+ value={apiKey}
+ revealed={revealed}
+ disabled={replaceFieldLocked}
+ autoFocus
+ label={t('settings.models.repair.replaceLabel')}
+ onChange={editKey}
+ onToggleReveal={() => setRevealed((value) => !value)}
+ onEnter={replaceTerminalFailure ? undefined : () => void submitReplacement(false)}
+ />
+ {replacePhase.kind === 'submitting' && (
+ <div className="model-hub-add-key-strip model-hub-add-key-strip--working">
+ <LoaderCircle className="model-hub-ink-mint size-3.5 shrink-0 animate-spin" />
+ <span className="model-hub-add-key-strip-title text-foreground">{t('settings.models.repair.replacing')}</span>
+ </div>
+ )}
+ {replacePhase.kind === 'failure' && (
+ <div
+ className="model-hub-add-key-strip model-hub-add-key-strip--error"
+ data-failure-class={replacePhase.failureClass}
+ >
+ <TriangleAlert className="model-hub-add-key-error-ink size-3.5 shrink-0" />
+ <span className="model-hub-add-key-error-ink model-hub-add-key-strip-title">
+ {t(REPLACE_FAILURE_KEY[replacePhase.failureClass])}
+ </span>
+ </div>
+ )}
+ {replacePhase.kind === 'done' && replacePhase.outcome.kind === 'impact' && (
+ <div className="flex flex-col gap-2 rounded-lg border border-gold/40 bg-gold/[0.08] px-3.5 py-3">
+ <span className="model-hub-ink-gold text-[12.5px] font-semibold leading-relaxed">
+ {t('settings.models.repair.refreshed')}
+ </span>
+ <GuardImpact
+ hops={replacePhase.outcome.hops}
+ gaps={replacePhase.outcome.gaps}
+ committed
+ />
+ </div>
+ )}
+ {replacePhase.kind === 'done' && replacePhase.outcome.kind === 'repaired' && (
+ <div className="model-hub-ink-mint flex items-center gap-2 rounded-lg border border-mint/30 bg-mint-soft/50 px-4 py-3 text-[13px] font-medium">
+ <CheckCircle2 className="size-4 shrink-0" />
+ {t(REPAIR_LINE_KEY.repaired)}
+ </div>
+ )}
+ </div>
+ )}
+
+ {!replaceMode && showForm && (
<div className="model-hub-add-key-body flex flex-col">
<Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={t('settings.models.addKey.field.name')}>
{(id) => <Input id={id} value={displayName} disabled={formLocked} aria-invalid={!displayNameValid} onChange={(event) => editDisplayName(event.target.value)} className="model-hub-add-key-input" />}
@@ -323,9 +622,14 @@ export const AddApiKeyDialog: React.FC<{
<Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" hintClassName="model-hub-add-key-hint" label={t('settings.models.addKey.field.baseUrl')} hint={t('settings.models.addKey.field.baseUrl.hint')}>
{(id) => <Input id={id} value={baseUrl} disabled={formLocked} autoComplete="url" spellCheck={false} onChange={(event) => editEndpoint(event.target.value)} className="model-hub-add-key-input font-mono" />}
</Field>
- <Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={t('settings.models.addKey.field.apiKey')}>
- {(id) => <span className="model-hub-add-key-secret relative flex items-center"><Input id={id} value={apiKey} type={revealed ? 'text' : 'password'} disabled={formLocked} autoComplete="off" spellCheck={false} onChange={(event) => editKey(event.target.value)} className="model-hub-add-key-input w-full pr-10 font-mono" /><Button type="button" variant="ghost" size="icon" className="model-hub-ink-59 absolute right-1 size-7" aria-label={t(`settings.models.addKey.field.apiKey.${revealed ? 'conceal' : 'reveal'}`)} disabled={formLocked} onClick={() => setRevealed((value) => !value)}>{revealed ? <EyeOff className="size-3.5" /> : <Eye className="size-3.5" />}</Button></span>}
- </Field>
+ <ApiKeyField
+ value={apiKey}
+ revealed={revealed}
+ disabled={formLocked}
+ label={t('settings.models.addKey.field.apiKey')}
+ onChange={editKey}
+ onToggleReveal={() => setRevealed((value) => !value)}
+ />
{!isWorking && (
<div className="model-hub-add-key-test-row flex items-center justify-between gap-4">
@@ -388,7 +692,7 @@ export const AddApiKeyDialog: React.FC<{
</div>
)}
- {phase.kind === 'undetermined' && (
+ {!replaceMode && phase.kind === 'undetermined' && (
<div className="model-hub-add-key-outcome flex flex-col">
<div className="model-hub-add-key-outcome-wrap">
<div className="model-hub-add-key-strip model-hub-add-key-strip--advisory">
@@ -422,7 +726,7 @@ export const AddApiKeyDialog: React.FC<{
</div>
)}
- {phase.kind === 'inventory' && (
+ {!replaceMode && phase.kind === 'inventory' && (
<div className="model-hub-add-key-outcome-wrap">
<div className="model-hub-add-key-strip model-hub-add-key-strip--advisory model-hub-add-key-strip--inventory">
<TriangleAlert className="model-hub-ink-gold size-3.5 shrink-0" />
@@ -432,51 +736,89 @@ export const AddApiKeyDialog: React.FC<{
)}
<footer className="model-hub-add-key-foot model-hub-fill-05 flex flex-row items-center justify-end border-t border-border">
- <Button
- type="button"
- variant="outline"
- className="model-hub-add-key-action"
- disabled={!canCancel}
- onClick={cancel}
- >
- {t('settings.models.addKey.cancel')}
- </Button>
- {phase.kind === 'inventory' && phase.origin === 'add' && (
- <Button type="button" variant="outline" className="model-hub-add-key-action" onClick={() => void addAnyway()}>
- {t('settings.models.addKey.addAnyway')}
- </Button>
- )}
- {phase.kind === 'form' && (
- <Button
- type="button"
- variant="brand"
- className="model-hub-add-key-action"
- disabled={!canSubmit}
- onClick={() => void observe('add')}
- >
- {t('settings.models.addKey.submit')}
- </Button>
- )}
- {phase.kind === 'working' && (
- <Button type="button" variant="brand" className="model-hub-add-key-action" disabled>
- <LoaderCircle className="size-3 animate-spin" />
- {t('settings.models.addKey.adding')}
- </Button>
- )}
- {(phase.kind === 'failure' || phase.kind === 'persist_failure' || phase.kind === 'save_unconfirmed' || phase.kind === 'inventory' || phase.kind === 'undetermined') && (
- <Button
- type="button"
- variant="brand"
- className={cn(
- 'model-hub-add-key-action',
- (phase.kind === 'inventory' || phase.kind === 'save_unconfirmed' || (phase.kind === 'undetermined' && !phase.hint))
- && 'model-hub-add-key-action--dim',
+ {replaceMode ? (
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ className="model-hub-add-key-action"
+ disabled={!canCancel}
+ onClick={cancel}
+ >
+ {t(replacePhase.kind === 'done'
+ ? 'common.close'
+ : replacePhase.kind === 'guard'
+ ? 'settings.models.guard.cancel'
+ : 'settings.models.addKey.cancel')}
+ </Button>
+ {replacePhase.kind !== 'done' && !replaceTerminalFailure && (
+ <Button
+ type="button"
+ variant={replacePhase.kind === 'guard' ? 'destructive' : 'brand'}
+ className="model-hub-add-key-action"
+ disabled={replacePhase.kind === 'submitting' || !apiKey.trim()}
+ onClick={() => void submitReplacement(replacePhase.kind === 'guard')}
+ >
+ {replacePhase.kind === 'submitting' && <LoaderCircle className="size-3 animate-spin" />}
+ {t(replacePhase.kind === 'submitting'
+ ? 'settings.models.repair.replacing'
+ : replacePhase.kind === 'guard'
+ ? 'settings.models.guard.confirm.replaceKey'
+ : replacePhase.kind === 'failure'
+ ? 'settings.models.addKey.retry'
+ : 'settings.models.repair.replaceSubmit')}
+ </Button>
)}
- disabled={phase.kind === 'undetermined' && !phase.hint}
- onClick={() => void retry()}
- >
- {t('settings.models.addKey.retry')}
- </Button>
+ </>
+ ) : (
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ className="model-hub-add-key-action"
+ disabled={!canCancel}
+ onClick={cancel}
+ >
+ {t('settings.models.addKey.cancel')}
+ </Button>
+ {phase.kind === 'inventory' && phase.origin === 'add' && (
+ <Button type="button" variant="outline" className="model-hub-add-key-action" onClick={() => void addAnyway()}>
+ {t('settings.models.addKey.addAnyway')}
+ </Button>
+ )}
+ {phase.kind === 'form' && (
+ <Button
+ type="button"
+ variant="brand"
+ className="model-hub-add-key-action"
+ disabled={!canSubmit}
+ onClick={() => void observe('add')}
+ >
+ {t('settings.models.addKey.submit')}
+ </Button>
+ )}
+ {phase.kind === 'working' && (
+ <Button type="button" variant="brand" className="model-hub-add-key-action" disabled>
+ <LoaderCircle className="size-3 animate-spin" />
+ {t('settings.models.addKey.adding')}
+ </Button>
+ )}
+ {(phase.kind === 'failure' || phase.kind === 'persist_failure' || phase.kind === 'save_unconfirmed' || phase.kind === 'inventory' || phase.kind === 'undetermined') && (
+ <Button
+ type="button"
+ variant="brand"
+ className={cn(
+ 'model-hub-add-key-action',
+ (phase.kind === 'inventory' || phase.kind === 'save_unconfirmed' || (phase.kind === 'undetermined' && !phase.hint))
+ && 'model-hub-add-key-action--dim',
+ )}
+ disabled={phase.kind === 'undetermined' && !phase.hint}
+ onClick={() => void retry()}
+ >
+ {t('settings.models.addKey.retry')}
+ </Button>
+ )}
+ </>
)}
</footer>
</DialogPrimitive.Content>
diff --git a/ui/src/components/settings/models/GuardGapList.tsx b/ui/src/components/settings/models/GuardGapList.tsx
index 1a498d8d0..fce004d0b 100644
--- a/ui/src/components/settings/models/GuardGapList.tsx
+++ b/ui/src/components/settings/models/GuardGapList.tsx
@@ -3,13 +3,16 @@ import { useTranslation } from "react-i18next";
import type { SupplyGap } from "./types";
-export const GuardGapList: React.FC<{ gaps: SupplyGap[] }> = ({ gaps }) => {
+export const GuardGapList: React.FC<{ gaps: SupplyGap[]; labelKey?: string }> = ({
+ gaps,
+ labelKey = "settings.models.guard.gap.label",
+}) => {
const { t, i18n } = useTranslation();
if (gaps.length === 0) return null;
return (
<>
<div className="model-hub-guard-label">
- <p>{t("settings.models.guard.gap.label")}</p>
+ <p>{t(labelKey)}</p>
<span>
{t("settings.models.gateway.modelCount", { count: gaps.length })}
</span>
diff --git a/ui/src/components/settings/models/GuardImpact.tsx b/ui/src/components/settings/models/GuardImpact.tsx
new file mode 100644
index 000000000..7c7f111c5
--- /dev/null
+++ b/ui/src/components/settings/models/GuardImpact.tsx
@@ -0,0 +1,51 @@
+import * as React from 'react';
+import { Info } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { cn } from '@/lib/utils';
+import { GuardGapList } from './GuardGapList';
+import type { RouteHopRef, SupplyGap } from './types';
+
+/** The shared evidence body for every guarded Model Hub mutation and its result. */
+export const GuardImpact: React.FC<{
+ hops: RouteHopRef[];
+ gaps: SupplyGap[];
+ committed?: boolean;
+}> = ({ hops, gaps, committed = false }) => {
+ const { t } = useTranslation();
+ return (
+ <>
+ {hops.length > 0 && (
+ <>
+ <div className="model-hub-guard-label">
+ <p>{t(committed ? 'settings.models.guard.result.label' : 'settings.models.guard.label')}</p>
+ <span>{t('settings.models.guard.count', { count: hops.length })}</span>
+ </div>
+ <div className="model-hub-guard-list">
+ {hops.map((hop) => (
+ <div
+ key={`${hop.backend}:${hop.menu_model}:${hop.position}:${hop.source_id}:${hop.model_id}`}
+ className="model-hub-guard-hop"
+ >
+ <span className="min-w-0 flex-1">
+ <strong>
+ {t(`settings.models.backends.${hop.backend}`, { defaultValue: hop.backend })} · {hop.menu_model}
+ </strong>
+ <span>{hop.model_id} · {t('settings.models.guard.hop.position', { n: hop.position })}</span>
+ </span>
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ <GuardGapList
+ gaps={gaps}
+ labelKey={committed ? 'settings.models.guard.result.gapLabel' : undefined}
+ />
+ <p className={cn('model-hub-guard-hint', gaps.length > 0 && 'text-destructive-ink')}>
+ <Info aria-hidden />
+ {t(`settings.models.guard.${committed ? 'result.' : ''}hint.${gaps.length > 0 ? 'interrupt' : 'safe'}`)}
+ </p>
+ </>
+ );
+};
diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
index 0e6c6760d..831e46dac 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
@@ -13,7 +13,7 @@ import { createPendingWrites } from './asyncLifetime';
import { modelsApi } from './modelsApi';
import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
import { GuardGapList } from './GuardGapList';
-import { repairAction } from './repair';
+import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, repairAction, type RepairKind } from './repair';
import { SourceDetailPanel } from './SourceDetailPanel';
import {
COOLDOWN_DETAIL_KEYS,
@@ -33,6 +33,7 @@ const source: Source = {
base_url: 'https://relay.example/v1',
supply_channel: 'hub',
billing: 'metered',
+ credential_ref: 'cred_detail',
state: { status: 'active', retry_at: null, detail_key: null },
models: [{ id: 'model-a', display_name: null, origin: 'manual', reasoning_efforts: ['high'] }],
};
@@ -453,14 +454,11 @@ describe('SourceDetailPanel', () => {
expect(screen.queryByRole('button', { name: /^Try again$|^重试$/i })).toBeNull();
});
- // The property, not the rows that satisfy it today: the entry is offered exactly
- // when `repairAction` — the module that owns 「which remedy this source has」 —
- // names a re-login. Seeding is complete by construction, so a status, cause,
- // kind or channel added later is swept without editing this test: the two
- // vocabularies are the const arrays `contractLocaleKeys` pins to the schema, and
- // the two unions are enumerated through `satisfies`, which stops compiling when
- // a member appears.
- it('offers the re-login entry exactly where repairAction names one', () => {
+ // The property, not today's button list: every remedy the authority can return
+ // reaches the control declared by its total destination Record. Seeding is
+ // complete by construction, so a new status/cause/kind/channel is swept without
+ // editing the test, while a new RepairKind fails the Record/type checks first.
+ it('gives every repair kind a reachable declared destination', () => {
const kinds = Object.keys({ subscription: 0, api_key: 0 } satisfies Record<SourceKind, 0>) as SourceKind[];
const channels = Object.keys({ native_cli: 0, hub: 0 } satisfies Record<SupplyChannel, 0>) as SupplyChannel[];
const causes: (SourceDetailKey | null)[] = [
@@ -477,6 +475,7 @@ describe('SourceDetailPanel', () => {
state: { status, retry_at: null, detail_key },
})),
)));
+ const reached = new Set<RepairKind>();
for (const shape of shapes) {
const view = render(
@@ -484,11 +483,43 @@ describe('SourceDetailPanel', () => {
<SourceDetailPanel source={shape} trackMutation={immediateTrack} onReauth={vi.fn()} />
</I18nextProvider>,
);
- const offered = screen.queryAllByRole('button', { name: /^Sign in$|^重新登录$/i }).length > 0;
- expect(offered, JSON.stringify({ kind: shape.kind, channel: shape.supply_channel, ...shape.state }))
- .toBe(repairAction(shape) === 'reauth');
+ const action = repairAction(shape);
+ const offered = view.container.querySelectorAll('[data-repair-kind]');
+ expect(offered.length, JSON.stringify({ kind: shape.kind, channel: shape.supply_channel, ...shape.state }))
+ .toBe(action ? 1 : 0);
+ if (action) {
+ reached.add(action);
+ expect(offered[0].getAttribute('data-repair-kind')).toBe(action);
+ expect(offered[0].getAttribute('data-repair-destination')).toBe(REPAIR_DESTINATION[action]);
+ }
view.unmount();
}
+
+ expect(reached).toEqual(new Set(Object.keys(REPAIR_LABEL_KEY) as RepairKind[]));
+ });
+
+ it('opens key replacement from the revoked hub credential repair tap', async () => {
+ render(
+ <I18nextProvider i18n={i18n}>
+ <SourceDetailPanel
+ source={{
+ ...source,
+ state: {
+ status: 'needs_action',
+ retry_at: null,
+ detail_key: 'models.source.needs_action.credential_revoked',
+ },
+ }}
+ trackMutation={immediateTrack}
+ onReauth={vi.fn()}
+ />
+ </I18nextProvider>,
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: /^Replace key$|^更换 Key$/i }));
+
+ expect(await screen.findByRole('dialog', { name: /Replace the API key|更换.*API Key/i })).toBeTruthy();
+ expect(screen.getByLabelText(/^New API key$|^新的 API Key$/i)).toBeTruthy();
});
it('confirms a native re-login with the cost it pays at start before handing the source up', async () => {
diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsx
index bbe6d82fe..f13565da6 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx
@@ -8,13 +8,14 @@ import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { Input } from '@/components/ui/input';
import { ResponsiveMenu } from '@/components/ui/responsive-menu';
import { cn } from '@/lib/utils';
-import { GuardGapList } from './GuardGapList';
import { formatRelativeTime } from '@/lib/relativeTime';
+import { AddApiKeyDialog } from './AddApiKeyDialog';
+import { GuardImpact } from './GuardImpact';
import { apiFailure, modelsApi, type GuardConfirmation } from './modelsApi';
import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';
import { handOffProviderTab } from './providerTab';
import { reconcileUnknownWrite } from './reconcileUnknownWrite';
-import { REPAIR_LABEL_KEY, reauthBodyKey, reauthCost, repairAction } from './repair';
+import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, reauthBodyKey, reauthCost, repairAction } from './repair';
import { sourceStatePresentation } from './sourceStatePresentation';
import { tierMutationPayload, type TierMutationIntent } from './tierMutation';
import { useDeadlineClock } from './useDeadlineClock';
@@ -223,6 +224,7 @@ export const SourceDetailPanel: React.FC<{
const { Icon, accent } = sourceVisual(source);
const [busy, setBusy] = React.useState(false);
const [confirmingReauth, setConfirmingReauth] = React.useState(false);
+ const [replacingKey, setReplacingKey] = React.useState(false);
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);
@@ -405,13 +407,11 @@ export const SourceDetailPanel: React.FC<{
native: source.supply_channel === 'native_cli',
});
const host = enteredHost(source);
- // `repairAction` is the authority on which remedy a stopped source has, so the
- // condition is 「this source's one tap IS a re-login」 rather than a status list
- // this file would have to keep in step with it. `retest` needs no entry of its
- // own — it is the same `POST …/refresh` the 重新拉取 button beside this one
- // already runs — and `replace_key` has no dialog in the UI yet (ledgered as
- // follow-up), so neither renders here.
+ // One authority picks the remedy and another total Record names its concrete
+ // control. In particular, `retest` points at the existing refetch button; it is
+ // not a special case that can fall out of destination-completeness checks.
const repair = repairAction(source);
+ const repairDestination = repair ? REPAIR_DESTINATION[repair] : null;
return (
<div className="model-hub-source-detail">
@@ -426,8 +426,9 @@ export const SourceDetailPanel: React.FC<{
<p className="model-hub-source-summary mt-1 truncate font-mono">{t(host ? 'settings.models.sourceDetail.summary' : 'settings.models.gateway.modelCount', { host, count: source.models.length })}</p>
</div>
<div className="flex shrink-0 gap-2">
- {repair === 'reauth' && <Button size="sm" className="model-hub-source-action" disabled={busy} onClick={() => setConfirmingReauth(true)}><LogIn />{t(REPAIR_LABEL_KEY.reauth)}</Button>}
- {source.supply_channel === 'hub' && <Button variant="outline" size="sm" className="model-hub-source-action" disabled={busy} onClick={() => void refetch()}>{busy ? <Loader2 className="animate-spin" /> : <RefreshCw />}{t('settings.models.sourceDetail.action.refetch')}</Button>}
+ {repairDestination === 'reauth_dialog' && <Button size="sm" className="model-hub-source-action" data-repair-kind={repair} data-repair-destination={repairDestination} disabled={busy} onClick={() => setConfirmingReauth(true)}><LogIn />{t(REPAIR_LABEL_KEY.reauth)}</Button>}
+ {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>}
</div>
</section>
@@ -508,6 +509,13 @@ export const SourceDetailPanel: React.FC<{
onReauth(source);
}}
/>
+ <AddApiKeyDialog
+ mode="replace"
+ open={replacingKey}
+ source={source}
+ trackMutation={trackMutation}
+ onClose={() => setReplacingKey(false)}
+ />
<DialogPrimitive.Root open={guard !== null} onOpenChange={(open) => !open && !busy && setGuard(null)}>
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="model-hub-guard-overlay fixed inset-0 z-50" />
@@ -519,14 +527,7 @@ export const SourceDetailPanel: React.FC<{
</div>
<DialogPrimitive.Description className="model-hub-guard-subtitle">{t(`settings.models.guard.subtitle.${guard?.kind === 'remove' ? 'removeModel' : 'refetch'}`)}</DialogPrimitive.Description>
</header>
- {guard && <div className="model-hub-guard-body">
- {guard.hops.length > 0 && <>
- <div className="model-hub-guard-label"><p>{t('settings.models.guard.label')}</p><span>{t('settings.models.guard.count', { count: guard.hops.length })}</span></div>
- <div className="model-hub-guard-list">{guard.hops.map((hop) => <div key={`${hop.backend}:${hop.menu_model}:${hop.position}:${hop.source_id}:${hop.model_id}`} className="model-hub-guard-hop"><span className="min-w-0 flex-1"><strong>{t(`settings.models.backends.${hop.backend}`, { defaultValue: hop.backend })} · {hop.menu_model}</strong><span>{hop.model_id} · {t('settings.models.guard.hop.position', { n: hop.position })}</span></span></div>)}</div>
- </>}
- <GuardGapList gaps={guard.gaps} />
- <p className={cn('model-hub-guard-hint', guard.gaps.length > 0 && 'text-destructive-ink')}><Info aria-hidden />{t(`settings.models.guard.hint.${guard.gaps.length > 0 ? 'interrupt' : 'safe'}`)}</p>
- </div>}
+ {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>
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.ts
index ae649be6a..241a948e2 100644
--- a/ui/src/components/settings/models/asyncLifetime.test.ts
+++ b/ui/src/components/settings/models/asyncLifetime.test.ts
@@ -63,6 +63,7 @@ import { describe, expect, it } from 'vitest';
import {
agentsWithEcho,
+ classifyModelHubFailure,
classifyOAuthFailure,
createFlowAuthority,
createLatestAsyncAuthority,
@@ -754,24 +755,25 @@ describe('flow authority', () => {
});
});
-describe('OAuth failure classification', () => {
+describe('Model Hub failure classification', () => {
const named = (code: string) => ({ serverNamed: true, code });
it('keeps transport failures and engine outages inconclusive', () => {
- expect(classifyOAuthFailure(null)).toBe('inconclusive');
- expect(classifyOAuthFailure({ serverNamed: false, code: 'bad_response' })).toBe('inconclusive');
- expect(classifyOAuthFailure(named('engine_down'))).toBe('inconclusive');
- expect(classifyOAuthFailure(named('modelHub.errors.engine_down'))).toBe('inconclusive');
+ expect(classifyModelHubFailure(null)).toBe('inconclusive');
+ expect(classifyModelHubFailure({ serverNamed: false, code: 'bad_response' })).toBe('inconclusive');
+ expect(classifyModelHubFailure(named('engine_down'))).toBe('inconclusive');
+ expect(classifyModelHubFailure(named('modelHub.errors.engine_down'))).toBe('inconclusive');
});
it.each(['source_not_found', 'flow_settled', 'already_connected'])(
'treats %s as an authoritative terminal',
(code) => {
- expect(classifyOAuthFailure(named(code))).toBe('authoritative-terminal');
+ expect(classifyModelHubFailure(named(code))).toBe('authoritative-terminal');
},
);
it('defaults other server-named failures to retryable provider failures', () => {
+ expect(classifyModelHubFailure(named('discovery_failed'))).toBe('retryable-provider');
expect(classifyOAuthFailure(named('discovery_failed'))).toBe('retryable-provider');
});
diff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.ts
index 5ea46b803..35a1e6f0e 100644
--- a/ui/src/components/settings/models/asyncLifetime.ts
+++ b/ui/src/components/settings/models/asyncLifetime.ts
@@ -358,12 +358,14 @@ export type FlowEvent =
*/
export type FlowAction = 'continue' | 'succeed' | 'fail' | 'timeout' | 'ignore';
-export type OAuthFailureClass =
+export type ModelHubFailureClass =
| 'authoritative-terminal'
| 'inconclusive'
| 'retryable-provider';
-type OAuthFailureEvidence = {
+export type OAuthFailureClass = ModelHubFailureClass;
+
+type ModelHubFailureEvidence = {
serverNamed: boolean;
code?: string;
detail?: string;
@@ -376,7 +378,7 @@ const AUTHORITATIVE_TERMINAL_CODES = new Set([
]);
/** One classification shared by polling, timeout recovery, and Retry. */
-export const classifyOAuthFailure = (failure: OAuthFailureEvidence): OAuthFailureClass => {
+export const classifyModelHubFailure = (failure: ModelHubFailureEvidence): ModelHubFailureClass => {
const rawCode = failure?.code ?? failure?.detail;
const code = rawCode?.startsWith('modelHub.errors.')
? rawCode.slice('modelHub.errors.'.length)
@@ -387,6 +389,8 @@ export const classifyOAuthFailure = (failure: OAuthFailureEvidence): OAuthFailur
: 'retryable-provider';
};
+export const classifyOAuthFailure = classifyModelHubFailure;
+
/** Everything that decides what the dialog shows, including its terminal latch. */
export type FlowView = {
flow: OAuthFlow | null;
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index badedd976..2be516000 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -58,6 +58,11 @@ import { AGENT_CHAIN_CONTRACT_VERSION, CONTRACT_VERSION, PROBE_RESULT_CONTRACT_V
export type Adoption = { added_to: AddedTo[]; adopted_by: AdoptedBy[] };
export type SourceCreated = { source: Source } & Adoption;
export type SourceRefresh = { source: Source; discovered: number };
+export type CredentialReplacement = {
+ source: Source;
+ removed_hops: RouteHopRef[];
+ interrupted: SupplyGap[];
+};
export type GuardConfirmation = {
force: true;
would_remove_hops: RouteHopRef[];
@@ -101,12 +106,11 @@ export type ModelsApi = {
* 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. `force` overrides the only-supplier guard. */
- deleteSource(id: string, force?: boolean): Promise<void>;
- /** Replace the credential of a hub-channel api_key source. Refuses with
- * `source_last_supplier` + `would_interrupt` when the replacement set would
- * strand a selected model; `force` commits anyway. */
- replaceCredential(id: string, body: CredentialReplace): Promise<SourceRepaired>;
+ /** Delete a source. A destructive retry echoes the server's exact guard plan. */
+ deleteSource(id: string, confirmation?: GuardConfirmation): Promise<void>;
+ /** 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>;
/** Start re-authorization for a subscription source. Irreversible once it
* begins, which is why the acknowledgement is sent unconditionally — the
* server rejects a native source without it (`reauth_confirmation_required`).
@@ -322,13 +326,16 @@ const created = (r: SourceCreatedResponse): SourceCreated => ({
...adoption(r),
});
-/** api.md "recovery symmetry": both repair routes answer with this same tail,
- * so both unwrap through one reader. */
-type SourceRepairedResponse = { source?: Source; recovered?: boolean; interrupted_pairs?: SupplyGap[] } & Source;
-const repaired = (r: SourceRepairedResponse): SourceRepaired => ({
+type CredentialReplacementResponse = {
+ source?: Source;
+ removed_hops?: RouteHopRef[];
+ interrupted?: SupplyGap[];
+} & Source;
+
+const credentialReplacement = (r: CredentialReplacementResponse): CredentialReplacement => ({
source: (r.source ?? r) as Source,
- recovered: r.recovered === true,
- interrupted_pairs: supplyGaps(r.interrupted_pairs),
+ removed_hops: routeHopRefs(r.removed_hops),
+ interrupted: supplyGaps(r.interrupted),
});
/** The oauth terminal envelope, unwrapped without discarding either tail. */
@@ -382,15 +389,20 @@ const liveApi: ModelsApi = {
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),
refreshSource: (id, confirmation) => call<SourceRefresh>(`/api/models/sources/${encodeURIComponent(id)}/refresh`, jsonInit('POST', confirmation ?? {})),
- deleteSource: (id, force) => call(`/api/models/sources/${encodeURIComponent(id)}${force ? '?force=true' : ''}`, jsonInit('DELETE')).then(() => undefined),
+ deleteSource: (id, confirmation) => call(
+ `/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),
// 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.
- replaceCredential: (id, body) => call<SourceRepairedResponse>(`/api/models/sources/${encodeURIComponent(id)}/credential`, jsonInit('PUT', body)).then(repaired),
- // The acknowledgement is unconditional by design: the server enforces it for
- // native sources pre-login, and api.md's per-channel truth makes a hub grant
- // replacement equally irreversible once new material is written. One confirm,
- // no channel branch.
+ replaceCredential: (id, body) => call<CredentialReplacementResponse>(`/api/models/sources/${encodeURIComponent(id)}/credential`, jsonInit('PUT', body)).then(credentialReplacement),
+ // The OAuth acknowledgement is unconditional because beginning reauth may
+ // irreversibly replace grant material. It does not stand in for destructive
+ // supply consent: guarded inventory mutations separately echo the server plan.
reauthSource: (id) => call<{ flow?: OAuthFlow } & OAuthFlow>(`/api/models/sources/${encodeURIComponent(id)}/reauth`, jsonInit('POST', { acknowledge_irreversible: true })).then((r) => (r.flow ?? r) as OAuthFlow),
listAgents: () => call<{ agents: AgentSupply[] }>('/api/models/agents').then((r) => r.agents),
getAgentSources: (backend) => call<{ agent: AgentSupply }>(`/api/models/agents/${backend}/sources`).then((r) => r.agent),
@@ -670,14 +682,14 @@ class MockStore {
return gaps;
}
- deleteSource(id: string, force = false) {
+ deleteSource(id: string, confirmation?: GuardConfirmation) {
this.syncAgents();
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 && !force)
+ if (gaps.length > 0 && !confirmation)
throw new ApiCallError('source_last_supplier', undefined, true, gaps);
this.sources = remaining;
// Orders and the rollup are recomputed on the next read (syncAgents).
@@ -709,10 +721,7 @@ class MockStore {
throw new ApiCallError('source_last_supplier', undefined, true, interrupted);
}
this.syncAgents();
- return delay(
- { source: structuredClone(source), recovered, interrupted_pairs: interrupted },
- 700,
- );
+ return delay({ source: structuredClone(source), removed_hops: [], interrupted }, 700);
}
reauthSource(id: string) {
@@ -1326,7 +1335,7 @@ const mockApi: ModelsApi = {
createApiKeySource: (draft) => mockStore.createApiKeySource(draft),
patchSource: (id, patch) => mockStore.patchSource(id, patch),
refreshSource: (id, confirmation) => mockStore.refreshSource(id, confirmation),
- deleteSource: (id, force) => mockStore.deleteSource(id, force),
+ deleteSource: (id, confirmation) => mockStore.deleteSource(id, confirmation),
replaceCredential: (id, body) => mockStore.replaceCredential(id, body),
reauthSource: (id) => mockStore.reauthSource(id),
listAgents: () => mockStore.listAgents(),
diff --git a/ui/src/components/settings/models/repair.test.ts b/ui/src/components/settings/models/repair.test.ts
index 0b440a587..5db7fd166 100644
--- a/ui/src/components/settings/models/repair.test.ts
+++ b/ui/src/components/settings/models/repair.test.ts
@@ -294,6 +294,18 @@ describe('the copy each remedy names', () => {
for (const bundle of [en, zh]) expect(typeof translated(bundle, key)).toBe('string');
});
+ it.each([
+ 'settings.models.guard.title.replaceKey',
+ 'settings.models.guard.subtitle.replaceKey',
+ 'settings.models.guard.confirm.replaceKey',
+ 'settings.models.guard.result.label',
+ 'settings.models.guard.result.gapLabel',
+ 'settings.models.guard.result.hint.safe',
+ 'settings.models.guard.result.hint.interrupt',
+ ])('has replacement guard copy in both locales for %s', (key) => {
+ for (const bundle of [en, zh]) expect(typeof translated(bundle, key)).toBe('string');
+ });
+
it('warns up front on a native re-login and only about failure on a hub one', () => {
// `mark_native_irreversible_start` rewrites every native source of that
// vendor's backend to 需要处理 as the login spawns, so 「开始后旧的登录立即失效」
diff --git a/ui/src/components/settings/models/repair.ts b/ui/src/components/settings/models/repair.ts
index bfa69e7ac..01e242d96 100644
--- a/ui/src/components/settings/models/repair.ts
+++ b/ui/src/components/settings/models/repair.ts
@@ -132,6 +132,20 @@ export const REPAIR_LABEL_KEY: Record<RepairKind, string> = {
retest: 'settings.models.repair.retest',
};
+/**
+ * The concrete control each remedy reaches. This is deliberately another total
+ * Record over `RepairKind`: a label without a destination is still the dead end
+ * this module exists to prevent. `retest` names the existing refetch control,
+ * rather than being treated as an exception by the component or its test.
+ */
+export type RepairDestination = 'reauth_dialog' | 'replace_key_dialog' | 'refetch_button';
+
+export const REPAIR_DESTINATION: Record<RepairKind, RepairDestination> = {
+ reauth: 'reauth_dialog',
+ replace_key: 'replace_key_dialog',
+ retest: 'refetch_button',
+};
+
/**
* What STARTING a re-login costs on this source's channel — the confirm's whole
* subject, and the one thing about it the two channels do not share.
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 6eee04c70..41feda904 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -584,6 +584,9 @@ export type OAuthSourceCreate = {
export type SourcePatch = {
display_name?: string;
base_url?: string | null;
+ force?: boolean;
+ would_remove_hops?: RouteHopRef[];
+ would_interrupt?: SupplyGap[];
};
/** PUT /api/models/agents/<backend>/sources — replaces the complete order. */
@@ -608,7 +611,12 @@ export type AgentChainMutation = {
* Also a TOTAL body that rejects unknown keys (`contract_version` included), so
* `force` is omitted rather than sent false on the unguarded first attempt.
*/
-export type CredentialReplace = { key: string; force?: boolean };
+export type CredentialReplace = {
+ key: string;
+ force?: boolean;
+ would_remove_hops?: RouteHopRef[];
+ would_interrupt?: SupplyGap[];
+};
/**
* POST /api/models/sources/<id>/reauth. The acknowledgement is server-enforced
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index f5a71131b..fc1a658d2 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1339,21 +1339,32 @@
"subject": "{{backend}} · {{menuModel}}",
"agents": "Agents pinned to it: {{agents}}"
},
+ "result": {
+ "label": "Removed hops",
+ "gapLabel": "Models left with no source",
+ "hint": {
+ "safe": "These models still have another source available.",
+ "interrupt": "Some models now have no usable source."
+ }
+ },
"cancel": "Cancel",
"title": {
"refetch": "Refetch models from {{source}}",
"removeModel": "Remove {{model}} from {{source}}",
- "saveRoute": "Save the route chain for {{menuModel}}"
+ "saveRoute": "Save the route chain for {{menuModel}}",
+ "replaceKey": "Replace key for {{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"
+ "saveRoute": "This save leaves a configured model with no usable source",
+ "replaceKey": "The replacement changes this source's model inventory."
},
"confirm": {
"refetch": "Refetch anyway",
"removeModel": "Remove anyway",
- "saveRoute": "Save anyway"
+ "saveRoute": "Save anyway",
+ "replaceKey": "Replace anyway"
}
},
"repair": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 547e3f23c..188cc3b78 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1339,21 +1339,32 @@
"subject": "{{backend}} · {{menuModel}}",
"agents": "已指定它的 Agent:{{agents}}"
},
+ "result": {
+ "label": "已移除的跳",
+ "gapLabel": "已经没有可用来源的型号",
+ "hint": {
+ "safe": "这些型号仍有别的来源可用。",
+ "interrupt": "有型号现在没有可用来源。"
+ }
+ },
"cancel": "取消",
"title": {
"refetch": "重新拉取 {{source}} 的型号",
"removeModel": "从 {{source}} 移除 {{model}}",
- "saveRoute": "保存 {{menuModel}} 的路由链"
+ "saveRoute": "保存 {{menuModel}} 的路由链",
+ "replaceKey": "更换 {{source}} 的 Key"
},
"subtitle": {
"refetch": "这次拉取会让部分型号从这个来源的清单里消失。",
"removeModel": "这个型号会从这个来源的清单里消失。",
- "saveRoute": "这次保存会让已配置的型号没有可用来源"
+ "saveRoute": "这次保存会让已配置的型号没有可用来源",
+ "replaceKey": "这次更换会改变这个来源的型号清单。"
},
"confirm": {
"refetch": "仍要拉取",
"removeModel": "仍要移除",
- "saveRoute": "仍要保存"
+ "saveRoute": "仍要保存",
+ "replaceKey": "仍要更换"
}
},
"repair": {
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index f3dad2d76..eb7ddc1f2 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -103,11 +103,41 @@ class ModelHubRemoteService:
{"source_id": source_id, "reauth": payload},
)
- async def delete_source(self, source_id: str, *, force: bool = False) -> dict:
- return await _rpc("delete_source", {"source_id": source_id, "force": force})
+ async def delete_source(
+ self,
+ source_id: str,
+ *,
+ force: bool = False,
+ confirmed_remove_hops: object = None,
+ confirmed_interruptions: object = None,
+ ) -> dict:
+ return await _rpc(
+ "delete_source",
+ {
+ "source_id": source_id,
+ "force": force,
+ "would_remove_hops": confirmed_remove_hops,
+ "would_interrupt": confirmed_interruptions,
+ },
+ )
- async def refresh_source(self, source_id: str, *, force: bool = False) -> dict:
- return await _rpc("refresh_source", {"source_id": source_id, "force": force})
+ async def refresh_source(
+ self,
+ source_id: str,
+ *,
+ force: bool = False,
+ confirmed_remove_hops: object = None,
+ confirmed_interruptions: object = None,
+ ) -> dict:
+ return await _rpc(
+ "refresh_source",
+ {
+ "source_id": source_id,
+ "force": force,
+ "would_remove_hops": confirmed_remove_hops,
+ "would_interrupt": confirmed_interruptions,
+ },
+ )
def list_agents(self) -> list[dict]:
return _rpc_sync("list_agents")
@@ -156,10 +186,18 @@ class ModelHubRemoteService:
model_id: object,
*,
force: bool = False,
+ confirmed_remove_hops: object = None,
+ confirmed_interruptions: object = None,
) -> dict:
return await _rpc(
"delete_custom_model",
- {"source_id": source_id, "model_id": model_id, "force": force},
+ {
+ "source_id": source_id,
+ "model_id": model_id,
+ "force": force,
+ "would_remove_hops": confirmed_remove_hops,
+ "would_interrupt": confirmed_interruptions,
+ },
)
def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index e280f6225..3c4cda1ad 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3997,7 +3997,20 @@ async def model_hub_sources_delete(source_id):
try:
force = str(request.args.get("force") or "").lower() in _TRUE_BOOL_STRINGS
- result = await _model_hub_service().delete_source(source_id, force=force)
+ payload = request.json
+ if payload is None:
+ payload = {}
+ if not isinstance(payload, dict) or set(payload) - {
+ "would_remove_hops",
+ "would_interrupt",
+ }:
+ raise ModelHubError("invalid_source_order")
+ result = await _model_hub_service().delete_source(
+ source_id,
+ force=force,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
+ )
return _model_hub_success(**result)
except ModelHubError as exc:
return _model_hub_error(exc)
@@ -4011,11 +4024,17 @@ async def model_hub_sources_refresh(source_id):
payload = request.json
if payload is None:
payload = {}
- if not isinstance(payload, dict) or set(payload) - {"force"}:
+ if not isinstance(payload, dict) or set(payload) - {
+ "force",
+ "would_remove_hops",
+ "would_interrupt",
+ }:
raise ModelHubError("invalid_source_order")
result = await _model_hub_service().refresh_source(
source_id,
force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
)
return _model_hub_success(**result)
except ModelHubError as exc:
@@ -4128,6 +4147,8 @@ async def model_hub_source_models_delete(source_id, model_id):
source_id,
model_id,
force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
)
return _model_hub_success(**result)
except ModelHubError as exc: