Skip to content

Commit 3753c5e

Browse files
authored
fix(inbound-meta): preserve reply-context body tails
Preserve actionable tail content in long reply-context bodies before they enter prompt JSON or inline reply context formatting. - Apply UTF-16-safe head+tail truncation to ReplyChain JSON bodies and fallback ReplyToBody JSON blocks. - Use the same body-aware truncation for Telegram inline ReplyToBody fallback and chat_window message bodies, so those paths cannot suppress the JSON fallback and still lose the tail. - Adds regression coverage for ReplyChain, fallback ReplyToBody, Telegram inline ReplyToBody, chat_window reply targets, and emoji-heavy heads. Verification: - node scripts/run-vitest.mjs src/auto-reply/reply/inbound-meta.test.ts - node_modules/.bin/oxfmt --check --threads=1 src/auto-reply/reply/inbound-meta.ts src/auto-reply/reply/inbound-meta.test.ts - node scripts/run-oxlint.mjs src/auto-reply/reply/inbound-meta.ts src/auto-reply/reply/inbound-meta.test.ts - .agents/skills/autoreview/scripts/autoreview --mode branch --base origin/main - Testbox-through-Crabbox check:changed: provider=blacksmith-testbox id=tbx_01ktgthbb5xa9d5ap58h4134s0 exit=0 - PR CI: 158/158 completed, no failures, MERGEABLE/CLEAN Fixes #91042
1 parent 9bafa2a commit 3753c5e

2 files changed

Lines changed: 154 additions & 5 deletions

File tree

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

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,29 @@ describe("buildInboundUserContextPrefix", () => {
598598
expect(text).not.toContain("Reply target of current user message");
599599
});
600600

