Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/OpenClaw.Tray.WinUI/Chat/ChatConversationState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand All @@ -2689,6 +2690,24 @@ message.ResponseTokens is not null ||
}
}

/// <summary>
/// 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.
/// </summary>
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,
Expand Down
30 changes: 24 additions & 6 deletions src/OpenClaw.Tray.WinUI/Chat/ChatEventMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -302,11 +302,7 @@ internal static IEnumerable<ChatEvent> 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,
};
}
Expand Down Expand Up @@ -689,7 +685,7 @@ private static string Localized(string key, string fallback, Func<string, string
return StringProperty(evt.Data, "state").ToLowerInvariant() switch
{
"done" => new ChatTurnEndEvent(),
"error" => new ChatErrorEvent(evt.Summary ?? "Agent error"),
"error" => new ChatErrorEvent(ResolveErrorText(evt)),
_ => null,
};
}
Expand Down Expand Up @@ -749,4 +745,26 @@ private static string StringProperty(JsonElement data, string name) =>
property.ValueKind == JsonValueKind.String
? property.GetString() ?? string.Empty
: string.Empty;

/// <summary>
/// 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).
/// </summary>
internal static string SanitizeGatewayErrorText(string error) =>
NativeToolProjector.SanitizeToolDisplayValue(TokenSanitizer.SanitizeLogMessage(error));

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 SanitizeGatewayErrorText(error);

var message = StringProperty(evt.Data, "message");
return string.IsNullOrWhiteSpace(message) ? "Agent error" : message;
}
}
72 changes: 72 additions & 0 deletions tests/OpenClaw.Tray.Tests/ChatRuntimeOwnersTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1138,6 +1138,78 @@ 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<string, string> { [stateField] = "error", ["error"] = explanation }));

var mapped = ChatEventMapper.Map(new AgentEventInfo
{
Stream = stream,
SessionKey = "main",
Data = document.RootElement.Clone(),
});

Assert.Equal(explanation, Assert.IsType<ChatErrorEvent>(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<ChatErrorEvent>(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<ChatErrorEvent>(mapped.Event).Text;
Assert.DoesNotContain("shortsecret", text);
Assert.DoesNotContain("querysecret", 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<string, string> { ["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<ChatErrorEvent>(mapped.Event).Text;
Assert.DoesNotContain(key, text);
Assert.StartsWith("Incorrect API key provided:", text);
}

[Fact]
public void Map_ApprovalRequestPreservesIdentityAndActions()
{
Expand Down
86 changes: 85 additions & 1 deletion tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2069,6 +2069,90 @@ 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<string, string> { [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");
}

[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<string, string> { ["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()
{
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()
{
Expand Down Expand Up @@ -10964,7 +11048,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"];
Expand Down