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.

feat(models): refresh source discovery on demand (#1127)

Call White8126b89383ee
diff --git a/config/v2_config.py b/config/v2_config.py
index aba0af9b0..1bb063c2a 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -499,6 +499,7 @@ class ModelHubSourceConfig:
state: ModelHubSourceStateConfig
models: list[ModelHubModelConfig]
created_at: str = MODEL_HUB_LEGACY_CREATED_AT
+ last_discovered_at: Optional[str] = None
base_url: Optional[str] = None
experimental_consent_at: Optional[str] = None
usage: Optional[ModelHubSourceUsageConfig] = None
@@ -541,6 +542,7 @@ class ModelHubSourceConfig:
account_label = payload.get("account_label")
masked_credential = payload.get("masked_credential")
created_at = payload.get("created_at")
+ last_discovered_at = payload.get("last_discovered_at")
if base_url is not None and not isinstance(base_url, str):
raise ValueError("Config 'model_hub.sources.base_url' is invalid")
if credential_ref is not None and not isinstance(credential_ref, str):
@@ -566,6 +568,10 @@ class ModelHubSourceConfig:
)
or MODEL_HUB_LEGACY_CREATED_AT
),
+ last_discovered_at=_validate_optional_datetime(
+ last_discovered_at,
+ "model_hub.sources.last_discovered_at",
+ ),
base_url=base_url,
experimental_consent_at=_validate_optional_datetime(
consent_at,
@@ -581,6 +587,7 @@ class ModelHubSourceConfig:
payload = {
"id": self.id,
"created_at": self.created_at,
+ "last_discovered_at": self.last_discovered_at,
"kind": self.kind,
"vendor": self.vendor,
"display_name": self.display_name,
diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.py
index 0af474e1a..9bea228e2 100644
--- a/core/handlers/model_hub/migration.py
+++ b/core/handlers/model_hub/migration.py
@@ -596,6 +596,7 @@ def _new_source(
return ModelHubSourceConfig(
id=item.source_id,
created_at=discovered_at,
+ last_discovered_at=discovered_at if models else None,
kind="subscription" if keep_native or controlled else "api_key",
vendor=item.vendor,
display_name=item.display_name,
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index d15606fc8..3bd2b1303 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -31,8 +31,8 @@ async def dispatch_model_hub_rpc(
if operation == "delete_source":
await service.delete_source(payload.get("source_id"), force=payload.get("force") is True)
return None
- if operation == "test_source":
- source, discovered = await service.test_source(payload.get("source_id"))
+ if operation == "refresh_source":
+ source, discovered = await service.refresh_source(payload.get("source_id"))
return {"source": source, "discovered": discovered}
if operation == "list_agents":
return service.list_agents()
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 8219973ba..8c1b7e9be 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -790,6 +790,7 @@ class ModelHubService:
for model_id in discovered
if model_id not in manual_model_ids
] + manual_models
+ source.last_discovered_at = discovered_at
async def _commit_new_source_locked(
self,
@@ -1433,6 +1434,7 @@ class ModelHubService:
"state",
"usage",
"created_at",
+ "last_discovered_at",
} & set(payload)
if forbidden:
raise ModelHubError("discovery_failed")
@@ -1819,7 +1821,7 @@ class ModelHubService:
if source.credential_ref:
self.revocations.remove(source.id, source.credential_ref)
- async def test_source(self, source_id: str) -> tuple[dict, int]:
+ async def refresh_source(self, source_id: str) -> tuple[dict, int]:
async with self._mutation_lock:
previous = self.store.load()
config = self._clone_config(previous)
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index f32a7cfa0..812fc228e 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -4,7 +4,9 @@ Status: **FROZEN v4 (targeted)** · 2026-07-30 · change only via orchestrator
Advances `agent-chain`, `probe-result`, and `turn-provenance` from contract
version 3 to 4. Later targeted-v4 amendments retain those pins while tightening
the channel-aware adapter seam and grafting derived truth onto the live
-AgentSupply/source-creation projections. The versionless `resolution-event`
+AgentSupply/source-creation projections. The 2026-07-31 source-refresh amendment
+adds persisted discovery freshness and makes `/sources/<id>/refresh` the single
+explicit refresh/recovery operation. The versionless `resolution-event`
includes the request-scoped `permission_denied` cause.
Derived from: spec v2 (`../model-hub.md`), implementation plan
(`../model-hub-implementation.md`),
@@ -67,6 +69,13 @@ messages alone never unfreeze a file. The first instance is this commit,
escalations #2+#3 as one class-level correction against master `807d1eee`; it remains
owner-vetoable.
+The 2026-07-31 source-refresh amendment is likewise orchestrator-authorized and
+owner-vetoable. It reuses the existing discovery commit point: one timestamp now
+stamps both the replacement discovered rows and their owning source, so a manual-only
+inventory or a failed attempt cannot fabricate freshness. The canonical POST route
+returns the updated `Source`; the UI uses that server echo before its sequenced
+full-surface read-back.
+
## Resolved decision, carried forward from v1 (owner, 2026-07-23 10:33)
**Hybrid supply by default + consent-gated experimental hub-held subscriptions.**
@@ -322,7 +331,7 @@ What the rules mean, and why the non-equality rules differ:
| File | Consumers |
| --- | --- |
-| `source.schema.json` | L2 API, L4 UI. **v2:** +`state.status: needs_action`, immutable `created_at`, optional `usage.projected_exhaust_at`. Targeted v4 audit changes no shape: healthy source state and a lapsed `retry_at` do not assert process-local native CLI availability. No ordering field, ever. |
+| `source.schema.json` | L2 API, L4 UI. **v2:** +`state.status: needs_action`, immutable `created_at`, optional `usage.projected_exhaust_at`. Targeted v4 adds required-nullable `last_discovered_at`: the latest successful full inventory replacement, never a failed-attempt time. Healthy source state and a lapsed `retry_at` do not assert process-local native CLI availability. No ordering field, ever. |
| `agent-supply.schema.json` | L2, L3 injection, L4/L5 UI. Owns `sources`, the selected-route rollup, and v3 `named_agents`. The channel class pass extends the complete eligibility inventory with current-chain membership and process availability, retaining non-members so one projection serves both the Agent row and all-sources drawer. |
| `agent-chain.schema.json` | **New in v2, targeted v4 amendment.** L2 API, L4 UI (model box drill-in, 模型菜单 drawer). Carries the CAPABILITY chain and preserves visibility/order for blocked members. Each item now distinguishes source-global `health` from resolve-time channel availability: `runnable = health-permits AND process-available`; Hub availability is definitionally true, while an unavailable native CLI item at any health stays dimmed in place with `reason: native_cli_unavailable`. Cooldown plus unavailable is `interrupted`, not `waiting`. |
| `probe-result.schema.json` | **New in v2, targeted v4 amendment.** L2 API, L4 UI (「试跑一次」). Outcome field is `reachable`; the object nests under `probe` so it never collides with the envelope's `ok`. The probe selects the first runnable item; unavailable chain items are skipped. Hub keeps v3's completed-request truth table. Native CLI re-verifies process readiness, never claims completion evidence, and pins `latency_ms: null` in both directions. It reads the requested model's `supply_state`, never `supply_status`. |
@@ -331,7 +340,7 @@ What the rules mean, and why the non-equality rules differ:
| `oauth-flow.schema.json` | L2, L4 UI. Remains presentation-only: channel is public, while engine credential refs and retained-material disposition stay on the service seam because the UI never consumes them. |
| `migration-scan.schema.json` | L6, L5 UI. Unchanged by the v2 ruling — native-config import is an onboarding feature, not a priority mechanism. |
| `runtime-dependency.schema.json` | L1, L2 status API, L7 guards. **URL policy (orchestrator, 07-23 12:05):** the example URLs are placeholders; L1 ships with upstream release URLs + SHA256 integrity verification. Availability guard = L7/orchestrator deliverable BEFORE GA: mirror the pinned assets into Avibe-owned release storage (same manifest-verified backup/recovery pattern as Show Runtime, per repo release rules), then point the manifest at the mirror with upstream recorded as provenance. SHA256s never change (same bytes). L1 must NOT build the mirror or touch the Show Runtime guard. **Platform expansion (07-23 13:13):** linux-arm64 / darwin-x64 assets get pinned (+ schema platform-enum rev) together with the mirror work at L7; until then unsupported hosts fail closed, Direct = escape hatch (L1's `model_hub_engine_platform_unsupported` coverage is the intended behavior). **Cross-vendor note (07-29):** if the v2.1 cross-vendor spike (spec §10.4) concludes that a conversion pair needs a CPA plugin or a different engine build, that lands here as a pin + SHA256 revision with mirrored assets published before the manifest moves — never as user-facing configuration. |
-| `api.md` | All route and envelope contracts. Targeted v4 keeps the shared envelope at v3 while documenting channel truth, the five-way OAuth repair partition, complete AgentSupply source signals, explicit skipped custom orders, and mapping/menu enrollment. |
+| `api.md` | All route and envelope contracts. Targeted v4 keeps the shared envelope at v3 while documenting channel truth, the five-way OAuth repair partition, complete AgentSupply source signals, explicit skipped custom orders, mapping/menu enrollment, and the single source refresh/recovery route. |
| `opencode-overlay.md` | L3, L7 (identifier-stability tests). Identifiers stay stable across per-agent reordering — a source is never encoded into the provider segment. |
| `adapter-interface.py` | L1 (implements), L2 (consumes; owns in-repo copy). v1.3 makes OAuth flow success channel-aware and adds the total retained-material disposition. The contract and `core/handlers/model_hub/adapter.py` remain byte-identical by mechanical guard. |
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index b3de0ce35..41fda4ba2 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -23,7 +23,7 @@ responses without changing the envelope version.
| PUT `/api/models/sources/<id>/credential` | `{key, force?: boolean}` → `{source, recovered, interrupted_pairs}` | API-key replacement. The optional `force` is a JSON body field, never a query parameter. |
| POST `/api/models/sources/<id>/reauth` | `{acknowledge_irreversible?: true}` → `{flow: OAuthFlow}` | A `native_cli` source requires the acknowledgement before OAuth starts. See repair rules. |
| DELETE `/api/models/sources/<id>?force=<bool>` | → `{ok}` or `source_last_supplier` + `would_interrupt` | Guard evaluates the post-delete enabled orders. |
-| POST `/api/models/sources/<id>/test` | → `{discovered: integer}` | Explicit source re-discovery, including blocked-source recovery. |
+| POST `/api/models/sources/<id>/refresh` | → `{source: Source, discovered: integer}` | Explicit source re-discovery, including blocked-source recovery. The returned source contains the replacement model list and successful `last_discovered_at`. |
| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | Backend records include `named_agents`, the enabled named-Agent live projection. |
| GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. |
| PUT `/api/models/agents/<backend>/sources` | source-order request → `{agent: AgentSupply}` | Full canonical order is re-echoed. |
@@ -393,16 +393,19 @@ API-key success:
}
```
-## Blocked-source test
+## Source refresh and blocked-source recovery
-`POST /api/models/sources/<id>/test` is an explicit source-scoped operation. It may
-test a source whose global state is `needs_action` or `error`, even though normal
+`POST /api/models/sources/<id>/refresh` is an explicit source-scoped operation. It may
+refresh a source whose global state is `needs_action` or `error`, even though normal
turn resolution and the chain probe exclude that source as non-runnable.
On usable discovery it updates the discovered model set, clears the blocker, and
-sets the source to `standby`. A classified failure updates the source-global state
-and returns the normal safe error. This route is the only recovery test added; v3
-does not add a second “recover” endpoint.
+sets the source to `standby`. The response returns that complete updated source and
+the discovered count; clients do not reconstruct the model list from the count.
+`last_discovered_at` advances only on this successful replacement. A classified
+failure updates the source-global state, preserves the last successful model list and
+timestamp, and returns the normal safe error. This route is the only refresh/recovery
+operation; there is no parallel “test” or “recover” endpoint.
## OAuth completion
@@ -632,7 +635,7 @@ contract harness and API-boundary tests enforce:
| probe `source_id` names an existing source | probe assembler |
| non-null event endpoints name existing sources at emission time | event emitter |
| `channel_switch.from_source == channel_switch.to_source` | event emitter |
-| API AgentSupply includes `selected_by_agent`, `selected_model_id`, `selected_model_explicit`, `sources`, `supply_status`, `model_supply`, and `named_agents`; source creation returns both `adopted_by` and `skipped_by` | API payload test |
+| API AgentSupply includes `selected_by_agent`, `selected_model_id`, `selected_model_explicit`, `sources`, `supply_status`, `model_supply`, and `named_agents`; every Source includes persisted `last_discovered_at`; source creation returns both `adopted_by` and `skipped_by`; source refresh returns the updated Source plus count | API payload test |
| every OAuthFlow response includes `intent` | API payload test |
| contract and in-repo adapter interface copies are byte-identical; the five retained-material enum members and ref-pairing predicates are mutation-tested | contract harness |
diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.json
index 2b0d391fb..67377589e 100644
--- a/docs/plans/model-hub-contracts/source.schema.json
+++ b/docs/plans/model-hub-contracts/source.schema.json
@@ -14,6 +14,7 @@
"billing",
"state",
"credential_ref",
+ "last_discovered_at",
"models"
],
"additionalProperties": false,
@@ -30,6 +31,15 @@
"format": "date-time",
"description": "v2 (2026-07-29): when the source was added. IMMUTABLE once written — edits, re-auth, re-discovery and cooldown cycles never touch it. This is not decoration: `follow` policy recommends api_key sources 'by creation time ascending' (spec §4.2), so without a persisted creation stamp that rule is not reproducible — the sources array is explicitly unordered (api.md) and insertion order in config is not a contract. Two sources imported in one batch can legitimately share a stamp, so `id` ascending is the tie-breaker. NULL PLACEMENT (07-29, review round 2) — a tie-breaker does not define how null compares to a real timestamp, and leaving that open would let two correct implementations publish different canonical orders: **a null stamp sorts BEFORE every non-null one**, ties among nulls by `id` ascending. That is not an arbitrary sentinel choice, it is the truth about the record — it predates this field, so it is older than anything that carries a stamp, and 跟随推荐 sorts oldest first. The serializer PR MUST backfill pre-existing sources with the constant `1970-01-01T00:00:00Z` rather than the upgrade timestamp, so the backfill preserves exactly the order the null rule already produced instead of silently reshuffling the user's chain on upgrade (spec §4.2 promises the product never reorders behind the user's back). With both halves stated the sort is total over every mix of stamped, unstamped and same-stamped sources. OPTIONAL here / required at the API boundary once the serializer emits it (README → required-vs-optional discipline)."
},
+ "last_discovered_at": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "date-time",
+ "description": "Targeted v4 (2026-07-31): the completion time of this source's latest successful full model discovery. The server updates it for every successful automatic or explicit discovery that replaces the discovered inventory, including source creation, credential/base-URL changes, re-auth, migration, and POST /sources/<id>/refresh. A failed attempt does not advance it, so the UI never presents failure time as freshness. null means the source predates this field or has no known successful discovery; no backfill invents a fetch time. This source-level fact cannot be derived from models[].discovered_at because a valid refresh may return no discovered rows while preserving manual rows. REQUIRED and nullable at the API boundary because the serializer always answers the question.",
+ "$comment": "Evidence-pinned targeted amendment: core/handlers/model_hub/service.py::_apply_discovered_models stamps the source from the same instant used for discovered rows; core/handlers/model_hub/migration.py::_new_source reuses its existing discovery stamp; config/v2_config.py::ModelHubSourceConfig persists and emits the nullable field."
+ },
"kind": {
"enum": [
"subscription",
@@ -509,6 +519,7 @@
"examples": [
{
"id": "src_claudepro1",
+ "last_discovered_at": "2026-07-23T03:00:00Z",
"kind": "subscription",
"vendor": "anthropic",
"display_name": "Claude Pro 订阅",
@@ -540,6 +551,7 @@
},
{
"id": "src_relay9c1x",
+ "last_discovered_at": null,
"kind": "api_key",
"vendor": "custom",
"display_name": "relay.example",
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 246a58045..f2346efcf 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -44,6 +44,12 @@ scenarios:
kind: recovery
layer: unit
test: tests/test_model_hub_resolution.py::test_quota_failure_cools_source_switches_and_emits_redacted_events
+ - id: MH-SRC-REFRESH-001
+ name: Manual source refresh replaces discovery inventory and freshness timestamp
+ status: partial
+ kind: recovery
+ layer: unit_contract
+ test: tests/test_model_hub_api.py::test_model_hub_rest_api_contract
- id: MH-PRI-001
name: Per-agent source-order mutations and follow restoration take effect immediately
status: covered
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index e98d89405..3be26ad73 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -525,7 +525,7 @@ def test_ui_model_hub_rpc_preserves_structured_guard_data():
("PUT", "/api/models/sources/src_test0001/credential"),
("POST", "/api/models/sources/src_test0001/reauth"),
("DELETE", "/api/models/sources/src_test0001"),
- ("POST", "/api/models/sources/src_test0001/test"),
+ ("POST", "/api/models/sources/src_test0001/refresh"),
("GET", "/api/models/agents"),
("GET", "/api/models/agents/claude/sources"),
("PUT", "/api/models/agents/claude/sources"),
@@ -626,7 +626,7 @@ def test_disabled_gate_preserves_existing_model_hub_config_bytes(monkeypatch):
def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
- """Scenarios: MH-PRI-001, MH-OAUTH-A-001, MH-OAUTH-ERR-001."""
+ """Scenarios: MH-SRC-REFRESH-001, MH-PRI-001, MH-OAUTH-A-001, MH-OAUTH-ERR-001."""
service, store, adapter = _service(tmp_path)
monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
@@ -773,20 +773,44 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
status="needs_action",
detail_key="models.source.needs_action.balance_exhausted",
)
+ previous_discovered_at = persisted_source.last_discovered_at
+ unauthorized = client.post(
+ f"/api/models/sources/{source_id}/refresh",
+ base_url=base_url,
+ )
+ assert unauthorized.status_code == 403
+ assert store.config.sources[0].last_discovered_at == previous_discovered_at
+
+ async def refreshed_models(vendor, protocol, endpoint, credential_ref):
+ return ("claude-opus-4-6", "claude-sonnet-4-6", "claude-opus-5")
+
+ adapter.discover_models = refreshed_models
+ original_now = service.now
+ service.now = lambda: datetime(2026, 7, 31, 5, 15, tzinfo=timezone.utc)
response = client.post(
- f"/api/models/sources/{source_id}/test",
+ f"/api/models/sources/{source_id}/refresh",
headers=headers,
base_url=base_url,
)
body = response.get_json()
_assert_envelope(body)
- assert body["discovered"] == 2
+ assert set(body) == {"ok", "contract_version", "source", "discovered"}
+ assert body["discovered"] == 3
+ _assert_valid("source.schema.json", body["source"])
+ assert {model["id"] for model in body["source"]["models"]} == {
+ "claude-opus-4-6",
+ "claude-sonnet-4-6",
+ "claude-opus-5",
+ }
+ assert body["source"]["last_discovered_at"] == "2026-07-31T05:15:00+00:00"
+ assert store.config.sources[0].last_discovered_at == body["source"]["last_discovered_at"]
assert store.config.sources[0].state.status == "standby"
assert (
store.config.sources[0].id,
store.config.sources[0].created_at,
store.config.sources[0].credential_ref,
) == immutable_identity
+ service.now = original_now
response = client.post(
"/api/models/custom-models",
@@ -3101,7 +3125,7 @@ def test_native_source_configuration_does_not_require_l1_engine(tmp_path):
retry_at="2026-07-23T03:05:00Z",
)
with pytest.raises(ModelHubError) as exc_info:
- asyncio.run(service.test_source(source["id"]))
+ asyncio.run(service.refresh_source(source["id"]))
assert exc_info.value.code == "discovery_failed"
assert store.config.sources[0].state.status == "cooldown"
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index b3e5ee344..a2687058c 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -559,6 +559,7 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tm
):
serialized_source = serialized_hub["sources"][0]
assert source_fields == set(serialized_source), label
+ assert serialized_source["last_discovered_at"] == source_example["last_discovered_at"], label
assert source_state_fields == set(serialized_source["state"]), label
assert source_usage_fields == set(serialized_source["usage"]), label
assert source_model_fields == set(serialized_source["models"][0]), label
@@ -798,6 +799,10 @@ def test_source_optional_fields_reject_schema_invalid_values():
invalid["models"][0]["discovered_at"] = "2026-07-23T03:00:00"
invalid_sources.append(invalid)
+ invalid = json.loads(json.dumps(source))
+ invalid["last_discovered_at"] = "2026-07-23T03:00:00"
+ invalid_sources.append(invalid)
+
invalid = json.loads(json.dumps(source))
invalid["state"]["detail_key"] = 1
invalid_sources.append(invalid)
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 51ea6f7f6..2e9d684e4 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -2373,7 +2373,7 @@ def test_failed_old_credential_revoke_reconciles_after_service_restart(tmp_path)
assert restarted.store.load().sources[0].credential_ref == "cred_replacement_1"
-def test_existing_source_test_clears_blocker_and_restores_runnable_supply(tmp_path):
+def test_existing_source_refresh_clears_blocker_and_restores_runnable_supply(tmp_path):
adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])
service = _service(tmp_path, adapter)
config = service.store.load()
@@ -2386,7 +2386,7 @@ def test_existing_source_test_clears_blocker_and_restores_runnable_supply(tmp_pa
for agent in config.agents.values():
agent.sources.order = [source.id]
- updated, discovered = asyncio.run(service.test_source(source.id))
+ updated, discovered = asyncio.run(service.refresh_source(source.id))
resolved = asyncio.run(
service.resolve(
backend="claude",
@@ -2397,10 +2397,12 @@ def test_existing_source_test_clears_blocker_and_restores_runnable_supply(tmp_pa
assert discovered == 1
assert updated["state"]["status"] == "standby"
+ assert updated["last_discovered_at"] == "2026-07-23T03:00:00+00:00"
+ assert service.store.load().sources[0].last_discovered_at == updated["last_discovered_at"]
assert resolved.source_id == source.id
-def test_existing_source_test_persists_safe_error_state_on_discovery_failure(
+def test_existing_source_refresh_persists_safe_error_state_on_discovery_failure(
tmp_path,
):
adapter = NarrowingCredentialAdapter()
@@ -2411,18 +2413,20 @@ def test_existing_source_test_persists_safe_error_state_on_discovery_failure(
status="needs_action",
detail_key="models.source.needs_action.balance_exhausted",
)
+ source.last_discovered_at = "2026-07-22T03:00:00+00:00"
with pytest.raises(ModelHubError) as exc_info:
- asyncio.run(service.test_source(source.id))
+ asyncio.run(service.refresh_source(source.id))
assert exc_info.value.code == "discovery_failed"
assert service.store.load().sources[0].state.status == "error"
assert service.store.load().sources[0].state.detail_key == (
"models.source.error.unclassified"
)
- source_test_event = service.list_events(limit=10)[0]
- assert source_test_event["agent"] == "system"
- assert source_test_event["model_id"] is None
+ assert service.store.load().sources[0].last_discovered_at == "2026-07-22T03:00:00+00:00"
+ source_refresh_event = service.list_events(limit=10)[0]
+ assert source_refresh_event["agent"] == "system"
+ assert source_refresh_event["model_id"] is None
turn_service = _service(
tmp_path / "turn",
@@ -2446,12 +2450,12 @@ def test_existing_source_test_persists_safe_error_state_on_discovery_failure(
if event["kind"] == "needs_action"
)
fields = ("kind", "reason", "from_source", "severity")
- assert tuple(source_test_event[field] for field in fields) == tuple(
+ assert tuple(source_refresh_event[field] for field in fields) == tuple(
turn_event[field] for field in fields
)
-def test_existing_source_test_rejects_empty_discovery_before_recovery(tmp_path):
+def test_existing_source_refresh_rejects_empty_discovery_before_recovery(tmp_path):
adapter = FakeAdapter([])
service = _service(tmp_path, adapter)
source = service.store.load().sources[0]
@@ -2466,7 +2470,7 @@ def test_existing_source_test_rejects_empty_discovery_before_recovery(tmp_path):
adapter.discover_models = empty_discovery
with pytest.raises(ModelHubError) as exc_info:
- asyncio.run(service.test_source(source.id))
+ asyncio.run(service.refresh_source(source.id))
assert exc_info.value.code == "discovery_failed"
persisted = service.store.load().sources[0]
@@ -2474,7 +2478,7 @@ def test_existing_source_test_rejects_empty_discovery_before_recovery(tmp_path):
assert persisted.state.detail_key == "models.source.error.unclassified"
-def test_existing_source_test_preserves_health_on_engine_outage(tmp_path):
+def test_existing_source_refresh_preserves_health_on_engine_outage(tmp_path):
adapter = NarrowingCredentialAdapter()
service = _service(tmp_path, adapter)
before = _serialized_config(service)
@@ -2484,7 +2488,7 @@ def test_existing_source_test_preserves_health_on_engine_outage(tmp_path):
adapter.discover_models = engine_unavailable
with pytest.raises(ModelHubError) as exc_info:
- asyncio.run(service.test_source("src_primary01"))
+ asyncio.run(service.refresh_source("src_primary01"))
assert exc_info.value.code == "engine_down"
assert _serialized_config(service) == before
diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsx
index a0a8554b5..0edc6bb43 100644
--- a/ui/src/components/settings/models/AgentCard.test.tsx
+++ b/ui/src/components/settings/models/AgentCard.test.tsx
@@ -28,6 +28,7 @@ const source = (id: string, name: string): Source => ({
supply_channel: 'hub',
billing: 'metered',
state: { status: 'active', retry_at: null, detail_key: null },
+ last_discovered_at: null,
models: [{ id: 'claude-opus-4-6', provenance: 'discovered' }],
});
diff --git a/ui/src/components/settings/models/RecentSwitchesCard.test.tsx b/ui/src/components/settings/models/RecentSwitchesCard.test.tsx
index effaed8b0..543309e57 100644
--- a/ui/src/components/settings/models/RecentSwitchesCard.test.tsx
+++ b/ui/src/components/settings/models/RecentSwitchesCard.test.tsx
@@ -32,6 +32,7 @@ const source = (id: string): Source => ({
supply_channel: 'hub',
billing: 'metered',
state: { status: 'active', retry_at: null, detail_key: null },
+ last_discovered_at: null,
models: [],
});
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 4c8a2a174..951a824ca 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -16,7 +16,13 @@ import { AdvancedRow } from './AdvancedRow';
import { AddApiKeyDialog } from './AddApiKeyDialog';
import { OAuthConnectDialog } from './OAuthConnectDialog';
import { RepairJourney, type RepairTarget } from './RepairJourney';
-import { agentsWithEcho, createLatestAsyncAuthority, createPendingWrites, mapWithConcurrency } from './asyncLifetime';
+import {
+ agentsWithEcho,
+ createLatestAsyncAuthority,
+ createPendingWrites,
+ mapWithConcurrency,
+ sourcesWithEcho,
+} from './asyncLifetime';
import {
emptyFeed,
feedAfterHeadRead,
@@ -84,6 +90,16 @@ const readModelSurface = async (): Promise<[Source[], AgentSupply[], ModelChainI
return [sources, agents, await readModelChains(agents)];
};
+type ModelSurfaceLanding =
+ | {
+ kind: 'surface';
+ sources: Source[];
+ agents: AgentSupply[];
+ events: ResolutionEvent[] | null;
+ chains: ModelChainIndex;
+ }
+ | { kind: 'source'; source: Source };
+
// 最近切换 is a cursor feed, not a fixed window: `/events` pages with `before`,
// so 「查看全部」 over one fetched page could never reach row 21. One page size for
// the first read and every 加载更早 read after it.
@@ -104,7 +120,7 @@ export const SettingsModelsPage: React.FC = () => {
const [loading, setLoading] = React.useState(true);
const [loadError, setLoadError] = React.useState<string | null>(null);
const [connecting, setConnecting] = React.useState<string | null>(null);
- const [retestingSourceId, setRetestingSourceId] = React.useState<string | null>(null);
+ const [refreshingSourceId, setRefreshingSourceId] = React.useState<string | null>(null);
const [issuesOnly, setIssuesOnly] = React.useState(false);
const agentSectionRef = React.useRef<HTMLDivElement>(null);
@@ -166,9 +182,14 @@ export const SettingsModelsPage: React.FC = () => {
// this refresh's job. A feed left one write behind is not wrong, only not newer,
// and the next mutation or reload catches it up.
const [refreshAuthority] = React.useState(() =>
- createLatestAsyncAuthority<[Source[], AgentSupply[], ResolutionEvent[] | null, ModelChainIndex]>(
- ([nextSources, nextAgents, headEvents, nextChains]) => {
+ createLatestAsyncAuthority<ModelSurfaceLanding>(
+ (landing) => {
if (!aliveRef.current) return;
+ if (landing.kind === 'source') {
+ setSources((previous) => sourcesWithEcho(previous, landing.source));
+ return;
+ }
+ const { sources: nextSources, agents: nextAgents, events: headEvents, chains: nextChains } = landing;
setSources(nextSources);
setAgents(nextAgents);
agentsRef.current = nextAgents;
@@ -216,7 +237,13 @@ export const SettingsModelsPage: React.FC = () => {
readModelSurface(),
modelsApi.listEvents(EVENT_PAGE).catch(() => null),
]);
- return [nextSources, nextAgents, headEvents, nextChains];
+ return {
+ kind: 'surface' as const,
+ sources: nextSources,
+ agents: nextAgents,
+ events: headEvents,
+ chains: nextChains,
+ };
});
} catch {
// A mutation may have succeeded server-side but the re-read failed — tell
@@ -336,24 +363,29 @@ export const SettingsModelsPage: React.FC = () => {
}
};
- const retestSource = async (source: Source) => {
- if (retestingSourceId !== null) return;
- setRetestingSourceId(source.id);
+ const refreshSource = async (source: Source) => {
+ if (refreshingSourceId !== null) return;
+ setRefreshingSourceId(source.id);
try {
- const count = await modelsApi.testSource(source.id);
- if (!aliveRef.current) return;
+ // The mutation must fail outside the read authority: that authority
+ // intentionally suppresses stale read errors, while a discovery failure
+ // writes the source's error state and must always reach the honest toast.
+ const refreshed = await modelsApi.refreshSource(source.id);
+ await refreshAuthority.run(() =>
+ Promise.resolve({ kind: 'source' as const, source: refreshed.source }),
+ );
await refreshSourcesAgents();
if (aliveRef.current) {
- showToast(t('settings.models.sourceActions.rediscovered', { count }) as string, 'success');
+ showToast(t('settings.models.sourceActions.refreshed', { count: refreshed.discovered }) as string, 'success');
}
} catch {
if (!aliveRef.current) return;
await refreshSourcesAgents();
if (aliveRef.current) {
- showToast(t('settings.models.sourceActions.rediscoverFailed') as string, 'error');
+ showToast(t('settings.models.sourceActions.refreshFailed') as string, 'error');
}
} finally {
- if (aliveRef.current) setRetestingSourceId(null);
+ if (aliveRef.current) setRefreshingSourceId(null);
}
};
@@ -416,8 +448,8 @@ export const SettingsModelsPage: React.FC = () => {
onSetRoute={setModelRoute}
onAddModel={(backend) => openCustomModel(undefined, backend)}
onRepair={(source, kind) => setRepairTarget({ source, kind })}
- onRetest={(source) => void retestSource(source)}
- retestingSourceId={retestingSourceId}
+ onRetest={(source) => void refreshSource(source)}
+ retestingSourceId={refreshingSourceId}
onProbeSettled={() => void refreshSourcesAgents()}
connectingBackend={connecting}
/>
@@ -428,6 +460,8 @@ export const SettingsModelsPage: React.FC = () => {
onConnectChatGPT={() => setOauthVendor('openai')}
onAddApiKey={() => setApiKeyOpen(true)}
onSourceChanged={() => void refreshSourcesAgents()}
+ onRefreshSource={(source) => void refreshSource(source)}
+ refreshingSourceId={refreshingSourceId}
onRepair={(source, kind) => setRepairTarget({ source, kind })}
onAddModel={(source) => openCustomModel(source.id)}
/>
diff --git a/ui/src/components/settings/models/SourceRow.test.tsx b/ui/src/components/settings/models/SourceRow.test.tsx
index abd0566d0..91ef04ebb 100644
--- a/ui/src/components/settings/models/SourceRow.test.tsx
+++ b/ui/src/components/settings/models/SourceRow.test.tsx
@@ -1,7 +1,7 @@
import { createInstance } from 'i18next';
import { renderToStaticMarkup } from 'react-dom/server';
import { I18nextProvider, initReactI18next } from 'react-i18next';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ToastProvider } from '@/context/ToastContext';
import en from '../../../i18n/en.json';
@@ -26,13 +26,22 @@ const source = (kind: Source['kind']): Source => ({
supply_channel: kind === 'subscription' ? 'native_cli' : 'hub',
billing: kind === 'subscription' ? 'monthly' : 'metered',
state: { status: 'active', retry_at: null, detail_key: null },
+ last_discovered_at: null,
models: [],
});
-const render = (row: Source) => renderToStaticMarkup(
+const render = (row: Source, refreshing = false) => renderToStaticMarkup(
<I18nextProvider i18n={i18n}>
<ToastProvider>
- <SourceRow source={row} onChanged={vi.fn()} onRepair={vi.fn()} onAddModel={vi.fn()} />
+ <SourceRow
+ source={row}
+ onChanged={vi.fn()}
+ onRefresh={vi.fn()}
+ refreshing={refreshing}
+ refreshDisabled={refreshing}
+ onRepair={vi.fn()}
+ onAddModel={vi.fn()}
+ />
</ToastProvider>
</I18nextProvider>,
);
@@ -52,3 +61,34 @@ describe('SourceRow empty inventory', () => {
expect(html).toContain(zh.settings.models.sources.addModel);
});
});
+
+describe('SourceRow discovery refresh', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-07-31T05:20:00Z'));
+ });
+
+ afterEach(() => vi.useRealTimers());
+
+ it('shows the persisted discovery time beside a quiet refresh action', () => {
+ const html = render({ ...source('api_key'), last_discovered_at: '2026-07-31T05:15:00Z' });
+
+ expect(html).toContain('上次自动获取 5 分钟前');
+ expect(html).toContain(`aria-label="${zh.settings.models.sourceActions.refresh}"`);
+ });
+
+ it('shows an honest never-fetched state and a stable refreshing control', () => {
+ const html = render(source('api_key'), true);
+
+ expect(html).toContain(zh.settings.models.sources.neverDiscovered);
+ expect(html).toContain(`aria-label="${zh.settings.models.sourceActions.refreshing}"`);
+ expect(html).toContain('aria-busy="true"');
+ expect(html).toContain('animate-spin');
+ expect(html).toContain('disabled=""');
+ });
+
+ it('keeps failure copy explicit that the last successful list remains visible', () => {
+ expect(zh.settings.models.sourceActions.refreshFailed).toContain('仍显示上次成功获取的清单');
+ expect(en.settings.models.sourceActions.refreshFailed).toContain('last successful list is still shown');
+ });
+});
diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsx
index b3643e462..d7cbc2a8d 100644
--- a/ui/src/components/settings/models/SourceRow.tsx
+++ b/ui/src/components/settings/models/SourceRow.tsx
@@ -15,12 +15,13 @@
// indented to match the frame. The sm+ layout is byte-for-byte the desktop
// frame, so the fixed-width chip columns still align down the list.
import * as React from 'react';
-import { LogIn, Plus } from 'lucide-react';
+import { LogIn, Plus, RefreshCw } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
+import { formatRelativeTime } from '@/lib/relativeTime';
import { BillingChip, ExperimentalChip, StateChip } from './chips';
import { SupplyTooltip } from './SupplyTooltip';
import { SourceRowMenu, type RaisedRepair } from './SourceRowMenu';
@@ -120,13 +121,16 @@ const StateCell: React.FC<{ source: Source }> = ({ source }) => (
export const SourceRow: React.FC<{
source: Source;
- /** Re-fetch after a row action (rename / re-discover / delete). */
+ /** Re-fetch after a row action (rename / delete). */
onChanged: () => void;
+ onRefresh: (source: Source) => void;
+ refreshing: boolean;
+ refreshDisabled: boolean;
/** Open a repair journey the page hosts — see SourceRowMenu's `onRepair`. */
onRepair?: (source: Source, kind: RaisedRepair) => void;
/** Open the shared manual-model action with this source preselected. */
onAddModel: (source: Source) => void;
-}> = ({ source, onChanged, onRepair, onAddModel }) => {
+}> = ({ source, onChanged, onRefresh, refreshing, refreshDisabled, onRepair, onAddModel }) => {
const { t } = useTranslation();
const { Icon, accent } = sourceVisual(source);
const subline = useSubline(source);
@@ -189,15 +193,48 @@ export const SourceRow: React.FC<{
slot because a stopped row puts its one-tap remedy beside the ⋯ — both
come from the menu component, which owns the actions. */}
<div className="order-2 flex shrink-0 items-center gap-1.5 sm:order-3">
- <SourceRowMenu source={source} onChanged={onChanged} onRepair={onRepair} />
+ <SourceRowMenu
+ source={source}
+ onChanged={onChanged}
+ onRefresh={onRefresh}
+ refreshing={refreshing}
+ refreshDisabled={refreshDisabled}
+ onRepair={onRepair}
+ />
</div>
</div>
<div className="flex flex-col gap-2 border-t border-border/70 bg-foreground/[0.012] px-4 py-3 sm:px-5">
<div className="flex items-center justify-between gap-3">
- <span className="text-[11px] font-semibold text-muted">
- {t('settings.models.sources.modelCount', { count: source.models.length })}
- </span>
+ <div className="flex min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1">
+ <span className="text-[11px] font-semibold text-muted">
+ {t('settings.models.sources.modelCount', { count: source.models.length })}
+ </span>
+ <span className="text-[10.5px] text-muted">
+ {source.last_discovered_at
+ ? t('settings.models.sources.lastDiscovery', {
+ time: formatRelativeTime(source.last_discovered_at, t),
+ })
+ : t('settings.models.sources.neverDiscovered')}
+ </span>
+ {source.supply_channel === 'hub' && (
+ <button
+ type="button"
+ onClick={() => onRefresh(source)}
+ disabled={refreshDisabled}
+ aria-busy={refreshing}
+ aria-label={t(
+ refreshing
+ ? 'settings.models.sourceActions.refreshing'
+ : 'settings.models.sourceActions.refresh',
+ ) as string}
+ title={t('settings.models.sourceActions.refresh') as string}
+ className="inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted transition-colors hover:bg-surface-2 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-45"
+ >
+ <RefreshCw className={cn('size-3.5', refreshing && 'animate-spin')} />
+ </button>
+ )}
+ </div>
{source.kind === 'api_key' && (
<button
type="button"
diff --git a/ui/src/components/settings/models/SourceRowMenu.tsx b/ui/src/components/settings/models/SourceRowMenu.tsx
index 807d1057b..ae04d860c 100644
--- a/ui/src/components/settings/models/SourceRowMenu.tsx
+++ b/ui/src/components/settings/models/SourceRowMenu.tsx
@@ -1,8 +1,7 @@
// Per-row lifecycle actions for the 来源 list (design.pen 「产品改造 V6 01」): an
// overflow menu that stays out of the way (hidden until row hover / focus on
// desktop) and exposes the contracted source mutations the list otherwise
-// couldn't reach — rename (PATCH), re-discover (POST /test, hub sources only),
-// and delete (DELETE, with the only-supplier guard escalating to a forced
+// couldn't reach — rename (PATCH) and delete (DELETE, with the only-supplier guard escalating to a forced
// delete). Presentation lives in SourceRow; this owns the actions + their
// dialogs so the row stays declarative.
//
@@ -80,17 +79,20 @@ const MenuAction: React.FC<{
export const SourceRowMenu: React.FC<{
source: Source;
- /** Re-fetch sources + agents after any successful mutation. */
+ /** Re-fetch sources + agents after a rename or delete. */
onChanged: () => void;
+ onRefresh: (source: Source) => void;
+ refreshing: boolean;
+ refreshDisabled: boolean;
/**
* Raise a remedy that needs a dialog + a server flow to the page, which
* outlives this row: a re-auth replaces the source's models and a key
* replacement re-discovers them, so both trigger the refetch that unmounts
- * whatever hosted the dialog. `retest` is handled here because it needs no
- * dialog at all.
+ * whatever hosted the dialog. `retest` delegates to the page-owned refresh
+ * operation so the row action and the inventory button share one lifetime.
*/
onRepair?: (source: Source, kind: RaisedRepair) => void;
-}> = ({ source, onChanged, onRepair }) => {
+}> = ({ source, onChanged, onRefresh, refreshing, refreshDisabled, onRepair }) => {
const { t } = useTranslation();
const { showToast } = useToast();
const isMobile = useIsMobile();
@@ -108,7 +110,6 @@ export const SourceRowMenu: React.FC<{
// confirm has to name the Agents, and re-deriving them from the loaded list
// would answer a question the guard already answered.
const [gaps, setGaps] = React.useState<SupplyGap[]>([]);
- const [testing, setTesting] = React.useState(false);
// Re-armed on mount, not only cleared on unmount: a cleanup-only guard is
// one-way, so StrictMode's mount → cleanup → mount would leave every 测试
@@ -121,10 +122,6 @@ export const SourceRowMenu: React.FC<{
};
}, []);
- // Re-discovery only applies to hub sources; native_cli subscriptions are
- // rejected server-side, so we don't offer the action for them.
- const canRediscover = source.supply_channel === 'hub';
-
const openRename = () => {
setMenuOpen(false);
setRenameValue(source.display_name);
@@ -151,30 +148,6 @@ export const SourceRowMenu: React.FC<{
}
};
- const rediscover = async () => {
- setMenuOpen(false);
- if (testing) return;
- setTesting(true);
- try {
- const count = await modelsApi.testSource(source.id);
- if (!aliveRef.current) return;
- onChanged();
- showToast(t('settings.models.sourceActions.rediscovered', { count }) as string, 'success');
- } catch {
- if (!aliveRef.current) return;
- // A failed test is NOT read-only: `test_source` persists the source as
- // error/unclassified and only then raises `discovery_failed`. Refreshing on
- // success alone would leave the row showing the cause it had before the
- // server replaced it — and for the inline repair, the remedy that cause
- // implied. Re-read either way; the toast reports the attempt, the row
- // reports the state.
- onChanged();
- showToast(t('settings.models.sourceActions.rediscoverFailed') as string, 'error');
- } finally {
- if (aliveRef.current) setTesting(false);
- }
- };
-
const openDelete = () => {
setMenuOpen(false);
setForceMode(false);
@@ -205,8 +178,8 @@ export const SourceRowMenu: React.FC<{
}
if (aliveRef.current) {
setDeleteOpen(false);
- // Same rule as `rediscover` above, for the same reason: a failed DELETE is
- // not read-only either. The supply guard is the one refusal that provably
+ // A failed DELETE is not necessarily read-only. The supply guard is the
+ // one refusal that provably
// wrote nothing — `delete_source` raises it off a CLONED config, before
// `_commit_synced` — and it left through the branch above. Everything that
// reaches here got past that commit or died inside it: a response lost on
@@ -230,7 +203,7 @@ export const SourceRowMenu: React.FC<{
const runRepair = (kind: RepairKind) => {
setMenuOpen(false);
if (kind === 'retest') {
- void rediscover();
+ onRefresh(source);
return;
}
onRepair?.(source, kind);
@@ -261,10 +234,10 @@ export const SourceRowMenu: React.FC<{
// Composed rather than a per-kind string: the label already says what
// happens, and every row on the page repeats it.
aria-label={`${t(REPAIR_LABEL_KEY[inlineRemedy])} · ${source.display_name}`}
- disabled={testing}
+ disabled={refreshDisabled}
onClick={() => runRepair(inlineRemedy)}
>
- {testing && inlineRemedy === 'retest' ? (
+ {refreshing && inlineRemedy === 'retest' ? (
<RefreshCw className="size-3 animate-spin" />
) : (
<RemedyIcon className="size-3" />
@@ -313,7 +286,7 @@ export const SourceRowMenu: React.FC<{
)}
>
<span className="flex size-9 items-center justify-center rounded-[10px] border border-border bg-surface/60 transition-colors group-hover/more:bg-surface-2 group-hover/more:text-foreground sm:size-8 sm:border-transparent sm:bg-transparent">
- {testing ? <RefreshCw className="size-4 animate-spin" /> : <MoreHorizontal className="size-4" />}
+ <MoreHorizontal className="size-4" />
</span>
</button>
}
@@ -324,14 +297,6 @@ export const SourceRowMenu: React.FC<{
description={hint('renameHint')}
onClick={openRename}
/>
- {canRediscover && (
- <MenuAction
- Icon={RefreshCw}
- label={t('settings.models.sourceActions.rediscover') as string}
- description={hint('rediscoverHint')}
- onClick={() => void rediscover()}
- />
- )}
{/* Elective credential maintenance — available on a HEALTHY source too
(api.md gives both routes an elective form, guard included), which is
why these read the per-route predicates rather than `repairAction`.
diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsx
index 51bbf80a6..eb6ea052f 100644
--- a/ui/src/components/settings/models/SourcesCard.tsx
+++ b/ui/src/components/settings/models/SourcesCard.tsx
@@ -18,12 +18,24 @@ export const SourcesCard: React.FC<{
onConnectClaude: () => void;
onConnectChatGPT: () => void;
onAddApiKey: () => void;
- /** Re-fetch after a per-row action (rename / re-discover / delete). */
+ /** Re-fetch after a per-row action (rename / delete). */
onSourceChanged: () => void;
+ onRefreshSource: (source: Source) => void;
+ refreshingSourceId: string | null;
/** Open a repair journey the page hosts — see SourceRowMenu's `onRepair`. */
onRepair?: (source: Source, kind: RaisedRepair) => void;
onAddModel: (source: Source) => void;
-}> = ({ sources, onConnectClaude, onConnectChatGPT, onAddApiKey, onSourceChanged, onRepair, onAddModel }) => {
+}> = ({
+ sources,
+ onConnectClaude,
+ onConnectChatGPT,
+ onAddApiKey,
+ onSourceChanged,
+ onRefreshSource,
+ refreshingSourceId,
+ onRepair,
+ onAddModel,
+}) => {
const { t } = useTranslation();
return (
@@ -50,6 +62,9 @@ export const SourcesCard: React.FC<{
key={source.id}
source={source}
onChanged={onSourceChanged}
+ onRefresh={onRefreshSource}
+ refreshing={refreshingSourceId === source.id}
+ refreshDisabled={refreshingSourceId !== null}
onRepair={onRepair}
onAddModel={onAddModel}
/>
diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.ts
index 857ae95e6..fb06374ba 100644
--- a/ui/src/components/settings/models/asyncLifetime.test.ts
+++ b/ui/src/components/settings/models/asyncLifetime.test.ts
@@ -80,10 +80,11 @@ import {
savedSourcesKey,
seedStep,
startNeedsStatusRead,
+ sourcesWithEcho,
terminalArrivalMovedRows,
type FlowView,
} from './asyncLifetime';
-import type { AgentSupply, OAuthFlow } from './types';
+import type { AgentSupply, OAuthFlow, Source } from './types';
const agent = (over: Partial<AgentSupply> = {}): AgentSupply => ({
backend: 'claude',
@@ -219,6 +220,50 @@ describe('agentsWithEcho — what speaks for a row when no read does', () => {
});
});
+describe('sourcesWithEcho — one refresh result inside the shared authority', () => {
+ const source = (id: string, models: string[]): Source => ({
+ id,
+ kind: 'api_key',
+ vendor: 'anthropic',
+ display_name: id,
+ protocol: 'anthropic',
+ supply_channel: 'hub',
+ billing: 'metered',
+ state: { status: 'standby', retry_at: null, detail_key: null },
+ last_discovered_at: '2026-07-31T05:00:00Z',
+ models: models.map((id) => ({ id, provenance: 'discovered' })),
+ });
+
+ it('replaces only the source named by the server echo', () => {
+ const first = source('src_first000', ['old-model']);
+ const second = source('src_second00', ['other-model']);
+ const echoed = source('src_first000', ['old-model', 'claude-opus-5']);
+
+ expect(sourcesWithEcho([first, second], echoed)).toEqual([echoed, second]);
+ });
+
+ it('does not append a row the inventory read never saw', () => {
+ const first = source('src_first000', ['old-model']);
+
+ expect(sourcesWithEcho([first], source('src_missing00', ['new-model']))).toEqual([first]);
+ });
+
+ it('routes refresh and full reads through the same latest-result authority', () => {
+ const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');
+
+ expect(page).toMatch(/const refreshed = await modelsApi\.refreshSource\(source\.id\);\s*await refreshAuthority\.run/);
+ expect(page).toMatch(/if \(landing\.kind === 'source'\)[\s\S]*?sourcesWithEcho\(previous, landing\.source\)/);
+ });
+
+ it('keeps the mutating refresh failure outside stale-read suppression', () => {
+ const page = readFileSync(join(__dirname, 'SettingsModelsPage.tsx'), 'utf8');
+ const refresh = page.slice(page.indexOf('const refreshSource ='), page.indexOf('// Resolve an open drawer'));
+
+ expect(refresh.indexOf('modelsApi.refreshSource')).toBeLessThan(refresh.indexOf('refreshAuthority.run'));
+ expect(refresh).toMatch(/catch \{[\s\S]*?sourceActions\.refreshFailed/);
+ });
+});
+
describe('createPendingWrites — a write that outlives the drawer that issued it', () => {
/** The published set, as the page would hold it in state. */
const registry = () => {
diff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.ts
index e4736e6c6..0c5de3bf2 100644
--- a/ui/src/components/settings/models/asyncLifetime.ts
+++ b/ui/src/components/settings/models/asyncLifetime.ts
@@ -2,7 +2,7 @@
// be exercised directly: which request may land, what speaks for a row when no
// read does, how long a write counts as outstanding, when a drawer re-seeds, and
// whether a connect-flow transition may change an already terminal view.
-import type { AgentMenu, AgentSupply, OAuthFlow, OAuthFlowState } from './types';
+import type { AgentMenu, AgentSupply, OAuthFlow, OAuthFlowState, Source } from './types';
// ── Latest async result ────────────────────────────────────────────────────
/**
@@ -90,6 +90,11 @@ export const agentsWithEcho = (
echoed: AgentSupply,
): AgentSupply[] => agents.map((agent) => (agent.backend === echoed.backend ? echoed : agent));
+/** Takes one source mutation echo into the already-loaded inventory without
+ * letting that single-row response answer which other rows exist. */
+export const sourcesWithEcho = (sources: readonly Source[], echoed: Source): Source[] =>
+ sources.map((source) => (source.id === echoed.id ? echoed : source));
+
// ── A write that outlives the drawer that issued it ────────────────────────
/**
* Which keys have a write outstanding, where 「outstanding」 spans the read-back
diff --git a/ui/src/components/settings/models/copyAgreement.test.ts b/ui/src/components/settings/models/copyAgreement.test.ts
index 3f8d47838..b528bbce1 100644
--- a/ui/src/components/settings/models/copyAgreement.test.ts
+++ b/ui/src/components/settings/models/copyAgreement.test.ts
@@ -44,7 +44,7 @@ const SINGULAR_VERB =
*
* `{{count}} model(s)` passes on purpose: it is correct at every count, and it is
* what the rest of this subtree already writes (`migration.applied`,
- * `sourceActions.rediscovered`, `migrationBanner.body`).
+ * `sourceActions.refreshed`, `migrationBanner.body`).
*/
const PLURAL_NOUN = /\{\{count\}\}\s+(?:more\s+)?[a-z]+s\b/i;
diff --git a/ui/src/components/settings/models/eligibility.test.ts b/ui/src/components/settings/models/eligibility.test.ts
index bfd5eb822..a32f82cb7 100644
--- a/ui/src/components/settings/models/eligibility.test.ts
+++ b/ui/src/components/settings/models/eligibility.test.ts
@@ -15,6 +15,7 @@ const source = (id: string): Source => ({
supply_channel: 'hub',
billing: 'metered',
state: { status: 'active', retry_at: null, detail_key: null },
+ last_discovered_at: null,
models: [],
});
diff --git a/ui/src/components/settings/models/eventFeed.test.ts b/ui/src/components/settings/models/eventFeed.test.ts
index d65d2be0a..be99ff001 100644
--- a/ui/src/components/settings/models/eventFeed.test.ts
+++ b/ui/src/components/settings/models/eventFeed.test.ts
@@ -213,7 +213,7 @@ describe('the page reads the feed through this owner', () => {
// the same Promise.all, one failing leg left repaired sources and the ● 当前
// the user just moved on screen as they were before the mutation.
expect(page).toMatch(/modelsApi\.listEvents\(EVENT_PAGE\)\.catch\(\(\) => null\)/);
- expect(page).toMatch(/createLatestAsyncAuthority<\[Source\[\], AgentSupply\[\], ResolutionEvent\[\] \| null, ModelChainIndex\]>/);
+ expect(page).toMatch(/createLatestAsyncAuthority<ModelSurfaceLanding>/);
// Sources and agents are NOT tolerated the same way — they are what this
// refresh is for, and the caller's toast is what reports them failing.
expect(page).not.toMatch(/modelsApi\.list(Sources|Agents)\(\)\.catch/);
diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.ts
index 0444da5ba..f5c40cee3 100644
--- a/ui/src/components/settings/models/mockData.ts
+++ b/ui/src/components/settings/models/mockData.ts
@@ -29,6 +29,7 @@ export function buildMockSources(): Source[] {
{
id: 'src_claudepro1',
created_at: iso(-30 * DAY),
+ last_discovered_at: iso(-3 * HOUR),
kind: 'subscription',
vendor: 'anthropic',
display_name: 'Claude Pro 订阅',
@@ -50,6 +51,7 @@ export function buildMockSources(): Source[] {
{
id: 'src_chatgptplus',
created_at: iso(-20 * DAY),
+ last_discovered_at: iso(-3 * HOUR),
kind: 'subscription',
vendor: 'openai',
display_name: 'ChatGPT Plus 订阅',
@@ -70,6 +72,7 @@ export function buildMockSources(): Source[] {
{
id: 'src_anthkey01',
created_at: iso(-10 * DAY),
+ last_discovered_at: iso(-6 * HOUR),
kind: 'api_key',
vendor: 'anthropic',
display_name: 'Anthropic API Key',
@@ -91,6 +94,7 @@ export function buildMockSources(): Source[] {
{
id: 'src_zhipukey01',
created_at: iso(-4 * DAY),
+ last_discovered_at: iso(-6 * HOUR),
kind: 'api_key',
vendor: 'zhipuai',
display_name: '智谱 API Key',
@@ -116,6 +120,7 @@ export function buildMockSources(): Source[] {
// chain as ChatGPT Plus › relay.example › 智谱 API Key, and under §4.2 an
// api_key's place in that chain is its created_at.
created_at: iso(-6 * DAY),
+ last_discovered_at: null,
kind: 'api_key',
vendor: 'custom',
display_name: 'relay.example',
diff --git a/ui/src/components/settings/models/modelRows.test.ts b/ui/src/components/settings/models/modelRows.test.ts
index 778baa711..9625f3db1 100644
--- a/ui/src/components/settings/models/modelRows.test.ts
+++ b/ui/src/components/settings/models/modelRows.test.ts
@@ -68,6 +68,7 @@ const source = (id: string): Source => ({
supply_channel: 'hub',
billing: 'metered',
state: { status: 'active' },
+ last_discovered_at: null,
models: [],
});
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index 647784cf6..591abfaf0 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -69,6 +69,7 @@ import { AGENT_CHAIN_CONTRACT_VERSION, PROBE_RESULT_CONTRACT_VERSION } from './t
*/
export type Adoption = { adopted_by: AdoptedBy[]; skipped_by: SkippedBy[] | null };
export type SourceCreated = { source: Source } & Adoption;
+export type SourceRefresh = { source: Source; discovered: number };
/**
* The response of BOTH oauth status and submit (api.md → OAuth completion): the
@@ -100,11 +101,11 @@ export type ModelsApi = {
createApiKeySource(draft: ApiKeySourceCreate): Promise<SourceCreated>;
/** Rename / re-point a source (display_name, base_url). */
patchSource(id: string, patch: SourcePatch): Promise<Source>;
- /** Re-run discovery on a hub source; resolves with the discovered count.
+ /** Re-run discovery on a hub source; resolves with the updated source and count.
* Contractually ALSO the recovery test: run on a needs_action / error source
* it clears the blocker and returns the source to standby. v3 adds no second
* 「recover」 endpoint, so this is the whole retry affordance. */
- testSource(id: string): Promise<number>;
+ refreshSource(id: string): 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
@@ -362,7 +363,7 @@ const liveApi: ModelsApi = {
// of them this commit changed.
createApiKeySource: (draft) => call<SourceCreatedResponse>('/api/models/sources', jsonInit('POST', draft)).then(created),
patchSource: (id, patch) => call<{ source?: Source } & Source>(`/api/models/sources/${encodeURIComponent(id)}`, jsonInit('PATCH', patch)).then((r) => (r.source ?? r) as Source),
- testSource: (id) => call<{ discovered: number }>(`/api/models/sources/${encodeURIComponent(id)}/test`, jsonInit('POST')).then((r) => r.discovered),
+ refreshSource: (id) => call<SourceRefresh>(`/api/models/sources/${encodeURIComponent(id)}/refresh`, jsonInit('POST')),
deleteSource: (id, force) => call(`/api/models/sources/${encodeURIComponent(id)}${force ? '?force=true' : ''}`, jsonInit('DELETE')).then(() => undefined),
// Both repair routes reject unknown body keys outright (`discovery_failed` /
// `reauth_confirmation_required`), so these bodies are exactly the contract's
@@ -543,6 +544,7 @@ class MockStore {
const source: Source = {
id: rid('src'),
created_at: new Date().toISOString(),
+ last_discovered_at: new Date().toISOString(),
kind: 'api_key',
vendor: draft.vendor,
display_name: draft.vendor === 'custom' ? hostLabel(draft.base_url) : vendorLabel(draft.vendor),
@@ -629,7 +631,7 @@ class MockStore {
const recovered = wasBlocked(source.state);
const previousMask = source.masked_credential;
const previousState = { ...source.state };
- // Atomic commit, standby-clearing semantics shared with testSource: a
+ // Atomic commit, standby-clearing semantics shared with refreshSource: a
// replacement re-discovers and lands on standby, never straight to active.
source.masked_credential = maskKey(body.key);
source.credential_ref = rid('cred');
@@ -947,6 +949,7 @@ class MockStore {
this.sources.push({
id: rid('src'),
created_at: new Date().toISOString(),
+ last_discovered_at: new Date().toISOString(),
kind: isKey ? 'api_key' : 'subscription',
vendor: item.backend === 'opencode' ? 'zhipuai' : item.backend === 'codex' ? 'openai' : 'anthropic',
display_name: item.masked_detail.split(' · ')[0] || 'Imported',
@@ -1066,6 +1069,7 @@ class MockStore {
if (!source) return;
source.account_label = '[email protected]';
source.state = { status: 'standby', retry_at: null, detail_key: null };
+ source.last_discovered_at = new Date().toISOString();
if (source.models.length === 0) {
source.models = [
{
@@ -1084,6 +1088,7 @@ class MockStore {
this.sources.push({
id,
created_at: new Date().toISOString(),
+ last_discovered_at: new Date().toISOString(),
kind: 'subscription',
vendor: flow.vendor,
display_name: isOpenai ? 'ChatGPT 订阅' : 'Claude 订阅',
@@ -1145,14 +1150,15 @@ class MockStore {
return delay(structuredClone(source), 300);
}
- testSource(id: string) {
+ refreshSource(id: string) {
const source = this.sources.find((s) => s.id === id);
if (!source) throw new ApiCallError('source_not_found');
// Native-CLI subscriptions can't be re-discovered (server rejects them);
// the UI only offers this action for hub sources, but fail closed anyway.
if (source.supply_channel === 'native_cli') throw new ApiCallError('discovery_failed');
source.state = { status: 'standby', retry_at: null, detail_key: null };
- return delay(source.models.length, 700);
+ source.last_discovered_at = new Date().toISOString();
+ return delay({ source: structuredClone(source), discovered: source.models.length }, 700);
}
}
@@ -1201,7 +1207,7 @@ const mockApi: ModelsApi = {
listSources: () => mockStore.listSources(),
createApiKeySource: (draft) => mockStore.createApiKeySource(draft),
patchSource: (id, patch) => mockStore.patchSource(id, patch),
- testSource: (id) => mockStore.testSource(id),
+ refreshSource: (id) => mockStore.refreshSource(id),
deleteSource: (id, force) => mockStore.deleteSource(id, force),
replaceCredential: (id, body) => mockStore.replaceCredential(id, body),
reauthSource: (id) => mockStore.reauthSource(id),
diff --git a/ui/src/components/settings/models/repair.test.ts b/ui/src/components/settings/models/repair.test.ts
index 06febf333..d12b59c16 100644
--- a/ui/src/components/settings/models/repair.test.ts
+++ b/ui/src/components/settings/models/repair.test.ts
@@ -47,6 +47,7 @@ const source = (over: Partial<Source> = {}): Source => ({
billing: 'metered',
credential_ref: 'cred_a',
state: { status: 'active' },
+ last_discovered_at: null,
models: [],
...over,
});
@@ -124,7 +125,7 @@ describe('repairAction — the one tap a stopped row offers (SourceRowMenu)', ()
});
it('offers nothing to a native source with an upstream cause', () => {
- // Nothing to re-discover (`POST …/test` rejects native), and NOT the re-login
+ // Nothing to re-discover (`POST …/refresh` rejects native), and NOT the re-login
// that the unclassified case below gets: a native re-login invalidates the
// working sign-in up front, so offering it for 账号被封 would charge the user
// that price for a blocker it cannot clear. This is rule 3's boundary.
@@ -167,8 +168,8 @@ describe('model-row repair routing', () => {
const page = readFileSync(join(here, 'SettingsModelsPage.tsx'), 'utf8');
expect(card).toMatch(/repair\?\.kind === 'retest'[\s\S]*?onRetest\(repair\.source\)/);
- expect(page).toMatch(/const retestSource = async \(source: Source\)[\s\S]*?modelsApi\.testSource\(source\.id\)/);
- expect(page).toMatch(/onRetest=\{\(source\) => void retestSource\(source\)\}/);
+ expect(page).toMatch(/const refreshSource = async \(source: Source\)[\s\S]*?modelsApi\.refreshSource\(source\.id\)/);
+ expect(page).toMatch(/onRetest=\{\(source\) => void refreshSource\(source\)\}/);
});
});
diff --git a/ui/src/components/settings/models/repair.ts b/ui/src/components/settings/models/repair.ts
index 38370ceb2..da41428bb 100644
--- a/ui/src/components/settings/models/repair.ts
+++ b/ui/src/components/settings/models/repair.ts
@@ -50,7 +50,7 @@ export const canReauth = (source: Source): boolean => source.kind === 'subscript
export const canReplaceKey = (source: Source): boolean =>
source.kind === 'api_key' && source.supply_channel === 'hub' && Boolean(source.credential_ref);
-/** `POST …/test` is the contract's ONE recovery endpoint (「v3 does not add a
+/** `POST …/refresh` is the contract's ONE recovery endpoint (「v3 does not add a
* second 'recover' endpoint」) and rejects native sources, which have nothing to
* re-discover. */
export const canRetest = (source: Source): boolean => source.supply_channel === 'hub';
@@ -99,7 +99,7 @@ export function repairAction(source: Source): RepairKind | null {
return null;
}
if (canRetest(source)) return 'retest';
- // Native has no recovery test — `test_source` refuses `native_cli` outright — so
+ // Native has no recovery refresh — `refresh_source` refuses `native_cli` outright — so
// rules 1 and 2 together leave a stopped native row with no tap at all, its
// remedy surviving only in the overflow menu. Rule 3 covers the one cause where
// signing in again is the answer rather than a guess, and the cause matters
diff --git a/ui/src/components/settings/models/sufficiency.test.ts b/ui/src/components/settings/models/sufficiency.test.ts
index 3f9157282..d8fceb5df 100644
--- a/ui/src/components/settings/models/sufficiency.test.ts
+++ b/ui/src/components/settings/models/sufficiency.test.ts
@@ -28,6 +28,7 @@ const source = (id: string, status: SourceStatus): Source => ({
supply_channel: 'hub',
billing: 'metered',
state: { status, ...(status === 'cooldown' ? { retry_at: '2030-01-01T00:00:00Z' } : {}) } as SourceState,
+ last_discovered_at: null,
models: [],
});
diff --git a/ui/src/components/settings/models/supply.test.ts b/ui/src/components/settings/models/supply.test.ts
index 52b87fe7e..73ee6b94e 100644
--- a/ui/src/components/settings/models/supply.test.ts
+++ b/ui/src/components/settings/models/supply.test.ts
@@ -20,6 +20,7 @@ const source = (id: string, state: SourceState, name = id): Source => ({
supply_channel: 'hub',
billing: 'metered',
state,
+ last_discovered_at: null,
models: [],
});
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 2a9269499..9496500e4 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -87,6 +87,9 @@ export type Source = {
* sources array itself is explicitly unordered). May be null on rows
* persisted before the field existed; `id` ascending is the tie-breaker. */
created_at?: string | null;
+ /** Latest successful full model discovery for this source. null means the
+ * source predates the field or has no known successful discovery. */
+ last_discovered_at: string | null;
kind: SourceKind;
/** Standard vendor id (anthropic|openai|zhipuai|kimi|xai|…) or 'custom'. */
vendor: string;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 7bb0bc590..d19f42ba0 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -635,6 +635,8 @@
"subtitle": "Manage shared accounts and model inventories; source order is set on each agent card",
"empty": "No sources yet — use “Add source” to connect a subscription or API key.",
"modelCount": "{{count}} model(s)",
+ "lastDiscovery": "Last fetched {{time}}",
+ "neverDiscovered": "Not fetched yet",
"addModel": "Add model",
"modelsEmpty": "No supplied models yet. Add one manually.",
"modelsEmptySubscription": "No supplied models were discovered."
@@ -1011,7 +1013,8 @@
"sourceActions": {
"more": "More actions",
"rename": "Rename",
- "rediscover": "Re-discover models",
+ "refresh": "Refresh models",
+ "refreshing": "Refreshing models",
"reauth": "Sign in again",
"replaceKey": "Replace API key",
"delete": "Delete source",
@@ -1020,8 +1023,8 @@
"renamePlaceholder": "e.g. Production key",
"renamed": "Renamed",
"renameFailed": "Couldn't rename, please retry",
- "rediscovered": "Re-discovered {{count}} model(s)",
- "rediscoverFailed": "Couldn't re-discover, please retry",
+ "refreshed": "Updated {{count}} model(s)",
+ "refreshFailed": "Couldn't fetch the latest models. The last successful list is still shown.",
"deleteTitle": "Delete source?",
"deleteBody": "This removes “{{name}}” from the Hub and revokes its credential. This can't be undone.",
"deleteConfirm": "Delete",
@@ -1031,7 +1034,6 @@
"deleted": "Source deleted",
"deleteFailed": "Couldn't delete, please retry",
"renameHint": "Changes the display name only — the credential is untouched",
- "rediscoverHint": "Re-fetch the models this source can supply",
"deleteHint": "You'll be asked to confirm first",
"reauthHint": "The old sign-in stops working right away",
"replaceKeyHint": "Enter a new key — the endpoint and name stay"
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index ec7624779..cba8d5777 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -635,6 +635,8 @@
"subtitle": "管理全局共用的账号和型号清单;来源顺序在各 Agent 卡片中调整",
"empty": "还没有来源,点“添加来源”连接订阅或 API Key。",
"modelCount": "{{count}} 个型号",
+ "lastDiscovery": "上次自动获取 {{time}}",
+ "neverDiscovered": "尚未自动获取",
"addModel": "添加型号",
"modelsEmpty": "还没有可供给的型号,请手动添加。",
"modelsEmptySubscription": "还没有发现可供给的型号。"
@@ -1011,7 +1013,8 @@
"sourceActions": {
"more": "更多操作",
"rename": "重命名",
- "rediscover": "重新发现模型",
+ "refresh": "刷新模型",
+ "refreshing": "正在刷新模型",
"reauth": "重新登录",
"replaceKey": "更换 API Key",
"delete": "删除来源",
@@ -1020,8 +1023,8 @@
"renamePlaceholder": "例如 生产环境 Key",
"renamed": "已重命名",
"renameFailed": "重命名失败,请重试",
- "rediscovered": "已重新发现 {{count}} 个模型",
- "rediscoverFailed": "重新发现失败,请重试",
+ "refreshed": "已更新 {{count}} 个模型",
+ "refreshFailed": "未能获取最新模型,仍显示上次成功获取的清单。",
"deleteTitle": "删除来源?",
"deleteBody": "将从中枢移除「{{name}}」并撤销其凭证,此操作不可撤销。",
"deleteConfirm": "删除",
@@ -1031,7 +1034,6 @@
"deleted": "已删除来源",
"deleteFailed": "删除失败,请重试",
"renameHint": "只改显示名,不动凭证",
- "rediscoverHint": "重新拉取这个来源能供给的模型",
"deleteHint": "删除前会再确认一次",
"reauthHint": "旧登录立即失效",
"replaceKeyHint": "填入新 Key,地址与显示名不变"
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index 3e1f6c8ca..c4b9d392c 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -103,8 +103,8 @@ class ModelHubRemoteService:
async def delete_source(self, source_id: str, *, force: bool = False) -> None:
await _rpc("delete_source", {"source_id": source_id, "force": force})
- async def test_source(self, source_id: str) -> tuple[dict, int]:
- result = await _rpc("test_source", {"source_id": source_id})
+ async def refresh_source(self, source_id: str) -> tuple[dict, int]:
+ result = await _rpc("refresh_source", {"source_id": source_id})
return result["source"], result["discovered"]
def list_agents(self) -> list[dict]:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index ffbc65526..856e487bf 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3230,13 +3230,13 @@ async def model_hub_sources_delete(source_id):
return _model_hub_error(exc)
[email protected]("/api/models/sources/<source_id>/test", methods=["POST"])
-async def model_hub_sources_test(source_id):
[email protected]("/api/models/sources/<source_id>/refresh", methods=["POST"])
+async def model_hub_sources_refresh(source_id):
from core.handlers.model_hub import ModelHubError
try:
- _, discovered = await _model_hub_service().test_source(source_id)
- return _model_hub_success(discovered=discovered)
+ source, discovered = await _model_hub_service().refresh_source(source_id)
+ return _model_hub_success(source=source, discovered=discovered)
except ModelHubError as exc:
return _model_hub_error(exc)