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