From b3b790a3ca3a1c0a0e40a00fbd860befd6171b3e Mon Sep 17 00:00:00 2001 From: Alberto Delgado <44581951+turutupa@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:17:43 -0800 Subject: [PATCH 1/3] fix: show gateway failure reasons in chat errors --- .../Chat/ChatEventMapper.cs | 22 +++++--- .../ChatRuntimeOwnersTests.cs | 52 +++++++++++++++++++ .../OpenClawChatDataProviderTests.cs | 2 +- 3 files changed, 69 insertions(+), 7 deletions(-) diff --git a/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs b/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs index 173fd243de..250bec1225 100644 --- a/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs +++ b/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs @@ -302,11 +302,7 @@ internal static IEnumerable MapContentTool(ChatToolContentInfo tool, "approval-resolved" => new ChatProgressEvent("Working"), "fallback" or "fallback_cleared" => MapFallback(evt, getString), "end" => new ChatTurnEndEvent(), - "error" => new ChatErrorEvent( - evt.Summary ?? - (evt.Data.TryGetProperty("message", out var message) - ? message.GetString() ?? "Agent error" - : "Agent error")), + "error" => new ChatErrorEvent(ResolveErrorText(evt)), _ => null, }; } @@ -689,7 +685,7 @@ private static string Localized(string key, string fallback, Func new ChatTurnEndEvent(), - "error" => new ChatErrorEvent(evt.Summary ?? "Agent error"), + "error" => new ChatErrorEvent(ResolveErrorText(evt)), _ => null, }; } @@ -749,4 +745,18 @@ private static string StringProperty(JsonElement data, string name) => property.ValueKind == JsonValueKind.String ? property.GetString() ?? string.Empty : string.Empty; + + private static string ResolveErrorText(AgentEventInfo evt) + { + if (!string.IsNullOrWhiteSpace(evt.Summary)) + return evt.Summary; + + // Gateway lifecycle failures carry their explanation in data.error. + var error = StringProperty(evt.Data, "error"); + if (!string.IsNullOrWhiteSpace(error)) + return TokenSanitizer.SanitizeLogMessage(error); + + var message = StringProperty(evt.Data, "message"); + return string.IsNullOrWhiteSpace(message) ? "Agent error" : message; + } } diff --git a/tests/OpenClaw.Tray.Tests/ChatRuntimeOwnersTests.cs b/tests/OpenClaw.Tray.Tests/ChatRuntimeOwnersTests.cs index 182a839a40..061b0fed7c 100644 --- a/tests/OpenClaw.Tray.Tests/ChatRuntimeOwnersTests.cs +++ b/tests/OpenClaw.Tray.Tests/ChatRuntimeOwnersTests.cs @@ -1138,6 +1138,58 @@ public void ClassifyDraftAdmission_DistinguishesTerminalOutcomeFromAcceptance( public sealed class ChatEventMapperTests { + [Theory] + [InlineData("lifecycle", "phase")] + [InlineData("job", "state")] + public void Map_ErrorShowsGatewayExplanationInsteadOfGenericFallback(string stream, string stateField) + { + const string explanation = "Secret owner provider:nvidia-inference is configured but unavailable (secret reference was not found)."; + using var document = JsonDocument.Parse(JsonSerializer.Serialize( + new Dictionary { [stateField] = "error", ["error"] = explanation })); + + var mapped = ChatEventMapper.Map(new AgentEventInfo + { + Stream = stream, + SessionKey = "main", + Data = document.RootElement.Clone(), + }); + + Assert.Equal(explanation, Assert.IsType(mapped.Event).Text); + } + + [Fact] + public void Map_LifecycleErrorKeepsGenericFallbackForNonStringExplanation() + { + using var document = JsonDocument.Parse("""{"phase":"error","error":{"message":"untrusted"}}"""); + + var mapped = ChatEventMapper.Map(new AgentEventInfo + { + Stream = "lifecycle", + SessionKey = "main", + Data = document.RootElement.Clone(), + }); + + Assert.Equal("Agent error", Assert.IsType(mapped.Event).Text); + } + + [Fact] + public void Map_LifecycleErrorRedactsCredentialInGatewayExplanation() + { + using var document = JsonDocument.Parse("""{"phase":"error","error":"api_key=shortsecret at https://gateway.example/path?token=querysecret"}"""); + + var mapped = ChatEventMapper.Map(new AgentEventInfo + { + Stream = "lifecycle", + SessionKey = "main", + Data = document.RootElement.Clone(), + }); + + var text = Assert.IsType(mapped.Event).Text; + Assert.DoesNotContain("shortsecret", text); + Assert.DoesNotContain("querysecret", text); + Assert.Contains("[REDACTED]", text); + } + [Fact] public void Map_ApprovalRequestPreservesIdentityAndActions() { diff --git a/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs b/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs index 16db0ccdd0..c3e872095f 100644 --- a/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs +++ b/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs @@ -10964,7 +10964,7 @@ public async Task AgentEvent_LifecycleError_AppendsErrorStatusEntry() snapshots.Clear(); bridge.RaiseAgent(MakeAgentEvent("lifecycle", """{"phase":"start"}""", runId: "run-1")); - var evt = MakeAgentEvent("lifecycle", """{"phase":"error","message":"model unreachable"}""", runId: "run-1"); + var evt = MakeAgentEvent("lifecycle", """{"phase":"error","error":"model unreachable"}""", runId: "run-1"); bridge.RaiseAgent(evt); var timeline = snapshots[^1].Timelines["main"]; From 2217c4a237ff8ce282a2f5862e1f2810b642585d Mon Sep 17 00:00:00 2001 From: Alberto Delgado <44581951+turutupa@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:26:37 -0800 Subject: [PATCH 2/3] fix(chat): show a failed run's gateway reason once A failed run reports its reason twice: on the lifecycle (or job) error event and again on the terminal chat frame. With the lifecycle reason now shown, skip the chat frame's status when it repeats the same reason for the same run. A different terminal error is still shown. Co-Authored-By: Claude Fable 5.2 --- .../Chat/ChatConversationState.cs | 21 +++++++- .../Chat/ChatEventMapper.cs | 6 ++- .../OpenClawChatDataProviderTests.cs | 49 +++++++++++++++++++ 3 files changed, 74 insertions(+), 2 deletions(-) diff --git a/src/OpenClaw.Tray.WinUI/Chat/ChatConversationState.cs b/src/OpenClaw.Tray.WinUI/Chat/ChatConversationState.cs index 9a6ee87f75..7cd1a75752 100644 --- a/src/OpenClaw.Tray.WinUI/Chat/ChatConversationState.cs +++ b/src/OpenClaw.Tray.WinUI/Chat/ChatConversationState.cs @@ -2678,7 +2678,8 @@ message.ResponseTokens is not null || !_timelines[threadId].Entries.Any(entry => entry.Kind == ChatTimelineItemKind.Status && GetOrCreateThreadMetaLocked(threadId).GetValueOrDefault(entry.Id)? - .Presentation?.RunFailure?.RunId == message.RunId)) + .Presentation?.RunFailure?.RunId == message.RunId) && + !HasRunErrorStatusLocked(threadId, message.RunId, message.ErrorMessage)) ApplyEventLocked(threadId, new ChatErrorEvent( NativeToolProjector.SanitizeToolDisplayValue(message.ErrorMessage) ?? ""), BuildLiveMetaLocked(threadId, message.Ts) with { LiveRunId = message.RunId }); @@ -2689,6 +2690,24 @@ message.ResponseTokens is not null || } } + /// + /// True when this run's lifecycle or job failure already put the same Gateway explanation on the timeline, + /// so the terminal chat frame that repeats it must not add a second status. + /// + private bool HasRunErrorStatusLocked(string threadId, string? runId, string errorMessage) + { + if (string.IsNullOrEmpty(runId)) + return false; + var shown = ChatContentFormatting.TruncateForChatEntry( + ChatEventMapper.SanitizeGatewayErrorText(errorMessage)); + var metadata = GetOrCreateThreadMetaLocked(threadId); + return _timelines[threadId].Entries.Any(entry => + entry.Kind == ChatTimelineItemKind.Status && + entry.Tone == ChatTone.Error && + string.Equals(entry.Text, shown, StringComparison.Ordinal) && + metadata.GetValueOrDefault(entry.Id)?.LiveRunId == runId); + } + private void ApplyAssistantContentLocked( ChatMessageInfo message, string assistantText, diff --git a/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs b/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs index 250bec1225..c600275f90 100644 --- a/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs +++ b/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs @@ -746,6 +746,10 @@ private static string StringProperty(JsonElement data, string name) => ? property.GetString() ?? string.Empty : string.Empty; + /// Display form of a Gateway-supplied failure explanation, with credentials redacted. + internal static string SanitizeGatewayErrorText(string error) => + TokenSanitizer.SanitizeLogMessage(error); + private static string ResolveErrorText(AgentEventInfo evt) { if (!string.IsNullOrWhiteSpace(evt.Summary)) @@ -754,7 +758,7 @@ private static string ResolveErrorText(AgentEventInfo evt) // Gateway lifecycle failures carry their explanation in data.error. var error = StringProperty(evt.Data, "error"); if (!string.IsNullOrWhiteSpace(error)) - return TokenSanitizer.SanitizeLogMessage(error); + return SanitizeGatewayErrorText(error); var message = StringProperty(evt.Data, "message"); return string.IsNullOrWhiteSpace(message) ? "Agent error" : message; diff --git a/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs b/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs index c3e872095f..d3c6ed471b 100644 --- a/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs +++ b/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs @@ -2069,6 +2069,55 @@ public async Task RunFailureNotice_ReplacesOnlyItsTerminalErrorInEitherArrivalOr Assert.Equal("failed-run", provider.GetEntryMetadata("main")[row.Id].Presentation?.RunFailure?.RunId); } + [Theory] + [InlineData("lifecycle", "phase")] + [InlineData("job", "state")] + public async Task GatewayFailureReason_AppearsOnceWhenTerminalChatFrameRepeatsIt(string stream, string stateField) + { + const string reason = "Couldn't connect to the AI service. Check your connection, then try again."; + var (bridge, provider, snapshots, _) = CreateProvider([MainSession()]); + await using var lifetime = provider; + await provider.LoadAsync(); + bridge.RaiseStatus(ConnectionStatus.Connected); + bridge.RaiseAgent(MakeAgentEvent("lifecycle", """{"phase":"start"}""", runId: "failed-run")); + + bridge.RaiseAgent(MakeAgentEvent( + stream, + JsonSerializer.Serialize(new Dictionary { [stateField] = "error", ["error"] = reason }), + runId: "failed-run")); + bridge.RaiseChat(new ChatMessageInfo + { + SessionKey = "main", Role = "assistant", RunId = "failed-run", + State = "error", ErrorMessage = reason, + }); + + var timeline = snapshots[^1].Timelines["main"]; + Assert.False(timeline.TurnActive); + Assert.Single(timeline.Entries, entry => entry.Kind == ChatTimelineItemKind.Status && entry.Text == reason); + Assert.DoesNotContain(timeline.Entries, entry => entry.Text == "Agent error"); + } + + [Fact] + public async Task GatewayFailureReason_KeepsADifferentTerminalChatError() + { + var (bridge, provider, snapshots, _) = CreateProvider([MainSession()]); + await using var lifetime = provider; + await provider.LoadAsync(); + bridge.RaiseStatus(ConnectionStatus.Connected); + bridge.RaiseAgent(MakeAgentEvent("lifecycle", """{"phase":"start"}""", runId: "failed-run")); + + bridge.RaiseAgent(MakeAgentEvent("lifecycle", """{"phase":"error","error":"model unreachable"}""", runId: "failed-run")); + bridge.RaiseChat(new ChatMessageInfo + { + SessionKey = "main", Role = "assistant", RunId = "failed-run", + State = "error", ErrorMessage = "provider returned 503", + }); + + var entries = snapshots[^1].Timelines["main"].Entries; + Assert.Single(entries, entry => entry.Text == "model unreachable"); + Assert.Single(entries, entry => entry.Text == "provider returned 503"); + } + [Fact] public async Task RunFailureNotice_DoesNotRemoveAnotherRunsError() { From 273a9f475410f860e51d543815081d8bd62a035f Mon Sep 17 00:00:00 2001 From: Alberto Delgado <44581951+turutupa@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:42:32 -0800 Subject: [PATCH 3/3] fix(chat): redact gateway failure text like the terminal chat error Lifecycle and job failure explanations now get the same display redaction and length cap as the terminal chat frame's error text, on top of the log redaction, so bare provider keys and hosts are hidden in either path. Adds tests for a bare key, a redacted URL in both arrival orders. Co-Authored-By: Claude Fable 5.2 --- .../Chat/ChatEventMapper.cs | 8 +++-- .../ChatRuntimeOwnersTests.cs | 22 +++++++++++- .../OpenClawChatDataProviderTests.cs | 35 +++++++++++++++++++ 3 files changed, 62 insertions(+), 3 deletions(-) diff --git a/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs b/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs index c600275f90..25b12a87fa 100644 --- a/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs +++ b/src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs @@ -746,9 +746,13 @@ private static string StringProperty(JsonElement data, string name) => ? property.GetString() ?? string.Empty : string.Empty; - /// Display form of a Gateway-supplied failure explanation, with credentials redacted. + /// + /// Display form of a Gateway-supplied failure explanation: log redaction (URL query secrets, key=value + /// credentials, local identity) followed by the display redaction and length cap that the terminal chat + /// frame's error text already gets (bare provider keys, bearer tokens). + /// internal static string SanitizeGatewayErrorText(string error) => - TokenSanitizer.SanitizeLogMessage(error); + NativeToolProjector.SanitizeToolDisplayValue(TokenSanitizer.SanitizeLogMessage(error)); private static string ResolveErrorText(AgentEventInfo evt) { diff --git a/tests/OpenClaw.Tray.Tests/ChatRuntimeOwnersTests.cs b/tests/OpenClaw.Tray.Tests/ChatRuntimeOwnersTests.cs index 061b0fed7c..e17cfdc3b0 100644 --- a/tests/OpenClaw.Tray.Tests/ChatRuntimeOwnersTests.cs +++ b/tests/OpenClaw.Tray.Tests/ChatRuntimeOwnersTests.cs @@ -1187,7 +1187,27 @@ public void Map_LifecycleErrorRedactsCredentialInGatewayExplanation() var text = Assert.IsType(mapped.Event).Text; Assert.DoesNotContain("shortsecret", text); Assert.DoesNotContain("querysecret", text); - Assert.Contains("[REDACTED]", text); + Assert.StartsWith("api_key=", text); + Assert.NotEqual("Agent error", text); + } + + [Fact] + public void Map_LifecycleErrorRedactsBareProviderKeyInGatewayExplanation() + { + const string key = "sk-proj-abcdefghijklmnopqrstuvwxyz0123456789ABCD"; + using var document = JsonDocument.Parse(JsonSerializer.Serialize( + new Dictionary { ["phase"] = "error", ["error"] = "Incorrect API key provided: " + key })); + + var mapped = ChatEventMapper.Map(new AgentEventInfo + { + Stream = "lifecycle", + SessionKey = "main", + Data = document.RootElement.Clone(), + }); + + var text = Assert.IsType(mapped.Event).Text; + Assert.DoesNotContain(key, text); + Assert.StartsWith("Incorrect API key provided:", text); } [Fact] diff --git a/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs b/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs index d3c6ed471b..ec89e5cc22 100644 --- a/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs +++ b/tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs @@ -2097,6 +2097,41 @@ public async Task GatewayFailureReason_AppearsOnceWhenTerminalChatFrameRepeatsIt Assert.DoesNotContain(timeline.Entries, entry => entry.Text == "Agent error"); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task GatewayFailureReason_WithRedactedUrlAppearsOnceInEitherArrivalOrder(bool chatFrameFirst) + { + const string reason = "Request to https://provider.example/v1/chat?api_key=querysecretvalue failed"; + var (bridge, provider, snapshots, _) = CreateProvider([MainSession()]); + await using var lifetime = provider; + await provider.LoadAsync(); + bridge.RaiseStatus(ConnectionStatus.Connected); + bridge.RaiseAgent(MakeAgentEvent("lifecycle", """{"phase":"start"}""", runId: "failed-run")); + var lifecycle = MakeAgentEvent( + "lifecycle", + JsonSerializer.Serialize(new Dictionary { ["phase"] = "error", ["error"] = reason }), + runId: "failed-run"); + var terminal = new ChatMessageInfo + { + SessionKey = "main", Role = "assistant", RunId = "failed-run", + State = "error", ErrorMessage = reason, + }; + + if (chatFrameFirst) + bridge.RaiseChat(terminal); + bridge.RaiseAgent(lifecycle); + if (!chatFrameFirst) + bridge.RaiseChat(terminal); + + var timeline = snapshots[^1].Timelines["main"]; + Assert.False(timeline.TurnActive); + var row = Assert.Single(timeline.Entries, entry => + entry.Kind == ChatTimelineItemKind.Status && entry.Tone == ChatTone.Error); + Assert.StartsWith("Request to https://", row.Text); + Assert.DoesNotContain("querysecretvalue", row.Text); + } + [Fact] public async Task GatewayFailureReason_KeepsADifferentTerminalChatError() {