The best way to control Claude Code, Codex and more from any computer or phone
fix(mobile): iOS Agent Activity widget shows your agents instead of a blank tile (#21163)
Co-authored-by: T3 Code Test <t3code-test@example.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: shivamhwp <shivamhwp@users.noreply.github.com> Co-authored-by: maria-rcks <maria@kuuro.net>
shivam committed
Nov 9, 2026 at 10:48 UTC
97c6773cc6797a28ea53927adf81d44644d818ee
9 files changed
+697
-13
apps/mobile/app.config.ts
+6
-1
@@ -195,7 +195,12 @@ const widgetsPlugin: NonNullable<ExpoConfig["plugins"]>[number] = [
195
displayName: "Agent Activity",
196
description: "Shows the current state of active T3 Code agents.",
197
android: null,
198
- ios: { supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"] },
198
+ ios: {
199
+ supportedFamilies: ["systemSmall", "systemMedium", "accessoryRectangular"],
200
+ // Embeds the layout so the gallery preview and a new widget render
201
+ // before the app has run once; the app replaces it on publish.
202
+ initialLayout: "./src/widgets/AgentActivityWidget.tsx",
203
+ },
204
},
205
],
206
},
apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
+275
-7
@@ -7,12 +7,15 @@ import { describe, expect, it } from "@effect/vitest";
7
import Constants from "expo-constants";
8
import * as Cause from "effect/Cause";
9
import * as Effect from "effect/Effect";
10
+import * as Deferred from "effect/Deferred";
11
import * as Exit from "effect/Exit";
12
import * as Fiber from "effect/Fiber";
13
import * as Layer from "effect/Layer";
14
import { Cookies, FetchHttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
15
import { ManagedRelay } from "@t3tools/client-runtime/relay";
16
17
+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
18
+import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
19
import { verifyDpopProof } from "@t3tools/shared/dpop";
20
import * as Dpop from "../cloud/dpop";
21
import * as ManagedRelayLayer from "../cloud/managedRelayLayer";
@@ -20,12 +23,15 @@ import {
23
clearAgentAwarenessRegistrationRecord,
24
loadAgentAwarenessRegistrationRecord,
25
loadOrCreateAgentAwarenessDeviceId,
26
+ loadPreferences,
27
saveAgentAwarenessRegistrationRecord,
28
} from "../../persistence/imperative";
29
+import type { Preferences } from "../../persistence/mobile-preferences";
30
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
31
import {
32
__resetAgentAwarenessRemoteRegistrationForTest,
33
getAgentAwarenessRegistrationStatus,
34
+ refreshActiveLiveActivityRemoteRegistration,
35
refreshAgentAwarenessRegistration,
36
registerLiveActivityPushToken,
37
releaseAgentAwarenessRelayTokenProvider,
@@ -49,6 +55,7 @@ const widgetMocks = vi.hoisted(() => ({
55
getInstances: vi.fn(() => []),
56
start: vi.fn(() => ({})),
57
}));
58
+const publishWidgetMock = vi.hoisted(() => vi.fn((_source: unknown) => Promise.resolve()));
59
const environmentConfigsMock = vi.hoisted(() => ({
60
configs: new Map<
61
string,
@@ -85,6 +92,10 @@ vi.mock("expo-widgets", () => ({
92
addPushToStartTokenListener: vi.fn(() => ({ remove: vi.fn() })),
93
}));
94
95
+vi.mock("../../widgets/publishAgentActivityWidget", () => ({
96
+ publishAgentActivityWidget: publishWidgetMock,
97
+}));
98
+
99
vi.mock("./agentLiveActivity", () => ({
100
dismissEndedAgentLiveActivities: widgetMocks.dismissEnded,
101
getAgentLiveActivities: widgetMocks.getInstances,
@@ -252,6 +263,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
263
widgetMocks.getInstances.mockReset();
264
widgetMocks.getInstances.mockReturnValue([]);
265
widgetMocks.start.mockClear();
266
+ publishWidgetMock.mockClear();
267
widgetMocks.dismissEnded.mockReset();
268
environmentConfigsMock.configs.clear();
269
});
@@ -520,12 +532,14 @@ describe("makeRelayDeviceRegistrationRequest", () => {
532
return Effect.gen(function* () {
533
yield* runBackgroundOperations();
534
523
- expect(fetchMock).toHaveBeenCalledTimes(2);
524
- const [request, init] = fetchMock.mock.calls[1] as unknown as [
525
- unknown,
526
- RequestInit | undefined,
527
- ];
528
- const url = request instanceof Request ? request.url : String(request);
535
+ const requestUrl = (request: unknown) =>
536
+ request instanceof Request ? request.url : String(request);
537
+ const deviceCalls = fetchMock.mock.calls.filter(([request]) =>
538
+ requestUrl(request).endsWith("/v1/mobile/devices"),
539
+ );
540
+ expect(deviceCalls).toHaveLength(1);
541
+ const [request, init] = deviceCalls[0] as unknown as [unknown, RequestInit | undefined];
542
+ const url = requestUrl(request);
543
const method = request instanceof Request ? request.method : init?.method;
544
const headers = request instanceof Request ? request.headers : new Headers(init?.headers);
545
const dpop = headers.get("dpop");
@@ -597,9 +611,12 @@ describe("makeRelayDeviceRegistrationRequest", () => {
611
},
612
};
613
614
+ // Sign-in first reads the widget snapshot, then registers the device; fail
615
+ // both lookups so the queued registration is the one that must recover.
616
const tokenProvider = vi
617
.fn<() => Promise<string | null>>()
618
.mockRejectedValueOnce(new Error("auth unavailable"))
619
+ .mockRejectedValueOnce(new Error("auth unavailable"))
620
.mockResolvedValue("clerk-token-user-a");
621
setAgentAwarenessRelayTokenProvider(tokenProvider);
622
const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];
@@ -610,7 +627,7 @@ describe("makeRelayDeviceRegistrationRequest", () => {
627
yield* runBackgroundOperations();
628
629
expect(backgroundRuntime.pending).toHaveLength(0);
613
- expect(tokenProvider).toHaveBeenCalledTimes(2);
630
+ expect(tokenProvider).toHaveBeenCalledTimes(3);
631
}).pipe(Effect.provide(layerRelayTest));
632
});
633
@@ -728,4 +745,255 @@ describe("makeRelayDeviceRegistrationRequest", () => {
745
}).pipe(Effect.provide(layerRelayTest));
746
},
747
);
748
+
749
+ describe("home-screen widget", () => {
750
+ // These cover the widget path only, so keep the Live Activity from priming.
751
+ beforeEach(() => {
752
+ vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: false } as Preferences);
753
+ });
754
+
755
+ const aggregate: RelayAgentActivityAggregateState = {
756
+ title: "T3 Code",
757
+ subtitle: "Agent work in progress",
758
+ activeCount: 1,
759
+ updatedAt: "2026-10-18T10:00:00.000Z",
760
+ activities: [
761
+ {
762
+ environmentId: "env-1" as EnvironmentId,
763
+ threadId: "thread-1" as ThreadId,
764
+ projectTitle: "t3code",
765
+ threadTitle: "Fix the widget",
766
+ modelTitle: "GPT-5.5",
767
+ phase: "running",
768
+ status: "Working",
769
+ updatedAt: "2026-10-18T10:00:00.000Z",
770
+ deepLink: "/threads/env-1/thread-1",
771
+ },
772
+ ],
773
+ };
774
+
775
+ // The shared fetch-backed relay layer keeps the first test's fetch stub,
776
+ // so these tests answer the snapshot read through a fake client instead.
777
+ function fakeRelay(
778
+ getAgentActivitySnapshot: () => Effect.Effect<
779
+ { readonly aggregate: typeof aggregate },
780
+ ManagedRelay.ManagedRelayRequestFailedError
781
+ >,
782
+ ) {
783
+ Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } };
784
+ const unexpected = () => Effect.die("Unexpected relay request");
785
+ return Layer.succeed(
786
+ ManagedRelay.ManagedRelayClient,
787
+ ManagedRelay.ManagedRelayClient.of({
788
+ relayUrl: "https://relay.example.test",
789
+ listEnvironments: unexpected,
790
+ listDevices: unexpected,
791
+ getT3ChatLink: unexpected,
792
+ createT3ChatLinkRequest: unexpected,
793
+ unlinkT3Chat: unexpected,
794
+ createEnvironmentLinkChallenge: unexpected,
795
+ linkEnvironment: unexpected,
796
+ unlinkEnvironment: unexpected,
797
+ getEnvironmentStatus: unexpected,
798
+ connectEnvironment: unexpected,
799
+ registerDevice: unexpected,
800
+ unregisterDevice: unexpected,
801
+ registerLiveActivity: unexpected,
802
+ getAgentActivitySnapshot,
803
+ resetTokenCache: Effect.void,
804
+ }),
805
+ );
806
+ }
807
+
808
+ it.effect("registers an existing Live Activity before waiting on the widget read", () => {
809
+ const order: Array<string> = [];
810
+ const activity = {
811
+ getId: () => "activity-1",
812
+ getPushToken: vi.fn(() => {
813
+ order.push("push-token");
814
+ return Promise.resolve(null);
815
+ }),
816
+ addPushTokenListener: vi.fn(),
817
+ };
818
+ widgetMocks.getInstances.mockReturnValue([activity] as never);
819
+ const relay = fakeRelay(() =>
820
+ Effect.sync(() => {
821
+ order.push("widget-snapshot");
822
+ return { aggregate };
823
+ }),
824
+ );
825
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
826
+
827
+ return Effect.gen(function* () {
828
+ yield* refreshActiveLiveActivityRemoteRegistration();
829
+
830
+ expect(order).toEqual(["push-token", "widget-snapshot"]);
831
+ expect(publishWidgetMock).toHaveBeenLastCalledWith({
832
+ kind: "snapshot",
833
+ aggregate,
834
+ });
835
+ }).pipe(Effect.provide(relay));
836
+ });
837
+
838
+ it.effect("keeps the newest rows when an older overlapping read finishes last", () =>
839
+ Effect.gen(function* () {
840
+ const newer = { ...aggregate, activeCount: 2 };
841
+ const olderRequested = yield* Deferred.make<void>();
842
+ const olderResponse = yield* Deferred.make<{ readonly aggregate: typeof aggregate }>();
843
+ let reads = 0;
844
+ const relay = fakeRelay(() => {
845
+ reads++;
846
+ return reads === 1
847
+ ? Deferred.succeed(olderRequested, undefined).pipe(
848
+ Effect.andThen(Deferred.await(olderResponse)),
849
+ )
850
+ : Effect.succeed({ aggregate: newer });
851
+ });
852
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
853
+
854
+ const older = yield* Effect.forkChild(
855
+ refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
856
+ );
857
+ yield* Deferred.await(olderRequested);
858
+ yield* refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay));
859
+ yield* Deferred.succeed(olderResponse, { aggregate });
860
+ yield* Fiber.join(older);
861
+
862
+ expect(publishWidgetMock).toHaveBeenLastCalledWith({
863
+ kind: "snapshot",
864
+ aggregate: newer,
865
+ });
866
+ }),
867
+ );
868
+
869
+ it.effect("an obsolete refresh does not discard the next account's read", () =>
870
+ Effect.gen(function* () {
871
+ let markTokenRequested = () => {};
872
+ const tokenRequested = new Promise<void>((resolve) => {
873
+ markTokenRequested = resolve;
874
+ });
875
+ let releaseToken = () => {};
876
+ widgetMocks.getInstances.mockReturnValueOnce([
877
+ {
878
+ getId: () => "activity-a",
879
+ getPushToken: () => {
880
+ markTokenRequested();
881
+ return new Promise<null>((resolve) => {
882
+ releaseToken = () => resolve(null);
883
+ });
884
+ },
885
+ addPushTokenListener: vi.fn(),
886
+ },
887
+ ] as never);
888
+ const requested = yield* Deferred.make<void>();
889
+ const response = yield* Deferred.make<{ readonly aggregate: typeof aggregate }>();
890
+ const relay = fakeRelay(() =>
891
+ Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(response))),
892
+ );
893
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
894
+
895
+ const refreshA = yield* Effect.forkChild(
896
+ refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
897
+ );
898
+ yield* Effect.promise(() => tokenRequested);
899
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-b"), "user-b");
900
+ const refreshB = yield* Effect.forkChild(
901
+ refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
902
+ );
903
+ yield* Deferred.await(requested);
904
+ releaseToken();
905
+ yield* Fiber.join(refreshA);
906
+ yield* Deferred.succeed(response, { aggregate });
907
+ yield* Fiber.join(refreshB);
908
+
909
+ expect(publishWidgetMock).toHaveBeenLastCalledWith({
910
+ kind: "snapshot",
911
+ aggregate,
912
+ });
913
+ }),
914
+ );
915
+
916
+ it.effect("does not prime a Live Activity from a read a newer one replaced", () =>
917
+ Effect.gen(function* () {
918
+ let markRequested = () => {};
919
+ const requested = new Promise<void>((resolve) => {
920
+ markRequested = resolve;
921
+ });
922
+ let resolvePreferences = (_preferences: Preferences) => {};
923
+ vi.mocked(loadPreferences).mockImplementationOnce(() => {
924
+ markRequested();
925
+ return new Promise((resolve) => {
926
+ resolvePreferences = resolve;
927
+ });
928
+ });
929
+ const idle = { ...aggregate, activeCount: 0, activities: [] };
930
+ let reads = 0;
931
+ const relay = fakeRelay(() =>
932
+ Effect.succeed({ aggregate: ++reads === 1 ? aggregate : idle }),
933
+ );
934
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
935
+
936
+ const older = yield* Effect.forkChild(
937
+ refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
938
+ );
939
+ yield* Effect.promise(() => requested);
940
+ yield* refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay));
941
+ resolvePreferences({ liveActivitiesEnabled: true } as Preferences);
942
+ yield* Fiber.join(older);
943
+
944
+ expect(widgetMocks.start).not.toHaveBeenCalled();
945
+ }),
946
+ );
947
+
948
+ it.effect("drops a snapshot that arrives after a sign-out, even on re-sign-in", () =>
949
+ Effect.gen(function* () {
950
+ const requested = yield* Deferred.make<void>();
951
+ const response = yield* Deferred.make<{ readonly aggregate: typeof aggregate }>();
952
+ const relay = fakeRelay(() =>
953
+ Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(response))),
954
+ );
955
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
956
+
957
+ const refresh = yield* Effect.forkChild(
958
+ refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
959
+ );
960
+ yield* Deferred.await(requested);
961
+ setAgentAwarenessRelayTokenProvider(null);
962
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a");
963
+ publishWidgetMock.mockClear();
964
+ yield* Deferred.succeed(response, { aggregate });
965
+ yield* Fiber.join(refresh);
966
+
967
+ expect(publishWidgetMock).not.toHaveBeenCalled();
968
+ }),
969
+ );
970
+
971
+ it.effect("does not prime a Live Activity after sign-out during the preference read", () =>
972
+ Effect.gen(function* () {
973
+ let markRequested = () => {};
974
+ const requested = new Promise<void>((resolve) => {
975
+ markRequested = resolve;
976
+ });
977
+ let resolvePreferences = (_preferences: Preferences) => {};
978
+ vi.mocked(loadPreferences).mockImplementationOnce(() => {
979
+ markRequested();
980
+ return new Promise((resolve) => {
981
+ resolvePreferences = resolve;
982
+ });
983
+ });
984
+ const relay = fakeRelay(() => Effect.succeed({ aggregate }));
985
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token"), "user-a");
986
+
987
+ const refresh = yield* Effect.forkChild(
988
+ refreshActiveLiveActivityRemoteRegistration().pipe(Effect.provide(relay)),
989
+ );
990
+ yield* Effect.promise(() => requested);
991
+ setAgentAwarenessRelayTokenProvider(null);
992
+ resolvePreferences({ liveActivitiesEnabled: true } as Preferences);
993
+ yield* Fiber.join(refresh);
994
+
995
+ expect(widgetMocks.start).not.toHaveBeenCalled();
996
+ }),
997
+ );
998
+ });
999
});
apps/mobile/src/features/agent-awareness/remoteRegistration.ts
+67
-5
@@ -37,6 +37,8 @@ import {
37
saveAgentAwarenessRegistrationRecord,
38
} from "../../persistence/imperative";
39
import type { AgentActivityProps } from "../../widgets/AgentActivity";
40
+import type { AgentActivityWidgetSource } from "../../widgets/agentActivityWidgetTimeline";
41
+import { publishAgentActivityWidget } from "../../widgets/publishAgentActivityWidget";
42
import {
43
dismissEndedAgentLiveActivities,
44
getAgentLiveActivities,
@@ -89,6 +91,9 @@ const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000;
91
const LIVE_ACTIVITY_STALE_AFTER_MS = 10 * 60_000;
92
const liveActivityStaleDate = () => new Date(Date.now() + LIVE_ACTIVITY_STALE_AFTER_MS);
93
const registeredActivityPushTokens = new Map<string, number>();
94
+// Refreshes can overlap (sign-in, foreground, retry); only the newest read may
95
+// repaint, so a slow older response never overwrites newer rows.
96
+let widgetSnapshotReads = 0;
97
let androidDeviceReplayedAt: number | null = null;
98
let pushTokenSubscription: { remove: () => void } | null = null;
99
let appStateSubscription: { remove: () => void } | null = null;
@@ -181,6 +186,9 @@ export function setAgentAwarenessRelayTokenProvider(
186
if (relayTokenProviderIdentity && identity !== relayTokenProviderIdentity) {
187
clearAndroidAgentNotifications();
188
}
189
+ if (provider) {
190
+ publishWidget({ kind: "loading" });
191
+ }
192
androidDeviceReplayedAt = null;
193
deviceRegistrationGeneration++;
194
activeDeviceRegistration = null;
@@ -201,6 +209,7 @@ export function setAgentAwarenessRelayTokenProvider(
209
}
210
// Signed-out activities would be orphaned because the relay can no longer update or end them.
211
endLocalLiveActivities("live activity cleanup after cloud sign-out failed");
212
+ publishWidget({ kind: "signed-out" });
213
setRegistrationStatus("unknown");
214
void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => {
215
logRegistrationError("clear registration record on sign-out failed", error);
@@ -737,6 +746,15 @@ function ensureAppStateListener(): void {
746
});
747
}
748
749
+function publishWidget(source: AgentActivityWidgetSource): void {
750
+ if (!canRegisterRemoteLiveActivities()) {
751
+ return;
752
+ }
753
+ publishAgentActivityWidget(source).catch((error: unknown) => {
754
+ logRegistrationError("agent activity widget publish failed", error);
755
+ });
756
+}
757
+
758
// Binaries built before the native dismissEnded method throw here.
759
function dismissEndedLocalLiveActivities(): void {
760
try {
@@ -813,6 +831,7 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void {
831
registrationStatusListeners.clear();
832
registeredActivityPushTokens.clear();
833
activityPushTokenLocks.clear();
834
+ widgetSnapshotReads = 0;
835
}
836
837
export const unregisterAgentAwarenessDeviceForCurrentUser: (
@@ -933,13 +952,40 @@ function scheduleActiveLiveActivityRegistrationRetry(): void {
952
}, REMOTE_ACTIVITY_REGISTRATION_RETRY_MS);
953
}
954
936
-const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
955
+export const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
956
"remoteRegistration.refreshActiveLiveActivityRemoteRegistration",
957
)(function* (): Effect.fn.Return<void, never, ManagedRelay.ManagedRelayClient> {
958
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
959
return;
960
}
961
962
+ // The home-screen widget has no push path of its own, so every foreground
963
+ // refresh repaints it from one snapshot read. Yields undefined once the
964
+ // account changed or a newer read started, so a stale result is never
965
+ // shown or primed.
966
+ const generation = deviceRegistrationGeneration;
967
+ const isCurrentAccount = () =>
968
+ relayTokenProvider !== null && deviceRegistrationGeneration === generation;
969
+ let read = 0;
970
+ const isNewestRead = () => isCurrentAccount() && read === widgetSnapshotReads;
971
+ const refreshWidget = Effect.gen(function* () {
972
+ // An obsolete refresh must not supersede the current account's read.
973
+ if (!isCurrentAccount()) {
974
+ return undefined;
975
+ }
976
+ read = ++widgetSnapshotReads;
977
+ const snapshot = yield* readAgentActivitySnapshot();
978
+ if (!isNewestRead()) {
979
+ return undefined;
980
+ }
981
+ if (snapshot) {
982
+ publishWidget({ kind: "snapshot", aggregate: snapshot.aggregate });
983
+ } else {
984
+ publishWidget({ kind: "unavailable" });
985
+ }
986
+ return { snapshot };
987
+ });
988
+
989
dismissEndedLocalLiveActivities();
990
let activities = yield* Effect.try({
991
try: () => getAgentLiveActivities(),
@@ -959,6 +1005,7 @@ const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
1005
1006
// The relay tracks exactly one card per device; if concurrent arming ever
1007
// produced extras, end them so only one keeps receiving updates.
1008
+ const hadActivities = activities.length > 0;
1009
if (activities.length > 1) {
1010
for (const extra of activities.slice(1)) {
1011
extra.end("immediate").catch((error: unknown) => {
@@ -972,7 +1019,12 @@ const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
1019
// update token can be observed and registered immediately — the relay never
1020
// remote-starts one (background push-to-start wakes proved too unreliable
1021
// to hand the token over).
975
- if (activities.length === 0) {
1022
+ if (!hadActivities) {
1023
+ const widgetRead = yield* refreshWidget;
1024
+ if (!widgetRead) {
1025
+ return;
1026
+ }
1027
+ const { snapshot } = widgetRead;
1028
const preferences = yield* Effect.tryPromise({
1029
try: () => loadPreferences(),
1030
catch: (cause) =>
@@ -981,10 +1033,14 @@ const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
1033
cause,
1034
}),
1035
}).pipe(Effect.orElseSucceed(() => null));
1036
+ // A sign-out, account switch, or newer read during the preference read
1037
+ // makes this snapshot stale; priming now could bring old rows back.
1038
+ if (!isNewestRead()) {
1039
+ return;
1040
+ }
1041
if (preferences?.liveActivitiesEnabled !== false) {
985
- const snapshot = yield* readAgentActivitySnapshot();
986
- // The snapshot request yields; an arm-on-send may have created the
987
- // card in the meantime. Re-check so two cards are never started.
1042
+ // The snapshot and preference reads yield; an arm-on-send may have
1043
+ // created the card in the meantime. Re-check so two cards are never started.
1044
const armedMeanwhile = yield* Effect.try({
1045
try: () => getAgentLiveActivities(),
1046
catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,
@@ -1040,4 +1096,10 @@ const refreshActiveLiveActivityRemoteRegistration = Effect.fn(
1096
if (registrationResults.some(Boolean)) {
1097
scheduleActiveLiveActivityRegistrationRetry();
1098
}
1099
+
1100
+ // An existing card keeps its push token registered without waiting on the
1101
+ // relay; the widget still repaints afterwards.
1102
+ if (hadActivities) {
1103
+ yield* refreshWidget;
1104
+ }
1105
});
apps/mobile/src/widgets/AgentActivityWidget.tsx
new
+199
@@ -0,0 +1,199 @@
1
+import { HStack, Image, Spacer, Text, VStack } from "@expo/ui/swift-ui";
2
+import {
3
+ containerBackground,
4
+ font,
5
+ foregroundStyle,
6
+ frame,
7
+ layoutPriority,
8
+ lineLimit,
9
+ resizable,
10
+ widgetURL,
11
+} from "@expo/ui/swift-ui/modifiers";
12
+import { createWidget, type WidgetEnvironment } from "expo-widgets";
13
+
14
+import type {
15
+ AgentActivityPhase,
16
+ AgentActivityProps,
17
+ AgentActivityRowProps,
18
+} from "./AgentActivity";
19
+
20
+// Home-screen and Lock Screen counterpart of the AgentActivity Live Activity.
21
+// It shares the Live Activity's name, but expo-widgets stores widget and Live
22
+// Activity layouts under different keys, so each needs its own registration.
23
+export function AgentActivityWidget(
24
+ publishedProps: Partial<AgentActivityProps> | undefined,
25
+ environment: WidgetEnvironment,
26
+) {
27
+ "widget";
28
+ // The extension evaluates this function without the app's module scope.
29
+ // Before the app's first publish, the embedded layout renders with no props.
30
+ const props = publishedProps ?? {};
31
+ const family = environment.widgetFamily;
32
+ const accessory = family === "accessoryRectangular";
33
+ const small = family === "systemSmall";
34
+ const monochrome =
35
+ environment.widgetRenderingMode === "accented" ||
36
+ environment.widgetRenderingMode === "vibrant" ||
37
+ environment.isLuminanceReduced === true;
38
+ const isLightScheme = environment.colorScheme === "light";
39
+
40
+ type Foreground = Parameters<typeof foregroundStyle>[0];
41
+ const primaryForeground = { type: "hierarchical", style: "primary" } as const;
42
+ const secondaryForeground = { type: "hierarchical", style: "secondary" } as const;
43
+ const phaseTint = (phase: AgentActivityPhase): Foreground => {
44
+ if (monochrome) return primaryForeground;
45
+ switch (phase) {
46
+ case "waiting_for_approval":
47
+ return isLightScheme ? "#d97706" : "#fcd34d";
48
+ case "waiting_for_input":
49
+ return isLightScheme ? "#4f46e5" : "#a5b4fc";
50
+ case "failed":
51
+ return isLightScheme ? "#dc2626" : "#fca5a5";
52
+ case "completed":
53
+ return isLightScheme ? "#059669" : "#6ee7b7";
54
+ case "stale":
55
+ return secondaryForeground;
56
+ case "starting":
57
+ case "running":
58
+ default:
59
+ return isLightScheme ? "#0284c7" : "#7dd3fc";
60
+ }
61
+ };
62
+ const phasePriority = (phase: AgentActivityPhase): number => {
63
+ if (phase === "waiting_for_approval" || phase === "waiting_for_input") return 0;
64
+ if (phase === "failed") return 1;
65
+ if (phase === "running" || phase === "starting") return 2;
66
+ return 3;
67
+ };
68
+
69
+ const loaded = props.activities !== undefined;
70
+ const rows = [...(props.activities ?? [])].sort(
71
+ (a, b) => phasePriority(a.phase) - phasePriority(b.phase),
72
+ );
73
+ const shown = rows.slice(0, accessory || small ? 2 : 4);
74
+ const attentionCount = rows.filter(
75
+ (row) => row.phase === "waiting_for_approval" || row.phase === "waiting_for_input",
76
+ ).length;
77
+ const workingCount = rows.filter(
78
+ (row) => row.phase === "running" || row.phase === "starting",
79
+ ).length;
80
+ const summary =
81
+ attentionCount > 0
82
+ ? `${attentionCount} need${attentionCount === 1 ? "s" : ""} ${small ? "you" : "attention"}`
83
+ : workingCount > 0
84
+ ? `${props.activeCount ?? workingCount} active`
85
+ : rows.some((row) => row.phase === "stale")
86
+ ? "Out of date"
87
+ : rows.some((row) => row.phase === "failed")
88
+ ? "Failed"
89
+ : rows.length > 0
90
+ ? "Done"
91
+ : "";
92
+ const summaryTint = rows[0] ? phaseTint(rows[0].phase) : secondaryForeground;
93
+ const emptyMessage = loaded
94
+ ? (props.subtitle ?? "No active agents")
95
+ : "Open T3 Code to load agent activity";
96
+
97
+ // Widget taps open the containing app, and every build accepts the prod
98
+ // scheme as a link prefix, so dev and preview builds route this too.
99
+ const linkRow = rows[0];
100
+ const deepLink =
101
+ linkRow && linkRow.deepLink.startsWith("/") && !linkRow.deepLink.startsWith("//")
102
+ ? `t3code://${linkRow.deepLink.slice(1)}`
103
+ : null;
104
+
105
+ const background = accessory ? "clear" : isLightScheme ? "#ffffff" : "#1c1c1e";
106
+ const rootModifiers = [
107
+ containerBackground(background, "widget"),
108
+ ...(deepLink ? [widgetURL(deepLink)] : []),
109
+ ];
110
+
111
+ // The template image ignores frame/foregroundStyle applied to itself; size
112
+ // and tint it through a container the resizable image fills.
113
+ const renderLogo = (height: number) => (
114
+ <HStack
115
+ modifiers={[frame({ width: height * 1.5, height }), foregroundStyle(primaryForeground)]}
116
+ >
117
+ <Image assetName="T3Mark" modifiers={[resizable()]} />
118
+ </HStack>
119
+ );
120
+
121
+ const renderRow = (row: AgentActivityRowProps, key: string) =>
122
+ small || accessory ? (
123
+ <VStack key={key} alignment="leading" spacing={1}>
124
+ <Text
125
+ modifiers={[
126
+ font({ weight: "semibold", size: accessory ? 13 : 12 }),
127
+ foregroundStyle(primaryForeground),
128
+ lineLimit(1),
129
+ ]}
130
+ >
131
+ {row.threadTitle}
132
+ </Text>
133
+ <Text
134
+ modifiers={[
135
+ font({ weight: "medium", size: 11 }),
136
+ foregroundStyle(phaseTint(row.phase)),
137
+ lineLimit(1),
138
+ ]}
139
+ >
140
+ {row.status}
141
+ </Text>
142
+ </VStack>
143
+ ) : (
144
+ <HStack key={key} spacing={7} alignment="center">
145
+ <Text
146
+ modifiers={[
147
+ font({ weight: "semibold", size: 13 }),
148
+ foregroundStyle(primaryForeground),
149
+ lineLimit(1),
150
+ ]}
151
+ >
152
+ {row.threadTitle}
153
+ </Text>
154
+ <Text modifiers={[font({ size: 11 }), foregroundStyle(secondaryForeground), lineLimit(1)]}>
155
+ {row.projectTitle}
156
+ </Text>
157
+ <Spacer minLength={8} />
158
+ <Text
159
+ modifiers={[
160
+ font({ weight: "semibold", size: 11 }),
161
+ foregroundStyle(phaseTint(row.phase)),
162
+ layoutPriority(1),
163
+ ]}
164
+ >
165
+ {row.status}
166
+ </Text>
167
+ </HStack>
168
+ );
169
+
170
+ return (
171
+ <VStack alignment="leading" spacing={accessory ? 2 : 8} modifiers={rootModifiers}>
172
+ <HStack spacing={6} alignment="center">
173
+ {accessory ? null : renderLogo(13)}
174
+ <Text
175
+ modifiers={[
176
+ font({ weight: "semibold", size: 12 }),
177
+ foregroundStyle(accessory ? primaryForeground : summaryTint),
178
+ lineLimit(1),
179
+ ]}
180
+ >
181
+ {summary || (accessory ? "T3 Code" : "")}
182
+ </Text>
183
+ <Spacer minLength={0} />
184
+ </HStack>
185
+ {shown.length > 0 ? (
186
+ <VStack alignment="leading" spacing={accessory ? 1 : small ? 6 : 5}>
187
+ {shown.map((row, index) => renderRow(row, `${row.threadId}:${index}`))}
188
+ </VStack>
189
+ ) : (
190
+ <Text modifiers={[font({ size: 12 }), foregroundStyle(secondaryForeground), lineLimit(2)]}>
191
+ {emptyMessage}
192
+ </Text>
193
+ )}
194
+ {accessory ? null : <Spacer minLength={0} />}
195
+ </VStack>
196
+ );
197
+}
198
+
199
+export default createWidget<Partial<AgentActivityProps>>("AgentActivity", AgentActivityWidget);
apps/mobile/src/widgets/agentActivityWidgetTimeline.test.ts
new
+72
@@ -0,0 +1,72 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4
+import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
5
+
6
+import {
7
+ AGENT_ACTIVITY_WIDGET_STALE_AFTER_MS,
8
+ agentActivityWidgetTimeline,
9
+} from "./agentActivityWidgetTimeline";
10
+
11
+const now = Date.parse("2026-10-18T10:00:00.000Z");
12
+
13
+type Row = RelayAgentActivityAggregateState["activities"][number];
14
+
15
+function row(phase: Row["phase"], status: string): Row {
16
+ return {
17
+ environmentId: "env-1" as EnvironmentId,
18
+ threadId: `thread-${phase}` as ThreadId,
19
+ projectTitle: "t3code",
20
+ threadTitle: `Thread ${phase}`,
21
+ modelTitle: "GPT-5.5",
22
+ phase,
23
+ status,
24
+ updatedAt: "2026-10-18T09:59:00.000Z",
25
+ deepLink: `/threads/env-1/thread-${phase}`,
26
+ };
27
+}
28
+
29
+function aggregate(activities: ReadonlyArray<Row>): RelayAgentActivityAggregateState {
30
+ return {
31
+ title: "T3 Code",
32
+ subtitle: "Agent work in progress",
33
+ activeCount: activities.length,
34
+ updatedAt: "2026-10-18T09:59:00.000Z",
35
+ activities,
36
+ };
37
+}
38
+
39
+describe("agentActivityWidgetTimeline", () => {
40
+ it("marks unfinished rows out of date once the widget can no longer vouch for them", () => {
41
+ const timeline = agentActivityWidgetTimeline(
42
+ {
43
+ kind: "snapshot",
44
+ aggregate: aggregate([row("running", "Working"), row("completed", "Done")]),
45
+ },
46
+ now,
47
+ );
48
+
49
+ expect(timeline.map((entry) => entry.date.getTime())).toEqual([
50
+ now,
51
+ now + AGENT_ACTIVITY_WIDGET_STALE_AFTER_MS,
52
+ ]);
53
+ expect(timeline[0]?.props.activities.map((entry) => entry.phase)).toEqual([
54
+ "running",
55
+ "completed",
56
+ ]);
57
+ expect(timeline[1]?.props.activities.map((entry) => [entry.phase, entry.status])).toEqual([
58
+ ["stale", "Out of date"],
59
+ ["completed", "Done"],
60
+ ]);
61
+ });
62
+
63
+ it("keeps finished outcomes on a single entry", () => {
64
+ const timeline = agentActivityWidgetTimeline(
65
+ { kind: "snapshot", aggregate: aggregate([row("failed", "Failed")]) },
66
+ now,
67
+ );
68
+
69
+ expect(timeline).toHaveLength(1);
70
+ expect(timeline[0]?.props.activities[0]?.phase).toBe("failed");
71
+ });
72
+});
apps/mobile/src/widgets/agentActivityWidgetTimeline.ts
new
+61
@@ -0,0 +1,61 @@
1
+import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
2
+
3
+import type { AgentActivityProps } from "./AgentActivity";
4
+
5
+// The widget only refreshes while the app is open, so after this long it stops
6
+// claiming an agent is still working. Matches the Live Activity's stale date.
7
+export const AGENT_ACTIVITY_WIDGET_STALE_AFTER_MS = 10 * 60_000;
8
+
9
+export type AgentActivityWidgetSource =
10
+ | { readonly kind: "signed-out" }
11
+ | { readonly kind: "unavailable" }
12
+ | { readonly kind: "loading" }
13
+ | { readonly kind: "snapshot"; readonly aggregate: RelayAgentActivityAggregateState | null };
14
+
15
+export function agentActivityWidgetTimeline(source: AgentActivityWidgetSource, now: number) {
16
+ const updatedAt = new Date(now).toISOString();
17
+ if (source.kind !== "snapshot" || !source.aggregate) {
18
+ const props: AgentActivityProps = {
19
+ title: "T3 Code",
20
+ subtitle:
21
+ source.kind === "signed-out"
22
+ ? "Sign in to T3 Connect to see agents"
23
+ : source.kind === "unavailable"
24
+ ? "Couldn't reach T3 Connect"
25
+ : source.kind === "loading"
26
+ ? "Loading agents…"
27
+ : "No active agents",
28
+ activeCount: 0,
29
+ updatedAt,
30
+ activities: [],
31
+ };
32
+ return [{ date: new Date(now), props }];
33
+ }
34
+
35
+ const { aggregate } = source;
36
+ const props: AgentActivityProps = {
37
+ title: aggregate.title,
38
+ subtitle: aggregate.subtitle,
39
+ activeCount: aggregate.activeCount,
40
+ updatedAt: aggregate.updatedAt,
41
+ activities: aggregate.activities,
42
+ };
43
+ const hasInFlightRows = props.activities.some(
44
+ (row) => row.phase !== "completed" && row.phase !== "failed",
45
+ );
46
+ if (!hasInFlightRows) {
47
+ return [{ date: new Date(now), props }];
48
+ }
49
+ const staleProps: AgentActivityProps = {
50
+ ...props,
51
+ activities: props.activities.map((row) =>
52
+ row.phase === "completed" || row.phase === "failed"
53
+ ? row
54
+ : { ...row, phase: "stale", status: "Out of date" },
55
+ ),
56
+ };
57
+ return [
58
+ { date: new Date(now), props },
59
+ { date: new Date(now + AGENT_ACTIVITY_WIDGET_STALE_AFTER_MS), props: staleProps },
60
+ ];
61
+}
apps/mobile/src/widgets/publishAgentActivityWidget.ios.ts
new
+12
@@ -0,0 +1,12 @@
1
+import { requireOptionalNativeModule } from "expo";
2
+
3
+import {
4
+ agentActivityWidgetTimeline,
5
+ type AgentActivityWidgetSource,
6
+} from "./agentActivityWidgetTimeline";
7
+
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()));
12
+}
apps/mobile/src/widgets/publishAgentActivityWidget.ts
new
+3
@@ -0,0 +1,3 @@
1
+import type { AgentActivityWidgetSource } from "./agentActivityWidgetTimeline";
2
+
3
+export async function publishAgentActivityWidget(_source: AgentActivityWidgetSource) {}
docs/user/mobile-notifications.md
+2
@@ -4,6 +4,8 @@ Sign in to T3 Connect, link your environments, and enable **Device Notifications
4
5
Enable **Live Activity Updates** on iOS, **Agent Live Updates** on Android 16 and newer, or **Ongoing Agent Activity** on older Android versions to follow work without opening the app. Finished results remain visible for up to 15 minutes. You can dismiss an Android activity card without disabling alerts; turn off the same switch to stop future cards.
6
7
+On iOS you can also add the **Agent Activity** widget to your Home Screen or Lock Screen. It shows the same agents as the Live Activity, using your T3 Connect sign-in. The widget refreshes when you open T3 and shows unfinished work as out of date after 10 minutes.
8
+
9
Ordinary alerts stay quiet while the mobile app is in the foreground. Ongoing activity continues to update. Viewing a thread on another device does not silence your phone's alerts.
10
11
Android notifications require Android 7.0 or newer and Google Play services. Android 16 and newer can promote ongoing activity to a Live Update, subject to system settings and device support. Other devices show a regular ongoing notification. If Live Updates don't appear on Android 16 or newer, check **Live Update Settings** in T3 Code's **Settings → Notifications**. Android 7's battery-saving modes can delay removal of expired cards.