@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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