From 70fe2cab0124131f0bf3e631f5ff022e5f6e7072 Mon Sep 17 00:00:00 2001 From: Shantur Rathore Date: Tue, 28 Oct 2025 21:36:16 +0000 Subject: [PATCH] fix: properly encode Unicode text in base64 attachments --- src/types/attachment.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/types/attachment.ts b/src/types/attachment.ts index 9becc069..706fe928 100644 --- a/src/types/attachment.ts +++ b/src/types/attachment.ts @@ -79,7 +79,7 @@ export function createFileAttachment( } export function createTextAttachment(value: string, display: string, filename: string): Attachment { - const base64 = btoa(value) + const base64 = encodeTextAsBase64(value) return { id: crypto.randomUUID(), type: "text", @@ -94,6 +94,24 @@ export function createTextAttachment(value: string, display: string, filename: s } } +function encodeTextAsBase64(value: string): string { + if (typeof TextEncoder !== "undefined") { + const encoder = new TextEncoder() + const bytes = encoder.encode(value) + let binary = "" + const chunkSize = 0x8000 + for (let index = 0; index < bytes.length; index += chunkSize) { + const chunk = bytes.subarray(index, Math.min(index + chunkSize, bytes.length)) + binary += String.fromCharCode(...chunk) + } + return btoa(binary) + } + + return btoa( + encodeURIComponent(value).replace(/%([0-9A-F]{2})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16))), + ) +} + export function createAgentAttachment(agentName: string): Attachment { return { id: crypto.randomUUID(),