Skip to content

Commit e84ec68

Browse files
committed
Control UI + auto-reply: address upstream review on scaffolding/metadata strip
Five review points across Codex, Copilot, and Greptile on the Control UI cleanup PR and its TUI symmetry follow-up: 1. Narrow System-event line signature (Codex P1, Copilot P1) The original per-line sweep stripped any line starting with `System:` or `System (untrusted):`. Two practical problems: - `sanitizeInboundSystemTags()` deliberately rewrites a user line-leading `System:` to `System (untrusted):`, so any legitimate user message whose first line happens to start with `System:` (pasted logs, exec output, YAML snippets, notes) was getting silently deleted after sanitization. - `stripInboundMetadata` is used beyond Control UI rendering (`command-detection.ts`, `send-policy.ts`, `chat-sanitize.ts`, `cli-session-history.merge.ts`, `session-cost-usage.ts`), so over-stripping here corrupts downstream command detection and session/cost accounting, not just UI. Tighten `SYSTEM_EVENT_LINE_RE` to require the bracketed timestamp marker `[Weekday YYYY-MM-DD HH:MM:SS TZ]` that `session-system-events.ts` always emits on the first sub-line of each injected event. User-authored `System:` prefixes without the timestamp signature stay intact. Continuation sub-lines of a single injected event may still leak, but that is strictly better than silently deleting real user input. 2. Narrow internal-instruction prefix matches (Codex P1, Copilot P1) Replaced `INTERNAL_INSTRUCTION_LINE_PREFIXES` with anchored regexes. - `Current time: ` was too generic — a user note like "Current time: I'll be free after lunch" matched. Require the injected shape `Current time: … / YYYY-MM-DD HH:MM UTC` emitted by `resolveCronStyleNow`. - `An async command you ran earlier has completed.` kept, since the full sentence emitted by `heartbeat-events-filter.ts` is long and specific enough. 3. Constrain stripLeadingInboundMetadata to leading metadata region (Codex P1 on commit 5ba2f48) The TUI formatter uses `stripLeadingInboundMetadata` for `user` and `command` turns. The previous follow-up applied the System/instruction filter globally, which silently truncated command transcript bodies containing `System: …` lines. Move the filter into the leading-metadata skip loop: drop timestamped System-event and injected-instruction lines only while we are still in the leading prelude (alongside leading blank lines); the moment we hit the first real user/command content line, filtering stops. Added tests for mid-body `System:` preservation. 4. Preserve reasoning-only assistant turns (Codex P2) Routing grouped assistant text through `processMessageText` stripped `<think>…</think>` scaffolding before the bubble-visibility check, so an assistant turn that produced only a reasoning block and no visible final answer was suppressed by the empty-group guard — the reasoning panel itself disappeared too. Include `reasoningMarkdown` in the visibility check in `renderGroupedMessage` and also treat reasoning content as visible in `groupHasVisibleContent`, so reasoning-only turns still render with the reasoning panel intact. 5. Use extractTextCached + normalize role (Copilot P2 x2, Greptile P2) - `renderGroupedMessage` and `groupHasVisibleContent` now read visible text through `extractTextCached(message)` instead of rebuilding it from `normalizeMessage(...).content`. `normalizeMessage` drops each block's `textSignature`, so the rebuilt path lost the assistant phase contract — `final_answer` preference and commentary-only suppression — and could re-introduce scaffolding that `extractTextCached` already handles. Routing both surfaces through the shared extractor also collapses the duplicated precheck work. - `processMessageText` and `extractText` now consistently normalise the role to lowercase before dispatching, so a `role: "Assistant"` message no longer skips the thinking-tag strip path. New tests cover: - User-authored `System:` prefix without timestamp stays intact. - User-authored `Current time: …` prose without the injected UTC suffix stays intact. - Mid-body `System: …` line in TUI command transcript is preserved.
1 parent 5ba2f48 commit e84ec68

4 files changed

Lines changed: 128 additions & 65 deletions

File tree

‎src/auto-reply/reply/strip-inbound-meta.test.ts‎

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -247,17 +247,19 @@ describe("builder compatibility", () => {
247247
});
248248

