Open History to see the last commit
1import * as NodeCrypto from "node:crypto";
2
3import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
5import { describe, expect, it } from "@effect/vitest";
6import * as DateTime from "effect/DateTime";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as Layer from "effect/Layer";
11import * as Redacted from "effect/Redacted";
12import * as Schema from "effect/Schema";
13import * as TestClock from "effect/testing/TestClock";
14import * as HttpClient from "effect/unstable/http/HttpClient";
15import * as HttpClientError from "effect/unstable/http/HttpClientError";
16import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
17
18import type { ApnsCredentials } from "../Config.ts";
19import * as ApnsClient from "./ApnsClient.ts";
20import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
21
22const isApnsJwtSigningError = Schema.is(ApnsClient.ApnsJwtSigningError);
23const isApnsHttpRequestError = Schema.is(ApnsClient.ApnsHttpRequestError);
24
25const TestLayer = ApnsClient.layer.pipe(
26 Layer.provide(ApnsProviderTokens.layer),
27 Layer.provide(
28 Layer.succeed(
29 HttpClient.HttpClient,
30 HttpClient.make(() => Effect.die("unexpected APNs HTTP request")),
31 ),
32 ),
33);
34
35describe("ApnsClient", () => {
36 const now = DateTime.makeUnsafe(0);
37 const state: RelayAgentActivityAggregateState = {
38 title: "T3 Code",
39 subtitle: "Agent work in progress",
40 activeCount: 1,
41 updatedAt: DateTime.formatIso(now),
42 activities: [
43 {
44 environmentId: EnvironmentId.make("env"),
45 threadId: ThreadId.make("thread"),
46 projectTitle: "Project",
47 threadTitle: "Thread",
48 modelTitle: "gpt-5.4",
49 phase: "running" as const,
50 status: "Working",
51 updatedAt: DateTime.formatIso(now),
52 deepLink: "/",
53 },
54 ],
55 };
56
57 it.effect("requests an update push token when remotely starting a Live Activity", () =>
58 Effect.gen(function* () {
59 const apns = yield* ApnsClient.ApnsClient;
60 const request = apns.makeLiveActivityRequest({
61 event: "start",
62 token: "token",
63 state,
64 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
65 nowIso: DateTime.formatIso(now),
66 });
67
68 expect(request.priority).toBe("10");
69 expect(request.payload).toMatchObject({
70 aps: {
71 event: "start",
72 "attributes-type": "LiveActivityAttributes",
73 "input-push-token": 1,
74 "content-state": {
75 name: "AgentActivity",
76 },
77 },
78 });
79 }).pipe(Effect.provide(TestLayer)),
80 );
81
82 it.effect("builds a low-priority update payload", () =>
83 Effect.gen(function* () {
84 const apns = yield* ApnsClient.ApnsClient;
85 const request = apns.makeLiveActivityRequest({
86 event: "update",
87 token: "token",
88 state,
89 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
90 nowIso: DateTime.formatIso(now),
91 });
92
93 expect(request.priority).toBe("5");
94 expect(request.payload).toMatchObject({
95 aps: {
96 event: "update",
97 "content-state": {
98 name: "AgentActivity",
99 },
100 },
101 });
102 }).pipe(Effect.provide(TestLayer)),
103 );
104
105 it.effect("builds a high-priority alerting update payload when an alert is attached", () =>
106 Effect.gen(function* () {
107 const apns = yield* ApnsClient.ApnsClient;
108 const request = apns.makeLiveActivityRequest({
109 event: "update",
110 token: "token",
111 state,
112 alert: { title: "Thread", body: "Approval: Project" },
113 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
114 nowIso: DateTime.formatIso(now),
115 });
116
117 expect(request.priority).toBe("10");
118 expect(request.payload).toMatchObject({
119 aps: {
120 event: "update",
121 alert: {
122 title: "Thread",
123 body: "Approval: Project",
124 sound: "default",
125 },
126 },
127 });
128 }).pipe(Effect.provide(TestLayer)),
129 );
130
131 it.effect("builds an end payload with a dismissal date", () =>
132 Effect.gen(function* () {
133 const apns = yield* ApnsClient.ApnsClient;
134 const request = apns.makeLiveActivityRequest({
135 event: "end",
136 token: "token",
137 state,
138 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
139 nowIso: DateTime.formatIso(now),
140 });
141
142 expect(request.priority).toBe("10");
143 expect(request.payload).toMatchObject({
144 aps: {
145 event: "end",
146 "dismissal-date": 300,
147 },
148 });
149
150 // Without final content the card would freeze on its previous state;
151 // contentless ends dismiss quickly instead.
152 const contentless = apns.makeLiveActivityRequest({
153 event: "end",
154 token: "token",
155 state: null,
156 nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
157 nowIso: DateTime.formatIso(now),
158 });
159 expect(contentless.payload).toMatchObject({
160 aps: {
161 event: "end",
162 "dismissal-date": 15,
163 },
164 });
165 }).pipe(Effect.provide(TestLayer)),
166 );
167
168 it.effect("builds a standard APNs alert payload with routing metadata", () =>
169 Effect.gen(function* () {
170 const apns = yield* ApnsClient.ApnsClient;
171 const request = apns.makePushNotificationRequest({
172 token: "push-token",
173 notification: {
174 title: "Thread",
175 body: "Input: Project",
176 environmentId: "env",
177 threadId: "thread",
178 deepLink: "/threads/env/thread",
179 },
180 });
181
182 expect(request.priority).toBe("10");
183 expect(request.payload).toMatchObject({
184 aps: {
185 alert: {
186 title: "Thread",
187 body: "Input: Project",
188 },
189 sound: "default",
190 "thread-id": "env/thread",
191 },
192 environmentId: "env",
193 threadId: "thread",
194 deepLink: "/threads/env/thread",
195 });
196 }).pipe(Effect.provide(TestLayer)),
197 );
198
199 it.effect("preserves JWT signing context and the crypto cause", () =>
200 Effect.gen(function* () {
201 const apns = yield* ApnsClient.ApnsClient;
202 const request = apns.makePushNotificationRequest({
203 token: "push-token",
204 notification: {
205 title: "Thread",
206 body: "Input: Project",
207 environmentId: "env",
208 threadId: "thread",
209 deepLink: "/threads/env/thread",
210 },
211 });
212 const error = yield* Effect.flip(
213 apns.sendPushNotificationRequest({
214 credentials: {
215 teamId: "team-1",
216 keyId: "key-1",
217 privateKey: Redacted.make("not-a-private-key"),
218 bundleId: "com.t3tools.test",
219 environment: "sandbox",
220 },
221 request,
222 issuedAtUnixSeconds: 123,
223 }),
224 );
225
226 expect(isApnsJwtSigningError(error)).toBe(true);
227 if (!isApnsJwtSigningError(error)) {
228 return yield* Effect.die("expected APNs JWT signing error");
229 }
230 expect(error).toMatchObject({
231 teamId: "team-1",
232 keyId: "key-1",
233 // The provider-token service quantizes iat to the reuse window, so
234 // the signing context carries the window start rather than the raw
235 // request time.
236 issuedAtUnixSeconds: 0,
237 cause: expect.any(Error),
238 message: "Failed to sign APNs JWT for key key-1.",
239 });
240 }).pipe(Effect.provide(TestLayer)),
241 );
242
243 it.effect("preserves APNs request context and the HTTP cause", () => {
244 const httpCause = new Error("network unavailable");
245 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
246 namedCurve: "prime256v1",
247 privateKeyEncoding: { type: "pkcs8", format: "pem" },
248 publicKeyEncoding: { type: "spki", format: "pem" },
249 });
250 const credentials = {
251 teamId: "team-1",
252 keyId: "key-1",
253 privateKey: Redacted.make(privateKey),
254 bundleId: "com.t3tools.test",
255 environment: "sandbox",
256 } satisfies ApnsCredentials;
257 const failingHttpClient = HttpClient.make((request) =>
258 Effect.fail(
259 new HttpClientError.HttpClientError({
260 reason: new HttpClientError.TransportError({ request, cause: httpCause }),
261 }),
262 ),
263 );
264 const layer = ApnsClient.layer.pipe(
265 Layer.provide(ApnsProviderTokens.layer),
266 Layer.provide(Layer.succeed(HttpClient.HttpClient, failingHttpClient)),
267 );
268
269 return Effect.gen(function* () {
270 const apns = yield* ApnsClient.ApnsClient;
271 const request = apns.makePushNotificationRequest({
272 token: "long-push-token",
273 notification: {
274 title: "Thread",
275 body: "Input: Project",
276 environmentId: "env",
277 threadId: "thread",
278 deepLink: "/threads/env/thread",
279 },
280 });
281 const error = yield* Effect.flip(
282 apns.sendPushNotificationRequest({
283 credentials,
284 request,
285 issuedAtUnixSeconds: 123,
286 }),
287 );
288
289 expect(isApnsHttpRequestError(error)).toBe(true);
290 if (!isApnsHttpRequestError(error)) {
291 return yield* Effect.die("expected APNs HTTP request error");
292 }
293 expect(error).toMatchObject({
294 requestKind: "push-notification",
295 event: null,
296 environment: "sandbox",
297 bundleId: "com.t3tools.test",
298 tokenSuffix: "sh-token",
299 stage: "send",
300 status: null,
301 message: "APNs push-notification request failed during send in sandbox.",
302 });
303 expect(error.cause).toBeInstanceOf(HttpClientError.HttpClientError);
304 expect((error.cause as HttpClientError.HttpClientError).reason).toMatchObject({
305 _tag: "TransportError",
306 cause: httpCause,
307 });
308 }).pipe(Effect.provide(layer));
309 });
310
311 it.effect("reuses the signed provider JWT across pushes within the reuse window", () => {
312 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
313 const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {
314 namedCurve: "prime256v1",
315 privateKeyEncoding: { type: "pkcs8", format: "pem" },
316 publicKeyEncoding: { type: "spki", format: "pem" },
317 });
318 const credentials = {
319 teamId: "team-jwt-cache",
320 keyId: "key-jwt-cache",
321 privateKey: Redacted.make(privateKey),
322 bundleId: "com.t3tools.test",
323 environment: "sandbox",
324 } satisfies ApnsCredentials;
325 const authorizations: Array<string> = [];
326 const capturingHttpClient = HttpClient.make((request) => {
327 authorizations.push(request.headers.authorization ?? "");
328 return Effect.succeed(
329 HttpClientResponse.fromWeb(
330 request,
331 new Response("", { status: 200, headers: { "apns-id": "apns-id-1" } }),
332 ),
333 );
334 });
335 const layer = ApnsClient.layer.pipe(
336 Layer.provide(ApnsProviderTokens.layer),
337 Layer.provide(Layer.succeed(HttpClient.HttpClient, capturingHttpClient)),
338 );
339
340 return Effect.gen(function* () {
341 const apns = yield* ApnsClient.ApnsClient;
342 const request = apns.makePushNotificationRequest({
343 token: "push-token",
344 notification: {
345 title: "Thread",
346 body: "Input: Project",
347 environmentId: "env",
348 threadId: "thread",
349 deepLink: "/threads/env/thread",
350 },
351 });
352 const send = (issuedAtUnixSeconds: number) =>
353 apns.sendPushNotificationRequest({ credentials, request, issuedAtUnixSeconds });
354
355 const window = ApnsProviderTokens.APNS_JWT_REUSE_SECONDS;
356 yield* send(window + 10);
357 yield* send(window * 2 - 1);
358 yield* send(window * 2);
359
360 expect(authorizations).toHaveLength(3);
361 // Within the 45-minute window APNs must see the byte-identical token;
362 // refreshing it per push trips TooManyProviderTokenUpdates.
363 expect(authorizations[1]).toBe(authorizations[0]);
364 expect(authorizations[2]).not.toBe(authorizations[0]);
365 ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();
366 }).pipe(Effect.provide(layer));
367 });
368
369 it.effect.each(
370 (["live-activity", "push-notification"] as const).flatMap((requestKind) =>
371 (["send", "read-response"] as const).map((stage) => ({ requestKind, stage })),
372 ),
373 )("aborts a stalled $requestKind $stage after ten seconds", ({ requestKind, stage }) =>
374 Effect.gen(function* () {
375 const started = yield* Deferred.make<void>();
376 const signals: AbortSignal[] = [];
377 const stalledHttpClient = HttpClient.make((request, _url, signal) => {
378 signals.push(signal);
379 const stall = Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never));
380 if (stage === "send") return stall;
381 const response = HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
382 Object.defineProperty(response, "text", { value: stall });
383 return Effect.succeed(response);
384 });
385 const layer = ApnsClient.layer.pipe(
386 Layer.provide(Layer.succeed(HttpClient.HttpClient, stalledHttpClient)),
387 Layer.provide(
388 Layer.succeed(ApnsProviderTokens.ApnsProviderTokens, {
389 getJwt: () => Effect.succeed("test-jwt"),
390 }),
391 ),
392 );
393 const apns = yield* ApnsClient.ApnsClient.pipe(Effect.provide(layer));
394 const credentials = {
395 teamId: "team-timeout",
396 keyId: "key-timeout",
397 privateKey: Redacted.make("unused-test-key"),
398 bundleId: "com.t3tools.test",
399 environment: "sandbox",
400 } satisfies ApnsCredentials;
401 const send =
402 requestKind === "live-activity"
403 ? apns.sendLiveActivityRequest({
404 credentials,
405 issuedAtUnixSeconds: 123,
406 request: apns.makeLiveActivityRequest({
407 event: "update",
408 token: "long-push-token",
409 state,
410 nowEpochSeconds: 123,
411 nowIso: DateTime.formatIso(now),
412 }),
413 })
414 : apns.sendPushNotificationRequest({
415 credentials,
416 issuedAtUnixSeconds: 123,
417 request: apns.makePushNotificationRequest({
418 token: "long-push-token",
419 notification: {
420 title: "Thread",
421 body: "Done",
422 environmentId: "env",
423 threadId: "thread",
424 deepLink: "/",
425 },
426 }),
427 });
428 const fiber = yield* send.pipe(Effect.flip, Effect.forkChild);
429 yield* Deferred.await(started);
430 yield* TestClock.adjust("10 seconds");
431 expect(signals[0]?.aborted).toBe(true);
432 const error = yield* Fiber.join(fiber);
433 expect(error).toMatchObject({
434 _tag: "ApnsHttpRequestError",
435 requestKind,
436 event: requestKind === "live-activity" ? "update" : null,
437 stage,
438 status: stage === "read-response" ? 200 : null,
439 tokenSuffix: "sh-token",
440 cause: { _tag: "TimeoutError" },
441 });
442 }),
443 );
444});