Skip to content

Commit f070681

Browse files
shivamhwpclaude
andcommitted
fix(mobile): drop the widget's account cache and guard reads by registration generation
The widget now always shows loading/unavailable/signed-out placeholders instead of preserving cached rows, which removes the cold-start and account-ownership edge cases. Stale reads compare the device registration generation, so a sign-out and re-sign-in to the same account also drops the old read. Trimmed tests to the race guards and stale timeline. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e34eaaf commit f070681

6 files changed

Lines changed: 27 additions & 263 deletions

File tree

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

Lines changed: 14 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -805,46 +805,6 @@ describe("makeRelayDeviceRegistrationRequest", () => {
805805
);
806806
}
807807

808-
it.effect("repaints from the relay snapshot when activity is reconciled", () => {
809-
const relay = fakeRelay(() => Effect.succeed({ aggregate }));
810-
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
811-
812-
return Effect.gen(function* () {
813-
yield* refreshActiveLiveActivityRemoteRegistration();
814-
815-
expect(publishWidgetMock).toHaveBeenLastCalledWith(
816-
{ kind: "snapshot", aggregate },
817-
"user-a",
818-
);
819-
}).pipe(Effect.provide(relay));
820-
});
821-
822-
it.effect("delegates failed reads to the account-aware native publisher", () => {
823-
const relayDown = new ManagedRelay.ManagedRelayRequestFailedError({
824-
action: "read relay agent activity snapshot",
825-
transportFailed: true,
826-
cause: new Error("relay down"),
827-
});
828-
let relayUp = false;
829-
const relay = fakeRelay(() =>
830-
relayUp ? Effect.succeed({ aggregate }) : Effect.fail(relayDown),
831-
);
832-
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
833-
834-
return Effect.gen(function* () {
835-
// After a cold start the persisted timeline may be a placeholder.
836-
yield* refreshActiveLiveActivityRemoteRegistration();
837-
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "unavailable" }, "user-a");
838-
839-
relayUp = true;
840-
yield* refreshActiveLiveActivityRemoteRegistration();
841-
relayUp = false;
842-
publishWidgetMock.mockClear();
843-
yield* refreshActiveLiveActivityRemoteRegistration();
844-
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "unavailable" }, "user-a");
845-
}).pipe(Effect.provide(relay));
846-
});
847-
848808
it.effect("registers an existing Live Activity before waiting on the widget read", () => {
849809
const order: Array<string> = [];
850810
const activity = {
@@ -868,10 +828,10 @@ describe("makeRelayDeviceRegistrationRequest", () => {
868828
yield* refreshActiveLiveActivityRemoteRegistration();
869829

870830
expect(order).toEqual(["push-token", "widget-snapshot"]);
871-
expect(publishWidgetMock).toHaveBeenLastCalledWith(
872-
{ kind: "snapshot", aggregate },
873-
"user-a",
874-
);
831+
expect(publishWidgetMock).toHaveBeenLastCalledWith({
832+
kind: "snapshot",
833+
aggregate,
834+
});
875835
}).pipe(Effect.provide(relay));
876836
});
877837

@@ -899,42 +859,13 @@ describe("makeRelayDeviceRegistrationRequest", () => {
899859
yield* Deferred.succeed(olderResponse, { aggregate });
900860
yield* Fiber.join(older);
901861

902-
expect(publishWidgetMock).toHaveBeenLastCalledWith(
903-
{ kind: "snapshot", aggregate: newer },
904-
"user-a",
905-
);
862+
expect(publishWidgetMock).toHaveBeenLastCalledWith({
863+
kind: "snapshot",
864+
aggregate: newer,
865+
});
906866
}),
907867
);
908868

