Skip to content
TypeScript

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

Julius Marminged913b61603a3
diff --git a/apps/web/reactCompiledFiles.ts b/apps/web/reactCompiledFiles.ts
index 05bf330dc23..7a5ec74bd1b 100644
--- a/apps/web/reactCompiledFiles.ts
+++ b/apps/web/reactCompiledFiles.ts
@@ -9,6 +9,7 @@ export const REACT_COMPILED_FILES = [
"apps/web/src/components/Sidebar.tsx",
"apps/web/src/components/chat/ChatComposer.tsx",
"apps/web/src/components/chat/usePendingThreadRequests.ts",
+ "apps/web/src/components/chat/MessagesTimeline.tsx",
"apps/web/src/components/chat/composerFocusRedirect.ts",
"apps/web/src/components/chat/useChatShortcuts.ts",
"apps/web/src/components/chat/useProjectScriptEditing.ts",
diff --git a/apps/web/src/components/chat/ExpandedImagePreview.tsx b/apps/web/src/components/chat/ExpandedImagePreview.tsx
index e241d53df16..55d4d90c0e2 100644
--- a/apps/web/src/components/chat/ExpandedImagePreview.tsx
+++ b/apps/web/src/components/chat/ExpandedImagePreview.tsx
@@ -106,7 +106,7 @@ export async function resolveMarkdownMediaPreview(input: {
export function buildAttachmentVideoAsset(
environmentId: EnvironmentId,
- attachment: ChatFileAttachment,
+ attachment: Pick<ChatFileAttachment, "id" | "name" | "mimeType">,
): NonNullable<MediaActionSource["asset"]> {
return {
environmentId,
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index e2a3b9dfd60..8f16ffd2f6b 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -1,4 +1,5 @@
import { ThreadFindTimelineContext } from "./ThreadFindProvider";
+import { shallow } from "zustand/vanilla/shallow";
import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
import { MarkdownFindContext, useFindRevealRef } from "./markdownFindContext";
import { useChatCanvas } from "./ChatCanvasContext";
@@ -72,11 +73,9 @@ import {
createContext,
memo,
use,
- useCallback,
useContext,
useEffect,
useLayoutEffect,
- useMemo,
useRef,
useState,
type KeyboardEvent,
@@ -182,6 +181,7 @@ import { useProject, useThreadShell } from "../../state/entities";
import {
CHAT_TIMELINE_ANCHOR_OFFSET,
readTimelinePosition,
+ type RememberedTimelinePosition,
rememberTimelinePosition,
timelineContentOverflowsViewport,
} from "./timelineScrollAnchoring";
@@ -374,6 +374,22 @@ const WorkGroupViewCtx = createContext<{
state: WorkGroupViewState;
onToggleEntry: (collapsed: boolean) => void;
} | null>(null);
+function timelineListStateFor(identity: string): {
+ readonly identity: string;
+ readonly rememberedPosition: RememberedTimelinePosition | undefined;
+ readonly workGroupViewState: WorkGroupViewState;
+} {
+ const rememberedPosition = readTimelinePosition(identity);
+ return {
+ identity,
+ rememberedPosition,
+ workGroupViewState: rememberedPosition?.disclosures?.workGroupState ?? {
+ scrollPositions: new Map(),
+ expandedEntries: new Set(),
+ },
+ };
+}
+
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
const TIMELINE_LIST_FADE_HEADER = (
<div className="h-[var(--workspace-titlebar-scroll-fade-height)]" />
@@ -591,34 +607,34 @@ const ConversationTimeline = memo(function ConversationTimeline({
loadEarlier = null,
}: MessagesTimelineProps) {
const listIdentityKey = displayThreadKey ?? routeThreadKey;
- const rememberedPosition = useMemo(
- () => readTimelinePosition(listIdentityKey),
- [listIdentityKey],
- );
+ // The remembered position is a snapshot taken when the list identity changes;
+ // scrolling keeps rewriting the stored entry, which must not move the restore.
+ const [listState, setListState] = useState(() => timelineListStateFor(listIdentityKey));
const [expandedRunIds, setExpandedRunIds] = useState<ReadonlySet<RunId>>(
- () => rememberedPosition?.disclosures?.runs ?? new Set(),
+ () => listState.rememberedPosition?.disclosures?.runs ?? new Set(),
);
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(
- () => rememberedPosition?.disclosures?.workGroups ?? new Set(),
+ () => listState.rememberedPosition?.disclosures?.workGroups ?? new Set(),
);
const [expandedAttemptIds, setExpandedAttemptIds] = useState<ReadonlySet<RunAttemptId>>(
- () => rememberedPosition?.disclosures?.attempts ?? new Set(),
+ () => listState.rememberedPosition?.disclosures?.attempts ?? new Set(),
);
const [positionedThreadKey, setPositionedThreadKey] = useState<string | null>(() =>
- rememberedPosition?.atEnd === false ? null : listIdentityKey,
+ listState.rememberedPosition?.atEnd === false ? null : listIdentityKey,
);
const restoringThreadPosition = positionedThreadKey !== listIdentityKey;
const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
- const listIdentityRef = useRef(listIdentityKey);
- const previousLatestRunRef = useRef(latestRun);
const [settlingListIdentity, setSettlingListIdentity] = useState<string | null>(listIdentityKey);
let paintedExpandedRunIds = expandedRunIds;
let paintedExpandedWorkGroupIds = expandedWorkGroupIds;
let paintedExpandedAttemptIds = expandedAttemptIds;
- if (listIdentityRef.current !== listIdentityKey) {
- listIdentityRef.current = listIdentityKey;
+ const identityChanged = listState.identity !== listIdentityKey;
+ const { rememberedPosition, workGroupViewState } = identityChanged
+ ? timelineListStateFor(listIdentityKey)
+ : listState;
+ if (identityChanged) {
+ setListState({ identity: listIdentityKey, rememberedPosition, workGroupViewState });
setPositionedThreadKey(null);
- previousLatestRunRef.current = latestRun;
setSettlingListIdentity(listIdentityKey);
paintedExpandedRunIds = rememberedPosition?.disclosures?.runs ?? new Set();
paintedExpandedWorkGroupIds = rememberedPosition?.disclosures?.workGroups ?? new Set();
@@ -627,19 +643,11 @@ const ConversationTimeline = memo(function ConversationTimeline({
setExpandedWorkGroupIds(paintedExpandedWorkGroupIds);
setExpandedAttemptIds(paintedExpandedAttemptIds);
}
- const citationThreadRef = useMemo(() => parseScopedThreadKey(routeThreadKey), [routeThreadKey]);
+ const citationThreadRef = parseScopedThreadKey(routeThreadKey);
const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined);
- const expandCitedRun = useCallback((runId: RunId) => {
+ const expandCitedRun = (runId: RunId) => {
setExpandedRunIds((current) => (current.has(runId) ? current : new Set([...current, runId])));
- }, []);
- const workGroupViewState = useMemo<WorkGroupViewState>(
- () =>
- rememberedPosition?.disclosures?.workGroupState ?? {
- scrollPositions: new Map(),
- expandedEntries: new Set(),
- },
- [listIdentityKey, rememberedPosition],
- );
+ };
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
const disclosureAnchorKeyRef = useRef<string | null>(null);
@@ -675,13 +683,13 @@ const ConversationTimeline = memo(function ConversationTimeline({
const disclosurePinsEndRef = useRef(false);
const disclosureCollapsedRef = useRef(false);
- const pinDisclosureToEnd = useCallback(() => {
+ const pinDisclosureToEnd = () => {
if (!disclosurePinsEndRef.current) return;
const element = listRef.current?.getScrollableNode();
if (element) element.scrollTop = element.scrollHeight;
- }, [listRef]);
+ };
- const scheduleDisclosureSettle = useCallback(() => {
+ const scheduleDisclosureSettle = () => {
if (disclosureSettleFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleFrameRef.current);
}
@@ -705,75 +713,64 @@ const ConversationTimeline = memo(function ConversationTimeline({
}
});
});
- }, [listRef, onToolOutputCollapsedAtEnd, pinDisclosureToEnd]);
-
- const suspendEndScrollMaintenanceForDisclosure = useCallback(
- (anchorKey: string, collapsed = false) => {
- disclosureAnchorKeyRef.current = anchorKey;
- disclosureCollapsedRef.current = collapsed;
- disclosurePinsEndRef.current = resolveTimelineIsAtEnd(listRef.current?.getState()) === true;
- setDisclosureToggleSettling(true);
- scheduleDisclosureSettle();
- },
- [listRef, scheduleDisclosureSettle],
- );
+ };
+
+ const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string, collapsed = false) => {
+ disclosureAnchorKeyRef.current = anchorKey;
+ disclosureCollapsedRef.current = collapsed;
+ disclosurePinsEndRef.current = resolveTimelineIsAtEnd(listRef.current?.getState()) === true;
+ setDisclosureToggleSettling(true);
+ scheduleDisclosureSettle();
+ };
- const shouldRestoreVisibleContentPosition = useCallback((row: MessagesTimelineRow) => {
+ const shouldRestoreVisibleContentPosition = (row: MessagesTimelineRow) => {
if (disclosurePinsEndRef.current) return false;
const disclosureAnchorKey = disclosureAnchorKeyRef.current;
return disclosureAnchorKey === null || row.id === disclosureAnchorKey;
- }, []);
+ };
- const onToggleTurnFold = useCallback(
- (runId: RunId) => {
- suspendEndScrollMaintenanceForDisclosure(`turn-fold:${runId}`);
- setExpandedRunIds((existing) => {
- const next = new Set(existing);
- if (next.has(runId)) {
- next.delete(runId);
- } else {
- next.add(runId);
- }
- return next;
- });
- },
- [suspendEndScrollMaintenanceForDisclosure],
- );
- const onToggleWorkGroup = useCallback(
- (groupId: string, anchorKey: string) => {
- suspendEndScrollMaintenanceForDisclosure(anchorKey, expandedWorkGroupIds.has(groupId));
- setExpandedWorkGroupIds((existing) => {
- const next = new Set(existing);
- if (next.has(groupId)) {
- next.delete(groupId);
- } else {
- next.add(groupId);
- }
- return next;
- });
- },
- [expandedWorkGroupIds, suspendEndScrollMaintenanceForDisclosure],
- );
- const onToggleAttemptFold = useCallback(
- (attemptId: RunAttemptId) => {
- suspendEndScrollMaintenanceForDisclosure(`attempt-fold:${attemptId}`);
- setExpandedAttemptIds((existing) => {
- const next = new Set(existing);
- if (next.has(attemptId)) {
- next.delete(attemptId);
- } else {
- next.add(attemptId);
- }
- return next;
- });
- },
- [suspendEndScrollMaintenanceForDisclosure],
- );
+ const onToggleTurnFold = (runId: RunId) => {
+ suspendEndScrollMaintenanceForDisclosure(`turn-fold:${runId}`);
+ setExpandedRunIds((existing) => {
+ const next = new Set(existing);
+ if (next.has(runId)) {
+ next.delete(runId);
+ } else {
+ next.add(runId);
+ }
+ return next;
+ });
+ };
+ const onToggleWorkGroup = (groupId: string, anchorKey: string) => {
+ suspendEndScrollMaintenanceForDisclosure(anchorKey, expandedWorkGroupIds.has(groupId));
+ setExpandedWorkGroupIds((existing) => {
+ const next = new Set(existing);
+ if (next.has(groupId)) {
+ next.delete(groupId);
+ } else {
+ next.add(groupId);
+ }
+ return next;
+ });
+ };
+ const onToggleAttemptFold = (attemptId: RunAttemptId) => {
+ suspendEndScrollMaintenanceForDisclosure(`attempt-fold:${attemptId}`);
+ setExpandedAttemptIds((existing) => {
+ const next = new Set(existing);
+ if (next.has(attemptId)) {
+ next.delete(attemptId);
+ } else {
+ next.add(attemptId);
+ }
+ return next;
+ });
+ };
+ const previousLatestRunRef = useRef({ identity: listIdentityKey, run: latestRun });
useEffect(() => {
- const previous = previousLatestRunRef.current;
- previousLatestRunRef.current = latestRun;
- if (!latestRun || previous?.runId === undefined) {
+ const { identity, run: previous } = previousLatestRunRef.current;
+ previousLatestRunRef.current = { identity: listIdentityKey, run: latestRun };
+ if (identity !== listIdentityKey || !latestRun || previous?.runId === undefined) {
return;
}
if (latestRun.runId === previous.runId) {
@@ -794,93 +791,59 @@ const ConversationTimeline = memo(function ConversationTimeline({
next.delete(previous.runId);
return next;
});
- }, [latestRun]);
+ }, [latestRun, listIdentityKey]);
// Find the fold that hides the match: imported turns have no run id but still
// fold under a synthetic key, so the match's own run id cannot open them.
- const findFoldRunIds = useMemo(
- () =>
- findActive
- ? timelineTurnFoldRunIdsByEntryId({
- timelineEntries,
- latestRun,
- runningRunId,
- isWorking,
- runlessWorkActive,
- })
- : null,
- [findActive, timelineEntries, latestRun, runningRunId, isWorking, runlessWorkActive],
- );
+ const findFoldRunIds = findActive
+ ? timelineTurnFoldRunIdsByEntryId({
+ timelineEntries,
+ latestRun,
+ runningRunId,
+ isWorking,
+ runlessWorkActive,
+ })
+ : null;
const activeFindRunId = activeFindMatch
? findFoldRunIds?.get(activeFindMatch.entryId)
: undefined;
- useEffect(() => {
- if (!activeFindRunId) return;
- setExpandedRunIds((previous) =>
- previous.has(activeFindRunId) ? previous : new Set(previous).add(activeFindRunId),
- );
- }, [activeFindRunId]);
- const visibleExpandedRunIds = useMemo(() => {
- if (!activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)) {
- return paintedExpandedRunIds;
+ const [expandedFindRunId, setExpandedFindRunId] = useState<RunId | undefined>();
+ if (expandedFindRunId !== activeFindRunId) {
+ setExpandedFindRunId(activeFindRunId);
+ if (activeFindRunId) {
+ setExpandedRunIds((previous) =>
+ previous.has(activeFindRunId) ? previous : new Set(previous).add(activeFindRunId),
+ );
}
- return new Set(paintedExpandedRunIds).add(activeFindRunId);
- }, [activeFindRunId, paintedExpandedRunIds]);
+ }
+ const visibleExpandedRunIds =
+ !activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)
+ ? paintedExpandedRunIds
+ : new Set(paintedExpandedRunIds).add(activeFindRunId);
const activeFindAttemptId = activeFindMatch
? timelineEntries.find((entry) => entry.id === activeFindMatch.entryId)?.attempt?.id
: undefined;
- useEffect(() => {
- if (!activeFindAttemptId) return;
- setExpandedAttemptIds((previous) =>
- previous.has(activeFindAttemptId) ? previous : new Set(previous).add(activeFindAttemptId),
- );
- }, [activeFindAttemptId]);
- const visibleExpandedAttemptIds = useMemo(
- () =>
- activeFindAttemptId && !paintedExpandedAttemptIds.has(activeFindAttemptId)
- ? new Set(paintedExpandedAttemptIds).add(activeFindAttemptId)
- : paintedExpandedAttemptIds,
- [activeFindAttemptId, paintedExpandedAttemptIds],
- );
+ const [expandedFindAttemptId, setExpandedFindAttemptId] = useState<RunAttemptId | undefined>();
+ if (expandedFindAttemptId !== activeFindAttemptId) {
+ setExpandedFindAttemptId(activeFindAttemptId);
+ if (activeFindAttemptId) {
+ setExpandedAttemptIds((previous) =>
+ previous.has(activeFindAttemptId) ? previous : new Set(previous).add(activeFindAttemptId),
+ );
+ }
+ }
+ const visibleExpandedAttemptIds =
+ activeFindAttemptId && !paintedExpandedAttemptIds.has(activeFindAttemptId)
+ ? new Set(paintedExpandedAttemptIds).add(activeFindAttemptId)
+ : paintedExpandedAttemptIds;
- const rowsProjectionRef = useRef<{
- readonly threadKey: string;
- readonly workspaceRoot: string | undefined;
- readonly projection: MessagesTimelineRowsProjection;
- } | null>(null);
- const rawRows = useMemo(() => {
- const previous = rowsProjectionRef.current;
- const projection = deriveMessagesTimelineRowsWithState(
- {
- timelineEntries,
- latestRun,
- runningRunId,
- expandedRunIds: visibleExpandedRunIds,
- expandedAttemptIds: visibleExpandedAttemptIds,
- expandedWorkGroupIds,
- isWorking,
- runlessWorkActive,
- activeTurnStartedAt,
- turnDiffSummaries,
- supportsConversationRollback,
- worktreeSetup,
- },
- previous?.threadKey === listIdentityKey && previous.workspaceRoot === workspaceRoot
- ? previous.projection
- : null,
- );
- rowsProjectionRef.current = { threadKey: listIdentityKey, workspaceRoot, projection };
- return projection.rows;
- }, [
- rowsProjectionRef,
- listIdentityKey,
- workspaceRoot,
+ const rawRows = useIncrementalTimelineRows(`${listIdentityKey}\0${workspaceRoot ?? ""}`, {
timelineEntries,
latestRun,
runningRunId,
- visibleExpandedRunIds,
- visibleExpandedAttemptIds,
+ expandedRunIds: visibleExpandedRunIds,
+ expandedAttemptIds: visibleExpandedAttemptIds,
expandedWorkGroupIds,
isWorking,
runlessWorkActive,
@@ -888,26 +851,24 @@ const ConversationTimeline = memo(function ConversationTimeline({
turnDiffSummaries,
supportsConversationRollback,
worktreeSetup,
- ]);
+ });
const rows = useStableRows(rawRows, listIdentityKey);
// Run status/timestamps churn on every stream event; the shared row context
// must not change with them or every timeline row re-renders per event.
const runs = useStableHandoffRuns(runsProp);
- const minimapItems = useMemo(() => deriveTimelineMinimapItems(rows), [rows]);
+ const minimapItems = deriveTimelineMinimapItems(rows);
const restoreRowIndex =
restoringThreadPosition && rememberedPosition?.atEnd === false
? rows.findIndex((row) => row.id === rememberedPosition.rowId)
: -1;
- const restoringAlwaysRender = useMemo(
- () =>
- restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined,
- [restoreRowIndex, restoringThreadPosition],
- );
+ const restoringAlwaysRender =
+ restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined;
useLayoutEffect(() => {
if (!restoringThreadPosition || rows.length === 0) return;
const list = listRef.current;
if (!list) return;
if (citationRequest !== null) {
+ // oxlint-disable-next-line react/set-state-in-effect -- The citation scroll owns positioning once the list has mounted.
setPositionedThreadKey(listIdentityKey);
return;
}
@@ -987,7 +948,8 @@ const ConversationTimeline = memo(function ConversationTimeline({
});
return;
}
- if (++stableFrames >= 2) {
+ stableFrames += 1;
+ if (stableFrames >= 2) {
setPositionedThreadKey(listIdentityKey);
} else {
settleFrame = requestAnimationFrame(reconcile);
@@ -1038,111 +1000,99 @@ const ConversationTimeline = memo(function ConversationTimeline({
onManualNavigation,
});
const [findListReady, setFindListReady] = useState(false);
- const handleListLoad = useCallback(() => {
+ const handleListLoad = () => {
onCitationListLoad();
setFindListReady(true);
- }, [onCitationListLoad]);
+ };
const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);
- const onAppFullscreenChange = useCallback((rowId: string, fullscreen: boolean) => {
+ const onAppFullscreenChange = (rowId: string, fullscreen: boolean) => {
setFullscreenAppRowId((current) => (fullscreen ? rowId : current === rowId ? null : current));
- }, []);
- const alwaysRender = useMemo(() => {
- const indices = restoringAlwaysRender?.indices ?? [];
- const keys = [
- ...(citationAlwaysRender?.keys ?? []),
- ...(fullscreenAppRowId === null ? [] : [fullscreenAppRowId]),
- ];
- if (indices.length === 0 && keys.length === 0) return undefined;
- return {
- ...(indices.length === 0 ? {} : { indices }),
- ...(keys.length === 0 ? {} : { keys }),
- };
- }, [citationAlwaysRender, restoringAlwaysRender, fullscreenAppRowId]);
+ };
+ const alwaysRenderIndices = restoringAlwaysRender?.indices ?? [];
+ const alwaysRenderKeys = [
+ ...(citationAlwaysRender?.keys ?? []),
+ ...(fullscreenAppRowId === null ? [] : [fullscreenAppRowId]),
+ ];
+ const alwaysRender =
+ alwaysRenderIndices.length === 0 && alwaysRenderKeys.length === 0
+ ? undefined
+ : {
+ ...(alwaysRenderIndices.length === 0 ? {} : { indices: alwaysRenderIndices }),
+ ...(alwaysRenderKeys.length === 0 ? {} : { keys: alwaysRenderKeys }),
+ };
const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
const [minimapCurrentIndex, setMinimapCurrentIndex] = useState<number | null>(null);
- const handleAnchorReady = useCallback(
- (info: { anchorIndex: number | undefined }) => {
- if (anchorMessageId !== null && info.anchorIndex !== undefined) {
- onAnchorReady(anchorMessageId, info.anchorIndex);
- }
- },
- [anchorMessageId, onAnchorReady],
+ const handleAnchorReady = (info: { anchorIndex: number | undefined }) => {
+ if (anchorMessageId !== null && info.anchorIndex !== undefined) {
+ onAnchorReady(anchorMessageId, info.anchorIndex);
+ }
+ };
+ const handleAnchorSizeChanged = (size: number) => {
+ if (anchorMessageId !== null) {
+ onAnchorSizeChanged(anchorMessageId, size);
+ }
+ };
+ const anchoredEndSpaceConfig = resolveChatListAnchoredEndSpace(
+ rows,
+ anchorMessageId,
+ (row) => (row.kind === "message" && row.message.role === "user" ? row.message.id : null),
+ { anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET },
);
- const handleAnchorSizeChanged = useCallback(
- (size: number) => {
- if (anchorMessageId !== null) {
- onAnchorSizeChanged(anchorMessageId, size);
+ const anchoredEndSpace = anchoredEndSpaceConfig
+ ? {
+ ...anchoredEndSpaceConfig,
+ onReady: handleAnchorReady,
+ onSizeChanged: handleAnchorSizeChanged,
}
- },
- [anchorMessageId, onAnchorSizeChanged],
- );
- const anchoredEndSpace = useMemo(() => {
- const config = resolveChatListAnchoredEndSpace(
- rows,
- anchorMessageId,
- (row) => (row.kind === "message" && row.message.role === "user" ? row.message.id : null),
- { anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET },
- );
- return config
- ? { ...config, onReady: handleAnchorReady, onSizeChanged: handleAnchorSizeChanged }
- : undefined;
- }, [anchorMessageId, handleAnchorReady, handleAnchorSizeChanged, rows]);
- const maintainVisibleContentPosition = useMemo(
- () => ({
- data: true,
- size: true,
- shouldRestorePosition: shouldRestoreVisibleContentPosition,
- }),
- [shouldRestoreVisibleContentPosition],
- );
- const timelineListFooter = useMemo(
- () => (
- <TimelineListFooter composerInset={anchoredEndSpace ? 0 : contentInsetEndAdjustment}>
- {footer}
- </TimelineListFooter>
- ),
- [anchoredEndSpace, contentInsetEndAdjustment, footer],
+ : undefined;
+ const maintainVisibleContentPosition = {
+ data: true,
+ size: true,
+ shouldRestorePosition: shouldRestoreVisibleContentPosition,
+ };
+ const timelineListFooter = (
+ <TimelineListFooter composerInset={anchoredEndSpace ? 0 : contentInsetEndAdjustment}>
+ {footer}
+ </TimelineListFooter>
);
- const measureContentOverflow = useCallback(
- () =>
- timelineContentOverflowsViewport(listRef.current?.getState?.(), {
- composerInset: contentInsetEndAdjustment,
- anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
- }),
- [contentInsetEndAdjustment, listRef],
- );
+ const measureContentOverflow = () =>
+ timelineContentOverflowsViewport(listRef.current?.getState?.(), {
+ composerInset: contentInsetEndAdjustment,
+ anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,
+ });
// LegendList lays rows out from layout effects, so a read on the next frame
// sees the settled positions.
const contentOverflowFrameRef = useRef<number | null>(null);
- const cancelContentOverflowFrame = useCallback(() => {
+ const cancelContentOverflowFrame = () => {
if (contentOverflowFrameRef.current !== null) {
cancelAnimationFrame(contentOverflowFrameRef.current);
contentOverflowFrameRef.current = null;
}
- }, []);
- const reportContentOverflow = useCallback(() => {
+ };
+ const reportContentOverflow = () => {
if (!onContentOverflowChange || contentOverflowFrameRef.current !== null) return;
contentOverflowFrameRef.current = requestAnimationFrame(() => {
contentOverflowFrameRef.current = null;
onContentOverflowChange(measureContentOverflow());
});
- }, [measureContentOverflow, onContentOverflowChange]);
- const handleItemSizeChanged = useCallback(() => {
+ };
+ const handleItemSizeChanged = () => {
if (disclosurePinsEndRef.current) {
queueMicrotask(pinDisclosureToEnd);
scheduleDisclosureSettle();
}
reportContentOverflow();
- }, [pinDisclosureToEnd, reportContentOverflow, scheduleDisclosureSettle]);
+ };
useEffect(() => cancelContentOverflowFrame, [cancelContentOverflowFrame]);
useLayoutEffect(() => {
cancelContentOverflowFrame();
onContentOverflowChange?.(measureContentOverflow());
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows change the content height.
}, [cancelContentOverflowFrame, measureContentOverflow, onContentOverflowChange, rows.length]);
- const handleScroll = useCallback(() => {
+ const handleScroll = () => {
const state = listRef.current?.getState?.();
if (restoringThreadPosition || state?.data !== rows) return;
const isAtEnd = resolveTimelineIsAtEnd(state);
@@ -1211,28 +1161,12 @@ const ConversationTimeline = memo(function ConversationTimeline({
setMinimapCurrentIndex((current) =>
current === nextCurrentIndex ? current : nextCurrentIndex,
);
- }, [
- citationPositioning,
- paintedExpandedRunIds,
- paintedExpandedWorkGroupIds,
- paintedExpandedAttemptIds,
- workGroupViewState,
- rows,
- listIdentityKey,
- liveFollowEnabled,
- anchoredEndSpace,
- paintOnly,
- restoringThreadPosition,
- listRef,
- minimapItems,
- minimapStripMap,
- onIsAtEndChange,
- reportContentOverflow,
- ]);
+ };
useEffect(() => {
const frame = requestAnimationFrame(handleScroll);
return () => cancelAnimationFrame(frame);
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows move the scroll position.
}, [handleScroll, rows.length]);
const savedLiveFollowEnabledRef = useRef(liveFollowEnabled);
@@ -1272,86 +1206,47 @@ const ConversationTimeline = memo(function ConversationTimeline({
cancelAnimationFrame(frame);
stopObserving();
};
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Rows and chat width resize the content without resizing the viewport.
}, [timelineViewportElement, rows.length, reportContentOverflow, chatWidth]);
- const sharedState = useMemo<TimelineRowSharedState>(
- () => ({
- citationRequest: readyCitationRequest,
- listRef,
- timestampFormat,
- routeThreadKey,
- threadRef: citationThreadRef,
- markdownCwd,
- resolvedTheme,
- workspaceRoot,
- skills,
- providerStatuses,
- runs,
- activeThreadEnvironmentId,
- onRevertToTurnCount,
- onRunShellCommand,
- findActive,
- onImageExpand,
- onFileOpen,
- onUseArtifactTemplate,
- onSendAppMessage,
- onAppFullscreenChange,
- onFileDownload,
- openPullRequest,
- onOpenTurnDiff,
- onOpenThread,
- onForkFromRun,
- onRollbackCheckpoint,
- onToggleTurnFold,
- onToggleAttemptFold,
- onToggleWorkGroup,
- onToggleWorkEntry: suspendEndScrollMaintenanceForDisclosure,
- onCancelWorktreeSetup: onCancelWorktreeSetup ?? null,
- retryableWorkspacePreparationRunIds,
- onRetryWorkspacePreparation: onRetryWorkspacePreparation ?? null,
- onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocally ?? null,
- onOpenWorktreeSetupTerminal: onOpenWorktreeSetupTerminal ?? null,
- workGroupViewState,
- }),
- [
- readyCitationRequest,
- listRef,
- timestampFormat,
- routeThreadKey,
- citationThreadRef,
- markdownCwd,
- resolvedTheme,
- workspaceRoot,
- skills,
- providerStatuses,
- runs,
- activeThreadEnvironmentId,
- onRevertToTurnCount,
- onRunShellCommand,
- findActive,
- onImageExpand,
- onFileOpen,
- onUseArtifactTemplate,
- onSendAppMessage,
- onAppFullscreenChange,
- onFileDownload,
- openPullRequest,
- onOpenTurnDiff,
- onOpenThread,
- onForkFromRun,
- onRollbackCheckpoint,
- onToggleTurnFold,
- onToggleAttemptFold,
- onToggleWorkGroup,
- suspendEndScrollMaintenanceForDisclosure,
- onCancelWorktreeSetup,
- retryableWorkspacePreparationRunIds,
- onRetryWorkspacePreparation,
- onWorktreeSetupWorkLocally,
- onOpenWorktreeSetupTerminal,
- workGroupViewState,
- ],
- );
+ const sharedState: TimelineRowSharedState = {
+ citationRequest: readyCitationRequest,
+ listRef,
+ timestampFormat,
+ routeThreadKey,
+ threadRef: citationThreadRef,
+ markdownCwd,
+ resolvedTheme,
+ workspaceRoot,
+ skills,
+ providerStatuses,
+ runs,
+ activeThreadEnvironmentId,
+ onRevertToTurnCount,
+ onRunShellCommand,
+ findActive,
+ onImageExpand,
+ onFileOpen,
+ onUseArtifactTemplate,
+ onSendAppMessage,
+ onAppFullscreenChange,
+ onFileDownload,
+ openPullRequest,
+ onOpenTurnDiff,
+ onOpenThread,
+ onForkFromRun,
+ onRollbackCheckpoint,
+ onToggleTurnFold,
+ onToggleAttemptFold,
+ onToggleWorkGroup,
+ onToggleWorkEntry: suspendEndScrollMaintenanceForDisclosure,
+ onCancelWorktreeSetup: onCancelWorktreeSetup ?? null,
+ retryableWorkspacePreparationRunIds,
+ onRetryWorkspacePreparation: onRetryWorkspacePreparation ?? null,
+ onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocally ?? null,
+ onOpenWorktreeSetupTerminal: onOpenWorktreeSetupTerminal ?? null,
+ workGroupViewState,
+ };
const compactionAwaitingRow =
isCompacting && !rows.some((row) => row.kind === "context-compaction" && row.active);
const backgroundWorktreeSetup =
@@ -1361,67 +1256,50 @@ const ConversationTimeline = memo(function ConversationTimeline({
latestRun?.startedAt != null
? worktreeSetup
: null;
- const activityState = useMemo<TimelineRowActivityState>(
- () => ({
- isWorking,
- isCompacting: compactionAwaitingRow,
- isRevertingCheckpoint,
- backgroundWorktreeSetup,
- activeTurnInProgress,
- awaitingUser,
- isPreparingWorktree,
- latestRunId: latestRun?.runId ?? null,
- }),
- [
- awaitingUser,
- compactionAwaitingRow,
- backgroundWorktreeSetup,
- activeTurnInProgress,
- isPreparingWorktree,
- isRevertingCheckpoint,
- isWorking,
- latestRun?.runId,
- ],
- );
- const listHeader = useMemo(() => {
- const leadingContent =
- parentThreadLink === null ? (
- topFadeEnabled ? (
- TIMELINE_LIST_FADE_HEADER
- ) : (
- TIMELINE_LIST_HEADER
- )
+ const activityState: TimelineRowActivityState = {
+ isWorking,
+ isCompacting: compactionAwaitingRow,
+ isRevertingCheckpoint,
+ backgroundWorktreeSetup,
+ activeTurnInProgress,
+ awaitingUser,
+ isPreparingWorktree,
+ latestRunId: latestRun?.runId ?? null,
+ };
+ const listHeaderLeadingContent =
+ parentThreadLink === null ? (
+ topFadeEnabled ? (
+ TIMELINE_LIST_FADE_HEADER
) : (
- <div className="messages-timeline-row-frame">
- <div className="chat-content-lane pt-1 sm:pt-2">
- <TimelineSystemDivider
- label="Subagent of"
- detail={parentThreadLink.title}
- icon={BotIcon}
- actionLabel="Open parent thread"
- onAction={() => onOpenThread(parentThreadLink.threadId)}
- />
- </div>
+ TIMELINE_LIST_HEADER
+ )
+ ) : (
+ <div className="messages-timeline-row-frame">
+ <div className="chat-content-lane pt-1 sm:pt-2">
+ <TimelineSystemDivider
+ label="Subagent of"
+ detail={parentThreadLink.title}
+ icon={BotIcon}
+ actionLabel="Open parent thread"
+ onAction={() => onOpenThread(parentThreadLink.threadId)}
+ />
</div>
- );
- return (
- <>
- {parentThreadLink === null ? leadingContent : null}
- {historyControls ? <TimelineHistoryControl {...historyControls} /> : null}
- {parentThreadLink !== null ? leadingContent : null}
- </>
+ </div>
);
- }, [historyControls, onOpenThread, parentThreadLink, topFadeEnabled]);
+ const listHeader = (
+ <>
+ {parentThreadLink === null ? listHeaderLeadingContent : null}
+ {historyControls ? <TimelineHistoryControl {...historyControls} /> : null}
+ {parentThreadLink !== null ? listHeaderLeadingContent : null}
+ </>
+ );
const canvas = useChatCanvas();
const registerTimeline = canvas?.registerTimeline;
- const setTimelineList = useCallback(
- (list: LegendListRef | null) => {
- listRef.current = list;
- registerTimeline?.(list?.getScrollableNode() ?? null);
- },
- [listRef, registerTimeline],
- );
+ const setTimelineList = (list: LegendListRef | null) => {
+ listRef.current = list;
+ registerTimeline?.(list?.getScrollableNode() ?? null);
+ };
useLayoutEffect(() => {
if (!findPositionReaderRef || !timelineViewportElement) return;
@@ -1501,24 +1379,18 @@ const ConversationTimeline = memo(function ConversationTimeline({
contentInsetEndAdjustment,
});
- const renderItem = useCallback(
- ({ item }: { item: MessagesTimelineRow }) => (
- <div className="messages-timeline-row-frame">
- <div className="chat-content-lane overflow-x-clip" data-timeline-root="true">
- <TimelineRowContent row={item} />
- </div>
+ const renderItem = ({ item }: { item: MessagesTimelineRow }) => (
+ <div className="messages-timeline-row-frame">
+ <div className="chat-content-lane overflow-x-clip" data-timeline-root="true">
+ <TimelineRowContent row={item} />
</div>
- ),
- [],
+ </div>
);
- const forwardMinimapWheel = useCallback(
- (event: WheelEvent) => {
- const scrollNode = listRef.current?.getScrollableNode();
- if (scrollNode) forwardWheelToTimeline(event, scrollNode);
- },
- [listRef],
- );
+ const forwardMinimapWheel = (event: WheelEvent) => {
+ const scrollNode = listRef.current?.getScrollableNode();
+ if (scrollNode) forwardWheelToTimeline(event, scrollNode);
+ };
if (
rows.length === 0 &&
@@ -1720,14 +1592,11 @@ function TimelineMinimap({
onSelect: (item: TimelineMinimapItem) => void;
}) {
const [activeIndex, setActiveIndex] = useState<number | null>(null);
- const wheelTargetRef = useCallback(
- (node: HTMLDivElement | null) => {
- if (!node) return;
- node.addEventListener("wheel", onWheel, { passive: false });
- return () => node.removeEventListener("wheel", onWheel);
- },
- [onWheel],
- );
+ const wheelTargetRef = (node: HTMLDivElement | null) => {
+ if (!node) return;
+ node.addEventListener("wheel", onWheel, { passive: false });
+ return () => node.removeEventListener("wheel", onWheel);
+ };
const pressedOnStripRef = useRef(false);
const [passThrough, setPassThrough] = useState(false);
@@ -1739,12 +1608,8 @@ function TimelineMinimap({
const resolvedActiveIndex =
activeIndex !== null && activeIndex < items.length ? activeIndex : null;
- const activeItem = useMemo(
- () =>
- resolveTimelineMinimapPreview(
- resolvedActiveIndex === null ? null : (items[resolvedActiveIndex] ?? null),
- ),
- [items, resolvedActiveIndex],
+ const activeItem = resolveTimelineMinimapPreview(
+ resolvedActiveIndex === null ? null : (items[resolvedActiveIndex] ?? null),
);
const navigationInteractive =
resolveTimelineMinimapNavigationInteractive(hitStripWidth) && !passThrough;
@@ -1766,36 +1631,27 @@ function TimelineMinimap({
resolvedCurrentIndex === null ? null : (items[resolvedCurrentIndex - 1] ?? null);
const nextItem = resolvedCurrentIndex === null ? null : (items[resolvedCurrentIndex + 1] ?? null);
- const resolveActiveIndexFromPointer = useCallback(
- (event: MouseEvent<HTMLElement>) => {
- const rect = event.currentTarget.getBoundingClientRect();
- return resolveTimelineMinimapIndexFromPointer({
- itemCount: items.length,
- railTop: rect.top,
- railHeight: rect.height,
- pointerY: event.clientY,
- });
- },
- [items.length],
- );
+ const resolveActiveIndexFromPointer = (event: MouseEvent<HTMLElement>) => {
+ const rect = event.currentTarget.getBoundingClientRect();
+ return resolveTimelineMinimapIndexFromPointer({
+ itemCount: items.length,
+ railTop: rect.top,
+ railHeight: rect.height,
+ pointerY: event.clientY,
+ });
+ };
- const updateActiveIndexFromPointer = useCallback(
- (event: MouseEvent<HTMLElement>) => {
- const nextIndex = resolveActiveIndexFromPointer(event);
- setActiveIndex(nextIndex);
- },
- [resolveActiveIndexFromPointer],
- );
+ const updateActiveIndexFromPointer = (event: MouseEvent<HTMLElement>) => {
+ const nextIndex = resolveActiveIndexFromPointer(event);
+ setActiveIndex(nextIndex);
+ };
- const moveActiveIndex = useCallback(
- (delta: number) => {
- setActiveIndex((current) => {
- const base = current ?? 0;
- return Math.max(0, Math.min(items.length - 1, base + delta));
- });
- },
- [items.length],
- );
+ const moveActiveIndex = (delta: number) => {
+ setActiveIndex((current) => {
+ const base = current ?? 0;
+ return Math.max(0, Math.min(items.length - 1, base + delta));
+ });
+ };
if (items.length < TIMELINE_MINIMAP_MIN_ITEMS) {
return null;
@@ -2112,10 +1968,7 @@ function WorktreeSetupTimelineRow({
const ctx = use(TimelineRowCtx);
const terminalId = row.snapshot.setupScript?.terminalId ?? null;
const openTerminal = ctx.onOpenWorktreeSetupTerminal;
- const onOpenTerminal = useMemo(
- () => (openTerminal && terminalId ? () => openTerminal(terminalId) : null),
- [openTerminal, terminalId],
- );
+ const onOpenTerminal = openTerminal && terminalId ? () => openTerminal(terminalId) : null;
return (
<WorktreeSetupCard
snapshot={row.snapshot}
@@ -2165,13 +2018,14 @@ function ContextCompactionTimelineRow({
function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
const ctx = use(TimelineRowCtx);
- const asset = useMemo(
- () =>
- file.downloadable === false
- ? null
- : buildAttachmentVideoAsset(ctx.activeThreadEnvironmentId, file),
- [ctx.activeThreadEnvironmentId, file.downloadable, file.id, file.mimeType, file.name],
- );
+ // Row updates rebuild attachment objects, so the asset follows only the
+ // fields it reads.
+ const { downloadable, id, mimeType, name } = file;
+ const environmentId = ctx.activeThreadEnvironmentId;
+ const asset =
+ downloadable === false
+ ? null
+ : buildAttachmentVideoAsset(environmentId, { id, mimeType, name });
const resource = asset?.resource ?? null;
const assetUrl = useAssetUrlState(ctx.activeThreadEnvironmentId, resource);
const refreshAssetUrl = useAssetUrlRefresh(ctx.activeThreadEnvironmentId, resource);
@@ -2216,40 +2070,28 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
const ctx = use(TimelineRowCtx);
const { onImageExpand, onFileOpen } = ctx;
const senderThreadId = row.message.senderThreadId;
- const resources = useMemo(
- () => selectMessageImageResources(row.message.attachments),
- [row.message.attachments],
- );
+ const resources = selectMessageImageResources(row.message.attachments);
const previewUrls = useAssetUrls(ctx.activeThreadEnvironmentId, resources);
const [projectPreviews] = useState(createMessageAttachmentPreviewProjector);
- const messageWithPreviews = useMemo(() => {
- const urlsById = new Map(
- resources.flatMap((resource, index) => {
- const url = previewUrls[index];
- return url ? [[resource.attachmentId, url] as const] : [];
- }),
- );
- return projectPreviews(row.message, (attachment) => urlsById.get(attachment.id));
- }, [previewUrls, projectPreviews, resources, row.message]);
- const userImages = useMemo(
- () => (messageWithPreviews.attachments ?? []).filter(isImageAttachment),
- [messageWithPreviews.attachments],
+ const previewUrlsById = new Map(
+ resources.flatMap((resource, index) => {
+ const url = previewUrls[index];
+ return url ? [[resource.attachmentId, url] as const] : [];
+ }),
);
- const userFiles = useMemo(
- () => (row.message.attachments ?? []).filter(isFileAttachment),
- [row.message.attachments],
+ const messageWithPreviews = projectPreviews(row.message, (attachment) =>
+ previewUrlsById.get(attachment.id),
);
+ const userImages = (messageWithPreviews.attachments ?? []).filter(isImageAttachment);
+ const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
const userVideos = userFiles.filter(isVideoAttachment);
const otherUserFiles = userFiles.filter((file) => !isVideoAttachment(file));
const unknownAttachments = (row.message.attachments ?? []).filter(
(attachment) => !isImageAttachment(attachment) && !isFileAttachment(attachment),
);
const userMessage = resolveUserMessagePresentation(row.message);
- const resolvedContext = useMemo(() => resolveUserMessageContext(row.message), [row.message]);
- const previewImages = useMemo(
- () => userImages.filter((image) => image.name.startsWith("preview-annotation-")),
- [userImages],
- );
+ const resolvedContext = resolveUserMessageContext(row.message);
+ const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
const revertTurnCount = row.revertTurnCount;
const chippedAttachmentIds = new Set(
collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => {
@@ -2259,18 +2101,14 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
);
const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));
- const annotationRecordIds = useMemo(
- () =>
- resolvedContext.records
- .filter((record) => record.kind === "preview-annotation")
- .map((record) => record.contextId),
- [resolvedContext.records],
- );
- const plainText = useMemo(
- () => replaceComposerContextReferences(resolvedContext.text, (reference) => reference.label),
- [resolvedContext.text],
+ const annotationRecordIds = resolvedContext.records
+ .filter((record) => record.kind === "preview-annotation")
+ .map((record) => record.contextId);
+ const plainText = replaceComposerContextReferences(
+ resolvedContext.text,
+ (reference) => reference.label,
);
- const promptLink = useMemo(() => promptLinkFor(plainText), [plainText]);
+ const promptLink = promptLinkFor(plainText);
const contextClipboardFragment =
resolvedContext.records.length === 0
? null
@@ -2316,56 +2154,44 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
}
event.clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);
};
- const renderContextReference = useCallback(
- (reference: ChatMarkdownContextReference) => {
- const record = asKnownContextRecord(resolvedContext.recordsById.get(reference.contextId));
- const annotationImage =
- record?.kind === "preview-annotation"
- ? resolvePreviewAnnotationImage({
- record,
- recordsById: resolvedContext.recordsById,
- userImages,
- previewImages,
- annotationRecordIds,
- })
+ const renderContextReference = (reference: ChatMarkdownContextReference) => {
+ const record = asKnownContextRecord(resolvedContext.recordsById.get(reference.contextId));
+ const annotationImage =
+ record?.kind === "preview-annotation"
+ ? resolvePreviewAnnotationImage({
+ record,
+ recordsById: resolvedContext.recordsById,
+ userImages,
+ previewImages,
+ annotationRecordIds,
+ })
+ : null;
+ const attachment =
+ record?.kind === "image"
+ ? (userImages.find((image) => image.id === record.attachmentId) ?? null)
+ : record?.kind === "file"
+ ? (userFiles.find((file) => file.id === record.attachmentId) ?? null)
: null;
- const attachment =
- record?.kind === "image"
- ? (userImages.find((image) => image.id === record.attachmentId) ?? null)
- : record?.kind === "file"
- ? (userFiles.find((file) => file.id === record.attachmentId) ?? null)
- : null;
- return (
- <span data-thread-find-ignore>
- <UserMessageContextReferenceChip
- reference={reference}
- record={record}
- annotationImage={annotationImage}
- attachment={attachment}
- onExpandImage={(image) => {
- const preview = buildExpandedImagePreview(userImages, image.id);
- if (preview) onImageExpand(preview);
- }}
- onOpenFile={onFileOpen}
- onExpandVideo={(file) => {
- const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
- if (preview) onImageExpand(preview);
- }}
- />
- </span>
- );
- },
- [
- resolvedContext.recordsById,
- userImages,
- userFiles,
- previewImages,
- annotationRecordIds,
- onImageExpand,
- onFileOpen,
- ctx.activeThreadEnvironmentId,
- ],
- );
+ return (
+ <span data-thread-find-ignore>
+ <UserMessageContextReferenceChip
+ reference={reference}
+ record={record}
+ annotationImage={annotationImage}
+ attachment={attachment}
+ onExpandImage={(image) => {
+ const preview = buildExpandedImagePreview(userImages, image.id);
+ if (preview) onImageExpand(preview);
+ }}
+ onOpenFile={onFileOpen}
+ onExpandVideo={(file) => {
+ const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
+ if (preview) onImageExpand(preview);
+ }}
+ />
+ </span>
+ );
+ };
return (
<div className="group flex flex-col items-end gap-1">
@@ -2967,10 +2793,7 @@ function ProposedPlanTimelineRow({
function HtmlRenderTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "html-render" }> }) {
const ctx = use(TimelineRowCtx);
const { onAppFullscreenChange } = ctx;
- const onFullscreenChange = useCallback(
- (fullscreen: boolean) => onAppFullscreenChange(row.id, fullscreen),
- [onAppFullscreenChange, row.id],
- );
+ const onFullscreenChange = (fullscreen: boolean) => onAppFullscreenChange(row.id, fullscreen);
return (
<div className="min-w-0 px-1">
@@ -3437,13 +3260,10 @@ const WorkGroupSection = memo(function WorkGroupSection({
displayLabel?: string | undefined;
}) {
const { workspaceRoot, routeThreadKey, onToggleWorkEntry } = use(TimelineRowCtx);
- const onToggleStandaloneEntry = useCallback(
- (collapsed: boolean) => onToggleWorkEntry(disclosureAnchorKey, collapsed),
- [disclosureAnchorKey, onToggleWorkEntry],
- );
- const nonEmptyEntries = useMemo(
- () => groupedEntries.filter((entry) => workEntryIsVisibleInGroup(entry, isExpandedToolGroup)),
- [groupedEntries, isExpandedToolGroup],
+ const onToggleStandaloneEntry = (collapsed: boolean) =>
+ onToggleWorkEntry(disclosureAnchorKey, collapsed);
+ const nonEmptyEntries = groupedEntries.filter((entry) =>
+ workEntryIsVisibleInGroup(entry, isExpandedToolGroup),
);
if (nonEmptyEntries.length === 0) return null;
@@ -3551,14 +3371,11 @@ function ExpandedWorkGroupEntries({
});
}
- const groupView = useMemo(
- () => ({
- state: viewState,
- onToggleEntry: (collapsed: boolean) => onToggleWorkEntry(disclosureAnchorKey, collapsed),
- }),
- [disclosureAnchorKey, onToggleWorkEntry, viewState],
- );
- const updateScrollFades = useCallback(() => {
+ const groupView = {
+ state: viewState,
+ onToggleEntry: (collapsed: boolean) => onToggleWorkEntry(disclosureAnchorKey, collapsed),
+ };
+ const updateScrollFades = () => {
const element = listRef.current?.getScrollableNode();
if (!element) return;
const distanceFromEnd = element.scrollHeight - element.clientHeight - element.scrollTop;
@@ -3572,9 +3389,9 @@ function ExpandedWorkGroupEntries({
? previous
: { top, bottom, viewportHeight },
);
- }, []);
+ };
- const handleScroll = useCallback(() => {
+ const handleScroll = () => {
const state = listRef.current?.getState();
const position = state && resolveWorkGroupScrollAnchor(state);
if (position) {
@@ -3584,9 +3401,9 @@ function ExpandedWorkGroupEntries({
});
}
updateScrollFades();
- }, [anchorKey, updateScrollFades, viewState]);
+ };
- const handleLoad = useCallback(() => {
+ const handleLoad = () => {
const list = listRef.current;
const element = list?.getScrollableNode();
if (initialScrollIndex && list && element) {
@@ -3601,7 +3418,7 @@ function ExpandedWorkGroupEntries({
}
}
setRestoringPosition(false);
- }, [initialScrollIndex]);
+ };
useLayoutEffect(() => {
const element = listRef.current?.getScrollableNode();
@@ -3611,14 +3428,11 @@ function ExpandedWorkGroupEntries({
return observeResize(content ? [element, content] : element, updateScrollFades);
}, [updateScrollFades]);
- const renderEntry = useCallback(
- ({ item }: { item: TimelineWorkEntry }) => (
- <SimpleWorkEntryRow key={item.id} workEntry={item} workspaceRoot={workspaceRoot} />
- ),
- [workspaceRoot],
+ const renderEntry = ({ item }: { item: TimelineWorkEntry }) => (
+ <SimpleWorkEntryRow key={item.id} workEntry={item} workspaceRoot={workspaceRoot} />
);
- const updateExpandedContentHeight = useCallback(() => {
+ const updateExpandedContentHeight = () => {
const state = listRef.current?.getState();
let height = 0;
for (const entryId of viewState.expandedEntries) {
@@ -3629,7 +3443,7 @@ function ExpandedWorkGroupEntries({
);
}
setExpandedContentHeight(height);
- }, [viewState]);
+ };
useLayoutEffect(updateExpandedContentHeight, [entries, updateExpandedContentHeight]);
@@ -3733,10 +3547,7 @@ function BackgroundWorktreeSetupChip({ snapshot }: { snapshot: WorktreeSetupSnap
const ctx = use(TimelineRowCtx);
const terminalId = snapshot.setupScript?.terminalId ?? null;
const openTerminal = ctx.onOpenWorktreeSetupTerminal;
- const onOpenTerminal = useMemo(
- () => (openTerminal && terminalId ? () => openTerminal(terminalId) : null),
- [openTerminal, terminalId],
- );
+ const onOpenTerminal = openTerminal && terminalId ? () => openTerminal(terminalId) : null;
const scriptName = snapshot.setupScript?.name ?? "Setup script";
return (
<Popover>
@@ -4697,7 +4508,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop
footer?: ReactNode;
}) {
const [expanded, setExpanded] = useState(false);
- const revealForFind = useCallback(() => setExpanded(true), []);
+ const revealForFind = () => setExpanded(true);
const findRevealRef = useFindRevealRef(revealForFind);
const hasVisibleBody = props.text.trim().length > 0;
const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text);
@@ -4845,51 +4656,90 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
);
}
+function handoffRunsSignature(runs: ReadonlyArray<HandoffTimelineRun>): string {
+ return runs
+ .map(
+ (run) =>
+ `${run.id}\0${run.providerInstanceId}\0${run.ordinal}\0${run.modelSelection.instanceId}\0${run.modelSelection.model}`,
+ )
+ .join("\n");
+}
+
function useStableHandoffRuns(
runs: ReadonlyArray<HandoffTimelineRun>,
): ReadonlyArray<HandoffTimelineRun> {
- const prev = useRef<{
- signature: string;
- value: ReadonlyArray<HandoffTimelineRun>;
- }>({ signature: "", value: EMPTY_TIMELINE_RUNS });
- return useMemo(() => {
- const signature = runs
- .map(
- (run) =>
- `${run.id}\0${run.providerInstanceId}\0${run.ordinal}\0${run.modelSelection.instanceId}\0${run.modelSelection.model}`,
- )
- .join("\n");
- if (signature === prev.current.signature) {
- return prev.current.value;
- }
- const value = runs.map((run) => ({
- id: run.id,
- ordinal: run.ordinal,
- providerInstanceId: run.providerInstanceId,
- modelSelection: run.modelSelection,
- }));
- prev.current = { signature, value };
- return value;
- }, [runs]);
+ const [state, setState] = useState<{
+ readonly source: ReadonlyArray<HandoffTimelineRun> | null;
+ readonly signature: string;
+ readonly value: ReadonlyArray<HandoffTimelineRun>;
+ }>({ source: null, signature: "", value: EMPTY_TIMELINE_RUNS });
+ if (state.source === runs) return state.value;
+ const signature = handoffRunsSignature(runs);
+ const value =
+ signature === state.signature
+ ? state.value
+ : runs.map((run) => ({
+ id: run.id,
+ ordinal: run.ordinal,
+ providerInstanceId: run.providerInstanceId,
+ modelSelection: run.modelSelection,
+ }));
+ setState({ source: runs, signature, value });
+ return value;
+}
+
+type MessagesTimelineRowsInput = MessagesTimelineRowsProjection["input"];
+
+// Expanded-id sets can be rebuilt during render; comparing them by content keeps
+// the render-time state update below from repeating forever.
+function sameRowsInput(left: MessagesTimelineRowsInput, right: MessagesTimelineRowsInput): boolean {
+ for (const key of Object.keys(right) as Array<keyof MessagesTimelineRowsInput>) {
+ const previous = left[key];
+ const next = right[key];
+ if (Object.is(previous, next)) continue;
+ if (previous instanceof Set && next instanceof Set && shallow(previous, next)) continue;
+ return false;
+ }
+ return Object.keys(left).length === Object.keys(right).length;
+}
+
+/**
+ * Rows derived from the previous projection of the same list, so a streamed
+ * text update patches its message rows instead of deriving every row again.
+ */
+function useIncrementalTimelineRows(
+ identity: string,
+ input: MessagesTimelineRowsInput,
+): MessagesTimelineRow[] {
+ const [state, setState] = useState(() => ({
+ identity,
+ input,
+ projection: deriveMessagesTimelineRowsWithState(input),
+ }));
+ if (state.identity === identity && sameRowsInput(state.input, input)) {
+ return state.projection.rows;
+ }
+ const projection = deriveMessagesTimelineRowsWithState(
+ input,
+ state.identity === identity ? state.projection : null,
+ );
+ setState({ identity, input, projection });
+ return projection.rows;
}
function useStableRows(rows: MessagesTimelineRow[], identity: string): MessagesTimelineRow[] {
- const prevState = useRef<StableMessagesTimelineRowsState>({
- byId: new Map<string, MessagesTimelineRow>(),
- result: [],
- });
- const prevIdentity = useRef(identity);
-
- return useMemo(() => {
- const previous =
- prevIdentity.current === identity
- ? prevState.current
- : { byId: new Map<string, MessagesTimelineRow>(), result: [] };
- prevIdentity.current = identity;
- const nextState = computeStableMessagesTimelineRows(rows, previous);
- prevState.current = nextState;
- return nextState.result;
- }, [identity, rows]);
+ const [state, setState] = useState<{
+ readonly identity: string;
+ readonly source: MessagesTimelineRow[] | null;
+ readonly stable: StableMessagesTimelineRowsState;
+ }>({ identity, source: null, stable: { byId: new Map(), result: [] } });
+ if (state.identity === identity && state.source === rows) return state.stable.result;
+ const stable = computeStableMessagesTimelineRows(
+ rows,
+ state.identity === identity ? state.stable : { byId: new Map(), result: [] },
+ );
+ setState({ identity, source: rows, stable });
+ return stable.result;
}
type WorkEntryIconName =
@@ -5744,15 +5594,11 @@ function QuestionAnswerHistory({
answer: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
}) {
const { activeThreadEnvironmentId } = use(TimelineRowCtx);
- const attachments = useMemo(() => Object.values(answer.attachmentsByQuestionId).flat(), [answer]);
- const resources = useMemo(
- () =>
- attachments.map((attachment) => ({
- _tag: "attachment" as const,
- attachmentId: attachment.id,
- })),
- [attachments],
- );
+ const attachments = Object.values(answer.attachmentsByQuestionId).flat();
+ const resources = attachments.map((attachment) => ({
+ _tag: "attachment" as const,
+ attachmentId: attachment.id,
+ }));
const urls = useAssetUrls(activeThreadEnvironmentId, resources);
return (
<div className="ms-7 mt-2 space-y-2" onClick={stopRowToggle}>
diff --git a/vite.config.ts b/vite.config.ts
index 6c0f3a7fbf8..7c76f955d95 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -331,6 +331,8 @@ export default defineConfig({
"react/globals": "error",
"react/hooks": "error",
"react/immutability": "error",
+ // The compiler memoizes context values; this rule would ask for useMemo.
+ "react/jsx-no-constructed-context-values": "off",
"react/memo-dependencies": "error",
"react/preserve-manual-memoization": "error",
"react/purity": "error",