Skip to content

Commit 176fee5

Browse files
steipetemaweibinly85206559lsr911wings1029
authored
fix: prevent garbled emoji at remaining text limits (#101685)
* fix: keep remaining bounded text UTF-16 safe Co-authored-by: 0668000787 <[email protected]> Co-authored-by: ben.li <[email protected]> Co-authored-by: 廖石荣 0668000909 <[email protected]> Co-authored-by: 陈志强0668000989 <[email protected]> * test: use tracked prompt template fixture --------- Co-authored-by: 0668000787 <[email protected]> Co-authored-by: ben.li <[email protected]> Co-authored-by: 廖石荣 0668000909 <[email protected]> Co-authored-by: 陈志强0668000989 <[email protected]>
1 parent 936136a commit 176fee5

27 files changed

Lines changed: 291 additions & 23 deletions

‎extensions/codex/src/app-server/app-inventory-cache.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,16 @@ describe("Codex app inventory cache", () => {
217217
);
218218
});
219219

220+
it("keeps serialized app/list error data on a UTF-16 boundary", () => {
221+
const error = Object.assign(new Error("app list failed"), {
222+
data: { label: `${"x".repeat(499)}🚀tail` },
223+
});
224+
225+
expect(serializeCodexAppInventoryError(error).data).toEqual({
226+
label: `${"x".repeat(499)}...`,
227+
});
228+
});
229+
220230
it("forces a post-install refresh past an older in-flight app/list", async () => {
221231
const cache = new CodexAppInventoryCache({ ttlMs: 1_000 });
222232
const key = "runtime";

‎extensions/codex/src/app-server/app-inventory-cache.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
resolveExpiresAtMsFromDurationMs,
1010
} from "openclaw/plugin-sdk/number-runtime";
1111
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
12+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
1213
import type { JsonValue, v2 } from "./protocol.js";
1314

1415
/** Default app inventory cache freshness window. */
@@ -360,7 +361,7 @@ function redactErrorData(value: unknown, depth = 0): JsonValue | undefined {
360361
return redacted;
361362
}
362363
if (typeof value === "string" && value.length > 500) {
363-
return `${value.slice(0, 500)}...`;
364+
return `${truncateUtf16Safe(value, 500)}...`;
364365
}
365366
if (typeof value === "string") {
366367
return value;

‎extensions/codex/src/app-server/run-attempt.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,13 @@ import {
6868
turnStartResult,
6969
userMessage,
7070
} from "./run-attempt-test-harness.js";
71-
import { resetCodexTestBindingStore } from "./session-binding.test-helpers.js";
7271
import { testing } from "./run-attempt.js";
7372
import {
7473
ensureCodexSandboxExecServerEnvironment,
7574
releaseCodexSandboxExecServerEnvironment,
7675
} from "./sandbox-exec-server.js";
7776
import { createSandboxContext } from "./sandbox-exec-server.test-helpers.js";
77+
import { resetCodexTestBindingStore } from "./session-binding.test-helpers.js";
7878
import {
7979
readCodexAppServerBinding,
8080
registerCodexTestSessionIdentity,
@@ -1327,6 +1327,7 @@ describe("runCodexAppServerAttempt", () => {
13271327
{ type: "inputText", text: `lookup result: ${rawToolSecret}` },
13281328
{ type: "inputImage", imageUrl: "data:image/png;base64,abc" },
13291329
{ type: "unsupportedCodexOutput", imageUrl: "data:image/png;base64,ignored" },
1330+
{ type: `${"x".repeat(79)}🚀tail` },
13301331
],
13311332
});
13321333
const content = result.content as Array<{ text?: string; type?: string; url?: string }>;
@@ -1341,6 +1342,10 @@ describe("runCodexAppServerAttempt", () => {
13411342
type: "text",
13421343
text: "[Unsupported Codex dynamic tool output: unsupportedCodexOutput]",
13431344
});
1345+
expect(content[3]).toEqual({
1346+
type: "text",
1347+
text: `[Unsupported Codex dynamic tool output: ${"x".repeat(79)}...]`,
1348+
});
13441349
expect(JSON.stringify(result)).not.toContain(rawToolSecret);
13451350
});
13461351

