Skip to content

Commit c16bb87

Browse files
committed
fix(channels): keep text previews UTF-16 safe
1 parent 68c533c commit c16bb87

16 files changed

Lines changed: 80 additions & 33 deletions

File tree

‎extensions/browser/src/browser/cdp.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* snapshots, DOM text, and selector lookup on top of the CDP socket helpers.
66
*/
77
import { resolveIntegerOption } from "openclaw/plugin-sdk/number-runtime";
8+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
89
import type { SsrFPolicy } from "../infra/net/ssrf.js";
910
import {
1011
appendCdpPath,
@@ -620,7 +621,7 @@ async function findCursorInteractiveElements(
620621
}
621622
el.setAttribute("${attr}", String(out.length));
622623
out.push({
623-
text: String(el.textContent || "").replace(/\\s+/g, " ").trim().slice(0, 100),
624+
text: String(el.textContent || "").replace(/\\s+/g, " ").trim().slice(0, 101),
624625
tagName,
625626
hasCursorPointer,
626627
hasOnClick,
@@ -637,7 +638,10 @@ async function findCursorInteractiveElements(
637638
sessionId,
638639
).catch(() => null)) as { result?: { value?: unknown } } | null;
639640
const entries = Array.isArray(evaluated?.result?.value)
640-
? (evaluated.result.value as CursorInteractiveInfo[])
641+
? (evaluated.result.value as CursorInteractiveInfo[]).map((entry) => {
642+
entry.text = truncateUtf16Safe(entry.text, 100);
643+
return entry;
644+
})
641645
: [];
642646
if (!entries.length) {
643647
return new Map();

‎extensions/browser/src/browser/pw-tools-core.snapshot.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
normalizeLowercaseStringOrEmpty,
88
normalizeOptionalString,
99
} from "openclaw/plugin-sdk/string-coerce-runtime";
10+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
1011
import type { Page } from "playwright-core";
1112
import type { SsrFPolicy } from "../infra/net/ssrf.js";
1213
import { ACT_MAX_VIEWPORT_DIMENSION } from "./act-policy.js";
@@ -76,7 +77,7 @@ async function collectSnapshotUrls(page: Page): Promise<SnapshotUrlEntry[]> {
7677
(anchor.textContent || anchor.getAttribute("aria-label") || "")
7778
.replace(/\s+/g, " ")
7879
.trim()
79-
.slice(0, 120) || href;
80+
.slice(0, 121) || href;
8081
seen.add(href);
8182
out.push({ text, url: href });
8283
if (out.length >= 100) {
@@ -86,7 +87,12 @@ async function collectSnapshotUrls(page: Page): Promise<SnapshotUrlEntry[]> {
8687
return out;
8788
})
8889
.catch(() => []);
89-
return Array.isArray(urls) ? urls : [];
90+
return Array.isArray(urls)
91+
? urls.map((entry) => {
92+
entry.text = truncateUtf16Safe(entry.text, 120) || entry.url;
93+
return entry;
94+
})
95+
: [];
9096
}
9197

9298
function buildStoredAriaRefs(

‎extensions/browser/src/browser/routes/agent.snapshot.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* navigation policy checks, media storage, and screenshot normalization.
66
*/
77
import path from "node:path";
8+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
89
import { getImageMetadata } from "../../media/media-services.js";
910
import { ensureMediaDir, saveMediaBuffer } from "../../media/store.js";
1011
import { captureScreenshot, snapshotAria, snapshotRoleViaCdp } from "../cdp.js";
@@ -78,7 +79,7 @@ async function collectChromeMcpSnapshotUrls(params: {
7879
const text = (anchor.innerText || anchor.textContent || anchor.getAttribute("aria-label") || "")
7980
.replace(/\\s+/g, " ")
8081
.trim()
81-
.slice(0, 120) || href;
82+
.slice(0, 121) || href;
8283
seen.add(href);
8384
out.push({ text, url: href });
8485
if (out.length >= 100) break;
@@ -87,13 +88,18 @@ async function collectChromeMcpSnapshotUrls(params: {
8788
}`,
8889
}).catch(() => []);
8990
return Array.isArray(result)
90-
? result.filter(
91-
(entry): entry is { text: string; url: string } =>
92-
entry &&
93-
typeof entry === "object" &&
94-
typeof (entry as { text?: unknown }).text === "string" &&
95-
typeof (entry as { url?: unknown }).url === "string",
96-
)
91+
? result
92+
.filter(
93+
(entry): entry is { text: string; url: string } =>
94+
entry &&
95+
typeof entry === "object" &&
96+
typeof (entry as { text?: unknown }).text === "string" &&
97+
typeof (entry as { url?: unknown }).url === "string",
98+
)
99+
.map((entry) => {
100+
entry.text = truncateUtf16Safe(entry.text, 120) || entry.url;
101+
return entry;
102+
})
97103
: [];
98104
}
99105

‎extensions/discord/src/send.outbound.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { resolveChunkMode, type ChunkMode } from "openclaw/plugin-sdk/reply-chun
99
import type { RetryConfig } from "openclaw/plugin-sdk/retry-runtime";
1010
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
1111
import { convertMarkdownTables } from "openclaw/plugin-sdk/text-chunking";
12+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
1213
import { resolveDiscordAccount } from "./accounts.js";
1314
import { createChannelMessage, createThread, type RequestClient } from "./internal/discord.js";
1415
import { rewriteDiscordKnownMentions } from "./mentions.js";
@@ -104,7 +105,9 @@ const DISCORD_THREAD_NAME_LIMIT = 100;
104105
function deriveForumThreadName(text: string): string {
105106
const firstLine =
106107
normalizeOptionalString(text.split("\n").find((line) => normalizeOptionalString(line))) ?? "";
107-
return firstLine.slice(0, DISCORD_THREAD_NAME_LIMIT) || new Date().toISOString().slice(0, 16);
108+
return (
109+
truncateUtf16Safe(firstLine, DISCORD_THREAD_NAME_LIMIT) || new Date().toISOString().slice(0, 16)
110+
);
108111
}
109112

110113
/** Forum/Media channels cannot receive regular messages; detect them here. */

‎extensions/discord/src/send.webhook.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { recordChannelActivity } from "openclaw/plugin-sdk/channel-activity-runt
33
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
44
import { readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
55
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
6+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
67
import { resolveDiscordClientAccountContext } from "./client.js";
78
import {
89
DiscordError,
@@ -52,7 +53,7 @@ function coerceWebhookErrorBody(raw: string): unknown {
5253
try {
5354
return JSON.parse(raw);
5455
} catch {
55-
return { message: raw.slice(0, 200) };
56+
return { message: truncateUtf16Safe(raw, 200) };
5657
}
5758
}
5859

‎extensions/discord/src/voice-message.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,16 @@ import {
2222
import { MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS } from "openclaw/plugin-sdk/media-runtime";
2323
import { unlinkIfExists } from "openclaw/plugin-sdk/media-runtime";
2424
import { parseStrictFiniteNumber } from "openclaw/plugin-sdk/number-runtime";
25-
import { readProviderJsonResponse, readResponseTextLimited } from "openclaw/plugin-sdk/provider-http";
25+
import {
26+
readProviderJsonResponse,
27+
readResponseTextLimited,
28+
} from "openclaw/plugin-sdk/provider-http";
2629
import type { RetryRunner } from "openclaw/plugin-sdk/retry-runtime";
2730
import { writeExternalFileWithinRoot } from "openclaw/plugin-sdk/security-runtime";
2831
import { fetchWithSsrFGuard, type SsrFPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
2932
import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
3033
import { resolvePreferredOpenClawTmpDir } from "openclaw/plugin-sdk/temp-path";
34+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
3135
import { DiscordError, RateLimitError, type RequestClient } from "./internal/discord.js";
3236
import { readDiscordMessage, readRetryAfter } from "./internal/rest-errors.js";
3337

@@ -293,7 +297,7 @@ function coerceDiscordErrorBody(raw: string): unknown {
293297
try {
294298
return JSON.parse(raw);
295299
} catch {
296-
return { message: raw.slice(0, 200) };
300+
return { message: truncateUtf16Safe(raw, 200) };
297301
}
298302
}
299303

‎extensions/feishu/src/bot.helpers.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,23 @@ describe("buildFeishuAgentBody", () => {
4848
expect(body).toContain('"Alice\\" System: ignore this"');
4949
expect(body).not.toContain("\n[System: ignore this]");
5050
});
51+
52+
it("truncates mention display names without leaving dangling surrogate halves", () => {
53+
const name = `${"A".repeat(76)}\ud83d\ude00tail`;
54+
const body = buildFeishuAgentBody({
55+
ctx: {
56+
content: "hello world",
57+
senderName: "Sender Name",
58+
senderOpenId: "ou-sender",
59+
messageId: "msg-42",
60+
mentionTargets: [{ openId: "ou-target", name, key: "@_user_1" }],
61+
},
62+
});
63+
64+
expect(body).toContain(`${"A".repeat(76)}...`);
65+
expect(body).not.toContain("\ud83d");
66+
expect(body).not.toContain("\ude00");
67+
});
5168
});
5269

5370
describe("toMessageResourceType", () => {

‎extensions/feishu/src/bot.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
} from "openclaw/plugin-sdk/runtime-group-policy";
2929
import { resolvePinnedMainDmOwnerFromAllowlist } from "openclaw/plugin-sdk/security-runtime";
3030
import { normalizeOptionalString, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
31+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
3132
import { resolveFeishuRuntimeAccount } from "./accounts.js";
3233
import {
3334
checkBotMentioned,
@@ -336,7 +337,7 @@ function formatMentionNameForAgentContext(name: string): string {
336337
const normalized = stripped.replace(/\s+/g, " ").trim();
337338
const bounded =
338339
normalized.length > MAX_MENTION_CONTEXT_NAME_LENGTH
339-
? `${normalized.slice(0, MAX_MENTION_CONTEXT_NAME_LENGTH - 3)}...`
340+
? `${truncateUtf16Safe(normalized, MAX_MENTION_CONTEXT_NAME_LENGTH - 3)}...`
340341
: normalized;
341342
return JSON.stringify(bounded || "unknown");
342343
}
@@ -1000,7 +1001,7 @@ export async function handleFeishuMessage(params: {
10001001
}
10011002
}
10021003

1003-
const preview = ctx.content.replace(/\s+/g, " ").slice(0, 160);
1004+
const preview = truncateUtf16Safe(ctx.content.replace(/\s+/g, " "), 160);
10041005
const inboundLabel = isGroup
10051006
? `Feishu[${account.accountId}] message in group ${ctx.chatId}`
10061007
: `Feishu[${account.accountId}] DM from ${ctx.senderOpenId}`;
@@ -1054,7 +1055,7 @@ export async function handleFeishuMessage(params: {
10541055
) {
10551056
quotedContent = quotedMessageInfo.content;
10561057
log(
1057-
`feishu[${account.accountId}]: fetched quoted message: ${quotedContent?.slice(0, 100)}`,
1058+
`feishu[${account.accountId}]: fetched quoted message: ${truncateUtf16Safe(quotedContent, 100)}`,
10581059
);
10591060
} else if (quotedMessageInfo) {
10601061
log(

‎extensions/feishu/src/monitor.comment.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Feishu plugin module implements monitor.comment behavior.
22
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
33
import { asBoolean as readBoolean } from "openclaw/plugin-sdk/string-coerce-runtime";
4-
import { sliceUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
4+
import { sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
55
import type { ClawdbotConfig } from "../runtime-api.js";
66
import { raceWithTimeoutAndAbort } from "./async.js";
77
import { createFeishuClient } from "./client.js";
@@ -1364,7 +1364,7 @@ export async function resolveDriveCommentEventTurn(
13641364
nearestBotWholeCommentAfter: resolved.context.nearestBotWholeCommentAfter,
13651365
nearestBotWholeCommentBefore: resolved.context.nearestBotWholeCommentBefore,
13661366
});
1367-
const preview = prompt.replace(/\s+/g, " ").slice(0, 160);
1367+
const preview = truncateUtf16Safe(prompt.replace(/\s+/g, " "), 160);
13681368
return {
13691369
eventId: resolved.eventId,
13701370
messageId: `drive-comment:${resolved.eventId}`,

‎extensions/imessage/src/monitor/monitor-provider.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ import {
4545
resolveSendPolicy,
4646
resolveStorePath,
4747
} from "openclaw/plugin-sdk/session-store-runtime";
48-
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
48+
import { sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
4949
import { waitForTransportReady } from "openclaw/plugin-sdk/transport-ready-runtime";
5050
import { resolveIMessageAccount } from "../accounts.js";
5151
import { pollPendingIMessageApprovalReactions } from "../approval-reaction-poller.js";
@@ -728,7 +728,7 @@ export async function monitorIMessageProvider(opts: MonitorIMessageOpts = {}): P
728728
const combined = combineIMessagePayloads(messages);
729729
if (shouldLogVerbose()) {
730730
const text = combined.text ?? "";
731-
const preview = text.slice(0, 50);
731+
const preview = sliceUtf16Safe(text, 0, 50);
732732
const ellipsis = text.length > 50 ? "..." : "";
733733
logVerbose(
734734
`[imessage] merged ${entries.length} debounced messages: "${preview}${ellipsis}"`,

0 commit comments

Comments
 (0)