Open History to see the last commit
1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
2import * as NodeCrypto from "node:crypto";
3β
4import { EnvironmentId, ThreadId } from "@t3tools/contracts";
5import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
6import { describe, expect, it } from "@effect/vitest";
7import * as Cause from "effect/Cause";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Layer from "effect/Layer";
12import * as Redacted from "effect/Redacted";
13import * as Tracer from "effect/Tracer";
14import * as HttpClient from "effect/http/HttpClient";
15import * as HttpClientError from "effect/http/HttpClientError";
16import * as HttpClientResponse from "effect/http/HttpClientResponse";
17β
18import type { ApnsCredentials } from "../Config.ts";
19import * as ApnsClient from "./ApnsClient.ts";
20import {
21 sanitizeAgentActivityAggregateState,
22 sanitizeApnsNotificationPayload,
23} from "./agentActivityPayloads.ts";
24import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
25β
26const layerTest = ApnsClient.layer.pipe(
27 Layer.provide(ApnsProviderTokens.layer),
28 Layer.provide(
29 Layer.succeed(
30 HttpClient.HttpClient,
31 HttpClient.make(() => Effect.die("unexpected APNs HTTP request")),
32 ),
33 ),
34);
35β
36describe("ApnsClient", () => {
37 const now = DateTime.makeUnsafe(0);
38 const state: RelayAgentActivityAggregateState = {
39 title: "T3 Code",
40 subtitle: "Agent work in progress",
41 activeCount: 1,
42 updatedAt: DateTime.formatIso(now),
43 activities: [
44 {
45 environmentId: EnvironmentId.make("env"),
46 threadId: ThreadId.make("thread"),
47 projectTitle: "Project",
48 threadTitle: "Thread",
49 modelTitle: "gpt-5.4",
50 phase: "running" as const,
51 status: "Working",
52 updatedAt: DateTime.formatIso(now),
53 deepLink: "/",
54 },
55 ],
56 };
57β
58 it.effect("builds a high-priority alerting update payload when an alert is attached", () =>
59 Effect.gen(function* () {
60 const apns = yield* ApnsClient.ApnsClient;
61 const request = apns.makeLiveActivityRequest({
62 event: "update",
63 token: "token",
64 state,
65 alert: { title: "Thread", body: "Approval: Project" },
66 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
67 nowIso: DateTime.formatIso(now),
68 });
69β
70 expect(request.priority).toBe("10");
71 expect(request.payload).toMatchObject({
72 aps: {
73 event: "update",
74 alert: {
75 title: "Thread",
76 body: "Approval: Project",
77 sound: "default",
78 },
79 },
80 });
81 }).pipe(Effect.provide(layerTest)),
82 );
83β
84 it.effect("builds an end payload with a dismissal date", () =>
85 Effect.gen(function* () {
86 const apns = yield* ApnsClient.ApnsClient;
87 const request = apns.makeLiveActivityRequest({
88 event: "end",
89 token: "token",
90 state,
91 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
92 nowIso: DateTime.formatIso(now),
93 });
94β
95 expect(request.priority).toBe("10");
96 expect(request.payload).toMatchObject({
97 aps: {
98 event: "end",
99 "dismissal-date": 300,
100 },
101 });
102β
103 const contentless = apns.makeLiveActivityRequest({
104 event: "end",
105 token: "token",
106 state: null,
107 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
108 nowIso: DateTime.formatIso(now),
109 });
110 expect(contentless.payload).toMatchObject({
111 aps: {
112 event: "end",
113 "dismissal-date": 15,
114 },
115 });
116 }).pipe(Effect.provide(layerTest)),
117 );
118β
119 it.effect("puts remote routing metadata only in Expo's body field", () =>
120 Effect.gen(function* () {
121 const apns = yield* ApnsClient.ApnsClient;
122 const request = apns.makePushNotificationRequest({
123 token: "push-token",
124 notification: {
125 title: "Thread",
126 body: "Input: Project",
127 environmentId: "env",
128 threadId: "thread",
129 deepLink: "/threads/env/thread",
130 },
131 });
132β
133 expect(request.priority).toBe("10");
134 expect(request.payload).toEqual({
135 aps: {
136 alert: {
137 title: "Thread",
138 body: "Input: Project",
139 },
140 sound: "default",
141 "thread-id": "env/thread",
142 },
143 body: {
144 environmentId: "env",
145 threadId: "thread",
146 deepLink: "/threads/env/thread",
147 },
148 });
149 }).pipe(Effect.provide(layerTest)),
150 );
151β
152 it.effect("fits long routing metadata and multibyte alerts within the APNs 4096-byte limit", () =>
153 Effect.gen(function* () {
154 const apns = yield* ApnsClient.ApnsClient;
155 const environmentId = "Γ©".repeat(191);
156 const threadId = "t".repeat(512);
157 const notification = sanitizeApnsNotificationPayload({
158 title: "π".repeat(120),
159 body: "η".repeat(120),
160 environmentId,
161 threadId,
162 deepLink: `/threads/${encodeURIComponent(environmentId)}/${threadId}`,
163 });
164 const request = apns.makePushNotificationRequest({ token: "push-token", notification });
165β
166 expect(notification.title).toBe(`${"π".repeat(58)}...`);
167β
168 expect(
169 new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
170 ).toBeLessThanOrEqual(4096);
171 expect(request.payload).toMatchObject({
172 body: {
173 environmentId,
174 threadId,
175 deepLink: notification.deepLink,
176 },
177 });
178 }).pipe(Effect.provide(layerTest)),
179 );
180β
181 it.effect("shortens multibyte row titles so Live Activity updates fit within 4096 bytes", () =>
182 Effect.gen(function* () {
183 const apns = yield* ApnsClient.ApnsClient;
184 const longState = sanitizeAgentActivityAggregateState({
185 ...state,
186 activeCount: 5,
187 activities: ["a", "b", "c", "d", "e"].map((id) => ({
188 ...state.activities[0]!,
189 threadId: ThreadId.make(id),
190 projectTitle: "η".repeat(200),
191 threadTitle: "η".repeat(200),
192 })),
193 });
194 const request = apns.makeLiveActivityRequest({
195 event: "update",
196 token: "token",
197 state: longState,
198 alert: { title: "η".repeat(120), body: "η".repeat(120) },
199 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
200 nowIso: DateTime.formatIso(now),
201 });
202β
203 expect(
204 new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
205 ).toBeLessThanOrEqual(4096);
206 const payload = request.payload as { aps: { "content-state": { props: string } } };
207 const sent = JSON.parse(payload.aps["content-state"].props) as typeof longState;
208 expect(sent.activities.map((row) => row.threadId)).toEqual(["a", "b", "c", "d", "e"]);
209 expect(sent.activities[0]?.threadTitle).toMatch(/^η+\.\.\.$/);
210 }).pipe(Effect.provide(layerTest)),
211 );
212β
213 it.effect("fits Live Activity updates at every sanitizer cap within 4096 bytes", () =>
214 Effect.gen(function* () {
215 const apns = yield* ApnsClient.ApnsClient;
216 const ids = ["a", "b", "c", "d", "e"];
217 const cappedState = sanitizeAgentActivityAggregateState({
218 ...state,
219 activeCount: 5,
220 activities: ids.map((id) => ({
221 ...state.activities[0]!,
222 threadId: ThreadId.make(id),
223 projectTitle: "η".repeat(120),
224 threadTitle: "η".repeat(120),
225 deepLink: `/${"d".repeat(511)}`,
226 })),
227 });
228 const alert = {
229 title: "η".repeat(120),
230 body: `Working: ${"η".repeat(120)}`,
231 };
232β
233 for (const event of ["update"] as const) {
234 const request = apns.makeLiveActivityRequest({
235 event,
236 token: "token",
237 state: cappedState,
238 alert,
239 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
240 nowIso: DateTime.formatIso(now),
241 });
242β
243 expect(
244 new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
245 ).toBeLessThanOrEqual(4096);
246 const payload = request.payload as { aps: { "content-state": { props: string } } };
247 const sent = JSON.parse(payload.aps["content-state"].props) as typeof cappedState;
248 expect(sent.activities.length).toBeGreaterThan(0);
249 expect(sent.activities.map((row) => row.threadId)).toEqual(
250 ids.slice(0, sent.activities.length),
251 );
252 }
253 }).pipe(Effect.provide(layerTest)),
254 );
255β
256 it.effect("reuses the signed provider JWT across pushes within the reuse window", () => {
257 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
258 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
259 namedCurve: "prime256v1",
260 privateKeyEncoding: { type: "pkcs8", format: "pem" },
261 publicKeyEncoding: { type: "spki", format: "pem" },
262 });
263 const credentials = {
264 teamId: "team-jwt-cache",
265 keyId: "key-jwt-cache",
266 privateKey: Redacted.make(privateKey),
267 bundleId: "com.t3tools.test",
268 environment: "sandbox",
269 } satisfies ApnsCredentials;
270 const authorizations: Array<string> = [];
271 const capturingHttpClient = HttpClient.make((request) => {
272 authorizations.push(request.headers.authorization ?? "");
273 return Effect.succeed(
274 HttpClientResponse.fromWeb(
275 request,
276 new Response("", { status: 200, headers: { "apns-id": "apns-id-1" } }),
277 ),
278 );
279 });
280 const layer = ApnsClient.layer.pipe(
281 Layer.provide(ApnsProviderTokens.layer),
282 Layer.provide(Layer.succeed(HttpClient.HttpClient, capturingHttpClient)),
283 );
284β
285 return Effect.gen(function* () {
286 const apns = yield* ApnsClient.ApnsClient;
287 const request = apns.makePushNotificationRequest({
288 token: "push-token",
289 notification: {
290 title: "Thread",
291 body: "Input: Project",
292 environmentId: "env",
293 threadId: "thread",
294 deepLink: "/threads/env/thread",
295 },
296 });
297 const send = (issuedAtUnixSeconds: number) =>
298 apns.sendPushNotificationRequest({ credentials, request, issuedAtUnixSeconds });
299β
300 const window = ApnsProviderTokens.APNS_JWT_REUSE_SECONDS;
301 yield* send(window + 10);
302 yield* send(window * 2 - 1);
303 yield* send(window * 2);
304β
305 expect(authorizations).toHaveLength(3);
306 expect(authorizations[1]).toBe(authorizations[0]);
307 expect(authorizations[2]).not.toBe(authorizations[0]);
308 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
309 }).pipe(Effect.provide(layer));
310 });
311β
312 it.effect("keeps device tokens out of spans, for delivered and failed requests", () => {
313 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
314 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
315 namedCurve: "prime256v1",
316 privateKeyEncoding: { type: "pkcs8", format: "pem" },
317 publicKeyEncoding: { type: "spki", format: "pem" },
318 });
319 const credentials = {
320 teamId: "team-spans",
321 keyId: "key-spans",
322 privateKey: Redacted.make(privateKey),
323 bundleId: "com.t3tools.test",
324 environment: "sandbox",
325 } satisfies ApnsCredentials;
326 const spans: Array<Tracer.NativeSpan> = [];
327 const tracer = Tracer.make({
328 span: (options) => {
329 const span = new Tracer.NativeSpan(options);
330 spans.push(span);
331 return span;
332 },
333 });
334 const urls: Array<string> = [];
335 let reachable = true;
336 const httpClient = HttpClient.make((request) => {
337 urls.push(request.url);
338 return reachable
339 ? Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 })))
340 : Effect.fail(
341 new HttpClientError.HttpClientError({
342 reason: new HttpClientError.TransportError({ request, cause: new Error("reset") }),
343 }),
344 );
345 });
346 const layer = ApnsClient.layer.pipe(
347 Layer.provide(ApnsProviderTokens.layer),
348 Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient)),
349 Layer.provideMerge(Layer.succeed(Tracer.Tracer, tracer)),
350 );
351β
352 return Effect.gen(function* () {
353 const apns = yield* ApnsClient.ApnsClient;
354 const sendBoth = Effect.all(
355 [
356 apns.sendLiveActivityRequest({
357 credentials,
358 request: apns.makeLiveActivityRequest({
359 event: "update",
360 token: "live-activity-device-token",
361 state,
362 nowEpochSeconds: 0,
363 nowIso: DateTime.formatIso(now),
364 }),
365 issuedAtUnixSeconds: 0,
366 }),
367 apns.sendPushNotificationRequest({
368 credentials,
369 request: apns.makePushNotificationRequest({
370 token: "push-notification-device-token",
371 notification: {
372 title: "Thread",
373 body: "Input: Project",
374 environmentId: "env",
375 threadId: "thread",
376 deepLink: "/threads/env/thread",
377 },
378 }),
379 issuedAtUnixSeconds: 0,
380 }),
381 ],
382 { mode: "result" },
383 );
384β
385 yield* sendBoth;
386 reachable = false;
387 yield* sendBoth;
388β
389 expect(urls).toHaveLength(4);
390 expect(urls[0]).toContain("live-activity-device-token");
391 expect(urls[1]).toContain("push-notification-device-token");
392 const recorded = spans
393 .flatMap((span) => [
394 span.name,
395 ...Array.from(span.attributes.values(), String),
396 ...(span.status._tag === "Ended" && Exit.isFailure(span.status.exit)
397 ? [Cause.pretty(span.status.exit.cause)]
398 : []),
399 ])
400 .join("\n");
401 expect(recorded).toContain("relay.apns.send_live_activity_request");
402 expect(recorded).toContain("ApnsHttpRequestError");
403 expect(recorded).not.toContain("device-token");
404 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
405 }).pipe(Effect.provide(layer));
406 });
407});