@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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