Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ApnsDeliveries.test.ts

1,409 lines47.1 KB

1import * as AgentActivityAlerts from "./agentActivityAlerts.ts";
2import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3import type {
4 RelayAgentActivityAggregateState,
5 RelayAgentActivityState,
6} from "@t3tools/contracts/relay";
7import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
8import { describe, expect, it } from "@effect/vitest";
9// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync.
10import * as NodeCrypto from "node:crypto";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as Fiber from "effect/Fiber";
14import * as Layer from "effect/Layer";
15import * as Redacted from "effect/Redacted";
16import * as Stream from "effect/Stream";
17import * as TestClock from "effect/testing/TestClock";
18import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
19​
20import {
21 makeApnsDeliveryJobPayload,
22 signApnsDeliveryJob,
23 type SignedApnsDeliveryJob,
24} from "./apnsDeliveryJobs.ts";
25import * as DeliveryAttempts from "./DeliveryAttempts.ts";
26import * as LiveActivities from "./LiveActivities.ts";
27import * as RelayConfiguration from "../Config.ts";
28import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
29import * as AgentActivityRows from "./AgentActivityRows.ts";
30import * as ApnsDeliveries from "./ApnsDeliveries.ts";
31import * as ApnsClient from "./ApnsClient.ts";
32import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
33​
34const config = RelayConfiguration.RelayConfiguration.of({
35 relayIssuer: "https://relay.example.test",
36 apns: {
37 environment: "sandbox",
38 teamId: "team-id",
39 keyId: "key-id",
40 privateKey: Redacted.make("not-a-private-key"),
41 bundleId: "com.t3tools.t3code.dev",
42 },
43 apnsDeliveryJobSigningSecret: Redacted.make("job-signing-secret"),
44 clerkSecretKey: Redacted.make("clerk-secret"),
45 clerkPublishableKey: "pk_test_test",
46 clerkJwtAudience: "t3-code-relay",
47 cloudMintPrivateKey: Redacted.make("cloud-private-key"),
48 cloudMintPublicKey: "cloud-public-key",
49 managedEndpointBaseDomain: undefined,
50 managedEndpointNamespace: undefined,
51});
52​
53const apnsSigningKeyPair = NodeCrypto.generateKeyPairSync("ec", {
54 namedCurve: "P-256",
55 privateKeyEncoding: { format: "pem", type: "pkcs8" },
56 publicKeyEncoding: { format: "pem", type: "spki" },
57});
58​
59const signingConfig = RelayConfiguration.RelayConfiguration.of({
60 ...config,
61 apns: {
62 ...config.apns!,
63 privateKey: Redacted.make(apnsSigningKeyPair.privateKey),
64 },
65});
66​
67const state: RelayAgentActivityState = {
68 environmentId: "env" as RelayAgentActivityState["environmentId"],
69 threadId: "thread" as RelayAgentActivityState["threadId"],
70 projectTitle: "Project",
71 threadTitle: "Thread",
72 modelTitle: "gpt-5.4",
73 phase: "running",
74 headline: "Running",
75 updatedAt: "1970-01-01T00:00:00.000Z",
76 deepLink: "/",
77};
78​
79const aggregate: RelayAgentActivityAggregateState = {
80 title: "T3 Code",
81 subtitle: "Agent work in progress",
82 activeCount: 1,
83 updatedAt: state.updatedAt,
84 activities: [
85 {
86 environmentId: state.environmentId,
87 threadId: state.threadId,
88 projectTitle: state.projectTitle,
89 threadTitle: state.threadTitle,
90 modelTitle: state.modelTitle,
91 phase: state.phase,
92 status: "Working",
93 updatedAt: state.updatedAt,
94 deepLink: state.deepLink,
95 },
96 ],
97};
98​
99const enabledPreferences = JSON.stringify({
100 liveActivitiesEnabled: true,
101 notificationsEnabled: true,
102 notifyOnApproval: true,
103 notifyOnInput: true,
104 notifyOnCompletion: true,
105 notifyOnFailure: true,
106});
107​
108const disabledPreferences = JSON.stringify({
109 liveActivitiesEnabled: false,
110 notificationsEnabled: true,
111 notifyOnApproval: true,
112 notifyOnInput: true,
113 notifyOnCompletion: true,
114 notifyOnFailure: true,
115});
116​
117const notificationsDisabledPreferences = JSON.stringify({
118 liveActivitiesEnabled: false,
119 notificationsEnabled: false,
120 notifyOnApproval: true,
121 notifyOnInput: true,
122 notifyOnCompletion: true,
123 notifyOnFailure: true,
124});
125​
126const target: LiveActivities.TargetRow = {
127 user_id: "dev:julius",
128 device_id: "device-1",
129 platform: "ios",
130 ios_major_version: 18,
131 app_version: "1.0.0",
132 bundle_id: null,
133 aps_environment: null,
134 push_token: null,
135 push_to_start_token: "start-token",
136 preferences_json: enabledPreferences,
137 activity_push_token: "activity-token",
138 remote_start_queued_at: null,
139 remote_started_at: "1970-01-01T00:00:00.000Z",
140 ended_at: null,
141 last_aggregate_json: null,
142 last_live_activity_delivery_at: null,
143};
144​
145function layerFor(input: {
146 readonly attempts: Array<DeliveryAttempts.DeliveryAttemptInput>;
147 readonly sourceJobClaims?: ReadonlyMap<string, DeliveryAttempts.DeliverySourceJobClaimResult>;
148 readonly queuedJobs?: Array<SignedApnsDeliveryJob>;
149 readonly markedDeliveries?: Array<
150 Parameters<LiveActivities.LiveActivities["Service"]["markDelivery"]>[0]
151 >;
152 readonly invalidatedTokens?: Array<
153 Parameters<LiveActivities.LiveActivities["Service"]["invalidateDeliveryToken"]>[0]
154 >;
155 readonly currentTargets?: ReadonlyArray<LiveActivities.TargetRow>;
156 readonly config?: RelayConfiguration.RelayConfiguration["Service"];
157 readonly activityStates?: ReadonlyArray<RelayAgentActivityState>;
158 readonly currentActivityStates?: ReadonlyArray<RelayAgentActivityState>;
159 readonly execute?: (
160 request: HttpClientRequest.HttpClientRequest,
161 ) => Effect.Effect<HttpClientResponse.HttpClientResponse>;
162}) {
163 return ApnsDeliveries.layer.pipe(
164 Layer.provideMerge(NodeCryptoLayer.layerMac),
165 Layer.provide(ApnsClient.layer),
166 Layer.provide(ApnsProviderTokens.layer),
167 Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),
168 Layer.provide(
169 Layer.mergeAll(
170 Layer.succeed(AgentActivityRows.AgentActivityRows, {
171 upsert: () => Effect.void,
172 remove: () => Effect.void,
173 pruneTerminal: () => Effect.void,
174 listForUser: () =>
175 input.activityStates !== undefined
176 ? Effect.succeed([...input.activityStates])
177 : Effect.succeed([state]),
178 getForUserThread: ({ environmentId, threadId }) =>
179 Effect.succeed(
180 (input.currentActivityStates ?? input.activityStates ?? [state]).find(
181 (current) =>
182 current.environmentId === environmentId && current.threadId === threadId,
183 ) ?? null,
184 ),
185 } satisfies AgentActivityRows.AgentActivityRows["Service"]),
186 Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {
187 send: (body) =>
188 Effect.sync(() => {
189 input.queuedJobs?.push(body);
190 }),
191 }),
192 Layer.succeed(DeliveryAttempts.DeliveryAttempts, {
193 pruneExpired: Effect.succeed(0),
194 claimSourceJob: (attempt) =>
195 Effect.sync(() => {
196 const claim = input.sourceJobClaims?.get(attempt.sourceJobId);
197 if (claim) {
198 return claim;
199 }
200 input.attempts.push(attempt);
201 return "claimed";
202 }),
203 completeSourceJob: (completion) =>
204 Effect.sync(() => {
205 const attempt = input.attempts.find(
206 (row) => row.sourceJobId === completion.sourceJobId,
207 );
208 if (attempt) {
209 Object.assign(attempt, completion);
210 }
211 }),
212 }),
213 Layer.succeed(LiveActivities.LiveActivities, {
214 register: () => Effect.void,
215 listTargets: () => Effect.succeed(input.currentTargets ?? [target]),
216 listIdleArmedTargets: () => Effect.succeed([]),
217 markDelivery: (delivery) =>
218 Effect.sync(() => {
219 input.markedDeliveries?.push(delivery);
220 }),
221 invalidateDeliveryToken: (invalidated) =>
222 Effect.sync(() => {
223 input.invalidatedTokens?.push(invalidated);
224 }),
225 }),
226 RelayConfiguration.layer(input.config ?? config),
227 input.execute
228 ? Layer.succeed(HttpClient.HttpClient, HttpClient.make(input.execute))
229 : FetchHttpClient.layer,
230 ),
231 ),
232 );
234​
235describe("ApnsDeliveries", () => {
236 it.effect("queues bounded Live Activity aggregate payloads", () => {
237 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
238 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
239 const longTitle = "x".repeat(300);
240 const inputAggregate: RelayAgentActivityAggregateState = {
241 ...aggregate,
242 title: longTitle,
243 subtitle: longTitle,
244 activities: [0, 1, 2, 3, 4, 5].map((index) =>
245 Object.assign({}, aggregate.activities[0]!, {
246 projectTitle: longTitle,
247 threadTitle: longTitle,
248 modelTitle: longTitle,
249 status: longTitle,
250 threadId: `thread-${index}` as RelayAgentActivityState["threadId"],
251 deepLink: "https://example.test/not-an-app-link",
252 }),
253 ),
254 };
255​
256 return Effect.gen(function* () {
257 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
258 yield* deliveries.sendForTarget({
259 target,
260 aggregate: inputAggregate,
261 nowMs: 10_000,
262 });
263​
264 const payloadAggregate = queuedJobs[0]?.payload.aggregate;
265 expect(payloadAggregate?.title.length).toBeLessThanOrEqual(120);
266 expect(payloadAggregate?.subtitle.length).toBeLessThanOrEqual(120);
267 expect(payloadAggregate?.activities).toHaveLength(5);
268 expect(payloadAggregate?.activities[0]?.projectTitle.length).toBeLessThanOrEqual(120);
269 expect(payloadAggregate?.activities[0]?.status.length).toBeLessThanOrEqual(40);
270 expect(payloadAggregate?.activities[0]?.deepLink).toBe("/");
271 expect(attempts).toEqual([]);
272 }).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));
273 });
274​
275 it.effect.each([
276 {
277 label: "connecting becomes working",
278 previousRows: [{ ...aggregate.activities[0]!, phase: "starting", status: "Connecting" }],
279 },
280 {
281 label: "input resumes working",
282 previousRows: [{ ...aggregate.activities[0]!, phase: "waiting_for_input", status: "Input" }],
283 },
284 {
285 label: "a settled terminal row leaves",
286 previousRows: [
287 aggregate.activities[0]!,
288 {
289 ...aggregate.activities[0]!,
290 threadId: ThreadId.make("finished"),
291 phase: "completed",
292 status: "Done",
293 },
294 ],
295 },
296 {
297 label: "the same thread id moves to another environment",
298 previousRows: [
299 { ...aggregate.activities[0]!, environmentId: EnvironmentId.make("other-env") },
300 ],
301 },
302 ] as const)("queues an update inside the throttle window when $label", ({ previousRows }) => {
303 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
304 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
305 const previousAggregate: RelayAgentActivityAggregateState = {
306 ...aggregate,
307 activities: previousRows,
308 };
309​
310 return Effect.gen(function* () {
311 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
312 const result = yield* deliveries.sendForTarget({
313 target: {
314 ...target,
315 last_aggregate_json: JSON.stringify(previousAggregate),
316 last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",
317 },
318 aggregate,
319 nowMs: 5_000,
320 });
321​
322 expect(result?.kind).toBe("live_activity_update");
323 expect(queuedJobs).toMatchObject([{ payload: { kind: "live_activity_update", aggregate } }]);
324 expect(queuedJobs[0]?.payload.alert ?? null).toBeNull();
325 expect(attempts).toEqual([]);
326 }).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));
327 });
328​
329 it.effect.each([
330 { label: "inside", nowMs: 5_000, queued: false },
331 { label: "after", nowMs: 19_000, queued: true },
332 ])("throttles timestamp-only updates $label the window", ({ nowMs, queued }) => {
333 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
334 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
335 const changedAggregate: RelayAgentActivityAggregateState = {
336 ...aggregate,
337 updatedAt: "1970-01-01T00:00:04.000Z",
338 activities: [{ ...aggregate.activities[0]!, updatedAt: "1970-01-01T00:00:04.000Z" }],
339 };
340 const previousAggregateJson = JSON.stringify(aggregate);
341​
342 return Effect.gen(function* () {
343 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
344 const result = yield* deliveries.sendForTarget({
345 target: {
346 ...target,
347 last_aggregate_json: previousAggregateJson,
348 last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",
349 },
350 aggregate: changedAggregate,
351 nowMs,
352 });
353​
354 expect(result?.kind ?? null).toBe(queued ? "live_activity_update" : null);
355 expect(queuedJobs).toHaveLength(queued ? 1 : 0);
356 }).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));
357 });
358​
359 it.effect(
360 "queues an alert while ending an active Live Activity when only Live Activities are disabled",
361 () => {
362 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
363 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
364 const inputAggregate: RelayAgentActivityAggregateState = {
365 ...aggregate,
366 activities: [
367 {
368 ...aggregate.activities[0]!,
369 phase: "waiting_for_input",
370 status: "Input",
371 },
372 ],
373 };
374​
375 return Effect.gen(function* () {
376 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
377 const result = yield* deliveries.sendForTarget({
378 target: {
379 ...target,
380 push_token: "apns-device-token",
381 preferences_json: disabledPreferences,
382 },
383 aggregate: inputAggregate,
384 state: { ...state, phase: "waiting_for_input" },
385 nowMs: 5_000,
386 });
387​
388 expect(result?.kind).toBe("live_activity_end");
389 expect(queuedJobs).toMatchObject([
390 {
391 payload: {
392 kind: "live_activity_end",
393 target: {
394 token: "activity-token",
395 },
396 },
397 },
398 {
399 payload: {
400 kind: "push_notification",
401 target: {
402 token: "apns-device-token",
403 },
404 notification: {
405 title: "Thread",
406 body: "Input: Project",
407 environmentId: "env",
408 threadId: "thread",
409 deepLink: "/",
410 phase: "waiting_for_input",
411 updatedAt: state.updatedAt,
412 },
413 },
414 },
415 ]);
416 expect(attempts).toEqual([]);
417 }).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));
418 },
419 );
420​
421 it.effect("does not queue alert pushes when notification permission is disabled", () => {
422 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
423 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
424 const inputAggregate: RelayAgentActivityAggregateState = {
425 ...aggregate,
426 activities: [
427 {
428 ...aggregate.activities[0]!,
429 phase: "waiting_for_input",
430 status: "Input",
431 },
432 ],
433 };
434​
435 return Effect.gen(function* () {
436 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
437 const result = yield* deliveries.sendForTarget({
438 target: {
439 ...target,
440 push_token: "apns-device-token",
441 preferences_json: notificationsDisabledPreferences,
442 },
443 aggregate: inputAggregate,
444 state: { ...state, phase: "waiting_for_input" },
445 nowMs: 5_000,
446 });
447​
448 expect(result?.kind).toBe("live_activity_end");
449 expect(queuedJobs).toMatchObject([
450 {
451 payload: {
452 kind: "live_activity_end",
453 target: {
454 token: "activity-token",
455 },
456 },
457 },
458 ]);
459 expect(attempts).toEqual([]);
460 }).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));
461 });
462​
463 it.effect(
464 "queues a push notification for approval and input states when no Live Activity delivery is available",
465 () => {
466 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
467 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
468 const inputAggregate: RelayAgentActivityAggregateState = {
469 ...aggregate,
470 activities: [
471 {
472 ...aggregate.activities[0]!,
473 phase: "waiting_for_input",
474 status: "Input",
475 },
476 ],
477 };
478​
479 return Effect.gen(function* () {
480 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
481 const result = yield* deliveries.sendForTarget({
482 target: {
483 ...target,
484 push_token: "apns-device-token",
485 push_to_start_token: null,
486 activity_push_token: null,
487 remote_started_at: null,
488 },
489 aggregate: inputAggregate,
490 state: { ...state, phase: "waiting_for_input" },
491 nowMs: 5_000,
492 });
493​
494 expect(result?.kind).toBe("push_notification");
495 expect(result?.ok).toBe(true);
496 expect(queuedJobs).toMatchObject([
497 {
498 payload: {
499 kind: "push_notification",
500 target: {
501 token: "apns-device-token",
502 },
503 notification: {
504 title: "Thread",
505 body: "Input: Project",
506 environmentId: "env",
507 threadId: "thread",
508 deepLink: "/",
509 },
510 },
511 },
512 ]);
513 expect(attempts).toEqual([]);
514 }).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));
515 },
516 );
517​
518 it.effect("push-only alerts describe the published thread, never a stale aggregate row", () => {
519 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
520 const pushOnly = {
521 ...target,
522 push_token: "apns-device-token",
523 push_to_start_token: null,
524 activity_push_token: null,
525 remote_started_at: null,
526 };
527 const completed = { ...state, phase: "completed" as const };
528 const doneAggregate: RelayAgentActivityAggregateState = {
529 ...aggregate,
530 activeCount: 0,
531 activities: [{ ...aggregate.activities[0]!, phase: "completed", status: "Done" }],
532 };
533​
534 return Effect.gen(function* () {
535 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
536 yield* deliveries.sendForTarget({
537 target: pushOnly,
538 aggregate: doneAggregate,
539 state: completed,
540 nowMs: 5_000,
541 });
542 yield* deliveries.sendForTarget({
543 target: pushOnly,
544 aggregate: doneAggregate,
545 state: null,
546 nowMs: 6_000,
547 });
548 const unrelated: RelayAgentActivityState = {
549 ...state,
550 threadId: "other-thread" as RelayAgentActivityState["threadId"],
551 threadTitle: "Other thread",
552 projectTitle: "Other project",
553 deepLink: "/threads/env/other-thread",
554 };
555 yield* deliveries.sendForTarget({
556 target: pushOnly,
557 aggregate: doneAggregate,
558 state: unrelated,
559 nowMs: 7_000,
560 });
561 yield* deliveries.sendForTarget({
562 target: pushOnly,
563 aggregate: doneAggregate,
564 state: { ...unrelated, phase: "waiting_for_input" },
565 nowMs: 8_000,
566 });
567​
568 expect(queuedJobs.map((job) => job.payload)).toMatchObject([
569 {
570 kind: "push_notification",
571 notification: { title: "Thread", body: "Done: Project", threadId: "thread" },
572 },
573 {
574 kind: "push_notification",
575 notification: {
576 title: "Other thread",
577 body: "Input: Other project",
578 threadId: "other-thread",
579 deepLink: "/threads/env/other-thread",
580 },
581 },
582 ]);
583 }).pipe(Effect.provide(layerFor({ attempts: [], queuedJobs })));
584 });
585​
586 it.effect("queues bounded alert notification payloads", () => {
587 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
588 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
589 const longTitle = "x".repeat(300);
590 const inputAggregate: RelayAgentActivityAggregateState = {
591 ...aggregate,
592 activities: [
593 {
594 ...aggregate.activities[0]!,
595 projectTitle: longTitle,
596 threadTitle: longTitle,
597 phase: "waiting_for_input",
598 status: "Input",
599 deepLink: "https://example.test/not-an-app-link",
600 },
601 ],
602 };
603​
604 return Effect.gen(function* () {
605 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
606 yield* deliveries.sendForTarget({
607 target: {
608 ...target,
609 push_token: "apns-device-token",
610 push_to_start_token: null,
611 activity_push_token: null,
612 remote_started_at: null,
613 },
614 aggregate: inputAggregate,
615 state: {
616 ...state,
617 projectTitle: longTitle,
618 threadTitle: longTitle,
619 phase: "waiting_for_input",
620 deepLink: "https://example.test/not-an-app-link",
621 },
622 nowMs: 5_000,
623 });
624​
625 const notification = queuedJobs[0]?.payload.notification;
626 expect(notification?.title.length).toBeLessThanOrEqual(120);
627 expect(notification?.body.length).toBeLessThanOrEqual(120);
628 expect(notification?.deepLink).toBe("/");
629 expect(attempts).toEqual([]);
630 }).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));
631 });
632​
633 it.effect.each([
634 { phase: "running", updatedAt: state.updatedAt, disabled: false, sends: false },
635 { phase: "completed", updatedAt: state.updatedAt, disabled: false, sends: false },
636 { phase: "completed", updatedAt: "1969-12-31T23:44:00.000Z", disabled: false, sends: true },
637 { phase: "running", updatedAt: state.updatedAt, disabled: true, sends: true },
638 ] as const)(
639 "rechecks a queued contentless end: $phase at $updatedAt, disabled=$disabled",
640 ({ phase, updatedAt, disabled, sends }) => {
641 const requests: HttpClientRequest.HttpClientRequest[] = [];
642 const signedEnd = signApnsDeliveryJob({
643 secret: config.apnsDeliveryJobSigningSecret,
644 payload: makeApnsDeliveryJobPayload({
645 kind: "live_activity_end",
646 userId: target.user_id,
647 deviceId: target.device_id,
648 token: "activity-token",
649 aggregate: null,
650 createdAt: state.updatedAt,
651 expiresAt: "1970-01-01T00:10:00.000Z",
652 jobId: "job-end-1",
653 }),
654 });
655 return Effect.gen(function* () {
656 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
657 const result = yield* deliveries.processSignedJob(yield* signedEnd);
658 expect(result.ok).toBe(true);
659 expect(requests).toHaveLength(sends ? 1 : 0);
660 if (sends) {
661 const request = requests[0]!;
662 expect(request.url).toBe("https://api.sandbox.push.apple.com/3/device/activity-token");
663 expect(request.body._tag).toBe("Uint8Array");
664 if (request.body._tag === "Uint8Array") {
665 const { aps } = JSON.parse(new TextDecoder().decode(request.body.body));
666 expect(aps.event).toBe("end");
667 expect(aps.alert).toBeUndefined();
668 expect(aps.sound).toBeUndefined();
669 }
670 }
671 }).pipe(
672 Effect.provide(
673 layerFor({
674 attempts: [],
675 config: signingConfig,
676 currentTargets: [
677 { ...target, preferences_json: disabled ? disabledPreferences : enabledPreferences },
678 ],
679 activityStates: [{ ...state, phase, updatedAt }],
680 execute: (request) =>
681 Effect.sync(() => {
682 requests.push(request);
683 return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
684 }),
685 }),
686 ),
687 );
688 },
689 );
690​
691 it.effect("processes signed push notification jobs through APNs and records attempts", () => {
692 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
693 const payload = makeApnsDeliveryJobPayload({
694 kind: "push_notification",
695 userId: target.user_id,
696 deviceId: target.device_id,
697 token: "apns-device-token",
698 aggregate: null,
699 notification: {
700 title: "Thread",
701 body: "Input: Project",
702 environmentId: "env",
703 threadId: "thread",
704 deepLink: "/",
705 },
706 createdAt: "1970-01-01T00:00:00.000Z",
707 expiresAt: "1970-01-01T00:10:00.000Z",
708 jobId: "job-push-1",
709 });
710 const signed = signApnsDeliveryJob({
711 secret: config.apnsDeliveryJobSigningSecret,
712 payload,
713 });
714 const execute = (request: HttpClientRequest.HttpClientRequest) =>
715 Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 })));
716​
717 return Effect.gen(function* () {
718 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
719 const result = yield* deliveries.processSignedJob(yield* signed);
720​
721 expect(result.kind).toBe("push_notification");
722 expect(result.ok).toBe(true);
723 expect(result.apnsStatus).toBe(200);
724 expect(attempts).toMatchObject([
725 {
726 kind: "push_notification",
727 sourceJobId: "job-push-1",
728 token: "apns-device-token",
729 environmentId: "env",
730 threadId: "thread",
731 deviceId: target.device_id,
732 apnsStatus: 200,
733 },
734 ]);
735 }).pipe(
736 Effect.provide(
737 layerFor({
738 attempts,
739 currentTargets: [
740 {
741 ...target,
742 push_token: "apns-device-token",
743 },
744 ],
745 config: signingConfig,
746 execute,
747 }),
748 ),
749 );
750 });
751​
752 it.effect("delivers to other devices without reordering a device's queued jobs", () =>
753 Effect.gen(function* () {
754 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
755 const requests: Array<string> = [];
756 let firstDeviceRequest = true;
757 const firstStarted = yield* Deferred.make<void>();
758 const otherDeviceDelivered = yield* Deferred.make<void>();
759 const devices = [
760 { ...target, push_token: "first-token" },
761 { ...target, device_id: "device-2", push_token: "other-token" },
762 ];
763 const jobs = yield* Effect.forEach([devices[0]!, devices[0]!, devices[1]!], (device, i) =>
764 signApnsDeliveryJob({
765 secret: signingConfig.apnsDeliveryJobSigningSecret,
766 payload: makeApnsDeliveryJobPayload({
767 kind: "push_notification",
768 userId: device.user_id,
769 deviceId: device.device_id,
770 token: device.push_token,
771 aggregate: null,
772 notification: {
773 title: "Thread",
774 body: "Done",
775 environmentId: "env",
776 threadId: `thread-${i}`,
777 deepLink: "/",
778 },
779 createdAt: "1970-01-01T00:00:00.000Z",
780 expiresAt: "1970-01-01T00:10:00.000Z",
781 jobId: `job-${i}`,
782 }),
783 }),
784 );
785 const batch = yield* Effect.flatMap(ApnsDeliveries.ApnsDeliveries, (deliveries) =>
786 deliveries.processBatch(Stream.fromIterable(jobs.map((body) => ({ body })))),
787 ).pipe(
788 Effect.provide(
789 layerFor({
790 attempts,
791 currentTargets: devices,
792 config: signingConfig,
793 execute: (request) =>
794 Effect.gen(function* () {
795 const token = request.url.split("/").at(-1)!;
796 requests.push(token);
797 if (request.url.endsWith("/other-token")) {
798 yield* Deferred.succeed(otherDeviceDelivered, undefined);
799 } else if (firstDeviceRequest) {
800 firstDeviceRequest = false;
801 yield* Deferred.succeed(firstStarted, undefined);
802 yield* Deferred.await(otherDeviceDelivered);
803 }
804 return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
805 }),
806 }),
807 ),
808 Effect.forkChild,
809 );
810 yield* Deferred.await(firstStarted);
811 yield* TestClock.adjust("10 seconds");
812 yield* Fiber.join(batch);
813​
814 expect(requests).toHaveLength(3);
815 expect(requests.filter((token) => token === "first-token")).toHaveLength(2);
816 expect(requests.indexOf("other-token")).toBeLessThan(requests.lastIndexOf("first-token"));
817 expect(attempts).toHaveLength(3);
818 expect(
819 attempts
820 .filter((attempt) => attempt.deviceId === target.device_id)
821 .map((attempt) => attempt.sourceJobId),
822 ).toEqual(["job-0", "job-1"]);
823 expect(attempts.every((attempt) => attempt.apnsStatus === 200)).toBe(true);
824 }).pipe(Effect.provide(NodeCryptoLayer.layerMac)),
825 );
826​
827 it.effect("skips duplicate signed queue jobs before calling APNs", () => {
828 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
829 let executeCount = 0;
830 const payload = makeApnsDeliveryJobPayload({
831 kind: "push_notification",
832 userId: target.user_id,
833 deviceId: target.device_id,
834 token: "apns-device-token",
835 aggregate: null,
836 notification: {
837 title: "Thread",
838 body: "Input: Project",
839 environmentId: "env",
840 threadId: "thread",
841 deepLink: "/",
842 },
843 createdAt: "1970-01-01T00:00:00.000Z",
844 expiresAt: "1970-01-01T00:10:00.000Z",
845 jobId: "job-push-duplicate",
846 });
847 const signed = signApnsDeliveryJob({
848 secret: config.apnsDeliveryJobSigningSecret,
849 payload,
850 });
851 const execute = (request: HttpClientRequest.HttpClientRequest) =>
852 Effect.sync(() => {
853 executeCount += 1;
854 return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
855 });
856​
857 return Effect.gen(function* () {
858 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
859 const result = yield* deliveries.processSignedJob(yield* signed);
860​
861 expect(result).toMatchObject({
862 kind: "push_notification",
863 ok: true,
864 apnsStatus: null,
865 apnsReason: "Duplicate APNs delivery job skipped.",
866 });
867 expect(executeCount).toBe(0);
868 expect(attempts).toEqual([]);
869 }).pipe(
870 Effect.provide(
871 layerFor({
872 attempts,
873 sourceJobClaims: new Map([["job-push-duplicate", "completed"]]),
874 config: signingConfig,
875 execute,
876 }),
877 ),
878 );
879 });
880​
881 it.effect("skips stale signed Live Activity jobs when the registered token changed", () => {
882 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
883 let executeCount = 0;
884 const payload = makeApnsDeliveryJobPayload({
885 kind: "live_activity_update",
886 userId: target.user_id,
887 deviceId: target.device_id,
888 token: "stale-activity-token",
889 aggregate,
890 createdAt: "1970-01-01T00:00:00.000Z",
891 expiresAt: "1970-01-01T00:10:00.000Z",
892 jobId: "job-update-stale-token",
893 });
894 const signed = signApnsDeliveryJob({
895 secret: config.apnsDeliveryJobSigningSecret,
896 payload,
897 });
898 const execute = (request: HttpClientRequest.HttpClientRequest) =>
899 Effect.sync(() => {
900 executeCount += 1;
901 return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
902 });
903​
904 return Effect.gen(function* () {
905 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
906 const result = yield* deliveries.processSignedJob(yield* signed);
907​
908 expect(result).toMatchObject({
909 kind: "live_activity_update",
910 ok: true,
911 apnsStatus: null,
912 apnsReason: "Stale APNs delivery job skipped.",
913 });
914 expect(executeCount).toBe(0);
915 expect(attempts).toMatchObject([
916 {
917 kind: "live_activity_update",
918 sourceJobId: "job-update-stale-token",
919 token: "stale-activity-token",
920 apnsReason: "Stale APNs delivery job skipped.",
921 },
922 ]);
923 }).pipe(
924 Effect.provide(
925 layerFor({
926 attempts,
927 config: signingConfig,
928 execute,
929 }),
930 ),
931 );
932 });
933​
934 it.effect("skips a queued Done Live Activity update after the thread resumes working", () => {
935 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
936 let executeCount = 0;
937 const completedAt = "1970-01-01T00:00:01.000Z";
938 const completedAggregate: RelayAgentActivityAggregateState = {
939 ...aggregate,
940 activeCount: 0,
941 updatedAt: completedAt,
942 activities: [
943 {
944 ...aggregate.activities[0]!,
945 phase: "completed",
946 status: "Done",
947 updatedAt: completedAt,
948 },
949 ],
950 };
951 const payload = makeApnsDeliveryJobPayload({
952 kind: "live_activity_update",
953 userId: target.user_id,
954 deviceId: target.device_id,
955 token: target.activity_push_token ?? "activity-token",
956 aggregate: completedAggregate,
957 alert: { title: "Thread", body: "Done: Project" },
958 createdAt: completedAt,
959 expiresAt: "1970-01-01T00:10:00.000Z",
960 jobId: "job-update-superseded-by-running",
961 });
962 const signed = signApnsDeliveryJob({
963 secret: config.apnsDeliveryJobSigningSecret,
964 payload,
965 });
966 const execute = (request: HttpClientRequest.HttpClientRequest) =>
967 Effect.sync(() => {
968 executeCount += 1;
969 return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
970 });
971​
972 return Effect.gen(function* () {
973 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
974 const result = yield* deliveries.processSignedJob(yield* signed);
975​
976 expect(result).toMatchObject({
977 kind: "live_activity_update",
978 ok: true,
979 apnsStatus: null,
980 apnsReason: "Stale APNs delivery job skipped.",
981 });
982 expect(executeCount).toBe(0);
983 expect(attempts).toMatchObject([
984 {
985 sourceJobId: "job-update-superseded-by-running",
986 apnsReason: "Stale agent activity state skipped.",
987 },
988 ]);
989 }).pipe(
990 Effect.provide(
991 layerFor({
992 attempts,
993 activityStates: [
994 {
995 ...state,
996 phase: "running",
997 headline: "Running",
998 updatedAt: "1970-01-01T00:00:02.000Z",
999 },
1000 ],
1001 config: signingConfig,
1002 execute,
1003 }),
1004 ),
1005 );
1006 });
1007​
1008 it.effect("retries an in-flight device's jobs without cancelling other devices", () => {
1009 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
1010 let executeCount = 0;
1011 const payload = makeApnsDeliveryJobPayload({
1012 kind: "push_notification",
1013 userId: target.user_id,
1014 deviceId: target.device_id,
1015 token: "apns-device-token",
1016 aggregate: null,
1017 notification: {
1018 title: "Thread",
1019 body: "Input: Project",
1020 environmentId: "env",
1021 threadId: "thread",
1022 deepLink: "/",
1023 },
1024 createdAt: "1970-01-01T00:00:00.000Z",
1025 expiresAt: "1970-01-01T00:10:00.000Z",
1026 jobId: "job-push-in-flight",
1027 });
1028 const signed = Effect.forEach(
1030 payload,
1031 { ...payload, jobId: "job-push-after-in-flight" },
1033 ...payload,
1034 jobId: "job-push-other-device",
1035 target: { ...payload.target, deviceId: "device-2", token: "other-token" },
1036 },
1037 ],
1038 (payload) => signApnsDeliveryJob({ secret: config.apnsDeliveryJobSigningSecret, payload }),
1039 );
1040 const execute = (request: HttpClientRequest.HttpClientRequest) =>
1041 Effect.sync(() => {
1042 executeCount += 1;
1043 return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
1044 });
1045​
1046 return Effect.gen(function* () {
1047 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
1048 const result = yield* Effect.exit(
1049 deliveries.processBatch(Stream.fromIterable((yield* signed).map((body) => ({ body })))),
1050 );
1051​
1052 expect(result._tag).toBe("Failure");
1053 if (result._tag === "Failure") {
1054 expect(result.cause.toString()).toContain("ApnsDeliveryJobClaimInFlight");
1056 expect(executeCount).toBe(1);
1057 expect(attempts).toMatchObject([{ sourceJobId: "job-push-other-device", apnsStatus: 200 }]);
1058 }).pipe(
1059 Effect.provide(
1060 layerFor({
1061 attempts,
1062 sourceJobClaims: new Map([["job-push-in-flight", "in_flight"]]),
1063 currentTargets: [{ ...target, device_id: "device-2", push_token: "other-token" }],
1064 config: signingConfig,
1065 execute,
1066 }),
1067 ),
1068 );
1069 });
1070​
1071 it.effect("invalidates dead device push tokens after permanent APNs alert failures", () => {
1072 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
1073 const invalidatedTokens: Array<
1074 Parameters<LiveActivities.LiveActivities["Service"]["invalidateDeliveryToken"]>[0]
1075 > = [];
1076 const payload = makeApnsDeliveryJobPayload({
1077 kind: "push_notification",
1078 userId: target.user_id,
1079 deviceId: target.device_id,
1080 token: "apns-device-token",
1081 aggregate: null,
1082 notification: {
1083 title: "Thread",
1084 body: "Failed: Project",
1085 environmentId: "env",
1086 threadId: "thread",
1087 deepLink: "/",
1088 },
1089 createdAt: "1970-01-01T00:00:00.000Z",
1090 expiresAt: "1970-01-01T00:10:00.000Z",
1091 jobId: "job-push-bad-token",
1092 });
1093 const signed = signApnsDeliveryJob({
1094 secret: config.apnsDeliveryJobSigningSecret,
1095 payload,
1096 });
1097 const execute = (request: HttpClientRequest.HttpClientRequest) =>
1098 Effect.succeed(
1099 HttpClientResponse.fromWeb(
1100 request,
1101 Response.json({ reason: "BadDeviceToken" }, { status: 400 }),
1102 ),
1103 );
1104​
1105 return Effect.gen(function* () {
1106 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
1107 const result = yield* deliveries.processSignedJob(yield* signed);
1108​
1109 expect(result.kind).toBe("push_notification");
1110 expect(result.ok).toBe(false);
1111 expect(result.apnsStatus).toBe(400);
1112 expect(result.apnsReason).toBe("BadDeviceToken");
1113 expect(invalidatedTokens).toMatchObject([
1115 userId: target.user_id,
1116 deviceId: target.device_id,
1117 kind: "push_notification",
1118 },
1119 ]);
1120 }).pipe(
1121 Effect.provide(
1122 layerFor({
1123 attempts,
1124 invalidatedTokens,
1125 currentTargets: [
1127 ...target,
1128 push_token: "apns-device-token",
1129 },
1130 ],
1131 config: signingConfig,
1132 execute,
1133 }),
1134 ),
1135 );
1136 });
1137​
1138 it.effect("invalidates dead Live Activity tokens after APNs unregisters them", () => {
1139 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
1140 const invalidatedTokens: Array<
1141 Parameters<LiveActivities.LiveActivities["Service"]["invalidateDeliveryToken"]>[0]
1142 > = [];
1143 const payload = makeApnsDeliveryJobPayload({
1144 kind: "live_activity_update",
1145 userId: target.user_id,
1146 deviceId: target.device_id,
1147 token: target.activity_push_token ?? "activity-token",
1148 aggregate,
1149 createdAt: "1970-01-01T00:00:00.000Z",
1150 expiresAt: "1970-01-01T00:10:00.000Z",
1151 jobId: "job-update-unregistered",
1152 });
1153 const signed = signApnsDeliveryJob({
1154 secret: config.apnsDeliveryJobSigningSecret,
1155 payload,
1156 });
1157 const execute = (request: HttpClientRequest.HttpClientRequest) =>
1158 Effect.succeed(
1159 HttpClientResponse.fromWeb(
1160 request,
1161 Response.json({ reason: "Unregistered" }, { status: 410 }),
1162 ),
1163 );
1164​
1165 return Effect.gen(function* () {
1166 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
1167 const result = yield* deliveries.processSignedJob(yield* signed);
1168​
1169 expect(result.kind).toBe("live_activity_update");
1170 expect(result.ok).toBe(false);
1171 expect(result.apnsStatus).toBe(410);
1172 expect(result.apnsReason).toBe("Unregistered");
1173 expect(invalidatedTokens).toMatchObject([
1175 userId: target.user_id,
1176 deviceId: target.device_id,
1177 kind: "live_activity_update",
1178 },
1179 ]);
1180 }).pipe(
1181 Effect.provide(layerFor({ attempts, invalidatedTokens, config: signingConfig, execute })),
1182 );
1183 });
1184});
1185​
1186describe("live activity alert decisions", () => {
1187 const preferences = {
1188 liveActivitiesEnabled: true,
1189 notificationsEnabled: true,
1190 notifyOnApproval: true,
1191 notifyOnInput: true,
1192 notifyOnCompletion: true,
1193 notifyOnFailure: true,
1194 };
1195​
1196 const attentionRow = {
1197 ...aggregate.activities[0]!,
1198 threadId: "thread-2" as RelayAgentActivityState["threadId"],
1199 threadTitle: "Blocked thread",
1200 phase: "waiting_for_approval" as const,
1201 status: "Approval",
1202 };
1203​
1204 it("alerts when a thread newly enters an attention phase", () => {
1205 const alert = AgentActivityAlerts.alertForAttentionTransition({
1206 previousAggregate: aggregate,
1207 nextAggregate: {
1208 ...aggregate,
1209 activeCount: 2,
1210 activities: [...aggregate.activities, attentionRow],
1211 },
1212 preferences,
1213 });
1214 expect(alert).toEqual({ title: "Blocked thread", body: "Approval: Project" });
1215 });
1216​
1217 it("stays silent without a delivered baseline so replays cannot buzz", () => {
1218 expect(
1219 AgentActivityAlerts.alertForAttentionTransition({
1220 previousAggregate: null,
1221 nextAggregate: { ...aggregate, activities: [attentionRow] },
1222 preferences,
1223 }),
1224 ).toBeNull();
1225 });
1226​
1227 it("alerts when a previously active thread finishes mid-flight", () => {
1228 const doneRow = {
1229 ...aggregate.activities[0]!,
1230 phase: "completed" as const,
1231 status: "Done",
1232 };
1233 const next = {
1234 ...aggregate,
1235 activeCount: 0,
1236 activities: [attentionRow, doneRow],
1237 };
1238 expect(
1239 AgentActivityAlerts.alertForNewlyTerminal({
1240 previousAggregate: aggregate,
1241 nextAggregate: next,
1242 preferences,
1243 nowMs: 0,
1244 }),
1245 ).toEqual({ title: "Thread", body: "Done: Project" });
1246 expect(
1247 AgentActivityAlerts.alertForNewlyTerminal({
1248 previousAggregate: aggregate,
1249 nextAggregate: next,
1250 preferences: { ...preferences, notifyOnCompletion: false },
1251 nowMs: 0,
1252 }),
1253 ).toBeNull();
1254 expect(
1255 AgentActivityAlerts.alertForNewlyTerminal({
1256 previousAggregate: null,
1257 nextAggregate: next,
1258 preferences,
1259 nowMs: 0,
1260 }),
1261 ).toBeNull();
1262 expect(
1263 AgentActivityAlerts.alertForNewlyTerminal({
1264 previousAggregate: next,
1265 nextAggregate: next,
1266 preferences,
1267 nowMs: 0,
1268 }),
1269 ).toBeNull();
1270 expect(
1271 AgentActivityAlerts.alertForNewlyTerminal({
1272 previousAggregate: { ...aggregate, activities: [attentionRow] },
1273 nextAggregate: next,
1274 preferences,
1275 nowMs: 0,
1276 }),
1277 ).toBeNull();
1278 });
1279});
1280​
1281describe("fast completion delivery", () => {
1282 it.effect("keeps a completion alert when work finishes before running delivery", () => {
1283 const queuedJobs: SignedApnsDeliveryJob[] = [];
1284 const old = {
1285 ...aggregate,
1286 activeCount: 0,
1287 activities: [
1289 ...aggregate.activities[0]!,
1290 threadId: "old" as RelayAgentActivityState["threadId"],
1291 phase: "completed" as const,
1292 },
1293 ],
1294 };
1295 const device = { ...target, last_aggregate_json: JSON.stringify(old) };
1296 const done = {
1297 ...aggregate,
1298 activeCount: 0,
1299 activities: [{ ...aggregate.activities[0]!, phase: "completed" as const }],
1300 };
1301 return Effect.gen(function* () {
1302 const d = yield* ApnsDeliveries.ApnsDeliveries;
1303 yield* d.sendForTarget({ target: device, aggregate, nowMs: 0 });
1304 yield* d.sendForTarget({ target: device, aggregate: done, nowMs: 0 });
1305 expect(
1306 queuedJobs.some((x) => x.payload.alert !== null && x.payload.alert !== undefined),
1307 ).toBe(true);
1308 }).pipe(Effect.provide(layerFor({ attempts: [], queuedJobs, currentTargets: [device] })));
1309 });
1310 it.effect("replays a newly visible completion without alerting", () => {
1311 const queuedJobs: SignedApnsDeliveryJob[] = [];
1312 const done = {
1313 ...aggregate,
1314 activeCount: 0,
1315 activities: [{ ...aggregate.activities[0]!, phase: "completed" as const }],
1316 };
1317 const previous = {
1318 ...aggregate,
1319 activities: [
1320 { ...aggregate.activities[0]!, threadId: "other" as RelayAgentActivityState["threadId"] },
1321 ],
1322 };
1323 const device = { ...target, last_aggregate_json: JSON.stringify(previous) };
1324 return Effect.gen(function* () {
1325 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
1326 yield* deliveries.sendForTarget({
1327 target: device,
1328 aggregate: done,
1329 nowMs: 0,
1330 replay: true,
1331 });
1332 expect(queuedJobs).toHaveLength(1);
1333 expect(queuedJobs[0]?.payload.alert).toBeUndefined();
1334 }).pipe(Effect.provide(layerFor({ attempts: [], queuedJobs })));
1335 });
1336});
1337​
1338describe("signed APNs registration metadata", () => {
1339 it.effect.each(
1340 (["live_activity_update", "push_notification"] as const).flatMap((kind) =>
1341 (["bundle", "environment", "legacy"] as const).map((changed) => ({ kind, changed })),
1342 ),
1343 )("routes $kind using current registration with $changed job metadata", ({ kind, changed }) => {
1344 const attempts: DeliveryAttempts.DeliveryAttemptInput[] = [];
1345 const requests: HttpClientRequest.HttpClientRequest[] = [];
1346 const payload = makeApnsDeliveryJobPayload({
1347 kind,
1348 userId: target.user_id,
1349 deviceId: target.device_id,
1350 token: "unchanged-token",
1351 ...(changed === "legacy"
1352 ? {}
1353 : { bundleId: "com.t3tools.t3code.dev", apsEnvironment: "sandbox" as const }),
1354 aggregate: kind === "live_activity_update" ? aggregate : null,
1355 ...(kind === "push_notification"
1356 ? {
1357 notification: {
1358 title: "Thread",
1359 body: "Input: Project",
1360 environmentId: "env",
1361 threadId: "thread",
1362 deepLink: "/",
1363 },
1365 : {}),
1366 createdAt: "1970-01-01T00:00:00.000Z",
1367 expiresAt: "1970-01-01T00:10:00.000Z",
1368 jobId: `metadata-${kind}-${changed}`,
1369 });
1370 const signed = signApnsDeliveryJob({
1371 secret: config.apnsDeliveryJobSigningSecret,
1372 payload,
1373 });
1374 return Effect.gen(function* () {
1375 const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
1376 const result = yield* deliveries.processSignedJob(yield* signed);
1377 expect(result.ok).toBe(true);
1378 expect(requests).toHaveLength(1);
1379 expect(requests[0]?.url).toBe(
1380 `${changed === "environment" ? "https://api.push.apple.com" : "https://api.sandbox.push.apple.com"}/3/device/unchanged-token`,
1381 );
1382 expect(requests[0]?.headers["apns-topic"]).toBe(
1383 `${changed === "bundle" ? "com.t3tools.t3code.preview" : "com.t3tools.t3code.dev"}${kind === "live_activity_update" ? ".push-type.liveactivity" : ""}`,
1384 );
1385 }).pipe(
1386 Effect.provide(
1387 layerFor({
1388 attempts,
1389 config: signingConfig,
1390 currentTargets: [
1392 ...target,
1393 push_token: "unchanged-token",
1394 activity_push_token: "unchanged-token",
1395 bundle_id:
1396 changed === "bundle" ? "com.t3tools.t3code.preview" : "com.t3tools.t3code.dev",
1397 aps_environment: changed === "environment" ? "production" : "sandbox",
1398 },
1399 ],
1400 execute: (request) =>
1401 Effect.sync(() => {
1402 requests.push(request);
1403 return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
1404 }),
1405 }),
1406 ),
1407 );
1408 });
1409});