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