Skip to content

Commit db1b617

Browse files
wesbillmanBrain
andauthored
perf(desktop): stop typing from re-rendering the channel pane + timeline (#1364)
Signed-off-by: Wes <[email protected]> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co>
1 parent 59be27f commit db1b617

15 files changed

Lines changed: 443 additions & 188 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,6 +412,7 @@ description. See [PR #803](https://github.com/block/buzz/pull/803).
412412
4. **Worktrees: `cd` in the same command** — shell CWD doesn't persist between tool calls. Use `cd /path && cargo build` as one command.
413413
5. **Desktop crate excluded from root workspace** — `cargo test` at repo root does NOT run desktop tests. Use `cargo test --manifest-path desktop/src-tauri/Cargo.toml` explicitly.
414414
6. **Desktop Tauri fmt fails in worktrees and blocks commits** — the pre-commit hook runs `just desktop-tauri-fmt`, which fails in git worktrees because `cargo fmt` resolves workspace paths relative to the worktree root. Run `just desktop-tauri-fmt` from the main checkout to apply the fix, then re-stage and commit. CI is unaffected.
415+
7. **React render perf: `React.memo` is all-or-nothing** — it only skips a re-render when *every* prop is reference-stable; one unstable prop (inline arrow/JSX, or a hook returning a fresh `{}`/`[]`/`Map` each render) defeats it. Two repeat offenders: (a) React Query results (`useMutation`/`useQuery`) are a **new object each render** — depend on the stable method (`mutation.mutateAsync`), not the object; (b) derived `Map`/array state that recomputes on a version bump — wrap in a content-equality ref cache (`shared/hooks/useStableReference.ts`). When chasing interaction lag, **measure with DevTools closed and no perf probes** (an open Web Inspector + per-keystroke `console.log` inflate the numbers), and isolate by removing one suspect at a time rather than guessing.
415416

416417
---
417418

‎desktop/src/features/channels/ui/ChannelScreen.tsx‎

Lines changed: 89 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,7 @@ export function ChannelScreen({
528528
(message: TimelineMessage) => handleMarkMessageRead(message.id),
529529
[handleMarkMessageRead],
530530
);
531+
const sendMessageMutateAsync = sendMessageMutation.mutateAsync;
531532
const handleSendVideoReviewComment = React.useCallback(
532533
async (
533534
message: { id: string },
@@ -536,19 +537,32 @@ export function ChannelScreen({
536537
mediaTags?: string[][],
537538
parentEventId?: string,
538539
) => {
539-
await sendMessageMutation.mutateAsync({
540+
await sendMessageMutateAsync({
540541
content,
541542
mediaTags,
542543
mentionPubkeys,
543544
parentEventId: parentEventId ?? message.id,
544545
});
545546
},
546-
[sendMessageMutation],
547+
[sendMessageMutateAsync],
547548
);
548549
const effectiveSendVideoReviewComment =
549550
activeChannel && !activeChannel.archivedAt && activeChannel.isMember
550551
? handleSendVideoReviewComment
551552
: undefined;
553+
const handleOpenAddBot = React.useCallback(() => setIsAddBotOpen(true), []);
554+
const handleOpenMembersSidebar = React.useCallback(
555+
() => setIsMembersSidebarOpen(true),
556+
[],
557+
);
558+
const handleCloseChannelManagement = React.useCallback(
559+
() => setChannelManagementOpen(false),
560+
[setChannelManagementOpen],
561+
);
562+
const handleChannelManagementDeleted = React.useCallback(() => {
563+
setChannelManagementOpen(false);
564+
void goHome({ replace: true });
565+
}, [setChannelManagementOpen, goHome]);
552566
const {
553567
agentSessionAgents,
554568
channelAgentSessionAgents,
@@ -727,44 +741,77 @@ export function ChannelScreen({
727741
enabled: !isSinglePanelView,
728742
});
729743

730-
const channelHeader = (
731-
<ChannelScreenHeader
732-
activeChannel={activeChannel}
733-
activeChannelEphemeralDisplay={activeChannelEphemeralDisplay}
734-
activeChannelTitle={activeChannelTitle}
735-
actionsVariant={shouldCompactHeaderActions ? "compact" : "inline"}
736-
activeDmAvatarUrl={activeDmAvatarUrl}
737-
activeDmHeaderParticipants={activeDmHeaderParticipants}
738-
activeDmPresenceStatus={activeDmPresenceStatus}
739-
chromeWrapperRef={channelHeaderChromeRef}
740-
currentPubkey={currentPubkey}
741-
isAddBotOpen={isAddBotOpen}
742-
isJoining={joinChannelMutation.isPending}
743-
onAddBotOpenChange={setIsAddBotOpen}
744-
onJoinChannel={joinChannelMutation.mutateAsync}
745-
onManageChannel={() => {
746-
if (activeChannel?.channelType === "forum") {
747-
openGlobalChannelManagement();
748-
return;
749-
}
744+
const handleManageChannel = React.useCallback(() => {
745+
if (activeChannel?.channelType === "forum") {
746+
openGlobalChannelManagement();
747+
return;
748+
}
750749

751-
if (channelManagementOpen) {
752-
setChannelManagementOpen(false);
753-
return;
754-
}
750+
if (channelManagementOpen) {
751+
setChannelManagementOpen(false);
752+
return;
753+
}
754+
755+
setOpenThreadHeadId(null);
756+
setExpandedThreadReplyIds(new Set());
757+
setThreadScrollTargetId(null);
758+
setThreadReplyTargetId(null);
759+
handleCloseAgentSession();
760+
setProfilePanelPubkey(null);
761+
setChannelManagementOpen(true);
762+
}, [
763+
activeChannel?.channelType,
764+
channelManagementOpen,
765+
openGlobalChannelManagement,
766+
setChannelManagementOpen,
767+
setOpenThreadHeadId,
768+
handleCloseAgentSession,
769+
setProfilePanelPubkey,
770+
]);
771+
const handleToggleMembers = React.useCallback(
772+
() => setIsMembersSidebarOpen((prev) => !prev),
773+
[],
774+
);
755775

756-
setOpenThreadHeadId(null);
757-
setExpandedThreadReplyIds(new Set());
758-
setThreadScrollTargetId(null);
759-
setThreadReplyTargetId(null);
760-
handleCloseAgentSession();
761-
setProfilePanelPubkey(null);
762-
setChannelManagementOpen(true);
763-
}}
764-
onToggleMembers={() => setIsMembersSidebarOpen((prev) => !prev)}
765-
showHeaderContent={!isSinglePanelView}
766-
transparentChrome={activeChannel?.channelType !== "forum"}
767-
/>
776+
const channelHeader = React.useMemo(
777+
() => (
778+
<ChannelScreenHeader
779+
activeChannel={activeChannel}
780+
activeChannelEphemeralDisplay={activeChannelEphemeralDisplay}
781+
activeChannelTitle={activeChannelTitle}
782+
actionsVariant={shouldCompactHeaderActions ? "compact" : "inline"}
783+
activeDmAvatarUrl={activeDmAvatarUrl}
784+
activeDmHeaderParticipants={activeDmHeaderParticipants}
785+
activeDmPresenceStatus={activeDmPresenceStatus}
786+
chromeWrapperRef={channelHeaderChromeRef}
787+
currentPubkey={currentPubkey}
788+
isAddBotOpen={isAddBotOpen}
789+
isJoining={joinChannelMutation.isPending}
790+
onAddBotOpenChange={setIsAddBotOpen}
791+
onJoinChannel={joinChannelMutation.mutateAsync}
792+
onManageChannel={handleManageChannel}
793+
onToggleMembers={handleToggleMembers}
794+
showHeaderContent={!isSinglePanelView}
795+
transparentChrome={activeChannel?.channelType !== "forum"}
796+
/>
797+
),
798+
[
799+
activeChannel,
800+
activeChannelEphemeralDisplay,
801+
activeChannelTitle,
802+
shouldCompactHeaderActions,
803+
activeDmAvatarUrl,
804+
activeDmHeaderParticipants,
805+
activeDmPresenceStatus,
806+
channelHeaderChromeRef,
807+
currentPubkey,
808+
isAddBotOpen,
809+
joinChannelMutation.isPending,
810+
joinChannelMutation.mutateAsync,
811+
handleManageChannel,
812+
handleToggleMembers,
813+
isSinglePanelView,
814+
],
768815
);
769816

770817
return (
@@ -807,9 +854,9 @@ export function ChannelScreen({
807854
fetchOlder={fetchOlder}
808855
header={channelHeader}
809856
hasOlderMessages={hasOlderMessages}
810-
onAddAgent={() => setIsAddBotOpen(true)}
857+
onAddAgent={handleOpenAddBot}
811858
onCreateChannel={openCreateChannel}
812-
onOpenMembers={() => setIsMembersSidebarOpen(true)}
859+
onOpenMembers={handleOpenMembersSidebar}
813860
isFetchingOlder={isFetchingOlder}
814861
editTarget={
815862
editTargetMessage
@@ -834,10 +881,7 @@ export function ChannelScreen({
834881
messages={timelineMessages}
835882
onCancelEdit={handleCancelEdit}
836883
onCancelThreadReply={handleCancelThreadReply}
837-
onChannelManagementDeleted={() => {
838-
setChannelManagementOpen(false);
839-
void goHome({ replace: true });
840-
}}
884+
onChannelManagementDeleted={handleChannelManagementDeleted}
841885
onFollowThread={
842886
effectiveOpenThreadHeadId != null &&
843887
!isNotifiedForEffectiveThread
@@ -851,9 +895,7 @@ export function ChannelScreen({
851895
: undefined
852896
}
853897
onCloseAgentSession={handleCloseAgentSession}
854-
onCloseChannelManagement={() =>
855-
setChannelManagementOpen(false)
856-
}
898+
onCloseChannelManagement={handleCloseChannelManagement}
857899
onCloseThread={handleCloseThread}
858900
onDelete={
859901
activeChannel?.archivedAt ? undefined : handleDelete

‎desktop/src/features/channels/ui/useChannelProfilePanel.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,13 @@ export function useChannelProfilePanel({
5050
setProfilePanelPubkey(null);
5151
}, [setProfilePanelPubkey]);
5252

53+
const openDmMutateAsync = openDmMutation.mutateAsync;
5354
const handleOpenDm = React.useCallback(
5455
async (pubkeys: string[]) => {
55-
const dm = await openDmMutation.mutateAsync({ pubkeys });
56+
const dm = await openDmMutateAsync({ pubkeys });
5657
await goChannel(dm.id);
5758
},
58-
[goChannel, openDmMutation],
59+
[goChannel, openDmMutateAsync],
5960
);
6061

6162
return {

‎desktop/src/features/channels/ui/useChannelUnreadState.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ import {
88
} from "@/features/channels/lib/subtreeCreatedAt";
99
import { computeThreadReplyUnreadCounts } from "@/features/channels/lib/threadReplyUnreadCounts";
1010
import { computeThreadBadgeCounts } from "@/features/channels/lib/threadBadgeCounts";
11+
import {
12+
useStableArrayShallow,
13+
useStableMap,
14+
} from "@/shared/hooks/useStableReference";
1115
import {
1216
buildThreadPanelDataFromIndex,
1317
buildThreadPanelIndex,
@@ -174,7 +178,7 @@ export function useChannelUnreadState({
174178
],
175179
);
176180
const openThreadHeadMessage = threadPanelData.threadHead;
177-
const threadMessages = threadPanelData.visibleReplies;
181+
const threadMessages = useStableArrayShallow(threadPanelData.visibleReplies);
178182
const threadReplyTargetMessage = threadPanelData.replyTargetMessage;
179183

180184
// Oldest unread top-level message + count from the open-time frontier.
@@ -332,7 +336,7 @@ export function useChannelUnreadState({
332336
// (LP4 Issue 2 by construction). readStateVersion is an intentional recompute
333337
// trigger so the badge re-reads after any marker advances.
334338
// biome-ignore lint/correctness/useExhaustiveDependencies: readStateVersion and forcedUnreadVersion are intentional recompute triggers
335-
const threadUnreadCounts = React.useMemo(
339+
const threadUnreadCountsRaw = React.useMemo(
336340
() =>
337341
computeThreadBadgeCounts(
338342
timelineMessages,
@@ -353,6 +357,11 @@ export function useChannelUnreadState({
353357
forcedUnreadVersion,
354358
],
355359
);
360+
// Keep the same Map reference across recomputes when the entries are
361+
// unchanged. readStateVersion bumps on read-state activity (frequent in busy
362+
// channels) and recomputes a fresh Map even when no count changed; without
363+
// this, every bump hands the timeline a new prop ref and reconciles all rows.
364+
const threadUnreadCounts = useStableMap(threadUnreadCountsRaw);
356365

357366
// Per-message unread predicate for the mark-read/unread menu toggle. Reuses
358367
// computeThreadUnreadMarker — the exact function the badge counts call

‎desktop/src/features/channels/useEphemeralChannelDisplay.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,20 @@ export function useEphemeralChannelDisplay(channel: Channel | null) {
2424
};
2525
}, [deadlineKey]);
2626

27-
return channel ? getEphemeralChannelDisplay(channel, Date.now()) : null;
27+
const display = channel
28+
? getEphemeralChannelDisplay(channel, Date.now())
29+
: null;
30+
// Stabilise the reference across renders when the rendered content is
31+
// unchanged: this object is recomputed from Date.now() every render, and it
32+
// feeds memoised header/timeline subtrees — a fresh ref each render would
33+
// defeat their React.memo on every background re-render.
34+
const stableRef = React.useRef(display);
35+
const prev = stableRef.current;
36+
if (
37+
prev?.detailLabel !== display?.detailLabel ||
38+
prev?.tooltipLabel !== display?.tooltipLabel
39+
) {
40+
stableRef.current = display;
41+
}
42+
return stableRef.current;
2843
}

‎desktop/src/features/forum/ui/ForumComposer.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,11 @@ export function ForumComposer({
9999
isAutocompleteOpen: isAutocompleteOpenRef,
100100
onEditLink: (info) => onEditLinkRef.current?.(info),
101101
onLinkSelectionChange: (info) => onLinkSelectionChangeRef.current?.(info),
102-
onUpdate: ({ markdown, text }) => {
102+
onUpdate: ({ cursor, text }) => {
103+
const markdown = richText.getMarkdown();
103104
setContent(markdown);
104105
contentRef.current = markdown;
105106

106-
const { cursor } = richText.getPlainTextAndCursor();
107107
mentions.updateMentionQuery(text, cursor);
108108
channelLinks.updateChannelQuery(text, cursor);
109109
},

‎desktop/src/features/messages/lib/useMediaUpload.ts‎

Lines changed: 40 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -530,26 +530,46 @@ export function useMediaUpload() {
530530

531531
const isUploading = uploadingCount > 0;
532532

533-
return {
534-
cancelUpload,
535-
handleDragEnter,
536-
handleDragLeave,
537-
handleDragOver,
538-
handleDrop,
539-
handlePaperclip,
540-
handlePaste,
541-
isDragOver,
542-
isUploading,
543-
pendingImeta,
544-
pendingImetaRef,
545-
removeAttachment,
546-
setPendingImeta,
547-
setUploadState,
548-
uploadFile,
549-
uploadingCount,
550-
uploadingPreviews,
551-
uploadState,
552-
};
533+
return React.useMemo(
534+
() => ({
535+
cancelUpload,
536+
handleDragEnter,
537+
handleDragLeave,
538+
handleDragOver,
539+
handleDrop,
540+
handlePaperclip,
541+
handlePaste,
542+
isDragOver,
543+
isUploading,
544+
pendingImeta,
545+
pendingImetaRef,
546+
removeAttachment,
547+
setPendingImeta,
548+
setUploadState,
549+
uploadFile,
550+
uploadingCount,
551+
uploadingPreviews,
552+
uploadState,
553+
}),
554+
[
555+
cancelUpload,
556+
handleDragEnter,
557+
handleDragLeave,
558+
handleDragOver,
559+
handleDrop,
560+
handlePaperclip,
561+
handlePaste,
562+
isDragOver,
563+
isUploading,
564+
pendingImeta,
565+
removeAttachment,
566+
setPendingImeta,
567+
uploadFile,
568+
uploadingCount,
569+
uploadingPreviews,
570+
uploadState,
571+
],
572+
);
553573
}
554574

555575
export type MediaUploadController = ReturnType<typeof useMediaUpload>;

‎desktop/src/features/messages/lib/useRichTextEditor.ts‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ export type AutocompleteEdit = {
5353

5454
export type RichTextEditorOptions = {
5555
placeholder?: string;
56-
onUpdate?: (info: { markdown: string; text: string }) => void;
56+
onUpdate?: (info: { text: string; cursor: number }) => void;
5757
editable?: boolean;
5858
mentionNames?: string[];
5959
agentMentionNames?: string[];
@@ -459,13 +459,15 @@ export function useRichTextEditor({
459459
},
460460
},
461461
onUpdate: ({ editor: ed }) => {
462-
const markdown = getMarkdownFromEditor(ed);
463-
// Use the same plain-text projection that `getPlainTextAndCursor`
464-
// uses, so autocomplete detection sees the *same* string the
465-
// cursor offset is mapped against. `state.doc.textContent` would
466-
// diverge by 1 per hard-break / block boundary.
467-
const text = buildPlainTextProjection(ed.state.doc).text;
468-
onUpdateRef.current?.({ markdown, text });
462+
// Keep the hot typing path lightweight. Markdown serialization is
463+
// still available through `getMarkdown()` for send/draft boundaries;
464+
// per-keystroke consumers only need textarea-shaped plain text for
465+
// autocomplete and empty/non-empty state.
466+
const projection = buildPlainTextProjection(ed.state.doc);
467+
onUpdateRef.current?.({
468+
cursor: projection.mapPMToTextOffset(ed.state.selection.anchor),
469+
text: projection.text,
470+
});
469471
},
470472
},
471473
[],

0 commit comments

Comments
 (0)