Skip to content

Commit bf76398

Browse files
committed
fix(chat): harden media replay and previews
Bound local preview memory, enforce guarded local image decoding, preserve media metadata across history and reset reconciliation, and keep runtime V2 credential upgrades without allowing downgrades. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 4f74b3dc-62de-4bf8-abee-aae3915b2f89
1 parent 6ea35c7 commit bf76398

14 files changed

Lines changed: 436 additions & 86 deletions

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2565,7 +2565,7 @@ private static bool IsSameCredentialHandoffRecord(
25652565
expected.BootstrapToken,
25662566
StringComparison.Ordinal) &&
25672567
current.IsLocal == expected.IsLocal &&
2568-
current.RequiresV2Signature == expected.RequiresV2Signature &&
2568+
(current.RequiresV2Signature || !expected.RequiresV2Signature) &&
25692569
string.Equals(
25702570
current.SetupManagedDistroName,
25712571
expected.SetupManagedDistroName,

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,3 +341,46 @@ internal sealed record ChatAssistantImageLoadState(
341341
BitmapImage? Bitmap,
342342
string SessionKey,
343343
ChatMediaContentInfo Reference);
344+
345+
internal static class ChatAttachmentBitmapDecoder
346+
{
347+
internal static BitmapImage? TryDecode(byte[] bytes)
348+
{
349+
try
350+
{
351+
using var stream = new InMemoryRandomAccessStream();
352+
using (var writer = new DataWriter(stream))
353+
{
354+
writer.WriteBytes(bytes);
355+
writer.StoreAsync().AsTask().GetAwaiter().GetResult();
356+
writer.DetachStream();
357+
}
358+
359+
stream.Seek(0);
360+
var decoder = BitmapDecoder.CreateAsync(stream).AsTask().GetAwaiter().GetResult();
361+
if (!ChatAssistantImageDecodePolicy.TryGetDecodeSize(
362+
decoder.PixelWidth,
363+
decoder.PixelHeight,
364+
out var decodeWidth,
365+
out var decodeHeight))
366+
{
367+
return null;
368+
}
369+
370+
stream.Seek(0);
371+
var bitmap = new BitmapImage
372+
{
373+
DecodePixelType = DecodePixelType.Physical,
374+
DecodePixelWidth = decodeWidth,
375+
DecodePixelHeight = decodeHeight,
376+
};
377+
bitmap.SetSource(stream);
378+
return bitmap;
379+
}
380+
catch (Exception ex)
381+
{
382+
Logger.Warn($"Attachment image decode failed ({ex.GetType().Name}).");
383+
return null;
384+
}
385+
}
386+
}

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

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using OpenClaw.Shared;
2+
13
namespace OpenClawTray.Chat;
24

35
public enum ChatAttachmentOrigin
@@ -24,6 +26,15 @@ public sealed record ChatAttachmentPresentation(
2426

2527
internal static class ChatAttachmentPreviewResolver
2628
{
29+
internal static bool TryGetBytes(
30+
ChatAttachmentPresentation attachment,
31+
out byte[] bytes)
32+
{
33+
bytes = Array.Empty<byte>();
34+
return attachment.CanAccessPreviewCache &&
35+
ChatImagePreviewCache.TryGet(attachment.PreviewCacheKey!, out bytes);
36+
}
37+
2738
internal static bool TryGetBytes(
2839
ChatAttachmentPresentation attachment,
2940
IReadOnlyDictionary<string, byte[]> previewCache,
@@ -34,3 +45,119 @@ internal static bool TryGetBytes(
3445
previewCache.TryGetValue(attachment.PreviewCacheKey!, out bytes!);
3546
}
3647
}
48+
49+
internal static class ChatImagePreviewCache
50+
{
51+
internal const int MaximumEntries = 32;
52+
internal const long MaximumTotalBytes = 64L * 1024 * 1024;
53+
internal const int MaximumPreviewBytes = (int)ChatAttachment.MaxSizeBytes;
54+
55+
private static readonly object s_gate = new();
56+
private static readonly Dictionary<string, byte[]> s_entries = new(StringComparer.Ordinal);
57+
private static readonly Queue<string> s_insertionOrder = new();
58+
private static long s_totalBytes;
59+
60+
internal static int Count
61+
{
62+
get
63+
{
64+
lock (s_gate)
65+
return s_entries.Count;
66+
}
67+
}
68+
69+
internal static long TotalBytes
70+
{
71+
get
72+
{
73+
lock (s_gate)
74+
return s_totalBytes;
75+
}
76+
}
77+
78+
internal static bool TryStoreBase64(string key, string encoded)
79+
{
80+
if (string.IsNullOrWhiteSpace(key) ||
81+
!TryDecodeBoundedBase64(encoded, MaximumPreviewBytes, out var bytes))
82+
{
83+
return false;
84+
}
85+
86+
lock (s_gate)
87+
{
88+
if (s_entries.TryGetValue(key, out var previous))
89+
{
90+
s_totalBytes -= previous.Length;
91+
}
92+
else
93+
{
94+
s_insertionOrder.Enqueue(key);
95+
}
96+
97+
s_entries[key] = bytes;
98+
s_totalBytes += bytes.Length;
99+
TrimLocked();
100+
return s_entries.ContainsKey(key);
101+
}
102+
}
103+
104+
internal static bool TryGet(string key, out byte[] bytes)
105+
{
106+
lock (s_gate)
107+
return s_entries.TryGetValue(key, out bytes!);
108+
}
109+
110+
internal static bool Contains(string key)
111+
{
112+
lock (s_gate)
113+
return s_entries.ContainsKey(key);
114+
}
115+
116+
internal static bool TryDecodeBoundedBase64(
117+
string? encoded,
118+
int maximumBytes,
119+
out byte[] bytes)
120+
{
121+
bytes = Array.Empty<byte>();
122+
if (string.IsNullOrEmpty(encoded) || maximumBytes <= 0)
123+
return false;
124+
125+
var maximumEncodedLength = ((maximumBytes + 2L) / 3L) * 4L;
126+
if (encoded.Length > maximumEncodedLength)
127+
return false;
128+
129+
try
130+
{
131+
bytes = Convert.FromBase64String(encoded);
132+
if (bytes.Length <= maximumBytes)
133+
return true;
134+
}
135+
catch (FormatException)
136+
{
137+
}
138+
139+
bytes = Array.Empty<byte>();
140+
return false;
141+
}
142+
143+
internal static void Clear()
144+
{
145+
lock (s_gate)
146+
{
147+
s_entries.Clear();
148+
s_insertionOrder.Clear();
149+
s_totalBytes = 0;
150+
}
151+
}
152+
153+
private static void TrimLocked()
154+
{
155+
while ((s_entries.Count > MaximumEntries ||
156+
s_totalBytes > MaximumTotalBytes) &&
157+
s_insertionOrder.TryDequeue(out var oldestKey))
158+
{
159+
if (s_entries.Remove(oldestKey, out var removed))
160+
s_totalBytes -= removed.Length;
161+
}
162+
}
163+
}

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

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1347,6 +1347,8 @@ internal ChatIncomingMessageGate GateIncomingChatMessage(
13471347
_queue.TryConsumeLocalEcho(
13481348
threadId,
13491349
resetGate.ConsumeEchoText,
1350+
attachmentCorrelationSignature,
1351+
hasMediaEnvelope,
13501352
out var queuedMessageId))
13511353
{
13521354
var confirmed = BuildLiveMetaLocked(
@@ -2064,48 +2066,46 @@ internal void CompleteRemoteBackfill(string threadId)
20642066
internal ChatRemoteUserBackfillTransition? ApplyRemoteUserBackfill(
20652067
string threadId,
20662068
ChatMessageInfo message,
2069+
GatewayMediaMessageProjectionResult projection,
2070+
IReadOnlyList<ChatAttachmentPresentation> attachments,
20672071
long expectedResetGeneration,
20682072
bool openResetGate,
20692073
ChatProjectionContext context)
20702074
{
2071-
var projection = GatewayMediaMessageProjection.Project(message.Text);
20722075
lock (_gate)
20732076
{
20742077
if (GetResetVersionLocked(threadId) != expectedResetGeneration ||
20752078
_reset.IsPreResetTimestamp(threadId, message.Ts))
20762079
{
20772080
return null;
20782081
}
2079-
if (_timelines.TryGetValue(threadId, out var timeline))
2080-
{
2081-
for (var i = timeline.Entries.Count - 1; i >= 0; i--)
2082-
{
2083-
if (timeline.Entries[i].Kind != ChatTimelineItemKind.User)
2084-
continue;
2085-
if (timeline.Entries[i].Text == projection.ReconciliationText)
2086-
return null;
2087-
break;
2088-
}
2089-
}
20902082
var openedLifecycle = openResetGate
20912083
? ApplyBufferedLifecycleOpenLocked(
20922084
threadId,
20932085
_reset.RecordRemoteUser(threadId),
20942086
allowRemoteTurn: true)
20952087
: null;
2096-
ApplyEventLocked(
2088+
var metadata = BuildLiveMetaLocked(
20972089
threadId,
2098-
new ChatUserMessageEvent(
2099-
ChatContentFormatting.TruncateForChatEntry(
2100-
projection.ReconciliationText)),
2101-
BuildLiveMetaLocked(
2102-
threadId,
2103-
message.Ts,
2104-
message.OpenClawId,
2105-
message.OpenClawSeq,
2106-
attachments: projection.Attachments));
2090+
message.Ts,
2091+
message.OpenClawId,
2092+
message.OpenClawSeq,
2093+
attachments: attachments);
2094+
var snapshot = ApplyProjectedRemoteUserMessageLocked(
2095+
threadId,
2096+
ChatContentFormatting.TruncateForChatEntry(
2097+
projection.HasMediaEnvelope
2098+
? projection.ReconciliationText
2099+
: ChatMetadataStore.EscapeUntrustedAttachmentMarkerLines(
2100+
message.Text)),
2101+
GatewayMediaMessageProjection.BuildAttachmentCorrelationSignature(
2102+
attachments),
2103+
metadata,
2104+
context);
2105+
if (snapshot is null && openedLifecycle is null)
2106+
return null;
21072107
return new(
2108-
BuildSnapshotLocked(context),
2108+
snapshot ?? BuildSnapshotLocked(context),
21092109
openedLifecycle,
21102110
CurrentRuntimeGenerationLocked(threadId));
21112111
}

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

Lines changed: 48 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,18 @@ ChatTimelineState Apply(
487487
if (!before.Contains(entry.Id) && !metadata.ContainsKey(entry.Id))
488488
metadata[entry.Id] = entryMetadata;
489489
}
490+
if (entryMetadata.AssistantContent is not null &&
491+
next.ActiveAssistantId is { } assistantId &&
492+
metadata.TryGetValue(assistantId, out var existingMetadata))
493+
{
494+
metadata[assistantId] = existingMetadata with
495+
{
496+
AssistantContent =
497+
ChatAssistantContentProjector.MergeLiveUpdate(
498+
existingMetadata.AssistantContent,
499+
entryMetadata.AssistantContent),
500+
};
501+
}
490502
}
491503
return next;
492504
}
@@ -504,6 +516,10 @@ ChatTimelineState Apply(
504516
}
505517

506518
var role = message.Role?.ToLowerInvariant() ?? string.Empty;
519+
var rawText = replayPart.Text;
520+
var userProjection = role == "user"
521+
? GatewayMediaMessageProjection.Project(rawText)
522+
: null;
507523
var entryMetadata = new ChatEntryMetadata(
508524
message.Ts > 0
509525
? DateTimeOffset.FromUnixTimeMilliseconds(message.Ts).ToLocalTime()
@@ -517,17 +533,37 @@ ChatTimelineState Apply(
517533
OpenClawSeq: message.OpenClawSeq,
518534
OpenClawKind: message.OpenClawKind,
519535
CompactionTokensBefore: message.CompactionTokensBefore,
520-
CompactionTokensAfter: message.CompactionTokensAfter);
536+
CompactionTokensAfter: message.CompactionTokensAfter,
537+
AssistantContent: role == "assistant"
538+
? ChatAssistantContentProjector.Project(
539+
replayPart.AssistantContentParts)
540+
: null);
521541
var text = ChatContentFormatting.TruncateForChatEntry(
522542
ChatMetadataStore.EscapeUntrustedAttachmentMarkerLines(
523-
replayPart.Text));
524-
if (role == "user")
525-
text = ChatMetadataStore.RehydrateAttachmentMarkers(
526-
attachmentMatcher,
527-
text,
543+
userProjection?.HasMediaEnvelope == true
544+
? userProjection.ReconciliationText
545+
: rawText));
546+
if (userProjection is not null)
547+
{
548+
var cachedAttachment = attachmentMatcher.TryMatch(
549+
userProjection.ReconciliationText,
550+
userProjection.AttachmentCorrelationSignature,
528551
message.Ts);
552+
var attachmentPresentations = cachedAttachment is not null
553+
? ChatMetadataStore.CreatePersistedLocalPresentations(
554+
cachedAttachment.Attachments)
555+
: userProjection.Attachments;
556+
entryMetadata = entryMetadata with
557+
{
558+
Attachments = attachmentPresentations,
559+
};
560+
}
529561
var hasStructuredToolContent =
530562
replayPart.ToolContent.Count > 0;
563+
var hasUserAttachments =
564+
entryMetadata.Attachments is { Count: > 0 };
565+
var hasAssistantMedia =
566+
entryMetadata.AssistantContent is { Media.Count: > 0 };
531567

532568
if (role == "user" &&
533569
_persistence.IsMessageAborted(
@@ -564,12 +600,16 @@ ChatTimelineState Apply(
564600
}
565601

566602
if (string.IsNullOrEmpty(text) &&
567-
!hasStructuredToolContent)
603+
!hasStructuredToolContent &&
604+
!hasUserAttachments &&
605+
!hasAssistantMedia)
568606
{
569607
continue;
570608
}
571609

572-
if (!string.IsNullOrEmpty(text))
610+
if (!string.IsNullOrEmpty(text) ||
611+
(role == "user" && hasUserAttachments) ||
612+
(role == "assistant" && hasAssistantMedia))
573613
{
574614
switch (role)
575615
{

0 commit comments

Comments
 (0)