Skip to content

A personal agent with a browser, terminal, files, and work that keeps going built with CopilotKit and AG-UI.

TypeScript

fix: keep surrogate pairs whole when truncating file names (#148)

Mrdifferent2ca0ffcc90b6
diff --git a/apps/server/src/files.ts b/apps/server/src/files.ts
index af41eb5..1445345 100644
--- a/apps/server/src/files.ts
+++ b/apps/server/src/files.ts
@@ -12,10 +12,11 @@ const FILE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-
export function sanitizeFileName(name: string): string {
const base = name.split(/[\\/]/).at(-1) ?? "document.pdf";
+ // Slice code points, not UTF-16 units, so a surrogate pair is never split in half.
const cleaned = Array.from(base)
.filter((character) => character.charCodeAt(0) >= 32 && character.charCodeAt(0) !== 127)
- .join("")
- .slice(0, 180);
+ .slice(0, 180)
+ .join("");
return cleaned || "document.pdf";
}
diff --git a/tests/resource-ids.test.ts b/tests/resource-ids.test.ts
index 0dd2255..84392cd 100644
--- a/tests/resource-ids.test.ts
+++ b/tests/resource-ids.test.ts
@@ -53,6 +53,11 @@ test("file names never collapse to an empty display name", () => {
const long = sanitizeFileName(`${"a".repeat(300)}.pdf`);
assert.ok(long.length <= 180);
assert.ok(long.length > 0);
+ // The 180-character bound slices whole code points, never half a surrogate pair.
+ const emoji = sanitizeFileName(`${"x".repeat(179)}πŸ˜€.pdf`);
+ assert.equal(emoji, `${"x".repeat(179)}πŸ˜€`);
+ assert.equal([...emoji].length, 180);
+ assert.equal([...sanitizeFileName(`${"x".repeat(180)}πŸ˜€.pdf`)].length, 180);
});
test("file lookups reject malformed IDs instead of probing storage", async (t) => {