Skip to content

Commit f8a8825

Browse files
karkarlCopilot
andauthored
refactor(chat): extract runtime state owners (#1096)
* refactor(chat): extract runtime state owners Co-authored-by: Copilot App <[email protected]> * fix(chat): harden history retry and disposal races Co-authored-by: Copilot App <[email protected]> * fix(chat): preserve post-reset terminal lifecycle Use exact submitted echoes to open buffered post-reset lifecycles after queue reconciliation, and fence deferred abort work to the active runtime generation. Co-authored-by: Copilot App <[email protected]> * fix(chat): correlate post-reset lifecycle events Track generation-scoped local submissions before send completion, select the correct buffered lifecycle on exact echo, and accept only same-run skewed terminal frames above the correlated floor. Co-authored-by: Copilot App <[email protected]> * fix(chat): isolate user frames across reset Keep run-scoped clock-skew floors limited to run-identifiable non-user frames so delayed pre-reset user messages cannot reappear after an exact echo opens the gate. Co-authored-by: Copilot App <[email protected]> --------- Co-authored-by: Copilot App <[email protected]>
1 parent d67ef51 commit f8a8825

26 files changed

Lines changed: 12525 additions & 6585 deletions

‎docs/ARCHITECTURE.md‎

Lines changed: 31 additions & 4 deletions
Large diffs are not rendered by default.
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
namespace OpenClawTray.Chat;
2+
3+
/// <summary>
4+
/// Owns bounded approval-request identity deduplication and alternate-ID
5+
/// correlation. The conversation-state root serializes every call.
6+
/// </summary>
7+
internal sealed class ChatApprovalState
8+
{
9+
private const int SeenCapacity = 128;
10+
11+
private readonly LinkedList<string> _seenOrder = new();
12+
private readonly HashSet<string> _seen = new(StringComparer.Ordinal);
13+
private readonly Dictionary<string, string> _alternateIds =
14+
new(StringComparer.Ordinal);
15+
16+
internal bool MarkSeen(string requestId, string? alternateId)
17+
{
18+
if (string.IsNullOrEmpty(requestId))
19+
return true;
20+
21+
RecordAlternateId(requestId, alternateId);
22+
if (IsSeen(requestId) ||
23+
IsDistinct(requestId, alternateId) && IsSeen(alternateId!))
24+
{
25+
return false;
26+
}
27+
28+
AddSeen(requestId);
29+
if (IsDistinct(requestId, alternateId))
30+
AddSeen(alternateId!);
31+
32+
while (_seenOrder.Count > SeenCapacity)
33+
{
34+
var oldest = _seenOrder.First!.Value;
35+
_seenOrder.RemoveFirst();
36+
Evict(oldest);
37+
}
38+
39+
return true;
40+
}
41+
42+
internal bool Matches(
43+
string pendingId,
44+
string primaryId,
45+
string alternateId)
46+
{
47+
if (string.IsNullOrEmpty(pendingId))
48+
return false;
49+
50+
_alternateIds.TryGetValue(pendingId, out var pendingAlternate);
51+
return MatchesOne(primaryId) || MatchesOne(alternateId);
52+
53+
bool MatchesOne(string value) =>
54+
!string.IsNullOrEmpty(value) &&
55+
(string.Equals(value, pendingId, StringComparison.Ordinal) ||
56+
!string.IsNullOrEmpty(pendingAlternate) &&
57+
string.Equals(value, pendingAlternate, StringComparison.Ordinal));
58+
}
59+
60+
internal void Reset()
61+
{
62+
_seen.Clear();
63+
_seenOrder.Clear();
64+
_alternateIds.Clear();
65+
}
66+
67+
private void AddSeen(string approvalId)
68+
{
69+
if (_seen.Add(approvalId))
70+
_seenOrder.AddLast(approvalId);
71+
}
72+
73+
private bool IsSeen(string approvalId) =>
74+
_seen.Contains(approvalId) ||
75+
_alternateIds.TryGetValue(approvalId, out var alternateId) &&
76+
_seen.Contains(alternateId);
77+
78+
private void RecordAlternateId(string requestId, string? alternateId)
79+
{
80+
if (!IsDistinct(requestId, alternateId))
81+
return;
82+
_alternateIds[requestId] = alternateId!;
83+
_alternateIds[alternateId!] = requestId;
84+
}
85+
86+
private void Evict(string approvalId)
87+
{
88+
_seen.Remove(approvalId);
89+
if (!_alternateIds.TryGetValue(approvalId, out var alternateId))
90+
return;
91+
92+
_alternateIds.Remove(approvalId);
93+
if (_alternateIds.TryGetValue(alternateId, out var reverse) &&
94+
string.Equals(reverse, approvalId, StringComparison.Ordinal))
95+
{
96+
_alternateIds.Remove(alternateId);
97+
}
98+
99+
if (!_seen.Remove(alternateId))
100+
return;
101+
102+
for (var node = _seenOrder.First; node is not null; node = node.Next)
103+
{
104+
if (!string.Equals(node.Value, alternateId, StringComparison.Ordinal))
105+
continue;
106+
_seenOrder.Remove(node);
107+
break;
108+
}
109+
}
110+
111+
private static bool IsDistinct(string requestId, string? alternateId) =>
112+
!string.IsNullOrEmpty(alternateId) &&
113+
!string.Equals(alternateId, requestId, StringComparison.Ordinal);
114+
}
Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
using System;
2+
using System.Buffers;
3+
using OpenClaw.Chat;
4+
#if !OPENCLAW_TRAY_TESTS
5+
using OpenClawTray.Helpers;
6+
#endif
7+
using OpenClawTray.Services;
8+
9+
namespace OpenClawTray.Chat;
10+
11+
internal static class ChatContentFormatting
12+
{
13+
// Keep this value in sync with OpenClawChatDataProvider.MaxEntryTextBytes for test compatibility.
14+
private const int MaxEntryTextBytes = 256 * 1024;
15+
16+
/// <summary>
17+
/// Truncate <paramref name="text"/> to at most
18+
/// <see cref="MaxEntryTextBytes"/> bytes when encoded as UTF-8 and
19+
/// append a <c> … [N bytes truncated]</c> marker. Slices at a UTF-16
20+
/// code-unit boundary that doesn't split a surrogate pair, then
21+
/// verifies the byte budget. Returns the input unchanged when it
22+
/// already fits or is null/empty.
23+
/// </summary>
24+
internal static string TruncateForChatEntry(string? text)
25+
{
26+
if (string.IsNullOrEmpty(text)) return text ?? string.Empty;
27+
var enc = System.Text.Encoding.UTF8;
28+
// Cheap upper bound: every char is at most 3 UTF-8 bytes for the
29+
// BMP and surrogate pairs encode to 4 bytes / 2 chars (still ≤ 3
30+
// bytes per char). 4 is the worst case and keeps the cheap path
31+
// safe. If even the worst case fits, we're done.
32+
if ((long)text.Length * 4 <= MaxEntryTextBytes) return text;
33+
var actual = enc.GetByteCount(text);
34+
if (actual <= MaxEntryTextBytes) return text;
35+
36+
// Binary search for the largest char-count whose UTF-8 byte count
37+
// fits in MaxEntryTextBytes minus a generous margin for the marker.
38+
var marker = string.Format(LocalizationHelper.GetString("Chat_TruncationMarkerFormat"), actual);
39+
int budget = MaxEntryTextBytes - enc.GetByteCount(marker);
40+
if (budget <= 0) budget = MaxEntryTextBytes / 2;
41+
42+
int lo = 0, hi = text.Length;
43+
while (lo < hi)
44+
{
45+
int mid = (lo + hi + 1) / 2;
46+
// Don't split a surrogate pair: nudge mid back if it lands on
47+
// a low surrogate.
48+
if (mid < text.Length && char.IsLowSurrogate(text[mid])) mid--;
49+
if (mid <= lo)
50+
{
51+
hi = lo;
52+
continue;
53+
}
54+
int bytes = enc.GetByteCount(text.AsSpan(0, mid));
55+
if (bytes <= budget) lo = mid;
56+
else hi = mid - 1;
57+
}
58+
if (lo > 0 && char.IsHighSurrogate(text[lo - 1])) lo--;
59+
60+
Logger.Debug($"[ChatTruncate] message {actual} bytes → {lo} chars (~{enc.GetByteCount(text.AsSpan(0, lo))} bytes); cap={MaxEntryTextBytes}");
61+
return string.Concat(text.AsSpan(0, lo), marker.AsSpan());
62+
}
63+
64+
/// <summary>
65+
/// True when text is one of the approval slash-commands we send on the
66+
/// user's behalf (<c>/approve &lt;slug&gt; allow-once</c>,
67+
/// <c>/approve &lt;slug&gt; allow-always</c>, or
68+
/// <c>/deny &lt;slug&gt;</c>). Matches the exact dashboard grammar
69+
/// — not just the prefix — so legitimate user prose like
70+
/// "/approve the design changes" still renders as a normal bubble.
71+
/// </summary>
72+
/// <remarks>
73+
/// Slug shape: hex-ish identifier (letters, digits, dashes, underscores;
74+
/// 4–64 chars). This mirrors what the gateway emits for
75+
/// ``approvalSlug``; we don't anchor on a specific length because the
76+
/// gateway has changed it before.
77+
/// </remarks>
78+
internal static bool LooksLikeApprovalSlashCommand(string text)
79+
{
80+
if (string.IsNullOrEmpty(text)) return false;
81+
var t = text.Trim();
82+
return s_approvalSlashCommandRegex.IsMatch(t);
83+
}
84+
85+
private static readonly System.Text.RegularExpressions.Regex s_approvalSlashCommandRegex =
86+
new(@"^/(?:approve\s+[A-Za-z0-9_-]{4,64}(?:\s+(?:allow-once|allow-always))?|deny\s+[A-Za-z0-9_-]{4,64})\s*$",
87+
System.Text.RegularExpressions.RegexOptions.Compiled);
88+
89+
private static readonly System.Text.RegularExpressions.Regex s_seamBoldClose =
90+
new(@"(?<=[a-z0-9])(\*\*)(?=[A-Z])",
91+
System.Text.RegularExpressions.RegexOptions.Compiled);
92+
93+
private static readonly System.Text.RegularExpressions.Regex s_seamSentencePunct =
94+
new(@"(?<=[a-z0-9][.!?:])(?=[A-Z][a-z]+[\s,;:!?])",
95+
System.Text.RegularExpressions.RegexOptions.Compiled);
96+
97+
private static readonly SearchValues<char> s_seamPunctChars = SearchValues.Create(".!?:");
98+
99+
/// <summary>
100+
/// Re-insert paragraph breaks at gateway-glued content-block seams in
101+
/// an assistant message. Safe to call on any text — short text, text
102+
/// without seams, and text that is entirely fenced code all pass
103+
/// through unchanged. Fenced code blocks (``` ``` ``` ```) are skipped
104+
/// so JSON/code samples never get whitespace injected inside them.
105+
/// </summary>
106+
internal static string RepairContentBlockSeams(string? text)
107+
{
108+
if (string.IsNullOrEmpty(text)) return text ?? string.Empty;
109+
if (text.Length < 4) return text;
110+
111+
// Fast path: if neither marker is present we can skip entirely.
112+
if (!text.Contains("**", System.StringComparison.Ordinal) &&
113+
text.AsSpan().IndexOfAny(s_seamPunctChars) < 0)
114+
{
115+
return text;
116+
}
117+
118+
// Walk the string, alternating between prose and fenced-code
119+
// segments. Apply seam regexes to prose only. We tolerate
120+
// unclosed fences by treating everything after the dangling
121+
// opener as code (matches Markdown renderer behavior).
122+
var sb = new System.Text.StringBuilder(text.Length + 16);
123+
int i = 0;
124+
while (i < text.Length)
125+
{
126+
int fenceStart = text.IndexOf("```", i, System.StringComparison.Ordinal);
127+
if (fenceStart < 0)
128+
{
129+
sb.Append(RepairProseSegment(text[i..]));
130+
break;
131+
}
132+
133+
sb.Append(RepairProseSegment(text.Substring(i, fenceStart - i)));
134+
135+
int fenceEnd = text.IndexOf("```", fenceStart + 3, System.StringComparison.Ordinal);
136+
if (fenceEnd < 0)
137+
{
138+
// Unclosed fence — append the rest verbatim as code.
139+
sb.Append(text, fenceStart, text.Length - fenceStart);
140+
break;
141+
}
142+
143+
// Append fenced block verbatim (including both fence markers).
144+
sb.Append(text, fenceStart, fenceEnd - fenceStart + 3);
145+
i = fenceEnd + 3;
146+
}
147+
148+
return sb.ToString();
149+
}
150+
151+
internal static string RepairProseSegment(string segment)
152+
{
153+
if (string.IsNullOrEmpty(segment)) return segment;
154+
segment = s_seamBoldClose.Replace(segment, "$1\n\n");
155+
// s_seamSentencePunct is a zero-width assertion (lookbehind +
156+
// lookahead) so the replacement is a pure insert of "\n\n" at
157+
// the seam — no captured punctuation to re-emit.
158+
segment = s_seamSentencePunct.Replace(segment, "\n\n");
159+
return segment;
160+
}
161+
162+
// Per-process random seed for ChatTraceHash. Mixing this into the FNV
163+
// initial state keeps identical-text frames colliding within a single
164+
// tray run (so duplicate-bubble diagnostics still work) while making
165+
// the hash useless as a content fingerprint outside this process: an
166+
// attacker with the log file can no longer rebuild the hash for a
167+
// guessed plaintext, and the value rotates on every tray restart.
168+
private static readonly uint ChatTraceHashSeed = unchecked((uint)System.Security.Cryptography.RandomNumberGenerator.GetInt32(int.MinValue, int.MaxValue));
169+
170+
// Short FNV-1a-style 32-bit fold of the message text, seeded with a
171+
// per-process random value. Used in trace logs to tell two near-
172+
// duplicate frames apart at a glance without dumping the text itself.
173+
// Not a security hash; not reproducible outside this process.
174+
internal static string ChatTraceHash(string text)
175+
{
176+
if (string.IsNullOrEmpty(text)) return "00000000";
177+
uint h = ChatTraceHashSeed;
178+
for (int i = 0; i < text.Length; i++)
179+
{
180+
h ^= text[i];
181+
h *= 16777619u;
182+
}
183+
return h.ToString("x8");
184+
}
185+
186+
/// <summary>
187+
/// Apply <see cref="TruncateForChatEntry(string?)"/> to whichever text
188+
/// payload a <see cref="ChatEvent"/> carries. Returns the input
189+
/// unchanged when there is nothing to truncate or the text already
190+
/// fits. Used by <see cref="ApplyEventAndPublish"/> to enforce the
191+
/// per-message size cap on every code path.
192+
/// </summary>
193+
/// <remarks>
194+
/// Coverage: every <see cref="ChatEvent"/> subtype that carries a
195+
/// caller-supplied text payload is truncated here, including the
196+
/// currently-unused
197+
/// <see cref="ChatModelChangedEvent"/> /
198+
/// <see cref="ChatPermissionRequestEvent"/> /
199+
/// <see cref="ChatIntentEvent"/> shapes — these don't flow through
200+
/// <see cref="ApplyEventAndPublish"/> today but covering them now
201+
/// prevents a future caller from bypassing the cap when wiring
202+
/// them up. The <see cref="ChatTurnEndEvent"/> /
203+
/// <see cref="ChatContextChangedEvent"/> shapes have no untrusted
204+
/// text fields and fall through unchanged.
205+
/// </remarks>
206+
internal static ChatEvent TruncateChatEvent(ChatEvent evt) => evt switch
207+
{
208+
ChatUserMessageEvent e => e with { Text = TruncateForChatEntry(e.Text) },
209+
ChatThinkingEvent e => e with { Text = TruncateForChatEntry(e.Text) },
210+
ChatReasoningEvent e => e with { Text = TruncateForChatEntry(e.Text) },
211+
ChatReasoningDeltaEvent e => e with { Text = TruncateForChatEntry(e.Text) },
212+
ChatMessageEvent e => e with
213+
{
214+
Text = TruncateForChatEntry(e.Text),
215+
ReasoningText = e.ReasoningText is null ? null : TruncateForChatEntry(e.ReasoningText)
216+
},
217+
ChatMessageDeltaEvent e => e with { Text = TruncateForChatEntry(e.Text) },
218+
ChatToolStartEvent e => e with
219+
{
220+
Text = TruncateForChatEntry(e.Text),
221+
ToolName = TruncateForChatEntry(e.ToolName)
222+
},
223+
ChatToolOutputEvent e => e with { Text = TruncateForChatEntry(e.Text) },
224+
ChatToolErrorEvent e => e with { Text = TruncateForChatEntry(e.Text) },
225+
ChatStatusEvent e => e with { Text = TruncateForChatEntry(e.Text) },
226+
ChatErrorEvent e => e with { Text = TruncateForChatEntry(e.Text) },
227+
ChatRestoredEvent e => e with { Text = TruncateForChatEntry(e.Text) },
228+
ChatRawEvent e => e with { Text = e.Text is null ? null : TruncateForChatEntry(e.Text) },
229+
ChatModelChangedEvent e => e with { Model = TruncateForChatEntry(e.Model) },
230+
ChatIntentEvent e => e with { Intent = TruncateForChatEntry(e.Intent) },
231+
ChatPermissionRequestEvent e => e with
232+
{
233+
PermissionKind = TruncateForChatEntry(e.PermissionKind),
234+
ToolName = TruncateForChatEntry(e.ToolName),
235+
Detail = TruncateForChatEntry(e.Detail)
236+
},
237+
_ => evt
238+
};
239+
240+
}

0 commit comments

Comments
 (0)