Skip to content

Commit 0b7c9d8

Browse files
t3dotggclaude
andcommitted
perf(mobile): instant send feedback and faster thread opens
Sending a message did nothing for seconds because the queued state waited on a durable file write, and thread opens stalled on quadratic feed grouping plus duplicated activity sorts. New-thread froze mid-sheet while native autoFocus forced the keyboard up during the present animation. - Publish outbox enqueues to the atom synchronously, write behind, roll back on failure; clear the composer draft on the tap frame - Arm the Live Activity after the send instead of before it - Make groupAdjacentActivities linear; sort activities once for approvals + user inputs instead of twice - Focus the new-task composer after interactions (iOS) instead of via native autoFocus during the transition - Memoize the v2 thread list's FlatList extraData - Host useThreadOutboxDrain in a null-rendering leaf so outbox/shell updates stop re-rendering the root navigation layout - Skip the active-thread shell subscription on iOS in useAppShortcuts (Android-only feature) Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent a8e05cb commit 0b7c9d8

10 files changed

Lines changed: 189 additions & 57 deletions

‎apps/mobile/src/Stack.tsx‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,15 @@ function workspacePathFromState(state: NavigationState): string {
284284
return path.startsWith("/") ? path : `/${path}`;
285285
}
286286

287+
// The drain hook subscribes to the outbox, all thread shells, projects, and
288+
// connection statuses. Hosting it in a null-rendering leaf keeps those
289+
// updates from re-rendering RootStackLayout (and with it every screen) on
290+
// each enqueue, shell change, or reconnect.
291+
function ThreadOutboxDrainWorker() {
292+
useThreadOutboxDrain();
293+
return null;
294+
}
295+
287296
function RootStackLayout(props: {
288297
readonly children: React.ReactNode;
289298
readonly state: NavigationState;
@@ -292,7 +301,6 @@ function RootStackLayout(props: {
292301
const { pendingShare } = useIncomingShare();
293302
const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);
294303
useAgentNotificationNavigation();
295-
useThreadOutboxDrain();
296304
// Presents the T3 Connect onboarding sheet after an in-session sign-in.
297305
useConnectOnboardingNavigation();
298306
// Launcher app shortcuts: routes shortcut taps and tracks opened threads.
@@ -320,6 +328,7 @@ function RootStackLayout(props: {
320328

321329
return (
322330
<HardwareKeyboardCommandProvider pathname={pathname}>
331+
<ThreadOutboxDrainWorker />
323332
<ShowcaseCaptureCoordinator pathname={pathname} />
324333
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
325334
<AdaptiveWorkspaceLayout pathname={workspacePathname}>

‎apps/mobile/src/features/home/HomeScreen.tsx‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -665,6 +665,26 @@ export function HomeScreen(props: HomeScreenProps) {
665665
);
666666
const v2KeyExtractor = useCallback((item: ThreadListV2ListItem) => item.key, []);
667667

668+
// FlatList treats a changed extraData identity as "re-render every visible
669+
// row", so an inline object literal would invalidate all rows on every
670+
// HomeScreen render.
671+
const v2ExtraData = useMemo(
672+
() => ({
673+
projectByKey,
674+
projectCwdByKey,
675+
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
676+
serverConfigs,
677+
savedConnectionsById: props.savedConnectionsById,
678+
}),
679+
[
680+
projectByKey,
681+
projectCwdByKey,
682+
props.savedConnectionsById,
683+
serverConfigs,
684+
v2ProjectTitleByProjectKey,
685+
],
686+
);
687+
668688
const extraData = useMemo(
669689
() => ({ savedConnectionsById: props.savedConnectionsById, projectCwdByKey }),
670690
[props.savedConnectionsById, projectCwdByKey],
@@ -900,13 +920,7 @@ export function HomeScreen(props: HomeScreenProps) {
900920
data={threadListV2Items}
901921
renderItem={renderV2Item}
902922
keyExtractor={v2KeyExtractor}
903-
extraData={{
904-
projectByKey,
905-
projectCwdByKey,
906-
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
907-
serverConfigs,
908-
savedConnectionsById: props.savedConnectionsById,
909-
}}
923+
extraData={v2ExtraData}
910924
ListHeaderComponent={v2ListHeader}
911925
ListFooterComponent={
912926
threadListV2Layout.hiddenSettledCount > 0 ? (

‎apps/mobile/src/features/shortcuts/useAppShortcuts.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,14 @@ function useShortcutNavigation(): void {
5454
}
5555

5656
function useRecentThreadShortcutSync(state: NavigationState): void {
57-
const threadRef = useMemo(() => activeThreadRef(state), [state]);
57+
// Launcher shortcuts are Android-only. A null ref on iOS keeps this hook
58+
// (mounted in the root stack layout) from subscribing the root to the
59+
// active thread's shell, which would re-render every screen on each
60+
// title/status/session change.
61+
const threadRef = useMemo(
62+
() => (Platform.OS === "android" ? activeThreadRef(state) : null),
63+
[state],
64+
);
5865
const threadShell = useThreadShell(threadRef);
5966
// null until the persisted list loads; recording waits on it so the first
6067
// thread opened after a cold start cannot clobber older entries.

‎apps/mobile/src/features/threads/NewTaskDraftScreen.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -946,7 +946,11 @@ export function NewTaskDraftScreen(props: {
946946
const promptEditor = (
947947
<ComposerEditor
948948
ref={promptInputRef}
949-
autoFocus={!isAndroid}
949+
// Native autoFocus fires becomeFirstResponder in didMoveToWindow, which
950+
// forces the iOS keyboard bring-up during the formSheet present
951+
// animation and stalls it. The runAfterInteractions effect above focuses
952+
// the editor once the transition settles instead.
953+
autoFocus={false}
950954
editable={!isIncomingShareTransferPending}
951955
multiline
952956
scrollEnabled={isExpanded}

‎apps/mobile/src/features/threads/ThreadComposer.tsx‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -518,14 +518,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
518518
const threadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
519519
if (inFlightThreadIdsRef.current.has(threadKey)) return;
520520
inFlightThreadIdsRef.current.add(threadKey);
521-
// Sending a prompt starts agent work: arm the lock-screen card now, while
522-
// the app is foregrounded and the activity token can be registered.
523-
armAgentAwarenessLiveActivityForLocalWork({
524-
threadTitle: props.selectedThread.title,
525-
projectTitle: props.environmentLabel ?? "T3 Code",
526-
});
527521
try {
528522
await onSendMessage();
523+
// Sending a prompt starts agent work: arm the lock-screen card while the
524+
// app is foregrounded and the activity token can be registered. Armed
525+
// after the send so its preference read and native Activity start don't
526+
// contend with the queued-message feedback on the tap frame.
527+
armAgentAwarenessLiveActivityForLocalWork({
528+
threadTitle: props.selectedThread.title,
529+
projectTitle: props.environmentLabel ?? "T3 Code",
530+
});
529531
} finally {
530532
inFlightThreadIdsRef.current.delete(threadKey);
531533
}

‎apps/mobile/src/lib/threadActivity.ts‎

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -957,6 +957,11 @@ function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
957957

958958
function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
959959
const grouped: ThreadFeedEntry[] = [];
960+
// Mutable backing array for the trailing group so appending an activity is
961+
// O(1) instead of re-copying the group (which made this loop quadratic on
962+
// long tool runs). The array is only mutated while it is the trailing group.
963+
let openGroupActivities: ThreadFeedActivity[] | null = null;
964+
let openGroupTurnId: TurnId | null = null;
960965

961966
for (const entry of entries) {
962967
// Skip empty messages so they don't break activity grouping.
@@ -966,24 +971,23 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
966971

967972
if (entry.type !== "activity") {
968973
grouped.push(entry);
974+
openGroupActivities = null;
969975
continue;
970976
}
971977

972-
const previous = grouped.at(-1);
973-
if (previous?.type === "activity-group" && previous.turnId === entry.turnId) {
974-
grouped[grouped.length - 1] = {
975-
...previous,
976-
activities: [...previous.activities, entry.activity],
977-
};
978+
if (openGroupActivities !== null && openGroupTurnId === entry.turnId) {
979+
openGroupActivities.push(entry.activity);
978980
continue;
979981
}
980982

983+
openGroupActivities = [entry.activity];
984+
openGroupTurnId = entry.turnId;
981985
grouped.push({
982986
type: "activity-group",
983987
id: entry.id,
984988
createdAt: entry.createdAt,
985989
turnId: entry.turnId,
986-
activities: [entry.activity],
990+
activities: openGroupActivities,
987991
});
988992
}
989993

@@ -1225,13 +1229,24 @@ function appendPresentedFeedEntry(
12251229
});
12261230
}
12271231

1228-
export function derivePendingApprovals(
1232+
/**
1233+
* Sorts activities into lifecycle order. `derivePendingApprovals` and
1234+
* `derivePendingUserInputs` both expect this ordering; sorting once and
1235+
* passing the result to both avoids re-sorting the full activity history
1236+
* per derivation.
1237+
*/
1238+
export function sortThreadActivities(
12291239
activities: ReadonlyArray<OrchestrationThreadActivity>,
1240+
): ReadonlyArray<OrchestrationThreadActivity> {
1241+
return Arr.sort(activities, activityOrder);
1242+
}
1243+
1244+
export function derivePendingApprovals(
1245+
sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
12301246
): PendingApproval[] {
12311247
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
1232-
const ordered = Arr.sort(activities, activityOrder);
12331248

1234-
for (const activity of ordered) {
1249+
for (const activity of sortedActivities) {
12351250
const payload =
12361251
activity.payload && typeof activity.payload === "object"
12371252
? (activity.payload as Record<string, unknown>)
@@ -1273,12 +1288,11 @@ export function derivePendingApprovals(
12731288
}
12741289

12751290
export function derivePendingUserInputs(
1276-
activities: ReadonlyArray<OrchestrationThreadActivity>,
1291+
sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
12771292
): PendingUserInput[] {
12781293
const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
1279-
const ordered = Arr.sort(activities, activityOrder);
12801294

1281-
for (const activity of ordered) {
1295+
for (const activity of sortedActivities) {
12821296
const payload =
12831297
activity.payload && typeof activity.payload === "object"
12841298
? (activity.payload as Record<string, unknown>)

‎apps/mobile/src/state/thread-outbox-manager.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -88,11 +88,22 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
8888
return loadPromise;
8989
};
9090

91-
const enqueue = (message: QueuedThreadMessage): Promise<void> =>
92-
serialize(async () => {
91+
// The queued atom drives the composer's immediate "queued" feedback, so it
92+
// is published synchronously; the durable write happens behind it and rolls
93+
// the message back out if it fails (durability only matters for crash
94+
// recovery, not for the in-session queue).
95+
const enqueue = (message: QueuedThreadMessage): Promise<void> => {
96+
setMessages([
97+
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
98+
message,
99+
]);
100+
return serialize(async () => {
93101
try {
94102
await options.storage.write(message);
95103
} catch (cause) {
104+
setMessages(
105+
currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
106+
);
96107
throw new ThreadOutboxManagerError({
97108
operation: "enqueue",
98109
environmentId: message.environmentId,
@@ -101,11 +112,8 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
101112
cause,
102113
});
103114
}
104-
setMessages([
105-
...currentMessages().filter((candidate) => candidate.messageId !== message.messageId),
106-
message,
107-
]);
108115
});
116+
};
109117

110118
// Rewrites an already-queued message. A no-op when the message has been
111119
// removed in the meantime (e.g. deleted or delivered), so a trailing editor

‎apps/mobile/src/state/thread-outbox.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,69 @@ describe("thread outbox", () => {
294294
registry.dispose();
295295
});
296296

297+
it("publishes an enqueued message before the durable write resolves", async () => {
298+
const registry = AtomRegistry.make();
299+
let releaseWrite!: () => void;
300+
const writeBlocked = new Promise<void>((resolve) => {
301+
releaseWrite = resolve;
302+
});
303+
const manager = createThreadOutboxManager({
304+
registry,
305+
storage: {
306+
load: async () => [],
307+
write: async () => writeBlocked,
308+
remove: async () => undefined,
309+
},
310+
});
311+
const message = queuedMessage({
312+
messageId: "message-1",
313+
createdAt: "2026-06-08T10:00:01.000Z",
314+
});
315+
316+
const enqueueing = manager.enqueue(message);
317+
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
318+
"environment-1:thread-1": [message],
319+
});
320+
321+
releaseWrite();
322+
await enqueueing;
323+
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
324+
"environment-1:thread-1": [message],
325+
});
326+
registry.dispose();
327+
});
328+
329+
it("rolls an enqueued message back out when the durable write fails", async () => {
330+
const registry = AtomRegistry.make();
331+
const writeCause = new Error("disk full");
332+
const manager = createThreadOutboxManager({
333+
registry,
334+
storage: {
335+
load: async () => [],
336+
write: async () => {
337+
throw writeCause;
338+
},
339+
remove: async () => undefined,
340+
},
341+
});
342+
const message = queuedMessage({
343+
messageId: "message-1",
344+
createdAt: "2026-06-08T10:00:01.000Z",
345+
});
346+
347+
await expect(manager.enqueue(message)).rejects.toEqual(
348+
new ThreadOutboxManagerError({
349+
operation: "enqueue",
350+
environmentId: message.environmentId,
351+
threadId: message.threadId,
352+
messageId: message.messageId,
353+
cause: writeCause,
354+
}),
355+
);
356+
expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({});
357+
registry.dispose();
358+
});
359+
297360
it("replaces an existing message when an enqueue retry uses the same id", async () => {
298361
const registry = AtomRegistry.make();
299362
const manager = createThreadOutboxManager({

‎apps/mobile/src/state/use-selected-thread-requests.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
derivePendingApprovals,
1212
derivePendingUserInputs,
1313
setPendingUserInputCustomAnswer,
14+
sortThreadActivities,
1415
type PendingUserInputDraftAnswer,
1516
} from "../lib/threadActivity";
1617
import { appAtomRegistry } from "./atom-registry";
@@ -70,14 +71,19 @@ export function useSelectedThreadRequests() {
7071
null,
7172
);
7273

73-
const activePendingApprovals = useMemo(
74-
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
74+
// Sort once; both derivations expect the same lifecycle ordering.
75+
const sortedActivities = useMemo(
76+
() => (selectedThread ? sortThreadActivities(selectedThread.activities) : []),
7577
[selectedThread],
7678
);
79+
const activePendingApprovals = useMemo(
80+
() => derivePendingApprovals(sortedActivities),
81+
[sortedActivities],
82+
);
7783
const activePendingApproval = activePendingApprovals[0] ?? null;
7884
const activePendingUserInputs = useMemo(
79-
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
80-
[selectedThread],
85+
() => derivePendingUserInputs(sortedActivities),
86+
[sortedActivities],
8187
);
8288
const activePendingUserInput = activePendingUserInputs[0] ?? null;
8389
const activePendingUserInputDrafts =

0 commit comments

Comments
 (0)