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