Open History to see the last commit
1import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as Headers from "effect/http/Headers";
8import * as HttpClient from "effect/http/HttpClient";
9import * as HttpClientError from "effect/http/HttpClientError";
10import * as HttpClientRequest from "effect/http/HttpClientRequest";
11import { ApnsEnvironment, type ApnsCredentials } from "../Config.ts";
12import { MAX_SUMMARY_TEXT_LENGTH, truncateText } from "./agentActivityPayloads.ts";
13import type { ApnsLiveActivityAlert, ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";
14import type { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";
15import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
16
17export { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";
18
19const LIVE_ACTIVITY_NAME = "AgentActivity";
20// Bound sending and reading separately so neither stage can hold a batch open.
21const APNS_HTTP_STAGE_TIMEOUT = "10 seconds";
22// Event-only updates can leave healthy agents silent for minutes.
23const STALE_AFTER_SECONDS = 10 * 60;
24const DISMISS_AFTER_SECONDS = 5 * 60;
25// Without final content, the card freezes at stale state; dismiss it promptly.
26const CONTENTLESS_DISMISS_AFTER_SECONDS = 15;
27const MAX_LIVE_ACTIVITY_PAYLOAD_BYTES = 4096;
28const MIN_FITTED_TEXT_LENGTH = 8;
29
30const ApnsLiveActivityEventSchema = Schema.Literals(["update", "end"]);
31export type ApnsLiveActivityEvent = typeof ApnsLiveActivityEventSchema.Type;
32
33const ApnsRequestKindSchema = Schema.Literals(["live-activity", "push-notification"]);
34
35interface ApnsLiveActivityRequest {
36 readonly token: string;
37 readonly event: ApnsLiveActivityEvent;
38 readonly priority: "5" | "10";
39 readonly payload: unknown;
40}
41
42interface ApnsPushNotificationRequest {
43 readonly token: string;
44 readonly priority: "10";
45 readonly payload: unknown;
46}
47
48export interface ApnsDeliveryResult {
49 readonly ok: boolean;
50 readonly status: number;
51 readonly reason?: string;
52 readonly apnsId: string | null;
53}
54
55export class ApnsHttpRequestError extends Schema.TaggedError<ApnsHttpRequestError>()(
56 "ApnsHttpRequestError",
57 {
58 requestKind: ApnsRequestKindSchema,
59 event: Schema.NullOr(ApnsLiveActivityEventSchema),
60 environment: ApnsEnvironment,
61 bundleId: Schema.String,
62 tokenSuffix: Schema.String,
63 stage: Schema.Literals(["send", "read-response"]),
64 status: Schema.NullOr(Schema.Number),
65 cause: Schema.Defect(),
66 },
67) {
68 override get message(): string {
69 return `APNs ${this.requestKind} request failed during ${this.stage} in ${this.environment}.`;
70 }
71}
72
73export type ApnsError = ApnsJwtEncodingError | ApnsJwtSigningError | ApnsHttpRequestError;
74
75const decodeApnsErrorResponseJson = Schema.decodeUnknownOption(
76 Schema.fromJsonString(
77 Schema.Struct({
78 reason: Schema.optional(Schema.String),
79 }),
80 ),
81);
82function contentState(state: RelayAgentActivityAggregateState) {
83 return {
84 name: LIVE_ACTIVITY_NAME,
85 props: JSON.stringify(state),
86 };
87}
88
89interface LiveActivityRequestBase {
90 readonly token: string;
91 readonly nowEpochSeconds: number;
92 readonly nowIso: string;
93}
94
95type MakeLiveActivityRequestInput =
96 | (LiveActivityRequestBase & {
97 readonly event: "end";
98 readonly state: RelayAgentActivityAggregateState | null;
99 readonly alert?: ApnsLiveActivityAlert | null;
100 })
101 | (LiveActivityRequestBase & {
102 readonly event: "update";
103 readonly state: RelayAgentActivityAggregateState;
104 readonly alert?: ApnsLiveActivityAlert | null;
105 });
106
107// Alert dictionaries wake the iOS screen and trigger haptics instead of silently refreshing.
108function liveActivityAlertPayload(alert: ApnsLiveActivityAlert) {
109 return {
110 alert: {
111 title: alert.title,
112 body: alert.body,
113 sound: "default",
114 },
115 };
116}
117
118// Text caps count characters, so multibyte titles can overflow APNs' 4 KB
119// limit. Shorten titles and alert text until the encoded payload fits. Links
120// and ids can't shrink, so if the shortest text still overflows, drop the last
121// (lowest-priority) row and fit again.
122function makeLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
123 let request = buildLiveActivityRequest(input);
124 const state = input.state;
125 if (state === null) {
126 return request;
127 }
128 const fit = (maxTextLength: number, rowCount: number) =>
129 buildLiveActivityRequest({
130 ...input,
131 state: {
132 ...state,
133 activities: state.activities.slice(0, rowCount).map((row) => ({
134 ...row,
135 projectTitle: truncateText(row.projectTitle, maxTextLength),
136 threadTitle: truncateText(row.threadTitle, maxTextLength),
137 modelTitle: truncateText(row.modelTitle, maxTextLength),
138 })),
139 },
140 alert: input.alert
141 ? {
142 title: truncateText(input.alert.title, maxTextLength),
143 body: truncateText(input.alert.body, maxTextLength),
144 }
145 : null,
146 });
147 let rowCount = state.activities.length;
148 let maxTextLength = MAX_SUMMARY_TEXT_LENGTH;
149 while (
150 !fitsLiveActivityLimit(request) &&
151 (rowCount > 0 || maxTextLength > MIN_FITTED_TEXT_LENGTH)
152 ) {
153 if (maxTextLength > MIN_FITTED_TEXT_LENGTH) {
154 maxTextLength = Math.floor(maxTextLength * 0.8);
155 } else {
156 rowCount -= 1;
157 maxTextLength = MAX_SUMMARY_TEXT_LENGTH;
158 }
159 request = fit(maxTextLength, rowCount);
160 }
161 return request;
162}
163
164function fitsLiveActivityLimit(request: ApnsLiveActivityRequest): boolean {
165 return (
166 new TextEncoder().encode(JSON.stringify(request.payload)).byteLength <=
167 MAX_LIVE_ACTIVITY_PAYLOAD_BYTES
168 );
169}
170
171function buildLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {
172 const timestamp = input.nowEpochSeconds;
173 if (input.event === "end") {
174 return {
175 token: input.token,
176 event: input.event,
177 priority: "10",
178 payload: {
179 aps: {
180 timestamp,
181 event: "end",
182 ...(input.state ? { "content-state": contentState(input.state) } : {}),
183 ...(input.alert ? liveActivityAlertPayload(input.alert) : {}),
184 "dismissal-date":
185 timestamp + (input.state ? DISMISS_AFTER_SECONDS : CONTENTLESS_DISMISS_AFTER_SECONDS),
186 },
187 },
188 };
189 }
190
191 const state = input.state;
192 return {
193 token: input.token,
194 event: input.event,
195 priority: input.event === "update" && !input.alert ? "5" : "10",
196 payload: {
197 aps: {
198 timestamp,
199 event: input.event,
200 ...(input.event === "update" && input.alert ? liveActivityAlertPayload(input.alert) : {}),
201 "content-state": contentState(state),
202 "stale-date": timestamp + STALE_AFTER_SECONDS,
203 },
204 },
205 };
206}
207
208function notificationThreadId(notification: ApnsNotificationPayload): string {
209 return notification.threadId.length > 0
210 ? `${notification.environmentId}/${notification.threadId}`
211 : "t3-agent-alerts";
212}
213
214function makePushNotificationRequest(input: {
215 readonly token: string;
216 readonly notification: ApnsNotificationPayload;
217}): ApnsPushNotificationRequest {
218 return {
219 token: input.token,
220 priority: "10",
221 payload: {
222 aps: {
223 alert: {
224 title: input.notification.title,
225 body: input.notification.body,
226 },
227 sound: "default",
228 "thread-id": notificationThreadId(input.notification),
229 },
230 // Expo iOS exposes userInfo.body as notification.content.data for remote pushes.
231 body: {
232 environmentId: input.notification.environmentId,
233 threadId: input.notification.threadId,
234 deepLink: input.notification.deepLink,
235 },
236 },
237 };
238}
239
240// The request URL ends in the device token. The client span records the URL,
241// and so does an HTTP client error's message, so neither reaches telemetry.
242const withoutClientSpan = Effect.provideService(HttpClient.TracerDisabledWhen, () => true);
243
244function causeWithoutRequestUrl(cause: unknown): unknown {
245 return HttpClientError.isHttpClientError(cause)
246 ? new Error(cause.reason._tag, { cause: cause.reason.cause })
247 : cause;
248}
249
250function apnsReasonFromBody(body: string): string | undefined {
251 if (body.trim().length === 0) {
252 return undefined;
253 }
254 return Option.match(decodeApnsErrorResponseJson(body), {
255 onNone: () => body,
256 onSome: (parsed) => parsed.reason ?? body,
257 });
258}
259
260export class ApnsClient extends Context.Service<
261 ApnsClient,
262 {
263 readonly makeLiveActivityRequest: typeof makeLiveActivityRequest;
264 readonly makePushNotificationRequest: typeof makePushNotificationRequest;
265 readonly sendLiveActivityRequest: (input: {
266 readonly credentials: ApnsCredentials;
267 readonly request: ApnsLiveActivityRequest;
268 readonly issuedAtUnixSeconds: number;
269 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
270 readonly sendPushNotificationRequest: (input: {
271 readonly credentials: ApnsCredentials;
272 readonly request: ApnsPushNotificationRequest;
273 readonly issuedAtUnixSeconds: number;
274 }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;
275 }
276>()("t3code-relay/agentActivity/ApnsClient") {}
277
278const make = Effect.gen(function* () {
279 const httpClient = yield* HttpClient.HttpClient;
280 const providerTokens = yield* ApnsProviderTokens.ApnsProviderTokens;
281
282 const sendLiveActivityRequest: ApnsClient["Service"]["sendLiveActivityRequest"] = Effect.fn(
283 "relay.apns.send_live_activity_request",
284 )(function* (input) {
285 yield* Effect.annotateCurrentSpan({ "relay.apns.event": input.request.event });
286 const jwt = yield* providerTokens.getJwt({
287 ...input.credentials,
288 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
289 });
290 const host =
291 input.credentials.environment === "production"
292 ? "https://api.push.apple.com"
293 : "https://api.sandbox.push.apple.com";
294 const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe(
295 HttpClientRequest.setHeaders({
296 authorization: `bearer ${jwt}`,
297 "apns-priority": input.request.priority,
298 "apns-push-type": "liveactivity",
299 "apns-topic": `${input.credentials.bundleId}.push-type.liveactivity`,
300 }),
301 HttpClientRequest.bodyJson(input.request.payload),
302 Effect.flatMap(httpClient.execute),
303 withoutClientSpan,
304 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
305 Effect.mapError(
306 (cause) =>
307 new ApnsHttpRequestError({
308 requestKind: "live-activity",
309 event: input.request.event,
310 environment: input.credentials.environment,
311 bundleId: input.credentials.bundleId,
312 tokenSuffix: input.request.token.slice(-8),
313 stage: "send",
314 status: null,
315 cause: causeWithoutRequestUrl(cause),
316 }),
317 ),
318 );
319 const responseText = yield* response.text.pipe(
320 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
321 Effect.mapError(
322 (cause) =>
323 new ApnsHttpRequestError({
324 requestKind: "live-activity",
325 event: input.request.event,
326 environment: input.credentials.environment,
327 bundleId: input.credentials.bundleId,
328 tokenSuffix: input.request.token.slice(-8),
329 stage: "read-response",
330 status: response.status,
331 cause: causeWithoutRequestUrl(cause),
332 }),
333 ),
334 );
335 const reason = apnsReasonFromBody(responseText);
336 return {
337 ok: response.status >= 200 && response.status < 300,
338 status: response.status,
339 ...(reason === undefined ? {} : { reason }),
340 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
341 };
342 });
343
344 const sendPushNotificationRequest: ApnsClient["Service"]["sendPushNotificationRequest"] =
345 Effect.fn("relay.apns.send_push_notification_request")(function* (input) {
346 yield* Effect.annotateCurrentSpan({ "relay.apns.event": "push_notification" });
347 const jwt = yield* providerTokens.getJwt({
348 ...input.credentials,
349 issuedAtUnixSeconds: input.issuedAtUnixSeconds,
350 });
351 const host =
352 input.credentials.environment === "production"
353 ? "https://api.push.apple.com"
354 : "https://api.sandbox.push.apple.com";
355 const response = yield* HttpClientRequest.post(
356 `${host}/3/device/${input.request.token}`,
357 ).pipe(
358 HttpClientRequest.setHeaders({
359 authorization: `bearer ${jwt}`,
360 "apns-priority": input.request.priority,
361 "apns-push-type": "alert",
362 "apns-topic": input.credentials.bundleId,
363 }),
364 HttpClientRequest.bodyJson(input.request.payload),
365 Effect.flatMap(httpClient.execute),
366 withoutClientSpan,
367 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
368 Effect.mapError(
369 (cause) =>
370 new ApnsHttpRequestError({
371 requestKind: "push-notification",
372 event: null,
373 environment: input.credentials.environment,
374 bundleId: input.credentials.bundleId,
375 tokenSuffix: input.request.token.slice(-8),
376 stage: "send",
377 status: null,
378 cause: causeWithoutRequestUrl(cause),
379 }),
380 ),
381 );
382 const responseText = yield* response.text.pipe(
383 Effect.timeout(APNS_HTTP_STAGE_TIMEOUT),
384 Effect.mapError(
385 (cause) =>
386 new ApnsHttpRequestError({
387 requestKind: "push-notification",
388 event: null,
389 environment: input.credentials.environment,
390 bundleId: input.credentials.bundleId,
391 tokenSuffix: input.request.token.slice(-8),
392 stage: "read-response",
393 status: response.status,
394 cause: causeWithoutRequestUrl(cause),
395 }),
396 ),
397 );
398 const reason = apnsReasonFromBody(responseText);
399 return {
400 ok: response.status >= 200 && response.status < 300,
401 status: response.status,
402 ...(reason === undefined ? {} : { reason }),
403 apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),
404 };
405 });
406
407 return ApnsClient.of({
408 makeLiveActivityRequest,
409 makePushNotificationRequest,
410 sendLiveActivityRequest,
411 sendPushNotificationRequest,
412 });
413});
414
415export const layer = Layer.effect(ApnsClient, make);