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