Skip to content
TypeScript

fix(relay): long CJK titles no longer stop Live Activity updates (#24679)

Victor Vogelc6bde56f1ef5
diff --git a/infra/relay/src/agentActivity/ApnsClient.test.ts b/infra/relay/src/agentActivity/ApnsClient.test.ts
index fd0d56ede1c..81e76b0391a 100644
--- a/infra/relay/src/agentActivity/ApnsClient.test.ts
+++ b/infra/relay/src/agentActivity/ApnsClient.test.ts
@@ -13,7 +13,10 @@ import * as HttpClientResponse from "effect/http/HttpClientResponse";
import type { ApnsCredentials } from "../Config.ts";
import * as ApnsClient from "./ApnsClient.ts";
-import { sanitizeApnsNotificationPayload } from "./agentActivityPayloads.ts";
+import {
+ sanitizeAgentActivityAggregateState,
+ sanitizeApnsNotificationPayload,
+} from "./agentActivityPayloads.ts";
import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
const layerTest = ApnsClient.layer.pipe(
@@ -169,6 +172,81 @@ describe("ApnsClient", () => {
}).pipe(Effect.provide(layerTest)),
);
+ it.effect("shortens multibyte row titles so Live Activity updates fit within 4096 bytes", () =>
+ Effect.gen(function* () {
+ const apns = yield* ApnsClient.ApnsClient;
+ const longState = sanitizeAgentActivityAggregateState({
+ ...state,
+ activeCount: 5,
+ activities: ["a", "b", "c", "d", "e"].map((id) => ({
+ ...state.activities[0]!,
+ threadId: ThreadId.make(id),
+ projectTitle: "界".repeat(200),
+ threadTitle: "界".repeat(200),
+ })),
+ });
+ const request = apns.makeLiveActivityRequest({
+ event: "update",
+ token: "token",
+ state: longState,
+ alert: { title: "界".repeat(120), body: "界".repeat(120) },
+ nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
+ nowIso: DateTime.formatIso(now),
+ });
+
+ expect(
+ new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
+ ).toBeLessThanOrEqual(4096);
+ const payload = request.payload as { aps: { "content-state": { props: string } } };
+ const sent = JSON.parse(payload.aps["content-state"].props) as typeof longState;
+ expect(sent.activities.map((row) => row.threadId)).toEqual(["a", "b", "c", "d", "e"]);
+ expect(sent.activities[0]?.threadTitle).toMatch(/^界+\.\.\.$/);
+ }).pipe(Effect.provide(layerTest)),
+ );
+
+ it.effect("fits Live Activity updates at every sanitizer cap within 4096 bytes", () =>
+ Effect.gen(function* () {
+ const apns = yield* ApnsClient.ApnsClient;
+ const ids = ["a", "b", "c", "d", "e"];
+ const cappedState = sanitizeAgentActivityAggregateState({
+ ...state,
+ activeCount: 5,
+ activities: ids.map((id) => ({
+ ...state.activities[0]!,
+ threadId: ThreadId.make(id),
+ projectTitle: "界".repeat(120),
+ threadTitle: "界".repeat(120),
+ deepLink: `/${"d".repeat(511)}`,
+ })),
+ });
+ const alert = {
+ title: "界".repeat(120),
+ body: `Working: ${"界".repeat(120)}`,
+ };
+
+ for (const event of ["update"] as const) {
+ const request = apns.makeLiveActivityRequest({
+ event,
+ token: "token",
+ state: cappedState,
+ alert,
+ nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
+ nowIso: DateTime.formatIso(now),
+ });
+
+ expect(
+ new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
+ ).toBeLessThanOrEqual(4096);
+ const payload = request.payload as { aps: { "content-state": { props: string } } };
+ const sent = JSON.parse(payload.aps["content-state"].props) as typeof cappedState;
+ expect(sent.activities.length).toBeGreaterThan(0);
+ expect(sent.activities.map((row) => row.threadId)).toEqual(
+ ids.slice(0, sent.activities.length),
+ );
+ }
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect("reuses the signed provider JWT across pushes within the reuse window", () => {
ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
diff --git a/infra/relay/src/agentActivity/ApnsClient.ts b/infra/relay/src/agentActivity/ApnsClient.ts
index a076cca8ef1..b21953c59ee 100644
--- a/infra/relay/src/agentActivity/ApnsClient.ts
+++ b/infra/relay/src/agentActivity/ApnsClient.ts
@@ -8,6 +8,7 @@ import * as Headers from "effect/http/Headers";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientRequest from "effect/http/HttpClientRequest";
import { ApnsEnvironment, type ApnsCredentials } from "../Config.ts";
+import { MAX_SUMMARY_TEXT_LENGTH, truncateText } from "./agentActivityPayloads.ts";
import type { ApnsLiveActivityAlert, ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
import type { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";
import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
@@ -22,6 +23,8 @@ const STALE_AFTER_SECONDS = 10 * 60;
const DISMISS_AFTER_SECONDS = 5 * 60;
// Without final content, the card freezes at stale state; dismiss it promptly.
const CONTENTLESS_DISMISS_AFTER_SECONDS = 15;
+const MAX_LIVE_ACTIVITY_PAYLOAD_BYTES = 4096;
+const MIN_FITTED_TEXT_LENGTH = 8;
const ApnsLiveActivityEventSchema = Schema.Literals(["update", "end"]);
export type ApnsLiveActivityEvent = typeof ApnsLiveActivityEventSchema.Type;
@@ -111,7 +114,60 @@ function liveActivityAlertPayload(alert: ApnsLiveActivityAlert) {
};
}
+// Text caps count characters, so multibyte titles can overflow APNs' 4 KB
+// limit. Shorten titles and alert text until the encoded payload fits. Links
+// and ids can't shrink, so if the shortest text still overflows, drop the last
+// (lowest-priority) row and fit again.
function makeLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
+ let request = buildLiveActivityRequest(input);
+ const state = input.state;
+ if (state === null) {
+ return request;
+ }
+ const fit = (maxTextLength: number, rowCount: number) =>
+ buildLiveActivityRequest({
+ ...input,
+ state: {
+ ...state,
+ activities: state.activities.slice(0, rowCount).map((row) => ({
+ ...row,
+ projectTitle: truncateText(row.projectTitle, maxTextLength),
+ threadTitle: truncateText(row.threadTitle, maxTextLength),
+ modelTitle: truncateText(row.modelTitle, maxTextLength),
+ })),
+ },
+ alert: input.alert
+ ? {
+ title: truncateText(input.alert.title, maxTextLength),
+ body: truncateText(input.alert.body, maxTextLength),
+ }
+ : null,
+ });
+ let rowCount = state.activities.length;
+ let maxTextLength = MAX_SUMMARY_TEXT_LENGTH;
+ while (
+ !fitsLiveActivityLimit(request) &&
+ (rowCount > 0 || maxTextLength > MIN_FITTED_TEXT_LENGTH)
+ ) {
+ if (maxTextLength > MIN_FITTED_TEXT_LENGTH) {
+ maxTextLength = Math.floor(maxTextLength * 0.8);
+ } else {
+ rowCount -= 1;
+ maxTextLength = MAX_SUMMARY_TEXT_LENGTH;
+ }
+ request = fit(maxTextLength, rowCount);
+ }
+ return request;
+}
+
+function fitsLiveActivityLimit(request: ApnsLiveActivityRequest): boolean {
+ return (
+ new TextEncoder().encode(JSON.stringify(request.payload)).byteLength <=
+ MAX_LIVE_ACTIVITY_PAYLOAD_BYTES
+ );
+}
+
+function buildLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
const timestamp = input.nowEpochSeconds;
if (input.event === "end") {
return {
diff --git a/infra/relay/src/agentActivity/agentActivityPayloads.ts b/infra/relay/src/agentActivity/agentActivityPayloads.ts
index b2086426a9e..4195c811718 100644
--- a/infra/relay/src/agentActivity/agentActivityPayloads.ts
+++ b/infra/relay/src/agentActivity/agentActivityPayloads.ts
@@ -41,13 +41,13 @@ export function isExpiredAgentActivityState(
return !Number.isFinite(expiresAt) || nowMs > expiresAt;
}
-const MAX_SUMMARY_TEXT_LENGTH = 120;
+export const MAX_SUMMARY_TEXT_LENGTH = 120;
const MAX_STATUS_TEXT_LENGTH = 40;
const MAX_DEEP_LINK_LENGTH = 512;
// Banners render five rows; the expanded Dynamic Island shows the top three.
export const MAX_ACTIVITY_ROWS = 5;
-function truncateText(value: string, maxLength: number): string {
+export function truncateText(value: string, maxLength: number): string {
const trimmed = value.trim();
if (trimmed.length <= maxLength) {
return trimmed;