Open History to see the last commit
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 { appAtomRegistry } from "../../state/atom-registry";
24import { environmentServerConfigsAtom } from "../../state/server";
25import type { Preferences } from "../../persistence/mobile-preferences";
26import {
27 clearAgentAwarenessRegistrationRecord,
28 loadAgentAwarenessDeviceId,
29 loadAgentAwarenessRegistrationRecord,
30 loadOrCreateAgentAwarenessDeviceId,
31 loadPreferences,
32 saveAgentAwarenessRegistrationRecord,
33} from "../../persistence/imperative";
34import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";
35import { resolveCloudPublicConfig } from "../cloud/publicConfig";
36import { supportsAgentAwarenessPush } from "./capabilities";
37import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
38
39const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
40
41const AgentAwarenessOperation = Schema.Literals([
42 "read-notification-permissions",
43 "read-native-push-token",
44 "read-device-registration-relay-token",
45 "read-device-unregistration-relay-token",
46 "read-live-activity-registration-relay-token",
47 "load-device-registration-identifier",
48 "load-device-registration-preferences",
49 "load-device-unregistration-identifier",
50 "read-live-activity-push-token",
51 "load-live-activity-registration-identifier",
52 "list-active-live-activities",
53 "load-live-activity-prime-preferences",
54 "prime-live-activity",
55]);
56
57export class AgentAwarenessOperationError extends Schema.TaggedError<AgentAwarenessOperationError>()(
58 "AgentAwarenessOperationError",
59 {
60 operation: AgentAwarenessOperation,
61 cause: Schema.Defect(),
62 },
63) {
64 override get message(): string {
65 return `Agent awareness operation ${this.operation} failed.`;
66 }
67}
68
69const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
70const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
71// Activity tokens the relay recently accepted, by acceptance time. The refresh
72// runs on sign-in, every app foreground, and every environment-connection
73// update, which arrive in bursts and spammed identical registrations. But the
74// registration is not a pure no-op: the relay replays the current aggregate to
75// this device on every accepted registration, and that replay is the
76// foreground reconciliation that repairs drifted or orphaned activities. So
77// dedupe only within a short window — bursts collapse to one request, while a
78// foreground after real time away still triggers a replay. Cleared on
79// sign-out/identity change alongside the device registration state.
80const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000;
81const registeredActivityPushTokens = new Map<string, number>();
82let pushTokenSubscription: { remove: () => void } | null = null;
83let appStateSubscription: { remove: () => void } | null = null;
84
85// Whether the relay has actually accepted this device's registration. The
86// notification/Live Activity settings toggles must reflect this rather than
87// only local iOS permission or saved preferences: if the registration request
88// never succeeded, the device cannot receive anything, so the switches must
89// not read as enabled.
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 }
102}
103
104export function getAgentAwarenessRegistrationStatus(): AgentAwarenessRegistrationStatus {
105 return registrationStatus;
106}
107
108export function subscribeAgentAwarenessRegistrationStatus(listener: () => void): () => void {
109 registrationStatusListeners.add(listener);
110 return () => {
111 registrationStatusListeners.delete(listener);
112 };
113}
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;
129}
130
131interface RegisterDeviceInput extends DeviceRegistrationInput {
132 readonly preferencesOverride?: Partial<Preferences>;
133}
134
135export function mergeAgentAwarenessRegistrationPreferences(
136 stored: Preferences,
137 override: Partial<Preferences> | undefined,
138): Preferences {
139 return { ...stored, ...override };
140}
141
142function readRelayConfig(): { readonly url: string } | null {
143 const relayUrl = resolveCloudPublicConfig().relay.url;
144 if (!relayUrl) {
145 logRegistrationDebug("relay registration skipped; relay config missing");
146 return null;
147 }
148
149 return { url: relayUrl };
150}
151
152function canRegisterRemoteLiveActivities(): boolean {
153 return Platform.OS === "ios";
154}
155
156export function shouldRegisterAgentAwarenessDeviceForProvider(
157 previousIdentity: string | null,
158 identity: string | undefined,
159): boolean {
160 return identity === undefined || identity !== previousIdentity;
161}
162
163export function setAgentAwarenessRelayTokenProvider(
164 provider: (() => Promise<string | null>) | null,
165 identity?: string,
166): void {
167 const isExistingIdentity =
168 provider !== null &&
169 !shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity);
170 if (!isExistingIdentity) {
171 deviceRegistrationGeneration++;
172 activeDeviceRegistration = null;
173 pendingDeviceRegistration = null;
174 registeredActivityPushTokens.clear();
175 }
176 relayTokenProvider = provider;
177 relayTokenProviderIdentity = provider ? (identity ?? null) : null;
178 if (!provider) {
179 pushTokenSubscription?.remove();
180 pushTokenSubscription = null;
181 appStateSubscription?.remove();
182 appStateSubscription = null;
183 if (activeLiveActivityRegistrationRetry) {
184 clearTimeout(activeLiveActivityRegistrationRetry);
185 activeLiveActivityRegistrationRetry = null;
186 }
187 // Without a signed-in user the relay can no longer update or end these
188 // activities, so they would sit orphaned on the lock screen.
189 endLocalLiveActivities("live activity cleanup after cloud sign-out failed");
190 setRegistrationStatus("unknown");
191 // Sign-out is the only thing that invalidates a stored registration, so the
192 // next sign-in re-registers.
193 void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => {
194 logRegistrationError("clear registration record on sign-out failed", error);
195 });
196 return;
197 }
198 ensurePushTokenListener();
199 ensureAppStateListener();
200 runRegistrationInBackground(
201 refreshActiveLiveActivityRemoteRegistration(),
202 "active live activity registration after cloud sign-in failed",
203 );
204 if (isExistingIdentity) {
205 // Same account re-activating (e.g. Clerk token refresh) normally needs no
206 // re-registration — but if the previous attempt never succeeded, this is
207 // the only trigger that will retry it before the next cold start.
208 if (registrationStatus !== "registered") {
209 enqueueDeviceRegistration({}, "device registration retry after cloud session refresh failed");
210 }
211 return;
212 }
213 enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");
214}
215
216// Detach the provider and native listeners without the destructive sign-out
217// cleanup. For provider teardown while the user is still signed in (e.g. the
218// auth bridge unmounting/remounting), ending lock-screen activities and wiping
219// the persisted registration would be wrong — the relay still holds a valid
220// registration and the next mount reuses it.
221export function releaseAgentAwarenessRelayTokenProvider(): void {
222 relayTokenProvider = null;
223 relayTokenProviderIdentity = null;
224 pushTokenSubscription?.remove();
225 pushTokenSubscription = null;
226 appStateSubscription?.remove();
227 appStateSubscription = null;
228 if (activeLiveActivityRegistrationRetry) {
229 clearTimeout(activeLiveActivityRegistrationRetry);
230 activeLiveActivityRegistrationRetry = null;
231 }
232}
233
234function iosMajorVersion(): number {
235 const version = Platform.Version;
236 if (typeof version === "number") {
237 return Math.floor(version);
238 }
239 const major = Number.parseInt(version.split(".")[0] ?? "", 10);
240 return Number.isFinite(major) ? major : 18;
241}
242
243function nativePushTokenRegistration(observedPushToken?: string) {
244 return Effect.gen(function* () {
245 if (!canRegisterRemoteLiveActivities() || !supportsAgentAwarenessPush()) {
246 return { notificationsEnabled: false, pushToken: null };
247 }
248 if (observedPushToken) {
249 return { notificationsEnabled: true, pushToken: observedPushToken };
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 const token = yield* Effect.tryPromise({
263 try: () => Notifications.getDevicePushTokenAsync(),
264 catch: (cause) =>
265 new AgentAwarenessOperationError({
266 operation: "read-native-push-token",
267 cause,
268 }),
269 }).pipe(
270 Effect.tapError((error) =>
271 Effect.sync(() => {
272 logRegistrationError("native APNs token lookup failed", error);
273 }),
274 ),
275 Effect.orElseSucceed(() => null),
276 );
277 const pushToken =
278 token?.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0
279 ? token.data.trim()
280 : null;
281 return { notificationsEnabled: pushToken !== null, pushToken };
282 });
283}
284
285const relayToken = (
286 operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",
287) =>
288 Effect.gen(function* () {
289 const provider = relayTokenProvider;
290 if (!provider) {
291 return null;
292 }
293 return yield* Effect.tryPromise({
294 try: provider,
295 catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),
296 });
297 });
298
299// Stable fingerprint of everything the relay stores for this device. When it
300// matches the last accepted registration for the same account, re-registering
301// is a no-op, so a launch that changed nothing skips the request entirely.
302function registrationSignature(body: RelayDeviceRegistrationRequest): string {
303 return [
304 body.deviceId,
305 body.pushToken ?? "",
306 body.bundleId ?? "",
307 body.apsEnvironment ?? "",
308 body.appVersion ?? "",
309 body.label,
310 body.iosMajorVersion,
311 body.preferences.notificationsEnabled,
312 body.preferences.liveActivitiesEnabled,
313 body.preferences.notifyOnApproval,
314 body.preferences.notifyOnInput,
315 body.preferences.notifyOnCompletion,
316 body.preferences.notifyOnFailure,
317 ].join("|");
318}
319
320function registerDeviceWithRelay(
321 body: RelayDeviceRegistrationRequest,
322 expectedGeneration: number,
323): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
324 return Effect.gen(function* () {
325 if (expectedGeneration !== deviceRegistrationGeneration) {
326 logRegistrationDebug("device registration cancelled before relay request", {
327 expectedGeneration,
328 currentGeneration: deviceRegistrationGeneration,
329 });
330 return;
331 }
332 const relayConfig = readRelayConfig();
333 if (!relayConfig) {
334 // Nothing is in flight and nothing can succeed until configuration
335 // appears; "pending" would otherwise stick forever.
336 setRegistrationStatus("unknown");
337 return;
338 }
339 const token = yield* relayToken("read-device-registration-relay-token");
340 if (expectedGeneration !== deviceRegistrationGeneration) {
341 logRegistrationDebug("device registration cancelled after auth lookup", {
342 expectedGeneration,
343 currentGeneration: deviceRegistrationGeneration,
344 });
345 return;
346 }
347 if (!token) {
348 logRegistrationDebug("relay device registration skipped; user is not signed in");
349 setRegistrationStatus("unknown");
350 return;
351 }
352
353 // Skip the request when this account already registered an identical
354 // payload; the relay upsert would be a no-op. The record is only cleared on
355 // sign-out, so a device stays registered across launches without re-hitting
356 // the relay every time the app opens.
357 const identity = relayTokenProviderIdentity ?? "";
358 const persisted = yield* Effect.tryPromise({
359 try: () => loadAgentAwarenessRegistrationRecord(),
360 catch: (cause) => cause,
361 }).pipe(Effect.orElseSucceed(() => null));
362 if (expectedGeneration !== deviceRegistrationGeneration) {
363 // Signed out while the record loaded — do not resurrect the cleared
364 // record or report the previous account's registration as current.
365 logRegistrationDebug("device registration cancelled after record lookup", {
366 expectedGeneration,
367 currentGeneration: deviceRegistrationGeneration,
368 });
369 return;
370 }
371 const payload = body;
372 // The relay URL participates so pointing the app at a different relay
373 // invalidates the record and re-registers there.
374 const signature = `${relayConfig.url}|${registrationSignature(payload)}`;
375 if (persisted && persisted.identity === identity && persisted.signature === signature) {
376 setRegistrationStatus("registered");
377 logRegistrationDebug("relay device registration skipped; already registered for account", {
378 expectedGeneration,
379 });
380 return;
381 }
382
383 const client = yield* ManagedRelay.ManagedRelayClient;
384 logRegistrationDebug("relay device registration request started", {
385 expectedGeneration,
386 });
387 yield* client.registerDevice({
388 clerkToken: token,
389 payload,
390 });
391 if (expectedGeneration !== deviceRegistrationGeneration) {
392 // Signed out while the request was in flight: the sign-out path already
393 // reset the status and cleared the record for the next account, so a
394 // stale success must not overwrite either.
395 logRegistrationDebug("device registration completed after sign-out; result discarded", {
396 expectedGeneration,
397 currentGeneration: deviceRegistrationGeneration,
398 });
399 return;
400 }
401 setRegistrationStatus("registered");
402 yield* Effect.promise(() =>
403 saveAgentAwarenessRegistrationRecord({
404 identity,
405 signature,
406 }).catch((error: unknown) => {
407 logRegistrationError("persist registration record failed", error);
408 }),
409 );
410 logRegistrationDebug("relay device registration request completed", {
411 expectedGeneration,
412 });
413 });
414}
415
416function unregisterDeviceWithRelay(input: {
417 readonly deviceId: string;
418 readonly tokenProvider: () => Promise<string | null>;
419}): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
420 return Effect.gen(function* () {
421 if (!readRelayConfig()) return;
422 const token = yield* Effect.tryPromise({
423 try: input.tokenProvider,
424 catch: (cause) =>
425 new AgentAwarenessOperationError({
426 operation: "read-device-unregistration-relay-token",
427 cause,
428 }),
429 });
430 if (!token) {
431 logRegistrationDebug("relay device unregistration skipped; user is not signed in");
432 return;
433 }
434
435 const client = yield* ManagedRelay.ManagedRelayClient;
436 yield* client.unregisterDevice({
437 clerkToken: token,
438 deviceId: input.deviceId,
439 });
440 });
441}
442
443// The environment descriptor advertises whether agent-activity publishes
444// currently leave that server (`capabilities.agentActivityPublishing`). Only
445// an explicit false skips the seed card: older servers omit the capability
446// but may still publish.
447function environmentPublishesAgentActivity(environmentId: EnvironmentId): boolean {
448 return (
449 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
450 .agentActivityPublishing !== false
451 );
452}
453
454// Arms the lock-screen card the moment the user starts agent work from this
455// phone, while the app is still foregrounded and the fresh activity's token
456// can be registered immediately. The seeded row is a best-effort placeholder;
457// the relay's registration replay repaints it with the authoritative
458// aggregate within seconds. No-ops when a card is already armed, and skips
459// environments that report publishing disabled — the seed would sit on
460// "Connecting" forever with no update ever arriving to repaint or end it.
461export function armAgentAwarenessLiveActivityForLocalWork(input: {
462 readonly environmentId: EnvironmentId;
463 readonly threadTitle: string;
464 readonly projectTitle: string;
465}): void {
466 if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
467 return;
468 }
469 if (!environmentPublishesAgentActivity(input.environmentId)) {
470 logRegistrationDebug("live activity arming skipped; environment does not publish", {
471 environmentId: input.environmentId,
472 });
473 return;
474 }
475 void loadPreferences()
476 .catch(() => null)
477 .then((preferences) => {
478 if (preferences?.liveActivitiesEnabled === false) {
479 return;
480 }
481 armAgentAwarenessLiveActivityForLocalWorkNow(input);
482 });
483}
484
485function armAgentAwarenessLiveActivityForLocalWorkNow(input: {
486 readonly threadTitle: string;
487 readonly projectTitle: string;
488}): void {
489 try {
490 if (AgentActivity.getInstances().length > 0) {
491 return;
492 }
493 const nowIso = new Date(Date.now()).toISOString();
494 const activity = AgentActivity.start({
495 title: "T3 Code",
496 subtitle: "Agent work in progress",
497 activeCount: 1,
498 updatedAt: nowIso,
499 activities: [
500 {
501 environmentId: "",
502 threadId: "",
503 projectTitle: input.projectTitle,
504 threadTitle: input.threadTitle,
505 modelTitle: "",
506 phase: "starting",
507 status: "Connecting",
508 updatedAt: nowIso,
509 deepLink: "/",
510 },
511 ],
512 });
513 logRegistrationDebug("live activity card armed for local work", {
514 threadTitle: input.threadTitle,
515 });
516 runRegistrationInBackground(
517 registerLiveActivityPushToken({ activity }).pipe(Effect.asVoid),
518 "live activity arming after local task start failed",
519 );
520 } catch (error) {
521 logRegistrationError("live activity arming failed", error);
522 }
523}
524
525function readAgentActivitySnapshot(): Effect.Effect<
526 RelayAgentActivitySnapshotResponse | null,
527 never,
528 ManagedRelay.ManagedRelayClient
529> {
530 return Effect.gen(function* () {
531 if (!readRelayConfig()) return null;
532 const token = yield* relayToken("read-live-activity-registration-relay-token");
533 if (!token) {
534 return null;
535 }
536 const client = yield* ManagedRelay.ManagedRelayClient;
537 return yield* client.getAgentActivitySnapshot({ clerkToken: token });
538 }).pipe(
539 Effect.catch((error) =>
540 Effect.sync(() => {
541 logRegistrationError("agent activity snapshot read failed", error);
542 return null;
543 }),
544 ),
545 );
546}
547
548function registerLiveActivityWithRelay(
549 body: RelayLiveActivityRegistrationRequest,
550): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
551 return Effect.gen(function* () {
552 if (!readRelayConfig()) return false;
553 const token = yield* relayToken("read-live-activity-registration-relay-token");
554 if (!token) {
555 logRegistrationDebug("relay live activity registration skipped; user is not signed in");
556 return false;
557 }
558
559 const client = yield* ManagedRelay.ManagedRelayClient;
560 yield* client.registerLiveActivity({
561 clerkToken: token,
562 payload: body,
563 });
564 return true;
565 });
566}
567
568function logRegistrationError(context: string, error: unknown): void {
569 if (!__DEV__) {
570 return;
571 }
572 console.warn(`[agent-awareness] ${context}`, {
573 message: error instanceof Error ? error.message : String(error),
574 traceId: findErrorTraceId(error),
575 error,
576 });
577}
578
579function logRegistrationDebug(context: string, details?: unknown): void {
580 if (!__DEV__) {
581 return;
582 }
583 console.log(`[agent-awareness] ${context}`, details ?? "");
584}
585
586function runRegistrationInBackground(
587 operation: Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
588 context: string,
589): void {
590 void (async () => {
591 const result = await settleAsyncResult(() => runtime.runPromiseExit(operation));
592 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
593 logRegistrationError(context, squashAtomCommandFailure(result));
594 }
595 })();
596}
597
598function mergeDeviceRegistrationInput(
599 current: DeviceRegistrationInput,
600 next: DeviceRegistrationInput,
601): DeviceRegistrationInput {
602 const observedPushToken = next.observedPushToken ?? current.observedPushToken;
603 return observedPushToken ? { observedPushToken } : {};
604}
605
606function registrationAddsInformation(
607 current: DeviceRegistrationInput,
608 next: DeviceRegistrationInput,
609): boolean {
610 return (
611 next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken
612 );
613}
614
615function startPendingDeviceRegistration(): void {
616 if (activeDeviceRegistration || !pendingDeviceRegistration) {
617 return;
618 }
619
620 const next = pendingDeviceRegistration;
621 pendingDeviceRegistration = null;
622 const generation = deviceRegistrationGeneration;
623 logRegistrationDebug("device registration started", {
624 generation,
625 hasObservedPushToken: next.input.observedPushToken !== undefined,
626 });
627 if (registrationStatus !== "registered") {
628 setRegistrationStatus("pending");
629 }
630 const registration = {
631 input: next.input,
632 operation: Promise.resolve(),
633 };
634 activeDeviceRegistration = registration;
635 registration.operation = (async () => {
636 const result = await settleAsyncResult(() =>
637 runtime.runPromiseExit(registerDevice(next.input, generation)),
638 );
639 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
640 // A transient failure on a later refresh (e.g. token rotation) leaves
641 // the prior accepted registration intact on the relay, so an already
642 // registered device stays "registered" rather than flipping the
643 // settings toggles off.
644 if (registrationStatus !== "registered") {
645 setRegistrationStatus("failed");
646 }
647 logRegistrationError(next.context, squashAtomCommandFailure(result));
648 }
649 logRegistrationDebug("device registration finished", { generation });
650 if (activeDeviceRegistration === registration) {
651 activeDeviceRegistration = null;
652 }
653 startPendingDeviceRegistration();
654 })();
655}
656
657function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: string): void {
658 if (
659 activeDeviceRegistration &&
660 !registrationAddsInformation(activeDeviceRegistration.input, input)
661 ) {
662 logRegistrationDebug("device registration coalesced with active request", {
663 generation: deviceRegistrationGeneration,
664 });
665 return;
666 }
667
668 logRegistrationDebug("device registration enqueued", {
669 generation: deviceRegistrationGeneration,
670 hasActiveRegistration: activeDeviceRegistration !== null,
671 hasPendingRegistration: pendingDeviceRegistration !== null,
672 });
673 pendingDeviceRegistration = pendingDeviceRegistration
674 ? {
675 input: mergeDeviceRegistrationInput(pendingDeviceRegistration.input, input),
676 context,
677 }
678 : { input, context };
679 startPendingDeviceRegistration();
680}
681
682function registerDevice(
683 input: RegisterDeviceInput = {},
684 expectedGeneration = deviceRegistrationGeneration,
685): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
686 return Effect.gen(function* () {
687 if (!canRegisterRemoteLiveActivities()) {
688 logRegistrationDebug("device registration skipped; platform does not support it");
689 return;
690 }
691
692 logRegistrationDebug("device registration loading local state", { expectedGeneration });
693 const [deviceId, storedPreferences] = yield* Effect.all([
694 Effect.tryPromise({
695 try: () => loadOrCreateAgentAwarenessDeviceId(),
696 catch: (cause) =>
697 new AgentAwarenessOperationError({
698 operation: "load-device-registration-identifier",
699 cause,
700 }),
701 }),
702 Effect.tryPromise({
703 try: () => loadPreferences(),
704 catch: (cause) =>
705 new AgentAwarenessOperationError({
706 operation: "load-device-registration-preferences",
707 cause,
708 }),
709 }),
710 ]);
711 const preferences = mergeAgentAwarenessRegistrationPreferences(
712 storedPreferences,
713 input.preferencesOverride,
714 );
715 const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
716 logRegistrationDebug("device registration local state ready", {
717 expectedGeneration,
718 notificationsEnabled: pushTokenRegistration.notificationsEnabled,
719 });
720 const bundleId = Constants.expoConfig?.ios?.bundleIdentifier?.trim();
721 yield* registerDeviceWithRelay(
722 makeRelayDeviceRegistrationRequest({
723 deviceId,
724 label: Constants.deviceName?.trim() || "iOS device",
725 iosMajorVersion: iosMajorVersion(),
726 appVersion: Constants.expoConfig?.version,
727 ...(bundleId ? { bundleId } : {}),
728 apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant),
729 ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),
730 notificationsEnabled: pushTokenRegistration.notificationsEnabled,
731 preferences,
732 }),
733 expectedGeneration,
734 );
735 });
736}
737
738function registerDeviceForCurrentUser(): Effect.Effect<
739 void,
740 unknown,
741 ManagedRelay.ManagedRelayClient
742> {
743 return registerDevice(undefined);
744}
745
746function ensurePushTokenListener(): void {
747 if (pushTokenSubscription || !canRegisterRemoteLiveActivities()) {
748 return;
749 }
750
751 pushTokenSubscription = Notifications.addPushTokenListener((token) => {
752 if (token.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0) {
753 enqueueDeviceRegistration(
754 { observedPushToken: token.data.trim() },
755 "native APNs token rotation registration failed",
756 );
757 }
758 });
759}
760
761// Re-registering activity tokens on foreground makes the relay replay the
762// current aggregate to this device, which updates content that drifted while
763// pushes could not be delivered and ends orphaned activities whose end push
764// never arrived. (Deduped by ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS: rapid
765// foreground/sign-in bursts collapse to one registration, but returning after
766// real time away still replays.)
767function ensureAppStateListener(): void {
768 if (appStateSubscription || !canRegisterRemoteLiveActivities()) {
769 return;
770 }
771
772 appStateSubscription = AppState.addEventListener("change", (state) => {
773 if (state !== "active") {
774 return;
775 }
776 runRegistrationInBackground(
777 refreshActiveLiveActivityRemoteRegistration(),
778 "active live activity reconciliation after app foreground failed",
779 );
780 });
781}
782
783function endLocalLiveActivities(context: string): void {
784 if (!canRegisterRemoteLiveActivities()) {
785 return;
786 }
787 try {
788 for (const activity of AgentActivity.getInstances()) {
789 activity.end("immediate").catch((error: unknown) => {
790 logRegistrationError(context, error);
791 });
792 }
793 } catch (error) {
794 logRegistrationError(context, error);
795 }
796}
797
798export function registerAgentAwarenessConnection(connection: SavedRemoteConnection): void {
799 if (!canRegisterRemoteLiveActivities()) {
800 return;
801 }
802
803 environmentConnections.set(connection.environmentId, connection);
804 ensurePushTokenListener();
805 ensureAppStateListener();
806 enqueueDeviceRegistration({}, "device registration failed");
807 runRegistrationInBackground(
808 refreshActiveLiveActivityRemoteRegistration(),
809 "active live activity registration after environment connection failed",
810 );
811}
812
813function removeAgentAwarenessConnection(environmentId: EnvironmentId): void {
814 environmentConnections.delete(environmentId);
815}
816
817export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId): void {
818 removeAgentAwarenessConnection(environmentId);
819}
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 );
838}
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 );
853}
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();
873}
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 );
898}
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 });
954}
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 });
987}
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);
1001}
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;
1011 }
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 });
1036 }
1037 activities = activities.slice(0, 1);
1038 }
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];
1097 }
1098 }
1099 }
1100 }
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();
1116 }
1117 });
1118}