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

remoteRegistration.ts

1,158 lines38.5 KB

1import { type LiveActivity } from "expo-widgets";
2import {
3 configureAndroidAgentNotifications,
4 clearAndroidAgentNotifications,
5} from "./androidNotifications";
6import Constants from "expo-constants";
7import * as Notifications from "expo-notifications";
8import * as Clock from "effect/Clock";
9import * as Effect from "effect/Effect";
10import * as Schema from "effect/Schema";
11import * as Semaphore from "effect/Semaphore";
12import { AppState, Platform } from "react-native";
13import type { EnvironmentId } from "@t3tools/contracts";
14import {
15 type RelayDeviceRegistrationRequest,
16 type RelayAgentActivitySnapshotResponse,
17 type RelayLiveActivityRegistrationRequest,
18} from "@t3tools/contracts/relay";
19import { findErrorTraceId } from "@t3tools/client-runtime/errors";
20import { ManagedRelay } from "@t3tools/client-runtime/relay";
21import {
22 isAtomCommandInterrupted,
23 settleAsyncResult,
24 squashAtomCommandFailure,
25} from "@t3tools/client-runtime/state/runtime";
26​
27import { runtime } from "../../lib/runtime";
28import { appAtomRegistry } from "../../state/atom-registry";
29import { environmentServerConfigsAtom } from "../../state/server";
30import type { Preferences } from "../../persistence/mobile-preferences";
31import {
32 clearAgentAwarenessRegistrationRecord,
33 loadAgentAwarenessDeviceId,
34 loadAgentAwarenessRegistrationRecord,
35 loadOrCreateAgentAwarenessDeviceId,
36 loadPreferences,
37 saveAgentAwarenessRegistrationRecord,
38} from "../../persistence/imperative";
39import type { AgentActivityProps } from "../../widgets/AgentActivity";
40import type { AgentActivityWidgetSource } from "../../widgets/agentActivityWidgetTimeline";
41import { publishAgentActivityWidget } from "../../widgets/publishAgentActivityWidget";
42import {
43 dismissEndedAgentLiveActivities,
44 getAgentLiveActivities,
45 startAgentLiveActivity,
46} from "./agentLiveActivity";
47import { resolveCloudPublicConfig } from "../cloud/publicConfig";
48import { supportsAgentAwarenessPush } from "./capabilities";
49import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
50​
51const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
52​
53const AgentAwarenessOperation = Schema.Literals([
54 "read-notification-permissions",
55 "read-native-push-token",
56 "read-device-registration-relay-token",
57 "read-device-unregistration-relay-token",
58 "read-live-activity-registration-relay-token",
59 "load-device-registration-identifier",
60 "load-device-registration-preferences",
61 "load-device-unregistration-identifier",
62 "read-live-activity-push-token",
63 "load-live-activity-registration-identifier",
64 "list-active-live-activities",
65 "load-live-activity-prime-preferences",
66 "prime-live-activity",
67 "load-registration-record",
68]);
69​
70export class AgentAwarenessOperationError extends Schema.TaggedError<AgentAwarenessOperationError>()(
71 "AgentAwarenessOperationError",
72 {
73 operation: AgentAwarenessOperation,
74 cause: Schema.Defect(),
75 },
76) {
77 override get message(): string {
78 return `Agent awareness operation ${this.operation} failed.`;
79 }
81​
82export type AgentAwarenessRegistrationError =
83 | AgentAwarenessOperationError
84 | ManagedRelay.ManagedRelayClientError;
85​
86// ActivityKit returns new wrappers per id; serialize by id to prevent stale-token registration.
87const activityPushTokenLocks = new Map<string, Semaphore.Semaphore>();
88// Each accepted registration replays the relay aggregate, repairing drifted or orphaned activities.
89const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000;
90// Match the relay's STALE_AFTER_SECONDS so activities expire even if registration fails.
91const LIVE_ACTIVITY_STALE_AFTER_MS = 10 * 60_000;
92const liveActivityStaleDate = () => new Date(Date.now() + LIVE_ACTIVITY_STALE_AFTER_MS);
93const registeredActivityPushTokens = new Map<string, number>();
94// Refreshes can overlap (sign-in, foreground, retry); only the newest read may
95// repaint, so a slow older response never overwrites newer rows.
96let widgetSnapshotReads = 0;
97let androidDeviceReplayedAt: number | null = null;
98let lastNativePushToken: string | null = null;
99let registeredWithPushToken = false;
100let nativePushTokenRotations = 0;
101let pushTokenSubscription: { remove: () => void } | null = null;
102let appStateSubscription: { remove: () => void } | null = null;
103​
104export type AgentAwarenessRegistrationStatus = "unknown" | "pending" | "registered" | "failed";
105let registrationStatus: AgentAwarenessRegistrationStatus = "unknown";
106const registrationStatusListeners = new Set<() => void>();
107​
108function setRegistrationStatus(
109 next: AgentAwarenessRegistrationStatus,
110 withPushToken = registeredWithPushToken,
111): void {
112 if (registrationStatus === next && registeredWithPushToken === withPushToken) {
113 return;
114 }
115 registrationStatus = next;
116 registeredWithPushToken = withPushToken;
117 for (const listener of registrationStatusListeners) {
118 listener();
119 }
121​
122export function getAgentAwarenessRegistrationStatus(): AgentAwarenessRegistrationStatus {
123 return registrationStatus;
125​
126// Live Activities use their own push tokens, so device registration alone does not mean
127// the relay can deliver notifications.
128export function agentAwarenessNotificationsReady(): boolean {
129 return registrationStatus === "registered" && registeredWithPushToken;
131​
132export function subscribeAgentAwarenessRegistrationStatus(listener: () => void): () => void {
133 registrationStatusListeners.add(listener);
134 return () => {
135 registrationStatusListeners.delete(listener);
136 };
138let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;
139let relayTokenProvider: (() => Promise<string | null>) | null = null;
140let relayTokenProviderIdentity: string | null = null;
141let deviceRegistrationGeneration = 0;
142let activeDeviceRegistration: {
143 readonly input: DeviceRegistrationInput;
144 operation: Promise<void>;
145} | null = null;
146let pendingDeviceRegistration: {
147 readonly input: DeviceRegistrationInput;
148 readonly context: string;
149} | null = null;
150​
151interface DeviceRegistrationInput {
152 readonly observedPushToken?: string;
154​
155interface RegisterDeviceInput extends DeviceRegistrationInput {
156 readonly preferencesOverride?: Partial<Preferences>;
158​
159function mergeAgentAwarenessRegistrationPreferences(
160 stored: Preferences,
161 override: Partial<Preferences> | undefined,
162): Preferences {
163 return { ...stored, ...override };
165​
166function readRelayConfig(): { readonly url: string } | null {
167 const relayUrl = resolveCloudPublicConfig().relay.url;
168 if (!relayUrl) {
169 return null;
170 }
171​
172 return { url: relayUrl };
174​
175function canRegisterRemoteLiveActivities(): boolean {
176 return Platform.OS === "ios";
178​
179function canRegisterPushNotifications(): boolean {
180 return Platform.OS === "ios" || Platform.OS === "android";
182​
183function shouldRegisterAgentAwarenessDeviceForProvider(
184 previousIdentity: string | null,
185 identity: string | undefined,
186): boolean {
187 return identity === undefined || identity !== previousIdentity;
189​
190export function setAgentAwarenessRelayTokenProvider(
191 provider: (() => Promise<string | null>) | null,
192 identity?: string,
193): void {
194 const isExistingIdentity =
195 provider !== null &&
196 !shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity);
197 if (!isExistingIdentity) {
198 // An unset JS identity may mean remount; native configure checks the persisted account on cold start.
199 if (relayTokenProviderIdentity && identity !== relayTokenProviderIdentity) {
200 clearAndroidAgentNotifications();
201 }
202 if (provider) {
203 publishWidget({ kind: "loading" });
204 }
205 androidDeviceReplayedAt = null;
206 deviceRegistrationGeneration++;
207 activeDeviceRegistration = null;
208 pendingDeviceRegistration = null;
209 registeredActivityPushTokens.clear();
210 }
211 relayTokenProvider = provider;
212 relayTokenProviderIdentity = provider ? (identity ?? null) : null;
213 if (!provider) {
214 clearAndroidAgentNotifications();
215 pushTokenSubscription?.remove();
216 pushTokenSubscription = null;
217 appStateSubscription?.remove();
218 appStateSubscription = null;
219 if (activeLiveActivityRegistrationRetry) {
220 clearTimeout(activeLiveActivityRegistrationRetry);
221 activeLiveActivityRegistrationRetry = null;
222 }
223 // Signed-out activities would be orphaned because the relay can no longer update or end them.
224 endLocalLiveActivities("live activity cleanup after cloud sign-out failed");
225 publishWidget({ kind: "signed-out" });
226 setRegistrationStatus("unknown");
227 void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => {
228 logRegistrationError("clear registration record on sign-out failed", error);
229 });
230 return;
231 }
232 ensurePushTokenListener();
233 ensureAppStateListener();
234 runRegistrationInBackground(
235 refreshActiveLiveActivityRemoteRegistration(),
236 "active live activity registration after cloud sign-in failed",
237 );
238 if (isExistingIdentity) {
239 if (registrationStatus !== "registered") {
240 enqueueDeviceRegistration({}, "device registration retry after cloud session refresh failed");
241 }
242 return;
243 }
244 enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");
246​
247// Provider remounts retain a valid relay registration; teardown must preserve it and lock-screen activities.
248export function releaseAgentAwarenessRelayTokenProvider(): void {
249 relayTokenProvider = null;
250 relayTokenProviderIdentity = null;
251 deviceRegistrationGeneration++;
252 activeDeviceRegistration = null;
253 pendingDeviceRegistration = null;
254 androidDeviceReplayedAt = null;
255 pushTokenSubscription?.remove();
256 pushTokenSubscription = null;
257 appStateSubscription?.remove();
258 appStateSubscription = null;
259 if (activeLiveActivityRegistrationRetry) {
260 clearTimeout(activeLiveActivityRegistrationRetry);
261 activeLiveActivityRegistrationRetry = null;
262 }
264​
265function iosMajorVersion(): number {
266 const version = Platform.Version;
267 if (typeof version === "number") {
268 return Math.floor(version);
269 }
270 const major = Number.parseInt(version.split(".")[0] ?? "", 10);
271 return Number.isFinite(major) ? major : 18;
273​
274const nativePushTokenRegistration = Effect.fn("remoteRegistration.nativePushTokenRegistration")(
275 function* (observedPushToken?: string) {
276 if (!canRegisterPushNotifications() || !supportsAgentAwarenessPush()) {
277 return { notificationsEnabled: false, pushToken: null, notificationPermissionGranted: false };
278 }
279 const permissions = yield* Effect.tryPromise({
280 try: () => Notifications.getPermissionsAsync(),
281 catch: (cause) =>
282 new AgentAwarenessOperationError({
283 operation: "read-notification-permissions",
284 cause,
285 }),
286 });
287 // Android FCM data delivery is independent of notification presentation permission.
288 if (!permissions.granted && Platform.OS !== "android") {
289 return { notificationsEnabled: false, pushToken: null, notificationPermissionGranted: false };
290 }
291 const alertsEnabled =
292 permissions.granted &&
293 (Platform.OS === "android" && Number(Platform.Version) >= 26
294 ? yield* Effect.tryPromise({
295 try: () => Notifications.getNotificationChannelAsync("agent-alerts"),
296 catch: (cause) =>
297 new AgentAwarenessOperationError({
298 operation: "read-notification-permissions",
299 cause,
300 }),
301 }).pipe(
302 Effect.map((channel) => channel?.importance !== Notifications.AndroidImportance.NONE),
303 Effect.orElseSucceed(() => false),
304 )
305 : true);
306 if (observedPushToken) {
307 lastNativePushToken = observedPushToken;
308 nativePushTokenRotations++;
309 return {
310 notificationsEnabled: alertsEnabled,
311 pushToken: observedPushToken,
312 notificationPermissionGranted: permissions.granted,
313 };
314 }
315 const rotationsBeforeLookup = nativePushTokenRotations;
316 const token = yield* Effect.tryPromise({
317 try: () => Notifications.getDevicePushTokenAsync(),
318 catch: (cause) =>
319 new AgentAwarenessOperationError({
320 operation: "read-native-push-token",
321 cause,
322 }),
323 }).pipe(
324 Effect.tapError((error) =>
325 Effect.sync(() => {
326 logRegistrationError("native push token lookup failed", error);
327 }),
328 ),
329 Effect.orElseSucceed(() => null),
330 );
331 const lookedUpPushToken =
332 token?.type === Platform.OS && typeof token.data === "string" && token.data.trim().length > 0
333 ? token.data.trim()
334 : null;
335 // A rotation observed while this lookup ran is newer than what the lookup returned.
336 if (lookedUpPushToken && rotationsBeforeLookup === nativePushTokenRotations) {
337 lastNativePushToken = lookedUpPushToken;
338 }
339 const pushToken = lastNativePushToken;
340 // A missing token must not disable notifications the relay accepted.
341 return {
342 notificationsEnabled: alertsEnabled,
343 pushToken,
344 notificationPermissionGranted: permissions.granted,
345 };
346 },
347);
348​
349const relayToken = Effect.fn("remoteRegistration.relayToken")(function* (
350 operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",
351) {
352 const provider = relayTokenProvider;
353 if (!provider) {
354 return null;
355 }
356 return yield* Effect.tryPromise({
357 try: provider,
358 catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),
359 });
360});
361​
362function registrationSignature(body: RelayDeviceRegistrationRequest): string {
363 return [
364 body.deviceId,
365 body.pushToken ?? "",
366 body.bundleId ?? "",
367 body.apsEnvironment ?? "",
368 body.appVersion ?? "",
369 body.label,
370 body.platform,
371 body.iosMajorVersion,
372 body.androidApiLevel,
373 body.preferences.notificationsEnabled,
374 body.preferences.liveActivitiesEnabled,
375 body.preferences.notifyOnApproval,
376 body.preferences.notifyOnInput,
377 body.preferences.notifyOnCompletion,
378 body.preferences.notifyOnFailure,
379 ].join("|");
381​
382const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWithRelay")(function* (
383 body: RelayDeviceRegistrationRequest,
384 expectedGeneration: number,
385): Effect.fn.Return<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
386 if (expectedGeneration !== deviceRegistrationGeneration) {
387 return;
388 }
389 const relayConfig = readRelayConfig();
390 if (!relayConfig) {
391 setRegistrationStatus("unknown");
392 return;
393 }
394 const token = yield* relayToken("read-device-registration-relay-token");
395 if (expectedGeneration !== deviceRegistrationGeneration) {
396 return;
397 }
398 if (!token) {
399 setRegistrationStatus("unknown");
400 return;
401 }
402​
403 const identity = relayTokenProviderIdentity ?? "";
404 const persisted = yield* Effect.tryPromise({
405 try: () => loadAgentAwarenessRegistrationRecord(),
406 catch: (cause) =>
407 new AgentAwarenessOperationError({ operation: "load-registration-record", cause }),
408 }).pipe(Effect.orElseSucceed(() => null));
409 if (expectedGeneration !== deviceRegistrationGeneration) {
410 // Signed out while the record loaded — do not resurrect the cleared
411 // record or report the previous account's registration as current.
412 return;
413 }
414 const payload = body;
415 const signature = `${relayConfig.url}|${registrationSignature(payload)}`;
416 // Android registration also silently replays the current card. Collapse
417 // foreground bursts, but repair missed pushes on cold start or a return
418 // after time away, just like re-registering an iOS activity token.
419 const now = yield* Clock.currentTimeMillis;
420 const needsAndroidReplay =
421 body.platform === "android" &&
422 (androidDeviceReplayedAt === null ||
423 now - androidDeviceReplayedAt >= ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS);
424 if (
425 persisted &&
426 persisted.identity === identity &&
427 persisted.signature === signature &&
428 !needsAndroidReplay
429 ) {
430 setRegistrationStatus("registered", Boolean(payload.pushToken));
431 return;
432 }
433​
434 const client = yield* ManagedRelay.ManagedRelayClient;
435 yield* client.registerDevice({
436 clerkToken: token,
437 payload,
438 });
439 if (expectedGeneration !== deviceRegistrationGeneration) {
440 // Signed out while the request was in flight: the sign-out path already
441 // reset the status and cleared the record for the next account, so a
442 // stale success must not overwrite either.
443 return;
444 }
445 if (body.platform === "android") androidDeviceReplayedAt = yield* Clock.currentTimeMillis;
446 setRegistrationStatus("registered", Boolean(payload.pushToken));
447 yield* Effect.promise(() =>
448 saveAgentAwarenessRegistrationRecord({
449 identity,
450 signature,
451 }).catch((error: unknown) => {
452 logRegistrationError("persist registration record failed", error);
453 }),
454 );
455});
456​
457const unregisterDeviceWithRelay = Effect.fn("remoteRegistration.unregisterDeviceWithRelay")(
458 function* (input: {
459 readonly deviceId: string;
460 readonly tokenProvider: () => Promise<string | null>;
461 }): Effect.fn.Return<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
462 if (!readRelayConfig()) return;
463 const token = yield* Effect.tryPromise({
464 try: input.tokenProvider,
465 catch: (cause) =>
466 new AgentAwarenessOperationError({
467 operation: "read-device-unregistration-relay-token",
468 cause,
469 }),
470 });
471 if (!token) {
472 return;
473 }
474​
475 const client = yield* ManagedRelay.ManagedRelayClient;
476 yield* client.unregisterDevice({
477 clerkToken: token,
478 deviceId: input.deviceId,
479 });
480 },
481);
482​
483function environmentPublishesAgentActivity(environmentId: EnvironmentId): boolean {
484 return (
485 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
486 .agentActivityPublishing !== false
487 );
489​
490export function armAgentAwarenessLiveActivityForLocalWork(input: {
491 readonly environmentId: EnvironmentId;
492 readonly threadTitle: string;
493 readonly projectTitle: string;
494}): void {
495 if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
496 return;
497 }
498 if (!environmentPublishesAgentActivity(input.environmentId)) {
499 return;
500 }
501 void loadPreferences()
502 .catch(() => null)
503 .then((preferences) => {
504 if (preferences?.liveActivitiesEnabled === false) {
505 return;
506 }
507 armAgentAwarenessLiveActivityForLocalWorkNow(input);
508 });
510​
511function armAgentAwarenessLiveActivityForLocalWorkNow(input: {
512 readonly threadTitle: string;
513 readonly projectTitle: string;
514}): void {
515 try {
516 if (getAgentLiveActivities().length > 0) {
517 return;
518 }
519 const nowIso = new Date(Date.now()).toISOString();
520 const activity = startAgentLiveActivity(
521 {
522 title: "T3 Code",
523 subtitle: "Agent work in progress",
524 activeCount: 1,
525 updatedAt: nowIso,
526 activities: [
527 {
528 environmentId: "",
529 threadId: "",
530 projectTitle: input.projectTitle,
531 threadTitle: input.threadTitle,
532 modelTitle: "",
533 phase: "starting",
534 status: "Connecting",
535 updatedAt: nowIso,
536 deepLink: "/",
537 },
538 ],
539 },
540 liveActivityStaleDate(),
541 );
542 if (!activity) {
543 return;
544 }
545 runRegistrationInBackground(
546 registerLiveActivityPushToken({ activity }).pipe(Effect.asVoid),
547 "live activity arming after local task start failed",
548 );
549 } catch (error) {
550 logRegistrationError("live activity arming failed", error);
551 }
553​
554const readAgentActivitySnapshot: () => Effect.Effect<
555 RelayAgentActivitySnapshotResponse | null,
556 never,
557 ManagedRelay.ManagedRelayClient
558> = Effect.fn("remoteRegistration.readAgentActivitySnapshot")(
559 function* () {
560 if (!readRelayConfig()) return null;
561 const token = yield* relayToken("read-live-activity-registration-relay-token");
562 if (!token) {
563 return null;
564 }
565 const client = yield* ManagedRelay.ManagedRelayClient;
566 return yield* client.getAgentActivitySnapshot({ clerkToken: token });
567 },
568 Effect.catch((error) =>
569 Effect.sync(() => {
570 logRegistrationError("agent activity snapshot read failed", error);
571 return null;
572 }),
573 ),
574);
575​
576const registerLiveActivityWithRelay = Effect.fn("remoteRegistration.registerLiveActivityWithRelay")(
577 function* (
578 body: RelayLiveActivityRegistrationRequest,
579 ): Effect.fn.Return<boolean, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
580 if (!readRelayConfig()) return false;
581 const token = yield* relayToken("read-live-activity-registration-relay-token");
582 if (!token) {
583 return false;
584 }
585​
586 const client = yield* ManagedRelay.ManagedRelayClient;
587 yield* client.registerLiveActivity({
588 clerkToken: token,
589 payload: body,
590 });
591 return true;
592 },
593);
594​
595function logRegistrationError(context: string, error: unknown): void {
596 if (!__DEV__) {
597 return;
598 }
599 console.warn(`[agent-awareness] ${context}`, {
600 message: error instanceof Error ? error.message : String(error),
601 traceId: findErrorTraceId(error),
602 error,
603 });
605​
606function runRegistrationInBackground<E>(
607 operation: Effect.Effect<unknown, E, ManagedRelay.ManagedRelayClient>,
608 context: string,
609): void {
610 void (async () => {
611 const result = await settleAsyncResult(() => runtime.runPromiseExit(operation));
612 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
613 logRegistrationError(context, squashAtomCommandFailure(result));
614 }
615 })();
617​
618function mergeDeviceRegistrationInput(
619 current: DeviceRegistrationInput,
620 next: DeviceRegistrationInput,
621): DeviceRegistrationInput {
622 const observedPushToken = next.observedPushToken ?? current.observedPushToken;
623 return observedPushToken ? { observedPushToken } : {};
625​
626function registrationAddsInformation(
627 current: DeviceRegistrationInput,
628 next: DeviceRegistrationInput,
629): boolean {
630 return (
631 next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken
632 );
634​
635function startPendingDeviceRegistration(): void {
636 if (activeDeviceRegistration || !pendingDeviceRegistration) {
637 return;
638 }
639​
640 const next = pendingDeviceRegistration;
641 pendingDeviceRegistration = null;
642 const generation = deviceRegistrationGeneration;
643 if (registrationStatus !== "registered") {
644 setRegistrationStatus("pending");
645 }
646 const registration = {
647 input: next.input,
648 operation: Promise.resolve(),
649 };
650 activeDeviceRegistration = registration;
651 registration.operation = (async () => {
652 const result = await settleAsyncResult(() =>
653 runtime.runPromiseExit(registerDevice(next.input, generation)),
654 );
655 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
656 // Refresh failures leave the relay's accepted registration intact; preserve registered status.
657 if (registrationStatus !== "registered") {
658 setRegistrationStatus("failed");
659 }
660 logRegistrationError(next.context, squashAtomCommandFailure(result));
661 }
662 if (activeDeviceRegistration === registration) {
663 activeDeviceRegistration = null;
664 }
665 startPendingDeviceRegistration();
666 })();
668​
669function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: string): void {
670 if (
671 activeDeviceRegistration &&
672 !registrationAddsInformation(activeDeviceRegistration.input, input)
673 ) {
674 return;
675 }
676​
677 pendingDeviceRegistration = pendingDeviceRegistration
678 ? {
679 input: mergeDeviceRegistrationInput(pendingDeviceRegistration.input, input),
680 context,
681 }
682 : { input, context };
683 startPendingDeviceRegistration();
685​
686const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* (
687 input: RegisterDeviceInput = {},
688 expectedGeneration = deviceRegistrationGeneration,
689): Effect.fn.Return<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
690 if (!canRegisterPushNotifications()) {
691 return;
692 }
693​
694 const [deviceId, storedPreferences] = yield* Effect.all([
695 Effect.tryPromise({
696 try: () => loadOrCreateAgentAwarenessDeviceId(),
697 catch: (cause) =>
698 new AgentAwarenessOperationError({
699 operation: "load-device-registration-identifier",
700 cause,
701 }),
702 }),
703 Effect.tryPromise({
704 try: () => loadPreferences(),
705 catch: (cause) =>
706 new AgentAwarenessOperationError({
707 operation: "load-device-registration-preferences",
708 cause,
709 }),
710 }),
711 ]);
712 const preferences = mergeAgentAwarenessRegistrationPreferences(
713 storedPreferences,
714 input.preferencesOverride,
715 );
716 if (expectedGeneration !== deviceRegistrationGeneration) return;
717 if (relayTokenProvider && relayTokenProviderIdentity) {
718 configureAndroidAgentNotifications(
719 deviceId,
720 relayTokenProviderIdentity,
721 preferences.liveActivitiesEnabled !== false,
722 );
723 }
724 const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
725 const bundleId =
726 Platform.OS === "android"
727 ? Constants.expoConfig?.android?.package?.trim()
728 : Constants.expoConfig?.ios?.bundleIdentifier?.trim();
729 yield* registerDeviceWithRelay(
730 makeRelayDeviceRegistrationRequest({
731 deviceId,
732 label:
733 Constants.deviceName?.trim() ||
734 (Platform.OS === "android" ? "Android device" : "iOS device"),
735 ...(Platform.OS === "android"
736 ? {
737 platform: "android" as const,
738 androidApiLevel: Number(Platform.Version),
739 notificationPermissionGranted: pushTokenRegistration.notificationPermissionGranted,
740 }
741 : { platform: "ios" as const, iosMajorVersion: iosMajorVersion() }),
742 appVersion: Constants.expoConfig?.version,
743 ...(bundleId ? { bundleId } : {}),
744 ...(Platform.OS === "ios"
745 ? { apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant) }
746 : {}),
747 ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),
748 notificationsEnabled: pushTokenRegistration.notificationsEnabled,
749 preferences,
750 }),
751 expectedGeneration,
752 );
753});
754​
755function registerDeviceForCurrentUser(): Effect.Effect<
756 void,
757 AgentAwarenessRegistrationError,
758 ManagedRelay.ManagedRelayClient
759> {
760 return registerDevice(undefined);
762​
763function ensurePushTokenListener(): void {
764 if (pushTokenSubscription || !canRegisterPushNotifications()) {
765 return;
766 }
767​
768 pushTokenSubscription = Notifications.addPushTokenListener((token) => {
769 if (
770 token.type === Platform.OS &&
771 typeof token.data === "string" &&
772 token.data.trim().length > 0
773 ) {
774 enqueueDeviceRegistration(
775 { observedPushToken: token.data.trim() },
776 "native push token rotation registration failed",
777 );
778 }
779 });
781​
782function ensureAppStateListener(): void {
783 if (appStateSubscription || !canRegisterPushNotifications()) {
784 return;
785 }
786​
787 appStateSubscription = AppState.addEventListener("change", (state) => {
788 if (state !== "active") {
789 return;
790 }
791 enqueueDeviceRegistration({}, "device registration after app foreground failed");
792 runRegistrationInBackground(
793 refreshActiveLiveActivityRemoteRegistration(),
794 "active live activity reconciliation after app foreground failed",
795 );
796 });
798​
799function publishWidget(source: AgentActivityWidgetSource): void {
800 if (!canRegisterRemoteLiveActivities()) {
801 return;
802 }
803 publishAgentActivityWidget(source).catch((error: unknown) => {
804 logRegistrationError("agent activity widget publish failed", error);
805 });
807​
808// Binaries built before the native dismissEnded method throw here.
809function dismissEndedLocalLiveActivities(): void {
810 try {
811 dismissEndedAgentLiveActivities();
812 } catch (error) {
813 logRegistrationError("ended live activity cleanup failed", error);
814 }
816​
817function endLocalLiveActivities(context: string): void {
818 if (!canRegisterRemoteLiveActivities()) {
819 return;
820 }
821 dismissEndedLocalLiveActivities();
822 try {
823 for (const activity of getAgentLiveActivities()) {
824 activity.end("immediate").catch((error: unknown) => {
825 logRegistrationError(context, error);
826 });
827 }
828 } catch (error) {
829 logRegistrationError(context, error);
830 }
832​
833export function refreshAgentAwarenessRegistration(): Effect.Effect<
834 void,
835 never,
836 ManagedRelay.ManagedRelayClient
837> {
838 return registerDeviceForCurrentUser().pipe(
839 Effect.catch((error) =>
840 Effect.sync(() => {
841 if (registrationStatus !== "registered") {
842 setRegistrationStatus("failed");
843 }
844 logRegistrationError("device registration refresh failed", error);
845 }),
846 ),
847 );
849​
850export function updateAgentAwarenessRegistrationPreferences(
851 preferencesOverride: Partial<Preferences>,
852): Effect.Effect<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
853 return registerDevice({ preferencesOverride }).pipe(
854 Effect.tapError((error) =>
855 Effect.sync(() => {
856 if (registrationStatus !== "registered") {
857 setRegistrationStatus("failed");
858 }
859 logRegistrationError("device preference registration refresh failed", error);
860 }),
861 ),
862 );
864​
865export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
866 pushTokenSubscription?.remove();
867 pushTokenSubscription = null;
868 appStateSubscription?.remove();
869 appStateSubscription = null;
870 if (activeLiveActivityRegistrationRetry) {
871 clearTimeout(activeLiveActivityRegistrationRetry);
872 activeLiveActivityRegistrationRetry = null;
873 }
874 relayTokenProvider = null;
875 relayTokenProviderIdentity = null;
876 deviceRegistrationGeneration++;
877 activeDeviceRegistration = null;
878 pendingDeviceRegistration = null;
879 registrationStatus = "unknown";
880 registeredWithPushToken = false;
881 androidDeviceReplayedAt = null;
882 lastNativePushToken = null;
883 nativePushTokenRotations = 0;
884 registrationStatusListeners.clear();
885 registeredActivityPushTokens.clear();
886 activityPushTokenLocks.clear();
887 widgetSnapshotReads = 0;
889​
890export const unregisterAgentAwarenessDeviceForCurrentUser: (
891 tokenProvider: () => Promise<string | null>,
892) => Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> = Effect.fn(
893 "remoteRegistration.unregisterAgentAwarenessDeviceForCurrentUser",
894)(
895 function* (tokenProvider: () => Promise<string | null>) {
896 const deviceId = yield* Effect.tryPromise({
897 try: () => loadAgentAwarenessDeviceId(),
898 catch: (cause) =>
899 new AgentAwarenessOperationError({
900 operation: "load-device-unregistration-identifier",
901 cause,
902 }),
903 });
904 if (!deviceId) {
905 return;
906 }
907 yield* unregisterDeviceWithRelay({ deviceId, tokenProvider });
908 },
909 Effect.catch((error) =>
910 Effect.sync(() => {
911 logRegistrationError("device unregistration failed", error);
912 }),
913 ),
914);
915​
916export const registerLiveActivityPushToken = Effect.fn(
917 "remoteRegistration.registerLiveActivityPushToken",
918)(function* (input: {
919 readonly activity: LiveActivity<AgentActivityProps>;
920}): Effect.fn.Return<boolean, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
921 if (!canRegisterRemoteLiveActivities()) {
922 return false;
923 }
924​
925 const lock = observeLiveActivityPushTokens(input.activity);
926 return yield* lock.withPermit(
927 Effect.gen(function* () {
928 const activityPushToken = yield* Effect.tryPromise({
929 try: () => input.activity.getPushToken(),
930 catch: (cause) =>
931 new AgentAwarenessOperationError({
932 operation: "read-live-activity-push-token",
933 cause,
934 }),
935 });
936 if (!activityPushToken) {
937 return false;
938 }
939​
940 return yield* registerLiveActivityPushTokenValue({ activityPushToken });
941 }),
942 );
943});
944​
945// Observe every token replacement: the relay otherwise keeps pushing to the old token until APNs rejects it.
946function observeLiveActivityPushTokens(
947 activity: LiveActivity<AgentActivityProps>,
948): Semaphore.Semaphore {
949 const activityId = activity.getId();
950 const existing = activityPushTokenLocks.get(activityId);
951 if (existing) return existing;
952 const lock = Semaphore.makeUnsafe(1);
953 activityPushTokenLocks.set(activityId, lock);
954 activity.addPushTokenListener((event) => {
955 if (!event.pushToken) return;
956 runRegistrationInBackground(
957 lock.withPermit(registerLiveActivityPushTokenValue({ activityPushToken: event.pushToken })),
958 "live activity token listener registration failed",
959 );
960 });
961 return lock;
963​
964const registerLiveActivityPushTokenValue = Effect.fn(
965 "remoteRegistration.registerLiveActivityPushTokenValue",
966)(function* (input: {
967 readonly activityPushToken: string;
968}): Effect.fn.Return<boolean, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
969 const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
970 if (
971 acceptedAt !== undefined &&
972 (yield* Clock.currentTimeMillis) - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS
973 ) {
974 return true;
975 }
976 const deviceId = yield* Effect.tryPromise({
977 try: () => loadOrCreateAgentAwarenessDeviceId(),
978 catch: (cause) =>
979 new AgentAwarenessOperationError({
980 operation: "load-live-activity-registration-identifier",
981 cause,
982 }),
983 });
984 const registered = yield* registerLiveActivityWithRelay({
985 deviceId,
986 activityPushToken: input.activityPushToken,
987 });
988 if (registered) {
989 registeredActivityPushTokens.set(input.activityPushToken, yield* Clock.currentTimeMillis);
990 }
991 return registered;
992});
993​
994function scheduleActiveLiveActivityRegistrationRetry(): void {
995 if (activeLiveActivityRegistrationRetry || !relayTokenProvider) {
996 return;
997 }
998​
999 activeLiveActivityRegistrationRetry = setTimeout(() => {
1000 activeLiveActivityRegistrationRetry = null;
1001 runRegistrationInBackground(
1002 refreshActiveLiveActivityRemoteRegistration(),
1003 "active live activity token retry failed",
1004 );
1005 }, REMOTE_ACTIVITY_REGISTRATION_RETRY_MS);
1007​
1008export const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
1009 "remoteRegistration.refreshActiveLiveActivityRemoteRegistration",
1010)(function* (): Effect.fn.Return<void, never, ManagedRelay.ManagedRelayClient> {
1011 if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
1012 return;
1014​
1015 // The home-screen widget has no push path of its own, so every foreground
1016 // refresh repaints it from one snapshot read. Yields undefined once the
1017 // account changed or a newer read started, so a stale result is never
1018 // shown or primed.
1019 const generation = deviceRegistrationGeneration;
1020 const isCurrentAccount = () =>
1021 relayTokenProvider !== null && deviceRegistrationGeneration === generation;
1022 let read = 0;
1023 const isNewestRead = () => isCurrentAccount() && read === widgetSnapshotReads;
1024 const refreshWidget = Effect.gen(function* () {
1025 // An obsolete refresh must not supersede the current account's read.
1026 if (!isCurrentAccount()) {
1027 return undefined;
1029 read = ++widgetSnapshotReads;
1030 const snapshot = yield* readAgentActivitySnapshot();
1031 if (!isNewestRead()) {
1032 return undefined;
1034 if (snapshot) {
1035 publishWidget({ kind: "snapshot", aggregate: snapshot.aggregate });
1036 } else {
1037 publishWidget({ kind: "unavailable" });
1039 return { snapshot };
1040 });
1041​
1042 dismissEndedLocalLiveActivities();
1043 let activities = yield* Effect.try({
1044 try: () => getAgentLiveActivities(),
1045 catch: (cause) =>
1046 new AgentAwarenessOperationError({
1047 operation: "list-active-live-activities",
1048 cause,
1049 }),
1050 }).pipe(
1051 Effect.catch((error) =>
1052 Effect.sync(() => {
1053 logRegistrationError("active live activity lookup failed", error);
1054 return [] as ReadonlyArray<LiveActivity<AgentActivityProps>>;
1055 }),
1056 ),
1057 );
1058​
1059 // The relay tracks exactly one card per device; if concurrent arming ever
1060 // produced extras, end them so only one keeps receiving updates.
1061 const hadActivities = activities.length > 0;
1062 if (activities.length > 1) {
1063 for (const extra of activities.slice(1)) {
1064 extra.end("immediate").catch((error: unknown) => {
1065 logRegistrationError("duplicate live activity cleanup failed", error);
1066 });
1068 activities = activities.slice(0, 1);
1070​
1071 // Activities are only ever created here, in the foreground, where the
1072 // update token can be observed and registered immediately — the relay never
1073 // remote-starts one (background push-to-start wakes proved too unreliable
1074 // to hand the token over).
1075 if (!hadActivities) {
1076 const widgetRead = yield* refreshWidget;
1077 if (!widgetRead) {
1078 return;
1080 const { snapshot } = widgetRead;
1081 const preferences = yield* Effect.tryPromise({
1082 try: () => loadPreferences(),
1083 catch: (cause) =>
1084 new AgentAwarenessOperationError({
1085 operation: "load-live-activity-prime-preferences",
1086 cause,
1087 }),
1088 }).pipe(Effect.orElseSucceed(() => null));
1089 // A sign-out, account switch, or newer read during the preference read
1090 // makes this snapshot stale; priming now could bring old rows back.
1091 if (!isNewestRead()) {
1092 return;
1094 if (preferences?.liveActivitiesEnabled !== false) {
1095 // The snapshot and preference reads yield; an arm-on-send may have
1096 // created the card in the meantime. Re-check so two cards are never started.
1097 const armedMeanwhile = yield* Effect.try({
1098 try: () => getAgentLiveActivities(),
1099 catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,
1100 }).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));
1101 if (armedMeanwhile.length > 0) {
1102 activities = [...armedMeanwhile];
1103 } else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {
1104 const aggregate = snapshot.aggregate;
1105 const primed = yield* Effect.try({
1106 try: () =>
1107 startAgentLiveActivity(
1109 title: aggregate.title,
1110 subtitle: aggregate.subtitle,
1111 activeCount: aggregate.activeCount,
1112 updatedAt: aggregate.updatedAt,
1113 activities: aggregate.activities,
1114 },
1115 liveActivityStaleDate(),
1116 ),
1117 catch: (cause) =>
1118 new AgentAwarenessOperationError({
1119 operation: "prime-live-activity",
1120 cause,
1121 }),
1122 }).pipe(
1123 Effect.catch((error) =>
1124 Effect.sync(() => {
1125 logRegistrationError("live activity priming failed", error);
1126 return null;
1127 }),
1128 ),
1129 );
1130 if (primed) {
1131 activities = [primed];
1136​
1137 const registrationResults = yield* Effect.forEach(activities, (activity) =>
1138 registerLiveActivityPushToken({ activity }).pipe(
1139 Effect.map((registered) => !registered),
1140 Effect.catch((error) =>
1141 Effect.sync(() => {
1142 logRegistrationError("active live activity token registration failed", error);
1143 return true;
1144 }),
1145 ),
1146 ),
1147 );
1148​
1149 if (registrationResults.some(Boolean)) {
1150 scheduleActiveLiveActivityRegistrationRetry();
1152​
1153 // An existing card keeps its push token registered without waiting on the
1154 // relay; the widget still repaints afterwards.
1155 if (hadActivities) {
1156 yield* refreshWidget;
1158});