909-
it("shows loading, not the sign-in prompt, while a switched account's first read runs", () => {
910-
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
911-
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "loading" }, "user-a");
912-
913-
// CloudAuthBridge deactivates the old account before activating the new one.
914-
setAgentAwarenessRelayTokenProvider(null);
915-
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-b"), "user-b");
916-
917-
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "loading" }, "user-b");
918-
});
919-
920-
it.effect("shows loading when another account signs in after a provider release", () => {
921-
const relay = fakeRelay(() => Effect.succeed({ aggregate }));
922-
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
923-
924-
return Effect.gen(function* () {
925-
yield* refreshActiveLiveActivityRemoteRegistration();
926-
927-
// The native publisher checks persisted ownership even on a same-account remount.
928-
releaseAgentAwarenessRelayTokenProvider();
929-
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
930-
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "loading" }, "user-a");
931-
932-
releaseAgentAwarenessRelayTokenProvider();
933-
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-b"), "user-b");
934-
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "loading" }, "user-b");
935-
}).pipe(Effect.provide(relay));
936-
});
937-
938869
it.effect("an obsolete refresh does not discard the next account's read", () =>
939870
Effect.gen(function* () {
940871
let markTokenRequested = () => {};
@@ -975,10 +906,10 @@ describe("makeRelayDeviceRegistrationRequest", () => {
975906
yield* Deferred.succeed(response, { aggregate });
976907
yield* Fiber.join(refreshB);
977908

978-
expect(publishWidgetMock).toHaveBeenLastCalledWith(
979-
{ kind: "snapshot", aggregate },
980-
"user-b",
981-
);
909+
expect(publishWidgetMock).toHaveBeenLastCalledWith({
910+
kind: "snapshot",
911+
aggregate,
912+
});
982913
}),
983914
);
984915

@@ -1014,14 +945,6 @@ describe("makeRelayDeviceRegistrationRequest", () => {
1014945
}),
1015946
);
1016947

1017-
it("shows the signed-out state after cloud sign-out", () => {
1018-
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1019-
1020-
setAgentAwarenessRelayTokenProvider(null);
1021-
1022-
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "signed-out" }, null);
1023-
});
1024-
1025948
it.effect("drops a snapshot that arrives after the account changed", () =>
1026949
Effect.gen(function* () {
1027950
const requested = yield* Deferred.make<void>();
@@ -1036,13 +959,11 @@ describe("makeRelayDeviceRegistrationRequest", () => {
1036959
);
1037960
yield* Deferred.await(requested);
1038961
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-b"), "user-b");
962+
publishWidgetMock.mockClear();
1039963
yield* Deferred.succeed(response, { aggregate });
1040964
yield* Fiber.join(refresh);
1041965

1042-
expect(publishWidgetMock).not.toHaveBeenCalledWith(
1043-
{ kind: "snapshot", aggregate },
1044-
"user-a",
1045-
);
966+
expect(publishWidgetMock).not.toHaveBeenCalled();
1046967
}),
1047968
);
1048969

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

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ export function setAgentAwarenessRelayTokenProvider(
187187
clearAndroidAgentNotifications();
188188
}
189189
if (provider) {
190-
publishWidget({ kind: "loading" }, identity ?? null);
190+
publishWidget({ kind: "loading" });
191191
}
192192
androidDeviceReplayedAt = null;
193193
deviceRegistrationGeneration++;
@@ -746,14 +746,11 @@ function ensureAppStateListener(): void {
746746
});
747747
}
748748

