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