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