Skip to content

Commit 8eca298

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 9c16146 commit 8eca298

9 files changed

Lines changed: 543 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: 139 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +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";
12+
import * as Fiber from "effect/Fiber";
1113
import * as Layer from "effect/Layer";
1214
import { Cookies, FetchHttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
1315
import { ManagedRelay } from "@t3tools/client-runtime/relay";
1416

15-
import type { EnvironmentId } from "@t3tools/contracts";
17+
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
18+
import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
1619
import { verifyDpopProof } from "@t3tools/shared/dpop";
1720
import type { SavedRemoteConnection } from "../../lib/connection";
1821
import * as Dpop from "../cloud/dpop";
@@ -60,6 +63,7 @@ const widgetMocks = vi.hoisted(() => ({
6063
getInstances: vi.fn(() => []),
6164
start: vi.fn(() => ({})),
6265
}));
66+
const publishWidgetMock = vi.hoisted(() => vi.fn((_source: unknown) => Promise.resolve()));
6367
const environmentConfigsMock = vi.hoisted(() => ({
6468
configs: new Map<
6569
string,
@@ -96,6 +100,10 @@ vi.mock("expo-widgets", () => ({
96100
addPushToStartTokenListener: vi.fn(() => ({ remove: vi.fn() })),
97101
}));
98102

103+
vi.mock("../../widgets/publishAgentActivityWidget", () => ({
104+
publishAgentActivityWidget: publishWidgetMock,
105+
}));
106+
99107
vi.mock("./agentLiveActivity", () => ({
100108
getAgentLiveActivities: widgetMocks.getInstances,
101109
startAgentLiveActivity: widgetMocks.start,
@@ -270,6 +278,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
270278
widgetMocks.getInstances.mockReset();
271279
widgetMocks.getInstances.mockReturnValue([]);
272280
widgetMocks.start.mockClear();
281+
publishWidgetMock.mockClear();
273282
environmentConfigsMock.configs.clear();
274283
});
275284

@@ -557,12 +566,14 @@ describe("makeRelayDeviceRegistrationRequest", () => {
557566
return Effect.gen(function* () {
558567
yield* runBackgroundOperations();
559568

560-
expect(fetchMock).toHaveBeenCalledTimes(2);
561-
const [request, init] = fetchMock.mock.calls[1] as unknown as [
562-
unknown,
563-
RequestInit | undefined,
564-
];
565-
const url = request instanceof Request ? request.url : String(request);
569+
const requestUrl = (request: unknown) =>
570+
request instanceof Request ? request.url : String(request);
571+
const deviceCalls = fetchMock.mock.calls.filter(([request]) =>
572+
requestUrl(request).endsWith("/v1/mobile/devices"),
573+
);
574+
expect(deviceCalls).toHaveLength(1);
575+
const [request, init] = deviceCalls[0] as unknown as [unknown, RequestInit | undefined];
576+
const url = requestUrl(request);
566577
const method = request instanceof Request ? request.method : init?.method;
567578
const headers = request instanceof Request ? request.headers : new Headers(init?.headers);
568579
const dpop = headers.get("dpop");
@@ -780,9 +791,12 @@ describe("makeRelayDeviceRegistrationRequest", () => {
780791
},
781792
};
782793

794+
// Sign-in first reads the widget snapshot, then registers the device; fail
795+
// both lookups so the queued registration is the one that must recover.
783796
const tokenProvider = vi
784797
.fn<() => Promise<string | null>>()
785798
.mockRejectedValueOnce(new Error("auth unavailable"))
799+
.mockRejectedValueOnce(new Error("auth unavailable"))
786800
.mockResolvedValue("clerk-token-user-a");
787801
setAgentAwarenessRelayTokenProvider(tokenProvider);
788802
const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
@@ -793,7 +807,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
793807
yield* runBackgroundOperations();
794808

795809
expect(backgroundRuntime.pending).toHaveLength(0);
796-
expect(tokenProvider).toHaveBeenCalledTimes(2);
810+
expect(tokenProvider).toHaveBeenCalledTimes(3);
797811
}).pipe(Effect.provide(layerRelayTest));
798812
});
799813

@@ -1124,4 +1138,121 @@ describe("makeRelayDeviceRegistrationRequest", () => {
11241138
}).pipe(Effect.provide(layerRelayTest));
11251139
},
11261140
);
1141+
1142+
describe("home-screen widget", () => {
1143+
const aggregate: RelayAgentActivityAggregateState = {
1144+
title: "T3 Code",
1145+
subtitle: "Agent work in progress",
1146+
activeCount: 1,
1147+
updatedAt: "2026-10-18T10:00:00.000Z",
1148+
activities: [
1149+
{
1150+
environmentId: "env-1" as EnvironmentId,
1151+
threadId: "thread-1" as ThreadId,
1152+
projectTitle: "t3code",
1153+
threadTitle: "Fix the widget",
1154+
modelTitle: "GPT-5.5",
1155+
phase: "running",
1156+
status: "Working",
1157+
updatedAt: "2026-10-18T10:00:00.000Z",
1158+
deepLink: "/threads/env-1/thread-1",
1159+
},
1160+
],
1161+
};
1162+
1163+
// The shared fetch-backed relay layer keeps the first test's fetch stub,
1164+
// so these tests answer the snapshot read through a fake client instead.
1165+
function fakeRelay(
1166+
getAgentActivitySnapshot: () => Effect.Effect<
1167+
{ readonly aggregate: typeof aggregate },
1168+
ManagedRelay.ManagedRelayRequestFailedError
1169+
>,
1170+
) {
1171+
Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
1172+
const unexpected = () => Effect.die("Unexpected relay request");
1173+
return Layer.succeed(
1174+
ManagedRelay.ManagedRelayClient,
1175+
ManagedRelay.ManagedRelayClient.of({
1176+
relayUrl: "https://relay.example.test",
1177+
listEnvironments: unexpected,
1178+
listDevices: unexpected,
1179+
createEnvironmentLinkChallenge: unexpected,
1180+
linkEnvironment: unexpected,
1181+
unlinkEnvironment: unexpected,
1182+
getEnvironmentStatus: unexpected,
1183+
connectEnvironment: unexpected,
1184+
registerDevice: unexpected,
1185+
unregisterDevice: unexpected,
1186+
registerLiveActivity: unexpected,
1187+
getAgentActivitySnapshot,
1188+
resetTokenCache: Effect.void,
1189+
}),
1190+
);
1191+
}
1192+
1193+
it.effect("repaints from the relay snapshot when activity is reconciled", () => {
1194+
const relay = fakeRelay(() => Effect.succeed({ aggregate }));
1195+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1196+
1197+
return Effect.gen(function* () {
1198+
yield* refreshActiveLiveActivityRemoteRegistration();
1199+
1200+
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "snapshot", aggregate });
1201+
}).pipe(Effect.provide(relay));
1202+
});
1203+
1204+
it.effect("keeps the last rows when a later read fails, but never the signed-out state", () => {
1205+
const relayDown = new ManagedRelay.ManagedRelayRequestFailedError({
1206+
action: "read relay agent activity snapshot",
1207+
transportFailed: true,
1208+
cause: new Error("relay down"),
1209+
});
1210+
let relayUp = false;
1211+
const relay = fakeRelay(() =>
1212+
relayUp ? Effect.succeed({ aggregate }) : Effect.fail(relayDown),
1213+
);
1214+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1215+
1216+
return Effect.gen(function* () {
1217+
yield* refreshActiveLiveActivityRemoteRegistration();
1218+
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "unavailable" });
1219+
1220+
relayUp = true;
1221+
yield* refreshActiveLiveActivityRemoteRegistration();
1222+
relayUp = false;
1223+
publishWidgetMock.mockClear();
1224+
yield* refreshActiveLiveActivityRemoteRegistration();
1225+
expect(publishWidgetMock).not.toHaveBeenCalled();
1226+
}).pipe(Effect.provide(relay));
1227+
});
1228+
1229+
it("shows the signed-out state after cloud sign-out", () => {
1230+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
1231+
1232+
setAgentAwarenessRelayTokenProvider(null);
1233+
1234+
expect(publishWidgetMock).toHaveBeenLastCalledWith({ kind: "signed-out" });
1235+
});
1236+
1237+
it.effect("drops a snapshot that arrives after the account changed", () =>
1238+
Effect.gen(function* () {
1239+
const requested = yield* Deferred.make<void>();
1240+
const response = yield* Deferred.make<{ readonly aggregate: typeof aggregate }>();
1241+
const relay = fakeRelay(() =>
1242+
Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(response))),
1243+
);
1244+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
1245+
1246+
const refresh = yield* Effect.forkChild(
1247+
refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
1248+
);
1249+
yield* Deferred.await(requested);
1250+
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-b"), "user-b");
1251+
yield* Deferred.succeed(response, { aggregate });
1252+
yield* Fiber.join(refresh);
1253+
1254+
expect(publishWidgetMock).not.toHaveBeenCalledWith({ kind: "snapshot", aggregate });
1255+
}),
1256+
);
1257+
});
11271258
});

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

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ import {
3636
saveAgentAwarenessRegistrationRecord,
3737
} from "../../persistence/imperative";
3838
import type { AgentActivityProps } from "../../widgets/AgentActivity";
39+
import type { AgentActivityWidgetSource } from "../../widgets/agentActivityWidgetTimeline";
40+
import { publishAgentActivityWidget } from "../../widgets/publishAgentActivityWidget";
3941
import { getAgentLiveActivities, startAgentLiveActivity } from "./agentLiveActivity";
4042
import { resolveCloudPublicConfig } from "../cloud/publicConfig";
4143
import { supportsAgentAwarenessPush } from "./capabilities";
@@ -83,6 +85,9 @@ const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000;
8385
const LIVE_ACTIVITY_STALE_AFTER_MS = 10 * 60_000;
8486
const liveActivityStaleDate = () => new Date(Date.now() + LIVE_ACTIVITY_STALE_AFTER_MS);
8587
const registeredActivityPushTokens = new Map<string, number>();
88+
// A failed read keeps the current account's last rows, but must not leave the
89+
// widget claiming the user is signed out or showing a previous account.
90+
let widgetShowsCurrentAccount = false;
8691
let androidDeviceReplayedAt: number | null = null;
8792
let pushTokenSubscription: { remove: () => void } | null = null;
8893
let appStateSubscription: { remove: () => void } | null = null;
@@ -182,6 +187,7 @@ export function setAgentAwarenessRelayTokenProvider(
182187
activeDeviceRegistration = null;
183188
pendingDeviceRegistration = null;
184189
registeredActivityPushTokens.clear();
190+
widgetShowsCurrentAccount = false;
185191
}
186192
relayTokenProvider = provider;
187193
relayTokenProviderIdentity = provider ? (identity ?? null) : null;
@@ -198,6 +204,7 @@ export function setAgentAwarenessRelayTokenProvider(
198204
// Without a signed-in user the relay can no longer update or end these
199205
// activities, so they would sit orphaned on the lock screen.
200206
endLocalLiveActivities("live activity cleanup after cloud sign-out failed");
207+
publishWidget({ kind: "signed-out" });
201208
setRegistrationStatus("unknown");
202209
void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => {
203210
logRegistrationError("clear registration record on sign-out failed", error);
@@ -804,6 +811,15 @@ function ensureAppStateListener(): void {
804811
});
805812
}
806813

