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

MobileRegistrations.test.ts

494 lines17.0 KB

1import type {
2 RelayAgentActivityState,
3 RelayDeviceRegistrationRequest,
4} from "@t3tools/contracts/relay";
5import type { SignedApnsDeliveryJob } from "./apnsDeliveryJobs.ts";
6import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
7import { describe, expect, it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Logger from "effect/Logger";
11import * as Redacted from "effect/Redacted";
12import { FetchHttpClient } from "effect/unstable/http";
13​
14import * as Devices from "./Devices.ts";
15import * as AgentActivityRows from "./AgentActivityRows.ts";
16import * as DeliveryAttempts from "./DeliveryAttempts.ts";
17import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
18import * as LiveActivities from "./LiveActivities.ts";
19import * as RelayConfiguration from "../Config.ts";
20import * as AgentActivityPublisher from "./AgentActivityPublisher.ts";
21import { FcmDeliveries } from "./FcmDeliveries.ts";
22​
23const publisherLayer = AgentActivityPublisher.layer.pipe(
24 Layer.provide(
25 Layer.succeed(FcmDeliveries, {
26 enqueue: () => Effect.succeed(null),
27 process: () => Effect.void,
28 }),
29 ),
30);
31import * as ApnsDeliveries from "./ApnsDeliveries.ts";
32import * as ApnsClient from "./ApnsClient.ts";
33import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
34import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
35import * as MobileRegistrations from "./MobileRegistrations.ts";
36​
37const device: RelayDeviceRegistrationRequest = {
38 deviceId: "device-1" as RelayDeviceRegistrationRequest["deviceId"],
39 label: "Julius's iPhone",
40 platform: "ios",
41 iosMajorVersion: 18,
42 appVersion: "1.0.0" as RelayDeviceRegistrationRequest["appVersion"],
43 preferences: {
44 liveActivitiesEnabled: true,
45 notificationsEnabled: true,
46 notifyOnApproval: true,
47 notifyOnInput: true,
48 notifyOnCompletion: true,
49 notifyOnFailure: true,
50 },
51};
52​
53function makeDevices(
54 overrides: Partial<Devices.Devices["Service"]> = {},
55): Devices.Devices["Service"] {
56 return {
57 register: () => Effect.void,
58 unregister: () => Effect.void,
59 listForUser: () => Effect.succeed([]),
60 ...overrides,
61 };
63​
64function makeLiveActivities(
65 overrides: Partial<LiveActivities.LiveActivities["Service"]> = {},
66): LiveActivities.LiveActivities["Service"] {
67 return {
68 register: () => Effect.void,
69 listTargets: () => Effect.succeed([]),
70 markDelivery: () => Effect.void,
71 markStartQueued: () => Effect.void,
72 clearStartQueued: () => Effect.void,
73 invalidateDeliveryToken: () => Effect.void,
74 ...overrides,
75 };
77​
78function makeAgentActivityRows(
79 overrides: Partial<AgentActivityRows.AgentActivityRows["Service"]> = {},
80): AgentActivityRows.AgentActivityRows["Service"] {
81 return {
82 upsert: () => Effect.void,
83 remove: () => Effect.void,
84 pruneTerminal: () => Effect.void,
85 listForUser: () => {
86 const activeState: RelayAgentActivityState = {
87 environmentId: "env-1" as RelayAgentActivityState["environmentId"],
88 threadId: "thread-1" as RelayAgentActivityState["threadId"],
89 projectTitle: "Project",
90 threadTitle: "Implement APNs",
91 modelTitle: "gpt-5.4",
92 phase: "running",
93 headline: "Working",
94 updatedAt: "1970-01-01T00:00:10.000Z",
95 deepLink: "/env-1/thread-1",
96 };
97 return Effect.succeed([activeState]);
98 },
99 getForUserThread: () => Effect.succeed(null),
100 ...overrides,
101 };
103​
104function makeEnvironmentLinks(
105 overrides: Partial<EnvironmentLinks.EnvironmentLinks["Service"]> = {},
106): EnvironmentLinks.EnvironmentLinks["Service"] {
107 return {
108 upsert: () => Effect.void,
109 listDeliveryUsersForEnvironment: () =>
110 Effect.succeed([
111 {
112 userId: "dev:julius",
113 notificationsEnabled: true,
114 liveActivitiesEnabled: true,
115 },
116 ]),
117 listForUser: () => Effect.succeed([]),
118 getForUser: () => Effect.succeed(null),
119 revokeForUser: () => Effect.succeed(false),
120 ...overrides,
121 };
123​
124function makeDeliveryAttempts(
125 overrides: Partial<DeliveryAttempts.DeliveryAttempts["Service"]> = {},
126): DeliveryAttempts.DeliveryAttempts["Service"] {
127 return {
128 record: () => Effect.void,
129 claimSourceJob: () => Effect.succeed("claimed"),
130 completeSourceJob: () => Effect.void,
131 ...overrides,
132 };
134​
135const config = RelayConfiguration.RelayConfiguration.of({
136 relayIssuer: "https://relay.example.test",
137 apns: {
138 environment: "sandbox",
139 teamId: "team-id",
140 keyId: "key-id",
141 bundleId: "codes.t3.mobile",
142 privateKey: Redacted.make("apns-private-key"),
143 },
144 clerkSecretKey: Redacted.make("clerk-secret"),
145 clerkPublishableKey: "pk_test_test",
146 clerkJwtAudience: "t3-code-relay",
147 apnsDeliveryJobSigningSecret: Redacted.make("apns-job-secret"),
148 cloudMintPrivateKey: Redacted.make("cloud-private-key"),
149 cloudMintPublicKey: "cloud-public-key",
150 managedEndpointBaseDomain: undefined,
151 managedEndpointNamespace: undefined,
152});
153​
154function makeRegistrationReplayLayer(input: {
155 readonly devices: Devices.Devices["Service"];
156 readonly liveActivities: LiveActivities.LiveActivities["Service"];
157 readonly queuedJobs: Array<SignedApnsDeliveryJob>;
158}) {
159 return MobileRegistrations.layer.pipe(
160 Layer.provide(publisherLayer),
161 Layer.provide(
162 ApnsDeliveries.layer.pipe(
163 Layer.provide(ApnsClient.layer.pipe(Layer.provide(ApnsProviderTokens.layer))),
164 ),
165 ),
166 Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),
167 Layer.provide(
168 Layer.mergeAll(
169 Layer.succeed(Devices.Devices, input.devices),
170 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
171 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
172 Layer.succeed(LiveActivities.LiveActivities, input.liveActivities),
173 Layer.succeed(DeliveryAttempts.DeliveryAttempts, makeDeliveryAttempts()),
174 RelayConfiguration.layer(config),
175 Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {
176 send: (body) =>
177 Effect.sync(() => {
178 input.queuedJobs.push(body);
179 }),
180 }),
181 ),
182 ),
183 Layer.provide(FetchHttpClient.layer),
184 );
186​
187function makeAgentActivityPublisher(
188 overrides: Partial<AgentActivityPublisher.AgentActivityPublisher["Service"]> = {},
189): AgentActivityPublisher.AgentActivityPublisher["Service"] {
190 return {
191 publish: () => Effect.succeed({ ok: true, deliveries: [] }),
192 replayForLiveActivityRegistration: () => Effect.succeed(null),
193 ...overrides,
194 };
196​
197describe("MobileRegistrations", () => {
198 it.effect("registers devices through the device persistence service", () => {
199 let registered: Parameters<Devices.Devices["Service"]["register"]>[0] | null = null;
200 let replayed:
201 | Parameters<
202 AgentActivityPublisher.AgentActivityPublisher["Service"]["replayForLiveActivityRegistration"]
203 >[0]
204 | null = null;
205​
206 return Effect.gen(function* () {
207 const result = yield* Effect.gen(function* () {
208 const registrations = yield* MobileRegistrations.MobileRegistrations;
209 return yield* registrations.registerDevice({ userId: "dev:julius", payload: device });
210 }).pipe(
211 Effect.provide(
212 MobileRegistrations.layer.pipe(
213 Layer.provide(
214 Layer.mergeAll(
215 Layer.succeed(
216 Devices.Devices,
217 makeDevices({
218 register: (input) =>
219 Effect.sync(() => {
220 registered = input;
221 }),
222 }),
223 ),
224 Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()),
225 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
226 Layer.succeed(
227 AgentActivityPublisher.AgentActivityPublisher,
228 makeAgentActivityPublisher({
229 replayForLiveActivityRegistration: (input) =>
230 Effect.sync(() => {
231 replayed = input;
232 return null;
233 }),
234 }),
235 ),
236 ),
237 ),
238 ),
239 ),
240 );
241​
242 expect(result).toEqual({ ok: true });
243 expect(registered).toEqual({ userId: "dev:julius", registration: device });
244 expect(replayed).toEqual({
245 userId: "dev:julius",
246 deviceId: "device-1",
247 });
248 });
249 });
250​
251 it.effect("keeps device registration successful when activity replay fails", () => {
252 const messages: unknown[] = [];
253 const logger = Logger.make(({ message }) => {
254 messages.push(message);
255 });
256​
257 return Effect.gen(function* () {
258 const result = yield* Effect.gen(function* () {
259 const registrations = yield* MobileRegistrations.MobileRegistrations;
260 return yield* registrations.registerDevice({ userId: "dev:julius", payload: device });
261 }).pipe(
262 Effect.provide(
263 MobileRegistrations.layer.pipe(
264 Layer.provide(
265 Layer.mergeAll(
266 Layer.succeed(Devices.Devices, makeDevices()),
267 Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()),
268 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
269 Layer.succeed(
270 AgentActivityPublisher.AgentActivityPublisher,
271 makeAgentActivityPublisher({
272 replayForLiveActivityRegistration: () =>
273 Effect.fail(
274 new AgentActivityRows.AgentActivityRowListPersistenceError({
275 userId: "dev:julius",
276 cause: "sensitive device replay detail",
277 }),
278 ),
279 }),
280 ),
281 ),
282 ),
283 ),
284 ),
285 );
286​
287 expect(result).toEqual({ ok: true });
288 expect(messages).toContainEqual([
289 "device registration activity replay failed",
290 { errorTag: "AgentActivityRowListPersistenceError" },
291 ]);
292 }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
293 });
294​
295 it.effect("unregisters the current user's device", () => {
296 let unregistered: Parameters<Devices.Devices["Service"]["unregister"]>[0] | null = null;
297​
298 return Effect.gen(function* () {
299 const result = yield* Effect.gen(function* () {
300 const registrations = yield* MobileRegistrations.MobileRegistrations;
301 return yield* registrations.unregisterDevice({
302 userId: "dev:julius",
303 deviceId: "device-1",
304 });
305 }).pipe(
306 Effect.provide(
307 MobileRegistrations.layer.pipe(
308 Layer.provide(
309 Layer.mergeAll(
310 Layer.succeed(
311 Devices.Devices,
312 makeDevices({
313 unregister: (input) =>
314 Effect.sync(() => {
315 unregistered = input;
316 }),
317 }),
318 ),
319 Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()),
320 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
321 Layer.succeed(
322 AgentActivityPublisher.AgentActivityPublisher,
323 makeAgentActivityPublisher(),
324 ),
325 ),
326 ),
327 ),
328 ),
329 );
330​
331 expect(result).toEqual({ ok: true });
332 expect(unregistered).toEqual({
333 userId: "dev:julius",
334 deviceId: "device-1",
335 });
336 });
337 });
338​
339 it.effect("replays the latest activity state after registering a Live Activity token", () => {
340 const liveActivity = {
341 deviceId: "device-1" as const,
342 activityPushToken: "activity-token" as const,
343 };
344 let registered: Parameters<LiveActivities.LiveActivities["Service"]["register"]>[0] | null =
345 null;
346 let replayed:
347 | Parameters<
348 AgentActivityPublisher.AgentActivityPublisher["Service"]["replayForLiveActivityRegistration"]
349 >[0]
350 | null = null;
351​
352 return Effect.gen(function* () {
353 const result = yield* Effect.gen(function* () {
354 const registrations = yield* MobileRegistrations.MobileRegistrations;
355 return yield* registrations.registerLiveActivity({
356 userId: "dev:julius",
357 payload: liveActivity,
358 });
359 }).pipe(
360 Effect.provide(
361 MobileRegistrations.layer.pipe(
362 Layer.provide(
363 Layer.mergeAll(
364 Layer.succeed(Devices.Devices, makeDevices()),
365 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
366 Layer.succeed(
367 LiveActivities.LiveActivities,
368 makeLiveActivities({
369 register: (input) =>
370 Effect.sync(() => {
371 registered = input;
372 }),
373 }),
374 ),
375 Layer.succeed(
376 AgentActivityPublisher.AgentActivityPublisher,
377 makeAgentActivityPublisher({
378 replayForLiveActivityRegistration: (input) =>
379 Effect.sync(() => {
380 replayed = input;
381 return null;
382 }),
383 }),
384 ),
385 ),
386 ),
387 ),
388 ),
389 );
390​
391 expect(result).toEqual({ ok: true });
392 expect(registered).toEqual({
393 userId: "dev:julius",
394 registration: liveActivity,
395 });
396 expect(replayed).toEqual({
397 userId: "dev:julius",
398 deviceId: "device-1",
399 });
400 });
401 });
402​
403 it.effect("returns the current aggregate for the app's arming decision", () => {
404 return Effect.gen(function* () {
405 const registrations = yield* MobileRegistrations.MobileRegistrations;
406 const snapshot = yield* registrations.getAgentActivitySnapshot({ userId: "dev:julius" });
407​
408 expect(snapshot.aggregate).toMatchObject({
409 activeCount: 1,
410 activities: [{ threadId: "thread-1", phase: "running" }],
411 });
412 }).pipe(
413 Effect.provide(
414 MobileRegistrations.layer.pipe(
415 Layer.provide(
416 Layer.mergeAll(
417 Layer.succeed(Devices.Devices, makeDevices()),
418 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
419 Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()),
420 Layer.succeed(
421 AgentActivityPublisher.AgentActivityPublisher,
422 makeAgentActivityPublisher(),
423 ),
424 ),
425 ),
426 ),
427 ),
428 );
429 });
430​
431 it.effect(
432 "does not remotely start a Live Activity when a device registers after work is already active",
433 () => {
434 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
435 const queuedStarts: Array<
436 Parameters<LiveActivities.LiveActivities["Service"]["markStartQueued"]>[0]
437 > = [];
438 const registeredDevices: Array<Parameters<Devices.Devices["Service"]["register"]>[0]> = [];
439 const devices = makeDevices({
440 register: (input) =>
441 Effect.sync(() => {
442 registeredDevices.push(input);
443 }),
444 });
445 const liveActivities = makeLiveActivities({
446 listTargets: () =>
447 Effect.succeed([
448 {
449 user_id: "dev:julius",
450 device_id: "device-1",
451 platform: "ios",
452 ios_major_version: 18,
453 app_version: "1.0.0",
454 bundle_id: null,
455 aps_environment: null,
456 push_token: "apns-device-token",
457 push_to_start_token: "push-to-start-token",
458 preferences_json: JSON.stringify(device.preferences),
459 activity_push_token: null,
460 remote_start_queued_at: null,
461 remote_started_at: null,
462 ended_at: null,
463 last_aggregate_json: null,
464 last_live_activity_delivery_at: null,
465 },
466 ]),
467 markStartQueued: (input) =>
468 Effect.sync(() => {
469 queuedStarts.push(input);
470 }),
471 });
472​
473 return Effect.gen(function* () {
474 const registrations = yield* MobileRegistrations.MobileRegistrations;
475 const result = yield* registrations.registerDevice({
476 userId: "dev:julius",
477 payload: {
478 ...device,
479 pushToken: "apns-device-token",
480 pushToStartToken: "push-to-start-token",
481 },
482 });
483​
484 // Activities are armed by the app in the foreground; a device
485 // registration alone never remote-starts one, even when work is
486 // already active and a push-to-start token is on file.
487 expect(result).toEqual({ ok: true });
488 expect(registeredDevices).toHaveLength(1);
489 expect(queuedStarts).toEqual([]);
490 expect(queuedJobs).toEqual([]);
491 }).pipe(Effect.provide(makeRegistrationReplayLayer({ devices, liveActivities, queuedJobs })));
492 },
493 );
494});