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