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

remoteRegistration.test.ts

1,273 lines49.4 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 Deferred from "effect/Deferred";
11import * as Exit from "effect/Exit";
12import * as Fiber from "effect/Fiber";
13import * as Layer from "effect/Layer";
14import { Cookies, FetchHttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
15import { ManagedRelay } from "@t3tools/client-runtime/relay";
16​
17import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
18import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
19import { verifyDpopProof } from "@t3tools/shared/dpop";
20import * as Dpop from "../cloud/dpop";
21import * as ManagedRelayLayer from "../cloud/managedRelayLayer";
22import {
23 clearAgentAwarenessRegistrationRecord,
24 loadAgentAwarenessDeviceId,
25 loadAgentAwarenessRegistrationRecord,
26 loadOrCreateAgentAwarenessDeviceId,
27 loadPreferences,
28 saveAgentAwarenessRegistrationRecord,
29} from "../../persistence/imperative";
30import {
31 MobilePreferencesLoadError,
32 MobilePreferencesStore,
33 type Preferences,
34} from "../../persistence/mobile-preferences";
35import { MobileSecureStorageError } from "../../persistence/mobile-secure-storage";
36import * as MobileStorage from "../../persistence/mobile-storage";
37import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
38import {
39 __resetAgentAwarenessRemoteRegistrationForTest,
40 agentAwarenessNotificationsReady,
41 getAgentAwarenessRegistrationStatus,
42 refreshActiveLiveActivityRemoteRegistration,
43 refreshAgentAwarenessRegistration,
44 registerLiveActivityPushToken,
45 releaseAgentAwarenessRelayTokenProvider,
46 setAgentAwarenessRelayTokenProvider,
47 subscribeAgentAwarenessRegistrationStatus,
48 updateAgentAwarenessRegistrationPreferences,
49 type AgentAwarenessRegistrationError,
50 type AgentAwarenessRegistrationServices,
51} from "./remoteRegistration";
52import * as Notifications from "expo-notifications";
53import { Platform } from "react-native";
54import { configureAndroidAgentNotifications } from "./androidNotifications";
55​
56vi.mock("./androidNotifications", () => ({
57 supportsAndroidAgentNotifications: vi.fn(() => true),
58 configureAndroidAgentNotifications: vi.fn(),
59 clearAndroidAgentNotifications: vi.fn(),
60}));
61​
62const secureStore = vi.hoisted(() => new Map<string, string>());
63const widgetMocks = vi.hoisted(() => ({
64 dismissEnded: vi.fn(),
65 getInstances: vi.fn(() => []),
66 start: vi.fn(() => ({})),
67}));
68const publishWidgetMock = vi.hoisted(() => vi.fn((_source: unknown) => Promise.resolve()));
69const environmentConfigsMock = vi.hoisted(() => ({
70 configs: new Map<
71 string,
72 { environment: { capabilities: { agentActivityPublishing?: boolean } } }
73 >(),
74}));
75const backgroundRuntime = vi.hoisted(() => ({
76 pending: [] as Array<{
77 readonly operation: unknown;
78 readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;
79 }>,
80}));
81const appStateMock = vi.hoisted(() => ({
82 listeners: [] as Array<(state: string) => void>,
83}));
84const registrationRecordStore = vi.hoisted(() => ({
85 current: null as {
86 readonly identity: string;
87 readonly signature: string;
88 readonly pushToStartToken?: string;
89 } | null,
90}));
91​
92vi.mock("expo-constants", () => ({
93 default: {
94 expoConfig: {
95 version: "1.0.0",
96 extra: {},
97 },
98 },
99}));
100​
101vi.mock("expo-widgets", () => ({
102 addPushToStartTokenListener: vi.fn(() => ({ remove: vi.fn() })),
103}));
104​
105vi.mock("../../widgets/publishAgentActivityWidget", () => ({
106 publishAgentActivityWidget: publishWidgetMock,
107}));
108​
109vi.mock("./agentLiveActivity", () => ({
110 dismissEndedAgentLiveActivities: widgetMocks.dismissEnded,
111 getAgentLiveActivities: widgetMocks.getInstances,
112 startAgentLiveActivity: widgetMocks.start,
113}));
114​
115// Avoid importing the native connection stack; this gate only needs configs.
116vi.mock("../../state/atom-registry", () => ({
117 appAtomRegistry: {
118 get: () => environmentConfigsMock.configs,
119 },
120}));
121​
122vi.mock("../../state/server", () => ({
123 environmentServerConfigsAtom: Symbol("environmentServerConfigsAtom"),
124}));
125​
126vi.mock("expo-notifications", () => ({
127 AndroidImportance: { NONE: 0, HIGH: 4 },
128 getNotificationChannelAsync: vi.fn(() => Promise.resolve(null)),
129 addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
130 getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),
131 getPermissionsAsync: vi.fn(() => Promise.resolve({ granted: true })),
132}));
133​
134vi.mock("expo-crypto", () => ({
135 CryptoDigestAlgorithm: {
136 SHA1: "SHA-1",
137 SHA256: "SHA-256",
138 SHA384: "SHA-384",
139 SHA512: "SHA-512",
140 },
141 getRandomBytes: (byteCount: number) => new Uint8Array(NodeCrypto.randomBytes(byteCount)),
142 getRandomBytesAsync: (byteCount: number) =>
143 Promise.resolve(new Uint8Array(NodeCrypto.randomBytes(byteCount))),
144 digest: (algorithm: string, data: unknown) => {
145 if (!(data instanceof Uint8Array)) {
146 return Promise.reject(new TypeError("expo-crypto digest data must be a typed array."));
147 }
148 return Promise.resolve(
149 new Uint8Array(NodeCrypto.createHash(algorithm).update(data).digest()).buffer,
150 );
151 },
152}));
153​
154vi.mock("expo", async () => {
155 const { createNodeDpopKeysModule } = await import("../cloud/dpop.testing");
156 const dpopKeys = createNodeDpopKeysModule();
157 return { requireNativeModule: () => dpopKeys };
158});
159​
160vi.mock("expo-secure-store", () => ({
161 getItemAsync: (key: string) => Promise.resolve(secureStore.get(key) ?? null),
162 setItemAsync: (key: string, value: string) => {
163 secureStore.set(key, value);
164 return Promise.resolve();
165 },
166}));
167​
168vi.mock("react-native", () => ({
169 Platform: {
170 get OS() {
171 return "ios";
172 },
173 get Version() {
174 return "18.0";
175 },
176 },
177 AppState: {
178 addEventListener: (_event: string, listener: (state: string) => void) => {
179 appStateMock.listeners.push(listener);
180 return {
181 remove: () => {
182 const index = appStateMock.listeners.indexOf(listener);
183 if (index >= 0) {
184 appStateMock.listeners.splice(index, 1);
185 }
186 },
187 };
188 },
189 },
190}));
191​
192vi.mock("../../lib/runtime", () => ({
193 runtime: {
194 runPromiseExit: (operation: unknown) =>
195 new Promise((resolve) => {
196 backgroundRuntime.pending.push({ operation, resolve });
197 }),
198 },
199}));
200​
201vi.mock("../../persistence/imperative", () => ({
202 loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
203 loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
204 loadPreferences: vi.fn(() => Promise.resolve({ liveActivitiesEnabled: false })),
205 loadAgentAwarenessRegistrationRecord: vi.fn(() =>
206 Promise.resolve(registrationRecordStore.current),
207 ),
208 saveAgentAwarenessRegistrationRecord: vi.fn((record: { identity: string; signature: string }) => {
209 registrationRecordStore.current = record;
210 return Promise.resolve();
211 }),
212 clearAgentAwarenessRegistrationRecord: vi.fn(() => {
213 registrationRecordStore.current = null;
214 return Promise.resolve();
215 }),
216}));
217​
218function proofIat(proof: string): number {
219 const payload = proof.split(".")[1];
220 if (!payload) {
221 throw new Error("Missing DPoP payload.");
222 }
223 const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {
224 readonly iat: number;
225 };
226 return decoded.iat;
228​
229const storageFailure = (cause: unknown) =>
230 new MobileSecureStorageError({ operation: "read", key: "test", cause });
231const unexpectedStorage = () => Effect.die("Unexpected storage request");
232​
233// Delegates to the persistence/imperative mocks so each test steers both paths the same way.
234const layerPersistenceTest = Layer.merge(
235 Layer.succeed(
236 MobileStorage.MobileStorage,
237 MobileStorage.MobileStorage.of({
238 loadOrCreateAgentAwarenessDeviceId: Effect.tryPromise({
239 try: () => loadOrCreateAgentAwarenessDeviceId(),
240 catch: storageFailure,
241 }),
242 loadOrCreateAnalyticsDeviceId: Effect.succeed("analytics-device-1"),
243 loadAgentAwarenessDeviceId: Effect.tryPromise({
244 try: () => loadAgentAwarenessDeviceId(),
245 catch: storageFailure,
246 }),
247 loadAgentAwarenessRegistrationRecord: Effect.tryPromise({
248 try: () => loadAgentAwarenessRegistrationRecord(),
249 catch: storageFailure,
250 }),
251 saveAgentAwarenessRegistrationRecord: (record) =>
252 Effect.tryPromise({
253 try: () => saveAgentAwarenessRegistrationRecord(record),
254 catch: storageFailure,
255 }),
256 clearAgentAwarenessRegistrationRecord: unexpectedStorage(),
257 loadRecentThreadShortcuts: unexpectedStorage(),
258 saveRecentThreadShortcuts: unexpectedStorage,
259 }),
260 ),
261 Layer.succeed(
262 MobilePreferencesStore,
263 MobilePreferencesStore.of({
264 load: Effect.tryPromise({
265 try: () => loadPreferences(),
266 catch: (cause) => new MobilePreferencesLoadError({ cause }),
267 }),
268 savePatch: unexpectedStorage,
269 update: unexpectedStorage,
270 }),
271 ),
272);
273​
274const layerRelayTest = ManagedRelayLayer.layer("https://relay.example.test").pipe(
275 Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Dpop.layer)),
276 Layer.merge(layerPersistenceTest),
277);
278​
279const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(
280 function* () {
281 let idlePasses = 0;
282 // oxlint-disable-next-line t3code/no-polling-loop-in-tests -- This harness drains mocked runtime jobs and their promise continuations, not external I/O or elapsed time.
283 for (;;) {
284 yield* Effect.promise(() => Promise.resolve());
285 const pending = backgroundRuntime.pending.shift();
286 if (!pending) {
287 idlePasses++;
288 if (idlePasses >= 3) {
289 return;
290 }
291 continue;
292 }
293 idlePasses = 0;
294 const exit = yield* Effect.exit(
295 pending.operation as Effect.Effect<
296 unknown,
297 AgentAwarenessRegistrationError,
298 AgentAwarenessRegistrationServices
299 >,
300 );
301 yield* Effect.sync(() => {
302 pending.resolve(exit);
303 });
304 }
305 },
306);
307​
308describe("makeRelayDeviceRegistrationRequest", () => {
309 beforeEach(() => {
310 vi.restoreAllMocks();
311 vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
312 type: "ios",
313 data: "apns-token",
314 });
315 vi.mocked(Notifications.getPermissionsAsync).mockReset();
316 vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({
317 granted: true,
318 } as Awaited<ReturnType<typeof Notifications.getPermissionsAsync>>);
319 vi.mocked(Notifications.getNotificationChannelAsync).mockResolvedValue(null);
320 vi.unstubAllGlobals();
321 vi.stubGlobal("__DEV__", false);
322 secureStore.clear();
323 backgroundRuntime.pending.length = 0;
324 Constants.expoConfig!.extra = {};
325 __resetAgentAwarenessRemoteRegistrationForTest();
326 appStateMock.listeners.length = 0;
327 registrationRecordStore.current = null;
328 vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
329 vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear();
330 vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear();
331 vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
332 vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: false });
333 widgetMocks.getInstances.mockReset();
334 widgetMocks.getInstances.mockReturnValue([]);
335 widgetMocks.start.mockClear();
336 publishWidgetMock.mockClear();
337 widgetMocks.dismissEnded.mockReset();
338 environmentConfigsMock.configs.clear();
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.effect("registers one push-token listener per Live Activity across wrappers", () => {
362 const addPushTokenListener = vi.fn();
363 // getInstances() returns a new wrapper for the same native activity each call.
364 const wrapper = () => ({
365 getId: () => "activity-1",
366 getPushToken: vi.fn(() => Promise.resolve(null)),
367 addPushTokenListener,
368 });
369​
370 return Effect.gen(function* () {
371 expect(yield* registerLiveActivityPushToken({ activity: wrapper() as never })).toBe(false);
372 expect(yield* registerLiveActivityPushToken({ activity: wrapper() as never })).toBe(false);
373​
374 expect(addPushTokenListener).toHaveBeenCalledTimes(1);
375 }).pipe(Effect.provide(layerRelayTest));
376 });
377​
378 it.effect("registers a Live Activity push token that rotates after registration", () => {
379 const registeredTokens: Array<string> = [];
380 vi.stubGlobal("fetch", async (request: RequestInfo | URL, init?: RequestInit) => {
381 const url = request instanceof Request ? request.url : String(request);
382 if (url.endsWith("/v1/client/dpop-token")) {
383 return Response.json({
384 access_token: "relay-dpop-token",
385 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
386 token_type: "DPoP",
387 expires_in: 300,
388 scope: "mobile:registration",
389 });
390 }
391 if (url.endsWith("/v1/mobile/live-activities")) {
392 const body = request instanceof Request ? await request.text() : String(init?.body);
393 registeredTokens.push(
394 (JSON.parse(body) as { readonly activityPushToken: string }).activityPushToken,
395 );
396 }
397 return Response.json({ ok: true });
398 });
399 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
400 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
401 let tokenListener: ((event: { readonly pushToken: string }) => void) | undefined;
402 const activity = {
403 getId: () => "activity-1",
404 getPushToken: vi.fn(() => Promise.resolve("activity-token")),
405 addPushTokenListener: vi.fn((listener: typeof tokenListener) => {
406 tokenListener = listener;
407 return { remove: vi.fn() };
408 }),
409 };
410​
411 return Effect.gen(function* () {
412 yield* runBackgroundOperations();
413 expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(true);
414​
415 tokenListener?.({ pushToken: "rotated-activity-token" });
416 yield* runBackgroundOperations();
417​
418 expect(registeredTokens).toEqual(["activity-token", "rotated-activity-token"]);
419 }).pipe(
420 Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
421 Effect.provide(layerRelayTest),
422 );
423 });
424​
425 it.effect("registers a rotated Live Activity token only after an older registration", () => {
426 const arrivals: Array<string> = [];
427 let openOldRequest: (() => void) | undefined;
428 const oldRequestGate = new Promise<void>((resolve) => {
429 openOldRequest = resolve;
430 });
431 let markOldRequestArrived: (() => void) | undefined;
432 const oldRequestArrived = new Promise<void>((resolve) => {
433 markOldRequestArrived = resolve;
434 });
435 vi.stubGlobal("fetch", async (request: RequestInfo | URL, init?: RequestInit) => {
436 const url = request instanceof Request ? request.url : String(request);
437 if (url.endsWith("/v1/client/dpop-token")) {
438 return Response.json({
439 access_token: "relay-dpop-token",
440 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
441 token_type: "DPoP",
442 expires_in: 300,
443 scope: "mobile:registration",
444 });
445 }
446 if (url.endsWith("/v1/mobile/live-activities")) {
447 const body = request instanceof Request ? await request.text() : String(init?.body);
448 const token = (JSON.parse(body) as { readonly activityPushToken: string })
449 .activityPushToken;
450 arrivals.push(token);
451 if (token === "activity-token") {
452 markOldRequestArrived?.();
453 await oldRequestGate;
454 }
455 }
456 return Response.json({ ok: true });
457 });
458 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
459 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
460 let tokenListener: ((event: { readonly pushToken: string }) => void) | undefined;
461 const activity = {
462 getId: () => "activity-1",
463 getPushToken: vi.fn(() => Promise.resolve("activity-token")),
464 addPushTokenListener: vi.fn((listener: typeof tokenListener) => {
465 tokenListener = listener;
466 return { remove: vi.fn() };
467 }),
468 };
469​
470 return Effect.gen(function* () {
471 yield* runBackgroundOperations();
472 const lookup = yield* Effect.forkChild(
473 registerLiveActivityPushToken({ activity: activity as never }),
474 );
475 yield* Effect.promise(() => oldRequestArrived);
476​
477 tokenListener?.({ pushToken: "rotated-activity-token" });
478 const deviceIdLookups = vi.mocked(loadOrCreateAgentAwarenessDeviceId).mock.calls.length;
479 const rotated = backgroundRuntime.pending.shift()!;
480 // Starting immediately runs the listener's registration until it suspends: on the
481 // activity lock, or, without one, at its device-id lookup.
482 const rotatedRegistration = yield* Effect.forkChild(
483 Effect.exit(
484 rotated.operation as Effect.Effect<
485 unknown,
486 AgentAwarenessRegistrationError,
487 ManagedRelay.ManagedRelayClient
488 >,
489 ),
490 { startImmediately: true },
491 );
492 expect(vi.mocked(loadOrCreateAgentAwarenessDeviceId).mock.calls).toHaveLength(
493 deviceIdLookups,
494 );
495 expect(arrivals).toEqual(["activity-token"]);
496​
497 openOldRequest?.();
498 yield* Fiber.join(lookup);
499 rotated.resolve(yield* Fiber.join(rotatedRegistration));
500 expect(arrivals).toEqual(["activity-token", "rotated-activity-token"]);
501 }).pipe(
502 Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
503 Effect.provide(layerRelayTest),
504 );
505 });
506​
507 it.effect("still registers the active card when ended-card cleanup throws", () => {
508 const registrations: unknown[] = [];
509 vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
510 const request = new Request(input, init);
511 if (request.url.endsWith("/v1/client/dpop-token")) {
512 return Response.json({
513 access_token: "relay-dpop-token",
514 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
515 token_type: "DPoP",
516 expires_in: 300,
517 scope: "mobile:registration",
518 });
519 }
520 if (request.url.endsWith("/v1/mobile/live-activities")) {
521 registrations.push(await request.json());
522 }
523 return Response.json({ ok: true });
524 });
525 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
526 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
527 const activity = {
528 getId: () => "activity-1",
529 getPushToken: vi.fn(() => Promise.resolve("activity-token")),
530 addPushTokenListener: vi.fn(),
531 end: vi.fn(),
532 };
533​
534 return Effect.gen(function* () {
535 yield* runBackgroundOperations();
536 widgetMocks.dismissEnded.mockReset();
537 widgetMocks.dismissEnded.mockImplementation(() => {
538 throw new Error("Cannot find function dismissEnded");
539 });
540 widgetMocks.getInstances.mockReturnValue([activity] as never);
541​
542 for (const listener of appStateMock.listeners) listener("active");
543 yield* runBackgroundOperations();
544​
545 expect(widgetMocks.dismissEnded).toHaveBeenCalledOnce();
546 expect(registrations).toEqual([
547 { deviceId: "device-1", activityPushToken: "activity-token" },
548 ]);
549 expect(activity.end).not.toHaveBeenCalled();
550 expect(widgetMocks.start).not.toHaveBeenCalled();
551 }).pipe(
552 Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
553 Effect.provide(layerRelayTest),
554 );
555 });
556​
557 it("ends local Live Activities and stops foreground reconciliation on cloud sign-out", () => {
558 const end = vi.fn(() => Promise.resolve());
559 const activity = {
560 getId: () => "activity-1",
561 getPushToken: vi.fn(() => Promise.resolve("activity-token")),
562 addPushTokenListener: vi.fn(),
563 end,
564 };
565 widgetMocks.getInstances.mockReturnValue([activity] as never);
566 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
567 expect(appStateMock.listeners).toHaveLength(1);
568​
569 setAgentAwarenessRelayTokenProvider(null);
570​
571 expect(end).toHaveBeenCalledWith("immediate");
572 expect(widgetMocks.dismissEnded).toHaveBeenCalled();
573 expect(appStateMock.listeners).toHaveLength(0);
574 });
575​
576 it.effect("registers the APNs device when cloud auth becomes available", () => {
577 const fetchMock = vi.fn((request: RequestInfo | URL) => {
578 const url = request instanceof Request ? request.url : String(request);
579 return Promise.resolve(
580 Response.json(
581 url.endsWith("/v1/client/dpop-token")
582 ? {
583 access_token: "relay-dpop-token",
584 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
585 token_type: "DPoP",
586 expires_in: 300,
587 scope: "mobile:registration",
588 }
589 : { ok: true },
590 ),
591 );
592 });
593 vi.stubGlobal("fetch", fetchMock);
594 Constants.expoConfig!.extra = {
595 relay: {
596 url: "https://relay.example.test/",
597 },
598 };
599​
600 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
601​
602 return Effect.gen(function* () {
603 yield* runBackgroundOperations();
604​
605 const requestUrl = (request: unknown) =>
606 request instanceof Request ? request.url : String(request);
607 const deviceCalls = fetchMock.mock.calls.filter(([request]) =>
608 requestUrl(request).endsWith("/v1/mobile/devices"),
609 );
610 expect(deviceCalls).toHaveLength(1);
611 const [request, init] = deviceCalls[0] as unknown as [unknown, RequestInit | undefined];
612 const url = requestUrl(request);
613 const method = request instanceof Request ? request.method : init?.method;
614 const headers = request instanceof Request ? request.headers : new Headers(init?.headers);
615 const dpop = headers.get("dpop");
616 expect(url).toBe("https://relay.example.test/v1/mobile/devices");
617 expect(method).toBe("POST");
618 expect(headers.get("authorization")).toBe("DPoP relay-dpop-token");
619 expect(dpop).toEqual(expect.any(String));
620 if (!dpop) {
621 throw new Error("Missing DPoP header.");
622 }
623 expect(
624 verifyDpopProof({
625 proof: dpop,
626 method: "POST",
627 url: "https://relay.example.test/v1/mobile/devices",
628 expectedAccessToken: "relay-dpop-token",
629 nowEpochSeconds: proofIat(dpop),
630 }),
631 ).toMatchObject({ ok: true });
632 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
633 }).pipe(Effect.provide(layerRelayTest));
634 });
635​
636 it.effect("keeps a registered status when a later refresh fails", () => {
637 Constants.expoConfig!.extra = {
638 relay: {
639 url: "https://relay.example.test/",
640 },
641 };
642 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
643​
644 return Effect.gen(function* () {
645 yield* runBackgroundOperations();
646 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
647​
648 vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(
649 new Error("transient failure"),
650 );
651 yield* refreshAgentAwarenessRegistration();
652 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
653 }).pipe(Effect.provide(layerRelayTest));
654 });
655​
656 it.effect("leaves the signed-out status alone when an obsolete registration fails", () => {
657 Constants.expoConfig!.extra = {
658 relay: {
659 url: "https://relay.example.test/",
660 },
661 };
662 vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValue(new Error("storage failure"));
663 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
664 setAgentAwarenessRelayTokenProvider(null);
665​
666 return Effect.gen(function* () {
667 yield* runBackgroundOperations();
668 expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");
669 }).pipe(Effect.provide(layerRelayTest));
670 });
671​
672 it.effect("does not re-register the same account when nothing has changed", () => {
673 Constants.expoConfig!.extra = {
674 relay: {
675 url: "https://relay.example.test/",
676 },
677 };
678 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
679​
680 return Effect.gen(function* () {
681 yield* refreshAgentAwarenessRegistration();
682 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
683 expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);
684 expect(registrationRecordStore.current).not.toBeNull();
685​
686 vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();
687 yield* refreshAgentAwarenessRegistration();
688 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
689 expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
690 }).pipe(Effect.provide(layerRelayTest));
691 });
692​
693 it.effect("continues queued device registration after a failed auth lookup", () => {
694 Constants.expoConfig!.extra = {
695 relay: {
696 url: "https://relay.example.test/",
697 },
698 };
699​
700 // Sign-in first reads the widget snapshot, then registers the device; fail
701 // both lookups so the queued registration is the one that must recover.
702 const tokenProvider = vi
703 .fn<() => Promise<string | null>>()
704 .mockRejectedValueOnce(new Error("auth unavailable"))
705 .mockRejectedValueOnce(new Error("auth unavailable"))
706 .mockResolvedValue("clerk-token-user-a");
707 setAgentAwarenessRelayTokenProvider(tokenProvider);
708 const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
709 expect(tokenListener).toBeDefined();
710 tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);
711​
712 return Effect.gen(function* () {
713 yield* runBackgroundOperations();
714​
715 expect(backgroundRuntime.pending).toHaveLength(0);
716 expect(tokenProvider).toHaveBeenCalledTimes(3);
717 }).pipe(Effect.provide(layerRelayTest));
718 });
719​
720 it.effect.each(["ios", "android"] as const)(
721 "does not enable %s notifications when a token rotates after permission is revoked",
722 (os) => {
723 vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: true });
724 vi.spyOn(Platform, "OS", "get").mockReturnValue(os);
725 vi.spyOn(Platform, "Version", "get").mockReturnValue(os === "ios" ? 18 : 36);
726 vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
727 type: os,
728 data: "initial",
729 });
730 const registrations: unknown[] = [];
731 vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
732 const request = new Request(input, init);
733 if (request.url.endsWith("/v1/client/dpop-token")) {
734 return Response.json({
735 access_token: "dpop",
736 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
737 token_type: "DPoP",
738 expires_in: 300,
739 scope: "mobile:registration",
740 });
741 }
742 registrations.push(await request.json());
743 return Response.json({ ok: true });
744 });
745 Constants.expoConfig!.extra = { relay: { url: "https://permission-relay.example.test" } };
746 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk"), "user-a");
747 return Effect.gen(function* () {
748 yield* runBackgroundOperations();
749 expect(registrations.at(-1)).toMatchObject({
750 preferences: { notificationsEnabled: true, liveActivitiesEnabled: true },
751 });
752 vi.mocked(Notifications.getPermissionsAsync).mockResolvedValueOnce({
753 granted: false,
754 } as Awaited<ReturnType<typeof Notifications.getPermissionsAsync>>);
755 const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0];
756 listener({ type: os, data: "rotated" });
757 yield* runBackgroundOperations();
758 expect(registrations.at(-1)).toMatchObject({
759 preferences: { notificationsEnabled: false, liveActivitiesEnabled: os === "ios" },
760 });
761 if (os === "android") {
762 expect(registrations.at(-1)).toMatchObject({ pushToken: "rotated" });
763 vi.mocked(Notifications.getPermissionsAsync).mockResolvedValueOnce({
764 granted: false,
765 } as Awaited<ReturnType<typeof Notifications.getPermissionsAsync>>);
766 yield* refreshAgentAwarenessRegistration();
767 expect(registrations.at(-1)).toMatchObject({
768 pushToken: "initial",
769 preferences: { notificationsEnabled: false, liveActivitiesEnabled: false },
770 });
771 } else {
772 expect(registrations.at(-1)).not.toHaveProperty("pushToken");
773 }
774 }).pipe(
775 Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
776 Effect.provide(
777 ManagedRelayLayer.layer("https://permission-relay.example.test").pipe(
778 Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Dpop.layer)),
779 Layer.merge(layerPersistenceTest),
780 ),
781 ),
782 );
783 },
784 );
785​
786 const stubAndroidDeviceRelay = () => {
787 vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
788 vi.spyOn(Platform, "Version", "get").mockReturnValue(36);
789 const registrations: Array<{
790 readonly preferences: { readonly notificationsEnabled: boolean };
791 }> = [];
792 vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
793 const request = new Request(input, init);
794 if (request.url.endsWith("/v1/client/dpop-token")) {
795 return Response.json({
796 access_token: "relay-dpop-token",
797 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
798 token_type: "DPoP",
799 expires_in: 300,
800 scope: "mobile:registration",
801 });
802 }
803 if (request.url.endsWith("/v1/mobile/devices")) {
804 registrations.push(await request.json());
805 }
806 return Response.json({ ok: true });
807 });
808 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } };
809 return registrations;
810 };
811​
812 it.effect("does not report notifications ready when its push token lookup fails", () => {
813 const registrations = stubAndroidDeviceRelay();
814 vi.mocked(Notifications.getDevicePushTokenAsync).mockRejectedValue(
815 new Error("Default FirebaseApp is not initialized"),
816 );
817 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"), "user-a");
818​
819 return Effect.gen(function* () {
820 yield* runBackgroundOperations();
821​
822 // Live Activities register with their own tokens, so the device stays registered.
823 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
824 expect(agentAwarenessNotificationsReady()).toBe(false);
825 expect(registrations).toMatchObject([{ preferences: { notificationsEnabled: true } }]);
826 expect(registrations[0]).not.toHaveProperty("pushToken");
827​
828 const onStatusChange = vi.fn();
829 subscribeAgentAwarenessRegistrationStatus(onStatusChange);
830 const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0];
831 listener({ type: "android", data: "fcm-token" } as never);
832 yield* runBackgroundOperations();
833​
834 expect(agentAwarenessNotificationsReady()).toBe(true);
835 expect(onStatusChange).toHaveBeenCalled();
836 }).pipe(
837 Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
838 Effect.provide(layerRelayTest),
839 );
840 });
841​
842 it.effect("keeps notifications enabled when a refresh cannot read the push token", () => {
843 const registrations = stubAndroidDeviceRelay();
844 vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
845 type: "android",
846 data: "fcm-token",
847 });
848 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"), "user-a");
849​
850 return Effect.gen(function* () {
851 yield* runBackgroundOperations();
852 expect(registrations).toMatchObject([{ preferences: { notificationsEnabled: true } }]);
853 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
854​
855 vi.mocked(Notifications.getDevicePushTokenAsync).mockRejectedValueOnce(
856 new Error("SERVICE_NOT_AVAILABLE"),
857 );
858 yield* refreshAgentAwarenessRegistration();
859​
860 expect(registrations).toMatchObject([{ preferences: { notificationsEnabled: true } }]);
861 expect(agentAwarenessNotificationsReady()).toBe(true);
862​
863 // A lookup that started before a rotation must not replace the rotated token.
864 let resolveStaleLookup: (token: { type: "android"; data: string }) => void = () => {};
865 let markLookupStarted: () => void = () => {};
866 const lookupStarted = new Promise<void>((resolve) => {
867 markLookupStarted = resolve;
868 });
869 vi.mocked(Notifications.getDevicePushTokenAsync).mockImplementationOnce(() => {
870 markLookupStarted();
871 return new Promise((resolve) => {
872 resolveStaleLookup = resolve;
873 });
874 });
875 const staleRefresh = yield* Effect.forkChild(refreshAgentAwarenessRegistration());
876 yield* Effect.promise(() => lookupStarted);
877 const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0];
878 listener({ type: "android", data: "rotated-fcm-token" } as never);
879 yield* runBackgroundOperations();
880 resolveStaleLookup({ type: "android", data: "fcm-token" });
881 yield* Fiber.join(staleRefresh);
882 vi.mocked(Notifications.getDevicePushTokenAsync).mockRejectedValueOnce(
883 new Error("SERVICE_NOT_AVAILABLE"),
884 );
885 yield* refreshAgentAwarenessRegistration();
886​
887 expect(registrations.at(-1)).toMatchObject({ pushToken: "rotated-fcm-token" });
888 }).pipe(
889 Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
890 Effect.provide(layerRelayTest),
891 );
892 });
893​
894 it.effect.each(["blocked", "unavailable"] as const)(
895 "keeps Android push delivery registered when the alert channel is %s",
896 (channelState) => {
897 vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: true });
898 vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
899 vi.spyOn(Platform, "Version", "get").mockReturnValue(36);
900 vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
901 type: "android",
902 data: "fcm-token",
903 });
904 vi.mocked(Notifications.getNotificationChannelAsync).mockResolvedValue({
905 id: "agent-alerts",
906 name: "Agent alerts",
907 importance: Notifications.AndroidImportance.NONE,
908 } as Awaited<ReturnType<typeof Notifications.getNotificationChannelAsync>>);
909 if (channelState === "unavailable") {
910 vi.mocked(Notifications.getNotificationChannelAsync).mockRejectedValue(
911 new Error("Android channel lookup failed"),
912 );
913 }
914 const registrations: unknown[] = [];
915 vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
916 const request = new Request(input, init);
917 if (request.url.endsWith("/v1/client/dpop-token")) {
918 return Response.json({
919 access_token: "dpop",
920 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
921 token_type: "DPoP",
922 expires_in: 300,
923 scope: "mobile:registration",
924 });
925 }
926 registrations.push(await request.json());
927 return Response.json({ ok: true });
928 });
929 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } };
930 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk"), "user-a");
931 return Effect.gen(function* () {
932 yield* runBackgroundOperations();
933 expect(registrations.at(-1)).toMatchObject({
934 pushToken: "fcm-token",
935 preferences: { notificationsEnabled: false, liveActivitiesEnabled: true },
936 });
937 expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
938​
939 const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0];
940 listener({ type: "android", data: "rotated-fcm-token" });
941 yield* runBackgroundOperations();
942 expect(registrations.at(-1)).toMatchObject({
943 pushToken: "rotated-fcm-token",
944 preferences: { notificationsEnabled: false, liveActivitiesEnabled: true },
945 });
946​
947 vi.mocked(Notifications.getNotificationChannelAsync).mockResolvedValue(null);
948 yield* refreshAgentAwarenessRegistration();
949 expect(registrations.at(-1)).toMatchObject({
950 pushToken: "fcm-token",
951 preferences: { notificationsEnabled: true },
952 });
953 }).pipe(
954 Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
955 Effect.provide(layerRelayTest),
956 );
957 },
958 );
959 it.effect("preserves relay rejection errors with React Native response headers", () => {
960 vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
961 vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
962 type: "android",
963 data: "fcm-token",
964 });
965 const rejectedResponse = new Response("Unsupported device platform", { status: 400 });
966 Object.defineProperty(rejectedResponse.headers, "getSetCookie", { value: undefined });
967 vi.stubGlobal("fetch", (request: RequestInfo | URL) => {
968 const url = request instanceof Request ? request.url : String(request);
969 const response = url.endsWith("/v1/client/dpop-token")
970 ? Response.json({
971 access_token: "relay-dpop-token",
972 issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
973 token_type: "DPoP",
974 expires_in: 300,
975 scope: "mobile:registration",
976 })
977 : rejectedResponse;
978 Object.defineProperty(response.headers, "getSetCookie", { value: undefined });
979 return Promise.resolve(response);
980 });
981 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } };
982 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"), "user-a");
983​
984 return Effect.gen(function* () {
985 // Hermes' compiled error hashing reads the response's cookie getter.
986 const httpResponse = HttpClientResponse.fromWeb(
987 HttpClientRequest.post("https://relay.example.test/v1/mobile/devices"),
988 rejectedResponse,
989 );
990 expect(httpResponse.cookies).toEqual(Cookies.empty);
991 const result = yield* Effect.exit(
992 updateAgentAwarenessRegistrationPreferences({ liveActivitiesEnabled: true }),
993 );
994 expect(Exit.isFailure(result)).toBe(true);
995 if (Exit.isFailure(result)) {
996 expect(Cause.hasDies(result.cause)).toBe(false);
997 expect(Cause.squash(result.cause)).toBeInstanceOf(
998 ManagedRelay.ManagedRelayRequestFailedError,
999 );
1001 expect(getAgentAwarenessRegistrationStatus()).toBe("failed");
1002 expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
1003 }).pipe(Effect.provide(layerRelayTest));
1004 });
1005​
1006 it.effect(
1007 "does not reconfigure or register a detached Android account from an in-flight operation",
1008 () => {
1009 vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
1010 vi.spyOn(Platform, "Version", "get").mockReturnValue(36);
1011 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } };
1012 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1013 releaseAgentAwarenessRelayTokenProvider();
1014 vi.mocked(configureAndroidAgentNotifications).mockClear();
1015 return Effect.gen(function* () {
1016 yield* runBackgroundOperations();
1017 expect(configureAndroidAgentNotifications).not.toHaveBeenCalled();
1018 expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();
1019 }).pipe(Effect.provide(layerRelayTest));
1020 },
1021 );
1022​
1023 describe("home-screen widget", () => {
1024 // These cover the widget path only, so keep the Live Activity from priming.
1025 beforeEach(() => {
1026 vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: false } as Preferences);
1027 });
1028​
1029 const aggregate: RelayAgentActivityAggregateState = {
1030 title: "T3 Code",
1031 subtitle: "Agent work in progress",
1032 activeCount: 1,
1033 updatedAt: "2026-10-18T10:00:00.000Z",
1034 activities: [
1036 environmentId: "env-1" as EnvironmentId,
1037 threadId: "thread-1" as ThreadId,
1038 projectTitle: "t3code",
1039 threadTitle: "Fix the widget",
1040 modelTitle: "GPT-5.5",
1041 phase: "running",
1042 status: "Working",
1043 updatedAt: "2026-10-18T10:00:00.000Z",
1044 deepLink: "/threads/env-1/thread-1",
1045 },
1046 ],
1047 };
1048​
1049 // The shared fetch-backed relay layer keeps the first test's fetch stub,
1050 // so these tests answer the snapshot read through a fake client instead.
1051 function fakeRelay(
1052 getAgentActivitySnapshot: () => Effect.Effect<
1053 { readonly aggregate: typeof aggregate },
1054 ManagedRelay.ManagedRelayRequestFailedError
1055 >,
1056 ) {
1057 Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
1058 const unexpected = () => Effect.die("Unexpected relay request");
1059 return Layer.succeed(
1060 ManagedRelay.ManagedRelayClient,
1061 ManagedRelay.ManagedRelayClient.of({
1062 relayUrl: "https://relay.example.test",
1063 listEnvironments: unexpected,
1064 listDevices: unexpected,
1065 getT3ChatLink: unexpected,
1066 createT3ChatLinkRequest: unexpected,
1067 unlinkT3Chat: unexpected,
1068 createEnvironmentLinkChallenge: unexpected,
1069 linkEnvironment: unexpected,
1070 unlinkEnvironment: unexpected,
1071 getEnvironmentStatus: unexpected,
1072 connectEnvironment: unexpected,
1073 registerDevice: unexpected,
1074 unregisterDevice: unexpected,
1075 registerLiveActivity: unexpected,
1076 getAgentActivitySnapshot,
1077 resetTokenCache: Effect.void,
1078 }),
1079 ).pipe(Layer.merge(layerPersistenceTest));
1081​
1082 it.effect("registers an existing Live Activity before waiting on the widget read", () => {
1083 const order: Array<string> = [];
1084 const activity = {
1085 getId: () => "activity-1",
1086 getPushToken: vi.fn(() => {
1087 order.push("push-token");
1088 return Promise.resolve(null);
1089 }),
1090 addPushTokenListener: vi.fn(),
1091 };
1092 widgetMocks.getInstances.mockReturnValue([activity] as never);
1093 const relay = fakeRelay(() =>
1094 Effect.sync(() => {
1095 order.push("widget-snapshot");
1096 return { aggregate };
1097 }),
1098 );
1099 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1100​
1101 return Effect.gen(function* () {
1102 yield* refreshActiveLiveActivityRemoteRegistration();
1103​
1104 expect(order).toEqual(["push-token", "widget-snapshot"]);
1105 expect(publishWidgetMock).toHaveBeenLastCalledWith({
1106 kind: "snapshot",
1107 aggregate,
1108 });
1109 }).pipe(Effect.provide(relay));
1110 });
1111​
1112 it.effect("keeps the newest rows when an older overlapping read finishes last", () =>
1113 Effect.gen(function* () {
1114 const newer = { ...aggregate, activeCount: 2 };
1115 const olderRequested = yield* Deferred.make<void>();
1116 const olderResponse = yield* Deferred.make<{ readonly aggregate: typeof aggregate }>();
1117 let reads = 0;
1118 const relay = fakeRelay(() => {
1119 reads++;
1120 return reads === 1
1121 ? Deferred.succeed(olderRequested, undefined).pipe(
1122 Effect.andThen(Deferred.await(olderResponse)),
1124 : Effect.succeed({ aggregate: newer });
1125 });
1126 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1127​
1128 const older = yield* Effect.forkChild(
1129 refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
1130 );
1131 yield* Deferred.await(olderRequested);
1132 yield* refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay));
1133 yield* Deferred.succeed(olderResponse, { aggregate });
1134 yield* Fiber.join(older);
1135​
1136 expect(publishWidgetMock).toHaveBeenLastCalledWith({
1137 kind: "snapshot",
1138 aggregate: newer,
1139 });
1140 }),
1141 );
1142​
1143 it.effect("an obsolete refresh does not discard the next account's read", () =>
1144 Effect.gen(function* () {
1145 let markTokenRequested = () => {};
1146 const tokenRequested = new Promise<void>((resolve) => {
1147 markTokenRequested = resolve;
1148 });
1149 let releaseToken = () => {};
1150 widgetMocks.getInstances.mockReturnValueOnce([
1152 getId: () => "activity-a",
1153 getPushToken: () => {
1154 markTokenRequested();
1155 return new Promise<null>((resolve) => {
1156 releaseToken = () => resolve(null);
1157 });
1158 },
1159 addPushTokenListener: vi.fn(),
1160 },
1161 ] as never);
1162 const requested = yield* Deferred.make<void>();
1163 const response = yield* Deferred.make<{ readonly aggregate: typeof aggregate }>();
1164 const relay = fakeRelay(() =>
1165 Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(response))),
1166 );
1167 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
1168​
1169 const refreshA = yield* Effect.forkChild(
1170 refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
1171 );
1172 yield* Effect.promise(() => tokenRequested);
1173 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-b"), "user-b");
1174 const refreshB = yield* Effect.forkChild(
1175 refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
1176 );
1177 yield* Deferred.await(requested);
1178 releaseToken();
1179 yield* Fiber.join(refreshA);
1180 yield* Deferred.succeed(response, { aggregate });
1181 yield* Fiber.join(refreshB);
1182​
1183 expect(publishWidgetMock).toHaveBeenLastCalledWith({
1184 kind: "snapshot",
1185 aggregate,
1186 });
1187 }),
1188 );
1189​
1190 it.effect("does not prime a Live Activity from a read a newer one replaced", () =>
1191 Effect.gen(function* () {
1192 let markRequested = () => {};
1193 const requested = new Promise<void>((resolve) => {
1194 markRequested = resolve;
1195 });
1196 let resolvePreferences = (_preferences: Preferences) => {};
1197 vi.mocked(loadPreferences).mockImplementationOnce(() => {
1198 markRequested();
1199 return new Promise((resolve) => {
1200 resolvePreferences = resolve;
1201 });
1202 });
1203 const idle = { ...aggregate, activeCount: 0, activities: [] };
1204 let reads = 0;
1205 const relay = fakeRelay(() =>
1206 Effect.succeed({ aggregate: ++reads === 1 ? aggregate : idle }),
1207 );
1208 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1209​
1210 const older = yield* Effect.forkChild(
1211 refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
1212 );
1213 yield* Effect.promise(() => requested);
1214 yield* refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay));
1215 resolvePreferences({ liveActivitiesEnabled: true } as Preferences);
1216 yield* Fiber.join(older);
1217​
1218 expect(widgetMocks.start).not.toHaveBeenCalled();
1219 }),
1220 );
1221​
1222 it.effect("drops a snapshot that arrives after a sign-out, even on re-sign-in", () =>
1223 Effect.gen(function* () {
1224 const requested = yield* Deferred.make<void>();
1225 const response = yield* Deferred.make<{ readonly aggregate: typeof aggregate }>();
1226 const relay = fakeRelay(() =>
1227 Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(response))),
1228 );
1229 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
1230​
1231 const refresh = yield* Effect.forkChild(
1232 refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
1233 );
1234 yield* Deferred.await(requested);
1235 setAgentAwarenessRelayTokenProvider(null);
1236 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
1237 publishWidgetMock.mockClear();
1238 yield* Deferred.succeed(response, { aggregate });
1239 yield* Fiber.join(refresh);
1240​
1241 expect(publishWidgetMock).not.toHaveBeenCalled();
1242 }),
1243 );
1244​
1245 it.effect("does not prime a Live Activity after sign-out during the preference read", () =>
1246 Effect.gen(function* () {
1247 let markRequested = () => {};
1248 const requested = new Promise<void>((resolve) => {
1249 markRequested = resolve;
1250 });
1251 let resolvePreferences = (_preferences: Preferences) => {};
1252 vi.mocked(loadPreferences).mockImplementationOnce(() => {
1253 markRequested();
1254 return new Promise((resolve) => {
1255 resolvePreferences = resolve;
1256 });
1257 });
1258 const relay = fakeRelay(() => Effect.succeed({ aggregate }));
1259 setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1260​
1261 const refresh = yield* Effect.forkChild(
1262 refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
1263 );
1264 yield* Effect.promise(() => requested);
1265 setAgentAwarenessRelayTokenProvider(null);
1266 resolvePreferences({ liveActivitiesEnabled: true } as Preferences);
1267 yield* Fiber.join(refresh);
1268​
1269 expect(widgetMocks.start).not.toHaveBeenCalled();
1270 }),
1271 );
1272 });
1273});