@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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