601+
it("preserves Telegram inline ReplyToBody tail content", () => {
602+
const head = "BEGIN. ".repeat(300);
603+
const tail = " TELEGRAM_INLINE_TAIL";
604+
const longBody = head + tail;
605+
expect(longBody.length).toBeGreaterThan(2_000);
606+
607+
const text = buildInboundUserContextPrefix({
608+
Provider: "telegram",
609+
Surface: "telegram",
610+
OriginatingChannel: "telegram",
611+
ChatType: "group",
612+
MessageSid: "34974",
613+
ReplyToId: "34971",
614+
ReplyToBody: longBody,
615+
SenderName: "obviyus",
616+
} as TemplateContext);
617+
618+
expect(text).toContain("TELEGRAM_INLINE_TAIL");
619+
expect(text).toContain("…[omitted]…");
620+
expect(text).not.toContain("…[truncated]");
621+
expect(text).not.toContain("Reply target of current user message");
622+
});
623+
601624
it("keeps Telegram current-message quote even when context already includes the target", () => {
602625
const text = buildInboundUserContextPrefix({
603626
Provider: "telegram",
@@ -948,6 +971,91 @@ describe("buildInboundUserContextPrefix", () => {
948971
expect(text).toContain('"body": "');
949972
});
950973

974+
it("preserves tail content in ReplyChain body via head+tail truncation", () => {
975+
const head = "BEGIN. ".repeat(300);
976+
const tail = " IMPORTANT_TAIL_SENTINEL";
977+
const longBody = head + tail;
978+
expect(longBody.length).toBeGreaterThan(2_000);
979+
980+
const text = buildInboundUserContextPrefix({
981+
ChatType: "group",
982+
ReplyChain: [{ body: longBody, sender: "Alice" }],
983+
} as TemplateContext);
984+
985+
const [reply] = parseReplyChainPayload(text);
986+
expect(reply?.["body"]).toContain("IMPORTANT_TAIL_SENTINEL");
987+
expect(reply?.["body"]).toContain("…[omitted]…");
988+
expect(reply?.["body"]).not.toContain("…[truncated]");
989+
});
990+
991+
it("preserves tail content in fallback ReplyToBody via head+tail truncation", () => {
992+
const head = "BEGIN. ".repeat(300);
993+
const tail = " REPLY_TAIL_SENTINEL";
994+
const longBody = head + tail;
995+
expect(longBody.length).toBeGreaterThan(2_000);
996+
997+
const text = buildInboundUserContextPrefix({
998+
ChatType: "group",
999+
ReplyToBody: longBody,
1000+
} as TemplateContext);
1001+
1002+
const reply = parseReplyPayload(text);
1003+
expect(reply["body"]).toContain("REPLY_TAIL_SENTINEL");
1004+
expect(reply["body"]).toContain("…[omitted]…");
1005+
expect(reply["body"]).not.toContain("…[truncated]");
1006+
});
1007+
1008+
it("preserves fallback ReplyToBody tail when the head is emoji-heavy", () => {
1009+
const head = "😀".repeat(1_200);
1010+
const tail = " TAIL_AFTER_EMOJI_HEAD";
1011+
const longBody = head + tail;
1012+
expect(longBody.length).toBeGreaterThan(2_000);
1013+
1014+
const text = buildInboundUserContextPrefix({
1015+
ReplyToSender: "Quoter",
1016+
ReplyToBody: longBody,
1017+
} as TemplateContext);
1018+
1019+
const reply = parseReplyPayload(text);
1020+
expect(reply["body"]).toContain("TAIL_AFTER_EMOJI_HEAD");
1021+
expect(reply["body"]).toContain("…[omitted]…");
1022+
expect(reply["body"]).not.toContain("…[truncated]");
1023+
});
1024+
1025+
it("preserves chat window reply-target body tail content", () => {
1026+
const head = "BEGIN. ".repeat(300);
1027+
const tail = " CHAT_WINDOW_TAIL";
1028+
const longBody = head + tail;
1029+
expect(longBody.length).toBeGreaterThan(2_000);
1030+
1031+
const text = buildInboundUserContextPrefix({
1032+
ChatType: "group",
1033+
ReplyToId: "msg-1",
1034+
UntrustedStructuredContext: [
1035+
{
1036+
label: "Conversation context",
1037+
type: "chat_window",
1038+
payload: {
1039+
relation: "around_reply_target",
1040+
messages: [
1041+
{
1042+
message_id: "msg-1",
1043+
sender: "Avery",
1044+
body: longBody,
1045+
is_reply_target: true,
1046+
},
1047+
],
1048+
},
1049+
},
1050+
],
1051+
} as TemplateContext);
1052+
1053+
expect(text).toContain("CHAT_WINDOW_TAIL");
1054+
expect(text).toContain("…[omitted]…");
1055+
expect(text).not.toContain("…[truncated]");
1056+
expect(text).not.toContain("Reply target of current user message");
1057+
});
1058+
9511059
it("caps serialized inbound history to the most recent bounded tail", () => {
9521060
const text = buildInboundUserContextPrefix({
9531061
ChatType: "group",

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

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { getLoadedChannelPluginById } from "../../channels/plugins/registry-load
66
import type { ChannelPlugin } from "../../channels/plugins/types.plugin.js";
77
import { normalizeAnyChannelId } from "../../channels/registry.js";
88
import { resolveSenderLabel } from "../../channels/sender-label.js";
9-
import { truncateUtf16Safe } from "../../utils.js";
9+
import { sliceUtf16Safe, truncateUtf16Safe } from "../../utils.js";
1010
import type { EnvelopeFormatOptions } from "../envelope.js";
1111
import { formatEnvelopeTimestamp } from "../envelope.js";
1212
import type { SourceReplyDeliveryMode } from "../get-reply-options.types.js";
@@ -65,6 +65,34 @@ function truncateUntrustedJsonString(value: string): string {
6565
return `${truncateUtf16Safe(value, Math.max(0, MAX_UNTRUSTED_JSON_STRING_CHARS - 14)).trimEnd()}…[truncated]`;
6666
}
6767

68+
const HEAD_TAIL_OMISSION_MARKER = "…[omitted]…";
69+
const HEAD_TAIL_MARKER_LENGTH = HEAD_TAIL_OMISSION_MARKER.length;
70+
const MIN_HEAD_TAIL_CHARS = 20;
71+
72+
/**
73+
* Applies head+tail truncation so the result is ≤ maxChars and the downstream
74+
* {@link truncateUntrustedJsonString} (prefix-only 2000-char cap) is a no-op.
75+
* Head and tail portions are sized to keep the body within
76+
* {@link MAX_UNTRUSTED_JSON_STRING_CHARS}, preserving actionable tail content
77+
* that prefix-only truncation would drop.
78+
*/
79+
function truncateBodyHeadTail(body: string, maxChars = MAX_UNTRUSTED_JSON_STRING_CHARS): string {
80+
if (body.length <= maxChars) {
81+
return body;
82+
}
83+
const available = maxChars - HEAD_TAIL_MARKER_LENGTH;
84+
if (available < MIN_HEAD_TAIL_CHARS * 2) {
85+
return `${truncateUtf16Safe(body, Math.max(0, maxChars - 14)).trimEnd()}…[truncated]`;
86+
}
87+
// Budget in UTF-16 code units because truncateUntrustedJsonString enforces
88+
// that same cap after JSON serialization.
89+
const headChars = Math.floor(available * 0.6);
90+
const tailChars = available - headChars;
91+
const head = truncateUtf16Safe(body, headChars);
92+
const tail = sliceUtf16Safe(body, -tailChars);
93+
return `${head}${HEAD_TAIL_OMISSION_MARKER}${tail}`;
94+
}
95+
6896
function sanitizeUntrustedJsonValue(value: unknown): unknown {
6997
if (typeof value === "string") {
7098
return neutralizeMarkdownFences(truncateUntrustedJsonString(value));
@@ -100,6 +128,17 @@ function sanitizeTranscriptField(value: unknown): string | undefined {
100128
.trim();
101129
}
102130

131+
function sanitizeTranscriptBody(value: unknown): string | undefined {
132+
const body = sanitizePromptBody(value);
133+
if (!body) {
134+
return undefined;
135+
}
136+
const sanitized = neutralizeMarkdownFences(truncateBodyHeadTail(body))
137+
.replace(/\s+/g, " ")
138+
.trim();
139+
return sanitized || undefined;
140+
}
141+
103142
function formatUntrustedStructuredContextLabel(label: unknown): string {
104143
const normalized = normalizePromptMetadataString(label);
105144
return normalized
@@ -156,7 +195,7 @@ function formatChatWindowMessage(
156195
const replyToId = sanitizeTranscriptField(value["reply_to_id"]);
157196
const mediaType = sanitizeTranscriptField(value["media_type"]);
158197
const mediaRef = sanitizeTranscriptField(value["media_ref"]);
159-
const body = sanitizeTranscriptField(value["body"]);
198+
const body = sanitizeTranscriptBody(value["body"]);
160199
const details = [
161200
messageId ? `#${messageId}` : undefined,
162201
timestamp,
@@ -274,7 +313,8 @@ function buildReplyChainPayload(ctx: TemplateContext): Array<Record<string, unkn
274313
return [];
275314
}
276315
return ctx.ReplyChain.flatMap((entry) => {
277-
const body = sanitizePromptBody(entry.body);
316+
const rawBody = sanitizePromptBody(entry.body);
317+
const body = rawBody ? truncateBodyHeadTail(rawBody) : rawBody;
278318
const mediaType = normalizePromptMetadataString(entry.mediaType);
279319
const mediaPath = normalizePromptMetadataString(entry.mediaPath);
280320
const mediaRef = normalizePromptMetadataString(entry.mediaRef);
@@ -312,7 +352,7 @@ function isTelegramInboundContext(ctx: TemplateContext): boolean {
312352
}
313353

314354
function resolveInlineReplyQuote(ctx: TemplateContext): string | undefined {
315-
return sanitizeTranscriptField(ctx.ReplyToQuoteText) ?? sanitizeTranscriptField(ctx.ReplyToBody);
355+
return sanitizeTranscriptField(ctx.ReplyToQuoteText) ?? sanitizeTranscriptBody(ctx.ReplyToBody);
316356
}
317357

318358
function formatTelegramCurrentMessageContext(ctx: TemplateContext): string | undefined {
@@ -552,7 +592,8 @@ export function buildInboundUserContextPrefix(
552592
);
553593
}
554594

555-
const replyToBody = sanitizePromptBody(ctx.ReplyToBody);
595+
const rawReplyToBody = sanitizePromptBody(ctx.ReplyToBody);
596+
const replyToBody = rawReplyToBody ? truncateBodyHeadTail(rawReplyToBody) : rawReplyToBody;
556597
if (replyChainPayload.length > 0 && !chatWindowCoversReplyContext && !currentMessageContext) {
557598
blocks.push(
558599
formatUntrustedJsonBlock(

0 commit comments

Comments
 (0)