Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(utils): preserve valid surrogate pairs in sanitizeUTF8 (#16879)

mengnanjiugaipeifensea92e46e03dba
diff --git a/packages/utils/src/sanitizeUTF8.test.ts b/packages/utils/src/sanitizeUTF8.test.ts
index b492a69c8b2..3897a3d3585 100644
--- a/packages/utils/src/sanitizeUTF8.test.ts
+++ b/packages/utils/src/sanitizeUTF8.test.ts
@@ -22,4 +22,15 @@ describe('UTF-8 Sanitization', () => {
const input = 'δ½ ε₯½οΌŒδΈ–η•ŒοΌ';
expect(sanitizeUTF8(input)).toBe('δ½ ε₯½οΌŒδΈ–η•ŒοΌ');
});
+
+ it('should preserve valid emoji and astral-plane characters (paired surrogates)', () => {
+ // πŸ˜€ = U+1F600, 𝕏 = U+1D54F β€” both are valid surrogate pairs in UTF-16
+ expect(sanitizeUTF8('aπŸ˜€b')).toBe('aπŸ˜€b');
+ expect(sanitizeUTF8('Hello πŸ˜€ δΈ–η•Œ 𝕏!')).toBe('Hello πŸ˜€ δΈ–η•Œ 𝕏!');
+ });
+
+ it('should still strip lone (unpaired) surrogates', () => {
+ expect(sanitizeUTF8('a\uD800b')).toBe('ab'); // lone high surrogate
+ expect(sanitizeUTF8('a\uDC00b')).toBe('ab'); // lone low surrogate
+ });
});
diff --git a/packages/utils/src/sanitizeUTF8.ts b/packages/utils/src/sanitizeUTF8.ts
index debc064c2c6..c2adee858ce 100644
--- a/packages/utils/src/sanitizeUTF8.ts
+++ b/packages/utils/src/sanitizeUTF8.ts
@@ -9,6 +9,9 @@ export const sanitizeUTF8 = (str: string) => {
.replaceAll('οΏ½', '') // Remove Unicode replacement character
// eslint-disable-next-line no-control-regex
.replaceAll(/[\u0000-\u0008\v\f\u000E-\u001F\u007F-\u009F]/g, '') // Remove control characters
- .replaceAll(/[\uD800-\uDFFF]/g, '')
- ); // Remove unpaired surrogate code points
+ // The `u` flag makes valid surrogate PAIRS match as a single code point
+ // outside this range, so emoji / astral-plane characters are preserved;
+ // only truly unpaired (lone) surrogates are removed.
+ .replaceAll(/[\uD800-\uDFFF]/gu, '')
+ );
};