Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): show, keep, and log what the upstream said on failure (#2376)
Call White2c56234994a0
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 4eb021670..b544e6aaf 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -145,11 +145,26 @@ class TurnSupplyFacts:blockers: tuple[TurnSupplyBlocker, ...] = ()+@dataclass(frozen=True)+class TurnUpstreamFailure:+ """The last upstream refusal or connection failure behind a failed turn."""++ source: str+ # None when no upstream answered: the text is the connection failure.+ http_status: int | None+ # Redacted and bounded by the engine client; display only.+ detail: str++@dataclass(frozen=True)class TurnOutcomeRenderingRule:outcome: strdiscriminator: strcopy_keys: tuple[tuple[str, str | None], ...]+ # Appended to the summary when the turn carries its last upstream failure:+ # an upstream refusal, or a connection that no upstream answered.+ upstream_failure_key: str | None = None+ connection_failure_key: str | None = None# This is the only executable projection of the authoritative section 4.5 matrix.@@ -167,6 +182,8 @@ TURN_OUTCOME_RENDERING_AUTHORITY: dict[str, TurnOutcomeRenderingRule] = {("waiting_without_retry", "modelHub.launch.waiting_without_retry"),("interrupted", "modelHub.launch.interrupted"),),+ upstream_failure_key="modelHub.launch.last_upstream_failure",+ connection_failure_key="modelHub.launch.last_connection_failure",),"turn.request_nonfallback": TurnOutcomeRenderingRule(outcome="failed_terminal",@@ -193,6 +210,8 @@ TURN_OUTCOME_RENDERING_AUTHORITY: dict[str, TurnOutcomeRenderingRule] = {("interrupted", "modelHub.launch.interrupted"),("transition_unpersisted", "modelHub.errors.stream_interrupted"),),+ upstream_failure_key="modelHub.launch.last_upstream_failure",+ connection_failure_key="modelHub.launch.last_connection_failure",),"turn.no_candidate.unconfigured": TurnOutcomeRenderingRule(outcome="no_candidate",@@ -212,6 +231,8 @@ TURN_OUTCOME_RENDERING_AUTHORITY: dict[str, TurnOutcomeRenderingRule] = {("waiting_without_retry", "modelHub.launch.waiting_without_retry"),("interrupted", "modelHub.launch.interrupted"),),+ upstream_failure_key="modelHub.launch.last_upstream_failure",+ connection_failure_key="modelHub.launch.last_connection_failure",),"turn.canceled": TurnOutcomeRenderingRule(outcome="canceled",@@ -233,6 +254,8 @@ class TurnOutcomeProjectionInput:upstream_detail: str | None = None# An OS-generated reason, separate from summary copy and upstream text.local_error_detail: str | None = None+ # The last fallback-class upstream refusal, appended to supply copy.+ last_upstream_failure: TurnUpstreamFailure | None = Noneclass TurnOutcomeProductionError(ValueError):@@ -295,6 +318,7 @@ def produce_turn_outcome(stream_started: bool = False,source_transition_persisted: bool | None = None,upstream_detail: str | None = None,+ last_upstream_failure: TurnUpstreamFailure | None = None,) -> TurnOutcomeProjectionInput:"""Produce complete terminal facts from one authoritative matrix row."""@@ -366,6 +390,9 @@ def produce_turn_outcome(if "upstream_detail" in variants and upstream_detailelse None),+ last_upstream_failure=(+ last_upstream_failure if rule.upstream_failure_key is not None else None+ ),)if _turn_outcome_variant(projection, rule) not in dict(rule.copy_keys):raise TurnOutcomeProductionError(@@ -563,7 +590,22 @@ def render_turn_outcome_copy(params["blockers"] = ", ".join(rendered)if params.get("backend"):params["backend"] = i18n_t(f"modelHub.backends.{params['backend']}", language)- return i18n_t(copy.key, language, **params)+ text = i18n_t(copy.key, language, **params)+ failure = projection.last_upstream_failure+ rule = _turn_outcome_rule(projection)+ suffix_key = (+ rule.upstream_failure_key if failure is not None and failure.http_status is not None+ else rule.connection_failure_key+ )+ if failure is not None and suffix_key is not None:+ text = " ".join((+ text,+ i18n_t(+ suffix_key, language,+ source=failure.source, status=failure.http_status, detail=failure.detail,+ ),+ ))+ return text# The request id for a turn's own single attempt: the native CLI path, where@@ -2163,11 +2205,20 @@ class TurnCorrelationRegistry:trace.served = identity.payload()trace.terminal_error = Nonereturn+ # The engine client already redacted and bounded this text.+ detail = {"upstream_detail": outcome.upstream_detail} if outcome.upstream_detail else {}+ logger.warning(+ "Model Hub attempt failed turn=%s source=%s model=%s http_status=%s reason=%s "+ "stream_started=%s detail=%s",+ turn_id, identity.source_id, identity.resolved_model_id, outcome.http_status,+ decision.reason or decision.error_code, outcome.stream_started, outcome.upstream_detail,+ )if decision.action == "fallback" and decision.reason is not None:trace.failed_attempts.append({**identity.payload(), "reason": decision.reason,**({"http_status": outcome.http_status} if type(outcome.http_status) is int and 100 <= outcome.http_status <= 599 else {}),+ **detail,})return@@ -2188,6 +2239,7 @@ class TurnCorrelationRegistry:else None),"upstream_error_code": diagnostic_code,+ **detail,}def close_turn_admission(self, turn_id: str, *, settled_by: Optional[str]) -> None:diff --git a/core/handlers/model_hub/retry.py b/core/handlers/model_hub/retry.pyindex fa1bec739..6dd589a91 100644--- a/core/handlers/model_hub/retry.py+++ b/core/handlers/model_hub/retry.py@@ -13,6 +13,7 @@ from typing import Awaitable, Callablefrom config.v2_config import ModelHubConfig, ModelHubSourceConfig+from .provenance import TurnUpstreamFailurefrom .resolver import SourceRecoveryAnnotation, parse_model_hub_timestamp@@ -72,6 +73,8 @@ class RecoveryRequest:observer: Callable[[dict | None], None] | None = None# A hard failure this request itself observed ends it with that verdict.non_retryable_failure: bool = False+ # Carried across walks so a later blocked walk still names what failed.+ last_upstream_failure: TurnUpstreamFailure | None = Nonedef start(self) -> None:if self.started is None:diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 3357e489a..79c42b15f 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -135,6 +135,7 @@ from .provenance import (ENGINE_DOWN_TURN_OUTCOME,ExactHopBlocker,TurnOutcomeProjectionInput,+ TurnUpstreamFailure,exact_hop_blockers,no_candidate_decision,produce_turn_outcome,@@ -7569,24 +7570,42 @@ class ModelHubService:backend=backend,model_id=model_id,)+ source_label = next(+ (source.display_name for source in config.sources if source.id == source_id), source_id,+ )return produce_turn_outcome("turn.streamed_fallback",config=config,resolution=resolution,attempted_hop=(source_id, source_model_id),source_transition_persisted=source_transition_persisted,+ last_upstream_failure=self._upstream_failure(source_label, outcome),)+ @staticmethod+ def _upstream_failure(source_label: str, outcome: RawCallOutcome) -> TurnUpstreamFailure | None:+ if not outcome.upstream_detail:+ return None+ if outcome.kind in {RawOutcomeKind.NETWORK_ERROR, RawOutcomeKind.TIMEOUT}:+ # The engine's own connection diagnostic: no upstream answered.+ return TurnUpstreamFailure(source=source_label, http_status=None, detail=outcome.upstream_detail)+ status = outcome.http_status+ if type(status) is not int or not 100 <= status <= 599:+ return None+ return TurnUpstreamFailure(source=source_label, http_status=status, detail=outcome.upstream_detail)+@staticmethoddef _produce_no_candidate_terminal_outcome(*,config: ModelHubConfig,resolution: ModelHubTurnResolution,+ last_upstream_failure: TurnUpstreamFailure | None = None,) -> TurnOutcomeProjectionInput:return produce_turn_outcome(no_candidate_decision(config, resolution),config=config,resolution=resolution,+ last_upstream_failure=last_upstream_failure,)@staticmethod@@ -7594,11 +7613,13 @@ class ModelHubService:*,config: ModelHubConfig,resolution: ModelHubTurnResolution,+ last_upstream_failure: TurnUpstreamFailure | None = None,) -> TurnOutcomeProjectionInput:return produce_turn_outcome("turn.exhausted",config=config,resolution=resolution,+ last_upstream_failure=last_upstream_failure,)@staticmethod@@ -8180,6 +8201,9 @@ class ModelHubService:)(config=projection_config,resolution=projection_resolution,+ last_upstream_failure=(+ recovery_request.last_upstream_failure if recovery_request is not None else None+ ),)facts = turn_outcome.supply_factsif facts is None:@@ -8196,6 +8220,9 @@ class ModelHubService:failed_source: Optional[ModelHubSourceConfig] = Nonefailed_reason: Optional[EventReason] = None+ last_upstream_failure = (+ recovery_request.last_upstream_failure if recovery_request is not None else None+ )window_closed = Falsenon_retryable_failure = Falseattempted = False@@ -8454,6 +8481,11 @@ class ModelHubService:recovery_request.reason = decision.reasonelif recovery_request is not None:recovery_request.non_retryable_failure = True+ # The newest refusal wins even without text: an older message+ # would name a response that did not end this request.+ last_upstream_failure = self._upstream_failure(source.display_name, outcome)+ if recovery_request is not None:+ recovery_request.last_upstream_failure = last_upstream_failureevent_reason, _persisted = await self._settle_fallback_source(source,decision,@@ -8488,6 +8520,7 @@ class ModelHubService:turn_outcome = produce_outcome(config=final_config,resolution=final_resolution,+ last_upstream_failure=last_upstream_failure,)final_facts = turn_outcome.supply_factsif final_facts is None:diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex dc8b5745f..97b9e02ca 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1319,8 +1319,8 @@ was observed and classification returned `upstream_request_invalid`, retain it oco-occurring generic `invalid_request_error` type; otherwise use existing specificityorder. This is diagnostic selection, not a classifier rank/decision change. Never infer`model_not_found` from `invalid_parameter`, the requested model, or today's route.-Unknown upstream strings, raw bodies, messages, headers and credentials are not-retained. These optional observations do not change classification, fallback or Source+Unknown upstream strings, raw bodies, headers and credentials are not retained; the+upstream message is kept only as the bounded `upstream_detail` below. These optional observations do not change classification, fallback or Sourcehealth. Historical records may omit both fields and keep their existing read behavior.`failed_attempts[].http_status` is independently optional: a strict integer@@ -1329,6 +1329,14 @@ It records the original upstream status, for example 503 even when nativecompatibility uses 400. Older retained records without it remain readable.This additive diagnostic changes neither the failure reason nor classifier.+`failed_attempts[].upstream_detail` and `terminal_error.upstream_detail` are+independently optional strings: the upstream error message the engine client+projected for that attempt, or for a `network` attempt the engine's own connection+diagnostic (which carries no `http_status`). The text is credential-redacted, stripped+of control and bidi characters, whitespace-collapsed, and bounded to 400 characters.+They are omitted when no message was observed and in older records, and are never+read by classification.+The dialog independently reads this projection on demand and labels it "Latest recordedturn" / "最近已记录回合". Its error panel and details action use the same structured record,recorded timestamp and exact historical Source/model identifiers. Deleted Sources keepdiff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.jsonindex 826bf93bc..e3cc35673 100644--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json@@ -94,6 +94,12 @@"maximum": 599,"description": "Optional actual upstream HTTP status, independent of the native-compatible recovery-exhausted gateway response. Absent for unobserved/native transport failures and historical records."},+ "upstream_detail": {+ "type": "string",+ "minLength": 1,+ "maxLength": 400,+ "description": "Optional error text for this attempt, credential-redacted, stripped of control and bidi characters, whitespace-collapsed, and bounded to 400 characters by the engine client: the upstream's message, or for a network attempt the engine's connection diagnostic. Display only; never read by classification. Absent when no message was observed and in historical records."+ },"reason": {"enum": ["quota_exhausted",@@ -204,7 +210,13 @@"api_error",null],- "description": "Optional observed machine code from classification.UPSTREAM_MACHINE_ERROR_CODES. If model_not_found was observed and classification returned upstream_request_invalid, retain that specific code over a co-occurring generic invalid_request_error type; otherwise use existing specificity order. This diagnostic selection never reranks or changes classification. Never derive a code from invalid_parameter; unknown codes, raw messages, bodies, headers and credentials are not retained. Absent evidence is null; historical records may omit the field."+ "description": "Optional observed machine code from classification.UPSTREAM_MACHINE_ERROR_CODES. If model_not_found was observed and classification returned upstream_request_invalid, retain that specific code over a co-occurring generic invalid_request_error type; otherwise use existing specificity order. This diagnostic selection never reranks or changes classification. Never derive a code from invalid_parameter; unknown codes, bodies, headers and credentials are not retained. Absent evidence is null; historical records may omit the field."+ },+ "upstream_detail": {+ "type": "string",+ "minLength": 1,+ "maxLength": 400,+ "description": "Optional upstream error message for this terminal attempt, under the same redaction and bound as failed_attempts[].upstream_detail. Display only; absent when no message was observed and in historical records."}},"dependencies": {diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex 23da7e746..f7c2e8e1e 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -1295,9 +1295,20 @@ checked mechanically against both `vibe/i18n` locale files. A new outcome, discror supply message ships as one new matrix row plus its enum/key/mirror fixtures; none mayland as standalone prose.-`upstream_detail` is display-only reply text. It is never read by classification,-never written to resolution events, probes, or persisted provenance, and lives only on-the in-memory turn projection that renders this turn's reply.+`upstream_detail` is display-only text. It is never read by classification and+never written to resolution events or probes. Owner decision (2026-10-07): an upstream+refusal that only says "server error" cannot be diagnosed, so persisted provenance keeps+it per attempt (`failed_attempts[].upstream_detail`, `terminal_error.upstream_detail`),+each failed Hub attempt logs it once, and the `turn.exhausted`,+`turn.no_candidate.blocked`, and `turn.streamed_fallback` rows append the last+fallback-class failure of the pending request to their summary copy. An upstream+refusal renders `modelHub.launch.last_upstream_failure` (Source, HTTP status, text).+The engine's own transport envelope (`network_failure.transport_before_first_byte`)+carries no upstream status and renders `modelHub.launch.last_connection_failure`+(Source, text), and Failure details labels that text as a connection error, never as+what the upstream said. The text is the same projection in every place:+credential-redacted, C0/C1 and Unicode Bidi_Control characters removed,+whitespace-collapsed, and bounded to 400 characters.For `turn.engine_down`, an optional `local_error_detail` carries the numeric OSerrno and its system message, such as `[Errno 28] No space left on device`.diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex d5760d723..128938121 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -223,6 +223,14 @@ scenarios:test: tests/test_model_hub_l3.py::test_a_request_ending_beside_an_open_peer_leaves_the_turn_to_that_peerrelated_tests:- tests/test_model_hub_retry_lifecycle.py::test_a_waiter_ending_beside_the_slot_owner_leaves_no_turn_projection+ - id: MH-UPSTREAM-DETAIL-001+ name: A failed turn shows, records, and logs what the upstream said, not only its class+ status: covered+ kind: copy+ layer: unit+ test: tests/test_model_hub_failure_presentation.py::test_upstream_refusal_text_reaches_reply_record_and_log+ related_tests:+ - ui/src/components/workbench/FailureDetails.test.tsx- id: MH-RETRY-ADVICE-001name: Failed HTTP advice retains the receipt clock across delayed or broken bodiesstatus: covereddiff --git a/tests/test_model_hub_failure_presentation.py b/tests/test_model_hub_failure_presentation.pyindex da9a834f5..4aa2991b0 100644--- a/tests/test_model_hub_failure_presentation.py+++ b/tests/test_model_hub_failure_presentation.py@@ -1,6 +1,7 @@"""User-visible failure copy consumes exact Hub facts, not native error text."""import json+from dataclasses import replacefrom types import SimpleNamespacefrom unittest.mock import AsyncMock, Mock@@ -16,6 +17,7 @@ from core.handlers.model_hub.provenance import (render_turn_outcome_copy,)from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from core.run_settlement import SETTLED_BY_TERMINAL_RESULTfrom modules.agents.model_hub import ModelHubRuntimeRouter, bind_launchfrom modules.im import MessageContextfrom tests.test_model_hub_l3 import _canonicalize_fixed_test_routes, _outcome@@ -218,6 +220,85 @@ async def test_gateway_terminal_survives_native_recorder_before_shared_notice(await gateway.close()[email protected]("last_said", ["text", "nothing", "connection"])[email protected]("backend,endpoint,status", [+ ("codex", "responses", 400), ("claude", "messages", 424),+])[email protected]("language", ["en", "zh"])+async def test_upstream_refusal_text_reaches_reply_record_and_log(+ tmp_path, caplog, backend, endpoint, status, language, last_said,+):+ """MH-UPSTREAM-DETAIL-001: what the upstream said is shown, kept, and logged, not only its class."""+ detail = "upstream request failed: read tcp 198.51.100.7:443: i/o timeout"+ if last_said == "connection":+ # The engine's own transport envelope: no upstream answered at all.+ texts = [detail] * 12+ failure = _outcome(RawOutcomeKind.NETWORK_ERROR, source_id="src_recovery01")+ else:+ # Only the first refusal carries text when the last one said nothing.+ texts = [detail] + [detail if last_said == "text" else None] * 4+ failure = _outcome(RawOutcomeKind.HTTP_ERROR, source_id="src_recovery01", status=500, code="server_error")+ service, _clock = clock_service(tmp_path, outcomes=[+ replace(failure, upstream_detail=text) for text in texts+ ])+ service.store.load().sources[0].display_name = "Relay 服务"+ models = _canonicalize_fixed_test_routes(service)+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ context = MessageContext(+ user_id="user", channel_id="channel", platform="avibe",+ platform_specific={"turn_token": "turn-detail"},+ )+ controller = SimpleNamespace(+ config=SimpleNamespace(language=language),+ model_hub_turn_gateway=gateway,+ emit_agent_message=AsyncMock(return_value="msg-failed"),+ )+ try:+ launch = await router.resolve(+ backend, models[backend], process_scope="fixture-detail", turn_id="turn-detail",+ )+ bind_launch(context, launch)+ caplog.set_level("WARNING", logger="core.handlers.model_hub.provenance")+ async with aiohttp.ClientSession(trust_env=False, timeout=aiohttp.ClientTimeout(total=5)) as client:+ async with client.post(+ f"{launch.gateway_base_url}/v1/{endpoint}",+ headers={+ "Authorization": f"Bearer {launch.gateway_token}",+ **({"x-codex-turn-metadata": json.dumps(launch.gateway_request_metadata)}+ if launch.gateway_request_metadata else {}),+ },+ json={"model": launch.runtime_model, "stream": False},+ ) as response:+ assert response.status == status+ attempts = len(service.adapter.invocations)+ assert attempts >= 2+ diagnostic = f"Native error {status}"+ assert await router.record_native_failure(context, diagnostic) is False+ await emit_backend_failure(controller, context, backend, diagnostic)+ notice, _terminal = controller.emit_agent_message.await_args_list+ projection = gateway.correlation.terminal_projection("turn-detail", backend=backend)+ assert notice.args[2] == render_turn_outcome_copy(projection, language)+ suffix = t(+ "modelHub.launch.last_upstream_failure", language,+ source="Relay 服务", status=500, detail=detail,+ )+ connection = t("modelHub.launch.last_connection_failure", language, source="Relay 服务", detail=detail)+ # An older message never stands in for a newer refusal that had none,+ # and a connection failure is never presented as an upstream answer.+ assert (suffix in notice.args[2]) is (last_said == "text")+ assert (connection in notice.args[2]) is (last_said == "connection")+ gateway.correlation.settle("turn-detail", settled_by=SETTLED_BY_TERMINAL_RESULT)+ record = service.provenance.get("turn-detail")+ assert [attempt.get("upstream_detail") for attempt in record["failed_attempts"]] == texts[:attempts]+ logged = [entry.getMessage() for entry in caplog.records if "Model Hub attempt failed" in entry.getMessage()]+ status_text = "http_status=None" if last_said == "connection" else "http_status=500"+ assert len(logged) == attempts and all(status_text in line for line in logged)+ assert detail in logged[0]+ finally:+ await gateway.close()++@pytest.mark.parametrize("language", ["en", "zh"])def test_terminal_copy_never_promises_automatic_recovery(language):"""MH-RETRY-COPY-001: final failures never promise that a timer will recover a Source."""diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex f8d482a9e..cd00f8e07 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -193,7 +193,11 @@ def test_turn_outcome_rendering_authority_covers_matrix_and_locales() -> None:projected_keys = {keyfor rule in TURN_OUTCOME_RENDERING_AUTHORITY.values()- for _variant, key in rule.copy_keys+ for key in (+ *(key for _variant, key in rule.copy_keys),+ rule.upstream_failure_key,+ rule.connection_failure_key,+ )if key is not None}locale_launch_keys = Nonediff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 49805f5be..fea440f86 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -7428,6 +7428,8 @@ def test_engine_reported_upstream_transport_failure_takes_network_recovery(assert outcome.kind is kindassert outcome.stream_started is stream_startedassert classify_outcome(outcome).reason == reason+ # The engine's own 500 is not an upstream status.+ assert (outcome.http_status is None) is (kind is RawOutcomeKind.NETWORK_ERROR)@pytest.mark.parametrize(@@ -7517,6 +7519,19 @@ def test_engine_upstream_detail_keeps_email_addresses_usable() -> None:)+def test_engine_upstream_detail_drops_terminal_control_characters() -> None:+ payload = json.dumps(+ {"error": {"message": (+ "relay \x1b]52;c;cGF5bG9hZA==\x07 down\x1b[2J\x9b now"+ " \u202egnp.exe\u202c \u2066a\u2069\u2067b\u2068c\u200e\u200f\u061c end"+ )}}+ ).encode()++ detail = client_module._upstream_error_detail(payload, (("error",),))++ assert detail == "relay ]52;c;cGF5bG9hZA== down [2J now gnp.exe a b c end"++def test_engine_upstream_detail_replaces_lone_surrogates_so_it_can_persist() -> None:payload = b'{"error": {"message": "bad \\ud800 byte"}}'diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 1e94daa74..4df3f900e 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -613,7 +613,7 @@ export type TurnProvenance = {agent: AgentBackend;requested_model_id: string;outcome: 'served' | 'exhausted' | 'failed_terminal' | 'no_candidate' | 'canceled';- failed_attempts: Array<RecordedAttempt & { reason: ResolutionReason; http_status?: number | null }>;+ failed_attempts: Array<RecordedAttempt & { reason: ResolutionReason; http_status?: number | null; upstream_detail?: string }>;served: RecordedAttempt | null;canceled_attempt: RecordedAttempt | null;terminal_error: {@@ -624,6 +624,7 @@ export type TurnProvenance = {stream_started: boolean;http_status?: number | null;upstream_error_code?: string | null;+ upstream_detail?: string;local_error_detail?: string;stripped_reasoning_efforts?: string[];declared_reasoning_efforts?: string[];diff --git a/ui/src/components/workbench/FailureDetails.test.tsx b/ui/src/components/workbench/FailureDetails.test.tsxindex 8688551d7..868abbb62 100644--- a/ui/src/components/workbench/FailureDetails.test.tsx+++ b/ui/src/components/workbench/FailureDetails.test.tsx@@ -33,13 +33,17 @@ const record = {requested_model_id: 'grok-4.6',outcome: 'failed_terminal',failed_attempts: [- { source_id: 'src_a', configured_model_id: 'grok-4.6', channel: 'hub', reason: 'rate_limited', http_status: 429 },+ {+ source_id: 'src_a', configured_model_id: 'grok-4.6', channel: 'hub', reason: 'rate_limited', http_status: 429,+ upstream_detail: 'Rate limit reached: 60 requests per minute',+ },],served: null,canceled_attempt: null,terminal_error: {source_id: 'src_b', configured_model_id: 'grok-4.6-beta', channel: 'hub',reason: 'invalid_parameter', stream_started: false, http_status: 400, upstream_error_code: 'model_not_found',+ upstream_detail: 'The model grok-4.6-beta does not exist',},model_supply_state: null,blockers: [{ source_id: 'src_c', model_id: 'grok-4.6', reason: 'source_missing' }],@@ -139,7 +143,7 @@ describe('failed-turn upstream details', () => {expect(sources).toHaveBeenCalledTimes(1);});- it('expands to the upstream status, error code and reason for every attempt', async () => {+ it('expands to the upstream status, error code, reason and message for every attempt', async () => {const read = vi.spyOn(modelsApi, 'getTurnProvenance').mockResolvedValue(record);mount();fireEvent.click(await screen.findByRole('button', { name: '查看详情' }));@@ -148,11 +152,13 @@ describe('failed-turn upstream details', () => {expect(screen.getByText('xAI 官方 · grok-4.6')).toBeTruthy();expect(screen.getByText('429')).toBeTruthy();expect(screen.getByText('触发限流')).toBeTruthy();+ expect(screen.getByText('Rate limit reached: 60 requests per minute')).toBeTruthy();// A source the Sources list no longer names still shows its stable id.expect(screen.getByText('src_b · grok-4.6-beta')).toBeTruthy();expect(screen.getByText('400')).toBeTruthy();expect(screen.getByText('model_not_found')).toBeTruthy();expect(screen.getByText('请求参数被拒绝')).toBeTruthy();+ expect(screen.getByText('The model grok-4.6-beta does not exist')).toBeTruthy();expect(screen.getByText(/供应商已不存在/)).toBeTruthy();expect(screen.getByText(/由上游供应商的 API 返回/)).toBeTruthy();fireEvent.click(screen.getByRole('button', { name: '收起详情' }));@@ -189,11 +195,32 @@ describe('failed-turn upstream details', () => {}});+ it('labels a network attempt\'s text as a connection error, not an upstream answer', async () => {+ vi.spyOn(modelsApi, 'getTurnProvenance').mockResolvedValue({+ ...record,+ outcome: 'exhausted',+ failed_attempts: [{+ source_id: 'src_a', configured_model_id: 'grok-4.6', channel: 'hub', reason: 'network',+ upstream_detail: 'read tcp 10.0.0.2:443: i/o timeout',+ }],+ terminal_error: null,+ } as unknown as TurnProvenance);+ mount();+ fireEvent.click(await screen.findByRole('button', { name: '查看详情' }));+ expect(screen.getByText('read tcp 10.0.0.2:443: i/o timeout')).toBeTruthy();+ expect(screen.getByText(/连接错误/)).toBeTruthy();+ expect(screen.queryByText(/上游返回/)).toBeNull();+ expect(screen.queryByText(/由上游供应商的 API 返回/)).toBeNull();+ });+it('names Avibe-side terminal failures and localizes every blocker reason', async () => {vi.spyOn(modelsApi, 'getTurnProvenance').mockResolvedValue({...record,failed_attempts: [],- terminal_error: { ...record.terminal_error, reason: 'engine_down', http_status: null, upstream_error_code: null },+ terminal_error: {+ ...record.terminal_error, reason: 'engine_down', http_status: null, upstream_error_code: null,+ upstream_detail: undefined,+ },blockers: [{ source_id: 'src_a', model_id: 'grok-4.6', reason: 'cooldown' }],} as unknown as TurnProvenance);mount();diff --git a/ui/src/components/workbench/FailureDetails.tsx b/ui/src/components/workbench/FailureDetails.tsxindex fc3c6c91f..96015376c 100644--- a/ui/src/components/workbench/FailureDetails.tsx+++ b/ui/src/components/workbench/FailureDetails.tsx@@ -6,8 +6,9 @@// HTTP status and machine error code, and why it moved on. That is what lets a// user see the refusal came from the upstream API and not from the gateway.//-// Raw upstream response prose is never retained. Local OS reasons are also-// carried by the notice, so details survive an unavailable provenance read.+// The upstream message is kept only as the engine client's credential-redacted,+// 400-character projection. Local OS reasons are also carried by the notice, so+// details survive an unavailable provenance read.import * as React from 'react';import { ChevronDown, ChevronRight } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -27,6 +28,9 @@ type Row = {status: number | null;code: string | null;reason: string;+ detail: string | null;+ // A network attempt's text is the connection failure, not an upstream answer.+ connection: boolean;};const RECORD_RETRIES = 3;@@ -97,6 +101,8 @@ export function FailureDetails({ message }: { message: WorkbenchMessage }) {status: entry.http_status ?? null,code: null,reason: t(`chat.failureDetails.reason.${entry.reason}`, { defaultValue: entry.reason }),+ detail: entry.upstream_detail ?? null,+ connection: entry.reason === 'network',}));const terminal = record.terminal_error;if (terminal) {@@ -107,6 +113,8 @@ export function FailureDetails({ message }: { message: WorkbenchMessage }) {status: terminal.http_status ?? null,code: terminal.upstream_error_code ?? null,reason: t(`settings.models.routing.errorReason.${terminal.reason}`),+ detail: terminal.upstream_detail ?? null,+ connection: false,});}return attempts;@@ -121,7 +129,9 @@ export function FailureDetails({ message }: { message: WorkbenchMessage }) {const outcome = record.outcome === 'failed_terminal' && record.terminal_error?.reason !== 'invalid_parameter'? 'failed_local': record.outcome;- const upstreamFacts = attempts.some((row) => row.status !== null || row.code !== null);+ const upstreamFacts = attempts.some(+ (row) => row.status !== null || row.code !== null || (row.detail !== null && !row.connection),+ );return (<div className="flex flex-col gap-2"><p className="text-gold-ink">@@ -137,6 +147,12 @@ export function FailureDetails({ message }: { message: WorkbenchMessage }) {{row.code && <span>{t('chat.failureDetails.errorCode')}: <span className="font-mono text-gold-ink">{row.code}</span></span>}<span>{t('chat.failureDetails.reasonLabel')}: <span className="text-gold-ink">{row.reason}</span></span></span>+ {row.detail && (+ <span className="text-gold-ink/70">+ {t(row.connection ? 'chat.failureDetails.connectionDetail' : 'chat.failureDetails.upstreamDetail')}:{' '}+ <span className="whitespace-pre-wrap break-words font-mono text-gold-ink">{row.detail}</span>+ </span>+ )}</li>))}</ol>diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex f296c9986..540236a98 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4741,7 +4741,9 @@"errorCode": "Error code","reasonLabel": "Reason","blockers": "Sources that were unavailable",- "upstreamNote": "These codes come from the upstream provider's API. Avibe keeps the status and error code but never stores the provider's raw response text, because it can echo credentials.",+ "upstreamNote": "These come from the upstream provider's API. Avibe keeps the status, error code, and the provider's error message with credentials removed, up to 400 characters.",+ "upstreamDetail": "Upstream said",+ "connectionDetail": "Connection error","copyRecord": "Copy record","reason": {"quota_exhausted": "Quota exhausted",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 50fb4ff31..35338441e 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4741,7 +4741,9 @@"errorCode": "错误码","reasonLabel": "原因","blockers": "当时不可用的供应商",- "upstreamNote": "以上状态码与错误码均由上游供应商的 API 返回。Avibe 会保留状态码和错误码,但不会保存供应商返回的原始报文,因为其中可能包含凭据。",+ "upstreamNote": "以上内容均由上游供应商的 API 返回。Avibe 会保留状态码、错误码,以及去除凭据后的上游报错信息(最多 400 字)。",+ "upstreamDetail": "上游返回",+ "connectionDetail": "连接错误","copyRecord": "复制记录","reason": {"quota_exhausted": "额度用尽",diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex a285ba1e5..0ddf43a9a 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -996,6 +996,8 @@"waiting_without_retry": "This request could not complete. Automatic recovery has ended. You can retry model {model} or choose another model.","interrupted": "Model {model} is unavailable: {blockers}. Open Models to resolve it.","route_unconfigured": "Model {model} has no configured route. Open Models to configure one.",+ "last_upstream_failure": "Last upstream error ({source}, HTTP {status}): {detail}",+ "last_connection_failure": "Last connection error ({source}): {detail}","model_unlisted": "Model {model} is not in the {backend} model list. Choose another model to continue.","request_incompatible": "This request is incompatible; switching Sources will not help.","request_incompatible_detail": "This request was rejected upstream and switching Sources will not help. Upstream said: {detail}"diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 54324f8f6..994a51f87 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -996,6 +996,8 @@"waiting_without_retry": "本次请求未完成,自动恢复已结束。你可以重试模型 {model} 或切换模型。","interrupted": "模型 {model} 当前不可用:{blockers}。请前往「模型」页处理。","route_unconfigured": "模型 {model} 尚未配置路由。请前往「模型」页配置。",+ "last_upstream_failure": "上游最后一次报错({source},HTTP {status}):{detail}",+ "last_connection_failure": "最后一次连接错误({source}):{detail}","model_unlisted": "模型 {model} 不在 {backend} 的模型列表中。请选择其他模型后继续。","request_incompatible": "此请求不兼容;切换模型供应商也无法解决。","request_incompatible_detail": "上游拒绝了此请求,切换模型供应商也无法解决。上游返回:{detail}"diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 5e162d1ea..77d8192ef 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -64,6 +64,9 @@ _ENGINE_TRANSPORT_FAILURE = re.compile(r"http2: (?:client connection lost|server sent GOAWAY)|server closed idle connection|"r"no such host|network is unreachable|proxyconnect")+# C0/C1 controls and every Unicode Bidi_Control character: either can act on+# whatever renders the text (a terminal, a log viewer, a browser).+_CONTROL_CHARACTERS = re.compile(r"[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]")# This threshold only selects memory or a temporary file; it never rejects or# truncates upstream response bytes._PRELUDE_MEMORY_BYTES = 256 * 1024@@ -1605,12 +1608,12 @@ def _reduce_protocol_observation(and _engine_transport_failure(observation.error_payload, observation.error_envelope_paths)):# The generic type is the engine's label for its own failure, so no- # machine code is carried that could outrank the network fact.+ # machine code is carried that could outrank the network fact. Its+ # status is the engine's too: no upstream answered.return _outcome(kind=RawOutcomeKind.NETWORK_ERROR,source=source,model_id=model_id,- http_status=http_status,message="engine could not reach the upstream",stream_started=stream_started,usage=observation.usage,@@ -1797,7 +1800,9 @@ def _upstream_error_detail(def _bounded_upstream_detail(message: str) -> str | None:- text = " ".join(message.split())+ # Control characters (terminal escapes, BEL) would act on whatever renders+ # the text, a log viewer included; they carry no message content.+ text = " ".join(_CONTROL_CHARACTERS.sub(" ", message).split())if not text:return Nonetext = plain_untrusted_text(redact_untrusted_text(text))