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

remoteRegistration.test.ts

927 lines32.7 KB

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