Skip to content

Commit 9b4cbe4

Browse files
wm0018steipete
andauthored
fix(agents): keep chunkString and buildResumeMessage truncation UTF-16 safe (#102085)
* fix(agents): keep chunkString and buildResumeMessage truncation UTF-16 safe * fix: preserve code points in agent output chunks --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent d6ec1c6 commit 9b4cbe4

4 files changed

Lines changed: 36 additions & 9 deletions

File tree

‎src/agents/bash-tools.shared.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
* Covers strict env parsing and compact session labels.
44
*/
55
import { afterEach, describe, expect, it, vi } from "vitest";
6-
import { deriveSessionName, readEnvInt } from "./bash-tools.shared.js";
6+
import { chunkString, deriveSessionName, readEnvInt } from "./bash-tools.shared.js";
77

88
describe("readEnvInt", () => {
99
afterEach(() => {
@@ -70,3 +70,22 @@ describe("deriveSessionName", () => {
7070
}
7171
});
7272
});
73+
74+
describe("chunkString", () => {
75+
it("preserves surrogate pairs at chunk boundaries", () => {
76+
const input = "a".repeat(8191) + "🚀b";
77+
expect(chunkString(input, 8192)).toEqual(["a".repeat(8191), "🚀b"]);
78+
});
79+
80+
it("returns single chunk for input smaller than limit", () => {
81+
expect(chunkString("hello", 8192)).toEqual(["hello"]);
82+
});
83+
84+
it("emits a whole code point when the limit is one UTF-16 unit", () => {
85+
expect(chunkString("😀a", 1)).toEqual(["😀", "a"]);
86+
});
87+
88+
it("preserves every code point across mixed chunk boundaries", () => {
89+
expect(chunkString("aa🚀bb", 2)).toEqual(["aa", "🚀", "bb"]);
90+
});
91+
});

‎src/agents/bash-tools.shared.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,11 +133,17 @@ export function readEnvInt(key: string, legacyKey?: string) {
133133
return parseStrictInteger(raw);
134134
}
135135

136-
/** Splits large output into fixed-size UTF-16 chunks for transport. */
136+
/** Splits output into bounded chunks without splitting UTF-16 surrogate pairs. */
137137
export function chunkString(input: string, limit = CHUNK_LIMIT) {
138138
const chunks: string[] = [];
139-
for (let i = 0; i < input.length; i += limit) {
140-
chunks.push(input.slice(i, i + limit));
139+
const chunkLimit = Number.isNaN(limit) ? CHUNK_LIMIT : Math.max(1, Math.floor(limit));
140+
let i = 0;
141+
while (i < input.length) {
142+
const firstCodePointWidth = (input.codePointAt(i) ?? 0) > 0xffff ? 2 : 1;
143+
// A code point is indivisible; a tiny limit may require one chunk to exceed it.
144+
const chunk = sliceUtf16Safe(input, i, i + Math.max(chunkLimit, firstCodePointWidth));
145+
chunks.push(chunk);
146+
i += chunk.length;
141147
}
142148
return chunks;
143149
}

‎src/agents/subagent-orphan-recovery.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -495,17 +495,17 @@ describe("subagent-orphan-recovery", () => {
495495
it("truncates long task descriptions in resume message", async () => {
496496
mockSingleAbortedSession();
497497

498-
const longTask = "x".repeat(5000);
498+
const taskPrefix = "x".repeat(1999);
499+
const longTask = `${taskPrefix}🚀 omitted tail`;
499500
const activeRuns = createActiveRuns(createTestRunRecord({ task: longTask }));
500501

501502
await recoverOrphanedSubagentSessions({
502503
getActiveRuns: () => activeRuns,
503504
});
504505

505506
const message = getResumeMessage();
506-
// Message should contain truncated task (2000 chars + "...")
507-
expect(message.length).toBeLessThan(5000);
508-
expect(message).toContain("...");
507+
expect(message).toContain(`Your original task was:\n\n${taskPrefix}...\n\n`);
508+
expect(message).not.toContain("🚀");
509509
});
510510

511511
it("includes last human message in resume when available", async () => {

‎src/agents/subagent-orphan-recovery.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { callGateway } from "../gateway/call.js";
2323
import { readSessionMessagesAsync } from "../gateway/session-transcript-readers.js";
2424
import { formatErrorMessage } from "../infra/errors.js";
2525
import { createSubsystemLogger } from "../logging/subsystem.js";
26+
import { truncateUtf16Safe } from "../utils.js";
2627
import { resolveInternalSessionEffectsTranscriptPath } from "./internal-session-effects.js";
2728
import {
2829
evaluateSubagentRecoveryGate,
@@ -72,7 +73,8 @@ function reclassifyLegacyRestartInterruptedRun(runRecord: SubagentRunRecord): vo
7273
*/
7374
function buildResumeMessage(task: string, lastHumanMessage?: string): string {
7475
const maxTaskLen = 2000;
75-
const truncatedTask = task.length > maxTaskLen ? `${task.slice(0, maxTaskLen)}...` : task;
76+
const truncatedTask =
77+
task.length > maxTaskLen ? `${truncateUtf16Safe(task, maxTaskLen)}...` : task;
7678

7779
let message =
7880
`[System] Your previous turn was interrupted by a gateway reload. ` +

0 commit comments

Comments
 (0)