Skip to content

Commit 44f04ee

Browse files
Aidid Haiqalclaude
andcommitted
fix(mobile): Live Activities keep updating after iOS rotates their push token
iOS can replace a running Live Activity's push token at any time. The app only listened for new tokens when an activity had none at registration, so a rotated token never reached the relay and the card stopped updating until the app was opened again. Every activity now gets one listener, keyed by its ActivityKit id because each getInstances() call returns a new wrapper. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent ea97e8b commit 44f04ee

2 files changed

Lines changed: 87 additions & 36 deletions

File tree

‎apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts‎

Lines changed: 61 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -391,26 +391,75 @@ describe("makeRelayDeviceRegistrationRequest", () => {
391391
).toEqual({ liveActivitiesEnabled: true, baseFontSize: 18 });
392392
});
393393

394-
it.effect("registers at most one listener while a Live Activity push token is pending", () => {
394+
it.effect("registers one push-token listener per Live Activity across wrappers", () => {
395395
registerAgentAwarenessConnection(savedConnection());
396396
const addPushTokenListener = vi.fn();
397-
const activity = {
397+
// getInstances() returns a new wrapper for the same native activity each call.
398+
const wrapper = () => ({
399+
getId: () => "activity-1",
398400
getPushToken: vi.fn(() => Promise.resolve(null)),
399401
addPushTokenListener,
400-
};
402+
});
401403

402404
return Effect.gen(function* () {
403-
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
404-
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);
405+
expect(yield* registerLiveActivityPushToken({ activity: wrapper() as never })).toBe(false);
406+
expect(yield* registerLiveActivityPushToken({ activity: wrapper() as never })).toBe(false);
405407

406-
expect(activity.getPushToken).toHaveBeenCalledTimes(2);
407408
expect(addPushTokenListener).toHaveBeenCalledTimes(1);
408409
}).pipe(Effect.provide(layerRelayTest));
409410
});
410411

412+
it.effect("registers a Live Activity push token that rotates after registration", () => {
413+
const registeredTokens: Array<string> = [];
414+
vi.stubGlobal("fetch", async (request: RequestInfo | URL, init?: RequestInit) => {
415+
const url = request instanceof Request ? request.url : String(request);
416+
if (url.endsWith("/v1/client/dpop-token")) {
417+
return Response.json({
418+
access_token: "relay-dpop-token",
419+
issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
420+
token_type: "DPoP",
421+
expires_in: 300,
422+
scope: "mobile:registration",
423+
});
424+
}
425+
if (url.endsWith("/v1/mobile/live-activities")) {
426+
const body = request instanceof Request ? await request.text() : String(init?.body);
427+
registeredTokens.push(
428+
(JSON.parse(body) as { readonly activityPushToken: string }).activityPushToken,
429+
);
430+
}
431+
return Response.json({ ok: true });
432+
});
433+
Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
434+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
435+
let tokenListener: ((event: { readonly pushToken: string }) => void) | undefined;
436+
const activity = {
437+
getId: () => "activity-1",
438+
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
439+
addPushTokenListener: vi.fn((listener: typeof tokenListener) => {
440+
tokenListener = listener;
441+
return { remove: vi.fn() };
442+
}),
443+
};
444+
445+
return Effect.gen(function* () {
446+
yield* runBackgroundOperations();
447+
expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(true);
448+
449+
tokenListener?.({ pushToken: "rotated-activity-token" });
450+
yield* runBackgroundOperations();
451+
452+
expect(registeredTokens).toEqual(["activity-token", "rotated-activity-token"]);
453+
}).pipe(
454+
Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
455+
Effect.provide(layerRelayTest),
456+
);
457+
});
458+
411459
it.effect("preserves Live Activity push-token lookup failures", () => {
412460
const cause = new Error("native token lookup failed");
413461
const activity = {
462+
getId: () => "activity-1",
414463
getPushToken: vi.fn(() => Promise.reject(cause)),
415464
addPushTokenListener: vi.fn(),
416465
};
@@ -435,6 +484,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
435484
() => {
436485
registerAgentAwarenessConnection(savedConnection());
437486
const activity = {
487+
getId: () => "activity-1",
438488
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
439489
addPushTokenListener: vi.fn(),
440490
};
@@ -449,6 +499,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
449499
"registers APNS-started Live Activities for relay updates without mutating them locally",
450500
() => {
451501
const activity = {
502+
getId: () => "activity-1",
452503
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
453504
addPushTokenListener: vi.fn(),
454505
start: vi.fn(),
@@ -473,6 +524,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
473524
"re-registers active Live Activity tokens when the app returns to the foreground",
474525
() => {
475526
const activity = {
527+
getId: () => "activity-1",
476528
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
477529
addPushTokenListener: vi.fn(),
478530
};
@@ -502,6 +554,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
502554
it("ends local Live Activities and stops foreground reconciliation on cloud sign-out", () => {
503555
const end = vi.fn(() => Promise.resolve());
504556
const activity = {
557+
getId: () => "activity-1",
505558
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
506559
addPushTokenListener: vi.fn(),
507560
end,
@@ -613,6 +666,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
613666
it("releases the provider without ending activities or clearing the registration", () => {
614667
const end = vi.fn(() => Promise.resolve());
615668
const activity = {
669+
getId: () => "activity-1",
616670
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
617671
addPushTokenListener: vi.fn(),
618672
end,
@@ -708,6 +762,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
708762
},
709763
};
710764
const activity = {
765+
getId: () => "activity-1",
711766
getPushToken: vi.fn(() => Promise.resolve("activity-token")),
712767
addPushTokenListener: vi.fn(),
713768
};

‎apps/mobile/src/features/agent-awareness/remoteRegistration.ts‎

Lines changed: 26 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,9 @@ export class AgentAwarenessOperationError extends Schema.TaggedError<AgentAwaren
7272
}
7373

7474
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
75-
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
75+
// Keyed by ActivityKit id: getAgentLiveActivities() wraps the same native
76+
// activity in a new object on every call.
77+
const activityPushTokenListeners = new Set<string>();
7678
// But the registration is not a pure no-op: the relay replays the current
7779
// aggregate to this device on every accepted registration, and that replay is
7880
// the foreground reconciliation that repairs drifted or orphaned activities.
@@ -893,6 +895,7 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
893895
androidDeviceReplayedAt = null;
894896
registrationStatusListeners.clear();
895897
registeredActivityPushTokens.clear();
898+
activityPushTokenListeners.clear();
896899
}
897900

898901
export function unregisterAgentAwarenessDeviceForCurrentUser(
@@ -928,6 +931,7 @@ export function registerLiveActivityPushToken(input: {
928931
return false;
929932
}
930933

934+
observeLiveActivityPushTokens(input.activity);
931935
const activityPushToken = yield* Effect.tryPromise({
932936
try: () => input.activity.getPushToken(),
933937
catch: (cause) =>
@@ -937,35 +941,8 @@ export function registerLiveActivityPushToken(input: {
937941
}),
938942
});
939943
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,
965-
}),
966-
"live activity token listener registration failed",
967-
);
968-
}
944+
logRegistrationDebug("live activity push token not available yet; waiting for token event", {
945+
connectionCount: environmentConnections.size,
969946
});
970947
return false;
971948
}
@@ -976,6 +953,25 @@ export function registerLiveActivityPushToken(input: {
976953
});
977954
}
978955

956+
// iOS can replace an activity's push token while it runs, not only deliver a
957+
// late first one. The relay keeps pushing to the old token until APNs rejects
958+
// it, so every activity needs a listener that registers each new token.
959+
function observeLiveActivityPushTokens(activity: LiveActivity<AgentActivityProps>): void {
960+
const activityId = activity.getId();
961+
if (activityPushTokenListeners.has(activityId)) return;
962+
activityPushTokenListeners.add(activityId);
963+
activity.addPushTokenListener((event) => {
964+
if (!event.pushToken) return;
965+
logRegistrationDebug("live activity push token event received", {
966+
tokenSuffix: event.pushToken.slice(-8),
967+
});
968+
runRegistrationInBackground(
969+
registerLiveActivityPushTokenValue({ activityPushToken: event.pushToken }),
970+
"live activity token listener registration failed",
971+
);
972+
});
973+
}
974+
979975
function registerLiveActivityPushTokenValue(input: {
980976
readonly activityPushToken: string;
981977
}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {

0 commit comments

Comments
 (0)