Skip to content

Commit c6bde56

Browse files
only21milclaudemaria-rcks
authored
fix(relay): long CJK titles no longer stop Live Activity updates (#24679)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent 16233e7 commit c6bde56

3 files changed

Lines changed: 137 additions & 3 deletions

File tree

‎infra/relay/src/agentActivity/ApnsClient.test.ts‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ import * as HttpClientResponse from "effect/http/HttpClientResponse";
1313

1414
import type { ApnsCredentials } from "../Config.ts";
1515
import * as ApnsClient from "./ApnsClient.ts";
16-
import { sanitizeApnsNotificationPayload } from "./agentActivityPayloads.ts";
16+
import {
17+
sanitizeAgentActivityAggregateState,
18+
sanitizeApnsNotificationPayload,
19+
} from "./agentActivityPayloads.ts";
1720
import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
1821

1922
const layerTest = ApnsClient.layer.pipe(
@@ -169,6 +172,81 @@ describe("ApnsClient", () => {
169172
}).pipe(Effect.provide(layerTest)),
170173
);
171174

175+
it.effect("shortens multibyte row titles so Live Activity updates fit within 4096 bytes", () =>
176+
Effect.gen(function* () {
177+
const apns = yield* ApnsClient.ApnsClient;
178+
const longState = sanitizeAgentActivityAggregateState({
179+
...state,
180+
activeCount: 5,
181+
activities: ["a", "b", "c", "d", "e"].map((id) => ({
182+
...state.activities[0]!,
183+
threadId: ThreadId.make(id),
184+
projectTitle: "界".repeat(200),
185+
threadTitle: "界".repeat(200),
186+
})),
187+
});
188+
const request = apns.makeLiveActivityRequest({
189+
event: "update",
190+
token: "token",
191+
state: longState,
192+
alert: { title: "界".repeat(120), body: "界".repeat(120) },
193+
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
194+
nowIso: DateTime.formatIso(now),
195+
});
196+
197+
expect(
198+
new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
199+
).toBeLessThanOrEqual(4096);
200+
const payload = request.payload as { aps: { "content-state": { props: string } } };
201+
const sent = JSON.parse(payload.aps["content-state"].props) as typeof longState;
202+
expect(sent.activities.map((row) => row.threadId)).toEqual(["a", "b", "c", "d", "e"]);
203+
expect(sent.activities[0]?.threadTitle).toMatch(/^界+\.\.\.$/);
204+
}).pipe(Effect.provide(layerTest)),
205+
);
206+
207+
it.effect("fits Live Activity updates at every sanitizer cap within 4096 bytes", () =>
208+
Effect.gen(function* () {
209+
const apns = yield* ApnsClient.ApnsClient;
210+
const ids = ["a", "b", "c", "d", "e"];
211+
const cappedState = sanitizeAgentActivityAggregateState({
212+
...state,
213+
activeCount: 5,
214+
activities: ids.map((id) => ({
215+
...state.activities[0]!,
216+
threadId: ThreadId.make(id),
217+
projectTitle: "界".repeat(120),
218+
threadTitle: "界".repeat(120),
219+
deepLink: `/${"d".repeat(511)}`,
220+
})),
221+
});
222+
const alert = {
223+
title: "界".repeat(120),
224+
body: `Working: ${"界".repeat(120)}`,
225+
};
226+
227+
for (const event of ["update"] as const) {
228+
const request = apns.makeLiveActivityRequest({
229+
event,
230+
token: "token",
231+
state: cappedState,
232+
alert,
233+
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
234+
nowIso: DateTime.formatIso(now),
235+
});
236+
237+
expect(
238+
new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
239+
).toBeLessThanOrEqual(4096);
240+
const payload = request.payload as { aps: { "content-state": { props: string } } };
241+
const sent = JSON.parse(payload.aps["content-state"].props) as typeof cappedState;
242+
expect(sent.activities.length).toBeGreaterThan(0);
243+
expect(sent.activities.map((row) => row.threadId)).toEqual(
244+
ids.slice(0, sent.activities.length),
245+
);
246+
}
247+
}).pipe(Effect.provide(layerTest)),
248+
);
249+
172250
it.effect("reuses the signed provider JWT across pushes within the reuse window", () => {
173251
ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
174252
const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {

‎infra/relay/src/agentActivity/ApnsClient.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import * as Headers from "effect/http/Headers";
88
import * as HttpClient from "effect/http/HttpClient";
99
import * as HttpClientRequest from "effect/http/HttpClientRequest";
1010
import { ApnsEnvironment, type ApnsCredentials } from "../Config.ts";
11+
import { MAX_SUMMARY_TEXT_LENGTH, truncateText } from "./agentActivityPayloads.ts";
1112
import type { ApnsLiveActivityAlert, ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
1213
import type { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";
1314
import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
@@ -22,6 +23,8 @@ const STALE_AFTER_SECONDS = 10 * 60;
2223
const DISMISS_AFTER_SECONDS = 5 * 60;
2324
// Without final content, the card freezes at stale state; dismiss it promptly.
2425
const CONTENTLESS_DISMISS_AFTER_SECONDS = 15;
26+
const MAX_LIVE_ACTIVITY_PAYLOAD_BYTES = 4096;
27+
const MIN_FITTED_TEXT_LENGTH = 8;
2528

2629
const ApnsLiveActivityEventSchema = Schema.Literals(["update", "end"]);
2730
export type ApnsLiveActivityEvent = typeof ApnsLiveActivityEventSchema.Type;
@@ -111,7 +114,60 @@ function liveActivityAlertPayload(alert: ApnsLiveActivityAlert) {
111114
};
112115
}
113116

117+
// Text caps count characters, so multibyte titles can overflow APNs' 4 KB
118+
// limit. Shorten titles and alert text until the encoded payload fits. Links
119+
// and ids can't shrink, so if the shortest text still overflows, drop the last
120+
// (lowest-priority) row and fit again.
114121
function makeLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
122+
let request = buildLiveActivityRequest(input);
123+
const state = input.state;
124+
if (state === null) {
125+
return request;
126+
}
127+
const fit = (maxTextLength: number, rowCount: number) =>
128+
buildLiveActivityRequest({
129+
...input,
130+
state: {
131+
...state,
132+
activities: state.activities.slice(0, rowCount).map((row) => ({
133+
...row,
134+
projectTitle: truncateText(row.projectTitle, maxTextLength),
135+
threadTitle: truncateText(row.threadTitle, maxTextLength),
136+
modelTitle: truncateText(row.modelTitle, maxTextLength),
137+
})),
138+
},
139+
alert: input.alert
140+
? {
141+
title: truncateText(input.alert.title, maxTextLength),
142+
body: truncateText(input.alert.body, maxTextLength),
143+
}
144+
: null,
145+
});
146+
let rowCount = state.activities.length;
147+
let maxTextLength = MAX_SUMMARY_TEXT_LENGTH;
148+
while (
149+
!fitsLiveActivityLimit(request) &&
150+
(rowCount > 0 || maxTextLength > MIN_FITTED_TEXT_LENGTH)
151+
) {
152+
if (maxTextLength > MIN_FITTED_TEXT_LENGTH) {
153+
maxTextLength = Math.floor(maxTextLength * 0.8);
154+
} else {
155+
rowCount -= 1;
156+
maxTextLength = MAX_SUMMARY_TEXT_LENGTH;
157+
}
158+
request = fit(maxTextLength, rowCount);
159+
}
160+
return request;
161+
}
162+
163+
function fitsLiveActivityLimit(request: ApnsLiveActivityRequest): boolean {
164+
return (
165+
new TextEncoder().encode(JSON.stringify(request.payload)).byteLength <=
166+
MAX_LIVE_ACTIVITY_PAYLOAD_BYTES
167+
);
168+
}
169+
170+
function buildLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
115171
const timestamp = input.nowEpochSeconds;
116172
if (input.event === "end") {
117173
return {

‎infra/relay/src/agentActivity/agentActivityPayloads.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,13 @@ export function isExpiredAgentActivityState(
4141
return !Number.isFinite(expiresAt) || nowMs > expiresAt;
4242
}
4343

44-
const MAX_SUMMARY_TEXT_LENGTH = 120;
44+
export const MAX_SUMMARY_TEXT_LENGTH = 120;
4545
const MAX_STATUS_TEXT_LENGTH = 40;
4646
const MAX_DEEP_LINK_LENGTH = 512;
4747
// Banners render five rows; the expanded Dynamic Island shows the top three.
4848
export const MAX_ACTIVITY_ROWS = 5;
4949

50-
function truncateText(value: string, maxLength: number): string {
50+
export function truncateText(value: string, maxLength: number): string {
5151
const trimmed = value.trim();
5252
if (trimmed.length <= maxLength) {
5353
return trimmed;

0 commit comments

Comments
 (0)