Skip to content

Commit c0b7b36

Browse files
calebedenCopilot
andcommitted
fix(chat): preserve history tool correlation
Prefer semantic tool-result call references and consume aborted assistant state on the first replayed part, including tool-first messages. Co-authored-by: Copilot App <[email protected]>
1 parent 8956667 commit c0b7b36

5 files changed

Lines changed: 232 additions & 38 deletions

File tree

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -705,22 +705,34 @@ private static IReadOnlyList<ChatToolContentInfo> ExtractToolContent(
705705
if (kind is null)
706706
continue;
707707

708+
var itemSemanticCallId = ReadFirstString(
709+
item,
710+
"tool_call_id",
711+
"toolCallId",
712+
"tool_use_id",
713+
"toolUseId");
714+
var messageSemanticCallId = ReadFirstString(
715+
message,
716+
"tool_call_id",
717+
"toolCallId",
718+
"tool_use_id",
719+
"toolUseId");
720+
var callId = kind == ChatToolContentKind.Call
721+
? ReadFirstString(
722+
item,
723+
"id",
724+
"tool_call_id",
725+
"toolCallId",
726+
"tool_use_id",
727+
"toolUseId")
728+
?? messageSemanticCallId
729+
: itemSemanticCallId
730+
?? messageSemanticCallId
731+
?? ReadFirstString(item, "id");
708732
blocks.Add(new ChatToolContentInfo
709733
{
710734
Kind = kind.Value,
711-
CallId = ReadFirstString(
712-
item,
713-
"id",
714-
"tool_call_id",
715-
"toolCallId",
716-
"tool_use_id",
717-
"toolUseId")
718-
?? ReadFirstString(
719-
message,
720-
"tool_call_id",
721-
"toolCallId",
722-
"tool_use_id",
723-
"toolUseId"),
735+
CallId = callId,
724736
ToolName = ReadFirstString(item, "name")
725737
?? ReadFirstString(message, "toolName", "tool_name")
726738
?? "tool",

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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ internal sealed record ChatHistoryReplayPart(
66
ChatMessageInfo Message,
77
string Text,
88
IReadOnlyList<ChatToolContentInfo> ToolContent,
9-
bool IsFirstTextPart);
9+
bool IsFirstPart);
1010

1111
internal static class ChatHistoryReplayProjection
1212
{
@@ -21,11 +21,11 @@ public static IEnumerable<ChatHistoryReplayPart> Project(
2121
message,
2222
message.Text ?? string.Empty,
2323
message.ToolContent,
24-
IsFirstTextPart: true);
24+
IsFirstPart: true);
2525
continue;
2626
}
2727

28-
var isFirstTextPart = true;
28+
var isFirstPart = true;
2929
foreach (var part in message.ContentParts)
3030
{
3131
if (part.Kind == ChatMessageContentPartKind.Text)
@@ -34,16 +34,17 @@ public static IEnumerable<ChatHistoryReplayPart> Project(
3434
message,
3535
part.Text ?? string.Empty,
3636
Array.Empty<ChatToolContentInfo>(),
37-
isFirstTextPart);
38-
isFirstTextPart = false;
37+
isFirstPart);
38+
isFirstPart = false;
3939
}
4040
else if (part.Tool is { } tool)
4141
{
4242
yield return new ChatHistoryReplayPart(
4343
message,
4444
string.Empty,
4545
new[] { tool },
46-
IsFirstTextPart: false);
46+
isFirstPart);
47+
isFirstPart = false;
4748
}
4849
}
4950
}

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

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1167,10 +1167,18 @@ ChatTimelineState ApplyAndCaptureMeta(ChatTimelineState s, ChatEvent e, ChatEntr
11671167
var attachmentMatcher = CreateAttachmentMetaMatcher(history.SessionId, threadId);
11681168
var pendingUnkeyedToolCalls = new Queue<string>();
11691169
var syntheticToolCallSequence = 0;
1170+
ChatMessageInfo? suppressedAbortedAssistant = null;
11701171

11711172
foreach (var replayPart in ChatHistoryReplayProjection.Project(ordered))
11721173
{
11731174
var msg = replayPart.Message;
1175+
if (suppressedAbortedAssistant is not null)
1176+
{
1177+
if (ReferenceEquals(suppressedAbortedAssistant, msg))
1178+
continue;
1179+
suppressedAbortedAssistant = null;
1180+
}
1181+
11741182
var roleLower = msg.Role?.ToLowerInvariant() ?? "";
11751183
var rawText = replayPart.Text;
11761184
var ts = msg.Ts > 0
@@ -1195,9 +1203,7 @@ ChatTimelineState ApplyAndCaptureMeta(ChatTimelineState s, ChatEvent e, ChatEntr
11951203
var text = TruncateForChatEntry(EscapeUntrustedAttachmentMarkerLines(rawText));
11961204
if (roleLower == "user")
11971205
text = RehydrateAttachmentMarkers(attachmentMatcher, text, msg.Ts);
1198-
11991206
var hasStructuredToolContent = replayPart.ToolContent.Count > 0;
1200-
if (string.IsNullOrEmpty(text) && !hasStructuredToolContent) continue;
12011207

12021208
// Check if this user message was aborted (persisted __openclaw.id match)
12031209
if (roleLower == "user")
@@ -1214,18 +1220,30 @@ ChatTimelineState ApplyAndCaptureMeta(ChatTimelineState s, ChatEvent e, ChatEntr
12141220
!string.Equals(msg.StopReason, "toolUse", StringComparison.OrdinalIgnoreCase) &&
12151221
!string.Equals(msg.StopReason, "end_turn", StringComparison.OrdinalIgnoreCase);
12161222

1217-
bool shouldMarkAborted = replayPart.IsFirstTextPart
1218-
&& ((roleLower == "assistant" && nextAssistantIsAborted) || gatewayAborted);
1219-
if (roleLower == "assistant" && replayPart.IsFirstTextPart)
1223+
var isFirstAssistantPart = roleLower == "assistant" && replayPart.IsFirstPart;
1224+
var shouldSuppressAssistant = isFirstAssistantPart
1225+
&& (nextAssistantIsAborted || gatewayAborted);
1226+
if (isFirstAssistantPart)
12201227
nextAssistantIsAborted = false;
1221-
if (gatewayAborted && !replayPart.IsFirstTextPart && !string.IsNullOrEmpty(text))
1228+
if (shouldSuppressAssistant)
1229+
{
1230+
Logger.Debug("[ChatHistory] → routed: ABORTED (response was stopped)");
1231+
rebuilt = ApplyAndCaptureMeta(
1232+
rebuilt,
1233+
new ChatStatusEvent("Response was stopped", ChatTone.Warning),
1234+
msgMeta);
1235+
rebuilt = ChatTimelineReducer.Apply(rebuilt, new ChatTurnEndEvent());
1236+
suppressedAbortedAssistant = msg;
12221237
continue;
1238+
}
1239+
1240+
if (string.IsNullOrEmpty(text) && !hasStructuredToolContent) continue;
12231241

12241242
// Diagnostic: log shape (role + length + heuristic flags) only.
12251243
// Never log the message text — see HIGH 4 logging audit.
12261244
var isFlat = NativeToolProjector.LooksLikeFlattenedToolOutput(text);
12271245
var isSys = NativeToolProjector.LooksLikeSystemControlNote(text);
1228-
Logger.Debug($"[ChatHistory] role='{roleLower}' len={text.Length} flat={isFlat} sys={isSys} aborted={shouldMarkAborted}");
1246+
Logger.Debug($"[ChatHistory] role='{roleLower}' len={text.Length} flat={isFlat} sys={isSys}");
12291247

12301248
if (!string.IsNullOrEmpty(text))
12311249
{
@@ -1277,18 +1295,6 @@ ChatTimelineState ApplyAndCaptureMeta(ChatTimelineState s, ChatEvent e, ChatEntr
12771295
break;
12781296
}
12791297

1280-
// If this assistant response was aborted, show a placeholder
1281-
// instead of the actual (partial) content.
1282-
if (shouldMarkAborted)
1283-
{
1284-
Logger.Debug($"[ChatHistory] → routed: ABORTED (response was stopped)");
1285-
rebuilt = ApplyAndCaptureMeta(
1286-
rebuilt,
1287-
new ChatStatusEvent("Response was stopped", ChatTone.Warning),
1288-
msgMeta);
1289-
rebuilt = ChatTimelineReducer.Apply(rebuilt, new ChatTurnEndEvent());
1290-
break;
1291-
}
12921298
// ── Heuristic recovery for history-flattened tool calls ──
12931299
// The gateway strips ``stream:"item"`` / ``command_output``
12941300
// detail server-side when serving ``chat.history`` —

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

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1260,6 +1260,82 @@ public void ParseChatHistoryPayload_ToolBlocks_PreservesInputsAndOutputs()
12601260
Assert.Equal("/workspace", result.Text);
12611261
}
12621262

1263+
[Theory]
1264+
[InlineData("tool_call_id")]
1265+
[InlineData("tool_use_id")]
1266+
public void ParseChatHistoryPayload_ToolResult_PrefersSemanticCallReference(string referenceProperty)
1267+
{
1268+
var helper = new GatewayClientTestHelper();
1269+
1270+
var history = helper.ParseChatHistoryPayload($$"""
1271+
{
1272+
"messages": [
1273+
{
1274+
"role": "assistant",
1275+
"content": [
1276+
{
1277+
"type": "tool_use",
1278+
"id": "call-1",
1279+
"tool_call_id": "not-the-definition-id",
1280+
"name": "exec",
1281+
"input": { "command": "pwd" }
1282+
}
1283+
],
1284+
"timestamp": 1
1285+
},
1286+
{
1287+
"role": "toolResult",
1288+
"toolCallId": "message-level-id",
1289+
"content": [
1290+
{
1291+
"type": "tool_result",
1292+
"id": "result-block-id",
1293+
"{{referenceProperty}}": "call-1",
1294+
"name": "exec",
1295+
"content": "/workspace"
1296+
}
1297+
],
1298+
"timestamp": 2
1299+
}
1300+
]
1301+
}
1302+
""");
1303+
1304+
Assert.Equal("call-1", Assert.Single(history.Messages[0].ToolContent).CallId);
1305+
Assert.Equal("call-1", Assert.Single(history.Messages[1].ToolContent).CallId);
1306+
}
1307+
1308+
[Theory]
1309+
[InlineData("toolCallId")]
1310+
[InlineData("toolUseId")]
1311+
public void ParseChatHistoryPayload_ToolResult_PrefersMessageCallReferenceOverBlockId(
1312+
string referenceProperty)
1313+
{
1314+
var helper = new GatewayClientTestHelper();
1315+
1316+
var history = helper.ParseChatHistoryPayload($$"""
1317+
{
1318+
"messages": [
1319+
{
1320+
"role": "toolResult",
1321+
"{{referenceProperty}}": "call-1",
1322+
"content": [
1323+
{
1324+
"type": "tool_result",
1325+
"id": "result-block-id",
1326+
"name": "exec",
1327+
"content": "/workspace"
1328+
}
1329+
],
1330+
"timestamp": 2
1331+
}
1332+
]
1333+
}
1334+
""");
1335+
1336+
Assert.Equal("call-1", Assert.Single(history.Messages[0].ToolContent).CallId);
1337+
}
1338+
12631339
[Theory]
12641340
[InlineData("toolResult")]
12651341
[InlineData("tool_result")]

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

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5927,6 +5927,92 @@ public async Task LoadHistoryAsync_StringToolResult_CompletesOriginalCall(string
59275927
Assert.Equal("/workspace", entry.ToolOutput);
59285928
}
59295929

5930+
[Theory]
5931+
[InlineData(false)]
5932+
[InlineData(true)]
5933+
public async Task LoadHistoryAsync_AbortedUserBeforeToolFirstAssistant_SuppressesEntireAssistantMessage(
5934+
bool includeTrailingText)
5935+
{
5936+
var tool = new ChatToolContentInfo
5937+
{
5938+
Kind = ChatToolContentKind.Call,
5939+
CallId = "call-1",
5940+
ToolName = "exec",
5941+
Args = JsonSerializer.Deserialize<JsonElement>("""{"command":"pwd"}"""),
5942+
};
5943+
var contentParts = new List<ChatMessageContentPartInfo>
5944+
{
5945+
new()
5946+
{
5947+
Kind = ChatMessageContentPartKind.Tool,
5948+
Tool = tool,
5949+
},
5950+
};
5951+
if (includeTrailingText)
5952+
{
5953+
contentParts.Add(new ChatMessageContentPartInfo
5954+
{
5955+
Kind = ChatMessageContentPartKind.Text,
5956+
Text = "partial answer",
5957+
});
5958+
}
5959+
5960+
var (bridge, provider, snapshots, _) = CreateProvider(new[] { MainSession() });
5961+
MarkPersistedMessageAborted(provider, "main", "aborted-user");
5962+
bridge.HistoryBehavior = _ => Task.FromResult(new ChatHistoryInfo
5963+
{
5964+
SessionKey = "main",
5965+
Messages =
5966+
[
5967+
new ChatMessageInfo
5968+
{
5969+
Role = "user",
5970+
Text = "run it",
5971+
State = "final",
5972+
Ts = 1,
5973+
OpenClawId = "aborted-user",
5974+
},
5975+
new ChatMessageInfo
5976+
{
5977+
Role = "assistant",
5978+
Text = includeTrailingText ? "partial answer" : string.Empty,
5979+
State = "final",
5980+
Ts = 2,
5981+
ToolContent = [tool],
5982+
ContentParts = contentParts,
5983+
},
5984+
new ChatMessageInfo
5985+
{
5986+
Role = "assistant",
5987+
Text = "next response",
5988+
State = "final",
5989+
Ts = 3,
5990+
},
5991+
],
5992+
});
5993+
5994+
await provider.LoadHistoryAsync("main");
5995+
5996+
Assert.Collection(
5997+
snapshots[^1].Timelines["main"].Entries,
5998+
entry =>
5999+
{
6000+
Assert.Equal(ChatTimelineItemKind.User, entry.Kind);
6001+
Assert.Equal("run it", entry.Text);
6002+
},
6003+
entry =>
6004+
{
6005+
Assert.Equal(ChatTimelineItemKind.Status, entry.Kind);
6006+
Assert.Equal("Response was stopped", entry.Text);
6007+
Assert.Equal(ChatTone.Warning, entry.Tone);
6008+
},
6009+
entry =>
6010+
{
6011+
Assert.Equal(ChatTimelineItemKind.Assistant, entry.Kind);
6012+
Assert.Equal("next response", entry.Text);
6013+
});
6014+
}
6015+
59306016
[Fact]
59316017
public async Task LoadHistoryAsync_InterleavedContentParts_PreserveChronologyAndCorrelation()
59326018
{
@@ -10125,6 +10211,19 @@ private static ISet<string> GetQueuedDrainScheduledThreads(OpenClawChatDataProvi
1012510211
return Assert.IsAssignableFrom<ISet<string>>(field.GetValue(provider));
1012610212
}
1012710213

10214+
private static void MarkPersistedMessageAborted(
10215+
OpenClawChatDataProvider provider,
10216+
string threadId,
10217+
string messageId)
10218+
{
10219+
var field = typeof(OpenClawChatDataProvider).GetField(
10220+
"_persistedAbortedIds",
10221+
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
10222+
Assert.NotNull(field);
10223+
var abortedIds = Assert.IsType<Dictionary<string, HashSet<string>>>(field.GetValue(provider));
10224+
abortedIds[threadId] = [messageId];
10225+
}
10226+
1012810227
private static bool HasFailedQueuedMessage(ChatDataSnapshot snapshot, string threadId, string text) =>
1012910228
GetQueuedMessages(snapshot, threadId).Any(message =>
1013010229
message.Text == text &&

0 commit comments

Comments
 (0)