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