‎extensions/codex/src/app-server/run-attempt.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import {
5050
} from "openclaw/plugin-sdk/diagnostic-runtime";
5151
import { loadExecApprovals } from "openclaw/plugin-sdk/exec-approvals-runtime";
5252
import { pathExists } from "openclaw/plugin-sdk/security-runtime";
53+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
5354
import {
5455
resolveCodexAppServerForModelProvider,
5556
resolveCodexAppServerForOpenClawToolPolicy,
@@ -403,7 +404,7 @@ function toTranscriptToolResultContentItem(item: unknown): Record<string, unknow
403404

404405
function formatUnsupportedCodexDynamicToolOutput(type: unknown): string {
405406
const rawType = typeof type === "string" ? type.replace(/\s+/g, " ").trim() : "";
406-
const label = rawType ? rawType.slice(0, 80) : "unknown";
407+
const label = rawType ? truncateUtf16Safe(rawType, 80) : "unknown";
407408
const suffix = rawType.length > 80 ? "..." : "";
408409
return `[Unsupported Codex dynamic tool output: ${label}${suffix}]`;
409410
}

‎extensions/discord/src/monitor/reply-delivery.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,4 +572,38 @@ describe("deliverDiscordReply", () => {
572572
expect(session.key).toBe("agent:main:subagent:child");
573573
expect(session.agentId).toBe("main");
574574
});
575+
576+
it("keeps bound thread persona names on a UTF-16 boundary", async () => {
577+
const threadBindings = {
578+
listBySessionKey: vi.fn(() => [
579+
{
580+
accountId: "default",
581+
channelId: "parent-1",
582+
threadId: "thread-1",
583+
targetSessionKey: "agent:main:subagent:child",
584+
agentId: "main",
585+
label: `${"a".repeat(76)}🚀tail`,
586+
webhookId: "wh_1",
587+
webhookToken: "tok_1",
588+
},
589+
]),
590+
};
591+
592+
await deliverDiscordReply({
593+
replies: [{ text: "Hello from subagent" }],
594+
target: "channel:thread-1",
595+
token: "token",
596+
accountId: "default",
597+
runtime,
598+
cfg,
599+
textLimit: 2000,
600+
sessionKey: "agent:main:subagent:child",
601+
threadBindings,
602+
kind: "final",
603+
});
604+
605+
expect(recordField(firstDeliverParams().identity, "identity").name).toBe(
606+
`🤖 ${"a".repeat(76)}`,
607+
);
608+
});
575609
});

‎extensions/discord/src/monitor/reply-delivery.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import type { ChunkMode } from "openclaw/plugin-sdk/reply-chunking";
1717
import type { ReplyPayload } from "openclaw/plugin-sdk/reply-dispatch-runtime";
1818
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env";
1919
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
20+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
2021
import type { RequestClient } from "../internal/discord.js";
2122
import { sendMessageDiscord, sendVoiceMessageDiscord } from "../send.js";
2223
import type { DiscordAllowedMentions } from "../send.shared.js";
@@ -71,8 +72,9 @@ function resolveBindingIdentity(
7172
return undefined;
7273
}
7374
const baseLabel = binding.label?.trim() || binding.agentId;
75+
const displayName = `🤖 ${baseLabel}`.trim() || "🤖 agent";
7476
const identity: OutboundIdentity = {
75-
name: (`🤖 ${baseLabel}`.trim() || "🤖 agent").slice(0, 80),
77+
name: truncateUtf16Safe(displayName, 80),
7678
};
7779
try {
7880
const avatar = resolveAgentAvatar(cfg, binding.agentId);

‎extensions/discord/src/outbound-adapter.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,27 @@ describe("discordOutbound", () => {
239239
});
240240
});
241241

