@devries-cameron20 / t3code-1 / commits / d913b61603
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(web): the React Compiler compiles MessagesTimeline (#20402)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 16, 2026 at 18:06 UTC d913b61603a3dce6d2765f9cfab83cfc84b45ccd
4 files changed +479 -630
apps/web/reactCompiledFiles.ts
+1
@@ -9,6 +9,7 @@ export const REACT_COMPILED_FILES = [
9 "apps/web/src/components/Sidebar.tsx",
10 "apps/web/src/components/chat/ChatComposer.tsx",
11 "apps/web/src/components/chat/usePendingThreadRequests.ts",
12 + "apps/web/src/components/chat/MessagesTimeline.tsx",
13 "apps/web/src/components/chat/composerFocusRedirect.ts",
14 "apps/web/src/components/chat/useChatShortcuts.ts",
15 "apps/web/src/components/chat/useProjectScriptEditing.ts",
apps/web/src/components/chat/ExpandedImagePreview.tsx
+1 -1
@@ -106,7 +106,7 @@ export async function resolveMarkdownMediaPreview(input: {
106
107 export function buildAttachmentVideoAsset(
108 environmentId: EnvironmentId,
109 - attachment: ChatFileAttachment,
109 + attachment: Pick<ChatFileAttachment, "id" | "name" | "mimeType">,
110 ): NonNullable<MediaActionSource["asset"]> {
111 return {
112 environmentId,
apps/web/src/components/chat/MessagesTimeline.tsx
+475 -629
@@ -1,4 +1,5 @@
1 import { ThreadFindTimelineContext } from "./ThreadFindProvider";
2 +import { shallow } from "zustand/vanilla/shallow";
3 import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
4 import { MarkdownFindContext, useFindRevealRef } from "./markdownFindContext";
5 import { useChatCanvas } from "./ChatCanvasContext";
@@ -72,11 +73,9 @@ import {
73 createContext,
74 memo,
75 use,
75 - useCallback,
76 useContext,
77 useEffect,
78 useLayoutEffect,
79 - useMemo,
79 useRef,
80 useState,
81 type KeyboardEvent,
@@ -182,6 +181,7 @@ import { useProject, useThreadShell } from "../../state/entities";
181 import {
182 CHAT_TIMELINE_ANCHOR_OFFSET,
183 readTimelinePosition,
184 + type RememberedTimelinePosition,
185 rememberTimelinePosition,
186 timelineContentOverflowsViewport,
187 } from "./timelineScrollAnchoring";
@@ -374,6 +374,22 @@ const WorkGroupViewCtx = createContext<{
374 state: WorkGroupViewState;
375 onToggleEntry: (collapsed: boolean) => void;
376 } | null>(null);
377 +function timelineListStateFor(identity: string): {
378 + readonly identity: string;
379 + readonly rememberedPosition: RememberedTimelinePosition | undefined;
380 + readonly workGroupViewState: WorkGroupViewState;
381 +} {
382 + const rememberedPosition = readTimelinePosition(identity);
383 + return {
384 + identity,
385 + rememberedPosition,
386 + workGroupViewState: rememberedPosition?.disclosures?.workGroupState ?? {
387 + scrollPositions: new Map(),
388 + expandedEntries: new Set(),
389 + },
390 + };
391 +}
392 +
393 const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
394 const TIMELINE_LIST_FADE_HEADER = (
395 <div className="h-[var(--workspace-titlebar-scroll-fade-height)]" />
@@ -591,34 +607,34 @@ const ConversationTimeline = memo(function ConversationTimeline({
607 loadEarlier = null,
608 }: MessagesTimelineProps) {
609 const listIdentityKey = displayThreadKey ?? routeThreadKey;
594 - const rememberedPosition = useMemo(
595 - () => readTimelinePosition(listIdentityKey),
596 - [listIdentityKey],
597 - );
610 + // The remembered position is a snapshot taken when the list identity changes;
611 + // scrolling keeps rewriting the stored entry, which must not move the restore.
612 + const [listState, setListState] = useState(() => timelineListStateFor(listIdentityKey));
613 const [expandedRunIds, setExpandedRunIds] = useState<ReadonlySet<RunId>>(
599 - () => rememberedPosition?.disclosures?.runs ?? new Set(),
614 + () => listState.rememberedPosition?.disclosures?.runs ?? new Set(),
615 );
616 const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(
602 - () => rememberedPosition?.disclosures?.workGroups ?? new Set(),
617 + () => listState.rememberedPosition?.disclosures?.workGroups ?? new Set(),
618 );
619 const [expandedAttemptIds, setExpandedAttemptIds] = useState<ReadonlySet<RunAttemptId>>(
605 - () => rememberedPosition?.disclosures?.attempts ?? new Set(),
620 + () => listState.rememberedPosition?.disclosures?.attempts ?? new Set(),
621 );
622 const [positionedThreadKey, setPositionedThreadKey] = useState<string | null>(() =>
608 - rememberedPosition?.atEnd === false ? null : listIdentityKey,
623 + listState.rememberedPosition?.atEnd === false ? null : listIdentityKey,
624 );
625 const restoringThreadPosition = positionedThreadKey !== listIdentityKey;
626 const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
612 - const listIdentityRef = useRef(listIdentityKey);
613 - const previousLatestRunRef = useRef(latestRun);
627 const [settlingListIdentity, setSettlingListIdentity] = useState<string | null>(listIdentityKey);
628 let paintedExpandedRunIds = expandedRunIds;
629 let paintedExpandedWorkGroupIds = expandedWorkGroupIds;
630 let paintedExpandedAttemptIds = expandedAttemptIds;
618 - if (listIdentityRef.current !== listIdentityKey) {
619 - listIdentityRef.current = listIdentityKey;
631 + const identityChanged = listState.identity !== listIdentityKey;
632 + const { rememberedPosition, workGroupViewState } = identityChanged
633 + ? timelineListStateFor(listIdentityKey)
634 + : listState;
635 + if (identityChanged) {
636 + setListState({ identity: listIdentityKey, rememberedPosition, workGroupViewState });
637 setPositionedThreadKey(null);
621 - previousLatestRunRef.current = latestRun;
638 setSettlingListIdentity(listIdentityKey);
639 paintedExpandedRunIds = rememberedPosition?.disclosures?.runs ?? new Set();
640 paintedExpandedWorkGroupIds = rememberedPosition?.disclosures?.workGroups ?? new Set();
@@ -627,19 +643,11 @@ const ConversationTimeline = memo(function ConversationTimeline({
643 setExpandedWorkGroupIds(paintedExpandedWorkGroupIds);
644 setExpandedAttemptIds(paintedExpandedAttemptIds);
645 }
630 - const citationThreadRef = useMemo(() => parseScopedThreadKey(routeThreadKey), [routeThreadKey]);
646 + const citationThreadRef = parseScopedThreadKey(routeThreadKey);
647 const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined);
632 - const expandCitedRun = useCallback((runId: RunId) => {
648 + const expandCitedRun = (runId: RunId) => {
649 setExpandedRunIds((current) => (current.has(runId) ? current : new Set([...current, runId])));
634 - }, []);
635 - const workGroupViewState = useMemo<WorkGroupViewState>(
636 - () =>
637 - rememberedPosition?.disclosures?.workGroupState ?? {
638 - scrollPositions: new Map(),
639 - expandedEntries: new Set(),
640 - },
641 - [listIdentityKey, rememberedPosition],
642 - );
650 + };
651 const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
652 const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
653 const disclosureAnchorKeyRef = useRef<string | null>(null);
@@ -675,13 +683,13 @@ const ConversationTimeline = memo(function ConversationTimeline({
683
684 const disclosurePinsEndRef = useRef(false);
685 const disclosureCollapsedRef = useRef(false);
678 - const pinDisclosureToEnd = useCallback(() => {
686 + const pinDisclosureToEnd = () => {
687 if (!disclosurePinsEndRef.current) return;
688 const element = listRef.current?.getScrollableNode();
689 if (element) element.scrollTop = element.scrollHeight;
682 - }, [listRef]);
690 + };
691
684 - const scheduleDisclosureSettle = useCallback(() => {
692 + const scheduleDisclosureSettle = () => {
693 if (disclosureSettleFrameRef.current !== null) {
694 cancelAnimationFrame(disclosureSettleFrameRef.current);
695 }
@@ -705,75 +713,64 @@ const ConversationTimeline = memo(function ConversationTimeline({
713 }
714 });
715 });
708 - }, [listRef, onToolOutputCollapsedAtEnd, pinDisclosureToEnd]);
709 -
710 - const suspendEndScrollMaintenanceForDisclosure = useCallback(
711 - (anchorKey: string, collapsed = false) => {
712 - disclosureAnchorKeyRef.current = anchorKey;
713 - disclosureCollapsedRef.current = collapsed;
714 - disclosurePinsEndRef.current = resolveTimelineIsAtEnd(listRef.current?.getState()) === true;
715 - setDisclosureToggleSettling(true);
716 - scheduleDisclosureSettle();
717 - },
718 - [listRef, scheduleDisclosureSettle],
719 - );
716 + };
717 +
718 + const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string, collapsed = false) => {
719 + disclosureAnchorKeyRef.current = anchorKey;
720 + disclosureCollapsedRef.current = collapsed;
721 + disclosurePinsEndRef.current = resolveTimelineIsAtEnd(listRef.current?.getState()) === true;
722 + setDisclosureToggleSettling(true);
723 + scheduleDisclosureSettle();
724 + };
725
721 - const shouldRestoreVisibleContentPosition = useCallback((row: MessagesTimelineRow) => {
726 + const shouldRestoreVisibleContentPosition = (row: MessagesTimelineRow) => {
727 if (disclosurePinsEndRef.current) return false;
728 const disclosureAnchorKey = disclosureAnchorKeyRef.current;
729 return disclosureAnchorKey === null || row.id === disclosureAnchorKey;
725 - }, []);
730 + };
731
727 - const onToggleTurnFold = useCallback(
728 - (runId: RunId) => {
729 - suspendEndScrollMaintenanceForDisclosure(`turn-fold:${runId}`);
730 - setExpandedRunIds((existing) => {
731 - const next = new Set(existing);
732 - if (next.has(runId)) {
733 - next.delete(runId);
734 - } else {
735 - next.add(runId);
736 - }
737 - return next;
738 - });
739 - },
740 - [suspendEndScrollMaintenanceForDisclosure],
741 - );
742 - const onToggleWorkGroup = useCallback(
743 - (groupId: string, anchorKey: string) => {
744 - suspendEndScrollMaintenanceForDisclosure(anchorKey, expandedWorkGroupIds.has(groupId));
745 - setExpandedWorkGroupIds((existing) => {
746 - const next = new Set(existing);
747 - if (next.has(groupId)) {
748 - next.delete(groupId);
749 - } else {
750 - next.add(groupId);
751 - }
752 - return next;
753 - });
754 - },
755 - [expandedWorkGroupIds, suspendEndScrollMaintenanceForDisclosure],
756 - );
757 - const onToggleAttemptFold = useCallback(
758 - (attemptId: RunAttemptId) => {
759 - suspendEndScrollMaintenanceForDisclosure(`attempt-fold:${attemptId}`);
760 - setExpandedAttemptIds((existing) => {
761 - const next = new Set(existing);
762 - if (next.has(attemptId)) {
763 - next.delete(attemptId);
764 - } else {
765 - next.add(attemptId);
766 - }
767 - return next;
768 - });
769 - },
770 - [suspendEndScrollMaintenanceForDisclosure],
771 - );
732 + const onToggleTurnFold = (runId: RunId) => {
733 + suspendEndScrollMaintenanceForDisclosure(`turn-fold:${runId}`);
734 + setExpandedRunIds((existing) => {
735 + const next = new Set(existing);
736 + if (next.has(runId)) {
737 + next.delete(runId);
738 + } else {
739 + next.add(runId);
740 + }
741 + return next;
742 + });
743 + };
744 + const onToggleWorkGroup = (groupId: string, anchorKey: string) => {
745 + suspendEndScrollMaintenanceForDisclosure(anchorKey, expandedWorkGroupIds.has(groupId));
746 + setExpandedWorkGroupIds((existing) => {
747 + const next = new Set(existing);
748 + if (next.has(groupId)) {
749 + next.delete(groupId);
750 + } else {
751 + next.add(groupId);
752 + }
753 + return next;
754 + });
755 + };
756 + const onToggleAttemptFold = (attemptId: RunAttemptId) => {
757 + suspendEndScrollMaintenanceForDisclosure(`attempt-fold:${attemptId}`);
758 + setExpandedAttemptIds((existing) => {
759 + const next = new Set(existing);
760 + if (next.has(attemptId)) {
761 + next.delete(attemptId);
762 + } else {
763 + next.add(attemptId);
764 + }
765 + return next;
766 + });
767 + };
768
769 + const previousLatestRunRef = useRef({ identity: listIdentityKey, run: latestRun });
770 useEffect(() => {
774 - const previous = previousLatestRunRef.current;
775 - previousLatestRunRef.current = latestRun;
776 - if (!latestRun || previous?.runId === undefined) {
771 + const { identity, run: previous } = previousLatestRunRef.current;
772 + previousLatestRunRef.current = { identity: listIdentityKey, run: latestRun };
773 + if (identity !== listIdentityKey || !latestRun || previous?.runId === undefined) {
774 return;
775 }
776 if (latestRun.runId === previous.runId) {
@@ -794,93 +791,59 @@ const ConversationTimeline = memo(function ConversationTimeline({
791 next.delete(previous.runId);
792 return next;
793 });
797 - }, [latestRun]);
794 + }, [latestRun, listIdentityKey]);
795
796 // Find the fold that hides the match: imported turns have no run id but still
797 // fold under a synthetic key, so the match's own run id cannot open them.
801 - const findFoldRunIds = useMemo(
802 - () =>
803 - findActive
804 - ? timelineTurnFoldRunIdsByEntryId({
805 - timelineEntries,
806 - latestRun,
807 - runningRunId,
808 - isWorking,
809 - runlessWorkActive,
810 - })
811 - : null,
812 - [findActive, timelineEntries, latestRun, runningRunId, isWorking, runlessWorkActive],
813 - );
798 + const findFoldRunIds = findActive
799 + ? timelineTurnFoldRunIdsByEntryId({
800 + timelineEntries,
801 + latestRun,
802 + runningRunId,
803 + isWorking,
804 + runlessWorkActive,
805 + })
806 + : null;
807 const activeFindRunId = activeFindMatch
808 ? findFoldRunIds?.get(activeFindMatch.entryId)
809 : undefined;
817 - useEffect(() => {
818 - if (!activeFindRunId) return;
819 - setExpandedRunIds((previous) =>
820 - previous.has(activeFindRunId) ? previous : new Set(previous).add(activeFindRunId),
821 - );
822 - }, [activeFindRunId]);
823 - const visibleExpandedRunIds = useMemo(() => {
824 - if (!activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)) {
825 - return paintedExpandedRunIds;
810 + const [expandedFindRunId, setExpandedFindRunId] = useState<RunId | undefined>();
811 + if (expandedFindRunId !== activeFindRunId) {
812 + setExpandedFindRunId(activeFindRunId);
813 + if (activeFindRunId) {
814 + setExpandedRunIds((previous) =>
815 + previous.has(activeFindRunId) ? previous : new Set(previous).add(activeFindRunId),
816 + );
817 }
827 - return new Set(paintedExpandedRunIds).add(activeFindRunId);
828 - }, [activeFindRunId, paintedExpandedRunIds]);
818 + }
819 + const visibleExpandedRunIds =
820 + !activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)
821 + ? paintedExpandedRunIds
822 + : new Set(paintedExpandedRunIds).add(activeFindRunId);
823
824 const activeFindAttemptId = activeFindMatch
825 ? timelineEntries.find((entry) => entry.id === activeFindMatch.entryId)?.attempt?.id
826 : undefined;
833 - useEffect(() => {
834 - if (!activeFindAttemptId) return;
835 - setExpandedAttemptIds((previous) =>
836 - previous.has(activeFindAttemptId) ? previous : new Set(previous).add(activeFindAttemptId),
837 - );
838 - }, [activeFindAttemptId]);
839 - const visibleExpandedAttemptIds = useMemo(
840 - () =>
841 - activeFindAttemptId && !paintedExpandedAttemptIds.has(activeFindAttemptId)
842 - ? new Set(paintedExpandedAttemptIds).add(activeFindAttemptId)
843 - : paintedExpandedAttemptIds,
844 - [activeFindAttemptId, paintedExpandedAttemptIds],
845 - );
827 + const [expandedFindAttemptId, setExpandedFindAttemptId] = useState<RunAttemptId | undefined>();
828 + if (expandedFindAttemptId !== activeFindAttemptId) {
829 + setExpandedFindAttemptId(activeFindAttemptId);
830 + if (activeFindAttemptId) {
831 + setExpandedAttemptIds((previous) =>
832 + previous.has(activeFindAttemptId) ? previous : new Set(previous).add(activeFindAttemptId),
833 + );
834 + }
835 + }
836 + const visibleExpandedAttemptIds =
837 + activeFindAttemptId && !paintedExpandedAttemptIds.has(activeFindAttemptId)
838 + ? new Set(paintedExpandedAttemptIds).add(activeFindAttemptId)
839 + : paintedExpandedAttemptIds;
840
847 - const rowsProjectionRef = useRef<{
848 - readonly threadKey: string;
849 - readonly workspaceRoot: string | undefined;
850 - readonly projection: MessagesTimelineRowsProjection;
851 - } | null>(null);
852 - const rawRows = useMemo(() => {
853 - const previous = rowsProjectionRef.current;
854 - const projection = deriveMessagesTimelineRowsWithState(
855 - {
856 - timelineEntries,
857 - latestRun,
858 - runningRunId,
859 - expandedRunIds: visibleExpandedRunIds,
860 - expandedAttemptIds: visibleExpandedAttemptIds,
861 - expandedWorkGroupIds,
862 - isWorking,
863 - runlessWorkActive,
864 - activeTurnStartedAt,
865 - turnDiffSummaries,
866 - supportsConversationRollback,
867 - worktreeSetup,
868 - },
869 - previous?.threadKey === listIdentityKey && previous.workspaceRoot === workspaceRoot
870 - ? previous.projection
871 - : null,
872 - );
873 - rowsProjectionRef.current = { threadKey: listIdentityKey, workspaceRoot, projection };
874 - return projection.rows;
875 - }, [
876 - rowsProjectionRef,
877 - listIdentityKey,
878 - workspaceRoot,
841 + const rawRows = useIncrementalTimelineRows(`${listIdentityKey}\0${workspaceRoot ?? ""}`, {
842 timelineEntries,
843 latestRun,
844 runningRunId,
882 - visibleExpandedRunIds,
883 - visibleExpandedAttemptIds,
845 + expandedRunIds: visibleExpandedRunIds,
846 + expandedAttemptIds: visibleExpandedAttemptIds,
847 expandedWorkGroupIds,
848 isWorking,
849 runlessWorkActive,
@@ -888,26 +851,24 @@ const ConversationTimeline = memo(function ConversationTimeline({
851 turnDiffSummaries,
852 supportsConversationRollback,
853 worktreeSetup,
891 - ]);
854 + });
855 const rows = useStableRows(rawRows, listIdentityKey);
856 // Run status/timestamps churn on every stream event; the shared row context
857 // must not change with them or every timeline row re-renders per event.
858 const runs = useStableHandoffRuns(runsProp);
896 - const minimapItems = useMemo(() => deriveTimelineMinimapItems(rows), [rows]);
859 + const minimapItems = deriveTimelineMinimapItems(rows);
860 const restoreRowIndex =
861 restoringThreadPosition && rememberedPosition?.atEnd === false
862 ? rows.findIndex((row) => row.id === rememberedPosition.rowId)
863 : -1;
901 - const restoringAlwaysRender = useMemo(
902 - () =>
903 - restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined,
904 - [restoreRowIndex, restoringThreadPosition],
905 - );
864 + const restoringAlwaysRender =
865 + restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined;
866 useLayoutEffect(() => {
867 if (!restoringThreadPosition || rows.length === 0) return;
868 const list = listRef.current;
869 if (!list) return;
870 if (citationRequest !== null) {
871 + // oxlint-disable-next-line react/set-state-in-effect -- The citation scroll owns positioning once the list has mounted.
872 setPositionedThreadKey(listIdentityKey);
873 return;
874 }
@@ -987,7 +948,8 @@ const ConversationTimeline = memo(function ConversationTimeline({
948 });
949 return;
950 }
990 - if (++stableFrames >= 2) {
951 + stableFrames += 1;
952 + if (stableFrames >= 2) {
953 setPositionedThreadKey(listIdentityKey);
954 } else {
955 settleFrame = requestAnimationFrame(reconcile);
@@ -1038,111 +1000,99 @@ const ConversationTimeline = memo(function ConversationTimeline({
1000 onManualNavigation,
1001 });
1002 const [findListReady, setFindListReady] = useState(false);
1041 - const handleListLoad = useCallback(() => {
1003 + const handleListLoad = () => {
1004 onCitationListLoad();
1005 setFindListReady(true);
1044 - }, [onCitationListLoad]);
1006 + };
1007 const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
1008 const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);
1047 - const onAppFullscreenChange = useCallback((rowId: string, fullscreen: boolean) => {
1009 + const onAppFullscreenChange = (rowId: string, fullscreen: boolean) => {
1010 setFullscreenAppRowId((current) => (fullscreen ? rowId : current === rowId ? null : current));
1049 - }, []);
1050 - const alwaysRender = useMemo(() => {
1051 - const indices = restoringAlwaysRender?.indices ?? [];
1052 - const keys = [
1053 - ...(citationAlwaysRender?.keys ?? []),
1054 - ...(fullscreenAppRowId === null ? [] : [fullscreenAppRowId]),
1055 - ];
1056 - if (indices.length === 0 && keys.length === 0) return undefined;
1057 - return {
1058 - ...(indices.length === 0 ? {} : { indices }),
1059 - ...(keys.length === 0 ? {} : { keys }),
1060 - };
1061 - }, [citationAlwaysRender, restoringAlwaysRender, fullscreenAppRowId]);
1011 + };
1012 + const alwaysRenderIndices = restoringAlwaysRender?.indices ?? [];
1013 + const alwaysRenderKeys = [
1014 + ...(citationAlwaysRender?.keys ?? []),
1015 + ...(fullscreenAppRowId === null ? [] : [fullscreenAppRowId]),
1016 + ];
1017 + const alwaysRender =
1018 + alwaysRenderIndices.length === 0 && alwaysRenderKeys.length === 0
1019 + ? undefined
1020 + : {
1021 + ...(alwaysRenderIndices.length === 0 ? {} : { indices: alwaysRenderIndices }),
1022 + ...(alwaysRenderKeys.length === 0 ? {} : { keys: alwaysRenderKeys }),
1023 + };
1024 const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
1025 const [minimapCurrentIndex, setMinimapCurrentIndex] = useState<number | null>(null);
1064 - const handleAnchorReady = useCallback(
1065 - (info: { anchorIndex: number | undefined }) => {
1066 - if (anchorMessageId !== null && info.anchorIndex !== undefined) {
1067 - onAnchorReady(anchorMessageId, info.anchorIndex);
1068 - }
1069 - },
1070 - [anchorMessageId, onAnchorReady],
1026 + const handleAnchorReady = (info: { anchorIndex: number | undefined }) => {
1027 + if (anchorMessageId !== null && info.anchorIndex !== undefined) {
1028 + onAnchorReady(anchorMessageId, info.anchorIndex);
1029 + }
1030 + };
1031 + const handleAnchorSizeChanged = (size: number) => {
1032 + if (anchorMessageId !== null) {
1033 + onAnchorSizeChanged(anchorMessageId, size);
1034 + }
1035 + };
1036 + const anchoredEndSpaceConfig = resolveChatListAnchoredEndSpace(
1037 + rows,
1038 + anchorMessageId,
1039 + (row) => (row.kind === "message" && row.message.role === "user" ? row.message.id : null),
1040 + { anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET },
1041 );
1072 - const handleAnchorSizeChanged = useCallback(
1073 - (size: number) => {
1074 - if (anchorMessageId !== null) {
1075 - onAnchorSizeChanged(anchorMessageId, size);
1042 + const anchoredEndSpace = anchoredEndSpaceConfig
1043 + ? {
1044 + ...anchoredEndSpaceConfig,
1045 + onReady: handleAnchorReady,
1046 + onSizeChanged: handleAnchorSizeChanged,
1047 }
1077 - },
1078 - [anchorMessageId, onAnchorSizeChanged],
1079 - );
1080 - const anchoredEndSpace = useMemo(() => {
1081 - const config = resolveChatListAnchoredEndSpace(
1082 - rows,
1083 - anchorMessageId,
1084 - (row) => (row.kind === "message" && row.message.role === "user" ? row.message.id : null),
1085 - { anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET },
1086 - );
1087 - return config
1088 - ? { ...config, onReady: handleAnchorReady, onSizeChanged: handleAnchorSizeChanged }
1089 - : undefined;
1090 - }, [anchorMessageId, handleAnchorReady, handleAnchorSizeChanged, rows]);
1091 - const maintainVisibleContentPosition = useMemo(
1092 - () => ({
1093 - data: true,
1094 - size: true,
1095 - shouldRestorePosition: shouldRestoreVisibleContentPosition,
1096 - }),
1097 - [shouldRestoreVisibleContentPosition],
1098 - );
1099 - const timelineListFooter = useMemo(
1100 - () => (
1101 - <TimelineListFooter composerInset={anchoredEndSpace ? 0 : contentInsetEndAdjustment}>
1102 - {footer}
1103 - </TimelineListFooter>
1104 - ),
1105 - [anchoredEndSpace, contentInsetEndAdjustment, footer],
1048 + : undefined;
1049 + const maintainVisibleContentPosition = {
1050 + data: true,
1051 + size: true,
1052 + shouldRestorePosition: shouldRestoreVisibleContentPosition,
1053 + };
1054 + const timelineListFooter = (
1055 + <TimelineListFooter composerInset={anchoredEndSpace ? 0 : contentInsetEndAdjustment}>
1056 + {footer}
1057 + </TimelineListFooter>
1058 );
1059
1108 - const measureContentOverflow = useCallback(
1109 - () =>
1110 - timelineContentOverflowsViewport(listRef.current?.getState?.(), {
1111 - composerInset: contentInsetEndAdjustment,
1112 - anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
1113 - }),
1114 - [contentInsetEndAdjustment, listRef],
1115 - );
1060 + const measureContentOverflow = () =>
1061 + timelineContentOverflowsViewport(listRef.current?.getState?.(), {
1062 + composerInset: contentInsetEndAdjustment,
1063 + anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
1064 + });
1065 // LegendList lays rows out from layout effects, so a read on the next frame
1066 // sees the settled positions.
1067 const contentOverflowFrameRef = useRef<number | null>(null);
1119 - const cancelContentOverflowFrame = useCallback(() => {
1068 + const cancelContentOverflowFrame = () => {
1069 if (contentOverflowFrameRef.current !== null) {
1070 cancelAnimationFrame(contentOverflowFrameRef.current);
1071 contentOverflowFrameRef.current = null;
1072 }
1124 - }, []);
1125 - const reportContentOverflow = useCallback(() => {
1073 + };
1074 + const reportContentOverflow = () => {
1075 if (!onContentOverflowChange || contentOverflowFrameRef.current !== null) return;
1076 contentOverflowFrameRef.current = requestAnimationFrame(() => {
1077 contentOverflowFrameRef.current = null;
1078 onContentOverflowChange(measureContentOverflow());
1079 });
1131 - }, [measureContentOverflow, onContentOverflowChange]);
1132 - const handleItemSizeChanged = useCallback(() => {
1080 + };
1081 + const handleItemSizeChanged = () => {
1082 if (disclosurePinsEndRef.current) {
1083 queueMicrotask(pinDisclosureToEnd);
1084 scheduleDisclosureSettle();
1085 }
1086 reportContentOverflow();
1138 - }, [pinDisclosureToEnd, reportContentOverflow, scheduleDisclosureSettle]);
1087 + };
1088 useEffect(() => cancelContentOverflowFrame, [cancelContentOverflowFrame]);
1089 useLayoutEffect(() => {
1090 cancelContentOverflowFrame();
1091 onContentOverflowChange?.(measureContentOverflow());
1092 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows change the content height.
1093 }, [cancelContentOverflowFrame, measureContentOverflow, onContentOverflowChange, rows.length]);
1094
1145 - const handleScroll = useCallback(() => {
1095 + const handleScroll = () => {
1096 const state = listRef.current?.getState?.();
1097 if (restoringThreadPosition || state?.data !== rows) return;
1098 const isAtEnd = resolveTimelineIsAtEnd(state);
@@ -1211,28 +1161,12 @@ const ConversationTimeline = memo(function ConversationTimeline({
1161 setMinimapCurrentIndex((current) =>
1162 current === nextCurrentIndex ? current : nextCurrentIndex,
1163 );
1214 - }, [
1215 - citationPositioning,
1216 - paintedExpandedRunIds,
1217 - paintedExpandedWorkGroupIds,
1218 - paintedExpandedAttemptIds,
1219 - workGroupViewState,
1220 - rows,
1221 - listIdentityKey,
1222 - liveFollowEnabled,
1223 - anchoredEndSpace,
1224 - paintOnly,
1225 - restoringThreadPosition,
1226 - listRef,
1227 - minimapItems,
1228 - minimapStripMap,
1229 - onIsAtEndChange,
1230 - reportContentOverflow,
1231 - ]);
1164 + };
1165
1166 useEffect(() => {
1167 const frame = requestAnimationFrame(handleScroll);
1168 return () => cancelAnimationFrame(frame);
1169 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows move the scroll position.
1170 }, [handleScroll, rows.length]);
1171
1172 const savedLiveFollowEnabledRef = useRef(liveFollowEnabled);
@@ -1272,86 +1206,47 @@ const ConversationTimeline = memo(function ConversationTimeline({
1206 cancelAnimationFrame(frame);
1207 stopObserving();
1208 };
1209 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Rows and chat width resize the content without resizing the viewport.
1210 }, [timelineViewportElement, rows.length, reportContentOverflow, chatWidth]);
1211
1277 - const sharedState = useMemo<TimelineRowSharedState>(
1278 - () => ({
1279 - citationRequest: readyCitationRequest,
1280 - listRef,
1281 - timestampFormat,
1282 - routeThreadKey,
1283 - threadRef: citationThreadRef,
1284 - markdownCwd,
1285 - resolvedTheme,
1286 - workspaceRoot,
1287 - skills,
1288 - providerStatuses,
1289 - runs,
1290 - activeThreadEnvironmentId,
1291 - onRevertToTurnCount,
1292 - onRunShellCommand,
1293 - findActive,
1294 - onImageExpand,
1295 - onFileOpen,
1296 - onUseArtifactTemplate,
1297 - onSendAppMessage,
1298 - onAppFullscreenChange,
1299 - onFileDownload,
1300 - openPullRequest,
1301 - onOpenTurnDiff,
1302 - onOpenThread,
1303 - onForkFromRun,
1304 - onRollbackCheckpoint,
1305 - onToggleTurnFold,
1306 - onToggleAttemptFold,
1307 - onToggleWorkGroup,
1308 - onToggleWorkEntry: suspendEndScrollMaintenanceForDisclosure,
1309 - onCancelWorktreeSetup: onCancelWorktreeSetup ?? null,
1310 - retryableWorkspacePreparationRunIds,
1311 - onRetryWorkspacePreparation: onRetryWorkspacePreparation ?? null,
1312 - onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocally ?? null,
1313 - onOpenWorktreeSetupTerminal: onOpenWorktreeSetupTerminal ?? null,
1314 - workGroupViewState,
1315 - }),
1316 - [
1317 - readyCitationRequest,
1318 - listRef,
1319 - timestampFormat,
1320 - routeThreadKey,
1321 - citationThreadRef,
1322 - markdownCwd,
1323 - resolvedTheme,
1324 - workspaceRoot,
1325 - skills,
1326 - providerStatuses,
1327 - runs,
1328 - activeThreadEnvironmentId,
1329 - onRevertToTurnCount,
1330 - onRunShellCommand,
1331 - findActive,
1332 - onImageExpand,
1333 - onFileOpen,
1334 - onUseArtifactTemplate,
1335 - onSendAppMessage,
1336 - onAppFullscreenChange,
1337 - onFileDownload,
1338 - openPullRequest,
1339 - onOpenTurnDiff,
1340 - onOpenThread,
1341 - onForkFromRun,
1342 - onRollbackCheckpoint,
1343 - onToggleTurnFold,
1344 - onToggleAttemptFold,
1345 - onToggleWorkGroup,
1346 - suspendEndScrollMaintenanceForDisclosure,
1347 - onCancelWorktreeSetup,
1348 - retryableWorkspacePreparationRunIds,
1349 - onRetryWorkspacePreparation,
1350 - onWorktreeSetupWorkLocally,
1351 - onOpenWorktreeSetupTerminal,
1352 - workGroupViewState,
1353 - ],
1354 - );
1212 + const sharedState: TimelineRowSharedState = {
1213 + citationRequest: readyCitationRequest,
1214 + listRef,
1215 + timestampFormat,
1216 + routeThreadKey,
1217 + threadRef: citationThreadRef,
1218 + markdownCwd,
1219 + resolvedTheme,
1220 + workspaceRoot,
1221 + skills,
1222 + providerStatuses,
1223 + runs,
1224 + activeThreadEnvironmentId,
1225 + onRevertToTurnCount,
1226 + onRunShellCommand,
1227 + findActive,
1228 + onImageExpand,
1229 + onFileOpen,
1230 + onUseArtifactTemplate,
1231 + onSendAppMessage,
1232 + onAppFullscreenChange,
1233 + onFileDownload,
1234 + openPullRequest,
1235 + onOpenTurnDiff,
1236 + onOpenThread,
1237 + onForkFromRun,
1238 + onRollbackCheckpoint,
1239 + onToggleTurnFold,
1240 + onToggleAttemptFold,
1241 + onToggleWorkGroup,
1242 + onToggleWorkEntry: suspendEndScrollMaintenanceForDisclosure,
1243 + onCancelWorktreeSetup: onCancelWorktreeSetup ?? null,
1244 + retryableWorkspacePreparationRunIds,
1245 + onRetryWorkspacePreparation: onRetryWorkspacePreparation ?? null,
1246 + onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocally ?? null,
1247 + onOpenWorktreeSetupTerminal: onOpenWorktreeSetupTerminal ?? null,
1248 + workGroupViewState,
1249 + };
1250 const compactionAwaitingRow =
1251 isCompacting && !rows.some((row) => row.kind === "context-compaction" && row.active);
1252 const backgroundWorktreeSetup =
@@ -1361,67 +1256,50 @@ const ConversationTimeline = memo(function ConversationTimeline({
1256 latestRun?.startedAt != null
1257 ? worktreeSetup
1258 : null;
1364 - const activityState = useMemo<TimelineRowActivityState>(
1365 - () => ({
1366 - isWorking,
1367 - isCompacting: compactionAwaitingRow,
1368 - isRevertingCheckpoint,
1369 - backgroundWorktreeSetup,
1370 - activeTurnInProgress,
1371 - awaitingUser,
1372 - isPreparingWorktree,
1373 - latestRunId: latestRun?.runId ?? null,
1374 - }),
1375 - [
1376 - awaitingUser,
1377 - compactionAwaitingRow,
1378 - backgroundWorktreeSetup,
1379 - activeTurnInProgress,
1380 - isPreparingWorktree,
1381 - isRevertingCheckpoint,
1382 - isWorking,
1383 - latestRun?.runId,
1384 - ],
1385 - );
1386 - const listHeader = useMemo(() => {
1387 - const leadingContent =
1388 - parentThreadLink === null ? (
1389 - topFadeEnabled ? (
1390 - TIMELINE_LIST_FADE_HEADER
1391 - ) : (
1392 - TIMELINE_LIST_HEADER
1393 - )
1259 + const activityState: TimelineRowActivityState = {
1260 + isWorking,
1261 + isCompacting: compactionAwaitingRow,
1262 + isRevertingCheckpoint,
1263 + backgroundWorktreeSetup,
1264 + activeTurnInProgress,
1265 + awaitingUser,
1266 + isPreparingWorktree,
1267 + latestRunId: latestRun?.runId ?? null,
1268 + };
1269 + const listHeaderLeadingContent =
1270 + parentThreadLink === null ? (
1271 + topFadeEnabled ? (
1272 + TIMELINE_LIST_FADE_HEADER
1273 ) : (
1395 - <div className="messages-timeline-row-frame">
1396 - <div className="chat-content-lane pt-1 sm:pt-2">
1397 - <TimelineSystemDivider
1398 - label="Subagent of"
1399 - detail={parentThreadLink.title}
1400 - icon={BotIcon}
1401 - actionLabel="Open parent thread"
1402 - onAction={() => onOpenThread(parentThreadLink.threadId)}
1403 - />
1404 - </div>
1274 + TIMELINE_LIST_HEADER
1275 + )
1276 + ) : (
1277 + <div className="messages-timeline-row-frame">
1278 + <div className="chat-content-lane pt-1 sm:pt-2">
1279 + <TimelineSystemDivider
1280 + label="Subagent of"
1281 + detail={parentThreadLink.title}
1282 + icon={BotIcon}
1283 + actionLabel="Open parent thread"
1284 + onAction={() => onOpenThread(parentThreadLink.threadId)}
1285 + />
1286 </div>
1406 - );
1407 - return (
1408 - <>
1409 - {parentThreadLink === null ? leadingContent : null}
1410 - {historyControls ? <TimelineHistoryControl {...historyControls} /> : null}
1411 - {parentThreadLink !== null ? leadingContent : null}
1412 - </>
1287 + </div>
1288 );
1414 - }, [historyControls, onOpenThread, parentThreadLink, topFadeEnabled]);
1289 + const listHeader = (
1290 + <>
1291 + {parentThreadLink === null ? listHeaderLeadingContent : null}
1292 + {historyControls ? <TimelineHistoryControl {...historyControls} /> : null}
1293 + {parentThreadLink !== null ? listHeaderLeadingContent : null}
1294 + </>
1295 + );
1296
1297 const canvas = useChatCanvas();
1298 const registerTimeline = canvas?.registerTimeline;
1418 - const setTimelineList = useCallback(
1419 - (list: LegendListRef | null) => {
1420 - listRef.current = list;
1421 - registerTimeline?.(list?.getScrollableNode() ?? null);
1422 - },
1423 - [listRef, registerTimeline],
1424 - );
1299 + const setTimelineList = (list: LegendListRef | null) => {
1300 + listRef.current = list;
1301 + registerTimeline?.(list?.getScrollableNode() ?? null);
1302 + };
1303
1304 useLayoutEffect(() => {
1305 if (!findPositionReaderRef || !timelineViewportElement) return;
@@ -1501,24 +1379,18 @@ const ConversationTimeline = memo(function ConversationTimeline({
1379 contentInsetEndAdjustment,
1380 });
1381
1504 - const renderItem = useCallback(
1505 - ({ item }: { item: MessagesTimelineRow }) => (
1506 - <div className="messages-timeline-row-frame">
1507 - <div className="chat-content-lane overflow-x-clip" data-timeline-root="true">
1508 - <TimelineRowContent row={item} />
1509 - </div>
1382 + const renderItem = ({ item }: { item: MessagesTimelineRow }) => (
1383 + <div className="messages-timeline-row-frame">
1384 + <div className="chat-content-lane overflow-x-clip" data-timeline-root="true">
1385 + <TimelineRowContent row={item} />
1386 </div>
1511 - ),
1512 - [],
1387 + </div>
1388 );
1389
1515 - const forwardMinimapWheel = useCallback(
1516 - (event: WheelEvent) => {
1517 - const scrollNode = listRef.current?.getScrollableNode();
1518 - if (scrollNode) forwardWheelToTimeline(event, scrollNode);
1519 - },
1520 - [listRef],
1521 - );
1390 + const forwardMinimapWheel = (event: WheelEvent) => {
1391 + const scrollNode = listRef.current?.getScrollableNode();
1392 + if (scrollNode) forwardWheelToTimeline(event, scrollNode);
1393 + };
1394
1395 if (
1396 rows.length === 0 &&
@@ -1720,14 +1592,11 @@ function TimelineMinimap({
1592 onSelect: (item: TimelineMinimapItem) => void;
1593 }) {
1594 const [activeIndex, setActiveIndex] = useState<number | null>(null);
1723 - const wheelTargetRef = useCallback(
1724 - (node: HTMLDivElement | null) => {
1725 - if (!node) return;
1726 - node.addEventListener("wheel", onWheel, { passive: false });
1727 - return () => node.removeEventListener("wheel", onWheel);
1728 - },
1729 - [onWheel],
1730 - );
1595 + const wheelTargetRef = (node: HTMLDivElement | null) => {
1596 + if (!node) return;
1597 + node.addEventListener("wheel", onWheel, { passive: false });
1598 + return () => node.removeEventListener("wheel", onWheel);
1599 + };
1600
1601 const pressedOnStripRef = useRef(false);
1602 const [passThrough, setPassThrough] = useState(false);
@@ -1739,12 +1608,8 @@ function TimelineMinimap({
1608
1609 const resolvedActiveIndex =
1610 activeIndex !== null && activeIndex < items.length ? activeIndex : null;
1742 - const activeItem = useMemo(
1743 - () =>
1744 - resolveTimelineMinimapPreview(
1745 - resolvedActiveIndex === null ? null : (items[resolvedActiveIndex] ?? null),
1746 - ),
1747 - [items, resolvedActiveIndex],
1611 + const activeItem = resolveTimelineMinimapPreview(
1612 + resolvedActiveIndex === null ? null : (items[resolvedActiveIndex] ?? null),
1613 );
1614 const navigationInteractive =
1615 resolveTimelineMinimapNavigationInteractive(hitStripWidth) && !passThrough;
@@ -1766,36 +1631,27 @@ function TimelineMinimap({
1631 resolvedCurrentIndex === null ? null : (items[resolvedCurrentIndex - 1] ?? null);
1632 const nextItem = resolvedCurrentIndex === null ? null : (items[resolvedCurrentIndex + 1] ?? null);
1633
1769 - const resolveActiveIndexFromPointer = useCallback(
1770 - (event: MouseEvent<HTMLElement>) => {
1771 - const rect = event.currentTarget.getBoundingClientRect();
1772 - return resolveTimelineMinimapIndexFromPointer({
1773 - itemCount: items.length,
1774 - railTop: rect.top,
1775 - railHeight: rect.height,
1776 - pointerY: event.clientY,
1777 - });
1778 - },
1779 - [items.length],
1780 - );
1634 + const resolveActiveIndexFromPointer = (event: MouseEvent<HTMLElement>) => {
1635 + const rect = event.currentTarget.getBoundingClientRect();
1636 + return resolveTimelineMinimapIndexFromPointer({
1637 + itemCount: items.length,
1638 + railTop: rect.top,
1639 + railHeight: rect.height,
1640 + pointerY: event.clientY,
1641 + });
1642 + };
1643
1782 - const updateActiveIndexFromPointer = useCallback(
1783 - (event: MouseEvent<HTMLElement>) => {
1784 - const nextIndex = resolveActiveIndexFromPointer(event);
1785 - setActiveIndex(nextIndex);
1786 - },
1787 - [resolveActiveIndexFromPointer],
1788 - );
1644 + const updateActiveIndexFromPointer = (event: MouseEvent<HTMLElement>) => {
1645 + const nextIndex = resolveActiveIndexFromPointer(event);
1646 + setActiveIndex(nextIndex);
1647 + };
1648
1790 - const moveActiveIndex = useCallback(
1791 - (delta: number) => {
1792 - setActiveIndex((current) => {
1793 - const base = current ?? 0;
1794 - return Math.max(0, Math.min(items.length - 1, base + delta));
1795 - });
1796 - },
1797 - [items.length],
1798 - );
1649 + const moveActiveIndex = (delta: number) => {
1650 + setActiveIndex((current) => {
1651 + const base = current ?? 0;
1652 + return Math.max(0, Math.min(items.length - 1, base + delta));
1653 + });
1654 + };
1655
1656 if (items.length < TIMELINE_MINIMAP_MIN_ITEMS) {
1657 return null;
@@ -2112,10 +1968,7 @@ function WorktreeSetupTimelineRow({
1968 const ctx = use(TimelineRowCtx);
1969 const terminalId = row.snapshot.setupScript?.terminalId ?? null;
1970 const openTerminal = ctx.onOpenWorktreeSetupTerminal;
2115 - const onOpenTerminal = useMemo(
2116 - () => (openTerminal && terminalId ? () => openTerminal(terminalId) : null),
2117 - [openTerminal, terminalId],
2118 - );
1971 + const onOpenTerminal = openTerminal && terminalId ? () => openTerminal(terminalId) : null;
1972 return (
1973 <WorktreeSetupCard
1974 snapshot={row.snapshot}
@@ -2165,13 +2018,14 @@ function ContextCompactionTimelineRow({
2018
2019 function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
2020 const ctx = use(TimelineRowCtx);
2168 - const asset = useMemo(
2169 - () =>
2170 - file.downloadable === false
2171 - ? null
2172 - : buildAttachmentVideoAsset(ctx.activeThreadEnvironmentId, file),
2173 - [ctx.activeThreadEnvironmentId, file.downloadable, file.id, file.mimeType, file.name],
2174 - );
2021 + // Row updates rebuild attachment objects, so the asset follows only the
2022 + // fields it reads.
2023 + const { downloadable, id, mimeType, name } = file;
2024 + const environmentId = ctx.activeThreadEnvironmentId;
2025 + const asset =
2026 + downloadable === false
2027 + ? null
2028 + : buildAttachmentVideoAsset(environmentId, { id, mimeType, name });
2029 const resource = asset?.resource ?? null;
2030 const assetUrl = useAssetUrlState(ctx.activeThreadEnvironmentId, resource);
2031 const refreshAssetUrl = useAssetUrlRefresh(ctx.activeThreadEnvironmentId, resource);
@@ -2216,40 +2070,28 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
2070 const ctx = use(TimelineRowCtx);
2071 const { onImageExpand, onFileOpen } = ctx;
2072 const senderThreadId = row.message.senderThreadId;
2219 - const resources = useMemo(
2220 - () => selectMessageImageResources(row.message.attachments),
2221 - [row.message.attachments],
2222 - );
2073 + const resources = selectMessageImageResources(row.message.attachments);
2074 const previewUrls = useAssetUrls(ctx.activeThreadEnvironmentId, resources);
2075 const [projectPreviews] = useState(createMessageAttachmentPreviewProjector);
2225 - const messageWithPreviews = useMemo(() => {
2226 - const urlsById = new Map(
2227 - resources.flatMap((resource, index) => {
2228 - const url = previewUrls[index];
2229 - return url ? [[resource.attachmentId, url] as const] : [];
2230 - }),
2231 - );
2232 - return projectPreviews(row.message, (attachment) => urlsById.get(attachment.id));
2233 - }, [previewUrls, projectPreviews, resources, row.message]);
2234 - const userImages = useMemo(
2235 - () => (messageWithPreviews.attachments ?? []).filter(isImageAttachment),
2236 - [messageWithPreviews.attachments],
2076 + const previewUrlsById = new Map(
2077 + resources.flatMap((resource, index) => {
2078 + const url = previewUrls[index];
2079 + return url ? [[resource.attachmentId, url] as const] : [];
2080 + }),
2081 );
2238 - const userFiles = useMemo(
2239 - () => (row.message.attachments ?? []).filter(isFileAttachment),
2240 - [row.message.attachments],
2082 + const messageWithPreviews = projectPreviews(row.message, (attachment) =>
2083 + previewUrlsById.get(attachment.id),
2084 );
2085 + const userImages = (messageWithPreviews.attachments ?? []).filter(isImageAttachment);
2086 + const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
2087 const userVideos = userFiles.filter(isVideoAttachment);
2088 const otherUserFiles = userFiles.filter((file) => !isVideoAttachment(file));
2089 const unknownAttachments = (row.message.attachments ?? []).filter(
2090 (attachment) => !isImageAttachment(attachment) && !isFileAttachment(attachment),
2091 );
2092 const userMessage = resolveUserMessagePresentation(row.message);
2248 - const resolvedContext = useMemo(() => resolveUserMessageContext(row.message), [row.message]);
2249 - const previewImages = useMemo(
2250 - () => userImages.filter((image) => image.name.startsWith("preview-annotation-")),
2251 - [userImages],
2252 - );
2093 + const resolvedContext = resolveUserMessageContext(row.message);
2094 + const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
2095 const revertTurnCount = row.revertTurnCount;
2096 const chippedAttachmentIds = new Set(
2097 collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => {
@@ -2259,18 +2101,14 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
2101 );
2102 const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
2103 const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));
2262 - const annotationRecordIds = useMemo(
2263 - () =>
2264 - resolvedContext.records
2265 - .filter((record) => record.kind === "preview-annotation")
2266 - .map((record) => record.contextId),
2267 - [resolvedContext.records],
2268 - );
2269 - const plainText = useMemo(
2270 - () => replaceComposerContextReferences(resolvedContext.text, (reference) => reference.label),
2271 - [resolvedContext.text],
2104 + const annotationRecordIds = resolvedContext.records
2105 + .filter((record) => record.kind === "preview-annotation")
2106 + .map((record) => record.contextId);
2107 + const plainText = replaceComposerContextReferences(
2108 + resolvedContext.text,
2109 + (reference) => reference.label,
2110 );
2273 - const promptLink = useMemo(() => promptLinkFor(plainText), [plainText]);
2111 + const promptLink = promptLinkFor(plainText);
2112 const contextClipboardFragment =
2113 resolvedContext.records.length === 0
2114 ? null
@@ -2316,56 +2154,44 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
2154 }
2155 event.clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);
2156 };
2319 - const renderContextReference = useCallback(
2320 - (reference: ChatMarkdownContextReference) => {
2321 - const record = asKnownContextRecord(resolvedContext.recordsById.get(reference.contextId));
2322 - const annotationImage =
2323 - record?.kind === "preview-annotation"
2324 - ? resolvePreviewAnnotationImage({
2325 - record,
2326 - recordsById: resolvedContext.recordsById,
2327 - userImages,
2328 - previewImages,
2329 - annotationRecordIds,
2330 - })
2157 + const renderContextReference = (reference: ChatMarkdownContextReference) => {
2158 + const record = asKnownContextRecord(resolvedContext.recordsById.get(reference.contextId));
2159 + const annotationImage =
2160 + record?.kind === "preview-annotation"
2161 + ? resolvePreviewAnnotationImage({
2162 + record,
2163 + recordsById: resolvedContext.recordsById,
2164 + userImages,
2165 + previewImages,
2166 + annotationRecordIds,
2167 + })
2168 + : null;
2169 + const attachment =
2170 + record?.kind === "image"
2171 + ? (userImages.find((image) => image.id === record.attachmentId) ?? null)
2172 + : record?.kind === "file"
2173 + ? (userFiles.find((file) => file.id === record.attachmentId) ?? null)
2174 : null;
2332 - const attachment =
2333 - record?.kind === "image"
2334 - ? (userImages.find((image) => image.id === record.attachmentId) ?? null)
2335 - : record?.kind === "file"
2336 - ? (userFiles.find((file) => file.id === record.attachmentId) ?? null)
2337 - : null;
2338 - return (
2339 - <span data-thread-find-ignore>
2340 - <UserMessageContextReferenceChip
2341 - reference={reference}
2342 - record={record}
2343 - annotationImage={annotationImage}
2344 - attachment={attachment}
2345 - onExpandImage={(image) => {
2346 - const preview = buildExpandedImagePreview(userImages, image.id);
2347 - if (preview) onImageExpand(preview);
2348 - }}
2349 - onOpenFile={onFileOpen}
2350 - onExpandVideo={(file) => {
2351 - const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
2352 - if (preview) onImageExpand(preview);
2353 - }}
2354 - />
2355 - </span>
2356 - );
2357 - },
2358 - [
2359 - resolvedContext.recordsById,
2360 - userImages,
2361 - userFiles,
2362 - previewImages,
2363 - annotationRecordIds,
2364 - onImageExpand,
2365 - onFileOpen,
2366 - ctx.activeThreadEnvironmentId,
2367 - ],
2368 - );
2175 + return (
2176 + <span data-thread-find-ignore>
2177 + <UserMessageContextReferenceChip
2178 + reference={reference}
2179 + record={record}
2180 + annotationImage={annotationImage}
2181 + attachment={attachment}
2182 + onExpandImage={(image) => {
2183 + const preview = buildExpandedImagePreview(userImages, image.id);
2184 + if (preview) onImageExpand(preview);
2185 + }}
2186 + onOpenFile={onFileOpen}
2187 + onExpandVideo={(file) => {
2188 + const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
2189 + if (preview) onImageExpand(preview);
2190 + }}
2191 + />
2192 + </span>
2193 + );
2194 + };
2195
2196 return (
2197 <div className="group flex flex-col items-end gap-1">
@@ -2967,10 +2793,7 @@ function ProposedPlanTimelineRow({
2793 function HtmlRenderTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "html-render" }> }) {
2794 const ctx = use(TimelineRowCtx);
2795 const { onAppFullscreenChange } = ctx;
2970 - const onFullscreenChange = useCallback(
2971 - (fullscreen: boolean) => onAppFullscreenChange(row.id, fullscreen),
2972 - [onAppFullscreenChange, row.id],
2973 - );
2796 + const onFullscreenChange = (fullscreen: boolean) => onAppFullscreenChange(row.id, fullscreen);
2797
2798 return (
2799 <div className="min-w-0 px-1">
@@ -3437,13 +3260,10 @@ const WorkGroupSection = memo(function WorkGroupSection({
3260 displayLabel?: string | undefined;
3261 }) {
3262 const { workspaceRoot, routeThreadKey, onToggleWorkEntry } = use(TimelineRowCtx);
3440 - const onToggleStandaloneEntry = useCallback(
3441 - (collapsed: boolean) => onToggleWorkEntry(disclosureAnchorKey, collapsed),
3442 - [disclosureAnchorKey, onToggleWorkEntry],
3443 - );
3444 - const nonEmptyEntries = useMemo(
3445 - () => groupedEntries.filter((entry) => workEntryIsVisibleInGroup(entry, isExpandedToolGroup)),
3446 - [groupedEntries, isExpandedToolGroup],
3263 + const onToggleStandaloneEntry = (collapsed: boolean) =>
3264 + onToggleWorkEntry(disclosureAnchorKey, collapsed);
3265 + const nonEmptyEntries = groupedEntries.filter((entry) =>
3266 + workEntryIsVisibleInGroup(entry, isExpandedToolGroup),
3267 );
3268
3269 if (nonEmptyEntries.length === 0) return null;
@@ -3551,14 +3371,11 @@ function ExpandedWorkGroupEntries({
3371 });
3372 }
3373
3554 - const groupView = useMemo(
3555 - () => ({
3556 - state: viewState,
3557 - onToggleEntry: (collapsed: boolean) => onToggleWorkEntry(disclosureAnchorKey, collapsed),
3558 - }),
3559 - [disclosureAnchorKey, onToggleWorkEntry, viewState],
3560 - );
3561 - const updateScrollFades = useCallback(() => {
3374 + const groupView = {
3375 + state: viewState,
3376 + onToggleEntry: (collapsed: boolean) => onToggleWorkEntry(disclosureAnchorKey, collapsed),
3377 + };
3378 + const updateScrollFades = () => {
3379 const element = listRef.current?.getScrollableNode();
3380 if (!element) return;
3381 const distanceFromEnd = element.scrollHeight - element.clientHeight - element.scrollTop;
@@ -3572,9 +3389,9 @@ function ExpandedWorkGroupEntries({
3389 ? previous
3390 : { top, bottom, viewportHeight },
3391 );
3575 - }, []);
3392 + };
3393
3577 - const handleScroll = useCallback(() => {
3394 + const handleScroll = () => {
3395 const state = listRef.current?.getState();
3396 const position = state && resolveWorkGroupScrollAnchor(state);
3397 if (position) {
@@ -3584,9 +3401,9 @@ function ExpandedWorkGroupEntries({
3401 });
3402 }
3403 updateScrollFades();
3587 - }, [anchorKey, updateScrollFades, viewState]);
3404 + };
3405
3589 - const handleLoad = useCallback(() => {
3406 + const handleLoad = () => {
3407 const list = listRef.current;
3408 const element = list?.getScrollableNode();
3409 if (initialScrollIndex && list && element) {
@@ -3601,7 +3418,7 @@ function ExpandedWorkGroupEntries({
3418 }
3419 }
3420 setRestoringPosition(false);
3604 - }, [initialScrollIndex]);
3421 + };
3422
3423 useLayoutEffect(() => {
3424 const element = listRef.current?.getScrollableNode();
@@ -3611,14 +3428,11 @@ function ExpandedWorkGroupEntries({
3428 return observeResize(content ? [element, content] : element, updateScrollFades);
3429 }, [updateScrollFades]);
3430
3614 - const renderEntry = useCallback(
3615 - ({ item }: { item: TimelineWorkEntry }) => (
3616 - <SimpleWorkEntryRow key={item.id} workEntry={item} workspaceRoot={workspaceRoot} />
3617 - ),
3618 - [workspaceRoot],
3431 + const renderEntry = ({ item }: { item: TimelineWorkEntry }) => (
3432 + <SimpleWorkEntryRow key={item.id} workEntry={item} workspaceRoot={workspaceRoot} />
3433 );
3434
3621 - const updateExpandedContentHeight = useCallback(() => {
3435 + const updateExpandedContentHeight = () => {
3436 const state = listRef.current?.getState();
3437 let height = 0;
3438 for (const entryId of viewState.expandedEntries) {
@@ -3629,7 +3443,7 @@ function ExpandedWorkGroupEntries({
3443 );
3444 }
3445 setExpandedContentHeight(height);
3632 - }, [viewState]);
3446 + };
3447
3448 useLayoutEffect(updateExpandedContentHeight, [entries, updateExpandedContentHeight]);
3449
@@ -3733,10 +3547,7 @@ function BackgroundWorktreeSetupChip({ snapshot }: { snapshot: WorktreeSetupSnap
3547 const ctx = use(TimelineRowCtx);
3548 const terminalId = snapshot.setupScript?.terminalId ?? null;
3549 const openTerminal = ctx.onOpenWorktreeSetupTerminal;
3736 - const onOpenTerminal = useMemo(
3737 - () => (openTerminal && terminalId ? () => openTerminal(terminalId) : null),
3738 - [openTerminal, terminalId],
3739 - );
3550 + const onOpenTerminal = openTerminal && terminalId ? () => openTerminal(terminalId) : null;
3551 const scriptName = snapshot.setupScript?.name ?? "Setup script";
3552 return (
3553 <Popover>
@@ -4697,7 +4508,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop
4508 footer?: ReactNode;
4509 }) {
4510 const [expanded, setExpanded] = useState(false);
4700 - const revealForFind = useCallback(() => setExpanded(true), []);
4511 + const revealForFind = () => setExpanded(true);
4512 const findRevealRef = useFindRevealRef(revealForFind);
4513 const hasVisibleBody = props.text.trim().length > 0;
4514 const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text);
@@ -4845,51 +4656,90 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
4656 );
4657 }
4658
4659 +function handoffRunsSignature(runs: ReadonlyArray<HandoffTimelineRun>): string {
4660 + return runs
4661 + .map(
4662 + (run) =>
4663 + `${run.id}\0${run.providerInstanceId}\0${run.ordinal}\0${run.modelSelection.instanceId}\0${run.modelSelection.model}`,
4664 + )
4665 + .join("\n");
4666 +}
4667 +
4668 function useStableHandoffRuns(
4669 runs: ReadonlyArray<HandoffTimelineRun>,
4670 ): ReadonlyArray<HandoffTimelineRun> {
4851 - const prev = useRef<{
4852 - signature: string;
4853 - value: ReadonlyArray<HandoffTimelineRun>;
4854 - }>({ signature: "", value: EMPTY_TIMELINE_RUNS });
4855 - return useMemo(() => {
4856 - const signature = runs
4857 - .map(
4858 - (run) =>
4859 - `${run.id}\0${run.providerInstanceId}\0${run.ordinal}\0${run.modelSelection.instanceId}\0${run.modelSelection.model}`,
4860 - )
4861 - .join("\n");
4862 - if (signature === prev.current.signature) {
4863 - return prev.current.value;
4864 - }
4865 - const value = runs.map((run) => ({
4866 - id: run.id,
4867 - ordinal: run.ordinal,
4868 - providerInstanceId: run.providerInstanceId,
4869 - modelSelection: run.modelSelection,
4870 - }));
4871 - prev.current = { signature, value };
4872 - return value;
4873 - }, [runs]);
4671 + const [state, setState] = useState<{
4672 + readonly source: ReadonlyArray<HandoffTimelineRun> | null;
4673 + readonly signature: string;
4674 + readonly value: ReadonlyArray<HandoffTimelineRun>;
4675 + }>({ source: null, signature: "", value: EMPTY_TIMELINE_RUNS });
4676 + if (state.source === runs) return state.value;
4677 + const signature = handoffRunsSignature(runs);
4678 + const value =
4679 + signature === state.signature
4680 + ? state.value
4681 + : runs.map((run) => ({
4682 + id: run.id,
4683 + ordinal: run.ordinal,
4684 + providerInstanceId: run.providerInstanceId,
4685 + modelSelection: run.modelSelection,
4686 + }));
4687 + setState({ source: runs, signature, value });
4688 + return value;
4689 +}
4690 +
4691 +type MessagesTimelineRowsInput = MessagesTimelineRowsProjection["input"];
4692 +
4693 +// Expanded-id sets can be rebuilt during render; comparing them by content keeps
4694 +// the render-time state update below from repeating forever.
4695 +function sameRowsInput(left: MessagesTimelineRowsInput, right: MessagesTimelineRowsInput): boolean {
4696 + for (const key of Object.keys(right) as Array<keyof MessagesTimelineRowsInput>) {
4697 + const previous = left[key];
4698 + const next = right[key];
4699 + if (Object.is(previous, next)) continue;
4700 + if (previous instanceof Set && next instanceof Set && shallow(previous, next)) continue;
4701 + return false;
4702 + }
4703 + return Object.keys(left).length === Object.keys(right).length;
4704 +}
4705 +
4706 +/**
4707 + * Rows derived from the previous projection of the same list, so a streamed
4708 + * text update patches its message rows instead of deriving every row again.
4709 + */
4710 +function useIncrementalTimelineRows(
4711 + identity: string,
4712 + input: MessagesTimelineRowsInput,
4713 +): MessagesTimelineRow[] {
4714 + const [state, setState] = useState(() => ({
4715 + identity,
4716 + input,
4717 + projection: deriveMessagesTimelineRowsWithState(input),
4718 + }));
4719 + if (state.identity === identity && sameRowsInput(state.input, input)) {
4720 + return state.projection.rows;
4721 + }
4722 + const projection = deriveMessagesTimelineRowsWithState(
4723 + input,
4724 + state.identity === identity ? state.projection : null,
4725 + );
4726 + setState({ identity, input, projection });
4727 + return projection.rows;
4728 }
4729
4730 function useStableRows(rows: MessagesTimelineRow[], identity: string): MessagesTimelineRow[] {
4877 - const prevState = useRef<StableMessagesTimelineRowsState>({
4878 - byId: new Map<string, MessagesTimelineRow>(),
4879 - result: [],
4880 - });
4881 - const prevIdentity = useRef(identity);
4882 -
4883 - return useMemo(() => {
4884 - const previous =
4885 - prevIdentity.current === identity
4886 - ? prevState.current
4887 - : { byId: new Map<string, MessagesTimelineRow>(), result: [] };
4888 - prevIdentity.current = identity;
4889 - const nextState = computeStableMessagesTimelineRows(rows, previous);
4890 - prevState.current = nextState;
4891 - return nextState.result;
4892 - }, [identity, rows]);
4731 + const [state, setState] = useState<{
4732 + readonly identity: string;
4733 + readonly source: MessagesTimelineRow[] | null;
4734 + readonly stable: StableMessagesTimelineRowsState;
4735 + }>({ identity, source: null, stable: { byId: new Map(), result: [] } });
4736 + if (state.identity === identity && state.source === rows) return state.stable.result;
4737 + const stable = computeStableMessagesTimelineRows(
4738 + rows,
4739 + state.identity === identity ? state.stable : { byId: new Map(), result: [] },
4740 + );
4741 + setState({ identity, source: rows, stable });
4742 + return stable.result;
4743 }
4744
4745 type WorkEntryIconName =
@@ -5744,15 +5594,11 @@ function QuestionAnswerHistory({
5594 answer: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
5595 }) {
5596 const { activeThreadEnvironmentId } = use(TimelineRowCtx);
5747 - const attachments = useMemo(() => Object.values(answer.attachmentsByQuestionId).flat(), [answer]);
5748 - const resources = useMemo(
5749 - () =>
5750 - attachments.map((attachment) => ({
5751 - _tag: "attachment" as const,
5752 - attachmentId: attachment.id,
5753 - })),
5754 - [attachments],
5755 - );
5597 + const attachments = Object.values(answer.attachmentsByQuestionId).flat();
5598 + const resources = attachments.map((attachment) => ({
5599 + _tag: "attachment" as const,
5600 + attachmentId: attachment.id,
5601 + }));
5602 const urls = useAssetUrls(activeThreadEnvironmentId, resources);
5603 return (
5604 <div className="ms-7 mt-2 space-y-2" onClick={stopRowToggle}>
vite.config.ts
+2
@@ -331,6 +331,8 @@ export default defineConfig({
331 "react/globals": "error",
332 "react/hooks": "error",
333 "react/immutability": "error",
334 + // The compiler memoizes context values; this rule would ask for useMemo.
335 + "react/jsx-no-constructed-context-values": "off",
336 "react/memo-dependencies": "error",
337 "react/preserve-manual-memoization": "error",
338 "react/purity": "error",