|
| 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 <slug> allow-once</c>, |
| 67 | + /// <c>/approve <slug> allow-always</c>, or |
| 68 | + /// <c>/deny <slug></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