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