From 77af6d749f1596ea7820e389d72cc6aa7ab78f85 Mon Sep 17 00:00:00 2001 From: ZhaoJun233 <240002450+ZhaoJun233@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:08:38 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E2=9A=A0=EF=B8=8F=20MODEL-FACING=20TEXT?= =?UTF-8?q?=20CHANGE=20=E2=80=94=20retain=20complete=20originals=20(#6834)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/stream.ts | 21 ++++--- tests/compress-original-cache.test.ts | 81 +++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 7 deletions(-) create mode 100644 tests/compress-original-cache.test.ts diff --git a/src/stream.ts b/src/stream.ts index e3e774cf74..77a785f0cf 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -1577,18 +1577,25 @@ export function applyRanges(parsed: ReturnType, ctx: if (scrubbed > 0) ctx.log(`[acp-proxy: scrubbed ${scrubbed} turn-separator id(s) from fold coverage (#2627)]`); } // Cache original content for newly-created blocks. At compress time the - // source messages are still in ctx.messages (this round's view, before - // the next processTurn folds them) — or in ctx.compressMessages when an - // EMPTY-view fold recovered its source from the unified store (#3982); - // collecting against [] would leave those blocks uncached for later - // decompress/range-restore. Storing the text here lets decompress work - // in later rounds where neither carries the originals. + // same source used by applyCompression still holds the originals. + // ctx.messages may already be emergency-truncated, so prefer the raw + // compressMessages view even when the display is nonempty. It also + // supplies recovered originals for EMPTY-view folds (#3982). Storing + // this text lets decompress work after both live views are evicted. // Two views are cached so decompress can honor the `full` flag: `one` // (direct messages + nested child summaries) and `full` (all originals). // Leaf blocks have no active nested children, so both kernel paths // emit byte-identical text — persist a single copy in that case // (#401: the duplicate was 50% of blockContents bytes on disk). - const contentSource = ctx.messages.length > 0 ? ctx.messages : (ctx.compressMessages ?? ctx.messages); + const displayById = new Map(ctx.messages.map(message => [message.id, message])); + const contentSource = (ctx.compressMessages ?? ctx.messages).map(message => { + // Keep the citation metadata already rendered for this message, + // but never use its potentially truncated display body as source. + const prefix = displayById.get(message.id)?.text?.match(/^\x3cacp [^\x3e]*\x3e(m\d+)\x3c\/acp\x3e\r?\n/); + if (!prefix || prefix[1] !== res.state.messageRefs.byRaw[message.id] + || message.text?.startsWith(prefix[0])) return message; + return { ...message, text: prefix[0] + (message.text ?? "") }; + }); for (const b of res.state.blocks) { if (beforeIds.has(b.blockId)) continue; const full = collectBlockContent(res.state, b, contentSource, { full: true }); diff --git a/tests/compress-original-cache.test.ts b/tests/compress-original-cache.test.ts new file mode 100644 index 0000000000..aae1024a59 --- /dev/null +++ b/tests/compress-original-cache.test.ts @@ -0,0 +1,81 @@ +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import test from "node:test"; +import { collectBlockContent, createCore, defaultConfig, type CoreMessage } from "acp-kernel"; +import { parseCompressInput } from "../src/compress-tool.ts"; +import { resolveDecompress } from "../src/decompress-shared.ts"; +import { getSession } from "../src/session.ts"; +import { applyRanges } from "../src/stream.ts"; + +function history(): CoreMessage[] { + return Array.from({ length: 7 }, (_, i) => ({ + id: "source_" + i, role: i % 2 ? "assistant" : "user", contentType: "text", + text: Array.from({ length: 40 }, (_, j) => + ("Record " + i + "-" + j + ": checksum " + (i === 1 && j === 17 ? 2711 : i * 1000 + j) + "; verified source for later lookup.").padEnd(121, "."), + ).join(" "), + })); +} + +for (const source of ["raw-with-display", "raw-with-empty-display", "display-only"] as const) { + test("compression caches its authoritative source after emergency truncation: " + source, () => { + const core = createCore(), config = defaultConfig(15904); + const session = getSession("original-cache-" + randomUUID()); + const raw = history(); + const turn = core.processTurn({ messages: raw, state: session.state, config, tokenCount: 18500, tokenCountSource: "usage", renderTags: "text-only" }); + session.state = turn.state; + const target = "Record 1-17: checksum 2711"; + assert.ok(raw[1]!.text?.includes(target)); + assert.ok(!turn.messages.some(message => message.text?.includes(target)), "real emergency truncation must hide the middle record"); + const applyView = source === "display-only" ? turn.messages : raw.map(message => { + if (source === "raw-with-empty-display") return message; + const rendered = turn.messages.find(candidate => candidate.id === message.id); + const tag = rendered?.text?.split("\n")[0]; + assert.match(tag ?? "", /^\x3cacp /, "the emergency view retains a citation line"); + return { ...message, text: tag + "\n" + message.text }; + }); + const ctx = { + core, config, session, log: () => {}, + messages: source === "raw-with-empty-display" ? [] : turn.messages, + ...(source === "display-only" ? {} : { compressMessages: raw }), + }; + const compressed = applyRanges(parseCompressInput({ content: "m00001–m00002 Verified source archive\nTASK AS OF THIS BLOCK: source verification is complete. Exact values are omitted from this summary; retrieve the archived sources for the pending lookup." }), ctx); + assert.equal(compressed.outcome, "applied"); + const block = session.state.blocks.find(candidate => candidate.active)!; + const expected = collectBlockContent(session.state, block, applyView, { full: true }); + assert.equal(session.blockContents.get(block.blockId)?.full.text, expected.text, "cache must preserve the complete fold source and its displayed citations"); + const evicted = { ...ctx, messages: [], compressMessages: [] }; + for (const full of [false, true]) { + const restored = resolveDecompress({ blockId: block.blockId, full }, evicted); + assert.equal(restored.outcome, "success"); + assert.ok(restored.text.includes(expected.text), "leaf originals must survive loss of both live views"); + assert.equal(restored.text.includes(target), source !== "display-only"); + } + }); +} + +test("original caching copies only a leading citation belonging to the same source message", () => { + const core = createCore(), config = defaultConfig(100000); + const session = getSession("original-citations-" + randomUUID()); + const raw = history(); + const turn = core.processTurn({ messages: raw, state: session.state, config, tokenCount: 18500 }); + session.state = turn.state; + const tag = '\x3cacp tokens="2.5K" type="text" time="2026-11-15 00:00:00"\x3em00001\x3c/acp\x3e\n'; + const foreignTag = '\x3cacp tokens="1" type="text"\x3em99999\x3c/acp\x3e\n'; + const secondTag = '\x3cacp tokens="1" type="text"\x3em00002\x3c/acp\x3e\n'; + for (const [label, displayed, expectedFirst, expectedSecond] of [ + ["owned", [tag + "clipped", foreignTag + "clipped"], tag + raw[0]!.text, raw[1]!.text], + ["quoted", ["quoted: " + tag, "prose\n" + secondTag], raw[0]!.text, raw[1]!.text], + ] as const) { + const fresh = getSession("original-citations-" + label + randomUUID()); + fresh.state = turn.state; + const ctx = { core, config, session: fresh, log: () => {}, compressMessages: raw, + messages: raw.map((message, index) => ({ ...message, text: displayed[index] === undefined + ? message.text : displayed[index] + "Display-only filler. ".repeat(100) })), + }; + const result = applyRanges(parseCompressInput({ content: "m00001–m00002 Archive\nVerified source records and their checksums are archived for a later exact lookup." }), ctx); + assert.equal(result.outcome, "applied", JSON.stringify(result)); + const block = fresh.state.blocks.find(candidate => candidate.active)!; + assert.equal(fresh.blockContents.get(block.blockId)?.full.text, "[user]\n" + expectedFirst + "\n\n[assistant]\n" + expectedSecond); + assert.equal(raw[0]!.text, history()[0]!.text, "adding cache citations must not mutate the source"); + } +});