249249
describe("per-line system events and internal instructions", () => {
250-
it("strips consecutive `System (untrusted):` exec lines", () => {
250+
it("strips consecutive timestamped `System (untrusted):` exec lines", () => {
251251
const input = [
252-
"System (untrusted): [2026-04-17 06:11:17 UTC] Exec completed (gentle-g, code 0) :: ok",
253-
"System (untrusted): [2026-04-17 06:12:04 UTC] Exec completed (swift-co, code 0) :: ok",
252+
"System (untrusted): [Wed 2026-04-17 06:11:17 UTC] Exec completed (gentle-g, code 0) :: ok",
253+
"System (untrusted): [Wed 2026-04-17 06:12:04 UTC] Exec completed (swift-co, code 0) :: ok",
254254
"Actual user message",
255255
].join("\n");
256256
expect(stripInboundMetadata(input)).toBe("Actual user message");
257257
});
258258

259-
it("strips `System:` (trusted) prefix lines too", () => {
260-
const input = ["System: session started", "real user prose"].join("\n");
259+
it("strips timestamped `System:` (trusted) prefix lines too", () => {
260+
const input = ["System: [Wed 2026-04-17 06:11:17 UTC] session started", "real user prose"].join(
261+
"\n",
262+
);
261263
expect(stripInboundMetadata(input)).toBe("real user prose");
262264
});
263265

@@ -275,9 +277,32 @@ describe("per-line system events and internal instructions", () => {
275277
expect(stripInboundMetadata(input)).toBe(input);
276278
});
277279

278-
it("strips leading System event lines in stripLeadingInboundMetadata for TUI history", () => {
280+
it("preserves user-authored `System:` prefix without a timestamp marker", () => {
281+
// After `sanitizeInboundSystemTags` rewrites a user line-leading `System:`
282+
// to `System (untrusted):`, the resulting line does NOT carry the
283+
// session-system-events timestamp signature and must not be stripped.
284+
const input = [
285+
"System (untrusted): paste log line from a user",
286+
"System: my note to self",
287+
"continuing user prose",
288+
].join("\n");
289+
expect(stripInboundMetadata(input)).toBe(input);
290+
});
291+
292+
it("preserves user-authored `Current time:` prefix without the injected UTC suffix", () => {
293+
// `appendCronStyleCurrentTimeLine` always ends with ` / YYYY-MM-DD HH:MM UTC`;
294+
// a plain user note that happens to start with "Current time: ..." must
295+
// not match the tighter pattern and must be kept intact.
279296
const input = [
280-
"System (untrusted): [2026-04-17 06:11:17 UTC] Exec completed (gentle-g, code 0) :: ok",
297+
"Current time: I'll be free after lunch",
298+
"Follow-up thought from the user",
299+
].join("\n");
300+
expect(stripInboundMetadata(input)).toBe(input);
301+
});
302+
303+
it("strips leading timestamped System event lines in stripLeadingInboundMetadata for TUI history", () => {
304+
const input = [
305+
"System (untrusted): [Wed 2026-04-17 06:11:17 UTC] Exec completed (gentle-g, code 0) :: ok",
281306
"",
282307
"Actual user message",
283308
].join("\n");
@@ -293,6 +318,16 @@ describe("per-line system events and internal instructions", () => {
293318
expect(stripLeadingInboundMetadata(input)).toBe("User question goes here");
294319
});
295320

321+
it("preserves a mid-body `System:` line in stripLeadingInboundMetadata (command transcript)", () => {
322+
// The TUI formatter uses `stripLeadingInboundMetadata` for `user` and
323+
// `command` turns. A command transcript body containing a line that
324+
// starts with `System:` (pasted log, exec output) must not be truncated.
325+
const input = ["User ran: /debug", "System: service is healthy", "Continuing transcript"].join(
326+
"\n",
327+
);
328+
expect(stripLeadingInboundMetadata(input)).toBe(input);
329+
});
330+
296331
it("preserves inline `Operating System:` prose in stripLeadingInboundMetadata", () => {
297332
const input = "Operating System: Linux — works as expected";
298333
expect(stripLeadingInboundMetadata(input)).toBe(input);

‎src/auto-reply/reply/strip-inbound-meta.ts‎

Lines changed: 54 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,39 @@ import { safeParseJsonWithSchema } from "../../utils/zod-parse.js";
1818
const LEADING_TIMESTAMP_PREFIX_RE = /^\[[A-Za-z]{3} \d{4}-\d{2}-\d{2} \d{2}:\d{2}[^\]]*\] */;
1919

2020
/**
21-
* Line-level sentinel for per-line system event prefix injection. Matches both
22-
* `System:` (trusted) and `System (untrusted):` variants emitted by
23-
* `session-system-events.ts`. These blocks may span multiple consecutive lines
24-
* — each continuation line re-uses the same prefix for safety, so a simple
25-
* consecutive-line sweep is sufficient to remove them.
21+
* Line-level sentinel for the first line of an injected system-event block.
22+
* Matches both `System:` (trusted) and `System (untrusted):` variants emitted
23+
* by `session-system-events.ts`, but ONLY when the prefix is immediately
24+
* followed by the bracketed timestamp marker that the injector always places
25+
* on the first sub-line of each event (e.g.
26+
* `System (untrusted): [Wed 2026-04-17 06:11:17 UTC] Exec completed (…) :: ok`).
27+
*
28+
* The tighter signature avoids deleting legitimate user content that happens
29+
* to start with `System:` or `System (untrusted):` (pasted logs, YAML, exec
30+
* output). Continuation sub-lines of a single event, channel-summary lines,
31+
* and other `System:` variants without the timestamp marker are left alone
32+
* — at worst that leaks one or two non-sensitive lines, which is strictly
33+
* better than silently deleting real user input.
2634
*/
27-
const SYSTEM_EVENT_LINE_RE = /^System(?: \(untrusted\))?:/;
35+
const SYSTEM_EVENT_LINE_RE =
36+
/^System(?: \(untrusted\))?: \[[A-Z][a-z]{2} \d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?[^\]]*\] /;
2837

2938
/**
30-
* Bare-line sentinels that mark OpenClaw-internal agent instructions leaking
31-
* into user-visible text (not user input). Stripped as standalone lines so
32-
* surrounding user prose is preserved.
39+
* Patterns for OpenClaw-internal agent-facing instruction lines that must
40+
* never surface in user-visible chat. Each pattern matches the exact injected
41+
* shape so user-authored look-alikes (pasted logs, note-taking text starting
42+
* with "Current time:", etc.) are preserved.
43+
*
44+
* - `An async command you ran earlier has completed.` — injected verbatim by
45+
* `heartbeat-events-filter.ts`; the full sentence is long and specific
46+
* enough that a `startsWith` guard already avoids user-text collisions.
47+
* - `Current time: … (TZ) / YYYY-MM-DD HH:MM UTC` — emitted by
48+
* `resolveCronStyleNow` in `agents/current-time.ts`. The closing UTC
49+
* timestamp after ` / ` is what pins the match to the injected shape.
3350
*/
34-
const INTERNAL_INSTRUCTION_LINE_PREFIXES = [
35-
"An async command you ran earlier has completed.",
36-
"Current time: ",
51+
const INTERNAL_INSTRUCTION_LINE_PATTERNS: readonly RegExp[] = [
52+
/^An async command you ran earlier has completed\./,
53+
/^Current time: .+ \/ \d{4}-\d{2}-\d{2} \d{2}:\d{2} UTC\s*$/,
3754
];
3855

3956
/**
@@ -56,16 +73,19 @@ const ACTIVE_MEMORY_CLOSE_TAG = "</active_memory_plugin>";
5673
const [CONVERSATION_INFO_SENTINEL, SENDER_INFO_SENTINEL] = INBOUND_META_SENTINELS;
5774
const InboundMetaBlockSchema = z.record(z.string(), z.unknown());
5875

59-
// Pre-compiled fast-path regex — avoids line-by-line parse when no blocks present.
60-
// Also catches per-line system-event prefixes and leaked internal instruction
61-
// lines so those variants still trigger the slow parse below.
76+
// Pre-compiled fast-path regex — avoids line-by-line parse when no inbound
77+
// metadata, system-event, or internal-instruction leaks are present.
78+
// Keeps the literal strings conservatively loose here so the slow path always
79+
// gets the chance to confirm/reject the tight line-anchored signatures above;
80+
// a false positive on the fast path only costs the slow parse, not an edit.
6281
const SENTINEL_FAST_RE = new RegExp(
6382
[
6483
...INBOUND_META_SENTINELS,
6584
UNTRUSTED_CONTEXT_HEADER,
66-
"System:",
67-
"System (untrusted):",
68-
...INTERNAL_INSTRUCTION_LINE_PREFIXES,
85+
"System: [",
86+
"System (untrusted): [",
87+
"An async command you ran earlier has completed",
88+
"Current time: ",
6989
]
7090
.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
7191
.join("|"),
@@ -81,8 +101,7 @@ function isSystemEventLine(line: string): boolean {
81101
}
82102

83103
function isInternalInstructionLine(line: string): boolean {
84-
const trimmed = line.trim();
85-
return INTERNAL_INSTRUCTION_LINE_PREFIXES.some((prefix) => trimmed.startsWith(prefix));
104+
return INTERNAL_INSTRUCTION_LINE_PATTERNS.some((pattern) => pattern.test(line));
86105
}
87106

88107
function restoreNeutralizedMarkdownFences(value: unknown): unknown {
@@ -288,13 +307,23 @@ export function stripLeadingInboundMetadata(text: string): string {
288307
return text;
289308
}
290309

291-
const lines = stripActiveMemoryPromptPrefixBlocks(text.split("\n")).filter(
292-
(line) => !isSystemEventLine(line) && !isInternalInstructionLine(line),
293-
);
310+
const lines = stripActiveMemoryPromptPrefixBlocks(text.split("\n"));
294311
let index = 0;
295312

296-
while (index < lines.length && lines[index] === "") {
297-
index++;
313+
// Leading-only filter: skip blank, timestamped system-event, and injected
314+
// internal-instruction lines at the very start of the message. Once we hit
315+
// the first line that is neither blank nor an injected prelude sentinel,
316+
// stop filtering — user-authored text from that point on must never be
317+
// silently removed just because a line happens to match one of these
318+
// patterns. (TUI formatter uses this for `user`/`command` turns; a command
319+
// transcript body containing `System: …` must not be truncated.)
320+
while (index < lines.length) {
321+
const line = lines[index];
322+
if (line === "" || isSystemEventLine(line) || isInternalInstructionLine(line)) {
323+
index++;
324+
continue;
325+
}
326+
break;
298327
}
299328
if (index >= lines.length) {
300329
return "";

‎ui/src/ui/chat/grouped-render.ts‎

Lines changed: 25 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import {
2020
extractTextCached,
2121
extractThinkingCached,
2222
formatReasoningMarkdown,
23-
processMessageText,
2423
} from "./message-extract.ts";
2524
import {
2625
isToolResultMessage,
@@ -169,25 +168,25 @@ export function renderMessageGroup(
169168
// when every inner message renders empty. Without this, a user turn whose
170169
// text consists entirely of now-stripped metadata/system-event lines still
171170
// leaves an orphan "You · 12:34" bubble in Control UI.
171+
//
172+
// Route text through `extractTextCached` rather than rebuilding it from
173+
// `normalizeMessage.content`, so this precheck respects the same
174+
// assistant-phase contract (`final_answer` preferred, commentary-only
175+
// suppressed) that `renderGroupedMessage` ultimately applies. Reasoning
176+
// content is treated as visible too, so an assistant turn that only
177+
// produced a reasoning block still shows the group bubble (and the
178+
// reasoning panel inside) instead of disappearing.
172179
const groupHasVisibleContent = group.messages.some(({ message }) => {
173-
const m = message as Record<string, unknown>;
174-
const role = typeof m.role === "string" ? m.role : "";
175-
const normalized = normalizeMessage(message);
176-
const rawText = normalized.content
177-
.reduce<string[]>((acc, item) => {
178-
if (item.type === "text" && typeof item.text === "string") {
179-
acc.push(item.text);
180-
}
181-
return acc;
182-
}, [])
183-
.join("\n")
184-
.trim();
185-
if (rawText && processMessageText(rawText, role).trim()) {
180+
if (extractTextCached(message)?.trim()) {
181+
return true;
182+
}
183+
if (extractThinkingCached(message)?.trim()) {
186184
return true;
187185
}
188186
if (extractImages(message).length > 0) {
189187
return true;
190188
}
189+
const normalized = normalizeMessage(message);
191190
if (normalized.replyTarget) {
192191
return true;
193192
}
@@ -1106,20 +1105,13 @@ function renderGroupedMessage(
11061105
const hasImages = images.length > 0;
11071106

11081107
const normalizedMessage = normalizeMessage(message);
1109-
const rawExtractedText = normalizedMessage.content
1110-
.reduce<string[]>((lines, item) => {
1111-
if (item.type === "text" && typeof item.text === "string") {
1112-
lines.push(item.text);
1113-
}
1114-
return lines;
1115-
}, [])
1116-
.join("\n")
1117-
.trim();
1118-
// Route through processMessageText so <think>/<final> scaffolding and
1119-
// inbound metadata sentinels are stripped before render. Previously the
1120-
// reduced text was rendered verbatim, leaking <final>…</final> tags and
1121-
// injected "Sender (untrusted metadata):" blocks into the Control UI.
1122-
const extractedText = rawExtractedText ? processMessageText(rawExtractedText, role) : "";
1108+
// Use `extractTextCached` as the text source rather than a fresh pass over
1109+
// `normalizedMessage.content`. `extractTextCached` already applies the
1110+
// shared assistant-visible-text contract (prefer `final_answer` phase,
1111+
// suppress commentary-only blocks) and runs `processMessageText`, so
1112+
// Control UI rendering stays aligned with the other surfaces and cannot
1113+
// re-introduce scaffolding that `normalizeMessage` drops the signature of.
1114+
const extractedText = extractTextCached(message) ?? "";
11231115
const assistantAttachments = normalizedMessage.content.filter(
11241116
(item): item is Extract<MessageContentItem, { type: "attachment" }> =>
11251117
item.type === "attachment",
@@ -1142,10 +1134,14 @@ function renderGroupedMessage(
11421134
.filter(Boolean)
11431135
.join(" ");
11441136

1145-
// Suppress empty bubbles when tool cards are the only content and toggle is off
1137+
// Suppress empty bubbles when tool cards are the only content and toggle is off.
1138+
// Reasoning markdown counts as visible content here: a turn that produced
1139+
// only a `<think>`/reasoning block (and no visible final answer) should
1140+
// still render so the reasoning panel can surface.
11461141
const visibleToolCards = hasToolCards && (opts.showToolCalls ?? true);
11471142
if (
11481143
!markdown &&
1144+
!reasoningMarkdown &&
11491145
!visibleToolCards &&
11501146
!hasImages &&
11511147
assistantAttachments.length === 0 &&

‎ui/src/ui/chat/message-extract.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,23 @@ const textCache = new WeakMap<object, string | null>();
88
const thinkingCache = new WeakMap<object, string | null>();
99

1010
export function processMessageText(text: string, role: string): string {
11-
const shouldStripInboundMetadata = normalizeLowercaseStringOrEmpty(role) === "user";
12-
if (role === "assistant") {
11+
const normalizedRole = normalizeLowercaseStringOrEmpty(role);
12+
if (normalizedRole === "assistant") {
1313
return stripThinkingTags(text);
1414
}
15-
return shouldStripInboundMetadata
15+
return normalizedRole === "user"
1616
? stripInboundMetadata(stripEnvelope(text))
1717
: stripEnvelope(text);
1818
}
1919

2020
export function extractText(message: unknown): string | null {
2121
const m = message as Record<string, unknown>;
2222
const role = typeof m.role === "string" ? m.role : "";
23+
const normalizedRole = normalizeLowercaseStringOrEmpty(role);
2324
const raw =
24-
role === "assistant" ? extractSharedAssistantVisibleText(message) : extractRawText(message);
25+
normalizedRole === "assistant"
26+
? extractSharedAssistantVisibleText(message)
27+
: extractRawText(message);
2528
if (!raw) {
2629
return null;
2730
}

0 commit comments

Comments
 (0)