Skip to content

Commit 5a1c6d9

Browse files
T3 Code Testclaude
andcommitted
fix(mobile): iOS Agent Activity widget renders instead of a blank tile
The home-screen widget was declared in the widget extension, but the app only registered the Live Activity layout and never published widget data, so the widget stayed blank forever. Register a home-screen layout with createWidget, embed it so it renders before the first launch, and repaint it from the relay snapshot the foreground refresh already reads. Unfinished rows go out of date after 10 minutes, sign-out shows a sign-in prompt, and a failed read never claims a signed-in user is signed out. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 1451e7c commit 5a1c6d9

9 files changed

Lines changed: 547 additions & 12 deletions

‎apps/mobile/app.config.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,12 @@ const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
185185
displayName: "Agent Activity",
186186
description: "Shows the current state of active T3 Code agents.",
187187
android: null,
188-
ios: { supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"] },
188+
ios: {
189+
supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
190+
// Embeds the layout so the gallery preview and a new widget render
191+
// before the app has run once; the app replaces it on publish.
192+
initialLayout: "./src/widgets/AgentActivityWidget.tsx",
193+
},
189194
},
190195
],
191196
},

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

Lines changed: 143 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,15 @@ import { describe, expect, it } from "@effect/vitest";
77
import Constants from "expo-constants";
88
import * as Cause from "effect/Cause";
99
import * as Effect from "effect/Effect";
10+
import * as Deferred from "effect/Deferred";
1011
import * as Exit from "effect/Exit";
1112
import * as Fiber from "effect/Fiber";
1213
import * as Layer from "effect/Layer";
1314
import { Cookies, FetchHttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
1415
import { ManagedRelay } from "@t3tools/client-runtime/relay";
1516

16-
import type { EnvironmentId } from "@t3tools/contracts";
17+
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
18+
import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
1719
import { verifyDpopProof } from "@t3tools/shared/dpop";
1820
import type { SavedRemoteConnection } from "../../lib/connection";
1921
import * as Dpop from "../cloud/dpop";
@@ -61,6 +63,7 @@ const widgetMocks = vi.hoisted(() => ({
6163
getInstances: vi.fn(() => []),
6264
start: vi.fn(() => ({})),
6365
}));
66+
const publishWidgetMock = vi.hoisted(() => vi.fn((_source: unknown) => Promise.resolve()));
6467
const environmentConfigsMock = vi.hoisted(() => ({
6568
configs: new Map<
6669
string,
@@ -97,6 +100,10 @@ vi.mock("expo-widgets", () => ({
97100
addPushToStartTokenListener: vi.fn(() => ({ remove: vi.fn() })),
98101
}));
99102

103+
vi.mock("../../widgets/publishAgentActivityWidget", () => ({
104+
publishAgentActivityWidget: publishWidgetMock,
105+
}));
106+
100107
vi.mock("./agentLiveActivity", () => ({
101108
getAgentLiveActivities: widgetMocks.getInstances,
102109
startAgentLiveActivity: widgetMocks.start,
@@ -271,6 +278,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
271278
widgetMocks.getInstances.mockReset();
272279
widgetMocks.getInstances.mockReturnValue([]);
273280
widgetMocks.start.mockClear();
281+
publishWidgetMock.mockClear();
274282
environmentConfigsMock.configs.clear();
275283
});
276284

@@ -680,12 +688,14 @@ describe("makeRelayDeviceRegistrationRequest", () => {
680688
return Effect.gen(function* () {
681689
yield* runBackgroundOperations();
682690

683-
expect(fetchMock).toHaveBeenCalledTimes(2);
684-
const [request, init] = fetchMock.mock.calls[1] as unknown as [
685-
unknown,
686-
RequestInit | undefined,
687-
];
688-
const url = request instanceof Request ? request.url : String(request);
691+
const requestUrl = (request: unknown) =>
692+
request instanceof Request ? request.url : String(request);
693+
const deviceCalls = fetchMock.mock.calls.filter(([request]) =>
694+
requestUrl(request).endsWith("/v1/mobile/devices"),
695+
);
696+
expect(deviceCalls).toHaveLength(1);
697+
const [request, init] = deviceCalls[0] as unknown as [unknown, RequestInit | undefined];
698+
const url = requestUrl(request);
689699
const method = request instanceof Request ? request.method : init?.method;
690700
const headers = request instanceof Request ? request.headers : new Headers(init?.headers);
691701
const dpop = headers.get("dpop");
@@ -905,9 +915,12 @@ describe("makeRelayDeviceRegistrationRequest", () => {
905915
},
906916
};
907917

918+
// Sign-in first reads the widget snapshot, then registers the device; fail
919+
// both lookups so the queued registration is the one that must recover.
908920
const tokenProvider = vi
909921
.fn<() => Promise<string | null>>()
910922
.mockRejectedValueOnce(new Error("auth unavailable"))
923+
.mockRejectedValueOnce(new Error("auth unavailable"))
911924
.mockResolvedValue("clerk-token-user-a");
912925
setAgentAwarenessRelayTokenProvider(tokenProvider);
913926
const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
@@ -918,7 +931,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
918931
yield* runBackgroundOperations();
919932

920933
expect(backgroundRuntime.pending).toHaveLength(0);
921-
expect(tokenProvider).toHaveBeenCalledTimes(2);
934+
expect(tokenProvider).toHaveBeenCalledTimes(3);
922935
}).pipe(Effect.provide(layerRelayTest));
923936
});
924937

@@ -1249,4 +1262,126 @@ describe("makeRelayDeviceRegistrationRequest", () => {
12491262
}).pipe(Effect.provide(layerRelayTest));
12501263
},
12511264
);
1265+
1266+
describe("home-screen widget", () => {
1267+
// These cover the widget path only, so keep the Live Activity from priming.
1268+
beforeEach(() => {
1269+
vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: false } as Preferences);
1270+
});
1271+
1272+
const aggregate: RelayAgentActivityAggregateState = {
1273+
title: "T3 Code",
1274+
subtitle: "Agent work in progress",
1275+
activeCount: 1,
1276+
updatedAt: "2026-10-18T10:00:00.000Z",
1277+
activities: [
1278+
{
1279+
environmentId: "env-1" as EnvironmentId,
1280+
threadId: "thread-1" as ThreadId,
1281+
projectTitle: "t3code",
1282+
threadTitle: "Fix the widget",
1283+
modelTitle: "GPT-5.5",
1284+
phase: "running",
1285+
status: "Working",
1286+
updatedAt: "2026-10-18T10:00:00.000Z",
1287+
deepLink: "/threads/env-1/thread-1",
1288+
},
1289+
],
1290+
};
1291+
1292+
// The shared fetch-backed relay layer keeps the first test's fetch stub,
1293+
// so these tests answer the snapshot read through a fake client instead.
1294+
function fakeRelay(
1295+
getAgentActivitySnapshot: () => Effect.Effect<
1296+
{ readonly aggregate: typeof aggregate },
1297+
ManagedRelay.ManagedRelayRequestFailedError
1298+
>,
1299+
) {
1300+
Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
1301+
const unexpected = () => Effect.die("Unexpected relay request");
1302+
return Layer.succeed(
1303+
ManagedRelay.ManagedRelayClient,
1304+
ManagedRelay.ManagedRelayClient.of({
1305+
relayUrl: "https://relay.example.test",
1306+
listEnvironments: unexpected,
1307+
listDevices: unexpected,
1308+
createEnvironmentLinkChallenge: unexpected,
1309+
linkEnvironment: unexpected,
1310+
unlinkEnvironment: unexpected,
1311+
getEnvironmentStatus: unexpected,
1312+
connectEnvironment: unexpected,
1313+
registerDevice: unexpected,
1314+
unregisterDevice: unexpected,
1315+
registerLiveActivity: unexpected,
1316+
getAgentActivitySnapshot,
1317+
resetTokenCache: Effect.void,
1318+
}),
1319+
);
1320+
}
1321+
1322+
it.effect("repaints from the relay snapshot when activity is reconciled", () => {
1323+
const relay = fakeRelay(() => Effect.succeed({ aggregate }));
1324+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1325+
1326+
return Effect.gen(function* () {
1327+
yield* refreshActiveLiveActivityRemoteRegistration();
1328+
1329+
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "snapshot", aggregate });
1330+
}).pipe(Effect.provide(relay));
1331+
});
1332+
1333+
it.effect("keeps the last rows when a later read fails, but never the signed-out state", () => {
1334+
const relayDown = new ManagedRelay.ManagedRelayRequestFailedError({
1335+
action: "read relay agent activity snapshot",
1336+
transportFailed: true,
1337+
cause: new Error("relay down"),
1338+
});
1339+
let relayUp = false;
1340+
const relay = fakeRelay(() =>
1341+
relayUp ? Effect.succeed({ aggregate }) : Effect.fail(relayDown),
1342+
);
1343+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1344+
1345+
return Effect.gen(function* () {
1346+
yield* refreshActiveLiveActivityRemoteRegistration();
1347+
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "unavailable" });
1348+
1349+
relayUp = true;
1350+
yield* refreshActiveLiveActivityRemoteRegistration();
1351+
relayUp = false;
1352+
publishWidgetMock.mockClear();
1353+
yield* refreshActiveLiveActivityRemoteRegistration();
1354+
expect(publishWidgetMock).not.toHaveBeenCalled();
1355+
}).pipe(Effect.provide(relay));
1356+
});
1357+
1358+
it("shows the signed-out state after cloud sign-out", () => {
1359+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1360+
1361+
setAgentAwarenessRelayTokenProvider(null);
1362+
1363+
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "signed-out" });
1364+
});
1365+
1366+
it.effect("drops a snapshot that arrives after the account changed", () =>
1367+
Effect.gen(function* () {
1368+
const requested = yield* Deferred.make<void>();
1369+
const response = yield* Deferred.make<{ readonly aggregate: typeof aggregate }>();
1370+
const relay = fakeRelay(() =>
1371+
Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(response))),
1372+
);
1373+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
1374+
1375+
const refresh = yield* Effect.forkChild(
1376+
refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
1377+
);
1378+
yield* Deferred.await(requested);
1379+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-b"), "user-b");
1380+
yield* Deferred.succeed(response, { aggregate });
1381+
yield* Fiber.join(refresh);
1382+
1383+
expect(publishWidgetMock).not.toHaveBeenCalledWith({ kind: "snapshot", aggregate });
1384+
}),
1385+
);
1386+
});
12521387
});

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

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ import {
3737
saveAgentAwarenessRegistrationRecord,
3838
} from "../../persistence/imperative";
3939
import type { AgentActivityProps } from "../../widgets/AgentActivity";
40+
import type { AgentActivityWidgetSource } from "../../widgets/agentActivityWidgetTimeline";
41+
import { publishAgentActivityWidget } from "../../widgets/publishAgentActivityWidget";
4042
import { getAgentLiveActivities, startAgentLiveActivity } from "./agentLiveActivity";
4143
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
4244
import { supportsAgentAwarenessPush } from "./capabilities";
@@ -89,6 +91,9 @@ const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000;
8991
const LIVE_ACTIVITY_STALE_AFTER_MS = 10 * 60_000;
9092
const liveActivityStaleDate = () => new Date(Date.now() + LIVE_ACTIVITY_STALE_AFTER_MS);
9193
const registeredActivityPushTokens = new Map<string, number>();
94+
// A failed read keeps the current account's last rows, but must not leave the
95+
// widget claiming the user is signed out or showing a previous account.
96+
let widgetShowsCurrentAccount = false;
9297
let androidDeviceReplayedAt: number | null = null;
9398
let pushTokenSubscription: { remove: () => void } | null = null;
9499
let appStateSubscription: { remove: () => void } | null = null;
@@ -188,6 +193,7 @@ export function setAgentAwarenessRelayTokenProvider(
188193
activeDeviceRegistration = null;
189194
pendingDeviceRegistration = null;
190195
registeredActivityPushTokens.clear();
196+
widgetShowsCurrentAccount = false;
191197
}
192198
relayTokenProvider = provider;
193199
relayTokenProviderIdentity = provider ? (identity ?? null) : null;
@@ -204,6 +210,7 @@ export function setAgentAwarenessRelayTokenProvider(
204210
// Without a signed-in user the relay can no longer update or end these
205211
// activities, so they would sit orphaned on the lock screen.
206212
endLocalLiveActivities("live activity cleanup after cloud sign-out failed");
213+
publishWidget({ kind: "signed-out" });
207214
setRegistrationStatus("unknown");
208215
void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => {
209216
logRegistrationError("clear registration record on sign-out failed", error);
@@ -810,6 +817,15 @@ function ensureAppStateListener(): void {
810817
});
811818
}
812819