242+
it("keeps webhook persona usernames on a UTF-16 boundary", async () => {
243+
mockDiscordBoundThreadManager(hoisted);
244+
245+
await discordOutbound.sendText?.({
246+
cfg: {},
247+
to: "channel:parent-1",
248+
text: "hello from persona",
249+
accountId: "default",
250+
threadId: "thread-1",
251+
identity: { name: `${"a".repeat(79)}🚀tail` },
252+
});
253+
254+
const options = mockObjectArg(
255+
hoisted.sendWebhookMessageDiscordMock,
256+
"sendWebhookMessageDiscord",
257+
0,
258+
1,
259+
);
260+
expect(options.username).toBe("a".repeat(79));
261+
});
262+
242263
it("falls back to bot send for silent delivery on bound threads", async () => {
243264
mockDiscordBoundThreadManager(hoisted);
244265

‎extensions/discord/src/outbound-adapter.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
normalizeOptionalString,
1313
normalizeOptionalStringifiedId,
1414
} from "openclaw/plugin-sdk/string-coerce-runtime";
15+
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
1516
import { chunkDiscordTextWithMode } from "./chunk.js";
1617
import { notifyDiscordInboundEventOutboundPayloadSuccess } from "./inbound-event-delivery.js";
1718
import { isLikelyDiscordVideoMedia } from "./media-detection.js";
@@ -54,7 +55,7 @@ function resolveDiscordWebhookIdentity(params: {
5455
}): { username?: string; avatarUrl?: string } {
5556
const usernameRaw = normalizeOptionalString(params.identity?.name);
5657
const fallbackUsername = normalizeOptionalString(params.binding.label) ?? params.binding.agentId;
57-
const username = (usernameRaw || fallbackUsername || "").slice(0, 80) || undefined;
58+
const username = truncateUtf16Safe(usernameRaw || fallbackUsername || "", 80) || undefined;
5859
const avatarUrl = normalizeOptionalString(params.identity?.avatarUrl);
5960
return { username, avatarUrl };
6061
}

‎src/agents/embedded-agent-error-observation.test.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,13 +104,13 @@ describe("buildApiErrorObservationFields", () => {
104104
});
105105

106106
it("truncates oversized raw and provider previews", () => {
107-
const longMessage = "X".repeat(260);
107+
const longMessage = `${"X".repeat(199)}🚀tail`;
108108
const observed = buildApiErrorObservationFields(
109109
`{"type":"error","error":{"type":"server_error","message":"${longMessage}"},"request_id":"req_long"}`,
110110
);
111111

112112
expect(observed.rawErrorPreview).toBeTypeOf("string");
113-
expect(observed.providerErrorMessagePreview).toBeTypeOf("string");
113+
expect(observed.providerErrorMessagePreview).toBe(`${"X".repeat(199)}…`);
114114
expect(observed.rawErrorPreview?.length).toBeLessThanOrEqual(401);
115115
expect(observed.providerErrorMessagePreview?.length).toBeLessThanOrEqual(201);
116116
expect(observed.providerErrorMessagePreview?.endsWith("…")).toBe(true);
@@ -119,15 +119,30 @@ describe("buildApiErrorObservationFields", () => {
119119
it("caps oversized raw inputs before hashing and fingerprinting", () => {
120120
// Hashing a bounded prefix keeps diagnostic work predictable for huge
121121
// provider payloads.
122-
const oversized = "X".repeat(70_000);
123-
const bounded = "X".repeat(64_000);
122+
const oversized = `${"X".repeat(63_999)}🚀tail`;
123+
const bounded = "X".repeat(63_999);
124124

125125
const observed = buildApiErrorObservationFields(oversized);
126126
const boundedObserved = buildApiErrorObservationFields(bounded);
127127
expect(observed.rawErrorHash).toBe(boundedObserved.rawErrorHash);
128128
expect(observed.rawErrorFingerprint).toBe(boundedObserved.rawErrorFingerprint);
129129
});
130130

131+
it("keeps fingerprint message bounds on a UTF-16 boundary", () => {
132+
const prefix = "X".repeat(7_999);
133+
const observed = buildApiErrorObservationFields(
134+
JSON.stringify({
135+
type: "error",
136+
error: { type: "server_error", message: `${prefix}🚀tail` },
137+
}),
138+
);
139+
const boundedObserved = buildApiErrorObservationFields(
140+
JSON.stringify({ type: "error", error: { type: "server_error", message: prefix } }),
141+
);
142+
143+
expect(observed.rawErrorFingerprint).toBe(boundedObserved.rawErrorFingerprint);
144+
});
145+
131146
it("returns empty observation fields for empty input", () => {
132147
expect(buildApiErrorObservationFields(undefined)).toStrictEqual({});
133148
expect(buildApiErrorObservationFields("")).toStrictEqual({});

‎src/agents/embedded-agent-error-observation.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* Builds structured observations for embedded-agent API/text failures.
33
*/
44
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
5+
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
56
import { readLoggingConfig } from "../logging/config.js";
67
import { redactIdentifier } from "../logging/redact-identifier.js";
78
import { getDefaultRedactPatterns, redactSensitiveText } from "../logging/redact.js";
@@ -43,7 +44,7 @@ function truncateForObservation(text: string | undefined, maxChars: number): str
4344
if (!trimmed) {
4445
return undefined;
4546
}
46-
return trimmed.length > maxChars ? `${trimmed.slice(0, maxChars)}…` : trimmed;
47+
return trimmed.length > maxChars ? `${truncateUtf16Safe(trimmed, maxChars)}…` : trimmed;
4748
}
4849

4950
function boundObservationInput(text: string | undefined): string | undefined {
@@ -52,7 +53,7 @@ function boundObservationInput(text: string | undefined): string | undefined {
5253
return undefined;
5354
}
5455
return trimmed.length > MAX_OBSERVATION_INPUT_CHARS
55-
? trimmed.slice(0, MAX_OBSERVATION_INPUT_CHARS)
56+
? truncateUtf16Safe(trimmed, MAX_OBSERVATION_INPUT_CHARS)
5657
: trimmed;
5758
}
5859

@@ -100,7 +101,7 @@ function buildObservationFingerprint(params: {
100101
}): string | null {
101102
const boundedMessage =
102103
params.message && params.message.length > MAX_FINGERPRINT_MESSAGE_CHARS
103-
? params.message.slice(0, MAX_FINGERPRINT_MESSAGE_CHARS)
104+
? truncateUtf16Safe(params.message, MAX_FINGERPRINT_MESSAGE_CHARS)
104105
: params.message;
105106
const structured =
106107
params.httpCode || params.type || boundedMessage

0 commit comments

Comments
 (0)