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

remoteRegistration.test.ts

1,127 lines41.8 KB

1/// <reference types="node" />
2​
3import * as NodeCrypto from "node:crypto";
4​
5import { beforeEach, vi } from "vite-plus/test";
6import { describe, expect, it } from "@effect/vitest";
7import Constants from "expo-constants";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Layer from "effect/Layer";
12import { Cookies, FetchHttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
13import { ManagedRelay } from "@t3tools/client-runtime/relay";
14​
15import type { EnvironmentId } from "@t3tools/contracts";
16import { verifyDpopProof } from "@t3tools/shared/dpop";
17import type { SavedRemoteConnection } from "../../lib/connection";
18import * as Dpop from "../cloud/dpop";
19import * as ManagedRelayLayer from "../cloud/managedRelayLayer";
20import {
21 clearAgentAwarenessRegistrationRecord,
22 loadAgentAwarenessRegistrationRecord,
23 loadOrCreateAgentAwarenessDeviceId,
24 loadPreferences,
25 saveAgentAwarenessRegistrationRecord,
26} from "../../persistence/imperative";
27import type { Preferences } from "../../persistence/mobile-preferences";
28import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
29import {
30 AgentAwarenessOperationError,
31 __resetAgentAwarenessRemoteRegistrationForTest,
32 armAgentAwarenessLiveActivityForLocalWork,
33 getAgentAwarenessRegistrationStatus,
34 mergeAgentAwarenessRegistrationPreferences,
35 refreshActiveLiveActivityRemoteRegistration,
36 refreshAgentAwarenessRegistration,
37 registerAgentAwarenessConnection,
38 registerLiveActivityPushToken,
39 releaseAgentAwarenessRelayTokenProvider,
40 setAgentAwarenessRelayTokenProvider,
41 shouldRegisterAgentAwarenessDeviceForProvider,
42 unregisterAgentAwarenessConnection,
43 updateAgentAwarenessRegistrationPreferences,
44} from "./remoteRegistration";
45import * as Notifications from "expo-notifications";
46import { Platform } from "react-native";
47import {
48 configureAndroidAgentNotifications,
49 clearAndroidAgentNotifications,
50} from "./androidNotifications";
51​
52vi.mock("./androidNotifications", () => ({
53 supportsAndroidAgentNotifications: vi.fn(() => true),
54 configureAndroidAgentNotifications: vi.fn(),
55 clearAndroidAgentNotifications: vi.fn(),
56}));
57​
58const secureStore = vi.hoisted(() => new Map<string, string>());
59const widgetMocks = vi.hoisted(() => ({
60 getInstances: vi.fn(() => []),
61 start: vi.fn(() => ({})),
62}));
63const environmentConfigsMock = vi.hoisted(() => ({
64 configs: new Map<
65 string,
66 { environment: { capabilities: { agentActivityPublishing?: boolean } } }
67 >(),
68}));
69const backgroundRuntime = vi.hoisted(() => ({
70 pending: [] as Array<{
71 readonly operation: unknown;
72 readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;
73 }>,
74}));
75const appStateMock = vi.hoisted(() => ({
76 listeners: [] as Array<(state: string) => void>,
77}));
78const registrationRecordStore = vi.hoisted(() => ({
79 current: null as {
80 readonly identity: string;
81 readonly signature: string;
82 readonly pushToStartToken?: string;
83 } | null,
84}));
85​
86vi.mock("expo-constants", () => ({
87 default: {
88 expoConfig: {
89 version: "1.0.0",
90 extra: {},
91 },
92 },
93}));
94​
95vi.mock("expo-widgets", () => ({
96 addPushToStartTokenListener: vi.fn(() => ({ remove: vi.fn() })),
97}));
98​
99vi.mock("./agentLiveActivity", () => ({
100 getAgentLiveActivities: widgetMocks.getInstances,
101 startAgentLiveActivity: widgetMocks.start,
102}));
103​
104// The state modules pull the whole connection stack (and native expo modules)
105// into the import graph; the arming gate only needs the configs map.
106vi.mock("../../state/atom-registry", () => ({
107 appAtomRegistry: {
108 get: () => environmentConfigsMock.configs,
109 },
110}));
111​
112vi.mock("../../state/server", () => ({
113 environmentServerConfigsAtom: Symbol("environmentServerConfigsAtom"),
114}));
115​
116vi.mock("expo-notifications", () => ({
117 addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
118 getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),
119 getPermissionsAsync: vi.fn(() => Promise.resolve({ granted: true })),
120}));
121​
122vi.mock("expo-crypto", () => ({
123 CryptoDigestAlgorithm: {
124 SHA1: "SHA-1",
125 SHA256: "SHA-256",
126 SHA384: "SHA-384",
127 SHA512: "SHA-512",
128 },
129 getRandomBytes: (byteCount: number) => new Uint8Array(NodeCrypto.randomBytes(byteCount)),
130 getRandomBytesAsync: (byteCount: number) =>
131 Promise.resolve(new Uint8Array(NodeCrypto.randomBytes(byteCount))),
132 digest: (algorithm: string, data: unknown) => {
133 if (!(data instanceof Uint8Array)) {
134 return Promise.reject(new TypeError("expo-crypto digest data must be a typed array."));
135 }
136 return Promise.resolve(
137 new Uint8Array(NodeCrypto.createHash(algorithm).update(data).digest()).buffer,
138 );
139 },
140}));
141​
142vi.mock("expo-secure-store", () => ({
143 getItemAsync: (key: string) => Promise.resolve(secureStore.get(key) ?? null),
144 setItemAsync: (key: string, value: string) => {
145 secureStore.set(key, value);
146 return Promise.resolve();
147 },
148}));
149​
150vi.mock("react-native", () => ({
151 Platform: {
152 get OS() {
153 return "ios";
154 },
155 get Version() {
156 return "18.0";
157 },
158 },
159 AppState: {
160 addEventListener: (_event: string, listener: (state: string) => void) => {
161 appStateMock.listeners.push(listener);
162 return {
163 remove: () => {
164 const index = appStateMock.listeners.indexOf(listener);
165 if (index >= 0) {
166 appStateMock.listeners.splice(index, 1);
167 }
168 },
169 };
170 },
171 },
172}));
173​
174vi.mock("../../lib/runtime", () => ({
175 runtime: {
176 runPromiseExit: (operation: unknown) =>
177 new Promise((resolve) => {
178 backgroundRuntime.pending.push({ operation, resolve });
179 }),
180 },
181}));
182​
183vi.mock("../../persistence/imperative", () => ({
184 loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
185 loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
186 loadPreferences: vi.fn(() => Promise.resolve({ liveActivitiesEnabled: false })),
187 loadAgentAwarenessRegistrationRecord: vi.fn(() =>
188 Promise.resolve(registrationRecordStore.current),
189 ),
190 saveAgentAwarenessRegistrationRecord: vi.fn((record: { identity: string; signature: string }) => {
191 registrationRecordStore.current = record;
192 return Promise.resolve();
193 }),
194 clearAgentAwarenessRegistrationRecord: vi.fn(() => {
195 registrationRecordStore.current = null;
196 return Promise.resolve();
197 }),
198}));
199​
200function proofIat(proof: string): number {
201 const payload = proof.split(".")[1];
202 if (!payload) {
203 throw new Error("Missing DPoP payload.");
204 }
205 const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
206 readonly iat: number;
207 };
208 return decoded.iat;
210​
211function savedConnection(): SavedRemoteConnection {
212 return {
213 environmentId: "env-1" as EnvironmentId,
214 environmentLabel: "Desktop",
215 pairingUrl: "https://desktop.example/pair",
216 displayUrl: "https://desktop.example",
217 httpBaseUrl: "https://desktop.example",
218 wsBaseUrl: "wss://desktop.example/ws",
219 bearerToken: "bearer-token",
220 };
222​
223const layerRelayTest = ManagedRelayLayer.layer("https://relay.example.test").pipe(
224 Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Dpop.layer)),
225);
226​
227const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(
228 function* () {
229 let idlePasses = 0;
230 for (;;) {
231 yield* Effect.promise(() => Promise.resolve());
232 const pending = backgroundRuntime.pending.shift();
233 if (!pending) {
234 idlePasses++;
235 if (idlePasses >= 3) {
236 return;
237 }
238 continue;
239 }
240 idlePasses = 0;
241 const exit = yield* Effect.exit(
242 pending.operation as Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
243 );
244 yield* Effect.sync(() => {
245 pending.resolve(exit);
246 });
247 }
248 },
249);
250​
251describe("makeRelayDeviceRegistrationRequest", () => {
252 beforeEach(() => {
253 vi.restoreAllMocks();
254 vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
255 type: "ios",
256 data: "apns-token",
257 });
258 vi.unstubAllGlobals();
259 vi.stubGlobal("__DEV__", false);
260 secureStore.clear();
261 backgroundRuntime.pending.length = 0;
262 Constants.expoConfig!.extra = {};
263 __resetAgentAwarenessRemoteRegistrationForTest();
264 appStateMock.listeners.length = 0;
265 registrationRecordStore.current = null;
266 vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
267 vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear();
268 vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear();
269 vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
270 widgetMocks.getInstances.mockReset();
271 widgetMocks.getInstances.mockReturnValue([]);
272 widgetMocks.start.mockClear();
273 environmentConfigsMock.configs.clear();
274 });
275​
276 it("preserves disabled Live Activity preferences in relay registrations", () => {
277 expect(
278 makeRelayDeviceRegistrationRequest({
279 deviceId: "device-1",
280 label: "Julius's iPhone",
281 iosMajorVersion: 18,
282 appVersion: "1.0.0",
283 pushToken: "apns-token",
284 pushToStartToken: "push-to-start-token",
285 notificationsEnabled: true,
286 preferences: {
287 liveActivitiesEnabled: false,
288 },
289 }),
290 ).toEqual({
291 deviceId: "device-1",
292 label: "Julius's iPhone",
293 platform: "ios",
294 iosMajorVersion: 18,
295 appVersion: "1.0.0",
296 pushToken: "apns-token",
297 pushToStartToken: "push-to-start-token",
298 preferences: {
299 liveActivitiesEnabled: false,
300 notificationsEnabled: true,
301 notifyOnApproval: true,
302 notifyOnInput: true,
303 notifyOnCompletion: true,
304 notifyOnFailure: true,
305 },
306 });
307 });
308​
309 it("registers the app's APNs routing so the relay targets the right bundle", () => {
310 expect(
311 makeRelayDeviceRegistrationRequest({
312 deviceId: "device-1",
313 label: "Julius's iPhone",
314 iosMajorVersion: 18,
315 appVersion: "1.0.0",
316 bundleId: "com.t3tools.t3code.preview",
317 apsEnvironment: resolveApsEnvironment("preview"),
318 notificationsEnabled: true,
319 preferences: {},
320 }),
321 ).toMatchObject({
322 bundleId: "com.t3tools.t3code.preview",
323 apsEnvironment: "production",
324 });
325 });
326​
327 it("routes development builds to the APNs sandbox", () => {
328 expect(resolveApsEnvironment("development")).toBe("sandbox");
329 expect(resolveApsEnvironment("preview")).toBe("production");
330 expect(resolveApsEnvironment("production")).toBe("production");
331 expect(resolveApsEnvironment(undefined)).toBe("production");
332 });
333​
334 it("disables push features in Personal Team relay registrations", () => {
335 Constants.expoConfig!.extra = { iosPersonalTeamBuild: true };
336​
337 expect(
338 makeRelayDeviceRegistrationRequest({
339 deviceId: "device-1",
340 label: "Julius's iPhone",
341 iosMajorVersion: 18,
342 appVersion: "1.0.0",
343 pushToken: "apns-token",
344 pushToStartToken: "push-to-start-token",
345 notificationsEnabled: true,
346 preferences: {},
347 }).preferences,
348 ).toMatchObject({
349 liveActivitiesEnabled: false,
350 notificationsEnabled: false,
351 });
352 });
353​
354 it("marks notification delivery disabled when APNs permission is unavailable", () => {
355 expect(
356 makeRelayDeviceRegistrationRequest({
357 deviceId: "device-1",
358 label: "Julius's iPhone",
359 iosMajorVersion: 18,
360 appVersion: "1.0.0",
361 pushToStartToken: "push-to-start-token",
362 notificationsEnabled: false,
363 preferences: {
364 liveActivitiesEnabled: true,
365 },
366 }),
367 ).toEqual({
368 deviceId: "device-1",
369 label: "Julius's iPhone",
370 platform: "ios",
371 iosMajorVersion: 18,
372 appVersion: "1.0.0",
373 pushToStartToken: "push-to-start-token",
374 preferences: {
375 liveActivitiesEnabled: true,
376 notificationsEnabled: false,
377 notifyOnApproval: true,
378 notifyOnInput: true,
379 notifyOnCompletion: true,
380 notifyOnFailure: true,
381 },
382 });
383 });
384​
385 it("overrides persisted preferences for an in-flight registration", () => {
386 expect(
387 mergeAgentAwarenessRegistrationPreferences(
388 { liveActivitiesEnabled: false, baseFontSize: 18 },
389 { liveActivitiesEnabled: true },
390 ),
391 ).toEqual({ liveActivitiesEnabled: true, baseFontSize: 18 });
392 });
393​
394 it.effect("registers at most one listener while a Live Activity push token is pending", () => {
395 registerAgentAwarenessConnection(savedConnection());
396 const addPushTokenListener = vi.fn();
397 const activity = {
398 getPushToken: vi.fn(() => Promise.resolve(null)),
399 addPushTokenListener,
400 };
401​
402 return Effect.gen(function* () {
403 expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
404 expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
405​
406 expect(activity.getPushToken).toHaveBeenCalledTimes(2);
407 expect(addPushTokenListener).toHaveBeenCalledTimes(1);
408 }).pipe(Effect.provide(layerRelayTest));
409 });
410​
411 it.effect("preserves Live Activity push-token lookup failures", () => {
412 const cause = new Error("native token lookup failed");
413 const activity = {
414 getPushToken: vi.fn(() => Promise.reject(cause)),
415 addPushTokenListener: vi.fn(),
416 };
417​
418 return Effect.gen(function* () {
419 const error = yield* Effect.flip(
420 registerLiveActivityPushToken({ activity: activity as never }),
421 );
422​
423 expect(error).toBeInstanceOf(AgentAwarenessOperationError);
424 expect(error).toMatchObject({
425 _tag: "AgentAwarenessOperationError",
426 operation: "read-live-activity-push-token",
427 cause,
428 message: "Agent awareness operation read-live-activity-push-token failed.",
429 });
430 }).pipe(Effect.provide(layerRelayTest));
431 });
432​
433 it.effect(
434 "reports Live Activity token registration as skipped when relay auth is unavailable",
435 () => {
436 registerAgentAwarenessConnection(savedConnection());
437 const activity = {
438 getPushToken: vi.fn(() => Promise.resolve("activity-token")),
439 addPushTokenListener: vi.fn(),
440 };
441​
442 return Effect.gen(function* () {
443 expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
444 }).pipe(Effect.provide(layerRelayTest));
445 },
446 );
447​
448 it.effect(
449 "registers APNS-started Live Activities for relay updates without mutating them locally",
450 () => {
451 const activity = {
452 getPushToken: vi.fn(() => Promise.resolve("activity-token")),
453 addPushTokenListener: vi.fn(),
454 start: vi.fn(),
455 update: vi.fn(),
456 end: vi.fn(),
457 };
458 widgetMocks.getInstances.mockReturnValue([activity] as never);
459 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
460​
461 return Effect.gen(function* () {
462 yield* refreshActiveLiveActivityRemoteRegistration();
463​
464 expect(activity.getPushToken).toHaveBeenCalled();
465 expect(activity.start).not.toHaveBeenCalled();
466 expect(activity.update).not.toHaveBeenCalled();
467 expect(activity.end).not.toHaveBeenCalled();
468 }).pipe(Effect.provide(layerRelayTest));
469 },
470 );
471​
472 it.effect(
473 "re-registers active Live Activity tokens when the app returns to the foreground",
474 () => {
475 const activity = {
476 getPushToken: vi.fn(() => Promise.resolve("activity-token")),
477 addPushTokenListener: vi.fn(),
478 };
479 widgetMocks.getInstances.mockReturnValue([activity] as never);
480 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
481​
482 return Effect.gen(function* () {
483 yield* runBackgroundOperations();
484 activity.getPushToken.mockClear();
485​
486 expect(appStateMock.listeners).toHaveLength(1);
487 for (const listener of appStateMock.listeners) {
488 listener("background");
489 }
490 yield* runBackgroundOperations();
491 expect(activity.getPushToken).not.toHaveBeenCalled();
492​
493 for (const listener of appStateMock.listeners) {
494 listener("active");
495 }
496 yield* runBackgroundOperations();
497 expect(activity.getPushToken).toHaveBeenCalled();
498 }).pipe(Effect.provide(layerRelayTest));
499 },
500 );
501​
502 it("ends local Live Activities and stops foreground reconciliation on cloud sign-out", () => {
503 const end = vi.fn(() => Promise.resolve());
504 const activity = {
505 getPushToken: vi.fn(() => Promise.resolve("activity-token")),
506 addPushTokenListener: vi.fn(),
507 end,
508 };
509 widgetMocks.getInstances.mockReturnValue([activity] as never);
510 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
511 expect(appStateMock.listeners).toHaveLength(1);
512​
513 setAgentAwarenessRelayTokenProvider(null);
514​
515 expect(end).toHaveBeenCalledWith("immediate");
516 expect(appStateMock.listeners).toHaveLength(0);
517 });
518​
519 it.effect("refreshes APNs registration for connected environments after settings changes", () => {
520 registerAgentAwarenessConnection(savedConnection());
521 return Effect.gen(function* () {
522 yield* runBackgroundOperations();
523 vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
524​
525 yield* refreshAgentAwarenessRegistration();
526​
527 expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
528 }).pipe(Effect.provide(layerRelayTest));
529 });
530​
531 it.effect("registers the APNs device when cloud auth becomes available", () => {
532 const fetchMock = vi.fn((request: RequestInfo | URL) => {
533 const url = request instanceof Request ? request.url : String(request);
534 return Promise.resolve(
535 Response.json(
536 url.endsWith("/v1/client/dpop-token")
537 ? {
538 access_token: "relay-dpop-token",
539 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
540 token_type: "DPoP",
541 expires_in: 300,
542 scope: "mobile:registration",
543 }
544 : { ok: true },
545 ),
546 );
547 });
548 vi.stubGlobal("fetch", fetchMock);
549 Constants.expoConfig!.extra = {
550 relay: {
551 url: "https://relay.example.test/",
552 },
553 };
554​
555 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
556​
557 return Effect.gen(function* () {
558 yield* runBackgroundOperations();
559​
560 expect(fetchMock).toHaveBeenCalledTimes(2);
561 const [request, init] = fetchMock.mock.calls[1] as unknown as [
562 unknown,
563 RequestInit | undefined,
564 ];
565 const url = request instanceof Request ? request.url : String(request);
566 const method = request instanceof Request ? request.method : init?.method;
567 const headers = request instanceof Request ? request.headers : new Headers(init?.headers);
568 const dpop = headers.get("dpop");
569 expect(url).toBe("https://relay.example.test/v1/mobile/devices");
570 expect(method).toBe("POST");
571 expect(headers.get("authorization")).toBe("DPoP relay-dpop-token");
572 expect(dpop).toEqual(expect.any(String));
573 if (!dpop) {
574 throw new Error("Missing DPoP header.");
575 }
576 expect(
577 verifyDpopProof({
578 proof: dpop,
579 method: "POST",
580 url: "https://relay.example.test/v1/mobile/devices",
581 expectedAccessToken: "relay-dpop-token",
582 nowEpochSeconds: proofIat(dpop),
583 }),
584 ).toMatchObject({ ok: true });
585 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
586 }).pipe(Effect.provide(layerRelayTest));
587 });
588​
589 it.effect("marks registration failed when device registration cannot complete", () => {
590 Constants.expoConfig!.extra = {
591 relay: {
592 url: "https://relay.example.test/",
593 },
594 };
595 vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
596 new Error("registration failed"),
597 );
598 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
599​
600 return Effect.gen(function* () {
601 yield* refreshAgentAwarenessRegistration();
602 expect(getAgentAwarenessRegistrationStatus()).toBe("failed");
603 }).pipe(Effect.provide(layerRelayTest));
604 });
605​
606 it("clears registration status on cloud sign-out", () => {
607 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
608 setAgentAwarenessRelayTokenProvider(null);
609 expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
610 expect(clearAgentAwarenessRegistrationRecord).toHaveBeenCalled();
611 });
612​
613 it("releases the provider without ending activities or clearing the registration", () => {
614 const end = vi.fn(() => Promise.resolve());
615 const activity = {
616 getPushToken: vi.fn(() => Promise.resolve("activity-token")),
617 addPushTokenListener: vi.fn(),
618 end,
619 };
620 widgetMocks.getInstances.mockReturnValue([activity] as never);
621 registrationRecordStore.current = { identity: "", signature: "sig" };
622 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
623 expect(appStateMock.listeners).toHaveLength(1);
624​
625 releaseAgentAwarenessRelayTokenProvider();
626​
627 expect(appStateMock.listeners).toHaveLength(0);
628 expect(end).not.toHaveBeenCalled();
629 expect(clearAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
630 expect(registrationRecordStore.current).not.toBeNull();
631 });
632​
633 it.effect("resets a pending status to unknown when relay config is missing", () => {
634 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
635​
636 return Effect.gen(function* () {
637 yield* runBackgroundOperations();
638 expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
639 }).pipe(Effect.provide(layerRelayTest));
640 });
641​
642 it.effect("keeps a registered status when a later refresh fails", () => {
643 Constants.expoConfig!.extra = {
644 relay: {
645 url: "https://relay.example.test/",
646 },
647 };
648 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
649​
650 return Effect.gen(function* () {
651 yield* runBackgroundOperations();
652 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
653​
654 vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
655 new Error("transient failure"),
656 );
657 yield* refreshAgentAwarenessRegistration();
658 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
659 }).pipe(Effect.provide(layerRelayTest));
660 });
661​
662 it.effect("does not re-register the same account when nothing has changed", () => {
663 Constants.expoConfig!.extra = {
664 relay: {
665 url: "https://relay.example.test/",
666 },
667 };
668 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
669​
670 return Effect.gen(function* () {
671 yield* refreshAgentAwarenessRegistration();
672 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
673 expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
674 expect(registrationRecordStore.current).not.toBeNull();
675​
676 vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
677 yield* refreshAgentAwarenessRegistration();
678 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
679 expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
680 }).pipe(Effect.provide(layerRelayTest));
681 });
682​
683 it.effect("dedupes rapid activity-token re-registrations within the replay window", () => {
684 // Fetch counts are unreliable here (the module-level relay layer captures
685 // the first test's fetch), so assert on the flow's own seams: a real
686 // registration attempt loads the device id, a deduped one short-circuits
687 // before it.
688 const fetchMock = vi.fn((request: RequestInfo | URL) => {
689 const url = request instanceof Request ? request.url : String(request);
690 return Promise.resolve(
691 Response.json(
692 url.endsWith("/v1/client/dpop-token")
693 ? {
694 access_token: "relay-dpop-token",
695 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
696 token_type: "DPoP",
697 expires_in: 300,
698 scope: "mobile:registration",
699 }
700 : { ok: true },
701 ),
702 );
703 });
704 vi.stubGlobal("fetch", fetchMock);
705 Constants.expoConfig!.extra = {
706 relay: {
707 url: "https://relay.example.test/",
708 },
709 };
710 const activity = {
711 getPushToken: vi.fn(() => Promise.resolve("activity-token")),
712 addPushTokenListener: vi.fn(),
713 };
714 widgetMocks.getInstances.mockReturnValue([activity] as never);
715 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
716​
717 return Effect.gen(function* () {
718 yield* runBackgroundOperations();
719 expect(activity.getPushToken).toHaveBeenCalled();
720​
721 vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockClear();
722 yield* refreshActiveLiveActivityRemoteRegistration();
723 expect(loadOrCreateAgentAwarenessDeviceId).not.toHaveBeenCalled();
724 }).pipe(Effect.provide(layerRelayTest));
725 });
726​
727 it.effect("re-registers when the stored account identity differs", () => {
728 Constants.expoConfig!.extra = {
729 relay: {
730 url: "https://relay.example.test/",
731 },
732 };
733 registrationRecordStore.current = { identity: "someone-else", signature: "stale" };
734 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
735​
736 return Effect.gen(function* () {
737 yield* refreshAgentAwarenessRegistration();
738 expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
739 }).pipe(Effect.provide(layerRelayTest));
740 });
741​
742 it.effect("coalesces simultaneous sign-in and environment connection registrations", () => {
743 const fetchMock = vi.fn((request: RequestInfo | URL) => {
744 const url = request instanceof Request ? request.url : String(request);
745 return Promise.resolve(
746 Response.json(
747 url.endsWith("/v1/client/dpop-token")
748 ? {
749 access_token: "relay-dpop-token",
750 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
751 token_type: "DPoP",
752 expires_in: 300,
753 scope: "mobile:registration",
754 }
755 : { ok: true },
756 ),
757 );
758 });
759 vi.stubGlobal("fetch", fetchMock);
760 Constants.expoConfig!.extra = {
761 relay: {
762 url: "https://relay.example.test/",
763 },
764 };
765​
766 vi.mocked(Notifications.getPermissionsAsync).mockClear();
767 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
768 registerAgentAwarenessConnection(savedConnection());
769​
770 return Effect.gen(function* () {
771 yield* runBackgroundOperations();
772 expect(Notifications.getPermissionsAsync).toHaveBeenCalledTimes(1);
773 }).pipe(Effect.provide(layerRelayTest));
774 });
775​
776 it.effect("continues queued device registration after a failed auth lookup", () => {
777 Constants.expoConfig!.extra = {
778 relay: {
779 url: "https://relay.example.test/",
780 },
781 };
782​
783 const tokenProvider = vi
784 .fn<() => Promise<string | null>>()
785 .mockRejectedValueOnce(new Error("auth unavailable"))
786 .mockResolvedValue("clerk-token-user-a");
787 setAgentAwarenessRelayTokenProvider(tokenProvider);
788 const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
789 expect(tokenListener).toBeDefined();
790 tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
791​
792 return Effect.gen(function* () {
793 yield* runBackgroundOperations();
794​
795 expect(backgroundRuntime.pending).toHaveLength(0);
796 expect(tokenProvider).toHaveBeenCalledTimes(2);
797 }).pipe(Effect.provide(layerRelayTest));
798 });
799​
800 it("only registers again when the authenticated identity changes", () => {
801 expect(shouldRegisterAgentAwarenessDeviceForProvider(null, "user-a")).toBe(true);
802 expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", "user-a")).toBe(false);
803 expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", "user-b")).toBe(true);
804 expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", undefined)).toBe(true);
805 });
806​
807 it.effect("registers rotated APNs tokens without rereading the native token", () => {
808 const fetchMock = vi.fn((request: RequestInfo | URL) => {
809 const url = request instanceof Request ? request.url : String(request);
810 return Promise.resolve(
811 Response.json(
812 url.endsWith("/v1/client/dpop-token")
813 ? {
814 access_token: "relay-dpop-token",
815 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
816 token_type: "DPoP",
817 expires_in: 300,
818 scope: "mobile:registration",
819 }
820 : { ok: true },
821 ),
822 );
823 });
824 vi.stubGlobal("fetch", fetchMock);
825 Constants.expoConfig!.extra = {
826 relay: {
827 url: "https://relay.example.test/",
828 },
829 };
830​
831 vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();
832 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
833​
834 const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
835 expect(tokenListener).toBeDefined();
836 tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
837​
838 return Effect.gen(function* () {
839 yield* runBackgroundOperations();
840 expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);
841 }).pipe(Effect.provide(layerRelayTest));
842 });
843​
844 it.effect(
845 "keeps the user-scoped relay APNs device when an environment connection is removed",
846 () => {
847 const fetchMock = vi.fn((request: RequestInfo | URL) => {
848 const url = request instanceof Request ? request.url : String(request);
849 return Promise.resolve(
850 Response.json(
851 url.endsWith("/v1/client/dpop-token")
852 ? {
853 access_token: "relay-dpop-token",
854 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
855 token_type: "DPoP",
856 expires_in: 300,
857 scope: "mobile:registration",
858 }
859 : { ok: true },
860 ),
861 );
862 });
863 vi.stubGlobal("fetch", fetchMock);
864 Constants.expoConfig!.extra = {
865 relay: {
866 url: "https://relay.example.test/",
867 },
868 };
869​
870 registerAgentAwarenessConnection(savedConnection());
871 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
872 return Effect.gen(function* () {
873 yield* runBackgroundOperations();
874 fetchMock.mockClear();
875​
876 unregisterAgentAwarenessConnection(savedConnection().environmentId);
877​
878 expect(fetchMock).not.toHaveBeenCalled();
879 }).pipe(Effect.provide(layerRelayTest));
880 },
881 );
882​
883 it("skips the Live Activity seed when the environment reports publishing disabled", async () => {
884 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
885 vi.mocked(loadPreferences).mockResolvedValueOnce({
886 liveActivitiesEnabled: true,
887 } as Preferences);
888 environmentConfigsMock.configs.set("env-1", {
889 environment: { capabilities: { agentActivityPublishing: false } },
890 });
891​
892 armAgentAwarenessLiveActivityForLocalWork({
893 environmentId: "env-1" as EnvironmentId,
894 threadTitle: "Fix the flaky test",
895 projectTitle: "t3code",
896 });
897 await new Promise((resolve) => setTimeout(resolve, 0));
898​
899 expect(widgetMocks.start).not.toHaveBeenCalled();
900 });
901​
902 it("seeds the Live Activity for publishing and pre-capability environments", async () => {
903 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
904 environmentConfigsMock.configs.set("env-publishing", {
905 environment: { capabilities: { agentActivityPublishing: true } },
906 });
907​
908 vi.mocked(loadPreferences).mockResolvedValueOnce({
909 liveActivitiesEnabled: true,
910 } as Preferences);
911 armAgentAwarenessLiveActivityForLocalWork({
912 environmentId: "env-publishing" as EnvironmentId,
913 threadTitle: "Fix the flaky test",
914 projectTitle: "t3code",
915 });
916 await new Promise((resolve) => setTimeout(resolve, 0));
917 expect(widgetMocks.start).toHaveBeenCalledTimes(1);
918​
919 widgetMocks.start.mockClear();
920 vi.mocked(loadPreferences).mockResolvedValueOnce({
921 liveActivitiesEnabled: true,
922 } as Preferences);
923 armAgentAwarenessLiveActivityForLocalWork({
924 environmentId: "env-pre-capability" as EnvironmentId,
925 threadTitle: "Fix the flaky test",
926 projectTitle: "t3code",
927 });
928 await new Promise((resolve) => setTimeout(resolve, 0));
929 expect(widgetMocks.start).toHaveBeenCalledTimes(1);
930 });
931 it.effect.each(["ios", "android"] as const)(
932 "does not enable %s notifications when a token rotates after permission is revoked",
933 (os) => {
934 vi.spyOn(Platform, "OS", "get").mockReturnValue(os);
935 vi.spyOn(Platform, "Version", "get").mockReturnValue(os === "ios" ? 18 : 36);
936 vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
937 type: os,
938 data: "initial",
939 });
940 const registrations: unknown[] = [];
941 vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
942 const request = new Request(input, init);
943 if (request.url.endsWith("/v1/client/dpop-token")) {
944 return Response.json({
945 access_token: "dpop",
946 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
947 token_type: "DPoP",
948 expires_in: 300,
949 scope: "mobile:registration",
950 });
951 }
952 registrations.push(await request.json());
953 return Response.json({ ok: true });
954 });
955 Constants.expoConfig!.extra = { relay: { url: "https://permission-relay.example.test" } };
956 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk"), "user-a");
957 return Effect.gen(function* () {
958 yield* runBackgroundOperations();
959 expect(registrations.at(-1)).toMatchObject({
960 preferences: { notificationsEnabled: true },
961 });
962 vi.mocked(Notifications.getPermissionsAsync).mockResolvedValueOnce({
963 granted: false,
964 } as Awaited<ReturnType<typeof Notifications.getPermissionsAsync>>);
965 const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0];
966 listener({ type: os, data: "rotated" });
967 yield* runBackgroundOperations();
968 expect(registrations.at(-1)).toMatchObject({
969 preferences: { notificationsEnabled: false },
970 });
971 expect(registrations.at(-1)).not.toHaveProperty("pushToken");
972 }).pipe(
973 Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
974 Effect.provide(
975 ManagedRelayLayer.layer("https://permission-relay.example.test").pipe(
976 Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Dpop.layer)),
977 ),
978 ),
979 );
980 },
981 );
982 it.effect("preserves relay rejection errors with React Native response headers", () => {
983 vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
984 vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
985 type: "android",
986 data: "fcm-token",
987 });
988 const rejectedResponse = new Response("Unsupported device platform", { status: 400 });
989 Object.defineProperty(rejectedResponse.headers, "getSetCookie", { value: undefined });
990 vi.stubGlobal("fetch", (request: RequestInfo | URL) => {
991 const url = request instanceof Request ? request.url : String(request);
992 const response = url.endsWith("/v1/client/dpop-token")
993 ? Response.json({
994 access_token: "relay-dpop-token",
995 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
996 token_type: "DPoP",
997 expires_in: 300,
998 scope: "mobile:registration",
999 })
1000 : rejectedResponse;
1001 Object.defineProperty(response.headers, "getSetCookie", { value: undefined });
1002 return Promise.resolve(response);
1003 });
1004 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } };
1005 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"), "user-a");
1006​
1007 return Effect.gen(function* () {
1008 // Hermes' compiled error hashing reads the response's cookie getter.
1009 const httpResponse = HttpClientResponse.fromWeb(
1010 HttpClientRequest.post("https://relay.example.test/v1/mobile/devices"),
1011 rejectedResponse,
1012 );
1013 expect(httpResponse.cookies).toEqual(Cookies.empty);
1014 const result = yield* Effect.exit(
1015 updateAgentAwarenessRegistrationPreferences({ liveActivitiesEnabled: true }),
1016 );
1017 expect(Exit.isFailure(result)).toBe(true);
1018 if (Exit.isFailure(result)) {
1019 expect(Cause.hasDies(result.cause)).toBe(false);
1020 expect(Cause.squash(result.cause)).toBeInstanceOf(
1021 ManagedRelay.ManagedRelayRequestFailedError,
1022 );
1024 expect(getAgentAwarenessRegistrationStatus()).toBe("failed");
1025 expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
1026 }).pipe(Effect.provide(layerRelayTest));
1027 });
1028​
1029 it.effect("registers an Android FCM token without invoking Apple Live Activities", () => {
1030 vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
1031 vi.spyOn(Platform, "Version", "get").mockReturnValue(36);
1032 vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
1033 type: "android",
1034 data: "fcm-token",
1035 });
1036 vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: true } as Preferences);
1037 vi.stubGlobal(
1038 "fetch",
1039 vi.fn((request: RequestInfo | URL) => {
1040 const url = request instanceof Request ? request.url : String(request);
1041 return Promise.resolve(
1042 Response.json(
1043 url.endsWith("/v1/client/dpop-token")
1044 ? {
1045 access_token: "relay-dpop-token",
1046 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
1047 token_type: "DPoP",
1048 expires_in: 300,
1049 scope: "mobile:registration",
1051 : { ok: true },
1052 ),
1053 );
1054 }),
1055 );
1056 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } };
1057 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"), "user-a");
1058 return Effect.gen(function* () {
1059 yield* refreshAgentAwarenessRegistration();
1060 expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalled();
1061 expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalled();
1062 expect(registrationRecordStore.current?.signature).toContain("fcm-token");
1063 expect(registrationRecordStore.current?.signature).toContain("android");
1064 expect(widgetMocks.getInstances).not.toHaveBeenCalled();
1065 expect(configureAndroidAgentNotifications).toHaveBeenCalledWith("device-1", "user-a", true);
1066 vi.mocked(clearAndroidAgentNotifications).mockClear();
1067 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-b"), "user-b");
1068 expect(clearAndroidAgentNotifications).toHaveBeenCalled();
1069 }).pipe(Effect.provide(layerRelayTest));
1070 });
1071 it.effect(
1072 "preserves same-account Android notifications and replays on remount and later foreground",
1073 () => {
1074 vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
1075 vi.spyOn(Platform, "Version", "get").mockReturnValue(36);
1076 vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
1077 type: "android",
1078 data: "fcm-token",
1079 });
1080 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } };
1081 const now = vi.spyOn(Date, "now").mockReturnValue(1000000);
1082 vi.mocked(clearAndroidAgentNotifications).mockClear();
1083 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1084 return Effect.gen(function* () {
1085 yield* runBackgroundOperations();
1086 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
1087 expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
1088 yield* refreshAgentAwarenessRegistration();
1089 expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
1090 releaseAgentAwarenessRelayTokenProvider();
1091 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1092 yield* runBackgroundOperations();
1093 expect(clearAndroidAgentNotifications).not.toHaveBeenCalled();
1094 expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(2);
1095 for (const listener of appStateMock.listeners) listener("active");
1096 yield* runBackgroundOperations();
1097 expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(2);
1098 now.mockReturnValue(1060001);
1099 for (const listener of appStateMock.listeners) listener("active");
1100 yield* runBackgroundOperations();
1101 expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(3);
1102 expect(clearAndroidAgentNotifications).not.toHaveBeenCalled();
1103 expect(widgetMocks.getInstances).not.toHaveBeenCalled();
1104 setAgentAwarenessRelayTokenProvider(null);
1105 expect(clearAndroidAgentNotifications).toHaveBeenCalled();
1106 expect(clearAgentAwarenessRegistrationRecord).toHaveBeenCalled();
1107 }).pipe(Effect.provide(layerRelayTest));
1108 },
1109 );
1110​
1111 it.effect(
1112 "does not reconfigure or register a detached Android account from an in-flight operation",
1113 () => {
1114 vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
1115 vi.spyOn(Platform, "Version", "get").mockReturnValue(36);
1116 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } };
1117 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1118 releaseAgentAwarenessRelayTokenProvider();
1119 vi.mocked(configureAndroidAgentNotifications).mockClear();
1120 return Effect.gen(function* () {
1121 yield* runBackgroundOperations();
1122 expect(configureAndroidAgentNotifications).not.toHaveBeenCalled();
1123 expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
1124 }).pipe(Effect.provide(layerRelayTest));
1125 },
1126 );
1127});