The best way to control Claude Code, Codex and more from any computer or phone
fix(mobile): Live Activities keep updating after iOS rotates their push token (#21134)
Co-authored-by: Aidid Haiqal <syafdo02@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Aidid Haiqal committed
Oct 19, 2026 at 03:23 UTC
f24e8006516870d42a2da06a596d847374396729
2 files changed
+180
-47
apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
+131
-6
@@ -8,6 +8,7 @@ import Constants from "expo-constants";
8
import * as Cause from "effect/Cause";
9
import * as Effect from "effect/Effect";
10
import * as Exit from "effect/Exit";
11
+import * as Fiber from "effect/Fiber";
12
import * as Layer from "effect/Layer";
13
import { Cookies, FetchHttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
14
import { ManagedRelay } from "@t3tools/client-runtime/relay";
@@ -391,26 +392,144 @@ describe("makeRelayDeviceRegistrationRequest", () => {
392
).toEqual({ liveActivitiesEnabled: true, baseFontSize: 18 });
393
});
394
394
- it.effect("registers at most one listener while a Live Activity push token is pending", () => {
395
+ it.effect("registers one push-token listener per Live Activity across wrappers", () => {
396
registerAgentAwarenessConnection(savedConnection());
397
const addPushTokenListener = vi.fn();
397
- const activity = {
398
+ // getInstances() returns a new wrapper for the same native activity each call.
399
+ const wrapper = () => ({
400
+ getId: () => "activity-1",
401
getPushToken: vi.fn(() => Promise.resolve(null)),
402
addPushTokenListener,
400
- };
403
+ });
404
405
return Effect.gen(function* () {
403
- expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
404
- expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
406
+ expect(yield* registerLiveActivityPushToken({ activity: wrapper() as never })).toBe(false);
407
+ expect(yield* registerLiveActivityPushToken({ activity: wrapper() as never })).toBe(false);
408
406
- expect(activity.getPushToken).toHaveBeenCalledTimes(2);
409
expect(addPushTokenListener).toHaveBeenCalledTimes(1);
410
}).pipe(Effect.provide(layerRelayTest));
411
});
412
413
+ it.effect("registers a Live Activity push token that rotates after registration", () => {
414
+ const registeredTokens: Array<string> = [];
415
+ vi.stubGlobal("fetch", async (request: RequestInfo | URL, init?: RequestInit) => {
416
+ const url = request instanceof Request ? request.url : String(request);
417
+ if (url.endsWith("/v1/client/dpop-token")) {
418
+ return Response.json({
419
+ access_token: "relay-dpop-token",
420
+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
421
+ token_type: "DPoP",
422
+ expires_in: 300,
423
+ scope: "mobile:registration",
424
+ });
425
+ }
426
+ if (url.endsWith("/v1/mobile/live-activities")) {
427
+ const body = request instanceof Request ? await request.text() : String(init?.body);
428
+ registeredTokens.push(
429
+ (JSON.parse(body) as { readonly activityPushToken: string }).activityPushToken,
430
+ );
431
+ }
432
+ return Response.json({ ok: true });
433
+ });
434
+ Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
435
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
436
+ let tokenListener: ((event: { readonly pushToken: string }) => void) | undefined;
437
+ const activity = {
438
+ getId: () => "activity-1",
439
+ getPushToken: vi.fn(() => Promise.resolve("activity-token")),
440
+ addPushTokenListener: vi.fn((listener: typeof tokenListener) => {
441
+ tokenListener = listener;
442
+ return { remove: vi.fn() };
443
+ }),
444
+ };
445
+
446
+ return Effect.gen(function* () {
447
+ yield* runBackgroundOperations();
448
+ expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(true);
449
+
450
+ tokenListener?.({ pushToken: "rotated-activity-token" });
451
+ yield* runBackgroundOperations();
452
+
453
+ expect(registeredTokens).toEqual(["activity-token", "rotated-activity-token"]);
454
+ }).pipe(
455
+ Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
456
+ Effect.provide(layerRelayTest),
457
+ );
458
+ });
459
+
460
+ it.effect("registers a rotated Live Activity token only after an older registration", () => {
461
+ const arrivals: Array<string> = [];
462
+ let openOldRequest: (() => void) | undefined;
463
+ const oldRequestGate = new Promise<void>((resolve) => {
464
+ openOldRequest = resolve;
465
+ });
466
+ let markOldRequestArrived: (() => void) | undefined;
467
+ const oldRequestArrived = new Promise<void>((resolve) => {
468
+ markOldRequestArrived = resolve;
469
+ });
470
+ vi.stubGlobal("fetch", async (request: RequestInfo | URL, init?: RequestInit) => {
471
+ const url = request instanceof Request ? request.url : String(request);
472
+ if (url.endsWith("/v1/client/dpop-token")) {
473
+ return Response.json({
474
+ access_token: "relay-dpop-token",
475
+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
476
+ token_type: "DPoP",
477
+ expires_in: 300,
478
+ scope: "mobile:registration",
479
+ });
480
+ }
481
+ if (url.endsWith("/v1/mobile/live-activities")) {
482
+ const body = request instanceof Request ? await request.text() : String(init?.body);
483
+ const token = (JSON.parse(body) as { readonly activityPushToken: string })
484
+ .activityPushToken;
485
+ arrivals.push(token);
486
+ if (token === "activity-token") {
487
+ markOldRequestArrived?.();
488
+ await oldRequestGate;
489
+ }
490
+ }
491
+ return Response.json({ ok: true });
492
+ });
493
+ Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
494
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
495
+ let tokenListener: ((event: { readonly pushToken: string }) => void) | undefined;
496
+ const activity = {
497
+ getId: () => "activity-1",
498
+ getPushToken: vi.fn(() => Promise.resolve("activity-token")),
499
+ addPushTokenListener: vi.fn((listener: typeof tokenListener) => {
500
+ tokenListener = listener;
501
+ return { remove: vi.fn() };
502
+ }),
503
+ };
504
+
505
+ return Effect.gen(function* () {
506
+ yield* runBackgroundOperations();
507
+ const lookup = yield* Effect.forkChild(
508
+ registerLiveActivityPushToken({ activity: activity as never }),
509
+ );
510
+ yield* Effect.promise(() => oldRequestArrived);
511
+
512
+ tokenListener?.({ pushToken: "rotated-activity-token" });
513
+ const listenerRegistration = yield* Effect.forkChild(runBackgroundOperations());
514
+ for (let pass = 0; pass < 5; pass++) {
515
+ yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
516
+ }
517
+ expect(arrivals).toEqual(["activity-token"]);
518
+
519
+ openOldRequest?.();
520
+ yield* Fiber.join(lookup);
521
+ yield* Fiber.join(listenerRegistration);
522
+ expect(arrivals).toEqual(["activity-token", "rotated-activity-token"]);
523
+ }).pipe(
524
+ Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
525
+ Effect.provide(layerRelayTest),
526
+ );
527
+ });
528
+
529
it.effect("preserves Live Activity push-token lookup failures", () => {
530
const cause = new Error("native token lookup failed");
531
const activity = {
532
+ getId: () => "activity-1",
533
getPushToken: vi.fn(() => Promise.reject(cause)),
534
addPushTokenListener: vi.fn(),
535
};
@@ -435,6 +554,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
554
() => {
555
registerAgentAwarenessConnection(savedConnection());
556
const activity = {
557
+ getId: () => "activity-1",
558
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
559
addPushTokenListener: vi.fn(),
560
};
@@ -449,6 +569,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
569
"registers APNS-started Live Activities for relay updates without mutating them locally",
570
() => {
571
const activity = {
572
+ getId: () => "activity-1",
573
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
574
addPushTokenListener: vi.fn(),
575
start: vi.fn(),
@@ -473,6 +594,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
594
"re-registers active Live Activity tokens when the app returns to the foreground",
595
() => {
596
const activity = {
597
+ getId: () => "activity-1",
598
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
599
addPushTokenListener: vi.fn(),
600
};
@@ -502,6 +624,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
624
it("ends local Live Activities and stops foreground reconciliation on cloud sign-out", () => {
625
const end = vi.fn(() => Promise.resolve());
626
const activity = {
627
+ getId: () => "activity-1",
628
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
629
addPushTokenListener: vi.fn(),
630
end,
@@ -613,6 +736,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
736
it("releases the provider without ending activities or clearing the registration", () => {
737
const end = vi.fn(() => Promise.resolve());
738
const activity = {
739
+ getId: () => "activity-1",
740
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
741
addPushTokenListener: vi.fn(),
742
end,
@@ -708,6 +832,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
832
},
833
};
834
const activity = {
835
+ getId: () => "activity-1",
836
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
837
addPushTokenListener: vi.fn(),
838
};
apps/mobile/src/features/agent-awareness/remoteRegistration.ts
+49
-41
@@ -7,6 +7,7 @@ import Constants from "expo-constants";
7
import * as Notifications from "expo-notifications";
8
import * as Effect from "effect/Effect";
9
import * as Schema from "effect/Schema";
10
+import * as Semaphore from "effect/Semaphore";
11
import { AppState, Platform } from "react-native";
12
import type { EnvironmentId } from "@t3tools/contracts";
13
import {
@@ -72,7 +73,12 @@ export class AgentAwarenessOperationError extends Schema.TaggedError<AgentAwaren
73
}
74
75
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
75
-const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
76
+// Keyed by ActivityKit id: getAgentLiveActivities() wraps the same native
77
+// activity in a new object on every call. The relay keeps only the latest token
78
+// a device registers, so each activity's token reads and registrations run one
79
+// at a time; otherwise a lookup that read the old token could land after the
80
+// rotated one.
81
+const activityPushTokenLocks = new Map<string, Semaphore.Semaphore>();
82
// But the registration is not a pure no-op: the relay replays the current
83
// aggregate to this device on every accepted registration, and that replay is
84
// the foreground reconciliation that repairs drifted or orphaned activities.
@@ -893,6 +899,7 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
899
androidDeviceReplayedAt = null;
900
registrationStatusListeners.clear();
901
registeredActivityPushTokens.clear();
902
+ activityPushTokenLocks.clear();
903
}
904
905
export function unregisterAgentAwarenessDeviceForCurrentUser(
@@ -928,52 +935,53 @@ export function registerLiveActivityPushToken(input: {
935
return false;
936
}
937
931
- const activityPushToken = yield* Effect.tryPromise({
932
- try: () => input.activity.getPushToken(),
933
- catch: (cause) =>
934
- new AgentAwarenessOperationError({
935
- operation: "read-live-activity-push-token",
936
- cause,
937
- }),
938
- });
939
- if (!activityPushToken) {
940
- if (activityPushTokenListeners.has(input.activity)) {
941
- logRegistrationDebug(
942
- "live activity push token not available yet; token listener already registered",
943
- {
944
- connectionCount: environmentConnections.size,
945
- },
946
- );
947
- return false;
948
- }
949
-
950
- logRegistrationDebug(
951
- "live activity push token not available yet; listening for token event",
952
- {
953
- connectionCount: environmentConnections.size,
954
- },
955
- );
956
- activityPushTokenListeners.add(input.activity);
957
- input.activity.addPushTokenListener((event) => {
958
- if (event.pushToken) {
959
- logRegistrationDebug("live activity push token event received", {
960
- tokenSuffix: event.pushToken.slice(-8),
961
- });
962
- runRegistrationInBackground(
963
- registerLiveActivityPushTokenValue({
964
- activityPushToken: event.pushToken,
938
+ const lock = observeLiveActivityPushTokens(input.activity);
939
+ return yield* lock.withPermit(
940
+ Effect.gen(function* () {
941
+ const activityPushToken = yield* Effect.tryPromise({
942
+ try: () => input.activity.getPushToken(),
943
+ catch: (cause) =>
944
+ new AgentAwarenessOperationError({
945
+ operation: "read-live-activity-push-token",
946
+ cause,
947
}),
966
- "live activity token listener registration failed",
948
+ });
949
+ if (!activityPushToken) {
950
+ logRegistrationDebug(
951
+ "live activity push token not available yet; waiting for token event",
952
+ { connectionCount: environmentConnections.size },
953
);
954
+ return false;
955
}
969
- });
970
- return false;
971
- }
956
973
- return yield* registerLiveActivityPushTokenValue({
974
- activityPushToken,
957
+ return yield* registerLiveActivityPushTokenValue({ activityPushToken });
958
+ }),
959
+ );
960
+ });
961
+}
962
+
963
+// iOS can replace an activity's push token while it runs, not only deliver a
964
+// late first one. The relay keeps pushing to the old token until APNs rejects
965
+// it, so every activity needs a listener that registers each new token.
966
+function observeLiveActivityPushTokens(
967
+ activity: LiveActivity<AgentActivityProps>,
968
+): Semaphore.Semaphore {
969
+ const activityId = activity.getId();
970
+ const existing = activityPushTokenLocks.get(activityId);
971
+ if (existing) return existing;
972
+ const lock = Semaphore.makeUnsafe(1);
973
+ activityPushTokenLocks.set(activityId, lock);
974
+ activity.addPushTokenListener((event) => {
975
+ if (!event.pushToken) return;
976
+ logRegistrationDebug("live activity push token event received", {
977
+ tokenSuffix: event.pushToken.slice(-8),
978
});
979
+ runRegistrationInBackground(
980
+ lock.withPermit(registerLiveActivityPushTokenValue({ activityPushToken: event.pushToken })),
981
+ "live activity token listener registration failed",
982
+ );
983
});
984
+ return lock;
985
}
986
987
function registerLiveActivityPushTokenValue(input: {