Skip to content

Commit 8ff0353

Browse files
TheAngryPitCassieMeikarkarl
authored
fix(chat): preserve persisted tool activity details (#1111)
* fix(chat): preserve persisted tool activity details * refactor(chat): centralize persisted argument projection * refactor(chat): simplify persisted tool projection * fix(chat): bound persisted argument decoding Co-authored-by: Copilot App <[email protected]> Copilot-Session: fbba7380-93e7-44a4-bd0b-d0ac1ebba543 --------- Co-authored-by: TheAngryPit <[email protected]> Co-authored-by: Karen Lai <[email protected]> Copilot-Session: fbba7380-93e7-44a4-bd0b-d0ac1ebba543
1 parent ccd64bb commit 8ff0353

8 files changed

Lines changed: 236 additions & 13 deletions

File tree

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -756,24 +756,21 @@ private static IReadOnlyList<ChatToolContentInfo> ExtractToolContent(
756756

757757
var itemSemanticCallId = ReadFirstString(
758758
item,
759+
"callId",
759760
"tool_call_id",
760761
"toolCallId",
761762
"tool_use_id",
762763
"toolUseId");
763764
var messageSemanticCallId = ReadFirstString(
764765
message,
766+
"callId",
765767
"tool_call_id",
766768
"toolCallId",
767769
"tool_use_id",
768770
"toolUseId");
769771
var callId = kind == ChatToolContentKind.Call
770-
? ReadFirstString(
771-
item,
772-
"id",
773-
"tool_call_id",
774-
"toolCallId",
775-
"tool_use_id",
776-
"toolUseId")
772+
? ReadFirstString(item, "id")
773+
?? itemSemanticCallId
777774
?? messageSemanticCallId
778775
: itemSemanticCallId
779776
?? messageSemanticCallId
@@ -791,7 +788,8 @@ private static IReadOnlyList<ChatToolContentInfo> ExtractToolContent(
791788
Text = kind == ChatToolContentKind.Result
792789
? ExtractToolContentText(item)
793790
: null,
794-
IsError = ReadBoolean(item, "isError", "is_error"),
791+
IsError = ReadNullableBoolean(item, "isError", "is_error")
792+
?? ReadBoolean(message, "isError", "is_error"),
795793
});
796794
}
797795
}
@@ -809,6 +807,7 @@ private static IReadOnlyList<ChatToolContentInfo> ExtractToolContent(
809807
Kind = ChatToolContentKind.Result,
810808
CallId = ReadFirstString(
811809
message,
810+
"callId",
812811
"tool_call_id",
813812
"toolCallId",
814813
"tool_use_id",
@@ -1141,6 +1140,9 @@ private static ChatMediaContentKind ClassifyMediaMimeType(
11411140
}
11421141

11431142
private static bool ReadBoolean(JsonElement value, params string[] propertyNames)
1143+
=> ReadNullableBoolean(value, propertyNames) ?? false;
1144+
1145+
private static bool? ReadNullableBoolean(JsonElement value, params string[] propertyNames)
11441146
{
11451147
foreach (var propertyName in propertyNames)
11461148
{
@@ -1151,7 +1153,7 @@ private static bool ReadBoolean(JsonElement value, params string[] propertyNames
11511153
}
11521154
}
11531155

1154-
return false;
1156+
return null;
11551157
}
11561158

11571159
private static string? ExtractToolContentText(JsonElement item)

‎src/OpenClaw.Tray.WinUI/Chat/ChatHistoryReplayProjection.cs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,7 @@ internal sealed record ChatHistoryReplayPart(
1414
internal static class ChatHistoryReplayProjection
1515
{
1616
internal static JsonObject? ProjectToolArgs(JsonElement? value) =>
17-
value is { ValueKind: JsonValueKind.Object } args
18-
? NativeToolProjector.ExtractSafeToolDisplayArgs(args)
19-
: null;
17+
NativeToolProjector.ExtractSafePersistedToolDisplayArgs(value);
2018

2119
internal static string ToolLabel(string toolName, JsonObject? args)
2220
{

‎src/OpenClaw.Tray.WinUI/Chat/ChatToolActivityPresentation.cs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,21 @@ public static IReadOnlyList<ChatToolActivityRow> Project(
6565
continue;
6666
}
6767

68+
if (entry.ToolResult == ChatToolCallStatus.Error)
69+
{
70+
if (showToolCalls)
71+
rows.Add(Standalone(entry, sessionId, timelineGeneration));
72+
index++;
73+
continue;
74+
}
75+
6876
var end = index + 1;
69-
while (end < entries.Count && entries[end].Kind == ChatTimelineItemKind.ToolCall)
77+
while (end < entries.Count
78+
&& entries[end].Kind == ChatTimelineItemKind.ToolCall
79+
&& entries[end].ToolResult != ChatToolCallStatus.Error)
80+
{
7081
end++;
82+
}
7183

7284
if (!showToolCalls)
7385
{

‎src/OpenClaw.Tray.WinUI/Chat/NativeToolProjector.cs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ internal static class NativeToolProjector
2121
["command", "path", "file_path", "query", "url", "pattern"];
2222

2323
internal const int MaxDisplayValueChars = 240;
24+
internal const int MaxPersistedToolArgumentsChars = 64 * 1024;
2425
private const int MaxIdentityChars = 80;
2526
private const int ToolOutputMaxChars = 4000;
2627

@@ -172,6 +173,34 @@ internal static string GetStringProperty(JsonElement data, params string[] names
172173
return displayArgs.Count == 0 ? null : displayArgs;
173174
}
174175

176+
internal static JsonObject? ExtractSafePersistedToolDisplayArgs(JsonElement? value)
177+
{
178+
if (value is { ValueKind: JsonValueKind.Object } data)
179+
return ExtractSafeToolDisplayArgs(data);
180+
181+
if (value is not { ValueKind: JsonValueKind.String } encoded)
182+
return null;
183+
184+
var json = encoded.GetString();
185+
if (string.IsNullOrWhiteSpace(json)
186+
|| json.Length > MaxPersistedToolArgumentsChars)
187+
{
188+
return null;
189+
}
190+
191+
try
192+
{
193+
using var document = JsonDocument.Parse(json);
194+
return document.RootElement.ValueKind == JsonValueKind.Object
195+
? ExtractSafeToolDisplayArgs(document.RootElement)
196+
: null;
197+
}
198+
catch (JsonException)
199+
{
200+
return null;
201+
}
202+
}
203+
175204
internal static string SanitizeToolDisplayValue(string? value)
176205
{
177206
if (string.IsNullOrWhiteSpace(value))

‎tests/OpenClaw.Shared.Tests/OpenClawGatewayClientTests.cs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1873,6 +1873,36 @@ public void ParseChatHistoryPayload_ToolResult_PrefersMessageCallReferenceOverBl
18731873
Assert.Equal("call-1", Assert.Single(history.Messages[0].ToolContent).CallId);
18741874
}
18751875

1876+
[Fact]
1877+
public void ParseChatHistoryPayload_ToolResult_UsesCallIdAndMessageErrorFallback()
1878+
{
1879+
var helper = new GatewayClientTestHelper();
1880+
1881+
var history = helper.ParseChatHistoryPayload("""
1882+
{
1883+
"messages": [
1884+
{
1885+
"role": "toolResult",
1886+
"isError": true,
1887+
"content": [
1888+
{
1889+
"type": "tool_result",
1890+
"callId": "call-1",
1891+
"name": "exec",
1892+
"content": "access denied"
1893+
}
1894+
],
1895+
"timestamp": 2
1896+
}
1897+
]
1898+
}
1899+
""");
1900+
1901+
var result = Assert.Single(Assert.Single(history.Messages).ToolContent);
1902+
Assert.Equal("call-1", result.CallId);
1903+
Assert.True(result.IsError);
1904+
}
1905+
18761906
[Theory]
18771907
[InlineData("toolResult")]
18781908
[InlineData("tool_result")]

‎tests/OpenClaw.Tray.Tests/ChatToolActivityPresentationTests.cs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,28 @@ public void Project_KeepsRowKeyStableWhenStandaloneToolBecomesGroup()
8787
Assert.Equal(standalone.Key, grouped.Key);
8888
}
8989

90+
[Fact]
91+
public void Project_KeepsFailedToolsVisibleOutsideActivityGroups()
92+
{
93+
var rows = ChatToolActivityPresentation.Project(
94+
[
95+
Tool("success-1", "read_file"),
96+
Tool("success-2", "write_file"),
97+
Tool("failed", "powershell", result: ChatToolCallStatus.Error),
98+
Tool("success-3", "web_fetch"),
99+
Tool("success-4", "grep"),
100+
],
101+
"session",
102+
9);
103+
104+
Assert.Equal(3, rows.Count);
105+
Assert.True(rows[0].IsActivityGroup);
106+
Assert.False(rows[1].IsActivityGroup);
107+
Assert.Equal("failed", rows[1].Entry?.Id);
108+
Assert.Equal(ChatToolCallStatus.Error, rows[1].Entry?.ToolResult);
109+
Assert.True(rows[2].IsActivityGroup);
110+
}
111+
90112
[Theory]
91113
[InlineData("powershell", ChatToolActivityCategory.Command)]
92114
[InlineData("system.run", ChatToolActivityCategory.Command)]

‎tests/OpenClaw.Tray.Tests/NativeToolProjectorTests.cs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,45 @@ public void ExtractSafeToolDisplayArgs_AllowlistsRedactsAndBoundsValues()
6868
Assert.DoesNotContain("json-must-not-render", args.ToJsonString(), StringComparison.Ordinal);
6969
}
7070

71+
[Fact]
72+
public void ExtractSafePersistedToolDisplayArgs_DecodesAllowlistedRedactedInput()
73+
{
74+
var value = JsonSerializer.SerializeToElement(
75+
"""{"command":"curl https://example.test --token abcdef1234567890ghij","workdir":"C:\\private","content":"must-not-render"}""");
76+
77+
var args = NativeToolProjector.ExtractSafePersistedToolDisplayArgs(value)!;
78+
79+
Assert.DoesNotContain(
80+
"abcdef1234567890ghij",
81+
args["command"]!.GetValue<string>(),
82+
StringComparison.Ordinal);
83+
Assert.False(args.ContainsKey("workdir"));
84+
Assert.False(args.ContainsKey("content"));
85+
Assert.DoesNotContain("must-not-render", args.ToJsonString(), StringComparison.Ordinal);
86+
}
87+
88+
[Theory]
89+
[InlineData("")]
90+
[InlineData("not-json")]
91+
[InlineData("[]")]
92+
[InlineData("null")]
93+
public void ExtractSafePersistedToolDisplayArgs_RejectsMalformedOrNonObjectInput(
94+
string encoded)
95+
{
96+
var value = JsonSerializer.SerializeToElement(encoded);
97+
98+
Assert.Null(NativeToolProjector.ExtractSafePersistedToolDisplayArgs(value));
99+
}
100+
101+
[Fact]
102+
public void ExtractSafePersistedToolDisplayArgs_RejectsOversizedInputBeforeParsing()
103+
{
104+
var value = JsonSerializer.SerializeToElement(
105+
new string('x', NativeToolProjector.MaxPersistedToolArgumentsChars + 1));
106+
107+
Assert.Null(NativeToolProjector.ExtractSafePersistedToolDisplayArgs(value));
108+
}
109+
71110
[Fact]
72111
public void ExtractToolCorrelationId_ExplicitToolCallIdIsOpaqueAndWins()
73112
{

‎tests/OpenClaw.Tray.Tests/OpenClawChatDataProviderTests.cs‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7326,6 +7326,97 @@ public async Task LoadHistoryAsync_StructuredToolBlocks_CorrelatesInputAndOutput
73267326
Assert.Equal("/workspace", entry.ToolOutput);
73277327
}
73287328

7329+
[Fact]
7330+
public async Task LoadHistoryAsync_StringEncodedToolArguments_PreservesSafeInput()
7331+
{
7332+
var (bridge, provider, snapshots, _) = CreateProvider(new[] { MainSession() });
7333+
bridge.HistoryBehavior = _ => Task.FromResult(new ChatHistoryInfo
7334+
{
7335+
SessionKey = "main",
7336+
Messages =
7337+
[
7338+
new ChatMessageInfo
7339+
{
7340+
Role = "assistant",
7341+
State = "final",
7342+
Ts = 1,
7343+
ToolContent =
7344+
[
7345+
new ChatToolContentInfo
7346+
{
7347+
Kind = ChatToolContentKind.Call,
7348+
CallId = "call-1",
7349+
ToolName = "exec",
7350+
Args = JsonSerializer.SerializeToElement(
7351+
"""{"command":"pwd","workdir":"/workspace"}"""),
7352+
},
7353+
],
7354+
},
7355+
],
7356+
});
7357+
7358+
await provider.LoadHistoryAsync("main");
7359+
7360+
var entry = Assert.Single(snapshots[^1].Timelines["main"].Entries);
7361+
Assert.Equal("pwd", entry.ToolArgs?["command"]?.GetValue<string>());
7362+
Assert.False(entry.ToolArgs?.ContainsKey("workdir"));
7363+
}
7364+
7365+
[Fact]
7366+
public async Task LoadHistoryAsync_AfterRestart_ReplaysSanitizedArgumentsWithoutLocalPersistence()
7367+
{
7368+
using var tempDir = new TempDirectory();
7369+
var cachePath = Path.Combine(tempDir.DirectoryPath, "tool-metadata.json");
7370+
static ChatHistoryInfo History() => new()
7371+
{
7372+
SessionKey = "main",
7373+
Messages =
7374+
[
7375+
new ChatMessageInfo
7376+
{
7377+
Role = "assistant",
7378+
State = "final",
7379+
Ts = 1,
7380+
ToolContent =
7381+
[
7382+
new ChatToolContentInfo
7383+
{
7384+
Kind = ChatToolContentKind.Call,
7385+
CallId = "call-1",
7386+
ToolName = "exec",
7387+
Args = JsonSerializer.SerializeToElement(
7388+
"""{"command":"curl https://example.test --token abcdef1234567890ghij","workdir":"C:\\private"}"""),
7389+
},
7390+
],
7391+
},
7392+
],
7393+
};
7394+
7395+
var first = CreateProvider(
7396+
new[] { MainSession() },
7397+
toolMetaCachePath: cachePath);
7398+
first.bridge.HistoryBehavior = _ => Task.FromResult(History());
7399+
await first.provider.LoadHistoryAsync("main");
7400+
await first.provider.DisposeAsync();
7401+
7402+
var second = CreateProvider(
7403+
new[] { MainSession() },
7404+
toolMetaCachePath: cachePath);
7405+
second.bridge.HistoryBehavior = _ => Task.FromResult(History());
7406+
await second.provider.LoadHistoryAsync("main");
7407+
7408+
var entry = Assert.Single(second.snapshots[^1].Timelines["main"].Entries);
7409+
var command = entry.ToolArgs?["command"]?.GetValue<string>();
7410+
Assert.NotNull(command);
7411+
Assert.DoesNotContain(
7412+
"abcdef1234567890ghij",
7413+
command,
7414+
StringComparison.Ordinal);
7415+
Assert.False(entry.ToolArgs?.ContainsKey("workdir"));
7416+
Assert.False(File.Exists(cachePath));
7417+
await second.provider.DisposeAsync();
7418+
}
7419+
73297420
[Theory]
73307421
[InlineData("toolResult")]
73317422
[InlineData("tool_result")]

0 commit comments

Comments
 (0)