749-
function publishWidget(
750-
source: AgentActivityWidgetSource,
751-
accountId = relayTokenProviderIdentity,
752-
): void {
749+
function publishWidget(source: AgentActivityWidgetSource): void {
753750
if (!canRegisterRemoteLiveActivities()) {
754751
return;
755752
}
756-
publishAgentActivityWidget(source, accountId).catch((error: unknown) => {
753+
publishAgentActivityWidget(source).catch((error: unknown) => {
757754
logRegistrationError("agent activity widget publish failed", error);
758755
});
759756
}
@@ -966,9 +963,9 @@ export const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
966963
// refresh repaints it from one snapshot read. Yields undefined once the
967964
// account changed or a newer read started, so a stale result is never
968965
// shown or primed.
969-
const identity = relayTokenProviderIdentity;
966+
const generation = deviceRegistrationGeneration;
970967
const isCurrentAccount = () =>
971-
relayTokenProvider !== null && relayTokenProviderIdentity === identity;
968+
relayTokenProvider !== null && deviceRegistrationGeneration === generation;
972969
let read = 0;
973970
const isNewestRead = () => isCurrentAccount() && read === widgetSnapshotReads;
974971
const refreshWidget = Effect.gen(function* () {

‎apps/mobile/src/widgets/AgentActivityWidget.tsx‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import type {
2121
// It shares the Live Activity's name, but expo-widgets stores widget and Live
2222
// Activity layouts under different keys, so each needs its own registration.
2323
export function AgentActivityWidget(
24-
publishedProps: (Partial<AgentActivityProps> & { readonly accountId?: string }) | undefined,
24+
publishedProps: Partial<AgentActivityProps> | undefined,
2525
environment: WidgetEnvironment,
2626
) {
2727
"widget";
@@ -196,7 +196,4 @@ export function AgentActivityWidget(
196196
);
197197
}
198198

199-
export default createWidget<Partial<AgentActivityProps> & { readonly accountId?: string }>(
200-
"AgentActivity",
201-
AgentActivityWidget,
202-
);
199+
export default createWidget<Partial<AgentActivityProps>>("AgentActivity", AgentActivityWidget);
Lines changed: 1 addition & 125 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, expect, it, vi } from "vite-plus/test";
1+
import { describe, expect, it } from "vite-plus/test";
22

33
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
44
import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
@@ -7,11 +7,6 @@ import {
77
AGENT_ACTIVITY_WIDGET_STALE_AFTER_MS,
88
agentActivityWidgetTimeline,
99
} from "./agentActivityWidgetTimeline";
10-
import { publishAgentActivityWidget } from "./publishAgentActivityWidget.ios";
11-
12-
const nativeWidget = vi.hoisted(() => ({ getTimeline: vi.fn(), updateTimeline: vi.fn() }));
13-
vi.mock("expo", () => ({ requireOptionalNativeModule: () => ({}) }));
14-
vi.mock("./AgentActivityWidget", () => ({ default: nativeWidget }));
1510

1611
const now = Date.parse("2026-10-18T10:00:00.000Z");
1712

@@ -42,104 +37,6 @@ function aggregate(activities: ReadonlyArray<Row>): RelayAgentActivityAggregateS
4237
}
4338

4439
describe("agentActivityWidgetTimeline", () => {
45-
it("persists the snapshot owner and clears rows on sign-out", async () => {
46-
nativeWidget.updateTimeline.mockClear();
47-
await publishAgentActivityWidget(
48-
{ kind: "snapshot", aggregate: aggregate([row("running", "Working")]) },
49-
"user-a",
50-
);
51-
expect(nativeWidget.updateTimeline).toHaveBeenLastCalledWith([
52-
expect.objectContaining({ props: expect.objectContaining({ accountId: "user-a" }) }),
53-
expect.objectContaining({ props: expect.objectContaining({ accountId: "user-a" }) }),
54-
]);
55-
56-
await publishAgentActivityWidget({ kind: "signed-out" }, null);
57-
expect(nativeWidget.updateTimeline).toHaveBeenLastCalledWith([
58-
expect.objectContaining({
59-
props: expect.objectContaining({ activities: [] }),
60-
}),
61-
]);
62-
expect(nativeWidget.updateTimeline.mock.lastCall?.[0][0].props).not.toHaveProperty("accountId");
63-
});
64-
65-
it("keeps sign-out last when an earlier cached timeline read is delayed", async () => {
66-
let release = (_entries: unknown[]) => {};
67-
let requested = () => {};
68-
const started = new Promise<void>((resolve) => {
69-
requested = resolve;
70-
});
71-
nativeWidget.getTimeline.mockImplementationOnce(
72-
() =>
73-
new Promise((resolve) => {
74-
release = resolve;
75-
requested();
76-
}),
77-
);
78-
nativeWidget.updateTimeline.mockClear();
79-
80-
const loading = publishAgentActivityWidget({ kind: "loading" }, "user-a");
81-
await started;
82-
const signOut = publishAgentActivityWidget({ kind: "signed-out" }, null);
83-
release([]);
84-
await Promise.all([loading, signOut]);
85-
86-
expect(nativeWidget.updateTimeline).toHaveBeenLastCalledWith([
87-
expect.objectContaining({
88-
props: expect.objectContaining({
89-
subtitle: "Sign in to T3 Connect to see agents",
90-
activities: [],
91-
}),
92-
}),
93-
]);
94-
});
95-
96-
it("keeps persisted account rows and their stale deadline after a cold-start read failure", async () => {
97-
const cached = agentActivityWidgetTimeline(
98-
{ kind: "snapshot", aggregate: aggregate([row("running", "Working")]) },
99-
now,
100-
).map((entry) => ({ ...entry, props: { ...entry.props, accountId: "user-a" } }));
101-
nativeWidget.getTimeline.mockResolvedValue(cached);
102-
nativeWidget.updateTimeline.mockClear();
103-
104-
await publishAgentActivityWidget({ kind: "loading" }, "user-a");
105-
await publishAgentActivityWidget({ kind: "unavailable" }, "user-a");
106-
107-
expect(nativeWidget.updateTimeline).not.toHaveBeenCalled();
108-
});
109-
110-
it("replaces another account's persisted rows before its first relay read", async () => {
111-
nativeWidget.getTimeline.mockResolvedValue(
112-
agentActivityWidgetTimeline(
113-
{ kind: "snapshot", aggregate: aggregate([row("running", "Working")]) },
114-
now,
115-
).map((entry) => ({ ...entry, props: { ...entry.props, accountId: "user-a" } })),
116-
);
117-
nativeWidget.updateTimeline.mockClear();
118-
119-
await publishAgentActivityWidget({ kind: "loading" }, "user-b");
120-
121-
expect(nativeWidget.updateTimeline).toHaveBeenLastCalledWith([
122-
expect.objectContaining({
123-
props: expect.objectContaining({ subtitle: "Loading agents…", activities: [] }),
124-
}),
125-
]);
126-
});
127-
128-
it("replaces persisted placeholders after a failed relay read", async () => {
129-
nativeWidget.getTimeline.mockResolvedValue(
130-
agentActivityWidgetTimeline({ kind: "signed-out" }, now),
131-
);
132-
nativeWidget.updateTimeline.mockClear();
133-
134-
await publishAgentActivityWidget({ kind: "unavailable" }, "user-a");
135-
136-
expect(nativeWidget.updateTimeline).toHaveBeenLastCalledWith([
137-
expect.objectContaining({
138-
props: expect.objectContaining({ subtitle: "Couldn't reach T3 Connect", activities: [] }),
139-
}),
140-
]);
141-
});
142-
14340
it("marks unfinished rows out of date once the widget can no longer vouch for them", () => {
14441
const timeline = agentActivityWidgetTimeline(
14542
{
@@ -172,25 +69,4 @@ describe("agentActivityWidgetTimeline", () => {
17269
expect(timeline).toHaveLength(1);
17370
expect(timeline[0]?.props.activities[0]?.phase).toBe("failed");
17471
});
175-
176-
it("says no agents are active when the relay has no activity", () => {
177-
const [entry] = agentActivityWidgetTimeline({ kind: "snapshot", aggregate: null }, now);
178-
179-
expect(entry?.props).toMatchObject({ subtitle: "No active agents", activities: [] });
180-
});
181-
182-
it("asks the user to sign in instead of showing a previous account's agents", () => {
183-
const [entry] = agentActivityWidgetTimeline({ kind: "signed-out" }, now);
184-
185-
expect(entry?.props).toMatchObject({
186-
subtitle: "Sign in to T3 Connect to see agents",
187-
activities: [],
188-
});
189-
});
190-
191-
it("says T3 Connect is unreachable instead of asking a signed-in user to sign in", () => {
192-
const [entry] = agentActivityWidgetTimeline({ kind: "unavailable" }, now);
193-
194-
expect(entry?.props).toMatchObject({ subtitle: "Couldn't reach T3 Connect", activities: [] });
195-
});
19672
});

‎apps/mobile/src/widgets/publishAgentActivityWidget.ios.ts‎

Lines changed: 4 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,32 +5,8 @@ import {
55
type AgentActivityWidgetSource,
66
} from "./agentActivityWidgetTimeline";
77

8-
let publication = Promise.resolve();
9-
10-
export function publishAgentActivityWidget(
11-
source: AgentActivityWidgetSource,
12-
accountId: string | null,
13-
) {
14-
const next = publication.then(async () => {
15-
if (!requireOptionalNativeModule("ExpoWidgets")) return;
16-
const { default: widget } = await import("./AgentActivityWidget");
17-
if (accountId && (source.kind === "loading" || source.kind === "unavailable")) {
18-
const cached = await widget.getTimeline().catch(() => []);
19-
if (cached.some(({ props }) => props?.accountId === accountId && props.activities?.length)) {
20-
return;
21-
}
22-
}
23-
widget.updateTimeline(
24-
agentActivityWidgetTimeline(source, Date.now()).map((entry) => ({
25-
...entry,
26-
props: {
27-
...entry.props,
28-
...(source.kind === "snapshot" && accountId ? { accountId } : {}),
29-
},
30-
})),
31-
);
32-
});
33-
// Failed native writes must not prevent a later sign-out from clearing the timeline.
34-
publication = next.catch(() => {});
35-
return next;
8+
export async function publishAgentActivityWidget(source: AgentActivityWidgetSource) {
9+
if (!requireOptionalNativeModule("ExpoWidgets")) return;
10+
const { default: widget } = await import("./AgentActivityWidget");
11+
widget.updateTimeline(agentActivityWidgetTimeline(source, Date.now()));
3612
}

0 commit comments

Comments
 (0)