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

remoteRegistration.test.ts

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