814+
function publishWidget(source: AgentActivityWidgetSource): void {
815+
if (!canRegisterRemoteLiveActivities()) {
816+
return;
817+
}
818+
publishAgentActivityWidget(source).catch((error: unknown) => {
819+
logRegistrationError("agent activity widget publish failed", error);
820+
});
821+
}
822+
807823
function endLocalLiveActivities(context: string): void {
808824
if (!canRegisterRemoteLiveActivities()) {
809825
return;
@@ -893,6 +909,7 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
893909
androidDeviceReplayedAt = null;
894910
registrationStatusListeners.clear();
895911
registeredActivityPushTokens.clear();
912+
widgetShowsCurrentAccount = false;
896913
}
897914

898915
export function unregisterAgentAwarenessDeviceForCurrentUser(
@@ -1033,6 +1050,20 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
10331050
return;
10341051
}
10351052

1053+
// The home-screen widget has no push path of its own, so every foreground
1054+
// refresh repaints it from the same snapshot that primes the Live Activity.
1055+
const identity = relayTokenProviderIdentity;
1056+
const snapshot = yield* readAgentActivitySnapshot();
1057+
if (!relayTokenProvider || relayTokenProviderIdentity !== identity) {
1058+
return;
1059+
}
1060+
if (snapshot) {
1061+
widgetShowsCurrentAccount = true;
1062+
publishWidget({ kind: "snapshot", aggregate: snapshot.aggregate });
1063+
} else if (!widgetShowsCurrentAccount) {
1064+
publishWidget({ kind: "unavailable" });
1065+
}
1066+
10361067
let activities = yield* Effect.try({
10371068
try: () => getAgentLiveActivities(),
10381069
catch: (cause) =>
@@ -1074,9 +1105,8 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
10741105
}),
10751106
}).pipe(Effect.orElseSucceed(() => null));
10761107
if (preferences?.liveActivitiesEnabled !== false) {
1077-
const snapshot = yield* readAgentActivitySnapshot();
1078-
// The snapshot request yields; an arm-on-send may have created the
1079-
// card in the meantime. Re-check so two cards are never started.
1108+
// Loading preferences yields; an arm-on-send may have created the card
1109+
// in the meantime. Re-check so two cards are never started.
10801110
const armedMeanwhile = yield* Effect.try({
10811111
try: () => getAgentLiveActivities(),
10821112
catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,

0 commit comments

Comments
 (0)