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 DateTime from "effect/DateTime";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Redacted from "effect/Redacted";
11import * as HttpClient from "effect/http/HttpClient";
12import * as HttpClientResponse from "effect/http/HttpClientResponse";
13
14import type { ApnsCredentials } from "../Config.ts";
15import * as ApnsClient from "./ApnsClient.ts";
16import {
17 sanitizeAgentActivityAggregateState,
18 sanitizeApnsNotificationPayload,
19} from "./agentActivityPayloads.ts";
20import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
21
22const layerTest = ApnsClient.layer.pipe(
23 Layer.provide(ApnsProviderTokens.layer),
24 Layer.provide(
25 Layer.succeed(
26 HttpClient.HttpClient,
27 HttpClient.make(() => Effect.die("unexpected APNs HTTP request")),
28 ),
29 ),
30);
31
32describe("ApnsClient", () => {
33 const now = DateTime.makeUnsafe(0);
34 const state: RelayAgentActivityAggregateState = {
35 title: "T3 Code",
36 subtitle: "Agent work in progress",
37 activeCount: 1,
38 updatedAt: DateTime.formatIso(now),
39 activities: [
40 {
41 environmentId: EnvironmentId.make("env"),
42 threadId: ThreadId.make("thread"),
43 projectTitle: "Project",
44 threadTitle: "Thread",
45 modelTitle: "gpt-5.4",
46 phase: "running" as const,
47 status: "Working",
48 updatedAt: DateTime.formatIso(now),
49 deepLink: "/",
50 },
51 ],
52 };
53
54 it.effect("builds a high-priority alerting update payload when an alert is attached", () =>
55 Effect.gen(function* () {
56 const apns = yield* ApnsClient.ApnsClient;
57 const request = apns.makeLiveActivityRequest({
58 event: "update",
59 token: "token",
60 state,
61 alert: { title: "Thread", body: "Approval: Project" },
62 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
63 nowIso: DateTime.formatIso(now),
64 });
65
66 expect(request.priority).toBe("10");
67 expect(request.payload).toMatchObject({
68 aps: {
69 event: "update",
70 alert: {
71 title: "Thread",
72 body: "Approval: Project",
73 sound: "default",
74 },
75 },
76 });
77 }).pipe(Effect.provide(layerTest)),
78 );
79
80 it.effect("builds an end payload with a dismissal date", () =>
81 Effect.gen(function* () {
82 const apns = yield* ApnsClient.ApnsClient;
83 const request = apns.makeLiveActivityRequest({
84 event: "end",
85 token: "token",
86 state,
87 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
88 nowIso: DateTime.formatIso(now),
89 });
90
91 expect(request.priority).toBe("10");
92 expect(request.payload).toMatchObject({
93 aps: {
94 event: "end",
95 "dismissal-date": 300,
96 },
97 });
98
99 const contentless = apns.makeLiveActivityRequest({
100 event: "end",
101 token: "token",
102 state: null,
103 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
104 nowIso: DateTime.formatIso(now),
105 });
106 expect(contentless.payload).toMatchObject({
107 aps: {
108 event: "end",
109 "dismissal-date": 15,
110 },
111 });
112 }).pipe(Effect.provide(layerTest)),
113 );
114
115 it.effect("puts remote routing metadata only in Expo's body field", () =>
116 Effect.gen(function* () {
117 const apns = yield* ApnsClient.ApnsClient;
118 const request = apns.makePushNotificationRequest({
119 token: "push-token",
120 notification: {
121 title: "Thread",
122 body: "Input: Project",
123 environmentId: "env",
124 threadId: "thread",
125 deepLink: "/threads/env/thread",
126 },
127 });
128
129 expect(request.priority).toBe("10");
130 expect(request.payload).toEqual({
131 aps: {
132 alert: {
133 title: "Thread",
134 body: "Input: Project",
135 },
136 sound: "default",
137 "thread-id": "env/thread",
138 },
139 body: {
140 environmentId: "env",
141 threadId: "thread",
142 deepLink: "/threads/env/thread",
143 },
144 });
145 }).pipe(Effect.provide(layerTest)),
146 );
147
148 it.effect("fits long routing metadata and multibyte alerts within the APNs 4096-byte limit", () =>
149 Effect.gen(function* () {
150 const apns = yield* ApnsClient.ApnsClient;
151 const environmentId = "é".repeat(191);
152 const threadId = "t".repeat(512);
153 const notification = sanitizeApnsNotificationPayload({
154 title: "😀".repeat(120),
155 body: "界".repeat(120),
156 environmentId,
157 threadId,
158 deepLink: `/threads/${encodeURIComponent(environmentId)}/${threadId}`,
159 });
160 const request = apns.makePushNotificationRequest({ token: "push-token", notification });
161
162 expect(notification.title).toBe(`${"😀".repeat(58)}...`);
163
164 expect(
165 new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
166 ).toBeLessThanOrEqual(4096);
167 expect(request.payload).toMatchObject({
168 body: {
169 environmentId,
170 threadId,
171 deepLink: notification.deepLink,
172 },
173 });
174 }).pipe(Effect.provide(layerTest)),
175 );
176
177 it.effect("shortens multibyte row titles so Live Activity updates fit within 4096 bytes", () =>
178 Effect.gen(function* () {
179 const apns = yield* ApnsClient.ApnsClient;
180 const longState = sanitizeAgentActivityAggregateState({
181 ...state,
182 activeCount: 5,
183 activities: ["a", "b", "c", "d", "e"].map((id) => ({
184 ...state.activities[0]!,
185 threadId: ThreadId.make(id),
186 projectTitle: "界".repeat(200),
187 threadTitle: "界".repeat(200),
188 })),
189 });
190 const request = apns.makeLiveActivityRequest({
191 event: "update",
192 token: "token",
193 state: longState,
194 alert: { title: "界".repeat(120), body: "界".repeat(120) },
195 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
196 nowIso: DateTime.formatIso(now),
197 });
198
199 expect(
200 new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
201 ).toBeLessThanOrEqual(4096);
202 const payload = request.payload as { aps: { "content-state": { props: string } } };
203 const sent = JSON.parse(payload.aps["content-state"].props) as typeof longState;
204 expect(sent.activities.map((row) => row.threadId)).toEqual(["a", "b", "c", "d", "e"]);
205 expect(sent.activities[0]?.threadTitle).toMatch(/^界+\.\.\.$/);
206 }).pipe(Effect.provide(layerTest)),
207 );
208
209 it.effect("fits Live Activity updates at every sanitizer cap within 4096 bytes", () =>
210 Effect.gen(function* () {
211 const apns = yield* ApnsClient.ApnsClient;
212 const ids = ["a", "b", "c", "d", "e"];
213 const cappedState = sanitizeAgentActivityAggregateState({
214 ...state,
215 activeCount: 5,
216 activities: ids.map((id) => ({
217 ...state.activities[0]!,
218 threadId: ThreadId.make(id),
219 projectTitle: "界".repeat(120),
220 threadTitle: "界".repeat(120),
221 deepLink: `/${"d".repeat(511)}`,
222 })),
223 });
224 const alert = {
225 title: "界".repeat(120),
226 body: `Working: ${"界".repeat(120)}`,
227 };
228
229 for (const event of ["update"] as const) {
230 const request = apns.makeLiveActivityRequest({
231 event,
232 token: "token",
233 state: cappedState,
234 alert,
235 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
236 nowIso: DateTime.formatIso(now),
237 });
238
239 expect(
240 new TextEncoder().encode(JSON.stringify(request.payload)).byteLength,
241 ).toBeLessThanOrEqual(4096);
242 const payload = request.payload as { aps: { "content-state": { props: string } } };
243 const sent = JSON.parse(payload.aps["content-state"].props) as typeof cappedState;
244 expect(sent.activities.length).toBeGreaterThan(0);
245 expect(sent.activities.map((row) => row.threadId)).toEqual(
246 ids.slice(0, sent.activities.length),
247 );
248 }
249 }).pipe(Effect.provide(layerTest)),
250 );
251
252 it.effect("reuses the signed provider JWT across pushes within the reuse window", () => {
253 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
254 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
255 namedCurve: "prime256v1",
256 privateKeyEncoding: { type: "pkcs8", format: "pem" },
257 publicKeyEncoding: { type: "spki", format: "pem" },
258 });
259 const credentials = {
260 teamId: "team-jwt-cache",
261 keyId: "key-jwt-cache",
262 privateKey: Redacted.make(privateKey),
263 bundleId: "com.t3tools.test",
264 environment: "sandbox",
265 } satisfies ApnsCredentials;
266 const authorizations: Array<string> = [];
267 const capturingHttpClient = HttpClient.make((request) => {
268 authorizations.push(request.headers.authorization ?? "");
269 return Effect.succeed(
270 HttpClientResponse.fromWeb(
271 request,
272 new Response("", { status: 200, headers: { "apns-id": "apns-id-1" } }),
273 ),
274 );
275 });
276 const layer = ApnsClient.layer.pipe(
277 Layer.provide(ApnsProviderTokens.layer),
278 Layer.provide(Layer.succeed(HttpClient.HttpClient, capturingHttpClient)),
279 );
280
281 return Effect.gen(function* () {
282 const apns = yield* ApnsClient.ApnsClient;
283 const request = apns.makePushNotificationRequest({
284 token: "push-token",
285 notification: {
286 title: "Thread",
287 body: "Input: Project",
288 environmentId: "env",
289 threadId: "thread",
290 deepLink: "/threads/env/thread",
291 },
292 });
293 const send = (issuedAtUnixSeconds: number) =>
294 apns.sendPushNotificationRequest({ credentials, request, issuedAtUnixSeconds });
295
296 const window = ApnsProviderTokens.APNS_JWT_REUSE_SECONDS;
297 yield* send(window + 10);
298 yield* send(window * 2 - 1);
299 yield* send(window * 2);
300
301 expect(authorizations).toHaveLength(3);
302 expect(authorizations[1]).toBe(authorizations[0]);
303 expect(authorizations[2]).not.toBe(authorizations[0]);
304 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
305 }).pipe(Effect.provide(layer));
306 });
307});