@devries-cameron20 / t3code Mirror · read-only / commits / da7ebc2116
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, 16:00 UTC

fix(mobile): push-token failures no longer report notifications as enabled (#26557)

Julius Marminge committed Nov 13, 2026 at 17:35 UTC da7ebc2116dde442221a8a39afc5a5b6e157e5a4
5 files changed +204 -9
apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
+111
@@ -30,12 +30,14 @@ import type { Preferences } from "../../persistence/mobile-preferences";
30 import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
31 import {
32 __resetAgentAwarenessRemoteRegistrationForTest,
33 + agentAwarenessNotificationsReady,
34 getAgentAwarenessRegistrationStatus,
35 refreshActiveLiveActivityRemoteRegistration,
36 refreshAgentAwarenessRegistration,
37 registerLiveActivityPushToken,
38 releaseAgentAwarenessRelayTokenProvider,
39 setAgentAwarenessRelayTokenProvider,
40 + subscribeAgentAwarenessRegistrationStatus,
41 updateAgentAwarenessRegistrationPreferences,
42 type AgentAwarenessRegistrationError,
43 } from "./remoteRegistration";
@@ -709,6 +711,115 @@ describe("makeRelayDeviceRegistrationRequest", () => {
711 );
712 },
713 );
714 +
715 + const stubAndroidDeviceRelay = () => {
716 + vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
717 + vi.spyOn(Platform, "Version", "get").mockReturnValue(36);
718 + const registrations: Array<{
719 + readonly preferences: { readonly notificationsEnabled: boolean };
720 + }> = [];
721 + vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
722 + const request = new Request(input, init);
723 + if (request.url.endsWith("/v1/client/dpop-token")) {
724 + return Response.json({
725 + access_token: "relay-dpop-token",
726 + issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
727 + token_type: "DPoP",
728 + expires_in: 300,
729 + scope: "mobile:registration",
730 + });
731 + }
732 + if (request.url.endsWith("/v1/mobile/devices")) {
733 + registrations.push(await request.json());
734 + }
735 + return Response.json({ ok: true });
736 + });
737 + Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } };
738 + return registrations;
739 + };
740 +
741 + it.effect("does not report notifications ready when its push token lookup fails", () => {
742 + const registrations = stubAndroidDeviceRelay();
743 + vi.mocked(Notifications.getDevicePushTokenAsync).mockRejectedValue(
744 + new Error("Default FirebaseApp is not initialized"),
745 + );
746 + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"), "user-a");
747 +
748 + return Effect.gen(function* () {
749 + yield* runBackgroundOperations();
750 +
751 + // Live Activities register with their own tokens, so the device stays registered.
752 + expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
753 + expect(agentAwarenessNotificationsReady()).toBe(false);
754 + expect(registrations).toMatchObject([{ preferences: { notificationsEnabled: true } }]);
755 + expect(registrations[0]).not.toHaveProperty("pushToken");
756 +
757 + const onStatusChange = vi.fn();
758 + subscribeAgentAwarenessRegistrationStatus(onStatusChange);
759 + const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0];
760 + listener({ type: "android", data: "fcm-token" } as never);
761 + yield* runBackgroundOperations();
762 +
763 + expect(agentAwarenessNotificationsReady()).toBe(true);
764 + expect(onStatusChange).toHaveBeenCalled();
765 + }).pipe(
766 + Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
767 + Effect.provide(layerRelayTest),
768 + );
769 + });
770 +
771 + it.effect("keeps notifications enabled when a refresh cannot read the push token", () => {
772 + const registrations = stubAndroidDeviceRelay();
773 + vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
774 + type: "android",
775 + data: "fcm-token",
776 + });
777 + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"), "user-a");
778 +
779 + return Effect.gen(function* () {
780 + yield* runBackgroundOperations();
781 + expect(registrations).toMatchObject([{ preferences: { notificationsEnabled: true } }]);
782 + expect(getAgentAwarenessRegistrationStatus()).toBe("registered");
783 +
784 + vi.mocked(Notifications.getDevicePushTokenAsync).mockRejectedValueOnce(
785 + new Error("SERVICE_NOT_AVAILABLE"),
786 + );
787 + yield* refreshAgentAwarenessRegistration();
788 +
789 + expect(registrations).toMatchObject([{ preferences: { notificationsEnabled: true } }]);
790 + expect(agentAwarenessNotificationsReady()).toBe(true);
791 +
792 + // A lookup that started before a rotation must not replace the rotated token.
793 + let resolveStaleLookup: (token: { type: "android"; data: string }) => void = () => {};
794 + let markLookupStarted: () => void = () => {};
795 + const lookupStarted = new Promise<void>((resolve) => {
796 + markLookupStarted = resolve;
797 + });
798 + vi.mocked(Notifications.getDevicePushTokenAsync).mockImplementationOnce(() => {
799 + markLookupStarted();
800 + return new Promise((resolve) => {
801 + resolveStaleLookup = resolve;
802 + });
803 + });
804 + const staleRefresh = yield* Effect.forkChild(refreshAgentAwarenessRegistration());
805 + yield* Effect.promise(() => lookupStarted);
806 + const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0];
807 + listener({ type: "android", data: "rotated-fcm-token" } as never);
808 + yield* runBackgroundOperations();
809 + resolveStaleLookup({ type: "android", data: "fcm-token" });
810 + yield* Fiber.join(staleRefresh);
811 + vi.mocked(Notifications.getDevicePushTokenAsync).mockRejectedValueOnce(
812 + new Error("SERVICE_NOT_AVAILABLE"),
813 + );
814 + yield* refreshAgentAwarenessRegistration();
815 +
816 + expect(registrations.at(-1)).toMatchObject({ pushToken: "rotated-fcm-token" });
817 + }).pipe(
818 + Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
819 + Effect.provide(layerRelayTest),
820 + );
821 + });
822 +
823 it.effect.each(["blocked", "unavailable"] as const)(
824 "keeps Android push delivery registered when the alert channel is %s",
825 (channelState) => {
apps/mobile/src/features/agent-awareness/remoteRegistration.ts
+31 -6
@@ -95,6 +95,9 @@ const registeredActivityPushTokens = new Map<string, number>();
95 // repaint, so a slow older response never overwrites newer rows.
96 let widgetSnapshotReads = 0;
97 let androidDeviceReplayedAt: number | null = null;
98 +let lastNativePushToken: string | null = null;
99 +let registeredWithPushToken = false;
100 +let nativePushTokenRotations = 0;
101 let pushTokenSubscription: { remove: () => void } | null = null;
102 let appStateSubscription: { remove: () => void } | null = null;
103
@@ -102,11 +105,15 @@ export type AgentAwarenessRegistrationStatus = "unknown" | "pending" | "register
105 let registrationStatus: AgentAwarenessRegistrationStatus = "unknown";
106 const registrationStatusListeners = new Set<() => void>();
107
105 -function setRegistrationStatus(next: AgentAwarenessRegistrationStatus): void {
106 - if (registrationStatus === next) {
108 +function setRegistrationStatus(
109 + next: AgentAwarenessRegistrationStatus,
110 + withPushToken = registeredWithPushToken,
111 +): void {
112 + if (registrationStatus === next && registeredWithPushToken === withPushToken) {
113 return;
114 }
115 registrationStatus = next;
116 + registeredWithPushToken = withPushToken;
117 for (const listener of registrationStatusListeners) {
118 listener();
119 }
@@ -116,6 +123,12 @@ export function getAgentAwarenessRegistrationStatus(): AgentAwarenessRegistratio
123 return registrationStatus;
124 }
125
126 +// Live Activities use their own push tokens, so device registration alone does not mean
127 +// the relay can deliver notifications.
128 +export function agentAwarenessNotificationsReady(): boolean {
129 + return registrationStatus === "registered" && registeredWithPushToken;
130 +}
131 +
132 export function subscribeAgentAwarenessRegistrationStatus(listener: () => void): () => void {
133 registrationStatusListeners.add(listener);
134 return () => {
@@ -291,12 +304,15 @@ const nativePushTokenRegistration = Effect.fn("remoteRegistration.nativePushToke
304 )
305 : true);
306 if (observedPushToken) {
307 + lastNativePushToken = observedPushToken;
308 + nativePushTokenRotations++;
309 return {
310 notificationsEnabled: alertsEnabled,
311 pushToken: observedPushToken,
312 notificationPermissionGranted: permissions.granted,
313 };
314 }
315 + const rotationsBeforeLookup = nativePushTokenRotations;
316 const token = yield* Effect.tryPromise({
317 try: () => Notifications.getDevicePushTokenAsync(),
318 catch: (cause) =>
@@ -312,12 +328,18 @@ const nativePushTokenRegistration = Effect.fn("remoteRegistration.nativePushToke
328 ),
329 Effect.orElseSucceed(() => null),
330 );
315 - const pushToken =
331 + const lookedUpPushToken =
332 token?.type === Platform.OS && typeof token.data === "string" && token.data.trim().length > 0
333 ? token.data.trim()
334 : null;
335 + // A rotation observed while this lookup ran is newer than what the lookup returned.
336 + if (lookedUpPushToken && rotationsBeforeLookup === nativePushTokenRotations) {
337 + lastNativePushToken = lookedUpPushToken;
338 + }
339 + const pushToken = lastNativePushToken;
340 + // A missing token must not disable notifications the relay accepted.
341 return {
320 - notificationsEnabled: alertsEnabled && pushToken !== null,
342 + notificationsEnabled: alertsEnabled,
343 pushToken,
344 notificationPermissionGranted: permissions.granted,
345 };
@@ -405,7 +427,7 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith
427 persisted.signature === signature &&
428 !needsAndroidReplay
429 ) {
408 - setRegistrationStatus("registered");
430 + setRegistrationStatus("registered", Boolean(payload.pushToken));
431 return;
432 }
433
@@ -421,7 +443,7 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith
443 return;
444 }
445 if (body.platform === "android") androidDeviceReplayedAt = yield* Clock.currentTimeMillis;
424 - setRegistrationStatus("registered");
446 + setRegistrationStatus("registered", Boolean(payload.pushToken));
447 yield* Effect.promise(() =>
448 saveAgentAwarenessRegistrationRecord({
449 identity,
@@ -855,7 +877,10 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
877 activeDeviceRegistration = null;
878 pendingDeviceRegistration = null;
879 registrationStatus = "unknown";
880 + registeredWithPushToken = false;
881 androidDeviceReplayedAt = null;
882 + lastNativePushToken = null;
883 + nativePushTokenRotations = 0;
884 registrationStatusListeners.clear();
885 registeredActivityPushTokens.clear();
886 activityPushTokenLocks.clear();
apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+12 -2
@@ -34,6 +34,7 @@ import {
34 import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";
35 import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";
36 import {
37 + agentAwarenessNotificationsReady,
38 getAgentAwarenessRegistrationStatus,
39 refreshAgentAwarenessRegistration,
40 subscribeAgentAwarenessRegistrationStatus,
@@ -108,6 +109,14 @@ function useDeviceRegistered(): boolean {
109 return status === "registered";
110 }
111
112 +function useNotificationsReady(): boolean {
113 + return useSyncExternalStore(
114 + subscribeAgentAwarenessRegistrationStatus,
115 + agentAwarenessNotificationsReady,
116 + () => false,
117 + );
118 +}
119 +
120 export function SettingsNotificationsRouteScreen() {
121 if (!hasCloudPublicConfig()) {
122 return (
@@ -160,6 +169,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
169 setLiveActivityOverride({ status, basis: liveActivityBasis });
170 const liveActivityWriteInFlight = useRef(false);
171 const deviceRegistered = useDeviceRegistered();
172 + const notificationsReady = useNotificationsReady();
173 const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)
174 ? preferencesResult.value.liveActivitiesEnabled !== false
175 : true;
@@ -192,7 +202,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
202 }
203 if (result.value.type === "granted") {
204 setNotificationStatus("enabled");
195 - if (getAgentAwarenessRegistrationStatus() === "registered") {
205 + if (agentAwarenessNotificationsReady()) {
206 Dialog.alert("Notifications enabled", "Agent notifications are enabled for this device.");
207 } else {
208 Dialog.alert(
@@ -434,7 +444,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
444 }
445 subtitle={agentAwarenessSubtitle}
446 value={
437 - agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered
447 + agentAwarenessPushAvailable && notificationStatus === "enabled" && notificationsReady
448 }
449 onValueChange={handleDeviceNotificationsChange}
450 />
infra/relay/src/agentActivity/Devices.test.ts new
+47
@@ -0,0 +1,47 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as Layer from "effect/Layer";
4 +
5 +import * as RelayDb from "../db.ts";
6 +import * as Devices from "./Devices.ts";
7 +
8 +const deviceRow = (pushToken: string | null) => ({
9 + deviceId: "device-1",
10 + label: "Pixel 9",
11 + platform: "android",
12 + iosMajorVersion: null,
13 + androidApiLevel: 36,
14 + appVersion: "2.2.0",
15 + pushToken,
16 + preferences: {
17 + notificationsEnabled: true,
18 + liveActivitiesEnabled: true,
19 + notifyOnApproval: true,
20 + notifyOnInput: true,
21 + notifyOnCompletion: true,
22 + notifyOnFailure: true,
23 + },
24 + updatedAt: "2026-10-28T00:00:00.000Z",
25 +});
26 +
27 +describe("Devices", () => {
28 + it.effect.each([
29 + [null, false],
30 + ["fcm-token", true],
31 + ] as const)("lists notifications for push token %s as enabled: %s", ([pushToken, enabled]) => {
32 + const fakeDb = {
33 + select: () => ({
34 + from: () => ({ where: () => Effect.succeed([deviceRow(pushToken)]) }),
35 + }),
36 + } as unknown as RelayDb.RelayDb["Service"];
37 +
38 + return Effect.gen(function* () {
39 + const devices = yield* Devices.Devices;
40 + const [device] = yield* devices.listForUser({ userId: "user-1" });
41 +
42 + expect(device?.notifications.enabled).toBe(enabled);
43 + }).pipe(
44 + Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),
45 + );
46 + });
47 +});
infra/relay/src/agentActivity/Devices.ts
+3 -1
@@ -222,6 +222,7 @@ const make = Effect.gen(function* () {
222 iosMajorVersion: relayMobileDevices.iosMajorVersion,
223 androidApiLevel: relayMobileDevices.androidApiLevel,
224 appVersion: relayMobileDevices.appVersion,
225 + pushToken: relayMobileDevices.pushToken,
226 preferences: relayMobileDevices.preferencesJson,
227 updatedAt: relayMobileDevices.updatedAt,
228 })
@@ -240,7 +241,8 @@ const make = Effect.gen(function* () {
241 androidApiLevel: row.androidApiLevel,
242 appVersion: row.appVersion,
243 notifications: {
243 - enabled: row.preferences.notificationsEnabled,
244 + // Clients keep the preference on while the device has no token; nothing is delivered then.
245 + enabled: row.preferences.notificationsEnabled && row.pushToken !== null,
246 notifyOnApproval: row.preferences.notifyOnApproval,
247 notifyOnInput: row.preferences.notifyOnInput,
248 notifyOnCompletion: row.preferences.notifyOnCompletion,