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
258function nativePushTokenRegistration(observedPushToken?: string) {
259 return Effect.gen(function* () {
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 = (
301 operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",
302) =>
303 Effect.gen(function* () {
304 const provider = relayTokenProvider;
305 if (!provider) {
306 return null;
307 }
308 return yield* Effect.tryPromise({
309 try: provider,
310 catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),
311 });
312 });
313
314function registrationSignature(body: RelayDeviceRegistrationRequest): string {
315 return [
316 body.deviceId,
317 body.pushToken ?? "",
318 body.bundleId ?? "",
319 body.apsEnvironment ?? "",
320 body.appVersion ?? "",
321 body.label,
322 body.platform,
323 body.iosMajorVersion,
324 body.androidApiLevel,
325 body.preferences.notificationsEnabled,
326 body.preferences.liveActivitiesEnabled,
327 body.preferences.notifyOnApproval,
328 body.preferences.notifyOnInput,
329 body.preferences.notifyOnCompletion,
330 body.preferences.notifyOnFailure,
331 ].join("|");
332}
333
334function registerDeviceWithRelay(
335 body: RelayDeviceRegistrationRequest,
336 expectedGeneration: number,
337): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
338 return Effect.gen(function* () {
339 if (expectedGeneration !== deviceRegistrationGeneration) {
340 logRegistrationDebug("device registration cancelled before relay request", {
341 expectedGeneration,
342 currentGeneration: deviceRegistrationGeneration,
343 });
344 return;
345 }
346 const relayConfig = readRelayConfig();
347 if (!relayConfig) {
348 setRegistrationStatus("unknown");
349 return;
350 }
351 const token = yield* relayToken("read-device-registration-relay-token");
352 if (expectedGeneration !== deviceRegistrationGeneration) {
353 logRegistrationDebug("device registration cancelled after auth lookup", {
354 expectedGeneration,
355 currentGeneration: deviceRegistrationGeneration,
356 });
357 return;
358 }
359 if (!token) {
360 logRegistrationDebug("relay device registration skipped; user is not signed in");
361 setRegistrationStatus("unknown");
362 return;
363 }
364
365 const identity = relayTokenProviderIdentity ?? "";
366 const persisted = yield* Effect.tryPromise({
367 try: () => loadAgentAwarenessRegistrationRecord(),
368 catch: (cause) => cause,
369 }).pipe(Effect.orElseSucceed(() => null));
370 if (expectedGeneration !== deviceRegistrationGeneration) {
371 // Signed out while the record loaded — do not resurrect the cleared
372 // record or report the previous account's registration as current.
373 logRegistrationDebug("device registration cancelled after record lookup", {
374 expectedGeneration,
375 currentGeneration: deviceRegistrationGeneration,
376 });
377 return;
378 }
379 const payload = body;
380 const signature = `${relayConfig.url}|${registrationSignature(payload)}`;
381 // Android registration also silently replays the current card. Collapse
382 // foreground bursts, but repair missed pushes on cold start or a return
383 // after time away, just like re-registering an iOS activity token.
384 const needsAndroidReplay =
385 body.platform === "android" &&
386 (androidDeviceReplayedAt === null ||
387 Date.now() - androidDeviceReplayedAt >= ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS);
388 if (
389 persisted &&
390 persisted.identity === identity &&
391 persisted.signature === signature &&
392 !needsAndroidReplay
393 ) {
394 setRegistrationStatus("registered");
395 logRegistrationDebug("relay device registration skipped; already registered for account", {
396 expectedGeneration,
397 });
398 return;
399 }
400
401 const client = yield* ManagedRelay.ManagedRelayClient;
402 logRegistrationDebug("relay device registration request started", {
403 expectedGeneration,
404 });
405 yield* client.registerDevice({
406 clerkToken: token,
407 payload,
408 });
409 if (expectedGeneration !== deviceRegistrationGeneration) {
410 // Signed out while the request was in flight: the sign-out path already
411 // reset the status and cleared the record for the next account, so a
412 // stale success must not overwrite either.
413 logRegistrationDebug("device registration completed after sign-out; result discarded", {
414 expectedGeneration,
415 currentGeneration: deviceRegistrationGeneration,
416 });
417 return;
418 }
419 if (body.platform === "android") androidDeviceReplayedAt = Date.now();
420 setRegistrationStatus("registered");
421 yield* Effect.promise(() =>
422 saveAgentAwarenessRegistrationRecord({
423 identity,
424 signature,
425 }).catch((error: unknown) => {
426 logRegistrationError("persist registration record failed", error);
427 }),
428 );
429 logRegistrationDebug("relay device registration request completed", {
430 expectedGeneration,
431 });
432 });
433}
434
435function unregisterDeviceWithRelay(input: {
436 readonly deviceId: string;
437 readonly tokenProvider: () => Promise<string | null>;
438}): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
439 return Effect.gen(function* () {
440 if (!readRelayConfig()) return;
441 const token = yield* Effect.tryPromise({
442 try: input.tokenProvider,
443 catch: (cause) =>
444 new AgentAwarenessOperationError({
445 operation: "read-device-unregistration-relay-token",
446 cause,
447 }),
448 });
449 if (!token) {
450 logRegistrationDebug("relay device unregistration skipped; user is not signed in");
451 return;
452 }
453
454 const client = yield* ManagedRelay.ManagedRelayClient;
455 yield* client.unregisterDevice({
456 clerkToken: token,
457 deviceId: input.deviceId,
458 });
459 });
460}
461
462function environmentPublishesAgentActivity(environmentId: EnvironmentId): boolean {
463 return (
464 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
465 .agentActivityPublishing !== false
466 );
467}
468
469export function armAgentAwarenessLiveActivityForLocalWork(input: {
470 readonly environmentId: EnvironmentId;
471 readonly threadTitle: string;
472 readonly projectTitle: string;
473}): void {
474 if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
475 return;
476 }
477 if (!environmentPublishesAgentActivity(input.environmentId)) {
478 logRegistrationDebug("live activity arming skipped; environment does not publish", {
479 environmentId: input.environmentId,
480 });
481 return;
482 }
483 void loadPreferences()
484 .catch(() => null)
485 .then((preferences) => {
486 if (preferences?.liveActivitiesEnabled === false) {
487 return;
488 }
489 armAgentAwarenessLiveActivityForLocalWorkNow(input);
490 });
491}
492
493function armAgentAwarenessLiveActivityForLocalWorkNow(input: {
494 readonly threadTitle: string;
495 readonly projectTitle: string;
496}): void {
497 try {
498 if (getAgentLiveActivities().length > 0) {
499 return;
500 }
501 const nowIso = new Date(Date.now()).toISOString();
502 const activity = startAgentLiveActivity(
503 {
504 title: "T3 Code",
505 subtitle: "Agent work in progress",
506 activeCount: 1,
507 updatedAt: nowIso,
508 activities: [
509 {
510 environmentId: "",
511 threadId: "",
512 projectTitle: input.projectTitle,
513 threadTitle: input.threadTitle,
514 modelTitle: "",
515 phase: "starting",
516 status: "Connecting",
517 updatedAt: nowIso,
518 deepLink: "/",
519 },
520 ],
521 },
522 liveActivityStaleDate(),
523 );
524 if (!activity) {
525 return;
526 }
527 logRegistrationDebug("live activity card armed for local work", {
528 threadTitle: input.threadTitle,
529 });
530 runRegistrationInBackground(
531 registerLiveActivityPushToken({ activity }).pipe(Effect.asVoid),
532 "live activity arming after local task start failed",
533 );
534 } catch (error) {
535 logRegistrationError("live activity arming failed", error);
536 }
537}
538
539function readAgentActivitySnapshot(): Effect.Effect<
540 RelayAgentActivitySnapshotResponse | null,
541 never,
542 ManagedRelay.ManagedRelayClient
543> {
544 return Effect.gen(function* () {
545 if (!readRelayConfig()) return null;
546 const token = yield* relayToken("read-live-activity-registration-relay-token");
547 if (!token) {
548 return null;
549 }
550 const client = yield* ManagedRelay.ManagedRelayClient;
551 return yield* client.getAgentActivitySnapshot({ clerkToken: token });
552 }).pipe(
553 Effect.catch((error) =>
554 Effect.sync(() => {
555 logRegistrationError("agent activity snapshot read failed", error);
556 return null;
557 }),
558 ),
559 );
560}
561
562function registerLiveActivityWithRelay(
563 body: RelayLiveActivityRegistrationRequest,
564): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
565 return Effect.gen(function* () {
566 if (!readRelayConfig()) return false;
567 const token = yield* relayToken("read-live-activity-registration-relay-token");
568 if (!token) {
569 logRegistrationDebug("relay live activity registration skipped; user is not signed in");
570 return false;
571 }
572
573 const client = yield* ManagedRelay.ManagedRelayClient;
574 yield* client.registerLiveActivity({
575 clerkToken: token,
576 payload: body,
577 });
578 return true;
579 });
580}
581
582function logRegistrationError(context: string, error: unknown): void {
583 if (!__DEV__) {
584 return;
585 }
586 console.warn(`[agent-awareness] ${context}`, {
587 message: error instanceof Error ? error.message : String(error),
588 traceId: findErrorTraceId(error),
589 error,
590 });
591}
592
593function logRegistrationDebug(context: string, details?: unknown): void {
594 if (!__DEV__) {
595 return;
596 }
597 console.log(`[agent-awareness] ${context}`, details ?? "");
598}
599
600function runRegistrationInBackground(
601 operation: Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
602 context: string,
603): void {
604 void (async () => {
605 const result = await settleAsyncResult(() => runtime.runPromiseExit(operation));
606 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
607 logRegistrationError(context, squashAtomCommandFailure(result));
608 }
609 })();
610}
611
612function mergeDeviceRegistrationInput(
613 current: DeviceRegistrationInput,
614 next: DeviceRegistrationInput,
615): DeviceRegistrationInput {
616 const observedPushToken = next.observedPushToken ?? current.observedPushToken;
617 return observedPushToken ? { observedPushToken } : {};
618}
619
620function registrationAddsInformation(
621 current: DeviceRegistrationInput,
622 next: DeviceRegistrationInput,
623): boolean {
624 return (
625 next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken
626 );
627}
628
629function startPendingDeviceRegistration(): void {
630 if (activeDeviceRegistration || !pendingDeviceRegistration) {
631 return;
632 }
633
634 const next = pendingDeviceRegistration;
635 pendingDeviceRegistration = null;
636 const generation = deviceRegistrationGeneration;
637 logRegistrationDebug("device registration started", {
638 generation,
639 hasObservedPushToken: next.input.observedPushToken !== undefined,
640 });
641 if (registrationStatus !== "registered") {
642 setRegistrationStatus("pending");
643 }
644 const registration = {
645 input: next.input,
646 operation: Promise.resolve(),
647 };
648 activeDeviceRegistration = registration;
649 registration.operation = (async () => {
650 const result = await settleAsyncResult(() =>
651 runtime.runPromiseExit(registerDevice(next.input, generation)),
652 );
653 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
654 // A transient failure on a later refresh (e.g. token rotation) leaves
655 // the prior accepted registration intact on the relay, so an already
656 // registered device stays "registered" rather than flipping the
657 // settings toggles off.
658 if (registrationStatus !== "registered") {
659 setRegistrationStatus("failed");
660 }
661 logRegistrationError(next.context, squashAtomCommandFailure(result));
662 }
663 logRegistrationDebug("device registration finished", { generation });
664 if (activeDeviceRegistration === registration) {
665 activeDeviceRegistration = null;
666 }
667 startPendingDeviceRegistration();
668 })();
669}
670
671function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: string): void {
672 if (
673 activeDeviceRegistration &&
674 !registrationAddsInformation(activeDeviceRegistration.input, input)
675 ) {
676 logRegistrationDebug("device registration coalesced with active request", {
677 generation: deviceRegistrationGeneration,
678 });
679 return;
680 }
681
682 logRegistrationDebug("device registration enqueued", {
683 generation: deviceRegistrationGeneration,
684 hasActiveRegistration: activeDeviceRegistration !== null,
685 hasPendingRegistration: pendingDeviceRegistration !== null,
686 });
687 pendingDeviceRegistration = pendingDeviceRegistration
688 ? {
689 input: mergeDeviceRegistrationInput(pendingDeviceRegistration.input, input),
690 context,
691 }
692 : { input, context };
693 startPendingDeviceRegistration();
694}
695
696function registerDevice(
697 input: RegisterDeviceInput = {},
698 expectedGeneration = deviceRegistrationGeneration,
699): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
700 return Effect.gen(function* () {
701 if (!canRegisterPushNotifications()) {
702 logRegistrationDebug("device registration skipped; platform does not support it");
703 return;
704 }
705
706 logRegistrationDebug("device registration loading local state", { expectedGeneration });
707 const [deviceId, storedPreferences] = yield* Effect.all([
708 Effect.tryPromise({
709 try: () => loadOrCreateAgentAwarenessDeviceId(),
710 catch: (cause) =>
711 new AgentAwarenessOperationError({
712 operation: "load-device-registration-identifier",
713 cause,
714 }),
715 }),
716 Effect.tryPromise({
717 try: () => loadPreferences(),
718 catch: (cause) =>
719 new AgentAwarenessOperationError({
720 operation: "load-device-registration-preferences",
721 cause,
722 }),
723 }),
724 ]);
725 const preferences = mergeAgentAwarenessRegistrationPreferences(
726 storedPreferences,
727 input.preferencesOverride,
728 );
729 if (expectedGeneration !== deviceRegistrationGeneration) return;
730 if (relayTokenProvider && relayTokenProviderIdentity) {
731 configureAndroidAgentNotifications(
732 deviceId,
733 relayTokenProviderIdentity,
734 preferences.liveActivitiesEnabled !== false,
735 );
736 }
737 const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
738 logRegistrationDebug("device registration local state ready", {
739 expectedGeneration,
740 notificationsEnabled: pushTokenRegistration.notificationsEnabled,
741 });
742 const bundleId =
743 Platform.OS === "android"
744 ? Constants.expoConfig?.android?.package?.trim()
745 : Constants.expoConfig?.ios?.bundleIdentifier?.trim();
746 yield* registerDeviceWithRelay(
747 makeRelayDeviceRegistrationRequest({
748 deviceId,
749 label:
750 Constants.deviceName?.trim() ||
751 (Platform.OS === "android" ? "Android device" : "iOS device"),
752 ...(Platform.OS === "android"
753 ? { platform: "android" as const, androidApiLevel: Number(Platform.Version) }
754 : { platform: "ios" as const, iosMajorVersion: iosMajorVersion() }),
755 appVersion: Constants.expoConfig?.version,
756 ...(bundleId ? { bundleId } : {}),
757 ...(Platform.OS === "ios"
758 ? { apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant) }
759 : {}),
760 ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),
761 notificationsEnabled: pushTokenRegistration.notificationsEnabled,
762 preferences,
763 }),
764 expectedGeneration,
765 );
766 });
767}
768
769function registerDeviceForCurrentUser(): Effect.Effect<
770 void,
771 unknown,
772 ManagedRelay.ManagedRelayClient
773> {
774 return registerDevice(undefined);
775}
776
777function ensurePushTokenListener(): void {
778 if (pushTokenSubscription || !canRegisterPushNotifications()) {
779 return;
780 }
781
782 pushTokenSubscription = Notifications.addPushTokenListener((token) => {
783 if (
784 token.type === Platform.OS &&
785 typeof token.data === "string" &&
786 token.data.trim().length > 0
787 ) {
788 enqueueDeviceRegistration(
789 { observedPushToken: token.data.trim() },
790 "native push token rotation registration failed",
791 );
792 }
793 });
794}
795
796function ensureAppStateListener(): void {
797 if (appStateSubscription || !canRegisterPushNotifications()) {
798 return;
799 }
800
801 appStateSubscription = AppState.addEventListener("change", (state) => {
802 if (state !== "active") {
803 return;
804 }
805 enqueueDeviceRegistration({}, "device registration after app foreground failed");
806 runRegistrationInBackground(
807 refreshActiveLiveActivityRemoteRegistration(),
808 "active live activity reconciliation after app foreground failed",
809 );
810 });
811}
812
813function endLocalLiveActivities(context: string): void {
814 if (!canRegisterRemoteLiveActivities()) {
815 return;
816 }
817 try {
818 for (const activity of getAgentLiveActivities()) {
819 activity.end("immediate").catch((error: unknown) => {
820 logRegistrationError(context, error);
821 });
822 }
823 } catch (error) {
824 logRegistrationError(context, error);
825 }
826}
827
828export function registerAgentAwarenessConnection(connection: SavedRemoteConnection): void {
829 if (!canRegisterPushNotifications()) {
830 return;
831 }
832
833 environmentConnections.set(connection.environmentId, connection);
834 ensurePushTokenListener();
835 ensureAppStateListener();
836 enqueueDeviceRegistration({}, "device registration failed");
837 runRegistrationInBackground(
838 refreshActiveLiveActivityRemoteRegistration(),
839 "active live activity registration after environment connection failed",
840 );
841}
842
843function removeAgentAwarenessConnection(environmentId: EnvironmentId): void {
844 environmentConnections.delete(environmentId);
845}
846
847export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId): void {
848 removeAgentAwarenessConnection(environmentId);
849}
850
851export function refreshAgentAwarenessRegistration(): Effect.Effect<
852 void,
853 never,
854 ManagedRelay.ManagedRelayClient
855> {
856 return registerDeviceForCurrentUser().pipe(
857 Effect.catch((error) =>
858 Effect.sync(() => {
859 if (registrationStatus !== "registered") {
860 setRegistrationStatus("failed");
861 }
862 logRegistrationError("device registration refresh failed", error);
863 }),
864 ),
865 );
866}
867
868export function updateAgentAwarenessRegistrationPreferences(
869 preferencesOverride: Partial<Preferences>,
870): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
871 return registerDevice({ preferencesOverride }).pipe(
872 Effect.tapError((error) =>
873 Effect.sync(() => {
874 if (registrationStatus !== "registered") {
875 setRegistrationStatus("failed");
876 }
877 logRegistrationError("device preference registration refresh failed", error);
878 }),
879 ),
880 );
881}
882
883export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
884 environmentConnections.clear();
885 pushTokenSubscription?.remove();
886 pushTokenSubscription = null;
887 appStateSubscription?.remove();
888 appStateSubscription = null;
889 if (activeLiveActivityRegistrationRetry) {
890 clearTimeout(activeLiveActivityRegistrationRetry);
891 activeLiveActivityRegistrationRetry = null;
892 }
893 relayTokenProvider = null;
894 relayTokenProviderIdentity = null;
895 deviceRegistrationGeneration++;
896 activeDeviceRegistration = null;
897 pendingDeviceRegistration = null;
898 registrationStatus = "unknown";
899 androidDeviceReplayedAt = null;
900 registrationStatusListeners.clear();
901 registeredActivityPushTokens.clear();
902 activityPushTokenLocks.clear();
903}
904
905export function unregisterAgentAwarenessDeviceForCurrentUser(
906 tokenProvider: () => Promise<string | null>,
907): Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> {
908 return Effect.gen(function* () {
909 const deviceId = yield* Effect.tryPromise({
910 try: () => loadAgentAwarenessDeviceId(),
911 catch: (cause) =>
912 new AgentAwarenessOperationError({
913 operation: "load-device-unregistration-identifier",
914 cause,
915 }),
916 });
917 if (!deviceId) {
918 return;
919 }
920 yield* unregisterDeviceWithRelay({ deviceId, tokenProvider });
921 }).pipe(
922 Effect.catch((error) =>
923 Effect.sync(() => {
924 logRegistrationError("device unregistration failed", error);
925 }),
926 ),
927 );
928}
929
930export function registerLiveActivityPushToken(input: {
931 readonly activity: LiveActivity<AgentActivityProps>;
932}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
933 return Effect.gen(function* () {
934 if (!canRegisterRemoteLiveActivities()) {
935 return false;
936 }
937
938 const lock = observeLiveActivityPushTokens(input.activity);
939 return yield* lock.withPermit(
940 Effect.gen(function* () {
941 const activityPushToken = yield* Effect.tryPromise({
942 try: () => input.activity.getPushToken(),
943 catch: (cause) =>
944 new AgentAwarenessOperationError({
945 operation: "read-live-activity-push-token",
946 cause,
947 }),
948 });
949 if (!activityPushToken) {
950 logRegistrationDebug(
951 "live activity push token not available yet; waiting for token event",
952 { connectionCount: environmentConnections.size },
953 );
954 return false;
955 }
956
957 return yield* registerLiveActivityPushTokenValue({ activityPushToken });
958 }),
959 );
960 });
961}
962
963// iOS can replace an activity's push token while it runs, not only deliver a
964// late first one. The relay keeps pushing to the old token until APNs rejects
965// it, so every activity needs a listener that registers each new token.
966function observeLiveActivityPushTokens(
967 activity: LiveActivity<AgentActivityProps>,
968): Semaphore.Semaphore {
969 const activityId = activity.getId();
970 const existing = activityPushTokenLocks.get(activityId);
971 if (existing) return existing;
972 const lock = Semaphore.makeUnsafe(1);
973 activityPushTokenLocks.set(activityId, lock);
974 activity.addPushTokenListener((event) => {
975 if (!event.pushToken) return;
976 logRegistrationDebug("live activity push token event received", {
977 tokenSuffix: event.pushToken.slice(-8),
978 });
979 runRegistrationInBackground(
980 lock.withPermit(registerLiveActivityPushTokenValue({ activityPushToken: event.pushToken })),
981 "live activity token listener registration failed",
982 );
983 });
984 return lock;
985}
986
987function registerLiveActivityPushTokenValue(input: {
988 readonly activityPushToken: string;
989}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
990 return Effect.gen(function* () {
991 const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
992 if (
993 acceptedAt !== undefined &&
994 Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS
995 ) {
996 return true;
997 }
998 const deviceId = yield* Effect.tryPromise({
999 try: () => loadOrCreateAgentAwarenessDeviceId(),
1000 catch: (cause) =>
1001 new AgentAwarenessOperationError({
1002 operation: "load-live-activity-registration-identifier",
1003 cause,
1004 }),
1005 });
1006 const registered = yield* registerLiveActivityWithRelay({
1007 deviceId,
1008 activityPushToken: input.activityPushToken,
1009 });
1010 if (registered) {
1011 registeredActivityPushTokens.set(input.activityPushToken, Date.now());
1012 logRegistrationDebug("live activity push token registered", {
1013 tokenSuffix: input.activityPushToken.slice(-8),
1014 });
1015 }
1016 return registered;
1017 });
1018}
1019
1020function scheduleActiveLiveActivityRegistrationRetry(): void {
1021 if (activeLiveActivityRegistrationRetry || !relayTokenProvider) {
1022 return;
1023 }
1024
1025 activeLiveActivityRegistrationRetry = setTimeout(() => {
1026 activeLiveActivityRegistrationRetry = null;
1027 runRegistrationInBackground(
1028 refreshActiveLiveActivityRemoteRegistration(),
1029 "active live activity token retry failed",
1030 );
1031 }, REMOTE_ACTIVITY_REGISTRATION_RETRY_MS);
1032}
1033
1034export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
1035 void,
1036 never,
1037 ManagedRelay.ManagedRelayClient
1038> {
1039 return Effect.gen(function* () {
1040 if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
1041 return;
1042 }
1043
1044 let activities = yield* Effect.try({
1045 try: () => getAgentLiveActivities(),
1046 catch: (cause) =>
1047 new AgentAwarenessOperationError({
1048 operation: "list-active-live-activities",
1049 cause,
1050 }),
1051 }).pipe(
1052 Effect.catch((error) =>
1053 Effect.sync(() => {
1054 logRegistrationError("active live activity lookup failed", error);
1055 return [] as ReadonlyArray<LiveActivity<AgentActivityProps>>;
1056 }),
1057 ),
1058 );
1059
1060 // The relay tracks exactly one card per device; if concurrent arming ever
1061 // produced extras, end them so only one keeps receiving updates.
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 });
1067 }
1068 activities = activities.slice(0, 1);
1069 }
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 (activities.length === 0) {
1076 const preferences = yield* Effect.tryPromise({
1077 try: () => loadPreferences(),
1078 catch: (cause) =>
1079 new AgentAwarenessOperationError({
1080 operation: "load-live-activity-prime-preferences",
1081 cause,
1082 }),
1083 }).pipe(Effect.orElseSucceed(() => null));
1084 if (preferences?.liveActivitiesEnabled !== false) {
1085 const snapshot = yield* readAgentActivitySnapshot();
1086 // The snapshot request yields; an arm-on-send may have created the
1087 // card in the meantime. Re-check so two cards are never started.
1088 const armedMeanwhile = yield* Effect.try({
1089 try: () => getAgentLiveActivities(),
1090 catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,
1091 }).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));
1092 if (armedMeanwhile.length > 0) {
1093 activities = [...armedMeanwhile];
1094 } else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {
1095 const aggregate = snapshot.aggregate;
1096 const primed = yield* Effect.try({
1097 try: () =>
1098 startAgentLiveActivity(
1099 {
1100 title: aggregate.title,
1101 subtitle: aggregate.subtitle,
1102 activeCount: aggregate.activeCount,
1103 updatedAt: aggregate.updatedAt,
1104 activities: aggregate.activities,
1105 },
1106 liveActivityStaleDate(),
1107 ),
1108 catch: (cause) =>
1109 new AgentAwarenessOperationError({
1110 operation: "prime-live-activity",
1111 cause,
1112 }),
1113 }).pipe(
1114 Effect.catch((error) =>
1115 Effect.sync(() => {
1116 logRegistrationError("live activity priming failed", error);
1117 return null;
1118 }),
1119 ),
1120 );
1121 if (primed) {
1122 logRegistrationDebug("live activity card primed", {
1123 activeCount: aggregate.activeCount,
1124 });
1125 activities = [primed];
1126 }
1127 }
1128 }
1129 }
1130
1131 const registrationResults = yield* Effect.forEach(activities, (activity) =>
1132 registerLiveActivityPushToken({ activity }).pipe(
1133 Effect.map((registered) => !registered),
1134 Effect.catch((error) =>
1135 Effect.sync(() => {
1136 logRegistrationError("active live activity token registration failed", error);
1137 return true;
1138 }),
1139 ),
1140 ),
1141 );
1142
1143 if (registrationResults.some(Boolean)) {
1144 scheduleActiveLiveActivityRegistrationRetry();
1145 }
1146 });
1147}