820+
function publishWidget(source: AgentActivityWidgetSource): void {
821+
if (!canRegisterRemoteLiveActivities()) {
822+
return;
823+
}
824+
publishAgentActivityWidget(source).catch((error: unknown) => {
825+
logRegistrationError("agent activity widget publish failed", error);
826+
});
827+
}
828+
813829
function endLocalLiveActivities(context: string): void {
814830
if (!canRegisterRemoteLiveActivities()) {
815831
return;
@@ -900,6 +916,7 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
900916
registrationStatusListeners.clear();
901917
registeredActivityPushTokens.clear();
902918
activityPushTokenLocks.clear();
919+
widgetShowsCurrentAccount = false;
903920
}
904921

905922
export function unregisterAgentAwarenessDeviceForCurrentUser(
@@ -1041,6 +1058,20 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
10411058
return;
10421059
}
10431060

1061+
// The home-screen widget has no push path of its own, so every foreground
1062+
// refresh repaints it from the same snapshot that primes the Live Activity.
1063+
const identity = relayTokenProviderIdentity;
1064+
const snapshot = yield* readAgentActivitySnapshot();
1065+
if (!relayTokenProvider || relayTokenProviderIdentity !== identity) {
1066+
return;
1067+
}
1068+
if (snapshot) {
1069+
widgetShowsCurrentAccount = true;
1070+
publishWidget({ kind: "snapshot", aggregate: snapshot.aggregate });
1071+
} else if (!widgetShowsCurrentAccount) {
1072+
publishWidget({ kind: "unavailable" });
1073+
}
1074+
10441075
let activities = yield* Effect.try({
10451076
try: () => getAgentLiveActivities(),
10461077
catch: (cause) =>
@@ -1082,9 +1113,8 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
10821113
}),
10831114
}).pipe(Effect.orElseSucceed(() => null));
10841115
if (preferences?.liveActivitiesEnabled !== false) {
1085-
const snapshot = yield* readAgentActivitySnapshot();
1086-
// The snapshot request yields; an arm-on-send may have created the
1087-
// card in the meantime. Re-check so two cards are never started.
1116+
// Loading preferences yields; an arm-on-send may have created the card
1117+
// in the meantime. Re-check so two cards are never started.
10881118
const armedMeanwhile = yield* Effect.try({
10891119
try: () => getAgentLiveActivities(),
10901120
catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,

0 commit comments

Comments
 (0)