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

remoteRegistration.test.ts

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