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 unregisterAllAgentAwarenessConnections(): void {
832 environmentConnections.clear();
833 pushTokenSubscription?.remove();
834 pushTokenSubscription = null;
835 appStateSubscription?.remove();
836 appStateSubscription = null;
837 if (activeLiveActivityRegistrationRetry) {
838 clearTimeout(activeLiveActivityRegistrationRetry);
839 activeLiveActivityRegistrationRetry = null;
840 }
841}
842
843export function refreshAgentAwarenessRegistration(): Effect.Effect<
844 void,
845 never,
846 ManagedRelay.ManagedRelayClient
847> {
848 return registerDeviceForCurrentUser().pipe(
849 Effect.catch((error) =>
850 Effect.sync(() => {
851 // Same rationale as the queued path: a failed refresh does not undo an
852 // already accepted registration.
853 if (registrationStatus !== "registered") {
854 setRegistrationStatus("failed");
855 }
856 logRegistrationError("device registration refresh failed", error);
857 }),
858 ),
859 );
860}
861
862export function updateAgentAwarenessRegistrationPreferences(
863 preferencesOverride: Partial<Preferences>,
864): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {
865 return registerDevice({ preferencesOverride }).pipe(
866 Effect.tapError((error) =>
867 Effect.sync(() => {
868 if (registrationStatus !== "registered") {
869 setRegistrationStatus("failed");
870 }
871 logRegistrationError("device preference registration refresh failed", error);
872 }),
873 ),
874 );
875}
876
877export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
878 environmentConnections.clear();
879 pushTokenSubscription?.remove();
880 pushTokenSubscription = null;
881 appStateSubscription?.remove();
882 appStateSubscription = null;
883 if (activeLiveActivityRegistrationRetry) {
884 clearTimeout(activeLiveActivityRegistrationRetry);
885 activeLiveActivityRegistrationRetry = null;
886 }
887 relayTokenProvider = null;
888 relayTokenProviderIdentity = null;
889 deviceRegistrationGeneration++;
890 activeDeviceRegistration = null;
891 pendingDeviceRegistration = null;
892 registrationStatus = "unknown";
893 registrationStatusListeners.clear();
894 registeredActivityPushTokens.clear();
895}
896
897export function unregisterAgentAwarenessDeviceForCurrentUser(
898 tokenProvider: () => Promise<string | null>,
899): Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> {
900 return Effect.gen(function* () {
901 const deviceId = yield* Effect.tryPromise({
902 try: () => loadAgentAwarenessDeviceId(),
903 catch: (cause) =>
904 new AgentAwarenessOperationError({
905 operation: "load-device-unregistration-identifier",
906 cause,
907 }),
908 });
909 if (!deviceId) {
910 return;
911 }
912 yield* unregisterDeviceWithRelay({ deviceId, tokenProvider });
913 }).pipe(
914 Effect.catch((error) =>
915 Effect.sync(() => {
916 logRegistrationError("device unregistration failed", error);
917 }),
918 ),
919 );
920}
921
922export function registerLiveActivityPushToken(input: {
923 readonly activity: LiveActivity<AgentActivityProps>;
924}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
925 return Effect.gen(function* () {
926 if (!canRegisterRemoteLiveActivities()) {
927 return false;
928 }
929
930 const activityPushToken = yield* Effect.tryPromise({
931 try: () => input.activity.getPushToken(),
932 catch: (cause) =>
933 new AgentAwarenessOperationError({
934 operation: "read-live-activity-push-token",
935 cause,
936 }),
937 });
938 if (!activityPushToken) {
939 if (activityPushTokenListeners.has(input.activity)) {
940 logRegistrationDebug(
941 "live activity push token not available yet; token listener already registered",
942 {
943 connectionCount: environmentConnections.size,
944 },
945 );
946 return false;
947 }
948
949 logRegistrationDebug(
950 "live activity push token not available yet; listening for token event",
951 {
952 connectionCount: environmentConnections.size,
953 },
954 );
955 activityPushTokenListeners.add(input.activity);
956 input.activity.addPushTokenListener((event) => {
957 if (event.pushToken) {
958 logRegistrationDebug("live activity push token event received", {
959 tokenSuffix: event.pushToken.slice(-8),
960 });
961 runRegistrationInBackground(
962 registerLiveActivityPushTokenValue({
963 activityPushToken: event.pushToken,
964 }),
965 "live activity token listener registration failed",
966 );
967 }
968 });
969 return false;
970 }
971
972 return yield* registerLiveActivityPushTokenValue({
973 activityPushToken,
974 });
975 });
976}
977
978function registerLiveActivityPushTokenValue(input: {
979 readonly activityPushToken: string;
980}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
981 return Effect.gen(function* () {
982 const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
983 if (
984 acceptedAt !== undefined &&
985 Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS
986 ) {
987 return true;
988 }
989 const deviceId = yield* Effect.tryPromise({
990 try: () => loadOrCreateAgentAwarenessDeviceId(),
991 catch: (cause) =>
992 new AgentAwarenessOperationError({
993 operation: "load-live-activity-registration-identifier",
994 cause,
995 }),
996 });
997 const registered = yield* registerLiveActivityWithRelay({
998 deviceId,
999 activityPushToken: input.activityPushToken,
1000 });
1001 if (registered) {
1002 registeredActivityPushTokens.set(input.activityPushToken, Date.now());
1003 logRegistrationDebug("live activity push token registered", {
1004 tokenSuffix: input.activityPushToken.slice(-8),
1005 });
1006 }
1007 return registered;
1008 });
1009}
1010
1011function scheduleActiveLiveActivityRegistrationRetry(): void {
1012 if (activeLiveActivityRegistrationRetry || !relayTokenProvider) {
1013 return;
1014 }
1015
1016 activeLiveActivityRegistrationRetry = setTimeout(() => {
1017 activeLiveActivityRegistrationRetry = null;
1018 runRegistrationInBackground(
1019 refreshActiveLiveActivityRemoteRegistration(),
1020 "active live activity token retry failed",
1021 );
1022 }, REMOTE_ACTIVITY_REGISTRATION_RETRY_MS);
1023}
1024
1025export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
1026 void,
1027 never,
1028 ManagedRelay.ManagedRelayClient
1029> {
1030 return Effect.gen(function* () {
1031 if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
1032 return;
1033 }
1034
1035 let activities = yield* Effect.try({
1036 try: () => AgentActivity.getInstances(),
1037 catch: (cause) =>
1038 new AgentAwarenessOperationError({
1039 operation: "list-active-live-activities",
1040 cause,
1041 }),
1042 }).pipe(
1043 Effect.catch((error) =>
1044 Effect.sync(() => {
1045 logRegistrationError("active live activity lookup failed", error);
1046 return [] as ReadonlyArray<LiveActivity<AgentActivityProps>>;
1047 }),
1048 ),
1049 );
1050
1051 // The relay tracks exactly one card per device; if concurrent arming ever
1052 // produced extras, end them so only one keeps receiving updates.
1053 if (activities.length > 1) {
1054 for (const extra of activities.slice(1)) {
1055 extra.end("immediate").catch((error: unknown) => {
1056 logRegistrationError("duplicate live activity cleanup failed", error);
1057 });
1058 }
1059 activities = activities.slice(0, 1);
1060 }
1061
1062 // Activities are only ever created here, in the foreground, where the
1063 // update token can be observed and registered immediately — the relay
1064 // never remote-starts one (background push-to-start wakes proved too
1065 // unreliable to hand the token over). Arming is conditional: the relay is
1066 // asked what the card would show first, so an idle open never creates an
1067 // empty lock-screen card, and an armed card is born with the real
1068 // aggregate instead of a placeholder.
1069 if (activities.length === 0) {
1070 const preferences = yield* Effect.tryPromise({
1071 try: () => loadPreferences(),
1072 catch: (cause) =>
1073 new AgentAwarenessOperationError({
1074 operation: "load-live-activity-prime-preferences",
1075 cause,
1076 }),
1077 }).pipe(Effect.orElseSucceed(() => null));
1078 // The toggle defaults to on: an unset preference (fresh install) must
1079 // prime, so only an explicit false blocks it.
1080 if (preferences?.liveActivitiesEnabled !== false) {
1081 const snapshot = yield* readAgentActivitySnapshot();
1082 // The snapshot request yields; an arm-on-send may have created the
1083 // card in the meantime. Re-check so two cards are never started.
1084 const armedMeanwhile = yield* Effect.try({
1085 try: () => AgentActivity.getInstances(),
1086 catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,
1087 }).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));
1088 if (armedMeanwhile.length > 0) {
1089 activities = [...armedMeanwhile];
1090 } else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {
1091 const aggregate = snapshot.aggregate;
1092 const primed = yield* Effect.try({
1093 try: () =>
1094 AgentActivity.start({
1095 title: aggregate.title,
1096 subtitle: aggregate.subtitle,
1097 activeCount: aggregate.activeCount,
1098 updatedAt: aggregate.updatedAt,
1099 activities: aggregate.activities,
1100 }),
1101 catch: (cause) =>
1102 new AgentAwarenessOperationError({
1103 operation: "prime-live-activity",
1104 cause,
1105 }),
1106 }).pipe(
1107 Effect.catch((error) =>
1108 Effect.sync(() => {
1109 logRegistrationError("live activity priming failed", error);
1110 return null;
1111 }),
1112 ),
1113 );
1114 if (primed) {
1115 logRegistrationDebug("live activity card primed", {
1116 activeCount: aggregate.activeCount,
1117 });
1118 activities = [primed];
1119 }
1120 }
1121 }
1122 }
1123
1124 const registrationResults = yield* Effect.forEach(activities, (activity) =>
1125 registerLiveActivityPushToken({ activity }).pipe(
1126 Effect.map((registered) => !registered),
1127 Effect.catch((error) =>
1128 Effect.sync(() => {
1129 logRegistrationError("active live activity token registration failed", error);
1130 return true;
1131 }),
1132 ),
1133 ),
1134 );
1135
1136 if (registrationResults.some(Boolean)) {
1137 scheduleActiveLiveActivityRegistrationRetry();
1138 }
1139 });
1140}