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