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

remoteRegistration.ts

1,118 lines38.2 KB

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