@devries-cameron20 / t3code-1 / commits / 46b14a6808
Fork 0

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

fix(mobile): device registration and Live Activity updates stay in Effect (#38913)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

Julius Marminge committed Nov 19, 2026 at 12:11 UTC 46b14a6808f6d130725cc5cb814c6b1b68f080c3
5 files changed +275 -155
apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts
+49 -1
@@ -3,10 +3,16 @@ import { describe, expect, it } from "@effect/vitest";
3 import * as Exit from "effect/Exit";
4 import * as Option from "effect/Option";
5 import * as Effect from "effect/Effect";
6 +import * as Layer from "effect/Layer";
7 import type { EnvironmentId } from "@t3tools/contracts";
8 import { ManagedRelay } from "@t3tools/client-runtime/relay";
9
10 import type { SavedRemoteConnection } from "../../lib/connection";
11 +import {
12 + MobilePreferencesSaveError,
13 + MobilePreferencesStore,
14 +} from "../../persistence/mobile-preferences";
15 +import { MobileStorage } from "../../persistence/mobile-storage";
16 import { CloudEnvironmentLinkError } from "../cloud/linkEnvironment";
17 import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences";
18 import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";
@@ -48,6 +54,10 @@ const linkEnvironment = vi.fn<
54 ) => Effect.Effect<void, CloudEnvironmentLinkError>
55 >(() => Effect.void);
56
57 +const saveLocalPreference = vi.fn<
58 + (enabled: boolean) => Effect.Effect<void, MobilePreferencesSaveError>
59 +>(() => Effect.void);
60 +
61 const connection: SavedRemoteConnection = {
62 environmentId: "env-1" as EnvironmentId,
63 environmentLabel: "Desktop",
@@ -58,7 +68,13 @@ const connection: SavedRemoteConnection = {
68 bearerToken: "local-bearer",
69 };
70
61 -const withRelayClient = Effect.provideService(ManagedRelay.ManagedRelayClient, null as never);
71 +const withRelayClient = Effect.provide(
72 + Layer.mergeAll(
73 + Layer.succeed(ManagedRelay.ManagedRelayClient, null as never),
74 + Layer.succeed(MobileStorage, null as never),
75 + Layer.succeed(MobilePreferencesStore, null as never),
76 + ),
77 +);
78
79 describe("liveActivityPreferences", () => {
80 beforeEach(() => {
@@ -76,6 +92,7 @@ describe("liveActivityPreferences", () => {
92 setLiveActivityUpdatesEnabled({
93 updateEnvironment,
94 linkEnvironment,
95 + saveLocalPreference,
96 enabled: false,
97 previousEnabled: true,
98 clerkToken: "clerk-token",
@@ -103,6 +120,33 @@ describe("liveActivityPreferences", () => {
120 }).pipe(withRelayClient);
121 });
122
123 + it.effect("restores the device preference when the device cannot save the setting", () => {
124 + saveLocalPreference.mockImplementationOnce(() =>
125 + Effect.fail(new MobilePreferencesSaveError({ cause: new Error("storage full") })),
126 + );
127 +
128 + return Effect.gen(function* () {
129 + const exit = yield* Effect.exit(
130 + setLiveActivityUpdatesEnabled({
131 + updateEnvironment,
132 + linkEnvironment,
133 + saveLocalPreference,
134 + enabled: true,
135 + previousEnabled: false,
136 + clerkToken: "clerk-token",
137 + connections: [connection],
138 + canConfigureEnvironment: () => false,
139 + canUpdateEnvironment: () => true,
140 + }),
141 + );
142 +
143 + expect(Exit.isFailure(exit)).toBe(true);
144 + expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenLastCalledWith({
145 + liveActivitiesEnabled: false,
146 + });
147 + }).pipe(withRelayClient);
148 + });
149 +
150 it.effect("reports a relay preference committed before environment configuration fails", () => {
151 const failure = new CloudEnvironmentLinkError({
152 message: "environment configuration failed",
@@ -116,6 +160,7 @@ describe("liveActivityPreferences", () => {
160 setLiveActivityUpdatesEnabled({
161 updateEnvironment,
162 linkEnvironment,
163 + saveLocalPreference,
164 enabled: true,
165 previousEnabled: false,
166 clerkToken: "clerk-token",
@@ -156,6 +201,7 @@ describe("liveActivityPreferences", () => {
201 yield* setLiveActivityUpdatesEnabled({
202 updateEnvironment,
203 linkEnvironment,
204 + saveLocalPreference,
205 enabled: true,
206 previousEnabled: false,
207 clerkToken: "clerk-token",
@@ -185,6 +231,7 @@ describe("liveActivityPreferences", () => {
231 const partial = yield* setLiveActivityUpdatesEnabled({
232 updateEnvironment,
233 linkEnvironment,
234 + saveLocalPreference,
235 enabled: false,
236 previousEnabled: true,
237 clerkToken: "clerk-token",
@@ -209,6 +256,7 @@ describe("liveActivityPreferences", () => {
256 yield* setLiveActivityUpdatesEnabled({
257 updateEnvironment,
258 linkEnvironment,
259 + saveLocalPreference,
260 enabled: false,
261 previousEnabled: true,
262 clerkToken: "clerk-token",
apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts
+84 -81
@@ -15,92 +15,95 @@ export class LiveActivityEnvironmentUpdateError extends Schema.TaggedError<LiveA
15 },
16 ) {}
17
18 -export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEnabled")(
19 - function* (input: {
20 - readonly enabled: boolean;
21 - readonly previousEnabled: boolean;
22 - readonly clerkToken: string | null;
23 - readonly connections: ReadonlyArray<SavedRemoteConnection>;
24 - readonly updateEnvironment: (
25 - environmentId: EnvironmentId,
26 - enabled: boolean,
27 - ) => Effect.Effect<
28 - "updated" | "unlinked" | "unsupported" | "disconnected",
29 - CloudEnvironmentLinkError
30 - >;
31 - readonly linkEnvironment: (
32 - environmentId: EnvironmentId,
33 - input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean },
34 - ) => Effect.Effect<void, CloudEnvironmentLinkError>;
35 - readonly canUpdateEnvironment: (environmentId: EnvironmentId) => boolean;
36 - readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean;
37 - }) {
38 - const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* (
39 - connection: SavedRemoteConnection,
40 - enabled: boolean,
41 - clerkToken: string | null,
42 - ) {
43 - const result = input.canUpdateEnvironment(connection.environmentId)
44 - ? yield* input.updateEnvironment(connection.environmentId, enabled)
45 - : "unlinked";
46 - if (result === "updated" || result === "disconnected") return result;
47 - if (!enabled || !clerkToken || !input.canConfigureEnvironment(connection.environmentId)) {
48 - return result;
49 - }
18 +export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEnabled")(function* <
19 + SaveError,
20 +>(input: {
21 + readonly enabled: boolean;
22 + readonly previousEnabled: boolean;
23 + readonly clerkToken: string | null;
24 + readonly connections: ReadonlyArray<SavedRemoteConnection>;
25 + readonly updateEnvironment: (
26 + environmentId: EnvironmentId,
27 + enabled: boolean,
28 + ) => Effect.Effect<
29 + "updated" | "unlinked" | "unsupported" | "disconnected",
30 + CloudEnvironmentLinkError
31 + >;
32 + readonly linkEnvironment: (
33 + environmentId: EnvironmentId,
34 + input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean },
35 + ) => Effect.Effect<void, CloudEnvironmentLinkError>;
36 + readonly canUpdateEnvironment: (environmentId: EnvironmentId) => boolean;
37 + readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean;
38 + readonly saveLocalPreference: (enabled: boolean) => Effect.Effect<unknown, SaveError>;
39 +}) {
40 + const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* (
41 + connection: SavedRemoteConnection,
42 + enabled: boolean,
43 + clerkToken: string | null,
44 + ) {
45 + const result = input.canUpdateEnvironment(connection.environmentId)
46 + ? yield* input.updateEnvironment(connection.environmentId, enabled)
47 + : "unlinked";
48 + if (result === "updated" || result === "disconnected") return result;
49 + if (!enabled || !clerkToken || !input.canConfigureEnvironment(connection.environmentId)) {
50 + return result;
51 + }
52
51 - yield* input.linkEnvironment(connection.environmentId, {
52 - clerkToken,
53 - liveActivitiesEnabled: enabled,
54 - });
55 - return "updated" as const;
53 + yield* input.linkEnvironment(connection.environmentId, {
54 + clerkToken,
55 + liveActivitiesEnabled: enabled,
56 });
57 + return "updated" as const;
58 + });
59
58 - const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) {
59 - yield* updateAgentAwarenessRegistrationPreferences({
60 - liveActivitiesEnabled: enabled,
61 - });
60 + const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) {
61 + yield* updateAgentAwarenessRegistrationPreferences({
62 + liveActivitiesEnabled: enabled,
63 + });
64
63 - const clerkToken = input.clerkToken;
64 - if (!clerkToken) return false;
65 + const clerkToken = input.clerkToken;
66 + if (!clerkToken) return false;
67
66 - const results = yield* Effect.forEach(
67 - input.connections,
68 - (connection) =>
69 - updateEnvironmentPreference(connection, enabled, clerkToken).pipe(
70 - Effect.result,
71 - Effect.map((result) => ({ connection, result })),
72 - ),
73 - { concurrency: "unbounded" },
74 - );
75 - const failure = results.find(({ result }) => Result.isFailure(result));
76 - if (failure && Result.isFailure(failure.result)) {
77 - const updatedEnvironments = results.flatMap(({ connection, result }) => {
78 - const changed = Result.isSuccess(result)
79 - ? result.success === "updated"
80 - : result.failure.relayLinkCommitted === true;
81 - return changed ? [connection.environmentLabel] : [];
82 - });
83 - if (updatedEnvironments.length === 0) return yield* failure.result.failure;
84 - return yield* new LiveActivityEnvironmentUpdateError({
85 - updatedEnvironments,
86 - cause: failure.result.failure,
87 - });
88 - }
89 - return results.some(
90 - ({ result }) => Result.isSuccess(result) && result.success === "unsupported",
91 - );
92 - });
68 + const results = yield* Effect.forEach(
69 + input.connections,
70 + (connection) =>
71 + updateEnvironmentPreference(connection, enabled, clerkToken).pipe(
72 + Effect.result,
73 + Effect.map((result) => ({ connection, result })),
74 + ),
75 + { concurrency: "unbounded" },
76 + );
77 + const failure = results.find(({ result }) => Result.isFailure(result));
78 + if (failure && Result.isFailure(failure.result)) {
79 + const updatedEnvironments = results.flatMap(({ connection, result }) => {
80 + const changed = Result.isSuccess(result)
81 + ? result.success === "updated"
82 + : result.failure.relayLinkCommitted === true;
83 + return changed ? [connection.environmentLabel] : [];
84 + });
85 + if (updatedEnvironments.length === 0) return yield* failure.result.failure;
86 + return yield* new LiveActivityEnvironmentUpdateError({
87 + updatedEnvironments,
88 + cause: failure.result.failure,
89 + });
90 + }
91 + return results.some(
92 + ({ result }) => Result.isSuccess(result) && result.success === "unsupported",
93 + );
94 + });
95
94 - return yield* updateRelayPreference(input.enabled).pipe(
95 - Effect.onError(() =>
96 - updateAgentAwarenessRegistrationPreferences({
97 - liveActivitiesEnabled: input.previousEnabled,
98 - }).pipe(
99 - Effect.catchCause((cause) =>
100 - Effect.logWarning("Could not restore Live Activity device preference.", cause),
101 - ),
96 + return yield* updateRelayPreference(input.enabled).pipe(
97 + // Saved here so a device that cannot keep the setting restores its registration too.
98 + Effect.tap(() => input.saveLocalPreference(input.enabled)),
99 + Effect.onError(() =>
100 + updateAgentAwarenessRegistrationPreferences({
101 + liveActivitiesEnabled: input.previousEnabled,
102 + }).pipe(
103 + Effect.catchCause((cause) =>
104 + Effect.logWarning("Could not restore Live Activity device preference.", cause),
105 ),
106 ),
104 - );
105 - },
106 -);
107 + ),
108 + );
109 +});
apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
+57 -3
@@ -21,12 +21,19 @@ import * as Dpop from "../cloud/dpop";
21 import * as ManagedRelayLayer from "../cloud/managedRelayLayer";
22 import {
23 clearAgentAwarenessRegistrationRecord,
24 + loadAgentAwarenessDeviceId,
25 loadAgentAwarenessRegistrationRecord,
26 loadOrCreateAgentAwarenessDeviceId,
27 loadPreferences,
28 saveAgentAwarenessRegistrationRecord,
29 } from "../../persistence/imperative";
29 -import type { Preferences } from "../../persistence/mobile-preferences";
30 +import {
31 + MobilePreferencesLoadError,
32 + MobilePreferencesStore,
33 + type Preferences,
34 +} from "../../persistence/mobile-preferences";
35 +import { MobileSecureStorageError } from "../../persistence/mobile-secure-storage";
36 +import * as MobileStorage from "../../persistence/mobile-storage";
37 import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
38 import {
39 __resetAgentAwarenessRemoteRegistrationForTest,
@@ -40,6 +47,7 @@ import {
47 subscribeAgentAwarenessRegistrationStatus,
48 updateAgentAwarenessRegistrationPreferences,
49 type AgentAwarenessRegistrationError,
50 + type AgentAwarenessRegistrationServices,
51 } from "./remoteRegistration";
52 import * as Notifications from "expo-notifications";
53 import { Platform } from "react-native";
@@ -218,8 +226,53 @@ function proofIat(proof: string): number {
226 return decoded.iat;
227 }
228
229 +const storageFailure = (cause: unknown) =>
230 + new MobileSecureStorageError({ operation: "read", key: "test", cause });
231 +const unexpectedStorage = () => Effect.die("Unexpected storage request");
232 +
233 +// Delegates to the persistence/imperative mocks so each test steers both paths the same way.
234 +const layerPersistenceTest = Layer.merge(
235 + Layer.succeed(
236 + MobileStorage.MobileStorage,
237 + MobileStorage.MobileStorage.of({
238 + loadOrCreateAgentAwarenessDeviceId: Effect.tryPromise({
239 + try: () => loadOrCreateAgentAwarenessDeviceId(),
240 + catch: storageFailure,
241 + }),
242 + loadAgentAwarenessDeviceId: Effect.tryPromise({
243 + try: () => loadAgentAwarenessDeviceId(),
244 + catch: storageFailure,
245 + }),
246 + loadAgentAwarenessRegistrationRecord: Effect.tryPromise({
247 + try: () => loadAgentAwarenessRegistrationRecord(),
248 + catch: storageFailure,
249 + }),
250 + saveAgentAwarenessRegistrationRecord: (record) =>
251 + Effect.tryPromise({
252 + try: () => saveAgentAwarenessRegistrationRecord(record),
253 + catch: storageFailure,
254 + }),
255 + clearAgentAwarenessRegistrationRecord: unexpectedStorage(),
256 + loadRecentThreadShortcuts: unexpectedStorage(),
257 + saveRecentThreadShortcuts: unexpectedStorage,
258 + }),
259 + ),
260 + Layer.succeed(
261 + MobilePreferencesStore,
262 + MobilePreferencesStore.of({
263 + load: Effect.tryPromise({
264 + try: () => loadPreferences(),
265 + catch: (cause) => new MobilePreferencesLoadError({ cause }),
266 + }),
267 + savePatch: unexpectedStorage,
268 + update: unexpectedStorage,
269 + }),
270 + ),
271 +);
272 +
273 const layerRelayTest = ManagedRelayLayer.layer("https://relay.example.test").pipe(
274 Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Dpop.layer)),
275 + Layer.merge(layerPersistenceTest),
276 );
277
278 const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(
@@ -241,7 +294,7 @@ const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundO
294 pending.operation as Effect.Effect<
295 unknown,
296 AgentAwarenessRegistrationError,
244 - ManagedRelay.ManagedRelayClient
297 + AgentAwarenessRegistrationServices
298 >,
299 );
300 yield* Effect.sync(() => {
@@ -722,6 +775,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
775 Effect.provide(
776 ManagedRelayLayer.layer("https://permission-relay.example.test").pipe(
777 Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Dpop.layer)),
778 + Layer.merge(layerPersistenceTest),
779 ),
780 ),
781 );
@@ -1021,7 +1075,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
1075 getAgentActivitySnapshot,
1076 resetTokenCache: Effect.void,
1077 }),
1024 - );
1078 + ).pipe(Layer.merge(layerPersistenceTest));
1079 }
1080
1081 it.effect("registers an existing Live Activity before waiting on the widget read", () => {
apps/mobile/src/features/agent-awareness/remoteRegistration.ts
+80 -66
@@ -29,14 +29,11 @@ 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 type { Preferences } from "../../persistence/mobile-preferences";
32 +import { MobilePreferencesStore, type Preferences } from "../../persistence/mobile-preferences";
33 +import * as MobileStorage from "../../persistence/mobile-storage";
34 import {
35 clearAgentAwarenessRegistrationRecord,
35 - loadAgentAwarenessDeviceId,
36 - loadAgentAwarenessRegistrationRecord,
37 - loadOrCreateAgentAwarenessDeviceId,
36 loadPreferences,
39 - saveAgentAwarenessRegistrationRecord,
37 } from "../../persistence/imperative";
38 import type { AgentActivityProps } from "../../widgets/AgentActivity";
39 import {
@@ -88,6 +85,11 @@ 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.
@@ -387,7 +389,7 @@ function registrationSignature(body: RelayDeviceRegistrationRequest): string {
389 const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWithRelay")(function* (
390 body: RelayDeviceRegistrationRequest,
391 expectedGeneration: number,
390 -): Effect.fn.Return<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
392 +): Effect.fn.Return<void, AgentAwarenessRegistrationError, AgentAwarenessRegistrationServices> {
393 if (expectedGeneration !== deviceRegistrationGeneration) {
394 return;
395 }
@@ -406,11 +408,13 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith
408 }
409
410 const identity = relayTokenProviderIdentity ?? "";
409 - const persisted = yield* Effect.tryPromise({
410 - try: () => loadAgentAwarenessRegistrationRecord(),
411 - catch: (cause) =>
412 - new AgentAwarenessOperationError({ operation: "load-registration-record", cause }),
413 - }).pipe(Effect.orElseSucceed(() => null));
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.
@@ -449,13 +453,12 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith
453 }
454 if (body.platform === "android") androidDeviceReplayedAt = yield* Clock.currentTimeMillis;
455 setRegistrationStatus("registered", Boolean(payload.pushToken));
452 - yield* Effect.promise(() =>
453 - saveAgentAwarenessRegistrationRecord({
454 - identity,
455 - signature,
456 - }).catch((error: unknown) => {
457 - logRegistrationError("persist registration record failed", error);
458 - }),
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
@@ -610,7 +613,7 @@ function logRegistrationError(context: string, error: unknown): void {
613 }
614
615 function runRegistrationInBackground<E>(
613 - operation: Effect.Effect<unknown, E, ManagedRelay.ManagedRelayClient>,
616 + operation: Effect.Effect<unknown, E, AgentAwarenessRegistrationServices>,
617 context: string,
618 ): void {
619 void (async () => {
@@ -693,28 +696,32 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri
696 const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* (
697 input: RegisterDeviceInput = {},
698 expectedGeneration = deviceRegistrationGeneration,
696 -): Effect.fn.Return<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
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([
702 - Effect.tryPromise({
703 - try: () => loadOrCreateAgentAwarenessDeviceId(),
704 - catch: (cause) =>
705 - new AgentAwarenessOperationError({
706 - operation: "load-device-registration-identifier",
707 - cause,
708 - }),
709 - }),
710 - Effect.tryPromise({
711 - try: () => loadPreferences(),
712 - catch: (cause) =>
713 - new AgentAwarenessOperationError({
714 - operation: "load-device-registration-preferences",
715 - cause,
716 - }),
717 - }),
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,
@@ -833,7 +840,7 @@ function endLocalLiveActivities(context: string): void {
840 export function refreshAgentAwarenessRegistration(): Effect.Effect<
841 void,
842 never,
836 - ManagedRelay.ManagedRelayClient
843 + AgentAwarenessRegistrationServices
844 > {
845 return Effect.suspend(() => {
846 const generation = deviceRegistrationGeneration;
@@ -852,7 +859,7 @@ export function refreshAgentAwarenessRegistration(): Effect.Effect<
859
860 export function updateAgentAwarenessRegistrationPreferences(
861 preferencesOverride: Partial<Preferences>,
855 -): Effect.Effect<void, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
862 +): Effect.Effect<void, AgentAwarenessRegistrationError, AgentAwarenessRegistrationServices> {
863 return Effect.suspend(() => {
864 const generation = deviceRegistrationGeneration;
865 return registerDevice({ preferencesOverride }, generation).pipe(
@@ -895,18 +902,20 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
902
903 export const unregisterAgentAwarenessDeviceForCurrentUser: (
904 tokenProvider: () => Promise<string | null>,
898 -) => Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> = Effect.fn(
905 +) => Effect.Effect<void, never, AgentAwarenessRegistrationServices> = Effect.fn(
906 "remoteRegistration.unregisterAgentAwarenessDeviceForCurrentUser",
907 )(
908 function* (tokenProvider: () => Promise<string | null>) {
902 - const deviceId = yield* Effect.tryPromise({
903 - try: () => loadAgentAwarenessDeviceId(),
904 - catch: (cause) =>
905 - new AgentAwarenessOperationError({
906 - operation: "load-device-unregistration-identifier",
907 - cause,
908 - }),
909 - });
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 }
@@ -923,7 +932,7 @@ export const registerLiveActivityPushToken = Effect.fn(
932 "remoteRegistration.registerLiveActivityPushToken",
933 )(function* (input: {
934 readonly activity: LiveActivity<AgentActivityProps>;
926 -}): Effect.fn.Return<boolean, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
935 +}): Effect.fn.Return<boolean, AgentAwarenessRegistrationError, AgentAwarenessRegistrationServices> {
936 if (!canRegisterRemoteLiveActivities()) {
937 return false;
938 }
@@ -971,7 +980,7 @@ const registerLiveActivityPushTokenValue = Effect.fn(
980 "remoteRegistration.registerLiveActivityPushTokenValue",
981 )(function* (input: {
982 readonly activityPushToken: string;
974 -}): Effect.fn.Return<boolean, AgentAwarenessRegistrationError, ManagedRelay.ManagedRelayClient> {
983 +}): Effect.fn.Return<boolean, AgentAwarenessRegistrationError, AgentAwarenessRegistrationServices> {
984 const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);
985 if (
986 acceptedAt !== undefined &&
@@ -979,14 +988,16 @@ const registerLiveActivityPushTokenValue = Effect.fn(
988 ) {
989 return true;
990 }
982 - const deviceId = yield* Effect.tryPromise({
983 - try: () => loadOrCreateAgentAwarenessDeviceId(),
984 - catch: (cause) =>
985 - new AgentAwarenessOperationError({
986 - operation: "load-live-activity-registration-identifier",
987 - cause,
988 - }),
989 - });
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,
@@ -1013,7 +1024,7 @@ function scheduleActiveLiveActivityRegistrationRetry(): void {
1024
1025 export const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
1026 "remoteRegistration.refreshActiveLiveActivityRemoteRegistration",
1016 -)(function* (): Effect.fn.Return<void, never, ManagedRelay.ManagedRelayClient> {
1027 +)(function* (): Effect.fn.Return<void, never, AgentAwarenessRegistrationServices> {
1028 if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
1029 return;
1030 }
@@ -1084,14 +1095,17 @@ export const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
1095 return;
1096 }
1097 const { snapshot } = widgetRead;
1087 - const preferences = yield* Effect.tryPromise({
1088 - try: () => loadPreferences(),
1089 - catch: (cause) =>
1090 - new AgentAwarenessOperationError({
1091 - operation: "load-live-activity-prime-preferences",
1092 - cause,
1093 - }),
1094 - }).pipe(Effect.orElseSucceed(() => null));
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()) {
apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+5 -4
@@ -61,7 +61,6 @@ import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/pu
61 import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
62 import { runtime } from "../../lib/runtime";
63 import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences";
64 -import { useAtomCommand } from "../../state/use-atom-command";
64 import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
65 import { SettingsRow } from "./components/SettingsRow";
66 import { SettingsSection } from "./components/SettingsSection";
@@ -102,6 +101,9 @@ const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(fun
101 );
102 });
103
104 +const saveLocalPreference = (liveActivitiesEnabled: boolean) =>
105 + saveMobilePreferences.run(appAtomRegistry, { liveActivitiesEnabled });
106 +
107 const linkEnvironmentWithPreference = Effect.fn("linkEnvironmentWithPreference")(function* (
108 environmentId: EnvironmentId,
109 input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean },
@@ -209,7 +211,6 @@ function ConfiguredSettingsNotificationsRouteScreen() {
211 const gt = useGT();
212 const m = useMessages();
213 const preferencesResult = useAtomValue(mobilePreferencesAtom);
212 - const savePreferences = useAtomCommand(saveMobilePreferences);
214 const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
215 const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS, m);
216 const agentAwarenessSubtitle =
@@ -386,6 +387,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
387 setLiveActivityUpdatesEnabled({
388 updateEnvironment: updateEnvironmentPreference,
389 linkEnvironment: linkEnvironmentWithPreference,
390 + saveLocalPreference,
391 canConfigureEnvironment: (id) =>
392 canManageConnect(id, AuthRelayConfigureScope) &&
393 canManageConnect(id, AuthRelayWriteScope),
@@ -414,7 +416,6 @@ function ConfiguredSettingsNotificationsRouteScreen() {
416 return;
417 }
418
417 - void savePreferences({ liveActivitiesEnabled: true });
419 refreshManagedRelayEnvironments();
420 setLiveActivityStatus("enabled");
421 // Environment linking can precede device registration; only registered devices can receive Live Activities.
@@ -484,6 +485,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
485 setLiveActivityUpdatesEnabled({
486 updateEnvironment: updateEnvironmentPreference,
487 linkEnvironment: linkEnvironmentWithPreference,
488 + saveLocalPreference,
489 canConfigureEnvironment: (id) =>
490 canManageConnect(id, AuthRelayConfigureScope) &&
491 canManageConnect(id, AuthRelayWriteScope),
@@ -504,7 +506,6 @@ function ConfiguredSettingsNotificationsRouteScreen() {
506 }
507 return;
508 }
507 - void savePreferences({ liveActivitiesEnabled: false });
509 refreshManagedRelayEnvironments();
510 setLiveActivityStatus("disabled");
511 if (updateResult.value) {