Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

remoteRegistration.ts

1,032 lines33.5 KB

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