Skip to content

Commit c244cad

Browse files
perf(mobile): typing in the composer no longer re-renders the thread screen
Every keystroke replaced the whole composer drafts map, and the thread route, the selected-thread request hook, Home's pending tasks and the upload worker all read that map. Each keystroke re-rendered the route, header, feed and Home behind it. The composer now reads its own draft through a per-key atom. The thread composer state reads only the draft's settings, and the request hook, pending tasks and upload worker read projections that stay equal while only text changes. A text edit keeps the draft's attachment array. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b633927 commit c244cad

10 files changed

Lines changed: 144 additions & 53 deletions

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

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ import {
5555
setComposerDraftText,
5656
composerContextImportsAtom,
5757
countComposerDraftAttachmentsAfterSelection,
58+
useComposerDraft,
5859
} from "../../state/use-composer-drafts";
5960
import { appAtomRegistry } from "../../state/atom-registry";
6061
import type { ComposerDocumentAttachment } from "../../lib/composerContext";
@@ -79,7 +80,6 @@ import {
7980
import { ProviderIcon } from "../../components/ProviderIcon";
8081
import {
8182
composerStripAttachments,
82-
type DraftComposerAttachment,
8383
type DraftComposerFileAttachment,
8484
} from "../../lib/composerImages";
8585
import {
@@ -130,8 +130,6 @@ export const COMPOSER_EXPANDED_CHROME = 156;
130130

131131
export interface ThreadComposerProps {
132132
readonly canOperateThread: boolean;
133-
readonly draftMessage: string;
134-
readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
135133
readonly placeholder: string;
136134
readonly contentMaxWidth?: number;
137135
readonly bottomInset?: number;
@@ -349,20 +347,23 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
349347

350348
const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
351349
const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
350+
const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
351+
const composerDraftKey = props.draftKey ?? composerOwnerKey;
352+
const { text: draftMessage, attachments: draftAttachments } = useComposerDraft(composerDraftKey);
352353
const queuedEdit = props.queuedEdit ?? null;
353354
const hasContent =
354-
props.draftMessage.trim().length > 0 ||
355-
props.draftAttachments.length > 0 ||
355+
draftMessage.trim().length > 0 ||
356+
draftAttachments.length > 0 ||
356357
(queuedEdit?.existingAttachments.length ?? 0) > 0;
357-
const stripAttachments = composerStripAttachments(props.draftAttachments);
358+
const stripAttachments = composerStripAttachments(draftAttachments);
358359
const showStopAction = !hasContent && props.canStopThread && queuedEdit === null;
359360

360361
const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
361362
const attachmentsUploading =
362363
props.connectionState === "connected" &&
363364
composerAttachmentsStillUploading({
364365
environmentId: props.environmentId,
365-
attachments: props.draftAttachments,
366+
attachments: draftAttachments,
366367
serverConfig: props.serverConfig,
367368
states: uploadStates,
368369
});
@@ -392,8 +393,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
392393
) ?? null
393394
);
394395
})();
395-
const composerOwnerKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
396-
const composerDraftKey = props.draftKey ?? composerOwnerKey;
397396
const openDraftDocument = (attachment: ComposerDocumentAttachment) => {
398397
Keyboard.dismiss();
399398
navigation.navigate("ThreadAttachment", {
@@ -429,7 +428,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
429428
};
430429

431430
const composerMenu = useComposerCommandMenu({
432-
draftMessage: props.draftMessage,
431+
draftMessage: draftMessage,
433432
ownerKey: composerOwnerKey,
434433
environmentId: props.environmentId,
435434
threadShells: useThreadShells(),
@@ -450,7 +449,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
450449
: props.onUpdateInteractionMode,
451450
offersUsageLimits: usageLimitsOffered,
452451
onUsageLimits:
453-
usageLimitsOffered && props.draftAttachments.length === 0 ? openUsageLimits : undefined,
452+
usageLimitsOffered && draftAttachments.length === 0 ? openUsageLimits : undefined,
454453
});
455454
const voiceInput = useVoiceInputController({
456455
ownerKey: composerDraftKey,
@@ -471,7 +470,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
471470
const isToolbarVisible = isExpanded || isVoiceInputPresented;
472471
const attachmentBlockReason = composerAttachmentUploadBlockReason({
473472
environmentId: props.environmentId,
474-
attachments: props.draftAttachments,
473+
attachments: draftAttachments,
475474
connected: props.connectionState === "connected",
476475
serverConfig: props.serverConfig,
477476
states: uploadStates,
@@ -501,7 +500,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
501500
(current) =>
502501
current ?? {
503502
...source,
504-
gallery: filePreviewGallery(source, composerImageGallery(props.draftAttachments)),
503+
gallery: filePreviewGallery(source, composerImageGallery(draftAttachments)),
505504
},
506505
);
507506
};
@@ -538,11 +537,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
538537
};
539538
const handleSend = async (followUp?: ActiveTurnComposerAction) => {
540539
if (voiceInput.blocksSubmission || pendingPastedTextAttachmentCountRef.current > 0) return;
541-
if (
542-
usageLimitsOffered &&
543-
isUsageLimitsCommand(props.draftMessage) &&
544-
props.draftAttachments.length === 0
545-
) {
540+
if (usageLimitsOffered && isUsageLimitsCommand(draftMessage) && draftAttachments.length === 0) {
546541
if (openUsageLimits()) onChangeDraftMessage("");
547542
return;
548543
}
@@ -808,7 +803,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
808803
onInertChipPress={() => inputRef.current?.focus()}
809804
ref={inputRef}
810805
multiline
811-
value={props.draftMessage}
806+
value={draftMessage}
812807
readOnly={voiceInput.freezesEditor}
813808
skills={composerMenu.skills}
814809
selection={composerMenu.selection}

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

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe
8888
import { collectProviderUsageLimits } from "@t3tools/shared/usageLimits";
8989
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
9090
import type { StatusTone } from "../../components/StatusPill";
91-
import type { DraftComposerAttachment } from "../../lib/composerImages";
91+
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
9292
import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";
9393
import {
9494
ANDROID_READING_MAX_WIDTH,
@@ -187,8 +187,6 @@ export interface ThreadDetailScreenProps {
187187
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
188188
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
189189
readonly respondingUserInputId: RuntimeRequestId | null;
190-
readonly draftMessage: string;
191-
readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
192190
readonly connectionStateLabel: EnvironmentConnectionPhase;
193191
readonly threadSyncStatus?: EnvironmentThreadStatus;
194192
readonly historyControls?: ThreadFeedHistoryControls;
@@ -949,8 +947,10 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
949947
};
950948

951949
const handleUseArtifactTemplate = (template: CodexArtifactTemplate) => {
952-
const nextDraft = appendCodexArtifactTemplateUsePrompt(props.draftMessage, template);
953-
if (nextDraft !== props.draftMessage) props.onChangeDraftMessage(nextDraft);
950+
const draftMessage =
951+
props.composerDraftKey === null ? "" : getComposerDraftSnapshot(props.composerDraftKey).text;
952+
const nextDraft = appendCodexArtifactTemplateUsePrompt(draftMessage, template);
953+
if (nextDraft !== draftMessage) props.onChangeDraftMessage(nextDraft);
954954
requestAnimationFrame(() => {
955955
composerEditorRef.current?.focus();
956956
composerEditorRef.current?.setSelection({ start: nextDraft.length, end: nextDraft.length });
@@ -1300,8 +1300,6 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
13001300
canOperateThread={props.canOperateThread}
13011301
reportedModelSelection={reportedModelSelection}
13021302
editorRef={composerEditorRef}
1303-
draftMessage={props.draftMessage}
1304-
draftAttachments={props.draftAttachments}
13051303
placeholder="Ask the repo agent, or run a command…"
13061304
contentMaxWidth={contentMaxWidth}
13071305
connectionState={props.connectionStateLabel}

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

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -926,8 +926,6 @@ function ThreadRouteContent(
926926
activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
927927
activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
928928
respondingUserInputId={requests.respondingUserInputId}
929-
draftMessage={composer.draftMessage}
930-
draftAttachments={composer.draftAttachments}
931929
connectionStateLabel={routeConnectionState}
932930
threadSyncStatus={selectedThreadDetailState.status}
933931
historyControls={historyControls}

‎apps/mobile/src/state/composer-attachment-uploads.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { flattenQueuedThreadMessages, threadOutboxManager } from "./thread-outbo
2020
import { useThreadOutboxMessages } from "./use-thread-outbox";
2121
import {
2222
composerDraftsAtom,
23+
composerDraftUploadSourcesAtom,
2324
ensureComposerDraftsLoaded,
2425
flushComposerDrafts,
2526
setComposerDraftAttachmentUpload,
@@ -55,7 +56,7 @@ export function retryComposerAttachmentUpload(environmentId: EnvironmentId, atta
5556
}
5657

5758
export function useComposerAttachmentUploadWorker() {
58-
const drafts = useAtomValue(composerDraftsAtom);
59+
const drafts = useAtomValue(composerDraftUploadSourcesAtom);
5960
const queuedMessages = useThreadOutboxMessages();
6061
const serverConfigs = useServerConfigs();
6162
const { connectedEnvironments } = useRemoteConnectionStatus();

‎apps/mobile/src/state/thread-task-permissions.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,8 @@ vi.mock("./use-composer-drafts", async () => {
126126
mergeComposerDraftContent: vi.fn(),
127127
removeComposerDraftAttachment: vi.fn(),
128128
useComposerDraft: () => state.draft,
129+
useComposerDraftSettings: () => ({}),
130+
questionAttachmentDraftsAtom: () => Atom.make({}),
129131
};
130132
});
131133
vi.mock("../lib/composerImages", () => ({

‎apps/mobile/src/state/use-composer-drafts.ts‎

Lines changed: 100 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -171,16 +171,18 @@ function withReferencedContextFiles(
171171
const retainedIds = new Set(
172172
context?.records.flatMap((record) => ("attachmentId" in record ? [record.attachmentId] : [])),
173173
);
174+
const attachments = draft.attachments.filter(
175+
(attachment) =>
176+
attachment.type === "image" ||
177+
!previousIds.has(attachment.id) ||
178+
retainedIds.has(attachment.id),
179+
);
180+
// Keep the array identity on plain text edits so attachment readers see no change.
174181
return {
175182
...draft,
176183
text,
177184
context,
178-
attachments: draft.attachments.filter(
179-
(attachment) =>
180-
attachment.type === "image" ||
181-
!previousIds.has(attachment.id) ||
182-
retainedIds.has(attachment.id),
183-
),
185+
attachments: attachments.length === draft.attachments.length ? draft.attachments : attachments,
184186
};
185187
}
186188

@@ -1885,12 +1887,102 @@ export async function clearComposerDraftsEnvironment(environmentId: EnvironmentI
18851887
await releaseUnusedComposerAttachmentFiles(removedAttachments);
18861888
}
18871889

1890+
// One atom per draft key, so typing in one composer only notifies readers of
1891+
// that draft instead of every subscriber to the whole drafts map.
1892+
const composerDraftAtom = Atom.family((draftKey: string) =>
1893+
Atom.make((get) => get(composerDraftsAtom)[draftKey] ?? EMPTY_DRAFT),
1894+
);
1895+
const EMPTY_DRAFT_ATOM = Atom.make(EMPTY_DRAFT);
1896+
1897+
type ComposerDraftsByKey = Readonly<Record<string, ComposerDraft>>;
1898+
const EMPTY_DRAFTS: ComposerDraftsByKey = {};
1899+
function sameDrafts(a: ComposerDraftsByKey, b: ComposerDraftsByKey): boolean {
1900+
const keys = Object.keys(a);
1901+
return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);
1902+
}
1903+
// The question drafts under one key prefix. Equal while only other drafts change
1904+
// (the open thread's composer text, for example), so typing does not notify readers.
1905+
export const questionAttachmentDraftsAtom = Atom.family((prefix: string) =>
1906+
Atom.make((get): ComposerDraftsByKey => {
1907+
if (prefix === "") return EMPTY_DRAFTS;
1908+
const matching = Object.entries(get(composerDraftsAtom)).filter(([key]) =>
1909+
key.startsWith(prefix),
1910+
);
1911+
return matching.length === 0 ? EMPTY_DRAFTS : Object.fromEntries(matching);
1912+
}).pipe(Atom.withEquality(sameDrafts)),
1913+
);
1914+
1915+
// New-task drafts only; equal while a thread composer's text changes.
1916+
export const newTaskComposerDraftsAtom = Atom.make((get): ComposerDraftsByKey => {
1917+
const matching = Object.entries(get(composerDraftsAtom)).filter(([key]) =>
1918+
isNewTaskDraftKey(key),
1919+
);
1920+
return matching.length === 0 ? EMPTY_DRAFTS : Object.fromEntries(matching);
1921+
}).pipe(Atom.withEquality(sameDrafts));
1922+
1923+
type ComposerDraftUploadSource = Pick<ComposerDraft, "attachments" | "project">;
1924+
// What the upload worker reads: equal while only draft text changes.
1925+
type ComposerDraftUploadSources = Readonly<Record<string, ComposerDraftUploadSource>>;
1926+
export const composerDraftUploadSourcesAtom = Atom.make((get): ComposerDraftUploadSources =>
1927+
Object.fromEntries(
1928+
Object.entries(get(composerDraftsAtom)).map(([key, draft]) => [
1929+
key,
1930+
{ attachments: draft.attachments, project: draft.project },
1931+
]),
1932+
),
1933+
).pipe(
1934+
Atom.withEquality((a: ComposerDraftUploadSources, b: ComposerDraftUploadSources) => {
1935+
const keys = Object.keys(a);
1936+
return (
1937+
keys.length === Object.keys(b).length &&
1938+
keys.every(
1939+
(key) => a[key]?.attachments === b[key]?.attachments && a[key]?.project === b[key]?.project,
1940+
)
1941+
);
1942+
}),
1943+
);
1944+
1945+
type ComposerDraftSettings = Pick<
1946+
ComposerDraft,
1947+
"modelSelection" | "runtimeMode" | "interactionMode"
1948+
>;
1949+
const EMPTY_DRAFT_SETTINGS: ComposerDraftSettings = {};
1950+
// Text edits copy the other fields by reference, so this stays equal while typing.
1951+
const composerDraftSettingsAtom = Atom.family((draftKey: string) =>
1952+
Atom.make((get): ComposerDraftSettings => {
1953+
const draft = get(composerDraftAtom(draftKey));
1954+
return {
1955+
modelSelection: draft.modelSelection,
1956+
runtimeMode: draft.runtimeMode,
1957+
interactionMode: draft.interactionMode,
1958+
};
1959+
}).pipe(
1960+
Atom.withEquality(
1961+
(a: ComposerDraftSettings, b: ComposerDraftSettings) =>
1962+
a.modelSelection === b.modelSelection &&
1963+
a.runtimeMode === b.runtimeMode &&
1964+
a.interactionMode === b.interactionMode,
1965+
),
1966+
),
1967+
);
1968+
const EMPTY_DRAFT_SETTINGS_ATOM = Atom.make(EMPTY_DRAFT_SETTINGS);
1969+
1970+
export function useComposerDraftSettings(draftKey: string | null): ComposerDraftSettings {
1971+
const settings = useAtomValue(
1972+
draftKey ? composerDraftSettingsAtom(draftKey) : EMPTY_DRAFT_SETTINGS_ATOM,
1973+
);
1974+
useEffect(() => {
1975+
ensureComposerDraftsLoaded();
1976+
}, []);
1977+
return settings;
1978+
}
1979+
18881980
export function useComposerDraft(draftKey: string | null): ComposerDraft {
1889-
const drafts = useAtomValue(composerDraftsAtom);
1981+
const draft = useAtomValue(draftKey ? composerDraftAtom(draftKey) : EMPTY_DRAFT_ATOM);
18901982
useEffect(() => {
18911983
ensureComposerDraftsLoaded();
18921984
}, []);
1893-
return draftKey ? normalizeDraft(drafts[draftKey]) : EMPTY_DRAFT;
1985+
return draft;
18941986
}
18951987

18961988
export function useStickyComposerModelSelection(): ModelSelection | null {

‎apps/mobile/src/state/use-pending-new-tasks.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
22
import { useMemo } from "react";
33
import { buildPendingNewTasks, type PendingNewTask } from "./pending-new-tasks-model";
44
import { flattenQueuedThreadMessages } from "./thread-outbox-model";
5-
import { composerDraftsAtom } from "./use-composer-drafts";
5+
import { newTaskComposerDraftsAtom } from "./use-composer-drafts";
66
import { useThreadOutboxMessages } from "./use-thread-outbox";
77

88
export type {
@@ -13,7 +13,7 @@ export type {
1313

1414
export function usePendingNewTasks(): ReadonlyArray<PendingNewTask> {
1515
const queuedMessagesByThreadKey = useThreadOutboxMessages();
16-
const drafts = useAtomValue(composerDraftsAtom);
16+
const drafts = useAtomValue(newTaskComposerDraftsAtom);
1717
return useMemo(
1818
() =>
1919
buildPendingNewTasks({

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ vi.mock("@effect/atom-react", () => ({
1919
: {},
2020
}));
2121
vi.mock("./use-composer-drafts", () => ({
22-
composerDraftsAtom: "drafts",
22+
composerDraftsAtom: "all-drafts",
23+
questionAttachmentDraftsAtom: () => "drafts",
2324
clearComposerDraft: vi.fn(),
2425
}));
2526
vi.mock("./composer-attachment-uploads", async () => ({

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@ import {
55
questionAttachmentDraftPrefix,
66
questionAttachmentPreparationAtom,
77
} from "./question-attachments";
8-
import { composerDraftsAtom, clearComposerDraft } from "./use-composer-drafts";
8+
import {
9+
clearComposerDraft,
10+
composerDraftsAtom,
11+
questionAttachmentDraftsAtom,
12+
} from "./use-composer-drafts";
913
import {
1014
composerAttachmentUploadsAtom,
1115
composerAttachmentUploadBlockReason,
@@ -119,7 +123,13 @@ export function useSelectedThreadRequests() {
119123
}
120124
}, [activePendingUserInput, selectedThreadShell]);
121125
const questionServerConfigs = useServerConfigs();
122-
const attachmentDrafts = useAtomValue(composerDraftsAtom);
126+
const attachmentDrafts = useAtomValue(
127+
questionAttachmentDraftsAtom(
128+
selectedThreadShell
129+
? questionAttachmentDraftPrefix(selectedThreadShell.environmentId, selectedThreadShell.id)
130+
: "",
131+
),
132+
);
123133
const preparationCounts = useAtomValue(questionAttachmentPreparationAtom);
124134
const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
125135
useEffect(() => {

0 commit comments

Comments
 (0)