230 lines
12 KiB
JavaScript
230 lines
12 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for utils/safe-truncate.js — the ONE helper for length caps that cut
|
|
// UTF-16 code units, introduced to fix the surrogate-pair-split defect class:
|
|
// a plain String.prototype.slice cap can land between the two units of an
|
|
// astral character (emoji, CJK Extension B, ...), and the stored lone high
|
|
// surrogate becomes U+FFFD in MySQL — the last visible character of the
|
|
// stored value is silently mangled. index.js already fixed this once inline
|
|
// in truncateChatMessageContent; this file pins the shared helper and that
|
|
// every cap cut in index.js (chat message content + the three planner
|
|
// cap/derive sites) routes through it.
|
|
//
|
|
// This file pins:
|
|
// - the cut dropping a trailing lone high surrogate (the regression itself),
|
|
// including a 4-byte character at position max-1;
|
|
// - complete pairs never being dropped (a LOW surrogate at the boundary is
|
|
// kept — only an unpaired HIGH is removed);
|
|
// - no-truncation, empty, short and astral-only inputs;
|
|
// - the invariant "the result never ends with a lone high surrogate" over a
|
|
// deterministic fuzz corpus, plus idempotency (f(f(x, cap), cap) ===
|
|
// f(x, cap));
|
|
// - source pins that index.js's four cut sites use the helper and no longer
|
|
// carry a plain .slice cap (same extraction technique as the other
|
|
// source-window tests in this repository).
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
|
|
const { safeTruncateUtf16 } = require("./safe-truncate");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
|
|
|
|
const EMOJI = "\u{1F600}"; // 4-byte char, two UTF-16 units (high 0xD83D, low 0xDE00)
|
|
const HI = "\uD83D";
|
|
const LO = "\uDE00";
|
|
|
|
function isHigh(unit) {
|
|
return unit >= 0xd800 && unit <= 0xdbff;
|
|
}
|
|
|
|
test("input at or under the cap is returned unchanged", () => {
|
|
assert.strictEqual(safeTruncateUtf16("", 10), "");
|
|
assert.strictEqual(safeTruncateUtf16("abc", 10), "abc");
|
|
assert.strictEqual(safeTruncateUtf16("abcdefghij", 10), "abcdefghij", "exactly at the cap: no cut");
|
|
assert.strictEqual(safeTruncateUtf16(`${"a".repeat(8)}${EMOJI}`, 10), `${"a".repeat(8)}${EMOJI}`, "complete pair ending exactly at the cap stays intact");
|
|
});
|
|
|
|
test("a cut straddling a surrogate pair drops the trailing high surrogate", () => {
|
|
// 9 BMP chars + emoji = 11 units; cap 10 slices between the pair's halves.
|
|
assert.strictEqual(safeTruncateUtf16(`${"a".repeat(9)}${EMOJI}`, 10), "a".repeat(9));
|
|
// The mangled alternative would be "aaaaaaaaa" + HI (a lone high surrogate).
|
|
const result = safeTruncateUtf16(`${"a".repeat(9)}${EMOJI}`, 10);
|
|
assert.ok(!isHigh(result.charCodeAt(result.length - 1)), "result never ends with a lone high surrogate");
|
|
});
|
|
|
|
test("a 4-byte character at position max-1 is dropped as a whole, not halved", () => {
|
|
// The emoji's high surrogate IS the last unit kept by the slice.
|
|
const text = `${"x".repeat(3)}${EMOJI}${"y".repeat(3)}`; // xxx🙂yyy, 8 units
|
|
assert.strictEqual(safeTruncateUtf16(text, 4), "xxx", "cap 4 would keep only the high half — one character earlier instead");
|
|
assert.strictEqual(safeTruncateUtf16(text, 5), `xxx${EMOJI}`, "cap 5 keeps the complete pair");
|
|
});
|
|
|
|
test("complete pairs are never dropped: a LOW surrogate at the boundary is kept", () => {
|
|
// cap lands after the full pair — the low half must not be mistaken for
|
|
// "a cut half" (only an unpaired HIGH is dropped).
|
|
assert.strictEqual(safeTruncateUtf16(`${EMOJI}${EMOJI}`, 4), `${EMOJI}${EMOJI}`);
|
|
assert.strictEqual(safeTruncateUtf16(`a${HI}${LO}b`, 3), `a${HI}${LO}`);
|
|
});
|
|
|
|
test("emoji-heavy and astral-only strings", () => {
|
|
assert.strictEqual(safeTruncateUtf16(EMOJI.repeat(5), 5), EMOJI.repeat(2), "10 units capped to 5 -> 2 pairs (third pair's high half dropped)");
|
|
assert.strictEqual(safeTruncateUtf16(EMOJI.repeat(5), 4), EMOJI.repeat(2), "cap exactly on a pair boundary keeps 2 pairs");
|
|
assert.strictEqual(safeTruncateUtf16(EMOJI.repeat(3), 3), EMOJI, "odd cap in astral-only text ends one character earlier");
|
|
assert.strictEqual(safeTruncateUtf16(EMOJI.repeat(2), 2), EMOJI.repeat(1));
|
|
assert.strictEqual(safeTruncateUtf16(EMOJI, 1), "", "cap 1 can only keep a lone high half -> empty result instead");
|
|
});
|
|
|
|
test("an input that itself ends with a lone high surrogate is cleaned even without a cut", () => {
|
|
// A client-supplied trailing lone surrogate can only ever store as U+FFFD;
|
|
// the helper's invariant ("never ends with a lone high surrogate") holds
|
|
// for every return value, not just cut ones.
|
|
assert.strictEqual(safeTruncateUtf16("abc\uD800", 10), "abc");
|
|
assert.strictEqual(safeTruncateUtf16(EMOJI.slice(0, 1), 10), "", "a bare high surrogate alone is dropped");
|
|
});
|
|
|
|
test("a RUN of trailing lone high surrogates is fully dropped (a trailing high is always unpaired)", () => {
|
|
assert.strictEqual(safeTruncateUtf16(`abc${HI}${HI}${HI}`, 10), "abc");
|
|
assert.strictEqual(safeTruncateUtf16(`a${HI.repeat(5)}`, 3), "a", "the cut can land inside a run of lone highs");
|
|
});
|
|
|
|
test("an input-borne lone LOW surrogate at the tail is left for the caller (documented scope)", () => {
|
|
// A slice can never CREATE a trailing lone low (a cut ending on a low unit
|
|
// always has its high half inside), so pre-broken interior/low input is
|
|
// not rewritten here — it stores as U+FFFD exactly as before the fix.
|
|
assert.strictEqual(safeTruncateUtf16(`ab${LO}`, 10), `ab${LO}`);
|
|
});
|
|
|
|
test("a lone surrogate NOT at the tail is left for the caller (documented scope)", () => {
|
|
// The helper owns the CUT boundary; rewriting interior lone surrogates is
|
|
// the caller's cleaning concern (the planner strip, upload-filename, etc.).
|
|
assert.strictEqual(safeTruncateUtf16(`\uD800abc`, 10), `\uD800abc`);
|
|
});
|
|
|
|
test("empty, short and degenerate caps", () => {
|
|
assert.strictEqual(safeTruncateUtf16("", 0), "");
|
|
assert.strictEqual(safeTruncateUtf16("abc", 0), "");
|
|
assert.strictEqual(safeTruncateUtf16("abc", -1), "", "negative caps never fall into slice-from-end semantics");
|
|
assert.strictEqual(safeTruncateUtf16("abc", 1.5), "", "non-integer caps are rejected, not sliced");
|
|
});
|
|
|
|
test("idempotent: f(f(x, cap), cap) === f(x, cap)", () => {
|
|
const samples = [
|
|
"",
|
|
"abc",
|
|
"abcdefghij",
|
|
`${"a".repeat(9)}${EMOJI}`,
|
|
EMOJI.repeat(5),
|
|
"abc\uD800",
|
|
`a${HI}${LO}b`,
|
|
`${"a".repeat(3)}${EMOJI}${"y".repeat(3)}`,
|
|
];
|
|
for (const text of samples) {
|
|
for (const cap of [1, 2, 3, 5, 10, 255, 4000]) {
|
|
const once = safeTruncateUtf16(text, cap);
|
|
assert.strictEqual(safeTruncateUtf16(once, cap), once, `idempotent for ${JSON.stringify(text)} @ ${cap}`);
|
|
}
|
|
}
|
|
});
|
|
|
|
test("fuzz: result is a short-or-exact prefix, never ends with a lone high surrogate, never exceeds the cap", () => {
|
|
// Deterministic pseudo-random corpus of WELL-FORMED text (BMP chars plus
|
|
// complete astral pairs) — the shapes real cap inputs take. Inputs that
|
|
// are already broken (lone halves, runs of them) have their trailing lone
|
|
// highs dropped by design; that behavior is pinned deterministically
|
|
// above, not fuzzed here, so the "at most one unit shorter than the plain
|
|
// cut" property below stays exact.
|
|
let seed = 0x2f6e2b1;
|
|
const next = () => {
|
|
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
|
|
return seed;
|
|
};
|
|
const pool = ["a", "b", " ", "\n", EMOJI, "\u{1F41B}", "\u4e2d", "\uFFFD"];
|
|
for (let i = 0; i < 500; i += 1) {
|
|
let text = "";
|
|
const len = next() % 40;
|
|
for (let j = 0; j < len; j += 1) text += pool[next() % pool.length];
|
|
const cap = 1 + (next() % 30);
|
|
const out = safeTruncateUtf16(text, cap);
|
|
assert.ok(out.length <= cap, `cap respected for case ${i}`);
|
|
if (out.length > 0) {
|
|
assert.ok(!isHigh(out.charCodeAt(out.length - 1)), `no trailing lone high surrogate for case ${i}`);
|
|
}
|
|
assert.ok(text.startsWith(out), `result is a prefix of the input for case ${i}`);
|
|
assert.ok(out.length >= Math.min(text.length, cap) - 1, `at most one unit shorter than the plain cut for case ${i}`);
|
|
const once = safeTruncateUtf16(out, cap);
|
|
assert.strictEqual(once, out, `idempotent for case ${i}`);
|
|
}
|
|
});
|
|
|
|
// Source pins: every cap cut in index.js routes through the one helper, and
|
|
// the plain .slice cuts are gone from those sites. Same window-extraction
|
|
// discipline as tests/planner-send-agent-hardening.test.js (index.js is a
|
|
// ~55k-line bundle that cannot be required here).
|
|
function functionWindow(src, anchor, label) {
|
|
const start = src.indexOf(anchor);
|
|
assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`);
|
|
const end = src.indexOf("\n}", start);
|
|
assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`);
|
|
return src.slice(start, end + 2);
|
|
}
|
|
|
|
test("index.js cut sites route through the shared helper", () => {
|
|
assert.ok(
|
|
INDEX_SRC.includes('require("./utils/safe-truncate")'),
|
|
"index.js must require utils/safe-truncate"
|
|
);
|
|
const workerStore = fs.readFileSync(require.resolve("../AgentWorker/job-store"), "utf8");
|
|
const chatWindow = functionWindow(workerStore, "async function publishAgentResult", "publishAgentResult");
|
|
assert.ok(
|
|
chatWindow.includes('safeTruncateUtf16(result.content || "Done.", RESULT_CHARS)') &&
|
|
chatWindow.includes('safeTruncateUtf16(result.thinking_content || "", RESULT_CHARS)'),
|
|
"worker result and thinking text must cut through safeTruncateUtf16"
|
|
);
|
|
assert.ok(
|
|
!chatWindow.includes(".slice(0,") && !chatWindow.includes("charCodeAt"),
|
|
"worker publication must not carry its own plain cut or surrogate scan"
|
|
);
|
|
// The three planner sites.
|
|
const titleWindow = functionWindow(INDEX_SRC, "function sanitizePlannerTitle", "sanitizePlannerTitle");
|
|
const promptWindow = functionWindow(INDEX_SRC, "function sanitizePlannerPrompt", "sanitizePlannerPrompt");
|
|
const deriveWindow = functionWindow(INDEX_SRC, "function derivePlannerTitleFromPrompt", "derivePlannerTitleFromPrompt");
|
|
for (const [body, label] of [[titleWindow, "sanitizePlannerTitle"], [promptWindow, "sanitizePlannerPrompt"], [deriveWindow, "derivePlannerTitleFromPrompt"]]) {
|
|
assert.ok(body.includes("safeTruncateUtf16("), `${label} must cut through safeTruncateUtf16`);
|
|
assert.ok(!body.includes(".slice("), `${label} must not carry a plain .slice cut anymore`);
|
|
}
|
|
// adpanel:surrogate-safe-cut — the agent-pipeline cuts route through the
|
|
// helper too: the enqueue-time prompt sanitizer and the agent chat-title
|
|
// cut (raw client title or derived fallback), plus the planner PUT route's
|
|
// kept-title fallback.
|
|
const agentPromptWindow = functionWindow(INDEX_SRC, "function sanitizeAiAgentPrompt", "sanitizeAiAgentPrompt");
|
|
assert.ok(
|
|
agentPromptWindow.includes("safeTruncateUtf16(String(value || \"\").replace(/\\0/g, \"\").trim(), AI_AGENT_PROMPT_MAX_CHARS)"),
|
|
"sanitizeAiAgentPrompt must cut through safeTruncateUtf16"
|
|
);
|
|
assert.ok(
|
|
!agentPromptWindow.includes(".slice("),
|
|
"sanitizeAiAgentPrompt must not carry a plain .slice cut"
|
|
);
|
|
const insertJobWindow = functionWindow(INDEX_SRC, "async function insertAiAgentChatJob", "insertAiAgentChatJob");
|
|
assert.ok(
|
|
insertJobWindow.includes("safeTruncateUtf16(String(title || deriveAiAgentChatTitle(safePrompt)), 255)"),
|
|
"insertAiAgentChatJob's chat-title cut must route through safeTruncateUtf16"
|
|
);
|
|
assert.ok(
|
|
!insertJobWindow.includes("String(title || deriveAiAgentChatTitle(safePrompt)).slice(0, 255)"),
|
|
"insertAiAgentChatJob must not carry the plain .slice(0, 255) title cut anymore"
|
|
);
|
|
assert.ok(
|
|
INDEX_SRC.includes("safeTruncateUtf16(String(current.title || '').trim(), PLANNER_TITLE_MAX_UNITS)"),
|
|
"the planner PUT route's kept-title fallback must cut through safeTruncateUtf16"
|
|
);
|
|
assert.ok(
|
|
!INDEX_SRC.includes("String(current.title || '').trim().slice(0, 255)"),
|
|
"the planner PUT route must not carry the plain .slice(0, 255) title fallback anymore"
|
|
);
|
|
});
|